@mark1russell7/service 0.8.19 → 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/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-BNKnwzeY.d.ts → limiter/quota.d.ts} +32 -74
- package/build/{limiter-DrM0PQV9.js → limiter/quota.js} +3 -418
- 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-DrM0PQV9.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,426 @@
|
|
|
1
|
+
import { realClock } from "../clock.js";
|
|
2
|
+
import { ageProblems, attachClient, clientBounds, clientProblems, clientRecorder, dialCheck, finiteMs, inFlight, localStateCheck, message, ms, notSent, operationTable, readyWait, retryBackoff, retryProblems, retrySchedule, roundTripCheck, sendWithReissue, socketEnds, stepChecks, timeProblems, trackWithTimer, wholeProblems, withinBound, wrapperTimerProblems, zeroProblems } from "../client/core.js";
|
|
3
|
+
import { helloDial } from "../client/dial.js";
|
|
4
|
+
import { nodeAmqp } from "./connection.js";
|
|
5
|
+
import { rabbitMeetings } from "./meets.js";
|
|
6
|
+
import { quantity } from "@mark1russell7/quantity";
|
|
7
|
+
// src/rabbitmq/client.ts
|
|
8
|
+
/** This function gives the problems of a spec: the knobs that the client cannot use. */
|
|
9
|
+
const specProblems = (name, spec) => {
|
|
10
|
+
const { knobs } = spec;
|
|
11
|
+
return [
|
|
12
|
+
...timeProblems(name, knobs),
|
|
13
|
+
...zeroProblems(name, "amqplib", knobs, {
|
|
14
|
+
bounded: ["connect_bound"],
|
|
15
|
+
open: ["heartbeat_interval", "keepalive_idle"]
|
|
16
|
+
}),
|
|
17
|
+
...wholeProblems(name, knobs, {
|
|
18
|
+
millis: ["connect_bound"],
|
|
19
|
+
seconds: ["heartbeat_interval", "keepalive_idle"]
|
|
20
|
+
}),
|
|
21
|
+
...retryProblems(name, knobs),
|
|
22
|
+
...wrapperTimerProblems(name, knobs, { request_timeout: "a call" }),
|
|
23
|
+
...ageProblems(name, knobs, "the client does not replace its connection at an age")
|
|
24
|
+
];
|
|
25
|
+
};
|
|
26
|
+
/** This function gives the node of a try: `host`, then each seed, in sequence. */
|
|
27
|
+
const nodeOf = (spec, index) => {
|
|
28
|
+
const nodes = [{
|
|
29
|
+
host: spec.host,
|
|
30
|
+
port: spec.port
|
|
31
|
+
}, ...spec.seeds ?? []];
|
|
32
|
+
return nodes[index % nodes.length];
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* This function gives the arguments of `connect` for one node of a spec. Each timer of amqplib
|
|
36
|
+
* comes from the declaration. The heartbeat goes in the URL, and "infinite" is 0, no heartbeat.
|
|
37
|
+
*/
|
|
38
|
+
const rabbitOptions = (name, spec, index = 0) => {
|
|
39
|
+
const { knobs } = spec;
|
|
40
|
+
const node = nodeOf(spec, index);
|
|
41
|
+
const user = spec.username === void 0 ? "" : `${encodeURIComponent(spec.username)}:${encodeURIComponent(spec.password ?? "")}@`;
|
|
42
|
+
const heartbeat = finiteMs(knobs.heartbeat_interval);
|
|
43
|
+
const keepalive = finiteMs(knobs.keepalive_idle);
|
|
44
|
+
return {
|
|
45
|
+
url: `amqp://${user}${node.host}:${node.port}/${encodeURIComponent(spec.vhost ?? "/")}?heartbeat=${heartbeat === void 0 ? 0 : heartbeat / 1e3}`,
|
|
46
|
+
socketOptions: {
|
|
47
|
+
timeout: ms(knobs.connect_bound),
|
|
48
|
+
noDelay: true,
|
|
49
|
+
keepAlive: keepalive !== void 0,
|
|
50
|
+
...keepalive === void 0 ? {} : { keepAliveDelay: keepalive },
|
|
51
|
+
clientProperties: { connection_name: name }
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
/** The bytes of the protocol header of AMQP 0-9-1. A broker answers it with `connection.start`, before the authentication. */
|
|
56
|
+
const AMQP_HEADER = Uint8Array.of(65, 77, 81, 80, 0, 0, 9, 1);
|
|
57
|
+
/**
|
|
58
|
+
* This judge reads the answer to the protocol header. A broker that takes the version sends a method
|
|
59
|
+
* frame on channel 0: `connection.start`, class 10 and method 10. A broker that refuses the version
|
|
60
|
+
* sends its own protocol header, and closes the socket.
|
|
61
|
+
*/
|
|
62
|
+
const startJudge = (received) => {
|
|
63
|
+
if (received.length < 4) return "more";
|
|
64
|
+
if (received.toString("latin1", 0, 4) === "AMQP") return /* @__PURE__ */ new Error(`the broker refused the version: it answered ${received.toString("hex")}`);
|
|
65
|
+
if (received.length < 11) return "more";
|
|
66
|
+
const type = received[0];
|
|
67
|
+
const channel = received.readUInt16BE(1);
|
|
68
|
+
const classId = received.readUInt16BE(7);
|
|
69
|
+
const methodId = received.readUInt16BE(9);
|
|
70
|
+
if (type !== 1 || channel !== 0) return /* @__PURE__ */ new Error(`the answer to the header is a frame of type ${type} on channel ${channel}, not a method on channel 0`);
|
|
71
|
+
return classId === 10 && methodId === 10 ? null : /* @__PURE__ */ new Error(`the answer to the header is the method ${classId}.${methodId}, not connection.start (10.10)`);
|
|
72
|
+
};
|
|
73
|
+
/** This dial function opens a TCP connection, sends the protocol header, and waits for `connection.start`. It needs no password. */
|
|
74
|
+
const amqpDial = helloDial(AMQP_HEADER, startJudge);
|
|
75
|
+
/**
|
|
76
|
+
* This function gives the outcome of a failure of amqplib. The library names few classes of error.
|
|
77
|
+
* Thus the wrapper reads the fields:
|
|
78
|
+
* - A throw before the write (`IllegalOperationError`: the channel is closed or closing) is certain: the call did not leave the client.
|
|
79
|
+
* - A reply code of the broker, from the close of the channel, is certain. The broker refused the call, or a call before it.
|
|
80
|
+
* - A nack, and an end of the channel before the reply or the confirm, are not certain.
|
|
81
|
+
*/
|
|
82
|
+
const failureOutcome = (error) => {
|
|
83
|
+
const text = message(error);
|
|
84
|
+
const { name, code } = typeof error === "object" && error !== null ? error : {};
|
|
85
|
+
if (name === "IllegalOperationError") return notSent(text);
|
|
86
|
+
if (typeof code === "number") return {
|
|
87
|
+
outcome: "error",
|
|
88
|
+
error: `${code} ${text}`,
|
|
89
|
+
reply: true
|
|
90
|
+
};
|
|
91
|
+
if (text === "message nacked") return {
|
|
92
|
+
outcome: "indeterminate",
|
|
93
|
+
error: "the broker nacked the message: a queue of the route can hold it, or not"
|
|
94
|
+
};
|
|
95
|
+
return {
|
|
96
|
+
outcome: "indeterminate",
|
|
97
|
+
error: text
|
|
98
|
+
};
|
|
99
|
+
};
|
|
100
|
+
/** This function gives the count of deliveries of a message, 1 at the first. A quorum queue counts in `x-delivery-count`. */
|
|
101
|
+
const deliveryCount = (message) => {
|
|
102
|
+
const count = message.properties.headers?.["x-delivery-count"];
|
|
103
|
+
if (typeof count === "number" && Number.isInteger(count) && count >= 0) return count + 1;
|
|
104
|
+
return message.fields.redelivered ? 2 : 1;
|
|
105
|
+
};
|
|
106
|
+
/** The exchange of each broker: the round-trip check declares it in passive mode, which changes nothing. */
|
|
107
|
+
const CHECK_EXCHANGE = "amq.direct";
|
|
108
|
+
/**
|
|
109
|
+
* This function makes a RabbitMQ client, a dependency of a service over amqplib 2.
|
|
110
|
+
* - It has one connection and one confirm channel, as one generation. The end of either one ends
|
|
111
|
+
* the generation. The client then connects again by itself, to the next node, after a backoff.
|
|
112
|
+
* - It sets each timer of amqplib from the declaration. The built-in recovery of amqplib stays off.
|
|
113
|
+
* - Its call is a confirmed publish, or an RPC with a reply. Each call has a timer of the wrapper, because amqplib has none.
|
|
114
|
+
* - It tells the outcome of a call in three values, and it settles each call in flight at the end of its generation (C8, C10).
|
|
115
|
+
* - It records the node and the name of each connection at the open of its channel (D1).
|
|
116
|
+
*
|
|
117
|
+
* These parts come from the core of the clients: the outcomes, the second try, the wait for a ready client and the backoff.
|
|
118
|
+
* 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.
|
|
119
|
+
*/
|
|
120
|
+
const rabbitClient = (name, spec, options = {}) => {
|
|
121
|
+
const problems = specProblems(name, spec);
|
|
122
|
+
if (problems.length > 0) throw new Error(problems.join("; "));
|
|
123
|
+
const { knobs } = spec;
|
|
124
|
+
const clock = options.clock ?? realClock;
|
|
125
|
+
const random = options.random ?? Math.random;
|
|
126
|
+
const create = options.create ?? nodeAmqp;
|
|
127
|
+
const dial = options.dial ?? amqpDial;
|
|
128
|
+
const operations = operationTable({}, spec.operations);
|
|
129
|
+
const requestTimeout = ms(knobs.request_timeout);
|
|
130
|
+
const backoff = retryBackoff(knobs);
|
|
131
|
+
let status = "none";
|
|
132
|
+
let connection = null;
|
|
133
|
+
let channel = null;
|
|
134
|
+
let generation = 0;
|
|
135
|
+
let token = 0;
|
|
136
|
+
let next = 0;
|
|
137
|
+
const retries = retrySchedule(clock, backoff, random);
|
|
138
|
+
const joins = [];
|
|
139
|
+
const flight = inFlight();
|
|
140
|
+
const readied = readyWait(clock, () => status === "ready");
|
|
141
|
+
const emit = clientRecorder(options.record, clock, name);
|
|
142
|
+
const record = (on, to = status, detail) => {
|
|
143
|
+
const from = status;
|
|
144
|
+
status = to;
|
|
145
|
+
emit(from, to, on, detail);
|
|
146
|
+
};
|
|
147
|
+
const closing = () => status === "closing" || status === "end";
|
|
148
|
+
/** This function closes a connection that the client does not use, in `close_bound`, then destroys its socket. */
|
|
149
|
+
const retire = (c) => {
|
|
150
|
+
withinBound(clock, ms(knobs.close_bound), Promise.resolve().then(() => c.close())).then((ended) => {
|
|
151
|
+
if (!ended) c.connection.stream?.destroy?.();
|
|
152
|
+
});
|
|
153
|
+
};
|
|
154
|
+
/** This function waits for the backoff of the next try, then opens a new generation on the next node. */
|
|
155
|
+
const scheduleRetry = () => retries.schedule(() => {
|
|
156
|
+
if (closing()) return;
|
|
157
|
+
record("retry.connect", "connecting", `try ${retries.tries}, ${nodeOf(spec, next).host}:${nodeOf(spec, next).port}`);
|
|
158
|
+
open();
|
|
159
|
+
});
|
|
160
|
+
/** This function ends the generation that is open. The calls in flight learn it after the rejections of amqplib, which can hold a reply code. */
|
|
161
|
+
const lose = (on, detail) => {
|
|
162
|
+
const c = connection;
|
|
163
|
+
connection = null;
|
|
164
|
+
channel = null;
|
|
165
|
+
if (closing() || c === null) return;
|
|
166
|
+
record(on, "failing", detail);
|
|
167
|
+
clock.after(0, () => flight.settleAll(`the generation ended with the call in flight (${detail})`));
|
|
168
|
+
if (on === "channel.end") retire(c);
|
|
169
|
+
scheduleRetry();
|
|
170
|
+
};
|
|
171
|
+
/** This function listens to a connection from its creation. The error listener stays: in Node, an error with no listener throws. */
|
|
172
|
+
const watch = (c) => {
|
|
173
|
+
c.on("error", (error) => {
|
|
174
|
+
if (c === connection) record("connection.error", status, message(error));
|
|
175
|
+
});
|
|
176
|
+
c.on("close", (error) => {
|
|
177
|
+
if (c === connection) lose("connection.end", error === void 0 ? "the connection closed" : message(error));
|
|
178
|
+
});
|
|
179
|
+
c.on("blocked", (reason) => {
|
|
180
|
+
if (c === connection && status === "ready") record("connection.blocked", "blocked", String(reason));
|
|
181
|
+
});
|
|
182
|
+
c.on("unblocked", () => {
|
|
183
|
+
if (c !== connection || status !== "blocked") return;
|
|
184
|
+
record("connection.unblocked", "ready");
|
|
185
|
+
readied.wake();
|
|
186
|
+
});
|
|
187
|
+
};
|
|
188
|
+
const join = (c, ch, address) => {
|
|
189
|
+
connection = c;
|
|
190
|
+
channel = ch;
|
|
191
|
+
retries.reset();
|
|
192
|
+
const ends = socketEnds(c.connection.stream);
|
|
193
|
+
generation = joins.length + 1;
|
|
194
|
+
const connectionName = ends.localAddress === null ? null : `${ends.localAddress}:${ends.localPort ?? "?"} -> ${ends.remoteAddress ?? "?"}:${ends.remotePort ?? "?"}`;
|
|
195
|
+
joins.push({
|
|
196
|
+
generation,
|
|
197
|
+
at: clock.now(),
|
|
198
|
+
address,
|
|
199
|
+
connectionName,
|
|
200
|
+
...ends
|
|
201
|
+
});
|
|
202
|
+
ch.on("error", (error) => {
|
|
203
|
+
if (ch === channel) record("channel.error", status, message(error));
|
|
204
|
+
});
|
|
205
|
+
ch.on("close", () => {
|
|
206
|
+
queueMicrotask(() => {
|
|
207
|
+
if (ch === channel) lose("channel.end", "the channel closed");
|
|
208
|
+
});
|
|
209
|
+
});
|
|
210
|
+
record("join", "ready", `generation ${generation}, ${address}`);
|
|
211
|
+
readied.wake();
|
|
212
|
+
};
|
|
213
|
+
/**
|
|
214
|
+
* This function opens one generation: a connection, then its confirm channel, in `connect_bound`.
|
|
215
|
+
* A failure goes to `failing`, and the backoff starts. A connection that arrives after its bound
|
|
216
|
+
* or after the close is closed at once. The promise resolves when this try ends.
|
|
217
|
+
*/
|
|
218
|
+
const open = () => {
|
|
219
|
+
const mine = token += 1;
|
|
220
|
+
const index = next;
|
|
221
|
+
next += 1;
|
|
222
|
+
const node = nodeOf(spec, index);
|
|
223
|
+
const address = `${node.host}:${node.port}`;
|
|
224
|
+
let opened = null;
|
|
225
|
+
let finish = () => {};
|
|
226
|
+
const ended = new Promise((resolve) => finish = resolve);
|
|
227
|
+
const stale = () => mine !== token || closing();
|
|
228
|
+
const fail = (detail) => {
|
|
229
|
+
bound();
|
|
230
|
+
finish();
|
|
231
|
+
if (stale()) return;
|
|
232
|
+
token += 1;
|
|
233
|
+
if (opened !== null) retire(opened);
|
|
234
|
+
record("connect.failed", "failing", `${address}: ${detail}`);
|
|
235
|
+
scheduleRetry();
|
|
236
|
+
};
|
|
237
|
+
const bound = clock.after(ms(knobs.connect_bound), () => fail("no open connection and channel in connect_bound"));
|
|
238
|
+
(async () => {
|
|
239
|
+
const c = await create(rabbitOptions(name, spec, index));
|
|
240
|
+
opened = c;
|
|
241
|
+
watch(c);
|
|
242
|
+
if (stale()) {
|
|
243
|
+
retire(c);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
const ch = await c.createConfirmChannel();
|
|
247
|
+
if (stale()) {
|
|
248
|
+
retire(c);
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
bound();
|
|
252
|
+
join(c, ch, address);
|
|
253
|
+
finish();
|
|
254
|
+
})().catch((error) => fail(message(error)));
|
|
255
|
+
return ended;
|
|
256
|
+
};
|
|
257
|
+
/** This function gives the channel for a call, or the reason that the call does not leave the client. */
|
|
258
|
+
const usable = (signal) => {
|
|
259
|
+
if (status === "none") return notSent(`${name} has not connected`);
|
|
260
|
+
if (status !== "ready" || channel === null) return notSent(`${name} is ${status}, not ready: the call did not leave the client`);
|
|
261
|
+
if (signal?.aborted) return notSent("the caller aborted the call before it left the client");
|
|
262
|
+
return channel;
|
|
263
|
+
};
|
|
264
|
+
/** This function makes one try of a publish: the write, then the confirm, in `request_timeout`. */
|
|
265
|
+
const publishAttempt = (sent, signal) => {
|
|
266
|
+
const ch = usable(signal);
|
|
267
|
+
if ("outcome" in ch) return Promise.resolve(ch);
|
|
268
|
+
const content = typeof sent.content === "string" ? Buffer.from(sent.content, "utf8") : sent.content;
|
|
269
|
+
return trackWithTimer(flight, clock, requestTimeout, signal, "the caller abandoned the publish after it was written", "no confirm in request_timeout: the broker can have the message", (settle) => {
|
|
270
|
+
try {
|
|
271
|
+
ch.publish(sent.exchange, sent.routingKey, content, sent.properties ?? {}, (error) => settle(error === null ? {
|
|
272
|
+
outcome: "ok",
|
|
273
|
+
value: void 0
|
|
274
|
+
} : failureOutcome(error)));
|
|
275
|
+
} catch (error) {
|
|
276
|
+
settle(failureOutcome(error));
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
};
|
|
280
|
+
/**
|
|
281
|
+
* This function makes one try of an RPC on the channel, in `request_timeout`. A reply that comes
|
|
282
|
+
* after the call settled goes to `late`, thus a message that nobody receives goes back to its queue.
|
|
283
|
+
*/
|
|
284
|
+
const rpcAttempt = (signal, what, run, value, late) => {
|
|
285
|
+
const ch = usable(signal);
|
|
286
|
+
if ("outcome" in ch) return Promise.resolve(ch);
|
|
287
|
+
let finished = false;
|
|
288
|
+
return trackWithTimer(flight, clock, requestTimeout, signal, `the caller abandoned ${what} after it was sent`, `no reply to ${what} in request_timeout`, (settle) => {
|
|
289
|
+
Promise.resolve().then(() => run(ch)).then((reply) => {
|
|
290
|
+
if (finished) late?.(reply, ch);
|
|
291
|
+
else settle({
|
|
292
|
+
outcome: "ok",
|
|
293
|
+
value: value(reply)
|
|
294
|
+
});
|
|
295
|
+
}, (error) => settle(failureOutcome(error)));
|
|
296
|
+
}, () => {
|
|
297
|
+
finished = true;
|
|
298
|
+
});
|
|
299
|
+
};
|
|
300
|
+
const publish = (operation, sent, sendOptions = {}) => sendWithReissue({
|
|
301
|
+
clock,
|
|
302
|
+
bound: requestTimeout,
|
|
303
|
+
operation: operations[operation],
|
|
304
|
+
options: sendOptions,
|
|
305
|
+
attempt: (signal) => publishAttempt(sent, signal),
|
|
306
|
+
beforeAgain: (left, signal) => readied.wait(left, signal),
|
|
307
|
+
onReissue: () => record("command.reissue", status, operation)
|
|
308
|
+
});
|
|
309
|
+
const get = (operation, queue, sendOptions = {}) => {
|
|
310
|
+
const at = () => generation;
|
|
311
|
+
return sendWithReissue({
|
|
312
|
+
clock,
|
|
313
|
+
bound: requestTimeout,
|
|
314
|
+
operation: operations[operation],
|
|
315
|
+
options: sendOptions,
|
|
316
|
+
attempt: (signal) => {
|
|
317
|
+
const held = at();
|
|
318
|
+
return rpcAttempt(signal, "basic.get", (ch) => ch.get(queue, { noAck: false }), (reply) => reply === false ? null : {
|
|
319
|
+
message: reply,
|
|
320
|
+
generation: held,
|
|
321
|
+
delivery: deliveryCount(reply)
|
|
322
|
+
}, (reply, ch) => {
|
|
323
|
+
if (reply === false) return;
|
|
324
|
+
try {
|
|
325
|
+
ch.nack(reply, false, true);
|
|
326
|
+
} catch {}
|
|
327
|
+
});
|
|
328
|
+
},
|
|
329
|
+
beforeAgain: (left, signal) => readied.wait(left, signal),
|
|
330
|
+
onReissue: () => record("command.reissue", status, operation)
|
|
331
|
+
});
|
|
332
|
+
};
|
|
333
|
+
/** This function gives the channel that holds a delivery. A delivery of an ended generation is back on its queue already (at least once). */
|
|
334
|
+
const holder = (job) => {
|
|
335
|
+
const ch = channel;
|
|
336
|
+
if (ch === null || job.generation !== generation) throw new Error(`${name}: the channel of generation ${job.generation} ended, thus the broker put the message back on its queue`);
|
|
337
|
+
return ch;
|
|
338
|
+
};
|
|
339
|
+
const jobs = (operation, queue) => ({
|
|
340
|
+
source: async (signal) => {
|
|
341
|
+
const taken = await get(operation, queue, { signal });
|
|
342
|
+
if (taken.outcome === "ok") return taken.value;
|
|
343
|
+
throw new Error(`${name} could not take a message from ${queue}: ${taken.error}`);
|
|
344
|
+
},
|
|
345
|
+
settle: {
|
|
346
|
+
ack: (job) => holder(job).ack(job.message),
|
|
347
|
+
requeue: (job) => holder(job).nack(job.message, false, true),
|
|
348
|
+
reject: (job) => holder(job).nack(job.message, false, false),
|
|
349
|
+
delivery: (job) => job.delivery
|
|
350
|
+
}
|
|
351
|
+
});
|
|
352
|
+
const handle = {
|
|
353
|
+
async connect(signal) {
|
|
354
|
+
if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);
|
|
355
|
+
record("status.connecting", "connecting");
|
|
356
|
+
await open();
|
|
357
|
+
},
|
|
358
|
+
async close() {
|
|
359
|
+
if (status === "none" || closing()) return;
|
|
360
|
+
record("close.request", "closing");
|
|
361
|
+
retries.cancel();
|
|
362
|
+
token += 1;
|
|
363
|
+
const c = connection;
|
|
364
|
+
if (c !== null) {
|
|
365
|
+
if (!await withinBound(clock, ms(knobs.close_bound), Promise.resolve().then(() => c.close()))) {
|
|
366
|
+
record("close.bound", "closing");
|
|
367
|
+
record("close.destroy", "closing");
|
|
368
|
+
c.connection.stream?.destroy?.();
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
connection = null;
|
|
372
|
+
channel = null;
|
|
373
|
+
flight.settleAll("the client closed with the call in flight");
|
|
374
|
+
record("status.end", "end");
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
const heartbeat = finiteMs(knobs.heartbeat_interval);
|
|
378
|
+
const declaration = {
|
|
379
|
+
system: spec.system,
|
|
380
|
+
knobs: {
|
|
381
|
+
connect_bound: knobs.connect_bound,
|
|
382
|
+
request_timeout: knobs.request_timeout,
|
|
383
|
+
heartbeat_interval: knobs.heartbeat_interval,
|
|
384
|
+
heartbeat_detection_time: heartbeat === void 0 ? knobs.heartbeat_interval : quantity(3 * heartbeat / 1e3, "s"),
|
|
385
|
+
retry_base: knobs.retry_base,
|
|
386
|
+
retry_cap: knobs.retry_cap,
|
|
387
|
+
keepalive_idle: knobs.keepalive_idle,
|
|
388
|
+
idle_refresh_interval: heartbeat === void 0 ? knobs.keepalive_idle : quantity(heartbeat / 2e3, "s"),
|
|
389
|
+
max_connection_age: knobs.max_connection_age,
|
|
390
|
+
close_bound: knobs.close_bound,
|
|
391
|
+
retrans_giveup_time: knobs.retrans_giveup_time
|
|
392
|
+
},
|
|
393
|
+
operations
|
|
394
|
+
};
|
|
395
|
+
const checks = (checkOptions) => stepChecks(name, checkOptions, {
|
|
396
|
+
"local-state": localStateCheck(() => status === "ready"),
|
|
397
|
+
"round-trip": roundTripCheck((sendOptions) => sendWithReissue({
|
|
398
|
+
clock,
|
|
399
|
+
bound: requestTimeout,
|
|
400
|
+
operation: void 0,
|
|
401
|
+
options: sendOptions,
|
|
402
|
+
attempt: (signal) => rpcAttempt(signal, "a passive exchange.declare", (ch) => ch.checkExchange(CHECK_EXCHANGE), () => void 0),
|
|
403
|
+
onReissue: () => {}
|
|
404
|
+
})),
|
|
405
|
+
dial: dialCheck(dial, spec.host, spec.port)
|
|
406
|
+
});
|
|
407
|
+
return {
|
|
408
|
+
name,
|
|
409
|
+
declaration,
|
|
410
|
+
handle,
|
|
411
|
+
meets: rabbitMeetings(name, knobs),
|
|
412
|
+
get status() {
|
|
413
|
+
return status;
|
|
414
|
+
},
|
|
415
|
+
joins,
|
|
416
|
+
publish,
|
|
417
|
+
get,
|
|
418
|
+
jobs,
|
|
419
|
+
checks,
|
|
420
|
+
attach: (svc, checkOptions) => attachClient(svc, name, declaration, handle, checks(checkOptions)),
|
|
421
|
+
problems: (description) => clientProblems(name, description, clientBounds(knobs))
|
|
422
|
+
};
|
|
423
|
+
};
|
|
424
|
+
export { AMQP_HEADER, amqpDial, deliveryCount, failureOutcome, rabbitClient, rabbitOptions, specProblems, startJudge };
|
|
425
|
+
|
|
426
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../../src/rabbitmq/client.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { quantity } from \"@mark1russell7/quantity\";\nimport { realClock } from \"../clock.ts\";\nimport type { Attempt, CheckOptions, Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, RetryKnobs, SendOptions, Sent } from \"../client/core.ts\";\nimport {\n ageProblems,\n attachClient,\n clientBounds,\n clientProblems,\n clientRecorder,\n dialCheck,\n finiteMs,\n inFlight,\n localStateCheck,\n message,\n ms,\n notSent,\n operationTable,\n readyWait,\n retryBackoff,\n retryProblems,\n retrySchedule,\n roundTripCheck,\n sendWithReissue,\n socketEnds,\n stepChecks,\n timeProblems,\n trackWithTimer,\n wholeProblems,\n withinBound,\n wrapperTimerProblems,\n zeroProblems,\n} from \"../client/core.ts\";\nimport type { Judge } from \"../client/dial.ts\";\nimport { helloDial } from \"../client/dial.ts\";\nimport type { Dependency } from \"../description.ts\";\nimport type { DependencyHandle } from \"../lifecycle.ts\";\nimport type { JobSettle } from \"../queue.ts\";\nimport type { RabbitChannel, RabbitConnectOptions, RabbitConnection, RabbitFactory, RabbitMessage, RabbitPublishOptions } from \"./connection.ts\";\nimport { nodeAmqp } from \"./connection.ts\";\nimport { rabbitMeetings } 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. The constant `RABBIT_STARTING_KNOBS` gives a declaration from the cells of R3. The knobs\n * that each client has come from the core.\n */\nexport interface RabbitKnobs extends ClientKnobs, RetryKnobs {\n /**\n * This time bounds the TCP connect and the handshake (`socketOptions.timeout`). The client also\n * bounds the open of its channel with it. The timer of amqplib stops when the connection opens.\n */\n readonly connect_bound: Quantity;\n /** This time bounds each call: a publish until its confirm, and an RPC until its reply. The wrapper has this timer, because amqplib has none. */\n readonly request_timeout: Quantity;\n /**\n * This time is the heartbeat that the client asks for (`heartbeat` in the URL), in whole seconds.\n * The connection uses the smaller of this value and the value of the broker. The value \"infinite\" asks for no heartbeat.\n */\n readonly heartbeat_interval: Extent;\n /** This time is the first delay before a new try to connect. The delay doubles after each try. */\n readonly retry_base: Quantity;\n /** This time is the most that one delay can be, before its jitter. */\n readonly retry_cap: Quantity;\n /** This time is the idle time of TCP keepalive (`keepAliveDelay`), in whole seconds. The value \"infinite\" turns keepalive off, as amqplib does by default. */\n readonly keepalive_idle: Extent;\n /** The client does not replace its connection at an age, thus this knob must be \"infinite\". */\n readonly max_connection_age: Extent;\n /** This time bounds the close of the client at the shutdown: `connection.close`, then a destroy of the socket. */\n readonly close_bound: Quantity;\n}\n\n/** A seed is one more node of the cluster. The client connects to the next node after each failure, in sequence. */\nexport interface RabbitSeed {\n readonly host: string;\n readonly port: number;\n}\n\n/** A RabbitMQ client spec is the declaration of one RabbitMQ client: where it connects, and its knobs. */\nexport interface RabbitClientSpec extends ClientSpec<RabbitKnobs> {\n /** This name is the virtual host. The default of the broker is \"/\". */\n readonly vhost?: string | undefined;\n /** This name is the user. Without it, amqplib connects as the user \"guest\". */\n readonly username?: string | undefined;\n /** These nodes are more nodes of the cluster, after `host` and `port`. */\n readonly seeds?: readonly RabbitSeed[] | undefined;\n /**\n * These operations are the calls of the service, by name, with their idempotency. A message does\n * not tell if a consumer removes its duplicates. Thus the client sends again only a call that this table names.\n */\n readonly operations?: ClientSpec<RabbitKnobs>[\"operations\"];\n}\n\n/** These options make a client. Without them, it uses amqplib, the real clock, `Math.random`, and a dial with the protocol header. */\nexport interface RabbitClientOptions extends ClientOptions<RabbitFactory> {\n readonly random?: (() => number) | undefined;\n}\n\n/**\n * A join is one generation of the client: one connection and its channel, when the channel is open\n * (D1, D2). The prober joins its kernel records to the view of the broker through it.\n */\nexport interface RabbitJoin extends ClientJoin {\n /** This text is the node of the connection, as `host:port`. */\n readonly address: string;\n /** This text is the name of the connection in the broker, `local:port -> remote:port`, or null when the socket gives no addresses. */\n readonly connectionName: string | null;\n}\n\n/** A publish is one message to an exchange. A string content goes as UTF-8. */\nexport interface RabbitPublish {\n readonly exchange: string;\n readonly routingKey: string;\n readonly content: Buffer | string;\n /** These properties go to amqplib, for example `persistent`, `messageId` and `headers`. */\n readonly properties?: RabbitPublishOptions | undefined;\n}\n\n/** A delivery is one message that the client took from a queue. It stays on the channel of its generation until a settle. */\nexport interface RabbitDelivery {\n readonly message: RabbitMessage;\n /** This number is the generation of the channel that holds the message. */\n readonly generation: number;\n /** This count is the delivery of the message, 1 at the first, from `x-delivery-count` or `redelivered`. */\n readonly delivery: number;\n}\n\n/** These are the source and the settle of a queue drain on one queue: `queueDrain({ source, settle, ... })`. */\nexport interface RabbitJobs {\n /** This function takes one job, or gives null when the queue is empty. It is a `JobSource` of the drain. */\n readonly source: (signal: AbortSignal) => Promise<RabbitDelivery | null>;\n readonly settle: JobSettle<RabbitDelivery>;\n}\n\n/** A RabbitMQ client is a dependency of a service: its declaration, its handle, its checks and its calls. */\nexport interface RabbitClient extends Client<ClientStep, RabbitJoin> {\n /** This text is the state of the client, as `RABBIT_CLIENT_MACHINE` names it. */\n readonly status: string;\n /**\n * This method publishes one message, and waits for its confirm. An ack is `ok`. The client sends\n * again only an idempotent operation, one time at most, after an outcome that is not certain.\n */\n publish(operation: string, message: RabbitPublish, options?: SendOptions): Promise<Sent<void>>;\n /** This method takes one message from a queue (`basic.get`), or gives null when the queue is empty. */\n get(operation: string, queue: string, options?: SendOptions): Promise<Sent<RabbitDelivery | null>>;\n /** This method gives the source and the settle of a queue drain. The source takes each job with `get`. */\n jobs(operation: string, queue: string): RabbitJobs;\n}\n\n/** This function gives the problems of a spec: the knobs that the client cannot use. */\nexport const specProblems = (name: string, spec: RabbitClientSpec): string[] => {\n const { knobs } = spec;\n return [\n ...timeProblems(name, knobs),\n // amqplib reads a socket timeout of 0 as no bound, and a heartbeat of 0 as no heartbeat\n ...zeroProblems(name, \"amqplib\", knobs, { bounded: [\"connect_bound\"], open: [\"heartbeat_interval\", \"keepalive_idle\"] }),\n // the URL takes the heartbeat in whole seconds, and Node truncates the keepalive delay to whole seconds\n ...wholeProblems(name, knobs, { millis: [\"connect_bound\"], seconds: [\"heartbeat_interval\", \"keepalive_idle\"] }),\n ...retryProblems(name, knobs),\n // amqplib has no timer of a call\n ...wrapperTimerProblems(name, knobs, { request_timeout: \"a call\" }),\n ...ageProblems(name, knobs, \"the client does not replace its connection at an age\"),\n ];\n};\n\n/** This function gives the node of a try: `host`, then each seed, in sequence. */\nconst nodeOf = (spec: RabbitClientSpec, index: number): RabbitSeed => {\n const nodes = [{ host: spec.host, port: spec.port }, ...(spec.seeds ?? [])];\n return nodes[index % nodes.length]!;\n};\n\n/**\n * This function gives the arguments of `connect` for one node of a spec. Each timer of amqplib\n * comes from the declaration. The heartbeat goes in the URL, and \"infinite\" is 0, no heartbeat.\n */\nexport const rabbitOptions = (name: string, spec: RabbitClientSpec, index = 0): RabbitConnectOptions => {\n const { knobs } = spec;\n const node = nodeOf(spec, index);\n const user = spec.username === undefined ? \"\" : `${encodeURIComponent(spec.username)}:${encodeURIComponent(spec.password ?? \"\")}@`;\n const heartbeat = finiteMs(knobs.heartbeat_interval);\n const keepalive = finiteMs(knobs.keepalive_idle);\n return {\n url: `amqp://${user}${node.host}:${node.port}/${encodeURIComponent(spec.vhost ?? \"/\")}?heartbeat=${heartbeat === undefined ? 0 : heartbeat / 1000}`,\n socketOptions: {\n timeout: ms(knobs.connect_bound),\n noDelay: true,\n keepAlive: keepalive !== undefined,\n ...(keepalive === undefined ? {} : { keepAliveDelay: keepalive }),\n clientProperties: { connection_name: name },\n },\n };\n};\n\n/** The bytes of the protocol header of AMQP 0-9-1. A broker answers it with `connection.start`, before the authentication. */\nexport const AMQP_HEADER: Uint8Array = Uint8Array.of(0x41, 0x4d, 0x51, 0x50, 0, 0, 9, 1);\n\n/**\n * This judge reads the answer to the protocol header. A broker that takes the version sends a method\n * frame on channel 0: `connection.start`, class 10 and method 10. A broker that refuses the version\n * sends its own protocol header, and closes the socket.\n */\nexport const startJudge: Judge = (received) => {\n if (received.length < 4) return \"more\";\n if (received.toString(\"latin1\", 0, 4) === \"AMQP\") return new Error(`the broker refused the version: it answered ${received.toString(\"hex\")}`);\n if (received.length < 11) return \"more\";\n const type = received[0];\n const channel = received.readUInt16BE(1);\n const classId = received.readUInt16BE(7);\n const methodId = received.readUInt16BE(9);\n if (type !== 1 || channel !== 0) return new Error(`the answer to the header is a frame of type ${type} on channel ${channel}, not a method on channel 0`);\n return classId === 10 && methodId === 10 ? null : new Error(`the answer to the header is the method ${classId}.${methodId}, not connection.start (10.10)`);\n};\n\n/** This dial function opens a TCP connection, sends the protocol header, and waits for `connection.start`. It needs no password. */\nexport const amqpDial: DialFn = helloDial(AMQP_HEADER, startJudge);\n\n/**\n * This function gives the outcome of a failure of amqplib. The library names few classes of error.\n * Thus the wrapper reads the fields:\n * - A throw before the write (`IllegalOperationError`: the channel is closed or closing) is certain: the call did not leave the client.\n * - A reply code of the broker, from the close of the channel, is certain. The broker refused the call, or a call before it.\n * - A nack, and an end of the channel before the reply or the confirm, are not certain.\n */\nexport const failureOutcome = (error: unknown): Attempt<never> => {\n const text = message(error);\n const { name, code } = (typeof error === \"object\" && error !== null ? error : {}) as { name?: unknown; code?: unknown };\n if (name === \"IllegalOperationError\") return notSent(text);\n if (typeof code === \"number\") return { outcome: \"error\", error: `${code} ${text}`, reply: true };\n if (text === \"message nacked\")\n return { outcome: \"indeterminate\", error: \"the broker nacked the message: a queue of the route can hold it, or not\" };\n return { outcome: \"indeterminate\", error: text };\n};\n\n/** This function gives the count of deliveries of a message, 1 at the first. A quorum queue counts in `x-delivery-count`. */\nexport const deliveryCount = (message: RabbitMessage): number => {\n const count = message.properties.headers?.[\"x-delivery-count\"];\n if (typeof count === \"number\" && Number.isInteger(count) && count >= 0) return count + 1;\n return message.fields.redelivered ? 2 : 1;\n};\n\n/** The exchange of each broker: the round-trip check declares it in passive mode, which changes nothing. */\nconst CHECK_EXCHANGE = \"amq.direct\";\n\n/**\n * This function makes a RabbitMQ client, a dependency of a service over amqplib 2.\n * - It has one connection and one confirm channel, as one generation. The end of either one ends\n * the generation. The client then connects again by itself, to the next node, after a backoff.\n * - It sets each timer of amqplib from the declaration. The built-in recovery of amqplib stays off.\n * - Its call is a confirmed publish, or an RPC with a reply. Each call has a timer of the wrapper, because amqplib has none.\n * - It tells the outcome of a call in three values, and it settles each call in flight at the end of its generation (C8, C10).\n * - It records the node and the name of each connection at the open of its channel (D1).\n *\n * These parts come from the core of the clients: the outcomes, the second try, the wait for a ready client and the backoff.\n * 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.\n */\nexport const rabbitClient = (name: string, spec: RabbitClientSpec, options: RabbitClientOptions = {}): RabbitClient => {\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 random = options.random ?? Math.random;\n const create = options.create ?? nodeAmqp;\n const dial = options.dial ?? amqpDial;\n const operations = operationTable({}, spec.operations);\n const requestTimeout = ms(knobs.request_timeout);\n const backoff = retryBackoff(knobs);\n\n let status = \"none\";\n let connection: RabbitConnection | null = null;\n let channel: RabbitChannel | null = null;\n // the generation of the channel that is open now, and the token of the open that is current\n let generation = 0;\n let token = 0;\n // the index of the node of the next try, and the tries since the last join\n let next = 0;\n const retries = retrySchedule(clock, backoff, random);\n const joins: RabbitJoin[] = [];\n const flight = inFlight();\n const readied = readyWait(clock, () => status === \"ready\");\n\n const emit = clientRecorder(options.record, clock, name);\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 /** This function closes a connection that the client does not use, in `close_bound`, then destroys its socket. */\n const retire = (c: RabbitConnection): void => {\n void withinBound(\n clock,\n ms(knobs.close_bound),\n Promise.resolve().then(() => c.close()),\n ).then((ended) => {\n if (!ended) c.connection.stream?.destroy?.();\n });\n };\n\n /** This function waits for the backoff of the next try, then opens a new generation on the next node. */\n const scheduleRetry = (): void =>\n retries.schedule(() => {\n if (closing()) return;\n record(\"retry.connect\", \"connecting\", `try ${retries.tries}, ${nodeOf(spec, next).host}:${nodeOf(spec, next).port}`);\n void open();\n });\n\n /** This function ends the generation that is open. The calls in flight learn it after the rejections of amqplib, which can hold a reply code. */\n const lose = (on: string, detail: string): void => {\n const c = connection;\n connection = null;\n channel = null;\n if (closing() || c === null) return;\n record(on, \"failing\", detail);\n clock.after(0, () => flight.settleAll(`the generation ended with the call in flight (${detail})`));\n // the end of the channel leaves its connection open: the client closes it\n if (on === \"channel.end\") retire(c);\n scheduleRetry();\n };\n\n /** This function listens to a connection from its creation. The error listener stays: in Node, an error with no listener throws. */\n const watch = (c: RabbitConnection): void => {\n c.on(\"error\", (error) => {\n if (c === connection) record(\"connection.error\", status, message(error));\n });\n c.on(\"close\", (error) => {\n if (c === connection) lose(\"connection.end\", error === undefined ? \"the connection closed\" : message(error));\n });\n c.on(\"blocked\", (reason) => {\n if (c === connection && status === \"ready\") record(\"connection.blocked\", \"blocked\", String(reason));\n });\n c.on(\"unblocked\", () => {\n if (c !== connection || status !== \"blocked\") return;\n record(\"connection.unblocked\", \"ready\");\n readied.wake();\n });\n };\n\n const join = (c: RabbitConnection, ch: RabbitChannel, address: string): void => {\n connection = c;\n channel = ch;\n retries.reset();\n const ends = socketEnds(c.connection.stream);\n generation = joins.length + 1;\n const connectionName =\n ends.localAddress === null ? null : `${ends.localAddress}:${ends.localPort ?? \"?\"} -> ${ends.remoteAddress ?? \"?\"}:${ends.remotePort ?? \"?\"}`;\n joins.push({ generation, at: clock.now(), address, connectionName, ...ends });\n ch.on(\"error\", (error) => {\n if (ch === channel) record(\"channel.error\", status, message(error));\n });\n // amqplib closes each channel of a connection that ends, then it emits the close of the connection in the same turn.\n // Thus the client waits for that turn, and an end of the connection is not recorded as an end of the channel\n ch.on(\"close\", () => {\n queueMicrotask(() => {\n if (ch === channel) lose(\"channel.end\", \"the channel closed\");\n });\n });\n record(\"join\", \"ready\", `generation ${generation}, ${address}`);\n readied.wake();\n };\n\n /**\n * This function opens one generation: a connection, then its confirm channel, in `connect_bound`.\n * A failure goes to `failing`, and the backoff starts. A connection that arrives after its bound\n * or after the close is closed at once. The promise resolves when this try ends.\n */\n const open = (): Promise<void> => {\n const mine = (token += 1);\n const index = next;\n next += 1;\n const node = nodeOf(spec, index);\n const address = `${node.host}:${node.port}`;\n let opened: RabbitConnection | null = null;\n let finish: () => void = () => {};\n const ended = new Promise<void>((resolve) => (finish = resolve));\n const stale = (): boolean => mine !== token || closing();\n const fail = (detail: string): void => {\n bound();\n finish();\n if (stale()) return;\n token += 1;\n if (opened !== null) retire(opened);\n record(\"connect.failed\", \"failing\", `${address}: ${detail}`);\n scheduleRetry();\n };\n const bound = clock.after(ms(knobs.connect_bound), () => fail(\"no open connection and channel in connect_bound\"));\n void (async () => {\n const c = await create(rabbitOptions(name, spec, index));\n opened = c;\n watch(c);\n if (stale()) {\n retire(c);\n return;\n }\n const ch = await c.createConfirmChannel();\n if (stale()) {\n retire(c);\n return;\n }\n bound();\n join(c, ch, address);\n finish();\n })().catch((error: unknown) => fail(message(error)));\n return ended;\n };\n\n /** This function gives the channel for a call, or the reason that the call does not leave the client. */\n const usable = (signal: AbortSignal | undefined): RabbitChannel | Attempt<never> => {\n if (status === \"none\") return notSent(`${name} has not connected`);\n if (status !== \"ready\" || channel === null) return notSent(`${name} is ${status}, not ready: the call did not leave the client`);\n if (signal?.aborted) return notSent(\"the caller aborted the call before it left the client\");\n return channel;\n };\n\n /** This function makes one try of a publish: the write, then the confirm, in `request_timeout`. */\n const publishAttempt = (sent: RabbitPublish, signal: AbortSignal | undefined): Promise<Attempt<void>> => {\n const ch = usable(signal);\n if (\"outcome\" in ch) return Promise.resolve(ch);\n const content = typeof sent.content === \"string\" ? Buffer.from(sent.content, \"utf8\") : sent.content;\n return trackWithTimer<void>(\n flight,\n clock,\n requestTimeout,\n signal,\n \"the caller abandoned the publish after it was written\",\n \"no confirm in request_timeout: the broker can have the message\",\n (settle) => {\n try {\n ch.publish(sent.exchange, sent.routingKey, content, sent.properties ?? {}, (error) =>\n settle(error === null ? { outcome: \"ok\", value: undefined } : failureOutcome(error)),\n );\n } catch (error) {\n settle(failureOutcome(error));\n }\n },\n );\n };\n\n /**\n * This function makes one try of an RPC on the channel, in `request_timeout`. A reply that comes\n * after the call settled goes to `late`, thus a message that nobody receives goes back to its queue.\n */\n const rpcAttempt = <T, R>(\n signal: AbortSignal | undefined,\n what: string,\n run: (ch: RabbitChannel) => Promise<R>,\n value: (reply: R) => T,\n late?: (reply: R, ch: RabbitChannel) => void,\n ): Promise<Attempt<T>> => {\n const ch = usable(signal);\n if (\"outcome\" in ch) return Promise.resolve(ch);\n let finished = false;\n return trackWithTimer<T>(\n flight,\n clock,\n requestTimeout,\n signal,\n `the caller abandoned ${what} after it was sent`,\n `no reply to ${what} in request_timeout`,\n (settle) => {\n Promise.resolve()\n .then(() => run(ch))\n .then(\n (reply) => {\n if (finished) late?.(reply, ch);\n else settle({ outcome: \"ok\", value: value(reply) });\n },\n (error: unknown) => settle(failureOutcome(error)),\n );\n },\n () => {\n finished = true;\n },\n );\n };\n\n const publish = (operation: string, sent: RabbitPublish, sendOptions: SendOptions = {}): Promise<Sent<void>> =>\n sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[operation],\n options: sendOptions,\n attempt: (signal) => publishAttempt(sent, signal),\n // the client connects again by itself: the second try waits for a ready client, in the time that is left\n beforeAgain: (left, signal) => readied.wait(left, signal),\n onReissue: () => record(\"command.reissue\", status, operation),\n });\n\n const get = (operation: string, queue: string, sendOptions: SendOptions = {}): Promise<Sent<RabbitDelivery | null>> => {\n const at = (): number => generation;\n return sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[operation],\n options: sendOptions,\n attempt: (signal) => {\n const held = at();\n return rpcAttempt<RabbitDelivery | null, RabbitMessage | false>(\n signal,\n \"basic.get\",\n (ch) => ch.get(queue, { noAck: false }),\n (reply) => (reply === false ? null : { message: reply, generation: held, delivery: deliveryCount(reply) }),\n // a message after the timeout or the abort: nobody holds it, thus it goes back to its queue at once\n (reply, ch) => {\n if (reply === false) return;\n try {\n ch.nack(reply, false, true);\n } catch {\n // the channel ended, and the broker puts the message back by itself\n }\n },\n );\n },\n beforeAgain: (left, signal) => readied.wait(left, signal),\n onReissue: () => record(\"command.reissue\", status, operation),\n });\n };\n\n /** This function gives the channel that holds a delivery. A delivery of an ended generation is back on its queue already (at least once). */\n const holder = (job: RabbitDelivery): RabbitChannel => {\n const ch = channel;\n if (ch === null || job.generation !== generation)\n throw new Error(`${name}: the channel of generation ${job.generation} ended, thus the broker put the message back on its queue`);\n return ch;\n };\n\n const jobs = (operation: string, queue: string): RabbitJobs => ({\n source: async (signal) => {\n const taken = await get(operation, queue, { signal });\n if (taken.outcome === \"ok\") return taken.value;\n throw new Error(`${name} could not take a message from ${queue}: ${taken.error}`);\n },\n settle: {\n ack: (job) => holder(job).ack(job.message),\n requeue: (job) => holder(job).nack(job.message, false, true),\n reject: (job) => holder(job).nack(job.message, false, false),\n delivery: (job) => job.delivery,\n },\n });\n\n const handle: DependencyHandle = {\n async connect(signal) {\n if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);\n record(\"status.connecting\", \"connecting\");\n // a broker that is down does not stop the startup: the client connects again in the background,\n // and its checks keep readiness tripped until it is ready (readiness is earned)\n await open();\n },\n async close() {\n if (status === \"none\" || closing()) return;\n record(\"close.request\", \"closing\");\n retries.cancel();\n // an open in flight is stale now: its connection is closed when it arrives\n token += 1;\n const c = connection;\n if (c !== null) {\n // behind a black hole, connection.close waits for close-ok with no bound: the bound destroys the socket\n if (!(await withinBound(clock, ms(knobs.close_bound), Promise.resolve().then(() => c.close())))) {\n record(\"close.bound\", \"closing\");\n record(\"close.destroy\", \"closing\");\n c.connection.stream?.destroy?.();\n }\n }\n connection = null;\n channel = null;\n flight.settleAll(\"the client closed with the call in flight\");\n record(\"status.end\", \"end\");\n },\n };\n\n const heartbeat = finiteMs(knobs.heartbeat_interval);\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 heartbeat_interval: knobs.heartbeat_interval,\n // each side checks for data at each heartbeat, and ends the connection after two checks with\n // none: 2 to 3 heartbeats after the last data. The cells measured 45.009 s at 15 s\n heartbeat_detection_time: heartbeat === undefined ? knobs.heartbeat_interval : quantity((3 * heartbeat) / 1000, \"s\"),\n retry_base: knobs.retry_base,\n retry_cap: knobs.retry_cap,\n keepalive_idle: knobs.keepalive_idle,\n // each side sends a heartbeat frame each half heartbeat when it sent nothing: that refreshes an idle flow (O03)\n idle_refresh_interval: heartbeat === undefined ? knobs.keepalive_idle : quantity(heartbeat / 2000, \"s\"),\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) =>\n stepChecks<ClientStep>(name, checkOptions, {\n // the state of the client, without a round trip\n \"local-state\": localStateCheck(() => status === \"ready\"),\n // a passive declare of an exchange of each broker, on the channel of the application\n \"round-trip\": roundTripCheck((sendOptions) =>\n sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: undefined,\n options: sendOptions,\n attempt: (signal) => rpcAttempt(signal, \"a passive exchange.declare\", (ch) => ch.checkExchange(CHECK_EXCHANGE), () => undefined),\n onReissue: () => {},\n }),\n ),\n // a new connection each time, with the protocol header and no login\n dial: dialCheck(dial, spec.host, spec.port),\n });\n\n return {\n name,\n declaration,\n handle,\n meets: rabbitMeetings(name, knobs),\n get status() {\n return status;\n },\n joins,\n publish,\n get,\n jobs,\n checks,\n attach: (svc, checkOptions) => attachClient(svc, name, declaration, handle, checks(checkOptions)),\n problems: (description) => clientProblems(name, description, clientBounds(knobs)),\n };\n};\n"],"mappings":";;;;;;;;AAuJA,MAAa,gBAAgB,MAAc,SAAqC;CAC9E,MAAM,EAAE,UAAU;CAClB,OAAO;EACL,GAAG,aAAa,MAAM,KAAK;EAE3B,GAAG,aAAa,MAAM,WAAW,OAAO;GAAE,SAAS,CAAC,eAAe;GAAG,MAAM,CAAC,sBAAsB,gBAAgB;EAAE,CAAC;EAEtH,GAAG,cAAc,MAAM,OAAO;GAAE,QAAQ,CAAC,eAAe;GAAG,SAAS,CAAC,sBAAsB,gBAAgB;EAAE,CAAC;EAC9G,GAAG,cAAc,MAAM,KAAK;EAE5B,GAAG,qBAAqB,MAAM,OAAO,EAAE,iBAAiB,SAAS,CAAC;EAClE,GAAG,YAAY,MAAM,OAAO,sDAAsD;CACpF;AACF;;AAGA,MAAM,UAAU,MAAwB,UAA8B;CACpE,MAAM,QAAQ,CAAC;EAAE,MAAM,KAAK;EAAM,MAAM,KAAK;CAAK,GAAG,GAAI,KAAK,SAAS,CAAC,CAAE;CAC1E,OAAO,MAAM,QAAQ,MAAM;AAC7B;;;;;AAMA,MAAa,iBAAiB,MAAc,MAAwB,QAAQ,MAA4B;CACtG,MAAM,EAAE,UAAU;CAClB,MAAM,OAAO,O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"}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { ClientSocket, Factory } from "../client/core.js";
|
|
2
|
+
/** A message is a message of the broker, as amqplib gives it from `get`. The wrapper reads only these fields. */
|
|
3
|
+
export interface RabbitMessage {
|
|
4
|
+
readonly content: Buffer;
|
|
5
|
+
readonly fields: {
|
|
6
|
+
readonly deliveryTag: number;
|
|
7
|
+
readonly redelivered: boolean;
|
|
8
|
+
readonly exchange: string;
|
|
9
|
+
readonly routingKey: string;
|
|
10
|
+
/** This count is the number of messages that stay on the queue after this one. */
|
|
11
|
+
readonly messageCount?: number | undefined;
|
|
12
|
+
};
|
|
13
|
+
readonly properties: {
|
|
14
|
+
readonly headers?: Readonly<Record<string, unknown>> | undefined;
|
|
15
|
+
readonly [property: string]: unknown;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** These are the properties of a publish that amqplib takes, for example `persistent`, `messageId` and `headers`. */
|
|
19
|
+
export type RabbitPublishOptions = Readonly<Record<string, unknown>>;
|
|
20
|
+
/** These are the events of a channel that the wrapper listens to. */
|
|
21
|
+
export type RabbitChannelEvent = "error" | "close";
|
|
22
|
+
/**
|
|
23
|
+
* A channel is the part of a `ConfirmChannel` of amqplib 2 that the wrapper uses. A confirm channel
|
|
24
|
+
* gives one result to the callback of each publish. The result is null for a `basic.ack`. It is an
|
|
25
|
+
* error for a `basic.nack` and for the end of the channel.
|
|
26
|
+
*/
|
|
27
|
+
export interface RabbitChannel {
|
|
28
|
+
/** This method writes one message. It throws when the channel is closed or closing. */
|
|
29
|
+
publish(exchange: string, routingKey: string, content: Buffer, options: RabbitPublishOptions, callback: (error: Error | null) => void): boolean;
|
|
30
|
+
/** This method takes one message (`basic.get`), or gives false when the queue is empty. It has no timer of its own. */
|
|
31
|
+
get(queue: string, options?: {
|
|
32
|
+
readonly noAck?: boolean | undefined;
|
|
33
|
+
}): Promise<RabbitMessage | false>;
|
|
34
|
+
/** This method declares an exchange in passive mode: an RPC that changes nothing. The round-trip check uses it. */
|
|
35
|
+
checkExchange(exchange: string): Promise<unknown>;
|
|
36
|
+
/** This method acknowledges one message. It is one frame, with no reply. */
|
|
37
|
+
ack(message: RabbitMessage): void;
|
|
38
|
+
/** This method gives one message back to the broker, to the queue or to its dead-letter route. It is one frame, with no reply. */
|
|
39
|
+
nack(message: RabbitMessage, allUpTo?: boolean, requeue?: boolean): void;
|
|
40
|
+
close(): Promise<void>;
|
|
41
|
+
on(event: RabbitChannelEvent, listener: (error?: Error) => void): unknown;
|
|
42
|
+
off(event: RabbitChannelEvent, listener: (error?: Error) => void): unknown;
|
|
43
|
+
}
|
|
44
|
+
/** These are the events of a connection that the wrapper listens to. The event `blocked` gives the reason of the broker. */
|
|
45
|
+
export type RabbitConnectionEvent = "error" | "close" | "blocked" | "unblocked";
|
|
46
|
+
/**
|
|
47
|
+
* A connection is the part of a `ChannelModel` of amqplib 2 that the wrapper uses. A `ChannelModel`
|
|
48
|
+
* has each part. A fake for tests has them too. Thus the package depends on no type of amqplib.
|
|
49
|
+
*/
|
|
50
|
+
export interface RabbitConnection {
|
|
51
|
+
/** This method opens a channel with confirms (`confirm.select`). */
|
|
52
|
+
createConfirmChannel(): Promise<RabbitChannel>;
|
|
53
|
+
/** This method sends `connection.close`, and waits for `connection.close-ok`. Behind a black hole, it waits with no bound. */
|
|
54
|
+
close(): Promise<void>;
|
|
55
|
+
on(event: RabbitConnectionEvent, listener: (detail?: unknown) => void): unknown;
|
|
56
|
+
off(event: RabbitConnectionEvent, listener: (detail?: unknown) => void): unknown;
|
|
57
|
+
/** This field holds the socket. The join reads its addresses, and the bounded close destroys it. */
|
|
58
|
+
readonly connection: {
|
|
59
|
+
readonly stream?: ClientSocket | undefined;
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* These are the socket options that the wrapper gives amqplib. Each one comes from the declaration.
|
|
64
|
+
* At its defaults, amqplib sets no connect timeout, no keepalive and no TCP_NODELAY.
|
|
65
|
+
*/
|
|
66
|
+
export interface RabbitSocketOptions {
|
|
67
|
+
/** This time bounds the TCP connect and the handshake. The timer stops when the connection opens. A time of 0 is no bound. */
|
|
68
|
+
readonly timeout: number;
|
|
69
|
+
/** The library turns Nagle off only when the caller asks. A confirm and a reply then do not wait for a delayed ACK. */
|
|
70
|
+
readonly noDelay: true;
|
|
71
|
+
readonly keepAlive: boolean;
|
|
72
|
+
/** This time is the idle time of TCP keepalive, in milliseconds. Node truncates it to whole seconds. */
|
|
73
|
+
readonly keepAliveDelay?: number | undefined;
|
|
74
|
+
/** The broker shows `connection_name` in its management view and its log, thus the prober can join on it too. */
|
|
75
|
+
readonly clientProperties: {
|
|
76
|
+
readonly connection_name: string;
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/** These are the arguments of `connect(url, socketOptions)`. The URL gives the host, the vhost, the user and the heartbeat. */
|
|
80
|
+
export interface RabbitConnectOptions {
|
|
81
|
+
readonly url: string;
|
|
82
|
+
readonly socketOptions: RabbitSocketOptions;
|
|
83
|
+
}
|
|
84
|
+
/** A connection factory makes one connection of amqplib from its options. A failure to open rejects. */
|
|
85
|
+
export type RabbitFactory = Factory<RabbitConnectOptions, RabbitConnection>;
|
|
86
|
+
/**
|
|
87
|
+
* This factory opens a connection of amqplib. It loads amqplib only when a client connects, thus a
|
|
88
|
+
* service that does not use RabbitMQ does not need it. The specifier is a value, thus the package
|
|
89
|
+
* needs no types of amqplib. The built-in recovery of amqplib stays off, because the wrapper connects again by itself.
|
|
90
|
+
*/
|
|
91
|
+
export declare const nodeAmqp: RabbitFactory;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// src/rabbitmq/connection.ts
|
|
2
|
+
/**
|
|
3
|
+
* This factory opens a connection of amqplib. It loads amqplib only when a client connects, thus a
|
|
4
|
+
* service that does not use RabbitMQ does not need it. The specifier is a value, thus the package
|
|
5
|
+
* needs no types of amqplib. The built-in recovery of amqplib stays off, because the wrapper connects again by itself.
|
|
6
|
+
*/
|
|
7
|
+
const nodeAmqp = async ({ url, socketOptions }) => {
|
|
8
|
+
const loaded = await import("amqplib");
|
|
9
|
+
const connect = loaded.connect ?? loaded.default?.connect;
|
|
10
|
+
if (connect === void 0) throw new Error("amqplib gives no connect function");
|
|
11
|
+
return connect(url, socketOptions);
|
|
12
|
+
};
|
|
13
|
+
export { nodeAmqp };
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=connection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connection.js","names":[],"sources":["../../src/rabbitmq/connection.ts"],"sourcesContent":["import type { ClientSocket, Factory } from \"../client/core.ts\";\n\n/** A message is a message of the broker, as amqplib gives it from `get`. The wrapper reads only these fields. */\nexport interface RabbitMessage {\n readonly content: Buffer;\n readonly fields: {\n readonly deliveryTag: number;\n readonly redelivered: boolean;\n readonly exchange: string;\n readonly routingKey: string;\n /** This count is the number of messages that stay on the queue after this one. */\n readonly messageCount?: number | undefined;\n };\n readonly properties: { readonly headers?: Readonly<Record<string, unknown>> | undefined; readonly [property: string]: unknown };\n}\n\n/** These are the properties of a publish that amqplib takes, for example `persistent`, `messageId` and `headers`. */\nexport type RabbitPublishOptions = Readonly<Record<string, unknown>>;\n\n/** These are the events of a channel that the wrapper listens to. */\nexport type RabbitChannelEvent = \"error\" | \"close\";\n\n/**\n * A channel is the part of a `ConfirmChannel` of amqplib 2 that the wrapper uses. A confirm channel\n * gives one result to the callback of each publish. The result is null for a `basic.ack`. It is an\n * error for a `basic.nack` and for the end of the channel.\n */\nexport interface RabbitChannel {\n /** This method writes one message. It throws when the channel is closed or closing. */\n publish(exchange: string, routingKey: string, content: Buffer, options: RabbitPublishOptions, callback: (error: Error | null) => void): boolean;\n /** This method takes one message (`basic.get`), or gives false when the queue is empty. It has no timer of its own. */\n get(queue: string, options?: { readonly noAck?: boolean | undefined }): Promise<RabbitMessage | false>;\n /** This method declares an exchange in passive mode: an RPC that changes nothing. The round-trip check uses it. */\n checkExchange(exchange: string): Promise<unknown>;\n /** This method acknowledges one message. It is one frame, with no reply. */\n ack(message: RabbitMessage): void;\n /** This method gives one message back to the broker, to the queue or to its dead-letter route. It is one frame, with no reply. */\n nack(message: RabbitMessage, allUpTo?: boolean, requeue?: boolean): void;\n close(): Promise<void>;\n on(event: RabbitChannelEvent, listener: (error?: Error) => void): unknown;\n off(event: RabbitChannelEvent, listener: (error?: Error) => void): unknown;\n}\n\n/** These are the events of a connection that the wrapper listens to. The event `blocked` gives the reason of the broker. */\nexport type RabbitConnectionEvent = \"error\" | \"close\" | \"blocked\" | \"unblocked\";\n\n/**\n * A connection is the part of a `ChannelModel` of amqplib 2 that the wrapper uses. A `ChannelModel`\n * has each part. A fake for tests has them too. Thus the package depends on no type of amqplib.\n */\nexport interface RabbitConnection {\n /** This method opens a channel with confirms (`confirm.select`). */\n createConfirmChannel(): Promise<RabbitChannel>;\n /** This method sends `connection.close`, and waits for `connection.close-ok`. Behind a black hole, it waits with no bound. */\n close(): Promise<void>;\n on(event: RabbitConnectionEvent, listener: (detail?: unknown) => void): unknown;\n off(event: RabbitConnectionEvent, listener: (detail?: unknown) => void): unknown;\n /** This field holds the socket. The join reads its addresses, and the bounded close destroys it. */\n readonly connection: { readonly stream?: ClientSocket | undefined };\n}\n\n/**\n * These are the socket options that the wrapper gives amqplib. Each one comes from the declaration.\n * At its defaults, amqplib sets no connect timeout, no keepalive and no TCP_NODELAY.\n */\nexport interface RabbitSocketOptions {\n /** This time bounds the TCP connect and the handshake. The timer stops when the connection opens. A time of 0 is no bound. */\n readonly timeout: number;\n /** The library turns Nagle off only when the caller asks. A confirm and a reply then do not wait for a delayed ACK. */\n readonly noDelay: true;\n readonly keepAlive: boolean;\n /** This time is the idle time of TCP keepalive, in milliseconds. Node truncates it to whole seconds. */\n readonly keepAliveDelay?: number | undefined;\n /** The broker shows `connection_name` in its management view and its log, thus the prober can join on it too. */\n readonly clientProperties: { readonly connection_name: string };\n}\n\n/** These are the arguments of `connect(url, socketOptions)`. The URL gives the host, the vhost, the user and the heartbeat. */\nexport interface RabbitConnectOptions {\n readonly url: string;\n readonly socketOptions: RabbitSocketOptions;\n}\n\n/** A connection factory makes one connection of amqplib from its options. A failure to open rejects. */\nexport type RabbitFactory = Factory<RabbitConnectOptions, RabbitConnection>;\n\n/**\n * This factory opens a connection of amqplib. It loads amqplib only when a client connects, thus a\n * service that does not use RabbitMQ does not need it. The specifier is a value, thus the package\n * needs no types of amqplib. The built-in recovery of amqplib stays off, because the wrapper connects again by itself.\n */\nexport const nodeAmqp: RabbitFactory = async ({ url, socketOptions }) => {\n const specifier = \"amqplib\";\n type Connect = (url: string, options: RabbitSocketOptions) => Promise<RabbitConnection>;\n const loaded = (await import(specifier)) as { readonly connect?: Connect; readonly default?: { readonly connect: Connect } };\n const connect = loaded.connect ?? loaded.default?.connect;\n if (connect === undefined) throw new Error(\"amqplib gives no connect function\");\n return connect(url, socketOptions);\n};\n"],"mappings":";;;;;;AA2FA,MAAa,WAA0B,OAAO,EAAE,KAAK,oBAAoB;CAGvE,MAAM,SAAU,MAAM,OAAO;CAC7B,MAAM,UAAU,OAAO,WAAW,OAAO,SAAS;CAClD,IAAI,YAAY,KAAA,GAAW,MAAM,IAAI,MAAM,mCAAmC;CAC9E,OAAO,QAAQ,KAAK,aAAa;AACnC"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Machine } from "@mark1russell7/algebra";
|
|
2
|
+
/**
|
|
3
|
+
* The RabbitMQ client of the service as a `mark1russell7.machine/1` document. It is one generation
|
|
4
|
+
* at a time: one connection of amqplib and its confirm channel. The machines `amqplib` and
|
|
5
|
+
* `rabbitmq-connection` of `@mark1russell7/machines` give the connection and its heartbeat. The states:
|
|
6
|
+
* - `ready`: the channel is open, and the client sends each call.
|
|
7
|
+
* - `blocked`: a resource alarm of the broker blocked the connection. Each call is not sent until the unblock.
|
|
8
|
+
* - `failing`: no generation is open. The client tries the next node after its backoff.
|
|
9
|
+
*
|
|
10
|
+
* The end of the channel or of the connection ends the generation. A test records the transitions
|
|
11
|
+
* of the client and replays them against this document.
|
|
12
|
+
*/
|
|
13
|
+
export declare const RABBIT_CLIENT_MACHINE: Machine;
|