Scoop API

scoop:scoop.http.client:0.1.0

src/response/body.scoop

Selected production source · src/response/body.scoop

1package scoop.http.client
3import scoop.asyncio.*
4import scoop.charset.*
5import scoop.http.*
6import scoop.json.Json
7import scoop.platform.memory.NativeByteBuffer
9/**
10 * A single forward-only response-body cursor with optional content decoding. Reads must not
11 * overlap; buffering helpers require an explicit byte limit.
12 */
13public class HttpResponseBody internal constructor(private val input: ClientResponseInput, private val fields: Array<HttpField>)
14 : AsyncByteSource, AsyncCloseable {
15 private val busy: AtomicBoolean = AtomicBoolean(false)
16 /**
17 * Whether the complete body and finalization have succeeded.
18 */
19 public val isComplete: Boolean get() = input.isComplete
20 /**
21 * The length of the delivered representation when known; automatic decoding can make this
22 * unknown.
23 */
24 public val contentLength: Long? get() = input.plan.contentLength
26 /**
27 * Reads up to count bytes into the writable buffer; positive-count zero indicates EOF. Only
28 * one reader may be active.
29 */
30 public override suspend fun readInto(buffer: NativeByteBuffer, count: Long): Long =
31 withReader(suspend { source -> source.readInto(buffer, count) })
33 /**
34 * Buffers the remaining body under an explicit byte limit; the body is not rewound.
35 */
36 public suspend fun readAllBytes(maxBytes: Long): Array<Byte> =
37 withReader(suspend { source -> source.readAllBytes(maxBytes) })
39 /**
40 * Buffers the remaining body under an explicit byte limit.
41 */
42 public suspend fun bytes(maxBytes: Long): Array<Byte> = readAllBytes(maxBytes)
44 /**
45 * Streams the remaining body into the borrowed sink using a positive buffer size.
46 */
47 public suspend fun copyTo(destination: AsyncByteSink, bufferSize: Long = 8192L): Long =
48 withReader(suspend { source -> source.copyTo(destination, bufferSize) })
50 /**
51 * Buffers under maxBytes and decodes using the explicit charset, Content-Type charset, or
52 * UTF-8 fallback. Malformed input is strict unless replacement is requested.
53 */
54 public suspend fun text(maxBytes: Long, charset: Charset? = None, options: CharsetDecodeOptions = CharsetDecodeOptions(),
55 malformedInput: CharsetErrorAction = CharsetErrorAction.Strict): String {
56 val selected = charset ?: responseTextCharset(fields)
57 val value = readAllBytes(maxBytes)
58 return when (malformedInput) {
59 case Strict -> selected.decode(value, options)
60 case Replace -> selected.decodeLossy(value, options)
61 }
62 }
64 /**
65 * Buffers under maxBytes, strictly decodes UTF-8, and uses the supplied JSON value decoder.
66 */
67 public suspend fun <T> json(codec: ValueDecoder<T>, maxBytes: Long): T =
68 Json.decodeFromString(Charset.Utf8.decode(readAllBytes(maxBytes)), codec)
70 /** Consumes this body once as JSON using the type companion and the same byte limit. */
71 public suspend fun <T> json(maxBytes: Long): T
72 where T.Companion : ValueDecoder<T> = json(T.Companion, maxBytes)
74 private suspend fun <T> withReader(block: suspend (AsyncByteSource) -> T): T {
75 val call = input.call
76 val reader = clientJob(call.client.loop, true)
77 if (!busy.compareAndSet(false, true)) throw IllegalStateException(Some("HTTP response body already has a reader"))
78 val listener = reader.invokeOnCancellation { error -> cancelClientCall(call, error, true) }
79 try { return block(input) }
80 finally { listener.dispose(); busy.store(false) }
81 }
83 /**
84 * Ends body consumption and awaits upload, stream, and call cleanup.
85 */
86 public override suspend fun close() { input.close() }
89private fun responseTextCharset(fields: Array<HttpField>): Charset {
90 val media = HttpMediaType.parseFields(fields)
91 val charset = when (media) { case Some(val value) -> value.parameter("charset"); case None -> None }
92 return when (charset) { case Some(val value) -> Charset.forName(String.fromUtf8(value.value)); case None -> Charset.Utf8 }