scoop:scoop.http.server:0.1.0
src/multipart/reader.scoop
Selected production source · src/multipart/reader.scoop
1
package scoop.http.server3
import scoop.asyncio.*4
import scoop.http.asyncio.MultipartSource5
import scoop.http.asyncio.MultipartPart7
/** A single-pass form-data view, borrowing the underlying HTTP request body. */8
public class RequestMultipart internal constructor(private val source: MultipartSource,9
private val options: RequestMultipartOptions) : AsyncCloseable {10
private val busy: AtomicBoolean = AtomicBoolean(false)11
private var current: RequestPart? = None13
/** Whether the closing delimiter and outer body EOF were both consumed. */14
public val isFinished: Boolean get() = source.isFinished15
/** Whether this view's local decoder and buffers have been released. */16
public val isClosed: Boolean get() = source.isClosed18
/** Receives the next part only after the current one has reached EOF or been discarded. */19
public suspend fun nextPart(): RequestPart? {20
if (!busy.compareAndSet(false, true)) throw IllegalStateException(Some("concurrent multipart iteration"))21
try {22
if (present(current)) {23
if (!current!!.isComplete) throw IllegalStateException(Some("current multipart part must be completed first"))24
}25
val next = multipartInput<MultipartPart?> suspend { source.nextPart() }26
if (present(current)) current!!.retire()27
current = None28
if (!present(next)) return None29
try {30
val part = RequestPart(next!!, this, options)31
current = Some(part)32
return Some(part)33
} catch (error: Throwable) { fail(error) }34
} finally { busy.store(false) }35
}37
/** Releases local state without draining or closing the borrowed HTTP body. */38
public override suspend fun close() {39
try { source.close() }40
finally { if (present(current)) current!!.retire(); current = None }41
}43
internal suspend fun fail(error: Throwable): Nothing {44
try { close() }45
catch (cleanup: Throwable) { throw ResourceUseException(error, cleanup) }46
throw error47
}48
}