scoop:scoop.http.server:0.1.0
src/body/input.scoop
Selected production source · src/body/input.scoop
1
package scoop.http.server3
import scoop.asyncio.*4
import scoop.platform.memory.NativeByteBuffer6
internal class RequestBodySource(private val source: AsyncByteSource, var limit: Long?,7
private val limitMessage: String = "request body exceeds input limit") : AsyncByteSource {8
val completed: AtomicBoolean = AtomicBoolean(false)9
private val retired: AtomicBoolean = AtomicBoolean(false)10
private val busy: AtomicBoolean = AtomicBoolean(false)11
private var received: Long = 0L12
private var delivered: Long = 0L13
val receivedBytes: Long get() = received14
val deliveredBytes: Long get() = delivered15
private var failure: Throwable? = None17
fun invalidate() { retired.store(true) }19
public override suspend fun readInto(buffer: NativeByteBuffer, count: Long): Long {20
if (count < 0L || count > buffer.writableBytes) throw IndexOutOfBoundsException()21
if (!busy.compareAndSet(false, true)) throw IllegalStateException(Some("concurrent request body reads"))22
try {23
ensureActive()24
if (retired.load()) throw IoClosedException()25
if (present(failure)) throw failure!!26
if (count == 0L || completed.load()) return 0L27
val remaining = if (!present(limit)) Long.MAX_VALUE - received else limit!! - received28
val requested = if (remaining < count) remaining + 1L else count29
val before = buffer.readableBytes30
val progress = source.readInto(buffer, requested)31
if (progress < 0L || progress > requested || buffer.readableBytes - before != progress)32
throw IllegalStateException(Some("invalid request source progress"))33
if (progress > Long.MAX_VALUE - received) throw ArithmeticException()34
received += progress35
if (progress > remaining) reject(413U, limitMessage)36
delivered = received37
if (progress == 0L) completed.store(true)38
return progress39
} catch (error: Throwable) {40
failure = Some(error)41
throw error42
} finally { busy.store(false) }43
}44
}