@amritk/nish-x86_64-linux 0.37.0 → 0.38.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.
@@ -0,0 +1,1005 @@
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 three 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
+ * **Its own encoder and framer.** A query is encoded and its answer framed
61
+ * here (`pgAsyncEncode`, `pgAsyncRead`), not by `PgConnection` or
62
+ * `PgCarrier`: those keep their buffers and rows in objects that outlive a
63
+ * query, which a task would have to grow inside the pool, and a
64
+ * `PgConnection` holds the password as a `Secret`, which a task may not be
65
+ * handed. The framer applies the same checks as `PgConnection`'s (PG-28 in
66
+ * `docs/security/postgres.md`).
67
+ *
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
72
+ * claim: `pgAsyncQuery` and `pgAsyncRelease` panic on one that is not the
73
+ * slot's current claim, so two tasks never share a connection and a
74
+ * connection is given back once.
75
+ *
76
+ * **Reuse.** A connection is given back only when its last query read to a
77
+ * ReadyForQuery that says "idle" and changed no session setting: a query that
78
+ * left a transaction open, a `SET` the server reported (a ParameterStatus),
79
+ * a socket error, a frame this module does not expect, a reply past a cap,
80
+ * or bytes after the ReadyForQuery closes it, so the next task never inherits
81
+ * another's session or the rest of its answer.
82
+ *
83
+ * **Limits.** `PgAsyncPool`'s caps (`maxMessage`, `maxColumns`, `maxRows`,
84
+ * `maxResultBytes`, `claimWaitMs`) bound what one query keeps; rows past
85
+ * `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.
90
+ *
91
+ * **Cancellation.** A task that is cancelled (`nish:async`'s `cancel`, a
92
+ * `cancelAfter` deadline, or `nish/net/serve` when the client hangs up, the
93
+ * request's deadline passes or the server drains) stops waiting at once.
94
+ * `pgAsyncClaim` answers `PG_ASYNC_CANCELLED` and claims nothing; a query
95
+ * not yet sent fails with nothing written and its connection reusable; a
96
+ * query cut off mid-answer fails with `PG_ERR_CLOSED`, `socketError`
97
+ * `PG_ASYNC_CANCELLED` and `reusable` false, so the task's
98
+ * `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.
101
+ *
102
+ * **Memory.** Run each query in a spawned task, as `title` does above: the
103
+ * task's region, and every buffer, row and string the query built in it,
104
+ * is freed when the task ends, so `Arena.used()` stays where it was across
105
+ * thousands of queries. A query awaited outside a task, through a function
106
+ * that is handed the pool, keeps what it built until an enclosing scope
107
+ * ends (about 9 KB a query, measured while writing
108
+ * `tests/link/std_postgres_async_flat`).
109
+ *
110
+ * **Errors.** A query answers `PG_CARRIER_DONE`, or `PG_CARRIER_FAILED` with
111
+ * `failure` a `PG_ERR_*` and `socketError` a negative errno, as
112
+ * `nish/net/postgres-carrier` does: `PG_ERR_NONE` when the server refused the
113
+ * statement (`errorCode` and `errorMessage` say why, and the connection is
114
+ * reused), `PG_ERR_CLOSED` when the socket ended, a wait could not be made or
115
+ * the task was cancelled (`socketError` `PG_ASYNC_CANCELLED`).
116
+ * Programming errors (a ticket that is not a current claim, a size or a cap
117
+ * out of range) panic.
118
+ *
119
+ * `tests/link/std_postgres_async` runs one against a loopback backend;
120
+ * `tests/link/std_postgres_async_flat` reads `Arena.used()` across thousands
121
+ * of queries. Caps and findings: `docs/security/postgres.md`.
122
+ *
123
+ * Written for this module; not ported from another implementation.
124
+ */
125
+
126
+ import { cancelled, readable, sleep, writable } from "nish:async"
127
+ import { connectResult, netAddress, netClose, netRead, netWrite, tcpConnect, unixConnect } from "nish:net"
128
+ import { Secret } from "nish:secret"
129
+ import { copyBytes, getI32BE, getU16BE, setI32BE, setU16BE } from "nish/bytes"
130
+ import {
131
+ PG_ERR_CLOSED,
132
+ PG_ERR_ENCODING,
133
+ PG_ERR_FRAME,
134
+ PG_ERR_NONE,
135
+ PG_ERR_TOO_BIG,
136
+ PG_ERR_UNEXPECTED,
137
+ PG_FAILED,
138
+ PG_NEED_MORE,
139
+ PG_READY,
140
+ PG_TARGET_OK,
141
+ PG_POOL_NONE,
142
+ PgConfig,
143
+ PgConnection,
144
+ PgTarget,
145
+ } from "nish/net/postgres"
146
+ import { PG_CARRIER_DONE, PG_CARRIER_FAILED, PG_CARRIER_FULL } from "nish/net/postgres-carrier"
147
+
148
+ /** The most connections one `PgAsyncPool` holds. */
149
+ export const PG_ASYNC_MAX_SIZE: i32 = 64
150
+
151
+ /**
152
+ * The calling task was cancelled (`nish:async`'s `cancel`, or a deadline set
153
+ * with `cancelAfter`): `pgAsyncClaim` answers it in place of a ticket, and a
154
+ * query cut off by it fails with `PG_ERR_CLOSED` and this as its
155
+ * `socketError`, which no socket read or write answers.
156
+ */
157
+ export const PG_ASYNC_CANCELLED: i32 = -3
158
+
159
+ // `netRead` and `netWrite`: nothing to read, or no room to write, now.
160
+ const PG_ASYNC_AGAIN: i32 = -11
161
+ // `readable` or `writable` could not wait on the descriptor: EBADF.
162
+ const PG_ASYNC_BAD_FD: i32 = -9
163
+ // A ticket is `claim * PG_ASYNC_MAX_SIZE + slot`; the claim count wraps below this.
164
+ 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
168
+ // What a query reads first; it grows by doubling up to one `maxMessage`.
169
+ const PG_ASYNC_INPUT_SIZE: i32 = 8192
170
+ // ReadyForQuery's transaction status for "idle", outside any transaction.
171
+ const PG_ASYNC_IDLE: i32 = 73
172
+ const PG_ASYNC_NONCE_BYTES: i32 = 18
173
+ // The largest `maxMessage` and `maxResultBytes`, as `nish/net/postgres` caps `PgConfig.maxMessage`.
174
+ const PG_ASYNC_MAX_CAP: i32 = 1073741823
175
+ // The most rows `maxRows` may allow.
176
+ const PG_ASYNC_MAX_ROWS: i32 = 16777216
177
+ // What a kept cell costs `maxResultBytes` beyond its bytes: its string and its NULL flag.
178
+ const PG_ASYNC_CELL_COST: i32 = 16
179
+
180
+ /**
181
+ * Authenticated PostgreSQL connections that spawned tasks share. Build one
182
+ * and connect it with `pgAsyncConnect` outside any task; tasks then claim,
183
+ * query and release through the `pgAsync*` functions, and the owner calls
184
+ * `close()` once they are done. It holds no secret: only sockets and numbers.
185
+ * The arrays are the functions' bookkeeping, readable for a test or a status
186
+ * page; a program writes none of them.
187
+ */
188
+ export class PgAsyncPool {
189
+ /** Each slot's socket, or -1 while it is not connected. */
190
+ readonly fds: i32[]
191
+ /** Each slot's state: 0 free, 1 claimed by a ticket. */
192
+ readonly claimed: u8[]
193
+ /** Each slot's claim count, the high part of its current ticket. */
194
+ readonly claims: i32[]
195
+ /** The number of connection slots, fixed at construction. */
196
+ 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. */
198
+ 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. */
200
+ 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`. */
202
+ maxRows: i32 = 100000
203
+ /**
204
+ * The most bytes of rows a query keeps, 1024 to 2^30 - 1: each row costs
205
+ * its DataRow's length and 16 bytes a cell. A row past it is dropped with
206
+ * every later one, read through to the ReadyForQuery, and the query fails
207
+ * with `PG_ERR_TOO_BIG`.
208
+ */
209
+ maxResultBytes: i32 = 16777216
210
+ /** The most milliseconds `pgAsyncClaim` sleeps waiting for a free connection before it answers `PG_CARRIER_FULL`. */
211
+ claimWaitMs: i32 = 5000
212
+ /** How many times `pgAsyncClaim` slept because every live connection was claimed. */
213
+ waits: i32 = 0
214
+ /** How many connections `pgAsyncRelease` closed rather than gave back. */
215
+ dropped: i32 = 0
216
+
217
+ /**
218
+ * A pool of `size` slots, none connected yet.
219
+ * @param size The number of connections, 1 to `PG_ASYNC_MAX_SIZE`; any
220
+ * other panics.
221
+ */
222
+ constructor(size: i32) {
223
+ if (size < 1 || size > PG_ASYNC_MAX_SIZE) {
224
+ panic("nish/net/postgres-async: a PgAsyncPool size out of range")
225
+ }
226
+ this.size = size
227
+ this.fds = new Array<i32>(size)
228
+ this.claimed = new Array<u8>(size)
229
+ this.claims = new Array<i32>(size)
230
+ for (let s: i32 = 0; s < size; s++) {
231
+ this.fds[s] = -1
232
+ }
233
+ }
234
+
235
+ /**
236
+ * The number of slots connected now, claimed or not.
237
+ * @returns The count, 0 to `size`.
238
+ */
239
+ live(): i32 {
240
+ let n: i32 = 0
241
+ for (let s: i32 = 0; s < this.size; s++) {
242
+ if (this.fds[s] >= 0) {
243
+ n += 1
244
+ }
245
+ }
246
+ return n
247
+ }
248
+
249
+ /**
250
+ * 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.
253
+ */
254
+ close(): void {
255
+ const terminate: u8[] = [88, 0, 0, 0, 4]
256
+ for (let s: i32 = 0; s < this.size; s++) {
257
+ const fd: i32 = this.fds[s]
258
+ if (fd >= 0) {
259
+ netWrite(fd, terminate, 0, 5)
260
+ netClose(fd)
261
+ this.fds[s] = -1
262
+ }
263
+ this.claimed[s] = 0
264
+ this.claims[s] = (this.claims[s] + 1) % PG_ASYNC_CLAIM_WRAP
265
+ }
266
+ }
267
+ }
268
+
269
+ /**
270
+ * A query's parameters, in text, in the order `$1`, `$2`, ... name them. A
271
+ * task builds its own; the values travel apart from the SQL, so none is ever
272
+ * read as SQL.
273
+ */
274
+ export class PgAsyncParams {
275
+ /** Each parameter's text, `""` for a NULL. */
276
+ readonly values: string[]
277
+ /** Whether each parameter is NULL. */
278
+ readonly nulls: boolean[]
279
+
280
+ /** No parameters yet. */
281
+ constructor() {
282
+ this.values = []
283
+ this.nulls = []
284
+ }
285
+
286
+ /**
287
+ * Adds a text parameter.
288
+ * @param value The text, sent as its UTF-8 bytes.
289
+ */
290
+ text(value: string): void {
291
+ this.values.push(value)
292
+ this.nulls.push(false)
293
+ }
294
+
295
+ /**
296
+ * Adds an integer parameter, sent as its decimal text.
297
+ * @param value The number.
298
+ */
299
+ int(value: i32): void {
300
+ this.values.push(`${value}`)
301
+ this.nulls.push(false)
302
+ }
303
+
304
+ /** Adds a NULL parameter. */
305
+ none(): void {
306
+ this.values.push("")
307
+ this.nulls.push(true)
308
+ }
309
+ }
310
+
311
+ /**
312
+ * One query's answer, in the task's own memory: its rows as text, its tag,
313
+ * and how it ended.
314
+ */
315
+ export class PgAsyncResult {
316
+ /** `PG_CARRIER_DONE` when the query worked, `PG_CARRIER_FAILED` when it did not. */
317
+ code: i32
318
+ /** When it failed: a `PG_ERR_*`, `PG_ERR_NONE` when the server refused the statement. */
319
+ 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. */
321
+ socketError: i32 = 0
322
+ /** Whether the connection may serve another query: hand it to `pgAsyncRelease`. */
323
+ reusable: boolean = false
324
+ /** The number of columns in each row (the first row's; every row must match). */
325
+ columns: i32 = 0
326
+ /** The number of rows kept. */
327
+ rows: i32 = 0
328
+ /** The command tag, e.g. `SELECT 2` or `UPDATE 1`; `""` for an empty query. */
329
+ tag: string = ""
330
+ /** The server's SQLSTATE when it refused the statement, e.g. `42P01`. */
331
+ errorCode: string = ""
332
+ /** The server's message when it refused the statement. */
333
+ errorMessage: string = ""
334
+ /** Every kept cell's text, row by row; `""` for a NULL. */
335
+ readonly values: string[]
336
+ /** Whether each kept cell is NULL, as `values`. */
337
+ readonly nulls: boolean[]
338
+
339
+ /** An answer with no rows that worked, until the query fills it in. */
340
+ constructor() {
341
+ this.code = PG_CARRIER_DONE
342
+ this.values = []
343
+ this.nulls = []
344
+ }
345
+
346
+ /**
347
+ * Whether the query worked.
348
+ * @returns True for `PG_CARRIER_DONE`.
349
+ */
350
+ ok(): boolean {
351
+ return this.code === PG_CARRIER_DONE
352
+ }
353
+
354
+ /**
355
+ * A cell's text, `""` for a NULL; panics on a row or column out of range.
356
+ * @param row The row, from 0.
357
+ * @param column The column, from 0.
358
+ * @returns The text the server sent.
359
+ */
360
+ text(row: i32, column: i32): string {
361
+ return this.values[this.cell(row, column)]
362
+ }
363
+
364
+ /**
365
+ * Whether a cell is NULL; panics on a row or column out of range.
366
+ * @param row The row, from 0.
367
+ * @param column The column, from 0.
368
+ * @returns True for a NULL.
369
+ */
370
+ isNull(row: i32, column: i32): boolean {
371
+ return this.nulls[this.cell(row, column)]
372
+ }
373
+
374
+ /**
375
+ * A cell read as a decimal `i32`, or `fallback` when it is NULL or not one.
376
+ * @param row The row, from 0.
377
+ * @param column The column, from 0.
378
+ * @param fallback The answer for a NULL or a cell that is not a decimal `i32`.
379
+ * @returns The number.
380
+ */
381
+ int(row: i32, column: i32, fallback: i32): i32 {
382
+ const at: i32 = this.cell(row, column)
383
+ if (this.nulls[at]) {
384
+ return fallback
385
+ }
386
+ return pgAsyncDecimal(this.values[at], fallback)
387
+ }
388
+
389
+ /** The index into `values` of a cell, after the bounds check. */
390
+ private cell(row: i32, column: i32): i32 {
391
+ if (row < 0 || row >= this.rows || column < 0 || column >= this.columns) {
392
+ panic("nish/net/postgres-async: a cell out of range")
393
+ }
394
+ return row * this.columns + column
395
+ }
396
+ }
397
+
398
+ /** `s` as a decimal `i32`, or `fallback` when it is not one. */
399
+ const pgAsyncDecimal = (s: string, fallback: i32): i32 => {
400
+ const n: i32 = toI32(s.length)
401
+ if (n === 0 || n > 11) {
402
+ return fallback
403
+ }
404
+ let at: i32 = 0
405
+ const negative: boolean = s.charCodeAt(0) === 45
406
+ if (negative) {
407
+ at = 1
408
+ if (n === 1) {
409
+ return fallback
410
+ }
411
+ }
412
+ let v: i64 = 0
413
+ while (at < n) {
414
+ const c: i32 = toI32(s.charCodeAt(at))
415
+ if (c < 48 || c > 57) {
416
+ return fallback
417
+ }
418
+ v = v * toI64(10) + toI64(c - 48)
419
+ at += 1
420
+ }
421
+ if (negative) {
422
+ v = -v
423
+ }
424
+ if (v < toI64(-2147483648) || v > toI64(2147483647)) {
425
+ return fallback
426
+ }
427
+ return toI32(v)
428
+ }
429
+
430
+ /**
431
+ * The one place a wait's outcome becomes a failure code: 0 when `readable`
432
+ * or `writable` waited, else what a query or a connect fails with
433
+ * (`PG_ERR_CLOSED` beside it): `PG_ASYNC_CANCELLED` when the task was
434
+ * cancelled, which fails every wait it makes, else EBADF.
435
+ */
436
+ const pgAsyncWaitFailure = (waited: boolean): i32 => {
437
+ if (waited) {
438
+ return 0
439
+ }
440
+ return cancelled() ? PG_ASYNC_CANCELLED : PG_ASYNC_BAD_FD
441
+ }
442
+
443
+ /** `ticket`'s slot, after checking it is the slot's current claim; panics otherwise. */
444
+ const pgAsyncSlot = (pool: PgAsyncPool, ticket: i32): i32 => {
445
+ const slot: i32 = ticket >= 0 ? ticket % PG_ASYNC_MAX_SIZE : -1
446
+ if (
447
+ slot < 0 ||
448
+ slot >= pool.size ||
449
+ toI32(pool.claimed[slot]) !== 1 ||
450
+ toI32(ticket / PG_ASYNC_MAX_SIZE) !== pool.claims[slot]
451
+ ) {
452
+ panic("nish/net/postgres-async: a ticket that is not a current claim")
453
+ }
454
+ return slot
455
+ }
456
+
457
+ /**
458
+ * Connects every slot of `pool` that is not connected, one after another,
459
+ * and authenticates each on a `PgConnection` (startup, then SCRAM-SHA-256 or
460
+ * `trust`), which wipes its copy of the password once the proof is made and
461
+ * is then dropped. Call it from `main` or another function that is not a
462
+ * spawned task: it holds the password. A slot that fails stays unconnected;
463
+ * call it again to retry.
464
+ * @param pool The pool to fill.
465
+ * @param config The startup parameters and caps for the handshake.
466
+ * @param password The role's password as UTF-8 bytes; copied for each
467
+ * connection, so the caller wipes its own afterwards.
468
+ * @param target Where the server is, as `pgTarget` made it; a TCP host must
469
+ * be a numeric address, and a target that failed panics.
470
+ * @returns The number of slots connected after the call.
471
+ */
472
+ export const pgAsyncConnect = async (
473
+ pool: PgAsyncPool,
474
+ config: PgConfig,
475
+ password: Secret<u8[]>,
476
+ target: PgTarget
477
+ ): Promise<i32> => {
478
+ if (target.failure !== PG_TARGET_OK) {
479
+ panic("nish/net/postgres-async: pgAsyncConnect to a target that failed")
480
+ }
481
+ const address: u8[] = new Array<u8>(18)
482
+ if (!target.unix && netAddress(address, target.host, target.port) < 0) {
483
+ panic("nish/net/postgres-async: a TCP host must be a numeric address")
484
+ }
485
+ const nonce: u8[] = new Array<u8>(PG_ASYNC_NONCE_BYTES)
486
+ for (let s: i32 = 0; s < pool.size; s++) {
487
+ if (pool.fds[s] >= 0) {
488
+ continue
489
+ }
490
+ crypto.getRandomValues(nonce)
491
+ const conn = new PgConnection(config, password, nonce)
492
+ const fd: i32 = target.unix ? unixConnect(target.path) : tcpConnect(address)
493
+ if (fd < 0) {
494
+ conn.dispose()
495
+ continue
496
+ }
497
+ const made: boolean = await pgAsyncStartup(conn, fd)
498
+ conn.dispose()
499
+ if (made) {
500
+ pool.fds[s] = fd
501
+ pool.claimed[s] = 0
502
+ } else {
503
+ netClose(fd)
504
+ }
505
+ }
506
+ return pool.live()
507
+ }
508
+
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) {
513
+ return false
514
+ }
515
+ while (true) {
516
+ while (conn.outputEnd() > conn.outputStart()) {
517
+ const n: i32 = netWrite(
518
+ fd,
519
+ conn.outputBuffer(),
520
+ conn.outputStart(),
521
+ conn.outputEnd() - conn.outputStart()
522
+ )
523
+ if (n === PG_ASYNC_AGAIN) {
524
+ const waited: boolean = await writable(fd)
525
+ if (pgAsyncWaitFailure(waited) !== 0) {
526
+ return false
527
+ }
528
+ } else if (n <= 0) {
529
+ conn.closed()
530
+ return false
531
+ } else {
532
+ conn.sent(n)
533
+ }
534
+ }
535
+ const event: i32 = conn.next()
536
+ if (event === PG_READY) {
537
+ return conn.txStatus === PG_ASYNC_IDLE
538
+ }
539
+ if (event === PG_FAILED) {
540
+ return false
541
+ }
542
+ // A step that queued an answer (the SCRAM messages) writes it before it
543
+ // reads: the server says nothing more until it has that answer.
544
+ if (event === PG_NEED_MORE && conn.outputEnd() === conn.outputStart()) {
545
+ const room: i32 = conn.inputRoom()
546
+ const got: i32 = room > 0 ? netRead(fd, conn.inputBuffer(), conn.inputEnd(), room) : 0
547
+ if (got === PG_ASYNC_AGAIN) {
548
+ const waited: boolean = await readable(fd)
549
+ if (pgAsyncWaitFailure(waited) !== 0) {
550
+ return false
551
+ }
552
+ } else if (got <= 0) {
553
+ conn.closed()
554
+ return false
555
+ } else {
556
+ conn.received(got)
557
+ }
558
+ }
559
+ }
560
+ }
561
+
562
+ /**
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
566
+ * connection is never taken by a task that would close it at its first wait.
567
+ * It writes only numbers into the pool, so a spawned task may call it.
568
+ * @param pool The pool.
569
+ * @returns A ticket (0 or more) for `pgAsyncQuery` and then exactly one
570
+ * `pgAsyncRelease`; `PG_POOL_NONE` (-1) when no slot is connected;
571
+ * `PG_CARRIER_FULL` (-2) when none came free in time;
572
+ * `PG_ASYNC_CANCELLED` (-3) when the calling task is cancelled, before or
573
+ * while it waits.
574
+ */
575
+ export const pgAsyncClaim = async (pool: PgAsyncPool): Promise<i32> => {
576
+ let slept: i32 = 0
577
+ let nap: i32 = PG_ASYNC_FIRST_SLEEP_MS
578
+ while (true) {
579
+ if (cancelled()) {
580
+ return PG_ASYNC_CANCELLED
581
+ }
582
+ let live: boolean = false
583
+ for (let s: i32 = 0; s < pool.size; s++) {
584
+ if (pool.fds[s] < 0) {
585
+ continue
586
+ }
587
+ live = true
588
+ if (toI32(pool.claimed[s]) === 0) {
589
+ pool.claimed[s] = 1
590
+ pool.claims[s] = (pool.claims[s] + 1) % PG_ASYNC_CLAIM_WRAP
591
+ return pool.claims[s] * PG_ASYNC_MAX_SIZE + s
592
+ }
593
+ }
594
+ if (!live) {
595
+ return PG_POOL_NONE
596
+ }
597
+ if (slept >= pool.claimWaitMs) {
598
+ return PG_CARRIER_FULL
599
+ }
600
+ 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
604
+ }
605
+ }
606
+
607
+ /**
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.
612
+ * @param pool The pool the ticket came from.
613
+ * @param ticket The ticket `pgAsyncClaim` answered.
614
+ * @param reusable The query's `reusable`; false closes the connection.
615
+ */
616
+ export const pgAsyncRelease = (pool: PgAsyncPool, ticket: i32, reusable: boolean): void => {
617
+ const slot: i32 = pgAsyncSlot(pool, ticket)
618
+ if (!reusable) {
619
+ netClose(pool.fds[slot])
620
+ pool.fds[slot] = -1
621
+ pool.dropped += 1
622
+ }
623
+ pool.claimed[slot] = 0
624
+ pool.claims[slot] = (pool.claims[slot] + 1) % PG_ASYNC_CLAIM_WRAP
625
+ }
626
+
627
+ /**
628
+ * Runs one statement on the ticket's connection: Parse, Bind (each parameter
629
+ * in text), Execute and Sync go out in one write, and the answer is read to
630
+ * its ReadyForQuery, waiting on the socket while other tasks run. It only
631
+ * reads the pool; its buffers and the answer are the calling task's.
632
+ * @param pool The pool the ticket came from; a cap out of its range panics.
633
+ * @param ticket A ticket `pgAsyncClaim` answered and no `pgAsyncRelease` has
634
+ * spent; any other panics.
635
+ * @param sql One statement, `$1`, `$2`, ... naming the parameters; a NUL in
636
+ * it fails the query with `PG_ERR_ENCODING` without sending anything.
637
+ * @param params The parameters, as many as the statement names; a NUL in
638
+ * a text one fails the query the same way.
639
+ * @returns The answer; its `reusable` goes to `pgAsyncRelease`.
640
+ */
641
+ export const pgAsyncQuery = async (
642
+ pool: PgAsyncPool,
643
+ ticket: i32,
644
+ sql: string,
645
+ params: PgAsyncParams
646
+ ): Promise<PgAsyncResult> => {
647
+ pgAsyncCheckCaps(pool)
648
+ const fd: i32 = pool.fds[pgAsyncSlot(pool, ticket)]
649
+ const result = new PgAsyncResult()
650
+ if (cancelled()) {
651
+ // Nothing is sent, so the connection is still in step and is given back.
652
+ result.code = PG_CARRIER_FAILED
653
+ result.failure = PG_ERR_CLOSED
654
+ result.socketError = PG_ASYNC_CANCELLED
655
+ result.reusable = true
656
+ return result
657
+ }
658
+ const out: u8[] | null = pgAsyncEncode(sql, params)
659
+ if (out === null) {
660
+ result.code = PG_CARRIER_FAILED
661
+ result.failure = PG_ERR_ENCODING
662
+ result.reusable = true
663
+ return result
664
+ }
665
+ let sent: i32 = 0
666
+ while (sent < toI32(out.length)) {
667
+ const n: i32 = netWrite(fd, out, sent, toI32(out.length) - sent)
668
+ if (n === PG_ASYNC_AGAIN) {
669
+ const waited: boolean = await writable(fd)
670
+ const failed: i32 = pgAsyncWaitFailure(waited)
671
+ if (failed !== 0) {
672
+ return pgAsyncLost(result, PG_ERR_CLOSED, failed)
673
+ }
674
+ } else if (n <= 0) {
675
+ return pgAsyncLost(result, PG_ERR_CLOSED, n)
676
+ } else {
677
+ sent += n
678
+ }
679
+ }
680
+ return await pgAsyncRead(fd, pool.maxMessage, pool.maxColumns, pool.maxRows, pool.maxResultBytes)
681
+ }
682
+
683
+ /**
684
+ * Panics on a cap that is a mistake in the program, as `PgConfig`'s are. The
685
+ * bounds keep `row * columns` in `PgAsyncResult` from overflowing: the cells
686
+ * kept are under `maxResultBytes / 16`, below 2^26.
687
+ */
688
+ const pgAsyncCheckCaps = (pool: PgAsyncPool): void => {
689
+ if (
690
+ pool.maxMessage < 1024 ||
691
+ pool.maxMessage > PG_ASYNC_MAX_CAP ||
692
+ pool.maxColumns < 1 ||
693
+ pool.maxColumns > 65535 ||
694
+ pool.maxRows < 1 ||
695
+ pool.maxRows > PG_ASYNC_MAX_ROWS ||
696
+ pool.maxResultBytes < 1024 ||
697
+ pool.maxResultBytes > PG_ASYNC_MAX_CAP
698
+ ) {
699
+ panic("nish/net/postgres-async: a PgAsyncPool cap out of range")
700
+ }
701
+ }
702
+
703
+ /** `result` failed for `failure`, its socket error `socketError`, and its connection unfit to reuse. */
704
+ const pgAsyncLost = (result: PgAsyncResult, failure: i32, socketError: i32): PgAsyncResult => {
705
+ result.code = PG_CARRIER_FAILED
706
+ result.failure = failure
707
+ result.socketError = socketError
708
+ result.reusable = false
709
+ return result
710
+ }
711
+
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)
715
+ const count: i32 = toI32(params.values.length)
716
+ if (sqlBytes === null || count > 65535) {
717
+ return null
718
+ }
719
+ 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)
723
+ for (let i: i32 = 0; i < count; i++) {
724
+ const v = pgAsyncBytes(params.values[i])
725
+ if (v === null) {
726
+ return null
727
+ }
728
+ values.push(v)
729
+ bind += toI32(4)
730
+ if (!params.nulls[i]) {
731
+ bind += toI32(v.length)
732
+ }
733
+ }
734
+ // The length, "" statement, the SQL and its NUL, no parameter types.
735
+ const parse: i32 = toI32(sqlBytes.length) + toI32(8)
736
+ // Parse, Bind, Execute ("" portal, no row limit: 4 + 1 + 4), Sync (4).
737
+ const total: i32 = 1 + parse + 1 + bind + 1 + 9 + 1 + 4
738
+ const out: u8[] = new Array<u8>(total)
739
+ let at: i32 = 0
740
+ out[at] = 80
741
+ setI32BE(out, at + 1, parse)
742
+ at += 5
743
+ out[at] = 0
744
+ at += 1
745
+ copyBytes(out, at, sqlBytes, 0, toI32(sqlBytes.length))
746
+ at += toI32(sqlBytes.length)
747
+ out[at] = 0
748
+ out[at + 1] = 0
749
+ out[at + 2] = 0
750
+ at += 3
751
+ out[at] = 66
752
+ setI32BE(out, at + 1, bind)
753
+ 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
+ // Bounded by `values` rather than `count`, which it equals, so the prover reads the index.
762
+ const encoded: i32 = toI32(values.length)
763
+ for (let i: i32 = 0; i < encoded; i++) {
764
+ if (params.nulls[i]) {
765
+ setI32BE(out, at, -1)
766
+ at += 4
767
+ continue
768
+ }
769
+ const v: u8[] = values[i]
770
+ setI32BE(out, at, toI32(v.length))
771
+ copyBytes(out, at + 4, v, 0, toI32(v.length))
772
+ at += 4 + toI32(v.length)
773
+ }
774
+ // No result format codes: every column in text.
775
+ out[at] = 0
776
+ out[at + 1] = 0
777
+ at += 2
778
+ out[at] = 69
779
+ setI32BE(out, at + 1, 9)
780
+ out[at + 5] = 0
781
+ setI32BE(out, at + 6, 0)
782
+ at += 10
783
+ out[at] = 83
784
+ setI32BE(out, at + 1, 4)
785
+ return out
786
+ }
787
+
788
+ /** `s`'s UTF-8 bytes, or null when one is zero, which a C string in the protocol cannot hold. */
789
+ const pgAsyncBytes = (s: string): u8[] | null => {
790
+ const n: i32 = toI32(s.length)
791
+ const b: u8[] = new Array<u8>(n)
792
+ const room: i32 = toI32(b.length)
793
+ // Bounded by each length it indexes, which are equal, so the prover reads both.
794
+ for (let i: i32 = 0; i < n && i < room; i++) {
795
+ const c: i32 = toI32(s.charCodeAt(i))
796
+ if (c === 0) {
797
+ return null
798
+ }
799
+ b[i] = toU8(c)
800
+ }
801
+ return b
802
+ }
803
+
804
+ /**
805
+ * 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.
809
+ */
810
+ const pgAsyncRead = async (
811
+ fd: i32,
812
+ maxMessage: i32,
813
+ maxColumns: i32,
814
+ maxRows: i32,
815
+ maxResultBytes: i32
816
+ ): Promise<PgAsyncResult> => {
817
+ const result = new PgAsyncResult()
818
+ let buf: u8[] = new Array<u8>(PG_ASYNC_INPUT_SIZE)
819
+ let start: i32 = 0
820
+ let end: i32 = 0
821
+ let refused: boolean = false
822
+ let tooBig: boolean = false
823
+ let changed: boolean = false
824
+ let shaped: boolean = false
825
+ // The bytes of rows, tags and error fields kept, under `maxResultBytes`.
826
+ let kept: i32 = 0
827
+ while (true) {
828
+ // Every whole message in [start, end).
829
+ while (end - start >= 5) {
830
+ // Always true, since `end` never passes the buffer; it proves the reads below.
831
+ if (start < 0 || start + 5 > toI32(buf.length)) {
832
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
833
+ }
834
+ const type: i32 = toI32(buf[start])
835
+ const length: i32 = getI32BE(buf, start + 1)
836
+ if (length < 4) {
837
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
838
+ }
839
+ if (length > maxMessage) {
840
+ return pgAsyncLost(result, PG_ERR_TOO_BIG, 0)
841
+ }
842
+ if (end - start - 1 < length) {
843
+ break
844
+ }
845
+ const body: i32 = start + 5
846
+ const stop: i32 = start + 1 + length
847
+ start = stop
848
+ if (type === 90) {
849
+ // 'Z': ReadyForQuery, the end of the answer.
850
+ if (stop - body !== 1 || body < 0 || body >= toI32(buf.length)) {
851
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
852
+ }
853
+ // Bytes after it answer no statement this query sent, so the
854
+ // connection is out of step and closed rather than given back.
855
+ result.reusable = toI32(buf[body]) === PG_ASYNC_IDLE && !changed && start === end
856
+ if (refused || tooBig) {
857
+ result.code = PG_CARRIER_FAILED
858
+ result.failure = tooBig ? PG_ERR_TOO_BIG : PG_ERR_NONE
859
+ }
860
+ return result
861
+ }
862
+ if (type === 68) {
863
+ // 'D': DataRow, a count then each column's length (-1 for NULL) and bytes.
864
+ if (stop - body < 2) {
865
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
866
+ }
867
+ const columns: i32 = toI32(getU16BE(buf, body))
868
+ if (columns > maxColumns) {
869
+ return pgAsyncLost(result, PG_ERR_TOO_BIG, 0)
870
+ }
871
+ if (shaped && columns !== result.columns) {
872
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
873
+ }
874
+ // The frame's length bounds its cells' bytes; each cell costs its string besides.
875
+ const cost: i32 = stop - body + columns * PG_ASYNC_CELL_COST
876
+ if (tooBig || result.rows >= maxRows || cost > maxResultBytes - kept) {
877
+ tooBig = true
878
+ continue
879
+ }
880
+ kept += cost
881
+ if (!pgAsyncRow(buf, body + 2, stop, columns, result)) {
882
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
883
+ }
884
+ result.columns = columns
885
+ shaped = true
886
+ result.rows += 1
887
+ continue
888
+ }
889
+ if (type === 67) {
890
+ // 'C': CommandComplete, a NUL-ended tag.
891
+ if (stop - body < 1 || toI32(buf[stop - 1]) !== 0) {
892
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
893
+ }
894
+ // A tag is kept, so it costs the budget too; past it, the answer fails.
895
+ if (stop - body > maxResultBytes - kept) {
896
+ tooBig = true
897
+ continue
898
+ }
899
+ kept += stop - body
900
+ result.tag = String.fromBytes(buf, body, stop - 1)
901
+ continue
902
+ }
903
+ if (type === 69) {
904
+ // 'E': ErrorResponse, fields of a code byte and a NUL-ended value.
905
+ // Its kept fields cost the budget, bounded by the frame; past it, none is kept.
906
+ refused = true
907
+ if (stop - body > maxResultBytes - kept) {
908
+ tooBig = true
909
+ continue
910
+ }
911
+ kept += stop - body
912
+ if (!pgAsyncError(buf, body, stop, result)) {
913
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
914
+ }
915
+ continue
916
+ }
917
+ if (type === 83) {
918
+ // 'S': a ParameterStatus after startup is a session setting a statement changed.
919
+ changed = true
920
+ continue
921
+ }
922
+ if (type === 49 || type === 50 || type === 73 || type === 78 || type === 65) {
923
+ // ParseComplete, BindComplete, EmptyQueryResponse, a notice, a notification.
924
+ continue
925
+ }
926
+ return pgAsyncLost(result, PG_ERR_UNEXPECTED, 0)
927
+ }
928
+ // Room for the rest of the message at `start`, then more input.
929
+ if (start > 0) {
930
+ copyBytes(buf, 0, buf, start, end - start)
931
+ end -= start
932
+ start = 0
933
+ }
934
+ if (end === toI32(buf.length)) {
935
+ const grown: u8[] = new Array<u8>(
936
+ toI32(buf.length) * 2 > maxMessage + 1 ? maxMessage + 1 : toI32(buf.length) * 2
937
+ )
938
+ copyBytes(grown, 0, buf, 0, end)
939
+ buf = grown
940
+ }
941
+ const got: i32 = netRead(fd, buf, end, toI32(buf.length) - end)
942
+ if (got === PG_ASYNC_AGAIN) {
943
+ const waited: boolean = await readable(fd)
944
+ const failed: i32 = pgAsyncWaitFailure(waited)
945
+ if (failed !== 0) {
946
+ return pgAsyncLost(result, PG_ERR_CLOSED, failed)
947
+ }
948
+ } else if (got <= 0) {
949
+ return pgAsyncLost(result, PG_ERR_CLOSED, got)
950
+ } else {
951
+ end += got
952
+ }
953
+ }
954
+ }
955
+
956
+ /** One DataRow's `columns` cells in `[at, stop)` into `result`; false for a frame that does not add up. */
957
+ const pgAsyncRow = (buf: u8[], at: i32, stop: i32, columns: i32, result: PgAsyncResult): boolean => {
958
+ let p: i32 = at
959
+ for (let c: i32 = 0; c < columns; c++) {
960
+ if (stop - p < 4 || p < 0 || p + 3 >= toI32(buf.length)) {
961
+ return false
962
+ }
963
+ const n: i32 =
964
+ (toI32(buf[p]) << 24) | (toI32(buf[p + 1]) << 16) | (toI32(buf[p + 2]) << 8) | toI32(buf[p + 3])
965
+ p += 4
966
+ if (n === -1) {
967
+ result.values.push("")
968
+ result.nulls.push(true)
969
+ continue
970
+ }
971
+ if (n < 0 || n > stop - p) {
972
+ return false
973
+ }
974
+ result.values.push(String.fromBytes(buf, p, p + n))
975
+ result.nulls.push(false)
976
+ p += n
977
+ }
978
+ return p === stop
979
+ }
980
+
981
+ /** An ErrorResponse's SQLSTATE and message in `[at, stop)` into `result`; false for a frame that does not add up. */
982
+ const pgAsyncError = (buf: u8[], at: i32, stop: i32, result: PgAsyncResult): boolean => {
983
+ let p: i32 = at
984
+ // `stop` never passes the buffer; each loop also tests `buf.length` so the prover reads the index.
985
+ while (p >= 0 && p < stop && p < toI32(buf.length)) {
986
+ const field: i32 = toI32(buf[p])
987
+ if (field === 0) {
988
+ return p === stop - 1
989
+ }
990
+ let e: i32 = p + 1
991
+ while (e < stop && e < toI32(buf.length) && toI32(buf[e]) !== 0) {
992
+ e += 1
993
+ }
994
+ if (e >= stop || e >= toI32(buf.length)) {
995
+ return false
996
+ }
997
+ if (field === 67) {
998
+ result.errorCode = String.fromBytes(buf, p + 1, e)
999
+ } else if (field === 77) {
1000
+ result.errorMessage = String.fromBytes(buf, p + 1, e)
1001
+ }
1002
+ p = e + 1
1003
+ }
1004
+ return false
1005
+ }