@mark1russell7/service 0.8.20 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/watchdog.js CHANGED
@@ -1,6 +1,10 @@
1
1
  import { valueIn } from "@mark1russell7/quantity";
2
2
  // src/watchdog.ts
3
- /** This function starts a watchdog on a clock. */
3
+ /**
4
+ * This function starts a watchdog on a clock. The tick only watches the event loop. Thus a service
5
+ * gives the watchdog `unrefClock(clock)`, and the work of the service keeps the process alive. A
6
+ * watchdog on a clock that keeps the process alive keeps it alive until `stop()`.
7
+ */
4
8
  const watchdog = (clock, spec, trace) => {
5
9
  const tick = valueIn(spec.tick, "ms");
6
10
  const threshold = valueIn(spec.threshold, "ms");
@@ -1 +1 @@
1
- {"version":3,"file":"watchdog.js","names":[],"sources":["../src/watchdog.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { valueIn } from \"@mark1russell7/quantity\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { Gate } from \"./description.ts\";\nimport type { Outcome, Trace } from \"./latch.ts\";\nimport type { Poll } from \"./timing.ts\";\n\n/**\n * A watchdog spec declares a watchdog of the event loop. The service declares it as a check whose\n * function the watchdog gives: the process's own wedge, which a liveness window reads.\n */\nexport interface WatchdogSpec {\n readonly name: string;\n /** This time is the interval of the tick of the watchdog. */\n readonly tick: Quantity;\n /** This time is the most that a tick can be late before the loop counts as blocked. */\n readonly threshold: Quantity;\n /** This gate is the policy that the check controls, or null for a check that only reports. */\n readonly gates: Gate | null;\n readonly poll: Poll;\n}\n\n/**\n * A watchdog measures how late its own tick comes. A blocked event loop delays each timer, thus a\n * tick that comes later than the threshold shows the block. Its states are `watching`, `blocked`\n * and `stopped`.\n */\nexport interface Watchdog {\n /** This function is the check: it fails when a tick since the last poll came late, or the loop is still blocked. */\n readonly check: () => Outcome;\n /** This time is the most that a tick was late, in milliseconds, since the start. */\n readonly worst: number;\n readonly blocked: boolean;\n stop(): void;\n}\n\n/** This function starts a watchdog on a clock. */\nexport const watchdog = (clock: Clock, spec: WatchdogSpec, trace?: Trace): Watchdog => {\n const tick = valueIn(spec.tick, \"ms\");\n const threshold = valueIn(spec.threshold, \"ms\");\n if (!(tick > 0)) throw new RangeError(`watchdog ${spec.name} ticks every ${tick} ms, not above zero`);\n let blocked = false;\n let stopped = false;\n let worst = 0;\n // the worst lateness since the last poll of the check\n let sincePoll = 0;\n let next: Cancel | null = null;\n\n const named = (): string => (stopped ? \"stopped\" : blocked ? \"blocked\" : \"watching\");\n const arm = (): void => {\n const due = clock.now() + tick;\n next = clock.after(tick, () => {\n next = null;\n if (stopped) return;\n const late = Math.max(0, clock.now() - due);\n worst = Math.max(worst, late);\n sincePoll = Math.max(sincePoll, late);\n const from = named();\n blocked = late > threshold;\n trace?.(from, named(), \"tick\");\n arm();\n });\n };\n arm();\n\n return {\n check: () => {\n const failed = blocked || sincePoll > threshold;\n sincePoll = 0;\n return failed ? \"error\" : \"ok\";\n },\n get worst() {\n return worst;\n },\n get blocked() {\n return blocked;\n },\n stop() {\n if (stopped) return;\n const from = named();\n stopped = true;\n next?.();\n next = null;\n trace?.(from, \"stopped\", \"stop\");\n },\n };\n};\n"],"mappings":";;;AAqCA,MAAa,YAAY,OAAc,MAAoB,UAA4B;CACrF,MAAM,OAAO,QAAQ,KAAK,MAAM,IAAI;CACpC,MAAM,YAAY,QAAQ,KAAK,WAAW,IAAI;CAC9C,IAAI,EAAE,OAAO,IAAI,MAAM,IAAI,WAAW,YAAY,KAAK,KAAK,eAAe,KAAK,oBAAoB;CACpG,IAAI,UAAU;CACd,IAAI,UAAU;CACd,IAAI,QAAQ;CAEZ,IAAI,YAAY;CAChB,IAAI,OAAsB;CAE1B,MAAM,cAAuB,UAAU,YAAY,UAAU,YAAY;CACzE,MAAM,YAAkB;EACtB,MAAM,MAAM,MAAM,IAAI,IAAI;EAC1B,OAAO,MAAM,MAAM,YAAY;GAC7B,OAAO;GACP,IAAI,SAAS;GACb,MAAM,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,IAAI,GAAG;GAC1C,QAAQ,KAAK,IAAI,OAAO,IAAI;GAC5B,YAAY,KAAK,IAAI,WAAW,IAAI;GACpC,MAAM,OAAO,MAAM;GACnB,UAAU,OAAO;GACjB,QAAQ,MAAM,MAAM,GAAG,MAAM;GAC7B,IAAI;EACN,CAAC;CACH;CACA,IAAI;CAEJ,OAAO;EACL,aAAa;GACX,MAAM,SAAS,WAAW,YAAY;GACtC,YAAY;GACZ,OAAO,SAAS,UAAU;EAC5B;EACA,IAAI,QAAQ;GACV,OAAO;EACT;EACA,IAAI,UAAU;GACZ,OAAO;EACT;EACA,OAAO;GACL,IAAI,SAAS;GACb,MAAM,OAAO,MAAM;GACnB,UAAU;GACV,OAAO;GACP,OAAO;GACP,QAAQ,MAAM,WAAW,MAAM;EACjC;CACF;AACF"}
1
+ {"version":3,"file":"watchdog.js","names":[],"sources":["../src/watchdog.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { valueIn } from \"@mark1russell7/quantity\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { Gate } from \"./description.ts\";\nimport type { Outcome, Trace } from \"./latch.ts\";\nimport type { Poll } from \"./timing.ts\";\n\n/**\n * A watchdog spec declares a watchdog of the event loop. The service declares it as a check whose\n * function the watchdog gives: the process's own wedge, which a liveness window reads.\n */\nexport interface WatchdogSpec {\n readonly name: string;\n /** This time is the interval of the tick of the watchdog. */\n readonly tick: Quantity;\n /** This time is the most that a tick can be late before the loop counts as blocked. */\n readonly threshold: Quantity;\n /** This gate is the policy that the check controls, or null for a check that only reports. */\n readonly gates: Gate | null;\n readonly poll: Poll;\n}\n\n/**\n * A watchdog measures how late its own tick comes. A blocked event loop delays each timer, thus a\n * tick that comes later than the threshold shows the block. Its states are `watching`, `blocked`\n * and `stopped`.\n */\nexport interface Watchdog {\n /** This function is the check: it fails when a tick since the last poll came late, or the loop is still blocked. */\n readonly check: () => Outcome;\n /** This time is the most that a tick was late, in milliseconds, since the start. */\n readonly worst: number;\n readonly blocked: boolean;\n stop(): void;\n}\n\n/**\n * This function starts a watchdog on a clock. The tick only watches the event loop. Thus a service\n * gives the watchdog `unrefClock(clock)`, and the work of the service keeps the process alive. A\n * watchdog on a clock that keeps the process alive keeps it alive until `stop()`.\n */\nexport const watchdog = (clock: Clock, spec: WatchdogSpec, trace?: Trace): Watchdog => {\n const tick = valueIn(spec.tick, \"ms\");\n const threshold = valueIn(spec.threshold, \"ms\");\n if (!(tick > 0)) throw new RangeError(`watchdog ${spec.name} ticks every ${tick} ms, not above zero`);\n let blocked = false;\n let stopped = false;\n let worst = 0;\n // the worst lateness since the last poll of the check\n let sincePoll = 0;\n let next: Cancel | null = null;\n\n const named = (): string => (stopped ? \"stopped\" : blocked ? \"blocked\" : \"watching\");\n const arm = (): void => {\n const due = clock.now() + tick;\n next = clock.after(tick, () => {\n next = null;\n if (stopped) return;\n const late = Math.max(0, clock.now() - due);\n worst = Math.max(worst, late);\n sincePoll = Math.max(sincePoll, late);\n const from = named();\n blocked = late > threshold;\n trace?.(from, named(), \"tick\");\n arm();\n });\n };\n arm();\n\n return {\n check: () => {\n const failed = blocked || sincePoll > threshold;\n sincePoll = 0;\n return failed ? \"error\" : \"ok\";\n },\n get worst() {\n return worst;\n },\n get blocked() {\n return blocked;\n },\n stop() {\n if (stopped) return;\n const from = named();\n stopped = true;\n next?.();\n next = null;\n trace?.(from, \"stopped\", \"stop\");\n },\n };\n};\n"],"mappings":";;;;;;;AAyCA,MAAa,YAAY,OAAc,MAAoB,UAA4B;CACrF,MAAM,OAAO,QAAQ,KAAK,MAAM,IAAI;CACpC,MAAM,YAAY,QAAQ,KAAK,WAAW,IAAI;CAC9C,IAAI,EAAE,OAAO,IAAI,MAAM,IAAI,WAAW,YAAY,KAAK,KAAK,eAAe,KAAK,oBAAoB;CACpG,IAAI,UAAU;CACd,IAAI,UAAU;CACd,IAAI,QAAQ;CAEZ,IAAI,YAAY;CAChB,IAAI,OAAsB;CAE1B,MAAM,cAAuB,UAAU,YAAY,UAAU,YAAY;CACzE,MAAM,YAAkB;EACtB,MAAM,MAAM,MAAM,IAAI,IAAI;EAC1B,OAAO,MAAM,MAAM,YAAY;GAC7B,OAAO;GACP,IAAI,SAAS;GACb,MAAM,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,IAAI,GAAG;GAC1C,QAAQ,KAAK,IAAI,OAAO,IAAI;GAC5B,YAAY,KAAK,IAAI,WAAW,IAAI;GACpC,MAAM,OAAO,MAAM;GACnB,UAAU,OAAO;GACjB,QAAQ,MAAM,MAAM,GAAG,MAAM;GAC7B,IAAI;EACN,CAAC;CACH;CACA,IAAI;CAEJ,OAAO;EACL,aAAa;GACX,MAAM,SAAS,WAAW,YAAY;GACtC,YAAY;GACZ,OAAO,SAAS,UAAU;EAC5B;EACA,IAAI,QAAQ;GACV,OAAO;EACT;EACA,IAAI,UAAU;GACZ,OAAO;EACT;EACA,OAAO;GACL,IAAI,SAAS;GACb,MAAM,OAAO,MAAM;GACnB,UAAU;GACV,OAAO;GACP,OAAO;GACP,QAAQ,MAAM,WAAW,MAAM;EACjC;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { realClock } from "../clock.js";
1
+ import { realClock, unrefClock } from "../clock.js";
2
2
  import { ageProblems, attachClient, clientBounds, clientProblems, clientRecorder, dialCheck, finiteMs, inFlight, localStateCheck, message, missesProblems, ms, notSent, operationTable, readyWait, retryBackoff, retryProblems, retrySchedule, roundTripCheck, sendWithReissue, socketEnds, stepChecks, timeProblems, trackWithTimer, wholeProblems, withinBound, wrapperTimerProblems, zeroProblems } from "../client/core.js";
3
3
  import { authority, helloDial, statusLineJudge } from "../client/dial.js";
4
4
  import { heartbeat } from "../heartbeat.js";
@@ -179,7 +179,7 @@ const wsClient = (name, spec, options = {}) => {
179
179
  interval: ms(knobs.heartbeat_interval),
180
180
  timeout: ms(knobs.heartbeat_timeout),
181
181
  misses: spec.heartbeatMisses,
182
- clock,
182
+ clock: unrefClock(clock),
183
183
  turn,
184
184
  due: () => status === "ready",
185
185
  live: () => status === "ready",
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":[],"sources":["../../src/websocket/client.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { realClock } from \"../clock.ts\";\nimport type {\n Attempt,\n CheckOptions,\n Client,\n ClientJoin,\n ClientKnobs,\n ClientOptions,\n ClientSpec,\n ClientStep,\n DialFn,\n RetryKnobs,\n SendOptions,\n Sent,\n Settle,\n} 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 missesProblems,\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 { authority, helloDial, statusLineJudge } from \"../client/dial.ts\";\nimport type { Dependency } from \"../description.ts\";\nimport type { Heartbeat } from \"../heartbeat.ts\";\nimport { heartbeat } from \"../heartbeat.ts\";\nimport type { DependencyHandle } from \"../lifecycle.ts\";\nimport type { Operation } from \"../operation.ts\";\nimport { heartbeatDetection } from \"../timing.ts\";\nimport type { WsConnectOptions, WsConnection, WsFactory } from \"./connection.ts\";\nimport { nodeWs } from \"./connection.ts\";\nimport { wsMeetings } from \"./meets.ts\";\n\n/**\n * These are the knobs of the client, each a time, by the names of the ordering law. The runtime has\n * no defaults, thus each knob is necessary. A bound that nobody gives is \"infinite\", not zero. The\n * constant `WS_CLIENT_STARTING_KNOBS` gives a declaration from the WS cells. The knobs that each client has come from the core.\n */\nexport interface WsKnobs extends ClientKnobs, RetryKnobs {\n /** This time bounds the TCP connect and the upgrade (`handshakeTimeout` of ws). The wrapper also bounds the open with it. */\n readonly connect_bound: Quantity;\n /** This time bounds each call: a request until its reply, and a ping until its pong. The wrapper has this timer, because ws has none. */\n readonly request_timeout: Quantity;\n /** This time is the interval of the ping frames of the heartbeat, from the start of one to the start of the next. \"infinite\" sends no ping. */\n readonly heartbeat_interval: Extent;\n /** This time bounds each ping of the heartbeat. A ping with no pong in this time is a miss. */\n readonly heartbeat_timeout: Quantity;\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 (`keepAliveInitialDelay`), in whole seconds. \"infinite\" keeps keepalive off, as ws does. */\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 at the shutdown: the calls in flight, then the close handshake. At the bound, `terminate()` destroys the socket. */\n readonly close_bound: Quantity;\n}\n\n/** A reply is the id of the request that a message answers, and the error of the server when the reply tells one. */\nexport interface WsReply {\n readonly id: string;\n readonly error?: string | undefined;\n}\n\n/**\n * The replies of a protocol tell which message of the server answers which request. WebSocket has no\n * reply of its own: each application protocol puts an id in its messages, for example JSON-RPC 2.0.\n */\nexport interface WsReplies {\n /** This function reads one message of the server. It gives its reply, or null for a message that answers no request. */\n reply(data: Buffer, binary: boolean): WsReply | null;\n}\n\n/** A WebSocket client spec is the declaration of one WebSocket client: where it connects, and its knobs. */\nexport interface WsClientSpec extends ClientSpec<WsKnobs> {\n /** This path is the path of the upgrade request. The default is \"/\". */\n readonly path?: string | undefined;\n /** These names are the subprotocols that the client offers (`Sec-WebSocket-Protocol`). */\n readonly protocols?: readonly string[] | undefined;\n /** These headers go with the upgrade request and with the dial, for example `authorization`. */\n readonly headers?: Readonly<Record<string, string>> | undefined;\n /** This count is the number of heartbeat misses in sequence that end the connection. The cells used 1. */\n readonly heartbeatMisses: number;\n /** These replies match a message of the server to its request. Without them, the client sends no request. */\n readonly replies?: WsReplies | undefined;\n /**\n * These operations are the calls of the service, by name, with their idempotency. A message does\n * not tell if the server removes its duplicates. Thus the client sends again only a call that this table names, and a ping.\n */\n readonly operations?: ClientSpec<WsKnobs>[\"operations\"];\n}\n\n/** These options make a client. Without them, it uses ws, the real clock, `Math.random`, and a dial with the upgrade request. */\nexport interface WsClientOptions extends ClientOptions<WsFactory> {\n readonly random?: (() => number) | undefined;\n /**\n * This function waits one turn of the event loop. The heartbeat waits it before it counts a miss,\n * thus a pong that is in the socket counts first. The default is `setImmediate`.\n */\n readonly turn?: (() => Promise<void>) | undefined;\n}\n\n/** A join is one generation of the client: one connection, when its upgrade ended with 101 (D1, D2). WebSocket gives no id of a connection. */\nexport interface WsJoin extends ClientJoin {\n /** This URL is the URL of the connection. */\n readonly url: string;\n /** This text is the subprotocol that the server chose, or \"\" when it chose none. */\n readonly protocol: string;\n}\n\n/** A request is one message to the server, with the id that its reply gives back. */\nexport interface WsRequest {\n readonly id: string;\n /** This data goes as one message. A string goes as a text message, and a buffer as a binary message. */\n readonly data: string | Buffer;\n}\n\n/** A response is the message of the server that answered a request. */\nexport interface WsResponse {\n readonly data: Buffer;\n readonly binary: boolean;\n}\n\n/** A message listener receives each message of the server that answers no request. */\nexport type WsMessageListener = (data: Buffer, binary: boolean) => void;\n\n/** A WebSocket client is a dependency of a service: its declaration, its handle, its checks and its calls. */\nexport interface WsClient extends Client<ClientStep, WsJoin> {\n /** This text is the state of the client, as `WS_CLIENT_MACHINE` names it. */\n readonly status: string;\n /**\n * This method sends a request, and waits for its reply. A reply is `ok`, or a certain error when it\n * tells one. The client sends again only an idempotent operation, one time at most, after an outcome that is not certain.\n */\n request(operation: string, call: WsRequest, options?: SendOptions): Promise<Sent<WsResponse>>;\n /** This method sends a ping frame, and waits for a pong. A pong is `ok`. A ping is idempotent, thus the client can send it again. */\n ping(options?: SendOptions): Promise<Sent<void>>;\n /** This method sends one message with no reply. It gives true when ws took the message, and false when the client is not ready. */\n send(data: string | Buffer): boolean;\n /** This method adds a listener of the messages that answer no request. It gives the function that removes it. */\n onMessage(listener: WsMessageListener): () => void;\n}\n\n/** These operations are in each table: a ping frame is idempotent (RFC 6455 §5.5.2). */\nexport const WS_OPERATIONS: Readonly<Record<string, Operation>> = { ping: { idempotent: true } };\n\n/** This function gives the problems of a spec: the knobs that the client cannot use. */\nexport const specProblems = (name: string, spec: WsClientSpec): string[] => {\n const { knobs } = spec;\n const problems = [\n ...timeProblems(name, knobs),\n // ws has no timer of a call. The open and the pings have a timer of the wrapper too\n ...wrapperTimerProblems(name, knobs, { connect_bound: \"an open\", request_timeout: \"a call\", heartbeat_timeout: \"a ping of the heartbeat\" }),\n ...zeroProblems(name, \"the client\", knobs, { open: [\"heartbeat_interval\", \"keepalive_idle\"] }),\n // Node truncates the keepalive delay to whole seconds\n ...wholeProblems(name, knobs, { seconds: [\"keepalive_idle\"] }),\n ...retryProblems(name, knobs),\n ...missesProblems(name, spec.heartbeatMisses, \"heartbeat\"),\n ...ageProblems(name, knobs, \"the client does not replace its connection at an age\"),\n ];\n // one ping at a time: the time of detection holds only when each tick sends a ping\n const interval = finiteMs(knobs.heartbeat_interval);\n const timeout = finiteMs(knobs.heartbeat_timeout);\n if (interval !== undefined && interval > 0 && timeout !== undefined && spec.heartbeatMisses > 1 && timeout >= interval)\n problems.push(`${name}'s heartbeat_timeout is not below its heartbeat_interval: with one ping at a time, a tick sends no ping while a ping waits`);\n if (spec.path !== undefined && !spec.path.startsWith(\"/\")) problems.push(`${name}'s path does not start with \"/\"`);\n if (spec.password !== undefined) problems.push(`${name} takes no password: give the credentials in headers, for example authorization`);\n return problems;\n};\n\n/** This function gives the URL of a spec. The client speaks ws:// only. */\nexport const wsUrl = (spec: WsClientSpec): string => `ws://${authority(spec.host, spec.port)}${spec.path ?? \"/\"}`;\n\n/** This function gives the arguments of `new WebSocket` from a spec. Each timer of ws comes from the declaration. */\nexport const wsOptions = (spec: WsClientSpec): WsConnectOptions => {\n const { knobs } = spec;\n const keepalive = finiteMs(knobs.keepalive_idle);\n return {\n url: wsUrl(spec),\n protocols: spec.protocols ?? [],\n options: {\n handshakeTimeout: ms(knobs.connect_bound),\n autoPong: true,\n closeTimeout: ms(knobs.close_bound),\n keepAlive: keepalive !== undefined,\n ...(keepalive === undefined ? {} : { keepAliveInitialDelay: keepalive }),\n ...(spec.headers === undefined ? {} : { headers: spec.headers }),\n },\n };\n};\n\n/** The key of the dial. RFC 6455 §1.3 gives it as its example. The dial does not read the accept of the server. */\nconst DIAL_KEY = \"dGhlIHNhbXBsZSBub25jZQ==\";\n\n/** This function gives the bytes of the dial: the upgrade request of RFC 6455 §4.1, with the subprotocols and the headers of the spec. */\nexport const upgradeRequest = (spec: Pick<WsClientSpec, \"host\" | \"port\" | \"path\" | \"protocols\" | \"headers\">): string => {\n const lines = [\n `GET ${spec.path ?? \"/\"} HTTP/1.1`,\n `Host: ${authority(spec.host, spec.port)}`,\n \"Upgrade: websocket\",\n \"Connection: Upgrade\",\n `Sec-WebSocket-Key: ${DIAL_KEY}`,\n \"Sec-WebSocket-Version: 13\",\n ...(spec.protocols === undefined || spec.protocols.length === 0 ? [] : [`Sec-WebSocket-Protocol: ${spec.protocols.join(\", \")}`]),\n ...Object.entries(spec.headers ?? {}).map(([header, value]) => `${header}: ${value}`),\n ];\n return `${lines.join(\"\\r\\n\")}\\r\\n\\r\\n`;\n};\n\n/** This judge reads the status line of the answer to the upgrade. Only 101 passes: a WebSocket server takes the upgrade. */\nexport const upgradeJudge: Judge = statusLineJudge((status, line) =>\n status === 101 ? null : new Error(`the server answered ${JSON.stringify(line)} to the upgrade, not 101`),\n);\n\n/** This function makes the dial of a spec: a new TCP connection, the upgrade request, and a wait for 101. The dial then destroys its socket. */\nexport const wsDial =\n (spec: Pick<WsClientSpec, \"path\" | \"protocols\" | \"headers\">): DialFn =>\n (host, port, signal) =>\n helloDial(upgradeRequest({ ...spec, host, port }), upgradeJudge)(host, port, signal);\n\n/** This function gives the payload of a ping: its sequence number as text. */\nconst payload = (sequence: number): Buffer => Buffer.from(String(sequence), \"latin1\");\n\n/**\n * This function makes a WebSocket client, a dependency of a service over ws 8.\n * - It has one connection as one generation. The end of the connection ends the generation. The\n * client then connects again by itself, after a backoff.\n * - Its calls are a request until its reply, and a ping until its pong. Each call has a timer of\n * the wrapper, because ws has none.\n * - Its heartbeat sends a ping frame each interval, one at a time. A ping with no pong in its timeout\n * is a miss. At the last miss, `terminate()` destroys the socket at once, and the client connects again.\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 URL and the ends of the socket of each connection at its open (D1).\n *\n * These parts come from the core of the clients: the outcomes, the second try and the wait for a ready\n * client. The backoff and its schedule, the calls in flight, the bounded close and the checks come from\n * the core too. The heartbeat is the heartbeat of the package. This entry gives what ws does in its own way.\n */\nexport const wsClient = (name: string, spec: WsClientSpec, options: WsClientOptions = {}): WsClient => {\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 ?? nodeWs;\n const dial = options.dial ?? wsDial(spec);\n const turn = options.turn ?? (() => new Promise<void>((resolve) => setImmediate(resolve)));\n const operations = operationTable(WS_OPERATIONS, spec.operations);\n const requestTimeout = ms(knobs.request_timeout);\n const url = wsUrl(spec);\n\n let status = \"none\";\n let connection: WsConnection | null = null;\n // the token of the open that is current, and the sequence of the ping frames\n let token = 0;\n let sequence = 0;\n let beat: Heartbeat | null = null;\n // this function ends the wait of the close for the close frame of the server\n let closed: (() => void) | null = null;\n const retries = retrySchedule(clock, retryBackoff(knobs), random);\n const joins: WsJoin[] = [];\n const flight = inFlight();\n const readied = readyWait(clock, () => status === \"ready\");\n const replies = new Map<string, Settle<WsResponse>>();\n const pings = new Map<number, Settle<void>>();\n const listeners = new Set<WsMessageListener>();\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 waits for the backoff of the next try, then opens a new generation. */\n const scheduleRetry = (): void =>\n retries.schedule(() => {\n if (closing()) return;\n record(\"retry.connect\", \"connecting\", `try ${retries.tries}, ${url}`);\n void open();\n });\n\n /** This function ends the generation that is open. It destroys the socket, because a close frame to a silent server gets no answer. */\n const lose = (on: string, detail: string): void => {\n const c = connection;\n if (c === null) return;\n connection = null;\n beat?.stop();\n beat = null;\n if (closing()) return;\n record(on, \"failing\", detail);\n flight.settleAll(`the generation ended with the call in flight (${detail})`);\n c.terminate();\n scheduleRetry();\n };\n\n /** This function gives a message of the server to the call that waits for it, or to the listeners. A late reply goes to nobody. */\n const receive = (data: Buffer, binary: boolean): void => {\n let matched: WsReply | null = null;\n try {\n matched = spec.replies?.reply(data, binary) ?? null;\n } catch {\n // a message that the replies cannot read answers no request\n }\n if (matched !== null) {\n replies.get(matched.id)?.(\n matched.error === undefined ? { outcome: \"ok\", value: { data, binary } } : { outcome: \"error\", error: matched.error, reply: true },\n );\n return;\n }\n for (const listener of [...listeners]) listener(data, binary);\n };\n\n /** This function counts a pong. Each pong answers the heartbeat. A pong for a ping answers each earlier ping too, as RFC 6455 §5.5.3 lets it. */\n const pong = (data: Buffer): void => {\n beat?.answer();\n const text = data.toString(\"latin1\");\n if (!/^\\d{1,15}$/.test(text)) return;\n const upTo = Number(text);\n for (const [at, settle] of [...pings]) if (at <= upTo) settle({ outcome: \"ok\", value: undefined });\n };\n\n /** This function starts the heartbeat of a generation: one ping at a time, while the client is ready. */\n const startBeat = (): Heartbeat =>\n heartbeat({\n interval: ms(knobs.heartbeat_interval),\n timeout: ms(knobs.heartbeat_timeout),\n misses: spec.heartbeatMisses,\n clock,\n turn,\n due: () => status === \"ready\",\n live: () => status === \"ready\",\n ping: () => {\n if (connection === null) throw new Error(`${name} has no connection`);\n connection.ping(payload((sequence += 1)));\n },\n onMiss: (misses) => record(\"heartbeat.miss\", status, `${misses} of ${spec.heartbeatMisses}`),\n onDead: () => lose(\"heartbeat.dead\", `no pong in heartbeat_timeout, ${spec.heartbeatMisses} times in sequence`),\n });\n\n const join = (c: WsConnection): void => {\n connection = c;\n retries.reset();\n const generation = joins.length + 1;\n joins.push({ generation, at: clock.now(), url, protocol: c.protocol, ...socketEnds(c.socket) });\n record(\"join\", \"ready\", `generation ${generation}, ${url}`);\n beat = startBeat();\n readied.wake();\n };\n\n /**\n * This function opens one generation in `connect_bound`. A failure goes to `failing`, and the\n * backoff starts. A connection that opens after its bound or after the close is destroyed at once.\n * The promise resolves when this try ends.\n */\n const open = (): Promise<void> => {\n const mine = (token += 1);\n let opened: WsConnection | null = null;\n let joined = false;\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 opened?.terminate();\n record(\"connect.failed\", \"failing\", detail);\n scheduleRetry();\n };\n const bound = clock.after(ms(knobs.connect_bound), () => fail(\"no open connection in connect_bound\"));\n void (async () => {\n const c = await create(wsOptions(spec));\n opened = c;\n if (stale()) {\n c.terminate();\n return;\n }\n c.listen({\n open: () => {\n if (stale()) {\n c.terminate();\n return;\n }\n bound();\n joined = true;\n join(c);\n finish();\n },\n message: (data, binary) => {\n if (c === connection) receive(data, binary);\n },\n pong: (data) => {\n if (c === connection) pong(data);\n },\n close: (code, reason) => {\n if (c === connection) closed?.();\n if (joined) {\n if (c === connection) lose(\"connection.end\", `code ${code}${reason === \"\" ? \"\" : `, ${reason}`}`);\n } else if (!stale()) fail(`the connection closed before its open, with code ${code}`);\n },\n error: (error) => {\n if (joined) {\n if (c === connection) record(\"connection.error\", status, message(error));\n } else if (!stale()) fail(message(error));\n },\n });\n })().catch((error: unknown) => fail(message(error)));\n return ended;\n };\n\n /** This function gives the connection for a call, or the reason that the call does not leave the client. */\n const usable = (signal: AbortSignal | undefined): WsConnection | Attempt<never> => {\n if (status === \"none\") return notSent(`${name} has not connected`);\n if (status !== \"ready\" || connection === 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 connection;\n };\n\n /** This function makes one try of a request: the write, then the reply, in `request_timeout`. */\n const requestAttempt = (call: WsRequest, signal: AbortSignal | undefined): Promise<Attempt<WsResponse>> => {\n const c = usable(signal);\n if (\"outcome\" in c) return Promise.resolve(c);\n if (spec.replies === undefined) return Promise.resolve(notSent(`${name} has no replies in its spec: no message can answer a request`));\n if (replies.has(call.id)) return Promise.resolve(notSent(`${name} has a request with the id ${call.id} in flight`));\n return trackWithTimer<WsResponse>(\n flight,\n clock,\n requestTimeout,\n signal,\n \"the caller abandoned the request after it was written\",\n \"no reply in request_timeout: the server can have applied the request\",\n (settle) => {\n replies.set(call.id, settle);\n try {\n c.send(call.data, (error) => {\n if (error !== undefined) settle({ outcome: \"indeterminate\", error: `the write failed: ${message(error)}` });\n });\n } catch (error) {\n settle(notSent(message(error)));\n }\n },\n () => {\n replies.delete(call.id);\n },\n );\n };\n\n /** This function makes one try of a ping: the ping frame, then a pong, in `request_timeout`. */\n const pingAttempt = (signal: AbortSignal | undefined): Promise<Attempt<void>> => {\n const c = usable(signal);\n if (\"outcome\" in c) return Promise.resolve(c);\n const at = (sequence += 1);\n return trackWithTimer<void>(\n flight,\n clock,\n requestTimeout,\n signal,\n \"the caller abandoned the ping after it was written\",\n \"no pong in request_timeout\",\n (settle) => {\n pings.set(at, settle);\n try {\n c.ping(payload(at));\n } catch (error) {\n settle(notSent(message(error)));\n }\n },\n () => {\n pings.delete(at);\n },\n );\n };\n\n const request = (operation: string, call: WsRequest, sendOptions: SendOptions = {}): Promise<Sent<WsResponse>> =>\n sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[operation],\n options: sendOptions,\n attempt: (signal) => requestAttempt(call, 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 ping = (sendOptions: SendOptions = {}): Promise<Sent<void>> =>\n sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[\"ping\"],\n options: sendOptions,\n attempt: (signal) => pingAttempt(signal),\n beforeAgain: (left, signal) => readied.wait(left, signal),\n onReissue: () => record(\"command.reissue\", status, \"ping\"),\n });\n\n const send = (data: string | Buffer): boolean => {\n const c = usable(undefined);\n if (\"outcome\" in c) return false;\n try {\n c.send(data, () => {});\n return true;\n } catch {\n return false;\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 server 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 destroyed when it opens\n token += 1;\n beat?.stop();\n beat = null;\n const c = connection;\n if (c !== null) {\n // the calls in flight end first, then the close handshake. A silent server answers neither: the bound destroys the socket\n const handshake = flight.idle().then(\n () =>\n new Promise<void>((resolve) => {\n closed = resolve;\n c.close(1000, \"the client closed\");\n }),\n );\n if (!(await withinBound(clock, ms(knobs.close_bound), handshake))) {\n record(\"close.bound\", \"closing\");\n record(\"close.destroy\", \"closing\");\n c.terminate();\n }\n closed = null;\n }\n connection = null;\n flight.settleAll(\"the client closed with the call in flight\");\n record(\"status.end\", \"end\");\n },\n };\n\n const interval = 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 heartbeat_timeout: knobs.heartbeat_timeout,\n // the last of the misses in sequence fails at its timeout: misses × interval + timeout\n heartbeat_detection_time: heartbeatDetection(knobs.heartbeat_interval, knobs.heartbeat_timeout, spec.heartbeatMisses),\n retry_base: knobs.retry_base,\n retry_cap: knobs.retry_cap,\n keepalive_idle: knobs.keepalive_idle,\n // a ping frame each interval refreshes an idle flow (O03). With no heartbeat, keepalive does\n idle_refresh_interval: interval === undefined ? knobs.keepalive_idle : knobs.heartbeat_interval,\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 ping frame on the connection of the application, until its pong\n \"round-trip\": roundTripCheck((sendOptions) => ping(sendOptions)),\n // a new connection each time, with the upgrade request\n dial: dialCheck(dial, spec.host, spec.port),\n });\n\n return {\n name,\n declaration,\n handle,\n meets: wsMeetings(name, knobs, spec.heartbeatMisses),\n get status() {\n return status;\n },\n joins,\n request,\n ping,\n send,\n onMessage(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\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":";;;;;;;;;AA2KA,MAAa,gBAAqD,EAAE,MAAM,EAAE,YAAY,KAAK,EAAE;;AAG/F,MAAa,gBAAgB,MAAc,SAAiC;CAC1E,MAAM,EAAE,UAAU;CAClB,MAAM,WAAW;EACf,GAAG,aAAa,MAAM,KAAK;EAE3B,GAAG,qBAAqB,MAAM,OAAO;GAAE,eAAe;GAAW,iBAAiB;GAAU,mBAAmB;EAA0B,CAAC;EAC1I,GAAG,aAAa,MAAM,cAAc,OAAO,EAAE,MAAM,CAAC,sBAAsB,gBAAgB,EAAE,CAAC;EAE7F,GAAG,cAAc,MAAM,OAAO,EAAE,SAAS,CAAC,gBAAgB,EAAE,CAAC;EAC7D,GAA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F;CAEA,MAAM,WAAW,SAAS,MAAM,kBAAkB;CAClD,MAAM,cAAwC;EAC5C,QAAQ,KAAK;EACb,OAAO;GACL,eAAe,MAAM;GACrB,iBAAiB,MAAM;GACvB,oBAAoB,MAAM;GAC1B,mBAAmB,MAAM;GAEzB,0BAA0B,mBAAmB,MAAM,oBAAoB,MAAM,mBAAmB,KAAK,eAAe;GACpH,YAAY,MAAM;GAClB,WAAW,MAAM;GACjB,gBAAgB,MAAM;GAEtB,uBAAuB,aAAa,KAAA,IAAY,MAAM,iBAAiB,MAAM;GAC7E,oBAAoB,MAAM;GAC1B,aAAa,MAAM;GACnB,qBAAqB,MAAM;EAC7B;EACA;CACF;CAEA,MAAM,UAAU,iBACd,WAAuB,MAAM,cAAc;EAEzC,eAAe,sBAAsB,WAAW,OAAO;EAEvD,cAAc,gBAAgB,gBAAgB,KAAK,WAAW,CAAC;EAE/D,MAAM,UAAU,MAAM,KAAK,MAAM,KAAK,IAAI;CAC5C,CAAC;CAEH,OAAO;EACL;EACA;EACA;EACA,OAAO,WAAW,MAAM,OAAO,KAAK,eAAe;EACnD,IAAI,SAAS;GACX,OAAO;EACT;EACA;EACA;EACA;EACA;EACA,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA;EACA,SAAS,KAAK,iBAAiB,aAAa,KAAK,MAAM,aAAa,QAAQ,OAAO,YAAY,CAAC;EAChG,WAAW,gBAAgB,eAAe,MAAM,aAAa,aAAa,KAAK,CAAC;CAClF;AACF"}
1
+ {"version":3,"file":"client.js","names":[],"sources":["../../src/websocket/client.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { realClock, unrefClock } from \"../clock.ts\";\nimport type {\n Attempt,\n CheckOptions,\n Client,\n ClientJoin,\n ClientKnobs,\n ClientOptions,\n ClientSpec,\n ClientStep,\n DialFn,\n RetryKnobs,\n SendOptions,\n Sent,\n Settle,\n} 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 missesProblems,\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 { authority, helloDial, statusLineJudge } from \"../client/dial.ts\";\nimport type { Dependency } from \"../description.ts\";\nimport type { Heartbeat } from \"../heartbeat.ts\";\nimport { heartbeat } from \"../heartbeat.ts\";\nimport type { DependencyHandle } from \"../lifecycle.ts\";\nimport type { Operation } from \"../operation.ts\";\nimport { heartbeatDetection } from \"../timing.ts\";\nimport type { WsConnectOptions, WsConnection, WsFactory } from \"./connection.ts\";\nimport { nodeWs } from \"./connection.ts\";\nimport { wsMeetings } from \"./meets.ts\";\n\n/**\n * These are the knobs of the client, each a time, by the names of the ordering law. The runtime has\n * no defaults, thus each knob is necessary. A bound that nobody gives is \"infinite\", not zero. The\n * constant `WS_CLIENT_STARTING_KNOBS` gives a declaration from the WS cells. The knobs that each client has come from the core.\n */\nexport interface WsKnobs extends ClientKnobs, RetryKnobs {\n /** This time bounds the TCP connect and the upgrade (`handshakeTimeout` of ws). The wrapper also bounds the open with it. */\n readonly connect_bound: Quantity;\n /** This time bounds each call: a request until its reply, and a ping until its pong. The wrapper has this timer, because ws has none. */\n readonly request_timeout: Quantity;\n /** This time is the interval of the ping frames of the heartbeat, from the start of one to the start of the next. \"infinite\" sends no ping. */\n readonly heartbeat_interval: Extent;\n /** This time bounds each ping of the heartbeat. A ping with no pong in this time is a miss. */\n readonly heartbeat_timeout: Quantity;\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 (`keepAliveInitialDelay`), in whole seconds. \"infinite\" keeps keepalive off, as ws does. */\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 at the shutdown: the calls in flight, then the close handshake. At the bound, `terminate()` destroys the socket. */\n readonly close_bound: Quantity;\n}\n\n/** A reply is the id of the request that a message answers, and the error of the server when the reply tells one. */\nexport interface WsReply {\n readonly id: string;\n readonly error?: string | undefined;\n}\n\n/**\n * The replies of a protocol tell which message of the server answers which request. WebSocket has no\n * reply of its own: each application protocol puts an id in its messages, for example JSON-RPC 2.0.\n */\nexport interface WsReplies {\n /** This function reads one message of the server. It gives its reply, or null for a message that answers no request. */\n reply(data: Buffer, binary: boolean): WsReply | null;\n}\n\n/** A WebSocket client spec is the declaration of one WebSocket client: where it connects, and its knobs. */\nexport interface WsClientSpec extends ClientSpec<WsKnobs> {\n /** This path is the path of the upgrade request. The default is \"/\". */\n readonly path?: string | undefined;\n /** These names are the subprotocols that the client offers (`Sec-WebSocket-Protocol`). */\n readonly protocols?: readonly string[] | undefined;\n /** These headers go with the upgrade request and with the dial, for example `authorization`. */\n readonly headers?: Readonly<Record<string, string>> | undefined;\n /** This count is the number of heartbeat misses in sequence that end the connection. The cells used 1. */\n readonly heartbeatMisses: number;\n /** These replies match a message of the server to its request. Without them, the client sends no request. */\n readonly replies?: WsReplies | undefined;\n /**\n * These operations are the calls of the service, by name, with their idempotency. A message does\n * not tell if the server removes its duplicates. Thus the client sends again only a call that this table names, and a ping.\n */\n readonly operations?: ClientSpec<WsKnobs>[\"operations\"];\n}\n\n/** These options make a client. Without them, it uses ws, the real clock, `Math.random`, and a dial with the upgrade request. */\nexport interface WsClientOptions extends ClientOptions<WsFactory> {\n readonly random?: (() => number) | undefined;\n /**\n * This function waits one turn of the event loop. The heartbeat waits it before it counts a miss,\n * thus a pong that is in the socket counts first. The default is `setImmediate`.\n */\n readonly turn?: (() => Promise<void>) | undefined;\n}\n\n/** A join is one generation of the client: one connection, when its upgrade ended with 101 (D1, D2). WebSocket gives no id of a connection. */\nexport interface WsJoin extends ClientJoin {\n /** This URL is the URL of the connection. */\n readonly url: string;\n /** This text is the subprotocol that the server chose, or \"\" when it chose none. */\n readonly protocol: string;\n}\n\n/** A request is one message to the server, with the id that its reply gives back. */\nexport interface WsRequest {\n readonly id: string;\n /** This data goes as one message. A string goes as a text message, and a buffer as a binary message. */\n readonly data: string | Buffer;\n}\n\n/** A response is the message of the server that answered a request. */\nexport interface WsResponse {\n readonly data: Buffer;\n readonly binary: boolean;\n}\n\n/** A message listener receives each message of the server that answers no request. */\nexport type WsMessageListener = (data: Buffer, binary: boolean) => void;\n\n/** A WebSocket client is a dependency of a service: its declaration, its handle, its checks and its calls. */\nexport interface WsClient extends Client<ClientStep, WsJoin> {\n /** This text is the state of the client, as `WS_CLIENT_MACHINE` names it. */\n readonly status: string;\n /**\n * This method sends a request, and waits for its reply. A reply is `ok`, or a certain error when it\n * tells one. The client sends again only an idempotent operation, one time at most, after an outcome that is not certain.\n */\n request(operation: string, call: WsRequest, options?: SendOptions): Promise<Sent<WsResponse>>;\n /** This method sends a ping frame, and waits for a pong. A pong is `ok`. A ping is idempotent, thus the client can send it again. */\n ping(options?: SendOptions): Promise<Sent<void>>;\n /** This method sends one message with no reply. It gives true when ws took the message, and false when the client is not ready. */\n send(data: string | Buffer): boolean;\n /** This method adds a listener of the messages that answer no request. It gives the function that removes it. */\n onMessage(listener: WsMessageListener): () => void;\n}\n\n/** These operations are in each table: a ping frame is idempotent (RFC 6455 §5.5.2). */\nexport const WS_OPERATIONS: Readonly<Record<string, Operation>> = { ping: { idempotent: true } };\n\n/** This function gives the problems of a spec: the knobs that the client cannot use. */\nexport const specProblems = (name: string, spec: WsClientSpec): string[] => {\n const { knobs } = spec;\n const problems = [\n ...timeProblems(name, knobs),\n // ws has no timer of a call. The open and the pings have a timer of the wrapper too\n ...wrapperTimerProblems(name, knobs, { connect_bound: \"an open\", request_timeout: \"a call\", heartbeat_timeout: \"a ping of the heartbeat\" }),\n ...zeroProblems(name, \"the client\", knobs, { open: [\"heartbeat_interval\", \"keepalive_idle\"] }),\n // Node truncates the keepalive delay to whole seconds\n ...wholeProblems(name, knobs, { seconds: [\"keepalive_idle\"] }),\n ...retryProblems(name, knobs),\n ...missesProblems(name, spec.heartbeatMisses, \"heartbeat\"),\n ...ageProblems(name, knobs, \"the client does not replace its connection at an age\"),\n ];\n // one ping at a time: the time of detection holds only when each tick sends a ping\n const interval = finiteMs(knobs.heartbeat_interval);\n const timeout = finiteMs(knobs.heartbeat_timeout);\n if (interval !== undefined && interval > 0 && timeout !== undefined && spec.heartbeatMisses > 1 && timeout >= interval)\n problems.push(`${name}'s heartbeat_timeout is not below its heartbeat_interval: with one ping at a time, a tick sends no ping while a ping waits`);\n if (spec.path !== undefined && !spec.path.startsWith(\"/\")) problems.push(`${name}'s path does not start with \"/\"`);\n if (spec.password !== undefined) problems.push(`${name} takes no password: give the credentials in headers, for example authorization`);\n return problems;\n};\n\n/** This function gives the URL of a spec. The client speaks ws:// only. */\nexport const wsUrl = (spec: WsClientSpec): string => `ws://${authority(spec.host, spec.port)}${spec.path ?? \"/\"}`;\n\n/** This function gives the arguments of `new WebSocket` from a spec. Each timer of ws comes from the declaration. */\nexport const wsOptions = (spec: WsClientSpec): WsConnectOptions => {\n const { knobs } = spec;\n const keepalive = finiteMs(knobs.keepalive_idle);\n return {\n url: wsUrl(spec),\n protocols: spec.protocols ?? [],\n options: {\n handshakeTimeout: ms(knobs.connect_bound),\n autoPong: true,\n closeTimeout: ms(knobs.close_bound),\n keepAlive: keepalive !== undefined,\n ...(keepalive === undefined ? {} : { keepAliveInitialDelay: keepalive }),\n ...(spec.headers === undefined ? {} : { headers: spec.headers }),\n },\n };\n};\n\n/** The key of the dial. RFC 6455 §1.3 gives it as its example. The dial does not read the accept of the server. */\nconst DIAL_KEY = \"dGhlIHNhbXBsZSBub25jZQ==\";\n\n/** This function gives the bytes of the dial: the upgrade request of RFC 6455 §4.1, with the subprotocols and the headers of the spec. */\nexport const upgradeRequest = (spec: Pick<WsClientSpec, \"host\" | \"port\" | \"path\" | \"protocols\" | \"headers\">): string => {\n const lines = [\n `GET ${spec.path ?? \"/\"} HTTP/1.1`,\n `Host: ${authority(spec.host, spec.port)}`,\n \"Upgrade: websocket\",\n \"Connection: Upgrade\",\n `Sec-WebSocket-Key: ${DIAL_KEY}`,\n \"Sec-WebSocket-Version: 13\",\n ...(spec.protocols === undefined || spec.protocols.length === 0 ? [] : [`Sec-WebSocket-Protocol: ${spec.protocols.join(\", \")}`]),\n ...Object.entries(spec.headers ?? {}).map(([header, value]) => `${header}: ${value}`),\n ];\n return `${lines.join(\"\\r\\n\")}\\r\\n\\r\\n`;\n};\n\n/** This judge reads the status line of the answer to the upgrade. Only 101 passes: a WebSocket server takes the upgrade. */\nexport const upgradeJudge: Judge = statusLineJudge((status, line) =>\n status === 101 ? null : new Error(`the server answered ${JSON.stringify(line)} to the upgrade, not 101`),\n);\n\n/** This function makes the dial of a spec: a new TCP connection, the upgrade request, and a wait for 101. The dial then destroys its socket. */\nexport const wsDial =\n (spec: Pick<WsClientSpec, \"path\" | \"protocols\" | \"headers\">): DialFn =>\n (host, port, signal) =>\n helloDial(upgradeRequest({ ...spec, host, port }), upgradeJudge)(host, port, signal);\n\n/** This function gives the payload of a ping: its sequence number as text. */\nconst payload = (sequence: number): Buffer => Buffer.from(String(sequence), \"latin1\");\n\n/**\n * This function makes a WebSocket client, a dependency of a service over ws 8.\n * - It has one connection as one generation. The end of the connection ends the generation. The\n * client then connects again by itself, after a backoff.\n * - Its calls are a request until its reply, and a ping until its pong. Each call has a timer of\n * the wrapper, because ws has none.\n * - Its heartbeat sends a ping frame each interval, one at a time. A ping with no pong in its timeout\n * is a miss. At the last miss, `terminate()` destroys the socket at once, and the client connects again.\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 URL and the ends of the socket of each connection at its open (D1).\n *\n * These parts come from the core of the clients: the outcomes, the second try and the wait for a ready\n * client. The backoff and its schedule, the calls in flight, the bounded close and the checks come from\n * the core too. The heartbeat is the heartbeat of the package. This entry gives what ws does in its own way.\n */\nexport const wsClient = (name: string, spec: WsClientSpec, options: WsClientOptions = {}): WsClient => {\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 ?? nodeWs;\n const dial = options.dial ?? wsDial(spec);\n const turn = options.turn ?? (() => new Promise<void>((resolve) => setImmediate(resolve)));\n const operations = operationTable(WS_OPERATIONS, spec.operations);\n const requestTimeout = ms(knobs.request_timeout);\n const url = wsUrl(spec);\n\n let status = \"none\";\n let connection: WsConnection | null = null;\n // the token of the open that is current, and the sequence of the ping frames\n let token = 0;\n let sequence = 0;\n let beat: Heartbeat | null = null;\n // this function ends the wait of the close for the close frame of the server\n let closed: (() => void) | null = null;\n const retries = retrySchedule(clock, retryBackoff(knobs), random);\n const joins: WsJoin[] = [];\n const flight = inFlight();\n const readied = readyWait(clock, () => status === \"ready\");\n const replies = new Map<string, Settle<WsResponse>>();\n const pings = new Map<number, Settle<void>>();\n const listeners = new Set<WsMessageListener>();\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 waits for the backoff of the next try, then opens a new generation. */\n const scheduleRetry = (): void =>\n retries.schedule(() => {\n if (closing()) return;\n record(\"retry.connect\", \"connecting\", `try ${retries.tries}, ${url}`);\n void open();\n });\n\n /** This function ends the generation that is open. It destroys the socket, because a close frame to a silent server gets no answer. */\n const lose = (on: string, detail: string): void => {\n const c = connection;\n if (c === null) return;\n connection = null;\n beat?.stop();\n beat = null;\n if (closing()) return;\n record(on, \"failing\", detail);\n flight.settleAll(`the generation ended with the call in flight (${detail})`);\n c.terminate();\n scheduleRetry();\n };\n\n /** This function gives a message of the server to the call that waits for it, or to the listeners. A late reply goes to nobody. */\n const receive = (data: Buffer, binary: boolean): void => {\n let matched: WsReply | null = null;\n try {\n matched = spec.replies?.reply(data, binary) ?? null;\n } catch {\n // a message that the replies cannot read answers no request\n }\n if (matched !== null) {\n replies.get(matched.id)?.(\n matched.error === undefined ? { outcome: \"ok\", value: { data, binary } } : { outcome: \"error\", error: matched.error, reply: true },\n );\n return;\n }\n for (const listener of [...listeners]) listener(data, binary);\n };\n\n /** This function counts a pong. Each pong answers the heartbeat. A pong for a ping answers each earlier ping too, as RFC 6455 §5.5.3 lets it. */\n const pong = (data: Buffer): void => {\n beat?.answer();\n const text = data.toString(\"latin1\");\n if (!/^\\d{1,15}$/.test(text)) return;\n const upTo = Number(text);\n for (const [at, settle] of [...pings]) if (at <= upTo) settle({ outcome: \"ok\", value: undefined });\n };\n\n /** This function starts the heartbeat of a generation: one ping at a time, while the client is ready. */\n const startBeat = (): Heartbeat =>\n heartbeat({\n interval: ms(knobs.heartbeat_interval),\n timeout: ms(knobs.heartbeat_timeout),\n misses: spec.heartbeatMisses,\n // the socket keeps the process alive, thus the heartbeat does not (SYS-126)\n clock: unrefClock(clock),\n turn,\n due: () => status === \"ready\",\n live: () => status === \"ready\",\n ping: () => {\n if (connection === null) throw new Error(`${name} has no connection`);\n connection.ping(payload((sequence += 1)));\n },\n onMiss: (misses) => record(\"heartbeat.miss\", status, `${misses} of ${spec.heartbeatMisses}`),\n onDead: () => lose(\"heartbeat.dead\", `no pong in heartbeat_timeout, ${spec.heartbeatMisses} times in sequence`),\n });\n\n const join = (c: WsConnection): void => {\n connection = c;\n retries.reset();\n const generation = joins.length + 1;\n joins.push({ generation, at: clock.now(), url, protocol: c.protocol, ...socketEnds(c.socket) });\n record(\"join\", \"ready\", `generation ${generation}, ${url}`);\n beat = startBeat();\n readied.wake();\n };\n\n /**\n * This function opens one generation in `connect_bound`. A failure goes to `failing`, and the\n * backoff starts. A connection that opens after its bound or after the close is destroyed at once.\n * The promise resolves when this try ends.\n */\n const open = (): Promise<void> => {\n const mine = (token += 1);\n let opened: WsConnection | null = null;\n let joined = false;\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 opened?.terminate();\n record(\"connect.failed\", \"failing\", detail);\n scheduleRetry();\n };\n // a caller can await the connection, thus this bound keeps the process alive (SYS-126)\n const bound = clock.after(ms(knobs.connect_bound), () => fail(\"no open connection in connect_bound\"));\n void (async () => {\n const c = await create(wsOptions(spec));\n opened = c;\n if (stale()) {\n c.terminate();\n return;\n }\n c.listen({\n open: () => {\n if (stale()) {\n c.terminate();\n return;\n }\n bound();\n joined = true;\n join(c);\n finish();\n },\n message: (data, binary) => {\n if (c === connection) receive(data, binary);\n },\n pong: (data) => {\n if (c === connection) pong(data);\n },\n close: (code, reason) => {\n if (c === connection) closed?.();\n if (joined) {\n if (c === connection) lose(\"connection.end\", `code ${code}${reason === \"\" ? \"\" : `, ${reason}`}`);\n } else if (!stale()) fail(`the connection closed before its open, with code ${code}`);\n },\n error: (error) => {\n if (joined) {\n if (c === connection) record(\"connection.error\", status, message(error));\n } else if (!stale()) fail(message(error));\n },\n });\n })().catch((error: unknown) => fail(message(error)));\n return ended;\n };\n\n /** This function gives the connection for a call, or the reason that the call does not leave the client. */\n const usable = (signal: AbortSignal | undefined): WsConnection | Attempt<never> => {\n if (status === \"none\") return notSent(`${name} has not connected`);\n if (status !== \"ready\" || connection === 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 connection;\n };\n\n /** This function makes one try of a request: the write, then the reply, in `request_timeout`. */\n const requestAttempt = (call: WsRequest, signal: AbortSignal | undefined): Promise<Attempt<WsResponse>> => {\n const c = usable(signal);\n if (\"outcome\" in c) return Promise.resolve(c);\n if (spec.replies === undefined) return Promise.resolve(notSent(`${name} has no replies in its spec: no message can answer a request`));\n if (replies.has(call.id)) return Promise.resolve(notSent(`${name} has a request with the id ${call.id} in flight`));\n return trackWithTimer<WsResponse>(\n flight,\n clock,\n requestTimeout,\n signal,\n \"the caller abandoned the request after it was written\",\n \"no reply in request_timeout: the server can have applied the request\",\n (settle) => {\n replies.set(call.id, settle);\n try {\n c.send(call.data, (error) => {\n if (error !== undefined) settle({ outcome: \"indeterminate\", error: `the write failed: ${message(error)}` });\n });\n } catch (error) {\n settle(notSent(message(error)));\n }\n },\n () => {\n replies.delete(call.id);\n },\n );\n };\n\n /** This function makes one try of a ping: the ping frame, then a pong, in `request_timeout`. */\n const pingAttempt = (signal: AbortSignal | undefined): Promise<Attempt<void>> => {\n const c = usable(signal);\n if (\"outcome\" in c) return Promise.resolve(c);\n const at = (sequence += 1);\n return trackWithTimer<void>(\n flight,\n clock,\n requestTimeout,\n signal,\n \"the caller abandoned the ping after it was written\",\n \"no pong in request_timeout\",\n (settle) => {\n pings.set(at, settle);\n try {\n c.ping(payload(at));\n } catch (error) {\n settle(notSent(message(error)));\n }\n },\n () => {\n pings.delete(at);\n },\n );\n };\n\n const request = (operation: string, call: WsRequest, sendOptions: SendOptions = {}): Promise<Sent<WsResponse>> =>\n sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[operation],\n options: sendOptions,\n attempt: (signal) => requestAttempt(call, 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 ping = (sendOptions: SendOptions = {}): Promise<Sent<void>> =>\n sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[\"ping\"],\n options: sendOptions,\n attempt: (signal) => pingAttempt(signal),\n beforeAgain: (left, signal) => readied.wait(left, signal),\n onReissue: () => record(\"command.reissue\", status, \"ping\"),\n });\n\n const send = (data: string | Buffer): boolean => {\n const c = usable(undefined);\n if (\"outcome\" in c) return false;\n try {\n c.send(data, () => {});\n return true;\n } catch {\n return false;\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 server 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 destroyed when it opens\n token += 1;\n beat?.stop();\n beat = null;\n const c = connection;\n if (c !== null) {\n // the calls in flight end first, then the close handshake. A silent server answers neither: the bound destroys the socket\n const handshake = flight.idle().then(\n () =>\n new Promise<void>((resolve) => {\n closed = resolve;\n c.close(1000, \"the client closed\");\n }),\n );\n if (!(await withinBound(clock, ms(knobs.close_bound), handshake))) {\n record(\"close.bound\", \"closing\");\n record(\"close.destroy\", \"closing\");\n c.terminate();\n }\n closed = null;\n }\n connection = null;\n flight.settleAll(\"the client closed with the call in flight\");\n record(\"status.end\", \"end\");\n },\n };\n\n const interval = 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 heartbeat_timeout: knobs.heartbeat_timeout,\n // the last of the misses in sequence fails at its timeout: misses × interval + timeout\n heartbeat_detection_time: heartbeatDetection(knobs.heartbeat_interval, knobs.heartbeat_timeout, spec.heartbeatMisses),\n retry_base: knobs.retry_base,\n retry_cap: knobs.retry_cap,\n keepalive_idle: knobs.keepalive_idle,\n // a ping frame each interval refreshes an idle flow (O03). With no heartbeat, keepalive does\n idle_refresh_interval: interval === undefined ? knobs.keepalive_idle : knobs.heartbeat_interval,\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 ping frame on the connection of the application, until its pong\n \"round-trip\": roundTripCheck((sendOptions) => ping(sendOptions)),\n // a new connection each time, with the upgrade request\n dial: dialCheck(dial, spec.host, spec.port),\n });\n\n return {\n name,\n declaration,\n handle,\n meets: wsMeetings(name, knobs, spec.heartbeatMisses),\n get status() {\n return status;\n },\n joins,\n request,\n ping,\n send,\n onMessage(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\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":";;;;;;;;;AA2KA,MAAa,gBAAqD,EAAE,MAAM,EAAE,YAAY,KAAK,EAAE;;AAG/F,MAAa,gBAAgB,MAAc,SAAiC;CAC1E,MAAM,EAAE,UAAU;CAClB,MAAM,WAAW;EACf,GAAG,aAAa,MAAM,KAAK;EAE3B,GAAG,qBAAqB,MAAM,OAAO;GAAE,eAAe;GAAW,iBAAiB;GAAU,mBAAmB;EAA0B,CAAC;EAC1I,GAAG,aAAa,MAAM,cAAc,OAAO,EAAE,MAAM,CAAC,sBAAsB,gBAAgB,EAAE,CAAC;EAE7F,GAAG,cAAc,MAAM,OAAO,EAAE,SAAS,CAAC,gBAAgB,EAAE,CAAC;EAC7D,GAAG,cAAc,MAAM,KAAK;EAC5B,GAAG,eAAe,MAAM,KAAK,iBAAiB,WAAW;EACzD,GAAG,YAAY,MAAM,OAAO,sDAAsD;CACpF;CAEA,MAAM,WAAW,SAAS,MAAM,kBAAkB;CAClD,MAAM,UAAU,SAAS,MAAM,iBAAiB;CAChD,IAAI,aAAa,KAAA,KAAa,WAAW,KAAK,YAAY,KAAA,KAAa,KAAK,kBAAkB,KAAK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Y,MAAM;GAClB,WAAW,MAAM;GACjB,gBAAgB,MAAM;GAEtB,uBAAuB,aAAa,KAAA,IAAY,MAAM,iBAAiB,MAAM;GAC7E,oBAAoB,MAAM;GAC1B,aAAa,MAAM;GACnB,qBAAqB,MAAM;EAC7B;EACA;CACF;CAEA,MAAM,UAAU,iBACd,WAAuB,MAAM,cAAc;EAEzC,eAAe,sBAAsB,WAAW,OAAO;EAEvD,cAAc,gBAAgB,gBAAgB,KAAK,WAAW,CAAC;EAE/D,MAAM,UAAU,MAAM,KAAK,MAAM,KAAK,IAAI;CAC5C,CAAC;CAEH,OAAO;EACL;EACA;EACA;EACA,OAAO,WAAW,MAAM,OAAO,KAAK,eAAe;EACnD,IAAI,SAAS;GACX,OAAO;EACT;EACA;EACA;EACA;EACA;EACA,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA;EACA,SAAS,KAAK,iBAAiB,aAAa,KAAK,MAAM,aAAa,QAAQ,OAAO,YAAY,CAAC;EAChG,WAAW,gBAAgB,eAAe,MAAM,aAAa,aAAa,KAAK,CAAC;CAClF;AACF"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/service",
4
- "version": "0.8.20",
4
+ "version": "0.9.0",
5
5
  "description": "A service declared as data before it starts, and its runtime: checks on jittered loops, a latch for each policy, probes from the cache, the startup in its sequence, and a staged, capped drain. The timer-ordering law checks the declaration. Its clock, heartbeat and backoff also work alone, in a browser too.",
6
6
  "keywords": [
7
7
  "service",
@@ -113,7 +113,7 @@
113
113
  "node": ">=22.19"
114
114
  },
115
115
  "dependencies": {
116
- "@mark1russell7/algebra": "^0.8.10",
116
+ "@mark1russell7/algebra": "^0.9.0",
117
117
  "@mark1russell7/collections": "^0.11.0",
118
118
  "@mark1russell7/quantity": "^0.4.1",
119
119
  "@mark1russell7/rational": "^0.1.2",
@@ -159,7 +159,7 @@
159
159
  "devDependencies": {
160
160
  "@grpc/grpc-js": "1.14.7",
161
161
  "@mark1russell7/cue": "github:mark1russell7/cue#da04dd56699a2ae806ab64da5b1d677476afe69e",
162
- "@mark1russell7/harness": "^0.16.1",
162
+ "@mark1russell7/harness": "^0.16.2",
163
163
  "@mark1russell7/otel-ts": "^0.7.4",
164
164
  "@mark1russell7/rigor-testkit": "^0.1.2",
165
165
  "@opentelemetry/api": "^1.10.0",