Scoop API

scoop:scoop.http.server:0.1.0

src/multipart/input.scoop

Selected production source · src/multipart/input.scoop

1package scoop.http.server
3import scoop.asyncio.*
4import scoop.http.asyncio.*
5import scoop.platform.memory.NativeByteBuffer
7internal 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 = 0L
12 val isComplete: Boolean get() = body.isComplete
14 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 - consumed
29 val requested = if (remaining < count) remaining + 1L else count
30 val read = multipartInput<Long> suspend { body.readInto(buffer, requested) }
31 if (read > remaining) exceeded("multipart part exceeds its byte limit")
32 consumed += read
33 return read
34 }
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 = 0L
40 while (true) {
41 buffer.clear()
42 val remaining = maxBytes - total
43 val count = read(buffer, if (remaining < 8192L) remaining + 1L else 8192L)
44 if (count == 0L) break
45 if (count > remaining) exceeded("multipart part exceeds its consumption limit")
46 accept(buffer, count)
47 total += count
48 }
49 total
50 }
51 }
53 suspend fun discard(maxBytes: Long): Long = withRead<Long> suspend {
54 val remaining = limit - consumed
55 val allowed = if (maxBytes < remaining) maxBytes else remaining
56 try {
57 val discarded = multipartInput<Long> suspend { body.discard(allowed) }
58 consumed += discarded
59 discarded
60 } 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 }