npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@mark1russell7/service

v0.13.3

Published

A service declared as data before it starts, and its runtime: checks on jittered loops, a latch for each policy, probes from the cache, the startup in its sequence, and a staged, capped drain. The timer-ordering law checks the declaration. Its clock, hear

Readme

@mark1russell7/service

A service that you declare as data before it starts. You compose it with plain calls: its dependencies, its checks, its policies and its shutdown. describe() gives the whole graph as data, and it starts nothing. lint() then applies the timer-ordering law to that graph. start() gives the graph to the health runtime, and run() starts the whole lifecycle.

This release has the declaration, its export, the law, the health runtime, the lifecycle and the edge of a service in Node (@mark1russell7/service/http). It also has the host of a program in Node (@mark1russell7/service/host). The wrappers of the clients come in a later release.

What the package does

  • The builder. service(name) gives a builder. You add each part with a call: svc.dependency(…), svc.server(…), svc.controller("checkout").requires(…).route(…), svc.check(check, run), the policies, the couplings and the shutdown phases.
  • No defaults. The runtime has no defaults of its own. Thus describe() refuses a service that does not declare its readiness, its liveness, its startup budget, its shutdown phases or its cooperative window. It also refuses a service that does not declare what a repeat signal does. The error tells which. start() also refuses a check without its function.
  • One timing shape. Each policy has a Timing: a debounce of polls, or a window of time. Each converts to the other (asWindow, asDebounce). failSpan and recoverSpan give the earliest and the latest time to detect a change. Each one takes a Poll, or the Schedule of a loop, for example pollSchedule(poll). At 3 polls of 5 s ± 20 %, a latch fails in 8–18 s on an error, and in 12–22 s on a 4 s timeout.
  • Checks. A check names the step of the connection that it examines (dial, round-trip, checkout and others). It also tells if it uses the connection of the application, and which policy it controls. The policy has no default.
  • The catalog of a client. The checks of each client name the steps that they gate: steps: { "round-trip": "readiness" }. With catalog: true, the client also gives a check for each other step that it has. These checks gate nothing and poll each 30 s. A nominated step that the client does not have then fails the attach. The name of each check is the pair of the component and the step (db.round-trip).
  • Idempotency for each operation. One dependency has the two kinds of operation. A Redis GET is safe to send again. An INCR that goes again after a timeout counts two times. Thus each operation of a dependency, and each route of a controller, declares if it can go again: true, false, or keyed.
  • Keyed operations. A keyed operation has the window that the server keeps its key for. mayReissue answers from the declaration of an operation. An operation without a declaration does not go again.
  • The law. evaluate and verdictOf decide one rule of the timer-ordering law on one binding. A rule is data: linear inequalities over symbol@hop, with a margin. A verdict is holds, violated, unbounded (it holds only because a timer is absent) or depends (nothing is bound).
  • The linter. lint(description, scenario, rules) applies the service rules (SERVICE_RULES) to a declaration. The declaration binds the symbols of the service: the polls of its checks, the windows of its policies, its drain. The scenario binds the symbols of the platform and of each dependency. A depends finding names the symbols that have no bound.
  • The claims of a scenario. A default is true only for a version: the keep-alive of Node is 5 s, but 65 s on main. Thus a value of the scenario can be a claim that names its epoch: { epoch: "node@22", value }. Each finding then gives the epoch of each value that its rule reads (epochs).
  • A measured value. A claim can give a distribution by its statistics: { epoch, distribution: { p50, p99 } }. The law binds the p99. A distribution without a p99 binds nothing, thus each rule that reads it depends.
  • The four ways that a pod stops. STOPS gives the steps of each way. A deletion and a liveness restart have the preStop hook and the drain. A crash and an OOM stop have neither. lintStop(description, scenario, rules, way) applies only the rules of the drain that guard that way: O04 for a deletion, O09 for a liveness restart. For a crash or an OOM stop, a finding of STOP_RULE depends on the time until the kubelet finds the exit.
  • The scopes of a rule. A rule about a client applies one time for each dependency. A rule about a consumer, for example O20, applies one time for each consumer and each worker.
  • A name of its own. Each part in a set of scopes has a name of its own. The sets are the dependencies and the server transports, the consumers and the workers, and the limiters. Two parts with one name in a set give a violated finding of NAME_RULE (unique-names), because their findings have one scope. Give one of the parts a different name.
  • The scope of a server. A rule with a symbol at @server, for example O19, also applies one time for each server transport. The knobs of the transport bind at @server, for example server_idle_close@server. scenario.transports[name] gives the client side, for example request_timeout@client. Without it, the finding is depends. In the scope of a dependency, @server is the server of the dependency. Thus the knobs of a server of the service do not bind there.
  • The loops of a progress check. A check of the step progress can name the loops that mark it, with its stall time: marks: { loops, stall }. Each loop is a check or a worker of the service.
  • The stall time. lint() compares the stall time with the longest gap between two marks of the slowest loop (PROGRESS_RULE). A loop marks at the end of each turn, also a turn that fails. The gap of a check is interval × (1 + jitter) + timeout. The gap of a worker is its sleep or its longest backoff, the longer one, plus unit_processing_time. At 300 s ± 20 % and a timeout of 10 s, a poll gives 370 s.
  • The marks of the timers. A harness that runs a service k times faster scales its timers. Each timer has a mark: scalable, fixed, stepped (only multiples of a step) or floored (a peer sets a floor).
  • The compression of a service. compressionOf(description, scenario, rules, k, marks) gives each rule and scope whose verdict the compression changes. It also names the symbols that have no mark. It reads the rules that lint() applies, with their bindings: the service rules and BOUND_RULES. PLATFORM_MARKS marks the timers of Kubernetes. For example, the propagation of the endpoints is fixed, thus a compression of the hold of O04 can break O04.
  • A name that is not a loop. A name that is not a check or a worker gets a depends finding. Without marks, a check gets no finding of this rule.
  • Keyed limiters. svc.limiter(name, spec) declares a rate limit for each key, as data. keyedLimiter makes its runtime on a store (The keyed limiter).
  • The hold. The cap of the fail readiness phase binds readiness_hold@process, and a service without that phase holds for zero. The hold keeps the listener open after the signal, as a preStop sleep does. Thus O04 can compare the sum of the two with the propagation of the endpoints.

The format of a description is mark1russell7.service/1.

The health runtime

await svc.start() closes the composition and gives a Health. The runtime reads each timing, poll and coupling from the description.

  • Checks on their own loops. Each check polls on a fixed delay from the planned start of each poll, with its jitter, as a loop of the loop core. Each poll has a timeout, and the runtime aborts the signal of the check at that timeout. An answer is "ok", "error" or "indeterminate". A throw is an error with a flag. An indeterminate poll measured nothing, thus it moves no streak.
  • A pending use is not started again. While a use of a check is pending, each later poll fails at once with the same cause. Thus a check that hangs fails a debounce of two polls or more as fast as an error does (failSpan(timing, poll, "hang")).
  • The metrics. health.metrics() gives the counts of the runtime, and starts no check. For each check, it counts each outcome, each throw and each forced failure. Its histogram counts the durations of the polls. The bounds are fractions of the timeout of the poll, and a poll that timed out goes into timedOut. Its last 8 episodes of failure each go from the first error to the next pass. The cause of an episode has no user, password or token (redact). It also counts each transition of the machines of the runtime.
  • A latch for each check that gates a policy. A debounce counts polls in sequence. A window measures time on the monotonic clock from the first failure of a sequence. A readiness latch starts tripped, thus readiness is earned. A liveness latch starts released.
  • The start. start() makes one warm-up sweep of each check, bounded by each timeout, and then starts the loops. The startup probe fails until the sweep ends. svc.health gives the runtime from the start of start(), thus the probes can answer during the sweep. The verdict says when the sweep outlasts the startup budget.
  • The verdicts. health.verdict() gives started, draining, ready, alive, each controller, each dependency and each check. The service is ready when it started, it does not drain, and each readiness latch is released. A controller is ready when its own dependencies are ready. Thus a failed dependency fails only the controllers that need it.
  • Couplings. A declared coupling fails a policy when the other one fails, for example { from: "liveness", to: "readiness", effect: "fails" }. Without a declaration, no coupling applies.
  • Late parts. A check that joins after the start polls at once, and its readiness latch starts tripped until its first pass. A dependency that joins after the start is tripped until a check on it passes.
  • Probes from the cache. health.probe("startup" | "readiness" | "liveness" | "report", controller?) gives a status (200 or 503) and an application/health+json body, for any HTTP framework. A probe starts no check. The report always answers 200, with the whole verdict.
  • Seams for tests. health.forceFail(name, true) makes the polls of a check or a dependency fail at once. health.drain() fails readiness for good. health.stop() stops each loop and each timer, and the timers of the real clock do not keep a Node process alive.

The lifecycle

await svc.run() starts the whole life of the service, and gives a Lifecycle when the startup ends. It refuses a declaration that it cannot start: a transport without its implementation, or a stage with work and no declared phase.

  • The parts. svc.server(name, knobs, impl), svc.consumer(…) and svc.worker(…) give a transport its implementation. Each transport has one contract: start(signal, life), stopIntake, drain(deadline, signal), inFlight and close. workerLoop and queueDrain give the implementation of a worker and of a consumer (Workers and queues). svc.dependency(name, spec, handle) gives a dependency a handle that connects and closes. svc.healthServer(server) gives the server of the probes.
  • The startup. The health server starts first, thus the probes answer while the dependencies connect. Then each dependency connects, in its declared sequence. Then each transport starts, and the startup gate opens last, after one warm-up sweep of each check. A part that does not start fails the startup. Then only the parts that started stop, and the exit code is 1.
  • The startup budget. When the gate is not open at the end of its budget, the gate says so. The runtime does not stop itself, because the startup probe of the platform acts on it.
  • The signals. The runtime owns the handlers of SIGINT, SIGTERM and SIGQUIT. The first signal starts the shutdown. A signal during the startup gets its shutdown after the startup ends.
  • A repeat signal. Each declaration tells what a signal during the shutdown does (svc.onRepeatSignal). With "exit", the signal ends the process at once, with the code 1. With "ignore", the signal has no effect, as in 0.4. A second shutdown() and a second process trigger do not end the process.
  • A declaration without the policy. describe() refuses a declaration that does not declare onRepeatSignal. A description from another source can lack it, for example the JSON of 0.4. Then lint() gives a depends finding of the rule declaration, and unbound names the field.
  • Process triggers. svc.trigger("stdin-close") starts the shutdown when the standard input ends, as when the parent of a stdio child stops. "ipc-close" starts it when the IPC channel to the parent closes. Each trigger is opt-in. The process must read its input, as a stdio transport does, or Node does not see the end.
  • A message of the IPC channel. Windows cannot give a child a SIGTERM that the child can catch, thus a parent sends a message. svc.trigger("ipc-message", { match: "shutdown", as: "SIGTERM" }) starts the shutdown at that message.
  • The shape of a message. match is a value of JSON. A string, a number, a boolean or null matches an equal message. An object matches a message that has each of its fields, and an array matches item by item.
  • A message as a signal. With as, the message is that exit signal: it gets its exit code and the policy of a repeat signal. Without as, the message is the trigger ipc-message, with its own exit code (svc.exitCode("ipc-message", code)).
  • The shutdown. Readiness fails first. Then the declared phases occur in their sequence, and each phase races its cap. svc.onPhase(name, work) adds the work of an owner to a phase.
  • The stages. A declared phase with the name of a stage gets the work of that stage. The stages are fail readiness, stop intake, drain, close transports, stop the poller, tear down dependencies, close the health server and flush the output. The phase fail readiness holds for its cap while the endpoints update. The signal of the service aborts after the poller stops. describe() refuses the stages out of their sequence.
  • The cooperative abort. During the drain, the requests and the transports get a signal that aborts at the cap less the cooperative window. With the floor half, that time is half the cap at the least, and a window without a bound gives half the cap. With svc.cooperativeFloor("none"), a window of the whole cap aborts the work at the start of the drain.
  • Requests. life.request(controller, route, work, { detail, scope }) does one request on a declared route or route pattern. While the service cannot take new work, it refuses the request with a retryable 503. That occurs before the start, after the intake stops, or while the controller is not ready. A route that no route and no pattern declares throws, because it has no idempotency.
  • The scope of a request. The work gets a signal and a scope: work(signal, scope). With the option scope, the scope of the work is a call child of that scope. That scope can be the scope of an HTTP request or of a job. Without it, the scope is a request entry with no trace and no identity. The signal of the work is the signal of that scope, and the scope closes at the end of the request.
  • Each request is a stream. The request gives a RequestStream: each item of the work, and then one end. A work that gives an async iterable is a stream, also through a promise. Each other value is a stream of one item. stream.collect() reads the items and the end.
  • The reader controls the work. The stream asks the work for an item only when its reader asks for the next event. The request stays in flight until the iterator of the work ends. Thus the drain waits for an open stream. When the reader stops before the end, the work gets its abort and the return() of its iterator.
  • The end. The end is done, failed, refused or cut, with the count of the delivered items. Before the first item, refused and cut have a status. After the first item, the end is in-band: the transport sent its answer, thus it writes the end as the last line of the stream.
  • Requests while the transports start. Each transport gets the lifecycle at its start, and svc.lifecycle gives it from the start of run(). Thus a transport tracks its requests from its start. A request before the end of the startup gets a retryable 503, and keepAlive() is false.
  • Cut requests. When the drain cuts a request, an idempotent route answers 503, retryable. Each other route answers 500, because the work can have had its effect. A keyed route is retryable only while the server keeps its key. After the first item, a cut has no status, and retryable tells the caller if it can send the request again.
  • The cooperative abort of a stream. At the cooperative abort, the work gets its abort, and its iterator gets return(). A stream that ends after the abort ends as a cut. At the deadline of the drain, each request that is left gets a cut at once.
  • Route patterns. controller.pattern(pattern, operations, operationOf) matches the routes that the exact routes do not name, in the sequence of the patterns. In a pattern, * matches each text, and :name matches one part without /. The declaration names each operation that a request of the pattern can be, with its idempotency.
  • The idempotency of each request. The function operationOf gets the route, the parts of the pattern and the detail of the request. It gives the name of the operation, thus the retry rule and the answer of a cut. A pattern with one operation needs no function. describe() exports each pattern and its operations as data, and it checks them as it checks a route.
  • Keep-alive. life.keepAlive() is false while the service is not ready. Thus each response then closes its connection.
  • The scopes of the lifecycle (SYS-134). life.scope is the service scope, and life.signal is its signal. It is a child of the process scope: the option run({ scope }), or a scope that the lifecycle makes and closes at the exit. After the poller stops, the service scope aborts with the reason the service stopped.
  • The scope of each phase. Each phase gets a phase scope under the process scope, with the cap of the phase as its timeout. Thus a phase after stop the poller does not start aborted. At the cap, its signal aborts with a TimeoutError. The phase scope closes at the end of its phase. The service scope closes before the lifecycle sets the exit code, and each close error is an error of the lifecycle.
  • The exit. Only the lifecycle ends the process, through its ProcessPort. The exit code is 0 after a clean shutdown. It is 1 after an error: a startup that failed, a phase whose work did not end in its cap, or a work that threw. A phase over its cap does not stop the sequence.
  • A phase fails only for its own work. At the cap of the drain, a transport that waits only for the bytes of its answers did its work. Then the cap is not a failure, and the exit code stays 0.
  • The answers that did not go. The event of that cap (phase.cap) gives the cause and the count, for example answers not flushed: 2. The close of the transports then destroys those sockets.
  • Work that did not end. A call whose end did not come, a transport that did not end its drain, or a step of an owner still fails the phase. The exit code is then 1, as before.
  • Only the work of the drain. The drain waits only for the streams that life.request of its lifecycle made, because only its cut ends them. A stream of another lifecycle, or of none, does not hold the drain. The record of the drain gives their count, for example streams outside the lifecycle: 1. Thus each exit code is the exit code of 0.5.4.
  • Uncaught errors. run({ uncaught: { exitCode, ignore } }) adds a handler for uncaughtException and unhandledRejection from the start to the exit. Without the option, the runtime adds no handler, as before.
  • An uncaught error starts the shutdown. The error is an error of the lifecycle, and the logger gets it at error, with its stack. Then the staged shutdown starts with exitCode, as a signal does. The default code is 1.
  • Skipped errors. ignore(error, origin) tells if the runtime skips an error, for example an ECONNRESET or an EPIPE of a peer socket. The logger gets a skipped error at warn, and the service continues.
  • The port of the errors. The runtime adds the handler through ProcessPort.onUncaught, an optional method. embeddedProcess() does not have it, because the owner of the process keeps its errors.
  • Exit codes. life.shutdown(cause, { code }) gives the exit code of the work, a whole number from 0 to 255. The first request with a code sets it. svc.exitCode(trigger, code) gives the code of a shutdown that a trigger starts, for example 130 for SIGINT. A code that is not 0 stays after an error. A code of 0, or no code, becomes 1 after an error.
  • The output. The stage flush the output comes last. The owners of the phase write their last output first, for example a log or a trace exporter. Then the ProcessPort writes the buffered output of stdout and stderr, in the cap of the stage. Without this phase, the process exits without a wait, as in 0.4.
  • Telemetry by default. run() starts the context of OpenTelemetry for the service, with startNodeContext({ serviceName }) of @mark1russell7/otel-ts/node/context. Each span of the service then has a trace, and the stage flush the output stops the context. A service without that stage stops it after its exit, with no wait.
  • No export without an endpoint. Without OTEL_EXPORTER_OTLP_ENDPOINT, no span leaves the process, and the exporters do not load. With it, the spans go to the exporters of exportSpanProcessors() of otel-ts.
  • Metrics with an endpoint. With otel-ts 0.11.2 or later, the metrics also go to the meter provider of exportMeterProvider(). OTEL_METRICS_EXPORTER=none turns them off.
  • The metrics of the Node runtime. The optional peer @opentelemetry/instrumentation-runtime-node (RUNTIME_METRICS) uses that meter provider. It records the delay and the use of the event loop and the heap of V8, for example nodejs.eventloop.delay.p99. Without the package, the service starts with no runtime metrics. The shutdown stops them before it flushes the meter provider.
  • No second context. run() starts nothing when contextOwner() of otel-ts gives an owner: the program started its own context, or a test captures the telemetry. The service then uses that context.
  • Without otel-ts. otel-ts is an optional peer. When it, or a package of its entry /node/context, is not installed, run() starts nothing, and the service starts as before.
  • The options. run({ telemetry: { env, version } }) gives the environment of the endpoint (the default is process.env) and the resource attribute service.version. run({ telemetry: false }) turns the telemetry off.
  • The hold. The lifecycle holds its process from its start to its exit, through ProcessPort.hold, as a listening socket does. The hold is one timer of the event loop, and the exit releases it. The other timers of the runtime still do not keep the process alive (A14).
  • Why the hold lasts to the exit. A drain can wait on a timer that does not keep the process alive. Without the hold, Node then ends the process with the code 0 in the drain. The teardown and the declared exit code are then lost. Thus the hold does not end at the stop of the intake, and it is not a knob.
  • The watchdog. svc.watchdog(spec) declares a check on the event loop. A blocked loop delays each timer, thus a tick that comes late by more than the threshold fails the check. A liveness window then reads the wedge of the process. The ticks of the watchdog are rounds of the loop core, thus they keep their grid after a block.
  • The logger. run({ logger }) and start({ logger }) give each transition of the machines to a logger, as an entry with a level and fields. The logger is one sink of the same stream as record (logEvents).
  • The levels. Each step of the startup, each phase with its cap, its outcome and its duration, and the exit code are info. A phase at its cap is warn, and an error of the lifecycle is error. The polls are debug.
  • The logger port. A Logger has one method, log(level, message, fields), thus an adapter to another logger is a few lines. consoleLogger({ level }) writes to the console at info and above by default.
  • Lines of JSON. consoleLogger({ level, format: "json" }) writes one line of JSON for each entry, with level, message and each field. An error field gives its name, its message and its stack. The default format is text, as before.
  • Trace ids. consoleLogger({ traceIds }), with traceIds from @mark1russell7/service/otel, adds the trace_id and the span_id of the active span of OpenTelemetry to each entry. A field of the entry with the same name stays. When no span is active, for example when no program registered an SDK, the entry does not change. Only the entry /otel loads @opentelemetry/api.
  • The context of a call. callContext from @mark1russell7/service/otel takes the trace, the baggage and the remaining time across the network, with the propagator that the program registers. It reads a trace (trace(headers, trusted)), makes a scope the active scope (run(scope, fn)), gives the active scope (current()) and writes trace headers (headers(scope)):
    • httpTransport(server, knobs, { callContext }) does each handler in the scope of its request (The HTTP edge). The request joins the trace of traceparent. Its baggage is dropped, unless trustBaggage(req) gives true, for example after a token check.
    • httpClient(name, spec, { callContext }) sends the trace headers of the active scope with each call, for example traceparent, and the remaining time of the scope in timeout-ms. A header of the call with the same name stays. The wait of each try ends at the earlier of request_timeout and the deadline of the scope.
    • grpcClient(name, spec, { callContext }) sends the trace headers of the active scope in the metadata of each call. Metadata of the spec or of the call with the same name stays. The deadline of the call is the earlier of request_timeout and the deadline of the scope.
  • No logger. Without a logger, the runtime writes no log, as before. testLogger() of @mark1russell7/service/testing keeps each entry, thus a test can examine the log.

The machines

The machines of the runtime are mark1russell7.machine/1 documents, which @mark1russell7/algebra reads. They are the gate, the latch (a debounce), the window, the poller, the exit manager and the watchdog. drainMachine(description) gives the drain of a declaration, with one state for each phase. The keyed limiter has its own documents.

Each machine gives its transitions to run({ record }) or start({ record }). replay(doc, events) gives each transition that the document does not permit. It is the replay of @mark1russell7/algebra, which reads a machine of any name.

The tests replay the real runtime against each document. They also compare each timer of the documents, from the algebra, with the time that the runtime keeps.

Composition

A process has one service, and one entry that uses run(). A component gives parts to that service, and it does not start them. For example, a component is the procedures host of another repository, or one of the HTTP hosts of a process.

  • The parts. A component gives a TransportImpl for each source of work, a DependencyHandle for each dependency that it owns, and each check with its CheckFn. It can also give work for a declared phase (onPhase).
  • The entry. The entry declares one service: the parts of each component, the policies, the startup budget, the phases and the cooperative window. Only the entry uses run(). Thus the process has one set of signal handlers, one staged shutdown and one exit.
  • What a component does not do. A component does not use start() or run(). It installs no signal handler, and it does not end the process. A service has one health server, thus the entry chooses it.
  • An entry in a process that another part owns. A script, a test of an application or a library entry can start a service in a process that it does not own. It gives run() the port embeddedProcess(). That port adds no signal handler, it does not hold the process, and its exit only records the code. The caller stops the service with life.shutdown() and reads the code from life.done.
  • Names. A service refuses a second part of one kind with the same name. Thus the entry gives each component a prefix, for example app.http and ingest.http.
  • The sequence. The lifecycle connects the dependencies of all components in their declared sequence, and then it starts each transport. Each stage of the shutdown acts on the transports of all components together. The dependencies close in the reverse sequence.
  • Requests. The transports start before the startup ends, but run() gives the Lifecycle only at that end. Thus each transport gets the lifecycle at its start (start(signal, life)), and its request tracking operates at once.
  • The builder form. A component can also take the builder of the entry and declare its parts on it. The Redis client does this: attach(svc, options) declares its dependency, its handle and its checks.
import type { Extent } from "@mark1russell7/quantity";
import { service } from "@mark1russell7/service";
import type { Check, CheckFn, Dependency, DependencyHandle, ServiceBuilder, TransportImpl } from "@mark1russell7/service";

// the parts of a component, as data: the component declares nothing, and it does not run
interface Parts {
  readonly servers: ReadonlyArray<{ name: string; knobs: Record<string, Extent>; impl: TransportImpl }>;
  readonly dependencies: ReadonlyArray<{ name: string; spec: Omit<Dependency, "name">; handle: DependencyHandle }>;
  readonly checks: ReadonlyArray<{ check: Check; run: CheckFn }>;
}

const declare = (svc: ServiceBuilder, parts: Parts): void => {
  for (const { name, spec, handle } of parts.dependencies) svc.dependency(name, spec, handle);
  for (const { name, knobs, impl } of parts.servers) svc.server(name, knobs, impl);
  for (const { check, run } of parts.checks) svc.check(check, run);
};

const s = (value: number) => ({ value, unit: "s" });
const svc = service("app");
// three hosts in one process: each component gives its parts under its own prefix
for (const [prefix, port] of [["app", 4820], ["ingest", 4830], ["remote", 4840]] as const)
  declare(svc, createHost({ prefix, port }));
svc
  .healthServer(probes) // the entry chooses the one health server of the process
  .readiness({ type: "debounce", interval: s(5), failAfter: 3, recoverAfter: 1 })
  .liveness({ type: "window", failAfter: s(45) })
  .startup(s(60))
  .phase("fail readiness", s(2))
  .phase("stop intake", s(5))
  .phase("drain", s(15))
  .phase("close transports", s(2))
  .phase("stop the poller", s(1))
  .phase("tear down dependencies", s(2))
  .phase("close the health server", s(1))
  .cooperativeWindow(s(5))
  .onRepeatSignal("ignore");

const life = await svc.run(); // only the entry calls run(), and the process exits after the shutdown

The requirements that the lifecycle follows are in the requirements of S6.

Workers and queues

workerLoop(knobs, options) makes a worker from a loop, and queueDrain(knobs, options) makes a consumer from a queue. Each one is a TransportImpl, with no defaults. Give loop.knobs to svc.worker(name, knobs, impl), and drain.knobs to svc.consumer(…). Thus the declaration and the law read the same knobs.

  • The worker loop (S6 A10). A worker has a setup, an iteration and a teardown. The start does the setup, and each iteration gets its state. Each lane does its iterations one at a time, thus two iterations of a lane do not overlap. concurrency is the number of lanes. The lanes are the lanes of a loop of the loop core, with workerSchedule(knobs).
  • The sleep. worker_sleep is the time from the end of one iteration to the start of the next. An iteration that gives "more" starts the next one after a zero sleep. A sleep without a bound waits for wake().
  • The first iteration. The first iteration of each lane comes after the startup ends, because the service refuses a request before that end.
  • The failures. A throw is a failure, and the lane then waits its backoff. The first delay is retry_base, and each delay is two times longer, up to retry_cap, with a jitter up to the base. A success ends the sequence. onError gets each failure, and the loop does not end the process (A5).
  • wake(). It ends each sleep at once, also a sleep that comes after the iteration in flight. Then the next iteration starts at the end of that iteration, with no timer. It does not end a backoff. After the stop of the intake, it gives false.
  • The queue drain (S6 A11). One taker takes a job from the source while a slot is free. concurrency is the number of slots, and a count without a bound takes each job that comes. The source is a function that takes the next job, or an async iterable.
  • An empty source. A take with no job waits queue_poll_interval, or until wake(). A failed take waits the backoff.
  • The end of a source. The end of an async iterable stops the takes. While the intake is open, onError gets that end, because the drain then takes no more jobs. An async generator that throws gives its throw and then its end.
  • The end of each job. A success gets settle.ack. A failure gets the action of the redelivery policy: requeue, reject or ack. The queue declares its policy, because the drain has no default.
  • The policy of A11. redeliverOnce(then, poison) gives ack to a poison message. Each other job goes back one time after its first failure, and then decides each later failure.
  • The deliveries. The policy gets the count of deliveries of the job, 1 at the first. settle.delivery gives that count from the queue, for example x-delivery-count of RabbitMQ or ApproximateReceiveCount of SQS. It is necessary, because a broker gives a new object at each delivery. A queue in memory counts for itself.
  • The bound of a unit. unit_processing_time is the most time of one iteration or one job. At it, the signal of the unit aborts, and a throw after it is a failure. The law reads it as unit_processing_time@consumer.
  • The scope of each unit (SYS-134). Each transport makes a work scope: a phase child of life.scope, with the name workerLoop or queueDrain. Each iteration is a round entry, and each job is a job entry, under the work scope. The deadline of a unit is its unit_processing_time, and at it the signal aborts with a TimeoutError. The scope of a unit closes after the unit ends, before the settle of its job.
  • The context of a unit. The context is the scope of the unit, with its facts. Each context has intake and life. An iteration also has state, lane and failures, and a job has delivery. A fact is an own property of the scope that cannot change.
  • The trace of a job. options.entry(job) gives the trace and the identity of the scope of a job, for example from the headers of a message. Without it, a job has no trace and no identity. A throw of entry is a failure of the job, and the handler does not start. A round gets the identity of the work scope.
  • The work scope. It aborts at the cooperative abort and at the close, and then it closes. onError gets each error of the close of a scope.
  • The stop of the intake. No new iteration starts, and the drain takes no new job. Each sleep and each backoff ends. The drain ends an async iterable through return(). A take that gives a job after the stop gives it back (settle.requeue(job, "unstarted")).
  • The drain. drain(deadline, signal) waits for each unit in flight until the deadline, and gives each one the cooperative abort. A throw after that abort is a cut, not a failure.
  • A cut iteration. A cut stops the worker loop: no lane starts an iteration after it. Each cut comes from the shutdown, and the lifecycle stops the intake before the shutdown.
  • A cut job. A cut job goes back ("cut") only when its route can go again (A12). Each other cut job gets settle.reject.
  • The close. close aborts each unit, waits for its end, and then does the teardown or options.close, all in close_bound. The teardown occurs each time that the setup started, also after a failed setup. The close rejects a job that does not end in the bound.
  • The request tracking. With request: { controller, route }, each unit goes through life.request. The service then admits, counts, drains and cuts each unit as it does each request. A route function and detail can give each job a route of a pattern. The request is a call child of the scope of its unit, and the handler gets it in scope.children().
  • The refusals. While the service refuses its units, the loop and the taker wait their backoff, and each refused job goes back ("unstarted"). Thus a worker stops while a dependency of its controller is not ready.
  • The clock. The sleeps and the backoffs use the clock of the options. Give the clock of the lifecycle. The bound of a unit is the deadline of its scope, on the clock of the tree of scopes: the clock of the lifecycle. With the real clock, the timers do not keep a Node process alive (A14). The lifecycle holds the process until its exit, thus a process whose only parts are workers does not end while it waits.
  • The law. lint() applies O20 one time for each consumer and each worker. A knob of the transport binds at the hop consumer, and a knob with a hop in its name binds at that hop. The scenario gives the lease of each source, for example the visibility timeout of SQS.
  • The bounds. lint() compares the bounds of each consumer and each worker with the caps of two phases (BOUND_RULES). unit_processing_time is less than the cap of drain, or the drain can cut a unit (unit-bound). close_bound is less than the cap of close transports (close-bound). A unit without a bound violates unit-bound.
  • The problems. problems(description) gives each phase that the loop needs and that the declaration does not give: drain and close transports.
import { kubernetes, lint, queueDrain, redeliverOnce, service, workerLoop } from "@mark1russell7/service";

const s = (value: number) => ({ value, unit: "s" });
const count = (value: number) => ({ value, unit: "count" });

// a heartbeat each 6 h, in one lane: a bound of 10 s for each beat, in the drain of 15 s, and a backoff from 10 s to 5 min
const heartbeat = workerLoop(
  { worker_sleep: s(6 * 3600), unit_processing_time: s(10), retry_base: s(10), retry_cap: s(300), close_bound: s(1), concurrency: count(1) },
  {
    setup: () => openClient(),
    iteration: ({ state, signal }) => state.beat(signal),
    teardown: (state) => state?.close(),
    onError: (error, failures) => log.warn({ error, failures }, "the heartbeat failed"),
  },
);

// the jobs of a table, 4 at a time: a poll each 2 s, and the policy of A11
const jobs = queueDrain(
  { queue_poll_interval: s(2), unit_processing_time: s(10), retry_base: s(1), retry_cap: s(30), close_bound: s(1), concurrency: count(4) },
  {
    source: (signal) => db.claimNextJob(signal), // a job, or null
    handle: (job, { signal, delivery }) => runPipeline(job, { signal, delivery }),
    settle: {
      ack: (job) => db.markDone(job),
      delivery: (job) => job.attempts, // the count of the table, 1 at the first take
      requeue: (job) => db.markQueued(job),
      reject: (job, error) => db.markFailed(job, error),
    },
    redelivery: redeliverOnce("reject", (error) => error instanceof InvalidJobError),
    request: { controller: "jobs", route: "RUN" },
  },
);

const app = service("app")
  .dependency("db", { system: null, knobs: {}, operations: {} }, { connect: () => db.connect(), close: () => db.end() })
  .worker("heartbeat", heartbeat.knobs, heartbeat)
  .consumer("jobs", jobs.knobs, jobs)
  .profile(kubernetes({ grace: s(30), preStop: s(0) }))
  .readiness({ type: "debounce", interval: s(5), failAfter: 3, recoverAfter: 1 })
  .liveness({ type: "window", failAfter: s(45) })
  .startup(s(60));
// a job that the shutdown cuts goes back on the queue, because its route can go again
app.controller("jobs").requires("db").route("RUN", { idempotent: true });

// O20: the lease of the queue, 30 s, against a job of 10 s
const scenario = { platform: {}, probes: { readiness: s(30), liveness: s(30) }, transports: { jobs: { "lease_duration@broker": s(30) } } };
// the findings also compare each bound with the cap of its phase (BOUND_RULES)
const findings = lint(app.describe(), scenario, rules);
const problems = [...heartbeat.problems(app.describe()), ...jobs.problems(app.describe())];
const life = await app.run();

Profiles

A profile is a part of a declaration as data: the phases, the cooperative window, the policies and the rules of the shutdown. svc.profile(profile) declares each field of a profile, as the method of that field does. The runtime still has no defaults, because the caller gives the profile. The caller changes a field with a spread, and describe() shows the values.

| Profile | For | What it declares | | --- | --- | --- | | localDev | A service on the computer of a developer | No readiness hold, caps that sum to 10 s, a flush of the output, and an exit on a second signal | | daemon | A background host on the computer of a developer | The caps of localDev, no effect for a repeat signal, and no process trigger | | kubernetes({ grace, preStop }) | A pod | Caps from the grace less the preStop sleep, and no effect for a repeat signal | | ephemeral | A command that runs one time, or a stdio child | No gating checks, an abort at the start of the drain, a flush of the output, and the exit codes 130, 143 and 131 |

  • Kubernetes. The budget is the grace less the preStop sleep: the time from SIGTERM to SIGKILL. The stages get 2, 5, 15, 2, 1, 2, 1 and 1 thirtieths of the budget, rounded down to the millisecond. The last stage flushes the output. The cooperative window is 5 thirtieths. Thus 1 thirtieth stays as a margin, and O10 and O16 hold.
  • The defaults of Kubernetes. At a grace of 30 s and no preStop hook, the caps are 2, 5, 15, 2, 1, 2, 1 and 1 s. The window is 5 s. These are the caps of the kind lab.
  • Local development. No load balancer routes to a computer of a developer, thus the profile has no readiness hold. A second Ctrl-C exits at once.
  • A background host. A supervisor or a command stops the host with a signal. A repeat signal has no effect, thus the host ends its drain. The host has no parent on stdin, thus the profile declares no process trigger.
  • The repeat signal. Each profile declares onRepeatSignal: "exit" for localDev and ephemeral, and "ignore" for daemon and kubernetes.
  • The policies. localDev and kubernetes do not declare readiness, liveness or the startup budget, because they depend on the checks of the service.
import { kubernetes, service } from "@mark1russell7/service";

const s = (value: number) => ({ value, unit: "s" });
const svc = service("app")
  .profile({ ...kubernetes({ grace: s(60), preStop: s(5) }), onRepeatSignal: "exit" })
  .readiness({ type: "debounce", interval: s(5), failAfter: 3, recoverAfter: 1 })
  .liveness({ type: "window", failAfter: s(45) })
  .startup(s(60));

A small process

A command that runs one time and a stdio child also use run(). Then the process has one shutdown and one exit, with the code of its work. The minimal declaration has no probes, no health server and no checks.

import { ephemeral, service } from "@mark1russell7/service";

// a stdio child: the end of stdin starts the staged shutdown
const mcp = service("mcp").profile({ ...ephemeral, triggers: ["stdin-close"] }).server("stdio", {}, stdio);
mcp.controller("tools").route("tools/call", { idempotent: false });
await mcp.run();

// a command: it runs one time, and the process exits with its code
const tool = service("tool").profile(ephemeral);
tool.controller("command").route("RUN", { idempotent: false });
const life = await tool.run();
const { items, end } = await life.request("command", "RUN", (signal) => main(signal)).collect();
await life.shutdown("the command ended", { code: end.kind === "done" ? items[0] : 1 });
  • The declaration. The profile ephemeral gives the policies, the startup budget, the phases and the rules of the shutdown. The recipe passes describe() and lint(), and a test holds it to them.
  • Ctrl-C. The floor of the cooperative abort is none, and the window is the whole drain. Thus a first Ctrl-C stops the work at once, and the process exits 130. A second Ctrl-C exits 1 at once.
  • The output. The stage flush the output waits for stdout and stderr. Thus the last lines of a command are not cut.
  • The dependencies. The phase tear down dependencies caps the close of the dependencies at 2 s.

The drain rules

The caller of lint() and lintStop() gives the rules. @mark1russell7/service/rules gives the rules of the drain as data: O04, O09, O10, O16 and the list DRAIN_RULES. The entry loads no module at run time. Thus it loads no Testcontainers, no node: module and no zod, and a service can import it in its tests. The root of the package also gives each rule, and @mark1russell7/kind gives the same objects.

  • O04. The preStop sleep plus the hold of fail readiness is at least the propagation of the endpoints.
  • O09. Readiness detection plus the propagation is no longer than liveness detection plus the preStop sleep.
  • O10. The preStop sleep plus the drain of the process fits in the grace period.
  • O16. The cooperative window is shorter than the drain, and the drain is shorter than the grace less the preStop sleep.
import { lint } from "@mark1russell7/service";
import { DRAIN_RULES } from "@mark1russell7/service/rules";

const findings = lint(svc.describe(), scenario, DRAIN_RULES);

The timers

The clock, the heartbeat and the backoff have their own entries. Each entry imports no node: module and no zod. The only other package that they import is @mark1russell7/algebra/clock, which imports nothing. Thus a client in a browser can use them. Each entry is less than 1 kB of gzip. The root of the package also gives each function.

| Entry | Exports | | --- | --- | | @mark1russell7/service/clock | Clock, Cancel, realClock, platformClock, unrefClock | | @mark1russell7/service/heartbeat | heartbeat, detectionTime | | @mark1russell7/service/backoff | backoffDelay, backoffBand, backoffProblems, doublingBackoff |

  • The clock. platformClock({ unref }) gives a clock on performance.now() and setTimeout. With unref: true, its timers do not keep a Node process alive. realClock is platformClock(): its timers keep the process alive, as setTimeout does. Each cancel also has unref, for one timer.
  • The rule of unref. The service uses the unref of a timer only when a socket, a child process or the hold of the lifecycle keeps the process alive. Each other timer stays referenced. Thus a wait that a caller awaits, for example retry or within, ends before the process exits.
  • The timers that do not keep the process alive. These timers only watch other work. Examples are the heartbeat of a connection, the checks and the watchdog of a service, and the sweep of a listener. The timers of a supervisor for a live child are also examples. unrefClock(clock) gives a part such a clock.
  • The timers that keep the process alive. These timers are work, or they bound work that a caller awaits. Examples are a retry, a ticker, the sleeps of a worker loop and the polls of watchTargets. The owner stops each one.
  • Before 0.9.0. The default clock did not keep the process alive. Thus a command-line tool ended in the wait of a retry, with the code 0 and lost work.
  • The home of the clock. The clock lives in @mark1russell7/algebra/clock, beside its fake. This entry gives the same functions. Thus a package that the service imports, for example collections, can use the clock with no cycle.
  • The heartbeat. heartbeat(options) sends a ping each interval, and a timeout bounds each ping. A ping without an answer at its timeout is a miss. The last of misses misses in sequence starts onDead. Each tick is a round of the loop core, thus the ticks keep their grid after a block of the event loop.
  • Two kinds of ping. A ping gives its answer as a promise, as a request and its reply do. Or the answer comes later through answer(), as a pong message does.
  • The hooks of a heartbeat. At each tick, due tells if the tick sends a ping. live tells if a miss counts. turn waits one turn of the event loop before the heartbeat counts. Without overlap, the heartbeat sends one ping at a time.
  • The detection time. detectionTime(interval, timeout, misses) gives the most time to find a silent peer: misses intervals plus a timeout. heartbeatDetection gives that time as an amount for the law.
  • The backoff. backoffDelay(policy, attempt, random) gives the delay before a try: base × factor^(attempt − 1), at most cap, with a jitter. The first try is 1.
  • The jitter. The jitter subtract takes a random part of the delay away, and a fraction of 1 is the full jitter. The jitter add adds a random time up to an amount.
  • The band. backoffBand(policy, attempt) gives the least and the most delay of one try. Without a try, it covers each try. The law reads the most delay from it. backoffProblems(policy) names each value that the delays cannot use.
  • The retrier. retrier({ base, factor, cap, jitter, clock, signal }) starts a function again after the backoff of each try. The root of the package gives it, and the entry ./backoff does not.
  • The calls of a retrier. schedule(run) counts one more try, and starts run after the delay of that try, on the clock. It gives the delay, and attempts gives the count. A second schedule stops the retry that waits.
  • The end of a retrier. reset() sets the count to 0, for example after a start that succeeded. cancel() stops the retry that waits. The abort of signal cancels the retrier, for example the signal of the lifecycle in the drain.
  • One call with retries. retry(run, { tries, retryable, delayOf, ...backoff }) starts an async run, and starts it again after an error. It stops at tries tries, the first included.
  • The errors of a retry. retryable(error) tells which errors get a new try. After the last try, retry throws the last error. The abort of signal stops the wait.
  • Retry-After. delayOf(error, attempt) gives a delay in place of the backoff. retryAfterDelay(header, now) reads the seconds or the HTTP date of a Retry-After header.
  • Milliseconds. These functions take times in milliseconds, as the clock does. The declaration and the law keep their amounts (Quantity).
import { retrier, retry, retryAfterDelay } from "@mark1russell7/service";
import { backoffDelay } from "@mark1russell7/service/backoff";
import { heartbeat } from "@mark1russell7/service/heartbeat";

const beat = heartbeat({
  interval: 30_000,
  timeout: 10_000,
  misses: 2,
  ping: () => socket.send(JSON.stringify({ type: "ping" })),
  onDead: () => socket.close(),
});
socket.addEventListener("message", (event) => {
  if (JSON.parse(event.data).type === "pong") beat.answer();
});

// full jitter: a random time from 0 to the backoff
const delay = backoffDelay({ base: 1000, factor: 1.5, cap: 30_000, jitter: { kind: "subtract", fraction: 1 } }, attempt);

// a watch that starts again after each failure, until the drain of the service
const rewatch = retrier({ base: 1000, factor: 2, cap: 30_000, jitter: { kind: "subtract", fraction: 1 }, signal: life.signal });
const watch = (): void => {
  start().then(
    () => rewatch.reset(),
    () => rewatch.schedule(watch),
  );
};

// one read with 4 tries at most: a 429 or a 5xx gets a new try, and a 429 waits for its Retry-After
class Busy extends Error {
  constructor(readonly response: Response) {
    super(`HTTP ${response.status}`);
  }
}
const response = await retry(
  async () => {
    const res = await fetch(url);
    if (res.status === 429 || res.status >= 500) throw new Busy(res);
    return res;
  },
  {
    tries: 4,
    base: 1000,
    factor: 2,
    cap: 15_000,
    jitter: { kind: "subtract", fraction: 1 },
    delayOf: (error) => (error instanceof Busy ? retryAfterDelay(error.response.headers.get("retry-after"), Date.now()) : null),
  },
);

The loop

@mark1russell7/service/loop is the one loop core of the service. A loop starts rounds on a schedule, on a clock, with a scope for each round. The entry imports only the quantity package and the clock: no node: module and no zod. Thus a client in a browser can use it. The root of the package does not give its functions.

| Entry | Exports | | --- | --- | | @mark1russell7/service/loop | loop, scheduleProblems, pollSchedule, workerSchedule, streamSchedule, LOOP_MACHINE and the types Schedule, Budget, Round, RoundContext, LoopRecord |

  • In place of setInterval. A schedule from start plans each round one period after the planned start of the last round. A round that is late does not move the grid.
  • In place of setTimeout after await. A schedule from end plans each round one period after the end of the last round. A lane from end has one round at a time.
  • The schedule is data. Each field of a Schedule is necessary. scheduleProblems(schedule) names each value that the loop cannot use, and loop() throws for a schedule with problems.
  • The period and the jitter. Each period is period × (1 ± jitter). A test gives a seeded random, and each gap is then exact. A period without a bound starts a round only at wake().
  • The timeout. At timeout, the scope of the round aborts, and the round is a failure. A round that does not stop at the abort keeps its lane hung until it settles.
  • The backoff. After the k-th failure in sequence, the gap is the backoff delay of try k. A pass sets the count to zero. With backoff: null, the gap after a failure is the period.
  • The overlap. A round can come due while its lane has a round in flight. From start, the due round fails at once (fail), does not occur (skip), or starts beside the other round (allow).
  • The lanes and the budget. lanes is the count of lanes. Each lane is one instance of LOOP_MACHINE. A budget lets at most rounds rounds start in each window of per, over all lanes. A due round past the budget waits for the window.
  • The hold. With hold: true, the timers of the loop keep a Node process alive. With hold: false, only the deadline of a round in flight keeps the process alive.
  • The proof of a stream. With a stable time, a round proves its lane when it uses reset(), or when it stays in flight for that time. A round with no proof is a failure, also when it passes. Its error is an UnprovedRoundError. Thus a stream that drops after each open backs off up to the cap.
  • Where to use reset(). Use reset() at a proof, for example the first useful message of a stream. Do not use it when a connection opens. Else a server that refuses each connection after the handshake gets a new connection with no backoff.
  • A round. A round gets its scope, its signal, its lane, its number, its planned start and the count of failures in sequence. It gives "more" for the next round at once, or nothing for a pass. A throw or a rejection is a failure.
  • The records. record gets one record for each start, end, skip and wait of the budget. onTransition gets each transition of each lane, with the instance <name>#<lane>. replay of @mark1russell7/algebra/replay checks them against LOOP_MACHINE.
  • wake(). It starts a round at once on each lane that waits for its period. A lane from end with a round in flight starts its next round at once after that round, in its settle, with no timer. A wake does not end a backoff.
  • The stop. stop() aborts and closes the scope of each round in flight. No round starts after it, and no timer of the schedule stays. A second stop gives the same promise.
  • The scope. The scope of a loop is a process, service or phase scope. An abort of it stops the loop. Without a scope, the loop makes a root scope of the kind service and closes it at the stop.
  • The metrics. loopMetrics() from @mark1russell7/service/otel gives a record and an onTransition for the options of loop(). They count the records as instruments of OpenTelemetry, with the names and units of the table below. Each metric has loop.name and loop.lane, and each failure has error.type: timeout, blocked, unproved, the class of the error, or _OTHER. LOOP_BOUNDS gives the bounds of the buckets in seconds.
  • The loops on the core. The heartbeat, the watchdog, the poller of the checks and the ticker of a channel are loops of this core, from start. Their ticks keep the grid. After a block of the event loop, the late tick comes at once, and the next tick comes at its planned time. The worker loop is a loop of this core from end, with workerSchedule(knobs).

| Metric | Kind | Unit | Value | | --- | --- | --- | --- | | loop.rounds | counter | {round} | each round that starts. A blocked round does not start, thus it is not in this count. | | loop.failures | counter | {round} | each round that fails, with each round past its timeout and each blocked round | | loop.skipped | counter | {round} | each round that a late loop skips, and each round that the overlap skip drops | | loop.deferred | counter | {round} | each round that waits for the window of the budget | | loop.lateness | histogram | s | the real start of a round minus its planned start | | loop.round.duration | histogram | s | the end of a round minus its start. A round past its timeout gives the timeout. | | loop.inflight | up-down counter | {round} | the rounds whose scope did not close yet. A round past its timeout stays in it until it settles. |

| Function | Schedule | | --- | --- | | pollSchedule(poll) | the health poller: from start, the jitter of the poll, no backoff, one lane, and overlap: "fail" | | workerSchedule(knobs) | a worker loop: from end, the sleep as the period, the doubling backoff, and one lane for each unit of concurrency | | streamSchedule(backoff, { stable }) | a stream: from end, no period, no timeout, and a stable time of 30 s by default |

import { doublingBackoff } from "@mark1russell7/service/backoff";
import { loop, streamSchedule } from "@mark1russell7/service/loop";

// one long connection for each round: after a drop, the next open waits for the backoff
const feed = loop(streamSchedule(doublingBackoff(1000, 30_000)), async ({ signal, reset }) => {
  for await (const message of openFeed({ signal })) {
    reset(); // the first useful message is the proof: the count of failures goes to zero
    handle(message);
  }
}, { name: "feed" });
feed.start();
life.signal.addEventListener("abort", () => feed.stop().catch(() => undefined)); // the drain stops the feed

// the same loop with its metrics: the meter of the provider that the program registers
import { loopMetrics } from "@mark1russell7/service/otel";
const meters = loopMetrics();
const counted = loop(schedule, round, { name: "feed", ...meters });

Move a loop to the core

A loop of a timer in a package of the preset service moves to loop(). Each case below gives the old form and its schedule. The stop of the loop replaces clearInterval, clearTimeout and the check of a flag.

| Old form | Schedule | | --- | --- | | setInterval(work, ms) | from start, period and first equal to ms | | a setTimeout that starts its own function again after an await | from end, period equal to the delay | | a for or while loop that awaits a timer after each step | from end, period equal to the delay, and backoff for the wait after a failure |

import { doublingBackoff } from "@mark1russell7/service/backoff";
import type { Schedule } from "@mark1russell7/service/loop";
import { loop } from "@mark1russell7/service/loop";

// old: const id = setInterval(() => void refresh(), 30_000); ... clearInterval(id);
const grid: Schedule = {
  from: "start", period: { value: 30, unit: "s" }, jitter: 0, first: { value: 30, unit: "s" },
  timeout: { value: 10, unit: "s" }, backoff: null, overlap: "skip", lanes: 1, budget: null, hold: true, stable: null,
};
const refresher = loop(grid, ({ signal }) => refresh(signal), { name: "refresh" });

// old: const tick = async () => { await sweep(); timer = setTimeout(tick, 5000); };
// old: while (!stopped) { try { await sweep(); } catch { await sleep(backoff(k++)); continue; } await sleep(5000); }
const afterEach: Schedule = {
  from: "end", period: { value: 5, unit: "s" }, jitter: 0, first: { value: 0, unit: "s" },
  timeout: { value: 1, unit: "min" }, backoff: doublingBackoff(1000, 60_000), overlap: "skip", lanes: 1, budget: null, hold: true, stable: null,
};
const sweeper = loop(afterEach, ({ signal }) => sweep(signal), { name: "sweep" });

refresher.start();
sweeper.start();
await Promise.all([refresher.stop(), sweeper.stop()]); // at the drain: no round starts, and no timer stays

The channels

@mark1russell7/service/channel has channels in the style of Go. The entry imports only the clock and @mark1russell7/collections: no node: module and no zod. Thus a client in a browser can use it. The root of the package does not give its functions.

| Function | What it does | | --- | --- | | channel(bufferSize), buffered, unbuffered | It makes a channel. With a buffer of 0, each send waits for a receiver. | | select(...cases) | It waits for the first case with a value. A case that loses keeps no receive. | | timeout(ms, clock) | It makes a channel that gets one value after ms, on the clock. | | ticker(ms, clock) | It makes a channel of ticks. Tick k comes due at the start plus (k + 1) periods, so the ticks do not drift. | | pipeline, fanOut, fanIn, merge, workerPool | They start work between channels. Each failure goes to onError, and the output closes. | | preemptivePool(max) | It operates at most max tasks at a time. A new task stops the oldest task with a PreemptedError, and stop stops each task. |

  • The clock. timeout and ticker take a clock. The default is realClock. A test gives fakeClock() of ./testing, and the time of each channel is then exact.
  • The timer of a timeout. timeout gives no cancel, as time.After of Go. Its timer stays until it comes due, also after select takes another case.
  • A late timer. A ticker gives the number of the last tick that came due, and skips the ticks that it missed. A slow receiver loses ticks, because the buffer has one tick.

The slices of long work

@mark1russell7/service/slices does long synchronous work in short slices. The entry imports only the clock. Thus a client in a browser can use it. The root of the package does not give its functions.

The work is a generator, and each yield ends one step. runSlices(steps, options) does the steps until a slice of sliceMs ends. Then it gives the event loop one turn. Thus the timers, the sockets and the probes of a server get their turns during a long calculation.

| Option | What it does | | --- | --- | | sliceMs | The time of one slice, in milliseconds. The default is SLICE_MS (8). With 0, each slice does one step. | | clock | The clock that measures a slice. The default is the real clock. | | turn | The function that gives the event loop one turn. The default is setImmediate. | | signal | An abort stops the work between two slices. The function closes the steps and rejects with the reason. |

The function gives the result with the counts of the steps and the slices, and the longest slice. A step is synchronous, thus a long step makes a long slice. Keep each step short.

The scopes

@mark1russell7/service/scope gives one scope for each part of the work. The parts are the process, the service, a phase, a request, a job, a