@serve.zone/witness 1.2.0 → 1.2.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/ts/index.ts CHANGED
@@ -2,10 +2,12 @@ export { Witness, type IWitnessOptions } from './classes.witness.js';
2
2
  export { witnessPairingCodeLifetime, type IWitnessIssuedPairingCode } from './classes.register.js';
3
3
  export {
4
4
  readWitnessConfig,
5
+ readWitnessObservabilityConfig,
5
6
  readWitnessServeConfig,
6
7
  witnessEnvironmentKeys,
7
8
  witnessPaths,
8
9
  type IWitnessConfig,
10
+ type IWitnessObservabilityConfig,
9
11
  type IWitnessPaths,
10
12
  type IWitnessServeConfig,
11
13
  type TWitnessEnvironment,
package/ts/plugins.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  // node native scope
2
2
  import * as crypto from 'node:crypto';
3
3
  import * as fs from 'node:fs/promises';
4
+ import * as net from 'node:net';
4
5
  import * as path from 'node:path';
5
6
  import * as util from 'node:util';
6
7
 
7
8
  export {
8
9
  crypto,
9
10
  fs,
11
+ net,
10
12
  path,
11
13
  util,
12
14
  }
@@ -32,7 +34,9 @@ export {
32
34
 
33
35
  // @serve.zone scope
34
36
  import * as servezoneInterfaces from '@serve.zone/interfaces';
37
+ import * as runtimeLifecycle from '@serve.zone/interfaces/runtime/lifecycle';
35
38
 
36
39
  export {
40
+ runtimeLifecycle,
37
41
  servezoneInterfaces,
38
42
  }
package/ts/witness.cli.ts CHANGED
@@ -5,11 +5,12 @@ import { Witness } from './classes.witness.js';
5
5
  import { enrollWitness, WITNESS_VERSION } from './witness.enroll.js';
6
6
  import {
7
7
  readWitnessConfig,
8
+ readWitnessObservabilityConfig,
8
9
  readWitnessServeConfig,
9
10
  witnessEnvironmentKeys,
10
11
  type TWitnessEnvironment,
11
12
  } from './witness.config.js';
12
- import { formatWitnessLogLine, WitnessLog, writeWitnessLogLine, type TWitnessLogSink } from './witness.log.js';
13
+ import { formatWitnessLogLine, WitnessLog, writeWitnessLogLine, type TWitnessLogSink, type TWitnessLogValue } from './witness.log.js';
13
14
 
14
15
  /** Where the CLI reads its configuration and writes its output. */
15
16
  export interface IWitnessCliIo {
@@ -20,6 +21,8 @@ export interface IWitnessCliIo {
20
21
  stderr: (textArg: string) => void;
21
22
  /** The log of `witness serve`. */
22
23
  logSink: TWitnessLogSink;
24
+ /** Optional process signal/exit target for in-process lifecycle testing. */
25
+ processTarget?: plugins.runtimeLifecycle.IProcessLifecycleProcessTarget;
23
26
  }
24
27
 
25
28
  const usage = [
@@ -32,33 +35,110 @@ const usage = [
32
35
  ` ${witnessEnvironmentKeys.dataDir}: absolute directory of the witness state (every command)`,
33
36
  ` ${witnessEnvironmentKeys.tlsCertPath}, ${witnessEnvironmentKeys.tlsKeyPath}: PEM certificate chain and key (serve)`,
34
37
  ` ${witnessEnvironmentKeys.listenHost} (default 0.0.0.0), ${witnessEnvironmentKeys.port} (default 443) (serve)`,
38
+ ` ${witnessEnvironmentKeys.observabilityHost} (default 127.0.0.1), ${witnessEnvironmentKeys.observabilityPort} (default 9443) (serve)`,
35
39
  '',
36
40
  ].join('\n');
37
41
 
38
- /** Serves until SIGINT or SIGTERM (exit 0) or until the storage engine fails (exit 1). */
42
+ const toLogFields = (metaArg: unknown): Record<string, TWitnessLogValue> => {
43
+ if (metaArg === undefined) {
44
+ return {};
45
+ }
46
+ if (metaArg instanceof Error) {
47
+ return WitnessLog.describeError(metaArg);
48
+ }
49
+ if (typeof metaArg === 'object' && metaArg !== null) {
50
+ const fields: Record<string, TWitnessLogValue> = {};
51
+ for (const [key, value] of Object.entries(metaArg as Record<string, unknown>)) {
52
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || value === null) {
53
+ fields[key] = value;
54
+ } else if (value !== undefined) {
55
+ fields[key] = String(value);
56
+ }
57
+ }
58
+ return fields;
59
+ }
60
+ return { detail: String(metaArg) };
61
+ };
62
+
63
+ /** Serves until SIGINT or SIGTERM (exit 0) or until the storage engine or fatal error fails (exit 1). */
39
64
  const serve = async (argsArg: string[], ioArg: IWitnessCliIo): Promise<number> => {
40
65
  plugins.util.parseArgs({ args: argsArg, options: {}, strict: true, allowPositionals: false });
41
66
  const config = readWitnessServeConfig(ioArg.env);
67
+ const observabilityConfig = readWitnessObservabilityConfig(ioArg.env);
42
68
  // The storage logs its own failure; serve only ends on it.
43
69
  let reportStorageFailure: () => void = () => undefined;
44
70
  const storageFailure = new Promise<'storage-failed'>((resolveArg) => {
45
71
  reportStorageFailure = () => resolveArg('storage-failed');
46
72
  });
47
- const witness = new Witness({ ...config, logSink: ioArg.logSink, onStorageFailure: () => reportStorageFailure() });
48
- let onSignal: () => void = () => undefined;
49
- const signal = new Promise<'signal'>((resolveArg) => {
50
- onSignal = () => resolveArg('signal');
73
+ let resolveLifecycleShutdown: (outcomeArg: 'signal' | 'fatal') => void = () => undefined;
74
+ const lifecycleShutdown = new Promise<'signal' | 'fatal'>((resolveArg) => {
75
+ resolveLifecycleShutdown = (outcomeArg) => resolveArg(outcomeArg);
76
+ });
77
+
78
+ let lifecycle: plugins.runtimeLifecycle.IProcessLifecycleHandle | null = null;
79
+ const witness = new Witness({
80
+ ...config,
81
+ ...observabilityConfig,
82
+ logSink: ioArg.logSink,
83
+ isShuttingDown: () => Boolean(lifecycle?.isShuttingDown()),
84
+ onStorageFailure: () => reportStorageFailure(),
85
+ });
86
+ const lifecycleLog = new WitnessLog(ioArg.logSink);
87
+ lifecycle = plugins.runtimeLifecycle.registerProcessLifecycle({
88
+ serviceName: 'witness',
89
+ shutdownTimeoutMs: 25_000,
90
+ fatalShutdownTimeoutMs: 5_000,
91
+ processTarget: ioArg.processTarget,
92
+ logger: {
93
+ log: (levelArg, messageArg, metaArg) => {
94
+ lifecycleLog.write(levelArg, 'process-lifecycle', {
95
+ message: messageArg,
96
+ ...toLogFields(metaArg),
97
+ });
98
+ },
99
+ },
100
+ onShutdown: async (reasonArg) => {
101
+ try {
102
+ await witness.stop();
103
+ } finally {
104
+ queueMicrotask(() => {
105
+ resolveLifecycleShutdown(reasonArg === 'fatal' ? 'fatal' : 'signal');
106
+ });
107
+ }
108
+ },
51
109
  });
52
- process.once('SIGINT', onSignal);
53
- process.once('SIGTERM', onSignal);
110
+
111
+ let lifecycleTriggered = false;
54
112
  try {
55
- await witness.start();
56
- const outcome = await Promise.race([signal, storageFailure]);
57
- return outcome === 'signal' ? 0 : 1;
113
+ if (!lifecycle.signal.aborted) {
114
+ try {
115
+ await witness.start();
116
+ } catch (error) {
117
+ if (!lifecycle.isShuttingDown()) {
118
+ throw error;
119
+ }
120
+ }
121
+ }
122
+ if (lifecycle.isShuttingDown()) {
123
+ lifecycleTriggered = true;
124
+ const outcome = await lifecycleShutdown;
125
+ return outcome === 'fatal' ? 1 : 0;
126
+ }
127
+ const outcome = await Promise.race([lifecycleShutdown, storageFailure]);
128
+ if (outcome === 'signal') {
129
+ lifecycleTriggered = true;
130
+ return 0;
131
+ }
132
+ if (outcome === 'fatal') {
133
+ lifecycleTriggered = true;
134
+ return 1;
135
+ }
136
+ return 1;
58
137
  } finally {
59
- process.off('SIGINT', onSignal);
60
- process.off('SIGTERM', onSignal);
61
138
  await witness.stop();
139
+ if (!lifecycleTriggered) {
140
+ lifecycle.dispose();
141
+ }
62
142
  }
63
143
  };
64
144
 
@@ -15,6 +15,10 @@ export const witnessEnvironmentKeys = Object.freeze({
15
15
  listenHost: 'WITNESS_LISTEN_HOST',
16
16
  /** TCP port of the listener; default 443. */
17
17
  port: 'WITNESS_PORT',
18
+ /** Loopback interface address for `/livez`, `/readyz`, `/metrics`; default `127.0.0.1`. */
19
+ observabilityHost: 'WITNESS_OBSERVABILITY_HOST',
20
+ /** Loopback TCP port for `/livez`, `/readyz`, `/metrics`; default 9443. */
21
+ observabilityPort: 'WITNESS_OBSERVABILITY_PORT',
18
22
  } as const);
19
23
 
20
24
  /** What every witness command needs: where the witness keeps its state. */
@@ -32,6 +36,13 @@ export interface IWitnessServeConfig extends IWitnessConfig {
32
36
  port: number;
33
37
  }
34
38
 
39
+ /** Loopback HTTP observability listener configuration for `witness serve`. */
40
+ export interface IWitnessObservabilityConfig {
41
+ observabilityHost: string;
42
+ /** 0 to 65535; default 9443. */
43
+ observabilityPort: number;
44
+ }
45
+
35
46
  /** The paths below `dataDir`. */
36
47
  export interface IWitnessPaths {
37
48
  /** The NoSQLDB storage root; NoSQLDB creates it accessible to its owner alone. */
@@ -105,3 +116,21 @@ export const readWitnessServeConfig = (environmentArg: TWitnessEnvironment): IWi
105
116
  port: Number(portValue),
106
117
  };
107
118
  };
119
+
120
+ /** Reads the loopback observability listener configuration of `witness serve`. */
121
+ export const readWitnessObservabilityConfig = (
122
+ environmentArg: TWitnessEnvironment,
123
+ ): IWitnessObservabilityConfig => {
124
+ const hostValue = readValue(environmentArg, witnessEnvironmentKeys.observabilityHost) ?? '127.0.0.1';
125
+ if (hostValue !== '127.0.0.1' && hostValue !== '::1') {
126
+ throw new Error(`${witnessEnvironmentKeys.observabilityHost} must be '127.0.0.1' or '::1'.`);
127
+ }
128
+ const portValue = readValue(environmentArg, witnessEnvironmentKeys.observabilityPort) ?? '9443';
129
+ if (!/^(?:0|[1-9][0-9]{0,4})$/.test(portValue) || Number(portValue) > 65535) {
130
+ throw new Error(`${witnessEnvironmentKeys.observabilityPort} must be a port from 0 to 65535.`);
131
+ }
132
+ return {
133
+ observabilityHost: hostValue,
134
+ observabilityPort: Number(portValue),
135
+ };
136
+ };