@mark1russell7/service 0.6.7 → 0.7.1
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 +12 -7
- package/build/{builder-bXJqMe2p.d.ts → builder-BWfcgx__.d.ts} +5 -5
- package/build/channel.d.ts +1 -1
- package/build/clock-DpVgpY4h.d.ts +2 -0
- package/build/clock.d.ts +2 -2
- package/build/clock.js +1 -38
- package/build/{core-B1zbS4WY.d.ts → core-Cuh3oSfr.d.ts} +5 -5
- package/build/{dial-CSGKVlZe.d.ts → dial-ZJNa6s9i.d.ts} +2 -2
- package/build/grpc.d.ts +3 -3
- package/build/heartbeat.d.ts +1 -1
- package/build/host.d.ts +6 -4
- package/build/host.js +125 -102
- package/build/host.js.map +1 -1
- package/build/http-client.d.ts +4 -4
- package/build/http.d.ts +9 -7
- package/build/http.js +19 -5
- package/build/http.js.map +1 -1
- package/build/index.d.ts +9 -9
- package/build/index.js +3 -3
- package/build/{lifecycle-Ks9Yd5CM.d.ts → lifecycle-C8ffyrQ9.d.ts} +3 -3
- package/build/{limiter-CmC4vCjk.js → limiter-BTgM4aXZ.js} +19 -8
- package/build/limiter-BTgM4aXZ.js.map +1 -0
- package/build/{limiter-BoZkXIxk.d.ts → limiter-D1aluA0V.d.ts} +3 -3
- package/build/limiter.d.ts +4 -4
- package/build/limiter.js +3 -3
- package/build/{logger-DhFgh48y.d.ts → logger-BY1RFLzq.d.ts} +2 -2
- package/build/mongodb.d.ts +3 -3
- package/build/pg.d.ts +2 -2
- package/build/{policy-G4QJ1ZZq.d.ts → policy-CwYR95Sz.d.ts} +51 -15
- package/build/{policy-CgS4y94U.js → policy-G-Y3Meku.js} +55 -14
- package/build/policy-G-Y3Meku.js.map +1 -0
- package/build/{ports-CZLzYK5d.d.ts → ports-D-Anj51B.d.ts} +3 -3
- package/build/{queue-BjiGodqh.d.ts → queue-rfmKMwju.d.ts} +4 -4
- package/build/rabbitmq.d.ts +4 -4
- package/build/redis.d.ts +10 -7
- package/build/redis.js +17 -8
- package/build/redis.js.map +1 -1
- package/build/{store-Cwuepb-z.d.ts → store-1CsNoJ8O.d.ts} +24 -13
- package/build/testing.d.ts +7 -20
- package/build/testing.js +1 -51
- package/build/testing.js.map +1 -1
- package/build/websocket.d.ts +3 -3
- package/package.json +3 -3
- package/build/clock-mVqhXD0b.d.ts +0 -37
- package/build/clock.js.map +0 -1
- package/build/limiter-CmC4vCjk.js.map +0 -1
- package/build/policy-CgS4y94U.js.map +0 -1
package/README.md
CHANGED
|
@@ -309,7 +309,7 @@ const findings = lint(svc.describe(), scenario, DRAIN_RULES);
|
|
|
309
309
|
|
|
310
310
|
## The timers
|
|
311
311
|
|
|
312
|
-
The clock, the heartbeat and the backoff have their own entries. Each entry imports no `node:` module
|
|
312
|
+
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.
|
|
313
313
|
|
|
314
314
|
| Entry | Exports |
|
|
315
315
|
| --- | --- |
|
|
@@ -318,6 +318,7 @@ The clock, the heartbeat and the backoff have their own entries. Each entry impo
|
|
|
318
318
|
| `@mark1russell7/service/backoff` | `backoffDelay`, `backoffBand`, `backoffProblems` |
|
|
319
319
|
|
|
320
320
|
- **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 that clock. Each cancel also has `unref`, for one timer.
|
|
321
|
+
- **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.
|
|
321
322
|
- **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`.
|
|
322
323
|
- **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.
|
|
323
324
|
- **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.
|
|
@@ -407,9 +408,10 @@ A keyed limiter gives each key its own limit, for example each tenant or each pr
|
|
|
407
408
|
| Export | Function |
|
|
408
409
|
| --- | --- |
|
|
409
410
|
| `svc.limiter(name, spec)` | The declaration of a limiter, as data. `describe()` shows it in `limiters`. |
|
|
410
|
-
| `keyedLimiter(name, spec, store)` | The runtime of a limiter: `take(key)` gives a `Decision`, and `tryTakeSync(key)` gives it at once on a memory store |
|
|
411
|
+
| `keyedLimiter(name, spec, store)` | The runtime of a limiter: `take(key, units?)` gives a `Decision`, and `tryTakeSync(key, units?)` gives it at once on a memory store |
|
|
411
412
|
| `memoryStore(clock)` | The store of one replica, on the injected monotonic clock |
|
|
412
|
-
| `decide(rule, state, now)`, `limitRule(policy)`, `freeAt(rule, state)` | The arithmetic of each store, for a store of your own |
|
|
413
|
+
| `decide(rule, state, now, units?)`, `limitRule(policy)`, `freeAt(rule, state)` | The arithmetic of each store, for a store of your own |
|
|
414
|
+
| `capacityOf(rule)`, `overCapacity(rule, units)`, `unitsOf(units)` | The most units of one take, its refusal, and the check of the units |
|
|
413
415
|
| `idleSpan(policy)`, `longestRetryAfter(policy)`, `retryAfterSeconds(retryAfter)` | The times of a policy, and `Retry-After` in whole seconds |
|
|
414
416
|
| `limiterProblems(name, spec)` | The problems of a spec that `describe()` and `keyedLimiter` refuse |
|
|
415
417
|
| `LIMITER_RULES` | The rules O29 and O30 of the law, as data. Their identifiers are provisional. |
|
|
@@ -420,7 +422,10 @@ A keyed limiter gives each key its own limit, for example each tenant or each pr
|
|
|
420
422
|
- **The key.** `key` tells what the key of each take is, for example `tenant`. The caller gives each key to `take(key)`.
|
|
421
423
|
- **A token bucket.** `{ type: "token-bucket", rate, burst }` gives a key `burst` takes at once, and then `rate` takes in each unit of time. The rate is a count for each unit of time, for example `count/s` or `count/min`.
|
|
422
424
|
- **A sliding window.** `{ type: "sliding-window", limit, window }` gives a key at most `limit` takes in each window. Each take counts for one window from its time.
|
|
423
|
-
- **The decision.** `take(key)` gives `{ allowed: true, remaining }` or
|
|
425
|
+
- **The decision.** `take(key)` gives `{ allowed: true, remaining }` or a refusal. The type of a refusal is a union on its `cause`, thus the compiler checks each branch.
|
|
426
|
+
- **A wait refusal.** `{ allowed: false, cause, retryAfter }` has the cause `limit`, `cap` or `store`. `retryAfter` is a `Quantity` above zero: the time until the limiter lets the same take in.
|
|
427
|
+
- **The units of a take.** `take(key, units)` takes `units` units in one atomic step, or none. The units are a whole number of 1 or more, and 1 when absent. Other units throw a `RangeError`.
|
|
428
|
+
- **The capacity.** The capacity of a policy is its `burst` or its `limit` (`capacityOf`). No wait lets in a take of more units, thus the limiter refuses it before the store with `{ allowed: false, cause: "capacity", units, capacity }`. Split such work into parts of at most the capacity.
|
|
424
429
|
- **A take with no promise.** `tryTakeSync(key)` gives the same `Decision` at once. `keyedLimiter` on a `memoryStore` gives a `LocalLimiter`, whose type has it. On `KeyedLimiter`, it is optional.
|
|
425
430
|
- **Only a local store.** `tryTakeSync` throws for a shared store, before the take. It also throws for a local store whose take gives a promise. That take still counts, thus use `take()` with such a store.
|
|
426
431
|
- **The clock.** `memoryStore(clock)` reads time only through its clock. Thus a step of the wall clock moves no count, and a fake clock gives exact decisions in a test.
|
|
@@ -435,7 +440,7 @@ A keyed limiter gives each key its own limit, for example each tenant or each pr
|
|
|
435
440
|
- **A bound on the keys.** `evict.maxKeys` is the most keys that the store holds for the limiter. `describe()` refuses a count without a bound.
|
|
436
441
|
- **The cost of a new key at the cap.** At the cap, the store refuses a new key with the cause `cap`. Its `retryAfter` is at most the time until the earliest held key is free. That time is at most `idleSpan`, and a held key keeps its count.
|
|
437
442
|
- **The cost of the bound.** A sweep at the cap reads each key one time. It occurs only when a held key can be free. A token bucket keeps one number for each key, thus at most `maxKeys` numbers. A sliding window keeps the time of each take in its window: at most `maxKeys × limit` times.
|
|
438
|
-
- **The HTTP edge.** `retryAfterSeconds(retryAfter)` gives whole seconds, rounded up, for `Retry-After` (RFC 9110). `limitedResponse(refused)` of `@mark1russell7/service/http` gives 429 with that header (RFC 6585).
|
|
443
|
+
- **The HTTP edge.** `retryAfterSeconds(retryAfter)` gives whole seconds, rounded up, for `Retry-After` (RFC 9110). `limitedResponse(refused)` of `@mark1russell7/service/http` gives 429 with that header (RFC 6585). For the cause `capacity`, it gives 413 with no `Retry-After`, and the body gives the units and the capacity.
|
|
439
444
|
- **The law.** `lint()` applies O29 and O30 (`LIMITER_RULES`) one time for each limiter. The scenario gives the values of the callers of each limiter (`scenario.limiters`).
|
|
440
445
|
- **Provisional identifiers.** The corpus of the law has the rules O01 to O28. It does not have these two rules yet, thus O29 and O30 are provisional identifiers.
|
|
441
446
|
- **O29.** The longest `Retry-After` of a limiter (`retry_after@limiter`) is at most the retry window of its caller (`client_retry_window@caller`). Its second inequality applies the same bound to a new key at the cap (`retry_after_at_cap@limiter`). Otherwise the caller stops before the limit lets its call in.
|
|
@@ -482,7 +487,7 @@ if (!decision.allowed) return limitedResponse(decision); // 429, with Retry-Afte
|
|
|
482
487
|
| `writeOutcome(res, stream, options)` | The stream of a request as a response of `node:http`, unary or a stream |
|
|
483
488
|
| `ndjson`, `sse` | The formats of a stream: NDJSON, and server-sent events |
|
|
484
489
|
| `outcomeResponse`, `endRecord`, `probeResponse`, `pathOf` | The same answers as data, for any HTTP framework or none |
|
|
485
|
-
| `limitedResponse(refused)` | The answer to a take that a keyed limiter refused: 429, with `Retry-After` in whole seconds |
|
|
490
|
+
| `limitedResponse(refused)` | The answer to a take that a keyed limiter refused: 429, with `Retry-After` in whole seconds, or 413 for the cause `capacity` |
|
|
486
491
|
|
|
487
492
|
- **The transport.** `httpTransport(server, knobs, options)` makes a server of `node:http` or `node:http2` (`EdgeServer`) a transport of the lifecycle. Give `transport.knobs` to `svc.server(name, knobs, impl)`. Thus the declaration and the law read the same knobs.
|
|
488
493
|
- **The knobs.** The transport has no defaults. `server_idle_sweep_interval` is the interval of the sweep of idle connections. `server_retry_after` goes in the `Retry-After` of each 503 of the transport.
|
|
@@ -692,7 +697,7 @@ console.log(outcome.kind);
|
|
|
692
697
|
- **The manifestations.** `meets` lists the manifestations that the client can meet, and the detectors of each, with their times from the knobs. `unwatched(meets)` lists each manifestation and situation that no detector finds.
|
|
693
698
|
- **The machine.** `REDIS_CLIENT_MACHINE` is the client as a `mark1russell7.machine/1` document. The tests replay the transitions of the client against it.
|
|
694
699
|
- **The store of a keyed limiter.** `redisLimiterStore(client, { prefix })` keeps the counts of a [keyed limiter](#the-keyed-limiter) in Redis 7, for each replica of a service. Give it to `keyedLimiter` with `{ kind: "shared", dependency, onStoreFailure }`.
|
|
695
|
-
- **One atomic step.** Each take is one `EVAL` of `LIMITER_SCRIPT`, which does the arithmetic of `decide
|
|
700
|
+
- **One atomic step.** Each take is one `EVAL` of `LIMITER_SCRIPT`, which does the arithmetic of `decide` for all the units of the take. The script reads `TIME` of the server, thus each replica gets the one clock of the store. A take over the capacity does not go to Redis.
|
|
696
701
|
- **No second send.** `EVAL` is not idempotent, thus the client does not send a take again. An error or an outcome that is not certain rejects the take of the store. `keyedLimiter` then applies `onStoreFailure`, as for each shared store.
|
|
697
702
|
- **The clock of the store.** `TIME` is the wall clock of the Redis host, not a monotonic clock. Thus a step of that clock moves the counts of each key. The replicas still share one clock.
|
|
698
703
|
- **Exact eviction in Redis.** The state of each key expires at the time that the key is free. A sorted set of each limiter bounds its busy keys to `maxKeys`, and it gives the exact `retryAfter` of a key at the cap.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as Clock } from "./clock-
|
|
2
|
-
import {
|
|
3
|
-
import { C as MessageTrigger, D as ServiceDescription, E as RepeatSignal, G as ExitTrigger, N as Timing, S as Gate, Z as ProcessTrigger, _ as CooperativeFloor, b as ExitCodes, ct as Operation, h as Check, j as Poll, v as Coupling, w as Phase, y as Dependency, z as OperationOf } from "./logger-
|
|
4
|
-
import { D as CheckFn, E as StartOptions, F as Outcome, L as Trace, S as Health, d as TransportImpl, n as HealthServer, o as PhaseWork, r as Lifecycle, s as RunOptions, t as DependencyHandle } from "./lifecycle-
|
|
1
|
+
import { n as Clock } from "./clock-DpVgpY4h.js";
|
|
2
|
+
import { l as LimiterSpec } from "./policy-CwYR95Sz.js";
|
|
3
|
+
import { C as MessageTrigger, D as ServiceDescription, E as RepeatSignal, G as ExitTrigger, N as Timing, S as Gate, Z as ProcessTrigger, _ as CooperativeFloor, b as ExitCodes, ct as Operation, h as Check, j as Poll, v as Coupling, w as Phase, y as Dependency, z as OperationOf } from "./logger-BY1RFLzq.js";
|
|
4
|
+
import { D as CheckFn, E as StartOptions, F as Outcome, L as Trace, S as Health, d as TransportImpl, n as HealthServer, o as PhaseWork, r as Lifecycle, s as RunOptions, t as DependencyHandle } from "./lifecycle-C8ffyrQ9.js";
|
|
5
5
|
import { Extent, Quantity } from "@mark1russell7/quantity";
|
|
6
6
|
//#region src/profiles.d.ts
|
|
7
7
|
/**
|
|
@@ -209,4 +209,4 @@ interface ServiceBuilder {
|
|
|
209
209
|
declare const service: (name: string) => ServiceBuilder;
|
|
210
210
|
//#endregion
|
|
211
211
|
export { WatchdogSpec as a, Profile as c, kubernetes as d, localDev as f, Watchdog as i, daemon as l, ServiceBuilder as n, watchdog as o, service as r, PodTiming as s, ControllerBuilder as t, ephemeral as u };
|
|
212
|
-
//# sourceMappingURL=builder-
|
|
212
|
+
//# sourceMappingURL=builder-BWfcgx__.d.ts.map
|
package/build/channel.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as Clock } from "./clock-
|
|
1
|
+
import { n as Clock } from "./clock-DpVgpY4h.js";
|
|
2
2
|
//#region src/channel.d.ts
|
|
3
3
|
/** This function gets a failure of the work that a function of this entry started. */
|
|
4
4
|
export type ErrorHandler = (error: unknown) => void;
|
package/build/clock.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as realClock, i as platformClock, n as Clock, r as PlatformClockOptions, t as Cancel } from "./clock-
|
|
2
|
-
export { Cancel, Clock, PlatformClockOptions, platformClock, realClock };
|
|
1
|
+
import { a as realClock, i as platformClock, n as Clock, r as PlatformClockOptions, t as Cancel } from "./clock-DpVgpY4h.js";
|
|
2
|
+
export { type Cancel, type Clock, type PlatformClockOptions, platformClock, realClock };
|
package/build/clock.js
CHANGED
|
@@ -1,38 +1 @@
|
|
|
1
|
-
|
|
2
|
-
/** This function gives the monotonic time: `performance.now()`, or `Date.now()` on a platform without `performance`. */
|
|
3
|
-
const monotonic = () => {
|
|
4
|
-
const performance = globalThis.performance;
|
|
5
|
-
return performance === void 0 ? Date.now() : performance.now();
|
|
6
|
-
};
|
|
7
|
-
/** This delay is the longest that `setTimeout` takes, in milliseconds. A longer delay starts the function after 1 ms. */
|
|
8
|
-
const LONGEST_DELAY = 2147483647;
|
|
9
|
-
/**
|
|
10
|
-
* This function makes a clock of the platform: `performance.now()` and `setTimeout`. Each cancel
|
|
11
|
-
* that it gives also has `unref`. A delay longer than `setTimeout` takes waits in steps.
|
|
12
|
-
*/
|
|
13
|
-
const platformClock = (options = {}) => ({
|
|
14
|
-
now: monotonic,
|
|
15
|
-
after(ms, run) {
|
|
16
|
-
let unrefed = options.unref === true;
|
|
17
|
-
const arm = (left) => {
|
|
18
|
-
const step = left > LONGEST_DELAY ? setTimeout(() => timer = arm(left - LONGEST_DELAY), LONGEST_DELAY) : setTimeout(run, Math.max(0, left));
|
|
19
|
-
if (unrefed) step.unref?.();
|
|
20
|
-
return step;
|
|
21
|
-
};
|
|
22
|
-
let timer = arm(ms);
|
|
23
|
-
const unref = () => {
|
|
24
|
-
unrefed = true;
|
|
25
|
-
timer.unref?.();
|
|
26
|
-
};
|
|
27
|
-
return Object.assign(() => clearTimeout(timer), { unref });
|
|
28
|
-
}
|
|
29
|
-
});
|
|
30
|
-
/**
|
|
31
|
-
* This clock reads `performance.now()` and uses `setTimeout`. Its timers do not keep a Node
|
|
32
|
-
* process alive, thus a timer that is not stopped cannot stop the exit of the process.
|
|
33
|
-
*/
|
|
34
|
-
const realClock = /* @__PURE__ */ platformClock({ unref: true });
|
|
35
|
-
//#endregion
|
|
36
|
-
export { platformClock, realClock };
|
|
37
|
-
|
|
38
|
-
//# sourceMappingURL=clock.js.map
|
|
1
|
+
export { platformClock, realClock } from "@mark1russell7/algebra/clock";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as Backoff } from "./backoff-B-jGWVDm.js";
|
|
2
|
-
import { n as Clock } from "./clock-
|
|
3
|
-
import { D as ServiceDescription, O as Step, S as Gate, ct as Operation, h as Check, j as Poll, m as Recorder, y as Dependency } from "./logger-
|
|
4
|
-
import { D as CheckFn, t as DependencyHandle } from "./lifecycle-
|
|
5
|
-
import { n as ServiceBuilder } from "./builder-
|
|
2
|
+
import { n as Clock } from "./clock-DpVgpY4h.js";
|
|
3
|
+
import { D as ServiceDescription, O as Step, S as Gate, ct as Operation, h as Check, j as Poll, m as Recorder, y as Dependency } from "./logger-BY1RFLzq.js";
|
|
4
|
+
import { D as CheckFn, t as DependencyHandle } from "./lifecycle-C8ffyrQ9.js";
|
|
5
|
+
import { n as ServiceBuilder } from "./builder-BWfcgx__.js";
|
|
6
6
|
import { Extent, Quantity } from "@mark1russell7/quantity";
|
|
7
7
|
//#region src/client/meets.d.ts
|
|
8
8
|
/** A situation is what the connection did when the failure started: a command in flight, or idle. */
|
|
@@ -231,4 +231,4 @@ declare const retryProblems: (name: string, knobs: RetryKnobs) => string[];
|
|
|
231
231
|
declare const STARTING_POLL: Poll;
|
|
232
232
|
//#endregion
|
|
233
233
|
export { MANIFESTATIONS as C, firstDetector as D, Situation as E, unwatched as O, Detector as S, Meeting as T, Sent as _, ClientKnobs as a, retryProblems as b, ClientSpec as c, Factory as d, ReadyWait as f, SendOptions as g, STARTING_POLL as h, ClientJoin as i, ClientStep as l, RetrySchedule as m, CheckOptions as n, ClientOptions as o, RetryKnobs as p, Client as r, ClientSocket as s, Attempt as t, DialFn as u, readyWait as v, Manifestation as w, retrySchedule as x, retryBackoff as y };
|
|
234
|
-
//# sourceMappingURL=core-
|
|
234
|
+
//# sourceMappingURL=core-Cuh3oSfr.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./core-
|
|
1
|
+
import "./core-Cuh3oSfr.js";
|
|
2
2
|
//#region src/client/dial.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* A judge reads the bytes that the server sent so far. It gives null for a good answer, an error for
|
|
@@ -13,4 +13,4 @@ type Judge = (received: Buffer) => Error | null | "more";
|
|
|
13
13
|
declare const statusLineJudge: (accept: (status: number, line: string) => Error | null) => Judge;
|
|
14
14
|
//#endregion
|
|
15
15
|
export { statusLineJudge as n, Judge as t };
|
|
16
|
-
//# sourceMappingURL=dial-
|
|
16
|
+
//# sourceMappingURL=dial-ZJNa6s9i.d.ts.map
|
package/build/grpc.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { ct as Operation, j as Poll } from "./logger-
|
|
2
|
-
import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, b as retryProblems, c as ClientSpec, d as Factory, f as ReadyWait, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, v as readyWait, w as Manifestation } from "./core-
|
|
3
|
-
import { t as Judge } from "./dial-
|
|
1
|
+
import { ct as Operation, j as Poll } from "./logger-BY1RFLzq.js";
|
|
2
|
+
import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, b as retryProblems, c as ClientSpec, d as Factory, f as ReadyWait, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, v as readyWait, w as Manifestation } from "./core-Cuh3oSfr.js";
|
|
3
|
+
import { t as Judge } from "./dial-ZJNa6s9i.js";
|
|
4
4
|
import { Extent, Quantity } from "@mark1russell7/quantity";
|
|
5
5
|
import { Machine } from "@mark1russell7/algebra";
|
|
6
6
|
//#region src/grpc/connection.d.ts
|
package/build/heartbeat.d.ts
CHANGED
package/build/host.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as Backoff } from "./backoff-B-jGWVDm.js";
|
|
2
|
-
import { n as Clock } from "./clock-
|
|
3
|
-
import { c as Logger, q as MessageShape } from "./logger-
|
|
4
|
-
import { a as FilePort, c as ProcessMark, d as StopSignal, f as joinPath, i as CommandResult, l as ProcessesPort, n as CommandOptions, o as HostPorts, r as CommandPort, s as NetPort, t as ChildHandle, u as SpawnRequest } from "./ports-
|
|
2
|
+
import { n as Clock } from "./clock-DpVgpY4h.js";
|
|
3
|
+
import { c as Logger, q as MessageShape } from "./logger-BY1RFLzq.js";
|
|
4
|
+
import { a as FilePort, c as ProcessMark, d as StopSignal, f as joinPath, i as CommandResult, l as ProcessesPort, n as CommandOptions, o as HostPorts, r as CommandPort, s as NetPort, t as ChildHandle, u as SpawnRequest } from "./ports-D-Anj51B.js";
|
|
5
5
|
import { Quantity } from "@mark1russell7/quantity";
|
|
6
6
|
//#region src/host/render.d.ts
|
|
7
7
|
/**
|
|
@@ -333,7 +333,9 @@ export declare const startService: (spec: ServiceSpec, ports: HostPorts) => Prom
|
|
|
333
333
|
* This function stops a service, and keeps it stopped until `startService`. It does not throw.
|
|
334
334
|
* - On Windows, it disables the task, thus its time trigger does not start it again, and ends the task.
|
|
335
335
|
* With a discovery file, it then stops the process tree of the instance. Windows has no signal that a child can catch.
|
|
336
|
-
* - On Linux,
|
|
336
|
+
* - On Linux, it disables the unit of a logon service, or the timer of a daily job, and stops it.
|
|
337
|
+
* Thus the next login or the next calendar time does not start it again. The stop sends SIGTERM,
|
|
338
|
+
* thus `run()` stops in its stages. A daily job that operates stops too.
|
|
337
339
|
*/
|
|
338
340
|
export declare const stopService: (spec: ServiceSpec, ports: HostPorts, options?: InstanceOptions) => Promise<ServiceOutcome>;
|
|
339
341
|
/**
|
package/build/host.js
CHANGED
|
@@ -305,102 +305,6 @@ const stopTree = async (pid, ports) => {
|
|
|
305
305
|
} : { kind: "absent" };
|
|
306
306
|
};
|
|
307
307
|
//#endregion
|
|
308
|
-
//#region src/host/discovery.ts
|
|
309
|
-
const isPort = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535;
|
|
310
|
-
/** This function reads a discovery record from a text. It gives the record, or the problem as a text. */
|
|
311
|
-
const parseDiscovery = (text) => {
|
|
312
|
-
let value;
|
|
313
|
-
try {
|
|
314
|
-
value = JSON.parse(text);
|
|
315
|
-
} catch (error) {
|
|
316
|
-
return `the file is not JSON: ${error instanceof Error ? error.message : String(error)}`;
|
|
317
|
-
}
|
|
318
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) return "the file is not a JSON object";
|
|
319
|
-
const { pid, startedAt, port, url, extra } = value;
|
|
320
|
-
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return "the field pid is not a process ID";
|
|
321
|
-
if (typeof startedAt !== "string" || !Number.isFinite(Date.parse(startedAt))) return "the field startedAt is not an ISO time";
|
|
322
|
-
if (port !== null && port !== void 0 && !isPort(port)) return "the field port is not a port from 1 to 65535";
|
|
323
|
-
if (url !== null && url !== void 0 && typeof url !== "string") return "the field url is not a text";
|
|
324
|
-
if (extra !== void 0 && (typeof extra !== "object" || extra === null || Array.isArray(extra))) return "the field extra is not an object";
|
|
325
|
-
return {
|
|
326
|
-
pid,
|
|
327
|
-
startedAt,
|
|
328
|
-
port: isPort(port) ? port : null,
|
|
329
|
-
url: typeof url === "string" ? url : null,
|
|
330
|
-
...extra === void 0 ? {} : { extra }
|
|
331
|
-
};
|
|
332
|
-
};
|
|
333
|
-
/** This function gives the discovery record of the process of the host, with its start time. */
|
|
334
|
-
const discoveryOf = (fields, ports) => ({
|
|
335
|
-
pid: ports.self.pid,
|
|
336
|
-
startedAt: new Date(ports.self.startedAt).toISOString(),
|
|
337
|
-
port: fields.port ?? null,
|
|
338
|
-
url: fields.url ?? null,
|
|
339
|
-
...fields.extra === void 0 ? {} : { extra: fields.extra }
|
|
340
|
-
});
|
|
341
|
-
/** This function writes a discovery file. The write replaces the file in one step, thus a reader sees the old record or the new one. */
|
|
342
|
-
const writeDiscovery = async (path, record, ports) => {
|
|
343
|
-
await ports.files.write(path, `${JSON.stringify(record, null, 2)}\n`);
|
|
344
|
-
};
|
|
345
|
-
/**
|
|
346
|
-
* This function reads a discovery file and examines its process. It does not throw: a file that is not
|
|
347
|
-
* a record, or a failed read, gives `malformed`. With `clean`, it removes a stale or malformed file.
|
|
348
|
-
*/
|
|
349
|
-
const readDiscovery = async (path, ports, options = {}) => {
|
|
350
|
-
const found = await examine(path, ports);
|
|
351
|
-
if (options.clean === true && (found.kind === "stale" || found.kind === "malformed")) try {
|
|
352
|
-
await ports.files.remove(path);
|
|
353
|
-
ports.logger?.log("info", `the host removed the ${found.kind} discovery file ${path}`, {
|
|
354
|
-
path,
|
|
355
|
-
kind: found.kind
|
|
356
|
-
});
|
|
357
|
-
} catch {}
|
|
358
|
-
return found;
|
|
359
|
-
};
|
|
360
|
-
const examine = async (path, ports) => {
|
|
361
|
-
let text;
|
|
362
|
-
try {
|
|
363
|
-
text = await ports.files.read(path);
|
|
364
|
-
} catch (error) {
|
|
365
|
-
return {
|
|
366
|
-
kind: "malformed",
|
|
367
|
-
problem: `the read failed: ${error instanceof Error ? error.message : String(error)}`
|
|
368
|
-
};
|
|
369
|
-
}
|
|
370
|
-
if (text === null) return { kind: "absent" };
|
|
371
|
-
const record = parseDiscovery(text);
|
|
372
|
-
if (typeof record === "string") return {
|
|
373
|
-
kind: "malformed",
|
|
374
|
-
problem: record
|
|
375
|
-
};
|
|
376
|
-
const mark = {
|
|
377
|
-
pid: record.pid,
|
|
378
|
-
startedAt: Date.parse(record.startedAt)
|
|
379
|
-
};
|
|
380
|
-
if (await sameProcess(mark, ports)) return {
|
|
381
|
-
kind: "running",
|
|
382
|
-
record
|
|
383
|
-
};
|
|
384
|
-
return {
|
|
385
|
-
kind: "stale",
|
|
386
|
-
record,
|
|
387
|
-
why: ports.processes.alive(record.pid) ? `the process ${record.pid} started after the record, thus it is a different process` : `the process ${record.pid} stopped`
|
|
388
|
-
};
|
|
389
|
-
};
|
|
390
|
-
/** This function removes a discovery file when it names the process `pid`, by default the process of the host. It tells if it removed the file. */
|
|
391
|
-
const removeDiscovery = async (path, ports, pid = ports.self.pid) => {
|
|
392
|
-
try {
|
|
393
|
-
const text = await ports.files.read(path);
|
|
394
|
-
if (text === null) return false;
|
|
395
|
-
const record = parseDiscovery(text);
|
|
396
|
-
if (typeof record === "string" || record.pid !== pid) return false;
|
|
397
|
-
await ports.files.remove(path);
|
|
398
|
-
return true;
|
|
399
|
-
} catch {
|
|
400
|
-
return false;
|
|
401
|
-
}
|
|
402
|
-
};
|
|
403
|
-
//#endregion
|
|
404
308
|
//#region src/host/lock.ts
|
|
405
309
|
const isMark = (value) => {
|
|
406
310
|
if (typeof value !== "object" || value === null) return false;
|
|
@@ -432,9 +336,9 @@ const lockText = (owner) => `${JSON.stringify(owner)}\n`;
|
|
|
432
336
|
const ownerAlive = async (owner, ports) => await sameProcess(owner, ports) || owner.child !== void 0 && await sameProcess(owner.child, ports);
|
|
433
337
|
const sleep = (ports, ms) => new Promise((resolve) => ports.clock.after(ms, resolve));
|
|
434
338
|
/**
|
|
435
|
-
* This function removes a
|
|
436
|
-
* `<path>.rm` for its read and its delete. Thus two processes that find
|
|
437
|
-
* remove each other's new
|
|
339
|
+
* This function removes a file only when it has this text: a lock file or a discovery file. The
|
|
340
|
+
* removal holds the removal lock `<path>.rm` for its read and its delete. Thus two processes that find
|
|
341
|
+
* the same stale file do not remove each other's new file. A removal lock whose owner stopped goes first.
|
|
438
342
|
*/
|
|
439
343
|
const removeIfSame = async (path, text, ports) => {
|
|
440
344
|
const removal = `${path}.rm`;
|
|
@@ -588,6 +492,115 @@ const held = (path, first, firstText, ports) => {
|
|
|
588
492
|
};
|
|
589
493
|
};
|
|
590
494
|
//#endregion
|
|
495
|
+
//#region src/host/discovery.ts
|
|
496
|
+
const isPort = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535;
|
|
497
|
+
/** This function reads a discovery record from a text. It gives the record, or the problem as a text. */
|
|
498
|
+
const parseDiscovery = (text) => {
|
|
499
|
+
let value;
|
|
500
|
+
try {
|
|
501
|
+
value = JSON.parse(text);
|
|
502
|
+
} catch (error) {
|
|
503
|
+
return `the file is not JSON: ${error instanceof Error ? error.message : String(error)}`;
|
|
504
|
+
}
|
|
505
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return "the file is not a JSON object";
|
|
506
|
+
const { pid, startedAt, port, url, extra } = value;
|
|
507
|
+
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return "the field pid is not a process ID";
|
|
508
|
+
if (typeof startedAt !== "string" || !Number.isFinite(Date.parse(startedAt))) return "the field startedAt is not an ISO time";
|
|
509
|
+
if (port !== null && port !== void 0 && !isPort(port)) return "the field port is not a port from 1 to 65535";
|
|
510
|
+
if (url !== null && url !== void 0 && typeof url !== "string") return "the field url is not a text";
|
|
511
|
+
if (extra !== void 0 && (typeof extra !== "object" || extra === null || Array.isArray(extra))) return "the field extra is not an object";
|
|
512
|
+
return {
|
|
513
|
+
pid,
|
|
514
|
+
startedAt,
|
|
515
|
+
port: isPort(port) ? port : null,
|
|
516
|
+
url: typeof url === "string" ? url : null,
|
|
517
|
+
...extra === void 0 ? {} : { extra }
|
|
518
|
+
};
|
|
519
|
+
};
|
|
520
|
+
/** This function gives the discovery record of the process of the host, with its start time. */
|
|
521
|
+
const discoveryOf = (fields, ports) => ({
|
|
522
|
+
pid: ports.self.pid,
|
|
523
|
+
startedAt: new Date(ports.self.startedAt).toISOString(),
|
|
524
|
+
port: fields.port ?? null,
|
|
525
|
+
url: fields.url ?? null,
|
|
526
|
+
...fields.extra === void 0 ? {} : { extra: fields.extra }
|
|
527
|
+
});
|
|
528
|
+
/** This function writes a discovery file. The write replaces the file in one step, thus a reader sees the old record or the new one. */
|
|
529
|
+
const writeDiscovery = async (path, record, ports) => {
|
|
530
|
+
await ports.files.write(path, `${JSON.stringify(record, null, 2)}\n`);
|
|
531
|
+
};
|
|
532
|
+
/**
|
|
533
|
+
* This function reads a discovery file and examines its process. It does not throw: a file that is not
|
|
534
|
+
* a record, or a failed read, gives `malformed`. With `clean`, it removes a stale or malformed file.
|
|
535
|
+
*/
|
|
536
|
+
const readDiscovery = async (path, ports, options = {}) => {
|
|
537
|
+
const { found, text } = await examine(path, ports);
|
|
538
|
+
if (options.clean === true && text !== null && (found.kind === "stale" || found.kind === "malformed")) try {
|
|
539
|
+
if (await removeIfSame(path, text, ports)) ports.logger?.log("info", `the host removed the ${found.kind} discovery file ${path}`, {
|
|
540
|
+
path,
|
|
541
|
+
kind: found.kind
|
|
542
|
+
});
|
|
543
|
+
} catch {}
|
|
544
|
+
return found;
|
|
545
|
+
};
|
|
546
|
+
const examine = async (path, ports) => {
|
|
547
|
+
let text;
|
|
548
|
+
try {
|
|
549
|
+
text = await ports.files.read(path);
|
|
550
|
+
} catch (error) {
|
|
551
|
+
return {
|
|
552
|
+
found: {
|
|
553
|
+
kind: "malformed",
|
|
554
|
+
problem: `the read failed: ${error instanceof Error ? error.message : String(error)}`
|
|
555
|
+
},
|
|
556
|
+
text: null
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
if (text === null) return {
|
|
560
|
+
found: { kind: "absent" },
|
|
561
|
+
text
|
|
562
|
+
};
|
|
563
|
+
const record = parseDiscovery(text);
|
|
564
|
+
if (typeof record === "string") return {
|
|
565
|
+
found: {
|
|
566
|
+
kind: "malformed",
|
|
567
|
+
problem: record
|
|
568
|
+
},
|
|
569
|
+
text
|
|
570
|
+
};
|
|
571
|
+
const mark = {
|
|
572
|
+
pid: record.pid,
|
|
573
|
+
startedAt: Date.parse(record.startedAt)
|
|
574
|
+
};
|
|
575
|
+
if (await sameProcess(mark, ports)) return {
|
|
576
|
+
found: {
|
|
577
|
+
kind: "running",
|
|
578
|
+
record
|
|
579
|
+
},
|
|
580
|
+
text
|
|
581
|
+
};
|
|
582
|
+
return {
|
|
583
|
+
found: {
|
|
584
|
+
kind: "stale",
|
|
585
|
+
record,
|
|
586
|
+
why: ports.processes.alive(record.pid) ? `the process ${record.pid} started after the record, thus it is a different process` : `the process ${record.pid} stopped`
|
|
587
|
+
},
|
|
588
|
+
text
|
|
589
|
+
};
|
|
590
|
+
};
|
|
591
|
+
/** This function removes a discovery file when it names the process `pid`, by default the process of the host. It tells if it removed the file. */
|
|
592
|
+
const removeDiscovery = async (path, ports, pid = ports.self.pid) => {
|
|
593
|
+
try {
|
|
594
|
+
const text = await ports.files.read(path);
|
|
595
|
+
if (text === null) return false;
|
|
596
|
+
const record = parseDiscovery(text);
|
|
597
|
+
if (typeof record === "string" || record.pid !== pid) return false;
|
|
598
|
+
return await removeIfSame(path, text, ports);
|
|
599
|
+
} catch {
|
|
600
|
+
return false;
|
|
601
|
+
}
|
|
602
|
+
};
|
|
603
|
+
//#endregion
|
|
591
604
|
//#region src/host/install.ts
|
|
592
605
|
/** This function gives the folder of the systemd user units: `$XDG_CONFIG_HOME/systemd/user`, or `~/.config/systemd/user`. */
|
|
593
606
|
const unitDir = (ports) => {
|
|
@@ -794,15 +807,18 @@ const startService = (spec, ports) => operate(spec, ports, async (run) => {
|
|
|
794
807
|
}
|
|
795
808
|
return firstFailure(await run.run("systemctl", [
|
|
796
809
|
"--user",
|
|
797
|
-
"
|
|
798
|
-
|
|
810
|
+
"enable",
|
|
811
|
+
"--now",
|
|
812
|
+
enabledUnit(spec)
|
|
799
813
|
]));
|
|
800
814
|
});
|
|
801
815
|
/**
|
|
802
816
|
* This function stops a service, and keeps it stopped until `startService`. It does not throw.
|
|
803
817
|
* - On Windows, it disables the task, thus its time trigger does not start it again, and ends the task.
|
|
804
818
|
* With a discovery file, it then stops the process tree of the instance. Windows has no signal that a child can catch.
|
|
805
|
-
* - On Linux,
|
|
819
|
+
* - On Linux, it disables the unit of a logon service, or the timer of a daily job, and stops it.
|
|
820
|
+
* Thus the next login or the next calendar time does not start it again. The stop sends SIGTERM,
|
|
821
|
+
* thus `run()` stops in its stages. A daily job that operates stops too.
|
|
806
822
|
*/
|
|
807
823
|
const stopService = (spec, ports, options = {}) => operate(spec, ports, async (run) => {
|
|
808
824
|
if (ports.platform === "win32") {
|
|
@@ -821,6 +837,13 @@ const stopService = (spec, ports, options = {}) => operate(spec, ports, async (r
|
|
|
821
837
|
await stopInstance(ports, options);
|
|
822
838
|
return null;
|
|
823
839
|
}
|
|
840
|
+
const disabled = await run.run("systemctl", [
|
|
841
|
+
"--user",
|
|
842
|
+
"disable",
|
|
843
|
+
"--now",
|
|
844
|
+
enabledUnit(spec)
|
|
845
|
+
]);
|
|
846
|
+
if (disabled.code !== 0 || spec.start === "logon") return firstFailure(disabled);
|
|
824
847
|
return firstFailure(await run.run("systemctl", [
|
|
825
848
|
"--user",
|
|
826
849
|
"stop",
|