@mark1russell7/service 0.8.18 → 0.8.20
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.
- package/README.md +19 -0
- package/build/backoff.d.ts +44 -2
- package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
- package/build/builder.js +499 -0
- package/build/builder.js.map +1 -0
- package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
- package/build/channel.d.ts +1 -1
- package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
- package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
- package/build/client/core.js.map +1 -0
- package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
- package/build/client/dial.js +52 -0
- package/build/client/dial.js.map +1 -0
- package/build/client/machine.js +29 -0
- package/build/client/machine.js.map +1 -0
- package/build/client/meets.d.ts +35 -0
- package/build/client/meets.js +78 -0
- package/build/client/meets.js.map +1 -0
- package/build/clock.d.ts +1 -1
- package/build/conformance.d.ts +122 -0
- package/build/conformance.js +470 -0
- package/build/conformance.js.map +1 -0
- package/build/contract.d.ts +28 -0
- package/build/contract.js +184 -0
- package/build/contract.js.map +1 -0
- package/build/description.d.ts +161 -0
- package/build/description.js +11 -0
- package/build/description.js.map +1 -0
- package/build/drains.js +35 -0
- package/build/drains.js.map +1 -0
- package/build/events.d.ts +25 -0
- package/build/fakes.d.ts +43 -0
- package/build/fakes.js +93 -0
- package/build/fakes.js.map +1 -0
- package/build/grpc/client.d.ts +153 -0
- package/build/grpc/client.js +474 -0
- package/build/grpc/client.js.map +1 -0
- package/build/grpc/connection.d.ts +97 -0
- package/build/grpc/connection.js +59 -0
- package/build/grpc/connection.js.map +1 -0
- package/build/grpc/machine.d.ts +12 -0
- package/build/grpc/machine.js +149 -0
- package/build/grpc/machine.js.map +1 -0
- package/build/grpc/meets.d.ts +14 -0
- package/build/grpc/meets.js +105 -0
- package/build/grpc/meets.js.map +1 -0
- package/build/grpc/starting.d.ts +33 -0
- package/build/grpc/starting.js +89 -0
- package/build/grpc/starting.js.map +1 -0
- package/build/grpc.d.ts +9 -303
- package/build/grpc.js +7 -854
- package/build/health.d.ts +93 -0
- package/build/health.js +223 -0
- package/build/health.js.map +1 -0
- package/build/heartbeat.d.ts +1 -1
- package/build/host/discovery.d.ts +61 -0
- package/build/host/discovery.js +113 -0
- package/build/host/discovery.js.map +1 -0
- package/build/host/env.d.ts +14 -0
- package/build/host/env.js +57 -0
- package/build/host/env.js.map +1 -0
- package/build/host/fakes.d.ts +82 -0
- package/build/host/fakes.js +239 -0
- package/build/host/fakes.js.map +1 -0
- package/build/host/group.d.ts +142 -0
- package/build/host/group.js +517 -0
- package/build/host/group.js.map +1 -0
- package/build/host/install.d.ts +96 -0
- package/build/host/install.js +330 -0
- package/build/host/install.js.map +1 -0
- package/build/host/lock.d.ts +78 -0
- package/build/host/lock.js +190 -0
- package/build/host/lock.js.map +1 -0
- package/build/host/logs.d.ts +26 -0
- package/build/host/logs.js +48 -0
- package/build/host/logs.js.map +1 -0
- package/build/host/node.d.ts +14 -0
- package/build/host/node.js +309 -0
- package/build/host/node.js.map +1 -0
- package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
- package/build/host/ports.js +17 -0
- package/build/host/ports.js.map +1 -0
- package/build/host/probes.d.ts +51 -0
- package/build/host/probes.js +139 -0
- package/build/host/probes.js.map +1 -0
- package/build/host/processes.d.ts +32 -0
- package/build/host/processes.js +63 -0
- package/build/host/processes.js.map +1 -0
- package/build/host/render.d.ts +84 -0
- package/build/host/render.js +235 -0
- package/build/host/render.js.map +1 -0
- package/build/host/watch.d.ts +90 -0
- package/build/host/watch.js +165 -0
- package/build/host/watch.js.map +1 -0
- package/build/host.d.ts +13 -671
- package/build/host.js +12 -2126
- package/build/http/answers.js +29 -0
- package/build/http/answers.js.map +1 -0
- package/build/http/fake-server.js +61 -0
- package/build/http/fake-server.js.map +1 -0
- package/build/http/outcome.d.ts +115 -0
- package/build/http/outcome.js +325 -0
- package/build/http/outcome.js.map +1 -0
- package/build/http/probes.d.ts +83 -0
- package/build/http/probes.js +232 -0
- package/build/http/probes.js.map +1 -0
- package/build/http/transport.d.ts +165 -0
- package/build/http/transport.js +517 -0
- package/build/http/transport.js.map +1 -0
- package/build/http-client/client.d.ts +121 -0
- package/build/http-client/client.js +330 -0
- package/build/http-client/client.js.map +1 -0
- package/build/http-client/connection.d.ts +78 -0
- package/build/http-client/connection.js +54 -0
- package/build/http-client/connection.js.map +1 -0
- package/build/http-client/machine.d.ts +14 -0
- package/build/http-client/machine.js +109 -0
- package/build/http-client/machine.js.map +1 -0
- package/build/http-client/meets.d.ts +11 -0
- package/build/http-client/meets.js +74 -0
- package/build/http-client/meets.js.map +1 -0
- package/build/http-client/session.d.ts +87 -0
- package/build/http-client/session.js +99 -0
- package/build/http-client/session.js.map +1 -0
- package/build/http-client/starting.d.ts +25 -0
- package/build/http-client/starting.js +65 -0
- package/build/http-client/starting.js.map +1 -0
- package/build/http-client.d.ts +9 -330
- package/build/http-client.js +8 -707
- package/build/http.d.ts +5 -353
- package/build/http.js +3 -1086
- package/build/identity.d.ts +16 -0
- package/build/identity.js +44 -0
- package/build/identity.js.map +1 -0
- package/build/index.d.ts +35 -412
- package/build/index.js +24 -3277
- package/build/knobs.d.ts +1 -0
- package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
- package/build/knobs.js.map +1 -0
- package/build/latch.d.ts +29 -0
- package/build/latch.js +122 -0
- package/build/latch.js.map +1 -0
- package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
- package/build/law.js +149 -0
- package/build/law.js.map +1 -0
- package/build/lifecycle.d.ts +144 -0
- package/build/lifecycle.js +411 -0
- package/build/lifecycle.js.map +1 -0
- package/build/limiter/machine.d.ts +40 -0
- package/build/limiter/machine.js +279 -0
- package/build/limiter/machine.js.map +1 -0
- package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
- package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
- package/build/limiter/policy.js.map +1 -0
- package/build/{limiter-Cm8nC-Gd.d.ts → limiter/quota.d.ts} +50 -76
- package/build/{limiter-Bgy6Gmvl.js → limiter/quota.js} +32 -425
- package/build/limiter/quota.js.map +1 -0
- package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
- package/build/limiter/store.js +145 -0
- package/build/limiter/store.js.map +1 -0
- package/build/limiter.d.ts +4 -3
- package/build/limiter.js +4 -2
- package/build/lint.d.ts +152 -0
- package/build/lint.js +576 -0
- package/build/lint.js.map +1 -0
- package/build/logger.d.ts +71 -0
- package/build/logger.js +183 -0
- package/build/logger.js.map +1 -0
- package/build/machines.d.ts +41 -0
- package/build/machines.js +451 -0
- package/build/machines.js.map +1 -0
- package/build/metrics.d.ts +53 -0
- package/build/metrics.js +111 -0
- package/build/metrics.js.map +1 -0
- package/build/mongodb/client.d.ts +131 -0
- package/build/mongodb/client.js +388 -0
- package/build/mongodb/client.js.map +1 -0
- package/build/mongodb/connection.d.ts +112 -0
- package/build/mongodb/connection.js +12 -0
- package/build/mongodb/connection.js.map +1 -0
- package/build/mongodb/machine.d.ts +14 -0
- package/build/mongodb/machine.js +122 -0
- package/build/mongodb/machine.js.map +1 -0
- package/build/mongodb/meets.d.ts +15 -0
- package/build/mongodb/meets.js +103 -0
- package/build/mongodb/meets.js.map +1 -0
- package/build/mongodb/starting.d.ts +29 -0
- package/build/mongodb/starting.js +77 -0
- package/build/mongodb/starting.js.map +1 -0
- package/build/mongodb.d.ts +8 -296
- package/build/mongodb.js +7 -682
- package/build/operation.d.ts +27 -0
- package/build/{operation-DF73RZOI.js → operation.js} +2 -2
- package/build/operation.js.map +1 -0
- package/build/otel.d.ts +2 -2
- package/build/pg/client.d.ts +96 -0
- package/build/pg/client.js +277 -0
- package/build/pg/client.js.map +1 -0
- package/build/pg/connection.d.ts +75 -0
- package/build/pg/connection.js +11 -0
- package/build/pg/connection.js.map +1 -0
- package/build/pg/machine.d.ts +13 -0
- package/build/pg/machine.js +111 -0
- package/build/pg/machine.js.map +1 -0
- package/build/pg/meets.d.ts +14 -0
- package/build/pg/meets.js +83 -0
- package/build/pg/meets.js.map +1 -0
- package/build/pg/starting.d.ts +26 -0
- package/build/pg/starting.js +62 -0
- package/build/pg/starting.js.map +1 -0
- package/build/pg.d.ts +8 -219
- package/build/pg.js +7 -525
- package/build/poller.d.ts +9 -0
- package/build/poller.js +152 -0
- package/build/poller.js.map +1 -0
- package/build/process.d.ts +114 -0
- package/build/process.js +170 -0
- package/build/process.js.map +1 -0
- package/build/profiles.d.ts +68 -0
- package/build/profiles.js +120 -0
- package/build/profiles.js.map +1 -0
- package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
- package/build/queue.js +279 -0
- package/build/queue.js.map +1 -0
- package/build/rabbitmq/client.d.ts +144 -0
- package/build/rabbitmq/client.js +426 -0
- package/build/rabbitmq/client.js.map +1 -0
- package/build/rabbitmq/connection.d.ts +91 -0
- package/build/rabbitmq/connection.js +15 -0
- package/build/rabbitmq/connection.js.map +1 -0
- package/build/rabbitmq/machine.d.ts +13 -0
- package/build/rabbitmq/machine.js +159 -0
- package/build/rabbitmq/machine.js.map +1 -0
- package/build/rabbitmq/meets.d.ts +12 -0
- package/build/rabbitmq/meets.js +96 -0
- package/build/rabbitmq/meets.js.map +1 -0
- package/build/rabbitmq/starting.d.ts +27 -0
- package/build/rabbitmq/starting.js +67 -0
- package/build/rabbitmq/starting.js.map +1 -0
- package/build/rabbitmq.d.ts +8 -283
- package/build/rabbitmq.js +7 -742
- package/build/redis/client.d.ts +86 -0
- package/build/redis/client.js +285 -0
- package/build/redis/client.js.map +1 -0
- package/build/redis/connection.d.ts +57 -0
- package/build/redis/connection.js +11 -0
- package/build/redis/connection.js.map +1 -0
- package/build/redis/limiter.d.ts +43 -0
- package/build/redis/limiter.js +164 -0
- package/build/redis/limiter.js.map +1 -0
- package/build/redis/machine.d.ts +12 -0
- package/build/redis/machine.js +144 -0
- package/build/redis/machine.js.map +1 -0
- package/build/redis/meets.d.ts +11 -0
- package/build/redis/meets.js +75 -0
- package/build/redis/meets.js.map +1 -0
- package/build/redis/operations.d.ts +5 -0
- package/build/redis/operations.js +114 -0
- package/build/redis/operations.js.map +1 -0
- package/build/redis.d.ts +10 -207
- package/build/redis.js +9 -771
- package/build/requests.d.ts +66 -0
- package/build/requests.js +279 -0
- package/build/requests.js.map +1 -0
- package/build/retrier.d.ts +62 -0
- package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
- package/build/retrier.js.map +1 -0
- package/build/routes.d.ts +35 -0
- package/build/routes.js +77 -0
- package/build/routes.js.map +1 -0
- package/build/rules.d.ts +19 -2
- package/build/stops.d.ts +51 -0
- package/build/stops.js +86 -0
- package/build/stops.js.map +1 -0
- package/build/testing.d.ts +8 -270
- package/build/testing.js +4 -1027
- package/build/testing.js.map +1 -1
- package/build/timing.d.ts +63 -0
- package/build/{timing-DZl36uXs.js → timing.js} +2 -2
- package/build/timing.js.map +1 -0
- package/build/units.d.ts +17 -0
- package/build/units.js +236 -0
- package/build/units.js.map +1 -0
- package/build/watchdog.d.ts +34 -0
- package/build/watchdog.js +53 -0
- package/build/watchdog.js.map +1 -0
- package/build/websocket/client.d.ts +136 -0
- package/build/websocket/client.js +422 -0
- package/build/websocket/client.js.map +1 -0
- package/build/websocket/connection.d.ts +83 -0
- package/build/websocket/connection.js +57 -0
- package/build/websocket/connection.js.map +1 -0
- package/build/websocket/machine.d.ts +12 -0
- package/build/websocket/machine.js +155 -0
- package/build/websocket/machine.js.map +1 -0
- package/build/websocket/meets.d.ts +14 -0
- package/build/websocket/meets.js +92 -0
- package/build/websocket/meets.js.map +1 -0
- package/build/websocket/starting.d.ts +25 -0
- package/build/websocket/starting.js +69 -0
- package/build/websocket/starting.js.map +1 -0
- package/build/websocket.d.ts +9 -264
- package/build/websocket.js +8 -774
- package/build/worker.d.ts +92 -0
- package/build/worker.js +153 -0
- package/build/worker.js.map +1 -0
- package/package.json +4 -3
- package/build/backoff-QTRGfkEK.d.ts +0 -45
- package/build/clock-DpVgpY4h.d.ts +0 -2
- package/build/grpc.js.map +0 -1
- package/build/host.js.map +0 -1
- package/build/http-client.js.map +0 -1
- package/build/http.js.map +0 -1
- package/build/index.js.map +0 -1
- package/build/knobs-BJcz6m01.js.map +0 -1
- package/build/lifecycle-D0J-zwZF.d.ts +0 -374
- package/build/limiter-Bgy6Gmvl.js.map +0 -1
- package/build/logger-B6drv9w0.d.ts +0 -488
- package/build/machine-BhVeHr_m.js.map +0 -1
- package/build/mongodb.js.map +0 -1
- package/build/operation-DF73RZOI.js.map +0 -1
- package/build/pg.js.map +0 -1
- package/build/policy-UYALkqVq.js.map +0 -1
- package/build/process-7R9M29wN.js +0 -437
- package/build/process-7R9M29wN.js.map +0 -1
- package/build/rabbitmq.js.map +0 -1
- package/build/redis.js.map +0 -1
- package/build/requests-DD2ALv0_.js +0 -583
- package/build/requests-DD2ALv0_.js.map +0 -1
- package/build/retrier-Dnjhvxol.js.map +0 -1
- package/build/timing-DZl36uXs.js.map +0 -1
- package/build/websocket.js.map +0 -1
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { Extent, Quantity } from "@mark1russell7/quantity";
|
|
2
|
+
/**
|
|
3
|
+
* This type tells if an operation can go again after a failure. It is a property of the
|
|
4
|
+
* operation, not of the dependency. One Redis client sends a GET, which is safe to send again. It
|
|
5
|
+
* also sends an INCR, which counts two times when it goes again after a timeout. Each operation
|
|
6
|
+
* declares its idempotency:
|
|
7
|
+
* - `true`: a second issue has the same effect. Examples are an HTTP GET or PUT, a SELECT, a
|
|
8
|
+
* Redis GET or SET, and a write that the server removes when it is a copy.
|
|
9
|
+
* - `false`: the client does not send it again after it can have reached the server.
|
|
10
|
+
* - keyed: the server keeps a key for a window, as with an `Idempotency-Key` header, and it
|
|
11
|
+
* ignores a copy in that window. A copy after the window is a second operation. Thus the
|
|
12
|
+
* window is a timer, and it must be longer than all retries of the operation.
|
|
13
|
+
*/
|
|
14
|
+
export type Idempotency = boolean | {
|
|
15
|
+
readonly key: string;
|
|
16
|
+
readonly window: Extent;
|
|
17
|
+
};
|
|
18
|
+
/** An operation is an endpoint that the service calls or serves, a command, or a query. */
|
|
19
|
+
export interface Operation {
|
|
20
|
+
readonly idempotent: Idempotency;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* This function tells if an operation can go again `since` its first issue. An idempotent
|
|
24
|
+
* operation can always go again, and other operations cannot. A keyed operation can go again
|
|
25
|
+
* while the server keeps its key.
|
|
26
|
+
*/
|
|
27
|
+
export declare const mayReissue: (operation: Operation, since: Quantity) => boolean;
|
|
@@ -19,6 +19,6 @@ const operationProblems = (owner, name, operation) => {
|
|
|
19
19
|
if (!convertible(idempotent.window.unit, "s")) problems.push(`${owner}'s ${name} holds its key for a span that is not a time`);
|
|
20
20
|
return problems;
|
|
21
21
|
};
|
|
22
|
-
export {
|
|
22
|
+
export { mayReissue, operationProblems };
|
|
23
23
|
|
|
24
|
-
//# sourceMappingURL=operation
|
|
24
|
+
//# sourceMappingURL=operation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"operation.js","names":[],"sources":["../src/operation.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { compare, convertible } from \"@mark1russell7/quantity\";\n\n/**\n * This type tells if an operation can go again after a failure. It is a property of the\n * operation, not of the dependency. One Redis client sends a GET, which is safe to send again. It\n * also sends an INCR, which counts two times when it goes again after a timeout. Each operation\n * declares its idempotency:\n * - `true`: a second issue has the same effect. Examples are an HTTP GET or PUT, a SELECT, a\n * Redis GET or SET, and a write that the server removes when it is a copy.\n * - `false`: the client does not send it again after it can have reached the server.\n * - keyed: the server keeps a key for a window, as with an `Idempotency-Key` header, and it\n * ignores a copy in that window. A copy after the window is a second operation. Thus the\n * window is a timer, and it must be longer than all retries of the operation.\n */\nexport type Idempotency = boolean | { readonly key: string; readonly window: Extent };\n\n/** An operation is an endpoint that the service calls or serves, a command, or a query. */\nexport interface Operation {\n readonly idempotent: Idempotency;\n}\n\n/**\n * This function tells if an operation can go again `since` its first issue. An idempotent\n * operation can always go again, and other operations cannot. A keyed operation can go again\n * while the server keeps its key.\n */\nexport const mayReissue = (operation: Operation, since: Quantity): boolean => {\n const { idempotent } = operation;\n if (typeof idempotent === \"boolean\") return idempotent;\n return compare(since, idempotent.window) < 0;\n};\n\n/** This function gives the problems in the declaration of an operation that `describe()` refuses. */\nexport const operationProblems = (owner: string, name: string, operation: Operation): string[] => {\n const { idempotent } = operation;\n if (typeof idempotent === \"boolean\") return [];\n const problems: string[] = [];\n if (idempotent.key.trim().length === 0) problems.push(`${owner}'s ${name} names no key`);\n if (!convertible(idempotent.window.unit, \"s\"))\n problems.push(`${owner}'s ${name} holds its key for a span that is not a time`);\n return problems;\n};\n"],"mappings":";;;;;;;AA2BA,MAAa,cAAc,WAAsB,UAA6B;CAC5E,MAAM,EAAE,eAAe;CACvB,IAAI,OAAO,eAAe,WAAW,OAAO;CAC5C,OAAO,QAAQ,OAAO,WAAW,MAAM,IAAI;AAC7C;;AAGA,MAAa,qBAAqB,OAAe,MAAc,cAAmC;CAChG,MAAM,EAAE,eAAe;CACvB,IAAI,OAAO,eAAe,WAAW,OAAO,CAAC;CAC7C,MAAM,WAAqB,CAAC;CAC5B,IAAI,WAAW,IAAI,KAAK,CAAC,CAAC,WAAW,GAAG,SAAS,KAAK,GAAG,MAAM,KAAK,KAAK,cAAc;CACvF,IAAI,CAAC,YAAY,WAAW,OAAO,MAAM,GAAG,GAC1C,SAAS,KAAK,GAAG,MAAM,KAAK,KAAK,6CAA6C;CAChF,OAAO;AACT"}
|
package/build/otel.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { CallContext, IncomingHeaders } from "./call-context.js";
|
|
2
|
+
import { TraceIds, TraceIdsSource } from "./logger.js";
|
|
3
3
|
/** This function gives the trace id and the span id of the active span, or nothing when no valid span is active. */
|
|
4
4
|
export declare const traceIds: () => TraceIds | undefined;
|
|
5
5
|
/**
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, SendOptions, Sent } from "../client/core.js";
|
|
2
|
+
import { Operation } from "../operation.js";
|
|
3
|
+
import { PgPoolOptions, PgResult, PoolFactory } from "./connection.js";
|
|
4
|
+
import { Extent, Quantity } from "@mark1russell7/quantity";
|
|
5
|
+
/**
|
|
6
|
+
* These are the knobs of the client, each a time, by the names of the ordering law where the law
|
|
7
|
+
* has them. The runtime has no defaults, thus each knob is necessary. A bound that nobody gives is
|
|
8
|
+
* "infinite", not zero. `PG_STARTING_KNOBS` gives a declaration from the cells of S1. The knobs
|
|
9
|
+
* that each client has come from the core.
|
|
10
|
+
*/
|
|
11
|
+
export interface PgKnobs extends ClientKnobs {
|
|
12
|
+
/**
|
|
13
|
+
* This time bounds a new connection (`connectionTimeoutMillis`): the TCP connect, the startup and
|
|
14
|
+
* the authentication. The pool uses the same knob to bound a checkout from a full pool.
|
|
15
|
+
* At the defaults pg has no bound, and the kernel gives up on the SYNs only after 131 s (A3, O15).
|
|
16
|
+
*/
|
|
17
|
+
readonly connect_bound: Quantity;
|
|
18
|
+
/** This time bounds each query on the client (`query_timeout`). pg sends no cancel at its end. */
|
|
19
|
+
readonly request_timeout: Quantity;
|
|
20
|
+
/**
|
|
21
|
+
* This time is the deadline of each statement on the server (`statement_timeout`). The server then
|
|
22
|
+
* ends the statement with ERROR 57014, a certain outcome. "infinite" sends no deadline.
|
|
23
|
+
*/
|
|
24
|
+
readonly statement_timeout: Extent;
|
|
25
|
+
/** This time ends an idle client of the pool (`idleTimeoutMillis`). The pool sends no test on an idle client. */
|
|
26
|
+
readonly pool_idle_expiry: Extent;
|
|
27
|
+
/** This time is the idle time of TCP keepalive, in whole seconds. Node then sends 10 probes 1 s apart. */
|
|
28
|
+
readonly keepalive_idle: Extent;
|
|
29
|
+
/** This time is the age at which the pool replaces a client (`maxLifetimeSeconds`), in whole seconds. */
|
|
30
|
+
readonly max_connection_age: Extent;
|
|
31
|
+
/** This time bounds the close of the pool at the shutdown: its end, then a destroy of each socket that stays. */
|
|
32
|
+
readonly close_bound: Quantity;
|
|
33
|
+
}
|
|
34
|
+
/** A pg client spec is the declaration of one PostgreSQL client: where it connects, its pool, and its knobs. */
|
|
35
|
+
export interface PgClientSpec extends ClientSpec<PgKnobs> {
|
|
36
|
+
readonly database?: string | undefined;
|
|
37
|
+
readonly user?: string | undefined;
|
|
38
|
+
/** These counts are the sizes of the pool: at most `max` clients, and an idle timer only above `min`. */
|
|
39
|
+
readonly pool: {
|
|
40
|
+
readonly max: number;
|
|
41
|
+
readonly min: number;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* These operations are the queries of the service, by name, with their idempotency. SQL text does
|
|
45
|
+
* not tell if a statement changes a state, thus the client sends again only a query that this table names.
|
|
46
|
+
*/
|
|
47
|
+
readonly operations?: Readonly<Record<string, Operation>> | undefined;
|
|
48
|
+
}
|
|
49
|
+
/** These options make a client. Without them, it uses pg, the real clock, and a dial with an SSLRequest. */
|
|
50
|
+
export type PgClientOptions = ClientOptions<PoolFactory>;
|
|
51
|
+
/**
|
|
52
|
+
* A join is one connection of the pool, at its connect (D1, D2). The prober joins its kernel records
|
|
53
|
+
* to the server's view of the connection through it. The server's view is the process id of the backend.
|
|
54
|
+
*/
|
|
55
|
+
export interface PgJoin extends ClientJoin {
|
|
56
|
+
/** 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. */
|
|
57
|
+
readonly backendPid: number | null;
|
|
58
|
+
}
|
|
59
|
+
/** The steps that the pg client gives a check for: the steps of each client, and a checkout from the pool (B14). */
|
|
60
|
+
export type PgStep = ClientStep | "checkout";
|
|
61
|
+
/** A pg client is a dependency of a service: its declaration, its handle, its checks and its queries. */
|
|
62
|
+
export interface PgClient extends Client<PgStep, PgJoin> {
|
|
63
|
+
/** This text is the state of the client, as `PG_CLIENT_MACHINE` names it. */
|
|
64
|
+
readonly status: string;
|
|
65
|
+
/**
|
|
66
|
+
* This method sends a query, and gives its outcome in three values. `operation` names the query
|
|
67
|
+
* in the table of operations. The client sends again only an idempotent operation, one time at
|
|
68
|
+
* most, after an outcome that is not certain. The second try stays in the bound of the request.
|
|
69
|
+
*/
|
|
70
|
+
query<Row = Record<string, unknown>>(operation: string, text: string, values?: readonly unknown[], options?: SendOptions): Promise<Sent<PgResult<Row>>>;
|
|
71
|
+
}
|
|
72
|
+
/** This function gives the problems of a spec: the knobs that pg cannot use. */
|
|
73
|
+
export declare const specProblems: (name: string, spec: PgClientSpec) => string[];
|
|
74
|
+
/** This function gives the options of `pg.Pool` from a spec. Each timer of pg comes from the declaration. */
|
|
75
|
+
export declare const poolOptions: (name: string, spec: PgClientSpec) => PgPoolOptions;
|
|
76
|
+
/**
|
|
77
|
+
* This dial function opens a TCP connection, sends an SSLRequest, and waits for its one byte. The
|
|
78
|
+
* server answers it before the authentication, thus the dial needs no password and opens no backend.
|
|
79
|
+
*/
|
|
80
|
+
export declare const sslRequestDial: DialFn;
|
|
81
|
+
/**
|
|
82
|
+
* This function makes a PostgreSQL client, a dependency of a service over a `pg.Pool`.
|
|
83
|
+
* - It sets each timer of pg from the declaration. The driver sends nothing again by itself, and the client
|
|
84
|
+
* sends again only an idempotent operation of its table.
|
|
85
|
+
* - It tells the outcome of a query in three values. An ERROR of the server is certain. A FATAL
|
|
86
|
+
* ends the session, thus its outcome is not certain.
|
|
87
|
+
* - It gives back a client whose query has no certain outcome with an error. The pool then ends it,
|
|
88
|
+
* thus an orphaned query does not hold the next checkout.
|
|
89
|
+
* - It listens to each error of the pool and of a client that it holds. In Node, an error with no
|
|
90
|
+
* listener throws, and library code does not end the process (A5).
|
|
91
|
+
* - It records the process id of the backend of each connection (D1).
|
|
92
|
+
*
|
|
93
|
+
* The outcomes, the second try, the queries in flight, the bounded close and the checks come from
|
|
94
|
+
* the core of the clients. This entry gives what pg does in its own way.
|
|
95
|
+
*/
|
|
96
|
+
export declare const pgClient: (name: string, spec: PgClientSpec, options?: PgClientOptions) => PgClient;
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { realClock } from "../clock.js";
|
|
2
|
+
import { attachClient, clientBounds, clientProblems, clientRecorder, deadlineProblem, dialCheck, finiteMs, inFlight, localStateCheck, message, ms, notSent, operationTable, orZero, poolProblems, roundTripCheck, sendWithReissue, socketEnds, stepChecks, timeProblems, wholeProblems, withinBound, zeroProblems } from "../client/core.js";
|
|
3
|
+
import { helloDial } from "../client/dial.js";
|
|
4
|
+
import { nodePostgres } from "./connection.js";
|
|
5
|
+
import { pgMeetings } from "./meets.js";
|
|
6
|
+
// src/pg/client.ts
|
|
7
|
+
/** This function gives the problems of a spec: the knobs that pg cannot use. */
|
|
8
|
+
const specProblems = (name, spec) => {
|
|
9
|
+
const { knobs } = spec;
|
|
10
|
+
return [
|
|
11
|
+
...timeProblems(name, knobs),
|
|
12
|
+
...zeroProblems(name, "pg", knobs, {
|
|
13
|
+
bounded: [
|
|
14
|
+
"connect_bound",
|
|
15
|
+
"request_timeout",
|
|
16
|
+
"close_bound"
|
|
17
|
+
],
|
|
18
|
+
open: [
|
|
19
|
+
"statement_timeout",
|
|
20
|
+
"pool_idle_expiry",
|
|
21
|
+
"keepalive_idle",
|
|
22
|
+
"max_connection_age"
|
|
23
|
+
]
|
|
24
|
+
}),
|
|
25
|
+
...wholeProblems(name, knobs, {
|
|
26
|
+
millis: [
|
|
27
|
+
"connect_bound",
|
|
28
|
+
"request_timeout",
|
|
29
|
+
"statement_timeout",
|
|
30
|
+
"pool_idle_expiry"
|
|
31
|
+
],
|
|
32
|
+
seconds: ["keepalive_idle", "max_connection_age"]
|
|
33
|
+
}),
|
|
34
|
+
...poolProblems(name, spec.pool)
|
|
35
|
+
];
|
|
36
|
+
};
|
|
37
|
+
/** This function gives the options of `pg.Pool` from a spec. Each timer of pg comes from the declaration. */
|
|
38
|
+
const poolOptions = (name, spec) => {
|
|
39
|
+
const { knobs } = spec;
|
|
40
|
+
return {
|
|
41
|
+
host: spec.host,
|
|
42
|
+
port: spec.port,
|
|
43
|
+
...spec.database === void 0 ? {} : { database: spec.database },
|
|
44
|
+
...spec.user === void 0 ? {} : { user: spec.user },
|
|
45
|
+
...spec.password === void 0 ? {} : { password: spec.password },
|
|
46
|
+
application_name: name,
|
|
47
|
+
max: spec.pool.max,
|
|
48
|
+
min: spec.pool.min,
|
|
49
|
+
connectionTimeoutMillis: ms(knobs.connect_bound),
|
|
50
|
+
query_timeout: ms(knobs.request_timeout),
|
|
51
|
+
statement_timeout: finiteMs(knobs.statement_timeout),
|
|
52
|
+
idleTimeoutMillis: orZero(knobs.pool_idle_expiry),
|
|
53
|
+
maxLifetimeSeconds: orZero(knobs.max_connection_age) / 1e3,
|
|
54
|
+
keepAlive: knobs.keepalive_idle.value !== "infinite",
|
|
55
|
+
keepAliveInitialDelayMillis: orZero(knobs.keepalive_idle),
|
|
56
|
+
allowExitOnIdle: true
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* This dial function opens a TCP connection, sends an SSLRequest, and waits for its one byte. The
|
|
61
|
+
* server answers it before the authentication, thus the dial needs no password and opens no backend.
|
|
62
|
+
*/
|
|
63
|
+
const sslRequestDial = helloDial(Uint8Array.of(0, 0, 0, 8, 4, 210, 22, 47), (received) => {
|
|
64
|
+
const answer = String.fromCharCode(received[0] ?? 0);
|
|
65
|
+
return answer === "S" || answer === "N" ? null : /* @__PURE__ */ new Error(`the answer to the SSLRequest was ${JSON.stringify(answer)}`);
|
|
66
|
+
});
|
|
67
|
+
/** A database error is an ErrorResponse of the server: pg gives its severity and its SQLSTATE code. */
|
|
68
|
+
const replyOf = (error) => {
|
|
69
|
+
if (typeof error !== "object" || error === null) return null;
|
|
70
|
+
const { severity, code } = error;
|
|
71
|
+
return typeof severity === "string" && typeof code === "string" && /^[0-9A-Z]{5}$/.test(code) ? {
|
|
72
|
+
severity,
|
|
73
|
+
code
|
|
74
|
+
} : null;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* This function makes a PostgreSQL client, a dependency of a service over a `pg.Pool`.
|
|
78
|
+
* - It sets each timer of pg from the declaration. The driver sends nothing again by itself, and the client
|
|
79
|
+
* sends again only an idempotent operation of its table.
|
|
80
|
+
* - It tells the outcome of a query in three values. An ERROR of the server is certain. A FATAL
|
|
81
|
+
* ends the session, thus its outcome is not certain.
|
|
82
|
+
* - It gives back a client whose query has no certain outcome with an error. The pool then ends it,
|
|
83
|
+
* thus an orphaned query does not hold the next checkout.
|
|
84
|
+
* - It listens to each error of the pool and of a client that it holds. In Node, an error with no
|
|
85
|
+
* listener throws, and library code does not end the process (A5).
|
|
86
|
+
* - It records the process id of the backend of each connection (D1).
|
|
87
|
+
*
|
|
88
|
+
* The outcomes, the second try, the queries in flight, the bounded close and the checks come from
|
|
89
|
+
* the core of the clients. This entry gives what pg does in its own way.
|
|
90
|
+
*/
|
|
91
|
+
const pgClient = (name, spec, options = {}) => {
|
|
92
|
+
const problems = specProblems(name, spec);
|
|
93
|
+
if (problems.length > 0) throw new Error(problems.join("; "));
|
|
94
|
+
const { knobs } = spec;
|
|
95
|
+
const clock = options.clock ?? realClock;
|
|
96
|
+
const create = options.create ?? nodePostgres;
|
|
97
|
+
const dial = options.dial ?? sslRequestDial;
|
|
98
|
+
const operations = operationTable({}, spec.operations);
|
|
99
|
+
const requestTimeout = ms(knobs.request_timeout);
|
|
100
|
+
let pool = null;
|
|
101
|
+
let status = "none";
|
|
102
|
+
const joins = [];
|
|
103
|
+
const open = /* @__PURE__ */ new Set();
|
|
104
|
+
const flight = inFlight();
|
|
105
|
+
const emit = clientRecorder(options.record, clock, name);
|
|
106
|
+
const record = (on, to = status, detail) => {
|
|
107
|
+
const from = status;
|
|
108
|
+
status = to;
|
|
109
|
+
emit(from, to, on, detail);
|
|
110
|
+
};
|
|
111
|
+
const closing = () => status === "closing" || status === "end";
|
|
112
|
+
const onConnect = (client) => {
|
|
113
|
+
open.add(client);
|
|
114
|
+
const generation = joins.length + 1;
|
|
115
|
+
const pid = client.processID;
|
|
116
|
+
joins.push({
|
|
117
|
+
generation,
|
|
118
|
+
at: clock.now(),
|
|
119
|
+
backendPid: typeof pid === "number" ? pid : null,
|
|
120
|
+
...socketEnds(client.connection?.stream)
|
|
121
|
+
});
|
|
122
|
+
record("join", closing() ? status : "ready", `generation ${generation}, backend ${pid ?? "unknown"}`);
|
|
123
|
+
};
|
|
124
|
+
const onRemove = (client) => {
|
|
125
|
+
open.delete(client);
|
|
126
|
+
record("client.removed");
|
|
127
|
+
};
|
|
128
|
+
const onPoolError = (error) => {
|
|
129
|
+
if (status !== "end") record("client.error", status, message(error));
|
|
130
|
+
};
|
|
131
|
+
/** This function records a failed checkout: a full pool at its bound, or a connect that failed. */
|
|
132
|
+
const checkoutFailed = (error) => {
|
|
133
|
+
const text = message(error);
|
|
134
|
+
if (/timeout exceeded when trying to connect/i.test(text)) record("checkout.timeout", status, text);
|
|
135
|
+
else record("connect.failed", closing() ? status : "failing", text);
|
|
136
|
+
};
|
|
137
|
+
/** This function checks out a client, or gives the reason why the query cannot leave the client. */
|
|
138
|
+
const checkout = (signal) => {
|
|
139
|
+
const p = pool;
|
|
140
|
+
if (p === null) return Promise.resolve(notSent(`${name} has not connected`));
|
|
141
|
+
if (closing()) return Promise.resolve(notSent(`${name} is ${status}: the query did not leave the client`));
|
|
142
|
+
if (signal?.aborted) return Promise.resolve(notSent("the caller aborted the query before it left the client"));
|
|
143
|
+
return new Promise((resolve) => {
|
|
144
|
+
let done = false;
|
|
145
|
+
const aborted = () => {
|
|
146
|
+
done = true;
|
|
147
|
+
resolve(notSent("the caller abandoned the query before it left the client"));
|
|
148
|
+
};
|
|
149
|
+
signal?.addEventListener("abort", aborted, { once: true });
|
|
150
|
+
p.connect().then((client) => {
|
|
151
|
+
signal?.removeEventListener("abort", aborted);
|
|
152
|
+
if (done) client.release();
|
|
153
|
+
else resolve(client);
|
|
154
|
+
}, (error) => {
|
|
155
|
+
signal?.removeEventListener("abort", aborted);
|
|
156
|
+
checkoutFailed(error);
|
|
157
|
+
if (!done) resolve(notSent(message(error)));
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
};
|
|
161
|
+
/** This function makes one try of a query: a checkout, the query, and the release. */
|
|
162
|
+
const attempt = async (text, values, signal) => {
|
|
163
|
+
const got = await checkout(signal);
|
|
164
|
+
if (!("release" in got)) return got;
|
|
165
|
+
const client = got;
|
|
166
|
+
const onClientError = (error) => record("client.error", status, message(error));
|
|
167
|
+
client.on("error", onClientError);
|
|
168
|
+
return flight.track(signal, "the caller abandoned the query after it was sent", (settle) => {
|
|
169
|
+
client.query(text, values).then((result) => settle({
|
|
170
|
+
outcome: "ok",
|
|
171
|
+
value: {
|
|
172
|
+
rows: result.rows,
|
|
173
|
+
rowCount: result.rowCount
|
|
174
|
+
}
|
|
175
|
+
}), (error) => {
|
|
176
|
+
const reply = replyOf(error);
|
|
177
|
+
const said = reply === null ? message(error) : `${reply.code} ${message(error)}`;
|
|
178
|
+
if (reply !== null && reply.severity === "ERROR") settle({
|
|
179
|
+
outcome: "error",
|
|
180
|
+
error: said,
|
|
181
|
+
reply: true
|
|
182
|
+
});
|
|
183
|
+
else settle({
|
|
184
|
+
outcome: "indeterminate",
|
|
185
|
+
error: said
|
|
186
|
+
}, error instanceof Error ? error : new Error(said));
|
|
187
|
+
});
|
|
188
|
+
}, (_value, cause) => {
|
|
189
|
+
client.off("error", onClientError);
|
|
190
|
+
client.release(cause);
|
|
191
|
+
});
|
|
192
|
+
};
|
|
193
|
+
const query = (operation, text, values, sendOptions = {}) => sendWithReissue({
|
|
194
|
+
clock,
|
|
195
|
+
bound: requestTimeout,
|
|
196
|
+
operation: operations[operation],
|
|
197
|
+
options: sendOptions,
|
|
198
|
+
attempt: (signal) => attempt(text, values, signal),
|
|
199
|
+
onReissue: () => record("command.reissue", status, operation)
|
|
200
|
+
});
|
|
201
|
+
const handle = {
|
|
202
|
+
async connect(signal) {
|
|
203
|
+
record("status.connecting", "connecting");
|
|
204
|
+
const p = await create(poolOptions(name, spec));
|
|
205
|
+
pool = p;
|
|
206
|
+
p.on("connect", onConnect);
|
|
207
|
+
p.on("remove", onRemove);
|
|
208
|
+
p.on("error", onPoolError);
|
|
209
|
+
if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);
|
|
210
|
+
const first = await checkout(signal);
|
|
211
|
+
if ("release" in first) first.release();
|
|
212
|
+
},
|
|
213
|
+
async close() {
|
|
214
|
+
const p = pool;
|
|
215
|
+
if (p === null || closing()) return;
|
|
216
|
+
record("close.request", "closing");
|
|
217
|
+
if (!await withinBound(clock, ms(knobs.close_bound), p.end())) {
|
|
218
|
+
record("close.bound");
|
|
219
|
+
for (const client of [...open]) client.connection?.stream?.destroy?.();
|
|
220
|
+
record("close.destroy", status, `${open.size} sockets`);
|
|
221
|
+
}
|
|
222
|
+
flight.settleAll("the client closed with the query in flight");
|
|
223
|
+
p.off("connect", onConnect);
|
|
224
|
+
p.off("remove", onRemove);
|
|
225
|
+
record("status.end", "end");
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
const declaration = {
|
|
229
|
+
system: spec.system,
|
|
230
|
+
knobs: {
|
|
231
|
+
connect_bound: knobs.connect_bound,
|
|
232
|
+
request_timeout: knobs.request_timeout,
|
|
233
|
+
statement_timeout: knobs.statement_timeout,
|
|
234
|
+
pool_idle_expiry: knobs.pool_idle_expiry,
|
|
235
|
+
keepalive_idle: knobs.keepalive_idle,
|
|
236
|
+
idle_refresh_interval: knobs.keepalive_idle,
|
|
237
|
+
max_connection_age: knobs.max_connection_age,
|
|
238
|
+
close_bound: knobs.close_bound,
|
|
239
|
+
retrans_giveup_time: knobs.retrans_giveup_time
|
|
240
|
+
},
|
|
241
|
+
operations
|
|
242
|
+
};
|
|
243
|
+
const checks = (checkOptions) => stepChecks(name, checkOptions, {
|
|
244
|
+
"local-state": localStateCheck(() => status === "ready"),
|
|
245
|
+
checkout: {
|
|
246
|
+
ownConnection: true,
|
|
247
|
+
run: async (signal) => {
|
|
248
|
+
const got = await checkout(signal);
|
|
249
|
+
if (!("release" in got)) return "error";
|
|
250
|
+
got.release();
|
|
251
|
+
return "ok";
|
|
252
|
+
}
|
|
253
|
+
},
|
|
254
|
+
"round-trip": roundTripCheck((sendOptions) => query("check", "SELECT 1", [], sendOptions)),
|
|
255
|
+
dial: dialCheck(dial, spec.host, spec.port)
|
|
256
|
+
});
|
|
257
|
+
return {
|
|
258
|
+
name,
|
|
259
|
+
declaration,
|
|
260
|
+
handle,
|
|
261
|
+
meets: pgMeetings(name, knobs),
|
|
262
|
+
get status() {
|
|
263
|
+
return status;
|
|
264
|
+
},
|
|
265
|
+
joins,
|
|
266
|
+
query,
|
|
267
|
+
checks,
|
|
268
|
+
attach: (svc, checkOptions) => attachClient(svc, name, declaration, handle, checks(checkOptions)),
|
|
269
|
+
problems(description) {
|
|
270
|
+
const deadline = deadlineProblem(name, knobs.request_timeout, knobs.statement_timeout, "statement");
|
|
271
|
+
return [...clientProblems(name, description, clientBounds(knobs)), ...deadline === null ? [] : [deadline]];
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
};
|
|
275
|
+
export { pgClient, poolOptions, specProblems, sslRequestDial };
|
|
276
|
+
|
|
277
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../../src/pg/client.ts"],"sourcesContent":["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"],"mappings":";;;;;;;AAgHA,MAAa,gBAAgB,MAAc,SAAiC;CAC1E,MAAM,EAAE,UAAU;CAClB,OAAO;EACL,GAAG,aAAa,MAAM,KAAK;EAE3B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A;EACA;EACA;EACA,SAAS,KAAK,iBAAiB,aAAa,KAAK,MAAM,aAAa,QAAQ,OAAO,YAAY,CAAC;EAChG,SAAS,aAAa;GAEpB,MAAM,WAAW,gBAAgB,MAAM,MAAM,iBAAiB,MAAM,mBAAmB,WAAW;GAClG,OAAO,CAAC,GAAG,eAAe,MAAM,aAAa,aAAa,KAAK,CAAC,GAAG,GAAI,aAAa,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAE;EAC7G;CACF;AACF"}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { ClientSocket, Factory } from "../client/core.js";
|
|
2
|
+
/** A pg socket is the socket of a client in the core: the join of the prober and the bounded close read it. */
|
|
3
|
+
export type PgSocket = ClientSocket;
|
|
4
|
+
/** A query result is the part of a result of pg that the wrapper gives back. */
|
|
5
|
+
export interface PgResult<Row = Record<string, unknown>> {
|
|
6
|
+
readonly rows: Row[];
|
|
7
|
+
readonly rowCount: number | null;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A pool client is the part of a `pg.PoolClient` that the wrapper uses. A pg 8 client has each part.
|
|
11
|
+
* A fake for tests has them too. Thus the package depends on no type of pg.
|
|
12
|
+
*/
|
|
13
|
+
export interface PgPoolClient {
|
|
14
|
+
/** This number is the id of the backend from BackendKeyData, which the server sends at the startup. */
|
|
15
|
+
readonly processID?: number | null | undefined;
|
|
16
|
+
/** This connection holds the socket of the client. */
|
|
17
|
+
readonly connection?: {
|
|
18
|
+
readonly stream?: PgSocket | undefined;
|
|
19
|
+
} | undefined;
|
|
20
|
+
query(text: string, values?: readonly unknown[]): Promise<PgResult<never>>;
|
|
21
|
+
/** This method gives the client back to the pool. With an error, the pool ends the client. */
|
|
22
|
+
release(error?: Error | boolean): void;
|
|
23
|
+
on(event: "error", listener: (error: Error) => void): unknown;
|
|
24
|
+
off(event: "error", listener: (error: Error) => void): unknown;
|
|
25
|
+
}
|
|
26
|
+
/** A pool is the part of a `pg.Pool` that the wrapper uses. */
|
|
27
|
+
export interface PgPool {
|
|
28
|
+
readonly totalCount: number;
|
|
29
|
+
readonly idleCount: number;
|
|
30
|
+
readonly waitingCount: number;
|
|
31
|
+
connect(): Promise<PgPoolClient>;
|
|
32
|
+
end(): Promise<void>;
|
|
33
|
+
on(event: "connect" | "remove", listener: (client: PgPoolClient) => void): unknown;
|
|
34
|
+
on(event: "error", listener: (error: Error, client: PgPoolClient) => void): unknown;
|
|
35
|
+
off(event: "connect" | "remove", listener: (client: PgPoolClient) => void): unknown;
|
|
36
|
+
off(event: "error", listener: (error: Error, client: PgPoolClient) => void): unknown;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* These are the options that the wrapper gives `pg.Pool`. Each one comes from the declaration. The
|
|
40
|
+
* wrapper sets each option that has an effect on a timer, thus no default of pg decides one. A knob
|
|
41
|
+
* of pg at 0 has no timer. The wrapper writes "infinite" as 0, and it refuses a bound of 0.
|
|
42
|
+
*/
|
|
43
|
+
export interface PgPoolOptions {
|
|
44
|
+
readonly host: string;
|
|
45
|
+
readonly port: number;
|
|
46
|
+
readonly database?: string | undefined;
|
|
47
|
+
readonly user?: string | undefined;
|
|
48
|
+
readonly password?: string | undefined;
|
|
49
|
+
/** The server shows this name in `pg_stat_activity`, thus the prober can join on it too. */
|
|
50
|
+
readonly application_name: string;
|
|
51
|
+
readonly max: number;
|
|
52
|
+
readonly min: number;
|
|
53
|
+
/** This time bounds the TCP connect, the startup and the authentication. It also bounds a checkout from a full pool. */
|
|
54
|
+
readonly connectionTimeoutMillis: number;
|
|
55
|
+
/** This time bounds each query on the client, from `client.query`. The client sends no cancel at its end. */
|
|
56
|
+
readonly query_timeout: number;
|
|
57
|
+
/** This time is the deadline of each statement on the server. The client sends it in the startup message. Undefined does not send it. */
|
|
58
|
+
readonly statement_timeout: number | undefined;
|
|
59
|
+
/** This time ends an idle client of the pool. 0 is no idle timer. */
|
|
60
|
+
readonly idleTimeoutMillis: number;
|
|
61
|
+
/** This time ends a client at this age from its connect, in whole seconds. 0 is no age. */
|
|
62
|
+
readonly maxLifetimeSeconds: number;
|
|
63
|
+
readonly keepAlive: boolean;
|
|
64
|
+
/** This time is the idle time of TCP keepalive. Node truncates it to whole seconds. */
|
|
65
|
+
readonly keepAliveInitialDelayMillis: number;
|
|
66
|
+
/** The idle timer and the idle sockets do not keep the process alive (A14). The lifecycle holds the process. */
|
|
67
|
+
readonly allowExitOnIdle: true;
|
|
68
|
+
}
|
|
69
|
+
/** A pool factory makes the pool of the client from its options. */
|
|
70
|
+
export type PoolFactory = Factory<PgPoolOptions, PgPool>;
|
|
71
|
+
/**
|
|
72
|
+
* This factory makes a `pg.Pool`. It loads pg only when a client connects, thus a service that does
|
|
73
|
+
* not use PostgreSQL does not need pg. The specifier is a value, thus the package needs no types of pg.
|
|
74
|
+
*/
|
|
75
|
+
export declare const nodePostgres: PoolFactory;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// src/pg/connection.ts
|
|
2
|
+
/**
|
|
3
|
+
* This factory makes a `pg.Pool`. It loads pg only when a client connects, thus a service that does
|
|
4
|
+
* not use PostgreSQL does not need pg. The specifier is a value, thus the package needs no types of pg.
|
|
5
|
+
*/
|
|
6
|
+
const nodePostgres = async (options) => {
|
|
7
|
+
return new (await (import("pg"))).default.Pool(options);
|
|
8
|
+
};
|
|
9
|
+
export { nodePostgres };
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=connection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connection.js","names":[],"sources":["../../src/pg/connection.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"],"mappings":";;;;;AA+EA,MAAa,eAA4B,OAAO,YAAY;CAG1D,OAAO,KAAI,OADW,OAAO,OAAA,CACX,QAAQ,KAAK,OAAO;AACxC"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Machine } from "@mark1russell7/algebra";
|
|
2
|
+
/**
|
|
3
|
+
* The pg client of the service as a `mark1russell7.machine/1` document. It is the pool as the
|
|
4
|
+
* wrapper sees it, not one connection: the document `node-postgres` of `@mark1russell7/machines`
|
|
5
|
+
* gives each client of the pool. The state is the outcome of the last connect:
|
|
6
|
+
* - `ready`: the last connect of the pool succeeded.
|
|
7
|
+
* - `failing`: the last connect failed. pg does not connect again by itself. The next checkout tries again.
|
|
8
|
+
*
|
|
9
|
+
* An idle client that fails and a client that the pool removes do not change the state. The pool
|
|
10
|
+
* removed that client, and the next checkout opens a new connection. A test records the transitions
|
|
11
|
+
* of the client and replays them against this document.
|
|
12
|
+
*/
|
|
13
|
+
export declare const PG_CLIENT_MACHINE: Machine;
|