Scoop API

scoop:scoop.http:0.1.0

src/http2_session.scoop

Selected production source · src/http2_session.scoop

1package scoop.http
3import scoop.platform.memory.NativeByteBuffer
5/**
6 * An owned in-memory HTTP/2 session. Serialize calls, drain events and output, and acknowledge
7 * received DATA only after consumption. It owns no network transport.
8 */
9public class Http2Session private constructor(private var handle: ULong,
10 /**
11 * The fixed client/server role of this codec.
12 */
13 public val role: HttpRole) : Closeable {
14 /**
15 * Factories for explicitly owned client/server codec instances.
16 */
17 public companion object {
18 /**
19 * Creates a client codec with the selected receive options and local limits.
20 */
21 public fun client(options: Http2ReceiveOptions = Http2ReceiveOptions(), limits: Http2Limits = Http2Limits(),
22 settings: Http2Settings = Http2Settings()): Http2Session = create(HttpRole.Client, options, limits, settings)
24 /**
25 * Creates a server codec with the selected receive options and local limits.
26 */
27 public fun server(options: Http2ReceiveOptions = Http2ReceiveOptions(), limits: Http2Limits = Http2Limits(),
28 settings: Http2Settings = Http2Settings()): Http2Session = create(HttpRole.Server, options, limits, settings)
30 /**
31 * Creates a client session after an accepted h2c upgrade, using exactly the SETTINGS sent
32 * in the request. Stream 1 represents that completed HTTP/1 request.
33 */
34 public fun upgradedClient(requestMethod: List<Byte>, settings: Http2Settings = Http2Settings(),
35 options: Http2ReceiveOptions = Http2ReceiveOptions(), limits: Http2Limits = Http2Limits()): Http2Session =
36 upgrade(HttpRole.Client, requestMethod, http2SettingsPayload(settings), options, limits, settings)
38 /**
39 * Creates a server session after the complete HTTP/1 upgrade request body, applying the
40 * decoded peer SETTINGS payload.
41 */
42 public fun upgradedServer(requestMethod: List<Byte>, settingsPayload: List<Byte>,
43 options: Http2ReceiveOptions = Http2ReceiveOptions(), limits: Http2Limits = Http2Limits(),
44 settings: Http2Settings = Http2Settings()): Http2Session =
45 upgrade(HttpRole.Server, requestMethod, settingsPayload.toArray(), options, limits, settings)
47 private fun upgrade(role: HttpRole, requestMethod: List<Byte>, payload: Array<Byte>,
48 options: Http2ReceiveOptions, limits: Http2Limits, settings: Http2Settings): Http2Session {
49 val method = requestMethod.toArray()
50 requireHttp1Method(method)
51 if (httpBytesEqual(method, "CONNECT".toByteArray()))
52 throw IllegalArgumentException(Some("h2c upgrade cannot use CONNECT"))
53 val session = create(role, options, limits, settings, true)
54 try { session.applyUpgrade(payload, httpBytesEqual(method, "HEAD".toByteArray())); return session }
55 catch (error: Throwable) { session.close(); throw error }
56 }
58 private fun create(role: HttpRole, options: Http2ReceiveOptions, limits: Http2Limits,
59 settings: Http2Settings, upgrading: Boolean = false): Http2Session {
60 val config = http2Config(options, limits)
61 val values = http2Settings(settings)
62 @Unsafe {
63 val native = http2New(if (role == HttpRole.Server) 1 else 0, config, values, if (upgrading) 1 else 0)
64 if (native == 0UL) throw http2Failure("create HTTP/2 session", -901, "cannot allocate HTTP/2 session")
65 return Http2Session(native, role)
66 }
67 }
68 }
70 /**
71 * Whether its state has been released.
72 */
73 public val isClosed: Boolean get() = handle == 0UL
74 /**
75 * Whether the session currently expects further peer input.
76 */
77 public val wantsRead: Boolean get() { @Unsafe { return http2Wants(nativeHandle(), 0) != 0 } }
78 /**
79 * Whether the backend currently has output work to drive.
80 */
81 public val wantsWrite: Boolean get() { @Unsafe { return http2Wants(nativeHandle(), 1) != 0 } }
82 /**
83 * The currently buffered output byte count.
84 */
85 public val bufferedOutputBytes: Long get() { @Unsafe { return http2Buffered(nativeHandle()) } }
87 /**
88 * Tests whether the specified positive stream ID still has queued output.
89 */
90 public fun hasPendingOutput(streamId: Int): Boolean {
91 if (streamId <= 0) throw IllegalArgumentException(Some("invalid HTTP/2 stream ID"))
92 @Unsafe { return http2Pending(nativeHandle(), streamId) != 0 }
93 }
95 private fun nativeHandle(): ULong {
96 if (handle == 0UL) throw IllegalStateException(Some("HTTP/2 session is closed"))
97 return handle
98 }
100 @Unsafe private fun check(code: Int, operation: String, id: Int = 0, scope: HttpFailureScope = HttpFailureScope.Operation) {
101 if (code < 0) throw http2Failure(operation, code, String.fromCString(http2Error(nativeHandle())), id, scope)
102 }
104 private fun applyUpgrade(payload: Array<Byte>, head: Boolean) {
105 @Unsafe {
106 val code = payload.withDataPointer { pointer, size ->
107 @Unsafe { return@withDataPointer http2Upgrade(nativeHandle(), pointer, size, if (head) 1 else 0) }
108 }
109 check(code, "upgrade HTTP/2 session")
110 }
111 }
113 /**
114 * Consumes up to count readable input bytes, advancing the buffer by the returned count. Drain
115 * queued events after feeding input.
116 */
117 public fun receive(buffer: NativeByteBuffer, count: Long = buffer.readableBytes): Long =
118 receiveBytes(nativeHandle(), buffer, count, false)
120 /**
121 * Consumes input and returns total and per-stream input progress for this call.
122 */
123 public fun receiveWithProgress(buffer: NativeByteBuffer, count: Long = buffer.readableBytes): Http2ReceiveResult {
124 val owned = nativeHandle()
125 val received = receiveBytes(owned, buffer, count, true)
126 if (received == 0L) return Http2ReceiveResult(0L, ArrayList<Http2InputProgress>().toArray())
127 @Unsafe { return Http2ReceiveResult(received, http2ReadInputProgress(owned)) }
128 }
130 private fun receiveBytes(owned: ULong, buffer: NativeByteBuffer, count: Long, capture: Boolean): Long {
131 if (count < 0L || count > buffer.readableBytes) throw IllegalArgumentException(Some("invalid HTTP/2 input count"))
132 if (count == 0L) return 0L
133 @Unsafe {
134 val step = buffer.withReadableBytes { pointer, _ ->
135 @Unsafe { return@withReadableBytes http2Receive(owned, pointer!!, count, if (capture) 1 else 0) }
136 }
137 buffer.skip(step.count)
138 check(step.code, "receive HTTP/2", 0, HttpFailureScope.Connection)
139 return step.count
140 }
141 }
143 /**
144 * Copies up to count outgoing bytes into the writable buffer and advances its writer position.
145 */
146 public fun takeOutput(buffer: NativeByteBuffer, count: Long = buffer.writableBytes): Long =
147 takeOutputChunk(buffer, count).count
149 /**
150 * Copies an output chunk and returns its byte count, stream ID, and category.
151 */
152 public fun takeOutputChunk(buffer: NativeByteBuffer, count: Long = buffer.writableBytes): Http2OutputChunk {
153 val owned = nativeHandle()
154 if (count < 0L || count > buffer.writableBytes) throw IllegalArgumentException(Some("invalid HTTP/2 output capacity"))
155 if (count == 0L) return Http2OutputChunk(0L, 0, Http2OutputKind.Control)
156 @Unsafe {
157 val borrow = buffer.borrowWritable(count)
158 val step = try { http2Output(owned, borrow.pointer()!!, count) }
159 catch (error: Throwable) { borrow.complete(0L); throw error }
160 borrow.complete(step.count)
161 check(step.code, "produce HTTP/2 output", 0, HttpFailureScope.Connection)
162 val kind = when (step.kind) {
163 case 0 -> Http2OutputKind.Control
164 case 1 -> Http2OutputKind.Headers
165 case 2 -> Http2OutputKind.Data
166 else -> throw IllegalStateException(Some("invalid native HTTP/2 output kind"))
167 }
168 return Http2OutputChunk(step.count, step.streamId, kind)
169 }
170 }
172 /**
173 * Queues a request and returns its new stream ID. Set endStream=false before writing a body or
174 * trailers.
175 */
176 public fun submitRequest(head: HttpRequestHead, endStream: Boolean = true): Int {
177 val owned = nativeHandle()
178 val fields = http2RequestFields(head)
179 try {
180 @Unsafe {
181 val id = http2Request(owned, fields.handle, if (endStream) 1 else 0, fields.length)
182 check(id, "submit HTTP/2 request")
183 return id
184 }
185 } finally { fields.close() }
186 }
188 /**
189 * Queues response headers for a stream; set endStream=false when body or trailers follow.
190 */
191 public fun submitResponse(streamId: Int, head: HttpResponseHead, endStream: Boolean = true) {
192 val owned = nativeHandle()
193 val fields = http2ResponseFields(head)
194 try { @Unsafe { check(http2Response(owned, streamId, fields.handle, head.status.toInt(),
195 if (endStream) 1 else 0, fields.length), "submit HTTP/2 response", streamId) } }
196 finally { fields.close() }
197 }
199 /**
200 * Queues body bytes and advances by the accepted count. Short writes or zero require draining
201 * output and/or receiving window updates.
202 */
203 public fun writeBody(streamId: Int, buffer: NativeByteBuffer, count: Long = buffer.readableBytes): Long {
204 val owned = nativeHandle()
205 if (count < 0L || count > buffer.readableBytes) throw IllegalArgumentException(Some("invalid HTTP/2 body count"))
206 @Unsafe {
207 val step = buffer.withReadableBytes { pointer, _ ->
208 @Unsafe { return@withReadableBytes http2Write(owned, streamId, pointer, count) }
209 }
210 buffer.skip(step.count)
211 check(step.code, "write HTTP/2 body", streamId)
212 return step.count
213 }
214 }
216 /**
217 * Ends this stream's outgoing body, optionally with trailers; queued bytes still need to be
218 * drained.
219 */
220 public fun finish(streamId: Int, trailers: List<HttpField> = ArrayList<HttpField>()) {
221 val owned = nativeHandle()
222 val fields = Http2Fields()
223 try {
224 fields.addRegular(trailers, true)
225 @Unsafe { check(http2Finish(owned, streamId, fields.handle), "finish HTTP/2 body", streamId) }
226 } finally { fields.close() }
227 }
229 /**
230 * Acknowledges DATA bytes actually read or discarded by the application so flow-control credit
231 * can be returned.
232 */
233 public fun consume(streamId: Int, count: Long) {
234 @Unsafe { check(http2Consume(nativeHandle(), streamId, count), "consume HTTP/2 body", streamId) }
235 }
237 /**
238 * Queues RST_STREAM and abandons the stream's unconsumed body; the default code is CANCEL.
239 */
240 public fun reset(streamId: Int, code: UInt = 8U) {
241 if (streamId <= 0) throw IllegalArgumentException(Some("invalid HTTP/2 stream ID"))
242 @Unsafe { check(http2Reset(nativeHandle(), streamId, code), "reset HTTP/2 stream", streamId) }
243 }
245 /**
246 * Queues GOAWAY with optional debug bytes and last accepted stream ID; output still needs to
247 * be drained.
248 */
249 public fun goAway(code: UInt = 0U, debugData: List<Byte> = ArrayList<Byte>(), lastStreamId: Int? = None) {
250 val owned = nativeHandle()
251 val last = lastStreamId ?: -1
252 if (lastStreamId != None && last < 0) throw IllegalArgumentException(Some("invalid last HTTP/2 stream ID"))
253 @Unsafe {
254 val result = debugData.toArray().withDataPointer { pointer, size ->
255 @Unsafe { return@withDataPointer http2Goaway(owned, last, code, pointer, size) }
256 }
257 check(result, "submit HTTP/2 GOAWAY")
258 }
259 }
261 /**
262 * Reports transport EOF and validates whether the protocol input ended cleanly.
263 */
264 public fun endInput() { @Unsafe { check(http2End(nativeHandle()), "finish HTTP/2 input", 0, HttpFailureScope.Connection) } }
266 /**
267 * Removes the next queued event, or returns None when none is ready.
268 */
269 public fun nextEvent(): Http2Event? {
270 @Unsafe {
271 val event = http2Next(nativeHandle())
272 if (event == 0UL) return None
273 try { return Some(http2ReadEvent(event)) }
274 finally { httpEventFree(event) }
275 }
276 }
278 /**
279 * Releases codec state without sending, finishing, or closing a transport.
280 */
281 public override fun close() {
282 val owned = handle
283 handle = 0UL
284 if (owned != 0UL) @Unsafe { http2Free(owned) }
285 }