@amritk/nish-aarch64-linux 0.37.0 → 0.39.0

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 (73) hide show
  1. package/INSTALL.md +28 -16
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +380 -47
  4. package/package.json +1 -1
  5. package/runtime/core/arrays.d.ts +4 -0
  6. package/runtime/core/arrays.mjs +33 -0
  7. package/runtime/core/host.d.ts +11 -0
  8. package/runtime/core/host.mjs +35 -0
  9. package/runtime/nish.d.ts +645 -66
  10. package/runtime/nish.h +101 -15
  11. package/runtime/nish.mjs +69 -6
  12. package/runtime/node.mjs +117 -0
  13. package/runtime/runtime-aes.c +12 -4
  14. package/runtime/runtime-async.c +267 -51
  15. package/runtime/runtime-checksum.c +207 -15
  16. package/runtime/runtime-cross.c +2 -1
  17. package/runtime/runtime-net.c +32 -3
  18. package/runtime/runtime-os.c +174 -27
  19. package/runtime/runtime-region.c +170 -8
  20. package/runtime/runtime-sandbox.c +377 -17
  21. package/runtime/runtime-sha256.c +11 -4
  22. package/runtime/runtime-text.c +1068 -0
  23. package/runtime/runtime-wasm.c +18 -3
  24. package/runtime/runtime.c +55 -961
  25. package/runtime/vite.mjs +48 -11
  26. package/scripts/build.sh +113 -36
  27. package/std/LICENSE-fdlibm +8 -0
  28. package/std/README.md +7 -4
  29. package/std/array.ts +266 -0
  30. package/std/compress/checksum.ts +13 -0
  31. package/std/compress/deflate.ts +0 -2
  32. package/std/crypto/p256.ts +247 -74
  33. package/std/crypto/p384.ts +3 -1
  34. package/std/crypto/pki.ts +35 -9
  35. package/std/crypto/x25519.ts +153 -64
  36. package/std/crypto/x509.ts +113 -10
  37. package/std/host/text.ts +86 -0
  38. package/std/json-tokenizer.ts +20 -0
  39. package/std/json-typed.ts +217 -8
  40. package/std/math.ts +743 -41
  41. package/std/net/dns-resolver.ts +46 -6
  42. package/std/net/dns.ts +50 -13
  43. package/std/net/fetch.ts +691 -129
  44. package/std/net/handler.ts +142 -16
  45. package/std/net/http-compress.ts +17 -9
  46. package/std/net/http-fields.ts +19 -4
  47. package/std/net/http1-codec.ts +517 -154
  48. package/std/net/http1-server.ts +508 -25
  49. package/std/net/http2-cleartext.ts +526 -0
  50. package/std/net/http2-tls.ts +48 -0
  51. package/std/net/http2.ts +84 -0
  52. package/std/net/postgres-async.ts +2223 -0
  53. package/std/net/postgres-carrier.ts +343 -10
  54. package/std/net/postgres.ts +129 -11
  55. package/std/net/prefork.ts +195 -11
  56. package/std/net/quic-datagram.ts +30 -0
  57. package/std/net/quic-listener.ts +38 -12
  58. package/std/net/quic-packet.ts +19 -6
  59. package/std/net/quic-recovery.ts +134 -19
  60. package/std/net/quic-stream.ts +174 -36
  61. package/std/net/quic.ts +418 -18
  62. package/std/net/router.ts +39 -17
  63. package/std/net/serve.ts +867 -0
  64. package/std/net/tls/codec.ts +110 -32
  65. package/std/net/tls/record-server.ts +37 -7
  66. package/std/net/tls-tcp.ts +56 -1
  67. package/std/net/tls.ts +196 -50
  68. package/std/net/websocket.ts +55 -18
  69. package/std/net/webtransport.ts +179 -1
  70. package/std/regex.ts +69 -47
  71. package/std/region.ts +62 -11
  72. package/std/secret.ts +26 -59
  73. package/std/text.ts +464 -5
@@ -0,0 +1,2223 @@
1
+ /**
2
+ * `nish/net/postgres-async` — `PgAsyncPool`, PostgreSQL connections an
3
+ * `async` task awaits a query on, so a task's query waits on its socket while
4
+ * the executor runs the others.
5
+ *
6
+ * import { spawn } from "nish:async"
7
+ * import { secret, wipe } from "nish:secret"
8
+ * import { PgConfig, pgTarget } from "nish/net/postgres"
9
+ * import {
10
+ * PgAsyncParams, PgAsyncPool, pgAsyncClaim, pgAsyncConnect, pgAsyncQuery, pgAsyncRelease,
11
+ * } from "nish/net/postgres-async"
12
+ *
13
+ * async function title(pool: PgAsyncPool, id: i32): Promise<void> {
14
+ * const ticket: i32 = await pgAsyncClaim(pool)
15
+ * if (ticket < 0) {
16
+ * return // no live connection, or none came free in time
17
+ * }
18
+ * const params = new PgAsyncParams()
19
+ * params.int(id)
20
+ * const r = await pgAsyncQuery(pool, ticket, "select title from article where id = $1", params)
21
+ * pgAsyncRelease(pool, ticket, r.reusable)
22
+ * if (r.ok() && r.rows > 0) {
23
+ * console.log(r.text(0, 0))
24
+ * }
25
+ * }
26
+ *
27
+ * export async function main(): Promise<i32> {
28
+ * const config = new PgConfig()
29
+ * config.user = "app"
30
+ * const pool = new PgAsyncPool(4)
31
+ * const password = secret(passwordBytes()) // the program's own source
32
+ * const live: i32 = await pgAsyncConnect(pool, config, password, pgTarget("127.0.0.1", 5432))
33
+ * wipe(password)
34
+ * spawn(title(pool, 1))
35
+ * spawn(title(pool, 2))
36
+ * // ... and close the pool once the tasks are done: `pool.close()`.
37
+ * return live === pool.size ? 0 : 1
38
+ * }
39
+ *
40
+ * **Why separate calls.** A spawned task shares the pool with the function that
41
+ * spawned it, and runs in memory of its own that is freed when it ends
42
+ * (docs/LANGUAGE.md → "What `spawn` may pass"). So a call that writes into
43
+ * the pool may allocate nothing, and one that allocates may not write into
44
+ * it: `pgAsyncClaim` and `pgAsyncRelease` write only numbers into the pool,
45
+ * and `pgAsyncQuery` only reads it, building its buffers, rows and strings in
46
+ * the task's own memory. One `async` function doing all three would be
47
+ * refused when a task calls it ("hands `pool` to ..., which may grow it").
48
+ *
49
+ * **The flow.** `pgAsyncConnect`, in `main` or any function that is not a
50
+ * spawned task, connects each slot and runs its startup and SCRAM exchange
51
+ * on a `PgConnection`, which then wipes the password and is dropped: the
52
+ * pool keeps only the authenticated socket, so it holds no `Secret` and a
53
+ * task may be handed it. `pgAsyncClaim` gives a task a ticket for one free
54
+ * connection; `pgAsyncQuery` writes Parse, Bind, Execute and Sync in one go
55
+ * (the parameters in text, never spliced into the SQL), waits on `writable`
56
+ * and `readable` for the socket while the executor runs the others, and reads
57
+ * to the ReadyForQuery; `pgAsyncRelease` gives the connection back, or closes
58
+ * it when the query left it unfit to reuse.
59
+ *
60
+ * **Pipelining.** Many tasks may share one connection instead of claiming
61
+ * it whole. `pgAsyncPrepare` registers a statement's SQL once, before the
62
+ * tasks run, and each task then runs it in five calls:
63
+ *
64
+ * const ticket: i32 = await pgAsyncSeat(pool, statement) // a place in a connection's order
65
+ * if (ticket >= 0) {
66
+ * const sent: i32 = await pgAsyncSend(pool, ticket, params) // Bind, Execute, Sync
67
+ * const turn: i32 = await pgAsyncTurn(pool, ticket, sent) // the answers before it, then its own
68
+ * const r = await pgAsyncAnswer(pool, ticket, turn) // its rows, in the task's memory
69
+ * pgAsyncDone(pool, ticket, turn, r.reusable)
70
+ * }
71
+ *
72
+ * Up to `pool.depth` statements are in flight on a connection at once, and
73
+ * its answers come back in the order they were sent; each task waits for the
74
+ * answers before its own on the pool's wake and reads its own when its turn
75
+ * comes, so one read often brings several. Each connection parses a
76
+ * statement once, named, and sends only Bind and Execute after; a Parse the
77
+ * server refused is sent again next time. Each statement has its own Sync, so
78
+ * a statement the server refuses fails alone. A pipelined statement whose
79
+ * task is cancelled before its answer is read fails alone too: its seat is
80
+ * abandoned, and the next task to read the connection reads past that
81
+ * answer. A connection is out of step when an answer behind which others
82
+ * wait is lost (a socket error, a frame this module does not expect, an
83
+ * abandoned answer that left a transaction open or changed a setting): every
84
+ * statement behind it fails `PG_ERR_CLOSED`, and the connection closes once
85
+ * the last is answered.
86
+ *
87
+ * **Its own encoder and framer.** A query is encoded and its answer framed
88
+ * here (`pgAsyncEncode`, `pgAsyncRead`), not by `PgConnection` or
89
+ * `PgCarrier`: those keep their buffers and rows in objects that outlive a
90
+ * query, which a task would have to grow inside the pool, and a
91
+ * `PgConnection` holds the password as a `Secret`, which a task may not be
92
+ * handed. The framer applies the same checks as `PgConnection`'s (PG-28 in
93
+ * `docs/security/postgres.md`).
94
+ *
95
+ * **Claiming.** When every live connection is claimed or in use,
96
+ * `pgAsyncClaim` (and `pgAsyncSeat`, when none has room) waits on the pool's
97
+ * wake, a socket pair `pgAsyncRelease` and each answer read write a byte to,
98
+ * until one is free or it has waited `claimWaitMs` in all; nothing polls on a
99
+ * clock. A ticket names a slot and that slot's
100
+ * claim: `pgAsyncQuery` and `pgAsyncRelease` panic on one that is not the
101
+ * slot's current claim, so two tasks never share a connection and a
102
+ * connection is given back once.
103
+ *
104
+ * **Reuse.** A connection is given back only when its last query read to a
105
+ * ReadyForQuery that says "idle" and changed no session setting: a query that
106
+ * left a transaction open, a `SET` the server reported (a ParameterStatus),
107
+ * a socket error, a frame this module does not expect, a reply past a cap,
108
+ * or bytes after the ReadyForQuery closes it, so the next task never inherits
109
+ * another's session or the rest of its answer.
110
+ *
111
+ * **Limits.** `PgAsyncPool`'s caps (`maxMessage`, `maxColumns`, `maxRows`,
112
+ * `maxResultBytes`, `claimWaitMs`) bound what one query keeps; rows past
113
+ * `maxRows` or `maxResultBytes` are read and dropped, and the query fails
114
+ * with `PG_ERR_TOO_BIG`. `pgAsyncConnect` gives each connection at most
115
+ * `connectWaitMs` (10 s) to connect and finish its startup. A query's wait
116
+ * has no deadline of its own: a server that accepts and never answers holds
117
+ * the task until it closes or the task is cancelled; bound a slow statement
118
+ * with the server's `statement_timeout` too.
119
+ *
120
+ * **Cancellation.** A task that is cancelled (`nish:async`'s `cancel`, a
121
+ * `cancelAfter` deadline, or `nish/net/serve` when the client hangs up, the
122
+ * request's deadline passes or the server drains) stops waiting at once.
123
+ * `pgAsyncClaim` and `pgAsyncSeat` answer `PG_ASYNC_CANCELLED` and take
124
+ * nothing; a query
125
+ * not yet sent fails with nothing written and its connection reusable; a
126
+ * query cut off mid-answer fails with `PG_ERR_CLOSED`, `socketError`
127
+ * `PG_ASYNC_CANCELLED` and `reusable` false, so the task's
128
+ * `pgAsyncRelease` closes the connection, whose unread answer would put the
129
+ * next task out of step. A pipelined statement (`pgAsyncSeat`) cancelled
130
+ * after it was sent fails the same way but alone: its seat is abandoned, and
131
+ * the task behind it, or the next to ask for a seat, reads its answer and
132
+ * drops it, so the connection stays when that answer is a plain one. No
133
+ * CancelRequest is sent: the server runs the statement on to its end (or,
134
+ * for a released connection, until it sees the socket closed).
135
+ *
136
+ * **Memory.** Run each query in a spawned task, as `title` does above: the
137
+ * task's region, and every buffer, row and string the query built in it,
138
+ * is freed when the task ends, so `Arena.used()` stays where it was across
139
+ * thousands of queries. A query awaited outside a task, through a function
140
+ * that is handed the pool, keeps what it built until an enclosing scope
141
+ * ends (about 9 KB a query, measured while writing
142
+ * `tests/link/std_postgres_async_flat`).
143
+ *
144
+ * **Errors.** A query answers `PG_CARRIER_DONE`, or `PG_CARRIER_FAILED` with
145
+ * `failure` a `PG_ERR_*` and `socketError` a negative errno, as
146
+ * `nish/net/postgres-carrier` does: `PG_ERR_NONE` when the server refused the
147
+ * statement (`errorCode` and `errorMessage` say why, and the connection is
148
+ * reused), `PG_ERR_CLOSED` when the socket ended, a wait could not be made or
149
+ * the task was cancelled (`socketError` `PG_ASYNC_CANCELLED`).
150
+ * Programming errors (a ticket that is not a current claim, a size or a cap
151
+ * out of range) panic.
152
+ *
153
+ * `tests/link/std_postgres_async` runs one against a loopback backend;
154
+ * `tests/link/std_postgres_async_pipeline` pipelines statements from many tasks;
155
+ * `tests/link/std_postgres_async_flat` reads `Arena.used()` across thousands
156
+ * of queries. Caps and findings: `docs/security/postgres.md`.
157
+ *
158
+ * Written for this module; not ported from another implementation.
159
+ */
160
+
161
+ import { cancelled, readable, readableWithin, sleep, writable, writableWithin } from "nish:async"
162
+ import {
163
+ NET_UNIX_STREAM,
164
+ connectResult,
165
+ netAddress,
166
+ netClose,
167
+ netRead,
168
+ netWrite,
169
+ tcpConnect,
170
+ unixConnect,
171
+ unixSocketPair,
172
+ } from "nish:net"
173
+ import { monotonicNanos } from "nish:process"
174
+ import { Secret } from "nish:secret"
175
+ import { copyBytes, getI32BE, getU16BE, setI32BE, setU16BE } from "nish/bytes"
176
+ import {
177
+ PG_ERR_CLOSED,
178
+ PG_ERR_ENCODING,
179
+ PG_ERR_FRAME,
180
+ PG_ERR_NONE,
181
+ PG_ERR_TOO_BIG,
182
+ PG_ERR_UNEXPECTED,
183
+ PG_FAILED,
184
+ PG_NEED_MORE,
185
+ PG_READY,
186
+ PG_TARGET_OK,
187
+ PG_POOL_NONE,
188
+ PgConfig,
189
+ PgConnection,
190
+ PgTarget,
191
+ } from "nish/net/postgres"
192
+ import { PG_CARRIER_DONE, PG_CARRIER_FAILED, PG_CARRIER_FULL } from "nish/net/postgres-carrier"
193
+
194
+ /** The most connections one `PgAsyncPool` holds. */
195
+ export const PG_ASYNC_MAX_SIZE: i32 = 64
196
+
197
+ /**
198
+ * The calling task was cancelled (`nish:async`'s `cancel`, or a deadline set
199
+ * with `cancelAfter`): `pgAsyncClaim` answers it in place of a ticket, and a
200
+ * query cut off by it fails with `PG_ERR_CLOSED` and this as its
201
+ * `socketError`, which no socket read or write answers.
202
+ */
203
+ export const PG_ASYNC_CANCELLED: i32 = -3
204
+
205
+ // `netRead` and `netWrite`: nothing to read, or no room to write, now.
206
+ const PG_ASYNC_AGAIN: i32 = -11
207
+ // `readable` or `writable` could not wait on the descriptor: EBADF.
208
+ const PG_ASYNC_BAD_FD: i32 = -9
209
+ // A ticket is `claim * PG_ASYNC_MAX_SIZE + slot`; the claim count wraps below this.
210
+ const PG_ASYNC_CLAIM_WRAP: i32 = 16777216
211
+ /** The most statements `pgAsyncPrepare` registers on one pool. */
212
+ export const PG_ASYNC_MAX_STATEMENTS: i32 = 64
213
+ /** The most statements one connection has in flight at once: `PgAsyncPool.depth`'s ceiling. */
214
+ export const PG_ASYNC_MAX_DEPTH: i32 = 16
215
+ /**
216
+ * `pgAsyncSend`'s answer for a statement it did not send because a parameter
217
+ * holds a NUL; `pgAsyncAnswer` fails it with `PG_ERR_ENCODING`, and the
218
+ * connection is reused.
219
+ */
220
+ export const PG_ASYNC_UNSENT: i32 = -1
221
+ /**
222
+ * `pgAsyncSend`'s answer for a statement it did not send because the task was
223
+ * cancelled; `pgAsyncAnswer` fails it with `PG_ERR_CLOSED` and
224
+ * `PG_ASYNC_CANCELLED`, and the connection is reused.
225
+ */
226
+ export const PG_ASYNC_UNSENT_CANCELLED: i32 = -2
227
+ // `pgAsyncSend` answers a write that broke as this plus the socket error (0 or less).
228
+ const PG_ASYNC_BROKEN: i32 = -16
229
+ // A seat's ticket is `claim * 1024 + seat`; the seat claim count wraps below this.
230
+ const PG_ASYNC_SEAT_WRAP: i32 = 1048576
231
+ const PG_ASYNC_SEATS: i32 = 1024
232
+ // A connection's statement sequence numbers wrap below this.
233
+ const PG_ASYNC_SEQ_WRAP: i32 = 16777216
234
+ // The most tasks `pgAsyncSeat` queues in the order they began to wait; more
235
+ // wait unqueued, behind them all. Queue numbers wrap below the wrap.
236
+ const PG_ASYNC_QUEUE: i32 = 16384
237
+ const PG_ASYNC_QUEUE_WRAP: i32 = 1073741824
238
+ // The wakes the queue's tasks wait on, a task on the one its number picks, so
239
+ // the queue's head moving wakes it and few others.
240
+ const PG_ASYNC_LANES: i32 = 128
241
+ // What a query reads first; it grows by doubling up to one `maxMessage`.
242
+ const PG_ASYNC_INPUT_SIZE: i32 = 8192
243
+ // Loop turns a seat yields for its turn before it parks on its slot's wake.
244
+ const PG_ASYNC_TURN_YIELDS: i32 = 4
245
+ // ReadyForQuery's transaction status for "idle", outside any transaction.
246
+ const PG_ASYNC_IDLE: i32 = 73
247
+ const PG_ASYNC_NONCE_BYTES: i32 = 18
248
+ // The largest `maxMessage` and `maxResultBytes`, as `nish/net/postgres` caps `PgConfig.maxMessage`.
249
+ const PG_ASYNC_MAX_CAP: i32 = 1073741823
250
+ // The most rows `maxRows` may allow.
251
+ const PG_ASYNC_MAX_ROWS: i32 = 16777216
252
+ // What a kept cell costs `maxResultBytes` beyond its bytes: its string and its NULL flag.
253
+ const PG_ASYNC_CELL_COST: i32 = 16
254
+
255
+ /**
256
+ * Authenticated PostgreSQL connections that spawned tasks share. Build one
257
+ * and connect it with `pgAsyncConnect` outside any task; tasks then claim,
258
+ * query and release through the `pgAsync*` functions, and the owner calls
259
+ * `close()` once they are done. It holds no secret: only sockets and numbers.
260
+ * The arrays are the functions' bookkeeping, readable for a test or a status
261
+ * page; a program writes none of them.
262
+ */
263
+ export class PgAsyncPool {
264
+ /** Each slot's socket, or -1 while it is not connected. */
265
+ readonly fds: i32[]
266
+ /** Each slot's state: 0 free, 1 claimed by a ticket. */
267
+ readonly claimed: u8[]
268
+ /** Each slot's claim count, the high part of its current ticket. */
269
+ readonly claims: i32[]
270
+ /** The number of connection slots, fixed at construction. */
271
+ readonly size: i32
272
+ /**
273
+ * The largest message a query accepts, in bytes, 1024 to 2^30 - 1; a larger
274
+ * one fails it with `PG_ERR_TOO_BIG` and closes the connection.
275
+ */
276
+ maxMessage: i32 = 1048576
277
+ /**
278
+ * The most columns a row may have, 1 to 65535; more fails the query with
279
+ * `PG_ERR_TOO_BIG` and closes the connection.
280
+ */
281
+ maxColumns: i32 = 1664
282
+ /**
283
+ * The most rows a query keeps, 1 to 2^24; later rows are read and dropped,
284
+ * and the query fails with `PG_ERR_TOO_BIG`.
285
+ */
286
+ maxRows: i32 = 100000
287
+ /**
288
+ * The most bytes of rows a query keeps, 1024 to 2^30 - 1: each row costs
289
+ * its DataRow's length and 16 bytes a cell. A row past it is dropped with
290
+ * every later one, read through to the ReadyForQuery, and the query fails
291
+ * with `PG_ERR_TOO_BIG`.
292
+ */
293
+ maxResultBytes: i32 = 16777216
294
+ /**
295
+ * The most milliseconds `pgAsyncClaim` or `pgAsyncSeat` waits for a free
296
+ * connection before it answers `PG_CARRIER_FULL`.
297
+ */
298
+ claimWaitMs: i32 = 5000
299
+ /**
300
+ * The most statements `pgAsyncSeat` puts in flight on one connection at once,
301
+ * 1 to `PG_ASYNC_MAX_DEPTH`.
302
+ */
303
+ depth: i32 = 8
304
+ /** How many times `pgAsyncClaim` or `pgAsyncSeat` waited because no live connection had room. */
305
+ waits: i32 = 0
306
+ /** How many times `pgAsyncTurn` waited for the answers seated ahead of its own. */
307
+ turnWaits: i32 = 0
308
+ /**
309
+ * How many connections were closed rather than given back: by
310
+ * `pgAsyncRelease`, or once a lost pipeline emptied.
311
+ */
312
+ dropped: i32 = 0
313
+ /**
314
+ * The most milliseconds `pgAsyncConnect` gives one connection to connect
315
+ * and finish its startup before it closes it and moves on; 0 or less waits
316
+ * for as long as the server takes.
317
+ */
318
+ connectWaitMs: i32 = 10000
319
+ /** How many connections `pgAsyncConnect` made, in all. */
320
+ connects: i32 = 0
321
+ /**
322
+ * The queue number of the first task still waiting for a seat. Of the
323
+ * tasks waiting, in the order they began to wait, the first as many as
324
+ * there are free seats may each take one, and a task that has not waited
325
+ * takes none while any is queued.
326
+ */
327
+ seatHead: i32 = 0
328
+ /** The queue number the next task to wait for a seat takes. */
329
+ seatTail: i32 = 0
330
+ /** Per queue number, modulo its length: 1 when its task stopped waiting before its turn. */
331
+ readonly seatGone: u8[]
332
+ /** Each statement `pgAsyncPrepare` registered: its SQL as UTF-8. */
333
+ readonly statements: u8[][]
334
+ /**
335
+ * Per slot and statement (`slot * PG_ASYNC_MAX_STATEMENTS + statement`): 1
336
+ * once a Parse for it was sent on that connection.
337
+ */
338
+ readonly prepared: u8[]
339
+ /** Per slot: answer bytes read past the last statement served, at `[inStart, inEnd)`. */
340
+ readonly inputs: u8[][]
341
+ /** Per slot: where the unserved bytes in `inputs` start. */
342
+ readonly inStart: i32[]
343
+ /** Per slot: where the unserved bytes in `inputs` end. */
344
+ readonly inEnd: i32[]
345
+ /**
346
+ * Per slot: where the answer in turn ends in `inputs`, past its
347
+ * ReadyForQuery, or -1 while it is not there whole.
348
+ */
349
+ readonly inAnswer: i32[]
350
+ /** Per slot: 1 when the answer in turn begins with a ParseComplete. */
351
+ readonly inParsed: u8[]
352
+ /** Per slot: the sequence number the next seated statement takes. */
353
+ readonly nextSeq: i32[]
354
+ /** Per slot: the sequence number whose answer is read next. */
355
+ readonly served: i32[]
356
+ /** Per slot: the first sequence number that is not served because the connection was lost, or -1. */
357
+ readonly doomAt: i32[]
358
+ /** Per slot: the seats in use. */
359
+ readonly seated: i32[]
360
+ /** Per slot: 1 while a seated statement has not yet been written whole. */
361
+ readonly writing: u8[]
362
+ /** Per seat (`slot * PG_ASYNC_MAX_DEPTH + k`): 1 while a ticket holds it. */
363
+ readonly seatUsed: u8[]
364
+ /** Per seat: its statement's sequence number on the connection. */
365
+ readonly seatSeq: i32[]
366
+ /** Per seat: its statement. */
367
+ readonly seatStatement: i32[]
368
+ /** Per seat: 1 when its write carries the statement's Parse. */
369
+ readonly seatParse: u8[]
370
+ /** Per seat: 1 while its task waits for its answer's turn. */
371
+ readonly seatWaiting: u8[]
372
+ /** Per seat: its claim count, the high part of its current ticket. */
373
+ readonly seatClaims: i32[]
374
+ /**
375
+ * Per seat: 0, or how far a seat whose task was cancelled with its answer
376
+ * unread has gone: 1 abandoned, 2 abandoned and its ticket spent, 3 its
377
+ * answer read past and its ticket not yet spent.
378
+ */
379
+ readonly seatAbandoned: u8[]
380
+ /** Per slot: 1 while a task reads past an abandoned seat's answer. */
381
+ readonly skipping: u8[]
382
+ /**
383
+ * Per slot, then one for the pool, then one per queue lane: a socket pair
384
+ * whose read end a waiting task waits on, or -1. A pair is opened the first
385
+ * time a task waits on its wake, so a pool nobody waits on holds none.
386
+ */
387
+ readonly wakes: i32[]
388
+ /** Where `pgAsyncPark` opens a wake's socket pair, so it does not allocate. */
389
+ readonly wakePair: i32[]
390
+ /** Per wake: 1 while a byte is written and not yet read. */
391
+ readonly wakePending: u8[]
392
+ /** The bytes a wake is rung with and read back into, so neither allocates. */
393
+ readonly wakeBytes: u8[]
394
+ /** Per wake: the tasks waiting on it. */
395
+ readonly waiters: i32[]
396
+ /** Per wake: how many bytes were written to it, wrapping; a waiter that sees it move was rung. */
397
+ readonly wakeRings: i32[]
398
+ /** Per wake: the tasks waiting when its byte was written that have not yet woken; it is read back at 0. */
399
+ readonly wakeUnseen: i32[]
400
+
401
+ /**
402
+ * A pool of `size` slots, none connected yet. A waiting task waits on a
403
+ * wake: one per slot, one for the pool and one per queue lane. Each opens
404
+ * its socket pair the first time a task waits on it; `close()` closes the
405
+ * pairs opened.
406
+ * @param size The number of connections, 1 to `PG_ASYNC_MAX_SIZE`; any
407
+ * other panics.
408
+ */
409
+ constructor(size: i32) {
410
+ if (size < 1 || size > PG_ASYNC_MAX_SIZE) {
411
+ panic("nish/net/postgres-async: a PgAsyncPool size out of range")
412
+ }
413
+ this.size = size
414
+ this.fds = new Array<i32>(size)
415
+ this.claimed = new Array<u8>(size)
416
+ this.claims = new Array<i32>(size)
417
+ this.statements = []
418
+ this.prepared = new Array<u8>(size * PG_ASYNC_MAX_STATEMENTS)
419
+ this.inputs = []
420
+ this.inStart = new Array<i32>(size)
421
+ this.inEnd = new Array<i32>(size)
422
+ this.inAnswer = new Array<i32>(size)
423
+ this.inParsed = new Array<u8>(size)
424
+ this.nextSeq = new Array<i32>(size)
425
+ this.served = new Array<i32>(size)
426
+ this.doomAt = new Array<i32>(size)
427
+ this.seated = new Array<i32>(size)
428
+ this.writing = new Array<u8>(size)
429
+ this.seatUsed = new Array<u8>(size * PG_ASYNC_MAX_DEPTH)
430
+ this.seatSeq = new Array<i32>(size * PG_ASYNC_MAX_DEPTH)
431
+ this.seatStatement = new Array<i32>(size * PG_ASYNC_MAX_DEPTH)
432
+ this.seatParse = new Array<u8>(size * PG_ASYNC_MAX_DEPTH)
433
+ this.seatWaiting = new Array<u8>(size * PG_ASYNC_MAX_DEPTH)
434
+ this.seatClaims = new Array<i32>(size * PG_ASYNC_MAX_DEPTH)
435
+ this.seatAbandoned = new Array<u8>(size * PG_ASYNC_MAX_DEPTH)
436
+ this.skipping = new Array<u8>(size)
437
+ const wakes: i32 = size + 1 + PG_ASYNC_LANES
438
+ this.wakes = new Array<i32>(wakes * 2)
439
+ this.wakePending = new Array<u8>(wakes)
440
+ this.wakeBytes = new Array<u8>(8)
441
+ this.wakePair = new Array<i32>(2)
442
+ this.waiters = new Array<i32>(wakes)
443
+ this.wakeRings = new Array<i32>(wakes)
444
+ this.wakeUnseen = new Array<i32>(wakes)
445
+ this.seatGone = new Array<u8>(PG_ASYNC_QUEUE)
446
+ for (let s: i32 = 0; s < size; s++) {
447
+ this.fds[s] = -1
448
+ this.doomAt[s] = -1
449
+ this.inputs.push(new Array<u8>(PG_ASYNC_INPUT_SIZE))
450
+ }
451
+ for (let w: i32 = 0; w < wakes * 2; w++) {
452
+ this.wakes[w] = -1
453
+ }
454
+ }
455
+
456
+ /**
457
+ * The number of slots connected now, claimed or not.
458
+ * @returns The count, 0 to `size`.
459
+ */
460
+ live(): i32 {
461
+ let n: i32 = 0
462
+ for (let s: i32 = 0; s < this.size; s++) {
463
+ if (this.fds[s] >= 0) {
464
+ n += 1
465
+ }
466
+ }
467
+ return n
468
+ }
469
+
470
+ /**
471
+ * Ends every connection: a Terminate is offered to each socket, which is
472
+ * then closed, claimed or not, and closes the wakes. Call it once the tasks
473
+ * that hold tickets are done; a ticket used afterwards panics.
474
+ */
475
+ close(): void {
476
+ const terminate: u8[] = [88, 0, 0, 0, 4]
477
+ for (let s: i32 = 0; s < this.size; s++) {
478
+ const fd: i32 = this.fds[s]
479
+ if (fd >= 0) {
480
+ netWrite(fd, terminate, 0, 5)
481
+ netClose(fd)
482
+ this.fds[s] = -1
483
+ }
484
+ this.claimed[s] = 0
485
+ this.claims[s] = (this.claims[s] + 1) % PG_ASYNC_CLAIM_WRAP
486
+ for (let k: i32 = 0; k < PG_ASYNC_MAX_DEPTH; k++) {
487
+ const seat: i32 = s * PG_ASYNC_MAX_DEPTH + k
488
+ this.seatUsed[seat] = 0
489
+ this.seatWaiting[seat] = 0
490
+ this.seatAbandoned[seat] = 0
491
+ this.seatClaims[seat] = (this.seatClaims[seat] + 1) % PG_ASYNC_SEAT_WRAP
492
+ }
493
+ pgAsyncForget(this, s)
494
+ }
495
+ for (let w: i32 = 0; w < toI32(this.wakes.length); w++) {
496
+ if (this.wakes[w] >= 0) {
497
+ netClose(this.wakes[w])
498
+ this.wakes[w] = -1
499
+ }
500
+ }
501
+ }
502
+ }
503
+
504
+ /** Resets slot `s`'s pipeline: nothing in flight, nothing prepared, nothing buffered. */
505
+ const pgAsyncForget = (pool: PgAsyncPool, s: i32): void => {
506
+ pool.nextSeq[s] = 0
507
+ pool.served[s] = 0
508
+ pool.doomAt[s] = -1
509
+ pool.seated[s] = 0
510
+ pool.writing[s] = 0
511
+ pool.inStart[s] = 0
512
+ pool.inEnd[s] = 0
513
+ pool.inAnswer[s] = -1
514
+ pool.inParsed[s] = 0
515
+ pool.skipping[s] = 0
516
+ for (let q: i32 = 0; q < PG_ASYNC_MAX_STATEMENTS; q++) {
517
+ pool.prepared[s * PG_ASYNC_MAX_STATEMENTS + q] = 0
518
+ }
519
+ }
520
+
521
+ /**
522
+ * A query's parameters, in text, in the order `$1`, `$2`, ... name them. A
523
+ * task builds its own; the values travel apart from the SQL, so none is ever
524
+ * read as SQL.
525
+ */
526
+ export class PgAsyncParams {
527
+ /** Each parameter's text, `""` for a NULL. */
528
+ readonly values: string[]
529
+ /** Whether each parameter is NULL. */
530
+ readonly nulls: boolean[]
531
+
532
+ /** No parameters yet. */
533
+ constructor() {
534
+ this.values = []
535
+ this.nulls = []
536
+ }
537
+
538
+ /**
539
+ * Adds a text parameter.
540
+ * @param value The text, sent as its UTF-8 bytes.
541
+ */
542
+ text(value: string): void {
543
+ this.values.push(value)
544
+ this.nulls.push(false)
545
+ }
546
+
547
+ /**
548
+ * Adds an integer parameter, sent as its decimal text.
549
+ * @param value The number.
550
+ */
551
+ int(value: i32): void {
552
+ this.values.push(`${value}`)
553
+ this.nulls.push(false)
554
+ }
555
+
556
+ /** Adds a NULL parameter. */
557
+ none(): void {
558
+ this.values.push("")
559
+ this.nulls.push(true)
560
+ }
561
+ }
562
+
563
+ /**
564
+ * One query's answer, in the task's own memory: its rows as text, its tag,
565
+ * and how it ended.
566
+ */
567
+ export class PgAsyncResult {
568
+ /** `PG_CARRIER_DONE` when the query worked, `PG_CARRIER_FAILED` when it did not. */
569
+ code: i32
570
+ /** When it failed: a `PG_ERR_*`, `PG_ERR_NONE` when the server refused the statement. */
571
+ failure: i32 = 0
572
+ /**
573
+ * When the socket failed: its negative errno, 0 when the server closed
574
+ * cleanly, `PG_ASYNC_CANCELLED` when the task was cancelled.
575
+ */
576
+ socketError: i32 = 0
577
+ /** Whether the connection may serve another query: hand it to `pgAsyncRelease`. */
578
+ reusable: boolean = false
579
+ /** The number of columns in each row (the first row's; every row must match). */
580
+ columns: i32 = 0
581
+ /** The number of rows kept. */
582
+ rows: i32 = 0
583
+ /** The command tag, e.g. `SELECT 2` or `UPDATE 1`; `""` for an empty query. */
584
+ tag: string = ""
585
+ /** The server's SQLSTATE when it refused the statement, e.g. `42P01`. */
586
+ errorCode: string = ""
587
+ /** The server's message when it refused the statement. */
588
+ errorMessage: string = ""
589
+ /** Every kept cell's text, row by row; `""` for a NULL. */
590
+ readonly values: string[]
591
+ /** Whether each kept cell is NULL, as `values`. */
592
+ readonly nulls: boolean[]
593
+
594
+ /** An answer with no rows that worked, until the query fills it in. */
595
+ constructor() {
596
+ this.code = PG_CARRIER_DONE
597
+ this.values = []
598
+ this.nulls = []
599
+ }
600
+
601
+ /**
602
+ * Whether the query worked.
603
+ * @returns True for `PG_CARRIER_DONE`.
604
+ */
605
+ ok(): boolean {
606
+ return this.code === PG_CARRIER_DONE
607
+ }
608
+
609
+ /**
610
+ * A cell's text, `""` for a NULL; panics on a row or column out of range.
611
+ * @param row The row, from 0.
612
+ * @param column The column, from 0.
613
+ * @returns The text the server sent.
614
+ */
615
+ text(row: i32, column: i32): string {
616
+ return this.values[this.cell(row, column)]
617
+ }
618
+
619
+ /**
620
+ * Whether a cell is NULL; panics on a row or column out of range.
621
+ * @param row The row, from 0.
622
+ * @param column The column, from 0.
623
+ * @returns True for a NULL.
624
+ */
625
+ isNull(row: i32, column: i32): boolean {
626
+ return this.nulls[this.cell(row, column)]
627
+ }
628
+
629
+ /**
630
+ * A cell read as a decimal `i32`, or `fallback` when it is NULL or not one.
631
+ * @param row The row, from 0.
632
+ * @param column The column, from 0.
633
+ * @param fallback The answer for a NULL or a cell that is not a decimal `i32`.
634
+ * @returns The number.
635
+ */
636
+ int(row: i32, column: i32, fallback: i32): i32 {
637
+ const at: i32 = this.cell(row, column)
638
+ if (this.nulls[at]) {
639
+ return fallback
640
+ }
641
+ return pgAsyncDecimal(this.values[at], fallback)
642
+ }
643
+
644
+ /** The index into `values` of a cell, after the bounds check. */
645
+ private cell(row: i32, column: i32): i32 {
646
+ if (row < 0 || row >= this.rows || column < 0 || column >= this.columns) {
647
+ panic("nish/net/postgres-async: a cell out of range")
648
+ }
649
+ return row * this.columns + column
650
+ }
651
+ }
652
+
653
+ /** `s` as a decimal `i32`, or `fallback` when it is not one. */
654
+ const pgAsyncDecimal = (s: string, fallback: i32): i32 => {
655
+ const n: i32 = toI32(s.length)
656
+ if (n === 0 || n > 11) {
657
+ return fallback
658
+ }
659
+ let at: i32 = 0
660
+ const negative: boolean = s.charCodeAt(0) === 45
661
+ if (negative) {
662
+ at = 1
663
+ if (n === 1) {
664
+ return fallback
665
+ }
666
+ }
667
+ let v: i64 = 0
668
+ while (at < n) {
669
+ const c: i32 = toI32(s.charCodeAt(at))
670
+ if (c < 48 || c > 57) {
671
+ return fallback
672
+ }
673
+ v = v * toI64(10) + toI64(c - 48)
674
+ at += 1
675
+ }
676
+ if (negative) {
677
+ v = -v
678
+ }
679
+ if (v < toI64(-2147483648) || v > toI64(2147483647)) {
680
+ return fallback
681
+ }
682
+ return toI32(v)
683
+ }
684
+
685
+ /**
686
+ * The one place a wait's outcome becomes a failure code: 0 when `readable`
687
+ * or `writable` waited, else what a query or a connect fails with
688
+ * (`PG_ERR_CLOSED` beside it): `PG_ASYNC_CANCELLED` when the task was
689
+ * cancelled, which fails every wait it makes, else EBADF.
690
+ */
691
+ const pgAsyncWaitFailure = (waited: boolean): i32 => {
692
+ if (waited) {
693
+ return 0
694
+ }
695
+ return cancelled() ? PG_ASYNC_CANCELLED : PG_ASYNC_BAD_FD
696
+ }
697
+
698
+ /** `ticket`'s slot, after checking it is the slot's current claim; panics otherwise. */
699
+ const pgAsyncSlot = (pool: PgAsyncPool, ticket: i32): i32 => {
700
+ const slot: i32 = ticket >= 0 ? ticket % PG_ASYNC_MAX_SIZE : -1
701
+ if (
702
+ slot < 0 ||
703
+ slot >= pool.size ||
704
+ toI32(pool.claimed[slot]) !== 1 ||
705
+ toI32(ticket / PG_ASYNC_MAX_SIZE) !== pool.claims[slot]
706
+ ) {
707
+ panic("nish/net/postgres-async: a ticket that is not a current claim")
708
+ }
709
+ return slot
710
+ }
711
+
712
+ /**
713
+ * Connects every slot of `pool` that is not connected, one after another,
714
+ * and authenticates each on a `PgConnection` (startup, then SCRAM-SHA-256 or
715
+ * `trust`), which wipes its copy of the password once the proof is made and
716
+ * is then dropped. Call it from `main` or another function that is not a
717
+ * spawned task: it holds the password. A slot that fails stays unconnected;
718
+ * call it again to retry.
719
+ * @param pool The pool to fill.
720
+ * @param config The startup parameters and caps for the handshake.
721
+ * @param password The role's password as UTF-8 bytes; copied for each
722
+ * connection, so the caller wipes its own afterwards.
723
+ * @param target Where the server is, as `pgTarget` made it; a TCP host must
724
+ * be a numeric address, and a target that failed panics.
725
+ * @returns The number of slots connected after the call.
726
+ */
727
+ export const pgAsyncConnect = async (
728
+ pool: PgAsyncPool,
729
+ config: PgConfig,
730
+ password: Secret<u8[]>,
731
+ target: PgTarget
732
+ ): Promise<i32> => {
733
+ if (target.failure !== PG_TARGET_OK) {
734
+ panic("nish/net/postgres-async: pgAsyncConnect to a target that failed")
735
+ }
736
+ const address: u8[] = new Array<u8>(18)
737
+ if (!target.unix && netAddress(address, target.host, target.port) < 0) {
738
+ panic("nish/net/postgres-async: a TCP host must be a numeric address")
739
+ }
740
+ const nonce: u8[] = new Array<u8>(PG_ASYNC_NONCE_BYTES)
741
+ for (let s: i32 = 0; s < pool.size; s++) {
742
+ if (pool.fds[s] >= 0) {
743
+ continue
744
+ }
745
+ crypto.getRandomValues(nonce)
746
+ const conn = new PgConnection(config, password, nonce)
747
+ const fd: i32 = target.unix ? unixConnect(target.path) : tcpConnect(address)
748
+ if (fd < 0) {
749
+ conn.dispose()
750
+ continue
751
+ }
752
+ const made: boolean = await pgAsyncStartup(conn, fd, monotonicNanos(), pool.connectWaitMs)
753
+ conn.dispose()
754
+ if (made) {
755
+ pool.fds[s] = fd
756
+ pool.claimed[s] = 0
757
+ pool.connects += 1
758
+ pgAsyncForget(pool, s)
759
+ } else {
760
+ netClose(fd)
761
+ }
762
+ }
763
+ return pool.live()
764
+ }
765
+
766
+ /**
767
+ * Runs `conn`'s startup on `fd` until it is ready (true) or has failed
768
+ * (false), failing too once `waitMs` have passed since `began` (a
769
+ * `monotonicNanos` reading) when `waitMs` is above 0.
770
+ */
771
+ const pgAsyncStartup = async (conn: PgConnection, fd: i32, began: i64, waitMs: i32): Promise<boolean> => {
772
+ const connected: boolean = await pgAsyncWaitUntil(fd, true, began, waitMs)
773
+ if (!connected || connectResult(fd) !== 0) {
774
+ return false
775
+ }
776
+ while (true) {
777
+ while (conn.outputEnd() > conn.outputStart()) {
778
+ const n: i32 = netWrite(
779
+ fd,
780
+ conn.outputBuffer(),
781
+ conn.outputStart(),
782
+ conn.outputEnd() - conn.outputStart()
783
+ )
784
+ if (n === PG_ASYNC_AGAIN) {
785
+ const waited: boolean = await pgAsyncWaitUntil(fd, true, began, waitMs)
786
+ if (!waited) {
787
+ return false
788
+ }
789
+ } else if (n <= 0) {
790
+ conn.closed()
791
+ return false
792
+ } else {
793
+ conn.sent(n)
794
+ }
795
+ }
796
+ const event: i32 = conn.next()
797
+ if (event === PG_READY) {
798
+ return conn.txStatus === PG_ASYNC_IDLE
799
+ }
800
+ if (event === PG_FAILED) {
801
+ return false
802
+ }
803
+ // A step that queued an answer (the SCRAM messages) writes it before it
804
+ // reads: the server says nothing more until it has that answer.
805
+ if (event === PG_NEED_MORE && conn.outputEnd() === conn.outputStart()) {
806
+ const room: i32 = conn.inputRoom()
807
+ const got: i32 = room > 0 ? netRead(fd, conn.inputBuffer(), conn.inputEnd(), room) : 0
808
+ if (got === PG_ASYNC_AGAIN) {
809
+ const waited: boolean = await pgAsyncWaitUntil(fd, false, began, waitMs)
810
+ if (!waited) {
811
+ return false
812
+ }
813
+ } else if (got <= 0) {
814
+ conn.closed()
815
+ return false
816
+ } else {
817
+ conn.received(got)
818
+ }
819
+ }
820
+ }
821
+ }
822
+
823
+ /**
824
+ * Waits until `fd` is writable (`write`) or readable: true once it is, false
825
+ * when the wait failed, the task is cancelled, or `waitMs` (when above 0)
826
+ * have passed since `began`, a `monotonicNanos` reading.
827
+ */
828
+ const pgAsyncWaitUntil = async (fd: i32, write: boolean, began: i64, waitMs: i32): Promise<boolean> => {
829
+ let waited: boolean = false
830
+ if (waitMs <= 0 && write) {
831
+ waited = await writable(fd)
832
+ } else if (waitMs <= 0) {
833
+ waited = await readable(fd)
834
+ } else {
835
+ const left: i32 = waitMs - pgAsyncSince(began)
836
+ if (left <= 0) {
837
+ return false
838
+ }
839
+ if (write) {
840
+ waited = await writableWithin(fd, left)
841
+ } else {
842
+ waited = await readableWithin(fd, left)
843
+ }
844
+ }
845
+ return pgAsyncWaitFailure(waited) === 0
846
+ }
847
+
848
+ /** Milliseconds since `began`, a `monotonicNanos` reading. */
849
+ const pgAsyncSince = (began: i64): i32 => {
850
+ const ms: i64 = (monotonicNanos() - began) / toI64(1000000)
851
+ return ms > toI64(1073741823) ? 1073741823 : toI32(ms)
852
+ }
853
+
854
+ /**
855
+ * Wakes the tasks waiting on wake `w` (a slot, or `pool.size` for the pool):
856
+ * one byte on its socket pair, unless one is already there or none waits.
857
+ * The byte stays until every task then waiting has woken: the runtime reports
858
+ * at most 64 ready sockets a turn, and a byte read back by the first of
859
+ * many would leave the rest waiting until their time ran out.
860
+ */
861
+ const pgAsyncSignal = (pool: PgAsyncPool, w: i32): void => {
862
+ const fd: i32 = pool.wakes[w * 2 + 1]
863
+ if (pool.waiters[w] <= 0 || fd < 0) {
864
+ return
865
+ }
866
+ if (toI32(pool.wakePending[w]) === 0) {
867
+ pool.wakeBytes[0] = 1
868
+ if (netWrite(fd, pool.wakeBytes, 0, 1) !== 1) {
869
+ return
870
+ }
871
+ pool.wakePending[w] = 1
872
+ }
873
+ // Rung again while its byte is there, the byte now stays for every task
874
+ // waiting at this ring too: one that waited again after the last ring would
875
+ // otherwise see the byte read back before it was polled, and wait for ever.
876
+ pool.wakeUnseen[w] = pool.waiters[w]
877
+ pool.wakeRings[w] = (pool.wakeRings[w] + 1) % PG_ASYNC_QUEUE_WRAP
878
+ }
879
+
880
+ /**
881
+ * The seats a task could take now: on each live connection no task claimed
882
+ * whole, none doomed and none mid-write, `depth` less those in flight. A
883
+ * connection mid-write is left out because a task woken for it would only
884
+ * wait again; the write's end wakes the pool once more.
885
+ */
886
+ const pgAsyncFreeSeats = (pool: PgAsyncPool): i32 => {
887
+ let free: i32 = 0
888
+ for (let s: i32 = 0; s < pool.size; s++) {
889
+ if (
890
+ pool.fds[s] >= 0 &&
891
+ toI32(pool.claimed[s]) === 0 &&
892
+ pool.doomAt[s] < 0 &&
893
+ toI32(pool.writing[s]) === 0 &&
894
+ pool.seated[s] < pool.depth
895
+ ) {
896
+ free += pool.depth - pool.seated[s]
897
+ }
898
+ }
899
+ return free
900
+ }
901
+
902
+ /**
903
+ * Wakes the tasks waiting for a slot or seat: those outside the queue, and as
904
+ * many of the queue's first as there are free seats, at least its head, so
905
+ * seats freed together are taken in one loop turn and not one a turn.
906
+ */
907
+ const pgAsyncWakePool = (pool: PgAsyncPool): void => {
908
+ pgAsyncSignal(pool, pool.size)
909
+ const queued: i32 = (pool.seatTail - pool.seatHead + PG_ASYNC_QUEUE_WRAP) % PG_ASYNC_QUEUE_WRAP
910
+ if (queued === 0) {
911
+ return
912
+ }
913
+ const free: i32 = pgAsyncFreeSeats(pool)
914
+ let wake: i32 = free < 1 ? 1 : free
915
+ wake = wake > queued ? queued : wake
916
+ wake = wake > PG_ASYNC_LANES ? PG_ASYNC_LANES : wake
917
+ for (let k: i32 = 0; k < wake; k++) {
918
+ pgAsyncSignal(pool, pool.size + 1 + ((pool.seatHead + k) % PG_ASYNC_LANES))
919
+ }
920
+ }
921
+
922
+ /** Reads wake `w`'s byte back once every task it was written for has woken, so its waiters wait again. */
923
+ const pgAsyncDrain = (pool: PgAsyncPool, w: i32): void => {
924
+ const fd: i32 = pool.wakes[w * 2]
925
+ if (toI32(pool.wakePending[w]) === 1 && pool.wakeUnseen[w] <= 0 && fd >= 0) {
926
+ netRead(fd, pool.wakeBytes, 0, 8)
927
+ pool.wakePending[w] = 0
928
+ }
929
+ }
930
+
931
+ /**
932
+ * Waits on wake `w` for up to `ms` milliseconds (no limit when negative),
933
+ * opening its socket pair the first time, or 1 ms when no pair can be opened.
934
+ * A cancelled task returns at once.
935
+ */
936
+ const pgAsyncPark = async (pool: PgAsyncPool, w: i32, ms: i32): Promise<void> => {
937
+ if (pool.wakes[w * 2] < 0 && unixSocketPair(NET_UNIX_STREAM, pool.wakePair) >= 0) {
938
+ // Opened before this task counts as waiting, so no byte is written to a
939
+ // wake without a pair. Out of descriptors, it sleeps 1 ms and tries again.
940
+ pool.wakes[w * 2] = pool.wakePair[0]
941
+ pool.wakes[w * 2 + 1] = pool.wakePair[1]
942
+ }
943
+ const fd: i32 = pool.wakes[w * 2]
944
+ const rings: i32 = pool.wakeRings[w]
945
+ pool.waiters[w] += 1
946
+ if (fd < 0) {
947
+ await sleep(1)
948
+ } else {
949
+ await readableWithin(fd, ms)
950
+ }
951
+ pool.waiters[w] -= 1
952
+ if (pool.wakeRings[w] !== rings) {
953
+ // Waiting when the byte was written: one fewer it waits for.
954
+ pool.wakeUnseen[w] -= 1
955
+ }
956
+ }
957
+
958
+ /**
959
+ * Claims a free connection for the calling task, the whole of it: one with
960
+ * no pipelined statement in flight. While every live one is busy it waits
961
+ * until `pgAsyncRelease` or a pipelined answer frees one and wakes it, for at
962
+ * most `pool.claimWaitMs` in all. A cancelled task claims nothing, so a
963
+ * connection is never taken by a task that would close it at its first wait.
964
+ * It writes only numbers into the pool, so a spawned task may call it.
965
+ * @param pool The pool.
966
+ * @returns A ticket (0 or more) for `pgAsyncQuery` and then exactly one
967
+ * `pgAsyncRelease`; `PG_POOL_NONE` (-1) when no slot is connected;
968
+ * `PG_CARRIER_FULL` (-2) when none came free in time;
969
+ * `PG_ASYNC_CANCELLED` (-3) when the calling task is cancelled, before or
970
+ * while it waits.
971
+ */
972
+ export const pgAsyncClaim = async (pool: PgAsyncPool): Promise<i32> => {
973
+ const began: i64 = monotonicNanos()
974
+ let waited: boolean = false
975
+ while (true) {
976
+ if (cancelled()) {
977
+ return PG_ASYNC_CANCELLED
978
+ }
979
+ let live: boolean = false
980
+ for (let s: i32 = 0; s < pool.size; s++) {
981
+ if (pool.fds[s] < 0) {
982
+ continue
983
+ }
984
+ live = true
985
+ if (toI32(pool.claimed[s]) === 0 && pool.seated[s] === 0 && pool.doomAt[s] < 0) {
986
+ pool.claimed[s] = 1
987
+ pool.claims[s] = (pool.claims[s] + 1) % PG_ASYNC_CLAIM_WRAP
988
+ if (waited) {
989
+ // Another waiter may find room this one did not take.
990
+ pgAsyncWakePool(pool)
991
+ }
992
+ return pool.claims[s] * PG_ASYNC_MAX_SIZE + s
993
+ }
994
+ }
995
+ if (!live) {
996
+ return PG_POOL_NONE
997
+ }
998
+ const left: i32 = pool.claimWaitMs - pgAsyncSince(began)
999
+ if (left <= 0) {
1000
+ return PG_CARRIER_FULL
1001
+ }
1002
+ const skipped: boolean = await pgAsyncSkipAny(pool)
1003
+ if (skipped) {
1004
+ continue
1005
+ }
1006
+ pool.waits += 1
1007
+ waited = true
1008
+ await pgAsyncPark(pool, pool.size, left)
1009
+ pgAsyncDrain(pool, pool.size)
1010
+ }
1011
+ }
1012
+
1013
+ /**
1014
+ * Gives a claimed connection back, or closes it when `reusable` is false, and
1015
+ * wakes the tasks waiting for one; the ticket is spent either way, and a
1016
+ * ticket that is not the slot's current claim (a second release, or one after
1017
+ * `close()`) panics. It writes only numbers into the pool, so a spawned task
1018
+ * may call it.
1019
+ * @param pool The pool the ticket came from.
1020
+ * @param ticket The ticket `pgAsyncClaim` answered.
1021
+ * @param reusable The query's `reusable`; false closes the connection.
1022
+ */
1023
+ export const pgAsyncRelease = (pool: PgAsyncPool, ticket: i32, reusable: boolean): void => {
1024
+ const slot: i32 = pgAsyncSlot(pool, ticket)
1025
+ if (!reusable) {
1026
+ netClose(pool.fds[slot])
1027
+ pool.fds[slot] = -1
1028
+ pool.dropped += 1
1029
+ pgAsyncForget(pool, slot)
1030
+ }
1031
+ pool.claimed[slot] = 0
1032
+ pool.claims[slot] = (pool.claims[slot] + 1) % PG_ASYNC_CLAIM_WRAP
1033
+ pgAsyncWakePool(pool)
1034
+ }
1035
+
1036
+ /**
1037
+ * Registers a statement the pipelined calls run by its number, prepared once
1038
+ * on each connection, the first time a task sends it there. Call it from
1039
+ * `main` or another function that is not a spawned task, before the tasks
1040
+ * start: it grows the pool.
1041
+ * @param pool The pool.
1042
+ * @param sql One statement, `$1`, `$2`, ... naming the parameters.
1043
+ * @returns The statement's number for `pgAsyncSeat`, 0 or more; -1 when the
1044
+ * SQL holds a NUL or `PG_ASYNC_MAX_STATEMENTS` are registered already.
1045
+ */
1046
+ export const pgAsyncPrepare = (pool: PgAsyncPool, sql: string): i32 => {
1047
+ const bytes = pgAsyncBytes(sql)
1048
+ if (bytes === null || toI32(pool.statements.length) >= PG_ASYNC_MAX_STATEMENTS) {
1049
+ return -1
1050
+ }
1051
+ pool.statements.push(bytes)
1052
+ return toI32(pool.statements.length) - 1
1053
+ }
1054
+
1055
+ /**
1056
+ * Takes queue number `n` out of the seat queue: at its head, moves the head
1057
+ * past it and past every number whose task left already, and wakes the
1058
+ * waiters so the new head looks for a seat; otherwise marks it gone. -1 is
1059
+ * no number.
1060
+ */
1061
+ const pgAsyncUnqueue = (pool: PgAsyncPool, n: i32): void => {
1062
+ if (n < 0) {
1063
+ return
1064
+ }
1065
+ if (n !== pool.seatHead) {
1066
+ pool.seatGone[n % PG_ASYNC_QUEUE] = 1
1067
+ return
1068
+ }
1069
+ pool.seatHead = (pool.seatHead + 1) % PG_ASYNC_QUEUE_WRAP
1070
+ while (pool.seatHead !== pool.seatTail && toI32(pool.seatGone[pool.seatHead % PG_ASYNC_QUEUE]) !== 0) {
1071
+ pool.seatGone[pool.seatHead % PG_ASYNC_QUEUE] = 0
1072
+ pool.seatHead = (pool.seatHead + 1) % PG_ASYNC_QUEUE_WRAP
1073
+ }
1074
+ pgAsyncWakePool(pool)
1075
+ }
1076
+
1077
+ /**
1078
+ * Takes a seat for one statement on a shared connection: the live one with
1079
+ * the fewest statements in flight, below `pool.depth`, that no task claimed
1080
+ * whole and no task is writing to. The seat fixes the statement's place in
1081
+ * the connection's order, so the calling task goes straight on, with no
1082
+ * other `await` between: `pgAsyncSend` writes the statement, `pgAsyncTurn`
1083
+ * waits for its answer, `pgAsyncAnswer` builds it and `pgAsyncDone` spends
1084
+ * the ticket. Until `pgAsyncTurn` no other seat on the connection is taken,
1085
+ * so the statements go out in the order of their seats. While no connection has room it waits until a seat
1086
+ * or a connection frees and wakes it, for at most `pool.claimWaitMs` in all;
1087
+ * waiting tasks are seated in the order they began to wait, the first as many
1088
+ * as there are seats free at once, and a task that has not waited is seated
1089
+ * only while none waits.
1090
+ * It writes only numbers into the pool, so a spawned task may call it.
1091
+ * @param pool The pool.
1092
+ * @param statement A number `pgAsyncPrepare` answered; any other panics, as
1093
+ * does a `pool.depth` out of range.
1094
+ * @returns A ticket (0 or more) for `pgAsyncSend`, `pgAsyncTurn`,
1095
+ * `pgAsyncAnswer` and `pgAsyncDone`, each called once; `PG_POOL_NONE` (-1) when no slot is connected;
1096
+ * `PG_CARRIER_FULL` (-2) when no seat came free in time;
1097
+ * `PG_ASYNC_CANCELLED` (-3) when the calling task is cancelled, before or
1098
+ * while it waits.
1099
+ */
1100
+ export const pgAsyncSeat = async (pool: PgAsyncPool, statement: i32): Promise<i32> => {
1101
+ if (statement < 0 || statement >= toI32(pool.statements.length)) {
1102
+ panic("nish/net/postgres-async: a statement pgAsyncPrepare did not register")
1103
+ }
1104
+ if (pool.depth < 1 || pool.depth > PG_ASYNC_MAX_DEPTH) {
1105
+ panic("nish/net/postgres-async: a PgAsyncPool depth out of range")
1106
+ }
1107
+ const began: i64 = monotonicNanos()
1108
+ // This task's queue number once it waits, or -1.
1109
+ let queued: i32 = -1
1110
+ while (true) {
1111
+ if (cancelled()) {
1112
+ pgAsyncUnqueue(pool, queued)
1113
+ return PG_ASYNC_CANCELLED
1114
+ }
1115
+ let live: boolean = false
1116
+ let best: i32 = -1
1117
+ let free: i32 = 0
1118
+ for (let s: i32 = 0; s < pool.size; s++) {
1119
+ if (pool.fds[s] < 0) {
1120
+ continue
1121
+ }
1122
+ live = true
1123
+ if (toI32(pool.claimed[s]) !== 0 || pool.doomAt[s] >= 0 || pool.seated[s] >= pool.depth) {
1124
+ continue
1125
+ }
1126
+ free += pool.depth - pool.seated[s]
1127
+ if (toI32(pool.writing[s]) !== 0) {
1128
+ continue
1129
+ }
1130
+ if (best < 0 || pool.seated[s] < pool.seated[best]) {
1131
+ best = s
1132
+ }
1133
+ }
1134
+ // First come, first seated: under load a task that lost the seat it was
1135
+ // woken for to another would wait on until `claimWaitMs` failed it. Of
1136
+ // the queue, the first as many as there are free seats may take one, so
1137
+ // seats freed together go in one loop turn; a task outside the queue
1138
+ // takes one only while none waits.
1139
+ const turn: boolean =
1140
+ queued >= 0
1141
+ ? (queued - pool.seatHead + PG_ASYNC_QUEUE_WRAP) % PG_ASYNC_QUEUE_WRAP < free
1142
+ : pool.seatHead === pool.seatTail
1143
+ if (best >= 0 && turn) {
1144
+ for (let k: i32 = 0; k < PG_ASYNC_MAX_DEPTH; k++) {
1145
+ const seat: i32 = best * PG_ASYNC_MAX_DEPTH + k
1146
+ if (toI32(pool.seatUsed[seat]) !== 0) {
1147
+ continue
1148
+ }
1149
+ const known: i32 = best * PG_ASYNC_MAX_STATEMENTS + statement
1150
+ pool.seatUsed[seat] = 1
1151
+ pool.seatWaiting[seat] = 0
1152
+ pool.seatSeq[seat] = pool.nextSeq[best]
1153
+ pool.seatStatement[seat] = statement
1154
+ pool.seatParse[seat] = toI32(pool.prepared[known]) === 0 ? 1 : 0
1155
+ pool.prepared[known] = 1
1156
+ pool.nextSeq[best] = (pool.nextSeq[best] + 1) % PG_ASYNC_SEQ_WRAP
1157
+ pool.seated[best] += 1
1158
+ pool.writing[best] = 1
1159
+ pool.seatClaims[seat] = (pool.seatClaims[seat] + 1) % PG_ASYNC_SEAT_WRAP
1160
+ // The next in the queue may find a seat this one did not take.
1161
+ pgAsyncUnqueue(pool, queued)
1162
+ return pool.seatClaims[seat] * PG_ASYNC_SEATS + seat
1163
+ }
1164
+ }
1165
+ if (!live) {
1166
+ pgAsyncUnqueue(pool, queued)
1167
+ return PG_POOL_NONE
1168
+ }
1169
+ const left: i32 = pool.claimWaitMs - pgAsyncSince(began)
1170
+ if (left <= 0) {
1171
+ pgAsyncUnqueue(pool, queued)
1172
+ return PG_CARRIER_FULL
1173
+ }
1174
+ if (
1175
+ queued < 0 &&
1176
+ (pool.seatTail - pool.seatHead + PG_ASYNC_QUEUE_WRAP) % PG_ASYNC_QUEUE_WRAP < PG_ASYNC_QUEUE
1177
+ ) {
1178
+ queued = pool.seatTail
1179
+ pool.seatTail = (pool.seatTail + 1) % PG_ASYNC_QUEUE_WRAP
1180
+ }
1181
+ const skipped: boolean = await pgAsyncSkipAny(pool)
1182
+ if (skipped) {
1183
+ continue
1184
+ }
1185
+ const w: i32 = queued >= 0 ? pool.size + 1 + (queued % PG_ASYNC_LANES) : pool.size
1186
+ pool.waits += 1
1187
+ await pgAsyncPark(pool, w, left)
1188
+ pgAsyncDrain(pool, w)
1189
+ }
1190
+ }
1191
+
1192
+ /** `ticket`'s seat, after checking it is the seat's current claim; panics otherwise. */
1193
+ const pgAsyncSeatOf = (pool: PgAsyncPool, ticket: i32): i32 => {
1194
+ const seat: i32 = ticket >= 0 ? ticket % PG_ASYNC_SEATS : -1
1195
+ if (
1196
+ seat < 0 ||
1197
+ seat >= pool.size * PG_ASYNC_MAX_DEPTH ||
1198
+ toI32(pool.seatUsed[seat]) !== 1 ||
1199
+ toI32(ticket / PG_ASYNC_SEATS) !== pool.seatClaims[seat]
1200
+ ) {
1201
+ panic("nish/net/postgres-async: a ticket that is not a current seat")
1202
+ }
1203
+ return seat
1204
+ }
1205
+
1206
+ /**
1207
+ * Writes the seat's statement: its Parse the first time the connection runs
1208
+ * it, then Bind (each parameter in text), Execute and Sync, whole, waiting on
1209
+ * the socket while other tasks run. It only reads the pool; its buffer is the
1210
+ * calling task's.
1211
+ * @param pool The pool the ticket came from.
1212
+ * @param ticket A ticket `pgAsyncSeat` answered and no `pgAsyncDone` has
1213
+ * spent; any other panics.
1214
+ * @param params The parameters, as many as the statement names; a NUL in
1215
+ * one sends nothing.
1216
+ * @returns What to hand `pgAsyncTurn`: the bytes written, or
1217
+ * `PG_ASYNC_UNSENT` or `PG_ASYNC_UNSENT_CANCELLED` when nothing was, or
1218
+ * less than -15 when the write broke.
1219
+ */
1220
+ export const pgAsyncSend = async (pool: PgAsyncPool, ticket: i32, params: PgAsyncParams): Promise<i32> => {
1221
+ const seat: i32 = pgAsyncSeatOf(pool, ticket)
1222
+ if (cancelled()) {
1223
+ return PG_ASYNC_UNSENT_CANCELLED
1224
+ }
1225
+ const statement: i32 = pool.seatStatement[seat]
1226
+ const out: u8[] | null = pgAsyncEncode(
1227
+ pool.statements[statement],
1228
+ statement,
1229
+ toI32(pool.seatParse[seat]) === 1,
1230
+ params
1231
+ )
1232
+ if (out === null) {
1233
+ return PG_ASYNC_UNSENT
1234
+ }
1235
+ const fd: i32 = pool.fds[toI32(seat / PG_ASYNC_MAX_DEPTH)]
1236
+ let sent: i32 = 0
1237
+ while (sent < toI32(out.length)) {
1238
+ const n: i32 = netWrite(fd, out, sent, toI32(out.length) - sent)
1239
+ if (n === PG_ASYNC_AGAIN) {
1240
+ const waited: boolean = await writable(fd)
1241
+ const failed: i32 = pgAsyncWaitFailure(waited)
1242
+ if (failed === PG_ASYNC_CANCELLED && sent === 0) {
1243
+ return PG_ASYNC_UNSENT_CANCELLED
1244
+ }
1245
+ if (failed !== 0) {
1246
+ return PG_ASYNC_BROKEN + failed
1247
+ }
1248
+ } else if (n <= 0) {
1249
+ return PG_ASYNC_BROKEN + (n < PG_ASYNC_BROKEN ? n : 0)
1250
+ } else {
1251
+ sent += n
1252
+ }
1253
+ }
1254
+ return sent
1255
+ }
1256
+
1257
+ /** How far `seq` is past slot `s`'s next answer, in the order of its pipeline. */
1258
+ const pgAsyncAhead = (pool: PgAsyncPool, s: i32, seq: i32): i32 =>
1259
+ (seq - pool.served[s] + PG_ASYNC_SEQ_WRAP) % PG_ASYNC_SEQ_WRAP
1260
+
1261
+ /** Whether seat `seat`'s answer is lost: its connection failed at or before it. */
1262
+ const pgAsyncLostSeat = (pool: PgAsyncPool, seat: i32): boolean => {
1263
+ const s: i32 = toI32(seat / PG_ASYNC_MAX_DEPTH)
1264
+ const at: i32 = pool.doomAt[s]
1265
+ return at >= 0 && pgAsyncAhead(pool, s, pool.seatSeq[seat]) >= pgAsyncAhead(pool, s, at)
1266
+ }
1267
+
1268
+ /**
1269
+ * Whether a task waiting on slot `s`, other than `except`'s, may go on: its
1270
+ * turn came, its answer is lost, or an abandoned answer ahead of it waits to
1271
+ * be read past.
1272
+ */
1273
+ const pgAsyncReady = (pool: PgAsyncPool, s: i32, except: i32): boolean => {
1274
+ let waiting: boolean = false
1275
+ for (let k: i32 = 0; k < PG_ASYNC_MAX_DEPTH; k++) {
1276
+ const seat: i32 = s * PG_ASYNC_MAX_DEPTH + k
1277
+ if (seat === except || toI32(pool.seatWaiting[seat]) === 0) {
1278
+ continue
1279
+ }
1280
+ if (pool.seatSeq[seat] === pool.served[s] || pgAsyncLostSeat(pool, seat)) {
1281
+ return true
1282
+ }
1283
+ waiting = true
1284
+ }
1285
+ return waiting && pgAsyncSkippable(pool, s) >= 0
1286
+ }
1287
+
1288
+ /**
1289
+ * Marks slot `s` lost from sequence number `seq` on, settles the abandoned
1290
+ * seats it loses, and wakes those it fails.
1291
+ */
1292
+ const pgAsyncDoom = (pool: PgAsyncPool, s: i32, seq: i32): void => {
1293
+ if (pool.doomAt[s] < 0 || pgAsyncAhead(pool, s, seq) < pgAsyncAhead(pool, s, pool.doomAt[s])) {
1294
+ pool.doomAt[s] = seq
1295
+ }
1296
+ // A seat freed here closes the connection only once no seat is left on it;
1297
+ // the one being read past is settled by its reader.
1298
+ for (let k: i32 = 0; k < PG_ASYNC_MAX_DEPTH; k++) {
1299
+ const seat: i32 = s * PG_ASYNC_MAX_DEPTH + k
1300
+ const state: i32 = toI32(pool.seatAbandoned[seat])
1301
+ const reading: boolean = toI32(pool.skipping[s]) === 1 && pool.seatSeq[seat] === pool.served[s]
1302
+ if (
1303
+ toI32(pool.seatUsed[seat]) === 1 &&
1304
+ (state === 1 || state === 2) &&
1305
+ !reading &&
1306
+ pgAsyncLostSeat(pool, seat)
1307
+ ) {
1308
+ pgAsyncSettle(pool, seat)
1309
+ }
1310
+ }
1311
+ if (pgAsyncReady(pool, s, -1)) {
1312
+ pgAsyncSignal(pool, s)
1313
+ }
1314
+ }
1315
+
1316
+ /**
1317
+ * Leaves seat `seat` to the pool: its task was cancelled with its answer
1318
+ * unread, so the next task to wait on the connection, or for a seat on it,
1319
+ * reads past that answer instead of the connection being closed.
1320
+ */
1321
+ const pgAsyncAbandon = (pool: PgAsyncPool, seat: i32): void => {
1322
+ const s: i32 = toI32(seat / PG_ASYNC_MAX_DEPTH)
1323
+ pool.seatAbandoned[seat] = 1
1324
+ if (pgAsyncReady(pool, s, seat)) {
1325
+ pgAsyncSignal(pool, s)
1326
+ }
1327
+ pgAsyncWakePool(pool)
1328
+ }
1329
+
1330
+ /**
1331
+ * An abandoned seat whose answer is read past or lost: freed once its ticket is
1332
+ * spent, else marked so `pgAsyncDone` frees it.
1333
+ */
1334
+ const pgAsyncSettle = (pool: PgAsyncPool, seat: i32): void => {
1335
+ if (toI32(pool.seatAbandoned[seat]) === 2) {
1336
+ pgAsyncFree(pool, seat)
1337
+ } else {
1338
+ pool.seatAbandoned[seat] = 3
1339
+ }
1340
+ }
1341
+
1342
+ /** The abandoned seat in turn on slot `s` when no task reads past it yet, or -1. */
1343
+ const pgAsyncSkippable = (pool: PgAsyncPool, s: i32): i32 => {
1344
+ if (pool.fds[s] < 0 || toI32(pool.skipping[s]) !== 0) {
1345
+ return -1
1346
+ }
1347
+ for (let k: i32 = 0; k < PG_ASYNC_MAX_DEPTH; k++) {
1348
+ const seat: i32 = s * PG_ASYNC_MAX_DEPTH + k
1349
+ const state: i32 = toI32(pool.seatAbandoned[seat])
1350
+ if (
1351
+ toI32(pool.seatUsed[seat]) === 1 &&
1352
+ (state === 1 || state === 2) &&
1353
+ pool.seatSeq[seat] === pool.served[s] &&
1354
+ !pgAsyncLostSeat(pool, seat)
1355
+ ) {
1356
+ return seat
1357
+ }
1358
+ }
1359
+ return -1
1360
+ }
1361
+
1362
+ /**
1363
+ * Reads past the answer of `seat`, an abandoned seat in turn on slot `s`,
1364
+ * and serves the next. An answer that is not a plain one ending idle (a
1365
+ * frame this module does not expect, a transaction left open, a setting
1366
+ * changed) or larger than the pool's input loses the connection from it on,
1367
+ * as does a socket error. A cancelled reader stops and leaves the bytes read
1368
+ * for the next.
1369
+ */
1370
+ const pgAsyncSkip = async (pool: PgAsyncPool, s: i32, seat: i32): Promise<void> => {
1371
+ const seq: i32 = pool.served[s]
1372
+ const fd: i32 = pool.fds[s]
1373
+ const input: u8[] = pool.inputs[s]
1374
+ pool.skipping[s] = 1
1375
+ let fit: boolean = true
1376
+ while (!pgAsyncScan(pool, s)) {
1377
+ if (pool.inStart[s] > 0) {
1378
+ copyBytes(input, 0, input, pool.inStart[s], pool.inEnd[s] - pool.inStart[s])
1379
+ pool.inEnd[s] -= pool.inStart[s]
1380
+ pool.inStart[s] = 0
1381
+ }
1382
+ if (pool.inEnd[s] >= toI32(input.length)) {
1383
+ fit = false
1384
+ break
1385
+ }
1386
+ const got: i32 = netRead(fd, input, pool.inEnd[s], toI32(input.length) - pool.inEnd[s])
1387
+ if (got === PG_ASYNC_AGAIN) {
1388
+ const waited: boolean = await readable(fd)
1389
+ if (pgAsyncLostSeat(pool, seat)) {
1390
+ pool.skipping[s] = 0
1391
+ pgAsyncSettle(pool, seat)
1392
+ return
1393
+ }
1394
+ if (!waited && cancelled()) {
1395
+ // Another task reads on from where this one stopped.
1396
+ pool.skipping[s] = 0
1397
+ if (pgAsyncReady(pool, s, -1)) {
1398
+ pgAsyncSignal(pool, s)
1399
+ }
1400
+ pgAsyncWakePool(pool)
1401
+ return
1402
+ }
1403
+ if (!waited) {
1404
+ fit = false
1405
+ break
1406
+ }
1407
+ } else if (got <= 0) {
1408
+ fit = false
1409
+ break
1410
+ } else {
1411
+ pool.inEnd[s] += got
1412
+ }
1413
+ }
1414
+ pool.skipping[s] = 0
1415
+ if (!fit || pool.inAnswer[s] < 0 || !pgAsyncPlain(pool, s)) {
1416
+ pgAsyncDoom(pool, s, seq)
1417
+ return
1418
+ }
1419
+ pool.inStart[s] = pool.inAnswer[s]
1420
+ if (pool.inStart[s] === pool.inEnd[s]) {
1421
+ pool.inStart[s] = 0
1422
+ pool.inEnd[s] = 0
1423
+ }
1424
+ pool.served[s] = (seq + 1) % PG_ASYNC_SEQ_WRAP
1425
+ if (toI32(pool.seatParse[seat]) === 1 && toI32(pool.inParsed[s]) === 0) {
1426
+ pool.prepared[s * PG_ASYNC_MAX_STATEMENTS + pool.seatStatement[seat]] = 0
1427
+ }
1428
+ pgAsyncSettle(pool, seat)
1429
+ if (pgAsyncReady(pool, s, -1)) {
1430
+ pgAsyncSignal(pool, s)
1431
+ }
1432
+ pgAsyncWakePool(pool)
1433
+ }
1434
+
1435
+ /**
1436
+ * Whether the answer in turn on slot `s`, at `[inStart, inAnswer)`, leaves
1437
+ * the connection as it found it: only the frames a statement's answer has,
1438
+ * ending with a ReadyForQuery that is idle.
1439
+ */
1440
+ const pgAsyncPlain = (pool: PgAsyncPool, s: i32): boolean => {
1441
+ const input: u8[] = pool.inputs[s]
1442
+ const stop: i32 = pool.inAnswer[s]
1443
+ let at: i32 = pool.inStart[s]
1444
+ while (at >= 0 && at + 5 < toI32(input.length) && at + 5 <= stop && stop <= toI32(input.length)) {
1445
+ const type: i32 = toI32(input[at])
1446
+ const next: i32 = at + 1 + getI32BE(input, at + 1)
1447
+ // Not reached: `pgAsyncScan` refused a length under 4 before this answer
1448
+ // could be read past. Kept so this walk does not rest on that.
1449
+ if (next < at + 5) {
1450
+ return false
1451
+ }
1452
+ if (type === 90) {
1453
+ return next === stop && next - at === 6 && toI32(input[at + 5]) === PG_ASYNC_IDLE
1454
+ }
1455
+ if (
1456
+ type !== 49 &&
1457
+ type !== 50 &&
1458
+ type !== 68 &&
1459
+ type !== 67 &&
1460
+ type !== 69 &&
1461
+ type !== 73 &&
1462
+ type !== 78 &&
1463
+ type !== 65
1464
+ ) {
1465
+ return false
1466
+ }
1467
+ at = next
1468
+ }
1469
+ return false
1470
+ }
1471
+
1472
+ /**
1473
+ * Reads past one abandoned answer, on any connection where no task reads past
1474
+ * it yet, for a task waiting for room: the seats of a connection whose tasks
1475
+ * were all cancelled are otherwise never given back.
1476
+ * @returns Whether it read past one, or tried to.
1477
+ */
1478
+ const pgAsyncSkipAny = async (pool: PgAsyncPool): Promise<boolean> => {
1479
+ for (let s: i32 = 0; s < pool.size; s++) {
1480
+ const seat: i32 = pgAsyncSkippable(pool, s)
1481
+ if (seat >= 0) {
1482
+ await pgAsyncSkip(pool, s, seat)
1483
+ return true
1484
+ }
1485
+ }
1486
+ return false
1487
+ }
1488
+
1489
+ /**
1490
+ * Gives seat `seat` back; the connection closes once a lost one has no seat
1491
+ * left. Wakes the tasks waiting for room.
1492
+ */
1493
+ const pgAsyncFree = (pool: PgAsyncPool, seat: i32): void => {
1494
+ const s: i32 = toI32(seat / PG_ASYNC_MAX_DEPTH)
1495
+ pool.seatUsed[seat] = 0
1496
+ pool.seatWaiting[seat] = 0
1497
+ pool.seatAbandoned[seat] = 0
1498
+ pool.seatClaims[seat] = (pool.seatClaims[seat] + 1) % PG_ASYNC_SEAT_WRAP
1499
+ pool.seated[s] -= 1
1500
+ if (pool.doomAt[s] >= 0 && pool.seated[s] === 0) {
1501
+ if (pool.fds[s] >= 0) {
1502
+ netClose(pool.fds[s])
1503
+ pool.fds[s] = -1
1504
+ pool.dropped += 1
1505
+ }
1506
+ pgAsyncForget(pool, s)
1507
+ }
1508
+ pgAsyncWakePool(pool)
1509
+ }
1510
+
1511
+ /**
1512
+ * Whether the answer in turn on slot `s` lies whole in its input, from
1513
+ * `inStart`: `inAnswer` is set to where it ends, past its ReadyForQuery, or
1514
+ * to -1 for a frame length no answer has, which `pgAsyncAnswer` fails.
1515
+ */
1516
+ const pgAsyncScan = (pool: PgAsyncPool, s: i32): boolean => {
1517
+ const input: u8[] = pool.inputs[s]
1518
+ const end: i32 = pool.inEnd[s]
1519
+ let at: i32 = pool.inStart[s]
1520
+ pool.inParsed[s] = 0
1521
+ while (end - at >= 5 && at >= 0 && at + 5 <= toI32(input.length)) {
1522
+ const length: i32 = getI32BE(input, at + 1)
1523
+ if (length < 4 || length > pool.maxMessage) {
1524
+ pool.inAnswer[s] = -1
1525
+ return true
1526
+ }
1527
+ if (end - at - 1 < length) {
1528
+ return false
1529
+ }
1530
+ const type: i32 = toI32(input[at])
1531
+ at += 1 + length
1532
+ if (type === 49) {
1533
+ pool.inParsed[s] = 1
1534
+ }
1535
+ if (type === 90) {
1536
+ pool.inAnswer[s] = at
1537
+ return true
1538
+ }
1539
+ }
1540
+ return false
1541
+ }
1542
+
1543
+ /**
1544
+ * Waits for the seat's turn and reads its answer off the connection: the
1545
+ * statements seated before it are answered first, to their own tasks, and
1546
+ * what they read past their own answers begins this one. One read takes what
1547
+ * the socket holds, up to the pool's input, so the answers behind this one
1548
+ * often arrive with it. A lost connection (a socket error) fails this
1549
+ * statement and every one behind it. A task cancelled with its answer unread
1550
+ * fails alone: its seat is abandoned, and the next task to wait on the
1551
+ * connection reads past that answer, or loses the connection from it on when
1552
+ * the answer is not a plain one ending idle or is larger than the pool's
1553
+ * input. It writes only numbers into the pool, so a spawned task may call it;
1554
+ * `pgAsyncAnswer` then builds the answer in the task's memory.
1555
+ * @param pool The pool the ticket came from; a cap out of its range panics.
1556
+ * @param ticket The ticket `pgAsyncSeat` answered and `pgAsyncSend` used;
1557
+ * any other panics.
1558
+ * @param sent What `pgAsyncSend` answered.
1559
+ * @returns What to hand `pgAsyncAnswer` and `pgAsyncDone`: 0 when the answer
1560
+ * is there to read, else less than 0 for a statement that failed unanswered.
1561
+ */
1562
+ export const pgAsyncTurn = async (pool: PgAsyncPool, ticket: i32, sent: i32): Promise<i32> => {
1563
+ pgAsyncCheckCaps(pool)
1564
+ const seat: i32 = pgAsyncSeatOf(pool, ticket)
1565
+ const s: i32 = toI32(seat / PG_ASYNC_MAX_DEPTH)
1566
+ const seq: i32 = pool.seatSeq[seat]
1567
+ if (sent === PG_ASYNC_UNSENT || sent === PG_ASYNC_UNSENT_CANCELLED) {
1568
+ // Nothing went out; `pgAsyncDone` hands its place in the order back
1569
+ // while `writing` keeps any other seat from being taken here.
1570
+ return sent
1571
+ }
1572
+ pool.writing[s] = 0
1573
+ pgAsyncWakePool(pool)
1574
+ if (sent < 0) {
1575
+ pgAsyncDoom(pool, s, seq)
1576
+ return sent <= PG_ASYNC_BROKEN ? sent : PG_ASYNC_BROKEN
1577
+ }
1578
+ pool.seatWaiting[seat] = 1
1579
+ let gaveUp: boolean = false
1580
+ let yields: i32 = 0
1581
+ while (pool.served[s] !== seq && !pgAsyncLostSeat(pool, seat)) {
1582
+ if (cancelled()) {
1583
+ gaveUp = true
1584
+ break
1585
+ }
1586
+ const ahead: i32 = pgAsyncSkippable(pool, s)
1587
+ if (ahead >= 0) {
1588
+ await pgAsyncSkip(pool, s, ahead)
1589
+ } else if (yields < PG_ASYNC_TURN_YIELDS) {
1590
+ // The answer ahead is usually read within a turn or two of the loop:
1591
+ // yielding costs no system call, where parking on the wake costs six.
1592
+ yields += 1
1593
+ await sleep(0)
1594
+ } else {
1595
+ pool.turnWaits += 1
1596
+ await pgAsyncPark(pool, s, -1)
1597
+ // The last of the waiters the byte woke reads it, as in the claim and
1598
+ // seat loops: a seat that waits again must not park on a byte nobody reads.
1599
+ pgAsyncDrain(pool, s)
1600
+ }
1601
+ }
1602
+ pool.seatWaiting[seat] = 0
1603
+ if (!pgAsyncReady(pool, s, seat)) {
1604
+ pgAsyncDrain(pool, s)
1605
+ }
1606
+ if (pgAsyncLostSeat(pool, seat)) {
1607
+ return PG_ASYNC_BROKEN + (cancelled() ? PG_ASYNC_CANCELLED : 0)
1608
+ }
1609
+ if (gaveUp) {
1610
+ // Its answer is on its way and this task will not read it: the next one does.
1611
+ pgAsyncAbandon(pool, seat)
1612
+ return PG_ASYNC_BROKEN + PG_ASYNC_CANCELLED
1613
+ }
1614
+ const fd: i32 = pool.fds[s]
1615
+ const input: u8[] = pool.inputs[s]
1616
+ while (!pgAsyncScan(pool, s)) {
1617
+ if (pool.inStart[s] > 0) {
1618
+ copyBytes(input, 0, input, pool.inStart[s], pool.inEnd[s] - pool.inStart[s])
1619
+ pool.inEnd[s] -= pool.inStart[s]
1620
+ pool.inStart[s] = 0
1621
+ }
1622
+ if (pool.inEnd[s] >= toI32(input.length)) {
1623
+ // Past the input: `pgAsyncAnswer` reads the rest of it alone.
1624
+ pool.inAnswer[s] = -1
1625
+ return 0
1626
+ }
1627
+ const got: i32 = netRead(fd, input, pool.inEnd[s], toI32(input.length) - pool.inEnd[s])
1628
+ if (got === PG_ASYNC_AGAIN) {
1629
+ const waited: boolean = await readable(fd)
1630
+ const failed: i32 = pgAsyncWaitFailure(waited)
1631
+ if (failed === PG_ASYNC_CANCELLED) {
1632
+ // The bytes read stay in the input for the task that reads past the rest.
1633
+ pgAsyncAbandon(pool, seat)
1634
+ return PG_ASYNC_BROKEN + failed
1635
+ }
1636
+ if (failed !== 0) {
1637
+ pgAsyncDoom(pool, s, seq)
1638
+ return PG_ASYNC_BROKEN + failed
1639
+ }
1640
+ } else if (got <= 0) {
1641
+ pgAsyncDoom(pool, s, seq)
1642
+ return PG_ASYNC_BROKEN + (got < 0 ? got : 0)
1643
+ } else {
1644
+ pool.inEnd[s] += got
1645
+ }
1646
+ }
1647
+ return 0
1648
+ }
1649
+
1650
+ /**
1651
+ * Builds the seat's answer, in the calling task's memory, from what
1652
+ * `pgAsyncTurn` read, reading the rest of an answer past the pool's input
1653
+ * from the socket, never past its ReadyForQuery. A statement the server
1654
+ * refuses fails alone (each has its own Sync); one seated behind a refused
1655
+ * Parse fails with SQLSTATE `26000` and the next one parses again. A frame
1656
+ * this module does not expect or a cap past which it cannot be read fails it
1657
+ * with `reusable` false. It only reads the pool, so a spawned task may call
1658
+ * it.
1659
+ * @param pool The pool the ticket came from; a cap out of its range panics.
1660
+ * @param ticket The ticket `pgAsyncTurn` used; any other panics, as does a
1661
+ * ticket whose turn has not come.
1662
+ * @param turn What `pgAsyncTurn` answered; one below 0 fails the answer
1663
+ * without reading, with `PG_ERR_ENCODING` for a parameter that could not be
1664
+ * sent and `PG_ERR_CLOSED` otherwise.
1665
+ * @returns The answer; its `reusable` goes to `pgAsyncDone`.
1666
+ */
1667
+ export const pgAsyncAnswer = async (pool: PgAsyncPool, ticket: i32, turn: i32): Promise<PgAsyncResult> => {
1668
+ pgAsyncCheckCaps(pool)
1669
+ const seat: i32 = pgAsyncSeatOf(pool, ticket)
1670
+ const s: i32 = toI32(seat / PG_ASYNC_MAX_DEPTH)
1671
+ if (turn < 0) {
1672
+ const result = new PgAsyncResult()
1673
+ if (turn === PG_ASYNC_UNSENT || turn === PG_ASYNC_UNSENT_CANCELLED) {
1674
+ result.code = PG_CARRIER_FAILED
1675
+ result.failure = turn === PG_ASYNC_UNSENT ? PG_ERR_ENCODING : PG_ERR_CLOSED
1676
+ result.socketError = turn === PG_ASYNC_UNSENT ? 0 : PG_ASYNC_CANCELLED
1677
+ result.reusable = true
1678
+ return result
1679
+ }
1680
+ return pgAsyncLost(result, PG_ERR_CLOSED, turn <= PG_ASYNC_BROKEN ? turn - PG_ASYNC_BROKEN : 0)
1681
+ }
1682
+ if (pool.served[s] !== pool.seatSeq[seat] || pgAsyncLostSeat(pool, seat)) {
1683
+ panic("nish/net/postgres-async: an answer read before its turn")
1684
+ }
1685
+ // Copied into the task's memory: the spawn rules read an array of the pool
1686
+ // handed across an `await` as one the callee may grow.
1687
+ const input: u8[] = pool.inputs[s]
1688
+ const from: i32 = pool.inStart[s]
1689
+ const to: i32 = pool.inAnswer[s] >= 0 ? pool.inAnswer[s] : pool.inEnd[s]
1690
+ const carried: u8[] = new Array<u8>(
1691
+ from >= 0 && from <= to && to <= toI32(input.length) ? to - from : toI32(0)
1692
+ )
1693
+ copyBytes(carried, 0, input, from, toI32(carried.length))
1694
+ return await pgAsyncRead(
1695
+ pool.fds[s],
1696
+ carried,
1697
+ true,
1698
+ pool.maxMessage,
1699
+ pool.maxColumns,
1700
+ pool.maxRows,
1701
+ pool.maxResultBytes
1702
+ )
1703
+ }
1704
+
1705
+ /**
1706
+ * Spends the seat's ticket once its answer is built: the connection moves
1707
+ * past the answer, the next seat in its order is served, and the tasks
1708
+ * waiting for room are woken. A Parse that failed is sent again by the next
1709
+ * seat that runs the statement; an answer that left the connection unfit
1710
+ * fails the seats behind it, and the connection closes once the last of them
1711
+ * is answered. It writes only numbers into the pool, so a spawned task may
1712
+ * call it.
1713
+ * @param pool The pool the ticket came from.
1714
+ * @param ticket The ticket `pgAsyncAnswer` used; it is spent here, and any
1715
+ * other panics.
1716
+ * @param turn What `pgAsyncTurn` answered.
1717
+ * @param reusable The answer's `reusable`.
1718
+ */
1719
+ export const pgAsyncDone = (pool: PgAsyncPool, ticket: i32, turn: i32, reusable: boolean): void => {
1720
+ const seat: i32 = pgAsyncSeatOf(pool, ticket)
1721
+ const s: i32 = toI32(seat / PG_ASYNC_MAX_DEPTH)
1722
+ const seq: i32 = pool.seatSeq[seat]
1723
+ const statement: i32 = s * PG_ASYNC_MAX_STATEMENTS + pool.seatStatement[seat]
1724
+ const abandoned: i32 = toI32(pool.seatAbandoned[seat])
1725
+ if (abandoned === 1) {
1726
+ // Its answer is not read past yet: the ticket is spent, the seat stays until it is.
1727
+ pool.seatAbandoned[seat] = 2
1728
+ pool.seatClaims[seat] = (pool.seatClaims[seat] + 1) % PG_ASYNC_SEAT_WRAP
1729
+ return
1730
+ }
1731
+ if (abandoned === 3) {
1732
+ pgAsyncFree(pool, seat)
1733
+ return
1734
+ }
1735
+ if (turn === PG_ASYNC_UNSENT || turn === PG_ASYNC_UNSENT_CANCELLED) {
1736
+ // No other seat was taken here while it was being written, so its place
1737
+ // in the order is handed back.
1738
+ pool.nextSeq[s] = seq
1739
+ if (toI32(pool.seatParse[seat]) === 1) {
1740
+ pool.prepared[statement] = 0
1741
+ }
1742
+ pool.writing[s] = 0
1743
+ pgAsyncFree(pool, seat)
1744
+ return
1745
+ }
1746
+ if (turn >= 0 && pool.served[s] === seq) {
1747
+ pool.inStart[s] = pool.inAnswer[s] >= 0 ? pool.inAnswer[s] : pool.inEnd[s]
1748
+ if (pool.inStart[s] === pool.inEnd[s]) {
1749
+ pool.inStart[s] = 0
1750
+ pool.inEnd[s] = 0
1751
+ }
1752
+ pool.served[s] = (seq + 1) % PG_ASYNC_SEQ_WRAP
1753
+ if (toI32(pool.seatParse[seat]) === 1 && toI32(pool.inParsed[s]) === 0) {
1754
+ pool.prepared[statement] = 0
1755
+ }
1756
+ if (!reusable) {
1757
+ // A lost frame, a transaction left open or a setting changed: the
1758
+ // statements behind this one would be read out of step, or run in a
1759
+ // session they did not ask for.
1760
+ pgAsyncDoom(pool, s, pool.served[s])
1761
+ }
1762
+ if (pgAsyncReady(pool, s, seat)) {
1763
+ pgAsyncSignal(pool, s)
1764
+ }
1765
+ }
1766
+ pgAsyncFree(pool, seat)
1767
+ }
1768
+
1769
+ /**
1770
+ * Runs one statement on the ticket's connection: Parse, Bind (each parameter
1771
+ * in text), Execute and Sync go out in one write, and the answer is read to
1772
+ * its ReadyForQuery, waiting on the socket while other tasks run. It only
1773
+ * reads the pool; its buffers and the answer are the calling task's.
1774
+ * @param pool The pool the ticket came from; a cap out of its range panics.
1775
+ * @param ticket A ticket `pgAsyncClaim` answered and no `pgAsyncRelease` has
1776
+ * spent; any other panics.
1777
+ * @param sql One statement, `$1`, `$2`, ... naming the parameters; a NUL in
1778
+ * it fails the query with `PG_ERR_ENCODING` without sending anything.
1779
+ * @param params The parameters, as many as the statement names; a NUL in
1780
+ * a text one fails the query the same way.
1781
+ * @returns The answer; its `reusable` goes to `pgAsyncRelease`.
1782
+ */
1783
+ export const pgAsyncQuery = async (
1784
+ pool: PgAsyncPool,
1785
+ ticket: i32,
1786
+ sql: string,
1787
+ params: PgAsyncParams
1788
+ ): Promise<PgAsyncResult> => {
1789
+ pgAsyncCheckCaps(pool)
1790
+ const fd: i32 = pool.fds[pgAsyncSlot(pool, ticket)]
1791
+ const result = new PgAsyncResult()
1792
+ if (cancelled()) {
1793
+ // Nothing is sent, so the connection is still in step and is given back.
1794
+ result.code = PG_CARRIER_FAILED
1795
+ result.failure = PG_ERR_CLOSED
1796
+ result.socketError = PG_ASYNC_CANCELLED
1797
+ result.reusable = true
1798
+ return result
1799
+ }
1800
+ const sqlBytes = pgAsyncBytes(sql)
1801
+ const out: u8[] | null = sqlBytes === null ? null : pgAsyncEncode(sqlBytes, -1, true, params)
1802
+ if (out === null) {
1803
+ result.code = PG_CARRIER_FAILED
1804
+ result.failure = PG_ERR_ENCODING
1805
+ result.reusable = true
1806
+ return result
1807
+ }
1808
+ let sent: i32 = 0
1809
+ while (sent < toI32(out.length)) {
1810
+ const n: i32 = netWrite(fd, out, sent, toI32(out.length) - sent)
1811
+ if (n === PG_ASYNC_AGAIN) {
1812
+ const waited: boolean = await writable(fd)
1813
+ const failed: i32 = pgAsyncWaitFailure(waited)
1814
+ if (failed !== 0) {
1815
+ return pgAsyncLost(result, PG_ERR_CLOSED, failed)
1816
+ }
1817
+ } else if (n <= 0) {
1818
+ return pgAsyncLost(result, PG_ERR_CLOSED, n)
1819
+ } else {
1820
+ sent += n
1821
+ }
1822
+ }
1823
+ const none: u8[] = []
1824
+ return await pgAsyncRead(
1825
+ fd,
1826
+ none,
1827
+ false,
1828
+ pool.maxMessage,
1829
+ pool.maxColumns,
1830
+ pool.maxRows,
1831
+ pool.maxResultBytes
1832
+ )
1833
+ }
1834
+
1835
+ /**
1836
+ * Panics on a cap that is a mistake in the program, as `PgConfig`'s are. The
1837
+ * bounds keep `row * columns` in `PgAsyncResult` from overflowing: the cells
1838
+ * kept are under `maxResultBytes / 16`, below 2^26.
1839
+ */
1840
+ const pgAsyncCheckCaps = (pool: PgAsyncPool): void => {
1841
+ if (
1842
+ pool.maxMessage < 1024 ||
1843
+ pool.maxMessage > PG_ASYNC_MAX_CAP ||
1844
+ pool.maxColumns < 1 ||
1845
+ pool.maxColumns > 65535 ||
1846
+ pool.maxRows < 1 ||
1847
+ pool.maxRows > PG_ASYNC_MAX_ROWS ||
1848
+ pool.maxResultBytes < 1024 ||
1849
+ pool.maxResultBytes > PG_ASYNC_MAX_CAP
1850
+ ) {
1851
+ panic("nish/net/postgres-async: a PgAsyncPool cap out of range")
1852
+ }
1853
+ }
1854
+
1855
+ /** `result` failed for `failure`, its socket error `socketError`, and its connection unfit to reuse. */
1856
+ const pgAsyncLost = (result: PgAsyncResult, failure: i32, socketError: i32): PgAsyncResult => {
1857
+ result.code = PG_CARRIER_FAILED
1858
+ result.failure = failure
1859
+ result.socketError = socketError
1860
+ result.reusable = false
1861
+ return result
1862
+ }
1863
+
1864
+ /**
1865
+ * Parse (when `parse`), Bind, Execute and Sync for the statement `sql` and
1866
+ * `params`, or null for a NUL in a parameter. `name` -1 is the unnamed
1867
+ * statement; 0 or more names it `n<name>`, which the connection keeps.
1868
+ */
1869
+ const pgAsyncEncode = (sql: u8[], name: i32, parse: boolean, params: PgAsyncParams): u8[] | null => {
1870
+ const count: i32 = toI32(params.values.length)
1871
+ if (count > 65535) {
1872
+ return null
1873
+ }
1874
+ // The statement's name: none, or `n` and its decimal digits (at most 2).
1875
+ const label: u8[] = pgAsyncLabel(name)
1876
+ const named: i32 = toI32(label.length)
1877
+ const values: u8[][] = []
1878
+ // The length, "" portal, the statement's name and NUL, no parameter formats,
1879
+ // the count, no result formats: 4 + 1 + named + 1 + 2 + 2 + 2, held as an
1880
+ // i32 in either number mode.
1881
+ let bind: i32 = toI32(12) + named
1882
+ for (let i: i32 = 0; i < count; i++) {
1883
+ const v = pgAsyncBytes(params.values[i])
1884
+ if (v === null) {
1885
+ return null
1886
+ }
1887
+ values.push(v)
1888
+ bind += toI32(4)
1889
+ if (!params.nulls[i]) {
1890
+ bind += toI32(v.length)
1891
+ }
1892
+ }
1893
+ const sqlLength: i32 = toI32(sql.length)
1894
+ // The length, the statement's name and NUL, the SQL and its NUL, no parameter types.
1895
+ const parseLength: i32 = parse ? sqlLength + named + toI32(8) : 0
1896
+ // Parse, Bind, Execute ("" portal, no row limit: 4 + 1 + 4), Sync (4).
1897
+ const total: i32 = (parse ? toI32(1) + parseLength : toI32(0)) + toI32(16) + bind
1898
+ const out: u8[] = new Array<u8>(total)
1899
+ let at: i32 = 0
1900
+ if (parse) {
1901
+ out[at] = 80
1902
+ setI32BE(out, at + 1, parseLength)
1903
+ at += 5
1904
+ for (let i: i32 = 0; i < toI32(label.length); i++) {
1905
+ out[at + i] = label[i]
1906
+ }
1907
+ at += named
1908
+ out[at] = 0
1909
+ at += 1
1910
+ for (let i: i32 = 0; i < sqlLength && at + i < total; i++) {
1911
+ out[at + i] = sql[i]
1912
+ }
1913
+ at += sqlLength
1914
+ out[at] = 0
1915
+ out[at + 1] = 0
1916
+ out[at + 2] = 0
1917
+ at += 3
1918
+ }
1919
+ out[at] = 66
1920
+ setI32BE(out, at + 1, bind)
1921
+ at += 5
1922
+ // The unnamed portal, the statement's name, no parameter format codes (all text).
1923
+ out[at] = 0
1924
+ at += 1
1925
+ for (let i: i32 = 0; i < toI32(label.length); i++) {
1926
+ out[at + i] = label[i]
1927
+ }
1928
+ at += named
1929
+ out[at] = 0
1930
+ out[at + 1] = 0
1931
+ out[at + 2] = 0
1932
+ setU16BE(out, at + 3, toU16(count))
1933
+ at += 5
1934
+ // Bounded by `values` rather than `count`, which it equals, so the prover reads the index.
1935
+ const encoded: i32 = toI32(values.length)
1936
+ for (let i: i32 = 0; i < encoded; i++) {
1937
+ if (params.nulls[i]) {
1938
+ setI32BE(out, at, -1)
1939
+ at += 4
1940
+ continue
1941
+ }
1942
+ const v: u8[] = values[i]
1943
+ setI32BE(out, at, toI32(v.length))
1944
+ copyBytes(out, at + 4, v, 0, toI32(v.length))
1945
+ at += 4 + toI32(v.length)
1946
+ }
1947
+ // No result format codes: every column in text.
1948
+ out[at] = 0
1949
+ out[at + 1] = 0
1950
+ at += 2
1951
+ out[at] = 69
1952
+ setI32BE(out, at + 1, 9)
1953
+ out[at + 5] = 0
1954
+ setI32BE(out, at + 6, 0)
1955
+ at += 10
1956
+ out[at] = 83
1957
+ setI32BE(out, at + 1, 4)
1958
+ return out
1959
+ }
1960
+
1961
+ /**
1962
+ * A prepared statement's name, `n` and the decimal digits of `name` (at most
1963
+ * 2), or none for a negative `name`.
1964
+ */
1965
+ const pgAsyncLabel = (name: i32): u8[] => {
1966
+ if (name >= 10) {
1967
+ return [110, toU8(toI32(48) + toI32(name / 10)), toU8(toI32(48) + (name % 10))]
1968
+ }
1969
+ if (name >= 0) {
1970
+ return [110, toU8(toI32(48) + name)]
1971
+ }
1972
+ return []
1973
+ }
1974
+
1975
+ /** `s`'s UTF-8 bytes, or null when one is zero, which a C string in the protocol cannot hold. */
1976
+ const pgAsyncBytes = (s: string): u8[] | null => {
1977
+ const n: i32 = toI32(s.length)
1978
+ const b: u8[] = new Array<u8>(n)
1979
+ const room: i32 = toI32(b.length)
1980
+ // Bounded by each length it indexes, which are equal, so the prover reads both.
1981
+ for (let i: i32 = 0; i < n && i < room; i++) {
1982
+ const c: i32 = toI32(s.charCodeAt(i))
1983
+ if (c === 0) {
1984
+ return null
1985
+ }
1986
+ b[i] = toU8(c)
1987
+ }
1988
+ return b
1989
+ }
1990
+
1991
+ /**
1992
+ * Reads the answer to one Parse, Bind, Execute and Sync from `fd`, through
1993
+ * its ReadyForQuery, under the caps, starting from `seed`, the part of it
1994
+ * already read. With `bounded` (a pipelined connection), no read passes the
1995
+ * answer's ReadyForQuery, so the next answer stays on the socket; without
1996
+ * it, input past the answer leaves the connection unfit to reuse. The result
1997
+ * is made here rather than handed in: the spawn rules read a callee that
1998
+ * grows an array it was handed across an `await` as one that may grow the
1999
+ * caller's pool.
2000
+ */
2001
+ const pgAsyncRead = async (
2002
+ fd: i32,
2003
+ seed: u8[],
2004
+ bounded: boolean,
2005
+ maxMessage: i32,
2006
+ maxColumns: i32,
2007
+ maxRows: i32,
2008
+ maxResultBytes: i32
2009
+ ): Promise<PgAsyncResult> => {
2010
+ const result = new PgAsyncResult()
2011
+ // The buffer starts the size of the seed, not a zero-filled 8 KiB: an answer
2012
+ // already scanned whole is parsed without clearing memory it never reads, and
2013
+ // only a read past it grows the buffer.
2014
+ let buf: u8[] = new Array<u8>(toI32(seed.length))
2015
+ copyBytes(buf, 0, seed, 0, toI32(seed.length))
2016
+ let start: i32 = 0
2017
+ let end: i32 = toI32(seed.length)
2018
+ let refused: boolean = false
2019
+ let tooBig: boolean = false
2020
+ let changed: boolean = false
2021
+ let shaped: boolean = false
2022
+ // The bytes of rows, tags and error fields kept, under `maxResultBytes`.
2023
+ let kept: i32 = 0
2024
+ while (true) {
2025
+ // Every whole message in [start, end).
2026
+ while (end - start >= 5) {
2027
+ // Always true, since `end` never passes the buffer; it proves the reads below.
2028
+ if (start < 0 || start + 5 > toI32(buf.length)) {
2029
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2030
+ }
2031
+ const type: i32 = toI32(buf[start])
2032
+ const length: i32 = getI32BE(buf, start + 1)
2033
+ if (length < 4) {
2034
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2035
+ }
2036
+ if (length > maxMessage) {
2037
+ return pgAsyncLost(result, PG_ERR_TOO_BIG, 0)
2038
+ }
2039
+ if (end - start - 1 < length) {
2040
+ break
2041
+ }
2042
+ const body: i32 = start + 5
2043
+ const stop: i32 = start + 1 + length
2044
+ start = stop
2045
+ if (type === 90) {
2046
+ // 'Z': ReadyForQuery, the end of the answer.
2047
+ if (stop - body !== 1 || body < 0 || body >= toI32(buf.length)) {
2048
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2049
+ }
2050
+ // Bytes after the ReadyForQuery answer no statement this one sent,
2051
+ // so the connection is out of step and closed rather than given
2052
+ // back. A pipelined read stops at the ReadyForQuery, so none are
2053
+ // read here unless the server sent them inside this answer.
2054
+ result.reusable = toI32(buf[body]) === PG_ASYNC_IDLE && !changed && start === end
2055
+ if (refused || tooBig) {
2056
+ result.code = PG_CARRIER_FAILED
2057
+ result.failure = tooBig ? PG_ERR_TOO_BIG : PG_ERR_NONE
2058
+ }
2059
+ return result
2060
+ }
2061
+ if (type === 68) {
2062
+ // 'D': DataRow, a count then each column's length (-1 for NULL) and bytes.
2063
+ if (stop - body < 2) {
2064
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2065
+ }
2066
+ const columns: i32 = toI32(getU16BE(buf, body))
2067
+ if (columns > maxColumns) {
2068
+ return pgAsyncLost(result, PG_ERR_TOO_BIG, 0)
2069
+ }
2070
+ if (shaped && columns !== result.columns) {
2071
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2072
+ }
2073
+ // The frame's length bounds its cells' bytes; each cell costs its string besides.
2074
+ const cost: i32 = stop - body + columns * PG_ASYNC_CELL_COST
2075
+ if (tooBig || result.rows >= maxRows || cost > maxResultBytes - kept) {
2076
+ tooBig = true
2077
+ continue
2078
+ }
2079
+ kept += cost
2080
+ if (!pgAsyncRow(buf, body + 2, stop, columns, result)) {
2081
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2082
+ }
2083
+ result.columns = columns
2084
+ shaped = true
2085
+ result.rows += 1
2086
+ continue
2087
+ }
2088
+ if (type === 67) {
2089
+ // 'C': CommandComplete, a NUL-ended tag.
2090
+ if (stop - body < 1 || toI32(buf[stop - 1]) !== 0) {
2091
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2092
+ }
2093
+ // A tag is kept, so it costs the budget too; past it, the answer fails.
2094
+ if (stop - body > maxResultBytes - kept) {
2095
+ tooBig = true
2096
+ continue
2097
+ }
2098
+ kept += stop - body
2099
+ result.tag = String.fromBytes(buf, body, stop - 1)
2100
+ continue
2101
+ }
2102
+ if (type === 69) {
2103
+ // 'E': ErrorResponse, fields of a code byte and a NUL-ended value.
2104
+ // Its kept fields cost the budget, bounded by the frame; past it, none is kept.
2105
+ refused = true
2106
+ if (stop - body > maxResultBytes - kept) {
2107
+ tooBig = true
2108
+ continue
2109
+ }
2110
+ kept += stop - body
2111
+ if (!pgAsyncError(buf, body, stop, result)) {
2112
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2113
+ }
2114
+ continue
2115
+ }
2116
+ if (type === 83) {
2117
+ // 'S': a ParameterStatus after startup is a session setting a statement changed.
2118
+ changed = true
2119
+ continue
2120
+ }
2121
+ if (type === 49 || type === 50 || type === 73 || type === 78 || type === 65) {
2122
+ // ParseComplete, BindComplete, EmptyQueryResponse, a notice, a notification.
2123
+ continue
2124
+ }
2125
+ return pgAsyncLost(result, PG_ERR_UNEXPECTED, 0)
2126
+ }
2127
+ // Room for the rest of the message at `start`, then more input.
2128
+ if (start > 0) {
2129
+ copyBytes(buf, 0, buf, start, end - start)
2130
+ end -= start
2131
+ start = 0
2132
+ }
2133
+ if (end === toI32(buf.length)) {
2134
+ const twice: i32 = toI32(buf.length) < PG_ASYNC_INPUT_SIZE ? PG_ASYNC_INPUT_SIZE : toI32(buf.length) * 2
2135
+ const grown: u8[] = new Array<u8>(
2136
+ twice > maxMessage + 1 && end < maxMessage + 1 ? maxMessage + 1 : twice
2137
+ )
2138
+ copyBytes(grown, 0, buf, 0, end)
2139
+ buf = grown
2140
+ }
2141
+ const room: i32 = toI32(buf.length) - end
2142
+ let want: i32 = room
2143
+ if (bounded) {
2144
+ // The rest of the frame at `start`, and the next header unless it is the ReadyForQuery.
2145
+ want = toI32(5) - (end - start)
2146
+ if (end - start >= 5 && start >= 0 && start < toI32(buf.length)) {
2147
+ const length: i32 = getI32BE(buf, start + 1)
2148
+ want = toI32(1) + length - (end - start) + (toI32(buf[start]) === 90 ? toI32(0) : toI32(5))
2149
+ }
2150
+ if (want > room) {
2151
+ want = room
2152
+ } else if (want < 1) {
2153
+ want = 1
2154
+ }
2155
+ }
2156
+ const got: i32 = netRead(fd, buf, end, want)
2157
+ if (got === PG_ASYNC_AGAIN) {
2158
+ const waited: boolean = await readable(fd)
2159
+ const failed: i32 = pgAsyncWaitFailure(waited)
2160
+ if (failed !== 0) {
2161
+ return pgAsyncLost(result, PG_ERR_CLOSED, failed)
2162
+ }
2163
+ } else if (got <= 0) {
2164
+ return pgAsyncLost(result, PG_ERR_CLOSED, got)
2165
+ } else {
2166
+ end += got
2167
+ }
2168
+ }
2169
+ }
2170
+
2171
+ /** One DataRow's `columns` cells in `[at, stop)` into `result`; false for a frame that does not add up. */
2172
+ const pgAsyncRow = (buf: u8[], at: i32, stop: i32, columns: i32, result: PgAsyncResult): boolean => {
2173
+ let p: i32 = at
2174
+ for (let c: i32 = 0; c < columns; c++) {
2175
+ if (stop - p < 4 || p < 0 || p + 3 >= toI32(buf.length)) {
2176
+ return false
2177
+ }
2178
+ const n: i32 =
2179
+ (toI32(buf[p]) << 24) | (toI32(buf[p + 1]) << 16) | (toI32(buf[p + 2]) << 8) | toI32(buf[p + 3])
2180
+ p += 4
2181
+ if (n === -1) {
2182
+ result.values.push("")
2183
+ result.nulls.push(true)
2184
+ continue
2185
+ }
2186
+ if (n < 0 || n > stop - p) {
2187
+ return false
2188
+ }
2189
+ result.values.push(String.fromBytes(buf, p, p + n))
2190
+ result.nulls.push(false)
2191
+ p += n
2192
+ }
2193
+ return p === stop
2194
+ }
2195
+
2196
+ /**
2197
+ * An ErrorResponse's SQLSTATE and message in `[at, stop)` into `result`; false
2198
+ * for a frame that does not add up.
2199
+ */
2200
+ const pgAsyncError = (buf: u8[], at: i32, stop: i32, result: PgAsyncResult): boolean => {
2201
+ let p: i32 = at
2202
+ // `stop` never passes the buffer; each loop also tests `buf.length` so the prover reads the index.
2203
+ while (p >= 0 && p < stop && p < toI32(buf.length)) {
2204
+ const field: i32 = toI32(buf[p])
2205
+ if (field === 0) {
2206
+ return p === stop - 1
2207
+ }
2208
+ let e: i32 = p + 1
2209
+ while (e < stop && e < toI32(buf.length) && toI32(buf[e]) !== 0) {
2210
+ e += 1
2211
+ }
2212
+ if (e >= stop || e >= toI32(buf.length)) {
2213
+ return false
2214
+ }
2215
+ if (field === 67) {
2216
+ result.errorCode = String.fromBytes(buf, p + 1, e)
2217
+ } else if (field === 77) {
2218
+ result.errorMessage = String.fromBytes(buf, p + 1, e)
2219
+ }
2220
+ p = e + 1
2221
+ }
2222
+ return false
2223
+ }