@mark1russell7/service 0.6.1 → 0.6.3

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 (49) hide show
  1. package/README.md +114 -5
  2. package/build/{builder-BNAkpeTT.d.ts → builder-bXJqMe2p.d.ts} +3 -2
  3. package/build/{core-CWsGgr9J.d.ts → core-B1zbS4WY.d.ts} +4 -3
  4. package/build/{dial-JEJavY0U.d.ts → dial-CSGKVlZe.d.ts} +2 -2
  5. package/build/grpc.d.ts +3 -3
  6. package/build/grpc.js +1 -1
  7. package/build/host.d.ts +556 -0
  8. package/build/host.js +1738 -0
  9. package/build/host.js.map +1 -0
  10. package/build/http-client.d.ts +3 -3
  11. package/build/http-client.js +1 -1
  12. package/build/http.d.ts +17 -3
  13. package/build/http.js +53 -10
  14. package/build/http.js.map +1 -1
  15. package/build/index.d.ts +44 -6
  16. package/build/index.js +78 -158
  17. package/build/index.js.map +1 -1
  18. package/build/lifecycle-Ks9Yd5CM.d.ts +387 -0
  19. package/build/{limiter-B0849Vhp.d.ts → limiter-BoZkXIxk.d.ts} +2 -2
  20. package/build/{limiter-pkBZUp-t.js → limiter-CmC4vCjk.js} +21 -13
  21. package/build/limiter-CmC4vCjk.js.map +1 -0
  22. package/build/limiter.d.ts +3 -3
  23. package/build/limiter.js +1 -1
  24. package/build/{lifecycle-CCDLvXLF.d.ts → logger-DhFgh48y.d.ts} +25 -367
  25. package/build/{machine-DZMb_QEU.js → machine-DKWLZOqu.js} +7 -19
  26. package/build/machine-DKWLZOqu.js.map +1 -0
  27. package/build/mongodb.d.ts +3 -3
  28. package/build/mongodb.js +1 -1
  29. package/build/pg.d.ts +2 -2
  30. package/build/pg.js +1 -1
  31. package/build/ports-CZLzYK5d.d.ts +125 -0
  32. package/build/process-DG_im2zc.js +171 -0
  33. package/build/process-DG_im2zc.js.map +1 -0
  34. package/build/{queue-eLs5IruM.d.ts → queue-BjiGodqh.d.ts} +3 -2
  35. package/build/rabbitmq.d.ts +4 -4
  36. package/build/rabbitmq.js +1 -1
  37. package/build/redis.d.ts +3 -3
  38. package/build/redis.js +1 -1
  39. package/build/retrier-Bzkme_yM.js +51 -0
  40. package/build/retrier-Bzkme_yM.js.map +1 -0
  41. package/build/{store-D5HLgBnW.d.ts → store-Cwuepb-z.d.ts} +14 -3
  42. package/build/testing.d.ts +86 -3
  43. package/build/testing.js +238 -2
  44. package/build/testing.js.map +1 -1
  45. package/build/websocket.d.ts +3 -3
  46. package/build/websocket.js +1 -1
  47. package/package.json +6 -2
  48. package/build/limiter-pkBZUp-t.js.map +0 -1
  49. package/build/machine-DZMb_QEU.js.map +0 -1
package/build/index.js CHANGED
@@ -4,9 +4,11 @@ import { a as recoverSpan, i as heartbeatDetection, n as asWindow, r as failSpan
4
4
  import { n as operationProblems, t as mayReissue } from "./operation-DL5RxFds.js";
5
5
  import { a as limiterProblems, i as limitRule, n as freeAt, o as longestRetryAfter, r as idleSpan, s as retryAfterSeconds, t as decide } from "./policy-CgS4y94U.js";
6
6
  import { a as lateHolds, l as takeOutside, n as countOf, r as millisecondsOf, s as ownStream, t as boundedMillisecondsOf } from "./knobs-D2ClI68I.js";
7
+ import { a as isExitCode, c as matchesMessage, i as embeddedProcess, l as nodeProcess, n as PROCESS_TRIGGERS, o as isExitSignal, r as UNCAUGHT_ORIGINS, s as isMessageShape, t as EXIT_SIGNALS, u as processPortOf } from "./process-DG_im2zc.js";
7
8
  import { backoffBand, backoffDelay, backoffProblems } from "./backoff.js";
8
9
  import { DRAIN_RULES, O04, O09, O10, O16 } from "./rules.js";
9
- import { a as keyedLimiter, i as limiterStateOf, n as TOKEN_BUCKET_MACHINE, o as memoryStore, r as limiterMachine, t as SLIDING_WINDOW_MACHINE } from "./limiter-pkBZUp-t.js";
10
+ import { t as retrier } from "./retrier-Bzkme_yM.js";
11
+ import { a as keyedLimiter, i as limiterStateOf, n as TOKEN_BUCKET_MACHINE, o as memoryStore, r as limiterMachine, t as SLIDING_WINDOW_MACHINE } from "./limiter-CmC4vCjk.js";
10
12
  import { convertExact, convertible, quantity, rationals, valueIn } from "@mark1russell7/quantity";
11
13
  import { replay } from "@mark1russell7/algebra/replay";
12
14
  //#region src/description.ts
@@ -620,16 +622,50 @@ const LOG_LEVELS = [
620
622
  ];
621
623
  /** This function tells if `level` is at `least` or more severe. */
622
624
  const atLeast = (level, least) => LOG_LEVELS.indexOf(level) >= LOG_LEVELS.indexOf(least);
625
+ /** This function gives a value of a field that JSON can write: an error as its name, message and stack, and a bigint as text. */
626
+ const jsonValue = (_key, value) => {
627
+ if (typeof value === "bigint") return value.toString();
628
+ if (value instanceof Error) return {
629
+ name: value.name,
630
+ message: value.message,
631
+ ...value.stack === void 0 ? {} : { stack: value.stack }
632
+ };
633
+ return value;
634
+ };
635
+ /**
636
+ * This function gives one line of JSON for an entry. A field named `level` or `message` does not
637
+ * replace the level or the message. A field that JSON cannot write, for example a cycle, gives its failure as text.
638
+ */
639
+ const jsonLine = (level, message, fields) => {
640
+ const { level: _level, message: _message, ...rest } = fields;
641
+ try {
642
+ return JSON.stringify({
643
+ level,
644
+ message,
645
+ ...rest
646
+ }, jsonValue);
647
+ } catch (error) {
648
+ return JSON.stringify({
649
+ level,
650
+ message,
651
+ unwritten: error instanceof Error ? error.message : String(error)
652
+ });
653
+ }
654
+ };
623
655
  /**
624
656
  * This function makes the console logger. It writes each entry at its level or more severe to the
625
- * method of that level, with the message first and then the fields.
657
+ * method of that level. In the format `text`, it writes the message first and then the fields. In
658
+ * the format `json`, it writes one line of JSON.
626
659
  */
627
660
  const consoleLogger = (options = {}) => {
628
661
  const least = options.level ?? "info";
662
+ const format = options.format ?? "text";
663
+ if (format !== "text" && format !== "json") throw new Error(`the log format ${JSON.stringify(format)} is not "text" or "json"`);
629
664
  return { log(level, message, fields) {
630
665
  if (!atLeast(level, least)) return;
631
666
  const target = options.console ?? globalThis.console;
632
- if (Object.keys(fields).length === 0) target[level](message);
667
+ if (format === "json") target[level](jsonLine(level, message, fields));
668
+ else if (Object.keys(fields).length === 0) target[level](message);
633
669
  else target[level](message, fields);
634
670
  } };
635
671
  };
@@ -744,159 +780,6 @@ const logEvents = (logger, description) => {
744
780
  };
745
781
  };
746
782
  //#endregion
747
- //#region src/process.ts
748
- /** These are the signals that the runtime handles. */
749
- const EXIT_SIGNALS = [
750
- "SIGINT",
751
- "SIGTERM",
752
- "SIGQUIT"
753
- ];
754
- /** These are the process triggers that a declaration can opt in to. */
755
- const PROCESS_TRIGGERS = [
756
- "stdin-close",
757
- "ipc-close",
758
- "ipc-message"
759
- ];
760
- /** This function tells if a number is an exit code of a process: a whole number from 0 to 255. */
761
- const isExitCode = (code) => Number.isInteger(code) && code >= 0 && code <= 255;
762
- /** This function tells if a trigger is an exit signal. A repeat signal obeys `onRepeatSignal`. */
763
- const isExitSignal = (trigger) => EXIT_SIGNALS.includes(trigger);
764
- /** This function tells if a value is a message shape: a value of JSON, with no function and no undefined. */
765
- const isMessageShape = (value) => {
766
- if (value === null || typeof value === "string" || typeof value === "boolean") return true;
767
- if (typeof value === "number") return Number.isFinite(value);
768
- if (Array.isArray(value)) return value.every(isMessageShape);
769
- if (typeof value !== "object") return false;
770
- const prototype = Object.getPrototypeOf(value);
771
- return (prototype === Object.prototype || prototype === null) && Object.values(value).every(isMessageShape);
772
- };
773
- /** This function tells if a message of the IPC channel matches a shape. */
774
- const matchesMessage = (shape, message) => {
775
- if (shape === null || typeof shape !== "object") return Object.is(shape, message);
776
- if (Array.isArray(shape)) {
777
- const items = shape;
778
- return Array.isArray(message) && message.length === items.length && items.every((item, at) => matchesMessage(item, message[at]));
779
- }
780
- if (message === null || typeof message !== "object" || Array.isArray(message)) return false;
781
- const fields = message;
782
- return Object.entries(shape).every(([field, value]) => Object.hasOwn(fields, field) && matchesMessage(value, fields[field]));
783
- };
784
- /** This time is the interval of the timer of a hold, the most that a timer of Node accepts. */
785
- const HOLD_INTERVAL = 2147483647;
786
- /** This function adds a handler to some events of an emitter. The handler operates one time at most. */
787
- const once = (emitter, events, handler) => {
788
- let called = false;
789
- const fire = () => {
790
- if (called) return;
791
- called = true;
792
- handler();
793
- };
794
- for (const event of events) emitter.on(event, fire);
795
- return () => {
796
- for (const event of events) emitter.off(event, fire);
797
- };
798
- };
799
- /** This function gives a promise that ends when the data before it in a stream is written. */
800
- const written = (stream) => new Promise((resolve) => {
801
- if (stream === void 0 || stream.destroyed === true || stream.writable === false) {
802
- resolve();
803
- return;
804
- }
805
- try {
806
- stream.write("", () => resolve());
807
- } catch {
808
- resolve();
809
- }
810
- });
811
- /**
812
- * This function makes a process port on a host. `find` gives the host at each use, or undefined
813
- * when the platform has no process. Then the use throws.
814
- */
815
- const processPortOf = (find) => {
816
- const hostProcess = () => {
817
- const host = find();
818
- if (host === void 0) throw new Error("no process: give the runtime a process port");
819
- return host;
820
- };
821
- return {
822
- on(trigger, handler) {
823
- const host = hostProcess();
824
- if (trigger === "stdin-close") {
825
- const input = host.stdin;
826
- if (input === void 0) return () => {};
827
- if (input.readableEnded === true) {
828
- let live = true;
829
- queueMicrotask(() => {
830
- if (live) handler();
831
- });
832
- return () => {
833
- live = false;
834
- };
835
- }
836
- return once(input, ["end", "close"], handler);
837
- }
838
- if (trigger === "ipc-close") return once(host, ["disconnect"], handler);
839
- if (trigger === "ipc-message") {
840
- const receive = (message) => handler(message);
841
- host.on("message", receive);
842
- return () => {
843
- host.off("message", receive);
844
- };
845
- }
846
- host.on(trigger, handler);
847
- return () => {
848
- host.off(trigger, handler);
849
- };
850
- },
851
- async flush() {
852
- const host = hostProcess();
853
- await Promise.all([written(host.stdout), written(host.stderr)]);
854
- },
855
- hold() {
856
- hostProcess();
857
- const timer = setInterval(() => {}, HOLD_INTERVAL);
858
- let held = true;
859
- return () => {
860
- if (!held) return;
861
- held = false;
862
- clearInterval(timer);
863
- };
864
- },
865
- exit(code) {
866
- hostProcess().exit(code);
867
- }
868
- };
869
- };
870
- /** This port is the process of Node. */
871
- const nodeProcess = processPortOf(() => globalThis.process);
872
- /**
873
- * This function gives a process port for a lifecycle in a process that another part owns. That
874
- * part is a script, a test of an application, or a library entry. The port adds no handler of a signal or of
875
- * a trigger, it does not hold the process, and its `exit` only records the code. The caller stops
876
- * the lifecycle with `life.shutdown()`. A process with a service of its own gives its parts to
877
- * that service, and does not use this port.
878
- */
879
- const embeddedProcess = () => {
880
- let code = null;
881
- let resolve = () => {};
882
- return {
883
- on() {
884
- return () => {};
885
- },
886
- exit(requested) {
887
- if (code !== null) return;
888
- code = requested;
889
- resolve(requested);
890
- },
891
- get exitCode() {
892
- return code;
893
- },
894
- exited: new Promise((done) => {
895
- resolve = done;
896
- })
897
- };
898
- };
899
- //#endregion
900
783
  //#region src/routes.ts
901
784
  const NAME = /^[A-Za-z_][A-Za-z0-9_]*/;
902
785
  /** This function gives the problems of the syntax of a pattern: an empty pattern, a part without a name, or a name two times. */
@@ -1516,7 +1399,18 @@ const cooperativeAbortAt = (cap, window, floor = "half") => {
1516
1399
  const before = window.value === "infinite" ? Number.POSITIVE_INFINITY : valueIn(window, "ms");
1517
1400
  return Math.max(cap - before, floor === "none" ? 0 : cap / 2);
1518
1401
  };
1402
+ /** This function gives the problems of the option `uncaught`: an exit code that is not from 0 to 255. */
1403
+ const uncaughtProblems = (uncaught) => {
1404
+ const code = uncaught?.exitCode;
1405
+ return code === void 0 || isExitCode(code) ? [] : [`the exit code ${code} of an uncaught error is not a whole number from 0 to 255`];
1406
+ };
1519
1407
  const message = (error) => error instanceof Error ? error.message : String(error);
1408
+ /** This function gives the text of an error with its stack, when it has one. */
1409
+ const withStack = (error) => error instanceof Error && typeof error.stack === "string" && error.stack.length > 0 ? error.stack : message(error);
1410
+ const UNCAUGHT_NAMES = {
1411
+ uncaughtException: "an uncaught exception",
1412
+ unhandledRejection: "an unhandled rejection"
1413
+ };
1520
1414
  /**
1521
1415
  * This function gives the problems of a declaration that the lifecycle cannot start: a stage with
1522
1416
  * work and no declared phase. The runtime has no defaults, thus a transport without a drain phase
@@ -1631,6 +1525,31 @@ const lifecycle = (description, runtime, components, options = {}, bind = () =>
1631
1525
  if (found.as === void 0) triggered("ipc-message");
1632
1526
  else triggered(found.as, `${found.as} (a message of the IPC channel)`);
1633
1527
  };
1528
+ const uncaught = options.uncaught;
1529
+ const uncaughtCode = uncaught?.exitCode !== void 0 && isExitCode(uncaught.exitCode) ? uncaught.exitCode : 1;
1530
+ /**
1531
+ * This function receives an error that no code caught. A skipped error goes to the logger at
1532
+ * `warn`. Each other error is an error of the lifecycle, and it starts the shutdown with its code.
1533
+ */
1534
+ const caught = (error, origin) => {
1535
+ if (exitState === "exited") return;
1536
+ const name = UNCAUGHT_NAMES[origin];
1537
+ let skip = false;
1538
+ try {
1539
+ skip = uncaught?.ignore?.(error, origin) === true;
1540
+ } catch {}
1541
+ if (skip) {
1542
+ try {
1543
+ options.logger?.log("warn", `${name} was skipped: ${message(error)}`, {
1544
+ origin,
1545
+ error: withStack(error)
1546
+ });
1547
+ } catch {}
1548
+ return;
1549
+ }
1550
+ fail(`${name}: ${withStack(error)}`);
1551
+ shutdown(`${name}: ${message(error)}`, { code: uncaughtCode });
1552
+ };
1634
1553
  /**
1635
1554
  * This function does the work of one phase, until its cap. It tells if the work ended in time. When
1636
1555
  * work is left at the cap, `excuse` gives the cause of a cap that is not a failure, or null.
@@ -1802,6 +1721,7 @@ const lifecycle = (description, runtime, components, options = {}, bind = () =>
1802
1721
  bind(life);
1803
1722
  release = port.hold?.() ?? (() => {});
1804
1723
  offs = [...EXIT_SIGNALS, ...description.shutdown.triggers ?? []].map((trigger) => port.on(trigger, trigger === "ipc-message" ? received : () => triggered(trigger)));
1724
+ if (uncaught !== void 0 && port.onUncaught !== void 0) offs.push(port.onUncaught(caught));
1805
1725
  (async () => {
1806
1726
  const started = (what) => record("gate", "starting", "starting", "component.started", what);
1807
1727
  try {
@@ -2358,7 +2278,7 @@ const service = (name) => {
2358
2278
  choices,
2359
2279
  stopPollers: () => {}
2360
2280
  };
2361
- const problems = lifecycleProblems(description, components);
2281
+ const problems = [...lifecycleProblems(description, components), ...uncaughtProblems(options.uncaught)];
2362
2282
  if (problems.length > 0) throw new Error(`${name}: ${problems.join("; ")}`);
2363
2283
  const made = makeRuntime(options);
2364
2284
  started = true;
@@ -4163,6 +4083,6 @@ const MACHINES = {
4163
4083
  watchdog: WATCHDOG_MACHINE
4164
4084
  };
4165
4085
  //#endregion
4166
- export { BOUND_RULES, CLOSE_BOUND_RULE, DECLARATION_RULE, DRAIN_RULES, DRAIN_RULE_IDS, DURATION_FRACTIONS, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, FORMAT, GATE_MACHINE, LATCH_MACHINE, LAW_STATISTIC, LIMITER_RULES, LOG_LEVELS, MACHINES, NAME_RULE, O04, O09, O10, O16, PLATFORM_MARKS, POLLER_MACHINE, PROCESS_TRIGGERS, PROGRESS_RULE, SERVICE_RULES, SLIDING_WINDOW_MACHINE, STAGES, STOPS, STOP_RULE, TOKEN_BUCKET_MACHINE, UNIT_BOUND_RULE, WATCHDOG_MACHINE, WINDOW_MACHINE, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capKnob, compress, compression, compressionOf, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, drainMachine, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, lint, lintStop, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryStore, nodeProcess, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, verdictOf, watchdog, workerLoop };
4086
+ export { BOUND_RULES, CLOSE_BOUND_RULE, DECLARATION_RULE, DRAIN_RULES, DRAIN_RULE_IDS, DURATION_FRACTIONS, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, FORMAT, GATE_MACHINE, LATCH_MACHINE, LAW_STATISTIC, LIMITER_RULES, LOG_LEVELS, MACHINES, NAME_RULE, O04, O09, O10, O16, PLATFORM_MARKS, POLLER_MACHINE, PROCESS_TRIGGERS, PROGRESS_RULE, SERVICE_RULES, SLIDING_WINDOW_MACHINE, STAGES, STOPS, STOP_RULE, TOKEN_BUCKET_MACHINE, UNCAUGHT_ORIGINS, UNIT_BOUND_RULE, WATCHDOG_MACHINE, WINDOW_MACHINE, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capKnob, compress, compression, compressionOf, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, drainMachine, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, lint, lintStop, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryStore, nodeProcess, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retrier, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, verdictOf, watchdog, workerLoop };
4167
4087
 
4168
4088
  //# sourceMappingURL=index.js.map