@amritk/nish-aarch64-linux 0.38.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 (58) hide show
  1. package/bin/nish +0 -0
  2. package/docs/AI.md +348 -37
  3. package/package.json +1 -1
  4. package/runtime/core/host.d.ts +11 -0
  5. package/runtime/core/host.mjs +35 -0
  6. package/runtime/nish.d.ts +301 -18
  7. package/runtime/nish.h +74 -10
  8. package/runtime/nish.mjs +69 -6
  9. package/runtime/node.mjs +117 -0
  10. package/runtime/runtime-aes.c +12 -4
  11. package/runtime/runtime-async.c +43 -10
  12. package/runtime/runtime-checksum.c +207 -15
  13. package/runtime/runtime-net.c +32 -3
  14. package/runtime/runtime-os.c +174 -27
  15. package/runtime/runtime-region.c +94 -10
  16. package/runtime/runtime-sandbox.c +377 -17
  17. package/runtime/runtime-sha256.c +11 -4
  18. package/runtime/runtime-wasm.c +15 -0
  19. package/runtime/runtime.c +5 -0
  20. package/scripts/build.sh +27 -8
  21. package/std/README.md +5 -4
  22. package/std/compress/checksum.ts +13 -0
  23. package/std/compress/deflate.ts +0 -2
  24. package/std/crypto/p256.ts +247 -74
  25. package/std/crypto/p384.ts +3 -1
  26. package/std/crypto/pki.ts +35 -9
  27. package/std/crypto/x25519.ts +153 -64
  28. package/std/crypto/x509.ts +113 -10
  29. package/std/json-tokenizer.ts +20 -0
  30. package/std/json-typed.ts +217 -8
  31. package/std/net/handler.ts +130 -16
  32. package/std/net/http1-codec.ts +499 -150
  33. package/std/net/http1-server.ts +495 -22
  34. package/std/net/http2-cleartext.ts +526 -0
  35. package/std/net/http2-tls.ts +48 -0
  36. package/std/net/http2.ts +84 -0
  37. package/std/net/postgres-async.ts +1304 -86
  38. package/std/net/postgres-carrier.ts +343 -10
  39. package/std/net/postgres.ts +122 -7
  40. package/std/net/prefork.ts +195 -11
  41. package/std/net/quic-datagram.ts +30 -0
  42. package/std/net/quic-listener.ts +38 -12
  43. package/std/net/quic-packet.ts +19 -6
  44. package/std/net/quic-recovery.ts +134 -19
  45. package/std/net/quic-stream.ts +174 -36
  46. package/std/net/quic.ts +418 -18
  47. package/std/net/router.ts +39 -17
  48. package/std/net/serve.ts +162 -58
  49. package/std/net/tls/codec.ts +110 -32
  50. package/std/net/tls/record-server.ts +37 -7
  51. package/std/net/tls-tcp.ts +56 -1
  52. package/std/net/tls.ts +196 -50
  53. package/std/net/websocket.ts +55 -18
  54. package/std/net/webtransport.ts +179 -1
  55. package/std/regex.ts +69 -47
  56. package/std/region.ts +62 -11
  57. package/std/secret.ts +26 -59
  58. package/std/text.ts +233 -0
@@ -37,7 +37,7 @@
37
37
  * return live === pool.size ? 0 : 1
38
38
  * }
39
39
  *
40
- * **Why three calls.** A spawned task shares the pool with the function that
40
+ * **Why separate calls.** A spawned task shares the pool with the function that
41
41
  * spawned it, and runs in memory of its own that is freed when it ends
42
42
  * (docs/LANGUAGE.md → "What `spawn` may pass"). So a call that writes into
43
43
  * the pool may allocate nothing, and one that allocates may not write into
@@ -57,6 +57,33 @@
57
57
  * to the ReadyForQuery; `pgAsyncRelease` gives the connection back, or closes
58
58
  * it when the query left it unfit to reuse.
59
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
+ *
60
87
  * **Its own encoder and framer.** A query is encoded and its answer framed
61
88
  * here (`pgAsyncEncode`, `pgAsyncRead`), not by `PgConnection` or
62
89
  * `PgCarrier`: those keep their buffers and rows in objects that outlive a
@@ -65,10 +92,11 @@
65
92
  * handed. The framer applies the same checks as `PgConnection`'s (PG-28 in
66
93
  * `docs/security/postgres.md`).
67
94
  *
68
- * **Claiming.** When every live connection is claimed, `pgAsyncClaim` sleeps
69
- * and looks again, 1 ms then doubling to 16 ms, until one is free or it has
70
- * slept `claimWaitMs` in all; a released connection is not announced, so a
71
- * waiter finds it on its next look. A ticket names a slot and that slot's
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
72
100
  * claim: `pgAsyncQuery` and `pgAsyncRelease` panic on one that is not the
73
101
  * slot's current claim, so two tasks never share a connection and a
74
102
  * connection is given back once.
@@ -83,21 +111,27 @@
83
111
  * **Limits.** `PgAsyncPool`'s caps (`maxMessage`, `maxColumns`, `maxRows`,
84
112
  * `maxResultBytes`, `claimWaitMs`) bound what one query keeps; rows past
85
113
  * `maxRows` or `maxResultBytes` are read and dropped, and the query fails
86
- * with `PG_ERR_TOO_BIG`. A wait has no deadline of its own: a server that
87
- * accepts and never answers holds the task until it closes, the task is
88
- * cancelled, or (in `pgAsyncConnect`) the caller gives up; bound a slow
89
- * statement with the server's `statement_timeout` too.
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.
90
119
  *
91
120
  * **Cancellation.** A task that is cancelled (`nish:async`'s `cancel`, a
92
121
  * `cancelAfter` deadline, or `nish/net/serve` when the client hangs up, the
93
122
  * request's deadline passes or the server drains) stops waiting at once.
94
- * `pgAsyncClaim` answers `PG_ASYNC_CANCELLED` and claims nothing; a query
123
+ * `pgAsyncClaim` and `pgAsyncSeat` answer `PG_ASYNC_CANCELLED` and take
124
+ * nothing; a query
95
125
  * not yet sent fails with nothing written and its connection reusable; a
96
126
  * query cut off mid-answer fails with `PG_ERR_CLOSED`, `socketError`
97
127
  * `PG_ASYNC_CANCELLED` and `reusable` false, so the task's
98
128
  * `pgAsyncRelease` closes the connection, whose unread answer would put the
99
- * next task out of step. No CancelRequest is sent: the server runs the
100
- * statement on until it sees the socket closed.
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).
101
135
  *
102
136
  * **Memory.** Run each query in a spawned task, as `title` does above: the
103
137
  * task's region, and every buffer, row and string the query built in it,
@@ -117,14 +151,26 @@
117
151
  * out of range) panic.
118
152
  *
119
153
  * `tests/link/std_postgres_async` runs one against a loopback backend;
154
+ * `tests/link/std_postgres_async_pipeline` pipelines statements from many tasks;
120
155
  * `tests/link/std_postgres_async_flat` reads `Arena.used()` across thousands
121
156
  * of queries. Caps and findings: `docs/security/postgres.md`.
122
157
  *
123
158
  * Written for this module; not ported from another implementation.
124
159
  */
125
160
 
126
- import { cancelled, readable, sleep, writable } from "nish:async"
127
- import { connectResult, netAddress, netClose, netRead, netWrite, tcpConnect, unixConnect } from "nish:net"
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"
128
174
  import { Secret } from "nish:secret"
129
175
  import { copyBytes, getI32BE, getU16BE, setI32BE, setU16BE } from "nish/bytes"
130
176
  import {
@@ -162,11 +208,40 @@ const PG_ASYNC_AGAIN: i32 = -11
162
208
  const PG_ASYNC_BAD_FD: i32 = -9
163
209
  // A ticket is `claim * PG_ASYNC_MAX_SIZE + slot`; the claim count wraps below this.
164
210
  const PG_ASYNC_CLAIM_WRAP: i32 = 16777216
165
- // The first and the longest sleep while every connection is claimed.
166
- const PG_ASYNC_FIRST_SLEEP_MS: i32 = 1
167
- const PG_ASYNC_LONGEST_SLEEP_MS: i32 = 16
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
168
241
  // What a query reads first; it grows by doubling up to one `maxMessage`.
169
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
170
245
  // ReadyForQuery's transaction status for "idle", outside any transaction.
171
246
  const PG_ASYNC_IDLE: i32 = 73
172
247
  const PG_ASYNC_NONCE_BYTES: i32 = 18
@@ -194,11 +269,20 @@ export class PgAsyncPool {
194
269
  readonly claims: i32[]
195
270
  /** The number of connection slots, fixed at construction. */
196
271
  readonly size: i32
197
- /** The largest message a query accepts, in bytes, 1024 to 2^30 - 1; a larger one fails it with `PG_ERR_TOO_BIG` and closes the connection. */
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
+ */
198
276
  maxMessage: i32 = 1048576
199
- /** The most columns a row may have, 1 to 65535; more fails the query with `PG_ERR_TOO_BIG` and closes the connection. */
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
+ */
200
281
  maxColumns: i32 = 1664
201
- /** The most rows a query keeps, 1 to 2^24; later rows are read and dropped, and the query fails with `PG_ERR_TOO_BIG`. */
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
+ */
202
286
  maxRows: i32 = 100000
203
287
  /**
204
288
  * The most bytes of rows a query keeps, 1024 to 2^30 - 1: each row costs
@@ -207,15 +291,118 @@ export class PgAsyncPool {
207
291
  * with `PG_ERR_TOO_BIG`.
208
292
  */
209
293
  maxResultBytes: i32 = 16777216
210
- /** The most milliseconds `pgAsyncClaim` sleeps waiting for a free connection before it answers `PG_CARRIER_FULL`. */
294
+ /**
295
+ * The most milliseconds `pgAsyncClaim` or `pgAsyncSeat` waits for a free
296
+ * connection before it answers `PG_CARRIER_FULL`.
297
+ */
211
298
  claimWaitMs: i32 = 5000
212
- /** How many times `pgAsyncClaim` slept because every live connection was claimed. */
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. */
213
305
  waits: i32 = 0
214
- /** How many connections `pgAsyncRelease` closed rather than gave back. */
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
+ */
215
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[]
216
400
 
217
401
  /**
218
- * A pool of `size` slots, none connected yet.
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.
219
406
  * @param size The number of connections, 1 to `PG_ASYNC_MAX_SIZE`; any
220
407
  * other panics.
221
408
  */
@@ -227,8 +414,42 @@ export class PgAsyncPool {
227
414
  this.fds = new Array<i32>(size)
228
415
  this.claimed = new Array<u8>(size)
229
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)
230
446
  for (let s: i32 = 0; s < size; s++) {
231
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
232
453
  }
233
454
  }
234
455
 
@@ -248,8 +469,8 @@ export class PgAsyncPool {
248
469
 
249
470
  /**
250
471
  * Ends every connection: a Terminate is offered to each socket, which is
251
- * then closed, claimed or not. Call it once the tasks that hold tickets
252
- * are done; a ticket used afterwards panics.
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.
253
474
  */
254
475
  close(): void {
255
476
  const terminate: u8[] = [88, 0, 0, 0, 4]
@@ -262,7 +483,38 @@ export class PgAsyncPool {
262
483
  }
263
484
  this.claimed[s] = 0
264
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)
265
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
266
518
  }
267
519
  }
268
520
 
@@ -317,7 +569,10 @@ export class PgAsyncResult {
317
569
  code: i32
318
570
  /** When it failed: a `PG_ERR_*`, `PG_ERR_NONE` when the server refused the statement. */
319
571
  failure: i32 = 0
320
- /** When the socket failed: its negative errno, 0 when the server closed cleanly, `PG_ASYNC_CANCELLED` when the task was cancelled. */
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
+ */
321
576
  socketError: i32 = 0
322
577
  /** Whether the connection may serve another query: hand it to `pgAsyncRelease`. */
323
578
  reusable: boolean = false
@@ -494,11 +749,13 @@ export const pgAsyncConnect = async (
494
749
  conn.dispose()
495
750
  continue
496
751
  }
497
- const made: boolean = await pgAsyncStartup(conn, fd)
752
+ const made: boolean = await pgAsyncStartup(conn, fd, monotonicNanos(), pool.connectWaitMs)
498
753
  conn.dispose()
499
754
  if (made) {
500
755
  pool.fds[s] = fd
501
756
  pool.claimed[s] = 0
757
+ pool.connects += 1
758
+ pgAsyncForget(pool, s)
502
759
  } else {
503
760
  netClose(fd)
504
761
  }
@@ -506,10 +763,14 @@ export const pgAsyncConnect = async (
506
763
  return pool.live()
507
764
  }
508
765
 
509
- /** Runs `conn`'s startup on `fd` until it is ready (true) or has failed (false). */
510
- const pgAsyncStartup = async (conn: PgConnection, fd: i32): Promise<boolean> => {
511
- const connected: boolean = await writable(fd)
512
- if (pgAsyncWaitFailure(connected) !== 0 || connectResult(fd) !== 0) {
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) {
513
774
  return false
514
775
  }
515
776
  while (true) {
@@ -521,8 +782,8 @@ const pgAsyncStartup = async (conn: PgConnection, fd: i32): Promise<boolean> =>
521
782
  conn.outputEnd() - conn.outputStart()
522
783
  )
523
784
  if (n === PG_ASYNC_AGAIN) {
524
- const waited: boolean = await writable(fd)
525
- if (pgAsyncWaitFailure(waited) !== 0) {
785
+ const waited: boolean = await pgAsyncWaitUntil(fd, true, began, waitMs)
786
+ if (!waited) {
526
787
  return false
527
788
  }
528
789
  } else if (n <= 0) {
@@ -545,8 +806,8 @@ const pgAsyncStartup = async (conn: PgConnection, fd: i32): Promise<boolean> =>
545
806
  const room: i32 = conn.inputRoom()
546
807
  const got: i32 = room > 0 ? netRead(fd, conn.inputBuffer(), conn.inputEnd(), room) : 0
547
808
  if (got === PG_ASYNC_AGAIN) {
548
- const waited: boolean = await readable(fd)
549
- if (pgAsyncWaitFailure(waited) !== 0) {
809
+ const waited: boolean = await pgAsyncWaitUntil(fd, false, began, waitMs)
810
+ if (!waited) {
550
811
  return false
551
812
  }
552
813
  } else if (got <= 0) {
@@ -560,9 +821,145 @@ const pgAsyncStartup = async (conn: PgConnection, fd: i32): Promise<boolean> =>
560
821
  }
561
822
 
562
823
  /**
563
- * Claims a free connection for the calling task, sleeping while every live
564
- * one is claimed: 1 ms, then twice as long each time up to 16 ms, for at most
565
- * `pool.claimWaitMs` in all. A cancelled task claims nothing, so a
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
566
963
  * connection is never taken by a task that would close it at its first wait.
567
964
  * It writes only numbers into the pool, so a spawned task may call it.
568
965
  * @param pool The pool.
@@ -573,8 +970,8 @@ const pgAsyncStartup = async (conn: PgConnection, fd: i32): Promise<boolean> =>
573
970
  * while it waits.
574
971
  */
575
972
  export const pgAsyncClaim = async (pool: PgAsyncPool): Promise<i32> => {
576
- let slept: i32 = 0
577
- let nap: i32 = PG_ASYNC_FIRST_SLEEP_MS
973
+ const began: i64 = monotonicNanos()
974
+ let waited: boolean = false
578
975
  while (true) {
579
976
  if (cancelled()) {
580
977
  return PG_ASYNC_CANCELLED
@@ -585,30 +982,40 @@ export const pgAsyncClaim = async (pool: PgAsyncPool): Promise<i32> => {
585
982
  continue
586
983
  }
587
984
  live = true
588
- if (toI32(pool.claimed[s]) === 0) {
985
+ if (toI32(pool.claimed[s]) === 0 && pool.seated[s] === 0 && pool.doomAt[s] < 0) {
589
986
  pool.claimed[s] = 1
590
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
+ }
591
992
  return pool.claims[s] * PG_ASYNC_MAX_SIZE + s
592
993
  }
593
994
  }
594
995
  if (!live) {
595
996
  return PG_POOL_NONE
596
997
  }
597
- if (slept >= pool.claimWaitMs) {
998
+ const left: i32 = pool.claimWaitMs - pgAsyncSince(began)
999
+ if (left <= 0) {
598
1000
  return PG_CARRIER_FULL
599
1001
  }
1002
+ const skipped: boolean = await pgAsyncSkipAny(pool)
1003
+ if (skipped) {
1004
+ continue
1005
+ }
600
1006
  pool.waits += 1
601
- await sleep(nap)
602
- slept += nap
603
- nap = nap * 2 > PG_ASYNC_LONGEST_SLEEP_MS ? PG_ASYNC_LONGEST_SLEEP_MS : nap * 2
1007
+ waited = true
1008
+ await pgAsyncPark(pool, pool.size, left)
1009
+ pgAsyncDrain(pool, pool.size)
604
1010
  }
605
1011
  }
606
1012
 
607
1013
  /**
608
- * Gives a claimed connection back, or closes it when `reusable` is false; the
609
- * ticket is spent either way, and a ticket that is not the slot's current
610
- * claim (a second release, or one after `close()`) panics. It writes only
611
- * numbers into the pool, so a spawned task may call it.
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.
612
1019
  * @param pool The pool the ticket came from.
613
1020
  * @param ticket The ticket `pgAsyncClaim` answered.
614
1021
  * @param reusable The query's `reusable`; false closes the connection.
@@ -619,9 +1026,744 @@ export const pgAsyncRelease = (pool: PgAsyncPool, ticket: i32, reusable: boolean
619
1026
  netClose(pool.fds[slot])
620
1027
  pool.fds[slot] = -1
621
1028
  pool.dropped += 1
1029
+ pgAsyncForget(pool, slot)
622
1030
  }
623
1031
  pool.claimed[slot] = 0
624
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)
625
1767
  }
626
1768
 
627
1769
  /**
@@ -655,7 +1797,8 @@ export const pgAsyncQuery = async (
655
1797
  result.reusable = true
656
1798
  return result
657
1799
  }
658
- const out: u8[] | null = pgAsyncEncode(sql, params)
1800
+ const sqlBytes = pgAsyncBytes(sql)
1801
+ const out: u8[] | null = sqlBytes === null ? null : pgAsyncEncode(sqlBytes, -1, true, params)
659
1802
  if (out === null) {
660
1803
  result.code = PG_CARRIER_FAILED
661
1804
  result.failure = PG_ERR_ENCODING
@@ -677,7 +1820,16 @@ export const pgAsyncQuery = async (
677
1820
  sent += n
678
1821
  }
679
1822
  }
680
- return await pgAsyncRead(fd, pool.maxMessage, pool.maxColumns, pool.maxRows, pool.maxResultBytes)
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
+ )
681
1833
  }
682
1834
 
683
1835
  /**
@@ -709,17 +1861,24 @@ const pgAsyncLost = (result: PgAsyncResult, failure: i32, socketError: i32): PgA
709
1861
  return result
710
1862
  }
711
1863
 
712
- /** Parse, Bind, Execute and Sync for `sql` and `params`, or null for a NUL in the SQL or a parameter. */
713
- const pgAsyncEncode = (sql: string, params: PgAsyncParams): u8[] | null => {
714
- const sqlBytes = pgAsyncBytes(sql)
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 => {
715
1870
  const count: i32 = toI32(params.values.length)
716
- if (sqlBytes === null || count > 65535) {
1871
+ if (count > 65535) {
717
1872
  return null
718
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)
719
1877
  const values: u8[][] = []
720
- // The length, "" portal, "" statement, no parameter formats, the count, no
721
- // result formats: 4 + 1 + 1 + 2 + 2 + 2, held as an i32 in either number mode.
722
- let bind: i32 = toI32(12)
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
723
1882
  for (let i: i32 = 0; i < count; i++) {
724
1883
  const v = pgAsyncBytes(params.values[i])
725
1884
  if (v === null) {
@@ -731,33 +1890,47 @@ const pgAsyncEncode = (sql: string, params: PgAsyncParams): u8[] | null => {
731
1890
  bind += toI32(v.length)
732
1891
  }
733
1892
  }
734
- // The length, "" statement, the SQL and its NUL, no parameter types.
735
- const parse: i32 = toI32(sqlBytes.length) + toI32(8)
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
736
1896
  // Parse, Bind, Execute ("" portal, no row limit: 4 + 1 + 4), Sync (4).
737
- const total: i32 = 1 + parse + 1 + bind + 1 + 9 + 1 + 4
1897
+ const total: i32 = (parse ? toI32(1) + parseLength : toI32(0)) + toI32(16) + bind
738
1898
  const out: u8[] = new Array<u8>(total)
739
1899
  let at: i32 = 0
740
- out[at] = 80
741
- setI32BE(out, at + 1, parse)
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)
742
1921
  at += 5
1922
+ // The unnamed portal, the statement's name, no parameter format codes (all text).
743
1923
  out[at] = 0
744
1924
  at += 1
745
- copyBytes(out, at, sqlBytes, 0, toI32(sqlBytes.length))
746
- at += toI32(sqlBytes.length)
1925
+ for (let i: i32 = 0; i < toI32(label.length); i++) {
1926
+ out[at + i] = label[i]
1927
+ }
1928
+ at += named
747
1929
  out[at] = 0
748
1930
  out[at + 1] = 0
749
1931
  out[at + 2] = 0
750
- at += 3
751
- out[at] = 66
752
- setI32BE(out, at + 1, bind)
1932
+ setU16BE(out, at + 3, toU16(count))
753
1933
  at += 5
754
- // The unnamed portal and statement, no parameter format codes (all text).
755
- out[at] = 0
756
- out[at + 1] = 0
757
- out[at + 2] = 0
758
- out[at + 3] = 0
759
- setU16BE(out, at + 4, toU16(count))
760
- at += 6
761
1934
  // Bounded by `values` rather than `count`, which it equals, so the prover reads the index.
762
1935
  const encoded: i32 = toI32(values.length)
763
1936
  for (let i: i32 = 0; i < encoded; i++) {
@@ -785,6 +1958,20 @@ const pgAsyncEncode = (sql: string, params: PgAsyncParams): u8[] | null => {
785
1958
  return out
786
1959
  }
787
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
+
788
1975
  /** `s`'s UTF-8 bytes, or null when one is zero, which a C string in the protocol cannot hold. */
789
1976
  const pgAsyncBytes = (s: string): u8[] | null => {
790
1977
  const n: i32 = toI32(s.length)
@@ -803,21 +1990,31 @@ const pgAsyncBytes = (s: string): u8[] | null => {
803
1990
 
804
1991
  /**
805
1992
  * Reads the answer to one Parse, Bind, Execute and Sync from `fd`, through
806
- * its ReadyForQuery, under the caps. The result is made here rather than
807
- * handed in: the spawn rules read a callee that grows an array it was handed
808
- * across an `await` as one that may grow the caller's pool.
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.
809
2000
  */
810
2001
  const pgAsyncRead = async (
811
2002
  fd: i32,
2003
+ seed: u8[],
2004
+ bounded: boolean,
812
2005
  maxMessage: i32,
813
2006
  maxColumns: i32,
814
2007
  maxRows: i32,
815
2008
  maxResultBytes: i32
816
2009
  ): Promise<PgAsyncResult> => {
817
2010
  const result = new PgAsyncResult()
818
- let buf: u8[] = new Array<u8>(PG_ASYNC_INPUT_SIZE)
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))
819
2016
  let start: i32 = 0
820
- let end: i32 = 0
2017
+ let end: i32 = toI32(seed.length)
821
2018
  let refused: boolean = false
822
2019
  let tooBig: boolean = false
823
2020
  let changed: boolean = false
@@ -850,8 +2047,10 @@ const pgAsyncRead = async (
850
2047
  if (stop - body !== 1 || body < 0 || body >= toI32(buf.length)) {
851
2048
  return pgAsyncLost(result, PG_ERR_FRAME, 0)
852
2049
  }
853
- // Bytes after it answer no statement this query sent, so the
854
- // connection is out of step and closed rather than given back.
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.
855
2054
  result.reusable = toI32(buf[body]) === PG_ASYNC_IDLE && !changed && start === end
856
2055
  if (refused || tooBig) {
857
2056
  result.code = PG_CARRIER_FAILED
@@ -932,13 +2131,29 @@ const pgAsyncRead = async (
932
2131
  start = 0
933
2132
  }
934
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
935
2135
  const grown: u8[] = new Array<u8>(
936
- toI32(buf.length) * 2 > maxMessage + 1 ? maxMessage + 1 : toI32(buf.length) * 2
2136
+ twice > maxMessage + 1 && end < maxMessage + 1 ? maxMessage + 1 : twice
937
2137
  )
938
2138
  copyBytes(grown, 0, buf, 0, end)
939
2139
  buf = grown
940
2140
  }
941
- const got: i32 = netRead(fd, buf, end, toI32(buf.length) - end)
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)
942
2157
  if (got === PG_ASYNC_AGAIN) {
943
2158
  const waited: boolean = await readable(fd)
944
2159
  const failed: i32 = pgAsyncWaitFailure(waited)
@@ -978,7 +2193,10 @@ const pgAsyncRow = (buf: u8[], at: i32, stop: i32, columns: i32, result: PgAsync
978
2193
  return p === stop
979
2194
  }
980
2195
 
981
- /** An ErrorResponse's SQLSTATE and message in `[at, stop)` into `result`; false for a frame that does not add up. */
2196
+ /**
2197
+ * An ErrorResponse's SQLSTATE and message in `[at, stop)` into `result`; false
2198
+ * for a frame that does not add up.
2199
+ */
982
2200
  const pgAsyncError = (buf: u8[], at: i32, stop: i32, result: PgAsyncResult): boolean => {
983
2201
  let p: i32 = at
984
2202
  // `stop` never passes the buffer; each loop also tests `buf.length` so the prover reads the index.