@mark1russell7/service 0.8.18 → 0.8.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -0
- package/build/backoff.d.ts +44 -2
- package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
- package/build/builder.js +499 -0
- package/build/builder.js.map +1 -0
- package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
- package/build/channel.d.ts +1 -1
- package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
- package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
- package/build/client/core.js.map +1 -0
- package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
- package/build/client/dial.js +52 -0
- package/build/client/dial.js.map +1 -0
- package/build/client/machine.js +29 -0
- package/build/client/machine.js.map +1 -0
- package/build/client/meets.d.ts +35 -0
- package/build/client/meets.js +78 -0
- package/build/client/meets.js.map +1 -0
- package/build/clock.d.ts +1 -1
- package/build/conformance.d.ts +122 -0
- package/build/conformance.js +470 -0
- package/build/conformance.js.map +1 -0
- package/build/contract.d.ts +28 -0
- package/build/contract.js +184 -0
- package/build/contract.js.map +1 -0
- package/build/description.d.ts +161 -0
- package/build/description.js +11 -0
- package/build/description.js.map +1 -0
- package/build/drains.js +35 -0
- package/build/drains.js.map +1 -0
- package/build/events.d.ts +25 -0
- package/build/fakes.d.ts +43 -0
- package/build/fakes.js +93 -0
- package/build/fakes.js.map +1 -0
- package/build/grpc/client.d.ts +153 -0
- package/build/grpc/client.js +474 -0
- package/build/grpc/client.js.map +1 -0
- package/build/grpc/connection.d.ts +97 -0
- package/build/grpc/connection.js +59 -0
- package/build/grpc/connection.js.map +1 -0
- package/build/grpc/machine.d.ts +12 -0
- package/build/grpc/machine.js +149 -0
- package/build/grpc/machine.js.map +1 -0
- package/build/grpc/meets.d.ts +14 -0
- package/build/grpc/meets.js +105 -0
- package/build/grpc/meets.js.map +1 -0
- package/build/grpc/starting.d.ts +33 -0
- package/build/grpc/starting.js +89 -0
- package/build/grpc/starting.js.map +1 -0
- package/build/grpc.d.ts +9 -303
- package/build/grpc.js +7 -854
- package/build/health.d.ts +93 -0
- package/build/health.js +223 -0
- package/build/health.js.map +1 -0
- package/build/heartbeat.d.ts +1 -1
- package/build/host/discovery.d.ts +61 -0
- package/build/host/discovery.js +113 -0
- package/build/host/discovery.js.map +1 -0
- package/build/host/env.d.ts +14 -0
- package/build/host/env.js +57 -0
- package/build/host/env.js.map +1 -0
- package/build/host/fakes.d.ts +82 -0
- package/build/host/fakes.js +239 -0
- package/build/host/fakes.js.map +1 -0
- package/build/host/group.d.ts +142 -0
- package/build/host/group.js +517 -0
- package/build/host/group.js.map +1 -0
- package/build/host/install.d.ts +96 -0
- package/build/host/install.js +330 -0
- package/build/host/install.js.map +1 -0
- package/build/host/lock.d.ts +78 -0
- package/build/host/lock.js +190 -0
- package/build/host/lock.js.map +1 -0
- package/build/host/logs.d.ts +26 -0
- package/build/host/logs.js +48 -0
- package/build/host/logs.js.map +1 -0
- package/build/host/node.d.ts +14 -0
- package/build/host/node.js +309 -0
- package/build/host/node.js.map +1 -0
- package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
- package/build/host/ports.js +17 -0
- package/build/host/ports.js.map +1 -0
- package/build/host/probes.d.ts +51 -0
- package/build/host/probes.js +139 -0
- package/build/host/probes.js.map +1 -0
- package/build/host/processes.d.ts +32 -0
- package/build/host/processes.js +63 -0
- package/build/host/processes.js.map +1 -0
- package/build/host/render.d.ts +84 -0
- package/build/host/render.js +235 -0
- package/build/host/render.js.map +1 -0
- package/build/host/watch.d.ts +90 -0
- package/build/host/watch.js +165 -0
- package/build/host/watch.js.map +1 -0
- package/build/host.d.ts +13 -671
- package/build/host.js +12 -2126
- package/build/http/answers.js +29 -0
- package/build/http/answers.js.map +1 -0
- package/build/http/fake-server.js +61 -0
- package/build/http/fake-server.js.map +1 -0
- package/build/http/outcome.d.ts +115 -0
- package/build/http/outcome.js +325 -0
- package/build/http/outcome.js.map +1 -0
- package/build/http/probes.d.ts +83 -0
- package/build/http/probes.js +232 -0
- package/build/http/probes.js.map +1 -0
- package/build/http/transport.d.ts +165 -0
- package/build/http/transport.js +517 -0
- package/build/http/transport.js.map +1 -0
- package/build/http-client/client.d.ts +121 -0
- package/build/http-client/client.js +330 -0
- package/build/http-client/client.js.map +1 -0
- package/build/http-client/connection.d.ts +78 -0
- package/build/http-client/connection.js +54 -0
- package/build/http-client/connection.js.map +1 -0
- package/build/http-client/machine.d.ts +14 -0
- package/build/http-client/machine.js +109 -0
- package/build/http-client/machine.js.map +1 -0
- package/build/http-client/meets.d.ts +11 -0
- package/build/http-client/meets.js +74 -0
- package/build/http-client/meets.js.map +1 -0
- package/build/http-client/session.d.ts +87 -0
- package/build/http-client/session.js +99 -0
- package/build/http-client/session.js.map +1 -0
- package/build/http-client/starting.d.ts +25 -0
- package/build/http-client/starting.js +65 -0
- package/build/http-client/starting.js.map +1 -0
- package/build/http-client.d.ts +9 -330
- package/build/http-client.js +8 -707
- package/build/http.d.ts +5 -353
- package/build/http.js +3 -1086
- package/build/identity.d.ts +16 -0
- package/build/identity.js +44 -0
- package/build/identity.js.map +1 -0
- package/build/index.d.ts +35 -412
- package/build/index.js +24 -3277
- package/build/knobs.d.ts +1 -0
- package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
- package/build/knobs.js.map +1 -0
- package/build/latch.d.ts +29 -0
- package/build/latch.js +122 -0
- package/build/latch.js.map +1 -0
- package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
- package/build/law.js +149 -0
- package/build/law.js.map +1 -0
- package/build/lifecycle.d.ts +144 -0
- package/build/lifecycle.js +411 -0
- package/build/lifecycle.js.map +1 -0
- package/build/limiter/machine.d.ts +40 -0
- package/build/limiter/machine.js +279 -0
- package/build/limiter/machine.js.map +1 -0
- package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
- package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
- package/build/limiter/policy.js.map +1 -0
- package/build/{limiter-Cm8nC-Gd.d.ts → limiter/quota.d.ts} +50 -76
- package/build/{limiter-Bgy6Gmvl.js → limiter/quota.js} +32 -425
- package/build/limiter/quota.js.map +1 -0
- package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
- package/build/limiter/store.js +145 -0
- package/build/limiter/store.js.map +1 -0
- package/build/limiter.d.ts +4 -3
- package/build/limiter.js +4 -2
- package/build/lint.d.ts +152 -0
- package/build/lint.js +576 -0
- package/build/lint.js.map +1 -0
- package/build/logger.d.ts +71 -0
- package/build/logger.js +183 -0
- package/build/logger.js.map +1 -0
- package/build/machines.d.ts +41 -0
- package/build/machines.js +451 -0
- package/build/machines.js.map +1 -0
- package/build/metrics.d.ts +53 -0
- package/build/metrics.js +111 -0
- package/build/metrics.js.map +1 -0
- package/build/mongodb/client.d.ts +131 -0
- package/build/mongodb/client.js +388 -0
- package/build/mongodb/client.js.map +1 -0
- package/build/mongodb/connection.d.ts +112 -0
- package/build/mongodb/connection.js +12 -0
- package/build/mongodb/connection.js.map +1 -0
- package/build/mongodb/machine.d.ts +14 -0
- package/build/mongodb/machine.js +122 -0
- package/build/mongodb/machine.js.map +1 -0
- package/build/mongodb/meets.d.ts +15 -0
- package/build/mongodb/meets.js +103 -0
- package/build/mongodb/meets.js.map +1 -0
- package/build/mongodb/starting.d.ts +29 -0
- package/build/mongodb/starting.js +77 -0
- package/build/mongodb/starting.js.map +1 -0
- package/build/mongodb.d.ts +8 -296
- package/build/mongodb.js +7 -682
- package/build/operation.d.ts +27 -0
- package/build/{operation-DF73RZOI.js → operation.js} +2 -2
- package/build/operation.js.map +1 -0
- package/build/otel.d.ts +2 -2
- package/build/pg/client.d.ts +96 -0
- package/build/pg/client.js +277 -0
- package/build/pg/client.js.map +1 -0
- package/build/pg/connection.d.ts +75 -0
- package/build/pg/connection.js +11 -0
- package/build/pg/connection.js.map +1 -0
- package/build/pg/machine.d.ts +13 -0
- package/build/pg/machine.js +111 -0
- package/build/pg/machine.js.map +1 -0
- package/build/pg/meets.d.ts +14 -0
- package/build/pg/meets.js +83 -0
- package/build/pg/meets.js.map +1 -0
- package/build/pg/starting.d.ts +26 -0
- package/build/pg/starting.js +62 -0
- package/build/pg/starting.js.map +1 -0
- package/build/pg.d.ts +8 -219
- package/build/pg.js +7 -525
- package/build/poller.d.ts +9 -0
- package/build/poller.js +152 -0
- package/build/poller.js.map +1 -0
- package/build/process.d.ts +114 -0
- package/build/process.js +170 -0
- package/build/process.js.map +1 -0
- package/build/profiles.d.ts +68 -0
- package/build/profiles.js +120 -0
- package/build/profiles.js.map +1 -0
- package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
- package/build/queue.js +279 -0
- package/build/queue.js.map +1 -0
- package/build/rabbitmq/client.d.ts +144 -0
- package/build/rabbitmq/client.js +426 -0
- package/build/rabbitmq/client.js.map +1 -0
- package/build/rabbitmq/connection.d.ts +91 -0
- package/build/rabbitmq/connection.js +15 -0
- package/build/rabbitmq/connection.js.map +1 -0
- package/build/rabbitmq/machine.d.ts +13 -0
- package/build/rabbitmq/machine.js +159 -0
- package/build/rabbitmq/machine.js.map +1 -0
- package/build/rabbitmq/meets.d.ts +12 -0
- package/build/rabbitmq/meets.js +96 -0
- package/build/rabbitmq/meets.js.map +1 -0
- package/build/rabbitmq/starting.d.ts +27 -0
- package/build/rabbitmq/starting.js +67 -0
- package/build/rabbitmq/starting.js.map +1 -0
- package/build/rabbitmq.d.ts +8 -283
- package/build/rabbitmq.js +7 -742
- package/build/redis/client.d.ts +86 -0
- package/build/redis/client.js +285 -0
- package/build/redis/client.js.map +1 -0
- package/build/redis/connection.d.ts +57 -0
- package/build/redis/connection.js +11 -0
- package/build/redis/connection.js.map +1 -0
- package/build/redis/limiter.d.ts +43 -0
- package/build/redis/limiter.js +164 -0
- package/build/redis/limiter.js.map +1 -0
- package/build/redis/machine.d.ts +12 -0
- package/build/redis/machine.js +144 -0
- package/build/redis/machine.js.map +1 -0
- package/build/redis/meets.d.ts +11 -0
- package/build/redis/meets.js +75 -0
- package/build/redis/meets.js.map +1 -0
- package/build/redis/operations.d.ts +5 -0
- package/build/redis/operations.js +114 -0
- package/build/redis/operations.js.map +1 -0
- package/build/redis.d.ts +10 -207
- package/build/redis.js +9 -771
- package/build/requests.d.ts +66 -0
- package/build/requests.js +279 -0
- package/build/requests.js.map +1 -0
- package/build/retrier.d.ts +62 -0
- package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
- package/build/retrier.js.map +1 -0
- package/build/routes.d.ts +35 -0
- package/build/routes.js +77 -0
- package/build/routes.js.map +1 -0
- package/build/rules.d.ts +19 -2
- package/build/stops.d.ts +51 -0
- package/build/stops.js +86 -0
- package/build/stops.js.map +1 -0
- package/build/testing.d.ts +8 -270
- package/build/testing.js +4 -1027
- package/build/testing.js.map +1 -1
- package/build/timing.d.ts +63 -0
- package/build/{timing-DZl36uXs.js → timing.js} +2 -2
- package/build/timing.js.map +1 -0
- package/build/units.d.ts +17 -0
- package/build/units.js +236 -0
- package/build/units.js.map +1 -0
- package/build/watchdog.d.ts +34 -0
- package/build/watchdog.js +53 -0
- package/build/watchdog.js.map +1 -0
- package/build/websocket/client.d.ts +136 -0
- package/build/websocket/client.js +422 -0
- package/build/websocket/client.js.map +1 -0
- package/build/websocket/connection.d.ts +83 -0
- package/build/websocket/connection.js +57 -0
- package/build/websocket/connection.js.map +1 -0
- package/build/websocket/machine.d.ts +12 -0
- package/build/websocket/machine.js +155 -0
- package/build/websocket/machine.js.map +1 -0
- package/build/websocket/meets.d.ts +14 -0
- package/build/websocket/meets.js +92 -0
- package/build/websocket/meets.js.map +1 -0
- package/build/websocket/starting.d.ts +25 -0
- package/build/websocket/starting.js +69 -0
- package/build/websocket/starting.js.map +1 -0
- package/build/websocket.d.ts +9 -264
- package/build/websocket.js +8 -774
- package/build/worker.d.ts +92 -0
- package/build/worker.js +153 -0
- package/build/worker.js.map +1 -0
- package/package.json +4 -3
- package/build/backoff-QTRGfkEK.d.ts +0 -45
- package/build/clock-DpVgpY4h.d.ts +0 -2
- package/build/grpc.js.map +0 -1
- package/build/host.js.map +0 -1
- package/build/http-client.js.map +0 -1
- package/build/http.js.map +0 -1
- package/build/index.js.map +0 -1
- package/build/knobs-BJcz6m01.js.map +0 -1
- package/build/lifecycle-D0J-zwZF.d.ts +0 -374
- package/build/limiter-Bgy6Gmvl.js.map +0 -1
- package/build/logger-B6drv9w0.d.ts +0 -488
- package/build/machine-BhVeHr_m.js.map +0 -1
- package/build/mongodb.js.map +0 -1
- package/build/operation-DF73RZOI.js.map +0 -1
- package/build/pg.js.map +0 -1
- package/build/policy-UYALkqVq.js.map +0 -1
- package/build/process-7R9M29wN.js +0 -437
- package/build/process-7R9M29wN.js.map +0 -1
- package/build/rabbitmq.js.map +0 -1
- package/build/redis.js.map +0 -1
- package/build/requests-DD2ALv0_.js +0 -583
- package/build/requests-DD2ALv0_.js.map +0 -1
- package/build/retrier-Dnjhvxol.js.map +0 -1
- package/build/timing-DZl36uXs.js.map +0 -1
- package/build/websocket.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
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,KA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A,MAAM,UAAU,UAA0B;EACxC,OAAO;EACP,IAAI,CAAC,SAAS,QAAQ,OAAO,KAAK;EAClC,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"}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/** An exit signal is a signal that asks the process to stop: each one starts the shutdown. */
|
|
2
|
+
export type ExitSignal = "SIGINT" | "SIGTERM" | "SIGQUIT";
|
|
3
|
+
/** These are the signals that the runtime handles. */
|
|
4
|
+
export declare const EXIT_SIGNALS: readonly ExitSignal[];
|
|
5
|
+
/**
|
|
6
|
+
* A process trigger is an event of the process, other than a signal, that starts the shutdown. A
|
|
7
|
+
* declaration opts in to each one (`svc.trigger`):
|
|
8
|
+
* - `stdin-close`: the standard input ends or closes, as when the parent of a stdio child goes away.
|
|
9
|
+
* The process must read its input, as a stdio transport does, or Node does not see the end.
|
|
10
|
+
* - `ipc-close`: the IPC channel to the parent process closes.
|
|
11
|
+
* - `ipc-message`: a message on the IPC channel matches a declared shape. Windows cannot give a
|
|
12
|
+
* child a SIGTERM that the child can catch, thus a parent sends a message.
|
|
13
|
+
*/
|
|
14
|
+
export type ProcessTrigger = "stdin-close" | "ipc-close" | "ipc-message";
|
|
15
|
+
/** These are the process triggers that a declaration can opt in to. */
|
|
16
|
+
export declare const PROCESS_TRIGGERS: readonly ProcessTrigger[];
|
|
17
|
+
/** An exit trigger is an event that starts the shutdown: an exit signal, or a declared process trigger. */
|
|
18
|
+
export type ExitTrigger = ExitSignal | ProcessTrigger;
|
|
19
|
+
/**
|
|
20
|
+
* An uncaught origin tells how an error that no code caught came to the process. It is an exception
|
|
21
|
+
* that no code caught, or a rejection of a promise that no code handled.
|
|
22
|
+
*/
|
|
23
|
+
export type UncaughtOrigin = "uncaughtException" | "unhandledRejection";
|
|
24
|
+
/** These are the origins of the errors that the option `uncaught` of `run()` receives. */
|
|
25
|
+
export declare const UNCAUGHT_ORIGINS: readonly UncaughtOrigin[];
|
|
26
|
+
/** This function tells if a number is an exit code of a process: a whole number from 0 to 255. */
|
|
27
|
+
export declare const isExitCode: (code: number) => boolean;
|
|
28
|
+
/** This function tells if a trigger is an exit signal. A repeat signal obeys `onRepeatSignal`. */
|
|
29
|
+
export declare const isExitSignal: (trigger: string) => trigger is ExitSignal;
|
|
30
|
+
/**
|
|
31
|
+
* A message shape is a value of JSON that a message of the IPC channel can match. A string, a
|
|
32
|
+
* number, a boolean or null matches an equal message. An object matches a message that has each of
|
|
33
|
+
* its fields, and each value of the field matches. An array matches an array of the same length, item by item.
|
|
34
|
+
*/
|
|
35
|
+
export type MessageShape = string | number | boolean | null | readonly MessageShape[] | {
|
|
36
|
+
readonly [field: string]: MessageShape;
|
|
37
|
+
};
|
|
38
|
+
/** This function tells if a value is a message shape: a value of JSON, with no function and no undefined. */
|
|
39
|
+
export declare const isMessageShape: (value: unknown) => value is MessageShape;
|
|
40
|
+
/** This function tells if a message of the IPC channel matches a shape. */
|
|
41
|
+
export declare const matchesMessage: (shape: MessageShape, message: unknown) => boolean;
|
|
42
|
+
/**
|
|
43
|
+
* A process port is the part of the process that the runtime uses: its exit triggers, its output
|
|
44
|
+
* and its exit. The runtime owns the handlers, because Node as PID 1 without a handler ignores
|
|
45
|
+
* SIGTERM. Only the runtime ends the process, and library code does not. A test gives a fake port,
|
|
46
|
+
* sends triggers, and reads the exit code.
|
|
47
|
+
*/
|
|
48
|
+
export interface ProcessPort {
|
|
49
|
+
/**
|
|
50
|
+
* This method adds a handler for a trigger, and gives the function that removes it. The runtime
|
|
51
|
+
* asks for a process trigger only when the declaration opts in to it. For `ipc-message`, the
|
|
52
|
+
* handler gets each message of the IPC channel, and the runtime matches it.
|
|
53
|
+
*/
|
|
54
|
+
on(trigger: ExitTrigger, handler: (message?: unknown) => void): () => void;
|
|
55
|
+
/**
|
|
56
|
+
* This method adds a handler for each error that no code caught, and gives the function that
|
|
57
|
+
* removes it. The runtime asks for it only when `run()` gets the option `uncaught`. A port without
|
|
58
|
+
* this method gets no handler, as the embedded port.
|
|
59
|
+
*/
|
|
60
|
+
onUncaught?(handler: (error: unknown, origin: UncaughtOrigin) => void): () => void;
|
|
61
|
+
/**
|
|
62
|
+
* This method writes each buffered line of the output, and its promise ends when the output is
|
|
63
|
+
* written. The stage `flush the output` uses it, in the cap of that stage.
|
|
64
|
+
*/
|
|
65
|
+
flush?(): Promise<void> | void;
|
|
66
|
+
/**
|
|
67
|
+
* This method keeps the process alive, and gives the function that releases it. The lifecycle
|
|
68
|
+
* holds its process from its start to its exit, as a listening socket does. Thus a process whose
|
|
69
|
+
* timers do not keep it alive does not end in the middle of its work. It keeps its teardown and its exit code.
|
|
70
|
+
*/
|
|
71
|
+
hold?(): () => void;
|
|
72
|
+
/** This method ends the process with a code: the code of the exit request, 1 after an error, or 0. */
|
|
73
|
+
exit(code: number): void;
|
|
74
|
+
}
|
|
75
|
+
/** A host stream is the part of a stream of Node that the port uses. */
|
|
76
|
+
export interface HostStream {
|
|
77
|
+
readonly writable?: boolean;
|
|
78
|
+
readonly destroyed?: boolean;
|
|
79
|
+
readonly readableEnded?: boolean;
|
|
80
|
+
write(chunk: string, done: (error?: unknown) => void): boolean;
|
|
81
|
+
on(event: string, handler: () => void): unknown;
|
|
82
|
+
off(event: string, handler: () => void): unknown;
|
|
83
|
+
}
|
|
84
|
+
/** A process host is the part of the process of Node that the port uses. Its event `message` gives the message of the IPC channel. */
|
|
85
|
+
export interface ProcessHost {
|
|
86
|
+
on(signal: string, handler: (message?: unknown) => void): unknown;
|
|
87
|
+
off(signal: string, handler: (message?: unknown) => void): unknown;
|
|
88
|
+
exit(code: number): unknown;
|
|
89
|
+
readonly stdin?: HostStream | undefined;
|
|
90
|
+
readonly stdout?: HostStream | undefined;
|
|
91
|
+
readonly stderr?: HostStream | undefined;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* This function makes a process port on a host. `find` gives the host at each use, or undefined
|
|
95
|
+
* when the platform has no process. Then the use throws.
|
|
96
|
+
*/
|
|
97
|
+
export declare const processPortOf: (find: () => ProcessHost | undefined) => ProcessPort;
|
|
98
|
+
/** This port is the process of Node. */
|
|
99
|
+
export declare const nodeProcess: ProcessPort;
|
|
100
|
+
/** An embedded process port records the exit code of a lifecycle that does not own its process. */
|
|
101
|
+
export interface EmbeddedProcess extends ProcessPort {
|
|
102
|
+
/** This code is the code of the exit request of the lifecycle, or null before that request. */
|
|
103
|
+
readonly exitCode: number | null;
|
|
104
|
+
/** This promise ends with the exit code when the lifecycle asks for its exit. */
|
|
105
|
+
readonly exited: Promise<number>;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* This function gives a process port for a lifecycle in a process that another part owns. That
|
|
109
|
+
* part is a script, a test of an application, or a library entry. The port adds no handler of a signal or of
|
|
110
|
+
* a trigger, it does not hold the process, and its `exit` only records the code. The caller stops
|
|
111
|
+
* the lifecycle with `life.shutdown()`. A process with a service of its own gives its parts to
|
|
112
|
+
* that service, and does not use this port.
|
|
113
|
+
*/
|
|
114
|
+
export declare const embeddedProcess: () => EmbeddedProcess;
|
package/build/process.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// src/process.ts
|
|
2
|
+
/** These are the signals that the runtime handles. */
|
|
3
|
+
const EXIT_SIGNALS = [
|
|
4
|
+
"SIGINT",
|
|
5
|
+
"SIGTERM",
|
|
6
|
+
"SIGQUIT"
|
|
7
|
+
];
|
|
8
|
+
/** These are the process triggers that a declaration can opt in to. */
|
|
9
|
+
const PROCESS_TRIGGERS = [
|
|
10
|
+
"stdin-close",
|
|
11
|
+
"ipc-close",
|
|
12
|
+
"ipc-message"
|
|
13
|
+
];
|
|
14
|
+
/** These are the origins of the errors that the option `uncaught` of `run()` receives. */
|
|
15
|
+
const UNCAUGHT_ORIGINS = ["uncaughtException", "unhandledRejection"];
|
|
16
|
+
/** This function tells if a number is an exit code of a process: a whole number from 0 to 255. */
|
|
17
|
+
const isExitCode = (code) => Number.isInteger(code) && code >= 0 && code <= 255;
|
|
18
|
+
/** This function tells if a trigger is an exit signal. A repeat signal obeys `onRepeatSignal`. */
|
|
19
|
+
const isExitSignal = (trigger) => EXIT_SIGNALS.includes(trigger);
|
|
20
|
+
/** This function tells if a value is a message shape: a value of JSON, with no function and no undefined. */
|
|
21
|
+
const isMessageShape = (value) => {
|
|
22
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
23
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
24
|
+
if (Array.isArray(value)) return value.every(isMessageShape);
|
|
25
|
+
if (typeof value !== "object") return false;
|
|
26
|
+
const prototype = Object.getPrototypeOf(value);
|
|
27
|
+
return (prototype === Object.prototype || prototype === null) && Object.values(value).every(isMessageShape);
|
|
28
|
+
};
|
|
29
|
+
/** This function tells if a message of the IPC channel matches a shape. */
|
|
30
|
+
const matchesMessage = (shape, message) => {
|
|
31
|
+
if (shape === null || typeof shape !== "object") return Object.is(shape, message);
|
|
32
|
+
if (Array.isArray(shape)) {
|
|
33
|
+
const items = shape;
|
|
34
|
+
return Array.isArray(message) && message.length === items.length && items.every((item, at) => matchesMessage(item, message[at]));
|
|
35
|
+
}
|
|
36
|
+
if (message === null || typeof message !== "object" || Array.isArray(message)) return false;
|
|
37
|
+
const fields = message;
|
|
38
|
+
return Object.entries(shape).every(([field, value]) => Object.hasOwn(fields, field) && matchesMessage(value, fields[field]));
|
|
39
|
+
};
|
|
40
|
+
/** This time is the interval of the timer of a hold, the most that a timer of Node accepts. */
|
|
41
|
+
const HOLD_INTERVAL = 2147483647;
|
|
42
|
+
/** This function adds a handler to some events of an emitter. The handler operates one time at most. */
|
|
43
|
+
const once = (emitter, events, handler) => {
|
|
44
|
+
let called = false;
|
|
45
|
+
const fire = () => {
|
|
46
|
+
if (called) return;
|
|
47
|
+
called = true;
|
|
48
|
+
handler();
|
|
49
|
+
};
|
|
50
|
+
for (const event of events) emitter.on(event, fire);
|
|
51
|
+
return () => {
|
|
52
|
+
for (const event of events) emitter.off(event, fire);
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
/** This function gives a promise that ends when the data before it in a stream is written. */
|
|
56
|
+
const written = (stream) => new Promise((resolve) => {
|
|
57
|
+
if (stream === void 0 || stream.destroyed === true || stream.writable === false) {
|
|
58
|
+
resolve();
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
stream.write("", () => resolve());
|
|
63
|
+
} catch {
|
|
64
|
+
resolve();
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
/**
|
|
68
|
+
* This function makes a process port on a host. `find` gives the host at each use, or undefined
|
|
69
|
+
* when the platform has no process. Then the use throws.
|
|
70
|
+
*/
|
|
71
|
+
const processPortOf = (find) => {
|
|
72
|
+
const hostProcess = () => {
|
|
73
|
+
const host = find();
|
|
74
|
+
if (host === void 0) throw new Error("no process: give the runtime a process port");
|
|
75
|
+
return host;
|
|
76
|
+
};
|
|
77
|
+
return {
|
|
78
|
+
on(trigger, handler) {
|
|
79
|
+
const host = hostProcess();
|
|
80
|
+
if (trigger === "stdin-close") {
|
|
81
|
+
const input = host.stdin;
|
|
82
|
+
if (input === void 0) return () => {};
|
|
83
|
+
if (input.readableEnded === true) {
|
|
84
|
+
let live = true;
|
|
85
|
+
queueMicrotask(() => {
|
|
86
|
+
if (live) handler();
|
|
87
|
+
});
|
|
88
|
+
return () => {
|
|
89
|
+
live = false;
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
return once(input, ["end", "close"], handler);
|
|
93
|
+
}
|
|
94
|
+
if (trigger === "ipc-close") return once(host, ["disconnect"], handler);
|
|
95
|
+
if (trigger === "ipc-message") {
|
|
96
|
+
const receive = (message) => handler(message);
|
|
97
|
+
host.on("message", receive);
|
|
98
|
+
return () => {
|
|
99
|
+
host.off("message", receive);
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
host.on(trigger, handler);
|
|
103
|
+
return () => {
|
|
104
|
+
host.off(trigger, handler);
|
|
105
|
+
};
|
|
106
|
+
},
|
|
107
|
+
onUncaught(handler) {
|
|
108
|
+
const host = hostProcess();
|
|
109
|
+
const offs = UNCAUGHT_ORIGINS.map((origin) => {
|
|
110
|
+
const receive = (error) => handler(error, origin);
|
|
111
|
+
host.on(origin, receive);
|
|
112
|
+
return () => {
|
|
113
|
+
host.off(origin, receive);
|
|
114
|
+
};
|
|
115
|
+
});
|
|
116
|
+
return () => {
|
|
117
|
+
for (const off of offs) off();
|
|
118
|
+
};
|
|
119
|
+
},
|
|
120
|
+
async flush() {
|
|
121
|
+
const host = hostProcess();
|
|
122
|
+
await Promise.all([written(host.stdout), written(host.stderr)]);
|
|
123
|
+
},
|
|
124
|
+
hold() {
|
|
125
|
+
hostProcess();
|
|
126
|
+
const timer = setInterval(() => {}, HOLD_INTERVAL);
|
|
127
|
+
let held = true;
|
|
128
|
+
return () => {
|
|
129
|
+
if (!held) return;
|
|
130
|
+
held = false;
|
|
131
|
+
clearInterval(timer);
|
|
132
|
+
};
|
|
133
|
+
},
|
|
134
|
+
exit(code) {
|
|
135
|
+
hostProcess().exit(code);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
};
|
|
139
|
+
/** This port is the process of Node. */
|
|
140
|
+
const nodeProcess = processPortOf(() => globalThis.process);
|
|
141
|
+
/**
|
|
142
|
+
* This function gives a process port for a lifecycle in a process that another part owns. That
|
|
143
|
+
* part is a script, a test of an application, or a library entry. The port adds no handler of a signal or of
|
|
144
|
+
* a trigger, it does not hold the process, and its `exit` only records the code. The caller stops
|
|
145
|
+
* the lifecycle with `life.shutdown()`. A process with a service of its own gives its parts to
|
|
146
|
+
* that service, and does not use this port.
|
|
147
|
+
*/
|
|
148
|
+
const embeddedProcess = () => {
|
|
149
|
+
let code = null;
|
|
150
|
+
let resolve = () => {};
|
|
151
|
+
return {
|
|
152
|
+
on() {
|
|
153
|
+
return () => {};
|
|
154
|
+
},
|
|
155
|
+
exit(requested) {
|
|
156
|
+
if (code !== null) return;
|
|
157
|
+
code = requested;
|
|
158
|
+
resolve(requested);
|
|
159
|
+
},
|
|
160
|
+
get exitCode() {
|
|
161
|
+
return code;
|
|
162
|
+
},
|
|
163
|
+
exited: new Promise((done) => {
|
|
164
|
+
resolve = done;
|
|
165
|
+
})
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
export { EXIT_SIGNALS, PROCESS_TRIGGERS, UNCAUGHT_ORIGINS, embeddedProcess, isExitCode, isExitSignal, isMessageShape, matchesMessage, nodeProcess, processPortOf };
|
|
169
|
+
|
|
170
|
+
//# sourceMappingURL=process.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"process.js","names":[],"sources":["../src/process.ts"],"sourcesContent":["/** An exit signal is a signal that asks the process to stop: each one starts the shutdown. */\nexport type ExitSignal = \"SIGINT\" | \"SIGTERM\" | \"SIGQUIT\";\n\n/** These are the signals that the runtime handles. */\nexport const EXIT_SIGNALS: readonly ExitSignal[] = [\"SIGINT\", \"SIGTERM\", \"SIGQUIT\"];\n\n/**\n * A process trigger is an event of the process, other than a signal, that starts the shutdown. A\n * declaration opts in to each one (`svc.trigger`):\n * - `stdin-close`: the standard input ends or closes, as when the parent of a stdio child goes away.\n * The process must read its input, as a stdio transport does, or Node does not see the end.\n * - `ipc-close`: the IPC channel to the parent process closes.\n * - `ipc-message`: a message on the IPC channel matches a declared shape. Windows cannot give a\n * child a SIGTERM that the child can catch, thus a parent sends a message.\n */\nexport type ProcessTrigger = \"stdin-close\" | \"ipc-close\" | \"ipc-message\";\n\n/** These are the process triggers that a declaration can opt in to. */\nexport const PROCESS_TRIGGERS: readonly ProcessTrigger[] = [\"stdin-close\", \"ipc-close\", \"ipc-message\"];\n\n/** An exit trigger is an event that starts the shutdown: an exit signal, or a declared process trigger. */\nexport type ExitTrigger = ExitSignal | ProcessTrigger;\n\n/**\n * An uncaught origin tells how an error that no code caught came to the process. It is an exception\n * that no code caught, or a rejection of a promise that no code handled.\n */\nexport type UncaughtOrigin = \"uncaughtException\" | \"unhandledRejection\";\n\n/** These are the origins of the errors that the option `uncaught` of `run()` receives. */\nexport const UNCAUGHT_ORIGINS: readonly UncaughtOrigin[] = [\"uncaughtException\", \"unhandledRejection\"];\n\n/** This function tells if a number is an exit code of a process: a whole number from 0 to 255. */\nexport const isExitCode = (code: number): boolean => Number.isInteger(code) && code >= 0 && code <= 255;\n\n/** This function tells if a trigger is an exit signal. A repeat signal obeys `onRepeatSignal`. */\nexport const isExitSignal = (trigger: string): trigger is ExitSignal =>\n (EXIT_SIGNALS as readonly string[]).includes(trigger);\n\n/**\n * A message shape is a value of JSON that a message of the IPC channel can match. A string, a\n * number, a boolean or null matches an equal message. An object matches a message that has each of\n * its fields, and each value of the field matches. An array matches an array of the same length, item by item.\n */\nexport type MessageShape = string | number | boolean | null | readonly MessageShape[] | { readonly [field: string]: MessageShape };\n\n/** This function tells if a value is a message shape: a value of JSON, with no function and no undefined. */\nexport const isMessageShape = (value: unknown): value is MessageShape => {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (Array.isArray(value)) return value.every(isMessageShape);\n if (typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n return (prototype === Object.prototype || prototype === null) && Object.values(value).every(isMessageShape);\n};\n\n/** This function tells if a message of the IPC channel matches a shape. */\nexport const matchesMessage = (shape: MessageShape, message: unknown): boolean => {\n if (shape === null || typeof shape !== \"object\") return Object.is(shape, message);\n if (Array.isArray(shape)) {\n const items: readonly MessageShape[] = shape;\n return Array.isArray(message) && message.length === items.length && items.every((item, at) => matchesMessage(item, message[at]));\n }\n if (message === null || typeof message !== \"object\" || Array.isArray(message)) return false;\n const fields = message as Readonly<Record<string, unknown>>;\n return Object.entries(shape).every(([field, value]) => Object.hasOwn(fields, field) && matchesMessage(value, fields[field]));\n};\n\n/**\n * A process port is the part of the process that the runtime uses: its exit triggers, its output\n * and its exit. The runtime owns the handlers, because Node as PID 1 without a handler ignores\n * SIGTERM. Only the runtime ends the process, and library code does not. A test gives a fake port,\n * sends triggers, and reads the exit code.\n */\nexport interface ProcessPort {\n /**\n * This method adds a handler for a trigger, and gives the function that removes it. The runtime\n * asks for a process trigger only when the declaration opts in to it. For `ipc-message`, the\n * handler gets each message of the IPC channel, and the runtime matches it.\n */\n on(trigger: ExitTrigger, handler: (message?: unknown) => void): () => void;\n /**\n * This method adds a handler for each error that no code caught, and gives the function that\n * removes it. The runtime asks for it only when `run()` gets the option `uncaught`. A port without\n * this method gets no handler, as the embedded port.\n */\n onUncaught?(handler: (error: unknown, origin: UncaughtOrigin) => void): () => void;\n /**\n * This method writes each buffered line of the output, and its promise ends when the output is\n * written. The stage `flush the output` uses it, in the cap of that stage.\n */\n flush?(): Promise<void> | void;\n /**\n * This method keeps the process alive, and gives the function that releases it. The lifecycle\n * holds its process from its start to its exit, as a listening socket does. Thus a process whose\n * timers do not keep it alive does not end in the middle of its work. It keeps its teardown and its exit code.\n */\n hold?(): () => void;\n /** This method ends the process with a code: the code of the exit request, 1 after an error, or 0. */\n exit(code: number): void;\n}\n\n/** A host stream is the part of a stream of Node that the port uses. */\nexport interface HostStream {\n readonly writable?: boolean;\n readonly destroyed?: boolean;\n readonly readableEnded?: boolean;\n write(chunk: string, done: (error?: unknown) => void): boolean;\n on(event: string, handler: () => void): unknown;\n off(event: string, handler: () => void): unknown;\n}\n\n/** A process host is the part of the process of Node that the port uses. Its event `message` gives the message of the IPC channel. */\nexport interface ProcessHost {\n on(signal: string, handler: (message?: unknown) => void): unknown;\n off(signal: string, handler: (message?: unknown) => void): unknown;\n exit(code: number): unknown;\n readonly stdin?: HostStream | undefined;\n readonly stdout?: HostStream | undefined;\n readonly stderr?: HostStream | undefined;\n}\n\n/** This time is the interval of the timer of a hold, the most that a timer of Node accepts. */\nconst HOLD_INTERVAL = 0x7fffffff;\n\n/** This function adds a handler to some events of an emitter. The handler operates one time at most. */\nconst once = (emitter: HostStream | ProcessHost, events: readonly string[], handler: () => void): (() => void) => {\n let called = false;\n const fire = (): void => {\n if (called) return;\n called = true;\n handler();\n };\n for (const event of events) emitter.on(event, fire);\n return () => {\n for (const event of events) emitter.off(event, fire);\n };\n};\n\n/** This function gives a promise that ends when the data before it in a stream is written. */\nconst written = (stream: HostStream | undefined): Promise<void> =>\n new Promise<void>((resolve) => {\n if (stream === undefined || stream.destroyed === true || stream.writable === false) {\n resolve();\n return;\n }\n try {\n // the callback of an empty write comes after each write before it\n stream.write(\"\", () => resolve());\n } catch {\n resolve();\n }\n });\n\n/**\n * This function makes a process port on a host. `find` gives the host at each use, or undefined\n * when the platform has no process. Then the use throws.\n */\nexport const processPortOf = (find: () => ProcessHost | undefined): ProcessPort => {\n const hostProcess = (): ProcessHost => {\n const host = find();\n if (host === undefined) throw new Error(\"no process: give the runtime a process port\");\n return host;\n };\n return {\n on(trigger, handler) {\n const host = hostProcess();\n if (trigger === \"stdin-close\") {\n const input = host.stdin;\n if (input === undefined) return () => {};\n // an input that ended before the handler was added still starts the shutdown\n if (input.readableEnded === true) {\n let live = true;\n queueMicrotask(() => {\n if (live) handler();\n });\n return () => {\n live = false;\n };\n }\n return once(input, [\"end\", \"close\"], handler);\n }\n if (trigger === \"ipc-close\") return once(host, [\"disconnect\"], handler);\n if (trigger === \"ipc-message\") {\n // each message goes to the runtime, which matches it with the declared shapes\n const receive = (message?: unknown): void => handler(message);\n host.on(\"message\", receive);\n return () => {\n host.off(\"message\", receive);\n };\n }\n host.on(trigger, handler);\n return () => {\n host.off(trigger, handler);\n };\n },\n onUncaught(handler) {\n const host = hostProcess();\n // a handler of each origin: Node then does not end the process, and the runtime does the shutdown\n const offs = UNCAUGHT_ORIGINS.map((origin) => {\n const receive = (error?: unknown): void => handler(error, origin);\n host.on(origin, receive);\n return () => {\n host.off(origin, receive);\n };\n });\n return () => {\n for (const off of offs) off();\n };\n },\n async flush() {\n const host = hostProcess();\n await Promise.all([written(host.stdout), written(host.stderr)]);\n },\n hold() {\n hostProcess();\n // one interval that keeps the event loop alive: its timer does nothing, and the release stops it\n const timer = setInterval(() => {}, HOLD_INTERVAL);\n let held = true;\n return () => {\n if (!held) return;\n held = false;\n clearInterval(timer);\n };\n },\n exit(code) {\n hostProcess().exit(code);\n },\n };\n};\n\n/** This port is the process of Node. */\nexport const nodeProcess: ProcessPort = processPortOf(() => (globalThis as { process?: ProcessHost }).process);\n\n/** An embedded process port records the exit code of a lifecycle that does not own its process. */\nexport interface EmbeddedProcess extends ProcessPort {\n /** This code is the code of the exit request of the lifecycle, or null before that request. */\n readonly exitCode: number | null;\n /** This promise ends with the exit code when the lifecycle asks for its exit. */\n readonly exited: Promise<number>;\n}\n\n/**\n * This function gives a process port for a lifecycle in a process that another part owns. That\n * part is a script, a test of an application, or a library entry. The port adds no handler of a signal or of\n * a trigger, it does not hold the process, and its `exit` only records the code. The caller stops\n * the lifecycle with `life.shutdown()`. A process with a service of its own gives its parts to\n * that service, and does not use this port.\n */\nexport const embeddedProcess = (): EmbeddedProcess => {\n let code: number | null = null;\n let resolve: (code: number) => void = () => {};\n const exited = new Promise<number>((done) => {\n resolve = done;\n });\n return {\n on() {\n // the owner of the process keeps its signals and triggers\n return () => {};\n },\n exit(requested) {\n if (code !== null) return;\n code = requested;\n resolve(requested);\n },\n get exitCode() {\n return code;\n },\n exited,\n };\n};\n"],"mappings":";;AAIA,MAAa,eAAsC;CAAC;CAAU;CAAW;AAAS;;AAclF,MAAa,mBAA8C;CAAC;CAAe;CAAa;AAAa;;AAYrG,MAAa,mBAA8C,CAAC,qBAAqB,oBAAoB;;AAGrG,MAAa,cAAc,SAA0B,OAAO,UAAU,IAAI,KAAK,QAAQ,KAAK,QAAQ;;AAGpG,MAAa,gBAAgB,YAC1B,aAAmC,SAAS,OAAO;;AAUtD,MAAa,kBAAkB,UAA0C;CACvE,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW,OAAO;CACtF,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,SAAS,KAAK;CAC3D,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,MAAM,cAAc;CAC3D,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,QAAQ,cAAc,OAAO,aAAa,cAAc,SAAS,OAAO,OAAO,KAAK,CAAC,CAAC,MAAM,cAAc;AAC5G;;AAGA,MAAa,kBAAkB,OAAqB,YAA8B;CAChF,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO,OAAO,GAAG,OAAO,OAAO;CAChF,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,MAAM,QAAiC;EACvC,OAAO,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,MAAM,UAAU,MAAM,OAAO,MAAM,OAAO,eAAe,MAAM,QAAQ,GAAG,CAAC;CACjI;CACA,IAAI,YAAY,QAAQ,OAAO,YAAY,YAAY,MAAM,Q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@ -0,0 +1,68 @@
|
|
|
1
|
+
import { CooperativeFloor, Coupling, ExitCodes, MessageTrigger, Phase, RepeatSignal } from "./description.js";
|
|
2
|
+
import { ProcessTrigger } from "./process.js";
|
|
3
|
+
import { Timing } from "./timing.js";
|
|
4
|
+
import { Extent, Quantity } from "@mark1russell7/quantity";
|
|
5
|
+
/**
|
|
6
|
+
* A profile is a part of a declaration as data: policies, phases and the rules of the shutdown.
|
|
7
|
+
* `svc.profile(profile)` declares each field, as its method does. The runtime has no defaults, and
|
|
8
|
+
* a profile is not a default, because the caller gives it. The caller can change each field with a
|
|
9
|
+
* spread. `describe()` then shows the values of the profile.
|
|
10
|
+
*
|
|
11
|
+
* svc.profile({ ...kubernetes({ grace: s(60), preStop: s(5) }), onRepeatSignal: "exit" });
|
|
12
|
+
*/
|
|
13
|
+
export interface Profile {
|
|
14
|
+
readonly readiness?: Timing | undefined;
|
|
15
|
+
readonly liveness?: Timing | undefined;
|
|
16
|
+
readonly startup?: Quantity | undefined;
|
|
17
|
+
readonly couplings?: readonly Coupling[] | undefined;
|
|
18
|
+
/** These are the phases of the shutdown, in their sequence. */
|
|
19
|
+
readonly phases?: readonly Phase[] | undefined;
|
|
20
|
+
readonly cooperativeWindow?: Extent | undefined;
|
|
21
|
+
readonly cooperativeFloor?: CooperativeFloor | undefined;
|
|
22
|
+
readonly onRepeatSignal?: RepeatSignal | undefined;
|
|
23
|
+
readonly triggers?: readonly ProcessTrigger[] | undefined;
|
|
24
|
+
/** These messages of the IPC channel start the shutdown, as `svc.trigger("ipc-message", message)` declares each one. */
|
|
25
|
+
readonly messages?: readonly MessageTrigger[] | undefined;
|
|
26
|
+
readonly exitCodes?: ExitCodes | undefined;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* This profile is for a service on the computer of a developer. No load balancer routes to it,
|
|
30
|
+
* thus it has no readiness hold. Its caps sum to 10 s, and a second signal exits at once. It
|
|
31
|
+
* declares no checks, thus the caller declares readiness, liveness and the startup budget.
|
|
32
|
+
*/
|
|
33
|
+
export declare const localDev: Profile;
|
|
34
|
+
/**
|
|
35
|
+
* This profile is for a background host on the computer of a developer, under a supervisor or a
|
|
36
|
+
* command that stops it. It has the caps of `localDev`. A repeat signal has no effect, thus the
|
|
37
|
+
* host ends its drain. It has no process trigger: a background host has no parent on stdin.
|
|
38
|
+
*/
|
|
39
|
+
export declare const daemon: Profile;
|
|
40
|
+
/**
|
|
41
|
+
* This profile is for a small process: a command that runs one time, or a child process on stdio.
|
|
42
|
+
* It has no checks and no probes, and its policies gate nothing. The cooperative abort occurs at the
|
|
43
|
+
* start of the drain, thus a first Ctrl-C stops the work at once. A second signal exits at once.
|
|
44
|
+
* The exit codes tell the shell how the process stopped: 130 for SIGINT, 143 for SIGTERM and 131
|
|
45
|
+
* for SIGQUIT. A stdio child also declares `triggers: ["stdin-close"]`.
|
|
46
|
+
*/
|
|
47
|
+
export declare const ephemeral: Profile;
|
|
48
|
+
/** These are the settings of a pod that the profile `kubernetes` derives its caps from. */
|
|
49
|
+
export interface PodTiming {
|
|
50
|
+
/** This time is `terminationGracePeriodSeconds`: from the deletion of the pod to SIGKILL. */
|
|
51
|
+
readonly grace: Quantity;
|
|
52
|
+
/** This time is the preStop sleep, or 0 for no preStop hook. SIGTERM comes after it. */
|
|
53
|
+
readonly preStop: Quantity;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* This function gives the profile of a pod in Kubernetes. The budget is the grace less the preStop
|
|
57
|
+
* sleep: the time from SIGTERM to SIGKILL. Each stage gets a part of the budget, rounded down to
|
|
58
|
+
* the millisecond.
|
|
59
|
+
* - The parts in thirtieths are 2, 5, 15, 2, 1, 2 and 1, in the sequence of the stages. Thus 2
|
|
60
|
+
* thirtieths of the budget stay as a margin before SIGKILL.
|
|
61
|
+
* - The cooperative window is 5 thirtieths of the budget.
|
|
62
|
+
* - The kubelet sends SIGTERM one time, thus a repeat signal has no effect.
|
|
63
|
+
*
|
|
64
|
+
* At the defaults of Kubernetes (a grace of 30 s and no preStop hook), the caps are 2, 5, 15, 2, 1,
|
|
65
|
+
* 2 and 1 s. Thus the sum of the caps and the preStop sleep fits in the grace (O10). The window is
|
|
66
|
+
* shorter than the drain, which is shorter than the budget (O16).
|
|
67
|
+
*/
|
|
68
|
+
export declare const kubernetes: (pod: PodTiming) => Profile;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { convertible, valueIn } from "@mark1russell7/quantity";
|
|
2
|
+
// src/profiles.ts
|
|
3
|
+
const s = (value) => ({
|
|
4
|
+
value,
|
|
5
|
+
unit: "s"
|
|
6
|
+
});
|
|
7
|
+
const phase = (name, cap) => ({
|
|
8
|
+
name,
|
|
9
|
+
cap
|
|
10
|
+
});
|
|
11
|
+
/**
|
|
12
|
+
* This profile is for a service on the computer of a developer. No load balancer routes to it,
|
|
13
|
+
* thus it has no readiness hold. Its caps sum to 10 s, and a second signal exits at once. It
|
|
14
|
+
* declares no checks, thus the caller declares readiness, liveness and the startup budget.
|
|
15
|
+
*/
|
|
16
|
+
const localDev = {
|
|
17
|
+
phases: [
|
|
18
|
+
phase("stop intake", s(1)),
|
|
19
|
+
phase("drain", s(4)),
|
|
20
|
+
phase("close transports", s(1)),
|
|
21
|
+
phase("stop the poller", s(1)),
|
|
22
|
+
phase("tear down dependencies", s(1)),
|
|
23
|
+
phase("close the health server", s(1)),
|
|
24
|
+
phase("flush the output", s(1))
|
|
25
|
+
],
|
|
26
|
+
cooperativeWindow: s(2),
|
|
27
|
+
cooperativeFloor: "half",
|
|
28
|
+
onRepeatSignal: "exit"
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* This profile is for a background host on the computer of a developer, under a supervisor or a
|
|
32
|
+
* command that stops it. It has the caps of `localDev`. A repeat signal has no effect, thus the
|
|
33
|
+
* host ends its drain. It has no process trigger: a background host has no parent on stdin.
|
|
34
|
+
*/
|
|
35
|
+
const daemon = {
|
|
36
|
+
phases: localDev.phases.map((each) => ({ ...each })),
|
|
37
|
+
cooperativeWindow: localDev.cooperativeWindow,
|
|
38
|
+
cooperativeFloor: "half",
|
|
39
|
+
onRepeatSignal: "ignore"
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* This profile is for a small process: a command that runs one time, or a child process on stdio.
|
|
43
|
+
* It has no checks and no probes, and its policies gate nothing. The cooperative abort occurs at the
|
|
44
|
+
* start of the drain, thus a first Ctrl-C stops the work at once. A second signal exits at once.
|
|
45
|
+
* The exit codes tell the shell how the process stopped: 130 for SIGINT, 143 for SIGTERM and 131
|
|
46
|
+
* for SIGQUIT. A stdio child also declares `triggers: ["stdin-close"]`.
|
|
47
|
+
*/
|
|
48
|
+
const ephemeral = {
|
|
49
|
+
readiness: {
|
|
50
|
+
type: "window",
|
|
51
|
+
failAfter: s(0)
|
|
52
|
+
},
|
|
53
|
+
liveness: {
|
|
54
|
+
type: "window",
|
|
55
|
+
failAfter: s(0)
|
|
56
|
+
},
|
|
57
|
+
startup: s(10),
|
|
58
|
+
phases: [
|
|
59
|
+
phase("stop intake", s(1)),
|
|
60
|
+
phase("drain", s(2)),
|
|
61
|
+
phase("close transports", s(1)),
|
|
62
|
+
phase("stop the poller", s(1)),
|
|
63
|
+
phase("tear down dependencies", s(2)),
|
|
64
|
+
phase("flush the output", s(1))
|
|
65
|
+
],
|
|
66
|
+
cooperativeWindow: s(2),
|
|
67
|
+
cooperativeFloor: "none",
|
|
68
|
+
onRepeatSignal: "exit",
|
|
69
|
+
exitCodes: {
|
|
70
|
+
SIGINT: 130,
|
|
71
|
+
SIGTERM: 143,
|
|
72
|
+
SIGQUIT: 131
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
/** These are the parts of the budget of each stage in the profile `kubernetes`, in thirtieths. */
|
|
76
|
+
const KUBERNETES_SHARES = [
|
|
77
|
+
["fail readiness", 2],
|
|
78
|
+
["stop intake", 5],
|
|
79
|
+
["drain", 15],
|
|
80
|
+
["close transports", 2],
|
|
81
|
+
["stop the poller", 1],
|
|
82
|
+
["tear down dependencies", 2],
|
|
83
|
+
["close the health server", 1]
|
|
84
|
+
];
|
|
85
|
+
/** This part of the budget is the cooperative window, in thirtieths. */
|
|
86
|
+
const KUBERNETES_WINDOW = 5;
|
|
87
|
+
/**
|
|
88
|
+
* This function gives the profile of a pod in Kubernetes. The budget is the grace less the preStop
|
|
89
|
+
* sleep: the time from SIGTERM to SIGKILL. Each stage gets a part of the budget, rounded down to
|
|
90
|
+
* the millisecond.
|
|
91
|
+
* - The parts in thirtieths are 2, 5, 15, 2, 1, 2 and 1, in the sequence of the stages. Thus 2
|
|
92
|
+
* thirtieths of the budget stay as a margin before SIGKILL.
|
|
93
|
+
* - The cooperative window is 5 thirtieths of the budget.
|
|
94
|
+
* - The kubelet sends SIGTERM one time, thus a repeat signal has no effect.
|
|
95
|
+
*
|
|
96
|
+
* At the defaults of Kubernetes (a grace of 30 s and no preStop hook), the caps are 2, 5, 15, 2, 1,
|
|
97
|
+
* 2 and 1 s. Thus the sum of the caps and the preStop sleep fits in the grace (O10). The window is
|
|
98
|
+
* shorter than the drain, which is shorter than the budget (O16).
|
|
99
|
+
*/
|
|
100
|
+
const kubernetes = (pod) => {
|
|
101
|
+
const time = (amount, what) => {
|
|
102
|
+
if (!convertible(amount.unit, "s")) throw new Error(`the ${what} of the pod is not a time`);
|
|
103
|
+
return valueIn(amount, "ms");
|
|
104
|
+
};
|
|
105
|
+
const grace = time(pod.grace, "grace");
|
|
106
|
+
const preStop = time(pod.preStop, "preStop sleep");
|
|
107
|
+
if (preStop < 0) throw new Error("the preStop sleep of the pod is less than 0");
|
|
108
|
+
const budget = grace - preStop;
|
|
109
|
+
if (!(budget > 0)) throw new Error(`the grace of the pod (${grace} ms) is not longer than its preStop sleep (${preStop} ms)`);
|
|
110
|
+
const part = (thirtieths) => s(Math.floor(budget * thirtieths / 30) / 1e3);
|
|
111
|
+
return {
|
|
112
|
+
phases: KUBERNETES_SHARES.map(([name, thirtieths]) => phase(name, part(thirtieths))),
|
|
113
|
+
cooperativeWindow: part(KUBERNETES_WINDOW),
|
|
114
|
+
cooperativeFloor: "half",
|
|
115
|
+
onRepeatSignal: "ignore"
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
export { daemon, ephemeral, kubernetes, localDev };
|
|
119
|
+
|
|
120
|
+
//# sourceMappingURL=profiles.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"profiles.js","names":[],"sources":["../src/profiles.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { convertible, valueIn } from \"@mark1russell7/quantity\";\nimport type { CooperativeFloor, Coupling, ExitCodes, MessageTrigger, Phase, RepeatSignal } from \"./description.ts\";\nimport type { ProcessTrigger } from \"./process.ts\";\nimport type { Timing } from \"./timing.ts\";\n\n/**\n * A profile is a part of a declaration as data: policies, phases and the rules of the shutdown.\n * `svc.profile(profile)` declares each field, as its method does. The runtime has no defaults, and\n * a profile is not a default, because the caller gives it. The caller can change each field with a\n * spread. `describe()` then shows the values of the profile.\n *\n * svc.profile({ ...kubernetes({ grace: s(60), preStop: s(5) }), onRepeatSignal: \"exit\" });\n */\nexport interface Profile {\n readonly readiness?: Timing | undefined;\n readonly liveness?: Timing | undefined;\n readonly startup?: Quantity | undefined;\n readonly couplings?: readonly Coupling[] | undefined;\n /** These are the phases of the shutdown, in their sequence. */\n readonly phases?: readonly Phase[] | undefined;\n readonly cooperativeWindow?: Extent | undefined;\n readonly cooperativeFloor?: CooperativeFloor | undefined;\n readonly onRepeatSignal?: RepeatSignal | undefined;\n readonly triggers?: readonly ProcessTrigger[] | undefined;\n /** These messages of the IPC channel start the shutdown, as `svc.trigger(\"ipc-message\", message)` declares each one. */\n readonly messages?: readonly MessageTrigger[] | undefined;\n readonly exitCodes?: ExitCodes | undefined;\n}\n\nconst s = (value: number): Quantity => ({ value, unit: \"s\" });\nconst phase = (name: string, cap: Quantity): Phase => ({ name, cap });\n\n/**\n * This profile is for a service on the computer of a developer. No load balancer routes to it,\n * thus it has no readiness hold. Its caps sum to 10 s, and a second signal exits at once. It\n * declares no checks, thus the caller declares readiness, liveness and the startup budget.\n */\nexport const localDev: Profile = {\n phases: [\n phase(\"stop intake\", s(1)),\n phase(\"drain\", s(4)),\n phase(\"close transports\", s(1)),\n phase(\"stop the poller\", s(1)),\n phase(\"tear down dependencies\", s(1)),\n phase(\"close the health server\", s(1)),\n phase(\"flush the output\", s(1)),\n ],\n cooperativeWindow: s(2),\n cooperativeFloor: \"half\",\n onRepeatSignal: \"exit\",\n};\n\n/**\n * This profile is for a background host on the computer of a developer, under a supervisor or a\n * command that stops it. It has the caps of `localDev`. A repeat signal has no effect, thus the\n * host ends its drain. It has no process trigger: a background host has no parent on stdin.\n */\nexport const daemon: Profile = {\n phases: localDev.phases!.map((each) => ({ ...each })),\n cooperativeWindow: localDev.cooperativeWindow!,\n cooperativeFloor: \"half\",\n onRepeatSignal: \"ignore\",\n};\n\n/**\n * This profile is for a small process: a command that runs one time, or a child process on stdio.\n * It has no checks and no probes, and its policies gate nothing. The cooperative abort occurs at the\n * start of the drain, thus a first Ctrl-C stops the work at once. A second signal exits at once.\n * The exit codes tell the shell how the process stopped: 130 for SIGINT, 143 for SIGTERM and 131\n * for SIGQUIT. A stdio child also declares `triggers: [\"stdin-close\"]`.\n */\nexport const ephemeral: Profile = {\n readiness: { type: \"window\", failAfter: s(0) },\n liveness: { type: \"window\", failAfter: s(0) },\n startup: s(10),\n phases: [\n phase(\"stop intake\", s(1)),\n phase(\"drain\", s(2)),\n phase(\"close transports\", s(1)),\n phase(\"stop the poller\", s(1)),\n phase(\"tear down dependencies\", s(2)),\n phase(\"flush the output\", s(1)),\n ],\n // the window is the whole drain, and no floor holds the abort back\n cooperativeWindow: s(2),\n cooperativeFloor: \"none\",\n onRepeatSignal: \"exit\",\n exitCodes: { SIGINT: 130, SIGTERM: 143, SIGQUIT: 131 },\n};\n\n/** These are the parts of the budget of each stage in the profile `kubernetes`, in thirtieths. */\nconst KUBERNETES_SHARES: ReadonlyArray<readonly [string, number]> = [\n [\"fail readiness\", 2],\n [\"stop intake\", 5],\n [\"drain\", 15],\n [\"close transports\", 2],\n [\"stop the poller\", 1],\n [\"tear down dependencies\", 2],\n [\"close the health server\", 1],\n];\n/** This part of the budget is the cooperative window, in thirtieths. */\nconst KUBERNETES_WINDOW = 5;\n\n/** These are the settings of a pod that the profile `kubernetes` derives its caps from. */\nexport interface PodTiming {\n /** This time is `terminationGracePeriodSeconds`: from the deletion of the pod to SIGKILL. */\n readonly grace: Quantity;\n /** This time is the preStop sleep, or 0 for no preStop hook. SIGTERM comes after it. */\n readonly preStop: Quantity;\n}\n\n/**\n * This function gives the profile of a pod in Kubernetes. The budget is the grace less the preStop\n * sleep: the time from SIGTERM to SIGKILL. Each stage gets a part of the budget, rounded down to\n * the millisecond.\n * - The parts in thirtieths are 2, 5, 15, 2, 1, 2 and 1, in the sequence of the stages. Thus 2\n * thirtieths of the budget stay as a margin before SIGKILL.\n * - The cooperative window is 5 thirtieths of the budget.\n * - The kubelet sends SIGTERM one time, thus a repeat signal has no effect.\n *\n * At the defaults of Kubernetes (a grace of 30 s and no preStop hook), the caps are 2, 5, 15, 2, 1,\n * 2 and 1 s. Thus the sum of the caps and the preStop sleep fits in the grace (O10). The window is\n * shorter than the drain, which is shorter than the budget (O16).\n */\nexport const kubernetes = (pod: PodTiming): Profile => {\n const time = (amount: Quantity, what: string): number => {\n if (!convertible(amount.unit, \"s\")) throw new Error(`the ${what} of the pod is not a time`);\n return valueIn(amount, \"ms\");\n };\n const grace = time(pod.grace, \"grace\");\n const preStop = time(pod.preStop, \"preStop sleep\");\n if (preStop < 0) throw new Error(\"the preStop sleep of the pod is less than 0\");\n const budget = grace - preStop;\n if (!(budget > 0)) throw new Error(`the grace of the pod (${grace} ms) is not longer than its preStop sleep (${preStop} ms)`);\n const part = (thirtieths: number): Quantity => s(Math.floor((budget * thirtieths) / 30) / 1000);\n return {\n phases: KUBERNETES_SHARES.map(([name, thirtieths])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