Scoop API

scoop:scoop.http.client:0.1.0

src/body/body.scoop

Selected production source · src/body/body.scoop

1package scoop.http.client
3import scoop.asyncio.*
4import scoop.charset.Charset
5import scoop.collections.emptyList
6import scoop.compression.CompressionOptions
7import scoop.compression.GzipOptions
8import scoop.http.HttpMediaType
9import scoop.http.HttpField
10import scoop.http.HttpTrailerDeclaration
11import scoop.http.MultipartBoundary
12import scoop.platform.fs.Path
13import scoop.url.UrlQuery
15/**
16 * A request-body plan with explicit metadata and replayability. One-shot sources cannot be retried
17 * after consumption; factories reopen state without implicit whole-body buffering.
18 */
19public class RequestBody internal constructor(
20 contentLength: Long?,
21 /**
22 * The body's media type, if supplied.
23 */
24 public val contentType: HttpMediaType?,
25 private val plan: RequestBodyPlan,
26 contentEncodings: List<String> = emptyList<String>(),
27 internal val trailerDeclaration: HttpTrailerDeclaration =
28 HttpTrailerDeclaration(emptyList<String>()),
29 internal val entityDigests: Array<ClientEntityDigest> = []
30) {
31 /**
32 * The declared outgoing representation length, or None when unknown.
33 */
34 public val contentLength: Long? = checkedBodyLength(contentLength)
35 /**
36 * Content codings applied to the outgoing body, in application order.
37 */
38 public val contentEncodings: Array<String> = contentEncodings.toArray()
39 /**
40 * The declared names that the producer may return as trailers.
41 */
42 public val trailerNames: Array<String> get() = trailerDeclaration.names
43 /**
44 * Whether the plan can create a fresh body traversal for another attempt.
45 */
46 public val isReplayable: Boolean get() = plan.isReplayable
48 /**
49 * Wraps this plan in streaming compression, preserving its replayability and updating coding
50 * metadata.
51 */
52 public fun compressed(
53 options: CompressionOptions = CompressionOptions.Gzip(GzipOptions())
54 ): RequestBody = compressedRequestBody(this, options)
56 /**
57 * Adds an explicit entity digest for the selected authentication algorithm; the caller
58 * supplies bytes matching the actual body.
59 */
60 public fun withDigest(algorithm: HttpDigestAlgorithm, bytes: List<Byte>): RequestBody =
61 RequestBody(
62 contentLength,
63 contentType,
64 plan,
65 contentEncodings,
66 trailerDeclaration,
67 replaceClientEntityDigest(entityDigests, algorithm, bytes)
68 )
70 /**
71 * Writes the body to a borrowed sink and verifies declared length; bodies declaring trailers
72 * require writeWithTrailersTo.
73 */
74 public suspend fun writeTo(destination: AsyncByteSink, bufferSize: Long = 8192L): Long {
75 ensureActive()
76 if (trailerNames.size != 0L)
77 throw IllegalArgumentException(
78 Some("request body trailers require writeWithTrailersTo")
79 )
80 return writeWithTrailersTo(destination, bufferSize).transferredBytes
81 }
83 /**
84 * Writes and length-checks the body, then returns transferred bytes and validated declared
85 * trailers.
86 */
87 public suspend fun writeWithTrailersTo(
88 destination: AsyncByteSink,
89 bufferSize: Long = 8192L
90 ): RequestBodyWriteResult {
91 ensureActive()
92 if (bufferSize <= 0L)
93 throw IllegalArgumentException(Some("request body buffer size must be positive"))
94 val sink = RequestBodySink(destination, contentLength)
95 try {
96 val trailers = plan.writeTo(sink, bufferSize).toArray()
97 val transferred = sink.finish()
98 trailerDeclaration.requireDeclared(trailers)
99 return RequestBodyWriteResult(transferred, trailers)
100 } finally {
101 sink.end()
102 }
103 }
105 /**
106 * Factories for buffered, streaming, and replayable body plans.
107 */
108 public companion object {
109 /**
110 * A replayable zero-byte body without a media type.
111 */
112 public val Empty: RequestBody =
113 RequestBody(Some(0L), None, RequestBytes(Array<Byte>(0L) { _ -> 0.toByte() }))
115 /**
116 * Copies bytes into a replayable body with known length.
117 */
118 public fun fromByteArray(
119 bytes: List<Byte>,
120 contentType: HttpMediaType? = None
121 ): RequestBody {
122 val snapshot = bytes.toArray()
123 return RequestBody(Some(snapshot.size), contentType, RequestBytes(snapshot))
124 }
126 /**
127 * Encodes text using the selected charset into a replayable body with text metadata.
128 */
129 public fun fromText(text: String, charset: Charset = Charset.Utf8): RequestBody =
130 textRequestBody(text, charset)
132 /**
133 * Encodes JSON into a replayable body under the explicit byte limit.
134 */
135 public fun <T> fromJson(value: T, codec: ValueEncoder<T>, maxBytes: Long): RequestBody =
136 jsonRequestBody(value, codec, maxBytes)
138 /** Encodes JSON using the value companion, retaining the explicit UTF-8 byte limit. */
139 public fun <T> fromJson(value: T, maxBytes: Long): RequestBody
140 where T.Companion: ValueEncoder<T> = fromJson(value, T.Companion, maxBytes)
142 /**
143 * Encodes form parameters as application/x-www-form-urlencoded.
144 */
145 public fun fromForm(parameters: UrlQuery): RequestBody = formRequestBody(parameters)
147 /**
148 * Borrows a one-shot asynchronous source without taking close ownership.
149 */
150 public fun fromSource(
151 source: AsyncByteSource,
152 contentLength: Long? = None,
153 contentType: HttpMediaType? = None
154 ): RequestBody =
155 RequestBody(
156 contentLength,
157 contentType,
158 RequestBodyOnce(
159 suspend {
160 destination, bufferSize ->
161 source.copyTo(destination, bufferSize)
162 emptyList<HttpField>()
163 }
164 )
165 )
167 /**
168 * Creates and closes a fresh owned source for each body attempt, enabling replay.
169 */
170 public fun <T> fromSourceFactory(
171 contentLength: Long? = None,
172 contentType: HttpMediaType? = None,
173 factory: suspend () -> T
174 ): RequestBody where T: AsyncByteSource, T: AsyncCloseable =
175 RequestBody(
176 contentLength,
177 contentType,
178 RequestBodyFactory(
179 suspend {
180 suspend {
181 destination, bufferSize ->
182 factory().useAsync suspend {
183 source ->
184 source.copyTo(destination, bufferSize);
185 Unit
186 }
187 emptyList<HttpField>()
188 }
189 }
190 )
191 )
193 /**
194 * Reopens the path for each attempt; it does not snapshot changing file contents.
195 */
196 public fun fromFile(
197 path: Path,
198 contentLength: Long? = None,
199 contentType: HttpMediaType? = None
200 ): RequestBody =
201 fromSourceFactory(
202 contentLength,
203 contentType,
204 suspend { currentEventLoop().openFile(path) }
205 )
207 /**
208 * Creates a one-shot producer that writes to a borrowed sink.
209 */
210 public fun fromProducer(
211 contentLength: Long? = None,
212 contentType: HttpMediaType? = None,
213 producer: suspend (AsyncByteSink) -> Unit
214 ): RequestBody =
215 RequestBody(
216 contentLength,
217 contentType,
218 RequestBodyOnce(
219 suspend {
220 destination, _ ->
221 producer(destination)
222 emptyList<HttpField>()
223 }
224 )
225 )
227 /**
228 * Creates a fresh producer for each attempt, enabling replay.
229 */
230 public fun fromProducerFactory(
231 contentLength: Long? = None,
232 contentType: HttpMediaType? = None,
233 factory: suspend () -> suspend (AsyncByteSink) -> Unit
234 ): RequestBody =
235 RequestBody(
236 contentLength,
237 contentType,
238 RequestBodyFactory(
239 suspend {
240 val producer = factory();
241 suspend {
242 destination, _ ->
243 producer(destination);
244 emptyList<HttpField>()
245 }
246 }
247 )
248 )
250 /**
251 * Creates a one-shot producer returning trailers from the declared name set.
252 */
253 public fun fromProducerWithTrailers(
254 trailerNames: List<String>,
255 contentLength: Long? = None,
256 contentType: HttpMediaType? = None,
257 producer: suspend (AsyncByteSink) -> List<HttpField>
258 ): RequestBody =
259 RequestBody(
260 contentLength,
261 contentType,
262 RequestBodyOnce(suspend { destination, _ -> producer(destination) }),
263 trailerDeclaration = HttpTrailerDeclaration(trailerNames)
264 )
266 /**
267 * Creates a fresh trailer-producing callback for each attempt, enabling replay.
268 */
269 public fun fromProducerWithTrailersFactory(
270 trailerNames: List<String>,
271 contentLength: Long? = None,
272 contentType: HttpMediaType? = None,
273 factory: suspend () -> suspend (AsyncByteSink) -> List<HttpField>
274 ): RequestBody =
275 RequestBody(
276 contentLength,
277 contentType,
278 RequestBodyFactory(
279 suspend {
280 val producer = factory();
281 suspend { destination, _ -> producer(destination) }
282 }
283 ),
284 trailerDeclaration = HttpTrailerDeclaration(trailerNames)
285 )
286 }
289/**
290 * The actual body bytes transferred and trailers produced after successful body completion.
291 */
292public class RequestBodyWriteResult internal constructor(
293 /**
294 * The actual outgoing body bytes accepted by the sink.
295 */
296 public val transferredBytes: Long,
297 /**
298 * Validated trailers produced after the body.
299 */
300 public val trailers: Array<HttpField>
303private fun checkedBodyLength(length: Long?): Long? {
304 if (length != None && length!! < 0L)
305 throw IllegalArgumentException(Some("negative request body length"))
306 return length