@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.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.
- package/CHANGELOG.md +107 -0
- package/README.md +333 -9
- package/dist/aim-CTp-kJW2.d.ts +139 -0
- package/dist/aim.d.ts +1 -116
- package/dist/alias-dhhr08Ei.d.ts +88 -0
- package/dist/alias.d.ts +2 -73
- package/dist/api-miiso81x.d.ts +77 -0
- package/dist/api.d.ts +1 -62
- package/dist/auth-2-jfgiHn.d.ts +34 -0
- package/dist/auth.d.ts +1 -26
- package/dist/cli-DLygZLi9.d.ts +450 -0
- package/dist/cli.d.ts +6 -309
- package/dist/cli.js +192 -63
- package/dist/config-BUY7_W2n.d.ts +103 -0
- package/dist/config.d.ts +1 -97
- package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
- package/dist/errcorrect.d.ts +1 -37
- package/dist/error-DISJKeDu.d.ts +144 -0
- package/dist/id/index.d.ts +2 -83
- package/dist/index-Bc5c7Ty5.d.ts +328 -0
- package/dist/index-C3Zw4wDJ.d.ts +359 -0
- package/dist/index-MLrRDvEG.d.ts +1073 -0
- package/dist/index-QSffbLnj.d.ts +94 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +6794 -0
- package/dist/llm-B5XUWH8T.d.ts +231 -0
- package/dist/llm.d.ts +1 -188
- package/dist/mcp/index.d.ts +2 -0
- package/dist/mcp/index.js +1453 -0
- package/dist/netpolicy-asvCfwi8.d.ts +138 -0
- package/dist/netpolicy.d.ts +1 -0
- package/dist/netpolicy.js +118 -0
- package/dist/output-4aXs91GY.d.ts +396 -0
- package/dist/output.d.ts +3 -213
- package/dist/output.js +567 -43
- package/dist/progress-CAzyxeWl.d.ts +38 -0
- package/dist/progress.d.ts +1 -30
- package/dist/provenance-SMFHm5gx.d.ts +30 -0
- package/dist/provenance.d.ts +1 -24
- package/dist/routellm-PGSt2D1y.d.ts +75 -0
- package/dist/routellm.d.ts +2 -64
- package/dist/rpc-D5xLEf8V.d.ts +32 -0
- package/dist/rpc.d.ts +2 -25
- package/dist/safety-CUaYEjZc.d.ts +30 -0
- package/dist/safety.d.ts +1 -24
- package/dist/scope-BrhYB4ij.d.ts +141 -0
- package/dist/scope.d.ts +1 -121
- package/dist/serve-DE-jscpb.d.ts +646 -0
- package/dist/serve.d.ts +3 -0
- package/dist/serve.js +1019 -0
- package/dist/stream-CrjeCp0M.d.ts +44 -0
- package/dist/stream.d.ts +1 -35
- package/dist/telemetry/index.d.ts +1 -315
- package/dist/telemetry/index.js +12 -1
- package/dist/tui/index.d.ts +5 -298
- package/dist/tui/index.js +3 -10
- package/dist/upgrade-p_zh3pvV.d.ts +102 -0
- package/dist/upgrade.d.ts +1 -95
- package/dist/xdg-DB7Shoib.d.ts +179 -0
- package/dist/xdg.d.ts +1 -169
- package/package.json +26 -3
- package/src/cli.offline.test.ts +93 -0
- package/src/cli.parity.test.ts +192 -0
- package/src/cli.ts +112 -12
- package/src/index.test.ts +58 -0
- package/src/index.ts +37 -0
- package/src/log.parity.test.ts +105 -0
- package/src/log.ts +64 -13
- package/src/mcp/bridge.test.ts +150 -0
- package/src/mcp/bridge.ts +246 -0
- package/src/mcp/conformance.test.ts +336 -0
- package/src/mcp/dispatch.ts +313 -0
- package/src/mcp/index.ts +138 -0
- package/src/mcp/legacy.ts +314 -0
- package/src/mcp/mcp.test.ts +697 -0
- package/src/mcp/modern-confirm.test.ts +520 -0
- package/src/mcp/modern-confirm.ts +452 -0
- package/src/mcp/modern.ts +723 -0
- package/src/mcp/tasks.ts +82 -0
- package/src/mcp/testtree.ts +250 -0
- package/src/mcp/types.ts +504 -0
- package/src/netpolicy.test.ts +202 -0
- package/src/netpolicy.ts +231 -0
- package/src/output/dispatch.ts +10 -2
- package/src/output/error.ts +316 -0
- package/src/output/formatter.ts +29 -5
- package/src/output/formatters/csv.ts +48 -12
- package/src/output/formatters/json.ts +4 -25
- package/src/output/formatters/project.ts +34 -0
- package/src/output/formatters/table.ts +8 -6
- package/src/output/formatters/text.ts +7 -3
- package/src/output/formatters/yaml.ts +5 -22
- package/src/output/projection.test.ts +298 -0
- package/src/output/projection.ts +33 -59
- package/src/output/template.ts +11 -21
- package/src/output.surface.test.ts +41 -0
- package/src/output.ts +41 -3
- package/src/serve.test.ts +1257 -0
- package/src/serve.ts +1665 -0
- package/src/telemetry/client.test.ts +31 -0
- package/src/telemetry/client.ts +7 -1
- package/src/telemetry/offline.test.ts +64 -0
- package/src/tui/parity.test.ts +120 -31
- package/src/tui/parity.ts +58 -7
- package/test/output/csv.test.ts +164 -0
- package/test/output/error.test.ts +246 -0
- package/src/tui/parity.json +0 -74
package/dist/serve.js
ADDED
|
@@ -0,0 +1,1019 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/serve.ts
|
|
31
|
+
var serve_exports = {};
|
|
32
|
+
__export(serve_exports, {
|
|
33
|
+
ACTION_FAILED: () => ACTION_FAILED,
|
|
34
|
+
ACTION_READY_REPORTED: () => ACTION_READY_REPORTED,
|
|
35
|
+
ACTION_STARTED: () => ACTION_STARTED,
|
|
36
|
+
ACTION_STOPPED: () => ACTION_STOPPED,
|
|
37
|
+
CODE_TRANSIENT: () => CODE_TRANSIENT,
|
|
38
|
+
DEFAULT_FAILURE_POLICY: () => DEFAULT_FAILURE_POLICY,
|
|
39
|
+
DEFAULT_READY_TIMEOUT_MS: () => DEFAULT_READY_TIMEOUT_MS,
|
|
40
|
+
DEFAULT_SHUTDOWN_TIMEOUT_MS: () => DEFAULT_SHUTDOWN_TIMEOUT_MS,
|
|
41
|
+
DEFAULT_STOP_TIMEOUT_MS: () => DEFAULT_STOP_TIMEOUT_MS,
|
|
42
|
+
DEFAULT_TOPIC_PREFIX: () => DEFAULT_TOPIC_PREFIX,
|
|
43
|
+
LoopKeepAlive: () => LoopKeepAlive,
|
|
44
|
+
NAME_PATTERN: () => NAME_PATTERN,
|
|
45
|
+
OBJECT_SERVICE: () => OBJECT_SERVICE,
|
|
46
|
+
OBJECT_SUPERVISOR: () => OBJECT_SUPERVISOR,
|
|
47
|
+
RESERVED_NAMES: () => RESERVED_NAMES,
|
|
48
|
+
SHUTDOWN_SIGNALS: () => SHUTDOWN_SIGNALS,
|
|
49
|
+
ServiceRegistrationError: () => ServiceRegistrationError,
|
|
50
|
+
ServiceRegistry: () => ServiceRegistry,
|
|
51
|
+
Supervisor: () => Supervisor,
|
|
52
|
+
applyEnableDisable: () => applyEnableDisable,
|
|
53
|
+
applyTimeoutOverrides: () => applyTimeoutOverrides,
|
|
54
|
+
codeFor: () => codeFor,
|
|
55
|
+
defaultTopics: () => defaultTopics,
|
|
56
|
+
exitCodeFor: () => exitCodeFor,
|
|
57
|
+
isFailure: () => isFailure,
|
|
58
|
+
isFailurePolicy: () => isFailurePolicy,
|
|
59
|
+
isReservedName: () => isReservedName,
|
|
60
|
+
parseDurationMs: () => parseDurationMs,
|
|
61
|
+
registerServe: () => registerServe,
|
|
62
|
+
resolve: () => resolve,
|
|
63
|
+
signalController: () => signalController,
|
|
64
|
+
startOrder: () => startOrder,
|
|
65
|
+
validateName: () => validateName,
|
|
66
|
+
worstOutcome: () => worstOutcome
|
|
67
|
+
});
|
|
68
|
+
module.exports = __toCommonJS(serve_exports);
|
|
69
|
+
|
|
70
|
+
// src/output/error.ts
|
|
71
|
+
var yaml = __toESM(require("js-yaml"));
|
|
72
|
+
var TRANSIENCE_PERMANENT = "permanent";
|
|
73
|
+
var CODE_OK = "OK";
|
|
74
|
+
var CODE_GENERIC = "GENERIC";
|
|
75
|
+
var CODE_USAGE = "USAGE";
|
|
76
|
+
var CODE_NOT_FOUND = "NOT_FOUND";
|
|
77
|
+
var CODE_UNAUTHORIZED = "UNAUTHORIZED";
|
|
78
|
+
var CODE_TRANSIENT = "TRANSIENT";
|
|
79
|
+
function notFoundError(message) {
|
|
80
|
+
return {
|
|
81
|
+
code: CODE_NOT_FOUND,
|
|
82
|
+
message,
|
|
83
|
+
exit_code: 3,
|
|
84
|
+
transience: TRANSIENCE_PERMANENT
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function unauthorizedError(message) {
|
|
88
|
+
return {
|
|
89
|
+
code: CODE_UNAUTHORIZED,
|
|
90
|
+
message,
|
|
91
|
+
exit_code: 5,
|
|
92
|
+
transience: TRANSIENCE_PERMANENT
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function usageError(message) {
|
|
96
|
+
return {
|
|
97
|
+
code: CODE_USAGE,
|
|
98
|
+
message,
|
|
99
|
+
exit_code: 2,
|
|
100
|
+
transience: TRANSIENCE_PERMANENT
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// src/serve.ts
|
|
105
|
+
var NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
106
|
+
var RESERVED_NAMES = ["all", "none", "list"];
|
|
107
|
+
function isReservedName(name) {
|
|
108
|
+
return RESERVED_NAMES.includes(name);
|
|
109
|
+
}
|
|
110
|
+
function validateName(name) {
|
|
111
|
+
if (name === "") return "serve: service name is empty";
|
|
112
|
+
if (!NAME_PATTERN.test(name)) {
|
|
113
|
+
return `serve: service name "${name}" must be lowercase letters, digits, or hyphens, starting with a letter`;
|
|
114
|
+
}
|
|
115
|
+
if (isReservedName(name)) return `serve: service name "${name}" is reserved`;
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
var ServiceRegistrationError = class extends Error {
|
|
119
|
+
constructor(message) {
|
|
120
|
+
super(message);
|
|
121
|
+
this.name = "ServiceRegistrationError";
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
var ServiceRegistry = class {
|
|
125
|
+
constructor() {
|
|
126
|
+
this.byName = /* @__PURE__ */ new Map();
|
|
127
|
+
this.order = [];
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Adds `svc` under its name.
|
|
131
|
+
*
|
|
132
|
+
* Throws on an invalid name and on a duplicate. An adopter
|
|
133
|
+
* deliberately replacing a kit-shipped service calls
|
|
134
|
+
* {@link ServiceRegistry.override} instead — the documented escape
|
|
135
|
+
* hatch, and the only path that accepts a duplicate name.
|
|
136
|
+
*/
|
|
137
|
+
register(svc) {
|
|
138
|
+
const invalid = validateName(svc.name);
|
|
139
|
+
if (invalid) throw new ServiceRegistrationError(invalid);
|
|
140
|
+
if (this.byName.has(svc.name)) {
|
|
141
|
+
throw new ServiceRegistrationError(
|
|
142
|
+
`serve: service "${svc.name}" already registered (use override to replace)`
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
this.byName.set(svc.name, svc);
|
|
146
|
+
this.order.push(svc.name);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Registers `svc`, replacing any service already under its name and
|
|
150
|
+
* keeping that name's original position in {@link list}.
|
|
151
|
+
*
|
|
152
|
+
* Still throws on an invalid name: override lifts the collision
|
|
153
|
+
* rule, not the grammar.
|
|
154
|
+
*/
|
|
155
|
+
override(svc) {
|
|
156
|
+
const invalid = validateName(svc.name);
|
|
157
|
+
if (invalid) throw new ServiceRegistrationError(invalid);
|
|
158
|
+
if (!this.byName.has(svc.name)) this.order.push(svc.name);
|
|
159
|
+
this.byName.set(svc.name, svc);
|
|
160
|
+
}
|
|
161
|
+
/** The service registered under `name`, if any. */
|
|
162
|
+
lookup(name) {
|
|
163
|
+
return this.byName.get(name);
|
|
164
|
+
}
|
|
165
|
+
/** Every registered identifier, in registration order. */
|
|
166
|
+
names() {
|
|
167
|
+
return [...this.order];
|
|
168
|
+
}
|
|
169
|
+
/** Every registered service, in registration order. */
|
|
170
|
+
list() {
|
|
171
|
+
return this.order.map((n) => this.byName.get(n));
|
|
172
|
+
}
|
|
173
|
+
/** Number of registered services. */
|
|
174
|
+
get size() {
|
|
175
|
+
return this.byName.size;
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
var DEFAULT_READY_TIMEOUT_MS = 3e4;
|
|
179
|
+
var DEFAULT_STOP_TIMEOUT_MS = 3e4;
|
|
180
|
+
var DEFAULT_SHUTDOWN_TIMEOUT_MS = 6e4;
|
|
181
|
+
var DEFAULT_FAILURE_POLICY = "fail-fast";
|
|
182
|
+
function isFailurePolicy(p) {
|
|
183
|
+
return p === "fail-fast" || p === "isolate";
|
|
184
|
+
}
|
|
185
|
+
var EXIT_TABLE = {
|
|
186
|
+
"clean-stop": { code: CODE_OK, exit: 0 },
|
|
187
|
+
"invalid-selection": { code: CODE_USAGE, exit: 2 },
|
|
188
|
+
"config-invalid": { code: CODE_USAGE, exit: 2 },
|
|
189
|
+
"no-services": { code: CODE_USAGE, exit: 2 },
|
|
190
|
+
"unknown-service": { code: CODE_NOT_FOUND, exit: 3 },
|
|
191
|
+
"policy-denied": { code: CODE_UNAUTHORIZED, exit: 5 },
|
|
192
|
+
"start-failed": { code: CODE_GENERIC, exit: 1 },
|
|
193
|
+
"runtime-crash": { code: CODE_GENERIC, exit: 1 },
|
|
194
|
+
"shutdown-timeout": { code: CODE_GENERIC, exit: 1 }
|
|
195
|
+
};
|
|
196
|
+
function exitCodeFor(o) {
|
|
197
|
+
return EXIT_TABLE[o]?.exit ?? 1;
|
|
198
|
+
}
|
|
199
|
+
function codeFor(o) {
|
|
200
|
+
return EXIT_TABLE[o]?.code ?? CODE_GENERIC;
|
|
201
|
+
}
|
|
202
|
+
function isFailure(o) {
|
|
203
|
+
return exitCodeFor(o) !== 0;
|
|
204
|
+
}
|
|
205
|
+
function worstOutcome(observed) {
|
|
206
|
+
let worst = "clean-stop";
|
|
207
|
+
for (const o of observed) {
|
|
208
|
+
if (isFailure(o) && !isFailure(worst)) worst = o;
|
|
209
|
+
}
|
|
210
|
+
return worst;
|
|
211
|
+
}
|
|
212
|
+
function resolve(registry, req) {
|
|
213
|
+
const base = { selected: [], explicit: false, skipped: [] };
|
|
214
|
+
if (req.args.length > 1) {
|
|
215
|
+
return {
|
|
216
|
+
...base,
|
|
217
|
+
outcome: "invalid-selection",
|
|
218
|
+
error: usageError(
|
|
219
|
+
`serve accepts at most one service name, got ${req.args.length}`
|
|
220
|
+
)
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
if (req.args.length === 1) {
|
|
224
|
+
return resolveExplicit(registry, req, req.args[0]);
|
|
225
|
+
}
|
|
226
|
+
return resolveAggregate(registry, req);
|
|
227
|
+
}
|
|
228
|
+
function resolveExplicit(registry, req, name) {
|
|
229
|
+
const base = { selected: [], explicit: true, skipped: [] };
|
|
230
|
+
const svc = registry.lookup(name);
|
|
231
|
+
if (!svc) {
|
|
232
|
+
const known = registry.names();
|
|
233
|
+
const err = notFoundError(
|
|
234
|
+
`unknown service "${name}"; known: ${known.join(", ")}`
|
|
235
|
+
);
|
|
236
|
+
const fix = nearestName(name, known);
|
|
237
|
+
if (fix) err.suggested_fix = `did you mean "${fix}"?`;
|
|
238
|
+
return { ...base, outcome: "unknown-service", error: err };
|
|
239
|
+
}
|
|
240
|
+
const invalid = validateConfig(svc);
|
|
241
|
+
if (invalid) {
|
|
242
|
+
return {
|
|
243
|
+
...base,
|
|
244
|
+
outcome: "config-invalid",
|
|
245
|
+
error: usageError(`service "${name}": ${invalid}`)
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
const denied = checkPolicy(req.policy, svc);
|
|
249
|
+
if (denied) return { ...base, outcome: "policy-denied", error: denied };
|
|
250
|
+
return { selected: [name], explicit: true, skipped: [] };
|
|
251
|
+
}
|
|
252
|
+
function resolveAggregate(registry, req) {
|
|
253
|
+
const out = { selected: [], explicit: false, skipped: [] };
|
|
254
|
+
const configs = req.configs ?? {};
|
|
255
|
+
for (const name of registry.names()) {
|
|
256
|
+
const cfg = configs[name];
|
|
257
|
+
if (cfg === void 0) continue;
|
|
258
|
+
if (cfg.enabled !== true) {
|
|
259
|
+
out.skipped.push(name);
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
const svc = registry.lookup(name);
|
|
263
|
+
if (!svc) continue;
|
|
264
|
+
const invalid = validateConfig(svc);
|
|
265
|
+
if (invalid) {
|
|
266
|
+
return {
|
|
267
|
+
selected: [],
|
|
268
|
+
explicit: false,
|
|
269
|
+
skipped: out.skipped,
|
|
270
|
+
outcome: "config-invalid",
|
|
271
|
+
error: usageError(`service "${name}": ${invalid}`)
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
const denied = checkPolicy(req.policy, svc);
|
|
275
|
+
if (denied) {
|
|
276
|
+
return {
|
|
277
|
+
selected: [],
|
|
278
|
+
explicit: false,
|
|
279
|
+
skipped: out.skipped,
|
|
280
|
+
outcome: "policy-denied",
|
|
281
|
+
error: denied
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
out.selected.push(name);
|
|
285
|
+
}
|
|
286
|
+
if (out.selected.length === 0) {
|
|
287
|
+
const err = usageError(
|
|
288
|
+
"no services configured and enabled; enable one under services.* or name one explicitly"
|
|
289
|
+
);
|
|
290
|
+
err.suggested_fix = "set services.<name>.enabled: true, or run: serve <service>";
|
|
291
|
+
out.error = err;
|
|
292
|
+
out.outcome = "no-services";
|
|
293
|
+
}
|
|
294
|
+
return out;
|
|
295
|
+
}
|
|
296
|
+
function validateConfig(svc) {
|
|
297
|
+
return svc.validate ? svc.validate() : null;
|
|
298
|
+
}
|
|
299
|
+
function checkPolicy(gate, svc) {
|
|
300
|
+
if (!gate || !svc.class) return null;
|
|
301
|
+
const [sideEffect, network] = svc.class();
|
|
302
|
+
const verdict = gate.allow(sideEffect, network);
|
|
303
|
+
if (verdict.ok) return null;
|
|
304
|
+
let msg = `service "${svc.name}" denied by policy (side_effect=${sideEffect}, network=${network})`;
|
|
305
|
+
if (verdict.reason) msg += `: ${verdict.reason}`;
|
|
306
|
+
return unauthorizedError(msg);
|
|
307
|
+
}
|
|
308
|
+
function nearestName(want, known) {
|
|
309
|
+
let best = null;
|
|
310
|
+
let bestDist = -1;
|
|
311
|
+
const limit = Math.floor(want.length / 2) + 1;
|
|
312
|
+
for (const k of [...known].sort()) {
|
|
313
|
+
const d = editDistance(want, k);
|
|
314
|
+
if (d > limit) continue;
|
|
315
|
+
if (bestDist === -1 || d < bestDist) {
|
|
316
|
+
best = k;
|
|
317
|
+
bestDist = d;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return best;
|
|
321
|
+
}
|
|
322
|
+
function editDistance(a, b) {
|
|
323
|
+
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
324
|
+
let cur = new Array(b.length + 1).fill(0);
|
|
325
|
+
for (let i = 1; i <= a.length; i++) {
|
|
326
|
+
cur[0] = i;
|
|
327
|
+
for (let j = 1; j <= b.length; j++) {
|
|
328
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
329
|
+
cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
|
|
330
|
+
}
|
|
331
|
+
[prev, cur] = [cur, prev];
|
|
332
|
+
}
|
|
333
|
+
return prev[b.length];
|
|
334
|
+
}
|
|
335
|
+
function startOrder(registry, selected) {
|
|
336
|
+
const inSet = new Set(selected);
|
|
337
|
+
const deps = /* @__PURE__ */ new Map();
|
|
338
|
+
for (const name of selected) {
|
|
339
|
+
const svc = registry.lookup(name);
|
|
340
|
+
if (!svc?.dependsOn) continue;
|
|
341
|
+
const want = svc.dependsOn().filter((d) => inSet.has(d) && d !== name);
|
|
342
|
+
if (want.length > 0) deps.set(name, want);
|
|
343
|
+
}
|
|
344
|
+
const WHITE = 0, GREY = 1, BLACK = 2;
|
|
345
|
+
const mark = /* @__PURE__ */ new Map();
|
|
346
|
+
const out = [];
|
|
347
|
+
const visit = (name, path) => {
|
|
348
|
+
const state = mark.get(name) ?? WHITE;
|
|
349
|
+
if (state === BLACK) return;
|
|
350
|
+
if (state === GREY) {
|
|
351
|
+
throw new ServiceRegistrationError(
|
|
352
|
+
`serve: dependency cycle: ${[...path, name].join(" -> ")}`
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
mark.set(name, GREY);
|
|
356
|
+
for (const want of deps.get(name) ?? []) visit(want, [...path, name]);
|
|
357
|
+
mark.set(name, BLACK);
|
|
358
|
+
out.push(name);
|
|
359
|
+
};
|
|
360
|
+
for (const name of selected) visit(name, []);
|
|
361
|
+
return out;
|
|
362
|
+
}
|
|
363
|
+
var DEFAULT_TOPIC_PREFIX = "kit.serve";
|
|
364
|
+
var ACTION_STARTED = "started";
|
|
365
|
+
var ACTION_READY_REPORTED = "ready_reported";
|
|
366
|
+
var ACTION_FAILED = "failed";
|
|
367
|
+
var ACTION_STOPPED = "stopped";
|
|
368
|
+
var OBJECT_SERVICE = "service";
|
|
369
|
+
var OBJECT_SUPERVISOR = "supervisor";
|
|
370
|
+
function defaultTopics(prefix = DEFAULT_TOPIC_PREFIX) {
|
|
371
|
+
const p = prefix === "" ? DEFAULT_TOPIC_PREFIX : prefix;
|
|
372
|
+
const out = {};
|
|
373
|
+
for (const [object, action] of [
|
|
374
|
+
[OBJECT_SERVICE, ACTION_STARTED],
|
|
375
|
+
[OBJECT_SERVICE, ACTION_READY_REPORTED],
|
|
376
|
+
[OBJECT_SERVICE, ACTION_FAILED],
|
|
377
|
+
[OBJECT_SERVICE, ACTION_STOPPED],
|
|
378
|
+
[OBJECT_SUPERVISOR, ACTION_READY_REPORTED],
|
|
379
|
+
[OBJECT_SUPERVISOR, ACTION_STOPPED]
|
|
380
|
+
]) {
|
|
381
|
+
out[`${object}.${action}`] = `${p}.${object}.${action}`;
|
|
382
|
+
}
|
|
383
|
+
return out;
|
|
384
|
+
}
|
|
385
|
+
var Emitter = class {
|
|
386
|
+
constructor(topics, source, pub, log) {
|
|
387
|
+
this.topics = topics;
|
|
388
|
+
this.source = source;
|
|
389
|
+
this.pub = pub;
|
|
390
|
+
this.log = log;
|
|
391
|
+
}
|
|
392
|
+
emit(object, action, payload) {
|
|
393
|
+
this.logEvent(object, action, payload);
|
|
394
|
+
if (!this.pub) return;
|
|
395
|
+
const topic = this.topics[`${object}.${action}`];
|
|
396
|
+
if (!topic) return;
|
|
397
|
+
try {
|
|
398
|
+
this.pub.publish({ topic, source: this.source, payload });
|
|
399
|
+
} catch {
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
logEvent(object, action, payload) {
|
|
403
|
+
if (!this.log) return;
|
|
404
|
+
const kv = ["object", object, "elapsed_ms", payload.elapsed_ms];
|
|
405
|
+
if (payload.service) kv.push("service", payload.service);
|
|
406
|
+
if (payload.address) kv.push("address", payload.address);
|
|
407
|
+
if (payload.reason) kv.push("reason", payload.reason);
|
|
408
|
+
if (action === ACTION_FAILED) {
|
|
409
|
+
if (payload.error) kv.push("error", payload.error);
|
|
410
|
+
this.log.error(`serve: ${action}`, ...kv);
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
this.log.info(`serve: ${action}`, ...kv);
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
var Supervisor = class {
|
|
417
|
+
constructor(registry, opts = {}) {
|
|
418
|
+
this.registry = registry;
|
|
419
|
+
this.failurePolicy = opts.config?.failurePolicy ?? DEFAULT_FAILURE_POLICY;
|
|
420
|
+
this.shutdownTimeoutMs = opts.config?.shutdownTimeoutMs && opts.config.shutdownTimeoutMs > 0 ? opts.config.shutdownTimeoutMs : DEFAULT_SHUTDOWN_TIMEOUT_MS;
|
|
421
|
+
this.emitter = new Emitter(
|
|
422
|
+
opts.topics ?? defaultTopics(),
|
|
423
|
+
opts.eventSource ?? DEFAULT_TOPIC_PREFIX,
|
|
424
|
+
opts.publisher,
|
|
425
|
+
opts.logger
|
|
426
|
+
);
|
|
427
|
+
this.now = opts.now ?? (() => Date.now());
|
|
428
|
+
this.escalate = opts.escalate;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Starts every service in `selected`, waits for the run to end, and
|
|
432
|
+
* stops everything in reverse start order.
|
|
433
|
+
*
|
|
434
|
+
* The run ends when `signal` aborts (the clean path: a signal, or
|
|
435
|
+
* the caller's own shutdown), when a failure trips the failure
|
|
436
|
+
* policy, or when every started service has returned. Run always
|
|
437
|
+
* performs the ordered stop before returning, so a caller never has
|
|
438
|
+
* to clean up after it.
|
|
439
|
+
*
|
|
440
|
+
* `selected` is normally {@link ResolveOutcome.selected}; run does
|
|
441
|
+
* not re-resolve and does not consult enablement, because the
|
|
442
|
+
* decision the caller already made is the one to honor.
|
|
443
|
+
*/
|
|
444
|
+
async run(signal, selected, configs = {}) {
|
|
445
|
+
const st = new RunState(this.now);
|
|
446
|
+
if (selected.length === 0) {
|
|
447
|
+
const err = usageError(
|
|
448
|
+
"no services configured and enabled; enable one under services.* or name one explicitly"
|
|
449
|
+
);
|
|
450
|
+
return this.finish(st, "no-services", err);
|
|
451
|
+
}
|
|
452
|
+
const order = startOrder(this.registry, selected);
|
|
453
|
+
const runAC = new AbortController();
|
|
454
|
+
const onOuterAbort = () => runAC.abort();
|
|
455
|
+
if (signal.aborted) runAC.abort();
|
|
456
|
+
else signal.addEventListener("abort", onOuterAbort, { once: true });
|
|
457
|
+
const keepAlive = new LoopKeepAlive();
|
|
458
|
+
keepAlive.hold();
|
|
459
|
+
try {
|
|
460
|
+
const startFailed = await this.startAll(runAC, order, configs, st);
|
|
461
|
+
if (!startFailed) {
|
|
462
|
+
this.emitAggregateReady(st);
|
|
463
|
+
await this.await_(runAC, st);
|
|
464
|
+
}
|
|
465
|
+
runAC.abort();
|
|
466
|
+
await this.stopAll(st, configs);
|
|
467
|
+
return this.finish(st, worstOutcome(st.observed));
|
|
468
|
+
} finally {
|
|
469
|
+
keepAlive.release();
|
|
470
|
+
signal.removeEventListener("abort", onOuterAbort);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Starts each service in order, waiting for each to report ready
|
|
475
|
+
* (or fail, or exhaust its budget) before starting the next.
|
|
476
|
+
*
|
|
477
|
+
* Serial start is what makes `dependsOn` mean anything: a dependent
|
|
478
|
+
* must not begin acquiring before its dependency is accepting work.
|
|
479
|
+
* Returns true when a start failure short-circuits the sequence.
|
|
480
|
+
*/
|
|
481
|
+
async startAll(runAC, order, configs, st) {
|
|
482
|
+
for (const name of order) {
|
|
483
|
+
const svc = this.registry.lookup(name);
|
|
484
|
+
if (!svc) {
|
|
485
|
+
const msg = `service "${name}" disappeared from the registry`;
|
|
486
|
+
st.noteFailure(name, msg, "start-failed");
|
|
487
|
+
this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
|
|
488
|
+
service: name,
|
|
489
|
+
error: msg,
|
|
490
|
+
reason: "unregistered",
|
|
491
|
+
elapsed_ms: st.elapsedMs()
|
|
492
|
+
});
|
|
493
|
+
return true;
|
|
494
|
+
}
|
|
495
|
+
let reportReady;
|
|
496
|
+
const readyPromise = new Promise((res) => {
|
|
497
|
+
reportReady = res;
|
|
498
|
+
});
|
|
499
|
+
st.started.push(name);
|
|
500
|
+
this.emitter.emit(OBJECT_SERVICE, ACTION_STARTED, {
|
|
501
|
+
service: name,
|
|
502
|
+
elapsed_ms: st.elapsedMs()
|
|
503
|
+
});
|
|
504
|
+
const running = svc.start(runAC.signal, reportReady).then(() => ({ name, error: null })).catch((e) => ({ name, error: errText(e) }));
|
|
505
|
+
st.live.set(name, running);
|
|
506
|
+
const failed = await this.awaitReady(name, readyPromise, configs, st);
|
|
507
|
+
if (failed) return true;
|
|
508
|
+
}
|
|
509
|
+
return false;
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Blocks until `name` reports ready, fails, or exhausts its
|
|
513
|
+
* readiness budget. A service that has not reported ready within the
|
|
514
|
+
* budget is a start failure.
|
|
515
|
+
*/
|
|
516
|
+
async awaitReady(name, readyPromise, configs, st) {
|
|
517
|
+
const budget = configs[name]?.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
|
|
518
|
+
const timer = new Timer(budget);
|
|
519
|
+
const running = st.live.get(name);
|
|
520
|
+
try {
|
|
521
|
+
const winner = await Promise.race([
|
|
522
|
+
readyPromise.then(() => "ready"),
|
|
523
|
+
running.then((e) => ({ exit: e })),
|
|
524
|
+
timer.promise.then(() => "timeout")
|
|
525
|
+
]);
|
|
526
|
+
if (winner === "ready") {
|
|
527
|
+
st.ready.push(name);
|
|
528
|
+
this.emitter.emit(OBJECT_SERVICE, ACTION_READY_REPORTED, {
|
|
529
|
+
service: name,
|
|
530
|
+
address: this.addrOf(name),
|
|
531
|
+
elapsed_ms: st.elapsedMs()
|
|
532
|
+
});
|
|
533
|
+
return false;
|
|
534
|
+
}
|
|
535
|
+
if (winner === "timeout") {
|
|
536
|
+
const msg2 = `not ready within ${budget}ms`;
|
|
537
|
+
st.noteFailure(name, msg2, "start-failed");
|
|
538
|
+
this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
|
|
539
|
+
service: name,
|
|
540
|
+
error: msg2,
|
|
541
|
+
reason: "ready_timeout",
|
|
542
|
+
elapsed_ms: st.elapsedMs()
|
|
543
|
+
});
|
|
544
|
+
return true;
|
|
545
|
+
}
|
|
546
|
+
st.live.delete(name);
|
|
547
|
+
const msg = winner.exit.error ?? "returned before reporting ready";
|
|
548
|
+
st.noteFailure(name, msg, "start-failed");
|
|
549
|
+
this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
|
|
550
|
+
service: name,
|
|
551
|
+
error: msg,
|
|
552
|
+
reason: "start",
|
|
553
|
+
elapsed_ms: st.elapsedMs()
|
|
554
|
+
});
|
|
555
|
+
return true;
|
|
556
|
+
} finally {
|
|
557
|
+
timer.cancel();
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Publishes the supervisor-scoped readiness event once every started
|
|
562
|
+
* service is ready.
|
|
563
|
+
*/
|
|
564
|
+
emitAggregateReady(st) {
|
|
565
|
+
if (st.started.length > 0 && st.ready.length === st.started.length) {
|
|
566
|
+
this.emitter.emit(OBJECT_SUPERVISOR, ACTION_READY_REPORTED, {
|
|
567
|
+
elapsed_ms: st.elapsedMs()
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Blocks while the services run. Returns when the run signal aborts,
|
|
573
|
+
* when the failure policy trips, or when the last running service
|
|
574
|
+
* has exited.
|
|
575
|
+
*/
|
|
576
|
+
async await_(runAC, st) {
|
|
577
|
+
const aborted = new Promise((res) => {
|
|
578
|
+
if (runAC.signal.aborted) {
|
|
579
|
+
res("aborted");
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
runAC.signal.addEventListener("abort", () => res("aborted"), { once: true });
|
|
583
|
+
});
|
|
584
|
+
while (st.live.size > 0) {
|
|
585
|
+
const races = [...st.live.entries()].map(([, p]) => p);
|
|
586
|
+
const winner = await Promise.race([aborted, ...races]);
|
|
587
|
+
if (winner === "aborted") return;
|
|
588
|
+
st.live.delete(winner.name);
|
|
589
|
+
if (winner.error !== null) {
|
|
590
|
+
st.noteFailure(winner.name, winner.error, "runtime-crash");
|
|
591
|
+
this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
|
|
592
|
+
service: winner.name,
|
|
593
|
+
error: winner.error,
|
|
594
|
+
reason: "runtime",
|
|
595
|
+
elapsed_ms: st.elapsedMs()
|
|
596
|
+
});
|
|
597
|
+
if (this.failurePolicy === "fail-fast") {
|
|
598
|
+
runAC.abort();
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
continue;
|
|
602
|
+
}
|
|
603
|
+
if (!st.markStopped(winner.name)) {
|
|
604
|
+
this.emitter.emit(OBJECT_SERVICE, ACTION_STOPPED, {
|
|
605
|
+
service: winner.name,
|
|
606
|
+
elapsed_ms: st.elapsedMs()
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
if (Object.keys(st.failed).length > 0 && this.failurePolicy === "isolate") {
|
|
611
|
+
st.observed.push("runtime-crash");
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Invokes stop in the exact reverse of the order services actually
|
|
616
|
+
* started, one at a time, so a dependent is always fully stopped
|
|
617
|
+
* before its dependency.
|
|
618
|
+
*
|
|
619
|
+
* Each stop is bounded by that service's budget. One that exceeds it
|
|
620
|
+
* is abandoned — logged, emitted as failed, and the supervisor
|
|
621
|
+
* proceeds to the next rather than blocking the whole shutdown on
|
|
622
|
+
* one straggler. Exceeding the total budget ends the sequence with
|
|
623
|
+
* `shutdown-timeout`.
|
|
624
|
+
*/
|
|
625
|
+
async stopAll(st, configs) {
|
|
626
|
+
const order = [...st.started];
|
|
627
|
+
const deadline = this.now() + this.shutdownTimeoutMs;
|
|
628
|
+
for (let i = order.length - 1; i >= 0; i--) {
|
|
629
|
+
const name = order[i];
|
|
630
|
+
if (this.escalate?.aborted) {
|
|
631
|
+
const msg = "drain aborted by second signal";
|
|
632
|
+
st.observed.push("runtime-crash");
|
|
633
|
+
for (const abandoned of order.slice(0, i + 1)) {
|
|
634
|
+
st.failed[abandoned] = msg;
|
|
635
|
+
this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
|
|
636
|
+
service: abandoned,
|
|
637
|
+
error: msg,
|
|
638
|
+
reason: "escalated",
|
|
639
|
+
elapsed_ms: st.elapsedMs()
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
if (this.now() >= deadline) {
|
|
645
|
+
st.observed.push("shutdown-timeout");
|
|
646
|
+
this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
|
|
647
|
+
service: name,
|
|
648
|
+
reason: "shutdown_timeout",
|
|
649
|
+
error: `shutdown budget ${this.shutdownTimeoutMs}ms exhausted before stopping`,
|
|
650
|
+
elapsed_ms: st.elapsedMs()
|
|
651
|
+
});
|
|
652
|
+
continue;
|
|
653
|
+
}
|
|
654
|
+
const svc = this.registry.lookup(name);
|
|
655
|
+
if (!svc) continue;
|
|
656
|
+
const budget = Math.min(
|
|
657
|
+
configs[name]?.stopTimeoutMs ?? DEFAULT_STOP_TIMEOUT_MS,
|
|
658
|
+
Math.max(0, deadline - this.now())
|
|
659
|
+
);
|
|
660
|
+
await this.stopOne(svc, name, budget, deadline, st);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
/** Bounds one stop by its budget and by whatever remains of the total. */
|
|
664
|
+
async stopOne(svc, name, budget, deadline, st) {
|
|
665
|
+
const stopAC = new AbortController();
|
|
666
|
+
const timer = new Timer(budget);
|
|
667
|
+
try {
|
|
668
|
+
const winner = await Promise.race([
|
|
669
|
+
svc.stop(stopAC.signal).then(() => "ok", (e) => ({ err: errText(e) })),
|
|
670
|
+
timer.promise.then(() => "timeout")
|
|
671
|
+
]);
|
|
672
|
+
if (winner === "timeout") {
|
|
673
|
+
stopAC.abort();
|
|
674
|
+
const overTotal = this.now() >= deadline;
|
|
675
|
+
st.noteFailure(
|
|
676
|
+
name,
|
|
677
|
+
`stop exceeded ${budget}ms`,
|
|
678
|
+
overTotal ? "shutdown-timeout" : "runtime-crash"
|
|
679
|
+
);
|
|
680
|
+
this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
|
|
681
|
+
service: name,
|
|
682
|
+
error: `stop exceeded ${budget}ms`,
|
|
683
|
+
reason: overTotal ? "shutdown_timeout" : "stop_timeout",
|
|
684
|
+
elapsed_ms: st.elapsedMs()
|
|
685
|
+
});
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
if (winner !== "ok") {
|
|
689
|
+
st.noteFailure(name, winner.err, "runtime-crash");
|
|
690
|
+
this.emitter.emit(OBJECT_SERVICE, ACTION_FAILED, {
|
|
691
|
+
service: name,
|
|
692
|
+
error: winner.err,
|
|
693
|
+
reason: "stop",
|
|
694
|
+
elapsed_ms: st.elapsedMs()
|
|
695
|
+
});
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
if (st.markStopped(name)) return;
|
|
699
|
+
this.emitter.emit(OBJECT_SERVICE, ACTION_STOPPED, {
|
|
700
|
+
service: name,
|
|
701
|
+
elapsed_ms: st.elapsedMs()
|
|
702
|
+
});
|
|
703
|
+
} finally {
|
|
704
|
+
timer.cancel();
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
addrOf(name) {
|
|
708
|
+
const a = this.registry.lookup(name)?.addr?.();
|
|
709
|
+
return a === "" ? void 0 : a;
|
|
710
|
+
}
|
|
711
|
+
/** Assembles the result from everything the run observed. */
|
|
712
|
+
finish(st, outcome, err) {
|
|
713
|
+
const error = err ?? (isFailure(outcome) ? failureError(outcome, st.failed) : void 0);
|
|
714
|
+
this.emitter.emit(OBJECT_SUPERVISOR, ACTION_STOPPED, {
|
|
715
|
+
reason: outcome,
|
|
716
|
+
elapsed_ms: st.elapsedMs()
|
|
717
|
+
});
|
|
718
|
+
return {
|
|
719
|
+
outcome,
|
|
720
|
+
error,
|
|
721
|
+
started: [...st.started],
|
|
722
|
+
ready: [...st.ready],
|
|
723
|
+
failed: { ...st.failed },
|
|
724
|
+
exitCode: exitCodeFor(outcome)
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
};
|
|
728
|
+
var RunState = class {
|
|
729
|
+
constructor(now) {
|
|
730
|
+
this.now = now;
|
|
731
|
+
this.started = [];
|
|
732
|
+
this.ready = [];
|
|
733
|
+
this.failed = {};
|
|
734
|
+
this.observed = [];
|
|
735
|
+
this.live = /* @__PURE__ */ new Map();
|
|
736
|
+
this.stopped = /* @__PURE__ */ new Set();
|
|
737
|
+
this.begin = now();
|
|
738
|
+
}
|
|
739
|
+
elapsedMs() {
|
|
740
|
+
return this.now() - this.begin;
|
|
741
|
+
}
|
|
742
|
+
noteFailure(name, error, outcome) {
|
|
743
|
+
this.failed[name] = error;
|
|
744
|
+
this.observed.push(outcome);
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Records that `name`'s stopped event has been emitted and reports
|
|
748
|
+
* whether it had been already. A service reports stopped once per
|
|
749
|
+
* run, whichever path noticed it first.
|
|
750
|
+
*/
|
|
751
|
+
markStopped(name) {
|
|
752
|
+
const already = this.stopped.has(name);
|
|
753
|
+
this.stopped.add(name);
|
|
754
|
+
return already;
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
var LoopKeepAlive = class {
|
|
758
|
+
hold() {
|
|
759
|
+
if (this.handle) return;
|
|
760
|
+
this.handle = setInterval(() => {
|
|
761
|
+
}, 2 ** 30);
|
|
762
|
+
}
|
|
763
|
+
release() {
|
|
764
|
+
if (!this.handle) return;
|
|
765
|
+
clearInterval(this.handle);
|
|
766
|
+
this.handle = void 0;
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Whether a referenced handle is currently held.
|
|
770
|
+
*
|
|
771
|
+
* Node's `process._getActiveHandles()` does not report timers, so
|
|
772
|
+
* this is the only honest way to observe the property that matters.
|
|
773
|
+
*/
|
|
774
|
+
get held() {
|
|
775
|
+
return this.handle !== void 0 && this.handle.hasRef?.() !== false;
|
|
776
|
+
}
|
|
777
|
+
};
|
|
778
|
+
var Timer = class {
|
|
779
|
+
constructor(ms) {
|
|
780
|
+
this.promise = new Promise((res) => {
|
|
781
|
+
this.handle = setTimeout(res, Math.max(0, ms));
|
|
782
|
+
this.handle.unref?.();
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
cancel() {
|
|
786
|
+
if (this.handle) clearTimeout(this.handle);
|
|
787
|
+
}
|
|
788
|
+
};
|
|
789
|
+
function errText(e) {
|
|
790
|
+
if (e instanceof Error) return e.message;
|
|
791
|
+
return String(e);
|
|
792
|
+
}
|
|
793
|
+
function failureError(outcome, failed) {
|
|
794
|
+
const names = Object.keys(failed).sort();
|
|
795
|
+
let msg;
|
|
796
|
+
switch (outcome) {
|
|
797
|
+
case "start-failed":
|
|
798
|
+
msg = "service failed to start";
|
|
799
|
+
break;
|
|
800
|
+
case "shutdown-timeout":
|
|
801
|
+
msg = "shutdown budget exceeded";
|
|
802
|
+
break;
|
|
803
|
+
default:
|
|
804
|
+
msg = "service failed";
|
|
805
|
+
}
|
|
806
|
+
names.forEach((name, i) => {
|
|
807
|
+
msg += `${i === 0 ? ": " : "; "}${name}: ${failed[name]}`;
|
|
808
|
+
});
|
|
809
|
+
return {
|
|
810
|
+
code: codeFor(outcome),
|
|
811
|
+
message: msg,
|
|
812
|
+
exit_code: exitCodeFor(outcome),
|
|
813
|
+
transience: "permanent"
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
var SHUTDOWN_SIGNALS = ["SIGINT", "SIGTERM"];
|
|
817
|
+
function signalController() {
|
|
818
|
+
const first = new AbortController();
|
|
819
|
+
const second = new AbortController();
|
|
820
|
+
let count = 0;
|
|
821
|
+
const onSignal = () => {
|
|
822
|
+
count++;
|
|
823
|
+
if (count === 1) first.abort();
|
|
824
|
+
else second.abort();
|
|
825
|
+
};
|
|
826
|
+
for (const sig of SHUTDOWN_SIGNALS) process.on(sig, onSignal);
|
|
827
|
+
let stopped = false;
|
|
828
|
+
return {
|
|
829
|
+
signal: first.signal,
|
|
830
|
+
escalate: second.signal,
|
|
831
|
+
stop: () => {
|
|
832
|
+
if (stopped) return;
|
|
833
|
+
stopped = true;
|
|
834
|
+
for (const sig of SHUTDOWN_SIGNALS) process.removeListener(sig, onSignal);
|
|
835
|
+
}
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
function applyEnableDisable(configs, enable, disable) {
|
|
839
|
+
const out = { ...configs };
|
|
840
|
+
for (const name of disable) {
|
|
841
|
+
if (out[name] !== void 0) out[name] = { ...out[name], enabled: false };
|
|
842
|
+
}
|
|
843
|
+
for (const name of enable) {
|
|
844
|
+
out[name] = { ...out[name] ?? {}, enabled: true };
|
|
845
|
+
}
|
|
846
|
+
return out;
|
|
847
|
+
}
|
|
848
|
+
function applyTimeoutOverrides(configs, readyTimeoutMs, stopTimeoutMs) {
|
|
849
|
+
const ready = readyTimeoutMs !== void 0 && readyTimeoutMs > 0;
|
|
850
|
+
const stop = stopTimeoutMs !== void 0 && stopTimeoutMs > 0;
|
|
851
|
+
if (!ready && !stop) return { ...configs };
|
|
852
|
+
const out = {};
|
|
853
|
+
for (const [name, cfg] of Object.entries(configs)) {
|
|
854
|
+
out[name] = {
|
|
855
|
+
...cfg,
|
|
856
|
+
...ready ? { readyTimeoutMs } : {},
|
|
857
|
+
...stop ? { stopTimeoutMs } : {}
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
return out;
|
|
861
|
+
}
|
|
862
|
+
var DURATION_UNIT_MS = { ms: 1, s: 1e3, m: 6e4, h: 36e5 };
|
|
863
|
+
function parseDurationMs(raw) {
|
|
864
|
+
const s = raw.trim();
|
|
865
|
+
if (s === "") return null;
|
|
866
|
+
if (/^\d+(?:\.\d+)?$/.test(s)) return Number(s) * 1e3;
|
|
867
|
+
const re = /(\d+(?:\.\d+)?)(ms|s|m|h)/g;
|
|
868
|
+
let total = 0;
|
|
869
|
+
let consumed = "";
|
|
870
|
+
for (const m of s.matchAll(re)) {
|
|
871
|
+
consumed += m[0];
|
|
872
|
+
total += Number(m[1]) * DURATION_UNIT_MS[m[2]];
|
|
873
|
+
}
|
|
874
|
+
return consumed === s ? total : null;
|
|
875
|
+
}
|
|
876
|
+
function registerServe(program, opts) {
|
|
877
|
+
const collect = (v, prev) => prev.concat([v]);
|
|
878
|
+
const cmd = program.command("serve [service...]").description("Run configured services under one lifecycle").option("--list", "List registered services and their state").option(
|
|
879
|
+
"--enable <name>",
|
|
880
|
+
"Enable a service for this run (repeatable, supervisor form only)",
|
|
881
|
+
collect,
|
|
882
|
+
[]
|
|
883
|
+
).option(
|
|
884
|
+
"--disable <name>",
|
|
885
|
+
"Disable a service for this run (repeatable, supervisor form only)",
|
|
886
|
+
collect,
|
|
887
|
+
[]
|
|
888
|
+
).option("--ready-timeout <duration>", "Per-service budget from start to ready (default 30s)").option("--stop-timeout <duration>", "Per-service budget for one stop (default 30s)").option("--shutdown-timeout <duration>", "Total shutdown budget across all services (default 60s)").action(async (services, flags) => {
|
|
889
|
+
if (flags.list) {
|
|
890
|
+
runList(opts);
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
await runServe(services ?? [], flags, opts);
|
|
894
|
+
});
|
|
895
|
+
return cmd;
|
|
896
|
+
}
|
|
897
|
+
function runList(opts) {
|
|
898
|
+
const w = opts.stdout ?? process.stdout;
|
|
899
|
+
const configs = opts.configs ?? {};
|
|
900
|
+
w.write("SERVICE CONFIGURED ENABLED READY\n");
|
|
901
|
+
for (const svc of opts.registry.list()) {
|
|
902
|
+
const cfg = configs[svc.name];
|
|
903
|
+
const configured = cfg !== void 0;
|
|
904
|
+
const enabled = cfg?.enabled === true;
|
|
905
|
+
w.write(
|
|
906
|
+
`${svc.name.padEnd(20)} ${String(configured).padEnd(11)} ${String(enabled).padEnd(8)} ${String(svc.ready())}
|
|
907
|
+
`
|
|
908
|
+
);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
async function runServe(args, flags, opts) {
|
|
912
|
+
const enable = flags.enable ?? [];
|
|
913
|
+
const disable = flags.disable ?? [];
|
|
914
|
+
if (args.length === 1 && (enable.length > 0 || disable.length > 0)) {
|
|
915
|
+
report(opts, exitCodeFor("invalid-selection"), usageError(
|
|
916
|
+
"--enable/--disable apply to the supervisor form; drop the service name or drop the flags"
|
|
917
|
+
));
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
const durations = {};
|
|
921
|
+
for (const [key, flag] of [
|
|
922
|
+
["readyTimeout", "--ready-timeout"],
|
|
923
|
+
["stopTimeout", "--stop-timeout"],
|
|
924
|
+
["shutdownTimeout", "--shutdown-timeout"]
|
|
925
|
+
]) {
|
|
926
|
+
const raw = flags[key];
|
|
927
|
+
if (raw === void 0) continue;
|
|
928
|
+
const ms = parseDurationMs(raw);
|
|
929
|
+
if (ms === null) {
|
|
930
|
+
report(opts, exitCodeFor("config-invalid"), usageError(`${flag}: invalid duration "${raw}"`));
|
|
931
|
+
return;
|
|
932
|
+
}
|
|
933
|
+
durations[key] = ms;
|
|
934
|
+
}
|
|
935
|
+
const configs = applyTimeoutOverrides(
|
|
936
|
+
applyEnableDisable(opts.configs ?? {}, enable, disable),
|
|
937
|
+
durations.readyTimeout,
|
|
938
|
+
durations.stopTimeout
|
|
939
|
+
);
|
|
940
|
+
const config = {
|
|
941
|
+
...opts.config,
|
|
942
|
+
...durations.shutdownTimeout !== void 0 ? { shutdownTimeoutMs: durations.shutdownTimeout } : {}
|
|
943
|
+
};
|
|
944
|
+
const outcome = resolve(opts.registry, {
|
|
945
|
+
args,
|
|
946
|
+
configs,
|
|
947
|
+
policy: opts.policy
|
|
948
|
+
});
|
|
949
|
+
if (outcome.error) {
|
|
950
|
+
report(opts, exitCodeFor(outcome.outcome ?? "config-invalid"), outcome.error);
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
const sig = signalController();
|
|
954
|
+
try {
|
|
955
|
+
const sup = new Supervisor(opts.registry, {
|
|
956
|
+
config,
|
|
957
|
+
publisher: opts.publisher,
|
|
958
|
+
logger: opts.logger,
|
|
959
|
+
escalate: sig.escalate
|
|
960
|
+
});
|
|
961
|
+
const res = await sup.run(sig.signal, outcome.selected, configs);
|
|
962
|
+
report(opts, res.exitCode, res.error);
|
|
963
|
+
} finally {
|
|
964
|
+
sig.stop();
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
function report(opts, code, error) {
|
|
968
|
+
if (opts.onExit) {
|
|
969
|
+
opts.onExit(code, error);
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
if (error) {
|
|
973
|
+
process.stderr.write(
|
|
974
|
+
error.code ? `${error.code}: ${error.message}
|
|
975
|
+
` : `${error.message}
|
|
976
|
+
`
|
|
977
|
+
);
|
|
978
|
+
if (error.suggested_fix) process.stderr.write(`Fix: ${error.suggested_fix}
|
|
979
|
+
`);
|
|
980
|
+
}
|
|
981
|
+
process.exitCode = code;
|
|
982
|
+
}
|
|
983
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
984
|
+
0 && (module.exports = {
|
|
985
|
+
ACTION_FAILED,
|
|
986
|
+
ACTION_READY_REPORTED,
|
|
987
|
+
ACTION_STARTED,
|
|
988
|
+
ACTION_STOPPED,
|
|
989
|
+
CODE_TRANSIENT,
|
|
990
|
+
DEFAULT_FAILURE_POLICY,
|
|
991
|
+
DEFAULT_READY_TIMEOUT_MS,
|
|
992
|
+
DEFAULT_SHUTDOWN_TIMEOUT_MS,
|
|
993
|
+
DEFAULT_STOP_TIMEOUT_MS,
|
|
994
|
+
DEFAULT_TOPIC_PREFIX,
|
|
995
|
+
LoopKeepAlive,
|
|
996
|
+
NAME_PATTERN,
|
|
997
|
+
OBJECT_SERVICE,
|
|
998
|
+
OBJECT_SUPERVISOR,
|
|
999
|
+
RESERVED_NAMES,
|
|
1000
|
+
SHUTDOWN_SIGNALS,
|
|
1001
|
+
ServiceRegistrationError,
|
|
1002
|
+
ServiceRegistry,
|
|
1003
|
+
Supervisor,
|
|
1004
|
+
applyEnableDisable,
|
|
1005
|
+
applyTimeoutOverrides,
|
|
1006
|
+
codeFor,
|
|
1007
|
+
defaultTopics,
|
|
1008
|
+
exitCodeFor,
|
|
1009
|
+
isFailure,
|
|
1010
|
+
isFailurePolicy,
|
|
1011
|
+
isReservedName,
|
|
1012
|
+
parseDurationMs,
|
|
1013
|
+
registerServe,
|
|
1014
|
+
resolve,
|
|
1015
|
+
signalController,
|
|
1016
|
+
startOrder,
|
|
1017
|
+
validateName,
|
|
1018
|
+
worstOutcome
|
|
1019
|
+
});
|