scoop:scoop.http.asyncio:0.1.0
src/http1_connection.scoop
Selected production source · src/http1_connection.scoop
1
package scoop.http.asyncio3
import scoop.asyncio.*4
import scoop.http.*5
import scoop.platform.memory.NativeByteBuffer6
import scoop.time.Duration7
import scoop.time.TimeMark9
/**10
* A received request head paired with its single-pass asynchronous body.11
*/12
public class Http1IncomingRequest internal constructor(13
/**14
* The received protocol head, preserving the original ordered fields.15
*/16
public val head: HttpRequestHead,17
/**18
* The single-pass input body associated with this head.19
*/20
public val body: AsyncHttp1Body21
)23
/**24
* A received response head, single-pass body, and optional captured first-byte timestamp.25
*/26
public class Http1IncomingResponse internal constructor(27
/**28
* The received protocol head, preserving the original ordered fields.29
*/30
public val head: HttpResponseHead,31
/**32
* The single-pass input body associated with this head.33
*/34
public val body: AsyncHttp1Body,35
/**36
* The first received response-byte time when timing collection is enabled.37
*/38
public val firstByteAt: TimeMark?39
)41
/**42
* An HTTP/1 client or server over an already-established asynchronous transport. It owns transport43
* cleanup and serializes each direction. Complete each message body before reusing that direction44
* or transferring an upgraded transport.45
*/46
public class AsyncHttp1Connection internal constructor(47
internal val state: H1State48
): AsyncCloseable {49
/**50
* Factories that transfer an established transport to structured protocol tasks.51
*/52
public companion object {53
/**54
* Takes an already-established transport as an HTTP client. The supplied scope owns55
* connection tasks; TCP connection and TLS handshake must already be complete.56
*/57
public suspend fun <T> takeOwnershipAsClient(58
transport: T,59
scope: CoroutineScope,60
options: Http1ReceiveOptions = Http1ReceiveOptions(),61
limits: Http1Limits = Http1Limits(),62
ioTimeouts: HttpIoTimeoutOptions = HttpIoTimeoutOptions(),63
captureTimings: Boolean = false64
): AsyncHttp1Connection65
where T: AsyncByteStream, T: AsyncCloseable =66
adoptH1(67
transport,68
transport,69
scope,70
HttpRole.Client,71
options,72
limits,73
ioTimeouts,74
captureTimings75
)77
/**78
* Takes an already-established transport as an HTTP server. The supplied scope owns79
* connection tasks; TCP connection and TLS handshake must already be complete.80
*/81
public suspend fun <T> takeOwnershipAsServer(82
transport: T,83
scope: CoroutineScope,84
options: Http1ReceiveOptions = Http1ReceiveOptions(),85
limits: Http1Limits = Http1Limits(),86
ioTimeouts: HttpIoTimeoutOptions = HttpIoTimeoutOptions()87
): AsyncHttp1Connection88
where T: AsyncByteStream, T: AsyncCloseable =89
adoptH1(transport, transport, scope, HttpRole.Server, options, limits, ioTimeouts)90
}92
/**93
* The local HTTP client or server role.94
*/95
public val role: HttpRole get() = state.encoder.role96
/**97
* The default I/O idle deadlines used by this connection.98
*/99
public val ioTimeouts: HttpIoTimeoutOptions get() = state.ioTimeouts100
/**101
* Whether connection cleanup has completed.102
*/103
public val isClosed: Boolean get() = state.lock.withLock { state.closed }104
/**105
* The captured first-byte time of the pending response, when timing collection is enabled and106
* input has arrived.107
*/108
public val pendingResponseFirstByteAt: TimeMark? get() =109
state.lock.withLock {110
if (state.captureTimings)111
state.responseStarts!!.firstOrNone()112
else113
None114
}115
/**116
* Whether both message directions and protocol state currently allow another exchange on this117
* connection.118
*/119
public val isReusable: Boolean get() =120
state.lock.withLock {121
!state.closing &&122
!state.inputEnded &&123
!state.closeAfterOutput &&124
!state.readBusy &&125
!state.writeBusy &&126
!present(state.incoming) &&127
!present(state.outgoing) &&128
state.clientPending ==129
0L &&130
state.requests.size ==131
0L &&132
!state.encoder.mustClose &&133
!state.encoder.isSwitched &&134
!state.decoder.isSwitched135
}136
/**137
* Begins a client request with explicit body framing and returns its writer. Finish the writer138
* even for an empty body.139
*/140
public suspend fun sendRequest(141
head: HttpRequestHead,142
body: Http1BodyFraming = Http1BodyFraming.Empty,143
writeIdle: Duration? = ioTimeouts.writeIdle144
): AsyncHttp1Writer = sendH1Request(state, head, body, writeIdle)145
/**146
* Begins a server response with explicit body framing and returns its writer.147
*/148
public suspend fun sendResponse(149
head: HttpResponseHead,150
body: Http1BodyFraming = Http1BodyFraming.Empty,151
writeIdle: Duration? = ioTimeouts.writeIdle152
): AsyncHttp1Writer = sendH1Response(state, head, body, writeIdle)153
/**154
* Sends and completes a response with an already-buffered body. The source cursor records155
* actual body progress, including a prefix accepted before failure.156
*/157
public suspend fun sendResponse(158
head: HttpResponseHead,159
buffer: NativeByteBuffer,160
count: Long = buffer.readableBytes,161
writeIdle: Duration? = ioTimeouts.writeIdle162
) {163
sendH1BufferedResponse(state, head, buffer, count, writeIdle)164
}165
/**166
* Sends an immutable byte prefix through the connection's reusable output buffer. Optional167
* progress remains readable after success or failure and excludes response-header bytes.168
*/169
public suspend fun sendResponse(170
head: HttpResponseHead,171
bytes: Array<Byte>,172
count: Long = bytes.size,173
writeIdle: Duration? = ioTimeouts.writeIdle,174
progress: Http1ResponseProgress? = None175
) {176
sendH1ArrayResponse(state, head, bytes, count, writeIdle, progress)177
}178
/**179
* Receives the next request head and body, or None at clean connection EOF.180
*/181
public suspend fun receiveRequest(182
readIdle: Duration? = ioTimeouts.readIdle183
): Http1IncomingRequest? = receiveH1Request(state, readIdle)184
/**185
* Receives a response associated with the previously submitted request context.186
*/187
public suspend fun receiveResponse(188
readIdle: Duration? = ioTimeouts.readIdle189
): Http1IncomingResponse {190
val response = receiveH1Response(state, readIdle)191
closeAfterH1Input(state, response.body.body)192
return response193
}194
/**195
* Transfers ownership after a completed protocol-switch boundary, preserving all already-read196
* suffix bytes.197
*/198
public suspend fun takeTransport(): HttpTransport = handoffH1(state)199
/**200
* Closes the connection and waits for owned transport I/O and cleanup.201
*/202
public override suspend fun close() {203
closeH1(state)204
}205
}207
private suspend fun adoptH1(208
transport: AsyncByteStream,209
owner: AsyncCloseable,210
scope: CoroutineScope,211
role: HttpRole,212
options: Http1ReceiveOptions,213
limits: Http1Limits,214
ioTimeouts: HttpIoTimeoutOptions,215
captureTimings: Boolean = false216
): AsyncHttp1Connection {217
val loop = currentEventLoop()218
val caller = httpJob(loop, true)219
if (scope.job.isCompleted)220
throw IllegalStateException(Some("HTTP connection scope is closed"))221
scope.job.ensureActive()222
requireHttpIoTimeouts(ioTimeouts)223
val state =224
allocateH1(transport, owner, loop, role, options, limits, ioTimeouts, captureTimings)225
try {226
awaitHttpOwnerStart(caller) {227
ready -> scope.launch suspend {228
val job = httpJob(loop, true)229
suspendCoroutine<Unit> {230
continuation ->231
state.lock.withLock {232
caller.ensureActive()233
job.ensureActive()234
state.ownerJob = Some(job)235
state.ownerWaiter = Some(continuation)236
state.adopted = true237
}238
val listener =239
job.invokeOnCancellation {240
error ->241
state.lock.withLock { terminateH1(state, error) }242
driveH1Close(state)243
}244
val closed =245
state.lock.withLock {246
if (state.closed)247
true248
else {249
state.ownerListener = Some(listener);250
false251
}252
}253
if (closed)254
listener.dispose()255
ready.trySend(Unit)256
}257
}258
}260
caller.ensureActive()261
state.lock.withLock {262
if (state.closing)263
throw (state.primary ?: IoClosedException());264
Unit265
}266
return AsyncHttp1Connection(state)267
} catch (error: Throwable) {268
if (!state.lock.withLock { state.adopted }) {269
try {270
releaseH1Buffers(state)271
}272
catch (cleanup: Throwable) {273
throw ResourceUseException(error, cleanup)274
}275
throw error276
}277
failH1Operation(state, error)278
}279
}281
private fun allocateH1(282
transport: AsyncByteStream,283
owner: AsyncCloseable,284
loop: EventLoop,285
role: HttpRole,286
options: Http1ReceiveOptions,287
limits: Http1Limits,288
ioTimeouts: HttpIoTimeoutOptions,289
captureTimings: Boolean290
): H1State {291
val decoder =292
if (role == HttpRole.Client)293
Http1Decoder.client(options, limits)294
else295
Http1Decoder.server(options, limits)296
val input =297
try {298
NativeByteBuffer.allocate(16384L)299
}300
catch (error: Throwable) {301
decoder.close();302
throw error303
}304
try {305
return H1State(306
decoder,307
Http1Encoder(role),308
transport,309
owner,310
loop,311
input,312
NativeByteBuffer.allocate(16384L),313
ioTimeouts,314
captureTimings315
)316
}317
catch (error: Throwable) {318
decoder.close();319
input.close();320
throw error321
}322
}