@mark1russell7/service 0.8.20 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -2
- package/build/builder.js +2 -2
- package/build/builder.js.map +1 -1
- package/build/channel.js.map +1 -1
- package/build/client/core.js.map +1 -1
- package/build/clock.d.ts +2 -2
- package/build/clock.js +1 -1
- package/build/conformance.js +3 -4
- package/build/conformance.js.map +1 -1
- package/build/health.js +4 -2
- package/build/health.js.map +1 -1
- package/build/heartbeat.d.ts +5 -1
- package/build/heartbeat.js.map +1 -1
- package/build/host/group.js +11 -4
- package/build/host/group.js.map +1 -1
- package/build/http/transport.js +1 -0
- package/build/http/transport.js.map +1 -1
- package/build/http-client/client.js.map +1 -1
- package/build/http-client/session.js +2 -2
- package/build/http-client/session.js.map +1 -1
- package/build/index.d.ts +2 -2
- package/build/index.js +2 -2
- package/build/latch.js.map +1 -1
- package/build/lifecycle.js.map +1 -1
- package/build/poller.js +2 -0
- package/build/poller.js.map +1 -1
- package/build/rabbitmq/client.js.map +1 -1
- package/build/redis/client.js +2 -2
- package/build/redis/client.js.map +1 -1
- package/build/requests.js.map +1 -1
- package/build/retrier.js.map +1 -1
- package/build/units.js.map +1 -1
- package/build/watchdog.d.ts +5 -1
- package/build/watchdog.js +5 -1
- package/build/watchdog.js.map +1 -1
- package/build/websocket/client.js +2 -2
- package/build/websocket/client.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../../src/http-client/client.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport type { CallContext } from \"../call-context.ts\";\nimport type { Cancel } from \"../clock.ts\";\nimport { realClock } from \"../clock.ts\";\nimport type { Attempt, CheckOptions, Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, SendOptions, Sent } from \"../client/core.ts\";\nimport {\n ageProblems,\n attachClient,\n clientBounds,\n clientProblems,\n clientRecorder,\n dialCheck,\n idleCloseProblem,\n inFlight,\n keepaliveOnProblems,\n localStateCheck,\n message,\n ms,\n notSent,\n operationTable,\n poolProblems,\n roundTripCheck,\n sendWithReissue,\n socketEnds,\n stepChecks,\n timeProblems,\n trackWithTimer,\n wholeProblems,\n withinBound,\n wrapperTimerProblems,\n zeroProblems,\n} from \"../client/core.ts\";\nimport type { Judge } from \"../client/dial.ts\";\nimport { authority, helloDial, statusLineJudge } from \"../client/dial.ts\";\nimport type { Dependency } from \"../description.ts\";\nimport type { DependencyHandle } from \"../lifecycle.ts\";\nimport type { Operation } from \"../operation.ts\";\nimport type { AgentExchange, AgentFactory, HttpAgent, HttpAgentOptions, HttpResponse, HttpSocket } from \"./connection.ts\";\nimport { nodeAgent } from \"./connection.ts\";\nimport { httpClientMeetings } from \"./meets.ts\";\n\n/**\n * These are the knobs of the client, each a time, by the names of the ordering law where the law\n * has them. The runtime has no defaults, thus each knob is necessary. The constant\n * `HTTP_CLIENT_STARTING_KNOBS` gives a declaration from the HTTP cells. The knobs that each client has come from the core.\n */\nexport interface HttpClientKnobs extends ClientKnobs {\n /** This time bounds the TCP connect of a new socket. The wrapper has this timer, because the agent has none. */\n readonly connect_bound: Quantity;\n /**\n * This time bounds each call: from its start until the end of the body of its response. It also\n * bounds the wait for a socket. The wrapper has this timer, because the agent has none.\n */\n readonly request_timeout: Quantity;\n /**\n * This time is the free socket timer of the agent (`timeout`). The agent closes a free socket at the\n * smaller of this time and the hint of the server less `hint_buffer`. It must be below `server_idle_close` (O01).\n */\n readonly pool_idle_expiry: Extent;\n /** This time is what the agent subtracts from the hint of the server (`agentKeepAliveTimeoutBuffer`). A hint at or below it gives no reuse. */\n readonly hint_buffer: Quantity;\n /**\n * This time is when the server closes an idle connection, after its response. A Node server closes\n * at `keepAliveTimeout` plus `keepAliveTimeoutBuffer`. \"infinite\" is a server that keeps an idle\n * connection with no bound. The client does not set it: `problems` compares it with `pool_idle_expiry` (O01).\n */\n readonly server_idle_close: Extent;\n /** This time is the idle time of TCP keepalive (`keepAliveMsecs`), in whole seconds. The agent always turns keepalive on. */\n readonly keepalive_idle: Extent;\n /** The agent does not replace a connection at an age, thus this knob must be \"infinite\". */\n readonly max_connection_age: Extent;\n /** This time bounds the close of the client: the wait for the calls in flight, then a destroy of each socket. */\n readonly close_bound: Quantity;\n}\n\n/** A check request is the request of the round-trip check, and of the first connection at the connect. */\nexport interface CheckRequest {\n readonly method: string;\n readonly path: string;\n}\n\n/**\n * This request asks about the server, not about a resource (RFC 9110 §9.3.7). Thus it changes no\n * state. A server that does not route it still answers with a status, and the status tells that it is alive.\n */\nexport const OPTIONS_STAR: CheckRequest = { method: \"OPTIONS\", path: \"*\" };\n\n/** An HTTP client spec is the declaration of one HTTP client: the origin that it connects to, its pool, and its knobs. */\nexport interface HttpClientSpec extends ClientSpec<HttpClientKnobs> {\n /** This count is the most sockets of the pool (`maxSockets`). It is also the most free sockets. */\n readonly pool: { readonly max: number };\n /** This request is the request of the round-trip check and of the first connection. Without it, the client uses `OPTIONS *`. */\n readonly check?: CheckRequest | undefined;\n /**\n * These operations add to the table of the client, or change it. The table names each method by\n * its idempotency in RFC 9110. A caller can name an operation of its own, for example a POST with an `Idempotency-Key`.\n */\n readonly operations?: Readonly<Record<string, Operation>> | undefined;\n}\n\n/** These options make a client. Without them, it uses the agent of Node, the real clock, and a dial with `OPTIONS *`. */\nexport interface HttpClientOptions extends ClientOptions<AgentFactory> {\n /**\n * With this call context, each request gets the headers of the active context of its caller, for\n * example `traceparent`. A header of the call with the same name stays. `callContext` of the entry `/otel` gives one.\n */\n readonly callContext?: CallContext | undefined;\n}\n\n/** An HTTP call is one request. A string body goes as UTF-8, with its `content-length`. */\nexport interface HttpCall {\n readonly method: string;\n readonly path: string;\n readonly headers?: Readonly<Record<string, string>> | undefined;\n readonly body?: string | Uint8Array | undefined;\n /** This name is the operation of the call in the table. Without it, the operation is the method. */\n readonly operation?: string | undefined;\n}\n\n/** An HTTP client is a dependency of a service: its declaration, its handle, its checks and its requests. */\nexport interface HttpClient extends Client<ClientStep, ClientJoin> {\n /** This text is the state of the client, as `HTTP_CLIENT_MACHINE` names it. */\n readonly status: string;\n /**\n * This method sends a request, and gives its outcome in three values. A whole response of each\n * status is `ok`. The client sends again only an idempotent operation, one time at most, after an\n * outcome that is not certain. The second try stays in the bound of the request.\n */\n request(call: HttpCall, options?: SendOptions): Promise<Sent<HttpResponse>>;\n}\n\n/**\n * These operations are the methods of HTTP, by their idempotency in RFC 9110 §9.2.2. A second\n * request of GET, HEAD, OPTIONS, TRACE, PUT or DELETE has the same effect as one. POST and PATCH do not.\n */\nexport const HTTP_OPERATIONS: Readonly<Record<string, Operation>> = {\n GET: { idempotent: true },\n HEAD: { idempotent: true },\n OPTIONS: { idempotent: true },\n TRACE: { idempotent: true },\n PUT: { idempotent: true },\n DELETE: { idempotent: true },\n POST: { idempotent: false },\n PATCH: { idempotent: false },\n};\n\n/** This function gives the problems of a spec: the knobs that the agent cannot use. */\nexport const specProblems = (name: string, spec: HttpClientSpec): string[] => {\n const { knobs } = spec;\n const problems = [\n ...timeProblems(name, knobs),\n // the agent has no timer of a connect or of a call\n ...wrapperTimerProblems(name, knobs, { connect_bound: \"a connect\", request_timeout: \"a call\" }),\n // the agent reads a timeout of 0 as no free socket timer, and then the hint of the server does not apply\n ...zeroProblems(name, \"the agent\", knobs, { bounded: [\"pool_idle_expiry\"] }),\n ...keepaliveOnProblems(name, knobs, \"the agent\"),\n // Node truncates the keepalive delay to whole seconds\n ...wholeProblems(name, knobs, { millis: [\"connect_bound\", \"request_timeout\", \"pool_idle_expiry\", \"hint_buffer\"], seconds: [\"keepalive_idle\"] }),\n ...poolProblems(name, { max: spec.pool.max, min: 0 }),\n ...ageProblems(name, knobs, \"the agent does not replace a connection at an age\"),\n ];\n if (!Number.isFinite(ms(knobs.hint_buffer))) problems.push(`${name}'s hint_buffer is not a finite time: the agent subtracts it from the hint of the server`);\n return problems;\n};\n\n/** This function gives the options of `new http.Agent` from a spec. Each timer of the agent comes from the declaration. */\nexport const agentOptions = (spec: HttpClientSpec): HttpAgentOptions => {\n const { knobs } = spec;\n return {\n keepAlive: true,\n timeout: ms(knobs.pool_idle_expiry),\n agentKeepAliveTimeoutBuffer: ms(knobs.hint_buffer),\n keepAliveMsecs: ms(knobs.keepalive_idle),\n maxSockets: spec.pool.max,\n maxFreeSockets: spec.pool.max,\n scheduling: \"lifo\",\n };\n};\n\n/** This function gives the bytes of the dial: `OPTIONS *` with the Host header, and a close after the answer. */\nexport const optionsRequest = (host: string, port: number): string => `OPTIONS * HTTP/1.1\\r\\nHost: ${authority(host, port)}\\r\\nConnection: close\\r\\n\\r\\n`;\n\n/** This judge reads the status line of the answer. Any status passes, because it tells that an HTTP server answered. */\nexport const statusJudge: Judge = statusLineJudge(() => null);\n\n/** This dial function opens a TCP connection, sends `OPTIONS *`, and waits for the status line. It changes no state on the server. */\nexport const httpDial: DialFn = (host, port, signal) => helloDial(optionsRequest(host, port), statusJudge)(host, port, signal);\n\n/**\n * This function makes an HTTP client, a dependency of a service over an `http.Agent` of Node.\n * - It sets each timer of the agent from the declaration. The agent sends no request again by itself,\n * and the client sends again only an idempotent operation of its table.\n * - Its call is a request until the end of the body of its response. The wrapper has a timer for the\n * connect and one for the call, because the agent has none.\n * - It tells the outcome of a call in three values. A request that did not get a connected socket\n * did not leave the client. A failure after that is not certain.\n * - It destroys the socket of each call that is not `ok`, thus no later request gets that socket.\n * - It records each new socket of the pool (D1). HTTP gives no id of a connection.\n *\n * The core of the clients gives the outcomes, the second try, the calls in flight and the timer of a\n * call. It also gives the bounded close and the checks. This entry gives what the agent does in its own way.\n */\nexport const httpClient = (name: string, spec: HttpClientSpec, options: HttpClientOptions = {}): HttpClient => {\n const problems = specProblems(name, spec);\n if (problems.length > 0) throw new Error(problems.join(\"; \"));\n const { knobs } = spec;\n const clock = options.clock ?? realClock;\n const create = options.create ?? nodeAgent;\n const dial = options.dial ?? httpDial;\n const operations = operationTable(HTTP_OPERATIONS, spec.operations);\n const requestTimeout = ms(knobs.request_timeout);\n const connectBound = ms(knobs.connect_bound);\n const check = spec.check ?? OPTIONS_STAR;\n\n let agent: HttpAgent | null = null;\n let status = \"none\";\n const joins: ClientJoin[] = [];\n // the calls that left the client: the close waits for them, in its bound\n const flight = inFlight();\n // the calls that did not leave the client: the close ends each one as not sent\n const waiting = new Set<(error: string) => void>();\n\n const emit = clientRecorder(options.record, clock, name);\n // the state of the client is the outcome of the last connect of a socket of its pool\n const record = (on: string, to: string = status, detail?: string): void => {\n const from = status;\n status = to;\n emit(from, to, on, detail);\n };\n const closing = (): boolean => status === \"closing\" || status === \"end\";\n\n /**\n * This function makes one try of a call. The try waits for a socket of the agent: a free one, or a\n * new one in `connect_bound`. A failure before the socket is ready is certain: the request did not\n * leave the client. After that, the try waits for the whole response in the rest of `request_timeout`.\n */\n const attempt = async (call: HttpCall, signal: AbortSignal | undefined): Promise<Attempt<HttpResponse>> => {\n const a = agent;\n if (a === null) return notSent(`${name} has not connected`);\n if (closing()) return notSent(`${name} is ${status}: the request did not leave the client`);\n if (signal?.aborted) return notSent(\"the caller aborted the request before it left the client\");\n const started = clock.now();\n const body = typeof call.body === \"string\" ? Buffer.from(call.body, \"utf8\") : call.body;\n const headers = { ...call.headers, ...(body === undefined ? {} : { \"content-length\": String(body.byteLength) }) };\n\n let socket: HttpSocket | undefined;\n let reused = false;\n let left = false;\n // true when the wrapper ended the try itself: the error of the agent that follows is not a failed connect\n let ending = false;\n let connectTimer: Cancel = () => {};\n let decide: (value: true | Attempt<never>) => void = () => {};\n const leaving = new Promise<true | Attempt<never>>((resolve) => {\n let decided = false;\n decide = (value) => {\n if (decided) return;\n decided = true;\n resolve(value);\n };\n });\n // a result of the agent that arrives before the try records it\n let deliver: ((value: Attempt<HttpResponse>, cause?: Error) => void) | null = null;\n let early: { readonly value: Attempt<HttpResponse>; readonly cause: Error | undefined } | null = null;\n let settled = false;\n const settleWith = (value: Attempt<HttpResponse>, cause?: Error): void => {\n if (deliver === null) early ??= { value, cause };\n else deliver(value, cause);\n };\n\n let exchange: AgentExchange | null = null;\n const stop = (text: string): void => {\n if (left) return;\n ending = true;\n connectTimer();\n exchange?.abort(new Error(text));\n decide(notSent(text));\n };\n const ready = (): void => {\n left = true;\n connectTimer();\n decide(true);\n };\n exchange = a.request(\n { host: spec.host, port: spec.port, method: call.method, path: call.path, headers, body },\n {\n socket(given, isReused) {\n socket = given;\n reused = isReused;\n if (isReused) {\n ready();\n return;\n }\n connectTimer = clock.after(connectBound, () => {\n if (left) return;\n record(\"connect.failed\", closing() ? status : \"failing\", \"no connection in connect_bound\");\n stop(\"no connection in connect_bound: the request did not leave the client\");\n });\n },\n connect() {\n const generation = joins.length + 1;\n joins.push({ generation, at: clock.now(), ...socketEnds(socket) });\n record(\"join\", closing() ? status : \"ready\", `socket ${generation}`);\n ready();\n },\n },\n );\n // the agent can fail a request in its queue or at its connect: it did not leave the client\n exchange.response.then(\n (response) => settleWith({ outcome: \"ok\", value: response }),\n (error: unknown) => {\n const cause = error instanceof Error ? error : new Error(message(error));\n if (!left) {\n connectTimer();\n if (!ending) record(\"connect.failed\", closing() ? status : \"failing\", message(error));\n decide(notSent(message(error)));\n return;\n }\n // the abort of the wrapper after the call settled is not a failure of the socket\n if (settled) return;\n // a reused socket that fails before the response: the server closed it, as in the keep-alive race\n if (reused) record(\"reuse.failed\", status, message(error));\n settleWith({ outcome: \"indeterminate\", error: message(error) }, cause);\n },\n );\n\n const abandoned = (): void => stop(\"the caller abandoned the request before it left the client\");\n signal?.addEventListener(\"abort\", abandoned, { once: true });\n const queued = clock.after(requestTimeout, () => stop(\"no socket in request_timeout: the request did not leave the client\"));\n waiting.add(stop);\n const got = await leaving;\n signal?.removeEventListener(\"abort\", abandoned);\n queued();\n waiting.delete(stop);\n if (got !== true) return got;\n\n const sent = exchange;\n return trackWithTimer<HttpResponse>(\n flight,\n clock,\n Math.max(0, requestTimeout - (clock.now() - started)),\n signal,\n \"the caller abandoned the request after it left the client\",\n \"no whole response in request_timeout: the server can have the request\",\n (settle) => {\n deliver = settle;\n if (early !== null) settle(early.value, early.cause);\n },\n (value, cause) => {\n settled = true;\n // the socket of a call that is not ok can hold a part of a response: it goes, and no later request gets it\n if (value.outcome !== \"ok\") sent.abort(cause ?? new Error(value.error));\n },\n );\n };\n\n const request = (given: HttpCall, sendOptions: SendOptions = {}): Promise<Sent<HttpResponse>> => {\n // the headers of the context of the caller, read now: each try of the call sends the same ones\n const call = options.callContext === undefined ? given : { ...given, headers: { ...options.callContext.headers(), ...given.headers } };\n const method = call.method.toUpperCase();\n const named = call.operation ?? method;\n return sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[named],\n options: sendOptions,\n attempt: (signal) => attempt({ ...call, method }, signal),\n onReissue: () => record(\"command.reissue\", status, named),\n });\n };\n\n const handle: DependencyHandle = {\n async connect(signal) {\n record(\"status.connecting\", \"connecting\");\n agent = await create(agentOptions(spec));\n if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);\n // the check request opens the first socket of the pool. A server that is down does not stop the\n // startup: the checks keep readiness tripped until a connect succeeds (readiness is earned)\n await request(check, { signal, reissue: false });\n },\n async close() {\n const a = agent;\n if (a === null || closing()) return;\n record(\"close.request\", \"closing\");\n for (const stop of [...waiting]) stop(\"the client closed before the request left\");\n // the agent has no close that waits: the client waits for its calls in flight, in its bound\n if (!(await withinBound(clock, ms(knobs.close_bound), flight.idle()))) {\n record(\"close.bound\");\n const open = a.sockets().length;\n flight.settleAll(\"the client closed with the request in flight\");\n a.destroy();\n record(\"close.destroy\", status, `open sockets: ${open}`);\n } else {\n // each free socket closes with a FIN\n a.destroy();\n }\n record(\"status.end\", \"end\");\n },\n };\n\n const declaration: Omit<Dependency, \"name\"> = {\n system: spec.system,\n knobs: {\n connect_bound: knobs.connect_bound,\n request_timeout: knobs.request_timeout,\n pool_idle_expiry: knobs.pool_idle_expiry,\n hint_buffer: knobs.hint_buffer,\n keepalive_idle: knobs.keepalive_idle,\n // the agent sends nothing on a free socket, thus its keepalive is the only refresh of an idle flow (O03)\n idle_refresh_interval: knobs.keepalive_idle,\n max_connection_age: knobs.max_connection_age,\n close_bound: knobs.close_bound,\n retrans_giveup_time: knobs.retrans_giveup_time,\n },\n operations,\n };\n\n const checks = (checkOptions: CheckOptions) =>\n stepChecks<ClientStep>(name, checkOptions, {\n // the outcome of the last connect of a socket, without a round trip\n \"local-state\": localStateCheck(() => status === \"ready\"),\n // the check request through the pool of the application. A status of 500 or more fails it\n \"round-trip\": roundTripCheck(async (sendOptions) => {\n const sent = await request(check, sendOptions);\n return sent.outcome === \"ok\" && sent.value.status >= 500\n ? { outcome: \"error\", error: `the server answered ${sent.value.status}`, reply: true, attempts: sent.attempts }\n : sent;\n }),\n // a new connection each time, with OPTIONS *\n dial: dialCheck(dial, spec.host, spec.port),\n });\n\n return {\n name,\n declaration,\n handle,\n meets: httpClientMeetings(name, knobs),\n get status() {\n return status;\n },\n joins,\n request,\n checks,\n attach: (svc, checkOptions) => attachClient(svc, name, declaration, handle, checks(checkOptions)),\n problems(description) {\n // O01: the pool must close an idle socket before the server does\n const idle = idleCloseProblem(name, knobs.pool_idle_expiry, knobs.server_idle_close);\n return [...clientProblems(name, description, clientBounds(knobs)), ...(idle === null ? [] : [idle])];\n },\n };\n};\n"],"mappings":";;;;;;;;;;AAqFA,MAAa,eAA6B;CAAE,QAAQ;CAAW,MAAM;AAAI;;;;;AAkDzE,MAAa,kBAAuD;CAClE,KAAK,EAAE,YAAY,KAAK;CACxB,MAAM,EAAE,YAAY,KAAK;CACzB,SAAS,EAAE,YAAY,KAAK;CAC5B,OAAO,EAAE,YAAY,KAAK;CAC1B,KAAK,EAAE,YAAY,KAAK;CACxB,QAAQ,EAAE,YAAY,KAAK;CAC3B,MAAM,EAAE,YAAY,MAAM;CAC1B,OAAO,EAAE,YAAY,MAAM;AAC7B;;AAGA,MAAa,gBAAgB,MAAc,SAAmC;CAC5E,MAAM,EAAE,UA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O,WAAW;GAC7C,OAAO,KAAK,YAAY,QAAQ,KAAK,MAAM,UAAU,MACjD;IAAE,SAAS;IAAS,OAAO,uBAAuB,KAAK,MAAM;IAAU,OAAO;IAAM,UAAU,KAAK;GAAS,IAC5G;EACN,CAAC;EAED,MAAM,UAAU,MAAM,KAAK,MAAM,KAAK,IAAI;CAC5C,CAAC;CAEH,OAAO;EACL;EACA;EACA;EACA,OAAO,mBAAmB,MAAM,KAAK;EACrC,IAAI,SAAS;GACX,OAAO;EACT;EACA;EACA;EACA;EACA,SAAS,KAAK,iBAAiB,aAAa,KAAK,MAAM,aAAa,QAAQ,OAAO,YAAY,CAAC;EAChG,SAAS,aAAa;GAEpB,MAAM,OAAO,iBAAiB,MAAM,MAAM,kBAAkB,MAAM,iBAAiB;GACnF,OAAO,CAAC,GAAG,eAAe,MAAM,aAAa,aAAa,KAAK,CAAC,GAAG,GAAI,SAAS,OAAO,CAAC,IAAI,CAAC,IAAI,CAAE;EACrG;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../../src/http-client/client.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport type { CallContext } from \"../call-context.ts\";\nimport type { Cancel } from \"../clock.ts\";\nimport { realClock } from \"../clock.ts\";\nimport type { Attempt, CheckOptions, Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, SendOptions, Sent } from \"../client/core.ts\";\nimport {\n ageProblems,\n attachClient,\n clientBounds,\n clientProblems,\n clientRecorder,\n dialCheck,\n idleCloseProblem,\n inFlight,\n keepaliveOnProblems,\n localStateCheck,\n message,\n ms,\n notSent,\n operationTable,\n poolProblems,\n roundTripCheck,\n sendWithReissue,\n socketEnds,\n stepChecks,\n timeProblems,\n trackWithTimer,\n wholeProblems,\n withinBound,\n wrapperTimerProblems,\n zeroProblems,\n} from \"../client/core.ts\";\nimport type { Judge } from \"../client/dial.ts\";\nimport { authority, helloDial, statusLineJudge } from \"../client/dial.ts\";\nimport type { Dependency } from \"../description.ts\";\nimport type { DependencyHandle } from \"../lifecycle.ts\";\nimport type { Operation } from \"../operation.ts\";\nimport type { AgentExchange, AgentFactory, HttpAgent, HttpAgentOptions, HttpResponse, HttpSocket } from \"./connection.ts\";\nimport { nodeAgent } from \"./connection.ts\";\nimport { httpClientMeetings } from \"./meets.ts\";\n\n/**\n * These are the knobs of the client, each a time, by the names of the ordering law where the law\n * has them. The runtime has no defaults, thus each knob is necessary. The constant\n * `HTTP_CLIENT_STARTING_KNOBS` gives a declaration from the HTTP cells. The knobs that each client has come from the core.\n */\nexport interface HttpClientKnobs extends ClientKnobs {\n /** This time bounds the TCP connect of a new socket. The wrapper has this timer, because the agent has none. */\n readonly connect_bound: Quantity;\n /**\n * This time bounds each call: from its start until the end of the body of its response. It also\n * bounds the wait for a socket. The wrapper has this timer, because the agent has none.\n */\n readonly request_timeout: Quantity;\n /**\n * This time is the free socket timer of the agent (`timeout`). The agent closes a free socket at the\n * smaller of this time and the hint of the server less `hint_buffer`. It must be below `server_idle_close` (O01).\n */\n readonly pool_idle_expiry: Extent;\n /** This time is what the agent subtracts from the hint of the server (`agentKeepAliveTimeoutBuffer`). A hint at or below it gives no reuse. */\n readonly hint_buffer: Quantity;\n /**\n * This time is when the server closes an idle connection, after its response. A Node server closes\n * at `keepAliveTimeout` plus `keepAliveTimeoutBuffer`. \"infinite\" is a server that keeps an idle\n * connection with no bound. The client does not set it: `problems` compares it with `pool_idle_expiry` (O01).\n */\n readonly server_idle_close: Extent;\n /** This time is the idle time of TCP keepalive (`keepAliveMsecs`), in whole seconds. The agent always turns keepalive on. */\n readonly keepalive_idle: Extent;\n /** The agent does not replace a connection at an age, thus this knob must be \"infinite\". */\n readonly max_connection_age: Extent;\n /** This time bounds the close of the client: the wait for the calls in flight, then a destroy of each socket. */\n readonly close_bound: Quantity;\n}\n\n/** A check request is the request of the round-trip check, and of the first connection at the connect. */\nexport interface CheckRequest {\n readonly method: string;\n readonly path: string;\n}\n\n/**\n * This request asks about the server, not about a resource (RFC 9110 §9.3.7). Thus it changes no\n * state. A server that does not route it still answers with a status, and the status tells that it is alive.\n */\nexport const OPTIONS_STAR: CheckRequest = { method: \"OPTIONS\", path: \"*\" };\n\n/** An HTTP client spec is the declaration of one HTTP client: the origin that it connects to, its pool, and its knobs. */\nexport interface HttpClientSpec extends ClientSpec<HttpClientKnobs> {\n /** This count is the most sockets of the pool (`maxSockets`). It is also the most free sockets. */\n readonly pool: { readonly max: number };\n /** This request is the request of the round-trip check and of the first connection. Without it, the client uses `OPTIONS *`. */\n readonly check?: CheckRequest | undefined;\n /**\n * These operations add to the table of the client, or change it. The table names each method by\n * its idempotency in RFC 9110. A caller can name an operation of its own, for example a POST with an `Idempotency-Key`.\n */\n readonly operations?: Readonly<Record<string, Operation>> | undefined;\n}\n\n/** These options make a client. Without them, it uses the agent of Node, the real clock, and a dial with `OPTIONS *`. */\nexport interface HttpClientOptions extends ClientOptions<AgentFactory> {\n /**\n * With this call context, each request gets the headers of the active context of its caller, for\n * example `traceparent`. A header of the call with the same name stays. `callContext` of the entry `/otel` gives one.\n */\n readonly callContext?: CallContext | undefined;\n}\n\n/** An HTTP call is one request. A string body goes as UTF-8, with its `content-length`. */\nexport interface HttpCall {\n readonly method: string;\n readonly path: string;\n readonly headers?: Readonly<Record<string, string>> | undefined;\n readonly body?: string | Uint8Array | undefined;\n /** This name is the operation of the call in the table. Without it, the operation is the method. */\n readonly operation?: string | undefined;\n}\n\n/** An HTTP client is a dependency of a service: its declaration, its handle, its checks and its requests. */\nexport interface HttpClient extends Client<ClientStep, ClientJoin> {\n /** This text is the state of the client, as `HTTP_CLIENT_MACHINE` names it. */\n readonly status: string;\n /**\n * This method sends a request, and gives its outcome in three values. A whole response of each\n * status is `ok`. The client sends again only an idempotent operation, one time at most, after an\n * outcome that is not certain. The second try stays in the bound of the request.\n */\n request(call: HttpCall, options?: SendOptions): Promise<Sent<HttpResponse>>;\n}\n\n/**\n * These operations are the methods of HTTP, by their idempotency in RFC 9110 §9.2.2. A second\n * request of GET, HEAD, OPTIONS, TRACE, PUT or DELETE has the same effect as one. POST and PATCH do not.\n */\nexport const HTTP_OPERATIONS: Readonly<Record<string, Operation>> = {\n GET: { idempotent: true },\n HEAD: { idempotent: true },\n OPTIONS: { idempotent: true },\n TRACE: { idempotent: true },\n PUT: { idempotent: true },\n DELETE: { idempotent: true },\n POST: { idempotent: false },\n PATCH: { idempotent: false },\n};\n\n/** This function gives the problems of a spec: the knobs that the agent cannot use. */\nexport const specProblems = (name: string, spec: HttpClientSpec): string[] => {\n const { knobs } = spec;\n const problems = [\n ...timeProblems(name, knobs),\n // the agent has no timer of a connect or of a call\n ...wrapperTimerProblems(name, knobs, { connect_bound: \"a connect\", request_timeout: \"a call\" }),\n // the agent reads a timeout of 0 as no free socket timer, and then the hint of the server does not apply\n ...zeroProblems(name, \"the agent\", knobs, { bounded: [\"pool_idle_expiry\"] }),\n ...keepaliveOnProblems(name, knobs, \"the agent\"),\n // Node truncates the keepalive delay to whole seconds\n ...wholeProblems(name, knobs, { millis: [\"connect_bound\", \"request_timeout\", \"pool_idle_expiry\", \"hint_buffer\"], seconds: [\"keepalive_idle\"] }),\n ...poolProblems(name, { max: spec.pool.max, min: 0 }),\n ...ageProblems(name, knobs, \"the agent does not replace a connection at an age\"),\n ];\n if (!Number.isFinite(ms(knobs.hint_buffer))) problems.push(`${name}'s hint_buffer is not a finite time: the agent subtracts it from the hint of the server`);\n return problems;\n};\n\n/** This function gives the options of `new http.Agent` from a spec. Each timer of the agent comes from the declaration. */\nexport const agentOptions = (spec: HttpClientSpec): HttpAgentOptions => {\n const { knobs } = spec;\n return {\n keepAlive: true,\n timeout: ms(knobs.pool_idle_expiry),\n agentKeepAliveTimeoutBuffer: ms(knobs.hint_buffer),\n keepAliveMsecs: ms(knobs.keepalive_idle),\n maxSockets: spec.pool.max,\n maxFreeSockets: spec.pool.max,\n scheduling: \"lifo\",\n };\n};\n\n/** This function gives the bytes of the dial: `OPTIONS *` with the Host header, and a close after the answer. */\nexport const optionsRequest = (host: string, port: number): string => `OPTIONS * HTTP/1.1\\r\\nHost: ${authority(host, port)}\\r\\nConnection: close\\r\\n\\r\\n`;\n\n/** This judge reads the status line of the answer. Any status passes, because it tells that an HTTP server answered. */\nexport const statusJudge: Judge = statusLineJudge(() => null);\n\n/** This dial function opens a TCP connection, sends `OPTIONS *`, and waits for the status line. It changes no state on the server. */\nexport const httpDial: DialFn = (host, port, signal) => helloDial(optionsRequest(host, port), statusJudge)(host, port, signal);\n\n/**\n * This function makes an HTTP client, a dependency of a service over an `http.Agent` of Node.\n * - It sets each timer of the agent from the declaration. The agent sends no request again by itself,\n * and the client sends again only an idempotent operation of its table.\n * - Its call is a request until the end of the body of its response. The wrapper has a timer for the\n * connect and one for the call, because the agent has none.\n * - It tells the outcome of a call in three values. A request that did not get a connected socket\n * did not leave the client. A failure after that is not certain.\n * - It destroys the socket of each call that is not `ok`, thus no later request gets that socket.\n * - It records each new socket of the pool (D1). HTTP gives no id of a connection.\n *\n * The core of the clients gives the outcomes, the second try, the calls in flight and the timer of a\n * call. It also gives the bounded close and the checks. This entry gives what the agent does in its own way.\n */\nexport const httpClient = (name: string, spec: HttpClientSpec, options: HttpClientOptions = {}): HttpClient => {\n const problems = specProblems(name, spec);\n if (problems.length > 0) throw new Error(problems.join(\"; \"));\n const { knobs } = spec;\n const clock = options.clock ?? realClock;\n const create = options.create ?? nodeAgent;\n const dial = options.dial ?? httpDial;\n const operations = operationTable(HTTP_OPERATIONS, spec.operations);\n const requestTimeout = ms(knobs.request_timeout);\n const connectBound = ms(knobs.connect_bound);\n const check = spec.check ?? OPTIONS_STAR;\n\n let agent: HttpAgent | null = null;\n let status = \"none\";\n const joins: ClientJoin[] = [];\n // the calls that left the client: the close waits for them, in its bound\n const flight = inFlight();\n // the calls that did not leave the client: the close ends each one as not sent\n const waiting = new Set<(error: string) => void>();\n\n const emit = clientRecorder(options.record, clock, name);\n // the state of the client is the outcome of the last connect of a socket of its pool\n const record = (on: string, to: string = status, detail?: string): void => {\n const from = status;\n status = to;\n emit(from, to, on, detail);\n };\n const closing = (): boolean => status === \"closing\" || status === \"end\";\n\n /**\n * This function makes one try of a call. The try waits for a socket of the agent: a free one, or a\n * new one in `connect_bound`. A failure before the socket is ready is certain: the request did not\n * leave the client. After that, the try waits for the whole response in the rest of `request_timeout`.\n */\n const attempt = async (call: HttpCall, signal: AbortSignal | undefined): Promise<Attempt<HttpResponse>> => {\n const a = agent;\n if (a === null) return notSent(`${name} has not connected`);\n if (closing()) return notSent(`${name} is ${status}: the request did not leave the client`);\n if (signal?.aborted) return notSent(\"the caller aborted the request before it left the client\");\n const started = clock.now();\n const body = typeof call.body === \"string\" ? Buffer.from(call.body, \"utf8\") : call.body;\n const headers = { ...call.headers, ...(body === undefined ? {} : { \"content-length\": String(body.byteLength) }) };\n\n let socket: HttpSocket | undefined;\n let reused = false;\n let left = false;\n // true when the wrapper ended the try itself: the error of the agent that follows is not a failed connect\n let ending = false;\n let connectTimer: Cancel = () => {};\n let decide: (value: true | Attempt<never>) => void = () => {};\n const leaving = new Promise<true | Attempt<never>>((resolve) => {\n let decided = false;\n decide = (value) => {\n if (decided) return;\n decided = true;\n resolve(value);\n };\n });\n // a result of the agent that arrives before the try records it\n let deliver: ((value: Attempt<HttpResponse>, cause?: Error) => void) | null = null;\n let early: { readonly value: Attempt<HttpResponse>; readonly cause: Error | undefined } | null = null;\n let settled = false;\n const settleWith = (value: Attempt<HttpResponse>, cause?: Error): void => {\n if (deliver === null) early ??= { value, cause };\n else deliver(value, cause);\n };\n\n let exchange: AgentExchange | null = null;\n const stop = (text: string): void => {\n if (left) return;\n ending = true;\n connectTimer();\n exchange?.abort(new Error(text));\n decide(notSent(text));\n };\n const ready = (): void => {\n left = true;\n connectTimer();\n decide(true);\n };\n exchange = a.request(\n { host: spec.host, port: spec.port, method: call.method, path: call.path, headers, body },\n {\n socket(given, isReused) {\n socket = given;\n reused = isReused;\n if (isReused) {\n ready();\n return;\n }\n // the request awaits its connection, thus this bound keeps the process alive (SYS-126)\n connectTimer = clock.after(connectBound, () => {\n if (left) return;\n record(\"connect.failed\", closing() ? status : \"failing\", \"no connection in connect_bound\");\n stop(\"no connection in connect_bound: the request did not leave the client\");\n });\n },\n connect() {\n const generation = joins.length + 1;\n joins.push({ generation, at: clock.now(), ...socketEnds(socket) });\n record(\"join\", closing() ? status : \"ready\", `socket ${generation}`);\n ready();\n },\n },\n );\n // the agent can fail a request in its queue or at its connect: it did not leave the client\n exchange.response.then(\n (response) => settleWith({ outcome: \"ok\", value: response }),\n (error: unknown) => {\n const cause = error instanceof Error ? error : new Error(message(error));\n if (!left) {\n connectTimer();\n if (!ending) record(\"connect.failed\", closing() ? status : \"failing\", message(error));\n decide(notSent(message(error)));\n return;\n }\n // the abort of the wrapper after the call settled is not a failure of the socket\n if (settled) return;\n // a reused socket that fails before the response: the server closed it, as in the keep-alive race\n if (reused) record(\"reuse.failed\", status, message(error));\n settleWith({ outcome: \"indeterminate\", error: message(error) }, cause);\n },\n );\n\n const abandoned = (): void => stop(\"the caller abandoned the request before it left the client\");\n signal?.addEventListener(\"abort\", abandoned, { once: true });\n // the caller awaits the request, thus this bound keeps the process alive (SYS-126)\n const queued = clock.after(requestTimeout, () => stop(\"no socket in request_timeout: the request did not leave the client\"));\n waiting.add(stop);\n const got = await leaving;\n signal?.removeEventListener(\"abort\", abandoned);\n queued();\n waiting.delete(stop);\n if (got !== true) return got;\n\n const sent = exchange;\n return trackWithTimer<HttpResponse>(\n flight,\n clock,\n Math.max(0, requestTimeout - (clock.now() - started)),\n signal,\n \"the caller abandoned the request after it left the client\",\n \"no whole response in request_timeout: the server can have the request\",\n (settle) => {\n deliver = settle;\n if (early !== null) settle(early.value, early.cause);\n },\n (value, cause) => {\n settled = true;\n // the socket of a call that is not ok can hold a part of a response: it goes, and no later request gets it\n if (value.outcome !== \"ok\") sent.abort(cause ?? new Error(value.error));\n },\n );\n };\n\n const request = (given: HttpCall, sendOptions: SendOptions = {}): Promise<Sent<HttpResponse>> => {\n // the headers of the context of the caller, read now: each try of the call sends the same ones\n const call = options.callContext === undefined ? given : { ...given, headers: { ...options.callContext.headers(), ...given.headers } };\n const method = call.method.toUpperCase();\n const named = call.operation ?? method;\n return sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[named],\n options: sendOptions,\n attempt: (signal) => attempt({ ...call, method }, signal),\n onReissue: () => record(\"command.reissue\", status, named),\n });\n };\n\n const handle: DependencyHandle = {\n async connect(signal) {\n record(\"status.connecting\", \"connecting\");\n agent = await create(agentOptions(spec));\n if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);\n // the check request opens the first socket of the pool. A server that is down does not stop the\n // startup: the checks keep readiness tripped until a connect succeeds (readiness is earned)\n await request(check, { signal, reissue: false });\n },\n async close() {\n const a = agent;\n if (a === null || closing()) return;\n record(\"close.request\", \"closing\");\n for (const stop of [...waiting]) stop(\"the client closed before the request left\");\n // the agent has no close that waits: the client waits for its calls in flight, in its bound\n if (!(await withinBound(clock, ms(knobs.close_bound), flight.idle()))) {\n record(\"close.bound\");\n const open = a.sockets().length;\n flight.settleAll(\"the client closed with the request in flight\");\n a.destroy();\n record(\"close.destroy\", status, `open sockets: ${open}`);\n } else {\n // each free socket closes with a FIN\n a.destroy();\n }\n record(\"status.end\", \"end\");\n },\n };\n\n const declaration: Omit<Dependency, \"name\"> = {\n system: spec.system,\n knobs: {\n connect_bound: knobs.connect_bound,\n request_timeout: knobs.request_timeout,\n pool_idle_expiry: knobs.pool_idle_expiry,\n hint_buffer: knobs.hint_buffer,\n keepalive_idle: knobs.keepalive_idle,\n // the agent sends nothing on a free socket, thus its keepalive is the only refresh of an idle flow (O03)\n idle_refresh_interval: knobs.keepalive_idle,\n max_connection_age: knobs.max_connection_age,\n close_bound: knobs.close_bound,\n retrans_giveup_time: knobs.retrans_giveup_time,\n },\n operations,\n };\n\n const checks = (checkOptions: CheckOptions) =>\n stepChecks<ClientStep>(name, checkOptions, {\n // the outcome of the last connect of a socket, without a round trip\n \"local-state\": localStateCheck(() => status === \"ready\"),\n // the check request through the pool of the application. A status of 500 or more fails it\n \"round-trip\": roundTripCheck(async (sendOptions) => {\n const sent = await request(check, sendOptions);\n return sent.outcome === \"ok\" && sent.value.status >= 500\n ? { outcome: \"error\", error: `the server answered ${sent.value.status}`, reply: true, attempts: sent.attempts }\n : sent;\n }),\n // a new connection each time, with OPTIONS *\n dial: dialCheck(dial, spec.host, spec.port),\n });\n\n return {\n name,\n declaration,\n handle,\n meets: httpClientMeetings(name, knobs),\n get status() {\n return status;\n },\n joins,\n request,\n checks,\n attach: (svc, checkOptions) => attachClient(svc, name, declaration, handle, checks(checkOptions)),\n problems(description) {\n // O01: the pool must close an idle socket before the server does\n const idle = idleCloseProblem(name, knobs.pool_idle_expiry, knobs.server_idle_close);\n return [...clientProblems(name, description, clientBounds(knobs)), ...(idle === null ? [] : [idle])];\n },\n };\n};\n"],"mappings":";;;;;;;;;;AAqFA,MAAa,eAA6B;CAAE,QAAQ;CAAW,MAAM;AAAI;;;;;AAkDzE,MAAa,kBAAuD;CAClE,KAAK,EAAE,YAAY,KAAK;CACxB,MAAM,EAAE,YAAY,KAAK;CACzB,SAAS,EAAE,YAAY,KAAK;CAC5B,OAAO,EAAE,YAAY,KAAK;CAC1B,KAAK,EAAE,YAAY,KAAK;CACxB,QAAQ,EAAE,YAAY,KAAK;CAC3B,MAAM,EAAE,YAAY,MAAM;CAC1B,OAAO,EAAE,YAAY,MAAM;AAC7B;;AAGA,MAAa,gBAAgB,MAAc,SAAmC;CAC5E,MAAM,EAAE,UAAU;CAClB,MAAM,WAAW;EACf,GAAG,aAAa,MAAM,KAAK;EAE3B,GAAG,qBAAqB,MAAM,OAAO;GAAE,eAAe;GAAa,iBAAiB;EAAS,CAAC;EAE9F,GAAG,aAAa,MAAM,aAAa,OAAO,EAAE,SAAS,CAAC,kBAAkB,EAAE,CAAC;EAC3E,GAAG,oBAAoB,MAAM,OAAO,WA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O;EACL;EACA;EACA;EACA,OAAO,mBAAmB,MAAM,KAAK;EACrC,IAAI,SAAS;GACX,OAAO;EACT;EACA;EACA;EACA;EACA,SAAS,KAAK,iBAAiB,aAAa,KAAK,MAAM,aAAa,QAAQ,OAAO,YAAY,CAAC;EAChG,SAAS,aAAa;GAEpB,MAAM,OAAO,iBAAiB,MAAM,MAAM,kBAAkB,MAAM,iBAAiB;GACnF,OAAO,CAAC,GAAG,eAAe,MAAM,aAAa,aAAa,KAAK,CAAC,GAAG,GAAI,SAAS,OAAO,CAAC,IAAI,CAAC,IAAI,CAAE;EACrG;CACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { realClock } from "../clock.js";
|
|
1
|
+
import { realClock, unrefClock } from "../clock.js";
|
|
2
2
|
import { ms, timeProblems, wrapperTimerProblems, zeroProblems } from "../client/core.js";
|
|
3
3
|
import { heartbeat } from "../heartbeat.js";
|
|
4
4
|
import { quantity } from "@mark1russell7/quantity";
|
|
@@ -31,7 +31,7 @@ const sessionCheck = (session, options) => {
|
|
|
31
31
|
interval: ms(knobs.keepalive_time),
|
|
32
32
|
timeout: ms(knobs.keepalive_timeout),
|
|
33
33
|
misses: 1,
|
|
34
|
-
clock,
|
|
34
|
+
clock: unrefClock(clock),
|
|
35
35
|
due: () => {
|
|
36
36
|
const quiet = !heardSince;
|
|
37
37
|
heardSince = false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","names":[],"sources":["../../src/http-client/session.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { quantity } from \"@mark1russell7/quantity\";\nimport type { Clock } from \"../clock.ts\";\nimport { realClock } from \"../clock.ts\";\nimport { ms, timeProblems, wrapperTimerProblems, zeroProblems } from \"../client/core.ts\";\nimport type { Heartbeat } from \"../heartbeat.ts\";\nimport { heartbeat } from \"../heartbeat.ts\";\n\n/**\n * These are the knobs of the session check of an HTTP/2 client. They have the names and the units of\n * the gRPC client, because the check is the same PING. The grpc-js driver ends its transport at the first PING with no ACK.\n */\nexport interface SessionCheckKnobs {\n /**\n * This time is the quiet interval of a session. A tick comes at each interval, and it sends a PING\n * when the session heard nothing since the last tick. \"infinite\" sends no PING.\n */\n readonly keepalive_time: Extent;\n /** This time bounds the ACK of each PING. With no ACK in it, the check closes the session. */\n readonly keepalive_timeout: Quantity;\n}\n\n/**\n * A session is the part of an HTTP/2 session that the check uses. A `ClientHttp2Session` of\n * `node:http2` has each member, thus the check does not load `node:http2`.\n */\nexport interface H2Session {\n /** This flag is true until the socket of the session connects. */\n readonly connecting: boolean;\n /** This method sends a PING. The callback gets null at the ACK, and an error otherwise. It gives false when the PING did not go. */\n ping(callback: (error: Error | null) => void): boolean;\n /** This method ends the session and each stream on it at once. */\n destroy(error?: Error): void;\n}\n\n/** A close is the part of the check that closed the session. */\nexport type SessionClose = \"stream timeout\" | \"no PING answer\";\n\n/** These options make a session check. */\nexport interface SessionCheckOptions {\n readonly knobs: SessionCheckKnobs;\n /**\n * True lets a quiet session with no stream get a PING, as the option of the gRPC client does.\n * The default is false: a server can refuse a PING with no stream (O26).\n */\n readonly keepaliveWithoutCalls?: boolean | undefined;\n /** This clock gives the ticks and the timeouts. The default is `realClock`. */\n readonly clock?: Clock | undefined;\n /** This function receives the close of the session by the check, with its cause. */\n readonly onClose?: ((cause: SessionClose) => void) | undefined;\n}\n\n/**\n * A session check closes an HTTP/2 session that stopped answering. The caller tells it of each\n * stream and of each frame from the peer. The next stream of the caller then opens a new session.\n */\nexport interface SessionCheck {\n /** This method tells the check that a stream started on the session. */\n opened(): void;\n /** This method tells the check that a stream ended with an answer or an error. */\n ended(): void;\n /** This method tells the check that a stream ended at its timeout. The check then closes the session. */\n timedOut(): void;\n /** This method tells the check that a frame came from the peer, for example a response or the SETTINGS of the peer. */\n heard(): void;\n /** This method stops the check, and the session stays. A second use does nothing. */\n stop(): void;\n /** This count is the streams in flight on the session. */\n readonly streams: number;\n /** This cause is why the check closed the session, or null while it did not. */\n readonly closed: SessionClose | null;\n}\n\n/** This code is on the error that ends each stream of a session that the check closes. */\nexport const SESSION_CHECK_CLOSE = \"ERR_SESSION_CHECK\";\n\n/**\n * This function starts the check of one HTTP/2 session. It has two parts:\n * - A stream that times out closes its session, and not only the stream. On HTTP/1.1, a request\n * that times out destroys its socket. On HTTP/2, the session is the connection.\n * - The heartbeat of the package sends a PING after a quiet interval. With no ACK in\n * `keepalive_timeout`, it closes the session.\n *\n * A session that has not connected cannot answer a PING. Thus its tick waits for the SETTINGS of the\n * peer through `heard()`, in `keepalive_timeout`.\n */\nexport const sessionCheck = (session: H2Session, options: SessionCheckOptions): SessionCheck => {\n const { knobs, keepaliveWithoutCalls = false, clock = realClock } = options;\n let streams = 0;\n let heardSince = false;\n let closed: SessionClose | null = null;\n\n const close = (cause: SessionClose, why: string): void => {\n if (closed !== null) return;\n closed = cause;\n beat.stop();\n session.destroy(Object.assign(new Error(`the session check closed the session: ${why}`), { code: SESSION_CHECK_CLOSE }));\n options.onClose?.(cause);\n };\n\n const beat: Heartbeat = heartbeat({\n interval: ms(knobs.keepalive_time),\n timeout: ms(knobs.keepalive_timeout),\n misses: 1,\n clock,\n due: () => {\n const quiet = !heardSince;\n heardSince = false;\n return closed === null && quiet && (keepaliveWithoutCalls || streams > 0);\n },\n ping: () => {\n // the answer of a session that connects is the SETTINGS of the peer, through heard()\n if (session.connecting) return undefined;\n return new Promise<boolean>((resolve) => {\n try {\n if (!session.ping((error) => resolve(error === null))) resolve(false);\n } catch {\n resolve(false);\n }\n });\n },\n onDead: () => close(\"no PING answer\", \"no PING ACK in keepalive_timeout\"),\n });\n\n return {\n opened() {\n streams += 1;\n },\n ended() {\n streams = Math.max(0, streams - 1);\n },\n timedOut() {\n streams = Math.max(0, streams - 1);\n close(\"stream timeout\", \"a stream timed out\");\n },\n heard() {\n heardSince = true;\n beat.answer();\n },\n stop() {\n beat.stop();\n },\n get streams() {\n return streams;\n },\n get closed() {\n return closed;\n },\n };\n};\n\n/**\n * This function gives the most time from the last frame of the peer to the close of a session by the\n * PING. The first quiet tick comes up to two intervals after that frame, and its PING then waits\n * `keepalive_timeout`. \"infinite\" is a check with no PING. Then only a stream timeout closes the session.\n */\nexport const sessionCheckDetection = (knobs: SessionCheckKnobs): Extent =>\n knobs.keepalive_time.value === \"infinite\"\n ? { value: \"infinite\", unit: \"s\" }\n : quantity((2 * ms(knobs.keepalive_time) + ms(knobs.keepalive_timeout)) / 1000, \"s\");\n\n/**\n * This function gives the problems of the knobs of a session check. Each knob is a time of zero or\n * more. `keepalive_time` is \"infinite\" for no PING, and not zero. `keepalive_timeout` is a finite time\n * above zero, because the check is the only bound of the PING.\n */\nexport const sessionCheckProblems = (name: string, knobs: SessionCheckKnobs): string[] => {\n const times = timeProblems(name, knobs);\n if (times.length > 0) return times;\n return [\n ...zeroProblems(name, \"the session check\", knobs, { open: [\"keepalive_time\"] }),\n ...wrapperTimerProblems(name, knobs, { keepalive_timeout: \"a PING\" }),\n ];\n};\n"],"mappings":";;;;;;AA0EA,MAAa,sBAAsB;;;;;;;;;;;AAYnC,MAAa,gBAAgB,SAAoB,YAA+C;CAC9F,MAAM,EAAE,OAAO,wBAAwB,OAAO,QAAQ,cAAc;CACpE,IAAI,UAAU;CACd,IAAI,aAAa;CACjB,IAAI,SAA8B;CAElC,MAAM,SAAS,OAAqB,QAAsB;EACxD,IAAI,WAAW,MAAM;EACrB,SAAS;EACT,KAAK,KAAK;EACV,QAAQ,QAAQ,OAAO,uBAAO,IAAI,MAAM,yCAAyC,KAAK,GAAG,EAAE,MAAM,oBAAoB,CAAC,CAAC;EACvH,QAAQ,UAAU,KAAK;CACzB;CAEA,MAAM,OAAkB,UAAU;EAChC,UAAU,GAAG,MAAM,cAAc;EACjC,SAAS,GAAG,MAAM,iBAAiB;EACnC,QAAQ;
|
|
1
|
+
{"version":3,"file":"session.js","names":[],"sources":["../../src/http-client/session.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { quantity } from \"@mark1russell7/quantity\";\nimport type { Clock } from \"../clock.ts\";\nimport { realClock, unrefClock } from \"../clock.ts\";\nimport { ms, timeProblems, wrapperTimerProblems, zeroProblems } from \"../client/core.ts\";\nimport type { Heartbeat } from \"../heartbeat.ts\";\nimport { heartbeat } from \"../heartbeat.ts\";\n\n/**\n * These are the knobs of the session check of an HTTP/2 client. They have the names and the units of\n * the gRPC client, because the check is the same PING. The grpc-js driver ends its transport at the first PING with no ACK.\n */\nexport interface SessionCheckKnobs {\n /**\n * This time is the quiet interval of a session. A tick comes at each interval, and it sends a PING\n * when the session heard nothing since the last tick. \"infinite\" sends no PING.\n */\n readonly keepalive_time: Extent;\n /** This time bounds the ACK of each PING. With no ACK in it, the check closes the session. */\n readonly keepalive_timeout: Quantity;\n}\n\n/**\n * A session is the part of an HTTP/2 session that the check uses. A `ClientHttp2Session` of\n * `node:http2` has each member, thus the check does not load `node:http2`.\n */\nexport interface H2Session {\n /** This flag is true until the socket of the session connects. */\n readonly connecting: boolean;\n /** This method sends a PING. The callback gets null at the ACK, and an error otherwise. It gives false when the PING did not go. */\n ping(callback: (error: Error | null) => void): boolean;\n /** This method ends the session and each stream on it at once. */\n destroy(error?: Error): void;\n}\n\n/** A close is the part of the check that closed the session. */\nexport type SessionClose = \"stream timeout\" | \"no PING answer\";\n\n/** These options make a session check. */\nexport interface SessionCheckOptions {\n readonly knobs: SessionCheckKnobs;\n /**\n * True lets a quiet session with no stream get a PING, as the option of the gRPC client does.\n * The default is false: a server can refuse a PING with no stream (O26).\n */\n readonly keepaliveWithoutCalls?: boolean | undefined;\n /** This clock gives the ticks and the timeouts. The default is `realClock`. */\n readonly clock?: Clock | undefined;\n /** This function receives the close of the session by the check, with its cause. */\n readonly onClose?: ((cause: SessionClose) => void) | undefined;\n}\n\n/**\n * A session check closes an HTTP/2 session that stopped answering. The caller tells it of each\n * stream and of each frame from the peer. The next stream of the caller then opens a new session.\n */\nexport interface SessionCheck {\n /** This method tells the check that a stream started on the session. */\n opened(): void;\n /** This method tells the check that a stream ended with an answer or an error. */\n ended(): void;\n /** This method tells the check that a stream ended at its timeout. The check then closes the session. */\n timedOut(): void;\n /** This method tells the check that a frame came from the peer, for example a response or the SETTINGS of the peer. */\n heard(): void;\n /** This method stops the check, and the session stays. A second use does nothing. */\n stop(): void;\n /** This count is the streams in flight on the session. */\n readonly streams: number;\n /** This cause is why the check closed the session, or null while it did not. */\n readonly closed: SessionClose | null;\n}\n\n/** This code is on the error that ends each stream of a session that the check closes. */\nexport const SESSION_CHECK_CLOSE = \"ERR_SESSION_CHECK\";\n\n/**\n * This function starts the check of one HTTP/2 session. It has two parts:\n * - A stream that times out closes its session, and not only the stream. On HTTP/1.1, a request\n * that times out destroys its socket. On HTTP/2, the session is the connection.\n * - The heartbeat of the package sends a PING after a quiet interval. With no ACK in\n * `keepalive_timeout`, it closes the session.\n *\n * A session that has not connected cannot answer a PING. Thus its tick waits for the SETTINGS of the\n * peer through `heard()`, in `keepalive_timeout`.\n */\nexport const sessionCheck = (session: H2Session, options: SessionCheckOptions): SessionCheck => {\n const { knobs, keepaliveWithoutCalls = false, clock = realClock } = options;\n let streams = 0;\n let heardSince = false;\n let closed: SessionClose | null = null;\n\n const close = (cause: SessionClose, why: string): void => {\n if (closed !== null) return;\n closed = cause;\n beat.stop();\n session.destroy(Object.assign(new Error(`the session check closed the session: ${why}`), { code: SESSION_CHECK_CLOSE }));\n options.onClose?.(cause);\n };\n\n const beat: Heartbeat = heartbeat({\n interval: ms(knobs.keepalive_time),\n timeout: ms(knobs.keepalive_timeout),\n misses: 1,\n // the session decides if it keeps the process alive: its owner can unref an idle session.\n // Thus the heartbeat does not keep the process alive (SYS-126)\n clock: unrefClock(clock),\n due: () => {\n const quiet = !heardSince;\n heardSince = false;\n return closed === null && quiet && (keepaliveWithoutCalls || streams > 0);\n },\n ping: () => {\n // the answer of a session that connects is the SETTINGS of the peer, through heard()\n if (session.connecting) return undefined;\n return new Promise<boolean>((resolve) => {\n try {\n if (!session.ping((error) => resolve(error === null))) resolve(false);\n } catch {\n resolve(false);\n }\n });\n },\n onDead: () => close(\"no PING answer\", \"no PING ACK in keepalive_timeout\"),\n });\n\n return {\n opened() {\n streams += 1;\n },\n ended() {\n streams = Math.max(0, streams - 1);\n },\n timedOut() {\n streams = Math.max(0, streams - 1);\n close(\"stream timeout\", \"a stream timed out\");\n },\n heard() {\n heardSince = true;\n beat.answer();\n },\n stop() {\n beat.stop();\n },\n get streams() {\n return streams;\n },\n get closed() {\n return closed;\n },\n };\n};\n\n/**\n * This function gives the most time from the last frame of the peer to the close of a session by the\n * PING. The first quiet tick comes up to two intervals after that frame, and its PING then waits\n * `keepalive_timeout`. \"infinite\" is a check with no PING. Then only a stream timeout closes the session.\n */\nexport const sessionCheckDetection = (knobs: SessionCheckKnobs): Extent =>\n knobs.keepalive_time.value === \"infinite\"\n ? { value: \"infinite\", unit: \"s\" }\n : quantity((2 * ms(knobs.keepalive_time) + ms(knobs.keepalive_timeout)) / 1000, \"s\");\n\n/**\n * This function gives the problems of the knobs of a session check. Each knob is a time of zero or\n * more. `keepalive_time` is \"infinite\" for no PING, and not zero. `keepalive_timeout` is a finite time\n * above zero, because the check is the only bound of the PING.\n */\nexport const sessionCheckProblems = (name: string, knobs: SessionCheckKnobs): string[] => {\n const times = timeProblems(name, knobs);\n if (times.length > 0) return times;\n return [\n ...zeroProblems(name, \"the session check\", knobs, { open: [\"keepalive_time\"] }),\n ...wrapperTimerProblems(name, knobs, { keepalive_timeout: \"a PING\" }),\n ];\n};\n"],"mappings":";;;;;;AA0EA,MAAa,sBAAsB;;;;;;;;;;;AAYnC,MAAa,gBAAgB,SAAoB,YAA+C;CAC9F,MAAM,EAAE,OAAO,wBAAwB,OAAO,QAAQ,cAAc;CACpE,IAAI,UAAU;CACd,IAAI,aAAa;CACjB,IAAI,SAA8B;CAElC,MAAM,SAAS,OAAqB,QAAsB;EACxD,IAAI,WAAW,MAAM;EACrB,SAAS;EACT,KAAK,KAAK;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,GAAG,OAAO;CAC7B,OAAO,CACL,GAAG,aAAa,MAAM,qBAAqB,OAAO,EAAE,MAAM,CAAC,gBAAgB,EAAE,CAAC,GAC9E,GAAG,qBAAqB,MAAM,OAAO,EAAE,mBAAmB,SAAS,CAAC,CACtE;AACF"}
|
package/build/index.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { DRAIN_RULE_IDS, STOPS, STOP_RULE, Stop, StopWay, lintStop } from "./sto
|
|
|
8
8
|
import { DRAIN_RULES, O04, O09, O10, O16 } from "./rules.js";
|
|
9
9
|
import { BOUND_RULES, CLOSE_BOUND_RULE, Claim, DECLARATION_RULE, Epochs, Finding, LAW_STATISTIC, LIMITER_RULES, NAME_RULE, PLATFORM_MARKS, PROGRESS_RULE, SERVICE_RULES, Scenario, ScenarioValue, ScopedChange, Statistic, UNIT_BOUND_RULE, compressionOf, lint, serviceBindings } from "./lint.js";
|
|
10
10
|
import { IDENTITY_TYPES, IdentityType } from "./identity.js";
|
|
11
|
-
import { Cancel, Clock, PlatformClockOptions, platformClock, realClock } from "./clock.js";
|
|
11
|
+
import { Cancel, Clock, PlatformClockOptions, platformClock, realClock, unrefClock } from "./clock.js";
|
|
12
12
|
import { Heartbeat, HeartbeatOptions, detectionTime, heartbeat } from "./heartbeat.js";
|
|
13
13
|
import { Backoff, DelayBand, Jitter, backoffBand, backoffDelay, backoffProblems } from "./backoff.js";
|
|
14
14
|
import { Retrier, RetrierOptions, RetryOptions, retrier, retry, retryAfterDelay } from "./retrier.js";
|
|
@@ -34,4 +34,4 @@ import { IterationContext, WorkerKnobs, WorkerLoop, WorkerLoopOptions, workerLoo
|
|
|
34
34
|
import { JobAction, JobContext, JobFailure, JobSettle, JobSource, QueueDrain, QueueDrainOptions, QueueKnobs, RedeliveryPolicy, RequeueCause, queueDrain, redeliverOnce } from "./queue.js";
|
|
35
35
|
import { EXIT_MACHINE, GATE_MACHINE, LATCH_MACHINE, MACHINES, POLLER_MACHINE, WATCHDOG_MACHINE, WINDOW_MACHINE, capKnob, drainMachine } from "./machines.js";
|
|
36
36
|
import { replay } from "@mark1russell7/algebra/replay";
|
|
37
|
-
export { type Allowed, BOUND_RULES, type Backoff, type Binding, type Bound, CLOSE_BOUND_RULE, type CalendarWindow, type CallContext, type Cancel, type CapacityRefused, type Change, type Check, type CheckFn, type CheckMetrics, type CheckVerdict, type Claim, type Clock, type Compressed, type Compression, type ConsoleLoggerOptions, type ConsoleTarget, type Controller, type ControllerBuilder, type CooperativeFloor, type Coupling, DECLARATION_RULE, DRAIN_RULES, DRAIN_RULE_IDS, DURATION_FRACTIONS, type Decision, type DelayBand, type Dependency, type DependencyHandle, type DurationHistogram, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, type EmbeddedProcess, type Episode, type Epochs, type Evaluated, type ExitCodes, type ExitSignal, type ExitTrigger, FORMAT, type FailsBy, type Finding, GATE_MACHINE, type Gate, type Health, type HealthMetrics, type HealthServer, type HealthVerdict, type Heartbeat, type HeartbeatOptions, type HostStream, IDENTITY_TYPES, type Idempotency, type IdentityType, type IncomingHeaders, type Inequality, type IterationContext, type Jitter, type JobAction, type JobContext, type JobFailure, type JobSettle, type JobSource, type KeyState, type KeyedLimiter, type KeyedQuota, LATCH_MACHINE, LAW_STATISTIC, LIMITER_RULES, LOG_LEVELS, type Lifecycle, type LifecycleEvent, type LifecycleState, type LimitPolicy, type LimitRule, type Limiter, type LimiterEviction, type LimiterSpec, type LimiterState, type LimiterStore, type LimiterStoreSpec, type LocalLimiter, type LogEntry, type LogFields, type LogFormat, type LogLevel, type Logger, MACHINES, type MachineName, type MemoryQuotaStore, type MemoryStore, type MessageShape, type MessageTrigger, NAME_RULE, O04, O09, O10, O16, type Operation, type OperationOf, type Outcome, PLATFORM_MARKS, POLLER_MACHINE, PROCESS_TRIGGERS, PROGRESS_RULE, type Phase, type PhaseContext, type PhaseWork, type PlatformClockOptions, type PodTiming, type Poll, type ProbeAnswer, type ProbeKind, type ProcessHost, type ProcessPort, type ProcessTrigger, type Profile, type ProgressMarks, type QueueDrain, type QueueDrainOptions, type QueueKnobs, type QuotaAllowed, type QuotaAnswer, type QuotaCapacityRefused, type QuotaChange, type QuotaEvent, type QuotaPart, type QuotaReading, type QuotaRecord, type QuotaRefused, type QuotaRule, type QuotaSpec, type QuotaState, type QuotaStep, type QuotaStore, type QuotaTakeStep, type QuotaVerdict, type QuotaWaitRefused, type QuotaWindow, type QuotasVerdict, type Recorder, type RedeliveryPolicy, type RefusalCause, type Refused, type RepeatSignal, type RequestEnd, type RequestEvent, type RequestFn, type RequestOptions, type RequestStream, type RequestWork, type RequeueCause, type Result, type Retrier, type RetrierOptions, type RetryOptions, type RollingWindow, type RoutePattern, type RouteRequest, type Rule, type RunOptions, SERVICE_RULES, SLIDING_WINDOW_MACHINE, STAGES, STOPS, STOP_RULE, type Scenario, type ScenarioValue, type ScopedChange, type ServiceBuilder, type ServiceDescription, type ShutdownOptions, type Side, type SlidingWindow, type Span, type Stage, type StartOptions, type Statistic, type Step, type Stop, type StopWay, type StoreFailure, TOKEN_BUCKET_MACHINE, type TakeQuotasOptions, type TakeRequest, type TakeStep, type Term, type TimerMark, type TimerMarks, type Timing, type TokenBucket, type TraceIds, type TraceIdsSource, type Transport, type TransportImpl, UNCAUGHT_ORIGINS, UNIT_BOUND_RULE, type UncaughtOptions, type UncaughtOrigin, type UnitRequest, type Verdict, WATCHDOG_MACHINE, WINDOW_MACHINE, type WaitCause, type WaitRefused, type Watchdog, type WatchdogSpec, type WorkerKnobs, type WorkerLoop, type WorkerLoopOptions, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capKnob, capacityOf, compress, compression, compressionOf, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, drainMachine, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, keyedQuota, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, lint, lintStop, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryQuotaStore, memoryStore, nodeProcess, overCapacity, platformClock, processPortOf, queueDrain, quotaProblems, quotaRule, quotaStep, realClock, recoverSpan, redact, redeliverOnce, replay, retrier, retry, retryAfterDelay, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, takeQuotas, unitsOf, verdictOf, watchdog, workerLoop };
|
|
37
|
+
export { type Allowed, BOUND_RULES, type Backoff, type Binding, type Bound, CLOSE_BOUND_RULE, type CalendarWindow, type CallContext, type Cancel, type CapacityRefused, type Change, type Check, type CheckFn, type CheckMetrics, type CheckVerdict, type Claim, type Clock, type Compressed, type Compression, type ConsoleLoggerOptions, type ConsoleTarget, type Controller, type ControllerBuilder, type CooperativeFloor, type Coupling, DECLARATION_RULE, DRAIN_RULES, DRAIN_RULE_IDS, DURATION_FRACTIONS, type Decision, type DelayBand, type Dependency, type DependencyHandle, type DurationHistogram, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, type EmbeddedProcess, type Episode, type Epochs, type Evaluated, type ExitCodes, type ExitSignal, type ExitTrigger, FORMAT, type FailsBy, type Finding, GATE_MACHINE, type Gate, type Health, type HealthMetrics, type HealthServer, type HealthVerdict, type Heartbeat, type HeartbeatOptions, type HostStream, IDENTITY_TYPES, type Idempotency, type IdentityType, type IncomingHeaders, type Inequality, type IterationContext, type Jitter, type JobAction, type JobContext, type JobFailure, type JobSettle, type JobSource, type KeyState, type KeyedLimiter, type KeyedQuota, LATCH_MACHINE, LAW_STATISTIC, LIMITER_RULES, LOG_LEVELS, type Lifecycle, type LifecycleEvent, type LifecycleState, type LimitPolicy, type LimitRule, type Limiter, type LimiterEviction, type LimiterSpec, type LimiterState, type LimiterStore, type LimiterStoreSpec, type LocalLimiter, type LogEntry, type LogFields, type LogFormat, type LogLevel, type Logger, MACHINES, type MachineName, type MemoryQuotaStore, type MemoryStore, type MessageShape, type MessageTrigger, NAME_RULE, O04, O09, O10, O16, type Operation, type OperationOf, type Outcome, PLATFORM_MARKS, POLLER_MACHINE, PROCESS_TRIGGERS, PROGRESS_RULE, type Phase, type PhaseContext, type PhaseWork, type PlatformClockOptions, type PodTiming, type Poll, type ProbeAnswer, type ProbeKind, type ProcessHost, type ProcessPort, type ProcessTrigger, type Profile, type ProgressMarks, type QueueDrain, type QueueDrainOptions, type QueueKnobs, type QuotaAllowed, type QuotaAnswer, type QuotaCapacityRefused, type QuotaChange, type QuotaEvent, type QuotaPart, type QuotaReading, type QuotaRecord, type QuotaRefused, type QuotaRule, type QuotaSpec, type QuotaState, type QuotaStep, type QuotaStore, type QuotaTakeStep, type QuotaVerdict, type QuotaWaitRefused, type QuotaWindow, type QuotasVerdict, type Recorder, type RedeliveryPolicy, type RefusalCause, type Refused, type RepeatSignal, type RequestEnd, type RequestEvent, type RequestFn, type RequestOptions, type RequestStream, type RequestWork, type RequeueCause, type Result, type Retrier, type RetrierOptions, type RetryOptions, type RollingWindow, type RoutePattern, type RouteRequest, type Rule, type RunOptions, SERVICE_RULES, SLIDING_WINDOW_MACHINE, STAGES, STOPS, STOP_RULE, type Scenario, type ScenarioValue, type ScopedChange, type ServiceBuilder, type ServiceDescription, type ShutdownOptions, type Side, type SlidingWindow, type Span, type Stage, type StartOptions, type Statistic, type Step, type Stop, type StopWay, type StoreFailure, TOKEN_BUCKET_MACHINE, type TakeQuotasOptions, type TakeRequest, type TakeStep, type Term, type TimerMark, type TimerMarks, type Timing, type TokenBucket, type TraceIds, type TraceIdsSource, type Transport, type TransportImpl, UNCAUGHT_ORIGINS, UNIT_BOUND_RULE, type UncaughtOptions, type UncaughtOrigin, type UnitRequest, type Verdict, WATCHDOG_MACHINE, WINDOW_MACHINE, type WaitCause, type WaitRefused, type Watchdog, type WatchdogSpec, type WorkerKnobs, type WorkerLoop, type WorkerLoopOptions, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capKnob, capacityOf, compress, compression, compressionOf, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, drainMachine, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, keyedQuota, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, lint, lintStop, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryQuotaStore, memoryStore, nodeProcess, overCapacity, platformClock, processPortOf, queueDrain, quotaProblems, quotaRule, quotaStep, realClock, recoverSpan, redact, redeliverOnce, replay, retrier, retry, retryAfterDelay, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, takeQuotas, unitsOf, unrefClock, verdictOf, watchdog, workerLoop };
|
package/build/index.js
CHANGED
|
@@ -7,7 +7,7 @@ import { DRAIN_RULE_IDS, STOPS, STOP_RULE, lintStop } from "./stops.js";
|
|
|
7
7
|
import { DRAIN_RULES, O04, O09, O10, O16 } from "./rules.js";
|
|
8
8
|
import { BOUND_RULES, CLOSE_BOUND_RULE, DECLARATION_RULE, LAW_STATISTIC, LIMITER_RULES, NAME_RULE, PLATFORM_MARKS, PROGRESS_RULE, SERVICE_RULES, UNIT_BOUND_RULE, compressionOf, lint, serviceBindings } from "./lint.js";
|
|
9
9
|
import { IDENTITY_TYPES } from "./identity.js";
|
|
10
|
-
import { platformClock, realClock } from "./clock.js";
|
|
10
|
+
import { platformClock, realClock, unrefClock } from "./clock.js";
|
|
11
11
|
import { detectionTime, heartbeat } from "./heartbeat.js";
|
|
12
12
|
import { backoffBand, backoffDelay, backoffProblems } from "./backoff.js";
|
|
13
13
|
import { retrier, retry, retryAfterDelay } from "./retrier.js";
|
|
@@ -25,4 +25,4 @@ import { workerLoop } from "./worker.js";
|
|
|
25
25
|
import { queueDrain, redeliverOnce } from "./queue.js";
|
|
26
26
|
import { EXIT_MACHINE, GATE_MACHINE, LATCH_MACHINE, MACHINES, POLLER_MACHINE, WATCHDOG_MACHINE, WINDOW_MACHINE, capKnob, drainMachine } from "./machines.js";
|
|
27
27
|
import { replay } from "@mark1russell7/algebra/replay";
|
|
28
|
-
export { BOUND_RULES, CLOSE_BOUND_RULE, DECLARATION_RULE, DRAIN_RULES, DRAIN_RULE_IDS, DURATION_FRACTIONS, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, FORMAT, GATE_MACHINE, IDENTITY_TYPES, LATCH_MACHINE, LAW_STATISTIC, LIMITER_RULES, LOG_LEVELS, MACHINES, NAME_RULE, O04, O09, O10, O16, PLATFORM_MARKS, POLLER_MACHINE, PROCESS_TRIGGERS, PROGRESS_RULE, SERVICE_RULES, SLIDING_WINDOW_MACHINE, STAGES, STOPS, STOP_RULE, TOKEN_BUCKET_MACHINE, UNCAUGHT_ORIGINS, UNIT_BOUND_RULE, WATCHDOG_MACHINE, WINDOW_MACHINE, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capKnob, capacityOf, compress, compression, compressionOf, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, drainMachine, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, keyedQuota, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, lint, lintStop, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryQuotaStore, memoryStore, nodeProcess, overCapacity, platformClock, processPortOf, queueDrain, quotaProblems, quotaRule, quotaStep, realClock, recoverSpan, redact, redeliverOnce, replay, retrier, retry, retryAfterDelay, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, takeQuotas, unitsOf, verdictOf, watchdog, workerLoop };
|
|
28
|
+
export { BOUND_RULES, CLOSE_BOUND_RULE, DECLARATION_RULE, DRAIN_RULES, DRAIN_RULE_IDS, DURATION_FRACTIONS, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, FORMAT, GATE_MACHINE, IDENTITY_TYPES, LATCH_MACHINE, LAW_STATISTIC, LIMITER_RULES, LOG_LEVELS, MACHINES, NAME_RULE, O04, O09, O10, O16, PLATFORM_MARKS, POLLER_MACHINE, PROCESS_TRIGGERS, PROGRESS_RULE, SERVICE_RULES, SLIDING_WINDOW_MACHINE, STAGES, STOPS, STOP_RULE, TOKEN_BUCKET_MACHINE, UNCAUGHT_ORIGINS, UNIT_BOUND_RULE, WATCHDOG_MACHINE, WINDOW_MACHINE, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capKnob, capacityOf, compress, compression, compressionOf, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, drainMachine, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, keyedQuota, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, lint, lintStop, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryQuotaStore, memoryStore, nodeProcess, overCapacity, platformClock, processPortOf, queueDrain, quotaProblems, quotaRule, quotaStep, realClock, recoverSpan, redact, redeliverOnce, replay, retrier, retry, retryAfterDelay, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, takeQuotas, unitsOf, unrefClock, verdictOf, watchdog, workerLoop };
|
package/build/latch.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"latch.js","names":[],"sources":["../src/latch.ts"],"sourcesContent":["import { valueIn } from \"@mark1russell7/quantity\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { Timing } from \"./timing.ts\";\n\n/**\n * An outcome is the result of one poll of a check. Only `\"ok\"` passes. An `\"indeterminate\"`\n * outcome measured nothing: it does not pass, and it does not fail.\n */\nexport type Outcome = \"ok\" | \"error\" | \"indeterminate\";\n\n/** A result is one poll of a check, as the runtime records it. */\nexport interface Result {\n readonly outcome: Outcome;\n /** This time is when the result came, on the monotonic clock, in milliseconds. */\n readonly at: number;\n /** This time is how long the poll took, in milliseconds. */\n readonly took: number;\n /** This text tells why the poll did not pass, or it is null. */\n readonly cause: string | null;\n /** This flag tells if the poll failed at its timeout. */\n readonly timedOut: boolean;\n /** This flag tells if the check threw. A throw is an error with a flag. */\n readonly thrown: boolean;\n /** This flag tells if the force-fail list made the poll fail. */\n readonly forced: boolean;\n}\n\n/**\n * A latch turns the results of one check into a verdict, by the timing of its policy. A debounce\n * counts polls in sequence. A window measures time on the monotonic clock from the first failure\n * of a sequence. A tripped latch fails its policy.\n */\nexport interface Latch {\n readonly tripped: boolean;\n /** This time is when the latch last tripped or released. */\n readonly since: number;\n /** This count is the sequence of the latest results: above zero for passes, below zero for failures. */\n readonly streak: number;\n record(result: Result): void;\n /** This method stops the timers of a window. */\n stop(): void;\n}\n\n/**\n * A trace receives each transition of a machine of the runtime: the state before, the state after,\n * and the event. The machine documents of the lifecycle name the same states and events, thus a\n * test can replay a trace against its document.\n */\nexport type Trace = (from: string, to: string, on: string) => void;\n\nconst ms = (amount: { readonly value: number; readonly unit: string }): number =>\n valueIn(amount, \"ms\");\n\n/**\n * This function makes a latch. `tripped` is its state at the start: a readiness latch starts\n * tripped, and a liveness latch starts released. The latch starts `changed` each time it trips or\n * releases, and it gives each transition to `trace`. A debounce has the states `released` and\n * `tripped`. A window also has the states `failing` and `recovering`, while one of its timers runs.\n */\nexport const latch = (\n timing: Timing,\n clock: Clock,\n tripped: boolean,\n changed: () => void,\n trace?: Trace,\n): Latch => {\n let state = tripped;\n let since = clock.now();\n let streak = 0;\n let fails = 0;\n let passes = 0;\n // the timers of a window: the time that a sequence of failures or passes started, and its timer\n let failingSince: number | null = null;\n let passingSince: number | null = null;\n let failTimer: Cancel | null = null;\n let passTimer: Cancel | null = null;\n\n /** This function gives the name of the state, as the machine documents name it. */\n const named = (): string =>\n state\n ? passingSince === null\n ? \"tripped\"\n : \"recovering\"\n : failingSince === null\n ? \"released\"\n : \"failing\";\n /** This function does one step of the machine, and gives its transition to the trace. */\n const step = (on: string, change: () => void): void => {\n const from = named();\n change();\n trace?.(from, named(), on);\n };\n\n const set = (next: boolean): void => {\n if (next === state) return;\n state = next;\n since = clock.now();\n changed();\n };\n const stopFail = (): void => {\n failTimer?.();\n failTimer = null;\n failingSince = null;\n };\n const stopPass = (): void => {\n passTimer?.();\n passTimer = null;\n passingSince = null;\n };\n\n const debounce = (result: Result): void => {\n if (timing.type !== \"debounce\") return;\n if (result.outcome === \"ok\") {\n passes += 1;\n fails = 0;\n if (state && passes >= timing.recoverAfter) set(false);\n } else {\n fails += 1;\n passes = 0;\n if (!state && fails >= timing.failAfter) set(true);\n }\n };\n\n const windowed = (result: Result): void => {\n if (timing.type !== \"window\") return;\n if (result.outcome === \"ok\") {\n stopFail();\n if (!state) return;\n if (timing.recoverAfter === undefined) {\n set(false);\n return;\n }\n if (passingSince !== null) return;\n const wait = ms(timing.recoverAfter);\n if (wait <= 0) {\n stopPass();\n set(false);\n return;\n }\n passingSince = result.at;\n passTimer = clock.after(wait, () =>\n step(\"window.recovered\", () => {\n passTimer = null;\n passingSince = null;\n set(false);\n }),\n );\n return;\n }\n stopPass();\n if (state || failingSince !== null) return;\n const wait = ms(timing.failAfter);\n if (wait <= 0) {\n stopFail();\n set(true);\n return;\n }\n failingSince = result.at;\n failTimer = clock.after(wait, () =>\n step(\"window.failed\", () => {\n failTimer = null;\n failingSince = null;\n set(true);\n }),\n );\n };\n\n return {\n get tripped() {\n return state;\n },\n get since() {\n return since;\n },\n get streak() {\n return streak;\n },\n record(result) {\n // an indeterminate poll measured nothing: it moves no sequence and no streak\n if (result.outcome === \"indeterminate\") return;\n const pass = result.outcome === \"ok\";\n step(pass ? \"poll.ok\" : \"poll.fail\", () => {\n streak = pass ? Math.max(0, streak) + 1 : Math.min(0, streak) - 1;\n debounce(result);\n windowed(result);\n });\n },\n stop() {\n stopFail();\n stopPass();\n },\n };\n};\n"],"mappings":";;AAkDA,MAAM,MAAM,WACV,QAAQ,QAAQ,IAAI;;;;;;;AAQtB,MAAa,SACX,QACA,OACA,SACA,SACA,UACU;CACV,IAAI,QAAQ;CACZ,IAAI,QAAQ,MAAM,IAAI;CACtB,IAAI,SAAS;CACb,IAAI,QAAQ;CACZ,IAAI,SAAS;CAEb,IAAI,eAA8B;CAClC,IAAI,eAA8B;CAClC,IAAI,YAA2B;CAC/B,IAAI,YAA2B;;
|
|
1
|
+
{"version":3,"file":"latch.js","names":[],"sources":["../src/latch.ts"],"sourcesContent":["import { valueIn } from \"@mark1russell7/quantity\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { Timing } from \"./timing.ts\";\n\n/**\n * An outcome is the result of one poll of a check. Only `\"ok\"` passes. An `\"indeterminate\"`\n * outcome measured nothing: it does not pass, and it does not fail.\n */\nexport type Outcome = \"ok\" | \"error\" | \"indeterminate\";\n\n/** A result is one poll of a check, as the runtime records it. */\nexport interface Result {\n readonly outcome: Outcome;\n /** This time is when the result came, on the monotonic clock, in milliseconds. */\n readonly at: number;\n /** This time is how long the poll took, in milliseconds. */\n readonly took: number;\n /** This text tells why the poll did not pass, or it is null. */\n readonly cause: string | null;\n /** This flag tells if the poll failed at its timeout. */\n readonly timedOut: boolean;\n /** This flag tells if the check threw. A throw is an error with a flag. */\n readonly thrown: boolean;\n /** This flag tells if the force-fail list made the poll fail. */\n readonly forced: boolean;\n}\n\n/**\n * A latch turns the results of one check into a verdict, by the timing of its policy. A debounce\n * counts polls in sequence. A window measures time on the monotonic clock from the first failure\n * of a sequence. A tripped latch fails its policy.\n */\nexport interface Latch {\n readonly tripped: boolean;\n /** This time is when the latch last tripped or released. */\n readonly since: number;\n /** This count is the sequence of the latest results: above zero for passes, below zero for failures. */\n readonly streak: number;\n record(result: Result): void;\n /** This method stops the timers of a window. */\n stop(): void;\n}\n\n/**\n * A trace receives each transition of a machine of the runtime: the state before, the state after,\n * and the event. The machine documents of the lifecycle name the same states and events, thus a\n * test can replay a trace against its document.\n */\nexport type Trace = (from: string, to: string, on: string) => void;\n\nconst ms = (amount: { readonly value: number; readonly unit: string }): number =>\n valueIn(amount, \"ms\");\n\n/**\n * This function makes a latch. `tripped` is its state at the start: a readiness latch starts\n * tripped, and a liveness latch starts released. The latch starts `changed` each time it trips or\n * releases, and it gives each transition to `trace`. A debounce has the states `released` and\n * `tripped`. A window also has the states `failing` and `recovering`, while one of its timers runs.\n */\nexport const latch = (\n timing: Timing,\n clock: Clock,\n tripped: boolean,\n changed: () => void,\n trace?: Trace,\n): Latch => {\n let state = tripped;\n let since = clock.now();\n let streak = 0;\n let fails = 0;\n let passes = 0;\n // the timers of a window: the time that a sequence of failures or passes started, and its timer\n let failingSince: number | null = null;\n let passingSince: number | null = null;\n let failTimer: Cancel | null = null;\n let passTimer: Cancel | null = null;\n // the owner gives the clock: a check of a service gives a clock whose timers do not keep the process alive (SYS-126)\n\n /** This function gives the name of the state, as the machine documents name it. */\n const named = (): string =>\n state\n ? passingSince === null\n ? \"tripped\"\n : \"recovering\"\n : failingSince === null\n ? \"released\"\n : \"failing\";\n /** This function does one step of the machine, and gives its transition to the trace. */\n const step = (on: string, change: () => void): void => {\n const from = named();\n change();\n trace?.(from, named(), on);\n };\n\n const set = (next: boolean): void => {\n if (next === state) return;\n state = next;\n since = clock.now();\n changed();\n };\n const stopFail = (): void => {\n failTimer?.();\n failTimer = null;\n failingSince = null;\n };\n const stopPass = (): void => {\n passTimer?.();\n passTimer = null;\n passingSince = null;\n };\n\n const debounce = (result: Result): void => {\n if (timing.type !== \"debounce\") return;\n if (result.outcome === \"ok\") {\n passes += 1;\n fails = 0;\n if (state && passes >= timing.recoverAfter) set(false);\n } else {\n fails += 1;\n passes = 0;\n if (!state && fails >= timing.failAfter) set(true);\n }\n };\n\n const windowed = (result: Result): void => {\n if (timing.type !== \"window\") return;\n if (result.outcome === \"ok\") {\n stopFail();\n if (!state) return;\n if (timing.recoverAfter === undefined) {\n set(false);\n return;\n }\n if (passingSince !== null) return;\n const wait = ms(timing.recoverAfter);\n if (wait <= 0) {\n stopPass();\n set(false);\n return;\n }\n passingSince = result.at;\n passTimer = clock.after(wait, () =>\n step(\"window.recovered\", () => {\n passTimer = null;\n passingSince = null;\n set(false);\n }),\n );\n return;\n }\n stopPass();\n if (state || failingSince !== null) return;\n const wait = ms(timing.failAfter);\n if (wait <= 0) {\n stopFail();\n set(true);\n return;\n }\n failingSince = result.at;\n failTimer = clock.after(wait, () =>\n step(\"window.failed\", () => {\n failTimer = null;\n failingSince = null;\n set(true);\n }),\n );\n };\n\n return {\n get tripped() {\n return state;\n },\n get since() {\n return since;\n },\n get streak() {\n return streak;\n },\n record(result) {\n // an indeterminate poll measured nothing: it moves no sequence and no streak\n if (result.outcome === \"indeterminate\") return;\n const pass = result.outcome === \"ok\";\n step(pass ? \"poll.ok\" : \"poll.fail\", () => {\n streak = pass ? Math.max(0, streak) + 1 : Math.min(0, streak) - 1;\n debounce(result);\n windowed(result);\n });\n },\n stop() {\n stopFail();\n stopPass();\n },\n };\n};\n"],"mappings":";;AAkDA,MAAM,MAAM,WACV,QAAQ,QAAQ,IAAI;;;;;;;AAQtB,MAAa,SACX,QACA,OACA,SACA,SACA,UACU;CACV,IAAI,QAAQ;CACZ,IAAI,QAAQ,MAAM,IAAI;CACtB,IAAI,SAAS;CACb,IAAI,QAAQ;CACZ,IAAI,SAAS;CAEb,IAAI,eAA8B;CAClC,IAAI,eAA8B;CAClC,IAAI,YAA2B;CAC/B,IAAI,YAA2B;;CAI/B,MAAM,cACJ,QACI,iBAAiB,OACf,YACA,eACF,iBAAiB,OACf,aACA;;CAER,MAAM,QAAQ,IAAY,WAA6B;EACrD,MAAM,OAAO,MAAM;EACnB,OAAO;EACP,QAAQ,MAAM,MAAM,GAAG,EAAE;CAC3B;CAEA,MAAM,OAAO,SAAwB;EACnC,IAAI,SAAS,OAAO;EACpB,QAAQ;EACR,QAAQ,MAAM,IAAI;EAClB,QAAQ;CACV;CACA,MAAM,iBAAuB;EAC3B,YAAY;EACZ,YAAY;EACZ,eAAe;CACjB;CACA,MAAM,iBAAuB;EAC3B,YAAY;EACZ,YAAY;EACZ,eAAe;CACjB;CAEA,MAAM,YAAY,WAA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GAAG,MAAM,IAAI;IAChE,SAAS,MAAM;IACf,SAAS,MAAM;GACjB,CAAC;EACH;EACA,OAAO;GACL,SAAS;GACT,SAAS;EACX;CACF;AACF"}
|
package/build/lifecycle.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycle.js","names":[],"sources":["../src/lifecycle.ts"],"sourcesContent":["import type { Extent } from \"@mark1russell7/quantity\";\nimport { valueIn } from \"@mark1russell7/quantity\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\nimport type { CooperativeFloor, Phase, ServiceDescription } from \"./description.ts\";\nimport { lateHolds, ownStream, takeOutside } from \"./drains.ts\";\nimport type { MachineName } from \"./events.ts\";\nimport type { Health, Runtime, StartOptions } from \"./health.ts\";\nimport type { ExitTrigger, ProcessPort, UncaughtOrigin } from \"./process.ts\";\nimport { EXIT_SIGNALS, isExitCode, isExitSignal, matchesMessage, nodeProcess } from \"./process.ts\";\nimport type { RequestFn, RequestOptions, RequestStream } from \"./requests.ts\";\nimport { tracker } from \"./requests.ts\";\nimport type { OperationOf } from \"./routes.ts\";\n\n/**\n * A transport is a source of work: a server, a consumer or a worker. Each has one contract. It\n * starts, stops its intake, and drains to a deadline without a throw. It counts its work in flight,\n * and it closes. A second close has no effect.\n */\nexport interface TransportImpl {\n /**\n * This method starts the transport. The lifecycle is the object that `run()` gives at the end of\n * the startup. Its request tracking operates from the start: a request before the startup ends\n * gets a retryable refusal, and `keepAlive()` is false. Do not wait for `life.started` here,\n * because the startup waits for this method.\n */\n start(signal: AbortSignal, life: Lifecycle): Promise<void> | void;\n stopIntake(): Promise<void> | void;\n /**\n * This method lets the work in flight end until `deadline` (milliseconds on the monotonic\n * clock). The signal is the cooperative abort, which comes before the deadline.\n */\n drain(deadline: number, signal: AbortSignal): Promise<void> | void;\n inFlight(): number;\n close(): Promise<void> | void;\n}\n\n/** A dependency handle connects to a dependency at the start, and closes the connection at the end. */\nexport interface DependencyHandle {\n connect(signal: AbortSignal): Promise<void> | void;\n close(): Promise<void> | void;\n}\n\n/**\n * A health server answers the probes, on its own port. It starts first, thus the probes answer\n * while the dependencies connect, and it closes last.\n */\nexport interface HealthServer {\n listen(health: Health): Promise<void> | void;\n close(): Promise<void> | void;\n}\n\n/** A phase context is what a phase gives its work: its deadline, its signal and the clock. */\nexport interface PhaseContext {\n /** This time is the end of the cap of the phase, in milliseconds on the monotonic clock. */\n readonly deadline: number;\n /** This signal aborts at the end of the cap of the phase. */\n readonly signal: AbortSignal;\n readonly clock: Clock;\n}\n\n/** A phase work is a step of the shutdown that an owner adds to a phase. */\nexport type PhaseWork = (context: PhaseContext) => Promise<void> | void;\n\n/**\n * These are the stages of the shutdown, in their sequence. A declared phase with one of these\n * names gets the work of the runtime for its stage. A phase with another name gets only the work of\n * its owners.\n * - `fail readiness`: readiness fails at the start of the shutdown. This phase then holds for its\n * cap, while the endpoints of the platform remove the service.\n * - `stop intake`: each transport stops its intake, and new requests get a retryable 503.\n * - `drain`: the transports and the requests in flight end, until the cap. The cooperative abort\n * comes before the end of the cap, by the cooperative window.\n * - `close transports`: each transport closes.\n * - `stop the poller`: each check and watchdog stops. Then the signal of the service aborts.\n * - `tear down dependencies`: each dependency closes, in the reverse sequence of its connection.\n * - `close the health server`: the probes stop.\n * - `flush the output`: the work of the owners of this phase ends, and then the process port\n * writes the buffered output. Without this phase, the process exits without a wait.\n */\nexport const STAGES = [\n \"fail readiness\",\n \"stop intake\",\n \"drain\",\n \"close transports\",\n \"stop the poller\",\n \"tear down dependencies\",\n \"close the health server\",\n \"flush the output\",\n] as const;\n\nexport type Stage = (typeof STAGES)[number];\n\n/** This function gives the place of a stage in the sequence, or -1 for a phase of another name. */\nexport const stageRank = (name: string): number => (STAGES as readonly string[]).indexOf(name);\n\n/** The signal of the service aborts after the poller stops, and before the dependencies close. */\nconst ABORT_AFTER = stageRank(\"stop the poller\");\n\n/**\n * This function gives the time of the cooperative abort, in milliseconds after the drain starts. It\n * is the cap less the cooperative window. With the floor `half`, it is not less than half the cap,\n * and a window without a bound gives half the cap. With the floor `none`, it is not less than 0.\n */\nexport const cooperativeAbortAt = (cap: number, window: Extent, floor: CooperativeFloor = \"half\"): number => {\n const before = window.value === \"infinite\" ? Number.POSITIVE_INFINITY : valueIn(window, \"ms\");\n return Math.max(cap - before, floor === \"none\" ? 0 : cap / 2);\n};\n\n/**\n * These options make each error that no code caught a trigger of the shutdown. They are an uncaught\n * exception and an unhandled rejection.\n */\nexport interface UncaughtOptions {\n /** This code is the exit code after an uncaught error, a whole number from 0 to 255. The default is 1. */\n readonly exitCode?: number | undefined;\n /**\n * This function tells if the runtime skips an error, for example an `ECONNRESET` of a peer socket.\n * The logger gets a skipped error at `warn`, and the service continues. A throw of this function skips nothing.\n */\n readonly ignore?: ((error: unknown, origin: UncaughtOrigin) => boolean) | undefined;\n}\n\n/** These options run the lifecycle. Without them, it uses the real clock and the process of Node. */\nexport interface RunOptions extends StartOptions {\n readonly process?: ProcessPort | undefined;\n /**\n * With these options, the lifecycle adds a handler for the errors that no code caught, from its start\n * to its exit. Each error that it does not skip is an error of the lifecycle at `error`. It then\n * starts the shutdown with its exit code, as a signal does. Without them, the runtime adds no handler.\n */\n readonly uncaught?: UncaughtOptions | undefined;\n}\n\n/** This function gives the problems of the option `uncaught`: an exit code that is not from 0 to 255. */\nexport const uncaughtProblems = (uncaught: UncaughtOptions | undefined): string[] => {\n const code = uncaught?.exitCode;\n return code === undefined || isExitCode(code) ? [] : [`the exit code ${code} of an uncaught error is not a whole number from 0 to 255`];\n};\n\n/** These options go with a request for the shutdown. */\nexport interface ShutdownOptions {\n /**\n * This code is the exit code that the work of the process gives, a whole number from 0 to 255. The\n * first exit request with a code sets it. A code of 0 lets an error make the exit code 1.\n */\n readonly code?: number | undefined;\n}\n\n/** A lifecycle state tells where the service is in its life. */\nexport type LifecycleState = \"starting\" | \"running\" | \"draining\" | \"exited\";\n\n/** The lifecycle of a running service. */\nexport interface Lifecycle {\n readonly health: Health;\n readonly state: LifecycleState;\n /** This code is the exit code, or null before the exit. */\n readonly exitCode: number | null;\n /** These texts are the errors of the lifecycle. An error makes the exit code 1, unless an exit request gives another code. */\n readonly errors: readonly string[];\n /** This promise ends when the startup ends: the service runs, or its startup failed. */\n readonly started: Promise<void>;\n /** This promise gives the exit code when the shutdown ends. */\n readonly done: Promise<number>;\n /** This signal aborts after the poller stops: the background work of the service stops with it. */\n readonly signal: AbortSignal;\n /**\n * This method asks for the shutdown, as an exit signal does. A second request does not start a\n * second shutdown. It can give the exit code, when no request gave one before.\n */\n shutdown(cause?: string, options?: ShutdownOptions): Promise<number>;\n /**\n * This method does one request of a controller, on a route or a route pattern that the controller\n * declares. It gives the stream of the request: each item of the work, then one end. The service\n * refuses the request while it cannot take new work, and the shutdown can cut it. An undeclared\n * route throws, because it has no idempotency.\n */\n request<T>(controller: string, route: string, work: RequestFn<T>, options?: RequestOptions): RequestStream<T>;\n inFlight(controller?: string): number;\n /**\n * This method tells if a response can keep its connection open. It is false while the service is\n * not ready, thus each response then closes its connection.\n */\n keepAlive(): boolean;\n}\n\n/** The parts that the builder gives the lifecycle, beside the declaration. */\nexport interface Components {\n readonly transports: ReadonlyMap<string, TransportImpl>;\n readonly dependencies: ReadonlyMap<string, DependencyHandle>;\n readonly healthServer: HealthServer | null;\n readonly phaseWork: ReadonlyMap<string, readonly PhaseWork[]>;\n /** These are the functions of the route patterns, by controller and by pattern. */\n readonly choices?: ReadonlyMap<string, ReadonlyMap<string, OperationOf>> | undefined;\n /** This function stops the parts that the poller stage stops beside the checks: the watchdogs. */\n readonly stopPollers: () => void;\n}\n\nconst message = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/** This function gives the text of an error with its stack, when it has one. */\nconst withStack = (error: unknown): string =>\n error instanceof Error && typeof error.stack === \"string\" && error.stack.length > 0 ? error.stack : message(error);\n\nconst UNCAUGHT_NAMES: Readonly<Record<UncaughtOrigin, string>> = {\n uncaughtException: \"an uncaught exception\",\n unhandledRejection: \"an unhandled rejection\",\n};\n\n/**\n * This function gives the problems of a declaration that the lifecycle cannot start: a stage with\n * work and no declared phase. The runtime has no defaults, thus a transport without a drain phase\n * has no time to drain.\n */\nexport const lifecycleProblems = (description: ServiceDescription, components: Components): string[] => {\n const declared = new Set(description.shutdown.phases.map((phase) => phase.name));\n const needs = (stage: Stage, why: string): string[] =>\n declared.has(stage) ? [] : [`${description.name} has ${why}, thus it declares the phase \"${stage}\"`];\n const problems: string[] = [];\n for (const transport of description.transports)\n if (!components.transports.has(transport.name))\n problems.push(`transport ${transport.name} has no implementation: the runtime has no defaults`);\n if (components.transports.size > 0 || description.controllers.length > 0) {\n problems.push(...needs(\"stop intake\", \"transports or controllers\"));\n problems.push(...needs(\"drain\", \"transports or controllers\"));\n }\n if (components.transports.size > 0) problems.push(...needs(\"close transports\", \"transports\"));\n if (description.checks.length > 0) problems.push(...needs(\"stop the poller\", \"checks\"));\n if (components.dependencies.size > 0) problems.push(...needs(\"tear down dependencies\", \"dependency handles\"));\n if (components.healthServer !== null) problems.push(...needs(\"close the health server\", \"a health server\"));\n return problems;\n};\n\n/**\n * This function starts the lifecycle of a service. The startup has a sequence: the health server\n * first, then each dependency, then each transport, and the startup gate last. A trigger during the\n * startup gets its shutdown after the startup ends. The shutdown does the declared phases in their\n * sequence, each one capped. Only the lifecycle ends the process. Its exit code is the code of the\n * exit request, else 1 after an error, else 0.\n */\nexport const lifecycle = (\n description: ServiceDescription,\n runtime: Runtime,\n components: Components,\n options: RunOptions = {},\n /** This function receives the lifecycle before the startup begins. */\n bind: (life: Lifecycle) => void = () => {},\n): Lifecycle => {\n const clock = options.clock ?? realClock;\n const port = options.process ?? nodeProcess;\n const record = (machine: MachineName, from: string, to: string, on: string, detail?: string): void =>\n options.record?.({\n at: clock.now(),\n machine,\n instance: description.name,\n from,\n to,\n on,\n ...(detail === undefined ? {} : { detail }),\n });\n const service = new AbortController();\n const errors: string[] = [];\n const exitCodes = description.shutdown.exitCodes ?? {};\n const repeatPolicy = description.shutdown.onRepeatSignal;\n let state: LifecycleState = \"starting\";\n let exitCode: number | null = null;\n // the code of the first exit request that gives one\n let requested: number | undefined;\n let intakeStopped = false;\n let shutdownStarted = false;\n let failedStartup = false;\n // the exit manager: running, stopping, exited\n let exitState = \"running\";\n const moveExit = (to: string, on: string, detail?: string): void => {\n record(\"exit\", exitState, to, on, detail);\n exitState = to;\n };\n const fail = (cause: string): void => {\n errors.push(cause);\n // after an exit, the process has ended: the exit manager does not move again\n if (exitState !== \"exited\") record(\"exit\", exitState, exitState, \"error\", cause);\n };\n\n const requests = tracker(description.controllers, clock, (controller) => {\n if (state === \"starting\") return \"the service has not started\";\n if (state === \"exited\") return \"the service has exited\";\n // while it drains and before its intake stops, the service still serves: the platform can\n // still route a request to it until its endpoints update\n if (state === \"draining\") return null;\n return runtime.verdict().controllers[controller] === true ? null : `controller ${controller} is not ready`;\n }, components.choices);\n\n let finish: (code: number) => void = () => {};\n const done = new Promise<number>((resolve) => {\n finish = resolve;\n });\n // what started, thus what the shutdown stops\n let healthListening = false;\n const connected: Array<[string, DependencyHandle]> = [];\n const startedTransports: Array<[string, TransportImpl]> = [];\n // the startup exists before any part starts: a transport that asks for the shutdown in its start waits for it\n let startupEnded: () => void = () => {};\n const startup = new Promise<void>((resolve) => {\n startupEnded = resolve;\n });\n let offs: Array<() => void> = [];\n // the hold of the process, from the start of the lifecycle to its exit\n let release: () => void = () => {};\n\n /** This function ends the process with a code, one time, and removes each handler of a trigger and the hold. */\n const end = (code: number, on: string): void => {\n state = \"exited\";\n exitCode = code;\n for (const off of offs) off();\n offs = [];\n moveExit(\"exited\", on, `exit ${code}`);\n finish(code);\n // the hold ends at the exit, not at the stop of the intake: the drain and the teardown still need the process\n release();\n port.exit(code);\n };\n\n /**\n * This function receives a trigger of the process: the first one starts the shutdown. The cause\n * names the trigger, and a message that stands for a signal tells it.\n */\n const triggered = (trigger: ExitTrigger, cause: string = trigger): void => {\n if (exitState === \"exited\") return;\n if (shutdownStarted || exitState === \"stopping\") {\n // a signal while the shutdown runs obeys the declared policy. Another trigger, for example the\n // end of stdin after a SIGTERM, has no effect\n if (isExitSignal(trigger) && repeatPolicy === \"exit\") {\n fail(`${cause} came again while the shutdown ran, and the declaration exits at once`);\n end(1, \"exit.repeat\");\n return;\n }\n record(\"exit\", exitState, exitState, \"exit.repeat\", cause);\n return;\n }\n const code = exitCodes[trigger];\n void shutdown(cause, code === undefined ? {} : { code });\n };\n const messages = description.shutdown.messages ?? [];\n /** This function receives a message of the IPC channel. The first declared shape that it matches gives its trigger. */\n const received = (message: unknown): void => {\n const found = messages.find((each) => matchesMessage(each.match, message));\n if (found === undefined) return;\n if (found.as === undefined) triggered(\"ipc-message\");\n else triggered(found.as, `${found.as} (a message of the IPC channel)`);\n };\n const uncaught = options.uncaught;\n const uncaughtCode = uncaught?.exitCode !== undefined && isExitCode(uncaught.exitCode) ? uncaught.exitCode : 1;\n /**\n * This function receives an error that no code caught. A skipped error goes to the logger at\n * `warn`. Each other error is an error of the lifecycle, and it starts the shutdown with its code.\n */\n const caught = (error: unknown, origin: UncaughtOrigin): void => {\n if (exitState === \"exited\") return;\n const name = UNCAUGHT_NAMES[origin];\n let skip = false;\n try {\n skip = uncaught?.ignore?.(error, origin) === true;\n } catch {\n // a throw of the function skips nothing\n }\n if (skip) {\n try {\n options.logger?.log(\"warn\", `${name} was skipped: ${message(error)}`, { origin, error: withStack(error) });\n } catch {\n // the lifecycle does not depend on its logger\n }\n return;\n }\n // the error event goes to the logger at `error`, with the stack\n fail(`${name}: ${withStack(error)}`);\n void shutdown(`${name}: ${message(error)}`, { code: uncaughtCode });\n };\n\n /**\n * This function does the work of one phase, until its cap. It tells if the work ended in time. When\n * work is left at the cap, `excuse` gives the cause of a cap that is not a failure, or null.\n */\n const runPhase = async (\n phase: Phase,\n hold: boolean,\n work: ReadonlyArray<(context: PhaseContext) => Promise<void> | void>,\n excuse: (left: number) => string | null = () => null,\n ): Promise<{ readonly inTime: boolean; readonly excused: string | null }> => {\n const cap = valueIn(phase.cap, \"ms\");\n const deadline = clock.now() + cap;\n const capped = new AbortController();\n const context: PhaseContext = { deadline, signal: capped.signal, clock };\n let pending = work.length;\n const all = Promise.all(\n work.map(async (each) => {\n try {\n await each(context);\n } catch (error) {\n fail(`the phase ${phase.name} failed: ${message(error)}`);\n } finally {\n pending -= 1;\n }\n }),\n );\n let cancelCap: Cancel = () => {};\n // the timer of the cap starts after the timers of the work: at the same time, the work comes first\n const end = new Promise<\"cap\">((resolve) => {\n cancelCap = clock.after(cap, () => resolve(\"cap\"));\n });\n const first = await Promise.race([all.then(() => \"work\" as const), end]);\n if (first === \"work\" && hold) await end;\n // the work that is left is read at the cap, before the next phase changes it\n const excused = pending > 0 ? excuse(pending) : null;\n cancelCap();\n capped.abort(new Error(`the phase ${phase.name} reached its cap`));\n return { inTime: pending === 0, excused };\n };\n\n async function shutdown(cause = \"the service asked for it\", request: ShutdownOptions = {}): Promise<number> {\n if (request.code !== undefined && !isExitCode(request.code))\n throw new Error(`${description.name}: the exit code ${request.code} is not a whole number from 0 to 255`);\n if (exitState === \"exited\") return done;\n if (request.code !== undefined && requested === undefined) requested = request.code;\n if (shutdownStarted) {\n if (exitState === \"stopping\") record(\"exit\", exitState, exitState, \"exit.repeat\", cause);\n return done;\n }\n shutdownStarted = true;\n if (exitState === \"running\") moveExit(\"stopping\", \"exit.request\", cause);\n // a trigger during the startup gets its shutdown after the startup ends\n await startup;\n // a repeat signal can end the process while the startup ends: then only the timers stop\n if (exitState === \"exited\") {\n runtime.stop();\n components.stopPollers();\n return exitCode!;\n }\n state = \"draining\";\n runtime.drain();\n let drainState = \"running\";\n const moveDrain = (to: string, on: string, detail?: string): void => {\n record(\"drain\", drainState, to, on, detail);\n drainState = to;\n };\n const abortService = (): void => {\n if (service.signal.aborted) return;\n service.abort(new Error(\"the service stopped\"));\n record(\"drain\", drainState, drainState, \"signal.abort\");\n };\n const phases = description.shutdown.phases;\n let on = \"exit.request\";\n let detail: string | undefined;\n for (const phase of phases) {\n // after a repeat signal ends the process, no phase starts\n if (exitState === \"exited\") break;\n const rank = stageRank(phase.name);\n moveDrain(phase.name, on, detail);\n if (rank > ABORT_AFTER) abortService();\n const work: Array<(context: PhaseContext) => Promise<void> | void> = [];\n const owned = components.phaseWork.get(phase.name) ?? [];\n if (phase.name === \"stop intake\") {\n work.push(() => {\n intakeStopped = true;\n requests.stopIntake();\n });\n for (const [, impl] of startedTransports) work.push(() => impl.stopIntake());\n }\n // the cooperative abort of the drain: the cap less the window, not before the floor. It ends\n // with the phase, thus a drain that ends before it does not abort anything\n let cancelAbort: Cancel = () => {};\n let excuse: ((left: number) => string | null) | undefined;\n if (phase.name === \"drain\") {\n const cap = valueIn(phase.cap, \"ms\");\n const cooperative = new AbortController();\n const fireAt = cooperativeAbortAt(cap, description.shutdown.cooperativeWindow, description.shutdown.cooperativeFloor);\n cancelAbort = clock.after(fireAt, () => {\n cooperative.abort(new Error(\"the cooperative abort of the drain\"));\n requests.cooperativeAbort();\n record(\"drain\", drainState, drainState, \"drain.cooperative-abort\");\n });\n // the cut of the requests is the first work, thus its timer comes before the timer of the cap. A\n // transport can reach the deadline before the cut: httpTransport then waits for the answers of the cut (SYS-29)\n work.push(({ deadline }) => requests.drain(deadline));\n let transportsLeft = 0;\n for (const [, impl] of startedTransports)\n work.push(async ({ deadline }) => {\n transportsLeft += 1;\n try {\n await impl.drain(deadline, cooperative.signal);\n } finally {\n transportsLeft -= 1;\n }\n });\n // a phase fails only for its own work. At the cap, a drain whose transports wait only for the\n // bytes of their answers did its work: the cap is not a failure, and its event gives the count (SYS-29)\n excuse = (left) => {\n const holds = lateHolds(life);\n if (left > transportsLeft || transportsLeft > holds.length || holds.some((each) => each.running > 0)) return null;\n return `answers not flushed: ${holds.reduce((sum, each) => sum + each.unflushed, 0)}`;\n };\n }\n if (phase.name === \"close transports\")\n for (const [, impl] of startedTransports) work.push(() => impl.close());\n if (phase.name === \"stop the poller\")\n work.push(() => {\n runtime.stop();\n components.stopPollers();\n });\n if (phase.name === \"tear down dependencies\")\n work.push(async () => {\n for (const [, handle] of [...connected].reverse()) await handle.close();\n });\n if (phase.name === \"close the health server\" && healthListening && components.healthServer !== null) {\n const server = components.healthServer;\n work.push(() => server.close());\n }\n if (phase.name === \"flush the output\")\n // the owners write their last output first (a log or a trace exporter), then the port writes it\n work.push(async (context) => {\n await Promise.all(\n owned.map(async (each) => {\n try {\n await each(context);\n } catch (error) {\n fail(`the phase ${phase.name} failed: ${message(error)}`);\n }\n }),\n );\n await port.flush?.();\n });\n else for (const each of owned) work.push(each);\n const { inTime, excused } = await runPhase(phase, phase.name === \"fail readiness\", work, excuse);\n cancelAbort();\n if (!inTime && excused === null) fail(`the phase ${phase.name} did not end in its cap of ${valueIn(phase.cap, \"s\")} s`);\n on = inTime ? \"phase.done\" : \"phase.cap\";\n // the streams outside the lifecycle do not hold the drain, and its record gives their count\n const outsideCount = phase.name === \"drain\" ? takeOutside(life) : 0;\n const parts = [inTime ? null : excused, outsideCount > 0 ? `streams outside the lifecycle: ${outsideCount}` : null].filter(\n (part): part is string => part !== null,\n );\n detail = parts.length > 0 ? parts.join(\", \") : undefined;\n }\n if (exitState !== \"exited\") moveDrain(\"done\", on, detail);\n abortService();\n // a stage that the declaration does not name still stops: the checks, at the end\n runtime.stop();\n components.stopPollers();\n if (!intakeStopped) requests.stopIntake();\n // a repeat signal can end the process during the sequence: then it ended already\n if (exitState === \"exited\") return exitCode!;\n const code = requested !== undefined && requested !== 0 ? requested : errors.length > 0 ? 1 : 0;\n end(code, \"shutdown.done\");\n return code;\n }\n\n const life: Lifecycle = {\n health: runtime,\n get state() {\n return state;\n },\n get exitCode() {\n return exitCode;\n },\n get errors() {\n return [...errors];\n },\n started: startup,\n done,\n signal: service.signal,\n shutdown,\n // the lifecycle owns each stream that it makes: its drain cuts the stream (SYS-29)\n request: (controller, route, work, request) => ownStream(requests.request(controller, route, work, request), life),\n inFlight: (controller) => requests.inFlight(controller),\n keepAlive: () => state === \"running\" && runtime.verdict().ready,\n };\n\n bind(life);\n release = port.hold?.() ?? (() => {});\n offs = [...EXIT_SIGNALS, ...(description.shutdown.triggers ?? [])].map((trigger: ExitTrigger) =>\n port.on(trigger, trigger === \"ipc-message\" ? received : () => triggered(trigger)),\n );\n // the handler of the uncaught errors goes at the exit, with the handlers of the triggers\n if (uncaught !== undefined && port.onUncaught !== undefined) offs.push(port.onUncaught(caught));\n\n void (async (): Promise<void> => {\n const started = (what: string): void => record(\"gate\", \"starting\", \"starting\", \"component.started\", what);\n try {\n runtime.beginStartup();\n if (components.healthServer !== null) {\n await components.healthServer.listen(runtime);\n healthListening = true;\n started(\"the health server\");\n }\n for (const dependency of description.dependencies) {\n const handle = components.dependencies.get(dependency.name);\n if (handle === undefined) continue;\n await handle.connect(service.signal);\n connected.push([dependency.name, handle]);\n started(`dependency ${dependency.name}`);\n }\n for (const transport of description.transports) {\n const impl = components.transports.get(transport.name)!;\n await impl.start(service.signal, life);\n startedTransports.push([transport.name, impl]);\n started(`${transport.kind} ${transport.name}`);\n }\n await runtime.warmUp();\n if (state === \"starting\") state = \"running\";\n } catch (error) {\n const cause = `the startup failed: ${message(error)}`;\n failedStartup = true;\n runtime.failStartup(cause);\n fail(cause);\n if (exitState === \"running\") moveExit(\"stopping\", \"startup.fail\", cause);\n else if (exitState === \"stopping\") record(\"exit\", exitState, exitState, \"startup.fail\", cause);\n } finally {\n startupEnded();\n }\n })();\n // a failed startup shuts down what started. An exit request during the startup waits for it\n void startup.then(() => {\n if (failedStartup && !shutdownStarted && exitState !== \"exited\") void shutdown(\"the startup failed\");\n });\n\n return life;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgFA,MAAa,SAAS;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAKA,MAAa,aAAa,SAA0B,OAA6B,QAAQ,IAAI;;AAG7F,MAAM,cAAc,UAAU,iBAAiB;;;;;;AAO/C,MAAa,sBAAsB,KAAa,QAA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AAK,CAAC,WAAW,MAAM,MAAM,CAAC;IACxC,QAAQ,cAAc,WAAW,MAAM;GACzC;GACA,KAAK,MAAM,aAAa,YAAY,YAAY;IAC9C,MAAM,OAAO,WAAW,WAAW,IAAI,UAAU,IAAI;IACrD,MAAM,KAAK,MAAM,QAAQ,QAAQ,IAAI;IACrC,kBAAkB,KAAK,CAAC,UAAU,MAAM,IAAI,CAAC;IAC7C,QAAQ,GAAG,UAAU,KAAK,GAAG,UAAU,MAAM;GAC/C;GACA,MAAM,QAAQ,OAAO;GACrB,IAAI,UAAU,YAAY,QAAQ;EACpC,SAAS,OAAO;GACd,MAAM,QAAQ,uBAAuB,QAAQ,KAAK;GAClD,gBAAgB;GAChB,QAAQ,YAAY,KAAK;GACzB,KAAK,KAAK;GACV,IAAI,cAAc,WAAW,SAAS,YAAY,gBAAgB,KAAK;QAClE,IAAI,cAAc,YAAY,OAAO,QAAQ,WAAW,WAAW,gBAAgB,KAAK;EAC/F,UAAU;GACR,aAAa;EACf;CACF,EAAA,CAAG;CAEH,QAAa,WAAW;EACtB,IAAI,iBAAiB,CAAC,mBAAmB,cAAc,UAAU,SAAc,oBAAoB;CACrG,CAAC;CAED,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"lifecycle.js","names":[],"sources":["../src/lifecycle.ts"],"sourcesContent":["import type { Extent } from \"@mark1russell7/quantity\";\nimport { valueIn } from \"@mark1russell7/quantity\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\nimport type { CooperativeFloor, Phase, ServiceDescription } from \"./description.ts\";\nimport { lateHolds, ownStream, takeOutside } from \"./drains.ts\";\nimport type { MachineName } from \"./events.ts\";\nimport type { Health, Runtime, StartOptions } from \"./health.ts\";\nimport type { ExitTrigger, ProcessPort, UncaughtOrigin } from \"./process.ts\";\nimport { EXIT_SIGNALS, isExitCode, isExitSignal, matchesMessage, nodeProcess } from \"./process.ts\";\nimport type { RequestFn, RequestOptions, RequestStream } from \"./requests.ts\";\nimport { tracker } from \"./requests.ts\";\nimport type { OperationOf } from \"./routes.ts\";\n\n/**\n * A transport is a source of work: a server, a consumer or a worker. Each has one contract. It\n * starts, stops its intake, and drains to a deadline without a throw. It counts its work in flight,\n * and it closes. A second close has no effect.\n */\nexport interface TransportImpl {\n /**\n * This method starts the transport. The lifecycle is the object that `run()` gives at the end of\n * the startup. Its request tracking operates from the start: a request before the startup ends\n * gets a retryable refusal, and `keepAlive()` is false. Do not wait for `life.started` here,\n * because the startup waits for this method.\n */\n start(signal: AbortSignal, life: Lifecycle): Promise<void> | void;\n stopIntake(): Promise<void> | void;\n /**\n * This method lets the work in flight end until `deadline` (milliseconds on the monotonic\n * clock). The signal is the cooperative abort, which comes before the deadline.\n */\n drain(deadline: number, signal: AbortSignal): Promise<void> | void;\n inFlight(): number;\n close(): Promise<void> | void;\n}\n\n/** A dependency handle connects to a dependency at the start, and closes the connection at the end. */\nexport interface DependencyHandle {\n connect(signal: AbortSignal): Promise<void> | void;\n close(): Promise<void> | void;\n}\n\n/**\n * A health server answers the probes, on its own port. It starts first, thus the probes answer\n * while the dependencies connect, and it closes last.\n */\nexport interface HealthServer {\n listen(health: Health): Promise<void> | void;\n close(): Promise<void> | void;\n}\n\n/** A phase context is what a phase gives its work: its deadline, its signal and the clock. */\nexport interface PhaseContext {\n /** This time is the end of the cap of the phase, in milliseconds on the monotonic clock. */\n readonly deadline: number;\n /** This signal aborts at the end of the cap of the phase. */\n readonly signal: AbortSignal;\n readonly clock: Clock;\n}\n\n/** A phase work is a step of the shutdown that an owner adds to a phase. */\nexport type PhaseWork = (context: PhaseContext) => Promise<void> | void;\n\n/**\n * These are the stages of the shutdown, in their sequence. A declared phase with one of these\n * names gets the work of the runtime for its stage. A phase with another name gets only the work of\n * its owners.\n * - `fail readiness`: readiness fails at the start of the shutdown. This phase then holds for its\n * cap, while the endpoints of the platform remove the service.\n * - `stop intake`: each transport stops its intake, and new requests get a retryable 503.\n * - `drain`: the transports and the requests in flight end, until the cap. The cooperative abort\n * comes before the end of the cap, by the cooperative window.\n * - `close transports`: each transport closes.\n * - `stop the poller`: each check and watchdog stops. Then the signal of the service aborts.\n * - `tear down dependencies`: each dependency closes, in the reverse sequence of its connection.\n * - `close the health server`: the probes stop.\n * - `flush the output`: the work of the owners of this phase ends, and then the process port\n * writes the buffered output. Without this phase, the process exits without a wait.\n */\nexport const STAGES = [\n \"fail readiness\",\n \"stop intake\",\n \"drain\",\n \"close transports\",\n \"stop the poller\",\n \"tear down dependencies\",\n \"close the health server\",\n \"flush the output\",\n] as const;\n\nexport type Stage = (typeof STAGES)[number];\n\n/** This function gives the place of a stage in the sequence, or -1 for a phase of another name. */\nexport const stageRank = (name: string): number => (STAGES as readonly string[]).indexOf(name);\n\n/** The signal of the service aborts after the poller stops, and before the dependencies close. */\nconst ABORT_AFTER = stageRank(\"stop the poller\");\n\n/**\n * This function gives the time of the cooperative abort, in milliseconds after the drain starts. It\n * is the cap less the cooperative window. With the floor `half`, it is not less than half the cap,\n * and a window without a bound gives half the cap. With the floor `none`, it is not less than 0.\n */\nexport const cooperativeAbortAt = (cap: number, window: Extent, floor: CooperativeFloor = \"half\"): number => {\n const before = window.value === \"infinite\" ? Number.POSITIVE_INFINITY : valueIn(window, \"ms\");\n return Math.max(cap - before, floor === \"none\" ? 0 : cap / 2);\n};\n\n/**\n * These options make each error that no code caught a trigger of the shutdown. They are an uncaught\n * exception and an unhandled rejection.\n */\nexport interface UncaughtOptions {\n /** This code is the exit code after an uncaught error, a whole number from 0 to 255. The default is 1. */\n readonly exitCode?: number | undefined;\n /**\n * This function tells if the runtime skips an error, for example an `ECONNRESET` of a peer socket.\n * The logger gets a skipped error at `warn`, and the service continues. A throw of this function skips nothing.\n */\n readonly ignore?: ((error: unknown, origin: UncaughtOrigin) => boolean) | undefined;\n}\n\n/** These options run the lifecycle. Without them, it uses the real clock and the process of Node. */\nexport interface RunOptions extends StartOptions {\n readonly process?: ProcessPort | undefined;\n /**\n * With these options, the lifecycle adds a handler for the errors that no code caught, from its start\n * to its exit. Each error that it does not skip is an error of the lifecycle at `error`. It then\n * starts the shutdown with its exit code, as a signal does. Without them, the runtime adds no handler.\n */\n readonly uncaught?: UncaughtOptions | undefined;\n}\n\n/** This function gives the problems of the option `uncaught`: an exit code that is not from 0 to 255. */\nexport const uncaughtProblems = (uncaught: UncaughtOptions | undefined): string[] => {\n const code = uncaught?.exitCode;\n return code === undefined || isExitCode(code) ? [] : [`the exit code ${code} of an uncaught error is not a whole number from 0 to 255`];\n};\n\n/** These options go with a request for the shutdown. */\nexport interface ShutdownOptions {\n /**\n * This code is the exit code that the work of the process gives, a whole number from 0 to 255. The\n * first exit request with a code sets it. A code of 0 lets an error make the exit code 1.\n */\n readonly code?: number | undefined;\n}\n\n/** A lifecycle state tells where the service is in its life. */\nexport type LifecycleState = \"starting\" | \"running\" | \"draining\" | \"exited\";\n\n/** The lifecycle of a running service. */\nexport interface Lifecycle {\n readonly health: Health;\n readonly state: LifecycleState;\n /** This code is the exit code, or null before the exit. */\n readonly exitCode: number | null;\n /** These texts are the errors of the lifecycle. An error makes the exit code 1, unless an exit request gives another code. */\n readonly errors: readonly string[];\n /** This promise ends when the startup ends: the service runs, or its startup failed. */\n readonly started: Promise<void>;\n /** This promise gives the exit code when the shutdown ends. */\n readonly done: Promise<number>;\n /** This signal aborts after the poller stops: the background work of the service stops with it. */\n readonly signal: AbortSignal;\n /**\n * This method asks for the shutdown, as an exit signal does. A second request does not start a\n * second shutdown. It can give the exit code, when no request gave one before.\n */\n shutdown(cause?: string, options?: ShutdownOptions): Promise<number>;\n /**\n * This method does one request of a controller, on a route or a route pattern that the controller\n * declares. It gives the stream of the request: each item of the work, then one end. The service\n * refuses the request while it cannot take new work, and the shutdown can cut it. An undeclared\n * route throws, because it has no idempotency.\n */\n request<T>(controller: string, route: string, work: RequestFn<T>, options?: RequestOptions): RequestStream<T>;\n inFlight(controller?: string): number;\n /**\n * This method tells if a response can keep its connection open. It is false while the service is\n * not ready, thus each response then closes its connection.\n */\n keepAlive(): boolean;\n}\n\n/** The parts that the builder gives the lifecycle, beside the declaration. */\nexport interface Components {\n readonly transports: ReadonlyMap<string, TransportImpl>;\n readonly dependencies: ReadonlyMap<string, DependencyHandle>;\n readonly healthServer: HealthServer | null;\n readonly phaseWork: ReadonlyMap<string, readonly PhaseWork[]>;\n /** These are the functions of the route patterns, by controller and by pattern. */\n readonly choices?: ReadonlyMap<string, ReadonlyMap<string, OperationOf>> | undefined;\n /** This function stops the parts that the poller stage stops beside the checks: the watchdogs. */\n readonly stopPollers: () => void;\n}\n\nconst message = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/** This function gives the text of an error with its stack, when it has one. */\nconst withStack = (error: unknown): string =>\n error instanceof Error && typeof error.stack === \"string\" && error.stack.length > 0 ? error.stack : message(error);\n\nconst UNCAUGHT_NAMES: Readonly<Record<UncaughtOrigin, string>> = {\n uncaughtException: \"an uncaught exception\",\n unhandledRejection: \"an unhandled rejection\",\n};\n\n/**\n * This function gives the problems of a declaration that the lifecycle cannot start: a stage with\n * work and no declared phase. The runtime has no defaults, thus a transport without a drain phase\n * has no time to drain.\n */\nexport const lifecycleProblems = (description: ServiceDescription, components: Components): string[] => {\n const declared = new Set(description.shutdown.phases.map((phase) => phase.name));\n const needs = (stage: Stage, why: string): string[] =>\n declared.has(stage) ? [] : [`${description.name} has ${why}, thus it declares the phase \"${stage}\"`];\n const problems: string[] = [];\n for (const transport of description.transports)\n if (!components.transports.has(transport.name))\n problems.push(`transport ${transport.name} has no implementation: the runtime has no defaults`);\n if (components.transports.size > 0 || description.controllers.length > 0) {\n problems.push(...needs(\"stop intake\", \"transports or controllers\"));\n problems.push(...needs(\"drain\", \"transports or controllers\"));\n }\n if (components.transports.size > 0) problems.push(...needs(\"close transports\", \"transports\"));\n if (description.checks.length > 0) problems.push(...needs(\"stop the poller\", \"checks\"));\n if (components.dependencies.size > 0) problems.push(...needs(\"tear down dependencies\", \"dependency handles\"));\n if (components.healthServer !== null) problems.push(...needs(\"close the health server\", \"a health server\"));\n return problems;\n};\n\n/**\n * This function starts the lifecycle of a service. The startup has a sequence: the health server\n * first, then each dependency, then each transport, and the startup gate last. A trigger during the\n * startup gets its shutdown after the startup ends. The shutdown does the declared phases in their\n * sequence, each one capped. Only the lifecycle ends the process. Its exit code is the code of the\n * exit request, else 1 after an error, else 0.\n */\nexport const lifecycle = (\n description: ServiceDescription,\n runtime: Runtime,\n components: Components,\n options: RunOptions = {},\n /** This function receives the lifecycle before the startup begins. */\n bind: (life: Lifecycle) => void = () => {},\n): Lifecycle => {\n const clock = options.clock ?? realClock;\n const port = options.process ?? nodeProcess;\n const record = (machine: MachineName, from: string, to: string, on: string, detail?: string): void =>\n options.record?.({\n at: clock.now(),\n machine,\n instance: description.name,\n from,\n to,\n on,\n ...(detail === undefined ? {} : { detail }),\n });\n const service = new AbortController();\n const errors: string[] = [];\n const exitCodes = description.shutdown.exitCodes ?? {};\n const repeatPolicy = description.shutdown.onRepeatSignal;\n let state: LifecycleState = \"starting\";\n let exitCode: number | null = null;\n // the code of the first exit request that gives one\n let requested: number | undefined;\n let intakeStopped = false;\n let shutdownStarted = false;\n let failedStartup = false;\n // the exit manager: running, stopping, exited\n let exitState = \"running\";\n const moveExit = (to: string, on: string, detail?: string): void => {\n record(\"exit\", exitState, to, on, detail);\n exitState = to;\n };\n const fail = (cause: string): void => {\n errors.push(cause);\n // after an exit, the process has ended: the exit manager does not move again\n if (exitState !== \"exited\") record(\"exit\", exitState, exitState, \"error\", cause);\n };\n\n const requests = tracker(description.controllers, clock, (controller) => {\n if (state === \"starting\") return \"the service has not started\";\n if (state === \"exited\") return \"the service has exited\";\n // while it drains and before its intake stops, the service still serves: the platform can\n // still route a request to it until its endpoints update\n if (state === \"draining\") return null;\n return runtime.verdict().controllers[controller] === true ? null : `controller ${controller} is not ready`;\n }, components.choices);\n\n let finish: (code: number) => void = () => {};\n const done = new Promise<number>((resolve) => {\n finish = resolve;\n });\n // what started, thus what the shutdown stops\n let healthListening = false;\n const connected: Array<[string, DependencyHandle]> = [];\n const startedTransports: Array<[string, TransportImpl]> = [];\n // the startup exists before any part starts: a transport that asks for the shutdown in its start waits for it\n let startupEnded: () => void = () => {};\n const startup = new Promise<void>((resolve) => {\n startupEnded = resolve;\n });\n let offs: Array<() => void> = [];\n // the hold of the process, from the start of the lifecycle to its exit\n let release: () => void = () => {};\n\n /** This function ends the process with a code, one time, and removes each handler of a trigger and the hold. */\n const end = (code: number, on: string): void => {\n state = \"exited\";\n exitCode = code;\n for (const off of offs) off();\n offs = [];\n moveExit(\"exited\", on, `exit ${code}`);\n finish(code);\n // the hold ends at the exit, not at the stop of the intake: the drain and the teardown still need the process\n release();\n port.exit(code);\n };\n\n /**\n * This function receives a trigger of the process: the first one starts the shutdown. The cause\n * names the trigger, and a message that stands for a signal tells it.\n */\n const triggered = (trigger: ExitTrigger, cause: string = trigger): void => {\n if (exitState === \"exited\") return;\n if (shutdownStarted || exitState === \"stopping\") {\n // a signal while the shutdown runs obeys the declared policy. Another trigger, for example the\n // end of stdin after a SIGTERM, has no effect\n if (isExitSignal(trigger) && repeatPolicy === \"exit\") {\n fail(`${cause} came again while the shutdown ran, and the declaration exits at once`);\n end(1, \"exit.repeat\");\n return;\n }\n record(\"exit\", exitState, exitState, \"exit.repeat\", cause);\n return;\n }\n const code = exitCodes[trigger];\n void shutdown(cause, code === undefined ? {} : { code });\n };\n const messages = description.shutdown.messages ?? [];\n /** This function receives a message of the IPC channel. The first declared shape that it matches gives its trigger. */\n const received = (message: unknown): void => {\n const found = messages.find((each) => matchesMessage(each.match, message));\n if (found === undefined) return;\n if (found.as === undefined) triggered(\"ipc-message\");\n else triggered(found.as, `${found.as} (a message of the IPC channel)`);\n };\n const uncaught = options.uncaught;\n const uncaughtCode = uncaught?.exitCode !== undefined && isExitCode(uncaught.exitCode) ? uncaught.exitCode : 1;\n /**\n * This function receives an error that no code caught. A skipped error goes to the logger at\n * `warn`. Each other error is an error of the lifecycle, and it starts the shutdown with its code.\n */\n const caught = (error: unknown, origin: UncaughtOrigin): void => {\n if (exitState === \"exited\") return;\n const name = UNCAUGHT_NAMES[origin];\n let skip = false;\n try {\n skip = uncaught?.ignore?.(error, origin) === true;\n } catch {\n // a throw of the function skips nothing\n }\n if (skip) {\n try {\n options.logger?.log(\"warn\", `${name} was skipped: ${message(error)}`, { origin, error: withStack(error) });\n } catch {\n // the lifecycle does not depend on its logger\n }\n return;\n }\n // the error event goes to the logger at `error`, with the stack\n fail(`${name}: ${withStack(error)}`);\n void shutdown(`${name}: ${message(error)}`, { code: uncaughtCode });\n };\n\n /**\n * This function does the work of one phase, until its cap. It tells if the work ended in time. When\n * work is left at the cap, `excuse` gives the cause of a cap that is not a failure, or null.\n */\n const runPhase = async (\n phase: Phase,\n hold: boolean,\n work: ReadonlyArray<(context: PhaseContext) => Promise<void> | void>,\n excuse: (left: number) => string | null = () => null,\n ): Promise<{ readonly inTime: boolean; readonly excused: string | null }> => {\n const cap = valueIn(phase.cap, \"ms\");\n const deadline = clock.now() + cap;\n const capped = new AbortController();\n const context: PhaseContext = { deadline, signal: capped.signal, clock };\n let pending = work.length;\n const all = Promise.all(\n work.map(async (each) => {\n try {\n await each(context);\n } catch (error) {\n fail(`the phase ${phase.name} failed: ${message(error)}`);\n } finally {\n pending -= 1;\n }\n }),\n );\n let cancelCap: Cancel = () => {};\n // the timer of the cap starts after the timers of the work: at the same time, the work comes first\n const end = new Promise<\"cap\">((resolve) => {\n // the phase awaits its cap, thus the cap keeps the process alive (SYS-126)\n cancelCap = clock.after(cap, () => resolve(\"cap\"));\n });\n const first = await Promise.race([all.then(() => \"work\" as const), end]);\n if (first === \"work\" && hold) await end;\n // the work that is left is read at the cap, before the next phase changes it\n const excused = pending > 0 ? excuse(pending) : null;\n cancelCap();\n capped.abort(new Error(`the phase ${phase.name} reached its cap`));\n return { inTime: pending === 0, excused };\n };\n\n async function shutdown(cause = \"the service asked for it\", request: ShutdownOptions = {}): Promise<number> {\n if (request.code !== undefined && !isExitCode(request.code))\n throw new Error(`${description.name}: the exit code ${request.code} is not a whole number from 0 to 255`);\n if (exitState === \"exited\") return done;\n if (request.code !== undefined && requested === undefined) requested = request.code;\n if (shutdownStarted) {\n if (exitState === \"stopping\") record(\"exit\", exitState, exitState, \"exit.repeat\", cause);\n return done;\n }\n shutdownStarted = true;\n if (exitState === \"running\") moveExit(\"stopping\", \"exit.request\", cause);\n // a trigger during the startup gets its shutdown after the startup ends\n await startup;\n // a repeat signal can end the process while the startup ends: then only the timers stop\n if (exitState === \"exited\") {\n runtime.stop();\n components.stopPollers();\n return exitCode!;\n }\n state = \"draining\";\n runtime.drain();\n let drainState = \"running\";\n const moveDrain = (to: string, on: string, detail?: string): void => {\n record(\"drain\", drainState, to, on, detail);\n drainState = to;\n };\n const abortService = (): void => {\n if (service.signal.aborted) return;\n service.abort(new Error(\"the service stopped\"));\n record(\"drain\", drainState, drainState, \"signal.abort\");\n };\n const phases = description.shutdown.phases;\n let on = \"exit.request\";\n let detail: string | undefined;\n for (const phase of phases) {\n // after a repeat signal ends the process, no phase starts\n if (exitState === \"exited\") break;\n const rank = stageRank(phase.name);\n moveDrain(phase.name, on, detail);\n if (rank > ABORT_AFTER) abortService();\n const work: Array<(context: PhaseContext) => Promise<void> | void> = [];\n const owned = components.phaseWork.get(phase.name) ?? [];\n if (phase.name === \"stop intake\") {\n work.push(() => {\n intakeStopped = true;\n requests.stopIntake();\n });\n for (const [, impl] of startedTransports) work.push(() => impl.stopIntake());\n }\n // the cooperative abort of the drain: the cap less the window, not before the floor. It ends\n // with the phase, thus a drain that ends before it does not abort anything\n let cancelAbort: Cancel = () => {};\n let excuse: ((left: number) => string | null) | undefined;\n if (phase.name === \"drain\") {\n const cap = valueIn(phase.cap, \"ms\");\n const cooperative = new AbortController();\n const fireAt = cooperativeAbortAt(cap, description.shutdown.cooperativeWindow, description.shutdown.cooperativeFloor);\n // the drain awaits its cooperative abort, thus the timer keeps the process alive (SYS-126)\n cancelAbort = clock.after(fireAt, () => {\n cooperative.abort(new Error(\"the cooperative abort of the drain\"));\n requests.cooperativeAbort();\n record(\"drain\", drainState, drainState, \"drain.cooperative-abort\");\n });\n // the cut of the requests is the first work, thus its timer comes before the timer of the cap. A\n // transport can reach the deadline before the cut: httpTransport then waits for the answers of the cut (SYS-29)\n work.push(({ deadline }) => requests.drain(deadline));\n let transportsLeft = 0;\n for (const [, impl] of startedTransports)\n work.push(async ({ deadline }) => {\n transportsLeft += 1;\n try {\n await impl.drain(deadline, cooperative.signal);\n } finally {\n transportsLeft -= 1;\n }\n });\n // a phase fails only for its own work. At the cap, a drain whose transports wait only for the\n // bytes of their answers did its work: the cap is not a failure, and its event gives the count (SYS-29)\n excuse = (left) => {\n const holds = lateHolds(life);\n if (left > transportsLeft || transportsLeft > holds.length || holds.some((each) => each.running > 0)) return null;\n return `answers not flushed: ${holds.reduce((sum, each) => sum + each.unflushed, 0)}`;\n };\n }\n if (phase.name === \"close transports\")\n for (const [, impl] of startedTransports) work.push(() => impl.close());\n if (phase.name === \"stop the poller\")\n work.push(() => {\n runtime.stop();\n components.stopPollers();\n });\n if (phase.name === \"tear down dependencies\")\n work.push(async () => {\n for (const [, handle] of [...connected].reverse()) await handle.close();\n });\n if (phase.name === \"close the health server\" && healthListening && components.healthServer !== null) {\n const server = components.healthServer;\n work.push(() => server.close());\n }\n if (phase.name === \"flush the output\")\n // the owners write their last output first (a log or a trace exporter), then the port writes it\n work.push(async (context) => {\n await Promise.all(\n owned.map(async (each) => {\n try {\n await each(context);\n } catch (error) {\n fail(`the phase ${phase.name} failed: ${message(error)}`);\n }\n }),\n );\n await port.flush?.();\n });\n else for (const each of owned) work.push(each);\n const { inTime, excused } = await runPhase(phase, phase.name === \"fail readiness\", work, excuse);\n cancelAbort();\n if (!inTime && excused === null) fail(`the phase ${phase.name} did not end in its cap of ${valueIn(phase.cap, \"s\")} s`);\n on = inTime ? \"phase.done\" : \"phase.cap\";\n // the streams outside the lifecycle do not hold the drain, and its record gives their count\n const outsideCount = phase.name === \"drain\" ? takeOutside(life) : 0;\n const parts = [inTime ? null : excused, outsideCount > 0 ? `streams outside the lifecycle: ${outsideCount}` : null].filter(\n (part): part is string => part !== null,\n );\n detail = parts.length > 0 ? parts.join(\", \") : undefined;\n }\n if (exitState !== \"exited\") moveDrain(\"done\", on, detail);\n abortService();\n // a stage that the declaration does not name still stops: the checks, at the end\n runtime.stop();\n components.stopPollers();\n if (!intakeStopped) requests.stopIntake();\n // a repeat signal can end the process during the sequence: then it ended already\n if (exitState === \"exited\") return exitCode!;\n const code = requested !== undefined && requested !== 0 ? requested : errors.length > 0 ? 1 : 0;\n end(code, \"shutdown.done\");\n return code;\n }\n\n const life: Lifecycle = {\n health: runtime,\n get state() {\n return state;\n },\n get exitCode() {\n return exitCode;\n },\n get errors() {\n return [...errors];\n },\n started: startup,\n done,\n signal: service.signal,\n shutdown,\n // the lifecycle owns each stream that it makes: its drain cuts the stream (SYS-29)\n request: (controller, route, work, request) => ownStream(requests.request(controller, route, work, request), life),\n inFlight: (controller) => requests.inFlight(controller),\n keepAlive: () => state === \"running\" && runtime.verdict().ready,\n };\n\n bind(life);\n release = port.hold?.() ?? (() => {});\n offs = [...EXIT_SIGNALS, ...(description.shutdown.triggers ?? [])].map((trigger: ExitTrigger) =>\n port.on(trigger, trigger === \"ipc-message\" ? received : () => triggered(trigger)),\n );\n // the handler of the uncaught errors goes at the exit, with the handlers of the triggers\n if (uncaught !== undefined && port.onUncaught !== undefined) offs.push(port.onUncaught(caught));\n\n void (async (): Promise<void> => {\n const started = (what: string): void => record(\"gate\", \"starting\", \"starting\", \"component.started\", what);\n try {\n runtime.beginStartup();\n if (components.healthServer !== null) {\n await components.healthServer.listen(runtime);\n healthListening = true;\n started(\"the health server\");\n }\n for (const dependency of description.dependencies) {\n const handle = components.dependencies.get(dependency.name);\n if (handle === undefined) continue;\n await handle.connect(service.signal);\n connected.push([dependency.name, handle]);\n started(`dependency ${dependency.name}`);\n }\n for (const transport of description.transports) {\n const impl = components.transports.get(transport.name)!;\n await impl.start(service.signal, life);\n startedTransports.push([transport.name, impl]);\n started(`${transport.kind} ${transport.name}`);\n }\n await runtime.warmUp();\n if (state === \"starting\") state = \"running\";\n } catch (error) {\n const cause = `the startup failed: ${message(error)}`;\n failedStartup = true;\n runtime.failStartup(cause);\n fail(cause);\n if (exitState === \"running\") moveExit(\"stopping\", \"startup.fail\", cause);\n else if (exitState === \"stopping\") record(\"exit\", exitState, exitState, \"startup.fail\", cause);\n } finally {\n startupEnded();\n }\n })();\n // a failed startup shuts down what started. An exit request during the startup waits for it\n void startup.then(() => {\n if (failedStartup && !shutdownStarted && exitState !== \"exited\") void shutdown(\"the startup failed\");\n });\n\n return life;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgFA,MAAa,SAAS;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAKA,MAAa,aAAa,SAA0B,OAA6B,QAAQ,IAAI;;AAG7F,MAAM,cAAc,UAAU,iBAAiB;;;;;;AAO/C,MAAa,sBAAsB,KAAa,QAAgB,QAA0B,WAAmB;CAC3G,MAAM,SAAS,OAAO,UAAU,aAAa,OAAO,oBAAoB,QAAQ,QAAQ,IAAI;CAC5F,OAAO,KAAK,IAAI,MAAM,QAAQ,UAAU,SAAS,IAAI,MAAM,CAAC;AAC9D;;AA4BA,MAAa,oBAAoB,aAAoD;CACnF,MAAM,OAAO,UAAU;CACvB,OAAO,SAAS,KAAA,KAAa,WAAW,IAAI,IAAI,CAAC,IAAI,CAAC,iBAAiB,KAAK,0DAA0D;AACxI;AA4DA,MAAM,WAAW,UACf,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;;AAGvD,MAAM,aAAa,UACjB,iBAAiB,SAAS,OAAO,MAAM,UAAU,YAAY,MAAM,MAAM,SAAS,IAAI,MAAM,QAAQ,QAAQ,KAAK;AAEnH,MAAM,iBAA2D;CAC/D,mBAAmB;CACnB,oBAAoB;AACtB;;;;;;AAOA,MA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,WAAW,WAAW,gBAAgB,KAAK;EAC/F,UAAU;GACR,aAAa;EACf;CACF,EAAA,CAAG;CAEH,QAAa,WAAW;EACtB,IAAI,iBAAiB,CAAC,mBAAmB,cAAc,UAAU,SAAc,oBAAoB;CACrG,CAAC;CAED,OAAO;AACT"}
|
package/build/poller.js
CHANGED
|
@@ -113,6 +113,7 @@ const poller = (options) => {
|
|
|
113
113
|
let polled;
|
|
114
114
|
step("tick", () => {
|
|
115
115
|
next = clock.after(jittered(), tick);
|
|
116
|
+
if (options.unrefLoop === true) next.unref?.();
|
|
116
117
|
polled = once();
|
|
117
118
|
});
|
|
118
119
|
polled.then(handle);
|
|
@@ -133,6 +134,7 @@ const poller = (options) => {
|
|
|
133
134
|
step("start", () => {
|
|
134
135
|
looping = true;
|
|
135
136
|
next = clock.after(Math.max(0, delay), tick);
|
|
137
|
+
if (options.unrefLoop === true) next.unref?.();
|
|
136
138
|
});
|
|
137
139
|
},
|
|
138
140
|
jittered,
|
package/build/poller.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"poller.js","names":[],"sources":["../src/poller.ts"],"sourcesContent":["import { valueIn } from \"@mark1russell7/quantity\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { Outcome, Result, Trace } from \"./latch.ts\";\nimport type { Poll } from \"./timing.ts\";\n\n/**\n * A check function measures one step of a connection. It ends with nothing or `\"ok\"` for a pass,\n * or with `\"error\"` or `\"indeterminate\"`. A throw is an error with a flag. The runtime aborts the\n * signal at the timeout of the poll.\n */\nexport type CheckFn = (signal: AbortSignal) => Outcome | void | Promise<Outcome | void>;\n\n/** A poller starts one check on its own loop, and gives each result to `record`. */\nexport interface Poller {\n /** This result is the latest one, or null before the first poll. */\n readonly last: Result | null;\n /** This method polls one time at once, outside the loop, and gives the result. */\n pollNow(): Promise<Result>;\n /** This method starts the loop. The first poll of the loop comes after `delay` milliseconds. */\n start(delay: number): void;\n /** This method gives the next delay of the loop: the interval, with the jitter. */\n jittered(): number;\n stop(): void;\n}\n\nexport interface PollerOptions {\n readonly name: string;\n readonly poll: Poll;\n readonly run: CheckFn;\n readonly clock: Clock;\n readonly random: () => number;\n /** This function tells if the force-fail list names the check at this time. */\n readonly forced: () => boolean;\n readonly record: (result: Result) => void;\n /**\n * This function receives each transition of the poller. Its states are `idle`, `waiting`,\n * `calling`, `hung` (a call that outlived its timeout) and `stopped`.\n */\n readonly trace?: Trace | undefined;\n}\n\nconst message = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/**\n * This function makes a poller. The loop is on a fixed delay from the start of each poll. Thus the\n * next poll starts one interval after the current poll starts, with the jitter (±20 % is 0.2).\n * The timing algebra of the declaration uses this model.\n *\n * Each poll makes a new measurement. While a use of the check is pending, the poller does not\n * start the check again. Such a poll fails at once with the same cause, and the sequence of\n * failures continues.\n */\nexport const poller = (options: PollerOptions): Poller => {\n const { clock, poll, run } = options;\n const interval = valueIn(poll.interval, \"ms\");\n const timeout = valueIn(poll.timeout, \"ms\");\n let last: Result | null = null;\n let next: Cancel | null = null;\n let stopped = false;\n let looping = false;\n // the call that has not ended, and when it started; `late` once the call outlived its timeout\n let pending: { readonly since: number; late: boolean } | null = null;\n // the polls in flight: stop() ends each one, and its timer\n const active = new Set<() => void>();\n\n /** This function gives the name of the state, as the machine document of the poller names it. */\n const named = (): string =>\n stopped\n ? \"stopped\"\n : pending !== null\n ? pending.late\n ? \"hung\"\n : \"calling\"\n : looping\n ? \"waiting\"\n : \"idle\";\n const step = (on: string, change: () => void): void => {\n const from = named();\n change();\n options.trace?.(from, named(), on);\n };\n\n const result = (\n outcome: Outcome,\n started: number,\n fields: Partial<Pick<Result, \"cause\" | \"timedOut\" | \"thrown\" | \"forced\">> = {},\n ): Result => ({\n outcome,\n at: clock.now(),\n took: clock.now() - started,\n cause: fields.cause ?? null,\n timedOut: fields.timedOut ?? false,\n thrown: fields.thrown ?? false,\n forced: fields.forced ?? false,\n });\n\n const once = (): Promise<Result> => {\n const started = clock.now();\n if (options.forced())\n return Promise.resolve(result(\"error\", started, { cause: \"the force-fail list names it\", forced: true }));\n if (pending !== null) {\n const cause = `its call of ${Math.round(started - pending.since)} ms ago is still pending`;\n return Promise.resolve(result(\"error\", started, { cause }));\n }\n const controller = new AbortController();\n return new Promise<Result>((resolve) => {\n let done = false;\n const finish = (value: Result): void => {\n if (done) return;\n done = true;\n active.delete(abandon);\n cancel();\n resolve(value);\n };\n const abandon = (): void => {\n controller.abort();\n finish(result(\"error\", started, { cause: \"the runtime stopped\" }));\n };\n active.add(abandon);\n const call = { since: started, late: false };\n pending = call;\n const cancel = clock.after(timeout, () => {\n controller.abort();\n // the poll fails at its timeout. The call stays pending until it settles\n step(\"timeout\", () => {\n if (pending === call) call.late = true;\n });\n finish(result(\"error\", started, { cause: `no answer in ${timeout} ms`, timedOut: true }));\n });\n const settled = (): void => {\n if (pending !== call) return;\n step(call.late ? \"late-answer\" : \"answer\", () => {\n pending = null;\n });\n };\n let answer: Promise<Outcome | void>;\n try {\n answer = Promise.resolve(run(controller.signal));\n } catch (error) {\n answer = Promise.reject(error);\n }\n answer.then(\n (value) => {\n settled();\n const outcome = value ?? \"ok\";\n finish(result(outcome, started, outcome === \"ok\" ? {} : { cause: `the check gave ${outcome}` }));\n },\n (error: unknown) => {\n settled();\n finish(result(\"error\", started, { cause: message(error), thrown: true }));\n },\n );\n });\n };\n\n const handle = (value: Result): Result => {\n last = value;\n if (!stopped) options.record(value);\n return value;\n };\n\n const jittered = (): number => interval * (1 + poll.jitter * (2 * options.random() - 1));\n\n const tick = (): void => {\n next = null;\n if (stopped) return;\n let polled: Promise<Result> | undefined;\n step(\"tick\", () => {\n next = clock.after(jittered(), tick);\n polled = once();\n });\n void polled!.then(handle);\n };\n\n return {\n get last() {\n return last;\n },\n pollNow: () => {\n let polled: Promise<Result> | undefined;\n step(\"sweep\", () => {\n polled = once();\n });\n return polled!.then(handle);\n },\n start(delay) {\n if (stopped || next !== null) return;\n step(\"start\", () => {\n looping = true;\n next = clock.after(Math.max(0, delay), tick);\n });\n },\n jittered,\n stop() {\n if (stopped) return;\n step(\"stop\", () => {\n stopped = true;\n next?.();\n next = null;\n });\n for (const abandon of [...active]) abandon();\n },\n };\n};\n"],"mappings":";;AAyCA,MAAM,WAAW,UACf,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;;;;;;;;;;AAWvD,MAAa,UAAU,YAAmC;CACxD,MAAM,EAAE,OAAO,MAAM,QAAQ;CAC7B,MAAM,WAAW,QAAQ,KAAK,UAAU,IAAI;CAC5C,MAAM,UAAU,QAAQ,KAAK,SAAS,IAAI;CAC1C,IAAI,OAAsB;CAC1B,IAAI,OAAsB;CAC1B,IAAI,UAAU;CACd,IAAI,UAAU;CAEd,IAAI,UAA4D;CAEhE,MAAM,yBAAS,IAAI,IAAgB;;CAGnC,MAAM,cACJ,UACI,YACA,YAAY,OACV,QAAQ,OACN,SACA,YACF,UACE,YACA;CACV,MAAM,QAAQ,IAAY,WAA6B;EACrD,MAAM,OAAO,MAAM;EACnB,OAAO;EACP,QAAQ,QAAQ,MAAM,MAAM,GAAG,EAAE;CACnC;CAEA,MAAM,UACJ,SACA,SACA,SAA4E,CAAC,OACjE;EACZ;EACA,IAAI,MAAM,IAAI;EACd,MAAM,MAAM,IAAI,IAAI;EACpB,OAAO,OAAO,SAAS;EACvB,UAAU,OAAO,YAAY;EAC7B,QAAQ,OAAO,UAAU;EACzB,QAAQ,OAAO,UAAU;CAC3B;CAEA,MAAM,aAA8B;EAClC,MAAM,UAAU,MAAM,IAAI;EAC1B,IAAI,QAAQ,OAAO,GACjB,OAAO,QAAQ,QAAQ,OAAO,SAAS,SAAS;GAAE,OAAO;GAAgC,QAAQ;EAAK,CAAC,CAAC;EAC1G,IAAI,YAAY,MAAM;GACpB,MAAM,QAAQ,eAAe,KAAK,MAAM,UAAU,QAAQ,KAAK,EAAE;GACjE,OAAO,QAAQ,QAAQ,OAAO,SAAS,SAAS,EAAE,MAAM,CAAC,CAAC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AClC,OAAO;CACT;CAEA,MAAM,iBAAyB,YAAY,IAAI,KAAK,UAAU,IAAI,QAAQ,OAAO,IAAI;CAErF,MAAM,aAAmB;EACvB,OAAO;EACP,IAAI,SAAS;EACb,IAAI;EACJ,KAAK,cAAc;GACjB,OAAO,MAAM,MAAM,SAAS,GAAG,IAAI;GACnC,SAAS,KAAK;EAChB,CAAC;EACD,OAAa,KAAK,MAAM;CAC1B;CAEA,OAAO;EACL,IAAI,OAAO;GACT,OAAO;EACT;EACA,eAAe;GACb,IAAI;GACJ,KAAK,eAAe;IAClB,SAAS,KAAK;GAChB,CAAC;GACD,OAAO,OAAQ,KAAK,MAAM;EAC5B;EACA,MAAM,OAAO;GACX,IAAI,WAAW,SAAS,MAAM;GAC9B,KAAK,eAAe;IAClB,UAAU;IACV,OAAO,MAAM,MAAM,KAAK,IAAI,GAAG,KAAK,GAAG,IAAI;GAC7C,CAAC;EACH;EACA;EACA,OAAO;GACL,IAAI,SAAS;GACb,KAAK,cAAc;IACjB,UAAU;IACV,OAAO;IACP,OAAO;GACT,CAAC;GACD,KAAK,MAAM,WAAW,CAAC,GAAG,MAAM,GAAG,QAAQ;EAC7C;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"poller.js","names":[],"sources":["../src/poller.ts"],"sourcesContent":["import { valueIn } from \"@mark1russell7/quantity\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { Outcome, Result, Trace } from \"./latch.ts\";\nimport type { Poll } from \"./timing.ts\";\n\n/**\n * A check function measures one step of a connection. It ends with nothing or `\"ok\"` for a pass,\n * or with `\"error\"` or `\"indeterminate\"`. A throw is an error with a flag. The runtime aborts the\n * signal at the timeout of the poll.\n */\nexport type CheckFn = (signal: AbortSignal) => Outcome | void | Promise<Outcome | void>;\n\n/** A poller starts one check on its own loop, and gives each result to `record`. */\nexport interface Poller {\n /** This result is the latest one, or null before the first poll. */\n readonly last: Result | null;\n /** This method polls one time at once, outside the loop, and gives the result. */\n pollNow(): Promise<Result>;\n /** This method starts the loop. The first poll of the loop comes after `delay` milliseconds. */\n start(delay: number): void;\n /** This method gives the next delay of the loop: the interval, with the jitter. */\n jittered(): number;\n stop(): void;\n}\n\nexport interface PollerOptions {\n readonly name: string;\n readonly poll: Poll;\n readonly run: CheckFn;\n readonly clock: Clock;\n readonly random: () => number;\n /** This function tells if the force-fail list names the check at this time. */\n readonly forced: () => boolean;\n readonly record: (result: Result) => void;\n /**\n * This function receives each transition of the poller. Its states are `idle`, `waiting`,\n * `calling`, `hung` (a call that outlived its timeout) and `stopped`.\n */\n readonly trace?: Trace | undefined;\n /**\n * True makes the timer of the loop not keep a Node process alive. A loop that only watches other\n * work uses it: that work keeps the process alive. The default is false. The timeout of a poll\n * keeps the process alive at each value, because a caller can await a poll (SYS-126).\n */\n readonly unrefLoop?: boolean | undefined;\n}\n\nconst message = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/**\n * This function makes a poller. The loop is on a fixed delay from the start of each poll. Thus the\n * next poll starts one interval after the current poll starts, with the jitter (±20 % is 0.2).\n * The timing algebra of the declaration uses this model.\n *\n * Each poll makes a new measurement. While a use of the check is pending, the poller does not\n * start the check again. Such a poll fails at once with the same cause, and the sequence of\n * failures continues.\n */\nexport const poller = (options: PollerOptions): Poller => {\n const { clock, poll, run } = options;\n const interval = valueIn(poll.interval, \"ms\");\n const timeout = valueIn(poll.timeout, \"ms\");\n let last: Result | null = null;\n let next: Cancel | null = null;\n let stopped = false;\n let looping = false;\n // the call that has not ended, and when it started; `late` once the call outlived its timeout\n let pending: { readonly since: number; late: boolean } | null = null;\n // the polls in flight: stop() ends each one, and its timer\n const active = new Set<() => void>();\n\n /** This function gives the name of the state, as the machine document of the poller names it. */\n const named = (): string =>\n stopped\n ? \"stopped\"\n : pending !== null\n ? pending.late\n ? \"hung\"\n : \"calling\"\n : looping\n ? \"waiting\"\n : \"idle\";\n const step = (on: string, change: () => void): void => {\n const from = named();\n change();\n options.trace?.(from, named(), on);\n };\n\n const result = (\n outcome: Outcome,\n started: number,\n fields: Partial<Pick<Result, \"cause\" | \"timedOut\" | \"thrown\" | \"forced\">> = {},\n ): Result => ({\n outcome,\n at: clock.now(),\n took: clock.now() - started,\n cause: fields.cause ?? null,\n timedOut: fields.timedOut ?? false,\n thrown: fields.thrown ?? false,\n forced: fields.forced ?? false,\n });\n\n const once = (): Promise<Result> => {\n const started = clock.now();\n if (options.forced())\n return Promise.resolve(result(\"error\", started, { cause: \"the force-fail list names it\", forced: true }));\n if (pending !== null) {\n const cause = `its call of ${Math.round(started - pending.since)} ms ago is still pending`;\n return Promise.resolve(result(\"error\", started, { cause }));\n }\n const controller = new AbortController();\n return new Promise<Result>((resolve) => {\n let done = false;\n const finish = (value: Result): void => {\n if (done) return;\n done = true;\n active.delete(abandon);\n cancel();\n resolve(value);\n };\n const abandon = (): void => {\n controller.abort();\n finish(result(\"error\", started, { cause: \"the runtime stopped\" }));\n };\n active.add(abandon);\n const call = { since: started, late: false };\n pending = call;\n // a caller can await this poll, thus its timeout keeps the process alive (SYS-126)\n const cancel = clock.after(timeout, () => {\n controller.abort();\n // the poll fails at its timeout. The call stays pending until it settles\n step(\"timeout\", () => {\n if (pending === call) call.late = true;\n });\n finish(result(\"error\", started, { cause: `no answer in ${timeout} ms`, timedOut: true }));\n });\n const settled = (): void => {\n if (pending !== call) return;\n step(call.late ? \"late-answer\" : \"answer\", () => {\n pending = null;\n });\n };\n let answer: Promise<Outcome | void>;\n try {\n answer = Promise.resolve(run(controller.signal));\n } catch (error) {\n answer = Promise.reject(error);\n }\n answer.then(\n (value) => {\n settled();\n const outcome = value ?? \"ok\";\n finish(result(outcome, started, outcome === \"ok\" ? {} : { cause: `the check gave ${outcome}` }));\n },\n (error: unknown) => {\n settled();\n finish(result(\"error\", started, { cause: message(error), thrown: true }));\n },\n );\n });\n };\n\n const handle = (value: Result): Result => {\n last = value;\n if (!stopped) options.record(value);\n return value;\n };\n\n const jittered = (): number => interval * (1 + poll.jitter * (2 * options.random() - 1));\n\n const tick = (): void => {\n next = null;\n if (stopped) return;\n let polled: Promise<Result> | undefined;\n step(\"tick\", () => {\n next = clock.after(jittered(), tick);\n if (options.unrefLoop === true) next.unref?.();\n polled = once();\n });\n void polled!.then(handle);\n };\n\n return {\n get last() {\n return last;\n },\n pollNow: () => {\n let polled: Promise<Result> | undefined;\n step(\"sweep\", () => {\n polled = once();\n });\n return polled!.then(handle);\n },\n start(delay) {\n if (stopped || next !== null) return;\n step(\"start\", () => {\n looping = true;\n next = clock.after(Math.max(0, delay), tick);\n if (options.unrefLoop === true) next.unref?.();\n });\n },\n jittered,\n stop() {\n if (stopped) return;\n step(\"stop\", () => {\n stopped = true;\n next?.();\n next = null;\n });\n for (const abandon of [...active]) abandon();\n },\n };\n};\n"],"mappings":";;AA+CA,MAAM,WAAW,UACf,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;;;;;;;;;;AAWvD,MAAa,UAAU,YAAmC;CACxD,MAAM,EAAE,OAAO,MAAM,QAAQ;CAC7B,MAAM,WAAW,QAAQ,KAAK,UAAU,IAAI;CAC5C,MAAM,UAAU,QAAQ,KAAK,SAAS,IAAI;CAC1C,IAAI,OAAsB;CAC1B,IAAI,OAAsB;CAC1B,IAAI,UAAU;CACd,IAAI,UAAU;CAEd,IAAI,UAA4D;CAEhE,MAAM,yBAAS,IAAI,IAAgB;;CAGnC,MAAM,cACJ,UACI,YACA,YAAY,OACV,QAAQ,OACN,SACA,YACF,UACE,YACA;CACV,MAAM,QAAQ,IAAY,WAA6B;EACrD,MAAM,OAAO,MAAM;EACnB,OAAO;EACP,QAAQ,QAAQ,MAAM,MAAM,GAAG,EAAE;CACnC;CAEA,MAAM,UACJ,SACA,SACA,SAA4E,CAAC,OACjE;EACZ;EACA,IAAI,MAAM,IAAI;EACd,MAAM,MAAM,IAAI,IAAI;EACpB,OAAO,OAAO,SAAS;EACvB,UAAU,OAAO,YAAY;EAC7B,QAAQ,OAAO,UAAU;EACzB,QAAQ,OAAO,UAAU;CA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