Scoop API

scoop:scoop.http:0.1.0

src/http1_encoder.scoop

Selected production source · src/http1_encoder.scoop

1package scoop.http
3import scoop.bytes.ByteArrayBuilder
4import scoop.platform.memory.NativeByteBuffer
5import scoop.text.*
7/**
8 * The explicit body-delimiting rule selected before encoding an HTTP/1 message.
9 */
10public enum Http1BodyFraming {
11 /**
12 * No body bytes are permitted.
13 */
14 Empty,
15 /**
16 * Exactly the supplied nonnegative body length must be written before finish.
17 */
18 Length(Long),
19 /**
20 * Writes chunked framing and permits trailers at finish.
21 */
22 Chunked,
23 /**
24 * Response body ends when the transport closes; the caller must close the connection after
25 * output.
26 */
27 Eof
30/** The bytes surrounding one accepted body prefix; the payload itself stays with the caller. */
31public struct Http1BodyChunk(
32 /** Bytes emitted before the accepted body prefix. */
33 val prefix: Array<Byte>,
34 /** Bytes emitted after the entire accepted body prefix. */
35 val suffix: Array<Byte>
38/**
39 * An HTTP/1 encoder with explicit message begin, body, and finish. It produces framing bytes
40 * without performing transport I/O; close does not finish a message.
41 */
42public class Http1Encoder public constructor(
43 /**
44 * The fixed client/server role of this codec.
45 */
46 public val role: HttpRole
47): Closeable {
48 private var closed: Boolean = false
49 private var active: Boolean = false
50 private var closing: Boolean = false
51 private var switched: Boolean = false
52 private var framing: Http1BodyFraming = Http1BodyFraming.Empty
53 private var remaining: Long = 0L
54 private var responseEncoding: Http1ResponseEncoding? = None
56 /**
57 * Whether its state has been released.
58 */
59 public val isClosed: Boolean get() = closed
60 /**
61 * Whether begin has started a message that still requires finish.
62 */
63 public val isMessageOpen: Boolean get() = active
64 /**
65 * Whether the caller must close the transport after the encoded message.
66 */
67 public val mustClose: Boolean get() = closing
68 /**
69 * Whether the encoded response transferred the connection to another protocol.
70 */
71 public val isSwitched: Boolean get() = switched
73 private fun requireOpen() {
74 if (closed)
75 throw IllegalStateException(Some("HTTP/1 encoder is closed"))
76 }
78 private fun requireBegin(expected: HttpRole) {
79 requireOpen()
80 if (role != expected || active || closing)
81 throw IllegalStateException(Some("cannot begin another HTTP/1 message here"))
82 }
84 private fun begin(
85 output: ByteArrayBuilder,
86 fields: Array<HttpField>,
87 version: HttpVersion,
88 mode: Http1BodyFraming,
89 kind: Http1HeadKind
90 ): Array<Byte> {
91 val close = appendHttp1Headers(output, fields, version, mode, kind)
92 val bytes = output.toByteArray()
93 beginMessage(mode, close, kind == Http1HeadKind.Switch)
94 return bytes
95 }
97 private fun beginMessage(mode: Http1BodyFraming, close: Boolean, switch: Boolean) {
98 active = true
99 framing = mode
100 remaining =
101 when (mode) {
102 case Length(val count) -> count;
103 else -> 0L
104 }
105 closing = close
106 switched = switch
107 }
109 /**
110 * Validates and encodes a client request head, selecting explicit body framing. Every
111 * successful begin requires finish.
112 */
113 public fun beginRequest(
114 head: HttpRequestHead,
115 body: Http1BodyFraming = Http1BodyFraming.Empty
116 ): Array<Byte> {
117 requireBegin(HttpRole.Client)
118 requireHttp1Method(head.method)
119 val target =
120 when (head.target) {
121 case Http1(val bytes) -> bytes
122 else -> throw IllegalArgumentException(Some("HTTP/1 requires a raw request target"))
123 }
124 if (target.size == 0L)
125 throw IllegalArgumentException(Some("HTTP request target is empty"))
126 for (byte in target) {
127 val value = byte.toUByte().toInt()
128 if (value <= 32 || value == 127)
129 throw IllegalArgumentException(Some("invalid HTTP request target byte"))
130 }
131 val output = ByteArrayBuilder()
132 output.append(head.method).append(32.toByte()).append(target).append(32.toByte())
133 .append((http1VersionText(head.version) + "\r\n").toByteArray())
134 return begin(output, head.fields, head.version, body, Http1HeadKind.Request)
135 }
137 /**
138 * Encodes a server response using the exact originating method to determine body and switching
139 * rules. Returned bytes are immutable and remain valid across later messages and close.
140 */
141 public fun beginResponse(
142 head: HttpResponseHead,
143 requestMethod: List<Byte>,
144 body: Http1BodyFraming = Http1BodyFraming.Empty
145 ): Array<Byte> {
146 requireBegin(HttpRole.Server)
147 val method = httpSnapshot(requestMethod)
148 when (responseEncoding) {
149 case Some(val encoded) -> {
150 if (
151 encoded.head ===
152 head &&
153 encoded.framing ==
154 body &&
155 httpBytesEqual(encoded.method, method)
156 ) {
157 beginMessage(body, encoded.closing, encoded.switched)
158 return encoded.bytes
159 }
160 }
161 case None -> {}
162 }
163 requireHttp1Method(method)
164 val kind = http1ResponseKind(head, method)
165 val output = ByteArrayBuilder()
166 output.append(
167 (http1VersionText(head.version) + " " + head.status.toString() + " ").toByteArray()
168 )
169 when (head.reason) {
170 case Some(val reason) -> {
171 requireHttpValue(reason);
172 output.append(reason)
173 }
174 case None -> {}
175 }
176 output.append("\r\n".toByteArray())
177 val close = appendHttp1Headers(output, head.fields, head.version, body, kind)
178 val bytes = output.toByteArray()
179 val switch = kind == Http1HeadKind.Switch
180 val encoded = Http1ResponseEncoding(head, method, body, bytes, close, switch)
181 beginMessage(body, close, switch)
182 responseEncoding = Some(encoded)
183 return bytes
184 }
186 private fun frameBody(count: Long): Http1BodyChunk {
187 requireOpen()
188 if (!active)
189 throw IllegalStateException(Some("HTTP/1 message has not begun"))
190 if (count < 0L)
191 throw IllegalArgumentException(Some("invalid HTTP body count"))
192 if (count == 0L)
193 return Http1BodyChunk("".toByteArray(), "".toByteArray())
194 when (framing) {
195 case Empty -> throw IllegalStateException(Some("this HTTP message has no body"))
196 case Length(_) -> {
197 if (count > remaining)
198 throw IllegalArgumentException(Some("HTTP body exceeds Content-Length"))
199 }
200 else -> {}
201 }
202 if (framing == Http1BodyFraming.Chunked)
203 return Http1BodyChunk((count.toString(16) + "\r\n").toByteArray(), "\r\n".toByteArray())
204 return Http1BodyChunk("".toByteArray(), "".toByteArray())
205 }
207 private fun acceptBody(count: Long) {
208 when (framing) {
209 case Length(_) -> remaining -= count;
210 else -> {}
211 }
212 }
214 /**
215 * Accepts a body length and returns only its surrounding framing. The caller emits prefix,
216 * its original payload, then suffix; a failed transmission must not retry this accepted chunk.
217 */
218 public fun prepareBody(count: Long): Http1BodyChunk {
219 val chunk = frameBody(count)
220 acceptBody(count)
221 return chunk
222 }
224 /**
225 * Consumes body bytes and returns their complete framed representation for in-memory use.
226 * Rejected or failed encoding leaves the input position and declared length unchanged.
227 */
228 public fun writeBody(buffer: NativeByteBuffer, count: Long = buffer.readableBytes): Array<
229 Byte
230 > {
231 if (count < 0L || count > buffer.readableBytes)
232 throw IllegalArgumentException(Some("invalid HTTP body count"))
233 val chunk = frameBody(count)
234 if (count == 0L)
235 return chunk.prefix
236 val output = ByteArrayBuilder()
237 output.append(chunk.prefix)
238 @Unsafe
239 {
240 val bytes =
241 buffer.withReadableBytes {
242 pointer,
243 _ -> @Unsafe
244 {
245 return@withReadableBytes httpBytes(NativeHttpBytes(pointer, count))
246 }
247 }
248 output.append(bytes)
249 }
250 output.append(chunk.suffix)
251 val result = output.toByteArray()
252 buffer.skip(count)
253 acceptBody(count)
254 return result
255 }
257 /**
258 * Completes the current message and returns final framing bytes; trailers require chunked
259 * framing and fixed-length bodies must be complete.
260 */
261 public fun finish(trailers: List<HttpField> = ArrayList<HttpField>()): Array<Byte> {
262 requireOpen()
263 if (!active)
264 throw IllegalStateException(Some("HTTP/1 message has not begun"))
265 if (remaining != 0L)
266 throw IllegalStateException(Some("HTTP body ended before Content-Length"))
267 val output = ByteArrayBuilder()
268 if (framing == Http1BodyFraming.Chunked) {
269 output.append("0\r\n".toByteArray())
270 for (field in trailers) {
271 requireHttpTrailerName(field.name)
272 appendHttp1Field(output, field)
273 }
274 output.append("\r\n".toByteArray())
275 } else
276 if (trailers.size != 0L)
277 throw IllegalArgumentException(Some("HTTP/1 trailers require chunked framing"))
278 val result = output.toByteArray()
279 active = false
280 return result
281 }
283 /**
284 * Releases codec state without sending, finishing, or closing a transport.
285 */
286 public override fun close() {
287 closed = true;
288 active = false
289 responseEncoding = None
290 }