@mark1russell7/service 0.8.4 → 0.8.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/{backoff-B-jGWVDm.d.ts → backoff-QTRGfkEK.d.ts} +1 -4
- package/build/backoff.d.ts +1 -1
- package/build/backoff.js +1 -2
- package/build/{builder-DQj3NNNc.d.ts → builder-zO48Vgoj.d.ts} +4 -11
- package/build/{call-context-gR8FhbF_.d.ts → call-context-DDhcVvn5.d.ts} +1 -4
- package/build/channel.d.ts +1 -4
- package/build/channel.js +1 -2
- package/build/{core-Dt0HEVMq.d.ts → core-BSzt4RI2.d.ts} +5 -10
- package/build/{dial-CSQOl-yj.d.ts → dial-ChwIcvd4.d.ts} +2 -5
- package/build/grpc.d.ts +5 -16
- package/build/grpc.js +7 -12
- package/build/grpc.js.map +1 -1
- package/build/heartbeat.d.ts +1 -4
- package/build/heartbeat.js +1 -2
- package/build/host.d.ts +10 -25
- package/build/host.js +21 -33
- package/build/host.js.map +1 -1
- package/build/http-client.d.ts +5 -18
- package/build/http-client.js +7 -13
- package/build/http-client.js.map +1 -1
- package/build/http.d.ts +4 -11
- package/build/http.js +6 -10
- package/build/http.js.map +1 -1
- package/build/index.d.ts +11 -24
- package/build/index.js +26 -43
- package/build/index.js.map +1 -1
- package/build/{knobs-D2ClI68I.js → knobs-BJcz6m01.js} +3 -5
- package/build/{knobs-D2ClI68I.js.map → knobs-BJcz6m01.js.map} +1 -1
- package/build/{lifecycle-Br0jAjTk.d.ts → lifecycle-D0J-zwZF.d.ts} +2 -15
- package/build/{limiter-BTgM4aXZ.js → limiter-BwGxEWpP.js} +4 -6
- package/build/{limiter-BTgM4aXZ.js.map → limiter-BwGxEWpP.js.map} +1 -1
- package/build/{limiter-D1aluA0V.d.ts → limiter-Djw39d_S.d.ts} +3 -6
- package/build/limiter.d.ts +3 -3
- package/build/limiter.js +2 -2
- package/build/{logger-BN2BfPgU.d.ts → logger-B6drv9w0.d.ts} +2 -17
- package/build/{machine-p4lENJ86.js → machine-mIW1qgEE.js} +7 -11
- package/build/{machine-p4lENJ86.js.map → machine-mIW1qgEE.js.map} +1 -1
- package/build/mongodb.d.ts +4 -15
- package/build/mongodb.js +6 -11
- package/build/mongodb.js.map +1 -1
- package/build/{operation-DL5RxFds.js → operation-DF73RZOI.js} +2 -3
- package/build/{operation-DL5RxFds.js.map → operation-DF73RZOI.js.map} +1 -1
- package/build/otel.d.ts +3 -6
- package/build/otel.js +1 -2
- package/build/pg.d.ts +3 -14
- package/build/pg.js +6 -11
- package/build/pg.js.map +1 -1
- package/build/{policy-G-Y3Meku.js → policy-B23MY52l.js} +2 -3
- package/build/{policy-G-Y3Meku.js.map → policy-B23MY52l.js.map} +1 -1
- package/build/{policy-CwYR95Sz.d.ts → policy-CBcK2XGg.d.ts} +1 -4
- package/build/{ports-CSr7qWrA.d.ts → ports-DZoipkSD.d.ts} +2 -5
- package/build/{process-DG_im2zc.js → process-Oe0Abbsm.js} +2 -3
- package/build/{process-DG_im2zc.js.map → process-Oe0Abbsm.js.map} +1 -1
- package/build/{queue-fIkOXKVG.d.ts → queue-DXdw1vLO.d.ts} +3 -8
- package/build/rabbitmq.d.ts +5 -16
- package/build/rabbitmq.js +6 -11
- package/build/rabbitmq.js.map +1 -1
- package/build/redis.d.ts +4 -17
- package/build/redis.js +10 -16
- package/build/redis.js.map +1 -1
- package/build/{requests-BIq9Tr4P.js → requests-DD2ALv0_.js} +6 -9
- package/build/{requests-BIq9Tr4P.js.map → requests-DD2ALv0_.js.map} +1 -1
- package/build/{retrier-Nt6r4r6R.js → retrier-BObZq10-.js} +3 -4
- package/build/{retrier-Nt6r4r6R.js.map → retrier-BObZq10-.js.map} +1 -1
- package/build/{rules-BBRopO1e.d.ts → rules-HyFCBStQ.d.ts} +1 -6
- package/build/rules.d.ts +1 -1
- package/build/rules.js +1 -2
- package/build/{store-1CsNoJ8O.d.ts → store-DFwFKrsB.d.ts} +2 -5
- package/build/testing.d.ts +5 -16
- package/build/testing.js +9 -15
- package/build/testing.js.map +1 -1
- package/build/{timing-DGRi3XCI.js → timing-DZl36uXs.js} +2 -3
- package/build/{timing-DGRi3XCI.js.map → timing-DZl36uXs.js.map} +1 -1
- package/build/websocket.d.ts +4 -15
- package/build/websocket.js +7 -12
- package/build/websocket.js.map +1 -1
- package/package.json +11 -10
package/build/redis.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redis.js","names":["knob","t"],"sources":["../src/redis/connection.ts","../src/redis/meets.ts","../src/redis/operations.ts","../src/redis/client.ts","../src/redis/limiter.ts","../src/redis/machine.ts"],"sourcesContent":["import type { ClientSocket, Factory } from \"../client/core.ts\";\n\n/**\n * A Redis connection is the part of an ioredis client that the wrapper uses. An ioredis 6 client has\n * each part. A fake for tests has them too. Thus the package depends on no type of ioredis.\n */\nexport interface RedisConnection {\n /** This text is the state of the client: wait, connecting, connect, ready, close, reconnecting or end. */\n readonly status: string;\n /** This socket is the socket of the current connection, when there is one. */\n readonly stream?: RedisSocket | undefined;\n connect(): Promise<void>;\n /** This method sends one command, and gives the reply. */\n call(command: string, ...args: Array<string | number>): Promise<unknown>;\n quit(): Promise<unknown>;\n /** This method closes the connection at once. With `true`, the client then connects again. */\n disconnect(reconnect?: boolean): void;\n on(event: string, listener: (...args: unknown[]) => void): unknown;\n off(event: string, listener: (...args: unknown[]) => void): unknown;\n}\n\n/** A Redis socket is the socket of a client in the core: the join of the prober and the bounded close read it. */\nexport type RedisSocket = ClientSocket;\n\n/**\n * These are the options that the wrapper gives ioredis. Each one comes from the declaration. The\n * wrapper sets each option that has an effect on a timer or on a send again, thus no default of\n * ioredis decides one.\n */\nexport interface RedisConnectionOptions {\n readonly host: string;\n readonly port: number;\n readonly db?: number | undefined;\n readonly username?: string | undefined;\n readonly password?: string | undefined;\n /** The wrapper connects in its own step of the startup. */\n readonly lazyConnect: true;\n readonly connectTimeout: number;\n readonly commandTimeout: number;\n /** This time destroys a socket that gives no data while a command waits. Undefined is no bound. */\n readonly socketTimeout: number | undefined;\n /** This time is the idle time of TCP keepalive. False is no keepalive. */\n readonly keepAlive: number | false;\n /** A command while the client is not ready fails at once: it did not reach the server. */\n readonly enableOfflineQueue: false;\n /** The client does not send again a command that can have reached the server. */\n readonly autoResendUnfulfilledCommands: false;\n readonly maxRetriesPerRequest: null;\n readonly enableReadyCheck: true;\n readonly connectionName: string;\n /** This function gives the delay before the next try to connect, or null to stop. */\n readonly retryStrategy: (times: number) => number | null;\n}\n\n/** A connection factory makes the connection of the client from its options. */\nexport type ConnectionFactory = Factory<RedisConnectionOptions, RedisConnection>;\n\n/**\n * This factory makes an ioredis client. It loads ioredis only when a client connects, thus a\n * service that does not use Redis does not need ioredis.\n */\nexport const ioredis: ConnectionFactory = async (options) => {\n const loaded = (await import(\"ioredis\")) as unknown as {\n readonly default: new (options: RedisConnectionOptions) => RedisConnection;\n };\n return new loaded.default(options);\n};\n","import type { Extent } from \"@mark1russell7/quantity\";\nimport type { Detector, Meeting, Situation } from \"../client/meets.ts\";\nimport { WHAT, immediate, keepaliveAnswered, keepaliveReset, keepaliveSilent, kernelGiveUp } from \"../client/meets.ts\";\nimport type { RedisKnobs } from \"./client.ts\";\n\n// the shapes and the queries moved to the core of the clients: this entry keeps them for the users of 0.5\nexport type { Detector, Meeting, Situation } from \"../client/meets.ts\";\nexport { firstDetector, unwatched } from \"../client/meets.ts\";\n\n/**\n * This function gives the manifestations that a Redis client can meet, and the detectors of each, from\n * its knobs. A reset or a FIN arrives on the next segment. A black hole and a host that is gone give\n * no answer at all. A frozen process and a stalled server keep a kernel that acknowledges each\n * segment. Thus TCP keepalive does not fire on them, and only the client's own timers find them.\n */\nexport const meetings = (name: string, knobs: RedisKnobs, heartbeat: Extent): Meeting[] => {\n const watchdog = (situation: Situation): Detector => ({\n by: \"heartbeat_detection_time\",\n within: heartbeat,\n situation,\n effect: `the watchdog of ${name} closes the connection, and the client connects again`,\n });\n const writeoff: Detector = {\n by: \"driver_writeoff_time\",\n within: knobs.driver_writeoff_time,\n situation: \"in flight\",\n effect: \"ioredis destroys the socket of a command without data, and the client connects again\",\n };\n const command: Detector = {\n by: \"request_timeout\",\n within: knobs.request_timeout,\n situation: \"in flight\",\n effect: \"the command fails as indeterminate, and the state of the connection does not change\",\n };\n const giveUp = kernelGiveUp(knobs.retrans_giveup_time);\n const silent = (manifestation: \"blackhole\" | \"freeze-host\"): Meeting => ({\n manifestation,\n what: WHAT[manifestation],\n detectors: [command, writeoff, watchdog(\"in flight\"), giveUp, watchdog(\"idle\"), keepaliveSilent(knobs.keepalive_idle)],\n });\n const acknowledged = (manifestation: string, what: string): Meeting => ({\n manifestation,\n what,\n detectors: [command, writeoff, watchdog(\"in flight\"), watchdog(\"idle\"), keepaliveAnswered()],\n });\n return [\n {\n manifestation: \"rst\",\n what: WHAT.rst,\n detectors: [\n immediate(\"in flight\", \"the command fails, and the client connects again, and each attempt is refused\"),\n watchdog(\"idle\"),\n keepaliveReset(knobs.keepalive_idle),\n ],\n },\n {\n manifestation: \"fin\",\n what: WHAT.fin,\n detectors: [immediate(\"in flight\", \"the close arrives, and the command fails\"), immediate(\"idle\", \"the close arrives\")],\n },\n silent(\"blackhole\"),\n silent(\"freeze-host\"),\n acknowledged(\"freeze-process\", WHAT[\"freeze-process\"]),\n acknowledged(\"app-stall\", \"the server stops its replies for a time, for example a long command, and its kernel stays up\"),\n ];\n};\n","import type { Operation } from \"../operation.ts\";\n\n/**\n * These are the Redis commands whose idempotency the client declares when the declaration does not\n * say. A second issue of an idempotent command has the same effect. Thus the client can send it\n * again after a failure that left its result unknown. The client does not send again a command\n * that is not in this table: a declaration that uses it says its idempotency itself.\n */\nconst SAME_EFFECT = [\n // reads\n \"PING\",\n \"ECHO\",\n \"GET\",\n \"MGET\",\n \"STRLEN\",\n \"GETRANGE\",\n \"EXISTS\",\n \"TYPE\",\n \"TTL\",\n \"PTTL\",\n \"EXPIRETIME\",\n \"HGET\",\n \"HMGET\",\n \"HGETALL\",\n \"HKEYS\",\n \"HVALS\",\n \"HLEN\",\n \"HEXISTS\",\n \"SMEMBERS\",\n \"SISMEMBER\",\n \"SMISMEMBER\",\n \"SCARD\",\n \"ZRANGE\",\n \"ZRANGEBYSCORE\",\n \"ZSCORE\",\n \"ZMSCORE\",\n \"ZRANK\",\n \"ZCARD\",\n \"ZCOUNT\",\n \"LRANGE\",\n \"LINDEX\",\n \"LLEN\",\n \"XRANGE\",\n \"XREVRANGE\",\n \"XLEN\",\n \"SCAN\",\n \"SSCAN\",\n \"HSCAN\",\n \"ZSCAN\",\n \"DBSIZE\",\n \"INFO\",\n \"CLIENT ID\",\n // writes that put a state, not a change of a state: a second issue puts the same state\n \"SET\",\n \"MSET\",\n \"SETEX\",\n \"PSETEX\",\n \"DEL\",\n \"UNLINK\",\n \"EXPIRE\",\n \"PEXPIRE\",\n \"EXPIREAT\",\n \"PEXPIREAT\",\n \"PERSIST\",\n \"HSET\",\n \"HDEL\",\n \"SADD\",\n \"SREM\",\n \"ZADD\",\n \"ZREM\",\n];\n\n/**\n * These commands change a state relative to the state before them. A second issue changes it again:\n * an INCR that the client sends again after a timeout counts two times.\n */\nconst CHANGE = [\n \"INCR\",\n \"INCRBY\",\n \"INCRBYFLOAT\",\n \"DECR\",\n \"DECRBY\",\n \"HINCRBY\",\n \"HINCRBYFLOAT\",\n \"ZINCRBY\",\n \"APPEND\",\n \"LPUSH\",\n \"RPUSH\",\n \"LPOP\",\n \"RPOP\",\n \"BLPOP\",\n \"BRPOP\",\n \"LMOVE\",\n \"BLMOVE\",\n \"SPOP\",\n \"XADD\",\n \"XACK\",\n \"PUBLISH\",\n \"EVAL\",\n \"EVALSHA\",\n \"FCALL\",\n \"MULTI\",\n \"EXEC\",\n \"GETDEL\",\n \"GETSET\",\n \"SETNX\",\n];\n\n/** These are the operations of the client: the idempotency of each command that the table names. */\nexport const REDIS_OPERATIONS: Readonly<Record<string, Operation>> = Object.fromEntries([\n ...SAME_EFFECT.map((command) => [command, { idempotent: true }] as const),\n ...CHANGE.map((command) => [command, { idempotent: false }] as const),\n]);\n\n/** This function gives the name of a command as the table writes it: upper case, and CLIENT ID with its subcommand. */\nexport const commandName = (command: string, args: readonly unknown[]): string => {\n const name = command.toUpperCase();\n if ((name === \"CLIENT\" || name === \"CONFIG\" || name === \"DEBUG\") && typeof args[0] === \"string\")\n return `${name} ${args[0].toUpperCase()}`;\n return name;\n};\n","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","import type { Clock } from \"../clock.ts\";\nimport type { Decision } from \"../limiter/policy.ts\";\nimport { overCapacity, unitsOf } from \"../limiter/policy.ts\";\nimport type { LimiterStore } from \"../limiter/store.ts\";\nimport type { RedisClient } from \"./client.ts\";\n\n/**\n * This script decides one take in one atomic step of Redis. It does the arithmetic of `decide`, and\n * it reads `TIME` of the server, the one clock of all replicas. A test can give the time in its place.\n * - KEYS[1] is the state of the key. KEYS[2] is the index of the limiter, a sorted set of its keys\n * by the time at which each key is free.\n * - ARGV is the type of the rule, its two numbers, the cap of keys and the key. Then it has the\n * time or \"\", and the units of the take. The store refuses a take over the capacity before the script, thus the units\n * are at most the capacity.\n * - The state of a bucket is its full time. The state of a window is the time of each take in it.\n * - The state expires at its free time (PX), and the index lets the cap count only busy keys.\n * - The reply is `{1, remaining}`, or `{0, retryAfter, cause}` with the time as text. Redis gives\n * each Lua number as a whole number, thus the fraction of a millisecond goes as text.\n */\nexport const LIMITER_SCRIPT = `\nlocal kind = ARGV[1]\nlocal a = tonumber(ARGV[2])\nlocal b = tonumber(ARGV[3])\nlocal cap = tonumber(ARGV[4])\nlocal member = ARGV[5]\nlocal units = tonumber(ARGV[7])\nlocal now\nif ARGV[6] == '' then\n local t = redis.call('TIME')\n now = tonumber(t[1]) * 1000 + tonumber(t[2]) / 1000\nelse\n now = tonumber(ARGV[6])\nend\nlocal TOL = 1e-6\nlocal function num(x) return string.format('%.6f', x) end\nlocal raw = redis.call('GET', KEYS[1])\nlocal full = nil\nlocal stamps = nil\nif raw then\n if kind == 'token-bucket' then\n full = tonumber(raw)\n else\n stamps = {}\n for x in string.gmatch(raw, '[^,]+') do stamps[#stamps + 1] = tonumber(x) end\n end\nend\nlocal function freeAt()\n if kind == 'token-bucket' then return full end\n if #stamps == 0 then return -math.huge end\n return stamps[#stamps] + b\nend\nif raw and freeAt() <= now then\n redis.call('DEL', KEYS[1])\n redis.call('ZREM', KEYS[2], member)\n raw = nil\n full = nil\n stamps = nil\nend\nif not raw then\n if redis.call('ZCARD', KEYS[2]) >= cap then\n redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', num(now))\n if redis.call('ZCARD', KEYS[2]) >= cap then\n local first = redis.call('ZRANGE', KEYS[2], 0, 0, 'WITHSCORES')\n return {0, num(tonumber(first[2]) - now), 'cap'}\n end\n end\nend\nlocal remaining\nlocal state\nif kind == 'token-bucket' then\n local span = a * b\n local base = now\n if full and full > now then base = full end\n local nxt = base + a * units\n if nxt - now > span + TOL then\n return {0, num(nxt - span - now), 'limit'}\n end\n remaining = math.floor((span - (nxt - now)) / a + TOL)\n if remaining < 0 then remaining = 0 end\n full = nxt\n state = num(full)\nelse\n local live = {}\n for _, stamp in ipairs(stamps or {}) do\n if stamp + b > now + TOL then live[#live + 1] = stamp end\n end\n if #live + units > a then\n return {0, num(live[#live + units - a] + b - now), 'limit'}\n end\n for _ = 1, units do live[#live + 1] = now end\n remaining = a - #live\n stamps = live\n local parts = {}\n for i, stamp in ipairs(live) do parts[i] = num(stamp) end\n state = table.concat(parts, ',')\nend\nlocal free = freeAt()\nlocal ttl = math.ceil(free - now)\nif ttl < 1 then ttl = 1 end\nredis.call('SET', KEYS[1], state, 'PX', ttl)\nredis.call('ZADD', KEYS[2], num(free), member)\nif redis.call('PTTL', KEYS[2]) < ttl then redis.call('PEXPIRE', KEYS[2], ttl) end\nreturn {1, remaining}\n`;\n\n/** These options make a store of a limiter in Redis. */\nexport interface RedisLimiterOptions {\n /** This text starts the name of each key of the store in Redis, for example `limit:`. It has no braces. */\n readonly prefix: string;\n /**\n * This clock replaces `TIME` of the server, for a test that compares the store with `decide`. Without\n * it, the script reads `TIME`, thus each replica gets the one clock of the store.\n */\n readonly clock?: Clock | undefined;\n}\n\n/** A Redis client part is the part of a Redis client that the store uses: `send`. */\nexport type RedisSender = Pick<RedisClient, \"send\">;\n\n/**\n * This function makes a store that the replicas share, in Redis 7. Each take is one `EVAL` of\n * `LIMITER_SCRIPT`, with all of its units. The client does not send it again, because a second take\n * counts two times.\n * - The names of the keys have the limiter in braces, a hash tag. Thus the state and the index of a\n * limiter are in one slot of a Redis Cluster.\n * - Each state expires at the time that the key is free, thus the eviction is exact, as in the memory\n * store. The index of the limiter bounds the count of busy keys to `maxKeys`.\n * - A reply of an error, an outcome that is not certain, or a reply of another shape rejects the\n * take of the store. `keyedLimiter` then applies the `onStoreFailure` of the spec.\n * - `TIME` is the wall clock of the Redis host, not a monotonic clock. Thus a step of that clock\n * moves the counts of each key. The replicas still share one clock.\n */\nexport const redisLimiterStore = (client: RedisSender, options: RedisLimiterOptions): LimiterStore => {\n if (/[{}]/.test(options.prefix)) throw new Error(`the prefix ${options.prefix} of a limiter store has a brace: the store puts the hash tag in it`);\n return {\n kind: \"shared\",\n async take({ limiter, key, rule, maxKeys, units }): Promise<Decision> {\n const n = unitsOf(units);\n // a take over the capacity is refused at each time, thus it does not go to Redis\n const over = overCapacity(rule, n);\n if (over !== undefined) return over;\n const base = `${options.prefix}{${limiter}}`;\n const numbers = rule.type === \"token-bucket\" ? [rule.interval, rule.burst] : [rule.limit, rule.window];\n const now = options.clock === undefined ? \"\" : String(options.clock.now());\n const sent = await client.send<unknown[]>(\"EVAL\", [\n LIMITER_SCRIPT,\n 2,\n `${base}:key:${key}`,\n `${base}:keys`,\n rule.type,\n String(numbers[0]),\n String(numbers[1]),\n String(maxKeys),\n key,\n now,\n String(n),\n ]);\n if (sent.outcome !== \"ok\") throw new Error(`the limiter store ${limiter} failed (${sent.outcome}): ${sent.error}`);\n return replyOf(limiter, sent.value);\n },\n };\n};\n\n/** This function gives the decision of a reply of `LIMITER_SCRIPT`. A reply of another shape throws. */\nconst replyOf = (limiter: string, reply: unknown): Decision => {\n if (Array.isArray(reply) && Number(reply[0]) === 1 && reply.length === 2) return { allowed: true, remaining: Number(reply[1]) };\n if (Array.isArray(reply) && Number(reply[0]) === 0 && reply.length === 3 && (reply[2] === \"limit\" || reply[2] === \"cap\")) {\n const retryAfter = Number(reply[1]);\n if (Number.isFinite(retryAfter) && retryAfter > 0) return { allowed: false, retryAfter: { value: retryAfter, unit: \"ms\" }, cause: reply[2] };\n }\n throw new Error(`the limiter store ${limiter} gave a reply that is not a decision: ${JSON.stringify(reply)}`);\n};\n","import type { Machine } from \"@mark1russell7/algebra\";\nimport { clientKnob as knob, closeTimer, transition as t } from \"../client/machine.ts\";\n\n/** The states where the connection exists or tries to exist, thus where it can close. */\nconst LIVE = [\"connecting\", \"connect\", \"ready\", \"reconnecting\"] as const;\nconst ANY = [\"none\", \"connecting\", \"connect\", \"ready\", \"close\", \"reconnecting\", \"end\"] as const;\n\n/**\n * The Redis client as a `mark1russell7.machine/1` document. Its states are the states of ioredis.\n * The wrapper adds its own events: the join at each `ready`, and the misses of its watchdog. It also\n * adds a command that it sends again, and the bound of its close. A test records the transitions of the\n * client and replays them against this document.\n *\n * The state `ready` hides states that the client cannot see (D4). In a black hole, ioredis stays\n * `ready` while the kernel retransmits, until `driver_writeoff_time` or the watchdog ends that\n * hidden interval. A timer of this document bounds each hidden interval.\n */\nexport const REDIS_CLIENT_MACHINE: Machine = {\n format: \"mark1russell7.machine/1\",\n id: \"service.machine.redis-client\",\n title: \"The Redis client of the service, over ioredis 6\",\n layer: \"driver\",\n version: \"0.2.0\",\n sources: [{ ref: \"packages/service/src/redis (the client implements this document)\", rung: \"implemented\" }],\n states: {\n none: { initial: true, note: \"the client exists, and its connection does not\" },\n connecting: { note: \"a TCP connection attempt\" },\n connect: { note: \"the handshake: HELLO, then the ready check (INFO)\" },\n ready: { note: \"it can hide a black hole or a frozen server, until a timer of the client ends it\" },\n close: { note: \"the socket closed. Each command in flight settles as indeterminate\" },\n reconnecting: { note: \"the delay of the retry strategy, which doubles to its cap\" },\n end: { note: \"the retry window ended, or the service closed the client. The watchdog starts it again\" },\n },\n events: {\n \"status.connecting\": { kind: \"local\" },\n \"status.connect\": { kind: \"rx\" },\n \"status.ready\": { kind: \"rx\" },\n \"status.close\": { kind: \"rx\" },\n \"status.reconnecting\": { kind: \"timer\" },\n \"status.end\": { kind: \"local\" },\n join: { kind: \"rx\", note: \"the reply of CLIENT ID at ready (D1)\" },\n error: { kind: \"rx\" },\n \"connect.failed\": { kind: \"local\" },\n \"command.written\": { kind: \"tx\" },\n \"command.reissue\": { kind: \"local\" },\n data: { kind: \"rx\" },\n heartbeat: { kind: \"timer\" },\n \"watchdog.miss\": { kind: \"local\" },\n \"watchdog.reconnect\": { kind: \"local\" },\n \"watchdog.revive\": { kind: \"local\" },\n \"retry.window-ended\": { kind: \"local\" },\n \"close.request\": { kind: \"local\" },\n \"close.bound\": { kind: \"timer\" },\n \"close.destroy\": { kind: \"local\", note: \"the bound destroys a socket that a silent server does not close\" },\n },\n knobs: {\n connect_bound: knob(\"connectTimeout\"),\n driver_writeoff_time: knob(\"socketTimeout\"),\n heartbeat_interval: knob(\"watchdog.interval\"),\n close_bound: knob(\"close.bound\"),\n },\n timers: {\n connect_timeout: {\n duration: { knob: \"connect_bound\", unit: \"s\" },\n arms: [\"enter:connecting\"],\n cancels: [\"status.connect\", \"status.close\"],\n fires: \"status.close\",\n note: \"ioredis destroys the attempt\",\n },\n writeoff: {\n duration: { knob: \"driver_writeoff_time\", unit: \"s\" },\n arms: [\"command.written\"],\n cancels: [\"data\", \"status.close\"],\n fires: \"status.close\",\n note: \"ioredis destroys a socket that gives no data while a command waits: it ends the hidden interval of a black hole\",\n },\n heartbeat: {\n duration: { knob: \"heartbeat_interval\", unit: \"s\" },\n arms: [\"enter:ready\", \"heartbeat\"],\n cancels: [\"status.close\", \"status.end\"],\n fires: \"heartbeat\",\n note: \"a PING on the connection of the application\",\n },\n close: closeTimer(),\n },\n transitions: [\n t(\"connect\", [\"none\", \"reconnecting\", \"end\", \"close\"], \"status.connecting\", \"connecting\"),\n t(\"tcp\", \"connecting\", \"status.connect\", \"connect\"),\n t(\"ready\", \"connect\", \"status.ready\", \"ready\"),\n t(\"close\", [...LIVE], \"status.close\", \"close\"),\n t(\"retry\", \"close\", \"status.reconnecting\", \"reconnecting\"),\n t(\"end\", [...LIVE, \"close\"], \"status.end\", \"end\"),\n t(\"join\", \"ready\", \"join\", \"ready\"),\n t(\"miss\", \"ready\", \"watchdog.miss\", \"ready\"),\n t(\"watchdog-reconnect\", \"ready\", \"watchdog.reconnect\", \"ready\"),\n t(\"revive\", \"end\", \"watchdog.revive\", \"end\"),\n // the retry strategy answers in `close`, before ioredis moves to `reconnecting` or `end`\n t(\"window-ended\", \"close\", \"retry.window-ended\", \"close\"),\n ...ANY.map((state) => t(`error-${state}`, state, \"error\", state)),\n ...ANY.map((state) => t(`connect-failed-${state}`, state, \"connect.failed\", state)),\n ...ANY.map((state) => t(`reissue-${state}`, state, \"command.reissue\", state)),\n ...ANY.map((state) => t(`close-bound-${state}`, state, \"close.bound\", state, { timer: \"close\" })),\n ...ANY.map((state) => t(`close-destroy-${state}`, state, \"close.destroy\", state)),\n ],\n};\n"],"mappings":";;;;;;;;;;;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+
{"version":3,"file":"redis.js","names":["knob","t"],"sources":["../src/redis/connection.ts","../src/redis/meets.ts","../src/redis/operations.ts","../src/redis/client.ts","../src/redis/limiter.ts","../src/redis/machine.ts"],"sourcesContent":["import type { ClientSocket, Factory } from \"../client/core.ts\";\n\n/**\n * A Redis connection is the part of an ioredis client that the wrapper uses. An ioredis 6 client has\n * each part. A fake for tests has them too. Thus the package depends on no type of ioredis.\n */\nexport interface RedisConnection {\n /** This text is the state of the client: wait, connecting, connect, ready, close, reconnecting or end. */\n readonly status: string;\n /** This socket is the socket of the current connection, when there is one. */\n readonly stream?: RedisSocket | undefined;\n connect(): Promise<void>;\n /** This method sends one command, and gives the reply. */\n call(command: string, ...args: Array<string | number>): Promise<unknown>;\n quit(): Promise<unknown>;\n /** This method closes the connection at once. With `true`, the client then connects again. */\n disconnect(reconnect?: boolean): void;\n on(event: string, listener: (...args: unknown[]) => void): unknown;\n off(event: string, listener: (...args: unknown[]) => void): unknown;\n}\n\n/** A Redis socket is the socket of a client in the core: the join of the prober and the bounded close read it. */\nexport type RedisSocket = ClientSocket;\n\n/**\n * These are the options that the wrapper gives ioredis. Each one comes from the declaration. The\n * wrapper sets each option that has an effect on a timer or on a send again, thus no default of\n * ioredis decides one.\n */\nexport interface RedisConnectionOptions {\n readonly host: string;\n readonly port: number;\n readonly db?: number | undefined;\n readonly username?: string | undefined;\n readonly password?: string | undefined;\n /** The wrapper connects in its own step of the startup. */\n readonly lazyConnect: true;\n readonly connectTimeout: number;\n readonly commandTimeout: number;\n /** This time destroys a socket that gives no data while a command waits. Undefined is no bound. */\n readonly socketTimeout: number | undefined;\n /** This time is the idle time of TCP keepalive. False is no keepalive. */\n readonly keepAlive: number | false;\n /** A command while the client is not ready fails at once: it did not reach the server. */\n readonly enableOfflineQueue: false;\n /** The client does not send again a command that can have reached the server. */\n readonly autoResendUnfulfilledCommands: false;\n readonly maxRetriesPerRequest: null;\n readonly enableReadyCheck: true;\n readonly connectionName: string;\n /** This function gives the delay before the next try to connect, or null to stop. */\n readonly retryStrategy: (times: number) => number | null;\n}\n\n/** A connection factory makes the connection of the client from its options. */\nexport type ConnectionFactory = Factory<RedisConnectionOptions, RedisConnection>;\n\n/**\n * This factory makes an ioredis client. It loads ioredis only when a client connects, thus a\n * service that does not use Redis does not need ioredis.\n */\nexport const ioredis: ConnectionFactory = async (options) => {\n const loaded = (await import(\"ioredis\")) as unknown as {\n readonly default: new (options: RedisConnectionOptions) => RedisConnection;\n };\n return new loaded.default(options);\n};\n","import type { Extent } from \"@mark1russell7/quantity\";\nimport type { Detector, Meeting, Situation } from \"../client/meets.ts\";\nimport { WHAT, immediate, keepaliveAnswered, keepaliveReset, keepaliveSilent, kernelGiveUp } from \"../client/meets.ts\";\nimport type { RedisKnobs } from \"./client.ts\";\n\n// the shapes and the queries moved to the core of the clients: this entry keeps them for the users of 0.5\nexport type { Detector, Meeting, Situation } from \"../client/meets.ts\";\nexport { firstDetector, unwatched } from \"../client/meets.ts\";\n\n/**\n * This function gives the manifestations that a Redis client can meet, and the detectors of each, from\n * its knobs. A reset or a FIN arrives on the next segment. A black hole and a host that is gone give\n * no answer at all. A frozen process and a stalled server keep a kernel that acknowledges each\n * segment. Thus TCP keepalive does not fire on them, and only the client's own timers find them.\n */\nexport const meetings = (name: string, knobs: RedisKnobs, heartbeat: Extent): Meeting[] => {\n const watchdog = (situation: Situation): Detector => ({\n by: \"heartbeat_detection_time\",\n within: heartbeat,\n situation,\n effect: `the watchdog of ${name} closes the connection, and the client connects again`,\n });\n const writeoff: Detector = {\n by: \"driver_writeoff_time\",\n within: knobs.driver_writeoff_time,\n situation: \"in flight\",\n effect: \"ioredis destroys the socket of a command without data, and the client connects again\",\n };\n const command: Detector = {\n by: \"request_timeout\",\n within: knobs.request_timeout,\n situation: \"in flight\",\n effect: \"the command fails as indeterminate, and the state of the connection does not change\",\n };\n const giveUp = kernelGiveUp(knobs.retrans_giveup_time);\n const silent = (manifestation: \"blackhole\" | \"freeze-host\"): Meeting => ({\n manifestation,\n what: WHAT[manifestation],\n detectors: [command, writeoff, watchdog(\"in flight\"), giveUp, watchdog(\"idle\"), keepaliveSilent(knobs.keepalive_idle)],\n });\n const acknowledged = (manifestation: string, what: string): Meeting => ({\n manifestation,\n what,\n detectors: [command, writeoff, watchdog(\"in flight\"), watchdog(\"idle\"), keepaliveAnswered()],\n });\n return [\n {\n manifestation: \"rst\",\n what: WHAT.rst,\n detectors: [\n immediate(\"in flight\", \"the command fails, and the client connects again, and each attempt is refused\"),\n watchdog(\"idle\"),\n keepaliveReset(knobs.keepalive_idle),\n ],\n },\n {\n manifestation: \"fin\",\n what: WHAT.fin,\n detectors: [immediate(\"in flight\", \"the close arrives, and the command fails\"), immediate(\"idle\", \"the close arrives\")],\n },\n silent(\"blackhole\"),\n silent(\"freeze-host\"),\n acknowledged(\"freeze-process\", WHAT[\"freeze-process\"]),\n acknowledged(\"app-stall\", \"the server stops its replies for a time, for example a long command, and its kernel stays up\"),\n ];\n};\n","import type { Operation } from \"../operation.ts\";\n\n/**\n * These are the Redis commands whose idempotency the client declares when the declaration does not\n * say. A second issue of an idempotent command has the same effect. Thus the client can send it\n * again after a failure that left its result unknown. The client does not send again a command\n * that is not in this table: a declaration that uses it says its idempotency itself.\n */\nconst SAME_EFFECT = [\n // reads\n \"PING\",\n \"ECHO\",\n \"GET\",\n \"MGET\",\n \"STRLEN\",\n \"GETRANGE\",\n \"EXISTS\",\n \"TYPE\",\n \"TTL\",\n \"PTTL\",\n \"EXPIRETIME\",\n \"HGET\",\n \"HMGET\",\n \"HGETALL\",\n \"HKEYS\",\n \"HVALS\",\n \"HLEN\",\n \"HEXISTS\",\n \"SMEMBERS\",\n \"SISMEMBER\",\n \"SMISMEMBER\",\n \"SCARD\",\n \"ZRANGE\",\n \"ZRANGEBYSCORE\",\n \"ZSCORE\",\n \"ZMSCORE\",\n \"ZRANK\",\n \"ZCARD\",\n \"ZCOUNT\",\n \"LRANGE\",\n \"LINDEX\",\n \"LLEN\",\n \"XRANGE\",\n \"XREVRANGE\",\n \"XLEN\",\n \"SCAN\",\n \"SSCAN\",\n \"HSCAN\",\n \"ZSCAN\",\n \"DBSIZE\",\n \"INFO\",\n \"CLIENT ID\",\n // writes that put a state, not a change of a state: a second issue puts the same state\n \"SET\",\n \"MSET\",\n \"SETEX\",\n \"PSETEX\",\n \"DEL\",\n \"UNLINK\",\n \"EXPIRE\",\n \"PEXPIRE\",\n \"EXPIREAT\",\n \"PEXPIREAT\",\n \"PERSIST\",\n \"HSET\",\n \"HDEL\",\n \"SADD\",\n \"SREM\",\n \"ZADD\",\n \"ZREM\",\n];\n\n/**\n * These commands change a state relative to the state before them. A second issue changes it again:\n * an INCR that the client sends again after a timeout counts two times.\n */\nconst CHANGE = [\n \"INCR\",\n \"INCRBY\",\n \"INCRBYFLOAT\",\n \"DECR\",\n \"DECRBY\",\n \"HINCRBY\",\n \"HINCRBYFLOAT\",\n \"ZINCRBY\",\n \"APPEND\",\n \"LPUSH\",\n \"RPUSH\",\n \"LPOP\",\n \"RPOP\",\n \"BLPOP\",\n \"BRPOP\",\n \"LMOVE\",\n \"BLMOVE\",\n \"SPOP\",\n \"XADD\",\n \"XACK\",\n \"PUBLISH\",\n \"EVAL\",\n \"EVALSHA\",\n \"FCALL\",\n \"MULTI\",\n \"EXEC\",\n \"GETDEL\",\n \"GETSET\",\n \"SETNX\",\n];\n\n/** These are the operations of the client: the idempotency of each command that the table names. */\nexport const REDIS_OPERATIONS: Readonly<Record<string, Operation>> = Object.fromEntries([\n ...SAME_EFFECT.map((command) => [command, { idempotent: true }] as const),\n ...CHANGE.map((command) => [command, { idempotent: false }] as const),\n]);\n\n/** This function gives the name of a command as the table writes it: upper case, and CLIENT ID with its subcommand. */\nexport const commandName = (command: string, args: readonly unknown[]): string => {\n const name = command.toUpperCase();\n if ((name === \"CLIENT\" || name === \"CONFIG\" || name === \"DEBUG\") && typeof args[0] === \"string\")\n return `${name} ${args[0].toUpperCase()}`;\n return name;\n};\n","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","import type { Clock } from \"../clock.ts\";\nimport type { Decision } from \"../limiter/policy.ts\";\nimport { overCapacity, unitsOf } from \"../limiter/policy.ts\";\nimport type { LimiterStore } from \"../limiter/store.ts\";\nimport type { RedisClient } from \"./client.ts\";\n\n/**\n * This script decides one take in one atomic step of Redis. It does the arithmetic of `decide`, and\n * it reads `TIME` of the server, the one clock of all replicas. A test can give the time in its place.\n * - KEYS[1] is the state of the key. KEYS[2] is the index of the limiter, a sorted set of its keys\n * by the time at which each key is free.\n * - ARGV is the type of the rule, its two numbers, the cap of keys and the key. Then it has the\n * time or \"\", and the units of the take. The store refuses a take over the capacity before the script, thus the units\n * are at most the capacity.\n * - The state of a bucket is its full time. The state of a window is the time of each take in it.\n * - The state expires at its free time (PX), and the index lets the cap count only busy keys.\n * - The reply is `{1, remaining}`, or `{0, retryAfter, cause}` with the time as text. Redis gives\n * each Lua number as a whole number, thus the fraction of a millisecond goes as text.\n */\nexport const LIMITER_SCRIPT = `\nlocal kind = ARGV[1]\nlocal a = tonumber(ARGV[2])\nlocal b = tonumber(ARGV[3])\nlocal cap = tonumber(ARGV[4])\nlocal member = ARGV[5]\nlocal units = tonumber(ARGV[7])\nlocal now\nif ARGV[6] == '' then\n local t = redis.call('TIME')\n now = tonumber(t[1]) * 1000 + tonumber(t[2]) / 1000\nelse\n now = tonumber(ARGV[6])\nend\nlocal TOL = 1e-6\nlocal function num(x) return string.format('%.6f', x) end\nlocal raw = redis.call('GET', KEYS[1])\nlocal full = nil\nlocal stamps = nil\nif raw then\n if kind == 'token-bucket' then\n full = tonumber(raw)\n else\n stamps = {}\n for x in string.gmatch(raw, '[^,]+') do stamps[#stamps + 1] = tonumber(x) end\n end\nend\nlocal function freeAt()\n if kind == 'token-bucket' then return full end\n if #stamps == 0 then return -math.huge end\n return stamps[#stamps] + b\nend\nif raw and freeAt() <= now then\n redis.call('DEL', KEYS[1])\n redis.call('ZREM', KEYS[2], member)\n raw = nil\n full = nil\n stamps = nil\nend\nif not raw then\n if redis.call('ZCARD', KEYS[2]) >= cap then\n redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', num(now))\n if redis.call('ZCARD', KEYS[2]) >= cap then\n local first = redis.call('ZRANGE', KEYS[2], 0, 0, 'WITHSCORES')\n return {0, num(tonumber(first[2]) - now), 'cap'}\n end\n end\nend\nlocal remaining\nlocal state\nif kind == 'token-bucket' then\n local span = a * b\n local base = now\n if full and full > now then base = full end\n local nxt = base + a * units\n if nxt - now > span + TOL then\n return {0, num(nxt - span - now), 'limit'}\n end\n remaining = math.floor((span - (nxt - now)) / a + TOL)\n if remaining < 0 then remaining = 0 end\n full = nxt\n state = num(full)\nelse\n local live = {}\n for _, stamp in ipairs(stamps or {}) do\n if stamp + b > now + TOL then live[#live + 1] = stamp end\n end\n if #live + units > a then\n return {0, num(live[#live + units - a] + b - now), 'limit'}\n end\n for _ = 1, units do live[#live + 1] = now end\n remaining = a - #live\n stamps = live\n local parts = {}\n for i, stamp in ipairs(live) do parts[i] = num(stamp) end\n state = table.concat(parts, ',')\nend\nlocal free = freeAt()\nlocal ttl = math.ceil(free - now)\nif ttl < 1 then ttl = 1 end\nredis.call('SET', KEYS[1], state, 'PX', ttl)\nredis.call('ZADD', KEYS[2], num(free), member)\nif redis.call('PTTL', KEYS[2]) < ttl then redis.call('PEXPIRE', KEYS[2], ttl) end\nreturn {1, remaining}\n`;\n\n/** These options make a store of a limiter in Redis. */\nexport interface RedisLimiterOptions {\n /** This text starts the name of each key of the store in Redis, for example `limit:`. It has no braces. */\n readonly prefix: string;\n /**\n * This clock replaces `TIME` of the server, for a test that compares the store with `decide`. Without\n * it, the script reads `TIME`, thus each replica gets the one clock of the store.\n */\n readonly clock?: Clock | undefined;\n}\n\n/** A Redis client part is the part of a Redis client that the store uses: `send`. */\nexport type RedisSender = Pick<RedisClient, \"send\">;\n\n/**\n * This function makes a store that the replicas share, in Redis 7. Each take is one `EVAL` of\n * `LIMITER_SCRIPT`, with all of its units. The client does not send it again, because a second take\n * counts two times.\n * - The names of the keys have the limiter in braces, a hash tag. Thus the state and the index of a\n * limiter are in one slot of a Redis Cluster.\n * - Each state expires at the time that the key is free, thus the eviction is exact, as in the memory\n * store. The index of the limiter bounds the count of busy keys to `maxKeys`.\n * - A reply of an error, an outcome that is not certain, or a reply of another shape rejects the\n * take of the store. `keyedLimiter` then applies the `onStoreFailure` of the spec.\n * - `TIME` is the wall clock of the Redis host, not a monotonic clock. Thus a step of that clock\n * moves the counts of each key. The replicas still share one clock.\n */\nexport const redisLimiterStore = (client: RedisSender, options: RedisLimiterOptions): LimiterStore => {\n if (/[{}]/.test(options.prefix)) throw new Error(`the prefix ${options.prefix} of a limiter store has a brace: the store puts the hash tag in it`);\n return {\n kind: \"shared\",\n async take({ limiter, key, rule, maxKeys, units }): Promise<Decision> {\n const n = unitsOf(units);\n // a take over the capacity is refused at each time, thus it does not go to Redis\n const over = overCapacity(rule, n);\n if (over !== undefined) return over;\n const base = `${options.prefix}{${limiter}}`;\n const numbers = rule.type === \"token-bucket\" ? [rule.interval, rule.burst] : [rule.limit, rule.window];\n const now = options.clock === undefined ? \"\" : String(options.clock.now());\n const sent = await client.send<unknown[]>(\"EVAL\", [\n LIMITER_SCRIPT,\n 2,\n `${base}:key:${key}`,\n `${base}:keys`,\n rule.type,\n String(numbers[0]),\n String(numbers[1]),\n String(maxKeys),\n key,\n now,\n String(n),\n ]);\n if (sent.outcome !== \"ok\") throw new Error(`the limiter store ${limiter} failed (${sent.outcome}): ${sent.error}`);\n return replyOf(limiter, sent.value);\n },\n };\n};\n\n/** This function gives the decision of a reply of `LIMITER_SCRIPT`. A reply of another shape throws. */\nconst replyOf = (limiter: string, reply: unknown): Decision => {\n if (Array.isArray(reply) && Number(reply[0]) === 1 && reply.length === 2) return { allowed: true, remaining: Number(reply[1]) };\n if (Array.isArray(reply) && Number(reply[0]) === 0 && reply.length === 3 && (reply[2] === \"limit\" || reply[2] === \"cap\")) {\n const retryAfter = Number(reply[1]);\n if (Number.isFinite(retryAfter) && retryAfter > 0) return { allowed: false, retryAfter: { value: retryAfter, unit: \"ms\" }, cause: reply[2] };\n }\n throw new Error(`the limiter store ${limiter} gave a reply that is not a decision: ${JSON.stringify(reply)}`);\n};\n","import type { Machine } from \"@mark1russell7/algebra\";\nimport { clientKnob as knob, closeTimer, transition as t } from \"../client/machine.ts\";\n\n/** The states where the connection exists or tries to exist, thus where it can close. */\nconst LIVE = [\"connecting\", \"connect\", \"ready\", \"reconnecting\"] as const;\nconst ANY = [\"none\", \"connecting\", \"connect\", \"ready\", \"close\", \"reconnecting\", \"end\"] as const;\n\n/**\n * The Redis client as a `mark1russell7.machine/1` document. Its states are the states of ioredis.\n * The wrapper adds its own events: the join at each `ready`, and the misses of its watchdog. It also\n * adds a command that it sends again, and the bound of its close. A test records the transitions of the\n * client and replays them against this document.\n *\n * The state `ready` hides states that the client cannot see (D4). In a black hole, ioredis stays\n * `ready` while the kernel retransmits, until `driver_writeoff_time` or the watchdog ends that\n * hidden interval. A timer of this document bounds each hidden interval.\n */\nexport const REDIS_CLIENT_MACHINE: Machine = {\n format: \"mark1russell7.machine/1\",\n id: \"service.machine.redis-client\",\n title: \"The Redis client of the service, over ioredis 6\",\n layer: \"driver\",\n version: \"0.2.0\",\n sources: [{ ref: \"packages/service/src/redis (the client implements this document)\", rung: \"implemented\" }],\n states: {\n none: { initial: true, note: \"the client exists, and its connection does not\" },\n connecting: { note: \"a TCP connection attempt\" },\n connect: { note: \"the handshake: HELLO, then the ready check (INFO)\" },\n ready: { note: \"it can hide a black hole or a frozen server, until a timer of the client ends it\" },\n close: { note: \"the socket closed. Each command in flight settles as indeterminate\" },\n reconnecting: { note: \"the delay of the retry strategy, which doubles to its cap\" },\n end: { note: \"the retry window ended, or the service closed the client. The watchdog starts it again\" },\n },\n events: {\n \"status.connecting\": { kind: \"local\" },\n \"status.connect\": { kind: \"rx\" },\n \"status.ready\": { kind: \"rx\" },\n \"status.close\": { kind: \"rx\" },\n \"status.reconnecting\": { kind: \"timer\" },\n \"status.end\": { kind: \"local\" },\n join: { kind: \"rx\", note: \"the reply of CLIENT ID at ready (D1)\" },\n error: { kind: \"rx\" },\n \"connect.failed\": { kind: \"local\" },\n \"command.written\": { kind: \"tx\" },\n \"command.reissue\": { kind: \"local\" },\n data: { kind: \"rx\" },\n heartbeat: { kind: \"timer\" },\n \"watchdog.miss\": { kind: \"local\" },\n \"watchdog.reconnect\": { kind: \"local\" },\n \"watchdog.revive\": { kind: \"local\" },\n \"retry.window-ended\": { kind: \"local\" },\n \"close.request\": { kind: \"local\" },\n \"close.bound\": { kind: \"timer\" },\n \"close.destroy\": { kind: \"local\", note: \"the bound destroys a socket that a silent server does not close\" },\n },\n knobs: {\n connect_bound: knob(\"connectTimeout\"),\n driver_writeoff_time: knob(\"socketTimeout\"),\n heartbeat_interval: knob(\"watchdog.interval\"),\n close_bound: knob(\"close.bound\"),\n },\n timers: {\n connect_timeout: {\n duration: { knob: \"connect_bound\", unit: \"s\" },\n arms: [\"enter:connecting\"],\n cancels: [\"status.connect\", \"status.close\"],\n fires: \"status.close\",\n note: \"ioredis destroys the attempt\",\n },\n writeoff: {\n duration: { knob: \"driver_writeoff_time\", unit: \"s\" },\n arms: [\"command.written\"],\n cancels: [\"data\", \"status.close\"],\n fires: \"status.close\",\n note: \"ioredis destroys a socket that gives no data while a command waits: it ends the hidden interval of a black hole\",\n },\n heartbeat: {\n duration: { knob: \"heartbeat_interval\", unit: \"s\" },\n arms: [\"enter:ready\", \"heartbeat\"],\n cancels: [\"status.close\", \"status.end\"],\n fires: \"heartbeat\",\n note: \"a PING on the connection of the application\",\n },\n close: closeTimer(),\n },\n transitions: [\n t(\"connect\", [\"none\", \"reconnecting\", \"end\", \"close\"], \"status.connecting\", \"connecting\"),\n t(\"tcp\", \"connecting\", \"status.connect\", \"connect\"),\n t(\"ready\", \"connect\", \"status.ready\", \"ready\"),\n t(\"close\", [...LIVE], \"status.close\", \"close\"),\n t(\"retry\", \"close\", \"status.reconnecting\", \"reconnecting\"),\n t(\"end\", [...LIVE, \"close\"], \"status.end\", \"end\"),\n t(\"join\", \"ready\", \"join\", \"ready\"),\n t(\"miss\", \"ready\", \"watchdog.miss\", \"ready\"),\n t(\"watchdog-reconnect\", \"ready\", \"watchdog.reconnect\", \"ready\"),\n t(\"revive\", \"end\", \"watchdog.revive\", \"end\"),\n // the retry strategy answers in `close`, before ioredis moves to `reconnecting` or `end`\n t(\"window-ended\", \"close\", \"retry.window-ended\", \"close\"),\n ...ANY.map((state) => t(`error-${state}`, state, \"error\", state)),\n ...ANY.map((state) => t(`connect-failed-${state}`, state, \"connect.failed\", state)),\n ...ANY.map((state) => t(`reissue-${state}`, state, \"command.reissue\", state)),\n ...ANY.map((state) => t(`close-bound-${state}`, state, \"close.bound\", state, { timer: \"close\" })),\n ...ANY.map((state) => t(`close-destroy-${state}`, state, \"close.destroy\", state)),\n ],\n};\n"],"mappings":";;;;;;;;;;;AA6DA,MAAa,UAA6B,OAAO,YAAY;CAI3D,OAAO,KAAI,OAHW,OAAO,YAAA,CAGX,QAAQ,OAAO;AACnC;;;;;;;;ACnDA,MAAa,YAAY,MAAc,OAAmB,cAAiC;CACzF,MAAM,YAAY,eAAoC;EACpD,IAAI;EACJ,QAAQ;EACR;EACA,QAAQ,mBAAmB,KAAK;CAClC;CACA,MAAM,WAAqB;EACzB,IAAI;EACJ,QAAQ,MAAM;EACd,WAAW;EACX,QAAQ;CACV;CACA,MAAM,UAAoB;EACxB,IAAI;EACJ,QAAQ,MAAM;EACd,WAAW;EACX,QAAQ;CACV;CACA,MAAM,SAAS,aAAa,MAAM,mBAAmB;CACrD,MAAM,UAAU,mBAAyD;EACvE;EACA,MAAM,KAAK;EACX,WAAW;GAAC;GAAS;GAAU,SAAS,WAAW;GAAG;GAAQ,SAAS,MAAM;GAAG,gBAAgB,MAAM,cAAc;EAAC;CACvH;CACA,MAAM,gBAAgB,eAAuB,UAA2B;EACtE;EACA;EACA,WAAW;GAAC;GAAS;GAAU,SAAS,WAAW;GAAG,SAAS,MAAM;GAAG,kBAAkB;EAAC;CAC7F;CACA,OAAO;EACL;GACE,eAAe;GACf,MAAM,KAAK;GACX,WAAW;IACT,UAAU,aAAa,+EAA+E;IACtG,SAAS,MAAM;IACf,eAAe,MAAM,cAAc;GACrC;EACF;EACA;GACE,eAAe;GACf,MAAM,KAAK;GACX,WAAW,CAAC,UAAU,aAAa,0CAA0C,GAAG,UAAU,QAAQ,mBAAmB,CAAC;EACxH;EACA,OAAO,WAAW;EAClB,OAAO,aAAa;EACpB,aAAa,kBAAkB,KAAK,iBAAiB;EACrD,aAAa,aAAa,8FAA8F;CAC1H;AACF;;;;;;;;ACzDA,MAAM,cAAc;CAElB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAMA,MAAM,SAAS;CACb;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;C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AAa;EACXC,WAAE,WAAW;GAAC;GAAQ;GAAgB;GAAO;EAAO,GAAG,qBAAqB,YAAY;EACxFA,WAAE,OAAO,cAAc,kBAAkB,SAAS;EAClDA,WAAE,SAAS,WAAW,gBAAgB,OAAO;EAC7CA,WAAE,SAAS,CAAC,GAAG,IAAI,GAAG,gBAAgB,OAAO;EAC7CA,WAAE,SAAS,SAAS,uBAAuB,cAAc;EACzDA,WAAE,OAAO,CAAC,GAAG,MAAM,OAAO,GAAG,cAAc,KAAK;EAChDA,WAAE,QAAQ,SAAS,QAAQ,OAAO;EAClCA,WAAE,QAAQ,SAAS,iBAAiB,OAAO;EAC3CA,WAAE,sBAAsB,SAAS,sBAAsB,OAAO;EAC9DA,WAAE,UAAU,OAAO,mBAAmB,KAAK;EAE3CA,WAAE,gBAAgB,SAAS,sBAAsB,OAAO;EACxD,GAAG,IAAI,KAAK,UAAUA,WAAE,SAAS,SAAS,OAAO,SAAS,KAAK,CAAC;EAChE,GAAG,IAAI,KAAK,UAAUA,WAAE,kBAAkB,SAAS,OAAO,kBAAkB,KAAK,CAAC;EAClF,GAAG,IAAI,KAAK,UAAUA,WAAE,WAAW,SAAS,OAAO,mBAAmB,KAAK,CAAC;EAC5E,GAAG,IAAI,KAAK,UAAUA,WAAE,eAAe,SAAS,OAAO,eAAe,OAAO,EAAE,OAAO,QAAQ,CAAC,CAAC;EAChG,GAAG,IAAI,KAAK,UAAUA,WAAE,iBAAiB,SAAS,OAAO,iBAAiB,KAAK,CAAC;CAClF;AACF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { n as operationProblems, t as mayReissue } from "./operation-
|
|
2
|
-
import { t as boundedMillisecondsOf } from "./knobs-D2ClI68I.js";
|
|
1
|
+
import { n as operationProblems, t as mayReissue } from "./operation-DF73RZOI.js";
|
|
3
2
|
import { backoffProblems } from "./backoff.js";
|
|
3
|
+
import { t as boundedMillisecondsOf } from "./knobs-BJcz6m01.js";
|
|
4
4
|
import { quantity } from "@mark1russell7/quantity";
|
|
5
|
-
|
|
5
|
+
// src/routes.ts
|
|
6
6
|
const NAME = /^[A-Za-z_][A-Za-z0-9_]*/;
|
|
7
7
|
/** This function gives the problems of the syntax of a pattern: an empty pattern, a part without a name, or a name two times. */
|
|
8
8
|
const patternProblems = (owner, pattern) => {
|
|
@@ -75,8 +75,7 @@ const compilePattern = (pattern) => {
|
|
|
75
75
|
}
|
|
76
76
|
};
|
|
77
77
|
};
|
|
78
|
-
|
|
79
|
-
//#region src/units.ts
|
|
78
|
+
// src/units.ts
|
|
80
79
|
/** This function gives the cause of an abort as text. */
|
|
81
80
|
const causeOf = (signal) => signal.reason instanceof Error ? signal.reason.message : String(signal.reason ?? "the unit got an abort");
|
|
82
81
|
/**
|
|
@@ -307,8 +306,7 @@ const boundProblems = (owner, description) => {
|
|
|
307
306
|
const has = (name) => description.shutdown.phases.some((each) => each.name === name);
|
|
308
307
|
return [...has("close transports") ? [] : [`${owner} needs the phase "close transports" to close`], ...has("drain") ? [] : [`${owner} needs the phase "drain" to end its units`]];
|
|
309
308
|
};
|
|
310
|
-
|
|
311
|
-
//#region src/requests.ts
|
|
309
|
+
// src/requests.ts
|
|
312
310
|
const isAsyncIterable = (value) => value !== null && (typeof value === "object" || typeof value === "function") && typeof value[Symbol.asyncIterator] === "function";
|
|
313
311
|
const isPromiseLike = (value) => value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
|
|
314
312
|
/** This function gives a stream of events from a function that gives the next event. */
|
|
@@ -580,7 +578,6 @@ const tracker = (controllers, clock, refuses, choices = /* @__PURE__ */ new Map(
|
|
|
580
578
|
}
|
|
581
579
|
};
|
|
582
580
|
};
|
|
583
|
-
//#endregion
|
|
584
581
|
export { runUnit as a, untilAbort as c, retryOf as i, routePatternProblems as l, boundProblems as n, settleWithin as o, flights as r, sleeper as s, tracker as t };
|
|
585
582
|
|
|
586
|
-
//# sourceMappingURL=requests-
|
|
583
|
+
//# sourceMappingURL=requests-DD2ALv0_.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"requests-BIq9Tr4P.js","names":[],"sources":["../src/routes.ts","../src/units.ts","../src/requests.ts"],"sourcesContent":["import type { Operation } from \"./operation.ts\";\nimport { operationProblems } from \"./operation.ts\";\n\n/**\n * A route pattern matches the routes of a controller that its exact routes do not name. A\n * registry that changes while the service operates, for example a registry of procedures, thus\n * needs no list of routes before the start. The syntax of a pattern:\n * - `*` matches each text, also an empty text and a text with `/`. The pattern `*` alone matches\n * each route.\n * - `:name` matches a text of one character or more without `/`, and gives it in `params.name`.\n * - Each other character matches itself.\n *\n * The declaration names the operations that a request of the pattern can be. Each operation\n * declares its idempotency, as a route does. A function picks the operation of each request.\n */\nexport interface RoutePattern {\n readonly pattern: string;\n /** These are the operations that a request of the pattern can be, by name. */\n readonly operations: Readonly<Record<string, Operation>>;\n}\n\n/** A route request is what the function of a pattern gets for one request. */\nexport interface RouteRequest {\n readonly controller: string;\n readonly route: string;\n /** These are the texts of the `:name` parts of the pattern, by name. */\n readonly params: Readonly<Record<string, string>>;\n /** These are the texts of the `*` parts of the pattern, in their sequence. */\n readonly wildcards: readonly string[];\n /** This value is the detail that the transport gives with the request, or undefined. */\n readonly detail: unknown;\n}\n\n/**\n * An operation choice gives the name of the operation of one request: one of the operations that\n * the pattern declares. Thus the function decides the idempotency of each request, and the\n * declaration keeps each window of a keyed operation as data.\n */\nexport type OperationOf = (request: RouteRequest) => string;\n\n/** A compiled pattern matches a route, and gives the parts of the route that it matched. */\nexport interface CompiledPattern {\n readonly pattern: string;\n match(route: string): { readonly params: Record<string, string>; readonly wildcards: string[] } | null;\n}\n\nconst NAME = /^[A-Za-z_][A-Za-z0-9_]*/;\n\n/** This function gives the problems of the syntax of a pattern: an empty pattern, a part without a name, or a name two times. */\nexport const patternProblems = (owner: string, pattern: string): string[] => {\n const problems: string[] = [];\n if (pattern.length === 0) problems.push(`${owner} has an empty route pattern`);\n const names = new Set<string>();\n for (let at = 0; at < pattern.length; at += 1) {\n if (pattern[at] !== \":\") continue;\n const name = NAME.exec(pattern.slice(at + 1))?.[0];\n if (name === undefined) {\n problems.push(`${owner}'s pattern ${pattern} has a \":\" without a name at ${at}`);\n continue;\n }\n if (names.has(name)) problems.push(`${owner}'s pattern ${pattern} names :${name} two times`);\n names.add(name);\n at += name.length;\n }\n return problems;\n};\n\n/** This function gives the problems of a pattern and of each of its operations, which `describe()` refuses. */\nexport const routePatternProblems = (owner: string, declared: RoutePattern): string[] => {\n const problems = patternProblems(owner, declared.pattern);\n const names = Object.keys(declared.operations);\n if (names.length === 0) problems.push(`${owner}'s pattern ${declared.pattern} declares no operation`);\n for (const name of names)\n problems.push(...operationProblems(owner, `${declared.pattern} (${name})`, declared.operations[name]!));\n return problems;\n};\n\n/** This function compiles a pattern to a matcher. The match must cover the whole route. */\nexport const compilePattern = (pattern: string): CompiledPattern => {\n const kinds: Array<{ kind: \"param\"; name: string } | { kind: \"wildcard\" }> = [];\n let source = \"^\";\n for (let at = 0; at < pattern.length; at += 1) {\n const char = pattern[at]!;\n if (char === \"*\") {\n source += \"([\\\\s\\\\S]*)\";\n kinds.push({ kind: \"wildcard\" });\n continue;\n }\n if (char === \":\") {\n const name = NAME.exec(pattern.slice(at + 1))?.[0];\n if (name !== undefined) {\n source += \"([^/]+)\";\n kinds.push({ kind: \"param\", name });\n at += name.length;\n continue;\n }\n }\n source += char.replace(/[.*+?^${}()|[\\]\\\\/]/g, \"\\\\$&\");\n }\n const matcher = new RegExp(`${source}$`);\n return {\n pattern,\n match(route) {\n const found = matcher.exec(route);\n if (found === null) return null;\n const params: Record<string, string> = {};\n const wildcards: string[] = [];\n kinds.forEach((part, index) => {\n const text = found[index + 1] ?? \"\";\n if (part.kind === \"param\") params[part.name] = text;\n else wildcards.push(text);\n });\n return { params, wildcards };\n },\n };\n};\n","// 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","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":";;;;;AA8CA,MAAM,OAAO;;AAGb,MAAa,mBAAmB,OAAe,YAA8B;CAC3E,MAAM,WAAqB,CAAC;CAC5B,IAAI,QAAQ,WAAW,GAAG,SAAS,KAAK,GAAG,MAAM,4BAA4B;CAC7E,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,IAAI,KAAK,GAAG,KAAK,QAAQ,QAAQ,MAAM,GAAG;EAC7C,IAAI,QAAQ,QAAQ,KAAK;EACzB,MAAM,OAAO,KAAK,KAAK,QAAQ,MAAM,KAAK,CAAC,CAAC,CAAC,GAAG;EAChD,IAAI,SAAS,KAAA,GAAW;GACtB,SAAS,KAAK,GAAG,MAAM,aAAa,QAAQ,+BAA+B,IAAI;GAC/E;EACF;EACA,IAAI,MAAM,IAAI,IAAI,GAAG,SAAS,KAAK,GAAG,MAAM,aAAa,QAAQ,UAAU,KAAK,WAAW;EAC3F,MAAM,IAAI,IAAI;EACd,MAAM,KAAK;CACb;CACA,OAAO;AACT;;AAGA,MAAa,wBAAwB,OAAe,aAAqC;CACvF,MAAM,WAAW,gBAAgB,OAAO,SAAS,OAAO;CACxD,MAAM,QAAQ,OAAO,KAAK,SAAS,UAAU;CAC7C,IAAI,MAAM,WAAW,GAAG,SAAS,KAAK,GAAG,MAAM,aAAa,SAAS,QAAQ,uBAAuB;CACpG,KAAK,MAAM,QAAQ,OACjB,SAAS,KAAK,GAAG,kBAAkB,OAAO,GAAG,SAAS,QAAQ,IAAI,KAAK,IAAI,SAAS,WAAW,KAAM,CAAC;CACxG,OAAO;AACT;;AAGA,MAAa,kBAAk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,UAA0B,CAAC,GAAG;GAC9F,MAAM,YAAY,YAAY,YAAY,OAAO,QAAQ,MAAM;GAC/D,MAAM,UAAU,SAAS,QAAQ,UAAU,IAAI;GAC/C,IAAI,YAAY,MAAM;IACpB,IAAI,QAAQ;IACZ,MAAM,UAAsB;KAAE,MAAM;KAAW,QAAQ;KAAK,WAAW;KAAM,OAAO;KAAS,WAAW;IAAE;IAC1G,OAAO,eACC;KACJ,IAAI,OAAO,OAAO,QAAQ,QAAQ,IAAI;KACtC,QAAQ;KACR,OAAO,QAAQ,QAAQ,OAAO;IAChC,SACM;KACJ,QAAQ;IACV,CACF;GACF;GACA,OAAO,KAAK,YAAY,WAAW,IAAI;EACzC;EACA,SAAS,YAAY;GACnB,IAAI,QAAQ;GACZ,KAAK,MAAM,UAAU,SAAS,IAAI,eAAe,KAAA,KAAa,OAAO,eAAe,YAAY,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;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-DD2ALv0_.js","names":[],"sources":["../src/routes.ts","../src/units.ts","../src/requests.ts"],"sourcesContent":["import type { Operation } from \"./operation.ts\";\nimport { operationProblems } from \"./operation.ts\";\n\n/**\n * A route pattern matches the routes of a controller that its exact routes do not name. A\n * registry that changes while the service operates, for example a registry of procedures, thus\n * needs no list of routes before the start. The syntax of a pattern:\n * - `*` matches each text, also an empty text and a text with `/`. The pattern `*` alone matches\n * each route.\n * - `:name` matches a text of one character or more without `/`, and gives it in `params.name`.\n * - Each other character matches itself.\n *\n * The declaration names the operations that a request of the pattern can be. Each operation\n * declares its idempotency, as a route does. A function picks the operation of each request.\n */\nexport interface RoutePattern {\n readonly pattern: string;\n /** These are the operations that a request of the pattern can be, by name. */\n readonly operations: Readonly<Record<string, Operation>>;\n}\n\n/** A route request is what the function of a pattern gets for one request. */\nexport interface RouteRequest {\n readonly controller: string;\n readonly route: string;\n /** These are the texts of the `:name` parts of the pattern, by name. */\n readonly params: Readonly<Record<string, string>>;\n /** These are the texts of the `*` parts of the pattern, in their sequence. */\n readonly wildcards: readonly string[];\n /** This value is the detail that the transport gives with the request, or undefined. */\n readonly detail: unknown;\n}\n\n/**\n * An operation choice gives the name of the operation of one request: one of the operations that\n * the pattern declares. Thus the function decides the idempotency of each request, and the\n * declaration keeps each window of a keyed operation as data.\n */\nexport type OperationOf = (request: RouteRequest) => string;\n\n/** A compiled pattern matches a route, and gives the parts of the route that it matched. */\nexport interface CompiledPattern {\n readonly pattern: string;\n match(route: string): { readonly params: Record<string, string>; readonly wildcards: string[] } | null;\n}\n\nconst NAME = /^[A-Za-z_][A-Za-z0-9_]*/;\n\n/** This function gives the problems of the syntax of a pattern: an empty pattern, a part without a name, or a name two times. */\nexport const patternProblems = (owner: string, pattern: string): string[] => {\n const problems: string[] = [];\n if (pattern.length === 0) problems.push(`${owner} has an empty route pattern`);\n const names = new Set<string>();\n for (let at = 0; at < pattern.length; at += 1) {\n if (pattern[at] !== \":\") continue;\n const name = NAME.exec(pattern.slice(at + 1))?.[0];\n if (name === undefined) {\n problems.push(`${owner}'s pattern ${pattern} has a \":\" without a name at ${at}`);\n continue;\n }\n if (names.has(name)) problems.push(`${owner}'s pattern ${pattern} names :${name} two times`);\n names.add(name);\n at += name.length;\n }\n return problems;\n};\n\n/** This function gives the problems of a pattern and of each of its operations, which `describe()` refuses. */\nexport const routePatternProblems = (owner: string, declared: RoutePattern): string[] => {\n const problems = patternProblems(owner, declared.pattern);\n const names = Object.keys(declared.operations);\n if (names.length === 0) problems.push(`${owner}'s pattern ${declared.pattern} declares no operation`);\n for (const name of names)\n problems.push(...operationProblems(owner, `${declared.pattern} (${name})`, declared.operations[name]!));\n return problems;\n};\n\n/** This function compiles a pattern to a matcher. The match must cover the whole route. */\nexport const compilePattern = (pattern: string): CompiledPattern => {\n const kinds: Array<{ kind: \"param\"; name: string } | { kind: \"wildcard\" }> = [];\n let source = \"^\";\n for (let at = 0; at < pattern.length; at += 1) {\n const char = pattern[at]!;\n if (char === \"*\") {\n source += \"([\\\\s\\\\S]*)\";\n kinds.push({ kind: \"wildcard\" });\n continue;\n }\n if (char === \":\") {\n const name = NAME.exec(pattern.slice(at + 1))?.[0];\n if (name !== undefined) {\n source += \"([^/]+)\";\n kinds.push({ kind: \"param\", name });\n at += name.length;\n continue;\n }\n }\n source += char.replace(/[.*+?^${}()|[\\]\\\\/]/g, \"\\\\$&\");\n }\n const matcher = new RegExp(`${source}$`);\n return {\n pattern,\n match(route) {\n const found = matcher.exec(route);\n if (found === null) return null;\n const params: Record<string, string> = {};\n const wildcards: string[] = [];\n kinds.forEach((part, index) => {\n const text = found[index + 1] ?? \"\";\n if (part.kind === \"param\") params[part.name] = text;\n else wildcards.push(text);\n });\n return { params, wildcards };\n },\n };\n};\n","// 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","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":";;;;;AA8CA,MAAM,OAAO;;AAGb,MAAa,mBAAmB,OAAe,YAA8B;CAC3E,MAAM,WAAqB,CAAC;CAC5B,IAAI,QAAQ,WAAW,GAAG,SAAS,KAAK,GAAG,MAAM,4BAA4B;CAC7E,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,IAAI,KAAK,GAAG,KAAK,QAAQ,QAAQ,MAAM,GAAG;EAC7C,IAAI,QAAQ,QAAQ,KAAK;EACzB,MAAM,OAAO,KAAK,KAAK,QAAQ,MAAM,KAAK,CAAC,CAAC,CAAC,GAAG;EAChD,IAAI,SAAS,KAAA,GAAW;GACtB,SAAS,KAAK,GAAG,MAAM,aAAa,QAAQ,+BAA+B,IAAI;GAC/E;EACF;EACA,IAAI,MAAM,IAAI,IAAI,GAAG,SAAS,KAAK,GAAG,MAAM,aAAa,QAAQ,UAAU,KAAK,WAAW;EAC3F,MAAM,IAAI,IAAI;EACd,MAAM,KAAK;CACb;CACA,OAAO;AACT;;AAGA,MAAa,wBAAwB,OAAe,aAAqC;CACvF,MAAM,WAAW,gBAAgB,OAAO,SAAS,OAAO;CACxD,MAAM,QAAQ,OAAO,KAAK,SAAS,UAAU;CAC7C,IAAI,MAAM,WAAW,GAAG,SAAS,KAAK,GAAG,MAAM,aAAa,SAAS,QAAQ,uBAAuB;CACpG,KAAK,MAAM,QAAQ,OACjB,SAAS,KAAK,GAAG,kBAAkB,OAAO,GAAG,SAAS,QAAQ,IAAI,KAAK,IAAI,SAAS,WAAW,KAAM,CAAC;CACxG,OAAO;AACT;;AAGA,MAAa,kBAAkB,YAAqC;CAClE,MAAM,QAAuE,CAAC;CAC9E,IAAI,SAAS;CACb,KAAK,IAAI,KAAK,GAAG,KAAK,QAAQ,QAAQ,MAAM,GAAG;EAC7C,MAAM,OAAO,QAAQ;EACrB,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I,QAAQ;IACZ,MAAM,UAAsB;KAAE,MAAM;KAAW,QAAQ;KAAK,WAAW;KAAM,OAAO;KAAS,WAAW;IAAE;IAC1G,OAAO,eACC;KACJ,IAAI,OAAO,OAAO,QAAQ,QAAQ,IAAI;KACtC,QAAQ;KACR,OAAO,QAAQ,QAAQ,OAAO;IAChC,SACM;KACJ,QAAQ;IACV,CACF;GACF;GACA,OAAO,KAAK,YAAY,WAAW,IAAI;EACzC;EACA,SAAS,YAAY;GACnB,IAAI,QAAQ;GACZ,KAAK,MAAM,UAAU,SAAS,IAAI,eAAe,KAAA,KAAa,OAAO,eAAe,YAAY,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;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,6 +1,6 @@
|
|
|
1
|
-
import { realClock } from "./clock.js";
|
|
2
1
|
import { backoffDelay, backoffProblems } from "./backoff.js";
|
|
3
|
-
|
|
2
|
+
import { realClock } from "./clock.js";
|
|
3
|
+
// src/retrier.ts
|
|
4
4
|
/** This function makes a retrier with no check of its policy. A client of the package uses it with its own knobs. */
|
|
5
5
|
const retrierOn = (clock, backoff, random, signal) => {
|
|
6
6
|
let tries = 0;
|
|
@@ -86,7 +86,6 @@ const retry = async (run, options) => {
|
|
|
86
86
|
});
|
|
87
87
|
}
|
|
88
88
|
};
|
|
89
|
-
//#endregion
|
|
90
89
|
export { retryAfterDelay as i, retrierOn as n, retry as r, retrier as t };
|
|
91
90
|
|
|
92
|
-
//# sourceMappingURL=retrier-
|
|
91
|
+
//# sourceMappingURL=retrier-BObZq10-.js.map
|