@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.
@@ -1 +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,OAAO,MAAM,KAAK;CAC/B,MAAM,OAAO,KAAK,aAAa,KAAA,IAAY,KAAK,GAAG,mBAAmB,KAAK,QAAQ,EAAE,GAAG,mBAAmB,KAAK,YAAY,EAAE,EAAE;CAChI,MAAM,YAAY,SAAS,MAAM,kBAAkB;CACnD,MAAM,YAAY,SAAS,MAAM,cAAc;CAC/C,OAAO;EACL,KAAK,UAAU,OAAO,KAAK,KAAK,GAAG,KAAK,KAAK,GAAG,mBAAmB,KAAK,SAAS,GAAG,EAAE,aAAa,cAAc,KAAA,IAAY,IAAI,YAAY;EAC7I,eAAe;GACb,SAA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,KAAA,IAAY,MAAM,qBAAqB,SAAU,IAAI,YAAa,KAAM,GAAG;GACnH,YAAY,MAAM;GAClB,WAAW,MAAM;GACjB,gBAAgB,MAAM;GAEtB,uBAAuB,cAAc,KAAA,IAAY,MAAM,iBAAiB,SAAS,YAAY,KAAM,GAAG;GACtG,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,gBAC5B,gBAAgB;GACd;GACA,OAAO;GACP,WAAW,KAAA;GACX,SAAS;GACT,UAAU,WAAW,WAAW,QAAQ,+BAA+B,OAAO,GAAG,cAAc,cAAc,SAAS,KAAA,CAAS;GAC/H,iBAAiB,CAAC;EACpB,CAAC,CACH;EAEA,MAAM,UAAU,MAAM,KAAK,MAAM,KAAK,IAAI;CAC5C,CAAC;CAEH,OAAO;EACL;EACA;EACA;EACA,OAAO,eAAe,MAAM,KAAK;EACjC,IAAI,SAAS;GACX,OAAO;EACT;EACA;EACA;EACA;EACA;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/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 // the calls in flight await this settle, thus the timer keeps the process alive (SYS-126)\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 // 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 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,sBAAs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AS;GACT,UAAU,WAAW,WAAW,QAAQ,+BAA+B,OAAO,GAAG,cAAc,cAAc,SAAS,KAAA,CAAS;GAC/H,iBAAiB,CAAC;EACpB,CAAC,CACH;EAEA,MAAM,UAAU,MAAM,KAAK,MAAM,KAAK,IAAI;CAC5C,CAAC;CAEH,OAAO;EACL;EACA;EACA;EACA,OAAO,eAAe,MAAM,KAAK;EACjC,IAAI,SAAS;GACX,OAAO;EACT;EACA;EACA;EACA;EACA;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,5 +1,5 @@
1
1
  import { backoffDelay } from "../backoff.js";
2
- import { realClock } from "../clock.js";
2
+ import { realClock, unrefClock } from "../clock.js";
3
3
  import { attachClient, clientBounds, clientProblems, clientRecorder, dialCheck, finiteMs, inFlight, localStateCheck, message, missesProblems, ms, notSent, operationTable, readyWait, retryBackoff, retryProblems, roundTripCheck, sendWithReissue, socketEnds, stepChecks, timeProblems, withinBound } from "../client/core.js";
4
4
  import { helloDial } from "../client/dial.js";
5
5
  import { heartbeat } from "../heartbeat.js";
@@ -177,7 +177,7 @@ const redisClient = (name, spec, options = {}) => {
177
177
  interval: ms(knobs.heartbeat_interval),
178
178
  timeout: ms(knobs.heartbeat_timeout),
179
179
  misses: spec.heartbeatMisses,
180
- clock,
180
+ clock: unrefClock(clock),
181
181
  turn,
182
182
  overlap: true,
183
183
  due: () => {
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":[],"sources":["../../src/redis/client.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { backoffDelay } from \"../backoff.ts\";\nimport type { Cancel } from \"../clock.ts\";\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 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 roundTripCheck,\n sendWithReissue,\n socketEnds,\n stepChecks,\n timeProblems,\n withinBound,\n} from \"../client/core.ts\";\nimport { helloDial } 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 { heartbeatDetection } from \"../timing.ts\";\nimport type { ConnectionFactory, RedisConnection, RedisConnectionOptions } from \"./connection.ts\";\nimport { ioredis } from \"./connection.ts\";\nimport { meetings } from \"./meets.ts\";\nimport { REDIS_OPERATIONS, commandName } from \"./operations.ts\";\n\n// the three outcomes, the send options and the checks moved to the core of the clients: this entry keeps them for the users of 0.5\nexport type { CheckOptions, ClientStep, DialFn, SendOptions, Sent } from \"../client/core.ts\";\n// the backoff of the tries to connect moved to the core, for RabbitMQ too: this entry keeps it for the users of 0.5\nexport { retryBackoff } from \"../client/core.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, and a bound that nobody gives\n * is \"infinite\", not zero. The knobs that each client has come from the core.\n */\nexport interface RedisKnobs extends ClientKnobs, RetryKnobs {\n /** This time bounds a try to connect, until the TCP connection exists (`connectTimeout`). */\n readonly connect_bound: Quantity;\n /** This time bounds each command, the handshake commands too (`commandTimeout`). */\n readonly request_timeout: Quantity;\n /** This time destroys a socket that gives no data while a command waits (`socketTimeout`). */\n readonly driver_writeoff_time: Extent;\n /** This time is the interval of the in-band watchdog: a PING on the connection of the application. */\n readonly heartbeat_interval: Extent;\n /** This time bounds each PING of the watchdog. */\n readonly heartbeat_timeout: Quantity;\n /** This time is how long the client tries to connect again before it stops. The watchdog then starts it again. */\n readonly client_retry_window: 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 bounds the close of the client at the shutdown: a QUIT, then a disconnect. */\n readonly close_bound: Quantity;\n /** This time is the age at which the client replaces its connection. The client supports only \"infinite\". */\n readonly max_connection_age: Extent;\n}\n\n/** A Redis client spec is the declaration of one Redis client: where it connects, and its knobs. */\nexport interface RedisClientSpec extends ClientSpec<RedisKnobs> {\n readonly db?: number | undefined;\n readonly username?: string | undefined;\n /** This count is the number of PINGs in sequence without an answer that make the watchdog connect again. */\n readonly heartbeatMisses: number;\n}\n\n/** These options make a client. Without them, it uses ioredis, the real clock and `Math.random`. */\nexport interface RedisClientOptions extends ClientOptions<ConnectionFactory> {\n readonly random?: (() => number) | undefined;\n /**\n * This function waits one turn of the event loop. The watchdog waits it before it counts a miss,\n * thus a reply that is in the socket is read first. Without it, the client uses `setImmediate`.\n */\n readonly turn?: (() => Promise<void>) | undefined;\n}\n\n/**\n * A join is one generation of the connection, at its `ready` (D1, D2). The prober joins its kernel\n * records to the server's view of the connection through it. A join holds the server's id of the\n * connection, and the local address and port of the socket.\n */\nexport interface Join extends ClientJoin {\n /** This number is the reply of CLIENT ID, or null when the server gave none. */\n readonly clientId: number | null;\n}\n\n/** A Redis client is a dependency of a service: its declaration, its handle, its checks and its commands. */\nexport interface RedisClient extends Client<ClientStep, Join> {\n /** This text is the state of the connection, as ioredis names it, or \"none\" before the connect. */\n readonly status: string;\n /**\n * This method sends a command, and gives its outcome in three values. The client sends again\n * only an idempotent operation, one time at most, after an outcome that is not certain. The\n * second try stays in the bound of the request. The client does not send again an operation that\n * the table does not name.\n */\n send<T = unknown>(command: string, args?: ReadonlyArray<string | number>, options?: SendOptions): Promise<Sent<T>>;\n}\n\n/** This function gives the problems of a spec: the knobs that the client cannot use. */\nexport const specProblems = (name: string, spec: RedisClientSpec): string[] => {\n const problems: string[] = [];\n const { knobs } = spec;\n problems.push(...missesProblems(name, spec.heartbeatMisses, \"watchdog\"));\n if (knobs.max_connection_age.value !== \"infinite\")\n problems.push(`${name} cannot replace its connection at an age: max_connection_age must be \"infinite\"`);\n problems.push(...timeProblems(name, knobs));\n if (ms(knobs.request_timeout) <= 0) problems.push(`${name}'s request_timeout is not above zero: each command must have a bound`);\n if (ms(knobs.heartbeat_timeout) <= 0) problems.push(`${name}'s heartbeat_timeout is not above zero`);\n problems.push(...retryProblems(name, knobs));\n return problems;\n};\n\n/** This dial function opens a TCP connection, sends an inline PING, and waits for +PONG. */\nexport const tcpDial: DialFn = helloDial(\"PING\\r\\n\", (received) => {\n const reply = received.toString();\n if (!reply.includes(\"\\r\\n\")) return \"more\";\n return reply.startsWith(\"+PONG\") ? null : new Error(`the reply was ${reply.trim()}`);\n});\n\n/**\n * This function makes a Redis client. It is a dependency of a service, with ioredis under it:\n * - It sets each timer of ioredis from the declaration, and it does not let ioredis send a command\n * again (R5 §8).\n * - It tells the outcome of a command in three values, and it settles each command in flight as\n * indeterminate when its connection closes (C8, C10).\n * - It records the server's id of each connection at `ready` (D1).\n * - A watchdog sends a PING in the band of the connection, and it connects again after the misses\n * of the declaration. It also starts a client that stopped (principle 19).\n *\n * The outcomes, the second try, the commands in flight, the bounded close and the checks come\n * from the core of the clients. This entry gives what ioredis does in its own way.\n */\nexport const redisClient = (name: string, spec: RedisClientSpec, options: RedisClientOptions = {}): RedisClient => {\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 ?? ioredis;\n const dial = options.dial ?? tcpDial;\n const turn = options.turn ?? (() => new Promise<void>((resolve) => setImmediate(resolve)));\n const operations = operationTable(REDIS_OPERATIONS, spec.operations);\n const requestTimeout = ms(knobs.request_timeout);\n const detection = heartbeatDetection(knobs.heartbeat_interval, knobs.heartbeat_timeout, spec.heartbeatMisses);\n const backoff = retryBackoff(knobs);\n\n let connection: RedisConnection | null = null;\n let status = \"none\";\n let closing = false;\n const joins: Join[] = [];\n // the commands that the client wrote while the connection was ready: a close settles each one\n const flight = inFlight();\n // the commands that wait for a ready connection before their second try\n const readied = readyWait(clock, () => connection?.status === \"ready\");\n const listeners: Array<[string, (...args: unknown[]) => void]> = [];\n\n const record = clientRecorder(options.record, clock, name);\n\n // the delays of the tries to connect (`retryBackoff`), and none after the retry window. The\n // watchdog starts the client again after that\n let retrySince: number | null = null;\n const retryStrategy = (times: number): number | null => {\n const now = clock.now();\n retrySince ??= now;\n if (now - retrySince > ms(knobs.client_retry_window)) {\n record(status, status, \"retry.window-ended\");\n return null;\n }\n return Math.round(backoffDelay(backoff, times, random));\n };\n\n const connectionOptions: RedisConnectionOptions = {\n host: spec.host,\n port: spec.port,\n ...(spec.db === undefined ? {} : { db: spec.db }),\n ...(spec.username === undefined ? {} : { username: spec.username }),\n ...(spec.password === undefined ? {} : { password: spec.password }),\n lazyConnect: true,\n connectTimeout: ms(knobs.connect_bound),\n commandTimeout: requestTimeout,\n // ioredis reads undefined as no socket timeout, and false as no keepalive\n socketTimeout: finiteMs(knobs.driver_writeoff_time),\n keepAlive: finiteMs(knobs.keepalive_idle) ?? false,\n enableOfflineQueue: false,\n autoResendUnfulfilledCommands: false,\n maxRetriesPerRequest: null,\n enableReadyCheck: true,\n connectionName: name,\n retryStrategy,\n };\n\n /** This function gives the outcome of a failed command: a reply of the server, a command that did not leave the client, or neither. */\n const failed = (error: unknown): Attempt => {\n const text = message(error);\n if (error instanceof Error && error.name === \"ReplyError\") return { outcome: \"error\", error: text, reply: true };\n if (/isn't writeable|enableOfflineQueue/i.test(text)) return notSent(text);\n return { outcome: \"indeterminate\", error: text };\n };\n\n const onReady = async (): Promise<void> => {\n retrySince = null;\n const c = connection;\n if (c === null) return;\n const generation = joins.length + 1;\n const at = clock.now();\n const socket = c.stream;\n let clientId: number | null = null;\n try {\n const reply = await c.call(\"CLIENT\", \"ID\");\n clientId = typeof reply === \"number\" ? reply : Number(reply);\n if (!Number.isFinite(clientId)) clientId = null;\n } catch {\n clientId = null;\n }\n // a connection that closed before its reply is a generation that never served\n if (connection !== c || c.status !== \"ready\") return;\n joins.push({ generation, at, clientId, ...socketEnds(socket) });\n record(\"ready\", \"ready\", \"join\", `generation ${generation}, client id ${clientId ?? \"unknown\"}`);\n readied.wake();\n };\n\n const onStatus = (to: string) => (): void => {\n const from = status;\n status = to;\n record(from, to, `status.${to}`);\n // the lower layer gave up the connection: each command in flight learns it now (C10)\n if (to === \"close\" || to === \"end\") flight.settleAll(`the connection closed with the command in flight (${from})`);\n if (to === \"ready\") void onReady();\n };\n\n const watch = (c: RedisConnection): void => {\n for (const state of [\"connecting\", \"connect\", \"ready\", \"close\", \"reconnecting\", \"end\"]) {\n const listener = onStatus(state);\n c.on(state, listener);\n listeners.push([state, listener]);\n }\n // an error of the connection comes before its close, which settles the commands: here it is only recorded\n const onError = (error: unknown): void => record(status, status, \"error\", message(error));\n c.on(\"error\", onError);\n listeners.push([\"error\", onError]);\n };\n\n const attempt = (command: string, args: ReadonlyArray<string | number>, signal?: AbortSignal): Promise<Attempt> => {\n const c = connection;\n if (c === null) return Promise.resolve(notSent(`${name} has not connected`));\n // ioredis has no offline queue here: a command while the client is not ready fails at once, before it leaves the client\n if (c.status !== \"ready\") return Promise.resolve(notSent(`${name} is ${c.status}, not ready: the command did not leave the client`));\n if (signal?.aborted) return Promise.resolve(notSent(\"the caller aborted the command before it left the client\"));\n return flight.track(signal, \"the caller abandoned the command after it was sent\", (settle) => {\n c.call(command, ...args).then(\n (value) => settle({ outcome: \"ok\", value }),\n (error: unknown) => settle(failed(error)),\n );\n });\n };\n\n const send = <T>(command: string, args: ReadonlyArray<string | number> = [], sendOptions: SendOptions = {}): Promise<Sent<T>> =>\n sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[commandName(command, args)],\n options: sendOptions,\n attempt: (signal) => attempt(command, args, signal) as Promise<Attempt<T>>,\n // ioredis connects again by itself: the second try waits for a ready connection, in the time that is left\n beforeAgain: (left, signal) => readied.wait(left, signal),\n onReissue: () => record(status, status, \"command.reissue\", commandName(command, args)),\n });\n\n // the watchdog: a heartbeat of PINGs on the connection of the application, each interval from the\n // start of the one before. A reply, an error reply too, is an answer. It waits one turn of the\n // event loop before it counts a miss, thus a slow loop is not a silent server. It acts only on a\n // ready connection, thus it never closes a connection in the middle of a new attempt\n let watchdog: Heartbeat | null = null;\n const startWatchdog = (): Heartbeat =>\n heartbeat({\n interval: ms(knobs.heartbeat_interval),\n timeout: ms(knobs.heartbeat_timeout),\n misses: spec.heartbeatMisses,\n clock,\n turn,\n // a PING starts at each tick, also while an earlier PING waits\n overlap: true,\n due: () => {\n const c = connection;\n if (c === null || closing) return false;\n if (c.status === \"end\") {\n // the retry window ended: the watchdog starts the client again\n record(status, status, \"watchdog.revive\");\n retrySince = null;\n c.connect().catch(() => {});\n return false;\n }\n return c.status === \"ready\";\n },\n ping: (signal) =>\n attempt(\"PING\", [], signal).then((result) => result.outcome === \"ok\" || (result.outcome === \"error\" && result.reply)),\n live: () => connection?.status === \"ready\" && !closing,\n onMiss: (misses) => record(status, status, \"watchdog.miss\", `${misses} of ${spec.heartbeatMisses}`),\n onDead: () => {\n record(status, status, \"watchdog.reconnect\");\n connection?.disconnect(true);\n },\n });\n\n const handle: DependencyHandle = {\n async connect(signal) {\n closing = false;\n const c = await create(connectionOptions);\n connection = c;\n watch(c);\n if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);\n // a server that is down at the start does not stop the startup: the client connects again in\n // the background, and its checks keep readiness tripped until it is ready (readiness is earned)\n await c.connect().catch((error: unknown) => record(status, status, \"connect.failed\", message(error)));\n watchdog?.stop();\n watchdog = startWatchdog();\n },\n async close() {\n closing = true;\n watchdog?.stop();\n watchdog = null;\n const c = connection;\n if (c === null) return;\n // a QUIT lets the replies in flight arrive. A silent server never answers it, thus the close has its bound\n const startedClose = clock.now();\n if (!(await withinBound(clock, ms(knobs.close_bound), c.quit()))) record(status, status, \"close.bound\");\n // a client that is not ready refuses the QUIT at once, and then it connects again: the close stops it\n if (c.status !== \"end\") c.disconnect(false);\n // ioredis is at `end` when its socket closes, a moment after the reply: the close waits for it, in its bound\n const ended = (within: number): Promise<void> =>\n c.status === \"end\"\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n let stop: Cancel = () => {};\n const end = (): void => {\n c.off(\"end\", end);\n stop();\n resolve();\n };\n c.on(\"end\", end);\n stop = clock.after(Math.max(0, within), end);\n });\n await ended(ms(knobs.close_bound) - (clock.now() - startedClose));\n // a disconnect only half-closes the socket, and a silent server never closes its half: the bound destroys it\n if (c.status !== \"end\") {\n record(status, status, \"close.destroy\");\n c.stream?.destroy?.();\n await ended(0);\n }\n for (const [event, listener] of listeners) c.off(event, listener);\n listeners.length = 0;\n flight.settleAll(\"the client closed with the command in flight\");\n status = \"end\";\n },\n };\n\n const declaration: Omit<Dependency, \"name\"> = {\n system: spec.system,\n knobs: {\n connect_bound: knobs.connect_bound,\n request_timeout: knobs.request_timeout,\n driver_writeoff_time: knobs.driver_writeoff_time,\n keepalive_idle: knobs.keepalive_idle,\n heartbeat_interval: knobs.heartbeat_interval,\n heartbeat_timeout: knobs.heartbeat_timeout,\n heartbeat_detection_time: detection,\n client_retry_window: knobs.client_retry_window,\n retry_base: knobs.retry_base,\n retry_cap: knobs.retry_cap,\n close_bound: knobs.close_bound,\n max_connection_age: knobs.max_connection_age,\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(() => connection?.status === \"ready\"),\n // a PING on the connection of the application: blind to nothing that the application meets\n \"round-trip\": roundTripCheck((sendOptions) => send(\"PING\", [], sendOptions)),\n // a new connection each time: it finds a server that refuses connections, but not a stalled connection of the application\n dial: dialCheck(dial, spec.host, spec.port),\n });\n\n return {\n name,\n declaration,\n handle,\n meets: meetings(name, knobs, detection),\n get status() {\n return connection === null ? \"none\" : connection.status;\n },\n joins,\n send,\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":";;;;;;;;;;;AAmHA,MAAa,gBAAgB,MAAc,SAAoC;CAC7E,MAAM,WAAqB,CAAC;CAC5B,MAAM,EAAE,UAAU;CAClB,SAAS,KAAK,GAAG,eAAe,MAAM,KAAK,iBAAiB,UAAU,CAAC;CACvE,IAAI,MAAM,mBAAmB,UAAU,YACrC,SAAS,KAAK,GAAG,KAAK,gFAAgF;CACxG,SAAS,KAAK,GAAG,aAAa,MAAM,KAAK,CAAC;CAC1C,IAAI,GAAG,MAAM,eAAe,KAAK,GAAG,SAAS,KAAK,GAAG,KAAK,qEAAqE;CAC/H,IAAI,GAAG,MAAM,iBAAiB,KAAK,GAAG,SAAS,KAAK,GAAG,KAAK,uCAAuC;CACnG,SAAS,KAAK,GAAG,cAAc,MAAM,KAAK,CAAC;CAC3C,OAAO;AACT;;AAGA,MAAa,UAAkB,UAAU,aAAa,aAAa;CACjE,MAAM,QAAQ,SAAS,SAAS;CAChC,IAAI,CAAC,MAAM,SAAS,MAAM,GAAG,OAAO;CACpC,OAAO,MAAM,WAAW,OAAO,IAAI,uBAAO,IAAI,MAAM,iBAAiB,MAAM,KAAK,GAAG;AACrF,CAAC;;;;;;;;;;;;;;AAeD,MAAa,eAAe,MAAc,MAAuB,UAA8B,CAAC,MAAmB;CACjH,MAAM,WAAW,aAAa,MAAM,IAAI;CACxC,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,MAAM,SAAS,KAAK,IAAI,CAAC;CAC5D,MAAM,EAAE,UAAU;CAClB,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,SAAS,QAAQ,UAAU,KAAK;CACtC,MAAM,SAAS,QAAQ,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,gBAAgB,eAAe,MAAM,aAAa,aAAa,KAAK,CAAC;CAClF;AACF"}
1
+ {"version":3,"file":"client.js","names":[],"sources":["../../src/redis/client.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { backoffDelay } from \"../backoff.ts\";\nimport type { Cancel } from \"../clock.ts\";\nimport { realClock, unrefClock } from \"../clock.ts\";\nimport type { Attempt, CheckOptions, Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, RetryKnobs, SendOptions, Sent } from \"../client/core.ts\";\nimport {\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 roundTripCheck,\n sendWithReissue,\n socketEnds,\n stepChecks,\n timeProblems,\n withinBound,\n} from \"../client/core.ts\";\nimport { helloDial } 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 { heartbeatDetection } from \"../timing.ts\";\nimport type { ConnectionFactory, RedisConnection, RedisConnectionOptions } from \"./connection.ts\";\nimport { ioredis } from \"./connection.ts\";\nimport { meetings } from \"./meets.ts\";\nimport { REDIS_OPERATIONS, commandName } from \"./operations.ts\";\n\n// the three outcomes, the send options and the checks moved to the core of the clients: this entry keeps them for the users of 0.5\nexport type { CheckOptions, ClientStep, DialFn, SendOptions, Sent } from \"../client/core.ts\";\n// the backoff of the tries to connect moved to the core, for RabbitMQ too: this entry keeps it for the users of 0.5\nexport { retryBackoff } from \"../client/core.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, and a bound that nobody gives\n * is \"infinite\", not zero. The knobs that each client has come from the core.\n */\nexport interface RedisKnobs extends ClientKnobs, RetryKnobs {\n /** This time bounds a try to connect, until the TCP connection exists (`connectTimeout`). */\n readonly connect_bound: Quantity;\n /** This time bounds each command, the handshake commands too (`commandTimeout`). */\n readonly request_timeout: Quantity;\n /** This time destroys a socket that gives no data while a command waits (`socketTimeout`). */\n readonly driver_writeoff_time: Extent;\n /** This time is the interval of the in-band watchdog: a PING on the connection of the application. */\n readonly heartbeat_interval: Extent;\n /** This time bounds each PING of the watchdog. */\n readonly heartbeat_timeout: Quantity;\n /** This time is how long the client tries to connect again before it stops. The watchdog then starts it again. */\n readonly client_retry_window: 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 bounds the close of the client at the shutdown: a QUIT, then a disconnect. */\n readonly close_bound: Quantity;\n /** This time is the age at which the client replaces its connection. The client supports only \"infinite\". */\n readonly max_connection_age: Extent;\n}\n\n/** A Redis client spec is the declaration of one Redis client: where it connects, and its knobs. */\nexport interface RedisClientSpec extends ClientSpec<RedisKnobs> {\n readonly db?: number | undefined;\n readonly username?: string | undefined;\n /** This count is the number of PINGs in sequence without an answer that make the watchdog connect again. */\n readonly heartbeatMisses: number;\n}\n\n/** These options make a client. Without them, it uses ioredis, the real clock and `Math.random`. */\nexport interface RedisClientOptions extends ClientOptions<ConnectionFactory> {\n readonly random?: (() => number) | undefined;\n /**\n * This function waits one turn of the event loop. The watchdog waits it before it counts a miss,\n * thus a reply that is in the socket is read first. Without it, the client uses `setImmediate`.\n */\n readonly turn?: (() => Promise<void>) | undefined;\n}\n\n/**\n * A join is one generation of the connection, at its `ready` (D1, D2). The prober joins its kernel\n * records to the server's view of the connection through it. A join holds the server's id of the\n * connection, and the local address and port of the socket.\n */\nexport interface Join extends ClientJoin {\n /** This number is the reply of CLIENT ID, or null when the server gave none. */\n readonly clientId: number | null;\n}\n\n/** A Redis client is a dependency of a service: its declaration, its handle, its checks and its commands. */\nexport interface RedisClient extends Client<ClientStep, Join> {\n /** This text is the state of the connection, as ioredis names it, or \"none\" before the connect. */\n readonly status: string;\n /**\n * This method sends a command, and gives its outcome in three values. The client sends again\n * only an idempotent operation, one time at most, after an outcome that is not certain. The\n * second try stays in the bound of the request. The client does not send again an operation that\n * the table does not name.\n */\n send<T = unknown>(command: string, args?: ReadonlyArray<string | number>, options?: SendOptions): Promise<Sent<T>>;\n}\n\n/** This function gives the problems of a spec: the knobs that the client cannot use. */\nexport const specProblems = (name: string, spec: RedisClientSpec): string[] => {\n const problems: string[] = [];\n const { knobs } = spec;\n problems.push(...missesProblems(name, spec.heartbeatMisses, \"watchdog\"));\n if (knobs.max_connection_age.value !== \"infinite\")\n problems.push(`${name} cannot replace its connection at an age: max_connection_age must be \"infinite\"`);\n problems.push(...timeProblems(name, knobs));\n if (ms(knobs.request_timeout) <= 0) problems.push(`${name}'s request_timeout is not above zero: each command must have a bound`);\n if (ms(knobs.heartbeat_timeout) <= 0) problems.push(`${name}'s heartbeat_timeout is not above zero`);\n problems.push(...retryProblems(name, knobs));\n return problems;\n};\n\n/** This dial function opens a TCP connection, sends an inline PING, and waits for +PONG. */\nexport const tcpDial: DialFn = helloDial(\"PING\\r\\n\", (received) => {\n const reply = received.toString();\n if (!reply.includes(\"\\r\\n\")) return \"more\";\n return reply.startsWith(\"+PONG\") ? null : new Error(`the reply was ${reply.trim()}`);\n});\n\n/**\n * This function makes a Redis client. It is a dependency of a service, with ioredis under it:\n * - It sets each timer of ioredis from the declaration, and it does not let ioredis send a command\n * again (R5 §8).\n * - It tells the outcome of a command in three values, and it settles each command in flight as\n * indeterminate when its connection closes (C8, C10).\n * - It records the server's id of each connection at `ready` (D1).\n * - A watchdog sends a PING in the band of the connection, and it connects again after the misses\n * of the declaration. It also starts a client that stopped (principle 19).\n *\n * The outcomes, the second try, the commands in flight, the bounded close and the checks come\n * from the core of the clients. This entry gives what ioredis does in its own way.\n */\nexport const redisClient = (name: string, spec: RedisClientSpec, options: RedisClientOptions = {}): RedisClient => {\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 ?? ioredis;\n const dial = options.dial ?? tcpDial;\n const turn = options.turn ?? (() => new Promise<void>((resolve) => setImmediate(resolve)));\n const operations = operationTable(REDIS_OPERATIONS, spec.operations);\n const requestTimeout = ms(knobs.request_timeout);\n const detection = heartbeatDetection(knobs.heartbeat_interval, knobs.heartbeat_timeout, spec.heartbeatMisses);\n const backoff = retryBackoff(knobs);\n\n let connection: RedisConnection | null = null;\n let status = \"none\";\n let closing = false;\n const joins: Join[] = [];\n // the commands that the client wrote while the connection was ready: a close settles each one\n const flight = inFlight();\n // the commands that wait for a ready connection before their second try\n const readied = readyWait(clock, () => connection?.status === \"ready\");\n const listeners: Array<[string, (...args: unknown[]) => void]> = [];\n\n const record = clientRecorder(options.record, clock, name);\n\n // the delays of the tries to connect (`retryBackoff`), and none after the retry window. The\n // watchdog starts the client again after that\n let retrySince: number | null = null;\n const retryStrategy = (times: number): number | null => {\n const now = clock.now();\n retrySince ??= now;\n if (now - retrySince > ms(knobs.client_retry_window)) {\n record(status, status, \"retry.window-ended\");\n return null;\n }\n return Math.round(backoffDelay(backoff, times, random));\n };\n\n const connectionOptions: RedisConnectionOptions = {\n host: spec.host,\n port: spec.port,\n ...(spec.db === undefined ? {} : { db: spec.db }),\n ...(spec.username === undefined ? {} : { username: spec.username }),\n ...(spec.password === undefined ? {} : { password: spec.password }),\n lazyConnect: true,\n connectTimeout: ms(knobs.connect_bound),\n commandTimeout: requestTimeout,\n // ioredis reads undefined as no socket timeout, and false as no keepalive\n socketTimeout: finiteMs(knobs.driver_writeoff_time),\n keepAlive: finiteMs(knobs.keepalive_idle) ?? false,\n enableOfflineQueue: false,\n autoResendUnfulfilledCommands: false,\n maxRetriesPerRequest: null,\n enableReadyCheck: true,\n connectionName: name,\n retryStrategy,\n };\n\n /** This function gives the outcome of a failed command: a reply of the server, a command that did not leave the client, or neither. */\n const failed = (error: unknown): Attempt => {\n const text = message(error);\n if (error instanceof Error && error.name === \"ReplyError\") return { outcome: \"error\", error: text, reply: true };\n if (/isn't writeable|enableOfflineQueue/i.test(text)) return notSent(text);\n return { outcome: \"indeterminate\", error: text };\n };\n\n const onReady = async (): Promise<void> => {\n retrySince = null;\n const c = connection;\n if (c === null) return;\n const generation = joins.length + 1;\n const at = clock.now();\n const socket = c.stream;\n let clientId: number | null = null;\n try {\n const reply = await c.call(\"CLIENT\", \"ID\");\n clientId = typeof reply === \"number\" ? reply : Number(reply);\n if (!Number.isFinite(clientId)) clientId = null;\n } catch {\n clientId = null;\n }\n // a connection that closed before its reply is a generation that never served\n if (connection !== c || c.status !== \"ready\") return;\n joins.push({ generation, at, clientId, ...socketEnds(socket) });\n record(\"ready\", \"ready\", \"join\", `generation ${generation}, client id ${clientId ?? \"unknown\"}`);\n readied.wake();\n };\n\n const onStatus = (to: string) => (): void => {\n const from = status;\n status = to;\n record(from, to, `status.${to}`);\n // the lower layer gave up the connection: each command in flight learns it now (C10)\n if (to === \"close\" || to === \"end\") flight.settleAll(`the connection closed with the command in flight (${from})`);\n if (to === \"ready\") void onReady();\n };\n\n const watch = (c: RedisConnection): void => {\n for (const state of [\"connecting\", \"connect\", \"ready\", \"close\", \"reconnecting\", \"end\"]) {\n const listener = onStatus(state);\n c.on(state, listener);\n listeners.push([state, listener]);\n }\n // an error of the connection comes before its close, which settles the commands: here it is only recorded\n const onError = (error: unknown): void => record(status, status, \"error\", message(error));\n c.on(\"error\", onError);\n listeners.push([\"error\", onError]);\n };\n\n const attempt = (command: string, args: ReadonlyArray<string | number>, signal?: AbortSignal): Promise<Attempt> => {\n const c = connection;\n if (c === null) return Promise.resolve(notSent(`${name} has not connected`));\n // ioredis has no offline queue here: a command while the client is not ready fails at once, before it leaves the client\n if (c.status !== \"ready\") return Promise.resolve(notSent(`${name} is ${c.status}, not ready: the command did not leave the client`));\n if (signal?.aborted) return Promise.resolve(notSent(\"the caller aborted the command before it left the client\"));\n return flight.track(signal, \"the caller abandoned the command after it was sent\", (settle) => {\n c.call(command, ...args).then(\n (value) => settle({ outcome: \"ok\", value }),\n (error: unknown) => settle(failed(error)),\n );\n });\n };\n\n const send = <T>(command: string, args: ReadonlyArray<string | number> = [], sendOptions: SendOptions = {}): Promise<Sent<T>> =>\n sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[commandName(command, args)],\n options: sendOptions,\n attempt: (signal) => attempt(command, args, signal) as Promise<Attempt<T>>,\n // ioredis connects again by itself: the second try waits for a ready connection, in the time that is left\n beforeAgain: (left, signal) => readied.wait(left, signal),\n onReissue: () => record(status, status, \"command.reissue\", commandName(command, args)),\n });\n\n // the watchdog: a heartbeat of PINGs on the connection of the application, each interval from the\n // start of the one before. A reply, an error reply too, is an answer. It waits one turn of the\n // event loop before it counts a miss, thus a slow loop is not a silent server. It acts only on a\n // ready connection, thus it never closes a connection in the middle of a new attempt\n let watchdog: Heartbeat | null = null;\n const startWatchdog = (): 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 // a PING starts at each tick, also while an earlier PING waits\n overlap: true,\n due: () => {\n const c = connection;\n if (c === null || closing) return false;\n if (c.status === \"end\") {\n // the retry window ended: the watchdog starts the client again\n record(status, status, \"watchdog.revive\");\n retrySince = null;\n c.connect().catch(() => {});\n return false;\n }\n return c.status === \"ready\";\n },\n ping: (signal) =>\n attempt(\"PING\", [], signal).then((result) => result.outcome === \"ok\" || (result.outcome === \"error\" && result.reply)),\n live: () => connection?.status === \"ready\" && !closing,\n onMiss: (misses) => record(status, status, \"watchdog.miss\", `${misses} of ${spec.heartbeatMisses}`),\n onDead: () => {\n record(status, status, \"watchdog.reconnect\");\n connection?.disconnect(true);\n },\n });\n\n const handle: DependencyHandle = {\n async connect(signal) {\n closing = false;\n const c = await create(connectionOptions);\n connection = c;\n watch(c);\n if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);\n // a server that is down at the start does not stop the startup: the client connects again in\n // the background, and its checks keep readiness tripped until it is ready (readiness is earned)\n await c.connect().catch((error: unknown) => record(status, status, \"connect.failed\", message(error)));\n watchdog?.stop();\n watchdog = startWatchdog();\n },\n async close() {\n closing = true;\n watchdog?.stop();\n watchdog = null;\n const c = connection;\n if (c === null) return;\n // a QUIT lets the replies in flight arrive. A silent server never answers it, thus the close has its bound\n const startedClose = clock.now();\n if (!(await withinBound(clock, ms(knobs.close_bound), c.quit()))) record(status, status, \"close.bound\");\n // a client that is not ready refuses the QUIT at once, and then it connects again: the close stops it\n if (c.status !== \"end\") c.disconnect(false);\n // ioredis is at `end` when its socket closes, a moment after the reply: the close waits for it, in its bound\n const ended = (within: number): Promise<void> =>\n c.status === \"end\"\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n let stop: Cancel = () => {};\n const end = (): void => {\n c.off(\"end\", end);\n stop();\n resolve();\n };\n c.on(\"end\", end);\n // the close awaits this wait, thus it keeps the process alive (SYS-126)\n stop = clock.after(Math.max(0, within), end);\n });\n await ended(ms(knobs.close_bound) - (clock.now() - startedClose));\n // a disconnect only half-closes the socket, and a silent server never closes its half: the bound destroys it\n if (c.status !== \"end\") {\n record(status, status, \"close.destroy\");\n c.stream?.destroy?.();\n await ended(0);\n }\n for (const [event, listener] of listeners) c.off(event, listener);\n listeners.length = 0;\n flight.settleAll(\"the client closed with the command in flight\");\n status = \"end\";\n },\n };\n\n const declaration: Omit<Dependency, \"name\"> = {\n system: spec.system,\n knobs: {\n connect_bound: knobs.connect_bound,\n request_timeout: knobs.request_timeout,\n driver_writeoff_time: knobs.driver_writeoff_time,\n keepalive_idle: knobs.keepalive_idle,\n heartbeat_interval: knobs.heartbeat_interval,\n heartbeat_timeout: knobs.heartbeat_timeout,\n heartbeat_detection_time: detection,\n client_retry_window: knobs.client_retry_window,\n retry_base: knobs.retry_base,\n retry_cap: knobs.retry_cap,\n close_bound: knobs.close_bound,\n max_connection_age: knobs.max_connection_age,\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(() => connection?.status === \"ready\"),\n // a PING on the connection of the application: blind to nothing that the application meets\n \"round-trip\": roundTripCheck((sendOptions) => send(\"PING\", [], sendOptions)),\n // a new connection each time: it finds a server that refuses connections, but not a stalled connection of the application\n dial: dialCheck(dial, spec.host, spec.port),\n });\n\n return {\n name,\n declaration,\n handle,\n meets: meetings(name, knobs, detection),\n get status() {\n return connection === null ? \"none\" : connection.status;\n },\n joins,\n send,\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":";;;;;;;;;;;AAmHA,MAAa,gBAAgB,MAAc,SAAoC;CAC7E,MAAM,WAAqB,CAAC;CAC5B,MAAM,EAAE,UAAU;CAClB,SAAS,KAAK,GAAG,eAAe,MAAM,KAAK,iBAAiB,UAAU,CAAC;CACvE,IAAI,MAAM,mBAAmB,UAAU,YACrC,SAAS,KAAK,GAAG,KAAK,gFAAgF;CACxG,SAAS,KAAK,GAAG,aAAa,MAAM,KAAK,CAAC;CAC1C,IAAI,GAAG,MAAM,eAAe,KAAK,GAAG,SAAS,KAAK,GAAG,KAAK,qEAAqE;CAC/H,IAAI,GAAG,MAAM,iBAAiB,KAAK,GAAG,SAAS,KAAK,GAAG,KAAK,uCAAuC;CACnG,SAAS,KAAK,GAAG,cAAc,MAAM,KAAK,CAAC;CAC3C,OAAO;AACT;;AAGA,MAAa,UAAkB,UAAU,aAAa,aAAa;CACjE,MAAM,QAAQ,SAAS,SAAS;CAChC,IAAI,CAAC,MAAM,SAAS,MAAM,GAA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UAAU,iBACd,WAAuB,MAAM,cAAc;EAEzC,eAAe,sBAAsB,YAAY,WAAW,OAAO;EAEnE,cAAc,gBAAgB,gBAAgB,KAAK,QAAQ,CAAC,GAAG,WAAW,CAAC;EAE3E,MAAM,UAAU,MAAM,KAAK,MAAM,KAAK,IAAI;CAC5C,CAAC;CAEH,OAAO;EACL;EACA;EACA;EACA,OAAO,SAAS,MAAM,OAAO,SAAS;EACtC,IAAI,SAAS;GACX,OAAO,eAAe,OAAO,SAAS,WAAW;EACnD;EACA;EACA;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 +1 @@
1
- {"version":3,"file":"requests.js","names":[],"sources":["../src/requests.ts"],"sourcesContent":["import { quantity } from \"@mark1russell7/quantity\";\nimport type { Clock } from \"./clock.ts\";\nimport type { Controller } from \"./description.ts\";\nimport type { Operation } from \"./operation.ts\";\nimport { mayReissue } from \"./operation.ts\";\nimport type { CompiledPattern, OperationOf } from \"./routes.ts\";\nimport { compilePattern } from \"./routes.ts\";\nimport { untilAbort } from \"./units.ts\";\n\n/**\n * A request end is the one final result of the stream of a request. Its count `delivered` is the\n * number of items that the stream gave before it. An end after the first item is in-band. The\n * transport sent its answer, thus it writes the end as the last line of the stream, not as a status.\n * - `done`: the work gave each of its items.\n * - `failed`: the work failed for a cause of its own. Before the first item, the adapter answers it\n * as it answers any error of the route.\n * - `refused`: the service did not admit the request. A refused request did not start, thus its\n * caller can send it again: 503, retryable.\n * - `cut`: the shutdown stopped the request. Before the first item, a route whose callers can send\n * it again answers 503, retryable, and each other route answers 500. After the first item, the\n * status is null, and the end is in-band.\n */\nexport type RequestEnd =\n | { readonly kind: \"done\"; readonly delivered: number }\n | { readonly kind: \"failed\"; readonly error: unknown; readonly delivered: number }\n | {\n readonly kind: \"refused\";\n readonly status: 503;\n readonly retryable: true;\n readonly cause: string;\n readonly delivered: 0;\n }\n | {\n readonly kind: \"cut\";\n readonly status: 503 | 500 | null;\n readonly retryable: boolean;\n readonly cause: string;\n readonly delivered: number;\n };\n\n/** A request event is one event of the stream of a request: an item, or the one end, which comes last. */\nexport type RequestEvent<T> = { readonly kind: \"item\"; readonly value: T } | RequestEnd;\n\n/**\n * A request stream is what a request comes to: its items, then one end. A unary work gives a stream\n * of one item. The stream gives an item only when its reader asks for the next event. Thus a slow\n * reader slows the work, and the request stays in flight until the work ends. When the reader\n * stops before the end, the work gets its abort and the `return()` of its iterator.\n */\nexport interface RequestStream<T> extends AsyncIterable<RequestEvent<T>> {\n /** This method reads the whole stream, and gives its items and its end. */\n collect(): Promise<{ readonly items: readonly T[]; readonly end: RequestEnd }>;\n}\n\n/**\n * A request work is what a request function gives: one value, or a stream of values. A work that\n * gives an async iterable is a stream, also through a promise. Each other value is a stream of one.\n */\nexport type RequestWork<T> = T | PromiseLike<T> | AsyncIterable<T> | PromiseLike<AsyncIterable<T>>;\n\n/** A request function does the work of one request. It receives a signal that the shutdown aborts. */\nexport type RequestFn<T> = (signal: AbortSignal) => RequestWork<T>;\n\n/** These options go with one request. */\nexport interface RequestOptions {\n /** This value goes to the function of a route pattern, for example the metadata of a procedure. */\n readonly detail?: unknown;\n}\n\n/** A tracker admits requests, counts the requests in flight, and ends what the shutdown cuts. */\nexport interface Tracker {\n request<T>(controller: string, route: string, work: RequestFn<T>, options?: RequestOptions): RequestStream<T>;\n inFlight(controller?: string): number;\n /** This method refuses each later request. */\n stopIntake(): void;\n /** This method aborts the signal of each request in flight, and ends each stream through `return()`: the cooperative abort of the drain. */\n cooperativeAbort(): void;\n /** This method waits until no request is in flight, or until `deadline`. Then it cuts each request that is left. */\n drain(deadline: number): Promise<void>;\n}\n\ninterface InFlight {\n readonly controller: string;\n /** This function aborts the work, and ends its iterator through `return()`. */\n readonly cooperative: () => void;\n /** This function ends the request with a cut, one time. */\n readonly cut: (cause: string) => void;\n}\n\nconst isAsyncIterable = (value: unknown): value is AsyncIterable<unknown> =>\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === \"function\";\nconst isPromiseLike = (value: unknown): value is PromiseLike<unknown> =>\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\";\n\n/** This function gives a stream of events from a function that gives the next event. */\nconst streamOf = <T>(next: () => Promise<RequestEvent<T> | null>, stop: () => void): RequestStream<T> => {\n let chain: Promise<unknown> = Promise.resolve();\n const iterator: AsyncIterator<RequestEvent<T>> = {\n next() {\n // a reader that asks again before an answer gets the events in their sequence\n const step = chain.then(next).then((event): IteratorResult<RequestEvent<T>> =>\n event === null ? { value: undefined, done: true } : { value: event, done: false },\n );\n chain = step.catch(() => {});\n return step;\n },\n return() {\n stop();\n return Promise.resolve({ value: undefined, done: true });\n },\n };\n return {\n [Symbol.asyncIterator]: () => iterator,\n async collect() {\n const items: T[] = [];\n for (;;) {\n const step = await iterator.next();\n if (step.done === true) throw new Error(\"the stream ended without its end\");\n if (step.value.kind === \"item\") items.push(step.value.value);\n else return { items, end: step.value };\n }\n },\n };\n};\n\n/**\n * This function makes a tracker. `refuses` gives the reason that the service refuses a new request\n * for a controller at this time, or null when it admits it. `choices` gives the function of each\n * route pattern, by controller and by pattern.\n */\nexport const tracker = (\n controllers: readonly Controller[],\n clock: Clock,\n refuses: (controller: string) => string | null,\n choices: ReadonlyMap<string, ReadonlyMap<string, OperationOf>> = new Map(),\n): Tracker => {\n const byName = new Map(\n controllers.map((controller) => [\n controller.name,\n {\n controller,\n patterns: (controller.patterns ?? []).map((declared) => ({ declared, compiled: compilePattern(declared.pattern) as CompiledPattern })),\n },\n ]),\n );\n const flights = new Set<InFlight>();\n const idle = new Set<() => void>();\n let intake = true;\n\n /** This function gives the operation of a request: its exact route, else the first pattern that matches it. */\n const operationOf = (controller: string, route: string, detail: unknown): Operation => {\n const held = byName.get(controller);\n if (held === undefined) throw new Error(`there is no controller ${controller}`);\n const exact = held.controller.routes[route];\n if (exact !== undefined) return exact;\n for (const { declared, compiled } of held.patterns) {\n const found = compiled.match(route);\n if (found === null) continue;\n const names = Object.keys(declared.operations);\n const choose = choices.get(controller)?.get(declared.pattern);\n const name = choose === undefined ? names[0]! : choose({ controller, route, ...found, detail });\n const operation = declared.operations[name];\n if (operation === undefined)\n throw new Error(`the pattern ${declared.pattern} of ${controller} declares no operation ${String(name)} for ${route}`);\n return operation;\n }\n // a route that nobody declared has no idempotency: the runtime has no defaults\n throw new Error(`controller ${controller} does not declare the route ${route}`);\n };\n\n const settle = (flight: InFlight): void => {\n if (!flights.delete(flight)) return;\n if (flights.size === 0) for (const done of [...idle]) done();\n };\n\n /** This function starts the work of an admitted request, and gives its stream. */\n const open = <T>(controller: string, operation: Operation, work: RequestFn<T>): RequestStream<T> => {\n const started = clock.now();\n const abort = new AbortController();\n let delivered = 0;\n let end: RequestEnd | null = null;\n let ended = false;\n let returned = false;\n let source: AsyncIterator<T> | null = null;\n // a unary work keeps its value until the reader asks for it\n let unary: { readonly value: T } | null = null;\n // Each wait of the reader listens for the end with a listener of its own, thus a long stream keeps no item that went.\n const interruption = new AbortController();\n const interrupt = (): void => interruption.abort();\n\n const cutEnd = (cause: string): RequestEnd => {\n const since = quantity(Math.max(0, clock.now() - started) / 1000, \"s\");\n const retryable = mayReissue(operation, since);\n return { kind: \"cut\", status: delivered > 0 ? null : retryable ? 503 : 500, retryable, cause, delivered };\n };\n /** This function ends the work of the request: the end is known, and the request leaves the flights. */\n const finish = (given: RequestEnd): void => {\n if (end !== null) return;\n end = given;\n settle(flight);\n interrupt();\n };\n /** This function ends the work after a throw: a failure after the shutdown aborted it is a cut. */\n const failed = (error: unknown): void =>\n finish(abort.signal.aborted ? cutEnd(\"the shutdown aborted it, and it failed\") : { kind: \"failed\", error, delivered });\n const closeSource = (): void => {\n if (source === null || returned) return;\n returned = true;\n try {\n void Promise.resolve(source.return?.()).catch(() => {});\n } catch {\n // an iterator whose return() throws has ended\n }\n };\n const flight: InFlight = {\n controller,\n cooperative: () => {\n abort.abort(new Error(\"the cooperative abort of the drain\"));\n closeSource();\n },\n cut: (cause) => {\n abort.abort(new Error(cause));\n finish(cutEnd(cause));\n closeSource();\n },\n };\n flights.add(flight);\n\n /** This function takes the result of the work: a stream, or one value. */\n const take = (result: unknown): void => {\n if (end !== null) return;\n if (isAsyncIterable(result)) {\n source = (result as AsyncIterable<T>)[Symbol.asyncIterator]();\n // a stream that comes after the cooperative abort ends at once\n if (abort.signal.aborted) closeSource();\n } else {\n unary = { value: result as T };\n // the unary work has ended: its value waits for the reader\n settle(flight);\n }\n };\n let ready: Promise<void>;\n try {\n const result = work(abort.signal);\n if (isAsyncIterable(result) || !isPromiseLike(result)) {\n take(result);\n ready = Promise.resolve();\n } else ready = Promise.resolve(result).then(take, failed);\n } catch (error) {\n failed(error);\n ready = Promise.resolve();\n }\n\n const next = async (): Promise<RequestEvent<T> | null> => {\n if (ended) return null;\n if (end === null) await untilAbort(ready, interruption.signal, \"interrupted\");\n if (end === null && unary !== null) {\n const { value } = unary;\n unary = null;\n delivered = 1;\n end = { kind: \"done\", delivered };\n return { kind: \"item\", value };\n }\n if (end === null && source !== null) {\n const pending = source.next();\n let step: IteratorResult<T> | \"interrupted\";\n try {\n step = await untilAbort(Promise.resolve(pending), interruption.signal, \"interrupted\" as const);\n } catch (error) {\n failed(error);\n step = \"interrupted\";\n }\n if (step !== \"interrupted\") {\n if (step.done !== true) {\n delivered += 1;\n return { kind: \"item\", value: step.value };\n }\n // a stream that ends after the abort of the shutdown is a cut\n finish(abort.signal.aborted ? cutEnd(\"the shutdown ended the stream\") : { kind: \"done\", delivered });\n }\n }\n ended = true;\n return end!;\n };\n const stop = (): void => {\n // the reader stopped before the end: the work stops too\n if (end === null) {\n abort.abort(new Error(\"the reader stopped the stream\"));\n finish({ kind: \"done\", delivered });\n closeSource();\n }\n ended = true;\n };\n return streamOf(next, stop);\n };\n\n return {\n request<T>(controller: string, route: string, work: RequestFn<T>, options: RequestOptions = {}) {\n const operation = operationOf(controller, route, options.detail);\n const refusal = intake ? refuses(controller) : \"the service stopped its intake\";\n if (refusal !== null) {\n let given = false;\n const refused: RequestEnd = { kind: \"refused\", status: 503, retryable: true, cause: refusal, delivered: 0 };\n return streamOf<T>(\n () => {\n if (given) return Promise.resolve(null);\n given = true;\n return Promise.resolve(refused);\n },\n () => {\n given = true;\n },\n );\n }\n return open(controller, operation, work);\n },\n inFlight(controller) {\n let count = 0;\n for (const flight of flights) if (controller === undefined || flight.controller === controller) count += 1;\n return count;\n },\n stopIntake() {\n intake = false;\n },\n cooperativeAbort() {\n for (const flight of [...flights]) flight.cooperative();\n },\n drain(deadline) {\n if (flights.size === 0) return Promise.resolve();\n return new Promise<void>((resolve) => {\n let finished = false;\n const done = (): void => {\n if (finished) return;\n finished = true;\n idle.delete(done);\n cancel();\n resolve();\n };\n idle.add(done);\n const cancel = clock.after(Math.max(0, deadline - clock.now()), () => {\n for (const flight of [...flights]) flight.cut(\"the drain reached its deadline\");\n done();\n });\n });\n },\n };\n};\n"],"mappings":";;;;;AAyFA,MAAM,mBAAmB,UACvB,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA+C,OAAO,mBAAmB;AACnF,MAAM,iBAAiB,UACrB,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA6B,SAAS;;AAGhD,MAAM,YAAe,MAA6C,SAAuC;CACvG,IAAI,QAA0B,QAAQ,QAAQ;CAC9C,MAAM,WAA2C;EAC/C,OAAO;GAEL,MAAM,OAAO,MAAM,KAAK,IAAI,CAAC,CAAC,MAAM,UAClC,UAAU,OAAO;IAAE,OAAO,KAAA;IAAW,MAAM;GAAK,IAAI;IAAE,OAAO;IAAO,MAAM;GAAM,CAClF;GACA,QAAQ,KAAK,YAAY,CAAC,CAAC;GAC3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BAAmB;GACjB,KAAK,MAAM,UAAU,CAAC,GAAG,OAAO,GAAG,OAAO,YAAY;EACxD;EACA,MAAM,UAAU;GACd,IAAI,QAAQ,SAAS,GAAG,OAAO,QAAQ,QAAQ;GAC/C,OAAO,IAAI,SAAe,YAAY;IACpC,IAAI,WAAW;IACf,MAAM,aAAmB;KACvB,IAAI,UAAU;KACd,WAAW;KACX,KAAK,OAAO,IAAI;KAChB,OAAO;KACP,QAAQ;IACV;IACA,KAAK,IAAI,IAAI;IACb,MAAM,SAAS,MAAM,MAAM,KAAK,IAAI,GAAG,WAAW,MAAM,IAAI,CAAC,SAAS;KACpE,KAAK,MAAM,UAAU,CAAC,GAAG,OAAO,GAAG,OAAO,IAAI,gCAAgC;KAC9E,KAAK;IACP,CAAC;GACH,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"requests.js","names":[],"sources":["../src/requests.ts"],"sourcesContent":["import { quantity } from \"@mark1russell7/quantity\";\nimport type { Clock } from \"./clock.ts\";\nimport type { Controller } from \"./description.ts\";\nimport type { Operation } from \"./operation.ts\";\nimport { mayReissue } from \"./operation.ts\";\nimport type { CompiledPattern, OperationOf } from \"./routes.ts\";\nimport { compilePattern } from \"./routes.ts\";\nimport { untilAbort } from \"./units.ts\";\n\n/**\n * A request end is the one final result of the stream of a request. Its count `delivered` is the\n * number of items that the stream gave before it. An end after the first item is in-band. The\n * transport sent its answer, thus it writes the end as the last line of the stream, not as a status.\n * - `done`: the work gave each of its items.\n * - `failed`: the work failed for a cause of its own. Before the first item, the adapter answers it\n * as it answers any error of the route.\n * - `refused`: the service did not admit the request. A refused request did not start, thus its\n * caller can send it again: 503, retryable.\n * - `cut`: the shutdown stopped the request. Before the first item, a route whose callers can send\n * it again answers 503, retryable, and each other route answers 500. After the first item, the\n * status is null, and the end is in-band.\n */\nexport type RequestEnd =\n | { readonly kind: \"done\"; readonly delivered: number }\n | { readonly kind: \"failed\"; readonly error: unknown; readonly delivered: number }\n | {\n readonly kind: \"refused\";\n readonly status: 503;\n readonly retryable: true;\n readonly cause: string;\n readonly delivered: 0;\n }\n | {\n readonly kind: \"cut\";\n readonly status: 503 | 500 | null;\n readonly retryable: boolean;\n readonly cause: string;\n readonly delivered: number;\n };\n\n/** A request event is one event of the stream of a request: an item, or the one end, which comes last. */\nexport type RequestEvent<T> = { readonly kind: \"item\"; readonly value: T } | RequestEnd;\n\n/**\n * A request stream is what a request comes to: its items, then one end. A unary work gives a stream\n * of one item. The stream gives an item only when its reader asks for the next event. Thus a slow\n * reader slows the work, and the request stays in flight until the work ends. When the reader\n * stops before the end, the work gets its abort and the `return()` of its iterator.\n */\nexport interface RequestStream<T> extends AsyncIterable<RequestEvent<T>> {\n /** This method reads the whole stream, and gives its items and its end. */\n collect(): Promise<{ readonly items: readonly T[]; readonly end: RequestEnd }>;\n}\n\n/**\n * A request work is what a request function gives: one value, or a stream of values. A work that\n * gives an async iterable is a stream, also through a promise. Each other value is a stream of one.\n */\nexport type RequestWork<T> = T | PromiseLike<T> | AsyncIterable<T> | PromiseLike<AsyncIterable<T>>;\n\n/** A request function does the work of one request. It receives a signal that the shutdown aborts. */\nexport type RequestFn<T> = (signal: AbortSignal) => RequestWork<T>;\n\n/** These options go with one request. */\nexport interface RequestOptions {\n /** This value goes to the function of a route pattern, for example the metadata of a procedure. */\n readonly detail?: unknown;\n}\n\n/** A tracker admits requests, counts the requests in flight, and ends what the shutdown cuts. */\nexport interface Tracker {\n request<T>(controller: string, route: string, work: RequestFn<T>, options?: RequestOptions): RequestStream<T>;\n inFlight(controller?: string): number;\n /** This method refuses each later request. */\n stopIntake(): void;\n /** This method aborts the signal of each request in flight, and ends each stream through `return()`: the cooperative abort of the drain. */\n cooperativeAbort(): void;\n /** This method waits until no request is in flight, or until `deadline`. Then it cuts each request that is left. */\n drain(deadline: number): Promise<void>;\n}\n\ninterface InFlight {\n readonly controller: string;\n /** This function aborts the work, and ends its iterator through `return()`. */\n readonly cooperative: () => void;\n /** This function ends the request with a cut, one time. */\n readonly cut: (cause: string) => void;\n}\n\nconst isAsyncIterable = (value: unknown): value is AsyncIterable<unknown> =>\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === \"function\";\nconst isPromiseLike = (value: unknown): value is PromiseLike<unknown> =>\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\";\n\n/** This function gives a stream of events from a function that gives the next event. */\nconst streamOf = <T>(next: () => Promise<RequestEvent<T> | null>, stop: () => void): RequestStream<T> => {\n let chain: Promise<unknown> = Promise.resolve();\n const iterator: AsyncIterator<RequestEvent<T>> = {\n next() {\n // a reader that asks again before an answer gets the events in their sequence\n const step = chain.then(next).then((event): IteratorResult<RequestEvent<T>> =>\n event === null ? { value: undefined, done: true } : { value: event, done: false },\n );\n chain = step.catch(() => {});\n return step;\n },\n return() {\n stop();\n return Promise.resolve({ value: undefined, done: true });\n },\n };\n return {\n [Symbol.asyncIterator]: () => iterator,\n async collect() {\n const items: T[] = [];\n for (;;) {\n const step = await iterator.next();\n if (step.done === true) throw new Error(\"the stream ended without its end\");\n if (step.value.kind === \"item\") items.push(step.value.value);\n else return { items, end: step.value };\n }\n },\n };\n};\n\n/**\n * This function makes a tracker. `refuses` gives the reason that the service refuses a new request\n * for a controller at this time, or null when it admits it. `choices` gives the function of each\n * route pattern, by controller and by pattern.\n */\nexport const tracker = (\n controllers: readonly Controller[],\n clock: Clock,\n refuses: (controller: string) => string | null,\n choices: ReadonlyMap<string, ReadonlyMap<string, OperationOf>> = new Map(),\n): Tracker => {\n const byName = new Map(\n controllers.map((controller) => [\n controller.name,\n {\n controller,\n patterns: (controller.patterns ?? []).map((declared) => ({ declared, compiled: compilePattern(declared.pattern) as CompiledPattern })),\n },\n ]),\n );\n const flights = new Set<InFlight>();\n const idle = new Set<() => void>();\n let intake = true;\n\n /** This function gives the operation of a request: its exact route, else the first pattern that matches it. */\n const operationOf = (controller: string, route: string, detail: unknown): Operation => {\n const held = byName.get(controller);\n if (held === undefined) throw new Error(`there is no controller ${controller}`);\n const exact = held.controller.routes[route];\n if (exact !== undefined) return exact;\n for (const { declared, compiled } of held.patterns) {\n const found = compiled.match(route);\n if (found === null) continue;\n const names = Object.keys(declared.operations);\n const choose = choices.get(controller)?.get(declared.pattern);\n const name = choose === undefined ? names[0]! : choose({ controller, route, ...found, detail });\n const operation = declared.operations[name];\n if (operation === undefined)\n throw new Error(`the pattern ${declared.pattern} of ${controller} declares no operation ${String(name)} for ${route}`);\n return operation;\n }\n // a route that nobody declared has no idempotency: the runtime has no defaults\n throw new Error(`controller ${controller} does not declare the route ${route}`);\n };\n\n const settle = (flight: InFlight): void => {\n if (!flights.delete(flight)) return;\n if (flights.size === 0) for (const done of [...idle]) done();\n };\n\n /** This function starts the work of an admitted request, and gives its stream. */\n const open = <T>(controller: string, operation: Operation, work: RequestFn<T>): RequestStream<T> => {\n const started = clock.now();\n const abort = new AbortController();\n let delivered = 0;\n let end: RequestEnd | null = null;\n let ended = false;\n let returned = false;\n let source: AsyncIterator<T> | null = null;\n // a unary work keeps its value until the reader asks for it\n let unary: { readonly value: T } | null = null;\n // Each wait of the reader listens for the end with a listener of its own, thus a long stream keeps no item that went.\n const interruption = new AbortController();\n const interrupt = (): void => interruption.abort();\n\n const cutEnd = (cause: string): RequestEnd => {\n const since = quantity(Math.max(0, clock.now() - started) / 1000, \"s\");\n const retryable = mayReissue(operation, since);\n return { kind: \"cut\", status: delivered > 0 ? null : retryable ? 503 : 500, retryable, cause, delivered };\n };\n /** This function ends the work of the request: the end is known, and the request leaves the flights. */\n const finish = (given: RequestEnd): void => {\n if (end !== null) return;\n end = given;\n settle(flight);\n interrupt();\n };\n /** This function ends the work after a throw: a failure after the shutdown aborted it is a cut. */\n const failed = (error: unknown): void =>\n finish(abort.signal.aborted ? cutEnd(\"the shutdown aborted it, and it failed\") : { kind: \"failed\", error, delivered });\n const closeSource = (): void => {\n if (source === null || returned) return;\n returned = true;\n try {\n void Promise.resolve(source.return?.()).catch(() => {});\n } catch {\n // an iterator whose return() throws has ended\n }\n };\n const flight: InFlight = {\n controller,\n cooperative: () => {\n abort.abort(new Error(\"the cooperative abort of the drain\"));\n closeSource();\n },\n cut: (cause) => {\n abort.abort(new Error(cause));\n finish(cutEnd(cause));\n closeSource();\n },\n };\n flights.add(flight);\n\n /** This function takes the result of the work: a stream, or one value. */\n const take = (result: unknown): void => {\n if (end !== null) return;\n if (isAsyncIterable(result)) {\n source = (result as AsyncIterable<T>)[Symbol.asyncIterator]();\n // a stream that comes after the cooperative abort ends at once\n if (abort.signal.aborted) closeSource();\n } else {\n unary = { value: result as T };\n // the unary work has ended: its value waits for the reader\n settle(flight);\n }\n };\n let ready: Promise<void>;\n try {\n const result = work(abort.signal);\n if (isAsyncIterable(result) || !isPromiseLike(result)) {\n take(result);\n ready = Promise.resolve();\n } else ready = Promise.resolve(result).then(take, failed);\n } catch (error) {\n failed(error);\n ready = Promise.resolve();\n }\n\n const next = async (): Promise<RequestEvent<T> | null> => {\n if (ended) return null;\n if (end === null) await untilAbort(ready, interruption.signal, \"interrupted\");\n if (end === null && unary !== null) {\n const { value } = unary;\n unary = null;\n delivered = 1;\n end = { kind: \"done\", delivered };\n return { kind: \"item\", value };\n }\n if (end === null && source !== null) {\n const pending = source.next();\n let step: IteratorResult<T> | \"interrupted\";\n try {\n step = await untilAbort(Promise.resolve(pending), interruption.signal, \"interrupted\" as const);\n } catch (error) {\n failed(error);\n step = \"interrupted\";\n }\n if (step !== \"interrupted\") {\n if (step.done !== true) {\n delivered += 1;\n return { kind: \"item\", value: step.value };\n }\n // a stream that ends after the abort of the shutdown is a cut\n finish(abort.signal.aborted ? cutEnd(\"the shutdown ended the stream\") : { kind: \"done\", delivered });\n }\n }\n ended = true;\n return end!;\n };\n const stop = (): void => {\n // the reader stopped before the end: the work stops too\n if (end === null) {\n abort.abort(new Error(\"the reader stopped the stream\"));\n finish({ kind: \"done\", delivered });\n closeSource();\n }\n ended = true;\n };\n return streamOf(next, stop);\n };\n\n return {\n request<T>(controller: string, route: string, work: RequestFn<T>, options: RequestOptions = {}) {\n const operation = operationOf(controller, route, options.detail);\n const refusal = intake ? refuses(controller) : \"the service stopped its intake\";\n if (refusal !== null) {\n let given = false;\n const refused: RequestEnd = { kind: \"refused\", status: 503, retryable: true, cause: refusal, delivered: 0 };\n return streamOf<T>(\n () => {\n if (given) return Promise.resolve(null);\n given = true;\n return Promise.resolve(refused);\n },\n () => {\n given = true;\n },\n );\n }\n return open(controller, operation, work);\n },\n inFlight(controller) {\n let count = 0;\n for (const flight of flights) if (controller === undefined || flight.controller === controller) count += 1;\n return count;\n },\n stopIntake() {\n intake = false;\n },\n cooperativeAbort() {\n for (const flight of [...flights]) flight.cooperative();\n },\n drain(deadline) {\n if (flights.size === 0) return Promise.resolve();\n return new Promise<void>((resolve) => {\n let finished = false;\n const done = (): void => {\n if (finished) return;\n finished = true;\n idle.delete(done);\n cancel();\n resolve();\n };\n idle.add(done);\n // the drain awaits its deadline, thus the timer keeps the process alive (SYS-126)\n const cancel = clock.after(Math.max(0, deadline - clock.now()), () => {\n for (const flight of [...flights]) flight.cut(\"the drain reached its deadline\");\n done();\n });\n });\n },\n };\n};\n"],"mappings":";;;;;AAyFA,MAAM,mBAAmB,UACvB,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA+C,OAAO,mBAAmB;AACnF,MAAM,iBAAiB,UACrB,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA6B,SAAS;;AAGhD,MAAM,YAAe,MAA6C,SAAuC;CACvG,IAAI,QAA0B,QAAQ,QAAQ;CAC9C,MAAM,WAA2C;EAC/C,OAAO;GAEL,MAAM,OAAO,MAAM,KAAK,IAAI,CAAC,CAAC,MAAM,UAClC,UAAU,OAAO;IAAE,OAAO,KAAA;IAAW,MAAM;GAAK,IAAI;IAAE,OAAO;IAAO,MAA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SAAS;GACzG,OAAO;EACT;EACA,aAAa;GACX,SAAS;EACX;EACA,mBAAmB;GACjB,KAAK,MAAM,UAAU,CAAC,GAAG,OAAO,GAAG,OAAO,YAAY;EACxD;EACA,MAAM,UAAU;GACd,IAAI,QAAQ,SAAS,GAAG,OAAO,QAAQ,QAAQ;GAC/C,OAAO,IAAI,SAAe,YAAY;IACpC,IAAI,WAAW;IACf,MAAM,aAAmB;KACvB,IAAI,UAAU;KACd,WAAW;KACX,KAAK,OAAO,IAAI;KAChB,OAAO;KACP,QAAQ;IACV;IACA,KAAK,IAAI,IAAI;IAEb,MAAM,SAAS,MAAM,MAAM,KAAK,IAAI,GAAG,WAAW,MAAM,IAAI,CAAC,SAAS;KACpE,KAAK,MAAM,UAAU,CAAC,GAAG,OAAO,GAAG,OAAO,IAAI,gCAAgC;KAC9E,KAAK;IACP,CAAC;GACH,CAAC;EACH;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"retrier.js","names":[],"sources":["../src/retrier.ts"],"sourcesContent":["import { delay } from \"@mark1russell7/algebra/clock\";\nimport type { Backoff } from \"./backoff.ts\";\nimport { backoffDelay, backoffProblems } from \"./backoff.ts\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\n\n/** These options make a retrier: a backoff policy, the clock of its timers, and the signal that cancels it. */\nexport interface RetrierOptions extends Backoff {\n /** This clock starts each retry. The default is the real clock. A test gives a fake clock. */\n readonly clock?: Clock | undefined;\n /** This function gives a number in [0, 1) for the jitter of each delay. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n /**\n * This signal cancels the retrier when it aborts, for example the `signal` of the lifecycle, which\n * aborts in the drain. After the abort, `schedule` starts nothing.\n */\n readonly signal?: AbortSignal | undefined;\n}\n\n/** A retrier starts a function again after the backoff of each try, on its clock. */\nexport interface Retrier {\n /** This count is the number of tries since the last reset. */\n readonly attempts: number;\n /** This flag tells if a retry waits for its timer. */\n readonly pending: boolean;\n /**\n * This method counts one more try, and starts `run` after the backoff delay of that try. It gives\n * the delay in milliseconds. A retry that waits stops, thus one retry at most waits. After the\n * abort of the signal, it starts nothing and gives null. The function catches its own errors.\n */\n schedule(run: () => void): number | null;\n /** This method sets the count of tries to 0, for example after a start that succeeded. A retry that waits stays. */\n reset(): void;\n /** This method stops the retry that waits. The count of tries stays. */\n cancel(): void;\n}\n\n/** This function makes a retrier with no check of its policy. A client of the package uses it with its own knobs. */\nexport const retrierOn = (clock: Clock, backoff: Backoff, random: () => number, signal?: AbortSignal): Retrier => {\n let tries = 0;\n let timer: Cancel | null = null;\n const cancel = (): void => {\n timer?.();\n timer = null;\n };\n signal?.addEventListener(\"abort\", cancel, { once: true });\n return {\n get attempts() {\n return tries;\n },\n get pending() {\n return timer !== null;\n },\n schedule(run) {\n if (signal?.aborted === true) return null;\n tries += 1;\n const delay = Math.round(backoffDelay(backoff, tries, random));\n timer?.();\n timer = clock.after(delay, () => {\n timer = null;\n run();\n });\n return delay;\n },\n cancel,\n reset() {\n tries = 0;\n },\n };\n};\n\n/**\n * This function makes a retrier over `backoffDelay`. The first try waits `base`, and each try after\n * it waits `factor` times more, to the `cap`, with the jitter of the policy. It refuses a policy\n * with a problem of `backoffProblems`.\n */\nexport const retrier = (options: RetrierOptions): Retrier => {\n const { clock = realClock, random = Math.random, signal, ...backoff } = options;\n const problems = backoffProblems(backoff);\n if (problems.length > 0) throw new Error(`the retrier has a bad backoff: ${problems.join(\"; \")}`);\n return retrierOn(clock, backoff, random, signal);\n};\n\n/** These options make one call with retries: the most tries, the errors to retry, and the policy of a retrier. */\nexport interface RetryOptions extends RetrierOptions {\n /** This number is the most tries of the call, the first try included. It is 1 or more. */\n readonly tries: number;\n /** This function tells if a try starts again after this error. The default retries each error. */\n readonly retryable?: ((error: unknown) => boolean) | undefined;\n /**\n * This function gives the delay in milliseconds before the next try, in place of the backoff. An example\n * is the `Retry-After` header of an HTTP 429. Null, undefined, NaN, an infinite or a negative number keeps\n * the backoff delay. The retry puts no cap on this delay, so the caller caps it, for example at 60 s.\n */\n readonly delayOf?: ((error: unknown, attempt: number) => number | null | undefined) | undefined;\n}\n\n/**\n * This function gives the wait of a `Retry-After` header (RFC 9110) in milliseconds: a count of seconds,\n * or an HTTP date after `now`. It gives null for a header with no valid value. A date before `now` gives 0.\n */\nexport const retryAfterDelay = (header: string | null | undefined, now: number): number | null => {\n const text = header?.trim() ?? \"\";\n if (text === \"\") return null;\n if (/^\\d+$/.test(text)) return Number(text) * 1000;\n // An HTTP date has the name of its day and month. Without a letter, Date.parse reads \"-3\" as a year.\n const at = /[A-Za-z]/.test(text) ? Date.parse(text) : Number.NaN;\n return Number.isNaN(at) ? null : Math.max(0, at - now);\n};\n\n/**\n * This function starts `run`, and starts it again after an error, to the count of `tries`. The delay\n * before try n + 1 is `delayOf(error, n)`, else the `backoffDelay` of try n, on the clock. The call gives\n * the value of the first try that succeeds. After the last try, an error that is not retryable, or the\n * abort of the signal, it throws the last error. It refuses a policy with a problem of `backoffProblems`.\n */\nexport const retry = async <T>(run: (attempt: number) => Promise<T>, options: RetryOptions): Promise<T> => {\n const { tries, retryable = () => true, delayOf, clock = realClock, random = Math.random, signal, ...backoff } = options;\n if (!Number.isInteger(tries) || tries < 1) throw new Error(`retry needs a whole number of tries of 1 or more, not ${tries}`);\n const problems = backoffProblems(backoff);\n if (problems.length > 0) throw new Error(`the retry has a bad backoff: ${problems.join(\"; \")}`);\n for (let attempt = 1; ; attempt += 1) {\n try {\n return await run(attempt);\n } catch (error) {\n if (attempt >= tries || signal?.aborted === true || !retryable(error)) throw error;\n const own = delayOf?.(error, attempt);\n // A bad delay (NaN, an infinite or a negative number) gets the backoff, so that it cannot start the tries at once.\n const valid = typeof own === \"number\" && Number.isFinite(own) && own >= 0;\n const wait = Math.round(valid ? own : backoffDelay(backoff, attempt, random));\n // An abort in the wait ends the call with the last error of the run, not with the reason of the signal.\n try {\n await delay(clock, wait, signal);\n } catch {\n throw error;\n }\n }\n }\n};\n"],"mappings":";;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W,SAAS,KAAK,QAAQ,QAAQ,GAAG,YAAY;CAChH,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAG,MAAM,IAAI,MAAM,yDAAyD,OAAO;CAC3H,MAAM,WAAW,gBAAgB,OAAO;CACxC,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,MAAM,gCAAgC,SAAS,KAAK,IAAI,GAAG;CAC9F,KAAK,IAAI,UAAU,IAAK,WAAW,GACjC,IAAI;EACF,OAAO,MAAM,IAAI,OAAO;CAC1B,SAAS,OAAO;EACd,IAAI,WAAW,SAAS,QAAQ,YAAY,QAAQ,CAAC,UAAU,KAAK,GAAG,MAAM;EAC7E,MAAM,MAAM,UAAU,OAAO,OAAO;EAGpC,MAAM,OAAO,KAAK,MADJ,OAAO,QAAQ,YAAY,OAAO,SAAS,GAAG,KAAK,OAAO,IACxC,MAAM,aAAa,SAAS,SAAS,MAAM,CAAC;EAE5E,IAAI;GACF,MAAM,MAAM,OAAO,MAAM,MAAM;EACjC,QAAQ;GACN,MAAM;EACR;CACF;AAEJ"}
1
+ {"version":3,"file":"retrier.js","names":[],"sources":["../src/retrier.ts"],"sourcesContent":["import { delay } from \"@mark1russell7/algebra/clock\";\nimport type { Backoff } from \"./backoff.ts\";\nimport { backoffDelay, backoffProblems } from \"./backoff.ts\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\n\n/** These options make a retrier: a backoff policy, the clock of its timers, and the signal that cancels it. */\nexport interface RetrierOptions extends Backoff {\n /** This clock starts each retry. The default is the real clock. A test gives a fake clock. */\n readonly clock?: Clock | undefined;\n /** This function gives a number in [0, 1) for the jitter of each delay. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n /**\n * This signal cancels the retrier when it aborts, for example the `signal` of the lifecycle, which\n * aborts in the drain. After the abort, `schedule` starts nothing.\n */\n readonly signal?: AbortSignal | undefined;\n}\n\n/** A retrier starts a function again after the backoff of each try, on its clock. */\nexport interface Retrier {\n /** This count is the number of tries since the last reset. */\n readonly attempts: number;\n /** This flag tells if a retry waits for its timer. */\n readonly pending: boolean;\n /**\n * This method counts one more try, and starts `run` after the backoff delay of that try. It gives\n * the delay in milliseconds. A retry that waits stops, thus one retry at most waits. After the\n * abort of the signal, it starts nothing and gives null. The function catches its own errors.\n */\n schedule(run: () => void): number | null;\n /** This method sets the count of tries to 0, for example after a start that succeeded. A retry that waits stays. */\n reset(): void;\n /** This method stops the retry that waits. The count of tries stays. */\n cancel(): void;\n}\n\n/** This function makes a retrier with no check of its policy. A client of the package uses it with its own knobs. */\nexport const retrierOn = (clock: Clock, backoff: Backoff, random: () => number, signal?: AbortSignal): Retrier => {\n let tries = 0;\n let timer: Cancel | null = null;\n const cancel = (): void => {\n timer?.();\n timer = null;\n };\n signal?.addEventListener(\"abort\", cancel, { once: true });\n return {\n get attempts() {\n return tries;\n },\n get pending() {\n return timer !== null;\n },\n schedule(run) {\n if (signal?.aborted === true) return null;\n tries += 1;\n const delay = Math.round(backoffDelay(backoff, tries, random));\n timer?.();\n // the next try is work, thus the timer keeps the process alive. The owner stops the retrier (SYS-126)\n timer = clock.after(delay, () => {\n timer = null;\n run();\n });\n return delay;\n },\n cancel,\n reset() {\n tries = 0;\n },\n };\n};\n\n/**\n * This function makes a retrier over `backoffDelay`. The first try waits `base`, and each try after\n * it waits `factor` times more, to the `cap`, with the jitter of the policy. It refuses a policy\n * with a problem of `backoffProblems`.\n */\nexport const retrier = (options: RetrierOptions): Retrier => {\n const { clock = realClock, random = Math.random, signal, ...backoff } = options;\n const problems = backoffProblems(backoff);\n if (problems.length > 0) throw new Error(`the retrier has a bad backoff: ${problems.join(\"; \")}`);\n return retrierOn(clock, backoff, random, signal);\n};\n\n/** These options make one call with retries: the most tries, the errors to retry, and the policy of a retrier. */\nexport interface RetryOptions extends RetrierOptions {\n /** This number is the most tries of the call, the first try included. It is 1 or more. */\n readonly tries: number;\n /** This function tells if a try starts again after this error. The default retries each error. */\n readonly retryable?: ((error: unknown) => boolean) | undefined;\n /**\n * This function gives the delay in milliseconds before the next try, in place of the backoff. An example\n * is the `Retry-After` header of an HTTP 429. Null, undefined, NaN, an infinite or a negative number keeps\n * the backoff delay. The retry puts no cap on this delay, so the caller caps it, for example at 60 s.\n */\n readonly delayOf?: ((error: unknown, attempt: number) => number | null | undefined) | undefined;\n}\n\n/**\n * This function gives the wait of a `Retry-After` header (RFC 9110) in milliseconds: a count of seconds,\n * or an HTTP date after `now`. It gives null for a header with no valid value. A date before `now` gives 0.\n */\nexport const retryAfterDelay = (header: string | null | undefined, now: number): number | null => {\n const text = header?.trim() ?? \"\";\n if (text === \"\") return null;\n if (/^\\d+$/.test(text)) return Number(text) * 1000;\n // An HTTP date has the name of its day and month. Without a letter, Date.parse reads \"-3\" as a year.\n const at = /[A-Za-z]/.test(text) ? Date.parse(text) : Number.NaN;\n return Number.isNaN(at) ? null : Math.max(0, at - now);\n};\n\n/**\n * This function starts `run`, and starts it again after an error, to the count of `tries`. The delay\n * before try n + 1 is `delayOf(error, n)`, else the `backoffDelay` of try n, on the clock. The call gives\n * the value of the first try that succeeds. After the last try, an error that is not retryable, or the\n * abort of the signal, it throws the last error. It refuses a policy with a problem of `backoffProblems`.\n */\nexport const retry = async <T>(run: (attempt: number) => Promise<T>, options: RetryOptions): Promise<T> => {\n const { tries, retryable = () => true, delayOf, clock = realClock, random = Math.random, signal, ...backoff } = options;\n if (!Number.isInteger(tries) || tries < 1) throw new Error(`retry needs a whole number of tries of 1 or more, not ${tries}`);\n const problems = backoffProblems(backoff);\n if (problems.length > 0) throw new Error(`the retry has a bad backoff: ${problems.join(\"; \")}`);\n for (let attempt = 1; ; attempt += 1) {\n try {\n return await run(attempt);\n } catch (error) {\n if (attempt >= tries || signal?.aborted === true || !retryable(error)) throw error;\n const own = delayOf?.(error, attempt);\n // A bad delay (NaN, an infinite or a negative number) gets the backoff, so that it cannot start the tries at once.\n const valid = typeof own === \"number\" && Number.isFinite(own) && own >= 0;\n const wait = Math.round(valid ? own : backoffDelay(backoff, attempt, random));\n // An abort in the wait ends the call with the last error of the run, not with the reason of the signal.\n try {\n await delay(clock, wait, signal);\n } catch {\n throw error;\n }\n }\n }\n};\n"],"mappings":";;;;;AAsCA,MAAa,aAAa,OAAc,SAAkB,QAAsB,WAAkC;CAChH,IAAI,QAAQ;CACZ,IAAI,QAAuB;CAC3B,MAAM,eAAqB;EACzB,QAAQ;EACR,QAAQ;CACV;CACA,QAAQ,iBAAiB,SAAS,QAAQ,EAAE,MAAM,KAAK,CAAC;CACxD,OAAO;EACL,IAAI,WAAW;GACb,OAAO;EACT;EACA,IAAI,UAAU;GACZ,OAAO,UAAU;EACnB;EACA,SAAS,KAAK;GACZ,IAAI,QAAQ,YAAY,MAAM,OAAO;GACrC,SAAS;GACT,MAAM,QAAQ,KAAK,MAAM,aAAa,SAAS,OAAO,MAAM,CAAC;GAC7D,QAAQ;GAER,QAAQ,MAAM,MAAM,aAAa;IAC/B,QAAQ;IACR,IAAI;GACN,CAAC;GACD,OAAO;EACT;EACA;EACA,QAAQ;GACN,QAAQ;EACV;CACF;AACF;;;;;;AAOA,MAAa,WAAW,YAAqC;CAC3D,MAAM,EAAE,QAAQ,WAAW,SAAS,KAAK,QAAQ,QAAQ,GAAG,YAAY;CACxE,MAAM,WAAW,gBAAgB,OAAO;CACxC,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,MAAM,kCAAkC,SAAS,KAAK,IAAI,GAAG;CAChG,OAAO,UAAU,OAAO,SAAS,QAAQ,MAAM;AACjD;;;;;AAoBA,MAAa,mBAAmB,QAAmC,QAA+B;CAChG,MAAM,OAAO,QAAQ,KAAK,KAAK;CAC/B,IAAI,SAAS,IAAI,OAAO;CACxB,IAAI,QAAQ,KAAK,IAAI,GAAG,OAAO,OAAO,IAAI,IAAI;CAE9C,MAAM,KAAK,WAAW,KAAK,IAAI,IAAI,KAAK,MAAM,IAAI,IAAI;CACtD,OAAO,OAAO,MAAM,EAAE,IAAI,OAAO,KAAK,IAAI,GAAG,KAAK,GAAG;AACvD;;;;;;;AAQA,MAAa,QAAQ,OAAU,KAAsC,YAAsC;CACzG,MAAM,EAAE,OAAO,kBAAkB,MAAM,SAAS,QAAQ,WAAW,SAAS,KAAK,QAAQ,QAAQ,GAAG,YAAY;CAChH,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAG,MAAM,IAAI,MAAM,yDAAyD,OAAO;CAC3H,MAAM,WAAW,gBAAgB,OAAO;CACxC,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,MAAM,gCAAgC,SAAS,KAAK,IAAI,GAAG;CAC9F,KAAK,IAAI,UAAU,IAAK,WAAW,GACjC,IAAI;EACF,OAAO,MAAM,IAAI,OAAO;CAC1B,SAAS,OAAO;EACd,IAAI,WAAW,SAAS,QAAQ,YAAY,QAAQ,CAAC,UAAU,KAAK,GAAG,MAAM;EAC7E,MAAM,MAAM,UAAU,OAAO,OAAO;EAGpC,MAAM,OAAO,KAAK,MADJ,OAAO,QAAQ,YAAY,OAAO,SAAS,GAAG,KAAK,OAAO,IACxC,MAAM,aAAa,SAAS,SAAS,MAAM,CAAC;EAE5E,IAAI;GACF,MAAM,MAAM,OAAO,MAAM,MAAM;EACjC,QAAQ;GACN,MAAM;EACR;CACF;AAEJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"units.js","names":[],"sources":["../src/units.ts"],"sourcesContent":["// The units of work of a worker loop and of a queue drain: the count of the units in flight, the\n// drain to a deadline with the cooperative abort, the sleeps on the clock, the bound of each unit,\n// and the request tracking of the service for each unit.\n\nimport type { Backoff } from \"./backoff.ts\";\nimport { backoffProblems } from \"./backoff.ts\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { ServiceDescription } from \"./description.ts\";\nimport type { KnobRecord } from \"./knobs.ts\";\nimport { boundedMillisecondsOf } from \"./knobs.ts\";\nimport type { Lifecycle } from \"./lifecycle.ts\";\nimport type { RequestEnd } from \"./requests.ts\";\n\n/**\n * A unit request names the route of each unit of work in the request tracking of the service. Then\n * the service admits, counts, drains and cuts each unit as it does each request (`life.request`).\n * The controller declares the route, thus its idempotency tells if a cut unit can go again.\n */\nexport interface UnitRequest<U> {\n /** This name is the controller that declares the route. */\n readonly controller: string;\n /** This name is the route of each unit, or a function that gives it from the unit. A route can match a route pattern. */\n readonly route: string | ((unit: U) => string);\n /** This function gives the detail of a unit, for the function of a route pattern. */\n readonly detail?: ((unit: U) => unknown) | undefined;\n}\n\n/**\n * A unit end tells how one unit of work ended:\n * - `done`: the work gave its value.\n * - `failed`: the work threw for a cause of its own, or after its bound aborted it.\n * - `refused`: the service did not admit the unit, thus the work did not start.\n * - `cut`: the shutdown stopped the unit. It is not a failure. `retryable` tells if the unit can go again.\n */\nexport type UnitEnd =\n | { readonly kind: \"done\"; readonly value: unknown }\n | { readonly kind: \"failed\"; readonly error: unknown }\n | { readonly kind: \"refused\"; readonly cause: string }\n | { readonly kind: \"cut\"; readonly cause: string; readonly retryable: boolean };\n\n/** This function gives the cause of an abort as text. */\nexport const causeOf = (signal: AbortSignal): string =>\n signal.reason instanceof Error ? signal.reason.message : String(signal.reason ?? \"the unit got an abort\");\n\n/** These are the parts of one unit of work. */\nexport interface UnitRun<U> {\n readonly clock: Clock;\n /** This time is the bound of the unit, in milliseconds, or infinity. At it, the signal of the work aborts. */\n readonly bound: number;\n /** This controller is the abort of the transport for the unit: the cooperative abort and the close. */\n readonly abort: AbortController;\n readonly life: Lifecycle;\n readonly request: UnitRequest<U> | undefined;\n readonly unit: U;\n /** This function starts the work, and gives its value or a promise. */\n readonly work: (signal: AbortSignal) => unknown;\n}\n\n/**\n * This function does one unit of work, and gives its end. With a request, the unit goes through\n * `life.request`, thus the service counts it, drains it and can cut it. A throw after the abort of\n * the transport is a cut, not a failure (S6 A10). A throw after the bound is a failure.\n */\nexport const runUnit = async <U>(run: UnitRun<U>): Promise<UnitEnd> => {\n const { clock, bound, abort, life, request, unit, work } = run;\n const timeout = new AbortController();\n const cancel: Cancel = Number.isFinite(bound)\n ? clock.after(bound, () => timeout.abort(new Error(`the unit did not end in its unit_processing_time of ${bound} ms`)))\n : () => {};\n const call = async (tracker?: AbortSignal): Promise<unknown> =>\n work(AbortSignal.any(tracker === undefined ? [abort.signal, timeout.signal] : [abort.signal, timeout.signal, tracker]));\n // the transport cannot read the idempotency of the route, thus a cut of its own does not go again\n const thrown = (error: unknown): UnitEnd => {\n if (abort.signal.aborted) return { kind: \"cut\", cause: causeOf(abort.signal), retryable: false };\n if (timeout.signal.aborted) return { kind: \"failed\", error: timeout.signal.reason };\n return { kind: \"failed\", error };\n };\n try {\n if (request === undefined) {\n try {\n return { kind: \"done\", value: await call() };\n } catch (error) {\n return thrown(error);\n }\n }\n let collected: Promise<{ readonly items: readonly unknown[]; readonly end: RequestEnd }>;\n try {\n const route = typeof request.route === \"string\" ? request.route : request.route(unit);\n const detail = request.detail?.(unit);\n // the value goes in a box: a work that gives an async iterable is one value here, not a stream\n const stream = life.request(request.controller, route, (signal) => call(signal).then((value) => ({ value })), detail === undefined ? {} : { detail });\n collected = stream.collect();\n } catch (error) {\n // an undeclared route, or a lifecycle with no service\n return { kind: \"failed\", error };\n }\n const { items, end } = await collected;\n if (end.kind === \"done\") return { kind: \"done\", value: (items[0] as { readonly value: unknown } | undefined)?.value };\n if (end.kind === \"failed\") return thrown(end.error);\n if (end.kind === \"refused\") return { kind: \"refused\", cause: end.cause };\n return { kind: \"cut\", cause: end.cause, retryable: end.retryable };\n } finally {\n cancel();\n }\n};\n\n/** A flight set counts the units in flight, from their events, and drains them to a deadline. */\nexport interface Flights {\n /** This count is the number of units in flight. */\n readonly size: number;\n /** This method adds a unit, and gives the function that removes it. A unit after the cooperative abort gets the abort at once. */\n add(unit: AbortController): () => void;\n /** This method aborts each unit in flight and each later unit: the cooperative abort, or the close. */\n abort(reason: unknown): void;\n /** This method removes each unit from the count: the close cuts them. */\n clear(): void;\n /** This method waits until no unit is in flight, or until the deadline. The signal is the cooperative abort. It does not throw. */\n drain(deadline: number, signal: AbortSignal): Promise<void>;\n /** This method gives a promise that ends when the count goes down, or at `release()`. */\n less(): Promise<void>;\n /** This method ends each promise of `less()`. */\n release(): void;\n}\n\n/** This function makes a flight set on a clock. */\nexport const flights = (clock: Clock): Flights => {\n const units = new Set<AbortController>();\n const idle = new Set<() => void>();\n const lower = new Set<() => void>();\n let aborted: { readonly reason: unknown } | null = null;\n const settle = (): void => {\n for (const done of [...lower]) done();\n lower.clear();\n if (units.size === 0) for (const done of [...idle]) done();\n };\n const abort = (reason: unknown): void => {\n aborted ??= { reason };\n for (const unit of [...units]) if (!unit.signal.aborted) unit.abort(aborted.reason);\n };\n return {\n get size() {\n return units.size;\n },\n add(unit) {\n units.add(unit);\n if (aborted !== null && !unit.signal.aborted) unit.abort(aborted.reason);\n return () => {\n if (units.delete(unit)) settle();\n };\n },\n abort,\n clear() {\n units.clear();\n settle();\n },\n drain(deadline, signal) {\n const cooperative = (): void => abort(signal.reason);\n if (signal.aborted) cooperative();\n else signal.addEventListener(\"abort\", cooperative, { once: true });\n // nothing in flight, or a deadline that passed: the drain ends at once, with no timer\n if (units.size === 0 || deadline <= clock.now()) {\n signal.removeEventListener(\"abort\", cooperative);\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n let cancel: Cancel = () => {};\n const done = (): void => {\n idle.delete(done);\n cancel();\n signal.removeEventListener(\"abort\", cooperative);\n resolve();\n };\n idle.add(done);\n cancel = clock.after(Math.max(0, deadline - clock.now()), done);\n });\n },\n less() {\n return new Promise<void>((resolve) => lower.add(resolve));\n },\n release() {\n for (const done of [...lower]) done();\n lower.clear();\n },\n };\n};\n\n/**\n * A sleeper gives the waits of a loop on the clock. `wake()` ends each wait that it can end, and\n * `stop()` ends each wait. A wait without a bound uses no timer.\n */\nexport interface Sleeper {\n /** This count goes up at each `wake()`. A loop reads it before a unit, and a wake during the unit then ends the next sleep at once. */\n readonly wakes: number;\n /** This method waits on the clock. A wake after `since` ends it, and with `since` past, it ends at once. */\n sleep(ms: number, since: number): Promise<void>;\n /** This method waits on the clock. A wake does not end it: it is a backoff after a failure. */\n backoff(ms: number): Promise<void>;\n /** This method ends each sleep, and gives the count of sleeps that it ended. */\n wake(): number;\n /** This method ends each wait, the backoffs too. Each later wait then ends at once. */\n stop(): void;\n}\n\n/** This function makes a sleeper on a clock. */\nexport const sleeper = (clock: Clock): Sleeper => {\n let wakes = 0;\n let stopped = false;\n const sleeps = new Set<() => void>();\n const backoffs = new Set<() => void>();\n const wait = (ms: number, into: Set<() => void>): Promise<void> =>\n stopped\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n let cancel: Cancel = () => {};\n const done = (): void => {\n if (!into.delete(done)) return;\n cancel();\n resolve();\n };\n into.add(done);\n if (Number.isFinite(ms)) cancel = clock.after(ms, done);\n });\n return {\n get wakes() {\n return wakes;\n },\n sleep(ms, since) {\n if (since !== wakes) return Promise.resolve();\n return wait(ms, sleeps);\n },\n backoff(ms) {\n return wait(ms, backoffs);\n },\n wake() {\n wakes += 1;\n const ended = sleeps.size;\n for (const done of [...sleeps]) done();\n return ended;\n },\n stop() {\n stopped = true;\n for (const done of [...sleeps, ...backoffs]) done();\n },\n };\n};\n\n/** A settled wait tells how a work ended in its bound: it ended, it threw, or the bound came first. */\nexport type Settled = { readonly kind: \"done\" } | { readonly kind: \"failed\"; readonly error: unknown } | { readonly kind: \"bound\" };\n\n/** This function waits for a work until a bound on the clock, in milliseconds. */\nexport const settleWithin = (clock: Clock, ms: number, work: Promise<unknown>): Promise<Settled> =>\n new Promise<Settled>((resolve) => {\n const cancel: Cancel = Number.isFinite(ms) ? clock.after(ms, () => resolve({ kind: \"bound\" })) : () => {};\n work.then(\n () => {\n cancel();\n resolve({ kind: \"done\" });\n },\n (error: unknown) => {\n cancel();\n resolve({ kind: \"failed\", error });\n },\n );\n });\n\n/**\n * This function gives the value of a promise, or `stop` when the signal aborts first. Each wait adds\n * its own listener, and removes it when the promise settles. A race against one pending promise\n * keeps each settled value until that promise ends.\n */\nexport const untilAbort = <T, S>(promise: Promise<T>, signal: AbortSignal, stop: S): Promise<T | S> => {\n // A promise that settled before the abort still comes first, as in a race.\n if (signal.aborted) return Promise.race([promise, Promise.resolve(stop)]);\n return new Promise<T | S>((resolve, reject) => {\n const onAbort = (): void => resolve(stop);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n },\n );\n });\n};\n\n/**\n * This function gives the backoff of the knobs of a loop. The first delay is `retry_base`, and each\n * delay is two times longer, up to `retry_cap`. Each delay has a jitter up to the base, as in the Redis client.\n */\nexport const retryOf = (knobs: KnobRecord, owner: string): Backoff => {\n const base = boundedMillisecondsOf(knobs, \"retry_base\", owner);\n const cap = boundedMillisecondsOf(knobs, \"retry_cap\", owner);\n const backoff: Backoff = { base, factor: 2, cap, jitter: { kind: \"add\", amount: base } };\n const problems = backoffProblems(backoff);\n if (problems.length > 0) throw new Error(`${owner}: the retry_base and retry_cap give no backoff: ${problems.join(\", \")}`);\n return backoff;\n};\n\n/**\n * This function gives the problems of a loop in a declaration: each phase that the loop needs and\n * that the declaration does not give. A loop closes in `close transports`, and it ends its units in\n * `drain`. `lint()` compares the bounds with the caps of the phases (`BOUND_RULES`, S6 A10).\n */\nexport const boundProblems = (owner: string, description: ServiceDescription): string[] => {\n const has = (name: string): boolean => description.shutdown.phases.some((each) => each.name === name);\n return [\n ...(has(\"close transports\") ? [] : [`${owner} needs the phase \"close transports\" to close`]),\n ...(has(\"drain\") ? [] : [`${owner} needs the phase \"drain\" to end its units`]),\n ];\n};\n"],"mappings":";;;;AAyCA,MAAa,WAAW,WACtB,OAAO,kBAAkB,QAAQ,OAAO,OAAO,UAAU,OAAO,OAAO,UAAU,uBAAuB;;;;;;AAqB1G,MAAa,UAAU,OAAU,QAAsC;CACrE,MAAM,EAAE,OAAO,OAAO,OAAO,MAAM,SAAS,M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,OAAe,gBAA8C;CACzF,MAAM,OAAO,SAA0B,YAAY,SAAS,OAAO,MAAM,SAAS,KAAK,SAAS,IAAI;CACpG,OAAO,CACL,GAAI,IAAI,kBAAkB,IAAI,CAAC,IAAI,CAAC,GAAG,MAAM,6CAA6C,GAC1F,GAAI,IAAI,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,MAAM,0CAA0C,CAC9E;AACF"}
1
+ {"version":3,"file":"units.js","names":[],"sources":["../src/units.ts"],"sourcesContent":["// The units of work of a worker loop and of a queue drain: the count of the units in flight, the\n// drain to a deadline with the cooperative abort, the sleeps on the clock, the bound of each unit,\n// and the request tracking of the service for each unit.\n\nimport type { Backoff } from \"./backoff.ts\";\nimport { backoffProblems } from \"./backoff.ts\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { ServiceDescription } from \"./description.ts\";\nimport type { KnobRecord } from \"./knobs.ts\";\nimport { boundedMillisecondsOf } from \"./knobs.ts\";\nimport type { Lifecycle } from \"./lifecycle.ts\";\nimport type { RequestEnd } from \"./requests.ts\";\n\n/**\n * A unit request names the route of each unit of work in the request tracking of the service. Then\n * the service admits, counts, drains and cuts each unit as it does each request (`life.request`).\n * The controller declares the route, thus its idempotency tells if a cut unit can go again.\n */\nexport interface UnitRequest<U> {\n /** This name is the controller that declares the route. */\n readonly controller: string;\n /** This name is the route of each unit, or a function that gives it from the unit. A route can match a route pattern. */\n readonly route: string | ((unit: U) => string);\n /** This function gives the detail of a unit, for the function of a route pattern. */\n readonly detail?: ((unit: U) => unknown) | undefined;\n}\n\n/**\n * A unit end tells how one unit of work ended:\n * - `done`: the work gave its value.\n * - `failed`: the work threw for a cause of its own, or after its bound aborted it.\n * - `refused`: the service did not admit the unit, thus the work did not start.\n * - `cut`: the shutdown stopped the unit. It is not a failure. `retryable` tells if the unit can go again.\n */\nexport type UnitEnd =\n | { readonly kind: \"done\"; readonly value: unknown }\n | { readonly kind: \"failed\"; readonly error: unknown }\n | { readonly kind: \"refused\"; readonly cause: string }\n | { readonly kind: \"cut\"; readonly cause: string; readonly retryable: boolean };\n\n/** This function gives the cause of an abort as text. */\nexport const causeOf = (signal: AbortSignal): string =>\n signal.reason instanceof Error ? signal.reason.message : String(signal.reason ?? \"the unit got an abort\");\n\n/** These are the parts of one unit of work. */\nexport interface UnitRun<U> {\n readonly clock: Clock;\n /** This time is the bound of the unit, in milliseconds, or infinity. At it, the signal of the work aborts. */\n readonly bound: number;\n /** This controller is the abort of the transport for the unit: the cooperative abort and the close. */\n readonly abort: AbortController;\n readonly life: Lifecycle;\n readonly request: UnitRequest<U> | undefined;\n readonly unit: U;\n /** This function starts the work, and gives its value or a promise. */\n readonly work: (signal: AbortSignal) => unknown;\n}\n\n/**\n * This function does one unit of work, and gives its end. With a request, the unit goes through\n * `life.request`, thus the service counts it, drains it and can cut it. A throw after the abort of\n * the transport is a cut, not a failure (S6 A10). A throw after the bound is a failure.\n */\nexport const runUnit = async <U>(run: UnitRun<U>): Promise<UnitEnd> => {\n const { clock, bound, abort, life, request, unit, work } = run;\n const timeout = new AbortController();\n // the unit awaits its bound, thus the timer keeps the process alive (SYS-126)\n const cancel: Cancel = Number.isFinite(bound)\n ? clock.after(bound, () => timeout.abort(new Error(`the unit did not end in its unit_processing_time of ${bound} ms`)))\n : () => {};\n const call = async (tracker?: AbortSignal): Promise<unknown> =>\n work(AbortSignal.any(tracker === undefined ? [abort.signal, timeout.signal] : [abort.signal, timeout.signal, tracker]));\n // the transport cannot read the idempotency of the route, thus a cut of its own does not go again\n const thrown = (error: unknown): UnitEnd => {\n if (abort.signal.aborted) return { kind: \"cut\", cause: causeOf(abort.signal), retryable: false };\n if (timeout.signal.aborted) return { kind: \"failed\", error: timeout.signal.reason };\n return { kind: \"failed\", error };\n };\n try {\n if (request === undefined) {\n try {\n return { kind: \"done\", value: await call() };\n } catch (error) {\n return thrown(error);\n }\n }\n let collected: Promise<{ readonly items: readonly unknown[]; readonly end: RequestEnd }>;\n try {\n const route = typeof request.route === \"string\" ? request.route : request.route(unit);\n const detail = request.detail?.(unit);\n // the value goes in a box: a work that gives an async iterable is one value here, not a stream\n const stream = life.request(request.controller, route, (signal) => call(signal).then((value) => ({ value })), detail === undefined ? {} : { detail });\n collected = stream.collect();\n } catch (error) {\n // an undeclared route, or a lifecycle with no service\n return { kind: \"failed\", error };\n }\n const { items, end } = await collected;\n if (end.kind === \"done\") return { kind: \"done\", value: (items[0] as { readonly value: unknown } | undefined)?.value };\n if (end.kind === \"failed\") return thrown(end.error);\n if (end.kind === \"refused\") return { kind: \"refused\", cause: end.cause };\n return { kind: \"cut\", cause: end.cause, retryable: end.retryable };\n } finally {\n cancel();\n }\n};\n\n/** A flight set counts the units in flight, from their events, and drains them to a deadline. */\nexport interface Flights {\n /** This count is the number of units in flight. */\n readonly size: number;\n /** This method adds a unit, and gives the function that removes it. A unit after the cooperative abort gets the abort at once. */\n add(unit: AbortController): () => void;\n /** This method aborts each unit in flight and each later unit: the cooperative abort, or the close. */\n abort(reason: unknown): void;\n /** This method removes each unit from the count: the close cuts them. */\n clear(): void;\n /** This method waits until no unit is in flight, or until the deadline. The signal is the cooperative abort. It does not throw. */\n drain(deadline: number, signal: AbortSignal): Promise<void>;\n /** This method gives a promise that ends when the count goes down, or at `release()`. */\n less(): Promise<void>;\n /** This method ends each promise of `less()`. */\n release(): void;\n}\n\n/** This function makes a flight set on a clock. */\nexport const flights = (clock: Clock): Flights => {\n const units = new Set<AbortController>();\n const idle = new Set<() => void>();\n const lower = new Set<() => void>();\n let aborted: { readonly reason: unknown } | null = null;\n const settle = (): void => {\n for (const done of [...lower]) done();\n lower.clear();\n if (units.size === 0) for (const done of [...idle]) done();\n };\n const abort = (reason: unknown): void => {\n aborted ??= { reason };\n for (const unit of [...units]) if (!unit.signal.aborted) unit.abort(aborted.reason);\n };\n return {\n get size() {\n return units.size;\n },\n add(unit) {\n units.add(unit);\n if (aborted !== null && !unit.signal.aborted) unit.abort(aborted.reason);\n return () => {\n if (units.delete(unit)) settle();\n };\n },\n abort,\n clear() {\n units.clear();\n settle();\n },\n drain(deadline, signal) {\n const cooperative = (): void => abort(signal.reason);\n if (signal.aborted) cooperative();\n else signal.addEventListener(\"abort\", cooperative, { once: true });\n // nothing in flight, or a deadline that passed: the drain ends at once, with no timer\n if (units.size === 0 || deadline <= clock.now()) {\n signal.removeEventListener(\"abort\", cooperative);\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n let cancel: Cancel = () => {};\n const done = (): void => {\n idle.delete(done);\n cancel();\n signal.removeEventListener(\"abort\", cooperative);\n resolve();\n };\n idle.add(done);\n // the drain awaits its deadline, thus the timer keeps the process alive (SYS-126)\n cancel = clock.after(Math.max(0, deadline - clock.now()), done);\n });\n },\n less() {\n return new Promise<void>((resolve) => lower.add(resolve));\n },\n release() {\n for (const done of [...lower]) done();\n lower.clear();\n },\n };\n};\n\n/**\n * A sleeper gives the waits of a loop on the clock. `wake()` ends each wait that it can end, and\n * `stop()` ends each wait. A wait without a bound uses no timer.\n */\nexport interface Sleeper {\n /** This count goes up at each `wake()`. A loop reads it before a unit, and a wake during the unit then ends the next sleep at once. */\n readonly wakes: number;\n /** This method waits on the clock. A wake after `since` ends it, and with `since` past, it ends at once. */\n sleep(ms: number, since: number): Promise<void>;\n /** This method waits on the clock. A wake does not end it: it is a backoff after a failure. */\n backoff(ms: number): Promise<void>;\n /** This method ends each sleep, and gives the count of sleeps that it ended. */\n wake(): number;\n /** This method ends each wait, the backoffs too. Each later wait then ends at once. */\n stop(): void;\n}\n\n/** This function makes a sleeper on a clock. */\nexport const sleeper = (clock: Clock): Sleeper => {\n let wakes = 0;\n let stopped = false;\n const sleeps = new Set<() => void>();\n const backoffs = new Set<() => void>();\n const wait = (ms: number, into: Set<() => void>): Promise<void> =>\n stopped\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n let cancel: Cancel = () => {};\n const done = (): void => {\n if (!into.delete(done)) return;\n cancel();\n resolve();\n };\n into.add(done);\n // a sleep or a backoff of a loop is work: an exit in a backoff loses the next try of an item.\n // Thus the timer keeps the process alive, and the lifecycle stops the loop (SYS-126)\n if (Number.isFinite(ms)) cancel = clock.after(ms, done);\n });\n return {\n get wakes() {\n return wakes;\n },\n sleep(ms, since) {\n if (since !== wakes) return Promise.resolve();\n return wait(ms, sleeps);\n },\n backoff(ms) {\n return wait(ms, backoffs);\n },\n wake() {\n wakes += 1;\n const ended = sleeps.size;\n for (const done of [...sleeps]) done();\n return ended;\n },\n stop() {\n stopped = true;\n for (const done of [...sleeps, ...backoffs]) done();\n },\n };\n};\n\n/** A settled wait tells how a work ended in its bound: it ended, it threw, or the bound came first. */\nexport type Settled = { readonly kind: \"done\" } | { readonly kind: \"failed\"; readonly error: unknown } | { readonly kind: \"bound\" };\n\n/** This function waits for a work until a bound on the clock, in milliseconds. */\nexport const settleWithin = (clock: Clock, ms: number, work: Promise<unknown>): Promise<Settled> =>\n new Promise<Settled>((resolve) => {\n // the caller awaits the work in its bound, thus the timer keeps the process alive (SYS-126)\n const cancel: Cancel = Number.isFinite(ms) ? clock.after(ms, () => resolve({ kind: \"bound\" })) : () => {};\n work.then(\n () => {\n cancel();\n resolve({ kind: \"done\" });\n },\n (error: unknown) => {\n cancel();\n resolve({ kind: \"failed\", error });\n },\n );\n });\n\n/**\n * This function gives the value of a promise, or `stop` when the signal aborts first. Each wait adds\n * its own listener, and removes it when the promise settles. A race against one pending promise\n * keeps each settled value until that promise ends.\n */\nexport const untilAbort = <T, S>(promise: Promise<T>, signal: AbortSignal, stop: S): Promise<T | S> => {\n // A promise that settled before the abort still comes first, as in a race.\n if (signal.aborted) return Promise.race([promise, Promise.resolve(stop)]);\n return new Promise<T | S>((resolve, reject) => {\n const onAbort = (): void => resolve(stop);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n },\n );\n });\n};\n\n/**\n * This function gives the backoff of the knobs of a loop. The first delay is `retry_base`, and each\n * delay is two times longer, up to `retry_cap`. Each delay has a jitter up to the base, as in the Redis client.\n */\nexport const retryOf = (knobs: KnobRecord, owner: string): Backoff => {\n const base = boundedMillisecondsOf(knobs, \"retry_base\", owner);\n const cap = boundedMillisecondsOf(knobs, \"retry_cap\", owner);\n const backoff: Backoff = { base, factor: 2, cap, jitter: { kind: \"add\", amount: base } };\n const problems = backoffProblems(backoff);\n if (problems.length > 0) throw new Error(`${owner}: the retry_base and retry_cap give no backoff: ${problems.join(\", \")}`);\n return backoff;\n};\n\n/**\n * This function gives the problems of a loop in a declaration: each phase that the loop needs and\n * that the declaration does not give. A loop closes in `close transports`, and it ends its units in\n * `drain`. `lint()` compares the bounds with the caps of the phases (`BOUND_RULES`, S6 A10).\n */\nexport const boundProblems = (owner: string, description: ServiceDescription): string[] => {\n const has = (name: string): boolean => description.shutdown.phases.some((each) => each.name === name);\n return [\n ...(has(\"close transports\") ? [] : [`${owner} needs the phase \"close transports\" to close`]),\n ...(has(\"drain\") ? [] : [`${owner} needs the phase \"drain\" to end its units`]),\n ];\n};\n"],"mappings":";;;;AAyCA,MAAa,WAAW,WACtB,OAAO,kBAAkB,QAAQ,OAAO,OAAO,UAAU,OAAO,OAAO,UAAU,uBAAuB;;;;;;AAqB1G,MAAa,UAAU,OAAU,QAAsC;CACrE,MAAM,EAAE,OAAO,OAAO,OAAO,MAAM,SAAS,MAAM,SAAS;CAC3D,MAAM,UAAU,IAAI,gBAAgB;CAEpC,MAAM,SAAiB,OAAO,SAAS,KAAK,IACxC,MAAM,MAAM,aAAa,QAAQ,sBAAM,IAAI,MAAM,uDAAuD,MAAM,IAAI,CAAC,CAAC,UAC9G,CAAC;CACX,MAAM,OAAO,OAAO,YAClB,KAAK,YAAY,IAAI,YAAY,KAAA,IAAY,CAAC,MAAM,QAAQ,QAAQ,MAAM,IAAI;EAAC,MAAM;EAAQ,QAAQ;EAAQ;CAAO,CAAC,CAAC;CAExH,MAAM,UA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dog on a clock. */
33
+ /**
34
+ * This function starts a watchdog on a clock. The tick only watches the event loop. Thus a service
35
+ * gives the watchdog `unrefClock(clock)`, and the work of the service keeps the process alive. A
36
+ * watchdog on a clock that keeps the process alive keeps it alive until `stop()`.
37
+ */
34
38
  export declare const watchdog: (clock: Clock, spec: WatchdogSpec, trace?: Trace) => Watchdog;