nish 0.42.0 → 0.45.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +11 -5
  2. package/docs/AI.md +287 -129
  3. package/package.json +9 -9
  4. package/runtime/core/numbers.mjs +3 -1
  5. package/runtime/core/strings.mjs +90 -38
  6. package/runtime/core.d.ts +24 -0
  7. package/runtime/core.mjs +21 -0
  8. package/runtime/nish.d.ts +167 -24
  9. package/runtime/nish.mjs +7 -1
  10. package/runtime/runtime-cross.c +9 -0
  11. package/runtime/runtime-net.c +51 -13
  12. package/runtime/runtime-region.c +13 -0
  13. package/runtime/runtime-text.c +11 -0
  14. package/runtime/runtime-uring.c +83 -25
  15. package/runtime/runtime-wasm.c +3 -0
  16. package/runtime/runtime.c +329 -6
  17. package/runtime/sqlite/README.md +16 -3
  18. package/runtime/sqlite/nish-sqlite.c +940 -29
  19. package/scripts/build.sh +111 -29
  20. package/skills/writing-nish/SKILL.md +12 -4
  21. package/std/README.md +6 -6
  22. package/std/array.ts +10 -2
  23. package/std/bytes.ts +239 -26
  24. package/std/cli-args.ts +1072 -606
  25. package/std/cli-flags.ts +180 -98
  26. package/std/cli.ts +21 -13
  27. package/std/collections.ts +245 -127
  28. package/std/compress/checksum.ts +32 -37
  29. package/std/compress/deflate.ts +1102 -542
  30. package/std/compress/gzip.ts +290 -145
  31. package/std/compress/zlib.ts +57 -21
  32. package/std/crypto/aes.ts +153 -75
  33. package/std/crypto/base64url.ts +163 -39
  34. package/std/crypto/bcrypt-batch.ts +164 -90
  35. package/std/crypto/bcrypt.ts +185 -107
  36. package/std/crypto/chacha20poly1305.ts +84 -68
  37. package/std/crypto/ct.ts +9 -7
  38. package/std/crypto/ed25519.ts +64 -27
  39. package/std/crypto/hkdf.ts +105 -63
  40. package/std/crypto/hmac.ts +95 -89
  41. package/std/crypto/jwt.ts +248 -126
  42. package/std/crypto/p256.ts +758 -444
  43. package/std/crypto/p384.ts +20 -13
  44. package/std/crypto/pki-roots.ts +95 -38
  45. package/std/crypto/pki.ts +164 -60
  46. package/std/crypto/rsa.ts +266 -223
  47. package/std/crypto/scram.ts +141 -0
  48. package/std/crypto/sha1.ts +157 -57
  49. package/std/crypto/sha256.ts +502 -422
  50. package/std/crypto/sha512.ts +204 -135
  51. package/std/crypto/x509-random.ts +9 -3
  52. package/std/crypto/x509.ts +331 -171
  53. package/std/host/ring.ts +1 -1
  54. package/std/host/text.ts +1 -1
  55. package/std/json-equal.ts +35 -19
  56. package/std/json-format.ts +215 -108
  57. package/std/json-number.ts +126 -72
  58. package/std/json-pointer.ts +42 -13
  59. package/std/json-tokenizer.ts +498 -307
  60. package/std/json-typed.ts +115 -36
  61. package/std/json-value.ts +341 -152
  62. package/std/json.ts +300 -158
  63. package/std/net/buffer-pool.ts +17 -7
  64. package/std/net/dns-config.ts +427 -236
  65. package/std/net/dns-message.ts +114 -47
  66. package/std/net/dns-resolver.ts +736 -237
  67. package/std/net/dns.ts +205 -52
  68. package/std/net/fetch.ts +320 -184
  69. package/std/net/grpc.ts +948 -0
  70. package/std/net/handler.ts +1276 -218
  71. package/std/net/hpack.ts +395 -180
  72. package/std/net/http-compress.ts +502 -65
  73. package/std/net/http-fields.ts +85 -49
  74. package/std/net/http-server.ts +1764 -603
  75. package/std/net/http1-client-codec.ts +372 -161
  76. package/std/net/http1-codec.ts +665 -331
  77. package/std/net/http1-server.ts +881 -269
  78. package/std/net/http2-cleartext.ts +165 -95
  79. package/std/net/http2-frame.ts +232 -89
  80. package/std/net/http2-tls.ts +42 -12
  81. package/std/net/http2.ts +327 -101
  82. package/std/net/http3-frame.ts +68 -33
  83. package/std/net/http3-server.ts +672 -206
  84. package/std/net/http3.ts +669 -191
  85. package/std/net/oidc.ts +63 -24
  86. package/std/net/outbound.ts +207 -142
  87. package/std/net/postgres-async.ts +1223 -470
  88. package/std/net/postgres-carrier.ts +575 -372
  89. package/std/net/postgres.ts +1521 -632
  90. package/std/net/prefork.ts +254 -98
  91. package/std/net/protobuf.ts +1017 -0
  92. package/std/net/qpack.ts +143 -92
  93. package/std/net/quic-conn-ack.ts +104 -22
  94. package/std/net/quic-conn-cid.ts +66 -26
  95. package/std/net/quic-conn-params.ts +13 -7
  96. package/std/net/quic-datagram.ts +90 -27
  97. package/std/net/quic-frame.ts +324 -121
  98. package/std/net/quic-listener.ts +206 -91
  99. package/std/net/quic-packet.ts +289 -163
  100. package/std/net/quic-recovery.ts +279 -128
  101. package/std/net/quic-stream.ts +466 -167
  102. package/std/net/quic.ts +584 -258
  103. package/std/net/router.ts +450 -99
  104. package/std/net/serve.ts +661 -240
  105. package/std/net/static.ts +1458 -0
  106. package/std/net/tls/client.ts +140 -45
  107. package/std/net/tls/codec.ts +510 -260
  108. package/std/net/tls/record-client.ts +268 -76
  109. package/std/net/tls/record-server.ts +236 -79
  110. package/std/net/tls/record.ts +173 -47
  111. package/std/net/tls/schedule.ts +58 -39
  112. package/std/net/tls/ticket.ts +295 -103
  113. package/std/net/tls/verify.ts +1 -1
  114. package/std/net/tls-tcp.ts +218 -75
  115. package/std/net/tls.ts +260 -152
  116. package/std/net/upstream.ts +283 -86
  117. package/std/net/url.ts +277 -102
  118. package/std/net/websocket.ts +532 -209
  119. package/std/net/webtransport.ts +755 -436
  120. package/std/regex.ts +1659 -829
  121. package/std/sqlite.ts +325 -0
  122. package/std/sync/ring.ts +320 -156
  123. package/std/sync/shm.ts +53 -6
  124. package/std/text.ts +285 -135
  125. package/std/threads.ts +22 -2
@@ -0,0 +1,948 @@
1
+ /**
2
+ * `nish/net/grpc` — Unary and streaming gRPC calls on `nish/net/http-server`'s HTTP/2
3
+ * listeners (`listenHttp2Tls` and `listenH2c`). A call is a route: its
4
+ * `:path` is `/<package>.<Service>/<Method>`, so the program adds it to the
5
+ * server's `Router` as any other path, takes the request, and hands it here
6
+ * to be read as a call and answered.
7
+ *
8
+ * import { GrpcLimits, GrpcServer, GRPC_CALL } from "nish/net/grpc";
9
+ * import { ProtoReader, ProtoWriter } from "nish/net/protobuf";
10
+ *
11
+ * const grpc = new GrpcServer(server, new GrpcLimits());
12
+ * const getSum: i32 = router.add("POST", "/benchmark.BenchmarkService/GetSum");
13
+ * // ... after server.wait(...):
14
+ * while (server.ready()) {
15
+ * const r = server.take();
16
+ * if (r.route === getSum && grpc.call(r) === GRPC_CALL) {
17
+ * const msg = new ProtoReader(r.body, grpc.messageStart(r), grpc.messageEnd(r));
18
+ * // ... decode, compute, encode the reply into w ...
19
+ * grpc.reply(r, w.buf, 0, w.end);
20
+ * }
21
+ * }
22
+ *
23
+ * **`call` reads the request and answers every fault itself.** A
24
+ * `content-type` other than `application/grpc` or `application/grpc+proto`
25
+ * is answered 415, and a request that did not come on HTTP/2 is answered 505,
26
+ * as plain HTTP. The rest are gRPC statuses in the Trailers-Only form (one
27
+ * HEADERS frame carrying `grpc-status`, ending the stream): a malformed
28
+ * `grpc-timeout` is `INTERNAL`, a call already past its deadline
29
+ * `DEADLINE_EXCEEDED`, a compressed message `UNIMPLEMENTED` (no
30
+ * `grpc-encoding` is offered), a declared length past `maxMessage`
31
+ * `RESOURCE_EXHAUSTED`, and a body that is not exactly one length-prefixed
32
+ * message `INTERNAL`. It answers `GRPC_CALL` only for a call the program now
33
+ * owes an answer, whose message is `r.body[messageStart(r) .. messageEnd(r))`.
34
+ *
35
+ * **A call's deadline** runs from when the server read its head: its
36
+ * `grpc-timeout`, capped at `limits.maxTimeout`, or `maxTimeout` when it has
37
+ * none. `reply`, `fail`, `send` and `finish` answer `DEADLINE_EXCEEDED` instead of the
38
+ * program's answer once it has passed.
39
+ *
40
+ * **The answer** is `:status` 200 and `content-type: application/grpc`, then
41
+ * the length-prefixed reply, then a trailer section with `grpc-status: 0`
42
+ * (`reply`); or a gRPC error (`fail`): Trailers-Only when it has no message,
43
+ * and a head followed by a trailer section with `grpc-status` and the
44
+ * percent-encoded `grpc-message` when it has one.
45
+ *
46
+ * **Streaming calls.** A server-streaming call's request is one message, so
47
+ * `call` reads it; the program then sends its replies with `send`, one
48
+ * message each, and ends the call with `finish(r, GRPC_OK, "")`. A
49
+ * client-streaming or bidirectional call's request is a stream of messages:
50
+ * the program marks its route with `server.streamBody(route)`, reads the
51
+ * call with `open`, and its messages with `next`, each time `take` hands the
52
+ * request over:
53
+ *
54
+ * let s = grpc.next(r);
55
+ * while (s === GRPC_MESSAGE) {
56
+ * const m = new ProtoReader(grpc.messageBytes(r), grpc.messageStart(r), grpc.messageEnd(r));
57
+ * // ... decode m, perhaps send(r, ...) a reply ...
58
+ * s = grpc.next(r);
59
+ * }
60
+ * if (s === GRPC_END) {
61
+ * grpc.finish(r, GRPC_OK, "");
62
+ * } // GRPC_MORE: wait for the next piece; GRPC_ANSWERED: r is the server's again
63
+ *
64
+ * `next` answers the faults `call` does, message by message, and a client
65
+ * that hung up (`CANCELLED`). `send` never blocks: it answers the bytes still
66
+ * queued, and a program that sends faster than the client reads stops above
67
+ * a budget of its own until `pending(r)` drains. A body the server streams
68
+ * is not under `bodyTimeout`, so a program waiting on a slow client checks
69
+ * `expired(r)` each turn and ends the call itself; `next`, `send` and
70
+ * `finish` answer `DEADLINE_EXCEEDED` once it has passed.
71
+ *
72
+ * The record of what this module refuses and why is `docs/security/grpc.md`.
73
+ */
74
+ import { tryCopyBytes } from "nish/bytes"
75
+ import { HANDLER_ABSENT, HANDLER_DROPPED, HANDLER_SENT } from "nish/net/handler"
76
+ import { httpFieldBytes } from "nish/net/http-fields"
77
+ import { HTTP1_CHUNKED } from "nish/net/http1-codec"
78
+ import { HttpServer, HttpServerRequest } from "nish/net/http-server"
79
+
80
+ /** The call succeeded. */
81
+ export const GRPC_OK: i32 = 0
82
+ /** The call was cancelled, usually by the caller. */
83
+ export const GRPC_CANCELLED: i32 = 1
84
+ /** An error with no better status. */
85
+ export const GRPC_UNKNOWN: i32 = 2
86
+ /** The caller's argument is invalid, whatever the server's state. */
87
+ export const GRPC_INVALID_ARGUMENT: i32 = 3
88
+ /** The deadline passed before the call was answered. */
89
+ export const GRPC_DEADLINE_EXCEEDED: i32 = 4
90
+ /** Something the call names was not found. */
91
+ export const GRPC_NOT_FOUND: i32 = 5
92
+ /** Something the call would create already exists. */
93
+ export const GRPC_ALREADY_EXISTS: i32 = 6
94
+ /** The caller may not do this. */
95
+ export const GRPC_PERMISSION_DENIED: i32 = 7
96
+ /** A resource ran out, a message too long for the server among them. */
97
+ export const GRPC_RESOURCE_EXHAUSTED: i32 = 8
98
+ /** The system is not in the state the call needs. */
99
+ export const GRPC_FAILED_PRECONDITION: i32 = 9
100
+ /** The call was aborted, usually by a conflict. */
101
+ export const GRPC_ABORTED: i32 = 10
102
+ /** A value was past the valid range. */
103
+ export const GRPC_OUT_OF_RANGE: i32 = 11
104
+ /** The method, or a feature the call asks for, is not implemented. */
105
+ export const GRPC_UNIMPLEMENTED: i32 = 12
106
+ /** An invariant the protocol or the server expects is broken. */
107
+ export const GRPC_INTERNAL: i32 = 13
108
+ /** The service is unavailable for now; the call may be retried. */
109
+ export const GRPC_UNAVAILABLE: i32 = 14
110
+ /** Data was lost or corrupted beyond recovery. */
111
+ export const GRPC_DATA_LOSS: i32 = 15
112
+ /** The caller is not authenticated. */
113
+ export const GRPC_UNAUTHENTICATED: i32 = 16
114
+
115
+ /** `call`'s answer for a call the program now owes an answer. */
116
+ export const GRPC_CALL: i32 = 1
117
+ /** `call`'s answer when it answered the request itself, with an HTTP status or a gRPC error; the request is the server's again. */
118
+ export const GRPC_ANSWERED: i32 = 0
119
+ /** `next`'s answer when it found a request message: `messageBytes(r)[messageStart(r) .. messageEnd(r))`. */
120
+ export const GRPC_MESSAGE: i32 = 2
121
+ /** `next`'s answer when the next message has not all arrived: wait until `take` hands the request over again. */
122
+ export const GRPC_MORE: i32 = 3
123
+ /** `next`'s answer when the client's stream of messages ended; the program ends the call with `finish`. */
124
+ export const GRPC_END: i32 = 4
125
+ /** `send`'s answer once the call is over: answered past its deadline, or its stream or connection gone. */
126
+ export const GRPC_ENDED: i32 = -1
127
+
128
+ /** A request index no call holds. */
129
+ const GRPC_IDLE: i32 = 0
130
+ /** A call read by `call` or `open`, whose answer has not begun. */
131
+ const GRPC_OPEN: i32 = 1
132
+ /** A call whose answer's head is sent: what is left is messages, then trailers. */
133
+ const GRPC_BEGUN: i32 = 2
134
+ /** A call that is answered, or whose stream is gone: the request is the server's again. */
135
+ const GRPC_OVER: i32 = 3
136
+ /** The largest per-call message buffer kept once its call is over. */
137
+ const GRPC_KEEP: i32 = 65536
138
+ /** The size a call's message buffer first grows to, before it doubles. */
139
+ const GRPC_GROW_FROM: i32 = 1024
140
+
141
+ /** The length prefix: one compressed-flag byte and a four-byte big-endian length. */
142
+ const GRPC_PREFIX: i32 = 5
143
+ /** The HTTP status of every answer that reaches gRPC's own framing. */
144
+ const GRPC_HTTP_OK: i32 = 200
145
+ /** The HTTP status of a call over HTTP/1.1 or HTTP/3. */
146
+ const GRPC_HTTP_VERSION_NOT_SUPPORTED: i32 = 505
147
+ /** The HTTP status of a request whose `content-type` is not gRPC's. */
148
+ const GRPC_HTTP_UNSUPPORTED_MEDIA_TYPE: i32 = 415
149
+ /** The most digits `grpc-timeout` may carry before its unit. */
150
+ const GRPC_TIMEOUT_DIGITS: i32 = 8
151
+ const GRPC_NANOS_PER_MS: i64 = 1000000
152
+
153
+ /** The caps a `GrpcServer` holds its calls to. */
154
+ export class GrpcLimits {
155
+ /** The longest request message, in bytes, the length prefix may declare; past it a call is `RESOURCE_EXHAUSTED`. 0 to 2^30. The server's `maxBody` caps the whole body first, answering 413. */
156
+ maxMessage: i32 = 4194304
157
+ /** The longest deadline a call is given, in milliseconds from its head, whatever its `grpc-timeout` asks. 1 to 2^31 - 1. */
158
+ maxTimeout: i32 = 30000
159
+ }
160
+
161
+ /**
162
+ * `a + b`, worked in `i64` and held to `i32`. Every caller adds an offset
163
+ * and a length that lie inside one array, so the sum is an index into it or
164
+ * just past it and always fits.
165
+ */
166
+ const grpcAdd = (a: i32, b: i32): i32 => toI32(toI64(a) + toI64(b))
167
+
168
+ /** `a - b`, worked as `grpcAdd` is, for offsets and lengths inside one array. */
169
+ const grpcSub = (a: i32, b: i32): i32 => toI32(toI64(a) - toI64(b))
170
+
171
+ /**
172
+ * A zeroed array of `n` bytes, or of none when `n` is below zero. Up to
173
+ * 65535 bytes is one allocation; past that the array grows a byte at a time
174
+ * from a 65535-byte start, which an `i32` length cannot make fail.
175
+ */
176
+ const grpcBytes = (n: i32): u8[] => {
177
+ if (n < 0) {
178
+ return []
179
+ }
180
+ if (n <= 65535) {
181
+ return new Array<u8>(toU16(n))
182
+ }
183
+ const out: u8[] = new Array<u8>(65535)
184
+ for (let k: i32 = 65535; k < n; k += 1) {
185
+ out.push(0)
186
+ }
187
+ return out
188
+ }
189
+
190
+ /** The answer `grpcPrefixLength` gives for a compressed message. */
191
+ const GRPC_COMPRESSED: i64 = -2
192
+
193
+ /**
194
+ * The length the 5-byte message prefix at `body[at]` declares: 0 to 2^32 - 1
195
+ * for an uncompressed message, `GRPC_COMPRESSED` for a compressed one, and
196
+ * -1 for a flag byte that is neither, or a prefix not wholly inside `body`.
197
+ */
198
+ const grpcPrefixLength = (body: u8[], at: i32): i64 => {
199
+ // 5 is `GRPC_PREFIX`, written as the literal the bound proofs read.
200
+ if (at < 0 || at > toI32(body.length) - 5) {
201
+ return -1
202
+ }
203
+ const flag: i32 = toI32(body[at])
204
+ if (flag === 1) {
205
+ return GRPC_COMPRESSED
206
+ }
207
+ if (flag !== 0) {
208
+ return -1
209
+ }
210
+ return (
211
+ (toI64(body[at + 1]) << 24) |
212
+ (toI64(body[at + 2]) << 16) |
213
+ (toI64(body[at + 3]) << 8) |
214
+ toI64(body[at + 4])
215
+ )
216
+ }
217
+
218
+ /** `len`'s uncompressed length prefix, fresh: the server may hold it until it is sent. */
219
+ const grpcPrefix = (len: i32): u8[] => [
220
+ toU8(0),
221
+ toU8((len >> 24) & 255),
222
+ toU8((len >> 16) & 255),
223
+ toU8((len >> 8) & 255),
224
+ toU8(len & 255),
225
+ ]
226
+
227
+ /** What a `GrpcServer` keeps for the call at one request index. */
228
+ class GrpcCall {
229
+ /** `GRPC_IDLE` (0), `GRPC_OPEN`, `GRPC_BEGUN` or `GRPC_OVER`. */
230
+ state: i32 = 0
231
+ /** How many bytes at the front of `body` `next` has read and not yet handed back with `consume`. */
232
+ readAt: i32 = 0
233
+ /** The length of the message `next` is copying into `buf`, or -1 for none. */
234
+ want: i32 = -1
235
+ /** How many of that message's bytes are copied. */
236
+ have: i32 = 0
237
+ /** The buffer a message split across pieces is copied into. */
238
+ buf: u8[]
239
+ /** Whether the last message is in `buf`, not `body`. */
240
+ inBuf: boolean = false
241
+ /** Where the last message starts. */
242
+ start: i32 = 0
243
+ /** Where the last message ends. */
244
+ end: i32 = 0
245
+ /** The `since` of the request the call was opened for. */
246
+ since: i64 = 0
247
+ /** The `stream` of the request the call was opened for. */
248
+ stream: i64 = 0
249
+
250
+ constructor() {
251
+ this.buf = []
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Reads gRPC calls from an `HttpServer`'s HTTP/2 requests and answers them:
257
+ * unary calls (`call`, `reply`, `fail`) and streaming ones (`open`, `next`,
258
+ * `begin`, `send`, `finish`). What it keeps per call is indexed by the
259
+ * request's `index`, and is the call's until it is answered.
260
+ */
261
+ export class GrpcServer {
262
+ private server: HttpServer
263
+ private maxMessage: i32
264
+ private maxTimeout: i64
265
+ private contentType: u8[][]
266
+ private grpcType: u8[][]
267
+ /** `application/grpc`, the `content-type` of every answer. */
268
+ private grpcTypeBytes: u8[]
269
+ private okNames: u8[][]
270
+ private okValues: u8[][]
271
+ private onlyNames: u8[][]
272
+ private statusName: u8[]
273
+ private messageName: u8[]
274
+ /** `[grpc-status]`, the trailer names of a status with no message. */
275
+ private statusNames: u8[][]
276
+ /** Per request index: the call there, idle until `call` or `open` reads one. */
277
+ private calls: GrpcCall[]
278
+
279
+ /**
280
+ * A gRPC reader and answerer over `server`. Panics on a limit outside its range.
281
+ * @param server the server whose requests `call` reads and answers
282
+ * @param limits the message and deadline caps
283
+ */
284
+ constructor(server: HttpServer, limits: GrpcLimits) {
285
+ if (limits.maxMessage < 0 || limits.maxMessage > 1073741824) {
286
+ panic(`GrpcServer: maxMessage ${limits.maxMessage} is outside 0 to 2^30`)
287
+ }
288
+ if (limits.maxTimeout < 1) {
289
+ panic(`GrpcServer: maxTimeout ${limits.maxTimeout} is below 1`)
290
+ }
291
+ this.server = server
292
+ this.maxMessage = limits.maxMessage
293
+ this.maxTimeout = toI64(limits.maxTimeout) * GRPC_NANOS_PER_MS
294
+ const grpcType: u8[] = httpFieldBytes("application/grpc")
295
+ const contentType: u8[] = httpFieldBytes("content-type")
296
+ this.contentType = [contentType]
297
+ this.grpcType = [grpcType]
298
+ this.grpcTypeBytes = grpcType
299
+ this.statusName = httpFieldBytes("grpc-status")
300
+ this.messageName = httpFieldBytes("grpc-message")
301
+ this.okNames = [this.statusName]
302
+ this.okValues = [httpFieldBytes("0")]
303
+ this.onlyNames = [contentType, this.statusName]
304
+ this.statusNames = [this.statusName]
305
+ this.calls = []
306
+ }
307
+
308
+ /**
309
+ * Reads `r` as a unary call, or a server-streaming one: a request that is
310
+ * one message, whole. Answers it itself, and says so, when it is
311
+ * not one the program can answer: 415 for a `content-type` other than
312
+ * `application/grpc` or `application/grpc+proto`, 505 off HTTP/2, and
313
+ * otherwise a gRPC error in the Trailers-Only form (see the module's
314
+ * comment). Never panics on what the peer sent; panics on a request whose
315
+ * body comes in pieces (`streaming`), which `open` and `next` read.
316
+ * @param r a request `take` handed over and not yet answered
317
+ * @returns `GRPC_CALL` when the program owes `r` an answer through `reply`, `fail`, or `send` and `finish`, or `GRPC_ANSWERED` when `r` is the server's again
318
+ */
319
+ call(r: HttpServerRequest): i32 {
320
+ if (r.streaming) {
321
+ panic("GrpcServer.call: the request's body comes in pieces; read it with open and next")
322
+ }
323
+ if (!this.admit(r)) {
324
+ return GRPC_ANSWERED
325
+ }
326
+ const status: i32 = this.framing(r)
327
+ if (status !== GRPC_OK) {
328
+ this.only(r, status)
329
+ return GRPC_ANSWERED
330
+ }
331
+ const c: GrpcCall | null = this.slot(r)
332
+ if (c === null) {
333
+ this.only(r, GRPC_INTERNAL)
334
+ return GRPC_ANSWERED
335
+ }
336
+ c.start = GRPC_PREFIX
337
+ c.end = r.bodyLength
338
+ return GRPC_CALL
339
+ }
340
+
341
+ /**
342
+ * Reads `r` as a call whose request is a stream of messages, client
343
+ * streaming or bidirectional, whether its body comes in pieces (a route
344
+ * `HttpServer.streamBody` marked, on HTTP/2) or whole. Answers it itself,
345
+ * and says so, as `call` does: 415, 505, a malformed `grpc-timeout`
346
+ * (`INTERNAL`) or a deadline already past. Its messages are read with
347
+ * `next`. Never panics on what the peer sent.
348
+ * @param r a request `take` handed over and not yet answered
349
+ * @returns `GRPC_CALL` when the program owes `r` an answer, or `GRPC_ANSWERED` when `r` is the server's again
350
+ */
351
+ open(r: HttpServerRequest): i32 {
352
+ if (!this.admit(r)) {
353
+ return GRPC_ANSWERED
354
+ }
355
+ if (this.slot(r) === null) {
356
+ this.only(r, GRPC_INTERNAL)
357
+ return GRPC_ANSWERED
358
+ }
359
+ return GRPC_CALL
360
+ }
361
+
362
+ /**
363
+ * Reads the call's next request message, across as many DATA frames as it
364
+ * came in. A message whole in `r.body` is read in place; one split across
365
+ * pieces is copied, piece by piece, into a buffer of the call's, each
366
+ * piece handed back with `consume` so the client may send more. Answers
367
+ * the call itself, and returns `GRPC_ANSWERED`, on a message whose prefix
368
+ * declares more than `maxMessage` bytes (`RESOURCE_EXHAUSTED`), a
369
+ * compressed one (`UNIMPLEMENTED`), an unknown flag byte or a body that
370
+ * ends inside a message (`INTERNAL`), a deadline past (`DEADLINE_EXCEEDED`)
371
+ * and a client that hung up (`CANCELLED`, which the server drops). Never
372
+ * panics on what the peer sent; panics on a request `open` or `call` did
373
+ * not answer `GRPC_CALL` for. A message read in place is handed back to
374
+ * the client's window only by a later `next`, so a program calls `next`
375
+ * until it answers `GRPC_MORE`, `GRPC_END` or `GRPC_ANSWERED` before it
376
+ * waits for `take`.
377
+ * @param r a call `open` read
378
+ * @returns `GRPC_MESSAGE` for a message, valid until the next call of `next`; `GRPC_MORE` to wait until `take` hands `r` over again; `GRPC_END` when the client's stream ended; `GRPC_ANSWERED` when `r` is the server's again
379
+ */
380
+ next(r: HttpServerRequest): i32 {
381
+ const c: GrpcCall = this.held(r, "next")
382
+ if (c.state === GRPC_OVER) {
383
+ return GRPC_ANSWERED
384
+ }
385
+ if (this.server.hungUp(r)) {
386
+ this.close(r, GRPC_CANCELLED, "")
387
+ return GRPC_ANSWERED
388
+ }
389
+ if (this.expired(r)) {
390
+ this.close(r, GRPC_DEADLINE_EXCEEDED, "")
391
+ return GRPC_ANSWERED
392
+ }
393
+ const body: u8[] = r.body
394
+ const total: i32 = r.bodyLength
395
+ let at: i32 = c.readAt
396
+ if (at < 0 || total < 0 || total < at || total > toI32(body.length)) {
397
+ // A body length the request's own bytes do not hold: nothing here reads as a message.
398
+ this.close(r, GRPC_INTERNAL, "")
399
+ return GRPC_ANSWERED
400
+ }
401
+ if (c.want < 0) {
402
+ const left: i32 = total - at
403
+ if (left < GRPC_PREFIX) {
404
+ if (r.bodyEnded) {
405
+ if (left === 0) {
406
+ return GRPC_END
407
+ }
408
+ this.close(r, GRPC_INTERNAL, "")
409
+ return GRPC_ANSWERED
410
+ }
411
+ // A prefix not yet whole waits where it is: fewer than 5 bytes never fill the window.
412
+ this.server.consume(r, at)
413
+ c.readAt = 0
414
+ return GRPC_MORE
415
+ }
416
+ const length: i64 = grpcPrefixLength(body, at)
417
+ if (length === GRPC_COMPRESSED) {
418
+ this.close(r, GRPC_UNIMPLEMENTED, "")
419
+ return GRPC_ANSWERED
420
+ }
421
+ if (length < 0) {
422
+ this.close(r, GRPC_INTERNAL, "")
423
+ return GRPC_ANSWERED
424
+ }
425
+ if (length > toI64(this.maxMessage)) {
426
+ this.close(r, GRPC_RESOURCE_EXHAUSTED, "")
427
+ return GRPC_ANSWERED
428
+ }
429
+ const n: i32 = toI32(length)
430
+ at = grpcAdd(at, GRPC_PREFIX)
431
+ if (grpcSub(left, GRPC_PREFIX) >= n) {
432
+ c.readAt = grpcAdd(at, n)
433
+ c.inBuf = false
434
+ c.start = at
435
+ c.end = c.readAt
436
+ return GRPC_MESSAGE
437
+ }
438
+ if (r.bodyEnded) {
439
+ // The rest can never come: answered before anything is allocated for it.
440
+ this.close(r, GRPC_INTERNAL, "")
441
+ return GRPC_ANSWERED
442
+ }
443
+ c.want = n
444
+ c.have = 0
445
+ }
446
+ const need: i32 = grpcSub(c.want, c.have)
447
+ const avail: i32 = grpcSub(total, at)
448
+ const piece: i32 = avail < need ? avail : need
449
+ if (!this.grow(c, grpcAdd(c.have, piece)) || !tryCopyBytes(c.buf, c.have, body, at, piece)) {
450
+ // A piece the call's buffer cannot take: its counts no longer describe the message.
451
+ this.close(r, GRPC_INTERNAL, "")
452
+ return GRPC_ANSWERED
453
+ }
454
+ c.have = grpcAdd(c.have, piece)
455
+ at = grpcAdd(at, piece)
456
+ if (c.have === c.want) {
457
+ c.readAt = at
458
+ c.inBuf = true
459
+ c.start = 0
460
+ c.end = c.want
461
+ c.want = -1
462
+ return GRPC_MESSAGE
463
+ }
464
+ this.server.consume(r, at)
465
+ c.readAt = 0
466
+ if (r.bodyEnded) {
467
+ this.close(r, GRPC_INTERNAL, "")
468
+ return GRPC_ANSWERED
469
+ }
470
+ return GRPC_MORE
471
+ }
472
+
473
+ /**
474
+ * The array that holds the message `call` or `next` found last: `r.body`,
475
+ * or the call's own buffer for a message `next` copied out of pieces.
476
+ * @param r a call `call` answered `GRPC_CALL` for, or `next` answered `GRPC_MESSAGE` for
477
+ * @returns the array whose `[messageStart(r) .. messageEnd(r))` is the message
478
+ */
479
+ messageBytes(r: HttpServerRequest): u8[] {
480
+ const c: GrpcCall | null = this.at(r)
481
+ return c !== null && c.inBuf ? c.buf : r.body
482
+ }
483
+
484
+ /**
485
+ * Where the message `call` or `next` found last starts in `messageBytes(r)`;
486
+ * for a unary call that is past the length prefix in `r.body`.
487
+ * @param r a call `call` answered `GRPC_CALL` for, or `next` answered `GRPC_MESSAGE` for
488
+ * @returns the offset of the message's first byte
489
+ */
490
+ messageStart(r: HttpServerRequest): i32 {
491
+ const c: GrpcCall | null = this.at(r)
492
+ if (c !== null) {
493
+ return c.start
494
+ }
495
+ return r.bodyLength < GRPC_PREFIX ? r.bodyLength : GRPC_PREFIX
496
+ }
497
+
498
+ /**
499
+ * Where the message `call` or `next` found last ends in `messageBytes(r)`;
500
+ * for a unary call that is `r.bodyLength`.
501
+ * @param r a call `call` answered `GRPC_CALL` for, or `next` answered `GRPC_MESSAGE` for
502
+ * @returns the offset just past the message's last byte
503
+ */
504
+ messageEnd(r: HttpServerRequest): i32 {
505
+ const c: GrpcCall | null = this.at(r)
506
+ return c !== null ? c.end : r.bodyLength
507
+ }
508
+
509
+ /**
510
+ * Whether `r`'s deadline has passed: its `grpc-timeout` capped at
511
+ * `maxTimeout`, from when its head was read. A malformed `grpc-timeout`,
512
+ * which `call` refused, counts as passed.
513
+ * @param r a request `take` handed over
514
+ * @returns true once an answer to `r` would come too late
515
+ */
516
+ expired(r: HttpServerRequest): boolean {
517
+ const timeout: i64 = this.timeout(r)
518
+ return timeout < 0 || monotonicNanos() - r.since > timeout
519
+ }
520
+
521
+ /**
522
+ * Sends the head of the call's answer, `:status` 200 and `content-type:
523
+ * application/grpc`, so its reply messages can follow with `send`; `send`
524
+ * begins it too. Once begun the call ends with `finish` (or `fail`).
525
+ * Panics on a request `open` or `call` did not answer `GRPC_CALL` for.
526
+ * @param r a call `call` or `open` read
527
+ * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the stream closed first and `r` is the server's again
528
+ */
529
+ begin(r: HttpServerRequest): i32 {
530
+ const c: GrpcCall = this.held(r, "begin")
531
+ if (c.state === GRPC_BEGUN) {
532
+ return HANDLER_SENT
533
+ }
534
+ if (c.state === GRPC_OVER) {
535
+ return HANDLER_DROPPED
536
+ }
537
+ const sent: i32 = this.server.start(r, GRPC_HTTP_OK, this.contentType, this.grpcType, HTTP1_CHUNKED)
538
+ if (sent !== HANDLER_SENT) {
539
+ this.gone(r)
540
+ return sent
541
+ }
542
+ c.state = GRPC_BEGUN
543
+ return HANDLER_SENT
544
+ }
545
+
546
+ /**
547
+ * Sends one reply message, `buf[off .. off + len)`, length-prefixed,
548
+ * beginning the answer if it has not begun. It never blocks: what the
549
+ * connection cannot take yet is queued, and the answer is how much is, so
550
+ * a program sending many messages stops above a budget of its own and goes
551
+ * back to its wait until `HttpServer.pending(r)` drops. Past the deadline
552
+ * it ends the call `DEADLINE_EXCEEDED` instead. Panics on a window outside
553
+ * `buf`, or a request `open` or `call` did not answer `GRPC_CALL` for.
554
+ * @param r a call `call` or `open` read
555
+ * @param buf the encoded reply message; the caller's again on return
556
+ * @param off where in `buf` the message starts
557
+ * @param len the message's length in bytes, at most 2^30 - 5
558
+ * @returns the bytes of the answer still queued, 0 or more, or `GRPC_ENDED` once the call is over and `r` is the server's again
559
+ */
560
+ send(r: HttpServerRequest, buf: u8[], off: i32, len: i32): i32 {
561
+ if (off < 0 || len < 0 || len > 1073741819 || off > toI32(buf.length) - len) {
562
+ panic(`GrpcServer.send: the window ${off} + ${len} is outside its ${buf.length} bytes`)
563
+ }
564
+ const c: GrpcCall = this.held(r, "send")
565
+ if (c.state === GRPC_OVER) {
566
+ return GRPC_ENDED
567
+ }
568
+ if (this.expired(r)) {
569
+ this.close(r, GRPC_DEADLINE_EXCEEDED, "")
570
+ return GRPC_ENDED
571
+ }
572
+ if (this.begin(r) !== HANDLER_SENT) {
573
+ return GRPC_ENDED
574
+ }
575
+ if (
576
+ this.server.write(r, grpcPrefix(len), toI32(0), GRPC_PREFIX) !== HANDLER_SENT ||
577
+ this.server.write(r, buf, off, len) !== HANDLER_SENT
578
+ ) {
579
+ this.gone(r)
580
+ return GRPC_ENDED
581
+ }
582
+ return this.server.pending(r)
583
+ }
584
+
585
+ /**
586
+ * Ends the call with `status`: trailers carrying `grpc-status` and, when
587
+ * `message` is not empty, `grpc-message`, percent-encoded as `fail`'s is.
588
+ * A call whose answer has not begun is answered Trailers-Only when
589
+ * `message` is empty. Past the deadline it answers `DEADLINE_EXCEEDED`
590
+ * instead. Panics on a status outside 0 to 16, or a request `open` or
591
+ * `call` did not answer `GRPC_CALL` for.
592
+ * @param r a call `call` or `open` read; the server's again after this call
593
+ * @param status `GRPC_OK`, or the error, one of the `GRPC_*` statuses to `GRPC_UNAUTHENTICATED`
594
+ * @param message what went wrong, for a person reading the client's error; empty for none
595
+ * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the stream closed first
596
+ */
597
+ finish(r: HttpServerRequest, status: i32, message: string): i32 {
598
+ if (status < GRPC_OK || status > GRPC_UNAUTHENTICATED) {
599
+ panic(`GrpcServer.finish: status ${status} is outside 0 to 16`)
600
+ }
601
+ const c: GrpcCall = this.held(r, "finish")
602
+ if (c.state === GRPC_OVER) {
603
+ return HANDLER_DROPPED
604
+ }
605
+ if (this.expired(r)) {
606
+ return this.close(r, GRPC_DEADLINE_EXCEEDED, "")
607
+ }
608
+ return this.close(r, status, message)
609
+ }
610
+
611
+ /**
612
+ * Answers the call `r` with the message `buf[off .. off + len)`: status
613
+ * 200, `content-type: application/grpc`, the length-prefixed message and a
614
+ * trailer section with `grpc-status: 0`. Past `r`'s deadline it answers
615
+ * `DEADLINE_EXCEEDED` instead. Panics on a window outside `buf`, on a call
616
+ * whose answer has begun, and as the server's `start` does.
617
+ * @param r a request `call` answered `GRPC_CALL` for; the server's again after this call
618
+ * @param buf the encoded reply message; the caller's again on return
619
+ * @param off where in `buf` the message starts
620
+ * @param len the message's length in bytes, at most 2^30 - 5
621
+ * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the stream closed first
622
+ */
623
+ reply(r: HttpServerRequest, buf: u8[], off: i32, len: i32): i32 {
624
+ if (off < 0 || len < 0 || len > 1073741819 || off > toI32(buf.length) - len) {
625
+ panic(`GrpcServer.reply: the window ${off} + ${len} is outside its ${buf.length} bytes`)
626
+ }
627
+ const c: GrpcCall | null = this.at(r)
628
+ if (c !== null && c.state === GRPC_BEGUN) {
629
+ panic("GrpcServer.reply: the call's answer has begun; end it with finish")
630
+ }
631
+ if (c !== null && c.state === GRPC_OVER) {
632
+ return HANDLER_DROPPED
633
+ }
634
+ this.over(r)
635
+ if (this.expired(r)) {
636
+ return this.only(r, GRPC_DEADLINE_EXCEEDED)
637
+ }
638
+ const sent: i32 = this.server.start(r, GRPC_HTTP_OK, this.contentType, this.grpcType, GRPC_PREFIX + len)
639
+ if (sent !== HANDLER_SENT) {
640
+ this.server.end(r)
641
+ return sent
642
+ }
643
+ if (
644
+ this.server.write(r, grpcPrefix(len), toI32(0), GRPC_PREFIX) !== HANDLER_SENT ||
645
+ this.server.write(r, buf, off, len) !== HANDLER_SENT
646
+ ) {
647
+ this.server.end(r)
648
+ return HANDLER_DROPPED
649
+ }
650
+ return this.server.trailers(r, this.okNames, this.okValues)
651
+ }
652
+
653
+ /**
654
+ * Answers the call `r` with the gRPC error `status`: the Trailers-Only form
655
+ * when `message` is empty, and otherwise a head and a trailer section
656
+ * carrying `grpc-status` and `grpc-message`, the message's UTF-8 with every
657
+ * byte outside printable ASCII, and `%`, percent-encoded. On a call whose
658
+ * answer has begun it ends it as `finish` does. Past `r`'s deadline it
659
+ * answers `DEADLINE_EXCEEDED` instead. Panics on a status outside 1 to 16.
660
+ * @param r a request `call` or `open` answered `GRPC_CALL` for; the server's again after this call
661
+ * @param status the error, one of the `GRPC_*` statuses from `GRPC_CANCELLED` to `GRPC_UNAUTHENTICATED`
662
+ * @param message what went wrong, for a person reading the client's error; empty for none
663
+ * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the stream closed first
664
+ */
665
+ fail(r: HttpServerRequest, status: i32, message: string): i32 {
666
+ if (status < GRPC_CANCELLED || status > GRPC_UNAUTHENTICATED) {
667
+ panic(`GrpcServer.fail: status ${status} is outside 1 to 16`)
668
+ }
669
+ const c: GrpcCall | null = this.at(r)
670
+ if (c !== null && c.state === GRPC_OVER) {
671
+ return HANDLER_DROPPED
672
+ }
673
+ if (this.expired(r)) {
674
+ return this.close(r, GRPC_DEADLINE_EXCEEDED, "")
675
+ }
676
+ return this.close(r, status, message)
677
+ }
678
+
679
+ /**
680
+ * Grows the call's message buffer to hold at least `size` bytes, keeping
681
+ * the `have` already copied: doubled from 1 KiB, and never past the
682
+ * message's declared length, so what the call holds tracks what the client
683
+ * sent rather than what its prefix declared. False when the bytes already
684
+ * copied do not fit the grown buffer.
685
+ */
686
+ private grow(c: GrpcCall, size: i32): boolean {
687
+ const held: i32 = toI32(c.buf.length)
688
+ if (held >= size) {
689
+ return true
690
+ }
691
+ const want: i32 = c.want
692
+ let grown: i32 = held < GRPC_GROW_FROM ? GRPC_GROW_FROM : held
693
+ while (grown < size) {
694
+ grown = grown >= grpcSub(want, grown) ? want : grpcAdd(grown, grown)
695
+ }
696
+ if (grown > want) {
697
+ grown = want
698
+ }
699
+ const bigger: u8[] = grpcBytes(grown)
700
+ if (!tryCopyBytes(bigger, 0, c.buf, 0, c.have)) {
701
+ return false
702
+ }
703
+ c.buf = bigger
704
+ return true
705
+ }
706
+
707
+ /** The version, `content-type`, `grpc-timeout` and deadline checks `call` and `open` share; false once it answered `r` itself. */
708
+ private admit(r: HttpServerRequest): boolean {
709
+ if (r.version !== 2) {
710
+ this.server.empty(r, GRPC_HTTP_VERSION_NOT_SUPPORTED)
711
+ return false
712
+ }
713
+ if (
714
+ !r.headerIs("content-type", "application/grpc") &&
715
+ !r.headerIs("content-type", "application/grpc+proto")
716
+ ) {
717
+ this.server.empty(r, GRPC_HTTP_UNSUPPORTED_MEDIA_TYPE)
718
+ return false
719
+ }
720
+ const timeout: i64 = this.timeout(r)
721
+ if (timeout < 0) {
722
+ this.only(r, GRPC_INTERNAL)
723
+ return false
724
+ }
725
+ if (monotonicNanos() - r.since > timeout) {
726
+ this.only(r, GRPC_DEADLINE_EXCEEDED)
727
+ return false
728
+ }
729
+ return true
730
+ }
731
+
732
+ /**
733
+ * Makes room for `r`'s index in the per-call state and opens a call there;
734
+ * null for a request with no index (below zero), which holds no call.
735
+ */
736
+ private slot(r: HttpServerRequest): GrpcCall | null {
737
+ const i: i32 = r.index
738
+ const calls: GrpcCall[] = this.calls
739
+ while (i >= 0 && toI32(calls.length) <= i) {
740
+ calls.push(new GrpcCall())
741
+ }
742
+ if (i < 0 || i >= toI32(calls.length)) {
743
+ return null
744
+ }
745
+ const c: GrpcCall = calls[i]
746
+ c.state = GRPC_OPEN
747
+ c.readAt = 0
748
+ c.want = -1
749
+ c.have = 0
750
+ c.inBuf = false
751
+ c.start = 0
752
+ c.end = 0
753
+ c.since = r.since
754
+ c.stream = r.stream
755
+ return c
756
+ }
757
+
758
+ /**
759
+ * `r`'s call when one is open, begun or over there for this request, or null.
760
+ * The façade reuses a request object and its index for a later request, so a
761
+ * call left there by an earlier one, told apart by its head's turn and its
762
+ * stream, is not `r`'s.
763
+ */
764
+ private at(r: HttpServerRequest): GrpcCall | null {
765
+ const i: i32 = r.index
766
+ const calls: GrpcCall[] = this.calls
767
+ if (i < 0 || i >= toI32(calls.length)) {
768
+ return null
769
+ }
770
+ const c: GrpcCall = calls[i]
771
+ if (c.state === GRPC_IDLE || c.since !== r.since || c.stream !== r.stream) {
772
+ return null
773
+ }
774
+ return c
775
+ }
776
+
777
+ /** `r`'s call once `call` or `open` read it; panics, naming `who`, on a request neither did. */
778
+ private held(r: HttpServerRequest, who: string): GrpcCall {
779
+ const c: GrpcCall | null = this.at(r)
780
+ if (c === null) {
781
+ panic(`GrpcServer.${who}: the request is not a call that open or call read`)
782
+ }
783
+ return c
784
+ }
785
+
786
+ /** Marks `r`'s call over, if it has one, and lets go of a large message buffer. */
787
+ private over(r: HttpServerRequest): void {
788
+ const c: GrpcCall | null = this.at(r)
789
+ if (c === null) {
790
+ return
791
+ }
792
+ c.state = GRPC_OVER
793
+ c.want = -1
794
+ if (toI32(c.buf.length) > GRPC_KEEP) {
795
+ c.buf = []
796
+ }
797
+ }
798
+
799
+ /** `r`'s stream closed under an answer the server started: hands `r` back and marks the call over. */
800
+ private gone(r: HttpServerRequest): void {
801
+ this.server.end(r)
802
+ this.over(r)
803
+ }
804
+
805
+ /**
806
+ * Ends the call `r` with `status` and, when not empty, `message`: trailers
807
+ * when its answer has begun, Trailers-Only when it has not and `message`
808
+ * is empty, and otherwise a head and then trailers.
809
+ */
810
+ private close(r: HttpServerRequest, status: i32, message: string): i32 {
811
+ const c: GrpcCall | null = this.at(r)
812
+ const begun: boolean = c !== null && c.state === GRPC_BEGUN
813
+ this.over(r)
814
+ if (!begun) {
815
+ if (message.length === 0) {
816
+ return this.only(r, status)
817
+ }
818
+ const sent: i32 = this.server.start(r, GRPC_HTTP_OK, this.contentType, this.grpcType, HTTP1_CHUNKED)
819
+ if (sent !== HANDLER_SENT) {
820
+ this.server.end(r)
821
+ return sent
822
+ }
823
+ }
824
+ // Fresh arrays, never written again: the server reads them until the trailers are sent.
825
+ if (message.length === 0) {
826
+ return this.server.trailers(r, this.statusNames, [grpcStatusValue(status)])
827
+ }
828
+ const values: u8[][] = [grpcStatusValue(status), grpcPercentEncode(message)]
829
+ return this.server.trailers(r, [this.statusName, this.messageName], values)
830
+ }
831
+
832
+ /**
833
+ * Answers `r` with `status` in the Trailers-Only form: one HEADERS frame
834
+ * that ends the stream, then `end`, which hands `r` back whether the head
835
+ * went or the stream closed first. A head declaring no body still leaves
836
+ * the request the program's until `end`.
837
+ */
838
+ private only(r: HttpServerRequest, status: i32): i32 {
839
+ const values: u8[][] = [this.grpcTypeBytes, grpcStatusValue(status)]
840
+ const sent: i32 = this.server.start(r, GRPC_HTTP_OK, this.onlyNames, values, toI32(0))
841
+ const ended: i32 = this.server.end(r)
842
+ return sent === HANDLER_SENT ? ended : sent
843
+ }
844
+
845
+ /**
846
+ * How long `r` may take, in nanoseconds from its head: its `grpc-timeout`
847
+ * capped at `maxTimeout`, `maxTimeout` without one, or -1 for a malformed
848
+ * one (not 1 to 8 ASCII digits and one of the units `H M S m u n`).
849
+ */
850
+ private timeout(r: HttpServerRequest): i64 {
851
+ const i: i32 = r.header("grpc-timeout")
852
+ if (i === HANDLER_ABSENT) {
853
+ return this.maxTimeout
854
+ }
855
+ const head: u8[] = r.head
856
+ const start: i32 = r.valueStart(i)
857
+ const end: i32 = r.valueEnd(i)
858
+ if (start < 0 || end < 1 || end < start || end > toI32(head.length)) {
859
+ return -1
860
+ }
861
+ const last: i32 = end - 1
862
+ const digits: i32 = last - start
863
+ if (digits < 1 || digits > GRPC_TIMEOUT_DIGITS) {
864
+ return -1
865
+ }
866
+ let value: i32 = 0
867
+ for (let k: i32 = start; k >= 0 && k < last; k++) {
868
+ const c: i32 = toI32(head[k])
869
+ if (c < 48 || c > 57) {
870
+ return -1
871
+ }
872
+ // At most 8 digits: `value` stays below 10^8, so the step never wraps.
873
+ if (value >= 0 && value <= 99999999) {
874
+ value = value * 10 + (c - 48)
875
+ }
876
+ }
877
+ const unit: i32 = toI32(head[last])
878
+ let scale: f64 = 0
879
+ if (unit === 72) {
880
+ scale = 3600000000000 // H
881
+ } else if (unit === 77) {
882
+ scale = 60000000000 // M
883
+ } else if (unit === 83) {
884
+ scale = 1000000000 // S
885
+ } else if (unit === 109) {
886
+ scale = 1000000 // m
887
+ } else if (unit === 117) {
888
+ scale = 1000 // u
889
+ } else if (unit === 110) {
890
+ scale = 1 // n
891
+ } else {
892
+ return -1
893
+ }
894
+ // Worked in f64: 99999999 hours is past what an i64 holds in nanoseconds.
895
+ // Below `maxTimeout` (under 2^53) the product of two whole numbers is exact.
896
+ const nanos: f64 = toF64(value) * scale
897
+ const max: i64 = this.maxTimeout
898
+ return nanos < toF64(max) ? toI64(nanos) : max
899
+ }
900
+
901
+ /** `GRPC_OK` when `r.body` is exactly one uncompressed length-prefixed message within `maxMessage`; otherwise the status to answer. */
902
+ private framing(r: HttpServerRequest): i32 {
903
+ const n: i32 = r.bodyLength
904
+ const body: u8[] = r.body
905
+ if (n < GRPC_PREFIX || n > toI32(body.length)) {
906
+ return GRPC_INTERNAL
907
+ }
908
+ const length: i64 = grpcPrefixLength(body, 0)
909
+ if (length === GRPC_COMPRESSED) {
910
+ return GRPC_UNIMPLEMENTED
911
+ }
912
+ if (length < 0) {
913
+ return GRPC_INTERNAL
914
+ }
915
+ if (length > toI64(this.maxMessage)) {
916
+ return GRPC_RESOURCE_EXHAUSTED
917
+ }
918
+ if (length !== toI64(grpcSub(n, GRPC_PREFIX))) {
919
+ return GRPC_INTERNAL
920
+ }
921
+ return GRPC_OK
922
+ }
923
+ }
924
+
925
+ /** The decimal bytes of `status`, as `grpc-status` carries it. */
926
+ const grpcStatusValue = (status: i32): u8[] => httpFieldBytes(`${status}`)
927
+
928
+ /** The uppercase hex digit of `v`, 0 to 15. */
929
+ const grpcHex = (v: i32): u8 => {
930
+ const d: i32 = v & 15
931
+ return toU8(d < 10 ? 48 + d : 55 + d)
932
+ }
933
+
934
+ /** `message` as UTF-8, with every byte outside `0x20 .. 0x7e`, and `%`, written `%XX` (uppercase hex), as `grpc-message` carries it. */
935
+ const grpcPercentEncode = (message: string): u8[] => {
936
+ const out: u8[] = []
937
+ for (let k: i32 = 0; k < toI32(message.length); k++) {
938
+ const b: i32 = toI32(message.charCodeAt(k)) & toI32(255)
939
+ if (b < 32 || b > 126 || b === 37) {
940
+ out.push(toU8(37))
941
+ out.push(grpcHex(b >> 4))
942
+ out.push(grpcHex(b & 15))
943
+ } else {
944
+ out.push(toU8(b))
945
+ }
946
+ }
947
+ return out
948
+ }