@mark1russell7/service 0.6.6 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +14 -6
  2. package/build/{builder-bXJqMe2p.d.ts → builder-DPsy9XVN.d.ts} +4 -4
  3. package/build/{core-B1zbS4WY.d.ts → core-BkdE4pz1.d.ts} +4 -4
  4. package/build/{dial-CSGKVlZe.d.ts → dial-CyVazFF-.d.ts} +2 -2
  5. package/build/grpc.d.ts +3 -3
  6. package/build/host.d.ts +5 -3
  7. package/build/host.js +13 -3
  8. package/build/host.js.map +1 -1
  9. package/build/http-client.d.ts +3 -3
  10. package/build/http.d.ts +8 -6
  11. package/build/http.js +19 -5
  12. package/build/http.js.map +1 -1
  13. package/build/index.d.ts +26 -8
  14. package/build/index.js +45 -3
  15. package/build/index.js.map +1 -1
  16. package/build/{lifecycle-Ks9Yd5CM.d.ts → lifecycle-BuFfbY3s.d.ts} +2 -2
  17. package/build/{limiter-CmC4vCjk.js → limiter-BTgM4aXZ.js} +19 -8
  18. package/build/limiter-BTgM4aXZ.js.map +1 -0
  19. package/build/{limiter-BoZkXIxk.d.ts → limiter-CkJ_QVFj.d.ts} +3 -3
  20. package/build/limiter.d.ts +4 -4
  21. package/build/limiter.js +3 -3
  22. package/build/{logger-DhFgh48y.d.ts → logger-BY1RFLzq.d.ts} +2 -2
  23. package/build/mongodb.d.ts +3 -3
  24. package/build/pg.d.ts +2 -2
  25. package/build/{policy-G4QJ1ZZq.d.ts → policy-CwYR95Sz.d.ts} +51 -15
  26. package/build/{policy-CgS4y94U.js → policy-G-Y3Meku.js} +55 -14
  27. package/build/policy-G-Y3Meku.js.map +1 -0
  28. package/build/{ports-CZLzYK5d.d.ts → ports-D1U2EHmR.d.ts} +2 -2
  29. package/build/{queue-BjiGodqh.d.ts → queue-CDYBywuU.d.ts} +3 -3
  30. package/build/rabbitmq.d.ts +4 -4
  31. package/build/redis.d.ts +9 -6
  32. package/build/redis.js +17 -8
  33. package/build/redis.js.map +1 -1
  34. package/build/{store-Cwuepb-z.d.ts → store-KWQVA3mp.d.ts} +23 -12
  35. package/build/testing.d.ts +4 -4
  36. package/build/websocket.d.ts +3 -3
  37. package/package.json +3 -3
  38. package/build/limiter-CmC4vCjk.js.map +0 -1
  39. package/build/policy-CgS4y94U.js.map +0 -1
package/README.md CHANGED
@@ -407,9 +407,10 @@ A keyed limiter gives each key its own limit, for example each tenant or each pr
407
407
  | Export | Function |
408
408
  | --- | --- |
409
409
  | `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 |
410
+ | `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
411
  | `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 |
412
+ | `decide(rule, state, now, units?)`, `limitRule(policy)`, `freeAt(rule, state)` | The arithmetic of each store, for a store of your own |
413
+ | `capacityOf(rule)`, `overCapacity(rule, units)`, `unitsOf(units)` | The most units of one take, its refusal, and the check of the units |
413
414
  | `idleSpan(policy)`, `longestRetryAfter(policy)`, `retryAfterSeconds(retryAfter)` | The times of a policy, and `Retry-After` in whole seconds |
414
415
  | `limiterProblems(name, spec)` | The problems of a spec that `describe()` and `keyedLimiter` refuse |
415
416
  | `LIMITER_RULES` | The rules O29 and O30 of the law, as data. Their identifiers are provisional. |
@@ -420,7 +421,10 @@ A keyed limiter gives each key its own limit, for example each tenant or each pr
420
421
  - **The key.** `key` tells what the key of each take is, for example `tenant`. The caller gives each key to `take(key)`.
421
422
  - **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
423
  - **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 `{ allowed: false, retryAfter, cause }`. `retryAfter` is a `Quantity` above zero: the time until the limiter lets the same take in. The cause is `limit`, `cap` or `store`.
424
+ - **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.
425
+ - **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.
426
+ - **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`.
427
+ - **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
428
  - **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
429
  - **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
430
  - **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 +439,7 @@ A keyed limiter gives each key its own limit, for example each tenant or each pr
435
439
  - **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
440
  - **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
441
  - **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).
442
+ - **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
443
  - **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
444
  - **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
445
  - **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 +486,7 @@ if (!decision.allowed) return limitedResponse(decision); // 429, with Retry-Afte
482
486
  | `writeOutcome(res, stream, options)` | The stream of a request as a response of `node:http`, unary or a stream |
483
487
  | `ndjson`, `sse` | The formats of a stream: NDJSON, and server-sent events |
484
488
  | `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 |
489
+ | `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
490
 
487
491
  - **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
492
  - **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 +696,7 @@ console.log(outcome.kind);
692
696
  - **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
697
  - **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
698
  - **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`. The script reads `TIME` of the server, thus each replica gets the one clock of the store.
699
+ - **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
700
  - **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
701
  - **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
702
  - **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.
@@ -811,6 +815,10 @@ For the Redis client, the application also installs `ioredis@6`. For the Postgre
811
815
 
812
816
  For the gRPC client, it installs `@grpc/grpc-js@1`. The HTTP client needs no other package.
813
817
 
818
+ ### One copy of service
819
+
820
+ Service keeps state for some objects by identity, for example the late holds of each lifecycle and the mark of each HTTP answer. Each copy of the package has its own state. Thus a lifecycle of one copy and a transport of another copy lose that state with no error. `IDENTITY_TYPES` names each exported type that holds or reaches such a value. A package whose public API takes or gives one of these types declares service as a peer dependency. A test calculates the list from the sources, thus the list stays current.
821
+
814
822
  The package uses [`@mark1russell7/quantity`](https://www.npmjs.com/package/@mark1russell7/quantity) for each amount. No entry of the service loads `zod` at run time, thus `zod` is an optional peer dependency. An application that validates amounts with the schemas of `quantity` installs `zod`.
815
823
 
816
824
  ## Example
@@ -1,7 +1,7 @@
1
1
  import { n as Clock } from "./clock-mVqhXD0b.js";
2
- import { c as LimiterSpec } from "./policy-G4QJ1ZZq.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-DhFgh48y.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-Ks9Yd5CM.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-BuFfbY3s.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-bXJqMe2p.d.ts.map
212
+ //# sourceMappingURL=builder-DPsy9XVN.d.ts.map
@@ -1,8 +1,8 @@
1
1
  import { t as Backoff } from "./backoff-B-jGWVDm.js";
2
2
  import { n as Clock } from "./clock-mVqhXD0b.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-DhFgh48y.js";
4
- import { D as CheckFn, t as DependencyHandle } from "./lifecycle-Ks9Yd5CM.js";
5
- import { n as ServiceBuilder } from "./builder-bXJqMe2p.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-BuFfbY3s.js";
5
+ import { n as ServiceBuilder } from "./builder-DPsy9XVN.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-B1zbS4WY.d.ts.map
234
+ //# sourceMappingURL=core-BkdE4pz1.d.ts.map
@@ -1,4 +1,4 @@
1
- import "./core-B1zbS4WY.js";
1
+ import "./core-BkdE4pz1.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-CSGKVlZe.d.ts.map
16
+ //# sourceMappingURL=dial-CyVazFF-.d.ts.map
package/build/grpc.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { ct as Operation, j as Poll } from "./logger-DhFgh48y.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-B1zbS4WY.js";
3
- import { t as Judge } from "./dial-CSGKVlZe.js";
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-BkdE4pz1.js";
3
+ import { t as Judge } from "./dial-CyVazFF-.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/host.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as Backoff } from "./backoff-B-jGWVDm.js";
2
2
  import { n as Clock } from "./clock-mVqhXD0b.js";
3
- import { c as Logger, q as MessageShape } from "./logger-DhFgh48y.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-CZLzYK5d.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-D1U2EHmR.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, `systemctl --user stop` sends SIGTERM, thus `run()` stops in its stages.
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
@@ -794,15 +794,18 @@ const startService = (spec, ports) => operate(spec, ports, async (run) => {
794
794
  }
795
795
  return firstFailure(await run.run("systemctl", [
796
796
  "--user",
797
- "start",
798
- spec.start === "logon" ? `${spec.name}.service` : `${spec.name}.timer`
797
+ "enable",
798
+ "--now",
799
+ enabledUnit(spec)
799
800
  ]));
800
801
  });
801
802
  /**
802
803
  * This function stops a service, and keeps it stopped until `startService`. It does not throw.
803
804
  * - On Windows, it disables the task, thus its time trigger does not start it again, and ends the task.
804
805
  * 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, `systemctl --user stop` sends SIGTERM, thus `run()` stops in its stages.
806
+ * - On Linux, it disables the unit of a logon service, or the timer of a daily job, and stops it.
807
+ * Thus the next login or the next calendar time does not start it again. The stop sends SIGTERM,
808
+ * thus `run()` stops in its stages. A daily job that operates stops too.
806
809
  */
807
810
  const stopService = (spec, ports, options = {}) => operate(spec, ports, async (run) => {
808
811
  if (ports.platform === "win32") {
@@ -821,6 +824,13 @@ const stopService = (spec, ports, options = {}) => operate(spec, ports, async (r
821
824
  await stopInstance(ports, options);
822
825
  return null;
823
826
  }
827
+ const disabled = await run.run("systemctl", [
828
+ "--user",
829
+ "disable",
830
+ "--now",
831
+ enabledUnit(spec)
832
+ ]);
833
+ if (disabled.code !== 0 || spec.start === "logon") return firstFailure(disabled);
824
834
  return firstFailure(await run.run("systemctl", [
825
835
  "--user",
826
836
  "stop",