scoop:scoop.http.server:0.1.0
src/multipart/input.scoop
Selected production source · src/multipart/input.scoop
1
package scoop.http.server3
import scoop.asyncio.*4
import scoop.http.asyncio.*5
import scoop.platform.memory.NativeByteBuffer7
internal class RequestPartInput(private val body: MultipartBody, private val owner: RequestMultipart,8
private val limit: Long) : AsyncByteSource {9
private val busy: AtomicBoolean = AtomicBoolean(false)10
private val retired: AtomicBoolean = AtomicBoolean(false)11
private var consumed: Long = 0L12
val isComplete: Boolean get() = body.isComplete14
suspend fun <T> withRead(block: suspend () -> T): T {15
if (!busy.compareAndSet(false, true)) throw IllegalStateException(Some("concurrent multipart part reads"))16
try {17
ensureActive()18
if (retired.load()) throw IllegalStateException(Some("multipart part is no longer current"))19
return block()20
} finally { busy.store(false) }21
}23
public override suspend fun readInto(buffer: NativeByteBuffer, count: Long): Long =24
withRead<Long> suspend { read(buffer, count) }26
private suspend fun read(buffer: NativeByteBuffer, count: Long): Long {27
if (count < 0L || count > buffer.writableBytes) throw IndexOutOfBoundsException()28
val remaining = limit - consumed29
val requested = if (remaining < count) remaining + 1L else count30
val read = multipartInput<Long> suspend { body.readInto(buffer, requested) }31
if (read > remaining) exceeded("multipart part exceeds its byte limit")32
consumed += read33
return read34
}36
suspend fun consume(maxBytes: Long, accept: suspend (NativeByteBuffer, Long) -> Unit): Long =37
withRead<Long> suspend {38
NativeByteBuffer.allocate(8192L).use suspend { buffer ->39
var total = 0L40
while (true) {41
buffer.clear()42
val remaining = maxBytes - total43
val count = read(buffer, if (remaining < 8192L) remaining + 1L else 8192L)44
if (count == 0L) break45
if (count > remaining) exceeded("multipart part exceeds its consumption limit")46
accept(buffer, count)47
total += count48
}49
total50
}51
}53
suspend fun discard(maxBytes: Long): Long = withRead<Long> suspend {54
val remaining = limit - consumed55
val allowed = if (maxBytes < remaining) maxBytes else remaining56
try {57
val discarded = multipartInput<Long> suspend { body.discard(allowed) }58
consumed += discarded59
discarded60
} catch (_: MultipartDiscardLimitException) { exceeded("multipart discard exceeds its byte limit") }61
}63
private suspend fun exceeded(detail: String): Nothing { owner.fail(HttpRejection(text(detail, 413U))) }65
fun retire() { retired.store(true) }67
suspend fun close() {68
try { body.close() }69
finally { retire() }70
}71
}