@mark1russell7/service 0.8.4 → 0.8.5

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 (77) hide show
  1. package/build/{backoff-B-jGWVDm.d.ts → backoff-QTRGfkEK.d.ts} +1 -3
  2. package/build/backoff.d.ts +1 -1
  3. package/build/backoff.js +1 -2
  4. package/build/{builder-DQj3NNNc.d.ts → builder-zO48Vgoj.d.ts} +4 -10
  5. package/build/{call-context-gR8FhbF_.d.ts → call-context-DDhcVvn5.d.ts} +1 -3
  6. package/build/channel.d.ts +0 -2
  7. package/build/channel.js +1 -2
  8. package/build/{core-Dt0HEVMq.d.ts → core-BSzt4RI2.d.ts} +5 -9
  9. package/build/{dial-CSQOl-yj.d.ts → dial-ChwIcvd4.d.ts} +2 -4
  10. package/build/grpc.d.ts +4 -14
  11. package/build/grpc.js +7 -12
  12. package/build/grpc.js.map +1 -1
  13. package/build/heartbeat.d.ts +0 -2
  14. package/build/heartbeat.js +1 -2
  15. package/build/host.d.ts +3 -23
  16. package/build/host.js +21 -33
  17. package/build/host.js.map +1 -1
  18. package/build/http-client.d.ts +4 -16
  19. package/build/http-client.js +7 -13
  20. package/build/http-client.js.map +1 -1
  21. package/build/http.d.ts +3 -9
  22. package/build/http.js +6 -10
  23. package/build/http.js.map +1 -1
  24. package/build/index.d.ts +10 -22
  25. package/build/index.js +26 -43
  26. package/build/index.js.map +1 -1
  27. package/build/{knobs-D2ClI68I.js → knobs-BJcz6m01.js} +3 -5
  28. package/build/{knobs-D2ClI68I.js.map → knobs-BJcz6m01.js.map} +1 -1
  29. package/build/{lifecycle-Br0jAjTk.d.ts → lifecycle-D0J-zwZF.d.ts} +2 -14
  30. package/build/{limiter-BTgM4aXZ.js → limiter-BwGxEWpP.js} +4 -6
  31. package/build/{limiter-BTgM4aXZ.js.map → limiter-BwGxEWpP.js.map} +1 -1
  32. package/build/{limiter-D1aluA0V.d.ts → limiter-Djw39d_S.d.ts} +3 -5
  33. package/build/limiter.d.ts +3 -3
  34. package/build/limiter.js +2 -2
  35. package/build/{logger-BN2BfPgU.d.ts → logger-B6drv9w0.d.ts} +2 -16
  36. package/build/{machine-p4lENJ86.js → machine-mIW1qgEE.js} +7 -11
  37. package/build/{machine-p4lENJ86.js.map → machine-mIW1qgEE.js.map} +1 -1
  38. package/build/mongodb.d.ts +3 -13
  39. package/build/mongodb.js +6 -11
  40. package/build/mongodb.js.map +1 -1
  41. package/build/{operation-DL5RxFds.js → operation-DF73RZOI.js} +2 -3
  42. package/build/{operation-DL5RxFds.js.map → operation-DF73RZOI.js.map} +1 -1
  43. package/build/otel.d.ts +2 -4
  44. package/build/otel.js +1 -2
  45. package/build/pg.d.ts +2 -12
  46. package/build/pg.js +6 -11
  47. package/build/pg.js.map +1 -1
  48. package/build/{policy-G-Y3Meku.js → policy-B23MY52l.js} +2 -3
  49. package/build/{policy-G-Y3Meku.js.map → policy-B23MY52l.js.map} +1 -1
  50. package/build/{policy-CwYR95Sz.d.ts → policy-CBcK2XGg.d.ts} +1 -3
  51. package/build/{ports-CSr7qWrA.d.ts → ports-DZoipkSD.d.ts} +2 -4
  52. package/build/{process-DG_im2zc.js → process-Oe0Abbsm.js} +2 -3
  53. package/build/{process-DG_im2zc.js.map → process-Oe0Abbsm.js.map} +1 -1
  54. package/build/{queue-fIkOXKVG.d.ts → queue-DXdw1vLO.d.ts} +3 -7
  55. package/build/rabbitmq.d.ts +4 -14
  56. package/build/rabbitmq.js +6 -11
  57. package/build/rabbitmq.js.map +1 -1
  58. package/build/redis.d.ts +3 -15
  59. package/build/redis.js +10 -16
  60. package/build/redis.js.map +1 -1
  61. package/build/{requests-BIq9Tr4P.js → requests-DD2ALv0_.js} +6 -9
  62. package/build/{requests-BIq9Tr4P.js.map → requests-DD2ALv0_.js.map} +1 -1
  63. package/build/{retrier-Nt6r4r6R.js → retrier-BObZq10-.js} +3 -4
  64. package/build/{retrier-Nt6r4r6R.js.map → retrier-BObZq10-.js.map} +1 -1
  65. package/build/{rules-BBRopO1e.d.ts → rules-HyFCBStQ.d.ts} +1 -5
  66. package/build/rules.d.ts +1 -1
  67. package/build/rules.js +1 -2
  68. package/build/{store-1CsNoJ8O.d.ts → store-DFwFKrsB.d.ts} +2 -4
  69. package/build/testing.d.ts +4 -14
  70. package/build/testing.js +9 -15
  71. package/build/testing.js.map +1 -1
  72. package/build/{timing-DGRi3XCI.js → timing-DZl36uXs.js} +2 -3
  73. package/build/{timing-DGRi3XCI.js.map → timing-DZl36uXs.js.map} +1 -1
  74. package/build/websocket.d.ts +3 -13
  75. package/build/websocket.js +7 -12
  76. package/build/websocket.js.map +1 -1
  77. package/package.json +4 -3
package/build/pg.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"pg.js","names":["knob","t"],"sources":["../src/pg/connection.ts","../src/pg/meets.ts","../src/pg/client.ts","../src/pg/machine.ts","../src/pg/starting.ts"],"sourcesContent":["import type { ClientSocket, Factory } from \"../client/core.ts\";\n\n/** A pg socket is the socket of a client in the core: the join of the prober and the bounded close read it. */\nexport type PgSocket = ClientSocket;\n\n/** A query result is the part of a result of pg that the wrapper gives back. */\nexport interface PgResult<Row = Record<string, unknown>> {\n readonly rows: Row[];\n readonly rowCount: number | null;\n}\n\n/**\n * A pool client is the part of a `pg.PoolClient` that the wrapper uses. A pg 8 client has each part.\n * A fake for tests has them too. Thus the package depends on no type of pg.\n */\nexport interface PgPoolClient {\n /** This number is the id of the backend from BackendKeyData, which the server sends at the startup. */\n readonly processID?: number | null | undefined;\n /** This connection holds the socket of the client. */\n readonly connection?: { readonly stream?: PgSocket | undefined } | undefined;\n query(text: string, values?: readonly unknown[]): Promise<PgResult<never>>;\n /** This method gives the client back to the pool. With an error, the pool ends the client. */\n release(error?: Error | boolean): void;\n on(event: \"error\", listener: (error: Error) => void): unknown;\n off(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\n/** A pool is the part of a `pg.Pool` that the wrapper uses. */\nexport interface PgPool {\n readonly totalCount: number;\n readonly idleCount: number;\n readonly waitingCount: number;\n connect(): Promise<PgPoolClient>;\n end(): Promise<void>;\n on(event: \"connect\" | \"remove\", listener: (client: PgPoolClient) => void): unknown;\n on(event: \"error\", listener: (error: Error, client: PgPoolClient) => void): unknown;\n off(event: \"connect\" | \"remove\", listener: (client: PgPoolClient) => void): unknown;\n off(event: \"error\", listener: (error: Error, client: PgPoolClient) => void): unknown;\n}\n\n/**\n * These are the options that the wrapper gives `pg.Pool`. Each one comes from the declaration. The\n * wrapper sets each option that has an effect on a timer, thus no default of pg decides one. A knob\n * of pg at 0 has no timer. The wrapper writes \"infinite\" as 0, and it refuses a bound of 0.\n */\nexport interface PgPoolOptions {\n readonly host: string;\n readonly port: number;\n readonly database?: string | undefined;\n readonly user?: string | undefined;\n readonly password?: string | undefined;\n /** The server shows this name in `pg_stat_activity`, thus the prober can join on it too. */\n readonly application_name: string;\n readonly max: number;\n readonly min: number;\n /** This time bounds the TCP connect, the startup and the authentication. It also bounds a checkout from a full pool. */\n readonly connectionTimeoutMillis: number;\n /** This time bounds each query on the client, from `client.query`. The client sends no cancel at its end. */\n readonly query_timeout: number;\n /** This time is the deadline of each statement on the server. The client sends it in the startup message. Undefined does not send it. */\n readonly statement_timeout: number | undefined;\n /** This time ends an idle client of the pool. 0 is no idle timer. */\n readonly idleTimeoutMillis: number;\n /** This time ends a client at this age from its connect, in whole seconds. 0 is no age. */\n readonly maxLifetimeSeconds: number;\n readonly keepAlive: boolean;\n /** This time is the idle time of TCP keepalive. Node truncates it to whole seconds. */\n readonly keepAliveInitialDelayMillis: number;\n /** The idle timer and the idle sockets do not keep the process alive (A14). The lifecycle holds the process. */\n readonly allowExitOnIdle: true;\n}\n\n/** A pool factory makes the pool of the client from its options. */\nexport type PoolFactory = Factory<PgPoolOptions, PgPool>;\n\n/**\n * This factory makes a `pg.Pool`. It loads pg only when a client connects, thus a service that does\n * not use PostgreSQL does not need pg. The specifier is a value, thus the package needs no types of pg.\n */\nexport const nodePostgres: PoolFactory = async (options) => {\n const specifier = \"pg\";\n const loaded = (await import(specifier)) as { readonly default: { readonly Pool: new (options: PgPoolOptions) => PgPool } };\n return new loaded.default.Pool(options);\n};\n","import type { Detector, Meeting } from \"../client/meets.ts\";\nimport { WHAT, immediate, keepaliveAnswered, keepaliveReset, keepaliveSilent, kernelGiveUp } from \"../client/meets.ts\";\nimport type { PgKnobs } from \"./client.ts\";\n\n/**\n * This function gives the manifestations that a pg client can meet, and the detectors of each, from\n * its knobs. The cells of S1 measured each one on node-postgres 8.23.1:\n * - A reset of a query gives ECONNRESET in 0.6 ms, and a FIN to an idle client gives EOF in 18 µs.\n * - A frozen server and a black hole have no detector in 60 s at the defaults: pg has no timer on a query and no keepalive.\n * - `query_timeout` ends a query in a black hole on time (9.503 s for 9.5 s).\n * - `statement_timeout` ends a slow statement on the server with ERROR 57014 (10.002 s for 10 s).\n *\n * pg has no watchdog and does not test an idle client. In place of a watchdog, the pool ends an\n * idle client at its idle timer. A later checkout then opens a new connection, which `connect_bound` bounds.\n */\nexport const pgMeetings = (name: string, knobs: PgKnobs): Meeting[] => {\n const query: Detector = {\n by: \"request_timeout\",\n within: knobs.request_timeout,\n situation: \"in flight\",\n effect: `the query fails as indeterminate, and ${name} gives the client back with an error, thus the pool ends it`,\n };\n const idleExpiry: Detector = {\n by: \"pool_idle_expiry\",\n within: knobs.pool_idle_expiry,\n situation: \"idle\",\n effect: \"the pool ends the idle client, thus no checkout gets the dead connection\",\n };\n const giveUp = kernelGiveUp(knobs.retrans_giveup_time, \"the query fails with its error\");\n const silent = (manifestation: \"blackhole\" | \"freeze-host\"): Meeting => ({\n manifestation,\n what: WHAT[manifestation],\n detectors: [query, giveUp, idleExpiry, keepaliveSilent(knobs.keepalive_idle)],\n });\n return [\n {\n manifestation: \"rst\",\n what: WHAT.rst,\n detectors: [\n immediate(\"in flight\", \"the query fails with ECONNRESET, and each new connect is refused\"),\n idleExpiry,\n keepaliveReset(knobs.keepalive_idle),\n ],\n },\n {\n manifestation: \"fin\",\n what: WHAT.fin,\n detectors: [\n immediate(\"in flight\", \"the query fails: 'Connection terminated unexpectedly'\"),\n immediate(\"idle\", \"the pool removes the idle client, and emits error\"),\n ],\n },\n silent(\"blackhole\"),\n silent(\"freeze-host\"),\n {\n manifestation: \"freeze-process\",\n what: WHAT[\"freeze-process\"],\n detectors: [query, idleExpiry, keepaliveAnswered()],\n },\n {\n manifestation: \"app-stall\",\n what: \"the server stops its replies for a time, for example behind a lock, and its kernel stays up\",\n detectors: [\n {\n by: \"statement_timeout\",\n within: knobs.statement_timeout,\n situation: \"in flight\",\n effect: \"the server ends the statement with ERROR 57014, a certain outcome, and the client stays\",\n },\n query,\n idleExpiry,\n keepaliveAnswered(),\n ],\n },\n ];\n};\n","import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { realClock } from \"../clock.ts\";\nimport type { Attempt, CheckOptions, Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, SendOptions, Sent } from \"../client/core.ts\";\nimport {\n attachClient,\n clientBounds,\n clientProblems,\n clientRecorder,\n deadlineProblem,\n dialCheck,\n finiteMs,\n inFlight,\n localStateCheck,\n message,\n ms,\n notSent,\n operationTable,\n orZero,\n poolProblems,\n roundTripCheck,\n sendWithReissue,\n socketEnds,\n stepChecks,\n timeProblems,\n wholeProblems,\n withinBound,\n zeroProblems,\n} from \"../client/core.ts\";\nimport { helloDial } from \"../client/dial.ts\";\nimport type { Dependency } from \"../description.ts\";\nimport type { DependencyHandle } from \"../lifecycle.ts\";\nimport type { Operation } from \"../operation.ts\";\nimport type { PgPool, PgPoolClient, PgPoolOptions, PgResult, PoolFactory } from \"./connection.ts\";\nimport { nodePostgres } from \"./connection.ts\";\nimport { pgMeetings } from \"./meets.ts\";\n\n/**\n * These are the knobs of the client, each a time, by the names of the ordering law where the law\n * has them. The runtime has no defaults, thus each knob is necessary. A bound that nobody gives is\n * \"infinite\", not zero. `PG_STARTING_KNOBS` gives a declaration from the cells of S1. The knobs\n * that each client has come from the core.\n */\nexport interface PgKnobs extends ClientKnobs {\n /**\n * This time bounds a new connection (`connectionTimeoutMillis`): the TCP connect, the startup and\n * the authentication. The pool uses the same knob to bound a checkout from a full pool.\n * At the defaults pg has no bound, and the kernel gives up on the SYNs only after 131 s (A3, O15).\n */\n readonly connect_bound: Quantity;\n /** This time bounds each query on the client (`query_timeout`). pg sends no cancel at its end. */\n readonly request_timeout: Quantity;\n /**\n * This time is the deadline of each statement on the server (`statement_timeout`). The server then\n * ends the statement with ERROR 57014, a certain outcome. \"infinite\" sends no deadline.\n */\n readonly statement_timeout: Extent;\n /** This time ends an idle client of the pool (`idleTimeoutMillis`). The pool sends no test on an idle client. */\n readonly pool_idle_expiry: Extent;\n /** This time is the idle time of TCP keepalive, in whole seconds. Node then sends 10 probes 1 s apart. */\n readonly keepalive_idle: Extent;\n /** This time is the age at which the pool replaces a client (`maxLifetimeSeconds`), in whole seconds. */\n readonly max_connection_age: Extent;\n /** This time bounds the close of the pool at the shutdown: its end, then a destroy of each socket that stays. */\n readonly close_bound: Quantity;\n}\n\n/** A pg client spec is the declaration of one PostgreSQL client: where it connects, its pool, and its knobs. */\nexport interface PgClientSpec extends ClientSpec<PgKnobs> {\n readonly database?: string | undefined;\n readonly user?: string | undefined;\n /** These counts are the sizes of the pool: at most `max` clients, and an idle timer only above `min`. */\n readonly pool: { readonly max: number; readonly min: number };\n /**\n * These operations are the queries of the service, by name, with their idempotency. SQL text does\n * not tell if a statement changes a state, thus the client sends again only a query that this table names.\n */\n readonly operations?: Readonly<Record<string, Operation>> | undefined;\n}\n\n/** These options make a client. Without them, it uses pg, the real clock, and a dial with an SSLRequest. */\nexport type PgClientOptions = ClientOptions<PoolFactory>;\n\n/**\n * A join is one connection of the pool, at its connect (D1, D2). The prober joins its kernel records\n * to the server's view of the connection through it. The server's view is the process id of the backend.\n */\nexport interface PgJoin extends ClientJoin {\n /** This number is the process id of the backend, or null when the server gave none. Through a pooler, it is the id that the pooler gives. */\n readonly backendPid: number | null;\n}\n\n/** The steps that the pg client gives a check for: the steps of each client, and a checkout from the pool (B14). */\nexport type PgStep = ClientStep | \"checkout\";\n\n/** A pg client is a dependency of a service: its declaration, its handle, its checks and its queries. */\nexport interface PgClient extends Client<PgStep, PgJoin> {\n /** This text is the state of the client, as `PG_CLIENT_MACHINE` names it. */\n readonly status: string;\n /**\n * This method sends a query, and gives its outcome in three values. `operation` names the query\n * in the table of operations. The client sends again only an idempotent operation, one time at\n * most, after an outcome that is not certain. The second try stays in the bound of the request.\n */\n query<Row = Record<string, unknown>>(\n operation: string,\n text: string,\n values?: readonly unknown[],\n options?: SendOptions,\n ): Promise<Sent<PgResult<Row>>>;\n}\n\n/** This function gives the problems of a spec: the knobs that pg cannot use. */\nexport const specProblems = (name: string, spec: PgClientSpec): string[] => {\n const { knobs } = spec;\n return [\n ...timeProblems(name, knobs),\n // pg reads 0 as no timer, thus a bound of 0 is not a bound\n ...zeroProblems(name, \"pg\", knobs, {\n bounded: [\"connect_bound\", \"request_timeout\", \"close_bound\"],\n open: [\"statement_timeout\", \"pool_idle_expiry\", \"keepalive_idle\", \"max_connection_age\"],\n }),\n // Node truncates the keepalive delay to whole seconds, and pg takes the age in whole seconds\n ...wholeProblems(name, knobs, {\n millis: [\"connect_bound\", \"request_timeout\", \"statement_timeout\", \"pool_idle_expiry\"],\n seconds: [\"keepalive_idle\", \"max_connection_age\"],\n }),\n ...poolProblems(name, spec.pool),\n ];\n};\n\n/** This function gives the options of `pg.Pool` from a spec. Each timer of pg comes from the declaration. */\nexport const poolOptions = (name: string, spec: PgClientSpec): PgPoolOptions => {\n const { knobs } = spec;\n return {\n host: spec.host,\n port: spec.port,\n ...(spec.database === undefined ? {} : { database: spec.database }),\n ...(spec.user === undefined ? {} : { user: spec.user }),\n ...(spec.password === undefined ? {} : { password: spec.password }),\n application_name: name,\n max: spec.pool.max,\n min: spec.pool.min,\n connectionTimeoutMillis: ms(knobs.connect_bound),\n query_timeout: ms(knobs.request_timeout),\n statement_timeout: finiteMs(knobs.statement_timeout),\n idleTimeoutMillis: orZero(knobs.pool_idle_expiry),\n maxLifetimeSeconds: orZero(knobs.max_connection_age) / 1000,\n keepAlive: knobs.keepalive_idle.value !== \"infinite\",\n keepAliveInitialDelayMillis: orZero(knobs.keepalive_idle),\n allowExitOnIdle: true,\n };\n};\n\n/** The bytes of an SSLRequest: a length of 8, then the code 80877103. A server answers with one byte, S or N. */\nconst SSL_REQUEST = Uint8Array.of(0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f);\n\n/**\n * This dial function opens a TCP connection, sends an SSLRequest, and waits for its one byte. The\n * server answers it before the authentication, thus the dial needs no password and opens no backend.\n */\nexport const sslRequestDial: DialFn = helloDial(SSL_REQUEST, (received) => {\n const answer = String.fromCharCode(received[0] ?? 0);\n return answer === \"S\" || answer === \"N\" ? null : new Error(`the answer to the SSLRequest was ${JSON.stringify(answer)}`);\n});\n\n/** A database error is an ErrorResponse of the server: pg gives its severity and its SQLSTATE code. */\nconst replyOf = (error: unknown): { readonly severity: string; readonly code: string } | null => {\n if (typeof error !== \"object\" || error === null) return null;\n const { severity, code } = error as { severity?: unknown; code?: unknown };\n return typeof severity === \"string\" && typeof code === \"string\" && /^[0-9A-Z]{5}$/.test(code) ? { severity, code } : null;\n};\n\n/**\n * This function makes a PostgreSQL client, a dependency of a service over a `pg.Pool`.\n * - It sets each timer of pg from the declaration. The driver sends nothing again by itself, and the client\n * sends again only an idempotent operation of its table.\n * - It tells the outcome of a query in three values. An ERROR of the server is certain. A FATAL\n * ends the session, thus its outcome is not certain.\n * - It gives back a client whose query has no certain outcome with an error. The pool then ends it,\n * thus an orphaned query does not hold the next checkout.\n * - It listens to each error of the pool and of a client that it holds. In Node, an error with no\n * listener throws, and library code does not end the process (A5).\n * - It records the process id of the backend of each connection (D1).\n *\n * The outcomes, the second try, the queries in flight, the bounded close and the checks come from\n * the core of the clients. This entry gives what pg does in its own way.\n */\nexport const pgClient = (name: string, spec: PgClientSpec, options: PgClientOptions = {}): PgClient => {\n const problems = specProblems(name, spec);\n if (problems.length > 0) throw new Error(problems.join(\"; \"));\n const { knobs } = spec;\n const clock = options.clock ?? realClock;\n const create = options.create ?? nodePostgres;\n const dial = options.dial ?? sslRequestDial;\n const operations = operationTable({}, spec.operations);\n const requestTimeout = ms(knobs.request_timeout);\n\n let pool: PgPool | null = null;\n let status = \"none\";\n const joins: PgJoin[] = [];\n // the clients of the pool whose socket did not close yet: the bound of the close destroys them\n const open = new Set<PgPoolClient>();\n // the queries in flight: the end of the close settles each one\n const flight = inFlight();\n\n const emit = clientRecorder(options.record, clock, name);\n // the state of the pg client is the outcome of its last connect: each record can move it\n const record = (on: string, to: string = status, detail?: string): void => {\n const from = status;\n status = to;\n emit(from, to, on, detail);\n };\n const closing = (): boolean => status === \"closing\" || status === \"end\";\n\n const onConnect = (client: PgPoolClient): void => {\n open.add(client);\n const generation = joins.length + 1;\n const pid = client.processID;\n joins.push({ generation, at: clock.now(), backendPid: typeof pid === \"number\" ? pid : null, ...socketEnds(client.connection?.stream) });\n record(\"join\", closing() ? status : \"ready\", `generation ${generation}, backend ${pid ?? \"unknown\"}`);\n };\n const onRemove = (client: PgPoolClient): void => {\n open.delete(client);\n record(\"client.removed\");\n };\n // an idle client failed. The pool removed it, and the next checkout opens a new connection\n // after the end, the listener only keeps the error from a throw\n const onPoolError = (error: Error): void => {\n if (status !== \"end\") record(\"client.error\", status, message(error));\n };\n\n /** This function records a failed checkout: a full pool at its bound, or a connect that failed. */\n const checkoutFailed = (error: unknown): void => {\n const text = message(error);\n if (/timeout exceeded when trying to connect/i.test(text)) record(\"checkout.timeout\", status, text);\n else record(\"connect.failed\", closing() ? status : \"failing\", text);\n };\n\n /** This function checks out a client, or gives the reason why the query cannot leave the client. */\n const checkout = (signal: AbortSignal | undefined): Promise<PgPoolClient | Attempt> => {\n const p = pool;\n if (p === null) return Promise.resolve(notSent(`${name} has not connected`));\n if (closing()) return Promise.resolve(notSent(`${name} is ${status}: the query did not leave the client`));\n if (signal?.aborted) return Promise.resolve(notSent(\"the caller aborted the query before it left the client\"));\n return new Promise((resolve) => {\n let done = false;\n const aborted = (): void => {\n done = true;\n resolve(notSent(\"the caller abandoned the query before it left the client\"));\n };\n signal?.addEventListener(\"abort\", aborted, { once: true });\n p.connect().then(\n (client) => {\n signal?.removeEventListener(\"abort\", aborted);\n // the caller left while the pool connected: the client goes back unused\n if (done) client.release();\n else resolve(client);\n },\n (error: unknown) => {\n signal?.removeEventListener(\"abort\", aborted);\n checkoutFailed(error);\n if (!done) resolve(notSent(message(error)));\n },\n );\n });\n };\n\n /** This function makes one try of a query: a checkout, the query, and the release. */\n const attempt = async (text: string, values: readonly unknown[] | undefined, signal: AbortSignal | undefined): Promise<Attempt> => {\n const got = await checkout(signal);\n if (!(\"release\" in got)) return got;\n const client = got;\n // a client that the application holds emits its own errors, and the pool does not listen to them\n const onClientError = (error: Error): void => record(\"client.error\", status, message(error));\n client.on(\"error\", onClientError);\n return flight.track(\n signal,\n \"the caller abandoned the query after it was sent\",\n (settle) => {\n client.query(text, values).then(\n (result) => settle({ outcome: \"ok\", value: { rows: result.rows, rowCount: result.rowCount } }),\n (error: unknown) => {\n const reply = replyOf(error);\n const said = reply === null ? message(error) : `${reply.code} ${message(error)}`;\n // an ERROR ends the statement and keeps the session. A FATAL or a PANIC ends the session, and the commit is not certain\n if (reply !== null && reply.severity === \"ERROR\") settle({ outcome: \"error\", error: said, reply: true });\n else settle({ outcome: \"indeterminate\", error: said }, error instanceof Error ? error : new Error(said));\n },\n );\n },\n (_value, cause) => {\n client.off(\"error\", onClientError);\n // pg keeps a query active on the server after its timeout: an error makes the pool end the client, and the end destroys the socket\n client.release(cause);\n },\n );\n };\n\n const query = <Row>(operation: string, text: string, values?: readonly unknown[], sendOptions: SendOptions = {}): Promise<Sent<PgResult<Row>>> =>\n sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[operation],\n options: sendOptions,\n attempt: (signal) => attempt(text, values, signal) as Promise<Attempt<PgResult<Row>>>,\n onReissue: () => record(\"command.reissue\", status, operation),\n });\n\n const handle: DependencyHandle = {\n async connect(signal) {\n record(\"status.connecting\", \"connecting\");\n const p = await create(poolOptions(name, spec));\n pool = p;\n p.on(\"connect\", onConnect);\n p.on(\"remove\", onRemove);\n p.on(\"error\", onPoolError);\n if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);\n // one checkout opens the first connection. A server that is down does not stop the startup:\n // the checks keep readiness tripped until a connect succeeds (readiness is earned)\n const first = await checkout(signal);\n if (\"release\" in first) first.release();\n },\n async close() {\n const p = pool;\n if (p === null || closing()) return;\n record(\"close.request\", \"closing\");\n if (!(await withinBound(clock, ms(knobs.close_bound), p.end()))) {\n // the end of a client sends Terminate and half-closes the socket. Behind a black hole the\n // socket never closes, and the pool waits with no bound: the bound destroys each socket\n record(\"close.bound\");\n for (const client of [...open]) client.connection?.stream?.destroy?.();\n record(\"close.destroy\", status, `${open.size} sockets`);\n }\n flight.settleAll(\"the client closed with the query in flight\");\n p.off(\"connect\", onConnect);\n p.off(\"remove\", onRemove);\n // the error listener stays: a socket that closes later emits an error, and with no listener it throws\n record(\"status.end\", \"end\");\n },\n };\n\n const declaration: Omit<Dependency, \"name\"> = {\n system: spec.system,\n knobs: {\n connect_bound: knobs.connect_bound,\n request_timeout: knobs.request_timeout,\n statement_timeout: knobs.statement_timeout,\n pool_idle_expiry: knobs.pool_idle_expiry,\n keepalive_idle: knobs.keepalive_idle,\n // pg sends nothing on an idle connection, thus its keepalive is the only refresh of an idle flow (O03)\n idle_refresh_interval: knobs.keepalive_idle,\n max_connection_age: knobs.max_connection_age,\n close_bound: knobs.close_bound,\n retrans_giveup_time: knobs.retrans_giveup_time,\n },\n operations,\n };\n\n const checks = (checkOptions: CheckOptions<PgStep>) =>\n stepChecks<PgStep>(name, checkOptions, {\n // the outcome of the last connect, without a round trip. pg does not connect again by itself,\n // thus pair it with a check that uses the pool\n \"local-state\": localStateCheck(() => status === \"ready\"),\n // a checkout and its release, with no query: it finds a full pool and a connect that fails,\n // but the pool sends no test on an idle client, thus not a dead idle connection\n checkout: {\n ownConnection: true,\n run: async (signal) => {\n const got = await checkout(signal);\n if (!(\"release\" in got)) return \"error\";\n got.release();\n return \"ok\";\n },\n },\n // a SELECT 1 through the pool of the application\n \"round-trip\": roundTripCheck((sendOptions) => query(\"check\", \"SELECT 1\", [], sendOptions)),\n // a new connection each time, with no backend\n dial: dialCheck(dial, spec.host, spec.port),\n });\n\n return {\n name,\n declaration,\n handle,\n meets: pgMeetings(name, knobs),\n get status() {\n return status;\n },\n joins,\n query,\n checks,\n attach: (svc, checkOptions) => attachClient(svc, name, declaration, handle, checks(checkOptions)),\n problems(description) {\n // O07: the server must end a slow statement first, with a certain error\n const deadline = deadlineProblem(name, knobs.request_timeout, knobs.statement_timeout, \"statement\");\n return [...clientProblems(name, description, clientBounds(knobs)), ...(deadline === null ? [] : [deadline])];\n },\n };\n};\n","import type { Machine } from \"@mark1russell7/algebra\";\nimport { clientKnob as knob, closeTimer, transition as t } from \"../client/machine.ts\";\n\n/** The states where the pool exists and serves. */\nconst SERVING = [\"connecting\", \"ready\", \"failing\"] as const;\nconst OPEN = [...SERVING, \"closing\"] as const;\n\n/**\n * The pg client of the service as a `mark1russell7.machine/1` document. It is the pool as the\n * wrapper sees it, not one connection: the document `node-postgres` of `@mark1russell7/machines`\n * gives each client of the pool. The state is the outcome of the last connect:\n * - `ready`: the last connect of the pool succeeded.\n * - `failing`: the last connect failed. pg does not connect again by itself. The next checkout tries again.\n *\n * An idle client that fails and a client that the pool removes do not change the state. The pool\n * removed that client, and the next checkout opens a new connection. A test records the transitions\n * of the client and replays them against this document.\n */\nexport const PG_CLIENT_MACHINE: Machine = {\n format: \"mark1russell7.machine/1\",\n id: \"service.machine.pg-client\",\n title: \"The PostgreSQL client of the service, over a pool of node-postgres 8\",\n layer: \"driver\",\n version: \"0.1.0\",\n sources: [{ ref: \"packages/service/src/pg (the client implements this document)\", rung: \"implemented\" }],\n states: {\n none: { initial: true, note: \"the client exists, and its pool does not\" },\n connecting: { note: \"the first checkout of the startup opens the first connection\" },\n ready: { note: \"the last connect succeeded. A dead idle client stays hidden until the pool ends it or a query meets it\" },\n failing: { note: \"the last connect failed. A checkout of a full pool that times out does not change the state\" },\n closing: { note: \"the end of the pool: each idle client sends Terminate, and each held client goes at its release\" },\n end: { final: true, note: \"the service closed the client\" },\n },\n events: {\n \"status.connecting\": { kind: \"local\" },\n join: { kind: \"rx\", note: \"the first ReadyForQuery of a new connection, with the process id of its backend (D1)\" },\n \"connect.failed\": { kind: \"local\", note: \"a connect failed: its error, a close, a FATAL of the server, or connect_bound\" },\n \"checkout.timeout\": { kind: \"timer\", note: \"a checkout of a full pool waited connect_bound\" },\n \"client.error\": { kind: \"rx\", note: \"an error of an idle client, or of a client that the service holds\" },\n \"client.removed\": { kind: \"local\", note: \"the socket of a client of the pool closed\" },\n \"command.reissue\": { kind: \"local\" },\n \"close.request\": { kind: \"local\" },\n \"close.bound\": { kind: \"timer\" },\n \"close.destroy\": { kind: \"local\", note: \"the bound destroys each socket that a silent server does not close\" },\n \"status.end\": { kind: \"local\" },\n },\n knobs: {\n connect_bound: knob(\"connectionTimeoutMillis\"),\n close_bound: knob(\"close.bound\"),\n },\n timers: {\n connect_timeout: {\n duration: { knob: \"connect_bound\", unit: \"s\" },\n arms: [\"enter:connecting\"],\n cancels: [\"join\", \"connect.failed\"],\n fires: \"connect.failed\",\n note: \"pg-pool destroys the socket of the attempt: 'Connection terminated due to connection timeout'\",\n },\n close: closeTimer(),\n },\n transitions: [\n t(\"connect\", \"none\", \"status.connecting\", \"connecting\"),\n t(\"join\", [...SERVING], \"join\", \"ready\"),\n t(\"connect-failed\", [...SERVING], \"connect.failed\", \"failing\", { timer: \"connect_timeout\" }),\n // a checkout that is in flight at the close can still connect, or fail\n t(\"join-closing\", \"closing\", \"join\", \"closing\"),\n t(\"connect-failed-closing\", \"closing\", \"connect.failed\", \"closing\"),\n ...OPEN.map((state) => t(`checkout-timeout-${state}`, state, \"checkout.timeout\", state)),\n ...OPEN.map((state) => t(`client-error-${state}`, state, \"client.error\", state)),\n ...OPEN.map((state) => t(`removed-${state}`, state, \"client.removed\", state)),\n ...OPEN.map((state) => t(`reissue-${state}`, state, \"command.reissue\", state)),\n t(\"close\", [...SERVING], \"close.request\", \"closing\"),\n t(\"close-bound\", \"closing\", \"close.bound\", \"closing\", { timer: \"close\" }),\n t(\"close-destroy\", \"closing\", \"close.destroy\", \"closing\"),\n t(\"end\", \"closing\", \"status.end\", \"end\"),\n ],\n};\n","import { STARTING_POLL } from \"../client/core.ts\";\nimport type { Poll } from \"../timing.ts\";\nimport type { PgKnobs } from \"./client.ts\";\n\n/**\n * This poll is the poll of the checks that `PG_STARTING_KNOBS` fits. It is `STARTING_POLL` of the\n * core: each 5 s with a jitter of 20 %, and a timeout of 4 s (B6, O12). The poll does not depend on the driver.\n */\nexport const PG_STARTING_POLL: Poll = STARTING_POLL;\n\n/**\n * These knobs are a declaration to start from, from what the cells of S1 measured on node-postgres\n * 8.23.1 against PostgreSQL 17.11. The runtime has no defaults: a service gives these knobs, or its\n * own. Each value holds the borders that the cells measured:\n * - `connect_bound` 5 s: at the defaults pg has no bound, and the kernel gives up on the SYNs only\n * after 131 s. The timer of the pool fired 7 ms late at most. Thus 5 s is in a startup budget of 30 s (O15).\n * - `request_timeout` 9.5 s: the cells ended a query in a black hole at 9.503 s. That is in the slowest poll of 10 s (O13).\n * - `statement_timeout` 9 s: below `request_timeout`, thus the server ends a slow statement first,\n * with ERROR 57014 (O07). The cells measured that end 2 ms after the deadline.\n * - `pool_idle_expiry` 10 s: the idle timer of pg-pool at its defaults, measured at 10.004 s. It is\n * below a router that forgets an idle flow at 12 s (O03), and below a `client_idle_timeout` of PgBouncer at 12 s (O01).\n * - `keepalive_idle` 30 s: at the defaults pg has no keepalive. This value refreshes a held idle\n * connection through the NAT forms of the cells (240 s and 350 s).\n * - `max_connection_age` \"infinite\": no cell measured an age, thus the declaration gives none.\n * - `close_bound` 2 s: behind a black hole the end of the pool waits with no bound. The cells saw\n * the pool emit `remove` only when the socket closes.\n * - `retrans_giveup_time` 924.6 s: the give-up of Linux at `tcp_retries2 = 15`. The cells measured 3.120 s at `tcp_retries2 = 3`.\n */\nexport const PG_STARTING_KNOBS: PgKnobs = {\n connect_bound: { value: 5, unit: \"s\" },\n request_timeout: { value: 9.5, unit: \"s\" },\n statement_timeout: { value: 9, unit: \"s\" },\n pool_idle_expiry: { value: 10, unit: \"s\" },\n keepalive_idle: { value: 30, unit: \"s\" },\n max_connection_age: { value: \"infinite\", unit: \"s\" },\n close_bound: { value: 2, unit: \"s\" },\n retrans_giveup_time: { value: 924.6, unit: \"s\" },\n};\n"],"mappings":";;;;;;;AA+EA,MAAa,eAA4B,OAAO,YAAY;CAG1D,OAAO,KAAI,OADW,OAAO,OAAA,CACX,QAAQ,KAAK,OAAO;AACxC;;;;;;;;;;;;;;ACpEA,MAAa,cAAc,MAAc,UAA8B;CACrE,MAAM,QAAkB;EACtB,IAAI;EACJ,QAAQ,MAAM;EACd,WAAW;EACX,QAAQ,yCAAyC,KAAK;CACxD;CACA,MAAM,aAAuB;EAC3B,IAAI;EACJ,QAAQ,MAAM;EACd,WAAW;EACX,QAAQ;CACV;CACA,MAAM,SAAS,aAAa,MAAM,qBAAqB,gCAAgC;CACvF,MAAM,UAAU,mBAAyD;EACvE;EACA,MAAM,KAAK;EACX,WAAW;GAAC;GAAO;GAAQ;GAAY,gBAAgB,MAAM,cAAc;EAAC;CAC9E;CACA,OAAO;EACL;GACE,eAAe;GACf,MAAM,KAAK;GACX,WAAW;IACT,UAAU,aAAa,kEAAkE;IACzF;IACA,eAAe,MAAM,cAAc;GACrC;EACF;EACA;GACE,eAAe;GACf,MAAM,KAAK;GACX,WAAW,CACT,UAAU,aAAa,uDAAuD,GAC9E,UAAU,QAAQ,mDAAmD,CACvE;EACF;EACA,OAAO,WAAW;EAClB,OAAO,aAAa;EACpB;GACE,eAAe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E,eAAe,WAAW,eAAe,WAAW,EAAE,OAAO,QAAQ,CAAC;EACxEA,WAAE,iBAAiB,WAAW,iBAAiB,SAAS;EACxDA,WAAE,OAAO,WAAW,cAAc,KAAK;CACzC;AACF;;;;;;;ACpEA,MAAa,mBAAyB;;;;;;;;;;;;;;;;;;;AAoBtC,MAAa,oBAA6B;CACxC,eAAe;EAAE,OAAO;EAAG,MAAM;CAAI;CACrC,iBAAiB;EAAE,OAAO;EAAK,MAAM;CAAI;CACzC,mBAAmB;EAAE,OAAO;EAAG,MAAM;CAAI;CACzC,kBAAkB;EAAE,OAAO;EAAI,MAAM;CAAI;CACzC,gBAAgB;EAAE,OAAO;EAAI,MAAM;CAAI;CACvC,oBAAoB;EAAE,OAAO;EAAY,MAAM;CAAI;CACnD,aAAa;EAAE,OAAO;EAAG,MAAM;CAAI;CACnC,qBAAqB;EAAE,OAAO;EAAO,MAAM;CAAI;AACjD"}
1
+ {"version":3,"file":"pg.js","names":["knob","t"],"sources":["../src/pg/connection.ts","../src/pg/meets.ts","../src/pg/client.ts","../src/pg/machine.ts","../src/pg/starting.ts"],"sourcesContent":["import type { ClientSocket, Factory } from \"../client/core.ts\";\n\n/** A pg socket is the socket of a client in the core: the join of the prober and the bounded close read it. */\nexport type PgSocket = ClientSocket;\n\n/** A query result is the part of a result of pg that the wrapper gives back. */\nexport interface PgResult<Row = Record<string, unknown>> {\n readonly rows: Row[];\n readonly rowCount: number | null;\n}\n\n/**\n * A pool client is the part of a `pg.PoolClient` that the wrapper uses. A pg 8 client has each part.\n * A fake for tests has them too. Thus the package depends on no type of pg.\n */\nexport interface PgPoolClient {\n /** This number is the id of the backend from BackendKeyData, which the server sends at the startup. */\n readonly processID?: number | null | undefined;\n /** This connection holds the socket of the client. */\n readonly connection?: { readonly stream?: PgSocket | undefined } | undefined;\n query(text: string, values?: readonly unknown[]): Promise<PgResult<never>>;\n /** This method gives the client back to the pool. With an error, the pool ends the client. */\n release(error?: Error | boolean): void;\n on(event: \"error\", listener: (error: Error) => void): unknown;\n off(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\n/** A pool is the part of a `pg.Pool` that the wrapper uses. */\nexport interface PgPool {\n readonly totalCount: number;\n readonly idleCount: number;\n readonly waitingCount: number;\n connect(): Promise<PgPoolClient>;\n end(): Promise<void>;\n on(event: \"connect\" | \"remove\", listener: (client: PgPoolClient) => void): unknown;\n on(event: \"error\", listener: (error: Error, client: PgPoolClient) => void): unknown;\n off(event: \"connect\" | \"remove\", listener: (client: PgPoolClient) => void): unknown;\n off(event: \"error\", listener: (error: Error, client: PgPoolClient) => void): unknown;\n}\n\n/**\n * These are the options that the wrapper gives `pg.Pool`. Each one comes from the declaration. The\n * wrapper sets each option that has an effect on a timer, thus no default of pg decides one. A knob\n * of pg at 0 has no timer. The wrapper writes \"infinite\" as 0, and it refuses a bound of 0.\n */\nexport interface PgPoolOptions {\n readonly host: string;\n readonly port: number;\n readonly database?: string | undefined;\n readonly user?: string | undefined;\n readonly password?: string | undefined;\n /** The server shows this name in `pg_stat_activity`, thus the prober can join on it too. */\n readonly application_name: string;\n readonly max: number;\n readonly min: number;\n /** This time bounds the TCP connect, the startup and the authentication. It also bounds a checkout from a full pool. */\n readonly connectionTimeoutMillis: number;\n /** This time bounds each query on the client, from `client.query`. The client sends no cancel at its end. */\n readonly query_timeout: number;\n /** This time is the deadline of each statement on the server. The client sends it in the startup message. Undefined does not send it. */\n readonly statement_timeout: number | undefined;\n /** This time ends an idle client of the pool. 0 is no idle timer. */\n readonly idleTimeoutMillis: number;\n /** This time ends a client at this age from its connect, in whole seconds. 0 is no age. */\n readonly maxLifetimeSeconds: number;\n readonly keepAlive: boolean;\n /** This time is the idle time of TCP keepalive. Node truncates it to whole seconds. */\n readonly keepAliveInitialDelayMillis: number;\n /** The idle timer and the idle sockets do not keep the process alive (A14). The lifecycle holds the process. */\n readonly allowExitOnIdle: true;\n}\n\n/** A pool factory makes the pool of the client from its options. */\nexport type PoolFactory = Factory<PgPoolOptions, PgPool>;\n\n/**\n * This factory makes a `pg.Pool`. It loads pg only when a client connects, thus a service that does\n * not use PostgreSQL does not need pg. The specifier is a value, thus the package needs no types of pg.\n */\nexport const nodePostgres: PoolFactory = async (options) => {\n const specifier = \"pg\";\n const loaded = (await import(specifier)) as { readonly default: { readonly Pool: new (options: PgPoolOptions) => PgPool } };\n return new loaded.default.Pool(options);\n};\n","import type { Detector, Meeting } from \"../client/meets.ts\";\nimport { WHAT, immediate, keepaliveAnswered, keepaliveReset, keepaliveSilent, kernelGiveUp } from \"../client/meets.ts\";\nimport type { PgKnobs } from \"./client.ts\";\n\n/**\n * This function gives the manifestations that a pg client can meet, and the detectors of each, from\n * its knobs. The cells of S1 measured each one on node-postgres 8.23.1:\n * - A reset of a query gives ECONNRESET in 0.6 ms, and a FIN to an idle client gives EOF in 18 µs.\n * - A frozen server and a black hole have no detector in 60 s at the defaults: pg has no timer on a query and no keepalive.\n * - `query_timeout` ends a query in a black hole on time (9.503 s for 9.5 s).\n * - `statement_timeout` ends a slow statement on the server with ERROR 57014 (10.002 s for 10 s).\n *\n * pg has no watchdog and does not test an idle client. In place of a watchdog, the pool ends an\n * idle client at its idle timer. A later checkout then opens a new connection, which `connect_bound` bounds.\n */\nexport const pgMeetings = (name: string, knobs: PgKnobs): Meeting[] => {\n const query: Detector = {\n by: \"request_timeout\",\n within: knobs.request_timeout,\n situation: \"in flight\",\n effect: `the query fails as indeterminate, and ${name} gives the client back with an error, thus the pool ends it`,\n };\n const idleExpiry: Detector = {\n by: \"pool_idle_expiry\",\n within: knobs.pool_idle_expiry,\n situation: \"idle\",\n effect: \"the pool ends the idle client, thus no checkout gets the dead connection\",\n };\n const giveUp = kernelGiveUp(knobs.retrans_giveup_time, \"the query fails with its error\");\n const silent = (manifestation: \"blackhole\" | \"freeze-host\"): Meeting => ({\n manifestation,\n what: WHAT[manifestation],\n detectors: [query, giveUp, idleExpiry, keepaliveSilent(knobs.keepalive_idle)],\n });\n return [\n {\n manifestation: \"rst\",\n what: WHAT.rst,\n detectors: [\n immediate(\"in flight\", \"the query fails with ECONNRESET, and each new connect is refused\"),\n idleExpiry,\n keepaliveReset(knobs.keepalive_idle),\n ],\n },\n {\n manifestation: \"fin\",\n what: WHAT.fin,\n detectors: [\n immediate(\"in flight\", \"the query fails: 'Connection terminated unexpectedly'\"),\n immediate(\"idle\", \"the pool removes the idle client, and emits error\"),\n ],\n },\n silent(\"blackhole\"),\n silent(\"freeze-host\"),\n {\n manifestation: \"freeze-process\",\n what: WHAT[\"freeze-process\"],\n detectors: [query, idleExpiry, keepaliveAnswered()],\n },\n {\n manifestation: \"app-stall\",\n what: \"the server stops its replies for a time, for example behind a lock, and its kernel stays up\",\n detectors: [\n {\n by: \"statement_timeout\",\n within: knobs.statement_timeout,\n situation: \"in flight\",\n effect: \"the server ends the statement with ERROR 57014, a certain outcome, and the client stays\",\n },\n query,\n idleExpiry,\n keepaliveAnswered(),\n ],\n },\n ];\n};\n","import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { realClock } from \"../clock.ts\";\nimport type { Attempt, CheckOptions, Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, SendOptions, Sent } from \"../client/core.ts\";\nimport {\n attachClient,\n clientBounds,\n clientProblems,\n clientRecorder,\n deadlineProblem,\n dialCheck,\n finiteMs,\n inFlight,\n localStateCheck,\n message,\n ms,\n notSent,\n operationTable,\n orZero,\n poolProblems,\n roundTripCheck,\n sendWithReissue,\n socketEnds,\n stepChecks,\n timeProblems,\n wholeProblems,\n withinBound,\n zeroProblems,\n} from \"../client/core.ts\";\nimport { helloDial } from \"../client/dial.ts\";\nimport type { Dependency } from \"../description.ts\";\nimport type { DependencyHandle } from \"../lifecycle.ts\";\nimport type { Operation } from \"../operation.ts\";\nimport type { PgPool, PgPoolClient, PgPoolOptions, PgResult, PoolFactory } from \"./connection.ts\";\nimport { nodePostgres } from \"./connection.ts\";\nimport { pgMeetings } from \"./meets.ts\";\n\n/**\n * These are the knobs of the client, each a time, by the names of the ordering law where the law\n * has them. The runtime has no defaults, thus each knob is necessary. A bound that nobody gives is\n * \"infinite\", not zero. `PG_STARTING_KNOBS` gives a declaration from the cells of S1. The knobs\n * that each client has come from the core.\n */\nexport interface PgKnobs extends ClientKnobs {\n /**\n * This time bounds a new connection (`connectionTimeoutMillis`): the TCP connect, the startup and\n * the authentication. The pool uses the same knob to bound a checkout from a full pool.\n * At the defaults pg has no bound, and the kernel gives up on the SYNs only after 131 s (A3, O15).\n */\n readonly connect_bound: Quantity;\n /** This time bounds each query on the client (`query_timeout`). pg sends no cancel at its end. */\n readonly request_timeout: Quantity;\n /**\n * This time is the deadline of each statement on the server (`statement_timeout`). The server then\n * ends the statement with ERROR 57014, a certain outcome. \"infinite\" sends no deadline.\n */\n readonly statement_timeout: Extent;\n /** This time ends an idle client of the pool (`idleTimeoutMillis`). The pool sends no test on an idle client. */\n readonly pool_idle_expiry: Extent;\n /** This time is the idle time of TCP keepalive, in whole seconds. Node then sends 10 probes 1 s apart. */\n readonly keepalive_idle: Extent;\n /** This time is the age at which the pool replaces a client (`maxLifetimeSeconds`), in whole seconds. */\n readonly max_connection_age: Extent;\n /** This time bounds the close of the pool at the shutdown: its end, then a destroy of each socket that stays. */\n readonly close_bound: Quantity;\n}\n\n/** A pg client spec is the declaration of one PostgreSQL client: where it connects, its pool, and its knobs. */\nexport interface PgClientSpec extends ClientSpec<PgKnobs> {\n readonly database?: string | undefined;\n readonly user?: string | undefined;\n /** These counts are the sizes of the pool: at most `max` clients, and an idle timer only above `min`. */\n readonly pool: { readonly max: number; readonly min: number };\n /**\n * These operations are the queries of the service, by name, with their idempotency. SQL text does\n * not tell if a statement changes a state, thus the client sends again only a query that this table names.\n */\n readonly operations?: Readonly<Record<string, Operation>> | undefined;\n}\n\n/** These options make a client. Without them, it uses pg, the real clock, and a dial with an SSLRequest. */\nexport type PgClientOptions = ClientOptions<PoolFactory>;\n\n/**\n * A join is one connection of the pool, at its connect (D1, D2). The prober joins its kernel records\n * to the server's view of the connection through it. The server's view is the process id of the backend.\n */\nexport interface PgJoin extends ClientJoin {\n /** This number is the process id of the backend, or null when the server gave none. Through a pooler, it is the id that the pooler gives. */\n readonly backendPid: number | null;\n}\n\n/** The steps that the pg client gives a check for: the steps of each client, and a checkout from the pool (B14). */\nexport type PgStep = ClientStep | \"checkout\";\n\n/** A pg client is a dependency of a service: its declaration, its handle, its checks and its queries. */\nexport interface PgClient extends Client<PgStep, PgJoin> {\n /** This text is the state of the client, as `PG_CLIENT_MACHINE` names it. */\n readonly status: string;\n /**\n * This method sends a query, and gives its outcome in three values. `operation` names the query\n * in the table of operations. The client sends again only an idempotent operation, one time at\n * most, after an outcome that is not certain. The second try stays in the bound of the request.\n */\n query<Row = Record<string, unknown>>(\n operation: string,\n text: string,\n values?: readonly unknown[],\n options?: SendOptions,\n ): Promise<Sent<PgResult<Row>>>;\n}\n\n/** This function gives the problems of a spec: the knobs that pg cannot use. */\nexport const specProblems = (name: string, spec: PgClientSpec): string[] => {\n const { knobs } = spec;\n return [\n ...timeProblems(name, knobs),\n // pg reads 0 as no timer, thus a bound of 0 is not a bound\n ...zeroProblems(name, \"pg\", knobs, {\n bounded: [\"connect_bound\", \"request_timeout\", \"close_bound\"],\n open: [\"statement_timeout\", \"pool_idle_expiry\", \"keepalive_idle\", \"max_connection_age\"],\n }),\n // Node truncates the keepalive delay to whole seconds, and pg takes the age in whole seconds\n ...wholeProblems(name, knobs, {\n millis: [\"connect_bound\", \"request_timeout\", \"statement_timeout\", \"pool_idle_expiry\"],\n seconds: [\"keepalive_idle\", \"max_connection_age\"],\n }),\n ...poolProblems(name, spec.pool),\n ];\n};\n\n/** This function gives the options of `pg.Pool` from a spec. Each timer of pg comes from the declaration. */\nexport const poolOptions = (name: string, spec: PgClientSpec): PgPoolOptions => {\n const { knobs } = spec;\n return {\n host: spec.host,\n port: spec.port,\n ...(spec.database === undefined ? {} : { database: spec.database }),\n ...(spec.user === undefined ? {} : { user: spec.user }),\n ...(spec.password === undefined ? {} : { password: spec.password }),\n application_name: name,\n max: spec.pool.max,\n min: spec.pool.min,\n connectionTimeoutMillis: ms(knobs.connect_bound),\n query_timeout: ms(knobs.request_timeout),\n statement_timeout: finiteMs(knobs.statement_timeout),\n idleTimeoutMillis: orZero(knobs.pool_idle_expiry),\n maxLifetimeSeconds: orZero(knobs.max_connection_age) / 1000,\n keepAlive: knobs.keepalive_idle.value !== \"infinite\",\n keepAliveInitialDelayMillis: orZero(knobs.keepalive_idle),\n allowExitOnIdle: true,\n };\n};\n\n/** The bytes of an SSLRequest: a length of 8, then the code 80877103. A server answers with one byte, S or N. */\nconst SSL_REQUEST = Uint8Array.of(0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f);\n\n/**\n * This dial function opens a TCP connection, sends an SSLRequest, and waits for its one byte. The\n * server answers it before the authentication, thus the dial needs no password and opens no backend.\n */\nexport const sslRequestDial: DialFn = helloDial(SSL_REQUEST, (received) => {\n const answer = String.fromCharCode(received[0] ?? 0);\n return answer === \"S\" || answer === \"N\" ? null : new Error(`the answer to the SSLRequest was ${JSON.stringify(answer)}`);\n});\n\n/** A database error is an ErrorResponse of the server: pg gives its severity and its SQLSTATE code. */\nconst replyOf = (error: unknown): { readonly severity: string; readonly code: string } | null => {\n if (typeof error !== \"object\" || error === null) return null;\n const { severity, code } = error as { severity?: unknown; code?: unknown };\n return typeof severity === \"string\" && typeof code === \"string\" && /^[0-9A-Z]{5}$/.test(code) ? { severity, code } : null;\n};\n\n/**\n * This function makes a PostgreSQL client, a dependency of a service over a `pg.Pool`.\n * - It sets each timer of pg from the declaration. The driver sends nothing again by itself, and the client\n * sends again only an idempotent operation of its table.\n * - It tells the outcome of a query in three values. An ERROR of the server is certain. A FATAL\n * ends the session, thus its outcome is not certain.\n * - It gives back a client whose query has no certain outcome with an error. The pool then ends it,\n * thus an orphaned query does not hold the next checkout.\n * - It listens to each error of the pool and of a client that it holds. In Node, an error with no\n * listener throws, and library code does not end the process (A5).\n * - It records the process id of the backend of each connection (D1).\n *\n * The outcomes, the second try, the queries in flight, the bounded close and the checks come from\n * the core of the clients. This entry gives what pg does in its own way.\n */\nexport const pgClient = (name: string, spec: PgClientSpec, options: PgClientOptions = {}): PgClient => {\n const problems = specProblems(name, spec);\n if (problems.length > 0) throw new Error(problems.join(\"; \"));\n const { knobs } = spec;\n const clock = options.clock ?? realClock;\n const create = options.create ?? nodePostgres;\n const dial = options.dial ?? sslRequestDial;\n const operations = operationTable({}, spec.operations);\n const requestTimeout = ms(knobs.request_timeout);\n\n let pool: PgPool | null = null;\n let status = \"none\";\n const joins: PgJoin[] = [];\n // the clients of the pool whose socket did not close yet: the bound of the close destroys them\n const open = new Set<PgPoolClient>();\n // the queries in flight: the end of the close settles each one\n const flight = inFlight();\n\n const emit = clientRecorder(options.record, clock, name);\n // the state of the pg client is the outcome of its last connect: each record can move it\n const record = (on: string, to: string = status, detail?: string): void => {\n const from = status;\n status = to;\n emit(from, to, on, detail);\n };\n const closing = (): boolean => status === \"closing\" || status === \"end\";\n\n const onConnect = (client: PgPoolClient): void => {\n open.add(client);\n const generation = joins.length + 1;\n const pid = client.processID;\n joins.push({ generation, at: clock.now(), backendPid: typeof pid === \"number\" ? pid : null, ...socketEnds(client.connection?.stream) });\n record(\"join\", closing() ? status : \"ready\", `generation ${generation}, backend ${pid ?? \"unknown\"}`);\n };\n const onRemove = (client: PgPoolClient): void => {\n open.delete(client);\n record(\"client.removed\");\n };\n // an idle client failed. The pool removed it, and the next checkout opens a new connection\n // after the end, the listener only keeps the error from a throw\n const onPoolError = (error: Error): void => {\n if (status !== \"end\") record(\"client.error\", status, message(error));\n };\n\n /** This function records a failed checkout: a full pool at its bound, or a connect that failed. */\n const checkoutFailed = (error: unknown): void => {\n const text = message(error);\n if (/timeout exceeded when trying to connect/i.test(text)) record(\"checkout.timeout\", status, text);\n else record(\"connect.failed\", closing() ? status : \"failing\", text);\n };\n\n /** This function checks out a client, or gives the reason why the query cannot leave the client. */\n const checkout = (signal: AbortSignal | undefined): Promise<PgPoolClient | Attempt> => {\n const p = pool;\n if (p === null) return Promise.resolve(notSent(`${name} has not connected`));\n if (closing()) return Promise.resolve(notSent(`${name} is ${status}: the query did not leave the client`));\n if (signal?.aborted) return Promise.resolve(notSent(\"the caller aborted the query before it left the client\"));\n return new Promise((resolve) => {\n let done = false;\n const aborted = (): void => {\n done = true;\n resolve(notSent(\"the caller abandoned the query before it left the client\"));\n };\n signal?.addEventListener(\"abort\", aborted, { once: true });\n p.connect().then(\n (client) => {\n signal?.removeEventListener(\"abort\", aborted);\n // the caller left while the pool connected: the client goes back unused\n if (done) client.release();\n else resolve(client);\n },\n (error: unknown) => {\n signal?.removeEventListener(\"abort\", aborted);\n checkoutFailed(error);\n if (!done) resolve(notSent(message(error)));\n },\n );\n });\n };\n\n /** This function makes one try of a query: a checkout, the query, and the release. */\n const attempt = async (text: string, values: readonly unknown[] | undefined, signal: AbortSignal | undefined): Promise<Attempt> => {\n const got = await checkout(signal);\n if (!(\"release\" in got)) return got;\n const client = got;\n // a client that the application holds emits its own errors, and the pool does not listen to them\n const onClientError = (error: Error): void => record(\"client.error\", status, message(error));\n client.on(\"error\", onClientError);\n return flight.track(\n signal,\n \"the caller abandoned the query after it was sent\",\n (settle) => {\n client.query(text, values).then(\n (result) => settle({ outcome: \"ok\", value: { rows: result.rows, rowCount: result.rowCount } }),\n (error: unknown) => {\n const reply = replyOf(error);\n const said = reply === null ? message(error) : `${reply.code} ${message(error)}`;\n // an ERROR ends the statement and keeps the session. A FATAL or a PANIC ends the session, and the commit is not certain\n if (reply !== null && reply.severity === \"ERROR\") settle({ outcome: \"error\", error: said, reply: true });\n else settle({ outcome: \"indeterminate\", error: said }, error instanceof Error ? error : new Error(said));\n },\n );\n },\n (_value, cause) => {\n client.off(\"error\", onClientError);\n // pg keeps a query active on the server after its timeout: an error makes the pool end the client, and the end destroys the socket\n client.release(cause);\n },\n );\n };\n\n const query = <Row>(operation: string, text: string, values?: readonly unknown[], sendOptions: SendOptions = {}): Promise<Sent<PgResult<Row>>> =>\n sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[operation],\n options: sendOptions,\n attempt: (signal) => attempt(text, values, signal) as Promise<Attempt<PgResult<Row>>>,\n onReissue: () => record(\"command.reissue\", status, operation),\n });\n\n const handle: DependencyHandle = {\n async connect(signal) {\n record(\"status.connecting\", \"connecting\");\n const p = await create(poolOptions(name, spec));\n pool = p;\n p.on(\"connect\", onConnect);\n p.on(\"remove\", onRemove);\n p.on(\"error\", onPoolError);\n if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);\n // one checkout opens the first connection. A server that is down does not stop the startup:\n // the checks keep readiness tripped until a connect succeeds (readiness is earned)\n const first = await checkout(signal);\n if (\"release\" in first) first.release();\n },\n async close() {\n const p = pool;\n if (p === null || closing()) return;\n record(\"close.request\", \"closing\");\n if (!(await withinBound(clock, ms(knobs.close_bound), p.end()))) {\n // the end of a client sends Terminate and half-closes the socket. Behind a black hole the\n // socket never closes, and the pool waits with no bound: the bound destroys each socket\n record(\"close.bound\");\n for (const client of [...open]) client.connection?.stream?.destroy?.();\n record(\"close.destroy\", status, `${open.size} sockets`);\n }\n flight.settleAll(\"the client closed with the query in flight\");\n p.off(\"connect\", onConnect);\n p.off(\"remove\", onRemove);\n // the error listener stays: a socket that closes later emits an error, and with no listener it throws\n record(\"status.end\", \"end\");\n },\n };\n\n const declaration: Omit<Dependency, \"name\"> = {\n system: spec.system,\n knobs: {\n connect_bound: knobs.connect_bound,\n request_timeout: knobs.request_timeout,\n statement_timeout: knobs.statement_timeout,\n pool_idle_expiry: knobs.pool_idle_expiry,\n keepalive_idle: knobs.keepalive_idle,\n // pg sends nothing on an idle connection, thus its keepalive is the only refresh of an idle flow (O03)\n idle_refresh_interval: knobs.keepalive_idle,\n max_connection_age: knobs.max_connection_age,\n close_bound: knobs.close_bound,\n retrans_giveup_time: knobs.retrans_giveup_time,\n },\n operations,\n };\n\n const checks = (checkOptions: CheckOptions<PgStep>) =>\n stepChecks<PgStep>(name, checkOptions, {\n // the outcome of the last connect, without a round trip. pg does not connect again by itself,\n // thus pair it with a check that uses the pool\n \"local-state\": localStateCheck(() => status === \"ready\"),\n // a checkout and its release, with no query: it finds a full pool and a connect that fails,\n // but the pool sends no test on an idle client, thus not a dead idle connection\n checkout: {\n ownConnection: true,\n run: async (signal) => {\n const got = await checkout(signal);\n if (!(\"release\" in got)) return \"error\";\n got.release();\n return \"ok\";\n },\n },\n // a SELECT 1 through the pool of the application\n \"round-trip\": roundTripCheck((sendOptions) => query(\"check\", \"SELECT 1\", [], sendOptions)),\n // a new connection each time, with no backend\n dial: dialCheck(dial, spec.host, spec.port),\n });\n\n return {\n name,\n declaration,\n handle,\n meets: pgMeetings(name, knobs),\n get status() {\n return status;\n },\n joins,\n query,\n checks,\n attach: (svc, checkOptions) => attachClient(svc, name, declaration, handle, checks(checkOptions)),\n problems(description) {\n // O07: the server must end a slow statement first, with a certain error\n const deadline = deadlineProblem(name, knobs.request_timeout, knobs.statement_timeout, \"statement\");\n return [...clientProblems(name, description, clientBounds(knobs)), ...(deadline === null ? [] : [deadline])];\n },\n };\n};\n","import type { Machine } from \"@mark1russell7/algebra\";\nimport { clientKnob as knob, closeTimer, transition as t } from \"../client/machine.ts\";\n\n/** The states where the pool exists and serves. */\nconst SERVING = [\"connecting\", \"ready\", \"failing\"] as const;\nconst OPEN = [...SERVING, \"closing\"] as const;\n\n/**\n * The pg client of the service as a `mark1russell7.machine/1` document. It is the pool as the\n * wrapper sees it, not one connection: the document `node-postgres` of `@mark1russell7/machines`\n * gives each client of the pool. The state is the outcome of the last connect:\n * - `ready`: the last connect of the pool succeeded.\n * - `failing`: the last connect failed. pg does not connect again by itself. The next checkout tries again.\n *\n * An idle client that fails and a client that the pool removes do not change the state. The pool\n * removed that client, and the next checkout opens a new connection. A test records the transitions\n * of the client and replays them against this document.\n */\nexport const PG_CLIENT_MACHINE: Machine = {\n format: \"mark1russell7.machine/1\",\n id: \"service.machine.pg-client\",\n title: \"The PostgreSQL client of the service, over a pool of node-postgres 8\",\n layer: \"driver\",\n version: \"0.1.0\",\n sources: [{ ref: \"packages/service/src/pg (the client implements this document)\", rung: \"implemented\" }],\n states: {\n none: { initial: true, note: \"the client exists, and its pool does not\" },\n connecting: { note: \"the first checkout of the startup opens the first connection\" },\n ready: { note: \"the last connect succeeded. A dead idle client stays hidden until the pool ends it or a query meets it\" },\n failing: { note: \"the last connect failed. A checkout of a full pool that times out does not change the state\" },\n closing: { note: \"the end of the pool: each idle client sends Terminate, and each held client goes at its release\" },\n end: { final: true, note: \"the service closed the client\" },\n },\n events: {\n \"status.connecting\": { kind: \"local\" },\n join: { kind: \"rx\", note: \"the first ReadyForQuery of a new connection, with the process id of its backend (D1)\" },\n \"connect.failed\": { kind: \"local\", note: \"a connect failed: its error, a close, a FATAL of the server, or connect_bound\" },\n \"checkout.timeout\": { kind: \"timer\", note: \"a checkout of a full pool waited connect_bound\" },\n \"client.error\": { kind: \"rx\", note: \"an error of an idle client, or of a client that the service holds\" },\n \"client.removed\": { kind: \"local\", note: \"the socket of a client of the pool closed\" },\n \"command.reissue\": { kind: \"local\" },\n \"close.request\": { kind: \"local\" },\n \"close.bound\": { kind: \"timer\" },\n \"close.destroy\": { kind: \"local\", note: \"the bound destroys each socket that a silent server does not close\" },\n \"status.end\": { kind: \"local\" },\n },\n knobs: {\n connect_bound: knob(\"connectionTimeoutMillis\"),\n close_bound: knob(\"close.bound\"),\n },\n timers: {\n connect_timeout: {\n duration: { knob: \"connect_bound\", unit: \"s\" },\n arms: [\"enter:connecting\"],\n cancels: [\"join\", \"connect.failed\"],\n fires: \"connect.failed\",\n note: \"pg-pool destroys the socket of the attempt: 'Connection terminated due to connection timeout'\",\n },\n close: closeTimer(),\n },\n transitions: [\n t(\"connect\", \"none\", \"status.connecting\", \"connecting\"),\n t(\"join\", [...SERVING], \"join\", \"ready\"),\n t(\"connect-failed\", [...SERVING], \"connect.failed\", \"failing\", { timer: \"connect_timeout\" }),\n // a checkout that is in flight at the close can still connect, or fail\n t(\"join-closing\", \"closing\", \"join\", \"closing\"),\n t(\"connect-failed-closing\", \"closing\", \"connect.failed\", \"closing\"),\n ...OPEN.map((state) => t(`checkout-timeout-${state}`, state, \"checkout.timeout\", state)),\n ...OPEN.map((state) => t(`client-error-${state}`, state, \"client.error\", state)),\n ...OPEN.map((state) => t(`removed-${state}`, state, \"client.removed\", state)),\n ...OPEN.map((state) => t(`reissue-${state}`, state, \"command.reissue\", state)),\n t(\"close\", [...SERVING], \"close.request\", \"closing\"),\n t(\"close-bound\", \"closing\", \"close.bound\", \"closing\", { timer: \"close\" }),\n t(\"close-destroy\", \"closing\", \"close.destroy\", \"closing\"),\n t(\"end\", \"closing\", \"status.end\", \"end\"),\n ],\n};\n","import { STARTING_POLL } from \"../client/core.ts\";\nimport type { Poll } from \"../timing.ts\";\nimport type { PgKnobs } from \"./client.ts\";\n\n/**\n * This poll is the poll of the checks that `PG_STARTING_KNOBS` fits. It is `STARTING_POLL` of the\n * core: each 5 s with a jitter of 20 %, and a timeout of 4 s (B6, O12). The poll does not depend on the driver.\n */\nexport const PG_STARTING_POLL: Poll = STARTING_POLL;\n\n/**\n * These knobs are a declaration to start from, from what the cells of S1 measured on node-postgres\n * 8.23.1 against PostgreSQL 17.11. The runtime has no defaults: a service gives these knobs, or its\n * own. Each value holds the borders that the cells measured:\n * - `connect_bound` 5 s: at the defaults pg has no bound, and the kernel gives up on the SYNs only\n * after 131 s. The timer of the pool fired 7 ms late at most. Thus 5 s is in a startup budget of 30 s (O15).\n * - `request_timeout` 9.5 s: the cells ended a query in a black hole at 9.503 s. That is in the slowest poll of 10 s (O13).\n * - `statement_timeout` 9 s: below `request_timeout`, thus the server ends a slow statement first,\n * with ERROR 57014 (O07). The cells measured that end 2 ms after the deadline.\n * - `pool_idle_expiry` 10 s: the idle timer of pg-pool at its defaults, measured at 10.004 s. It is\n * below a router that forgets an idle flow at 12 s (O03), and below a `client_idle_timeout` of PgBouncer at 12 s (O01).\n * - `keepalive_idle` 30 s: at the defaults pg has no keepalive. This value refreshes a held idle\n * connection through the NAT forms of the cells (240 s and 350 s).\n * - `max_connection_age` \"infinite\": no cell measured an age, thus the declaration gives none.\n * - `close_bound` 2 s: behind a black hole the end of the pool waits with no bound. The cells saw\n * the pool emit `remove` only when the socket closes.\n * - `retrans_giveup_time` 924.6 s: the give-up of Linux at `tcp_retries2 = 15`. The cells measured 3.120 s at `tcp_retries2 = 3`.\n */\nexport const PG_STARTING_KNOBS: PgKnobs = {\n connect_bound: { value: 5, unit: \"s\" },\n request_timeout: { value: 9.5, unit: \"s\" },\n statement_timeout: { value: 9, unit: \"s\" },\n pool_idle_expiry: { value: 10, unit: \"s\" },\n keepalive_idle: { value: 30, unit: \"s\" },\n max_connection_age: { value: \"infinite\", unit: \"s\" },\n close_bound: { value: 2, unit: \"s\" },\n retrans_giveup_time: { value: 924.6, unit: \"s\" },\n};\n"],"mappings":";;;;;;;AA+EA,MAAa,eAA4B,OAAO,YAAY;CAG1D,OAAO,KAAI,OADW,OAAO,OAAA,CACX,QAAQ,KAAK,OAAO;AACxC;;;;;;;;;;;;;ACpEA,MAAa,cAAc,MAAc,UAA8B;CACrE,MAAM,QAAkB;EACtB,IAAI;EACJ,QAAQ,MAAM;EACd,WAAW;EACX,QAAQ,yCAAyC,KAAK;CACxD;CACA,MAAM,aAAuB;EAC3B,IAAI;EACJ,QAAQ,MAAM;EACd,WAAW;EACX,QAAQ;CACV;CACA,MAAM,SAAS,aAAa,MAAM,qBAAqB,gCAAgC;CACvF,MAAM,UAAU,mBAAyD;EACvE;EACA,MAAM,KAAK;EACX,WAAW;GAAC;GAAO;GAAQ;GAAY,gBAAgB,MAAM,cAAc;EAAC;CAC9E;CACA,OAAO;EACL;GACE,eAAe;GACf,MAAM,KAAK;GACX,WAAW;IACT,UAAU,aAAa,kEAAkE;IACzF;IACA,eAAe,MAAM,cAAc;GACrC;EACF;EACA;GACE,eAAe;GACf,MAAM,KAAK;GACX,WA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A,WAAE,WAAW,SAAS,OAAO,mBAAmB,KAAK,CAAC;EAC7EA,WAAE,SAAS,CAAC,GAAG,OAAO,GAAG,iBAAiB,SAAS;EACnDA,WAAE,eAAe,WAAW,eAAe,WAAW,EAAE,OAAO,QAAQ,CAAC;EACxEA,WAAE,iBAAiB,WAAW,iBAAiB,SAAS;EACxDA,WAAE,OAAO,WAAW,cAAc,KAAK;CACzC;AACF;;;;;;ACpEA,MAAa,mBAAyB;;;;;;;;;;;;;;;;;;;AAoBtC,MAAa,oBAA6B;CACxC,eAAe;EAAE,OAAO;EAAG,MAAM;CAAI;CACrC,iBAAiB;EAAE,OAAO;EAAK,MAAM;CAAI;CACzC,mBAAmB;EAAE,OAAO;EAAG,MAAM;CAAI;CACzC,kBAAkB;EAAE,OAAO;EAAI,MAAM;CAAI;CACzC,gBAAgB;EAAE,OAAO;EAAI,MAAM;CAAI;CACvC,oBAAoB;EAAE,OAAO;EAAY,MAAM;CAAI;CACnD,aAAa;EAAE,OAAO;EAAG,MAAM;CAAI;CACnC,qBAAqB;EAAE,OAAO;EAAO,MAAM;CAAI;AACjD"}
@@ -1,5 +1,5 @@
1
1
  import { convertExact, convertible, rationals } from "@mark1russell7/quantity";
2
- //#region src/limiter/policy.ts
2
+ // src/limiter/policy.ts
3
3
  /**
4
4
  * This tolerance is one nanosecond, in milliseconds. A comparison of times permits it, because a
5
5
  * rate of 3 for each second gives an interval that floating point cannot hold exactly.
@@ -222,7 +222,6 @@ const decide = (rule, state, now, units) => {
222
222
  }
223
223
  };
224
224
  };
225
- //#endregion
226
225
  export { limitRule as a, overCapacity as c, idleSpan as i, retryAfterSeconds as l, decide as n, limiterProblems as o, freeAt as r, longestRetryAfter as s, capacityOf as t, unitsOf as u };
227
226
 
228
- //# sourceMappingURL=policy-G-Y3Meku.js.map
227
+ //# sourceMappingURL=policy-B23MY52l.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"policy-G-Y3Meku.js","names":["r"],"sources":["../src/limiter/policy.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertExact, convertible, rationals as r } from \"@mark1russell7/quantity\";\n\n/**\n * A token bucket gives each key a bucket of `burst` tokens. The bucket refills at `rate`, and each\n * take uses one token. Thus a key can make `burst` takes at once after an idle time, and then\n * `rate` takes in each unit of time.\n */\nexport interface TokenBucket {\n readonly type: \"token-bucket\";\n /** This rate is how fast the bucket refills: a count for each unit of time, for example `{ value: 10, unit: \"count/s\" }`. */\n readonly rate: Quantity;\n /** This count is the size of the bucket: the most takes in a sequence after an idle time. */\n readonly burst: Quantity;\n}\n\n/**\n * A sliding window gives each key at most `limit` takes in each `window`. Each take counts for one\n * window from its time, thus the window moves with the clock and has no fixed edges.\n */\nexport interface SlidingWindow {\n readonly type: \"sliding-window\";\n /** This count is the most takes of one key in one window. */\n readonly limit: Quantity;\n /** This time is the length of the window. */\n readonly window: Quantity;\n}\n\n/** A limit policy is the rule that a keyed limiter applies to each key, as data. It has no defaults. */\nexport type LimitPolicy = TokenBucket | SlidingWindow;\n\n/**\n * A store failure policy tells what a take does when a shared store fails. It has no default.\n * - `open`: the limiter lets the take in. The count is not known, thus `remaining` is 0.\n * - `closed`: the limiter refuses the take with the cause `store`. Its `retryAfter` is the longest\n * `retryAfter` of the policy (`longestRetryAfter`). Thus O29 and O30 apply to it too.\n */\nexport type StoreFailure = \"open\" | \"closed\";\n\n/**\n * A store spec tells where the counts of the keys are:\n * - `local`: in the memory of each replica. A limit L over N replicas is then L / N on each\n * replica. That sum holds only on average, when the balancer spreads the takes of each key evenly.\n * A local store does not fail, thus it has no `onStoreFailure`, and the limiter ignores one.\n * - `shared`: in a store that the replicas share, the dependency of that name. The store decides\n * each take in one atomic step, on its own clock. Thus the limit holds across the replicas.\n * `onStoreFailure` tells what a take does when the store fails.\n */\nexport type LimiterStoreSpec =\n | { readonly kind: \"local\" }\n | { readonly kind: \"shared\"; readonly dependency: string; readonly onStoreFailure: StoreFailure };\n\n/**\n * The eviction of a limiter bounds its keys. A store removes a key only when its state is equal to\n * the state of a new key. That is a bucket that is full again, or a window with no take in it.\n * Thus an eviction changes no decision.\n */\nexport interface LimiterEviction {\n /**\n * This count is the most keys that the store holds. At the cap, the store refuses a take of a new\n * key until a held key is idle for its span (`idleSpan`). A held key keeps its count.\n */\n readonly maxKeys: Quantity;\n}\n\n/** A limiter spec is the declaration of one keyed limiter. Each part is necessary, because the limiter has no defaults. */\nexport interface LimiterSpec {\n /** This text tells what the key of each take is, for example `tenant` or `principal`. The caller gives each key. */\n readonly key: string;\n readonly policy: LimitPolicy;\n readonly store: LimiterStoreSpec;\n readonly evict: LimiterEviction;\n}\n\n/** A limiter is a keyed limiter in the description of a service: its name and its spec. */\nexport interface Limiter extends LimiterSpec {\n readonly name: string;\n}\n\n/**\n * A wait cause tells why a take is refused for a time:\n * - `limit`: the key used its limit.\n * - `cap`: the store holds its cap of keys, and the key is new.\n * - `store`: the shared store failed, and its spec declares `onStoreFailure: \"closed\"`.\n */\nexport type WaitCause = \"limit\" | \"cap\" | \"store\";\n\n/**\n * A refusal cause tells why a take is refused: a wait cause, or `capacity`. The cause `capacity` is\n * a take whose units are over the capacity of the policy. No wait lets it in.\n */\nexport type RefusalCause = WaitCause | \"capacity\";\n\n/**\n * A permitted take used its units of its key. `remaining` is the count of units that the key can\n * take at this time.\n */\nexport interface Allowed {\n readonly allowed: true;\n readonly remaining: number;\n /** This text is the failure of a shared store, when `onStoreFailure: \"open\"` lets the take in. */\n readonly failure?: string | undefined;\n}\n\n/**\n * A wait refusal used nothing. `retryAfter` is the time until the limiter lets the same take in, when\n * no other take comes first. It is always above zero.\n */\nexport interface WaitRefused {\n readonly allowed: false;\n readonly cause: WaitCause;\n readonly retryAfter: Quantity;\n /** This text is the failure of a shared store, for the cause `store`. */\n readonly failure?: string | undefined;\n}\n\n/**\n * A capacity refusal used nothing, and the same take is refused at each time. Its `units` are over\n * the `capacity` of the policy: the `burst` of a bucket, or the `limit` of a window. A caller can\n * split the take into parts of at most `capacity` units.\n */\nexport interface CapacityRefused {\n readonly allowed: false;\n readonly cause: \"capacity\";\n readonly units: number;\n readonly capacity: number;\n}\n\n/**\n * A refused take used nothing. The cause tells the type: a `WaitRefused` has a `retryAfter`, and a\n * `CapacityRefused` has none. Thus a caller examines the cause before it reads `retryAfter`.\n */\nexport type Refused = WaitRefused | CapacityRefused;\n\n/** A decision is the answer of a limiter to one take. */\nexport type Decision = Allowed | Refused;\n\n/**\n * A limit rule is a policy in numbers, which a store applies: each time in milliseconds, and each\n * count as a number. A store in another process, for example a script of Redis, gets these numbers.\n */\nexport type LimitRule =\n | {\n readonly type: \"token-bucket\";\n /** This time is the refill of one token, in milliseconds. */\n readonly interval: number;\n readonly burst: number;\n }\n | {\n readonly type: \"sliding-window\";\n readonly limit: number;\n /** This time is the length of the window, in milliseconds. */\n readonly window: number;\n };\n\n/**\n * A key state is what a store keeps for one key:\n * - A token bucket keeps the time at which its bucket is full again (`full`, in milliseconds).\n * - A sliding window keeps the time of each permitted take in the window, the oldest first.\n */\nexport type KeyState =\n | { readonly type: \"token-bucket\"; readonly full: number }\n | { readonly type: \"sliding-window\"; readonly stamps: readonly number[] };\n\n/** A step is the decision of one take, and the state of its key after the take. A refusal keeps the count of the key. */\nexport interface TakeStep {\n readonly decision: Decision;\n readonly state: KeyState;\n}\n\n/**\n * This tolerance is one nanosecond, in milliseconds. A comparison of times permits it, because a\n * rate of 3 for each second gives an interval that floating point cannot hold exactly.\n */\nconst TOLERANCE = 1e-6;\n\nconst isCount = (amount: Quantity | undefined): boolean => amount !== undefined && convertible(amount.unit, \"count\");\nconst isTime = (amount: Quantity | undefined): boolean => amount !== undefined && convertible(amount.unit, \"s\");\nconst isRate = (amount: Quantity | undefined): boolean => amount !== undefined && convertible(amount.unit, \"count/s\");\n/** This function tells if a unit converts, also for a unit that the quantity package does not know. */\nconst safely = (test: (amount: Quantity | undefined) => boolean, amount: Quantity | undefined): boolean => {\n try {\n return test(amount);\n } catch {\n return false;\n }\n};\nconst finiteAbove = (amount: Quantity): boolean => typeof amount.value === \"number\" && Number.isFinite(amount.value) && amount.value > 0;\nconst wholeCount = (amount: Quantity): boolean => finiteAbove(amount) && Number.isInteger(r.toNumber(convertExact(r.fromNumber(amount.value), amount.unit, \"count\")));\n\n/** A loose policy is a policy from any source, with each part optional, for the check of its parts. */\ninterface LoosePolicy {\n readonly type?: string;\n readonly rate?: Quantity;\n readonly burst?: Quantity;\n readonly limit?: Quantity;\n readonly window?: Quantity;\n}\n\n/**\n * This function gives the problems of a limiter spec. `describe()` and `keyedLimiter` refuse a spec\n * with a problem. A part that is absent is a problem, because the limiter has no defaults.\n */\nexport const limiterProblems = (name: string, spec: Partial<LimiterSpec> | undefined): string[] => {\n const owner = `limiter ${name}`;\n if (spec === undefined || (spec as unknown) === null) return [`${owner} has no spec: a limiter has no defaults`];\n const problems: string[] = [];\n const missing = (part: string): void => {\n problems.push(`${owner} does not declare ${part}: a limiter has no defaults`);\n };\n if (typeof spec.key !== \"string\") missing(\"what its key is (key)\");\n else if (spec.key.trim().length === 0) problems.push(`${owner} names no key`);\n const policy = spec.policy as LoosePolicy | undefined;\n if (policy === undefined) missing(\"its policy (policy)\");\n else if (policy.type === \"token-bucket\") {\n if (policy.rate === undefined) missing(\"the rate of its bucket (policy.rate)\");\n else if (!safely(isRate, policy.rate)) problems.push(`${owner}'s rate is not a count for each unit of time, for example count/s`);\n else if (!finiteAbove(policy.rate)) problems.push(`${owner}'s rate is not a finite rate above zero`);\n if (policy.burst === undefined) missing(\"the size of its bucket (policy.burst)\");\n else if (!safely(isCount, policy.burst)) problems.push(`${owner}'s burst is not a count`);\n else if (!wholeCount(policy.burst)) problems.push(`${owner}'s burst is not a whole count above zero`);\n } else if (policy.type === \"sliding-window\") {\n if (policy.limit === undefined) missing(\"the limit of its window (policy.limit)\");\n else if (!safely(isCount, policy.limit)) problems.push(`${owner}'s limit is not a count`);\n else if (!wholeCount(policy.limit)) problems.push(`${owner}'s limit is not a whole count above zero`);\n if (policy.window === undefined) missing(\"the length of its window (policy.window)\");\n else if (!safely(isTime, policy.window)) problems.push(`${owner}'s window is not a time`);\n else if (!finiteAbove(policy.window)) problems.push(`${owner}'s window is not a finite time above zero`);\n } else problems.push(`${owner}'s policy ${String(policy.type)} is not \"token-bucket\" or \"sliding-window\"`);\n const store = spec.store as { kind?: string; dependency?: unknown; onStoreFailure?: unknown } | undefined;\n if (store === undefined) missing(`its store, { kind: \"local\" } or { kind: \"shared\", dependency, onStoreFailure } (store)`);\n else if (store.kind === \"shared\") {\n if (typeof store.dependency !== \"string\" || store.dependency.trim().length === 0)\n problems.push(`${owner}'s shared store names no dependency`);\n if (store.onStoreFailure === undefined) missing(`what a failure of its shared store does, \"open\" or \"closed\" (store.onStoreFailure)`);\n else if (store.onStoreFailure !== \"open\" && store.onStoreFailure !== \"closed\")\n problems.push(`${owner}'s onStoreFailure ${String(store.onStoreFailure)} is not \"open\" or \"closed\"`);\n } else if (store.kind !== \"local\") problems.push(`${owner}'s store ${String(store.kind)} is not \"local\" or \"shared\"`);\n const evict = spec.evict as Partial<LimiterEviction> | undefined;\n if (evict === undefined || evict.maxKeys === undefined) missing(\"the most keys that it holds (evict.maxKeys)\");\n else if (!safely(isCount, evict.maxKeys)) problems.push(`${owner}'s maxKeys is not a count`);\n else if (!wholeCount(evict.maxKeys)) problems.push(`${owner}'s maxKeys is not a whole count above zero: the count of keys has a bound`);\n return problems;\n};\n\n/** This function gives an amount in milliseconds, exactly where the units permit, as one number. */\nconst milliseconds = (amount: Quantity): number => r.toNumber(convertExact(r.fromNumber(amount.value), amount.unit, \"ms\"));\n/** This function gives a count as one number. */\nconst countOf = (amount: Quantity): number => r.toNumber(convertExact(r.fromNumber(amount.value), amount.unit, \"count\"));\n\n/**\n * This function gives the rule of a policy in numbers. The interval of a bucket is exact as a\n * rational, and it becomes one number only at the end. Thus 10 for each minute gives 6000 ms.\n */\nexport const limitRule = (policy: LimitPolicy): LimitRule => {\n if (policy.type === \"token-bucket\") {\n const perMs = convertExact(r.fromNumber(policy.rate.value), policy.rate.unit, \"count/ms\");\n return { type: \"token-bucket\", interval: r.toNumber(r.div(r.ONE, perMs)), burst: countOf(policy.burst) };\n }\n return { type: \"sliding-window\", limit: countOf(policy.limit), window: milliseconds(policy.window) };\n};\n\n/** This function gives a time in milliseconds as a quantity. */\nconst ms = (value: number): Quantity => ({ value, unit: \"ms\" });\n\n/**\n * This function gives the span after which an idle key is equal to a new key. That span is\n * `burst / rate` for a token bucket, and one window for a sliding window. A store can remove the key\n * after it, and no decision changes. It is also the longest `retryAfter` of a new key that the store\n * refuses at its cap.\n */\nexport const idleSpan = (policy: LimitPolicy): Quantity => {\n const rule = limitRule(policy);\n return ms(rule.type === \"token-bucket\" ? rule.interval * rule.burst : rule.window);\n};\n\n/**\n * This function gives the longest `retryAfter` of a refusal by the policy: one interval of the\n * bucket (`1 / rate`), or one window. A refusal at the cap of keys can be longer, up to `idleSpan`.\n */\nexport const longestRetryAfter = (policy: LimitPolicy): Quantity => {\n const rule = limitRule(policy);\n return ms(rule.type === \"token-bucket\" ? rule.interval : rule.window);\n};\n\n/**\n * This function gives a `retryAfter` in whole seconds, rounded up, as the header `Retry-After`\n * (RFC 9110) has it. A time over a whole second by less than one nanosecond rounds down to it,\n * because that part is an error of floating point.\n */\nexport const retryAfterSeconds = (retryAfter: Quantity): number => {\n const seconds = r.toNumber(convertExact(r.fromNumber(retryAfter.value), retryAfter.unit, \"s\"));\n return Math.max(0, Math.ceil(seconds - TOLERANCE / 1000));\n};\n\n/** This function gives the time at which a key state is equal to the state of a new key, in milliseconds. */\nexport const freeAt = (rule: LimitRule, state: KeyState): number => {\n if (state.type === \"token-bucket\") return state.full;\n const last = state.stamps[state.stamps.length - 1];\n return last === undefined ? Number.NEGATIVE_INFINITY : last + (rule.type === \"sliding-window\" ? rule.window : 0);\n};\n\n/** This function gives the capacity of a rule: the most units of one take. That is the `burst` of a bucket, or the `limit` of a window. */\nexport const capacityOf = (rule: LimitRule): number => (rule.type === \"token-bucket\" ? rule.burst : rule.limit);\n\n/**\n * This function gives the units of a take: 1 when they are absent. It throws for units that are not\n * a whole number of 1 or more, because such a take has no meaning.\n */\nexport const unitsOf = (units: number | undefined): number => {\n if (units === undefined) return 1;\n if (typeof units !== \"number\" || !Number.isSafeInteger(units) || units < 1)\n throw new RangeError(`the units of a take are a whole number of 1 or more, not ${String(units)}`);\n return units;\n};\n\n/** This function gives the capacity refusal of a take whose units are over the capacity of its rule, or `undefined`. */\nexport const overCapacity = (rule: LimitRule, units: number): CapacityRefused | undefined => {\n const capacity = capacityOf(rule);\n return units > capacity ? { allowed: false, cause: \"capacity\", units, capacity } : undefined;\n};\n\n/**\n * This function decides one take of `units` units (1 when absent) of a key at the time `now`, in\n * milliseconds, from the state of the key (`undefined` for a new key). It is the one decision of each\n * store in this process. A store in another process does the same arithmetic in its own atomic step.\n * - A take over the capacity of the rule (`capacityOf`) is refused with the cause `capacity`, and\n * the state does not change.\n * - A token bucket (GCRA): the store lets the take in when, with the take, the bucket is full\n * again in at most `burst` intervals. A refusal waits until `units` tokens are back.\n * - A sliding window: the store lets the take in when at most `limit - units` takes are in the\n * window. A refusal waits until enough of the oldest takes leave the window.\n * - A take of `units` units is the same as `units` takes of 1 at one time, when all of them are let in.\n */\nexport const decide = (rule: LimitRule, state: KeyState | undefined, now: number, units?: number): TakeStep => {\n const n = unitsOf(units);\n const over = overCapacity(rule, n);\n if (rule.type === \"token-bucket\") {\n const span = rule.interval * rule.burst;\n const full = state?.type === \"token-bucket\" ? Math.max(state.full, now) : now;\n if (over !== undefined) return { decision: over, state: { type: \"token-bucket\", full } };\n const next = full + rule.interval * n;\n if (next - now > span + TOLERANCE)\n return { decision: { allowed: false, retryAfter: ms(next - span - now), cause: \"limit\" }, state: { type: \"token-bucket\", full } };\n const remaining = Math.max(0, Math.floor((span - (next - now)) / rule.interval + TOLERANCE));\n return { decision: { allowed: true, remaining }, state: { type: \"token-bucket\", full: next } };\n }\n const held = state?.type === \"sliding-window\" ? state.stamps : [];\n // a take counts for one window from its time: it leaves the window at stamp + window\n const live = held.filter((stamp) => stamp + rule.window > now + TOLERANCE);\n if (over !== undefined) return { decision: over, state: { type: \"sliding-window\", stamps: live } };\n // the take fits when the oldest (live + n - limit) takes have left the window\n const excess = live.length + n - rule.limit;\n if (excess > 0)\n return { decision: { allowed: false, retryAfter: ms(live[excess - 1]! + rule.window - now), cause: \"limit\" }, state: { type: \"sliding-window\", stamps: live } };\n return {\n decision: { allowed: true, remaining: rule.limit - live.length - n },\n state: { type: \"sliding-window\", stamps: [...live, ...Array.from({ length: n }, () => now)] },\n };\n};\n"],"mappings":";;;;;;AA8KA,MAAM,YAAY;AAElB,MAAM,WAAW,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,OAAO;AACnH,MAAM,UAAU,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,GAAG;AAC9G,MAAM,UAAU,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,SAAS;;AAEpH,MAAM,UAAU,MAAiD,WAA0C;CACzG,IAAI;EACF,OAAO,KAAK,MAAM;CACpB,QAAQ;EACN,OAAO;CACT;AACF;AACA,MAAM,eAAe,WAA8B,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,OAAO,KAAK,KAAK,OAAO,QAAQ;AACvI,MAAM,cAAc,WAA8B,YAAY,MAAM,KAAK,OAAO,UAAUA,UAAE,SAAS,aAAaA,UAAE,WAAW,OAAO,KAAK,GAAG,OAAO,MAAM,OAAO,CAAC,CAAC;;;;;AAepK,MAAa,mBAAmB,MAAc,SAAqD;CACjG,MAAM,QAAQ,WAAW;CACzB,IAAI,SAAS,KAAA,KAAc,SAAqB,MAAM,OAAO,CAAC,GAAG,MAAM,wCAAwC;CAC/G,MAAM,WAAqB,CAAC;CAC5B,MAAM,WAAW,SAAuB;EACtC,SAAS,KAAK,GAAG,MAAM,oBAAoB,KAAK,4BAA4B;CAC9E;CACA,IAAI,OAAO,KAAK,QAAQ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;EAAE;EACnE,OAAO;GAAE,MAAM;GAAkB,QAAQ,CAAC,GAAG,MAAM,GAAG,MAAM,KAAK,EAAE,QAAQ,EAAE,SAAS,GAAG,CAAC;EAAE;CAC9F;AACF"}
1
+ {"version":3,"file":"policy-B23MY52l.js","names":["r"],"sources":["../src/limiter/policy.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertExact, convertible, rationals as r } from \"@mark1russell7/quantity\";\n\n/**\n * A token bucket gives each key a bucket of `burst` tokens. The bucket refills at `rate`, and each\n * take uses one token. Thus a key can make `burst` takes at once after an idle time, and then\n * `rate` takes in each unit of time.\n */\nexport interface TokenBucket {\n readonly type: \"token-bucket\";\n /** This rate is how fast the bucket refills: a count for each unit of time, for example `{ value: 10, unit: \"count/s\" }`. */\n readonly rate: Quantity;\n /** This count is the size of the bucket: the most takes in a sequence after an idle time. */\n readonly burst: Quantity;\n}\n\n/**\n * A sliding window gives each key at most `limit` takes in each `window`. Each take counts for one\n * window from its time, thus the window moves with the clock and has no fixed edges.\n */\nexport interface SlidingWindow {\n readonly type: \"sliding-window\";\n /** This count is the most takes of one key in one window. */\n readonly limit: Quantity;\n /** This time is the length of the window. */\n readonly window: Quantity;\n}\n\n/** A limit policy is the rule that a keyed limiter applies to each key, as data. It has no defaults. */\nexport type LimitPolicy = TokenBucket | SlidingWindow;\n\n/**\n * A store failure policy tells what a take does when a shared store fails. It has no default.\n * - `open`: the limiter lets the take in. The count is not known, thus `remaining` is 0.\n * - `closed`: the limiter refuses the take with the cause `store`. Its `retryAfter` is the longest\n * `retryAfter` of the policy (`longestRetryAfter`). Thus O29 and O30 apply to it too.\n */\nexport type StoreFailure = \"open\" | \"closed\";\n\n/**\n * A store spec tells where the counts of the keys are:\n * - `local`: in the memory of each replica. A limit L over N replicas is then L / N on each\n * replica. That sum holds only on average, when the balancer spreads the takes of each key evenly.\n * A local store does not fail, thus it has no `onStoreFailure`, and the limiter ignores one.\n * - `shared`: in a store that the replicas share, the dependency of that name. The store decides\n * each take in one atomic step, on its own clock. Thus the limit holds across the replicas.\n * `onStoreFailure` tells what a take does when the store fails.\n */\nexport type LimiterStoreSpec =\n | { readonly kind: \"local\" }\n | { readonly kind: \"shared\"; readonly dependency: string; readonly onStoreFailure: StoreFailure };\n\n/**\n * The eviction of a limiter bounds its keys. A store removes a key only when its state is equal to\n * the state of a new key. That is a bucket that is full again, or a window with no take in it.\n * Thus an eviction changes no decision.\n */\nexport interface LimiterEviction {\n /**\n * This count is the most keys that the store holds. At the cap, the store refuses a take of a new\n * key until a held key is idle for its span (`idleSpan`). A held key keeps its count.\n */\n readonly maxKeys: Quantity;\n}\n\n/** A limiter spec is the declaration of one keyed limiter. Each part is necessary, because the limiter has no defaults. */\nexport interface LimiterSpec {\n /** This text tells what the key of each take is, for example `tenant` or `principal`. The caller gives each key. */\n readonly key: string;\n readonly policy: LimitPolicy;\n readonly store: LimiterStoreSpec;\n readonly evict: LimiterEviction;\n}\n\n/** A limiter is a keyed limiter in the description of a service: its name and its spec. */\nexport interface Limiter extends LimiterSpec {\n readonly name: string;\n}\n\n/**\n * A wait cause tells why a take is refused for a time:\n * - `limit`: the key used its limit.\n * - `cap`: the store holds its cap of keys, and the key is new.\n * - `store`: the shared store failed, and its spec declares `onStoreFailure: \"closed\"`.\n */\nexport type WaitCause = \"limit\" | \"cap\" | \"store\";\n\n/**\n * A refusal cause tells why a take is refused: a wait cause, or `capacity`. The cause `capacity` is\n * a take whose units are over the capacity of the policy. No wait lets it in.\n */\nexport type RefusalCause = WaitCause | \"capacity\";\n\n/**\n * A permitted take used its units of its key. `remaining` is the count of units that the key can\n * take at this time.\n */\nexport interface Allowed {\n readonly allowed: true;\n readonly remaining: number;\n /** This text is the failure of a shared store, when `onStoreFailure: \"open\"` lets the take in. */\n readonly failure?: string | undefined;\n}\n\n/**\n * A wait refusal used nothing. `retryAfter` is the time until the limiter lets the same take in, when\n * no other take comes first. It is always above zero.\n */\nexport interface WaitRefused {\n readonly allowed: false;\n readonly cause: WaitCause;\n readonly retryAfter: Quantity;\n /** This text is the failure of a shared store, for the cause `store`. */\n readonly failure?: string | undefined;\n}\n\n/**\n * A capacity refusal used nothing, and the same take is refused at each time. Its `units` are over\n * the `capacity` of the policy: the `burst` of a bucket, or the `limit` of a window. A caller can\n * split the take into parts of at most `capacity` units.\n */\nexport interface CapacityRefused {\n readonly allowed: false;\n readonly cause: \"capacity\";\n readonly units: number;\n readonly capacity: number;\n}\n\n/**\n * A refused take used nothing. The cause tells the type: a `WaitRefused` has a `retryAfter`, and a\n * `CapacityRefused` has none. Thus a caller examines the cause before it reads `retryAfter`.\n */\nexport type Refused = WaitRefused | CapacityRefused;\n\n/** A decision is the answer of a limiter to one take. */\nexport type Decision = Allowed | Refused;\n\n/**\n * A limit rule is a policy in numbers, which a store applies: each time in milliseconds, and each\n * count as a number. A store in another process, for example a script of Redis, gets these numbers.\n */\nexport type LimitRule =\n | {\n readonly type: \"token-bucket\";\n /** This time is the refill of one token, in milliseconds. */\n readonly interval: number;\n readonly burst: number;\n }\n | {\n readonly type: \"sliding-window\";\n readonly limit: number;\n /** This time is the length of the window, in milliseconds. */\n readonly window: number;\n };\n\n/**\n * A key state is what a store keeps for one key:\n * - A token bucket keeps the time at which its bucket is full again (`full`, in milliseconds).\n * - A sliding window keeps the time of each permitted take in the window, the oldest first.\n */\nexport type KeyState =\n | { readonly type: \"token-bucket\"; readonly full: number }\n | { readonly type: \"sliding-window\"; readonly stamps: readonly number[] };\n\n/** A step is the decision of one take, and the state of its key after the take. A refusal keeps the count of the key. */\nexport interface TakeStep {\n readonly decision: Decision;\n readonly state: KeyState;\n}\n\n/**\n * This tolerance is one nanosecond, in milliseconds. A comparison of times permits it, because a\n * rate of 3 for each second gives an interval that floating point cannot hold exactly.\n */\nconst TOLERANCE = 1e-6;\n\nconst isCount = (amount: Quantity | undefined): boolean => amount !== undefined && convertible(amount.unit, \"count\");\nconst isTime = (amount: Quantity | undefined): boolean => amount !== undefined && convertible(amount.unit, \"s\");\nconst isRate = (amount: Quantity | undefined): boolean => amount !== undefined && convertible(amount.unit, \"count/s\");\n/** This function tells if a unit converts, also for a unit that the quantity package does not know. */\nconst safely = (test: (amount: Quantity | undefined) => boolean, amount: Quantity | undefined): boolean => {\n try {\n return test(amount);\n } catch {\n return false;\n }\n};\nconst finiteAbove = (amount: Quantity): boolean => typeof amount.value === \"number\" && Number.isFinite(amount.value) && amount.value > 0;\nconst wholeCount = (amount: Quantity): boolean => finiteAbove(amount) && Number.isInteger(r.toNumber(convertExact(r.fromNumber(amount.value), amount.unit, \"count\")));\n\n/** A loose policy is a policy from any source, with each part optional, for the check of its parts. */\ninterface LoosePolicy {\n readonly type?: string;\n readonly rate?: Quantity;\n readonly burst?: Quantity;\n readonly limit?: Quantity;\n readonly window?: Quantity;\n}\n\n/**\n * This function gives the problems of a limiter spec. `describe()` and `keyedLimiter` refuse a spec\n * with a problem. A part that is absent is a problem, because the limiter has no defaults.\n */\nexport const limiterProblems = (name: string, spec: Partial<LimiterSpec> | undefined): string[] => {\n const owner = `limiter ${name}`;\n if (spec === undefined || (spec as unknown) === null) return [`${owner} has no spec: a limiter has no defaults`];\n const problems: string[] = [];\n const missing = (part: string): void => {\n problems.push(`${owner} does not declare ${part}: a limiter has no defaults`);\n };\n if (typeof spec.key !== \"string\") missing(\"what its key is (key)\");\n else if (spec.key.trim().length === 0) problems.push(`${owner} names no key`);\n const policy = spec.policy as LoosePolicy | undefined;\n if (policy === undefined) missing(\"its policy (policy)\");\n else if (policy.type === \"token-bucket\") {\n if (policy.rate === undefined) missing(\"the rate of its bucket (policy.rate)\");\n else if (!safely(isRate, policy.rate)) problems.push(`${owner}'s rate is not a count for each unit of time, for example count/s`);\n else if (!finiteAbove(policy.rate)) problems.push(`${owner}'s rate is not a finite rate above zero`);\n if (policy.burst === undefined) missing(\"the size of its bucket (policy.burst)\");\n else if (!safely(isCount, policy.burst)) problems.push(`${owner}'s burst is not a count`);\n else if (!wholeCount(policy.burst)) problems.push(`${owner}'s burst is not a whole count above zero`);\n } else if (policy.type === \"sliding-window\") {\n if (policy.limit === undefined) missing(\"the limit of its window (policy.limit)\");\n else if (!safely(isCount, policy.limit)) problems.push(`${owner}'s limit is not a count`);\n else if (!wholeCount(policy.limit)) problems.push(`${owner}'s limit is not a whole count above zero`);\n if (policy.window === undefined) missing(\"the length of its window (policy.window)\");\n else if (!safely(isTime, policy.window)) problems.push(`${owner}'s window is not a time`);\n else if (!finiteAbove(policy.window)) problems.push(`${owner}'s window is not a finite time above zero`);\n } else problems.push(`${owner}'s policy ${String(policy.type)} is not \"token-bucket\" or \"sliding-window\"`);\n const store = spec.store as { kind?: string; dependency?: unknown; onStoreFailure?: unknown } | undefined;\n if (store === undefined) missing(`its store, { kind: \"local\" } or { kind: \"shared\", dependency, onStoreFailure } (store)`);\n else if (store.kind === \"shared\") {\n if (typeof store.dependency !== \"string\" || store.dependency.trim().length === 0)\n problems.push(`${owner}'s shared store names no dependency`);\n if (store.onStoreFailure === undefined) missing(`what a failure of its shared store does, \"open\" or \"closed\" (store.onStoreFailure)`);\n else if (store.onStoreFailure !== \"open\" && store.onStoreFailure !== \"closed\")\n problems.push(`${owner}'s onStoreFailure ${String(store.onStoreFailure)} is not \"open\" or \"closed\"`);\n } else if (store.kind !== \"local\") problems.push(`${owner}'s store ${String(store.kind)} is not \"local\" or \"shared\"`);\n const evict = spec.evict as Partial<LimiterEviction> | undefined;\n if (evict === undefined || evict.maxKeys === undefined) missing(\"the most keys that it holds (evict.maxKeys)\");\n else if (!safely(isCount, evict.maxKeys)) problems.push(`${owner}'s maxKeys is not a count`);\n else if (!wholeCount(evict.maxKeys)) problems.push(`${owner}'s maxKeys is not a whole count above zero: the count of keys has a bound`);\n return problems;\n};\n\n/** This function gives an amount in milliseconds, exactly where the units permit, as one number. */\nconst milliseconds = (amount: Quantity): number => r.toNumber(convertExact(r.fromNumber(amount.value), amount.unit, \"ms\"));\n/** This function gives a count as one number. */\nconst countOf = (amount: Quantity): number => r.toNumber(convertExact(r.fromNumber(amount.value), amount.unit, \"count\"));\n\n/**\n * This function gives the rule of a policy in numbers. The interval of a bucket is exact as a\n * rational, and it becomes one number only at the end. Thus 10 for each minute gives 6000 ms.\n */\nexport const limitRule = (policy: LimitPolicy): LimitRule => {\n if (policy.type === \"token-bucket\") {\n const perMs = convertExact(r.fromNumber(policy.rate.value), policy.rate.unit, \"count/ms\");\n return { type: \"token-bucket\", interval: r.toNumber(r.div(r.ONE, perMs)), burst: countOf(policy.burst) };\n }\n return { type: \"sliding-window\", limit: countOf(policy.limit), window: milliseconds(policy.window) };\n};\n\n/** This function gives a time in milliseconds as a quantity. */\nconst ms = (value: number): Quantity => ({ value, unit: \"ms\" });\n\n/**\n * This function gives the span after which an idle key is equal to a new key. That span is\n * `burst / rate` for a token bucket, and one window for a sliding window. A store can remove the key\n * after it, and no decision changes. It is also the longest `retryAfter` of a new key that the store\n * refuses at its cap.\n */\nexport const idleSpan = (policy: LimitPolicy): Quantity => {\n const rule = limitRule(policy);\n return ms(rule.type === \"token-bucket\" ? rule.interval * rule.burst : rule.window);\n};\n\n/**\n * This function gives the longest `retryAfter` of a refusal by the policy: one interval of the\n * bucket (`1 / rate`), or one window. A refusal at the cap of keys can be longer, up to `idleSpan`.\n */\nexport const longestRetryAfter = (policy: LimitPolicy): Quantity => {\n const rule = limitRule(policy);\n return ms(rule.type === \"token-bucket\" ? rule.interval : rule.window);\n};\n\n/**\n * This function gives a `retryAfter` in whole seconds, rounded up, as the header `Retry-After`\n * (RFC 9110) has it. A time over a whole second by less than one nanosecond rounds down to it,\n * because that part is an error of floating point.\n */\nexport const retryAfterSeconds = (retryAfter: Quantity): number => {\n const seconds = r.toNumber(convertExact(r.fromNumber(retryAfter.value), retryAfter.unit, \"s\"));\n return Math.max(0, Math.ceil(seconds - TOLERANCE / 1000));\n};\n\n/** This function gives the time at which a key state is equal to the state of a new key, in milliseconds. */\nexport const freeAt = (rule: LimitRule, state: KeyState): number => {\n if (state.type === \"token-bucket\") return state.full;\n const last = state.stamps[state.stamps.length - 1];\n return last === undefined ? Number.NEGATIVE_INFINITY : last + (rule.type === \"sliding-window\" ? rule.window : 0);\n};\n\n/** This function gives the capacity of a rule: the most units of one take. That is the `burst` of a bucket, or the `limit` of a window. */\nexport const capacityOf = (rule: LimitRule): number => (rule.type === \"token-bucket\" ? rule.burst : rule.limit);\n\n/**\n * This function gives the units of a take: 1 when they are absent. It throws for units that are not\n * a whole number of 1 or more, because such a take has no meaning.\n */\nexport const unitsOf = (units: number | undefined): number => {\n if (units === undefined) return 1;\n if (typeof units !== \"number\" || !Number.isSafeInteger(units) || units < 1)\n throw new RangeError(`the units of a take are a whole number of 1 or more, not ${String(units)}`);\n return units;\n};\n\n/** This function gives the capacity refusal of a take whose units are over the capacity of its rule, or `undefined`. */\nexport const overCapacity = (rule: LimitRule, units: number): CapacityRefused | undefined => {\n const capacity = capacityOf(rule);\n return units > capacity ? { allowed: false, cause: \"capacity\", units, capacity } : undefined;\n};\n\n/**\n * This function decides one take of `units` units (1 when absent) of a key at the time `now`, in\n * milliseconds, from the state of the key (`undefined` for a new key). It is the one decision of each\n * store in this process. A store in another process does the same arithmetic in its own atomic step.\n * - A take over the capacity of the rule (`capacityOf`) is refused with the cause `capacity`, and\n * the state does not change.\n * - A token bucket (GCRA): the store lets the take in when, with the take, the bucket is full\n * again in at most `burst` intervals. A refusal waits until `units` tokens are back.\n * - A sliding window: the store lets the take in when at most `limit - units` takes are in the\n * window. A refusal waits until enough of the oldest takes leave the window.\n * - A take of `units` units is the same as `units` takes of 1 at one time, when all of them are let in.\n */\nexport const decide = (rule: LimitRule, state: KeyState | undefined, now: number, units?: number): TakeStep => {\n const n = unitsOf(units);\n const over = overCapacity(rule, n);\n if (rule.type === \"token-bucket\") {\n const span = rule.interval * rule.burst;\n const full = state?.type === \"token-bucket\" ? Math.max(state.full, now) : now;\n if (over !== undefined) return { decision: over, state: { type: \"token-bucket\", full } };\n const next = full + rule.interval * n;\n if (next - now > span + TOLERANCE)\n return { decision: { allowed: false, retryAfter: ms(next - span - now), cause: \"limit\" }, state: { type: \"token-bucket\", full } };\n const remaining = Math.max(0, Math.floor((span - (next - now)) / rule.interval + TOLERANCE));\n return { decision: { allowed: true, remaining }, state: { type: \"token-bucket\", full: next } };\n }\n const held = state?.type === \"sliding-window\" ? state.stamps : [];\n // a take counts for one window from its time: it leaves the window at stamp + window\n const live = held.filter((stamp) => stamp + rule.window > now + TOLERANCE);\n if (over !== undefined) return { decision: over, state: { type: \"sliding-window\", stamps: live } };\n // the take fits when the oldest (live + n - limit) takes have left the window\n const excess = live.length + n - rule.limit;\n if (excess > 0)\n return { decision: { allowed: false, retryAfter: ms(live[excess - 1]! + rule.window - now), cause: \"limit\" }, state: { type: \"sliding-window\", stamps: live } };\n return {\n decision: { allowed: true, remaining: rule.limit - live.length - n },\n state: { type: \"sliding-window\", stamps: [...live, ...Array.from({ length: n }, () => now)] },\n };\n};\n"],"mappings":";;;;;;AA8KA,MAAM,YAAY;AAElB,MAAM,WAAW,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,OAAO;AACnH,MAAM,UAAU,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,GAAG;AAC9G,MAAM,UAAU,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,SAAS;;AAEpH,MAAM,UAAU,MAAiD,WAA0C;CACzG,IAAI;EACF,OAAO,KAAK,MAAM;CACpB,QAAQ;EACN,OAAO;CACT;AACF;AACA,MAAM,eAAe,WAA8B,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,OAAO,KAAK,KAAK,OAAO,QAAQ;AACvI,MAAM,cAAc,WAA8B,YAAY,MAAM,KAAK,OAAO,UAAUA,UAAE,SAAS,aAAaA,UAAE,WAAW,OAAO,KAAK,GAAG,OAAO,MAAM,OAAO,CAAC,CAAC;;;;;AAepK,MAAa,mBAAmB,MAAc,SAAqD;CACjG,MAAM,QAAQ,WAAW;CACzB,IAAI,SAAS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SAAS;GAAO,YAAY,GAAG,KAAK,SAAS,KAAM,KAAK,SAAS,GAAG;GAAG,OAAO;EAAQ;EAAG,OAAO;GAAE,MAAM;GAAkB,QAAQ;EAAK;CAAE;CAChK,OAAO;EACL,UAAU;GAAE,SAAS;GAAM,WAAW,KAAK,QAAQ,KAAK,SAAS;EAAE;EACnE,OAAO;GAAE,MAAM;GAAkB,QAAQ,CAAC,GAAG,MAAM,GAAG,MAAM,KAAK,EAAE,QAAQ,EAAE,SAAS,GAAG,CAAC;EAAE;CAC9F;AACF"}
@@ -1,5 +1,4 @@
1
1
  import { Quantity } from "@mark1russell7/quantity";
2
- //#region src/limiter/policy.d.ts
3
2
  /**
4
3
  * A token bucket gives each key a bucket of `burst` tokens. The bucket refills at `rate`, and each
5
4
  * take uses one token. Thus a key can make `burst` takes at once after an idle time, and then
@@ -207,6 +206,5 @@ declare const overCapacity: (rule: LimitRule, units: number) => CapacityRefused
207
206
  * - A take of `units` units is the same as `units` takes of 1 at one time, when all of them are let in.
208
207
  */
209
208
  declare const decide: (rule: LimitRule, state: KeyState | undefined, now: number, units?: number) => TakeStep;
210
- //#endregion
211
209
  export { limitRule as C, retryAfterSeconds as D, overCapacity as E, unitsOf as O, idleSpan as S, longestRetryAfter as T, WaitCause as _, LimitPolicy as a, decide as b, LimiterEviction as c, RefusalCause as d, Refused as f, TokenBucket as g, TakeStep as h, KeyState as i, LimiterSpec as l, StoreFailure as m, CapacityRefused as n, LimitRule as o, SlidingWindow as p, Decision as r, Limiter as s, Allowed as t, LimiterStoreSpec as u, WaitRefused as v, limiterProblems as w, freeAt as x, capacityOf as y };
212
- //# sourceMappingURL=policy-CwYR95Sz.d.ts.map
210
+ //# sourceMappingURL=policy-CBcK2XGg.d.ts.map
@@ -1,6 +1,5 @@
1
1
  import { n as Clock } from "./clock-DpVgpY4h.js";
2
- import { c as Logger } from "./logger-BN2BfPgU.js";
3
- //#region src/host/ports.d.ts
2
+ import { c as Logger } from "./logger-B6drv9w0.js";
4
3
  /** These options go with one command: the folder that it runs in, and the most time that it can take. */
5
4
  interface CommandOptions {
6
5
  readonly cwd?: string | undefined;
@@ -120,6 +119,5 @@ interface HostPorts {
120
119
  }
121
120
  /** This function joins the parts of a path with the separator of the platform. */
122
121
  declare const joinPath: (platform: string, ...parts: readonly string[]) => string;
123
- //#endregion
124
122
  export { FilePort as a, ProcessMark as c, StopSignal as d, joinPath as f, CommandResult as i, ProcessesPort as l, CommandOptions as n, HostPorts as o, CommandPort as r, NetPort as s, ChildHandle as t, SpawnRequest as u };
125
- //# sourceMappingURL=ports-CSr7qWrA.d.ts.map
123
+ //# sourceMappingURL=ports-DZoipkSD.d.ts.map
@@ -1,4 +1,4 @@
1
- //#region src/process.ts
1
+ // src/process.ts
2
2
  /** These are the signals that the runtime handles. */
3
3
  const EXIT_SIGNALS = [
4
4
  "SIGINT",
@@ -165,7 +165,6 @@ const embeddedProcess = () => {
165
165
  })
166
166
  };
167
167
  };
168
- //#endregion
169
168
  export { isExitCode as a, matchesMessage as c, embeddedProcess as i, nodeProcess as l, PROCESS_TRIGGERS as n, isExitSignal as o, UNCAUGHT_ORIGINS as r, isMessageShape as s, EXIT_SIGNALS as t, processPortOf as u };
170
169
 
171
- //# sourceMappingURL=process-DG_im2zc.js.map
170
+ //# sourceMappingURL=process-Oe0Abbsm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"process-DG_im2zc.js","names":[],"sources":["../src/process.ts"],"sourcesContent":["/** An exit signal is a signal that asks the process to stop: each one starts the shutdown. */\nexport type ExitSignal = \"SIGINT\" | \"SIGTERM\" | \"SIGQUIT\";\n\n/** These are the signals that the runtime handles. */\nexport const EXIT_SIGNALS: readonly ExitSignal[] = [\"SIGINT\", \"SIGTERM\", \"SIGQUIT\"];\n\n/**\n * A process trigger is an event of the process, other than a signal, that starts the shutdown. A\n * declaration opts in to each one (`svc.trigger`):\n * - `stdin-close`: the standard input ends or closes, as when the parent of a stdio child goes away.\n * The process must read its input, as a stdio transport does, or Node does not see the end.\n * - `ipc-close`: the IPC channel to the parent process closes.\n * - `ipc-message`: a message on the IPC channel matches a declared shape. Windows cannot give a\n * child a SIGTERM that the child can catch, thus a parent sends a message.\n */\nexport type ProcessTrigger = \"stdin-close\" | \"ipc-close\" | \"ipc-message\";\n\n/** These are the process triggers that a declaration can opt in to. */\nexport const PROCESS_TRIGGERS: readonly ProcessTrigger[] = [\"stdin-close\", \"ipc-close\", \"ipc-message\"];\n\n/** An exit trigger is an event that starts the shutdown: an exit signal, or a declared process trigger. */\nexport type ExitTrigger = ExitSignal | ProcessTrigger;\n\n/**\n * An uncaught origin tells how an error that no code caught came to the process. It is an exception\n * that no code caught, or a rejection of a promise that no code handled.\n */\nexport type UncaughtOrigin = \"uncaughtException\" | \"unhandledRejection\";\n\n/** These are the origins of the errors that the option `uncaught` of `run()` receives. */\nexport const UNCAUGHT_ORIGINS: readonly UncaughtOrigin[] = [\"uncaughtException\", \"unhandledRejection\"];\n\n/** This function tells if a number is an exit code of a process: a whole number from 0 to 255. */\nexport const isExitCode = (code: number): boolean => Number.isInteger(code) && code >= 0 && code <= 255;\n\n/** This function tells if a trigger is an exit signal. A repeat signal obeys `onRepeatSignal`. */\nexport const isExitSignal = (trigger: string): trigger is ExitSignal =>\n (EXIT_SIGNALS as readonly string[]).includes(trigger);\n\n/**\n * A message shape is a value of JSON that a message of the IPC channel can match. A string, a\n * number, a boolean or null matches an equal message. An object matches a message that has each of\n * its fields, and each value of the field matches. An array matches an array of the same length, item by item.\n */\nexport type MessageShape = string | number | boolean | null | readonly MessageShape[] | { readonly [field: string]: MessageShape };\n\n/** This function tells if a value is a message shape: a value of JSON, with no function and no undefined. */\nexport const isMessageShape = (value: unknown): value is MessageShape => {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (Array.isArray(value)) return value.every(isMessageShape);\n if (typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n return (prototype === Object.prototype || prototype === null) && Object.values(value).every(isMessageShape);\n};\n\n/** This function tells if a message of the IPC channel matches a shape. */\nexport const matchesMessage = (shape: MessageShape, message: unknown): boolean => {\n if (shape === null || typeof shape !== \"object\") return Object.is(shape, message);\n if (Array.isArray(shape)) {\n const items: readonly MessageShape[] = shape;\n return Array.isArray(message) && message.length === items.length && items.every((item, at) => matchesMessage(item, message[at]));\n }\n if (message === null || typeof message !== \"object\" || Array.isArray(message)) return false;\n const fields = message as Readonly<Record<string, unknown>>;\n return Object.entries(shape).every(([field, value]) => Object.hasOwn(fields, field) && matchesMessage(value, fields[field]));\n};\n\n/**\n * A process port is the part of the process that the runtime uses: its exit triggers, its output\n * and its exit. The runtime owns the handlers, because Node as PID 1 without a handler ignores\n * SIGTERM. Only the runtime ends the process, and library code does not. A test gives a fake port,\n * sends triggers, and reads the exit code.\n */\nexport interface ProcessPort {\n /**\n * This method adds a handler for a trigger, and gives the function that removes it. The runtime\n * asks for a process trigger only when the declaration opts in to it. For `ipc-message`, the\n * handler gets each message of the IPC channel, and the runtime matches it.\n */\n on(trigger: ExitTrigger, handler: (message?: unknown) => void): () => void;\n /**\n * This method adds a handler for each error that no code caught, and gives the function that\n * removes it. The runtime asks for it only when `run()` gets the option `uncaught`. A port without\n * this method gets no handler, as the embedded port.\n */\n onUncaught?(handler: (error: unknown, origin: UncaughtOrigin) => void): () => void;\n /**\n * This method writes each buffered line of the output, and its promise ends when the output is\n * written. The stage `flush the output` uses it, in the cap of that stage.\n */\n flush?(): Promise<void> | void;\n /**\n * This method keeps the process alive, and gives the function that releases it. The lifecycle\n * holds its process from its start to its exit, as a listening socket does. Thus a process whose\n * timers do not keep it alive does not end in the middle of its work. It keeps its teardown and its exit code.\n */\n hold?(): () => void;\n /** This method ends the process with a code: the code of the exit request, 1 after an error, or 0. */\n exit(code: number): void;\n}\n\n/** A host stream is the part of a stream of Node that the port uses. */\nexport interface HostStream {\n readonly writable?: boolean;\n readonly destroyed?: boolean;\n readonly readableEnded?: boolean;\n write(chunk: string, done: (error?: unknown) => void): boolean;\n on(event: string, handler: () => void): unknown;\n off(event: string, handler: () => void): unknown;\n}\n\n/** A process host is the part of the process of Node that the port uses. Its event `message` gives the message of the IPC channel. */\nexport interface ProcessHost {\n on(signal: string, handler: (message?: unknown) => void): unknown;\n off(signal: string, handler: (message?: unknown) => void): unknown;\n exit(code: number): unknown;\n readonly stdin?: HostStream | undefined;\n readonly stdout?: HostStream | undefined;\n readonly stderr?: HostStream | undefined;\n}\n\n/** This time is the interval of the timer of a hold, the most that a timer of Node accepts. */\nconst HOLD_INTERVAL = 0x7fffffff;\n\n/** This function adds a handler to some events of an emitter. The handler operates one time at most. */\nconst once = (emitter: HostStream | ProcessHost, events: readonly string[], handler: () => void): (() => void) => {\n let called = false;\n const fire = (): void => {\n if (called) return;\n called = true;\n handler();\n };\n for (const event of events) emitter.on(event, fire);\n return () => {\n for (const event of events) emitter.off(event, fire);\n };\n};\n\n/** This function gives a promise that ends when the data before it in a stream is written. */\nconst written = (stream: HostStream | undefined): Promise<void> =>\n new Promise<void>((resolve) => {\n if (stream === undefined || stream.destroyed === true || stream.writable === false) {\n resolve();\n return;\n }\n try {\n // the callback of an empty write comes after each write before it\n stream.write(\"\", () => resolve());\n } catch {\n resolve();\n }\n });\n\n/**\n * This function makes a process port on a host. `find` gives the host at each use, or undefined\n * when the platform has no process. Then the use throws.\n */\nexport const processPortOf = (find: () => ProcessHost | undefined): ProcessPort => {\n const hostProcess = (): ProcessHost => {\n const host = find();\n if (host === undefined) throw new Error(\"no process: give the runtime a process port\");\n return host;\n };\n return {\n on(trigger, handler) {\n const host = hostProcess();\n if (trigger === \"stdin-close\") {\n const input = host.stdin;\n if (input === undefined) return () => {};\n // an input that ended before the handler was added still starts the shutdown\n if (input.readableEnded === true) {\n let live = true;\n queueMicrotask(() => {\n if (live) handler();\n });\n return () => {\n live = false;\n };\n }\n return once(input, [\"end\", \"close\"], handler);\n }\n if (trigger === \"ipc-close\") return once(host, [\"disconnect\"], handler);\n if (trigger === \"ipc-message\") {\n // each message goes to the runtime, which matches it with the declared shapes\n const receive = (message?: unknown): void => handler(message);\n host.on(\"message\", receive);\n return () => {\n host.off(\"message\", receive);\n };\n }\n host.on(trigger, handler);\n return () => {\n host.off(trigger, handler);\n };\n },\n onUncaught(handler) {\n const host = hostProcess();\n // a handler of each origin: Node then does not end the process, and the runtime does the shutdown\n const offs = UNCAUGHT_ORIGINS.map((origin) => {\n const receive = (error?: unknown): void => handler(error, origin);\n host.on(origin, receive);\n return () => {\n host.off(origin, receive);\n };\n });\n return () => {\n for (const off of offs) off();\n };\n },\n async flush() {\n const host = hostProcess();\n await Promise.all([written(host.stdout), written(host.stderr)]);\n },\n hold() {\n hostProcess();\n // one interval that keeps the event loop alive: its timer does nothing, and the release stops it\n const timer = setInterval(() => {}, HOLD_INTERVAL);\n let held = true;\n return () => {\n if (!held) return;\n held = false;\n clearInterval(timer);\n };\n },\n exit(code) {\n hostProcess().exit(code);\n },\n };\n};\n\n/** This port is the process of Node. */\nexport const nodeProcess: ProcessPort = processPortOf(() => (globalThis as { process?: ProcessHost }).process);\n\n/** An embedded process port records the exit code of a lifecycle that does not own its process. */\nexport interface EmbeddedProcess extends ProcessPort {\n /** This code is the code of the exit request of the lifecycle, or null before that request. */\n readonly exitCode: number | null;\n /** This promise ends with the exit code when the lifecycle asks for its exit. */\n readonly exited: Promise<number>;\n}\n\n/**\n * This function gives a process port for a lifecycle in a process that another part owns. That\n * part is a script, a test of an application, or a library entry. The port adds no handler of a signal or of\n * a trigger, it does not hold the process, and its `exit` only records the code. The caller stops\n * the lifecycle with `life.shutdown()`. A process with a service of its own gives its parts to\n * that service, and does not use this port.\n */\nexport const embeddedProcess = (): EmbeddedProcess => {\n let code: number | null = null;\n let resolve: (code: number) => void = () => {};\n const exited = new Promise<number>((done) => {\n resolve = done;\n });\n return {\n on() {\n // the owner of the process keeps its signals and triggers\n return () => {};\n },\n exit(requested) {\n if (code !== null) return;\n code = requested;\n resolve(requested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X,KAAK,IAAI,SAAS,OAAO;GAC3B;EACF;EACA,WAAW,SAAS;GAClB,MAAM,OAAO,YAAY;GAEzB,MAAM,OAAO,iBAAiB,KAAK,WAAW;IAC5C,MAAM,WAAW,UAA0B,QAAQ,OAAO,MAAM;IAChE,KAAK,GAAG,QAAQ,OAAO;IACvB,aAAa;KACX,KAAK,IAAI,QAAQ,OAAO;IAC1B;GACF,CAAC;GACD,aAAa;IACX,KAAK,MAAM,OAAO,MAAM,IAAI;GAC9B;EACF;EACA,MAAM,QAAQ;GACZ,MAAM,OAAO,YAAY;GACzB,MAAM,QAAQ,IAAI,CAAC,QAAQ,KAAK,MAAM,GAAG,QAAQ,KAAK,MAAM,CAAC,CAAC;EAChE;EACA,OAAO;GACL,YAAY;GAEZ,MAAM,QAAQ,kBAAkB,CAAC,GAAG,aAAa;GACjD,IAAI,OAAO;GACX,aAAa;IACX,IAAI,CAAC,MAAM;IACX,OAAO;IACP,cAAc,KAAK;GACrB;EACF;EACA,KAAK,MAAM;GACT,YAAY,CAAC,CAAC,KAAK,IAAI;EACzB;CACF;AACF;;AAGA,MAAa,cAA2B,oBAAqB,WAAyC,OAAO;;;;;;;;AAiB7G,MAAa,wBAAyC;CACpD,IAAI,OAAsB;CAC1B,IAAI,gBAAwC,CAAC;CAI7C,OAAO;EACL,KAAK;GAEH,aAAa,CAAC;EAChB;EACA,KAAK,WAAW;GACd,IAAI,SAAS,MAAM;GACnB,OAAO;GACP,QAAQ,SAAS;EACnB;EACA,IAAI,WAAW;GACb,OAAO;EACT;EACA,QAAA,IAhBiB,SAAiB,SAAS;GAC3C,UAAU;EACZ,CAcO;CACP;AACF"}
1
+ {"version":3,"file":"process-Oe0Abbsm.js","names":[],"sources":["../src/process.ts"],"sourcesContent":["/** An exit signal is a signal that asks the process to stop: each one starts the shutdown. */\nexport type ExitSignal = \"SIGINT\" | \"SIGTERM\" | \"SIGQUIT\";\n\n/** These are the signals that the runtime handles. */\nexport const EXIT_SIGNALS: readonly ExitSignal[] = [\"SIGINT\", \"SIGTERM\", \"SIGQUIT\"];\n\n/**\n * A process trigger is an event of the process, other than a signal, that starts the shutdown. A\n * declaration opts in to each one (`svc.trigger`):\n * - `stdin-close`: the standard input ends or closes, as when the parent of a stdio child goes away.\n * The process must read its input, as a stdio transport does, or Node does not see the end.\n * - `ipc-close`: the IPC channel to the parent process closes.\n * - `ipc-message`: a message on the IPC channel matches a declared shape. Windows cannot give a\n * child a SIGTERM that the child can catch, thus a parent sends a message.\n */\nexport type ProcessTrigger = \"stdin-close\" | \"ipc-close\" | \"ipc-message\";\n\n/** These are the process triggers that a declaration can opt in to. */\nexport const PROCESS_TRIGGERS: readonly ProcessTrigger[] = [\"stdin-close\", \"ipc-close\", \"ipc-message\"];\n\n/** An exit trigger is an event that starts the shutdown: an exit signal, or a declared process trigger. */\nexport type ExitTrigger = ExitSignal | ProcessTrigger;\n\n/**\n * An uncaught origin tells how an error that no code caught came to the process. It is an exception\n * that no code caught, or a rejection of a promise that no code handled.\n */\nexport type UncaughtOrigin = \"uncaughtException\" | \"unhandledRejection\";\n\n/** These are the origins of the errors that the option `uncaught` of `run()` receives. */\nexport const UNCAUGHT_ORIGINS: readonly UncaughtOrigin[] = [\"uncaughtException\", \"unhandledRejection\"];\n\n/** This function tells if a number is an exit code of a process: a whole number from 0 to 255. */\nexport const isExitCode = (code: number): boolean => Number.isInteger(code) && code >= 0 && code <= 255;\n\n/** This function tells if a trigger is an exit signal. A repeat signal obeys `onRepeatSignal`. */\nexport const isExitSignal = (trigger: string): trigger is ExitSignal =>\n (EXIT_SIGNALS as readonly string[]).includes(trigger);\n\n/**\n * A message shape is a value of JSON that a message of the IPC channel can match. A string, a\n * number, a boolean or null matches an equal message. An object matches a message that has each of\n * its fields, and each value of the field matches. An array matches an array of the same length, item by item.\n */\nexport type MessageShape = string | number | boolean | null | readonly MessageShape[] | { readonly [field: string]: MessageShape };\n\n/** This function tells if a value is a message shape: a value of JSON, with no function and no undefined. */\nexport const isMessageShape = (value: unknown): value is MessageShape => {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (Array.isArray(value)) return value.every(isMessageShape);\n if (typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n return (prototype === Object.prototype || prototype === null) && Object.values(value).every(isMessageShape);\n};\n\n/** This function tells if a message of the IPC channel matches a shape. */\nexport const matchesMessage = (shape: MessageShape, message: unknown): boolean => {\n if (shape === null || typeof shape !== \"object\") return Object.is(shape, message);\n if (Array.isArray(shape)) {\n const items: readonly MessageShape[] = shape;\n return Array.isArray(message) && message.length === items.length && items.every((item, at) => matchesMessage(item, message[at]));\n }\n if (message === null || typeof message !== \"object\" || Array.isArray(message)) return false;\n const fields = message as Readonly<Record<string, unknown>>;\n return Object.entries(shape).every(([field, value]) => Object.hasOwn(fields, field) && matchesMessage(value, fields[field]));\n};\n\n/**\n * A process port is the part of the process that the runtime uses: its exit triggers, its output\n * and its exit. The runtime owns the handlers, because Node as PID 1 without a handler ignores\n * SIGTERM. Only the runtime ends the process, and library code does not. A test gives a fake port,\n * sends triggers, and reads the exit code.\n */\nexport interface ProcessPort {\n /**\n * This method adds a handler for a trigger, and gives the function that removes it. The runtime\n * asks for a process trigger only when the declaration opts in to it. For `ipc-message`, the\n * handler gets each message of the IPC channel, and the runtime matches it.\n */\n on(trigger: ExitTrigger, handler: (message?: unknown) => void): () => void;\n /**\n * This method adds a handler for each error that no code caught, and gives the function that\n * removes it. The runtime asks for it only when `run()` gets the option `uncaught`. A port without\n * this method gets no handler, as the embedded port.\n */\n onUncaught?(handler: (error: unknown, origin: UncaughtOrigin) => void): () => void;\n /**\n * This method writes each buffered line of the output, and its promise ends when the output is\n * written. The stage `flush the output` uses it, in the cap of that stage.\n */\n flush?(): Promise<void> | void;\n /**\n * This method keeps the process alive, and gives the function that releases it. The lifecycle\n * holds its process from its start to its exit, as a listening socket does. Thus a process whose\n * timers do not keep it alive does not end in the middle of its work. It keeps its teardown and its exit code.\n */\n hold?(): () => void;\n /** This method ends the process with a code: the code of the exit request, 1 after an error, or 0. */\n exit(code: number): void;\n}\n\n/** A host stream is the part of a stream of Node that the port uses. */\nexport interface HostStream {\n readonly writable?: boolean;\n readonly destroyed?: boolean;\n readonly readableEnded?: boolean;\n write(chunk: string, done: (error?: unknown) => void): boolean;\n on(event: string, handler: () => void): unknown;\n off(event: string, handler: () => void): unknown;\n}\n\n/** A process host is the part of the process of Node that the port uses. Its event `message` gives the message of the IPC channel. */\nexport interface ProcessHost {\n on(signal: string, handler: (message?: unknown) => void): unknown;\n off(signal: string, handler: (message?: unknown) => void): unknown;\n exit(code: number): unknown;\n readonly stdin?: HostStream | undefined;\n readonly stdout?: HostStream | undefined;\n readonly stderr?: HostStream | undefined;\n}\n\n/** This time is the interval of the timer of a hold, the most that a timer of Node accepts. */\nconst HOLD_INTERVAL = 0x7fffffff;\n\n/** This function adds a handler to some events of an emitter. The handler operates one time at most. */\nconst once = (emitter: HostStream | ProcessHost, events: readonly string[], handler: () => void): (() => void) => {\n let called = false;\n const fire = (): void => {\n if (called) return;\n called = true;\n handler();\n };\n for (const event of events) emitter.on(event, fire);\n return () => {\n for (const event of events) emitter.off(event, fire);\n };\n};\n\n/** This function gives a promise that ends when the data before it in a stream is written. */\nconst written = (stream: HostStream | undefined): Promise<void> =>\n new Promise<void>((resolve) => {\n if (stream === undefined || stream.destroyed === true || stream.writable === false) {\n resolve();\n return;\n }\n try {\n // the callback of an empty write comes after each write before it\n stream.write(\"\", () => resolve());\n } catch {\n resolve();\n }\n });\n\n/**\n * This function makes a process port on a host. `find` gives the host at each use, or undefined\n * when the platform has no process. Then the use throws.\n */\nexport const processPortOf = (find: () => ProcessHost | undefined): ProcessPort => {\n const hostProcess = (): ProcessHost => {\n const host = find();\n if (host === undefined) throw new Error(\"no process: give the runtime a process port\");\n return host;\n };\n return {\n on(trigger, handler) {\n const host = hostProcess();\n if (trigger === \"stdin-close\") {\n const input = host.stdin;\n if (input === undefined) return () => {};\n // an input that ended before the handler was added still starts the shutdown\n if (input.readableEnded === true) {\n let live = true;\n queueMicrotask(() => {\n if (live) handler();\n });\n return () => {\n live = false;\n };\n }\n return once(input, [\"end\", \"close\"], handler);\n }\n if (trigger === \"ipc-close\") return once(host, [\"disconnect\"], handler);\n if (trigger === \"ipc-message\") {\n // each message goes to the runtime, which matches it with the declared shapes\n const receive = (message?: unknown): void => handler(message);\n host.on(\"message\", receive);\n return () => {\n host.off(\"message\", receive);\n };\n }\n host.on(trigger, handler);\n return () => {\n host.off(trigger, handler);\n };\n },\n onUncaught(handler) {\n const host = hostProcess();\n // a handler of each origin: Node then does not end the process, and the runtime does the shutdown\n const offs = UNCAUGHT_ORIGINS.map((origin) => {\n const receive = (error?: unknown): void => handler(error, origin);\n host.on(origin, receive);\n return () => {\n host.off(origin, receive);\n };\n });\n return () => {\n for (const off of offs) off();\n };\n },\n async flush() {\n const host = hostProcess();\n await Promise.all([written(host.stdout), written(host.stderr)]);\n },\n hold() {\n hostProcess();\n // one interval that keeps the event loop alive: its timer does nothing, and the release stops it\n const timer = setInterval(() => {}, HOLD_INTERVAL);\n let held = true;\n return () => {\n if (!held) return;\n held = false;\n clearInterval(timer);\n };\n },\n exit(code) {\n hostProcess().exit(code);\n },\n };\n};\n\n/** This port is the process of Node. */\nexport const nodeProcess: ProcessPort = processPortOf(() => (globalThis as { process?: ProcessHost }).process);\n\n/** An embedded process port records the exit code of a lifecycle that does not own its process. */\nexport interface EmbeddedProcess extends ProcessPort {\n /** This code is the code of the exit request of the lifecycle, or null before that request. */\n readonly exitCode: number | null;\n /** This promise ends with the exit code when the lifecycle asks for its exit. */\n readonly exited: Promise<number>;\n}\n\n/**\n * This function gives a process port for a lifecycle in a process that another part owns. That\n * part is a script, a test of an application, or a library entry. The port adds no handler of a signal or of\n * a trigger, it does not hold the process, and its `exit` only records the code. The caller stops\n * the lifecycle with `life.shutdown()`. A process with a service of its own gives its parts to\n * that service, and does not use this port.\n */\nexport const embeddedProcess = (): EmbeddedProcess => {\n let code: number | null = null;\n let resolve: (code: number) => void = () => {};\n const exited = new Promise<number>((done) => {\n resolve = done;\n });\n return {\n on() {\n // the owner of the process keeps its signals and triggers\n return () => {};\n },\n exit(requested) {\n if (code !== null) return;\n code = requested;\n resolve(requested);\n },\n get exitCode() {\n return code;\n },\n exited,\n };\n};\n"],"mappings":";;AAIA,MAAa,eAAsC;CAAC;CAAU;CAAW;AAAS;;AAclF,MAAa,mBAA8C;CAAC;CAAe;CAAa;AAAa;;AAYrG,MAAa,mBAA8C,CAAC,qBAAqB,oBAAoB;;AAGrG,MAAa,cAAc,SAA0B,OAAO,UAAU,IAAI,KAAK,QAAQ,KAAK,QAAQ;;AAGpG,MAAa,gBAAgB,YAC1B,aAAmC,SAAS,OAAO;;AAUtD,MAAa,kBAAkB,UAA0C;CACvE,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW,OAAO;CACtF,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,SAAS,KAAK;CAC3D,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,MAAM,cAAc;CAC3D,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,QAAQ,cAAc,OAAO,aAAa,cAAc,SAAS,OAAO,OAAO,KAAK,CAAC,CAAC,MAAM,cAAc;AAC5G;;AAGA,MAAa,kBAAkB,OAAqB,YAA8B;CAChF,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO,OAAO,GAAG,OAAO,OAAO;CAChF,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,MAAM,QAAiC;EACvC,OAAO,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,MAAM,UAAU,MAAM,OAAO,MAAM,OAAO,eAAe,MAAM,QAAQ,GAAG,CAAC;CACjI;CACA,IAAI,YAAY,QAAQ,OAAO,YAAY,YAAY,MAAM,QAAQ,OAAO,GA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
1
  import { n as Clock } from "./clock-DpVgpY4h.js";
2
- import { k as ServiceDescription } from "./logger-BN2BfPgU.js";
3
- import { d as TransportImpl, r as Lifecycle } from "./lifecycle-Br0jAjTk.js";
2
+ import { k as ServiceDescription } from "./logger-B6drv9w0.js";
3
+ import { d as TransportImpl, r as Lifecycle } from "./lifecycle-D0J-zwZF.js";
4
4
  import { Extent, Quantity } from "@mark1russell7/quantity";
5
- //#region src/units.d.ts
6
5
  /**
7
6
  * A unit request names the route of each unit of work in the request tracking of the service. Then
8
7
  * the service admits, counts, drains and cuts each unit as it does each request (`life.request`).
@@ -16,8 +15,6 @@ interface UnitRequest<U> {
16
15
  /** This function gives the detail of a unit, for the function of a route pattern. */
17
16
  readonly detail?: ((unit: U) => unknown) | undefined;
18
17
  }
19
- //#endregion
20
- //#region src/queue.d.ts
21
18
  /**
22
19
  * These are the knobs of a queue drain, by the names of the ordering law where the law has them.
23
20
  * The drain has no defaults, thus each knob is necessary. A bound that nobody gives is "infinite".
@@ -146,6 +143,5 @@ declare const redeliverOnce: <J>(then: JobAction | RedeliveryPolicy<J>, poison?:
146
143
  * that does not end in the bound gets `reject`.
147
144
  */
148
145
  declare const queueDrain: <J>(knobs: QueueKnobs, options: QueueDrainOptions<J>) => QueueDrain;
149
- //#endregion
150
146
  export { JobSource as a, QueueKnobs as c, queueDrain as d, redeliverOnce as f, JobSettle as i, RedeliveryPolicy as l, JobContext as n, QueueDrain as o, UnitRequest as p, JobFailure as r, QueueDrainOptions as s, JobAction as t, RequeueCause as u };
151
- //# sourceMappingURL=queue-fIkOXKVG.d.ts.map
147
+ //# sourceMappingURL=queue-DXdw1vLO.d.ts.map
@@ -1,10 +1,9 @@
1
- import { N as Poll } from "./logger-BN2BfPgU.js";
2
- import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, b as retryProblems, c as ClientSpec, d as Factory, f as ReadyWait, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, v as readyWait, w as Manifestation, y as retryBackoff } from "./core-Dt0HEVMq.js";
3
- import { t as Judge } from "./dial-CSQOl-yj.js";
4
- import { i as JobSettle } from "./queue-fIkOXKVG.js";
1
+ import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, b as retryProblems, c as ClientSpec, d as Factory, f as ReadyWait, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, v as readyWait, w as Manifestation, y as retryBackoff } from "./core-BSzt4RI2.js";
2
+ import { t as Judge } from "./dial-ChwIcvd4.js";
3
+ import { i as JobSettle } from "./queue-DXdw1vLO.js";
4
+ import { N as Poll } from "./logger-B6drv9w0.js";
5
5
  import { Extent, Quantity } from "@mark1russell7/quantity";
6
6
  import { Machine } from "@mark1russell7/algebra";
7
- //#region src/rabbitmq/connection.d.ts
8
7
  /** A message is a message of the broker, as amqplib gives it from `get`. The wrapper reads only these fields. */
9
8
  interface RabbitMessage {
10
9
  readonly content: Buffer;
@@ -95,8 +94,6 @@ type RabbitFactory = Factory<RabbitConnectOptions, RabbitConnection>;
95
94
  * needs no types of amqplib. The built-in recovery of amqplib stays off, because the wrapper connects again by itself.
96
95
  */
97
96
  export declare const nodeAmqp: RabbitFactory;
98
- //#endregion
99
- //#region src/rabbitmq/client.d.ts
100
97
  /**
101
98
  * These are the knobs of the client, each a time, by the names of the ordering law where the law
102
99
  * has them. The runtime has no defaults, thus each knob is necessary. A bound that nobody gives is
@@ -236,8 +233,6 @@ export declare const deliveryCount: (message: RabbitMessage) => number;
236
233
  * The calls in flight, the bounded close and the checks also come from the core. This entry gives what amqplib does in its own way.
237
234
  */
238
235
  export declare const rabbitClient: (name: string, spec: RabbitClientSpec, options?: RabbitClientOptions) => RabbitClient;
239
- //#endregion
240
- //#region src/rabbitmq/machine.d.ts
241
236
  /**
242
237
  * The RabbitMQ client of the service as a `mark1russell7.machine/1` document. It is one generation
243
238
  * at a time: one connection of amqplib and its confirm channel. The machines `amqplib` and
@@ -250,8 +245,6 @@ export declare const rabbitClient: (name: string, spec: RabbitClientSpec, option
250
245
  * of the client and replays them against this document.
251
246
  */
252
247
  export declare const RABBIT_CLIENT_MACHINE: Machine;
253
- //#endregion
254
- //#region src/rabbitmq/meets.d.ts
255
248
  /**
256
249
  * This function gives the manifestations that a RabbitMQ client can meet, and the detectors of each,
257
250
  * from its knobs. The cells of R3 measured them on amqplib 2.2.0 against RabbitMQ 4.3.6:
@@ -262,8 +255,6 @@ export declare const RABBIT_CLIENT_MACHINE: Machine;
262
255
  * - A broker with a resource alarm blocks each connection that publishes, and it still sends its heartbeats.
263
256
  */
264
257
  export declare const rabbitMeetings: (name: string, knobs: RabbitKnobs) => Meeting[];
265
- //#endregion
266
- //#region src/rabbitmq/starting.d.ts
267
258
  /**
268
259
  * This poll is the poll of the checks that `RABBIT_STARTING_KNOBS` fits. It is `STARTING_POLL` of
269
260
  * the core: each 5 s with a jitter of 20 %, and a timeout of 4 s (B6, O12). The poll does not depend on the driver.
@@ -289,6 +280,5 @@ export declare const RABBIT_STARTING_POLL: Poll;
289
280
  * - `retrans_giveup_time` 924.6 s: the give-up of Linux at `tcp_retries2 = 15`.
290
281
  */
291
282
  export declare const RABBIT_STARTING_KNOBS: RabbitKnobs;
292
- //#endregion
293
283
  export { type Attempt, type CheckOptions, type Client, type ClientJoin, type ClientKnobs, type ClientOptions, type ClientSocket, type ClientSpec, type ClientStep, type Detector, type DialFn, type Factory, MANIFESTATIONS, type Manifestation, type Meeting, type RabbitChannel, type RabbitChannelEvent, type RabbitClient, type RabbitClientOptions, type RabbitClientSpec, type RabbitConnectOptions, type RabbitConnection, type RabbitConnectionEvent, type RabbitDelivery, type RabbitFactory, type RabbitJobs, type RabbitJoin, type RabbitKnobs, type RabbitMessage, type RabbitPublish, type RabbitPublishOptions, type RabbitSeed, type RabbitSocketOptions, type ReadyWait, type RetryKnobs, STARTING_POLL, type SendOptions, type Sent, type Situation, firstDetector, readyWait, retryBackoff, retryProblems, unwatched };
294
284
  //# sourceMappingURL=rabbitmq.d.ts.map