scoop:scoop.http:0.1.0
src/http1_decoder.scoop
Selected production source · src/http1_decoder.scoop
1
package scoop.http3
import scoop.platform.memory.NativeByteBuffer5
/**6
* One decoded HTTP/1 event. A message head is followed by body/trailer events and End; Switch7
* marks transfer to another protocol.8
*/9
public enum Http1Event {10
/**11
* A complete incoming request head.12
*/13
Request(HttpRequestHead),14
/**15
* An incoming response head, including informational responses.16
*/17
Response(HttpResponseHead),18
/**19
* An owned body-byte chunk.20
*/21
Data(Array<Byte>),22
/**23
* Ordered trailer fields after the body.24
*/25
Trailers(Array<HttpField>),26
/**27
* The current message ended; the Boolean indicates that the connection must close.28
*/29
End(Boolean),30
/**31
* The decoder reached a protocol-switch boundary and leaves the unread suffix in the input32
* buffer.33
*/34
Switch35
}37
/**38
* Input bytes consumed and messages started in this call, including partial start lines and39
* informational responses; zero input yields two zero counts.40
*/41
public struct Http1ReceiveResult(val count: Long, val startedMessages: Long)43
/**44
* An incremental in-memory HTTP/1 decoder. Register client request methods in order, feed bytes,45
* and drain events; serialize operations on one instance and close it explicitly.46
*/47
public class Http1Decoder private constructor(48
private var handle: ULong,49
/**50
* The fixed client/server role of this codec.51
*/52
public val role: HttpRole53
): Closeable {54
private var batch: ULong = 0UL55
private var pending: ULong = 0UL56
/**57
* Factories for explicitly owned client/server codec instances.58
*/59
public companion object {60
/**61
* Creates a client codec with the selected receive options and local limits.62
*/63
public fun client(64
options: Http1ReceiveOptions = Http1ReceiveOptions(),65
limits: Http1Limits = Http1Limits()66
): Http1Decoder = create(HttpRole.Client, options, limits)68
/**69
* Creates a server codec with the selected receive options and local limits.70
*/71
public fun server(72
options: Http1ReceiveOptions = Http1ReceiveOptions(),73
limits: Http1Limits = Http1Limits()74
): Http1Decoder = create(HttpRole.Server, options, limits)76
private fun create(77
role: HttpRole,78
options: Http1ReceiveOptions,79
limits: Http1Limits80
): Http1Decoder {81
val config = http1Config(options, limits)82
@Unsafe83
{84
val native =85
http1New(86
if (role == HttpRole.Server)87
188
else89
0,90
config91
)92
if (native == 0UL)93
throw HttpException(94
"create HTTP/1 decoder",95
HttpProtocol.Http1,96
HttpFailureScope.Operation,97
0,98
"llhttp 9.4.3",99
-1,100
"cannot allocate HTTP/1 decoder"101
)102
return Http1Decoder(native, role)103
}104
}105
}107
/**108
* Whether its state has been released.109
*/110
public val isClosed: Boolean get() = handle == 0UL111
/**112
* Whether parsing stopped at a protocol-switch boundary.113
*/114
public val isSwitched: Boolean get() {115
@Unsafe116
{117
return http1Switched(nativeHandle()) != 0118
}119
}121
private fun nativeHandle(): ULong {122
if (handle == 0UL)123
throw IllegalStateException(Some("HTTP/1 decoder is closed"))124
return handle125
}127
@Unsafe128
private fun check(129
code: Int,130
operation: String,131
scope: HttpFailureScope = HttpFailureScope.Connection132
) {133
if (code != 0)134
throw HttpException(135
operation,136
HttpProtocol.Http1,137
scope,138
0,139
"llhttp 9.4.3",140
code,141
String.fromCString(http1Error(nativeHandle())),142
http1IsUnexpectedEof(code) != 0143
)144
}146
/**147
* Queues the exact request method before client response parsing, enabling HEAD and CONNECT148
* response semantics.149
*/150
public fun expectResponse(method: List<Byte>) {151
val owned = nativeHandle()152
val bytes = method.toArray()153
requireHttp1Method(bytes)154
@Unsafe155
{156
val code =157
bytes.withDataPointer {158
pointer,159
count -> @Unsafe160
{161
return@withDataPointer http1Expect(owned, pointer, count)162
}163
}164
check(code, "register HTTP/1 response", HttpFailureScope.Operation)165
}166
}168
/**169
* Consumes up to count readable input bytes, advancing the buffer by the returned count. Drain170
* queued events after feeding input.171
*/172
public fun receive(buffer: NativeByteBuffer, count: Long = buffer.readableBytes): Long {173
val owned = nativeHandle()174
if (count < 0L || count > buffer.readableBytes)175
throw IllegalArgumentException(Some("invalid HTTP input count"))176
if (count == 0L)177
return 0L178
@Unsafe179
{180
val step =181
buffer.withReadableBytes {182
pointer,183
_ -> @Unsafe184
{185
return@withReadableBytes http1Receive(owned, pointer!!, count)186
}187
}188
buffer.skip(step.count)189
check(step.code, "receive HTTP/1")190
return step.count191
}192
}194
/**195
* Reports transport EOF and validates whether the protocol input ended cleanly.196
*/197
public fun endInput() {198
@Unsafe199
{200
check(http1End(nativeHandle()), "finish HTTP/1 input")201
}202
}204
/**205
* Consumes input and also reports how many messages started during this call.206
*/207
public fun receiveWithProgress(208
buffer: NativeByteBuffer,209
count: Long = buffer.readableBytes210
): Http1ReceiveResult {211
val consumed = receive(buffer, count)212
if (count == 0L)213
return Http1ReceiveResult(0L, 0L)214
@Unsafe215
{216
return Http1ReceiveResult(consumed, http1StartedMessages(nativeHandle()))217
}218
}220
/**221
* Resumes HTTP/1 parsing after the server declines a candidate upgrade.222
*/223
public fun resumeHttp1() {224
@Unsafe225
{226
check(http1Resume(nativeHandle()), "decline HTTP/1 upgrade", HttpFailureScope.Operation)227
}228
}230
/**231
* Removes the next queued event, or returns None when none is ready.232
*/233
public fun nextEvent(): Http1Event? {234
@Unsafe235
{236
val owned = nativeHandle()237
if (pending == 0UL) {238
batch = http1TakeEvents(owned)239
pending = batch240
}241
if (pending == 0UL)242
return None243
val event = httpEventView(pending)244
pending = event.next245
try {246
val info = event.info247
return Some(248
when (info.kind) {249
case 1 -> Http1Event.Request(250
HttpRequestHead(251
httpEventVersion(info),252
httpBytes(event.first),253
HttpRequestTarget.Http1(httpBytes(event.second)),254
httpEventFields(event)255
)256
)257
case 2 -> Http1Event.Response(258
HttpResponseHead(259
httpEventVersion(info),260
info.status.toUInt(),261
Some(httpBytes(event.first)),262
httpEventFields(event)263
)264
)265
case 3 -> Http1Event.Data(httpBytes(event.first))266
case 4 -> Http1Event.Trailers(httpEventFields(event))267
case 5 -> Http1Event.End(info.flags != 0U)268
case 6 -> Http1Event.Switch269
else -> throw IllegalStateException(Some("invalid native HTTP/1 event"))270
}271
)272
} finally {273
if (pending == 0UL) {274
val completed = batch275
batch = 0UL276
httpEventBatchFree(completed)277
}278
}279
}280
}282
/**283
* Releases codec state without sending, finishing, or closing a transport.284
*/285
public override fun close() {286
val owned = handle287
handle = 0UL288
if (owned != 0UL)289
@Unsafe290
{291
val remaining = batch292
batch = 0UL293
pending = 0UL294
if (remaining != 0UL)295
httpEventBatchFree(remaining)296
http1Free(owned)297
}298
}299
}