@crvouga/mockingbird-service-docker 1.3.0 → 1.4.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.
- package/CHANGELOG.md +12 -4
- package/dist/{chunk-Y4JH3Q6Z.js → chunk-DG4KWFV5.js} +2 -2
- package/dist/{chunk-NSZYARVW.js → chunk-PEU54Q4H.js} +108 -5
- package/dist/chunk-PEU54Q4H.js.map +7 -0
- package/dist/cli.js +3951 -143
- package/dist/cli.js.map +4 -4
- package/dist/index.d.ts +15 -1
- package/dist/index.js +1 -1
- package/dist/server.d.ts +31 -2
- package/dist/server.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-NSZYARVW.js.map +0 -7
- /package/dist/{chunk-Y4JH3Q6Z.js.map → chunk-DG4KWFV5.js.map} +0 -0
package/dist/cli.js
CHANGED
|
@@ -1,103 +1,3192 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
serveTarget
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-DG4KWFV5.js";
|
|
5
5
|
import {
|
|
6
6
|
createClock,
|
|
7
7
|
normalizeBootControls,
|
|
8
|
+
normalizeControls,
|
|
9
|
+
ownedTransport,
|
|
8
10
|
parseDuration,
|
|
9
11
|
parseFaultHeader,
|
|
10
12
|
resolveAdminPrefix,
|
|
11
13
|
restoreClock
|
|
12
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-PEU54Q4H.js";
|
|
13
15
|
|
|
14
16
|
// ../../adapters/node/dist/cli.js
|
|
15
|
-
import { readFile as
|
|
16
|
-
import { createRequire } from "node:module";
|
|
17
|
-
import { resolve } from "node:path";
|
|
17
|
+
import { readFile as readFile5 } from "node:fs/promises";
|
|
18
|
+
import { createRequire as createRequire3 } from "node:module";
|
|
19
|
+
import { resolve as resolve3 } from "node:path";
|
|
18
20
|
import { pathToFileURL } from "node:url";
|
|
19
21
|
import { parseArgs } from "node:util";
|
|
20
22
|
|
|
21
|
-
// ../../adapters/node/dist/fleet.js
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
23
|
+
// ../../adapters/node/dist/fleet.js
|
|
24
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
25
|
+
import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
|
|
26
|
+
import { chmod, readFile as readFile2, rename, rm, writeFile } from "node:fs/promises";
|
|
27
|
+
|
|
28
|
+
// ../../adapters/node/dist/fleet-management.js
|
|
29
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
30
|
+
import { createHash as createHash3, randomBytes, randomUUID as randomUUID3 } from "node:crypto";
|
|
31
|
+
|
|
32
|
+
// ../../adapters/node/dist/fleet-archive.js
|
|
33
|
+
import { createHash } from "node:crypto";
|
|
34
|
+
var canonical = (value) => {
|
|
35
|
+
if (Array.isArray(value))
|
|
36
|
+
return `[${value.map(canonical).join(",")}]`;
|
|
37
|
+
if (value !== null && typeof value === "object")
|
|
38
|
+
return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
|
|
39
|
+
return JSON.stringify(value);
|
|
40
|
+
};
|
|
41
|
+
var digest = (value) => createHash("sha256").update(canonical(value)).digest("hex");
|
|
42
|
+
var sealArchive = (content) => ({
|
|
43
|
+
...content,
|
|
44
|
+
sha256: digest(content)
|
|
45
|
+
});
|
|
46
|
+
function validateArchive(value) {
|
|
47
|
+
if (!value || typeof value !== "object")
|
|
48
|
+
throw new Error("expected fleet archive");
|
|
49
|
+
const doc = value;
|
|
50
|
+
const { sha256, ...content } = doc;
|
|
51
|
+
if (doc.format !== "mockingbird.fleet/v1" || typeof doc.sourceId !== "string" || typeof doc.createdAt !== "string" || !doc.namespaces || typeof doc.namespaces !== "object" || Array.isArray(doc.namespaces) || sha256 !== digest(content))
|
|
52
|
+
throw new Error("unsupported or corrupt fleet archive");
|
|
53
|
+
for (const [namespace, entry] of Object.entries(doc.namespaces)) {
|
|
54
|
+
if (!/^[A-Za-z0-9_.-]{1,64}$/.test(namespace) || !entry || !Number.isFinite(entry.clock?.now) || typeof entry.clock?.frozen !== "boolean" || !entry.services || !Object.keys(entry.services).length)
|
|
55
|
+
throw new Error("invalid archive namespace");
|
|
56
|
+
for (const [name, child] of Object.entries(entry.services))
|
|
57
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) || !child || child.version !== 1 || !["http", "postgres", "redis", "external"].includes(child.protocol))
|
|
58
|
+
throw new Error("unsupported archive service/version");
|
|
59
|
+
}
|
|
60
|
+
return doc;
|
|
61
|
+
}
|
|
62
|
+
function inspectArchive(input) {
|
|
63
|
+
const archive = validateArchive(input);
|
|
64
|
+
return {
|
|
65
|
+
format: archive.format,
|
|
66
|
+
createdAt: archive.createdAt,
|
|
67
|
+
sha256: archive.sha256,
|
|
68
|
+
namespaces: Object.fromEntries(Object.entries(archive.namespaces).map(([name, ns]) => [
|
|
69
|
+
name,
|
|
70
|
+
{
|
|
71
|
+
clock: ns.clock,
|
|
72
|
+
services: Object.fromEntries(Object.entries(ns.services).map(([service, state]) => [
|
|
73
|
+
service,
|
|
74
|
+
{
|
|
75
|
+
protocol: state.protocol,
|
|
76
|
+
version: state.version,
|
|
77
|
+
bytes: Buffer.byteLength(canonical(state.state))
|
|
78
|
+
}
|
|
79
|
+
]))
|
|
80
|
+
}
|
|
81
|
+
]))
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function diffArchives(left, right, options = {}) {
|
|
85
|
+
const a = validateArchive(left), b = validateArchive(right);
|
|
86
|
+
const limit = Math.min(1e3, Math.max(1, options.limit ?? 100));
|
|
87
|
+
const changes = [];
|
|
88
|
+
let total = 0;
|
|
89
|
+
const walk = (namespace, service, path, before, after) => {
|
|
90
|
+
if (canonical(before) === canonical(after))
|
|
91
|
+
return;
|
|
92
|
+
if (before && after && typeof before === "object" && typeof after === "object" && !Array.isArray(before) && !Array.isArray(after)) {
|
|
93
|
+
for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)]))
|
|
94
|
+
walk(namespace, service, `${path}/${key}`, before[key], after[key]);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
total++;
|
|
98
|
+
if (changes.length < limit)
|
|
99
|
+
changes.push({
|
|
100
|
+
namespace,
|
|
101
|
+
service,
|
|
102
|
+
path,
|
|
103
|
+
kind: before === void 0 ? "added" : after === void 0 ? "removed" : "changed",
|
|
104
|
+
...options.values ? { before, after } : {}
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
for (const ns of /* @__PURE__ */ new Set([...Object.keys(a.namespaces), ...Object.keys(b.namespaces)])) {
|
|
108
|
+
if (options.namespace !== void 0 && options.namespace !== ns)
|
|
109
|
+
continue;
|
|
110
|
+
const an = a.namespaces[ns], bn = b.namespaces[ns];
|
|
111
|
+
walk(ns, "$clock", "/clock", an?.clock, bn?.clock);
|
|
112
|
+
for (const service of /* @__PURE__ */ new Set([
|
|
113
|
+
...Object.keys(an?.services ?? {}),
|
|
114
|
+
...Object.keys(bn?.services ?? {})
|
|
115
|
+
])) {
|
|
116
|
+
if (options.service !== void 0 && options.service !== service)
|
|
117
|
+
continue;
|
|
118
|
+
const x = an?.services[service], y = bn?.services[service];
|
|
119
|
+
if (x && y && (x.protocol !== y.protocol || x.version !== y.version))
|
|
120
|
+
throw new Error("incompatible snapshot comparison");
|
|
121
|
+
const normalize = (state) => {
|
|
122
|
+
if (state && typeof state === "object") {
|
|
123
|
+
const obj = state;
|
|
124
|
+
if (obj.format === "mockingbird.postgres/v1" && obj.inventory) {
|
|
125
|
+
if (options.values)
|
|
126
|
+
throw new Error("raw PostgreSQL row diff is unsupported; use bounded namespace inspection");
|
|
127
|
+
const { databases: _databases, ...metadata } = obj;
|
|
128
|
+
return metadata;
|
|
129
|
+
}
|
|
130
|
+
if (obj.$redis === "map" && Array.isArray(obj.value))
|
|
131
|
+
return Object.fromEntries(obj.value.map((pair) => [
|
|
132
|
+
typeof pair[0] === "string" ? pair[0] : canonical(pair[0]),
|
|
133
|
+
normalize(pair[1])
|
|
134
|
+
]));
|
|
135
|
+
if (Array.isArray(state))
|
|
136
|
+
return Object.fromEntries(state.map((value, index) => [String(index), normalize(value)]));
|
|
137
|
+
}
|
|
138
|
+
if (state && typeof state === "object" && Array.isArray(state.records)) {
|
|
139
|
+
const { records, ...rest } = state;
|
|
140
|
+
return {
|
|
141
|
+
...rest,
|
|
142
|
+
records: Object.fromEntries(records.map((r) => [`${r.collection}/${r.id}`, r]))
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
if (state && typeof state === "object" && !Array.isArray(state))
|
|
146
|
+
return Object.fromEntries(Object.entries(state).map(([k, v]) => [k, normalize(v)]));
|
|
147
|
+
return state;
|
|
148
|
+
};
|
|
149
|
+
walk(ns, service, "/state", normalize(x?.state), normalize(y?.state));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return { format: "mockingbird.fleet-diff/v1", total, truncated: total > changes.length, changes };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// ../../adapters/node/dist/fleet-bindings.js
|
|
156
|
+
var object = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
157
|
+
async function planRestoreBindings(input, plan, resolveSecret) {
|
|
158
|
+
const source = validateArchive(input), copy = structuredClone(source);
|
|
159
|
+
if (!plan || !Array.isArray(plan.bindings) || !object(plan.endpoints))
|
|
160
|
+
throw new Error("expected explicit restore bindings and endpoint references");
|
|
161
|
+
const changes = [];
|
|
162
|
+
const seen = /* @__PURE__ */ new Set();
|
|
163
|
+
const endpoint = (reference) => {
|
|
164
|
+
const value = plan.endpoints[reference];
|
|
165
|
+
if (typeof value !== "string")
|
|
166
|
+
throw new Error(`unresolved endpoint reference ${reference}`);
|
|
167
|
+
const url = new URL(value);
|
|
168
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password)
|
|
169
|
+
throw new Error(`invalid endpoint reference ${reference}`);
|
|
170
|
+
return url.href;
|
|
171
|
+
};
|
|
172
|
+
for (const binding of plan.bindings) {
|
|
173
|
+
const identity = `${binding.namespace}/${binding.service}/${binding.endpointId}`;
|
|
174
|
+
if (seen.has(identity))
|
|
175
|
+
throw new Error(`ambiguous binding ${identity}`);
|
|
176
|
+
seen.add(identity);
|
|
177
|
+
const section = copy.namespaces[binding.namespace]?.services[binding.service];
|
|
178
|
+
if (section?.protocol !== "http" || !object(section.state) || !object(section.state.webhooks) || !Array.isArray(section.state.webhooks.endpoints))
|
|
179
|
+
throw new Error(`unsupported callback binding ${identity}`);
|
|
180
|
+
const hub = section.state.webhooks;
|
|
181
|
+
const matches = hub.endpoints.filter((e) => object(e) && e.id === binding.endpointId);
|
|
182
|
+
if (matches.length !== 1)
|
|
183
|
+
throw new Error(`unresolved or ambiguous endpoint ${identity}`);
|
|
184
|
+
const current = matches[0], old = String(current.url), destination2 = endpoint(binding.endpointRef);
|
|
185
|
+
if (current.signUrl !== void 0 && binding.signing === void 0)
|
|
186
|
+
throw new Error(`signing policy required for ${identity}`);
|
|
187
|
+
if (binding.signing !== void 0 && !["preserve", "replace"].includes(binding.signing))
|
|
188
|
+
throw new Error(`unsupported signing policy ${identity}`);
|
|
189
|
+
const signUrl = binding.signing === "replace" ? endpoint(binding.signingRef ?? binding.endpointRef) : current.signUrl;
|
|
190
|
+
let secret;
|
|
191
|
+
if (binding.secretRef !== void 0) {
|
|
192
|
+
if (!resolveSecret)
|
|
193
|
+
throw new Error(`unresolved secret reference ${binding.secretRef}`);
|
|
194
|
+
try {
|
|
195
|
+
secret = await resolveSecret(binding.secretRef);
|
|
196
|
+
if (typeof secret !== "string" || !secret)
|
|
197
|
+
throw new Error();
|
|
198
|
+
} catch {
|
|
199
|
+
throw new Error(`unresolved secret reference ${binding.secretRef}`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const apply = (value) => {
|
|
203
|
+
value.url = destination2;
|
|
204
|
+
if (signUrl !== void 0)
|
|
205
|
+
value.signUrl = signUrl;
|
|
206
|
+
if (secret !== void 0)
|
|
207
|
+
value.secret = secret;
|
|
208
|
+
};
|
|
209
|
+
apply(current);
|
|
210
|
+
if (Array.isArray(hub.payloads)) {
|
|
211
|
+
for (const pair of hub.payloads)
|
|
212
|
+
if (Array.isArray(pair) && object(pair[1]) && object(pair[1].endpoint) && pair[1].endpoint.id === binding.endpointId)
|
|
213
|
+
apply(pair[1].endpoint);
|
|
214
|
+
}
|
|
215
|
+
if (Array.isArray(hub.deliveries)) {
|
|
216
|
+
for (const pair of hub.deliveries)
|
|
217
|
+
if (Array.isArray(pair) && object(pair[1]) && pair[1].endpointId === binding.endpointId)
|
|
218
|
+
pair[1].url = destination2;
|
|
219
|
+
}
|
|
220
|
+
if (Array.isArray(section.state.records)) {
|
|
221
|
+
for (const row of section.state.records)
|
|
222
|
+
if (object(row) && row.collection === "runtime_webhook_endpoints" && object(row.value) && row.value.id === binding.endpointId)
|
|
223
|
+
apply(row.value);
|
|
224
|
+
}
|
|
225
|
+
changes.push({
|
|
226
|
+
namespace: binding.namespace,
|
|
227
|
+
service: binding.service,
|
|
228
|
+
endpointId: binding.endpointId,
|
|
229
|
+
endpointRef: binding.endpointRef,
|
|
230
|
+
...binding.secretRef ? { secretRef: binding.secretRef } : {},
|
|
231
|
+
previousFingerprint: digest(old),
|
|
232
|
+
destinationFingerprint: digest(destination2),
|
|
233
|
+
signing: binding.signing ?? "not-configured"
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
const { sha256: _sha, ...content } = copy;
|
|
237
|
+
return {
|
|
238
|
+
report: {
|
|
239
|
+
version: 1,
|
|
240
|
+
source: source.sha256,
|
|
241
|
+
changes,
|
|
242
|
+
limitations: [
|
|
243
|
+
"opaque payloads, tokens, issuer material and application URLs are unchanged",
|
|
244
|
+
"protocol key rebinding requires a registered participant transformation"
|
|
245
|
+
]
|
|
246
|
+
},
|
|
247
|
+
archive: sealArchive(content)
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
var rebaseArchiveNamespace = (input, source, destination2) => {
|
|
251
|
+
const archive = validateArchive(input);
|
|
252
|
+
if (!/^[A-Za-z0-9_.-]{1,64}$/.test(destination2) || !archive.namespaces[source])
|
|
253
|
+
throw new Error("invalid namespace fork");
|
|
254
|
+
const { sha256: _sha, ...content } = archive;
|
|
255
|
+
return sealArchive({
|
|
256
|
+
...content,
|
|
257
|
+
namespaces: { [destination2]: structuredClone(archive.namespaces[source]) }
|
|
258
|
+
});
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
// ../../adapters/node/dist/fleet-instrumentation.js
|
|
262
|
+
import { randomUUID } from "node:crypto";
|
|
263
|
+
var FleetInstrumentation = class {
|
|
264
|
+
options;
|
|
265
|
+
auditEntries = [];
|
|
266
|
+
started = /* @__PURE__ */ new Map();
|
|
267
|
+
terminal = /* @__PURE__ */ new Set();
|
|
268
|
+
metrics = {
|
|
269
|
+
started: 0,
|
|
270
|
+
succeeded: 0,
|
|
271
|
+
failed: 0,
|
|
272
|
+
cancelled: 0,
|
|
273
|
+
recoveryRequired: 0,
|
|
274
|
+
phaseEvents: 0,
|
|
275
|
+
auditFailures: 0,
|
|
276
|
+
rollbackAttempts: 0,
|
|
277
|
+
rollbackFailures: 0,
|
|
278
|
+
telemetryFailures: 0,
|
|
279
|
+
durationsMs: { count: 0, sum: 0, max: 0 }
|
|
280
|
+
};
|
|
281
|
+
constructor(options = {}) {
|
|
282
|
+
this.options = options;
|
|
283
|
+
}
|
|
284
|
+
async audit(input) {
|
|
285
|
+
const event = { ...input, id: randomUUID(), timestamp: (/* @__PURE__ */ new Date()).toISOString() };
|
|
286
|
+
let accepted = true;
|
|
287
|
+
try {
|
|
288
|
+
if (this.options.audit) {
|
|
289
|
+
await this.options.audit.write(event);
|
|
290
|
+
event.durable = true;
|
|
291
|
+
} else
|
|
292
|
+
event.durable = false;
|
|
293
|
+
} catch {
|
|
294
|
+
this.metrics.auditFailures++;
|
|
295
|
+
event.durable = false;
|
|
296
|
+
accepted = this.options.audit?.failurePolicy !== "closed";
|
|
297
|
+
}
|
|
298
|
+
this.auditEntries.push(event);
|
|
299
|
+
if (this.auditEntries.length > 200)
|
|
300
|
+
this.auditEntries.shift();
|
|
301
|
+
return accepted;
|
|
302
|
+
}
|
|
303
|
+
phase(operation, recoveryRequired) {
|
|
304
|
+
if (!this.started.has(operation.id)) {
|
|
305
|
+
this.started.set(operation.id, performance.now());
|
|
306
|
+
this.metrics.started++;
|
|
307
|
+
}
|
|
308
|
+
const elapsedMs = Math.max(0, performance.now() - this.started.get(operation.id));
|
|
309
|
+
this.metrics.phaseEvents++;
|
|
310
|
+
if (operation.phase === "rolling-back")
|
|
311
|
+
this.metrics.rollbackAttempts++;
|
|
312
|
+
if (operation.phase === "rollback-failed")
|
|
313
|
+
this.metrics.rollbackFailures++;
|
|
314
|
+
if (operation.status !== "running" && !this.terminal.has(operation.id)) {
|
|
315
|
+
this.terminal.add(operation.id);
|
|
316
|
+
if (operation.status === "succeeded")
|
|
317
|
+
this.metrics.succeeded++;
|
|
318
|
+
else if (operation.status === "cancelled")
|
|
319
|
+
this.metrics.cancelled++;
|
|
320
|
+
else
|
|
321
|
+
this.metrics.failed++;
|
|
322
|
+
if (recoveryRequired)
|
|
323
|
+
this.metrics.recoveryRequired++;
|
|
324
|
+
this.metrics.durationsMs.count++;
|
|
325
|
+
this.metrics.durationsMs.sum += elapsedMs;
|
|
326
|
+
this.metrics.durationsMs.max = Math.max(this.metrics.durationsMs.max, elapsedMs);
|
|
327
|
+
}
|
|
328
|
+
const action = operation.action.replace(/\/namespaces\/[^/]+/g, "/namespaces/{namespace}").replace(/\/snapshots\/[^/]+/g, "/snapshots/{id}").replace(/\/scenarios\/[^/]+/g, "/scenarios/{name}");
|
|
329
|
+
try {
|
|
330
|
+
const sent = this.options.telemetry?.({
|
|
331
|
+
...operation.participant ? { participant: operation.participant } : {},
|
|
332
|
+
operationId: operation.id,
|
|
333
|
+
phase: operation.phase,
|
|
334
|
+
action,
|
|
335
|
+
services: operation.services ?? [],
|
|
336
|
+
status: operation.status,
|
|
337
|
+
elapsedMs,
|
|
338
|
+
recoveryRequired
|
|
339
|
+
});
|
|
340
|
+
if (sent)
|
|
341
|
+
void sent.catch(() => {
|
|
342
|
+
this.metrics.telemetryFailures++;
|
|
343
|
+
});
|
|
344
|
+
} catch {
|
|
345
|
+
this.metrics.telemetryFailures++;
|
|
346
|
+
}
|
|
347
|
+
while (this.started.size > 200) {
|
|
348
|
+
const id = this.started.keys().next().value;
|
|
349
|
+
this.started.delete(id);
|
|
350
|
+
this.terminal.delete(id);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
snapshot() {
|
|
354
|
+
return {
|
|
355
|
+
version: 1,
|
|
356
|
+
metrics: structuredClone(this.metrics),
|
|
357
|
+
cardinality: "aggregate-no-namespace-labels"
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
auditTrail() {
|
|
361
|
+
return {
|
|
362
|
+
version: 1,
|
|
363
|
+
entries: structuredClone(this.auditEntries),
|
|
364
|
+
retention: 200,
|
|
365
|
+
durableSink: Boolean(this.options.audit),
|
|
366
|
+
failurePolicy: this.options.audit?.failurePolicy ?? "memory-only"
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
|
|
371
|
+
// ../../adapters/node/dist/fleet-journal.js
|
|
372
|
+
import { mkdir, readdir } from "node:fs/promises";
|
|
373
|
+
import { join } from "node:path";
|
|
374
|
+
var validate = (record) => {
|
|
375
|
+
if (record?.version !== 1 || !Number.isSafeInteger(record.revision) || record.revision < 1 || !/^[a-f0-9-]{36}$/.test(record.operationId) || !Array.isArray(record.scope) || record.scope.length > 1e3 || record.scope.some((ns) => !/^[A-Za-z0-9_.-]{1,64}$/.test(ns)) || ![
|
|
376
|
+
"prepared",
|
|
377
|
+
"committing",
|
|
378
|
+
"uploading",
|
|
379
|
+
"publishing",
|
|
380
|
+
"succeeded",
|
|
381
|
+
"failed",
|
|
382
|
+
"recovery-required",
|
|
383
|
+
"resolved"
|
|
384
|
+
].includes(record.phase) || [record.before, record.after].some((id) => id !== void 0 && !/^[a-f0-9]{64}$/.test(id)) || Object.keys(record).some((key) => ![
|
|
385
|
+
"version",
|
|
386
|
+
"revision",
|
|
387
|
+
"operationId",
|
|
388
|
+
"controller",
|
|
389
|
+
"namespace",
|
|
390
|
+
"scope",
|
|
391
|
+
"action",
|
|
392
|
+
"phase",
|
|
393
|
+
"timestamp",
|
|
394
|
+
"requestFingerprint",
|
|
395
|
+
"before",
|
|
396
|
+
"after",
|
|
397
|
+
"writerGeneration",
|
|
398
|
+
"resolution"
|
|
399
|
+
].includes(key)))
|
|
400
|
+
throw new Error("invalid durable operation metadata");
|
|
401
|
+
};
|
|
402
|
+
async function reconcileOperation(record, repository) {
|
|
403
|
+
validate(record);
|
|
404
|
+
if (["succeeded", "failed", "resolved"].includes(record.phase))
|
|
405
|
+
return { status: "terminal", operationId: record.operationId };
|
|
406
|
+
if (record.phase === "prepared")
|
|
407
|
+
return { status: "abandoned-before-commit", operationId: record.operationId };
|
|
408
|
+
if (record.after) {
|
|
409
|
+
try {
|
|
410
|
+
const archive = await repository.get(record.after), publication = await repository.publicationMetadata?.();
|
|
411
|
+
if (archive.sha256 === record.after && publication?.id === record.after && record.writerGeneration !== void 0 && publication.generation === record.writerGeneration)
|
|
412
|
+
return {
|
|
413
|
+
status: "verified-publication",
|
|
414
|
+
operationId: record.operationId,
|
|
415
|
+
archive: record.after
|
|
416
|
+
};
|
|
417
|
+
} catch {
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
if (record.before)
|
|
421
|
+
try {
|
|
422
|
+
await repository.get(record.before);
|
|
423
|
+
} catch {
|
|
424
|
+
return {
|
|
425
|
+
status: "recovery-required",
|
|
426
|
+
operationId: record.operationId,
|
|
427
|
+
reason: "before-state archive unavailable",
|
|
428
|
+
scope: record.scope
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
return {
|
|
432
|
+
status: "recovery-required",
|
|
433
|
+
operationId: record.operationId,
|
|
434
|
+
reason: "commit or rollback cannot be proven",
|
|
435
|
+
scope: record.scope
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// ../../adapters/node/dist/fleet-observations.js
|
|
440
|
+
import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
|
|
441
|
+
var hash = (text) => createHash2("sha256").update(text).digest("hex");
|
|
442
|
+
var boundedText = async (stream, max) => {
|
|
443
|
+
if (!stream)
|
|
444
|
+
return "";
|
|
445
|
+
const reader = stream.getReader(), chunks = [];
|
|
446
|
+
let bytes = 0, timedOut = false;
|
|
447
|
+
const timer = setTimeout(() => {
|
|
448
|
+
timedOut = true;
|
|
449
|
+
void reader.cancel().catch(() => {
|
|
450
|
+
});
|
|
451
|
+
}, 100);
|
|
452
|
+
try {
|
|
453
|
+
for (; ; ) {
|
|
454
|
+
const result = await reader.read();
|
|
455
|
+
if (result.done)
|
|
456
|
+
break;
|
|
457
|
+
bytes += result.value.length;
|
|
458
|
+
if (bytes > max)
|
|
459
|
+
throw new Error("capture byte limit");
|
|
460
|
+
chunks.push(result.value);
|
|
461
|
+
}
|
|
462
|
+
if (timedOut)
|
|
463
|
+
throw new Error("capture deadline");
|
|
464
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
465
|
+
} finally {
|
|
466
|
+
clearTimeout(timer);
|
|
467
|
+
void reader.cancel().catch(() => {
|
|
468
|
+
});
|
|
469
|
+
reader.releaseLock();
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
var FleetObservations = class {
|
|
473
|
+
processId;
|
|
474
|
+
limits;
|
|
475
|
+
sequence = 0;
|
|
476
|
+
entries = [];
|
|
477
|
+
baselines = /* @__PURE__ */ new Map();
|
|
478
|
+
traces = /* @__PURE__ */ new Map();
|
|
479
|
+
constructor(processId, limits = { events: 500, traceEvents: 200, traceBytes: 1024 * 1024 }) {
|
|
480
|
+
this.processId = processId;
|
|
481
|
+
this.limits = limits;
|
|
482
|
+
}
|
|
483
|
+
record(event) {
|
|
484
|
+
this.entries.push({ ...event, id: ++this.sequence });
|
|
485
|
+
if (this.entries.length > this.limits.events)
|
|
486
|
+
this.entries.shift();
|
|
487
|
+
}
|
|
488
|
+
baseline(namespace, services) {
|
|
489
|
+
const id = randomUUID2();
|
|
490
|
+
this.baselines.set(id, { namespace, services, sequence: this.sequence });
|
|
491
|
+
while (this.baselines.size > 200)
|
|
492
|
+
this.baselines.delete(this.baselines.keys().next().value);
|
|
493
|
+
return { id, namespace, services, sequence: this.sequence };
|
|
494
|
+
}
|
|
495
|
+
assertClean(id, namespace, diagnostics, options = {}) {
|
|
496
|
+
const baseline = this.baselines.get(id);
|
|
497
|
+
if (!baseline || baseline.namespace !== namespace)
|
|
498
|
+
throw new Error("assertion baseline not found in this namespace");
|
|
499
|
+
const allowances = options.allowances ?? [];
|
|
500
|
+
if (!Array.isArray(allowances) || allowances.some((a) => !["unmatched", "rejected", "fault"].includes(a.kind) || !a.service || !a.pathFingerprint && !a.operationId || !Number.isSafeInteger(a.maxCount) || a.maxCount < 1))
|
|
501
|
+
throw new Error("allowances must identify a service and exact operation or path fingerprint with a bounded count");
|
|
502
|
+
const consumed = /* @__PURE__ */ new Map(), failures = [];
|
|
503
|
+
if (this.entries.length && baseline.sequence < (this.entries[0]?.id ?? 0) - 1)
|
|
504
|
+
failures.push({ kind: "evidence_truncated" });
|
|
505
|
+
for (const entry of this.entries) {
|
|
506
|
+
if (entry.id <= baseline.sequence || entry.namespace !== namespace || !baseline.services.includes(entry.service))
|
|
507
|
+
continue;
|
|
508
|
+
const kinds = entry.kind === "webhook" ? entry.deliveryState === "failed" || entry.deliveryState === "dropped" ? ["failed_delivery"] : [] : entry.fault ? ["fault"] : entry.unmatched ? ["unmatched"] : (entry.status ?? 0) >= 400 ? ["rejected"] : [];
|
|
509
|
+
for (const kind of kinds) {
|
|
510
|
+
const allowed = allowances.find((a) => a.kind === kind && a.service === entry.service && (!a.pathFingerprint || a.pathFingerprint === entry.pathFingerprint) && (!a.operationId || a.operationId === entry.operationId) && (a.status === void 0 || a.status === entry.status) && (consumed.get(a) ?? 0) < a.maxCount);
|
|
511
|
+
if (allowed)
|
|
512
|
+
consumed.set(allowed, (consumed.get(allowed) ?? 0) + 1);
|
|
513
|
+
else
|
|
514
|
+
failures.push({
|
|
515
|
+
kind,
|
|
516
|
+
service: entry.service,
|
|
517
|
+
method: entry.method,
|
|
518
|
+
pathFingerprint: entry.pathFingerprint,
|
|
519
|
+
operationId: entry.operationId,
|
|
520
|
+
status: entry.status,
|
|
521
|
+
journalReference: entry.id
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
for (const service of baseline.services) {
|
|
526
|
+
const d = diagnostics[service];
|
|
527
|
+
if (!d)
|
|
528
|
+
throw new Error(`missing assertion diagnostics for ${service}`);
|
|
529
|
+
if (d.activeRequests + d.activeConnections + d.blockedCommands + d.pendingWebhooks + (d.activeJobs ?? 0) > 0 || !options.allowCheckpointablePending && d.pendingJobs > 0)
|
|
530
|
+
failures.push({ kind: "leftover_work", service, diagnostics: d });
|
|
531
|
+
}
|
|
532
|
+
return {
|
|
533
|
+
format: "mockingbird.assertions/v1",
|
|
534
|
+
clean: failures.length === 0,
|
|
535
|
+
namespace,
|
|
536
|
+
baseline: id,
|
|
537
|
+
failures: failures.slice(0, 100),
|
|
538
|
+
truncated: failures.length > 100,
|
|
539
|
+
inspectedThrough: this.sequence
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
startTrace(namespace, input, includeBodies = false, limitations = []) {
|
|
543
|
+
const baseline = validateArchive(input);
|
|
544
|
+
if (!baseline.namespaces[namespace])
|
|
545
|
+
throw new Error("trace baseline lacks selected namespace");
|
|
546
|
+
if (Buffer.byteLength(JSON.stringify(baseline)) > 8 * 1024 * 1024)
|
|
547
|
+
throw new Error("trace baseline exceeds 8 MiB limit");
|
|
548
|
+
if (this.traces.size >= 4 && !this.traces.has(namespace))
|
|
549
|
+
throw new Error("trace capacity reached");
|
|
550
|
+
const artifact = {
|
|
551
|
+
format: "mockingbird.trace/v1",
|
|
552
|
+
sourceProcess: this.processId,
|
|
553
|
+
namespace,
|
|
554
|
+
baseline: structuredClone(baseline),
|
|
555
|
+
events: [],
|
|
556
|
+
limitations: [...limitations],
|
|
557
|
+
truncated: false,
|
|
558
|
+
active: true
|
|
559
|
+
};
|
|
560
|
+
this.traces.set(namespace, { artifact, includeBodies, bytes: 0, inFlight: 0, next: 0 });
|
|
561
|
+
return structuredClone(artifact);
|
|
562
|
+
}
|
|
563
|
+
limitation(artifact, limitation) {
|
|
564
|
+
if (!artifact.limitations.includes(limitation))
|
|
565
|
+
artifact.limitations.push(limitation);
|
|
566
|
+
}
|
|
567
|
+
beginHTTP(namespace, service, request, logicalPath) {
|
|
568
|
+
const trace = this.traces.get(namespace);
|
|
569
|
+
if (!trace?.artifact.active)
|
|
570
|
+
return void 0;
|
|
571
|
+
const url = new URL(request.url), omitted = [];
|
|
572
|
+
if (logicalPath)
|
|
573
|
+
url.pathname = logicalPath;
|
|
574
|
+
for (const key of [...url.searchParams.keys()])
|
|
575
|
+
if (/(token|key|password|secret|signature|credential)/i.test(key)) {
|
|
576
|
+
url.searchParams.set(key, "[redacted]");
|
|
577
|
+
omitted.push("sensitive query fields redacted");
|
|
578
|
+
}
|
|
579
|
+
if ([...request.headers.keys()].some((h) => /authorization|api-key|token|secret|cookie/i.test(h)))
|
|
580
|
+
omitted.push("credential headers require explicit replay bindings");
|
|
581
|
+
const event = {
|
|
582
|
+
sequence: ++trace.next,
|
|
583
|
+
kind: "http",
|
|
584
|
+
service,
|
|
585
|
+
method: request.method,
|
|
586
|
+
path: `${url.pathname}${url.search}`,
|
|
587
|
+
contentType: request.headers.get("content-type") ?? "",
|
|
588
|
+
omitted
|
|
589
|
+
};
|
|
590
|
+
if (trace.inFlight++)
|
|
591
|
+
this.limitation(trace.artifact, "concurrent interactions are not certified for serial replay");
|
|
592
|
+
let body = Promise.resolve({ omitted: [] });
|
|
593
|
+
if (request.body) {
|
|
594
|
+
if (!trace.includeBodies)
|
|
595
|
+
body = Promise.resolve({ omitted: ["request body omitted"] });
|
|
596
|
+
else {
|
|
597
|
+
body = (async () => {
|
|
598
|
+
let timeout;
|
|
599
|
+
try {
|
|
600
|
+
let text = await Promise.race([
|
|
601
|
+
boundedText(request.clone().body, 65536),
|
|
602
|
+
new Promise((_, reject) => {
|
|
603
|
+
timeout = setTimeout(() => reject(new Error("capture deadline")), 100);
|
|
604
|
+
})
|
|
605
|
+
]);
|
|
606
|
+
const removed = [];
|
|
607
|
+
if (event.contentType?.includes("json")) {
|
|
608
|
+
text = JSON.stringify(JSON.parse(text), (key, value) => {
|
|
609
|
+
if (/(token|password|secret|credential|authorization|api.?key)/i.test(key)) {
|
|
610
|
+
removed.push("sensitive JSON body fields redacted");
|
|
611
|
+
return "[redacted]";
|
|
612
|
+
}
|
|
613
|
+
return value;
|
|
614
|
+
});
|
|
615
|
+
} else if (event.contentType?.includes("x-www-form-urlencoded")) {
|
|
616
|
+
const form = new URLSearchParams(text);
|
|
617
|
+
for (const key of [...form.keys()])
|
|
618
|
+
if (/(token|password|secret|credential|api.?key)/i.test(key)) {
|
|
619
|
+
form.set(key, "[redacted]");
|
|
620
|
+
removed.push("sensitive form fields redacted");
|
|
621
|
+
}
|
|
622
|
+
text = form.toString();
|
|
623
|
+
}
|
|
624
|
+
return { text, omitted: removed };
|
|
625
|
+
} catch {
|
|
626
|
+
return { omitted: ["request body capture truncated or unavailable"] };
|
|
627
|
+
} finally {
|
|
628
|
+
clearTimeout(timeout);
|
|
629
|
+
}
|
|
630
|
+
})();
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
return { artifact: trace.artifact, event, body };
|
|
634
|
+
}
|
|
635
|
+
async finishHTTP(token, response) {
|
|
636
|
+
if (!token)
|
|
637
|
+
return;
|
|
638
|
+
const trace = this.traces.get(token.artifact.namespace);
|
|
639
|
+
if (!trace || trace.artifact !== token.artifact)
|
|
640
|
+
return;
|
|
641
|
+
const captured = await token.body;
|
|
642
|
+
token.event.status = response.status;
|
|
643
|
+
token.event.omitted.push(...captured.omitted);
|
|
644
|
+
if (captured.text !== void 0)
|
|
645
|
+
token.event.body = captured.text;
|
|
646
|
+
if (response.headers.get("content-type")?.includes("text/event-stream"))
|
|
647
|
+
token.event.omitted.push("streaming responses are unsupported");
|
|
648
|
+
else {
|
|
649
|
+
try {
|
|
650
|
+
const text = await boundedText(response.clone().body, 65536);
|
|
651
|
+
token.event.responseHash = hash(text);
|
|
652
|
+
} catch {
|
|
653
|
+
token.event.omitted.push("response hash unavailable or truncated");
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
trace.inFlight--;
|
|
657
|
+
for (const omitted of token.event.omitted)
|
|
658
|
+
this.limitation(trace.artifact, omitted);
|
|
659
|
+
this.append(trace, token.event);
|
|
660
|
+
}
|
|
661
|
+
append(trace, event) {
|
|
662
|
+
const bytes = Buffer.byteLength(JSON.stringify(event));
|
|
663
|
+
if (trace.artifact.events.length >= this.limits.traceEvents || trace.bytes + bytes > this.limits.traceBytes) {
|
|
664
|
+
trace.artifact.truncated = true;
|
|
665
|
+
trace.artifact.active = false;
|
|
666
|
+
this.limitation(trace.artifact, "recording limits reached");
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
trace.bytes += bytes;
|
|
670
|
+
trace.artifact.events.push(event);
|
|
671
|
+
trace.artifact.events.sort((a, b) => a.sequence - b.sequence);
|
|
672
|
+
}
|
|
673
|
+
unsupportedControl(namespace, action) {
|
|
674
|
+
const trace = this.traces.get(namespace);
|
|
675
|
+
if (trace?.artifact.active)
|
|
676
|
+
this.limitation(trace.artifact, `control not replayable: ${action}`);
|
|
677
|
+
}
|
|
678
|
+
control(namespace, action, controls) {
|
|
679
|
+
const trace = this.traces.get(namespace);
|
|
680
|
+
if (trace?.artifact.active)
|
|
681
|
+
this.append(trace, {
|
|
682
|
+
sequence: ++trace.next,
|
|
683
|
+
kind: "control",
|
|
684
|
+
action,
|
|
685
|
+
controls: structuredClone(controls),
|
|
686
|
+
omitted: []
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
trace(namespace, stop = false) {
|
|
690
|
+
const trace = this.traces.get(namespace);
|
|
691
|
+
if (!trace)
|
|
692
|
+
throw new Error("trace not started");
|
|
693
|
+
if (stop)
|
|
694
|
+
trace.artifact.active = false;
|
|
695
|
+
if (trace.inFlight)
|
|
696
|
+
this.limitation(trace.artifact, "requests still in flight when inspected");
|
|
697
|
+
return structuredClone(trace.artifact);
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
|
|
701
|
+
// ../../adapters/node/dist/fleet-proxy.js
|
|
702
|
+
var ingressSupport = {
|
|
703
|
+
stripe: {
|
|
704
|
+
publicOrigin: true,
|
|
705
|
+
pathPrefix: true,
|
|
706
|
+
namespaces: "path-or-header",
|
|
707
|
+
streaming: true,
|
|
708
|
+
signing: "vendor request signing is not used; webhook signatures remain payload based"
|
|
709
|
+
},
|
|
710
|
+
other: {
|
|
711
|
+
publicOrigin: false,
|
|
712
|
+
reason: "host/path-sensitive signing and hosted URL rewriting are not certified; use a direct endpoint"
|
|
713
|
+
}
|
|
714
|
+
};
|
|
715
|
+
function advertisedHttpBase(entry) {
|
|
716
|
+
if (entry.publicPath !== void 0 && !entry.publicOrigin)
|
|
717
|
+
throw new Error("publicPath requires publicOrigin");
|
|
718
|
+
if (!entry.publicOrigin)
|
|
719
|
+
return void 0;
|
|
720
|
+
const url = new URL(entry.publicOrigin);
|
|
721
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.pathname !== "/" || url.search || url.hash)
|
|
722
|
+
throw new Error("publicOrigin must be an HTTP(S) origin without credentials or a path");
|
|
723
|
+
const prefix = entry.publicPath ?? "";
|
|
724
|
+
if (prefix && (!/^\/(?:[A-Za-z0-9_-]+\/?)*$/.test(prefix) || prefix.endsWith("/")))
|
|
725
|
+
throw new Error("publicPath must be a canonical path prefix without a trailing slash");
|
|
726
|
+
return `${url.origin}${prefix}`;
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// ../../adapters/node/dist/fleet-time.js
|
|
730
|
+
var FleetTimeController = class {
|
|
731
|
+
context;
|
|
732
|
+
constructor(context) {
|
|
733
|
+
this.context = context;
|
|
734
|
+
}
|
|
735
|
+
async run(namespace, selected, body, single) {
|
|
736
|
+
const condition = body.condition ?? "no-events", maxEvents = single ? 1 : body.maxEvents ?? 100, maxAdvanceMs = body.maxAdvanceMs ?? 864e5, timeoutMs = body.timeoutMs ?? 5e3;
|
|
737
|
+
if (!["no-events", "idle", "checkpoint-ready"].includes(String(condition)) || typeof maxEvents !== "number" || !Number.isSafeInteger(maxEvents) || maxEvents < 1 || maxEvents > 1e4 || typeof maxAdvanceMs !== "number" || !Number.isFinite(maxAdvanceMs) || maxAdvanceMs < 0 || typeof timeoutMs !== "number" || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 3e4)
|
|
738
|
+
throw new Error("invalid bounded time-control condition or budgets");
|
|
739
|
+
const unsupported = [...selected].filter(([, child]) => !child.nextEvent).map(([name]) => name);
|
|
740
|
+
if (unsupported.length)
|
|
741
|
+
throw new Error(`next-event inspection unsupported for ${unsupported.join(", ")}`);
|
|
742
|
+
const clocks = [...selected.values()].map((child) => child.clock(namespace).state());
|
|
743
|
+
if (clocks.some((clock) => !clock.frozen || clock.now !== clocks[0]?.now))
|
|
744
|
+
throw new Error("freeze and align selected participant clocks before event stepping");
|
|
745
|
+
const start2 = clocks[0]?.now ?? this.context.clock(namespace).now(), deadline = Date.now() + timeoutMs;
|
|
746
|
+
const steps = [];
|
|
747
|
+
const diagnostics = () => Object.fromEntries([...selected].map(([name, child]) => [name, child.diagnostics(namespace)]));
|
|
748
|
+
const bounded = async (promise) => {
|
|
749
|
+
let timer;
|
|
750
|
+
try {
|
|
751
|
+
return await Promise.race([
|
|
752
|
+
promise,
|
|
753
|
+
new Promise((_, reject) => {
|
|
754
|
+
timer = setTimeout(() => reject(Object.assign(new Error("time-control host budget exceeded; recovery may be required"), { code: "MOCKINGBIRD_WORKLOAD_UNCERTAIN" })), Math.max(1, deadline - Date.now()));
|
|
755
|
+
})
|
|
756
|
+
]);
|
|
757
|
+
} finally {
|
|
758
|
+
clearTimeout(timer);
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
for (; ; ) {
|
|
762
|
+
const due = await bounded(Promise.all([...selected].map(async ([name, child]) => [name, await child.nextEvent?.(namespace)])));
|
|
763
|
+
if (due.some(([, time]) => time !== void 0 && !Number.isFinite(time)))
|
|
764
|
+
throw new Error("participant returned an invalid event time");
|
|
765
|
+
const services = diagnostics(), states = Object.values(services);
|
|
766
|
+
const ready = condition === "checkpoint-ready" ? states.every((d) => d.activeRequests + d.blockedCommands + d.pendingWebhooks + (d.activeJobs ?? 0) === 0) : condition === "idle" ? states.every((d) => d.activeRequests + d.blockedCommands + d.pendingWebhooks + d.pendingJobs === 0) : due.every(([, time]) => time === void 0);
|
|
767
|
+
if (!single && ready)
|
|
768
|
+
return Response.json({ status: "settled", namespace, condition, steps, services });
|
|
769
|
+
const times = due.flatMap(([, time]) => time === void 0 ? [] : [time]);
|
|
770
|
+
if (!times.length)
|
|
771
|
+
return Response.json({
|
|
772
|
+
status: "no-events",
|
|
773
|
+
namespace,
|
|
774
|
+
condition,
|
|
775
|
+
settled: ready,
|
|
776
|
+
steps,
|
|
777
|
+
services
|
|
778
|
+
});
|
|
779
|
+
const current = [...selected.values()][0]?.clock(namespace).now() ?? start2, target = Math.max(current, Math.min(...times));
|
|
780
|
+
if (Date.now() >= deadline || steps.length >= maxEvents || target - start2 > maxAdvanceMs)
|
|
781
|
+
return Response.json({ status: "budget-exhausted", namespace, condition, steps, services }, { status: 409 });
|
|
782
|
+
const signal = AbortSignal.timeout(Math.max(1, deadline - Date.now()));
|
|
783
|
+
const response = await this.context.transaction(namespace, selected, async (_name, child) => {
|
|
784
|
+
child.clock(namespace).set(target);
|
|
785
|
+
if (child.settle)
|
|
786
|
+
await bounded(child.settle(namespace, signal));
|
|
787
|
+
});
|
|
788
|
+
if (!response.ok)
|
|
789
|
+
return response;
|
|
790
|
+
this.context.clock(namespace).freeze();
|
|
791
|
+
this.context.clock(namespace).set(target);
|
|
792
|
+
try {
|
|
793
|
+
if (this.context.synchronize)
|
|
794
|
+
await bounded(this.context.synchronize({
|
|
795
|
+
namespace,
|
|
796
|
+
services: [...selected.keys()],
|
|
797
|
+
now: target,
|
|
798
|
+
signal
|
|
799
|
+
}));
|
|
800
|
+
} catch (error) {
|
|
801
|
+
const fences = [];
|
|
802
|
+
for (const child of selected.values())
|
|
803
|
+
try {
|
|
804
|
+
fences.push(child.lock(namespace));
|
|
805
|
+
} catch {
|
|
806
|
+
}
|
|
807
|
+
this.context.recovery.set(namespace, fences);
|
|
808
|
+
throw error;
|
|
809
|
+
}
|
|
810
|
+
const processed = due.filter(([, time]) => time !== void 0 && time <= target).map(([name]) => name);
|
|
811
|
+
steps.push({ now: target, processed });
|
|
812
|
+
this.context.phase(namespace, "stepping", steps.length, steps.length);
|
|
813
|
+
if (single)
|
|
814
|
+
return Response.json({
|
|
815
|
+
status: "stepped",
|
|
816
|
+
namespace,
|
|
817
|
+
steps,
|
|
818
|
+
services: diagnostics(),
|
|
819
|
+
clientClockSynchronization: this.context.synchronize ? "hook-invoked" : "external worker clocks are unchanged"
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
};
|
|
824
|
+
|
|
825
|
+
// ../../adapters/node/dist/fleet-management.js
|
|
826
|
+
var object2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
827
|
+
var fleetError = (status, message, extra = {}) => Response.json({
|
|
828
|
+
...extra,
|
|
829
|
+
error: {
|
|
830
|
+
type: "mockingbird_admin",
|
|
831
|
+
code: {
|
|
832
|
+
400: "invalid_request",
|
|
833
|
+
401: "unauthorized",
|
|
834
|
+
403: "forbidden",
|
|
835
|
+
404: "not_found",
|
|
836
|
+
409: "conflict",
|
|
837
|
+
413: "too_large",
|
|
838
|
+
429: "quota_exceeded",
|
|
839
|
+
500: "operation_failed",
|
|
840
|
+
503: "unavailable"
|
|
841
|
+
}[status] ?? "request_failed",
|
|
842
|
+
message
|
|
843
|
+
}
|
|
844
|
+
}, { status });
|
|
845
|
+
var checked = (body, keys) => {
|
|
846
|
+
const unknown = Object.keys(body).filter((k) => !keys.includes(k));
|
|
847
|
+
if (unknown.length)
|
|
848
|
+
throw new Error(`unknown fields: ${unknown.join(", ")}`);
|
|
849
|
+
};
|
|
850
|
+
var namePattern = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
851
|
+
var FleetManagement = class {
|
|
852
|
+
ctx;
|
|
853
|
+
operationContext = new AsyncLocalStorage();
|
|
854
|
+
interrupted = /* @__PURE__ */ new Map();
|
|
855
|
+
durable = /* @__PURE__ */ new Map();
|
|
856
|
+
async recoverOperations() {
|
|
857
|
+
if (!this.ctx.options.journal)
|
|
858
|
+
return;
|
|
859
|
+
if (!this.ctx.options.repository)
|
|
860
|
+
throw new Error("durable journal requires a portable archive repository");
|
|
861
|
+
let records;
|
|
862
|
+
try {
|
|
863
|
+
records = await this.ctx.options.journal.load();
|
|
864
|
+
} catch {
|
|
865
|
+
throw new Error("durable operation journal unavailable");
|
|
866
|
+
}
|
|
867
|
+
for (const record of records) {
|
|
868
|
+
const decision = await reconcileOperation(record, this.ctx.options.repository);
|
|
869
|
+
if (decision.status === "terminal")
|
|
870
|
+
continue;
|
|
871
|
+
if (decision.status === "abandoned-before-commit" || decision.status === "verified-publication") {
|
|
872
|
+
if (decision.status === "verified-publication")
|
|
873
|
+
await this.restoreArchive(await this.ctx.options.repository.get(decision.archive));
|
|
874
|
+
await this.ctx.options.journal.write({
|
|
875
|
+
...record,
|
|
876
|
+
revision: record.revision + 1,
|
|
877
|
+
phase: "resolved",
|
|
878
|
+
resolution: decision.status,
|
|
879
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
880
|
+
});
|
|
881
|
+
continue;
|
|
882
|
+
}
|
|
883
|
+
this.interrupted.set(record.operationId, record);
|
|
884
|
+
for (const namespace of record.scope) {
|
|
885
|
+
if (!this.namespaces.has(namespace)) {
|
|
886
|
+
const result = await this.createNamespace(namespace);
|
|
887
|
+
if (!result.ok)
|
|
888
|
+
throw new Error("cannot prepare interrupted namespace for recovery");
|
|
889
|
+
}
|
|
890
|
+
if (this.ctx.recovery.has(namespace))
|
|
891
|
+
continue;
|
|
892
|
+
const releases = [];
|
|
893
|
+
for (const child of this.ctx.children.values())
|
|
894
|
+
try {
|
|
895
|
+
releases.push(child.lock(namespace));
|
|
896
|
+
} catch {
|
|
897
|
+
}
|
|
898
|
+
this.ctx.recovery.set(namespace, releases);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
fenceNamespaces(scope) {
|
|
903
|
+
for (const namespace of scope) {
|
|
904
|
+
const releases = this.ctx.recovery.get(namespace) ?? [];
|
|
905
|
+
for (const child of this.ctx.children.values())
|
|
906
|
+
try {
|
|
907
|
+
releases.push(child.lock(namespace));
|
|
908
|
+
} catch {
|
|
909
|
+
}
|
|
910
|
+
this.ctx.recovery.set(namespace, releases);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
async journalPhase(operationId, phase, extra = {}) {
|
|
914
|
+
const current = this.durable.get(operationId);
|
|
915
|
+
if (!current || !this.ctx.options.journal)
|
|
916
|
+
return;
|
|
917
|
+
const next = {
|
|
918
|
+
...current,
|
|
919
|
+
...extra,
|
|
920
|
+
revision: current.revision + 1,
|
|
921
|
+
phase,
|
|
922
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
923
|
+
};
|
|
924
|
+
await this.ctx.options.journal.write(next);
|
|
925
|
+
this.durable.set(operationId, next);
|
|
926
|
+
}
|
|
927
|
+
observations;
|
|
928
|
+
requestPath(service, request) {
|
|
929
|
+
const prefix = this.ctx.config.services[service]?.adminPrefix ?? this.ctx.config.adminPrefix ?? "/__admin";
|
|
930
|
+
let path = new URL(request.url).pathname;
|
|
931
|
+
if (path.startsWith(`${prefix}/ns/`)) {
|
|
932
|
+
const tail = path.slice(`${prefix}/ns/`.length), slash = tail.indexOf("/");
|
|
933
|
+
path = slash < 0 ? "/" : tail.slice(slash);
|
|
934
|
+
}
|
|
935
|
+
return { path, admin: path === prefix || path.startsWith(`${prefix}/`) };
|
|
936
|
+
}
|
|
937
|
+
beginRequest(service, namespace, request) {
|
|
938
|
+
const route = this.requestPath(service, request);
|
|
939
|
+
return route.admin ? void 0 : this.observations.beginHTTP(namespace, service, request, route.path);
|
|
940
|
+
}
|
|
941
|
+
async finishRequest(service, namespace, _request, response, log, token) {
|
|
942
|
+
if (this.requestPath(service, _request).admin)
|
|
943
|
+
return;
|
|
944
|
+
const pathFingerprint = createHash3("sha256").update(log.path).digest("hex");
|
|
945
|
+
this.observations.record({
|
|
946
|
+
namespace,
|
|
947
|
+
service,
|
|
948
|
+
kind: "http",
|
|
949
|
+
method: log.method,
|
|
950
|
+
pathFingerprint,
|
|
951
|
+
status: log.status,
|
|
952
|
+
unmatched: log.unmatched,
|
|
953
|
+
fault: log.faultId !== void 0,
|
|
954
|
+
...log.operationId ? { operationId: log.operationId } : {}
|
|
955
|
+
});
|
|
956
|
+
await this.observations.finishHTTP(token, response);
|
|
957
|
+
}
|
|
958
|
+
observeDelivery(service, event) {
|
|
959
|
+
this.observations.record({
|
|
960
|
+
namespace: event.namespace,
|
|
961
|
+
service,
|
|
962
|
+
kind: "webhook",
|
|
963
|
+
deliveryState: event.state
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
instrumentation;
|
|
967
|
+
initializationToken = randomBytes(32).toString("base64url");
|
|
968
|
+
environmentContext = new AsyncLocalStorage();
|
|
969
|
+
environment;
|
|
970
|
+
ownsEnvironment() {
|
|
971
|
+
return this.environment !== void 0 && this.environmentContext.getStore() === this.environment.id;
|
|
972
|
+
}
|
|
973
|
+
topologyBusy(namespace) {
|
|
974
|
+
return this.topology.has(namespace) || this.environment !== void 0 && !this.ownsEnvironment();
|
|
975
|
+
}
|
|
976
|
+
environmentFence(namespace, service) {
|
|
977
|
+
return this.ownsEnvironment() && this.environment?.fences.get(namespace)?.has(service) === true;
|
|
978
|
+
}
|
|
979
|
+
checkCancelled(namespace) {
|
|
980
|
+
const id = this.operationId(namespace);
|
|
981
|
+
if (id && this.aborts.get(id)?.signal.aborted)
|
|
982
|
+
throw new Error("operation cancelled before commit");
|
|
983
|
+
}
|
|
984
|
+
activeOperation(namespace) {
|
|
985
|
+
const current = this.operationContext.getStore();
|
|
986
|
+
return current?.status === "running" ? current : [...this.operations.values()].find((operation) => operation.namespace === namespace && operation.status === "running");
|
|
987
|
+
}
|
|
988
|
+
operationId(namespace) {
|
|
989
|
+
return this.activeOperation(namespace)?.id;
|
|
990
|
+
}
|
|
991
|
+
async withEnvironment(namespaces, selected, run) {
|
|
992
|
+
if (this.ownsEnvironment())
|
|
993
|
+
return run();
|
|
994
|
+
if (this.environment || this.ctx.controlling.size || this.topology.size)
|
|
995
|
+
throw new Error("environment operation conflicts with active namespace work");
|
|
996
|
+
const env = { id: randomUUID3(), fences: /* @__PURE__ */ new Map() };
|
|
997
|
+
this.environment = env;
|
|
998
|
+
return this.environmentContext.run(env.id, async () => {
|
|
999
|
+
try {
|
|
1000
|
+
for (const ns of namespaces) {
|
|
1001
|
+
if (!this.namespaces.has(ns))
|
|
1002
|
+
continue;
|
|
1003
|
+
await this.hook("prepare", ns, selected);
|
|
1004
|
+
const fences = /* @__PURE__ */ new Map();
|
|
1005
|
+
env.fences.set(ns, fences);
|
|
1006
|
+
for (const [name, child] of selected) {
|
|
1007
|
+
if (child.protocol !== "http" && !Object.hasOwn(child.namespaces.endpoints ?? {}, ns))
|
|
1008
|
+
continue;
|
|
1009
|
+
if (this.ctx.recovery.has(ns))
|
|
1010
|
+
continue;
|
|
1011
|
+
fences.set(name, child.lock(ns));
|
|
1012
|
+
}
|
|
1013
|
+
if (this.busy(ns, selected).length)
|
|
1014
|
+
throw new Error(`namespace ${ns} is not quiescent`);
|
|
1015
|
+
}
|
|
1016
|
+
return await run();
|
|
1017
|
+
} finally {
|
|
1018
|
+
for (const [ns, fences] of env.fences) {
|
|
1019
|
+
if (this.ctx.recovery.has(ns))
|
|
1020
|
+
this.ctx.recovery.get(ns)?.push(...fences.values());
|
|
1021
|
+
else
|
|
1022
|
+
for (const unlock of [...fences.values()].reverse())
|
|
1023
|
+
unlock();
|
|
1024
|
+
}
|
|
1025
|
+
this.environment = void 0;
|
|
1026
|
+
}
|
|
1027
|
+
});
|
|
1028
|
+
}
|
|
1029
|
+
operations = /* @__PURE__ */ new Map();
|
|
1030
|
+
namespaces = /* @__PURE__ */ new Map();
|
|
1031
|
+
credentials = /* @__PURE__ */ new Map();
|
|
1032
|
+
retries = /* @__PURE__ */ new Map();
|
|
1033
|
+
events = [];
|
|
1034
|
+
subscribers = /* @__PURE__ */ new Set();
|
|
1035
|
+
aborts = /* @__PURE__ */ new Map();
|
|
1036
|
+
topology = /* @__PURE__ */ new Set();
|
|
1037
|
+
privateRequests = /* @__PURE__ */ new Map();
|
|
1038
|
+
privateRequest(namespace, request) {
|
|
1039
|
+
const token = request.headers.get("x-mockingbird-initializer");
|
|
1040
|
+
return token !== null && (this.privateRequests.get(namespace) === token || this.lifecycle === "initializing" && token === this.initializationToken);
|
|
1041
|
+
}
|
|
1042
|
+
sequence = 0;
|
|
1043
|
+
timer;
|
|
1044
|
+
expiryTimer;
|
|
1045
|
+
backupRunning = false;
|
|
1046
|
+
backupStatus = {};
|
|
1047
|
+
lifecycle = "starting";
|
|
1048
|
+
constructor(ctx) {
|
|
1049
|
+
this.ctx = ctx;
|
|
1050
|
+
this.instrumentation = new FleetInstrumentation(ctx.options);
|
|
1051
|
+
this.observations = new FleetObservations(ctx.id);
|
|
1052
|
+
this.remember("default");
|
|
1053
|
+
for (const child of ctx.children.values())
|
|
1054
|
+
for (const ns of Object.keys(child.namespaces.endpoints ?? {}))
|
|
1055
|
+
this.remember(ns);
|
|
1056
|
+
for (const value of Object.values(ctx.options.limits ?? {}))
|
|
1057
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
1058
|
+
throw new Error("limits must be nonnegative integers");
|
|
1059
|
+
for (const child of ctx.children.values())
|
|
1060
|
+
child.setAdmission?.((namespace) => {
|
|
1061
|
+
const entry = this.namespaces.get(namespace);
|
|
1062
|
+
if (entry)
|
|
1063
|
+
entry.activityAt = Date.now();
|
|
1064
|
+
if (this.lifecycle === "initializing" || this.lifecycle === "draining" || this.lifecycle === "failed" || this.environment || this.topology.has(namespace) || this.ctx.recovery.has(namespace))
|
|
1065
|
+
return false;
|
|
1066
|
+
const limit = this.ctx.options.limits?.connections;
|
|
1067
|
+
if (limit === void 0)
|
|
1068
|
+
return true;
|
|
1069
|
+
let connections = 0;
|
|
1070
|
+
for (const c of ctx.children.values()) {
|
|
1071
|
+
if (c.protocol !== "http" && !Object.hasOwn(c.namespaces.endpoints ?? {}, namespace))
|
|
1072
|
+
continue;
|
|
1073
|
+
const d = c.diagnostics(namespace);
|
|
1074
|
+
connections += d.activeConnections + (c.protocol === "http" ? d.activeRequests : 0);
|
|
1075
|
+
}
|
|
1076
|
+
return connections < limit;
|
|
1077
|
+
});
|
|
1078
|
+
const retention = ctx.options.retention;
|
|
1079
|
+
if (retention?.maxCount !== void 0 && (!Number.isSafeInteger(retention.maxCount) || retention.maxCount < 1))
|
|
1080
|
+
throw new Error("retention maxCount must be positive");
|
|
1081
|
+
if (retention?.ttlMs !== void 0 && (!Number.isFinite(retention.ttlMs) || retention.ttlMs < 1))
|
|
1082
|
+
throw new Error("retention ttlMs must be positive");
|
|
1083
|
+
}
|
|
1084
|
+
remember(namespace) {
|
|
1085
|
+
if (!this.namespaces.has(namespace))
|
|
1086
|
+
this.namespaces.set(namespace, {
|
|
1087
|
+
generation: randomUUID3(),
|
|
1088
|
+
createdAt: Date.now(),
|
|
1089
|
+
activityAt: Date.now(),
|
|
1090
|
+
pinned: false
|
|
1091
|
+
});
|
|
1092
|
+
return this.namespaces.get(namespace);
|
|
1093
|
+
}
|
|
1094
|
+
generation(namespace) {
|
|
1095
|
+
return this.remember(namespace).generation;
|
|
1096
|
+
}
|
|
1097
|
+
admit(namespace, request) {
|
|
1098
|
+
if (this.privateRequest(namespace, request))
|
|
1099
|
+
return void 0;
|
|
1100
|
+
if (this.topology.has(namespace) || this.environment)
|
|
1101
|
+
return fleetError(409, "namespace lifecycle operation in progress", { namespace });
|
|
1102
|
+
if (this.lifecycle === "initializing" && request.headers.get("x-mockingbird-initializer") === this.initializationToken)
|
|
1103
|
+
return void 0;
|
|
1104
|
+
if (this.lifecycle !== "ready" && this.lifecycle !== "starting")
|
|
1105
|
+
return fleetError(503, `fleet is ${this.lifecycle}`);
|
|
1106
|
+
if (!this.namespaces.has(namespace) && this.ctx.options.limits?.maxNamespaces !== void 0 && this.namespaces.size + this.topology.size >= this.ctx.options.limits.maxNamespaces)
|
|
1107
|
+
return fleetError(429, "maximum namespaces reached");
|
|
1108
|
+
const entry = this.remember(namespace);
|
|
1109
|
+
entry.activityAt = Date.now();
|
|
1110
|
+
const expected = request.headers.get("x-mockingbird-generation");
|
|
1111
|
+
if (!["GET", "HEAD", "OPTIONS"].includes(request.method) && expected !== null && expected !== entry.generation)
|
|
1112
|
+
return fleetError(409, "stale namespace generation", { generation: entry.generation });
|
|
1113
|
+
const limits = this.ctx.options.limits;
|
|
1114
|
+
if (limits)
|
|
1115
|
+
for (const child of this.ctx.children.values()) {
|
|
1116
|
+
if (child.protocol !== "http" && !Object.hasOwn(child.namespaces.endpoints ?? {}, namespace))
|
|
1117
|
+
continue;
|
|
1118
|
+
const usage = child.diagnostics(namespace);
|
|
1119
|
+
if (limits.connections !== void 0 && usage.activeConnections + usage.activeRequests >= limits.connections)
|
|
1120
|
+
return fleetError(429, "namespace admission quota reached", { namespace });
|
|
1121
|
+
}
|
|
1122
|
+
return void 0;
|
|
1123
|
+
}
|
|
1124
|
+
emit(operation) {
|
|
1125
|
+
this.instrumentation.phase(operation, (operation.scope ?? [operation.namespace]).some((namespace) => this.ctx.recovery.has(namespace)));
|
|
1126
|
+
const event = {
|
|
1127
|
+
id: `${this.ctx.id}:${++this.sequence}`,
|
|
1128
|
+
namespace: operation.namespace,
|
|
1129
|
+
operation: structuredClone(operation)
|
|
1130
|
+
};
|
|
1131
|
+
this.events.push(event);
|
|
1132
|
+
if (this.events.length > 500)
|
|
1133
|
+
this.events.shift();
|
|
1134
|
+
for (const sub of this.subscribers)
|
|
1135
|
+
if (sub.namespace === operation.namespace) {
|
|
1136
|
+
const data = sub.member ? {
|
|
1137
|
+
id: event.id,
|
|
1138
|
+
namespace: event.namespace,
|
|
1139
|
+
operation: {
|
|
1140
|
+
id: operation.id,
|
|
1141
|
+
phase: operation.phase,
|
|
1142
|
+
status: operation.status,
|
|
1143
|
+
completed: operation.completed,
|
|
1144
|
+
total: operation.total
|
|
1145
|
+
}
|
|
1146
|
+
} : event;
|
|
1147
|
+
sub.push(`id: ${event.id}
|
|
1148
|
+
event: lifecycle
|
|
1149
|
+
data: ${JSON.stringify(data)}
|
|
1150
|
+
|
|
1151
|
+
`);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
phase(namespace, phase, completed, total, participant) {
|
|
1155
|
+
const operation = this.activeOperation(namespace);
|
|
1156
|
+
if (operation) {
|
|
1157
|
+
operation.phase = phase;
|
|
1158
|
+
if (participant)
|
|
1159
|
+
operation.participant = participant;
|
|
1160
|
+
else
|
|
1161
|
+
delete operation.participant;
|
|
1162
|
+
if (completed !== void 0)
|
|
1163
|
+
operation.completed = completed;
|
|
1164
|
+
if (total !== void 0)
|
|
1165
|
+
operation.total = total;
|
|
1166
|
+
this.emit(operation);
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
prune() {
|
|
1170
|
+
const { maxCount = 50, ttlMs = 24 * 36e5 } = this.ctx.options.retention ?? {};
|
|
1171
|
+
const entries = [...this.ctx.checkpoints];
|
|
1172
|
+
for (const [id, point] of entries)
|
|
1173
|
+
if (Date.now() - Date.parse(point.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()) > ttlMs)
|
|
1174
|
+
this.ctx.checkpoints.delete(id);
|
|
1175
|
+
while (this.ctx.checkpoints.size > maxCount)
|
|
1176
|
+
this.ctx.checkpoints.delete(this.ctx.checkpoints.keys().next().value);
|
|
1177
|
+
}
|
|
1178
|
+
select(body) {
|
|
1179
|
+
if (body.services === void 0)
|
|
1180
|
+
return this.ctx.children;
|
|
1181
|
+
if (!Array.isArray(body.services) || !body.services.length || body.services.some((n) => typeof n !== "string" || !this.ctx.children.has(n)))
|
|
1182
|
+
throw new Error("services must be a nonempty list of configured service names");
|
|
1183
|
+
return new Map(body.services.map((n) => [n, this.ctx.children.get(n)]));
|
|
1184
|
+
}
|
|
1185
|
+
scope(namespace, selected) {
|
|
1186
|
+
for (const [name, child] of selected)
|
|
1187
|
+
if (child.protocol !== "http" && !Object.hasOwn(child.namespaces.endpoints ?? {}, namespace))
|
|
1188
|
+
throw new Error(`namespace ${namespace} is not configured for ${name}`);
|
|
1189
|
+
}
|
|
1190
|
+
capability() {
|
|
1191
|
+
return {
|
|
1192
|
+
version: 1,
|
|
1193
|
+
archiveFormat: "mockingbird.fleet/v1",
|
|
1194
|
+
archiveProtection: this.ctx.options.archiveProtection?.policy ?? { format: "none" },
|
|
1195
|
+
processId: this.ctx.id,
|
|
1196
|
+
authentication: ["admin-key", "scoped-credential"],
|
|
1197
|
+
scopes: ["namespace", "services", "environment"],
|
|
1198
|
+
routes: [
|
|
1199
|
+
["GET", ""],
|
|
1200
|
+
["GET", "/namespaces"],
|
|
1201
|
+
["POST", "/namespaces/{namespace}/fork"],
|
|
1202
|
+
["GET", "/audit"],
|
|
1203
|
+
["GET", "/telemetry"],
|
|
1204
|
+
["GET", "/recovery"],
|
|
1205
|
+
["POST", "/recovery/{id}/rollback"],
|
|
1206
|
+
["POST", "/time/step-next"],
|
|
1207
|
+
["POST", "/time/run-until"],
|
|
1208
|
+
["POST", "/assertions/baseline"],
|
|
1209
|
+
["POST", "/assertions/{id}/check"],
|
|
1210
|
+
["POST", "/trace/start"],
|
|
1211
|
+
["POST", "/trace/stop"],
|
|
1212
|
+
["GET", "/trace"],
|
|
1213
|
+
["POST", "/archives/bindings"],
|
|
1214
|
+
["POST", "/namespaces/{namespace}"],
|
|
1215
|
+
["DELETE", "/namespaces/{namespace}"],
|
|
1216
|
+
["GET", "/namespaces/{namespace}/snapshots"],
|
|
1217
|
+
["POST", "/namespaces/{namespace}/snapshots"],
|
|
1218
|
+
["GET", "/namespaces/{namespace}/snapshots/{id}"],
|
|
1219
|
+
["DELETE", "/namespaces/{namespace}/snapshots/{id}"],
|
|
1220
|
+
["POST", "/namespaces/{namespace}/snapshots/{id}/restore"],
|
|
1221
|
+
["GET", "/metrics"],
|
|
1222
|
+
["GET", "/clock"],
|
|
1223
|
+
["POST", "/clock"],
|
|
1224
|
+
["POST", "/can-checkpoint"],
|
|
1225
|
+
["POST", "/wait-until-idle"],
|
|
1226
|
+
["POST", "/archives/export"],
|
|
1227
|
+
["POST", "/archives/import"],
|
|
1228
|
+
["POST", "/archives/inspect"],
|
|
1229
|
+
["POST", "/archives/diff"],
|
|
1230
|
+
["GET", "/operations"],
|
|
1231
|
+
["GET", "/operations/{id}"],
|
|
1232
|
+
["POST", "/operations/{id}/cancel"],
|
|
1233
|
+
["GET", "/events"],
|
|
1234
|
+
["POST", "/profiles/apply"],
|
|
1235
|
+
["POST", "/profiles/baseline"],
|
|
1236
|
+
["GET", "/scenarios"],
|
|
1237
|
+
["POST", "/scenarios/{name}/apply"],
|
|
1238
|
+
["GET", "/inspect"],
|
|
1239
|
+
["GET", "/diagnostics"],
|
|
1240
|
+
["POST", "/credentials"],
|
|
1241
|
+
["DELETE", "/credentials/{id}"],
|
|
1242
|
+
["POST", "/backups"],
|
|
1243
|
+
["GET", "/backups"],
|
|
1244
|
+
["GET", "/cleanup"],
|
|
1245
|
+
["POST", "/cleanup"],
|
|
1246
|
+
["POST", "/namespaces/{namespace}/policy"]
|
|
1247
|
+
].map(([method, path]) => ({ method, path })),
|
|
1248
|
+
services: Object.fromEntries([...this.ctx.children].map(([name, c]) => [
|
|
1249
|
+
name,
|
|
1250
|
+
{
|
|
1251
|
+
protocol: c.protocol,
|
|
1252
|
+
coverage: c.coverage,
|
|
1253
|
+
ingress: c.targetName === "stripe" ? ingressSupport.stripe : ingressSupport.other,
|
|
1254
|
+
target: c.targetName,
|
|
1255
|
+
outboundPolicy: c.outboundPolicy ?? "unsupported",
|
|
1256
|
+
version: 1,
|
|
1257
|
+
packageVersion: c.packageVersion,
|
|
1258
|
+
nextEvent: Boolean(c.nextEvent),
|
|
1259
|
+
externalWorkerClock: "requires explicit harness synchronization",
|
|
1260
|
+
checkpoint: true,
|
|
1261
|
+
portable: Boolean(c.exportCheckpoint && c.importCheckpoint),
|
|
1262
|
+
provisioning: Boolean(c.createNamespace && c.deleteNamespace),
|
|
1263
|
+
inspect: Boolean(c.inspect),
|
|
1264
|
+
controls: c.protocol === "http" ? ["clock", "faults", "latency", "seed"] : ["clock"],
|
|
1265
|
+
stalePrecondition: c.protocol === "http"
|
|
1266
|
+
}
|
|
1267
|
+
])),
|
|
1268
|
+
limits: {
|
|
1269
|
+
usage: {
|
|
1270
|
+
namespaces: this.namespaces.size,
|
|
1271
|
+
listeners: [...this.ctx.children.values()].reduce((n, c) => n + (c.protocol === "http" ? 1 : Object.keys(c.namespaces.endpoints ?? {}).length), 1)
|
|
1272
|
+
},
|
|
1273
|
+
headroom: {
|
|
1274
|
+
namespaces: this.ctx.options.limits?.maxNamespaces === void 0 ? null : this.ctx.options.limits.maxNamespaces - this.namespaces.size
|
|
1275
|
+
},
|
|
1276
|
+
checkpoints: this.ctx.options.retention?.maxCount ?? 50,
|
|
1277
|
+
eventHistory: 500,
|
|
1278
|
+
operationHistory: 200,
|
|
1279
|
+
idempotencyMs: 36e5,
|
|
1280
|
+
supportedBudgets: ["maxNamespaces", "maxListeners", "connections"],
|
|
1281
|
+
unsupportedBudgets: ["objectBytes", "records", "pendingJobs"],
|
|
1282
|
+
...this.ctx.options.limits
|
|
1283
|
+
}
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
action(path, method) {
|
|
1287
|
+
if (["GET", "HEAD"].includes(method))
|
|
1288
|
+
return "read";
|
|
1289
|
+
if (/\/credentials/.test(path))
|
|
1290
|
+
return "credentials";
|
|
1291
|
+
if (/\/reset$/.test(path))
|
|
1292
|
+
return "reset";
|
|
1293
|
+
if (/\/restore$/.test(path) || path.endsWith("/archives/import"))
|
|
1294
|
+
return "restore";
|
|
1295
|
+
if (/\/snapshots/.test(path) || path.endsWith("/archives/export"))
|
|
1296
|
+
return "snapshot";
|
|
1297
|
+
if (/\/namespaces\/[^/]+$/.test(path))
|
|
1298
|
+
return "namespace";
|
|
1299
|
+
return "control";
|
|
1300
|
+
}
|
|
1301
|
+
auth(request, namespace, action, path) {
|
|
1302
|
+
const key = request.headers.get("x-mockingbird-admin-key");
|
|
1303
|
+
const adminKey = this.ctx.config.adminKey ?? process.env.MOCKINGBIRD_ADMIN_KEY;
|
|
1304
|
+
if (key !== null && (adminKey === void 0 || key !== adminKey)) {
|
|
1305
|
+
const credential = this.credentials.get(digest(key));
|
|
1306
|
+
if (credential && credential.expiresAt > Date.now()) {
|
|
1307
|
+
if (!credential.namespaces.includes(namespace) || !credential.actions.includes(action) || /\/(credentials|cleanup|backups)(\/|$)/.test(path) || ["/fleet", "/fleet/namespaces"].includes(path) || path === "/fleet/archives/import" || path === "/fleet/archives/export")
|
|
1308
|
+
return fleetError(403, "credential does not permit this scope or action");
|
|
1309
|
+
return credential.id;
|
|
1310
|
+
}
|
|
1311
|
+
return fleetError(401, "invalid or expired credential");
|
|
1312
|
+
}
|
|
1313
|
+
if (adminKey !== void 0 && key !== adminKey)
|
|
1314
|
+
return fleetError(401, "admin key required");
|
|
1315
|
+
return "admin";
|
|
1316
|
+
}
|
|
1317
|
+
async dispatch(request, fallback) {
|
|
1318
|
+
const cors = this.ctx.options.cors;
|
|
1319
|
+
const url = new URL(request.url), prefix = this.ctx.config.adminPrefix ?? "/__admin";
|
|
1320
|
+
const controlled = url.pathname === `${prefix}/fleet` || url.pathname.startsWith(`${prefix}/fleet/`) || url.pathname === `${prefix}/ui`;
|
|
1321
|
+
const origin = request.headers.get("origin");
|
|
1322
|
+
const allowed = controlled && cors !== void 0 && origin !== null && cors.origins.includes(origin);
|
|
1323
|
+
const methods = cors?.methods ?? ["GET", "POST", "DELETE", "OPTIONS"];
|
|
1324
|
+
const headers = cors?.headers ?? [
|
|
1325
|
+
"content-type",
|
|
1326
|
+
"x-mockingbird-admin-key",
|
|
1327
|
+
"x-mockingbird-namespace",
|
|
1328
|
+
"idempotency-key",
|
|
1329
|
+
"last-event-id"
|
|
1330
|
+
];
|
|
1331
|
+
if (controlled && cors && request.method === "OPTIONS" && origin !== null) {
|
|
1332
|
+
const method = request.headers.get("access-control-request-method");
|
|
1333
|
+
const requested = (request.headers.get("access-control-request-headers") ?? "").split(",").map((h) => h.trim().toLowerCase()).filter(Boolean);
|
|
1334
|
+
if (!allowed || !method || !methods.includes(method) || requested.some((h) => !headers.map((v) => v.toLowerCase()).includes(h)))
|
|
1335
|
+
return fleetError(403, "CORS preflight denied");
|
|
1336
|
+
return new Response(null, {
|
|
1337
|
+
status: 204,
|
|
1338
|
+
headers: {
|
|
1339
|
+
"access-control-allow-origin": origin,
|
|
1340
|
+
"access-control-allow-methods": methods.join(", "),
|
|
1341
|
+
"access-control-allow-headers": headers.join(", "),
|
|
1342
|
+
vary: "Origin, Access-Control-Request-Method, Access-Control-Request-Headers"
|
|
1343
|
+
}
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
const response = await this.dispatchControl(request, fallback);
|
|
1347
|
+
if (controlled && cors) {
|
|
1348
|
+
response.headers.append("vary", "Origin");
|
|
1349
|
+
if (allowed && origin)
|
|
1350
|
+
response.headers.set("access-control-allow-origin", origin);
|
|
1351
|
+
}
|
|
1352
|
+
return response;
|
|
1353
|
+
}
|
|
1354
|
+
async dispatchControl(request, fallback) {
|
|
1355
|
+
const url = new URL(request.url), prefix = this.ctx.config.adminPrefix ?? "/__admin";
|
|
1356
|
+
if (!url.pathname.startsWith(`${prefix}/`) && url.pathname !== prefix)
|
|
1357
|
+
return fallback();
|
|
1358
|
+
const path = url.pathname.slice(prefix.length).replace(/\/$/, "");
|
|
1359
|
+
if (path === "/live" && request.method === "GET")
|
|
1360
|
+
return Response.json({ status: this.lifecycle === "stopped" ? "stopped" : "alive", id: this.ctx.id }, { status: this.lifecycle === "stopped" ? 503 : 200 });
|
|
1361
|
+
if (path === "/health" && (this.lifecycle !== "ready" || this.ctx.controlling.size || this.ctx.recovery.size || this.environment))
|
|
1362
|
+
return Response.json({
|
|
1363
|
+
status: this.ctx.recovery.size ? "failed" : this.ctx.controlling.size || this.environment ? "maintenance" : this.lifecycle,
|
|
1364
|
+
alive: this.lifecycle !== "stopped",
|
|
1365
|
+
operations: [...this.ctx.controlling].map(([namespace2, operationId]) => ({
|
|
1366
|
+
namespace: namespace2,
|
|
1367
|
+
operationId
|
|
1368
|
+
})),
|
|
1369
|
+
fenced: [...this.ctx.recovery.keys()]
|
|
1370
|
+
}, { status: 503 });
|
|
1371
|
+
if (!path.startsWith("/fleet") && path !== "/ui")
|
|
1372
|
+
return fallback();
|
|
1373
|
+
let namespace;
|
|
1374
|
+
try {
|
|
1375
|
+
namespace = /^\/fleet\/namespaces\/([^/]+)/.test(path) ? decodeURIComponent(path.split("/")[3]) : url.searchParams.get("namespace") ?? request.headers.get("x-mockingbird-namespace") ?? this.ctx.config.namespace ?? "default";
|
|
1376
|
+
} catch {
|
|
1377
|
+
return fleetError(400, "invalid namespace encoding");
|
|
1378
|
+
}
|
|
1379
|
+
if (!namePattern.test(namespace))
|
|
1380
|
+
return fleetError(400, "invalid namespace");
|
|
1381
|
+
const action = this.action(path, request.method), caller = this.auth(request, namespace, action, path);
|
|
1382
|
+
const member = path === "/fleet/events" && request.method === "GET" && this.ctx.options.memberStatus === true;
|
|
1383
|
+
if (caller instanceof Response && !member) {
|
|
1384
|
+
const audited = await this.instrumentation.audit({
|
|
1385
|
+
actor: "unauthorized",
|
|
1386
|
+
namespace,
|
|
1387
|
+
action: `${request.method} ${this.action(path, request.method)}`,
|
|
1388
|
+
services: [],
|
|
1389
|
+
stage: "denied"
|
|
1390
|
+
});
|
|
1391
|
+
if (!audited)
|
|
1392
|
+
return fleetError(503, "required audit sink unavailable");
|
|
1393
|
+
return caller;
|
|
1394
|
+
}
|
|
1395
|
+
let body = {};
|
|
1396
|
+
if (!["GET", "HEAD", "DELETE"].includes(request.method)) {
|
|
1397
|
+
try {
|
|
1398
|
+
const text = await request.clone().text();
|
|
1399
|
+
const parsed = text ? JSON.parse(text) : {};
|
|
1400
|
+
if (!object2(parsed))
|
|
1401
|
+
throw new Error();
|
|
1402
|
+
body = parsed;
|
|
1403
|
+
} catch {
|
|
1404
|
+
return fleetError(400, "expected JSON object");
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
this.prune();
|
|
1408
|
+
const mutating = !["GET", "HEAD"].includes(request.method);
|
|
1409
|
+
const run = async () => {
|
|
1410
|
+
let operation;
|
|
1411
|
+
if (mutating && !path.includes("/operations/") && !path.endsWith("/can-checkpoint") && !path.endsWith("/wait-until-idle")) {
|
|
1412
|
+
operation = {
|
|
1413
|
+
id: randomUUID3(),
|
|
1414
|
+
scope: body.allNamespaces === true ? [...this.namespaces.keys()] : [namespace],
|
|
1415
|
+
actor: typeof caller === "string" ? caller : "member",
|
|
1416
|
+
services: Array.isArray(body.services) && body.services.every((s) => typeof s === "string" && this.ctx.children.has(s)) ? body.services : [...this.ctx.children.keys()],
|
|
1417
|
+
namespace,
|
|
1418
|
+
action: `${request.method} ${path}`,
|
|
1419
|
+
phase: "validating",
|
|
1420
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1421
|
+
status: "running",
|
|
1422
|
+
completed: 0,
|
|
1423
|
+
total: this.ctx.children.size
|
|
1424
|
+
};
|
|
1425
|
+
this.operations.set(operation.id, operation);
|
|
1426
|
+
this.aborts.set(operation.id, new AbortController());
|
|
1427
|
+
this.emit(operation);
|
|
1428
|
+
}
|
|
1429
|
+
const execute = async () => {
|
|
1430
|
+
try {
|
|
1431
|
+
if (operation && !await this.instrumentation.audit({
|
|
1432
|
+
actor: operation.actor ?? "admin",
|
|
1433
|
+
namespace,
|
|
1434
|
+
action,
|
|
1435
|
+
services: operation.services ?? [],
|
|
1436
|
+
operationId: operation.id,
|
|
1437
|
+
stage: "attempt"
|
|
1438
|
+
}))
|
|
1439
|
+
throw new Error("required audit sink unavailable before mutation");
|
|
1440
|
+
if (operation && this.ctx.options.journal && !path.startsWith("/fleet/recovery") && !path.includes("/assertions/") && !path.startsWith("/fleet/trace")) {
|
|
1441
|
+
if (!this.ctx.options.repository)
|
|
1442
|
+
throw new Error("durable journal requires a repository");
|
|
1443
|
+
let before;
|
|
1444
|
+
if (this.namespaces.has(namespace) && !this.ctx.recovery.has(namespace)) {
|
|
1445
|
+
const archive = await this.capture(body.allNamespaces === true ? [...this.namespaces.keys()] : [namespace], this.select(body));
|
|
1446
|
+
before = await this.ctx.options.repository.put(archive);
|
|
1447
|
+
await this.ctx.options.repository.get(before);
|
|
1448
|
+
}
|
|
1449
|
+
const record = {
|
|
1450
|
+
version: 1,
|
|
1451
|
+
revision: 1,
|
|
1452
|
+
operationId: operation.id,
|
|
1453
|
+
controller: this.ctx.id,
|
|
1454
|
+
namespace,
|
|
1455
|
+
scope: body.allNamespaces === true ? [...this.namespaces.keys()] : [namespace],
|
|
1456
|
+
action,
|
|
1457
|
+
phase: "prepared",
|
|
1458
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1459
|
+
requestFingerprint: digest({ path, body, method: request.method }),
|
|
1460
|
+
...before ? { before } : {}
|
|
1461
|
+
};
|
|
1462
|
+
await this.ctx.options.journal.write(record);
|
|
1463
|
+
this.durable.set(operation.id, record);
|
|
1464
|
+
await this.journalPhase(operation.id, "committing");
|
|
1465
|
+
}
|
|
1466
|
+
const result = await this.handle(request, path, namespace, body, caller === "admin" && (!member || request.headers.has("x-mockingbird-admin-key"))) ?? await fallback();
|
|
1467
|
+
if (operation) {
|
|
1468
|
+
operation.status = this.aborts.get(operation.id)?.signal.aborted ? "cancelled" : result.ok ? "succeeded" : "failed";
|
|
1469
|
+
operation.phase = operation.status;
|
|
1470
|
+
operation.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1471
|
+
const payload = await result.clone().json().catch(() => void 0);
|
|
1472
|
+
operation.result = object2(payload) ? Object.fromEntries(Object.entries(payload).filter(([key2]) => [
|
|
1473
|
+
"status",
|
|
1474
|
+
"id",
|
|
1475
|
+
"namespace",
|
|
1476
|
+
"failedService",
|
|
1477
|
+
"rollback",
|
|
1478
|
+
"rolledBack",
|
|
1479
|
+
"error",
|
|
1480
|
+
"sha256"
|
|
1481
|
+
].includes(key2))) : { status: result.status };
|
|
1482
|
+
if (result.ok)
|
|
1483
|
+
operation.completed = operation.total;
|
|
1484
|
+
await this.journalPhase(operation.id, result.ok ? "succeeded" : this.ctx.recovery.has(namespace) ? "recovery-required" : "failed");
|
|
1485
|
+
if (result.ok && (action === "reset" || action === "restore")) {
|
|
1486
|
+
for (const record of this.interrupted.values())
|
|
1487
|
+
if (record.scope.includes(namespace)) {
|
|
1488
|
+
const scope2 = record.scope.filter((ns) => ns !== namespace);
|
|
1489
|
+
const resolved = {
|
|
1490
|
+
...record,
|
|
1491
|
+
scope: scope2,
|
|
1492
|
+
revision: record.revision + 1,
|
|
1493
|
+
phase: scope2.length ? "recovery-required" : "resolved",
|
|
1494
|
+
resolution: `explicit-${action}`,
|
|
1495
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
1496
|
+
};
|
|
1497
|
+
try {
|
|
1498
|
+
await this.ctx.options.journal?.write(resolved);
|
|
1499
|
+
} catch (error) {
|
|
1500
|
+
this.fenceNamespaces(record.scope);
|
|
1501
|
+
throw error;
|
|
1502
|
+
}
|
|
1503
|
+
if (scope2.length)
|
|
1504
|
+
this.interrupted.set(record.operationId, resolved);
|
|
1505
|
+
else
|
|
1506
|
+
this.interrupted.delete(record.operationId);
|
|
1507
|
+
}
|
|
1508
|
+
await this.ctx.publish();
|
|
1509
|
+
}
|
|
1510
|
+
if (!await this.instrumentation.audit({
|
|
1511
|
+
actor: operation.actor ?? "admin",
|
|
1512
|
+
namespace,
|
|
1513
|
+
action,
|
|
1514
|
+
services: operation.services ?? [],
|
|
1515
|
+
operationId: operation.id,
|
|
1516
|
+
stage: "terminal",
|
|
1517
|
+
result: operation.status === "succeeded" ? "succeeded" : operation.status === "cancelled" ? "cancelled" : "failed"
|
|
1518
|
+
})) {
|
|
1519
|
+
const fences = [];
|
|
1520
|
+
for (const name of operation.services ?? [])
|
|
1521
|
+
try {
|
|
1522
|
+
const release = this.ctx.children.get(name)?.lock(namespace);
|
|
1523
|
+
if (release)
|
|
1524
|
+
fences.push(release);
|
|
1525
|
+
} catch {
|
|
1526
|
+
}
|
|
1527
|
+
this.ctx.recovery.set(namespace, fences);
|
|
1528
|
+
await this.journalPhase(operation.id, "recovery-required");
|
|
1529
|
+
throw new Error("required terminal audit unavailable; recovery required");
|
|
1530
|
+
}
|
|
1531
|
+
result.headers.set("x-mockingbird-operation-id", operation.id);
|
|
1532
|
+
this.emit(operation);
|
|
1533
|
+
if (result.ok && request.method !== "DELETE" && (action === "restore" || action === "reset" || action === "namespace"))
|
|
1534
|
+
this.remember(namespace).generation = randomUUID3();
|
|
1535
|
+
}
|
|
1536
|
+
if (result.ok && request.method === "POST") {
|
|
1537
|
+
if (path === "/fleet/clock")
|
|
1538
|
+
this.observations.control(namespace, "clock", body);
|
|
1539
|
+
else if (/^\/fleet\/namespaces\/[^/]+\/reset$/.test(path))
|
|
1540
|
+
this.observations.control(namespace, "reset", body);
|
|
1541
|
+
else if (!path.startsWith("/fleet/trace") && !path.includes("/assertions/"))
|
|
1542
|
+
this.observations.unsupportedControl(namespace, action);
|
|
1543
|
+
}
|
|
1544
|
+
for (const point of this.ctx.checkpoints.values())
|
|
1545
|
+
if (!point.createdAt) {
|
|
1546
|
+
point.createdAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1547
|
+
if (body.label !== void 0)
|
|
1548
|
+
point.label = body.label;
|
|
1549
|
+
}
|
|
1550
|
+
this.prune();
|
|
1551
|
+
if (this.ctx.recovery.size)
|
|
1552
|
+
await this.ctx.publish();
|
|
1553
|
+
return result;
|
|
1554
|
+
} catch (error) {
|
|
1555
|
+
if (operation && ["committing", "uploading", "publishing"].includes(this.durable.get(operation.id)?.phase ?? "")) {
|
|
1556
|
+
const releases = this.ctx.recovery.get(namespace) ?? [];
|
|
1557
|
+
for (const child of this.ctx.children.values())
|
|
1558
|
+
try {
|
|
1559
|
+
releases.push(child.lock(namespace));
|
|
1560
|
+
} catch {
|
|
1561
|
+
}
|
|
1562
|
+
this.ctx.recovery.set(namespace, releases);
|
|
1563
|
+
}
|
|
1564
|
+
if (operation) {
|
|
1565
|
+
operation.status = "failed";
|
|
1566
|
+
operation.phase = "failed";
|
|
1567
|
+
operation.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1568
|
+
operation.result = {
|
|
1569
|
+
message: error instanceof Error ? error.message : "operation failed"
|
|
1570
|
+
};
|
|
1571
|
+
this.emit(operation);
|
|
1572
|
+
}
|
|
1573
|
+
if (this.ctx.recovery.size)
|
|
1574
|
+
await this.ctx.publish().catch(() => {
|
|
1575
|
+
});
|
|
1576
|
+
return fleetError(400, error instanceof Error ? error.message : "invalid control");
|
|
1577
|
+
} finally {
|
|
1578
|
+
if (operation)
|
|
1579
|
+
this.aborts.delete(operation.id);
|
|
1580
|
+
while (this.operations.size > 200) {
|
|
1581
|
+
const entry = [...this.operations].find(([, o]) => o.status !== "running");
|
|
1582
|
+
if (!entry)
|
|
1583
|
+
break;
|
|
1584
|
+
this.operations.delete(entry[0]);
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
};
|
|
1588
|
+
return operation ? this.operationContext.run(operation, execute) : execute();
|
|
1589
|
+
};
|
|
1590
|
+
const key = request.headers.get("idempotency-key");
|
|
1591
|
+
if (!key || !mutating)
|
|
1592
|
+
return run();
|
|
1593
|
+
if (key.length > 256)
|
|
1594
|
+
return fleetError(400, "idempotency key too long");
|
|
1595
|
+
for (const [id, kept] of this.retries)
|
|
1596
|
+
if (kept.expires < Date.now())
|
|
1597
|
+
this.retries.delete(id);
|
|
1598
|
+
const scope = `${typeof caller === "string" ? caller : "member"}:${namespace}:${key}`;
|
|
1599
|
+
const fingerprint = digest({ path, method: request.method, body });
|
|
1600
|
+
const existing = this.retries.get(scope);
|
|
1601
|
+
if (existing)
|
|
1602
|
+
return existing.fingerprint === fingerprint ? (await existing.response).clone() : fleetError(409, "idempotency key reused with different request");
|
|
1603
|
+
if (this.retries.size >= 1e3)
|
|
1604
|
+
return fleetError(429, "idempotency retention capacity reached");
|
|
1605
|
+
const response = Promise.resolve().then(run);
|
|
1606
|
+
this.retries.set(scope, { fingerprint, expires: Date.now() + 36e5, response });
|
|
1607
|
+
return (await response).clone();
|
|
1608
|
+
}
|
|
1609
|
+
async handle(request, path, namespace, body, admin) {
|
|
1610
|
+
const route = path.slice("/fleet".length), method = request.method;
|
|
1611
|
+
if (path === "/ui")
|
|
1612
|
+
return new Response(fleetConsole(this.ctx.config.adminPrefix ?? "/__admin"), {
|
|
1613
|
+
headers: { "content-type": "text/html; charset=utf-8" }
|
|
1614
|
+
});
|
|
1615
|
+
if (route === "" && method === "GET")
|
|
1616
|
+
return Response.json({
|
|
1617
|
+
...this.capability(),
|
|
1618
|
+
manifest: this.ctx.manifest(),
|
|
1619
|
+
namespaces: this.namespaceStatus()
|
|
1620
|
+
});
|
|
1621
|
+
if (route === "/recovery" && method === "GET")
|
|
1622
|
+
return admin ? Response.json({
|
|
1623
|
+
version: 1,
|
|
1624
|
+
interrupted: [...this.interrupted.values()],
|
|
1625
|
+
resumable: Boolean(this.ctx.options.journal)
|
|
1626
|
+
}) : fleetError(403, "recovery administration required");
|
|
1627
|
+
const recovery = /^\/recovery\/([^/]+)\/rollback$/.exec(route);
|
|
1628
|
+
if (recovery && method === "POST") {
|
|
1629
|
+
checked(body, []);
|
|
1630
|
+
if (!admin)
|
|
1631
|
+
return fleetError(403, "recovery administration required");
|
|
1632
|
+
const record = this.interrupted.get(recovery[1]);
|
|
1633
|
+
if (!record?.before || !this.ctx.options.repository || !this.ctx.options.journal)
|
|
1634
|
+
throw new Error("interrupted operation has no verified portable before-state; explicit namespace reset is required");
|
|
1635
|
+
const beforeArchive = await this.ctx.options.repository.get(record.before);
|
|
1636
|
+
const { sha256: _identity, ...content } = beforeArchive;
|
|
1637
|
+
await this.restoreArchive(sealArchive({
|
|
1638
|
+
...content,
|
|
1639
|
+
namespaces: Object.fromEntries(Object.entries(beforeArchive.namespaces).filter(([namespace2]) => record.scope.includes(namespace2)))
|
|
1640
|
+
}));
|
|
1641
|
+
try {
|
|
1642
|
+
await this.ctx.options.journal.write({
|
|
1643
|
+
...record,
|
|
1644
|
+
revision: record.revision + 1,
|
|
1645
|
+
phase: "resolved",
|
|
1646
|
+
resolution: "explicit-restore-before",
|
|
1647
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
1648
|
+
});
|
|
1649
|
+
} catch (error) {
|
|
1650
|
+
this.fenceNamespaces(record.scope);
|
|
1651
|
+
throw error;
|
|
1652
|
+
}
|
|
1653
|
+
this.interrupted.delete(record.operationId);
|
|
1654
|
+
await this.ctx.publish();
|
|
1655
|
+
return Response.json({
|
|
1656
|
+
status: "resolved",
|
|
1657
|
+
operationId: record.operationId,
|
|
1658
|
+
resolution: "restored-before-state"
|
|
1659
|
+
});
|
|
1660
|
+
}
|
|
1661
|
+
if (route === "/telemetry" && method === "GET")
|
|
1662
|
+
return admin ? Response.json(this.instrumentation.snapshot()) : fleetError(403, "operator telemetry requires administrator scope");
|
|
1663
|
+
if (route === "/audit" && method === "GET")
|
|
1664
|
+
return admin ? Response.json(this.instrumentation.auditTrail()) : fleetError(403, "audit trail requires administrator scope");
|
|
1665
|
+
if (route === "/namespaces" && method === "GET")
|
|
1666
|
+
return Response.json({ namespaces: this.namespaceStatus() });
|
|
1667
|
+
const fork = /^\/namespaces\/[^/]+\/fork$/.test(route);
|
|
1668
|
+
if (fork && method === "POST") {
|
|
1669
|
+
checked(body, ["destination", "bindings"]);
|
|
1670
|
+
if (!admin)
|
|
1671
|
+
return fleetError(403, "namespace fork requires administrator scope");
|
|
1672
|
+
if (typeof body.destination !== "string" || !namePattern.test(body.destination))
|
|
1673
|
+
throw new Error("destination namespace required");
|
|
1674
|
+
const destination2 = body.destination;
|
|
1675
|
+
if (this.namespaces.has(destination2))
|
|
1676
|
+
return fleetError(409, "destination namespace already exists");
|
|
1677
|
+
return this.withEnvironment([namespace, destination2], this.ctx.children, async () => {
|
|
1678
|
+
let archive = await this.capture([namespace]);
|
|
1679
|
+
let bindings = {
|
|
1680
|
+
changes: [],
|
|
1681
|
+
limitations: ["opaque namespace-bearing keys and application credentials are unchanged"]
|
|
1682
|
+
};
|
|
1683
|
+
if (body.bindings !== void 0) {
|
|
1684
|
+
const prepared = await planRestoreBindings(archive, body.bindings, this.ctx.options.resolveArchiveSecret);
|
|
1685
|
+
archive = prepared.archive;
|
|
1686
|
+
bindings = prepared.report;
|
|
1687
|
+
}
|
|
1688
|
+
await this.restoreArchive(rebaseArchiveNamespace(archive, namespace, destination2));
|
|
1689
|
+
return Response.json({
|
|
1690
|
+
namespace: destination2,
|
|
1691
|
+
generation: this.generation(destination2),
|
|
1692
|
+
manifest: this.ctx.manifest(),
|
|
1693
|
+
bindings,
|
|
1694
|
+
connections: Object.fromEntries([...this.ctx.children].map(([name, child]) => [
|
|
1695
|
+
name,
|
|
1696
|
+
child.connections?.[destination2] ?? `${child.url}${this.ctx.config.adminPrefix ?? "/__admin"}/ns/${destination2}`
|
|
1697
|
+
]))
|
|
1698
|
+
}, { status: 201 });
|
|
1699
|
+
});
|
|
1700
|
+
}
|
|
1701
|
+
if (route === "/archives/bindings" && method === "POST") {
|
|
1702
|
+
if (!admin)
|
|
1703
|
+
return fleetError(403, "restore binding plans require administrator scope");
|
|
1704
|
+
checked(body, ["archive", "plan"]);
|
|
1705
|
+
const prepared = await planRestoreBindings(body.archive, body.plan, this.ctx.options.resolveArchiveSecret);
|
|
1706
|
+
return Response.json(prepared.report);
|
|
1707
|
+
}
|
|
1708
|
+
if (route === "/assertions/baseline" && method === "POST") {
|
|
1709
|
+
checked(body, ["services"]);
|
|
1710
|
+
const selected = this.select(body);
|
|
1711
|
+
this.scope(namespace, selected);
|
|
1712
|
+
return Response.json(this.observations.baseline(namespace, [...selected.keys()]));
|
|
1713
|
+
}
|
|
1714
|
+
const assertion = /^\/assertions\/([^/]+)\/check$/.exec(route);
|
|
1715
|
+
if (assertion && method === "POST") {
|
|
1716
|
+
checked(body, ["allowances", "allowCheckpointablePending"]);
|
|
1717
|
+
if (body.allowCheckpointablePending !== void 0 && typeof body.allowCheckpointablePending !== "boolean")
|
|
1718
|
+
throw new Error("allowCheckpointablePending must be boolean");
|
|
1719
|
+
const diagnostics = Object.fromEntries([...this.ctx.children].filter(([, child]) => child.protocol === "http" || Object.hasOwn(child.namespaces.endpoints ?? {}, namespace)).map(([name, child]) => [name, child.diagnostics(namespace)]));
|
|
1720
|
+
const report = this.observations.assertClean(assertion[1], namespace, diagnostics, body);
|
|
1721
|
+
return Response.json(report, { status: report.clean ? 200 : 409 });
|
|
1722
|
+
}
|
|
1723
|
+
if (route.startsWith("/trace")) {
|
|
1724
|
+
if (!admin)
|
|
1725
|
+
return fleetError(403, "trace capture requires administrator scope");
|
|
1726
|
+
if (!this.ctx.options.trace)
|
|
1727
|
+
return fleetError(400, "trace capture is not enabled");
|
|
1728
|
+
if (route === "/trace/start" && method === "POST") {
|
|
1729
|
+
checked(body, ["includeBodies"]);
|
|
1730
|
+
if (body.includeBodies !== void 0 && typeof body.includeBodies !== "boolean")
|
|
1731
|
+
throw new Error("includeBodies must be boolean");
|
|
1732
|
+
const baseline = await this.capture([namespace]);
|
|
1733
|
+
const limitations = [...this.ctx.children.values()].some((child) => child.protocol !== "http") ? ["protocol/external interactions are not captured"] : [];
|
|
1734
|
+
return Response.json(this.observations.startTrace(namespace, baseline, body.includeBodies === true, limitations));
|
|
1735
|
+
}
|
|
1736
|
+
if (route === "/trace" && method === "GET")
|
|
1737
|
+
return Response.json(this.observations.trace(namespace));
|
|
1738
|
+
if (route === "/trace/stop" && method === "POST") {
|
|
1739
|
+
checked(body, []);
|
|
1740
|
+
return Response.json(this.observations.trace(namespace, true));
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
const nsRoute = /^\/namespaces\/([^/]+)$/.exec(route);
|
|
1744
|
+
if (nsRoute && method === "POST") {
|
|
1745
|
+
checked(body, ["baseline"]);
|
|
1746
|
+
if (body.baseline !== void 0 && typeof body.baseline !== "string")
|
|
1747
|
+
throw new Error("baseline must be a checkpoint id");
|
|
1748
|
+
return this.createNamespace(namespace, body.baseline);
|
|
1749
|
+
}
|
|
1750
|
+
if (nsRoute && method === "DELETE")
|
|
1751
|
+
return this.deleteNamespace(namespace);
|
|
1752
|
+
if (/^\/namespaces\/[^/]+\/policy$/.test(route) && method === "POST") {
|
|
1753
|
+
checked(body, ["pinned", "expiresInMs"]);
|
|
1754
|
+
if (body.pinned !== void 0 && typeof body.pinned !== "boolean")
|
|
1755
|
+
throw new Error("pinned must be boolean");
|
|
1756
|
+
if (body.expiresInMs !== void 0 && (typeof body.expiresInMs !== "number" || !Number.isSafeInteger(body.expiresInMs) || body.expiresInMs < 1 || body.expiresInMs > 864e5))
|
|
1757
|
+
throw new Error("expiry must be within one host day");
|
|
1758
|
+
if (body.pinned === void 0 && body.expiresInMs === void 0)
|
|
1759
|
+
throw new Error("namespace policy required");
|
|
1760
|
+
if (typeof body.pinned === "boolean")
|
|
1761
|
+
this.remember(namespace).pinned = body.pinned;
|
|
1762
|
+
if (typeof body.expiresInMs === "number") {
|
|
1763
|
+
this.remember(namespace).expiresAt = Date.now() + body.expiresInMs;
|
|
1764
|
+
if (!this.expiryTimer) {
|
|
1765
|
+
this.expiryTimer = setInterval(() => {
|
|
1766
|
+
for (const entry of this.cleanupPreview())
|
|
1767
|
+
if (entry.eligible)
|
|
1768
|
+
void this.deleteNamespace(entry.namespace).catch(() => {
|
|
1769
|
+
});
|
|
1770
|
+
}, Math.max(10, Math.min(6e4, body.expiresInMs)));
|
|
1771
|
+
this.expiryTimer.unref?.();
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
return Response.json({ namespace, ...this.remember(namespace) });
|
|
1775
|
+
}
|
|
1776
|
+
const snapshot = /^\/namespaces\/[^/]+\/snapshots(?:\/([^/]+))?$/.exec(route);
|
|
1777
|
+
if (snapshot && (method === "GET" || method === "DELETE")) {
|
|
1778
|
+
const info = (id, p) => ({
|
|
1779
|
+
id,
|
|
1780
|
+
namespace: p.namespace,
|
|
1781
|
+
label: p.label,
|
|
1782
|
+
createdAt: p.createdAt,
|
|
1783
|
+
services: [...p.values.keys()],
|
|
1784
|
+
portable: [...p.values.keys()].every((s) => Boolean(this.ctx.children.get(s)?.exportCheckpoint))
|
|
1785
|
+
});
|
|
1786
|
+
if (!snapshot[1]) {
|
|
1787
|
+
if (method !== "GET")
|
|
1788
|
+
return fleetError(405, "select a checkpoint to delete");
|
|
1789
|
+
return Response.json({
|
|
1790
|
+
snapshots: [...this.ctx.checkpoints].filter(([, p]) => p.namespace === namespace).map(([id, p]) => info(id, p))
|
|
1791
|
+
});
|
|
1792
|
+
}
|
|
1793
|
+
const point = this.ctx.checkpoints.get(snapshot[1]);
|
|
1794
|
+
if (!point || point.namespace !== namespace)
|
|
1795
|
+
return fleetError(404, "no checkpoint in this namespace");
|
|
1796
|
+
if (method === "DELETE")
|
|
1797
|
+
this.ctx.checkpoints.delete(snapshot[1]);
|
|
1798
|
+
return Response.json(method === "DELETE" ? { status: "deleted", id: snapshot[1] } : info(snapshot[1], point));
|
|
1799
|
+
}
|
|
1800
|
+
if ((route === "/time/step-next" || route === "/time/run-until") && method === "POST") {
|
|
1801
|
+
checked(body, ["services", "condition", "maxEvents", "maxAdvanceMs", "timeoutMs"]);
|
|
1802
|
+
const selected = this.select(body);
|
|
1803
|
+
this.scope(namespace, selected);
|
|
1804
|
+
const controller = new FleetTimeController({
|
|
1805
|
+
clock: this.ctx.clock,
|
|
1806
|
+
transaction: this.ctx.transaction,
|
|
1807
|
+
phase: (ns, phase, done, total) => this.phase(ns, phase, done, total),
|
|
1808
|
+
recovery: this.ctx.recovery,
|
|
1809
|
+
...this.ctx.options.synchronizeClock ? { synchronize: this.ctx.options.synchronizeClock } : {}
|
|
1810
|
+
});
|
|
1811
|
+
return controller.run(namespace, selected, body, route === "/time/step-next");
|
|
1812
|
+
}
|
|
1813
|
+
if (route === "/can-checkpoint" && method === "POST") {
|
|
1814
|
+
checked(body, ["services", "timeoutMs"]);
|
|
1815
|
+
if (body.timeoutMs !== void 0 && (typeof body.timeoutMs !== "number" || body.timeoutMs < 0 || body.timeoutMs > 3e4))
|
|
1816
|
+
throw new Error("timeoutMs must be between 0 and 30000");
|
|
1817
|
+
const selected = this.select(body);
|
|
1818
|
+
this.scope(namespace, selected);
|
|
1819
|
+
const until = Date.now() + (body.timeoutMs ?? 0);
|
|
1820
|
+
for (; ; ) {
|
|
1821
|
+
const services = Object.fromEntries([...selected].map(([n, c]) => {
|
|
1822
|
+
const d = c.diagnostics(namespace);
|
|
1823
|
+
return [
|
|
1824
|
+
n,
|
|
1825
|
+
{
|
|
1826
|
+
...d,
|
|
1827
|
+
checkpointReady: d.activeRequests + d.blockedCommands + d.pendingWebhooks + (d.activeJobs ?? 0) === 0,
|
|
1828
|
+
idle: d.activeRequests + d.blockedCommands + d.pendingWebhooks + d.pendingJobs === 0
|
|
1829
|
+
}
|
|
1830
|
+
];
|
|
1831
|
+
}));
|
|
1832
|
+
const ready = !this.ctx.controlling.has(namespace) && !this.ctx.recovery.has(namespace) && Object.values(services).every((d) => d.checkpointReady);
|
|
1833
|
+
if (ready || Date.now() >= until)
|
|
1834
|
+
return Response.json({ namespace, checkpointReady: ready, services }, { status: ready ? 200 : 409 });
|
|
1835
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
if (route === "/operations" && method === "GET")
|
|
1839
|
+
return Response.json({
|
|
1840
|
+
operations: [...this.operations.values()].filter((o) => o.namespace === namespace)
|
|
1841
|
+
});
|
|
1842
|
+
const operationRoute = /^\/operations\/([^/]+)(\/cancel)?$/.exec(route);
|
|
1843
|
+
if (operationRoute) {
|
|
1844
|
+
const op = this.operations.get(operationRoute[1]);
|
|
1845
|
+
if (!op || op.namespace !== namespace)
|
|
1846
|
+
return fleetError(404, "operation not found");
|
|
1847
|
+
if (operationRoute[2] && method === "POST") {
|
|
1848
|
+
checked(body, []);
|
|
1849
|
+
if (op.status !== "running" || !["validating", "preparing", "checkpointing"].includes(op.phase))
|
|
1850
|
+
return fleetError(409, "operation has passed cancellable phase");
|
|
1851
|
+
this.aborts.get(op.id)?.abort();
|
|
1852
|
+
return Response.json({ id: op.id, cancellationRequested: true });
|
|
1853
|
+
}
|
|
1854
|
+
if (method === "GET")
|
|
1855
|
+
return Response.json(op);
|
|
1856
|
+
}
|
|
1857
|
+
if (route === "/events" && method === "GET") {
|
|
1858
|
+
const cursor = request.headers.get("last-event-id");
|
|
1859
|
+
const encode = new TextEncoder();
|
|
1860
|
+
let subscription;
|
|
1861
|
+
let heartbeat;
|
|
1862
|
+
const cleanup = () => {
|
|
1863
|
+
if (subscription)
|
|
1864
|
+
this.subscribers.delete(subscription);
|
|
1865
|
+
clearInterval(heartbeat);
|
|
1866
|
+
};
|
|
1867
|
+
const stream = new ReadableStream({
|
|
1868
|
+
start: (controller) => {
|
|
1869
|
+
subscription = {
|
|
1870
|
+
namespace,
|
|
1871
|
+
member: this.ctx.options.memberStatus === true && !admin,
|
|
1872
|
+
push: (event) => {
|
|
1873
|
+
if ((controller.desiredSize ?? 0) < -32) {
|
|
1874
|
+
cleanup();
|
|
1875
|
+
controller.close();
|
|
1876
|
+
} else
|
|
1877
|
+
controller.enqueue(encode.encode(event));
|
|
1878
|
+
}
|
|
1879
|
+
};
|
|
1880
|
+
this.subscribers.add(subscription);
|
|
1881
|
+
const at = this.events.findIndex((e) => e.id === cursor);
|
|
1882
|
+
if (cursor === null || at < 0)
|
|
1883
|
+
subscription.push(`event: resync
|
|
1884
|
+
data: ${JSON.stringify({ processId: this.ctx.id, namespace, generation: this.generation(namespace), lifecycle: this.lifecycle })}
|
|
1885
|
+
|
|
1886
|
+
`);
|
|
1887
|
+
for (const event of this.events.slice(at < 0 ? 0 : at + 1))
|
|
1888
|
+
if (event.namespace === namespace) {
|
|
1889
|
+
const data = this.ctx.options.memberStatus && !admin ? {
|
|
1890
|
+
id: event.id,
|
|
1891
|
+
namespace,
|
|
1892
|
+
operation: {
|
|
1893
|
+
id: event.operation.id,
|
|
1894
|
+
phase: event.operation.phase,
|
|
1895
|
+
status: event.operation.status,
|
|
1896
|
+
completed: event.operation.completed,
|
|
1897
|
+
total: event.operation.total
|
|
1898
|
+
}
|
|
1899
|
+
} : event;
|
|
1900
|
+
subscription.push(`id: ${event.id}
|
|
1901
|
+
event: lifecycle
|
|
1902
|
+
data: ${JSON.stringify(data)}
|
|
1903
|
+
|
|
1904
|
+
`);
|
|
1905
|
+
}
|
|
1906
|
+
heartbeat = setInterval(() => subscription.push(": heartbeat\n\n"), 15e3);
|
|
1907
|
+
heartbeat.unref?.();
|
|
1908
|
+
request.signal.addEventListener("abort", () => {
|
|
1909
|
+
cleanup();
|
|
1910
|
+
try {
|
|
1911
|
+
controller.close();
|
|
1912
|
+
} catch {
|
|
1913
|
+
}
|
|
1914
|
+
}, { once: true });
|
|
1915
|
+
},
|
|
1916
|
+
cancel: cleanup
|
|
1917
|
+
});
|
|
1918
|
+
return new Response(stream, {
|
|
1919
|
+
headers: { "content-type": "text/event-stream", "cache-control": "no-cache" }
|
|
1920
|
+
});
|
|
1921
|
+
}
|
|
1922
|
+
if (route === "/archives/export" && method === "POST") {
|
|
1923
|
+
checked(body, ["services", "allNamespaces"]);
|
|
1924
|
+
if (body.allNamespaces !== void 0 && typeof body.allNamespaces !== "boolean")
|
|
1925
|
+
throw new Error("allNamespaces must be boolean");
|
|
1926
|
+
const archive = await this.capture(body.allNamespaces === true ? [...this.namespaces.keys()] : [namespace], this.select(body));
|
|
1927
|
+
return Response.json(this.ctx.options.archiveProtection ? await this.ctx.options.archiveProtection.seal(archive) : archive);
|
|
1928
|
+
}
|
|
1929
|
+
if (route === "/archives/import" && method === "POST") {
|
|
1930
|
+
checked(body, ["archive", "namespace", "bindings"]);
|
|
1931
|
+
let archive = this.ctx.options.archiveProtection ? await this.ctx.options.archiveProtection.open(body.archive) : validateArchive(body.archive);
|
|
1932
|
+
if (body.namespace !== void 0 && (typeof body.namespace !== "string" || !namePattern.test(body.namespace)))
|
|
1933
|
+
throw new Error("invalid selected archive namespace");
|
|
1934
|
+
if (body.bindings !== void 0)
|
|
1935
|
+
archive = (await planRestoreBindings(archive, body.bindings, this.ctx.options.resolveArchiveSecret)).archive;
|
|
1936
|
+
await this.restoreArchive(archive, body.namespace);
|
|
1937
|
+
return Response.json({
|
|
1938
|
+
status: "restored",
|
|
1939
|
+
sha256: archive.sha256,
|
|
1940
|
+
namespaces: body.namespace ? [body.namespace] : Object.keys(archive.namespaces)
|
|
1941
|
+
});
|
|
1942
|
+
}
|
|
1943
|
+
if (route === "/archives/inspect" && method === "POST") {
|
|
1944
|
+
checked(body, ["archive"]);
|
|
1945
|
+
return Response.json(inspectArchive(body.archive));
|
|
1946
|
+
}
|
|
1947
|
+
if (route === "/archives/diff" && method === "POST") {
|
|
1948
|
+
checked(body, ["left", "right", "namespace", "service", "values", "limit"]);
|
|
1949
|
+
if (body.values !== void 0 && typeof body.values !== "boolean" || body.limit !== void 0 && (typeof body.limit !== "number" || !Number.isInteger(body.limit) || body.limit < 1 || body.limit > 1e3))
|
|
1950
|
+
throw new Error("invalid diff options");
|
|
1951
|
+
return Response.json(diffArchives(body.left, body.right, body));
|
|
1952
|
+
}
|
|
1953
|
+
if (route === "/profiles/apply" && method === "POST") {
|
|
1954
|
+
checked(body, ["name", "profile"]);
|
|
1955
|
+
const profile = typeof body.name === "string" ? this.ctx.options.profiles?.[body.name] : body.profile;
|
|
1956
|
+
return this.applyProfile(namespace, profile);
|
|
1957
|
+
}
|
|
1958
|
+
if (route === "/profiles/baseline" && method === "POST") {
|
|
1959
|
+
checked(body, ["services"]);
|
|
1960
|
+
return this.applyProfile(namespace, Object.fromEntries([...this.select(body)].map(([name, c]) => [
|
|
1961
|
+
name,
|
|
1962
|
+
c.protocol === "http" ? { faults: [], latency: 0 } : {}
|
|
1963
|
+
])));
|
|
1964
|
+
}
|
|
1965
|
+
if (route === "/scenarios" && method === "GET")
|
|
1966
|
+
return Response.json({
|
|
1967
|
+
scenarios: Object.entries(this.ctx.options.scenarios ?? {}).map(([name, b]) => ({
|
|
1968
|
+
name,
|
|
1969
|
+
format: b.format,
|
|
1970
|
+
version: b.version,
|
|
1971
|
+
description: b.description,
|
|
1972
|
+
services: Object.keys(b.services)
|
|
1973
|
+
}))
|
|
1974
|
+
});
|
|
1975
|
+
const scenario = /^\/scenarios\/([^/]+)\/apply$/.exec(route);
|
|
1976
|
+
if (scenario && method === "POST") {
|
|
1977
|
+
checked(body, []);
|
|
1978
|
+
const bundle = this.ctx.options.scenarios?.[scenario[1]];
|
|
1979
|
+
if (bundle?.format !== "mockingbird.scenario/v1" || !Number.isSafeInteger(bundle.version) || bundle.version < 1)
|
|
1980
|
+
throw new Error("unknown or incompatible scenario bundle");
|
|
1981
|
+
for (const [name, entry] of Object.entries(bundle.services))
|
|
1982
|
+
if (this.ctx.children.get(name)?.protocol !== entry.protocol)
|
|
1983
|
+
throw new Error(`incompatible scenario service ${name}`);
|
|
1984
|
+
for (const [name, entry] of Object.entries(bundle.services))
|
|
1985
|
+
if (entry.fixtures !== void 0) {
|
|
1986
|
+
const child = this.ctx.children.get(name);
|
|
1987
|
+
if (entry.protocol !== "http" || !child?.importCheckpoint)
|
|
1988
|
+
throw new Error(`scenario fixtures unsupported for ${name}`);
|
|
1989
|
+
await child.importCheckpoint(namespace, {
|
|
1990
|
+
format: "mockingbird.snapshot/v1",
|
|
1991
|
+
service: name,
|
|
1992
|
+
records: entry.fixtures
|
|
1993
|
+
});
|
|
1994
|
+
}
|
|
1995
|
+
const profile = Object.fromEntries(Object.entries(bundle.services).map(([name, entry]) => [
|
|
1996
|
+
name,
|
|
1997
|
+
{
|
|
1998
|
+
...entry.controls,
|
|
1999
|
+
...bundle.seed !== void 0 && entry.protocol === "http" ? { seed: bundle.seed } : {},
|
|
2000
|
+
...bundle.clock ? { clock: bundle.clock } : {}
|
|
2001
|
+
}
|
|
2002
|
+
]));
|
|
2003
|
+
const response = await this.applyProfile(namespace, profile, async (name, child) => {
|
|
2004
|
+
const fixtures = bundle.services[name]?.fixtures;
|
|
2005
|
+
if (fixtures !== void 0) {
|
|
2006
|
+
if (!child.configure)
|
|
2007
|
+
throw new Error(`fixtures unsupported for ${name}`);
|
|
2008
|
+
const document = { format: "mockingbird.snapshot/v1", service: name, records: fixtures };
|
|
2009
|
+
await child.configure(namespace, { snapshot: document });
|
|
2010
|
+
}
|
|
2011
|
+
}, bundle.seedApplication);
|
|
2012
|
+
return response;
|
|
2013
|
+
}
|
|
2014
|
+
if (route === "/inspect" && method === "GET") {
|
|
2015
|
+
const url = new URL(request.url), service = url.searchParams.get("service");
|
|
2016
|
+
const child = service ? this.ctx.children.get(service) : void 0;
|
|
2017
|
+
if (!child?.inspect)
|
|
2018
|
+
return fleetError(400, "service inspection is unsupported");
|
|
2019
|
+
const offset = Number(url.searchParams.get("offset") ?? 0), limit = Number(url.searchParams.get("limit") ?? 100);
|
|
2020
|
+
if (!Number.isInteger(offset) || offset < 0 || !Number.isInteger(limit) || limit < 1 || limit > 1e3)
|
|
2021
|
+
throw new Error("invalid pagination");
|
|
2022
|
+
this.scope(namespace, /* @__PURE__ */ new Map([[service, child]]));
|
|
2023
|
+
const collection = url.searchParams.get("collection");
|
|
2024
|
+
return Response.json({
|
|
2025
|
+
namespace,
|
|
2026
|
+
service,
|
|
2027
|
+
result: await child.inspect(namespace, {
|
|
2028
|
+
offset,
|
|
2029
|
+
limit,
|
|
2030
|
+
...collection !== null ? { collection } : {}
|
|
2031
|
+
})
|
|
2032
|
+
});
|
|
2033
|
+
}
|
|
2034
|
+
if (route === "/diagnostics" && method === "GET") {
|
|
2035
|
+
const selected = new URL(request.url).searchParams.getAll("service");
|
|
2036
|
+
const children = selected.length ? this.select({ services: selected }) : this.ctx.children;
|
|
2037
|
+
this.scope(namespace, children);
|
|
2038
|
+
return Response.json({
|
|
2039
|
+
format: "mockingbird.diagnostics/v1",
|
|
2040
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2041
|
+
processId: this.ctx.id,
|
|
2042
|
+
namespace,
|
|
2043
|
+
generation: this.generation(namespace),
|
|
2044
|
+
configurationFingerprint: digest(this.ctx.config),
|
|
2045
|
+
capabilities: this.capability(),
|
|
2046
|
+
services: Object.fromEntries([...children].map(([name, c]) => [
|
|
2047
|
+
name,
|
|
2048
|
+
{
|
|
2049
|
+
protocol: c.protocol,
|
|
2050
|
+
diagnostics: c.diagnostics(namespace),
|
|
2051
|
+
unmatched: c.unmatched?.(namespace, 50)
|
|
2052
|
+
}
|
|
2053
|
+
])),
|
|
2054
|
+
operations: [...this.operations.values()].filter((o) => o.namespace === namespace).slice(-50).map(({ id, phase, action, status, startedAt, finishedAt }) => ({
|
|
2055
|
+
id,
|
|
2056
|
+
phase,
|
|
2057
|
+
action,
|
|
2058
|
+
status,
|
|
2059
|
+
startedAt,
|
|
2060
|
+
finishedAt
|
|
2061
|
+
})),
|
|
2062
|
+
truncated: [...this.operations.values()].filter((o) => o.namespace === namespace).length > 50,
|
|
2063
|
+
excluded: ["credentials", "requestBodies", "records", "modelText", "operationPayloads"]
|
|
2064
|
+
});
|
|
2065
|
+
}
|
|
2066
|
+
if (route === "/credentials" && method === "POST") {
|
|
2067
|
+
checked(body, ["namespaces", "actions", "ttlMs"]);
|
|
2068
|
+
if (!admin)
|
|
2069
|
+
return fleetError(403, "admin credential required");
|
|
2070
|
+
if (!Array.isArray(body.namespaces) || !body.namespaces.length || body.namespaces.some((n) => typeof n !== "string" || !namePattern.test(n)) || !Array.isArray(body.actions) || !body.actions.length || body.actions.some((a) => !["read", "reset", "restore", "snapshot", "control"].includes(String(a))) || typeof body.ttlMs !== "number" || body.ttlMs <= 0 || body.ttlMs > 864e5)
|
|
2071
|
+
throw new Error("expected namespaces, actions and ttlMs (at most one day)");
|
|
2072
|
+
const credential2 = randomBytes(32).toString("base64url"), id = randomUUID3(), expiresAt = Date.now() + body.ttlMs;
|
|
2073
|
+
this.credentials.set(digest(credential2), {
|
|
2074
|
+
id,
|
|
2075
|
+
namespaces: body.namespaces,
|
|
2076
|
+
actions: body.actions,
|
|
2077
|
+
expiresAt
|
|
2078
|
+
});
|
|
2079
|
+
return Response.json({ id, credential: credential2, expiresAt }, { status: 201 });
|
|
2080
|
+
}
|
|
2081
|
+
const credential = /^\/credentials\/([^/]+)$/.exec(route);
|
|
2082
|
+
if (credential && method === "DELETE") {
|
|
2083
|
+
if (!admin)
|
|
2084
|
+
return fleetError(403, "admin credential required");
|
|
2085
|
+
for (const [key, c] of this.credentials)
|
|
2086
|
+
if (c.id === credential[1]) {
|
|
2087
|
+
this.credentials.delete(key);
|
|
2088
|
+
return Response.json({ status: "revoked", id: c.id });
|
|
2089
|
+
}
|
|
2090
|
+
return fleetError(404, "credential not found");
|
|
2091
|
+
}
|
|
2092
|
+
if (route === "/backups" && method === "GET")
|
|
2093
|
+
return Response.json({
|
|
2094
|
+
...this.backupStatus,
|
|
2095
|
+
running: this.backupRunning,
|
|
2096
|
+
archives: await this.ctx.options.repository?.list() ?? []
|
|
2097
|
+
});
|
|
2098
|
+
if (route === "/backups" && method === "POST") {
|
|
2099
|
+
checked(body, ["allNamespaces"]);
|
|
2100
|
+
return Response.json(await this.backup(body.allNamespaces === true ? [...this.namespaces.keys()] : [namespace], [...this.operations.values()].reverse().find((o) => o.status === "running" && o.namespace === namespace)?.id));
|
|
2101
|
+
}
|
|
2102
|
+
if (route === "/cleanup" && method === "GET")
|
|
2103
|
+
return Response.json({ candidates: this.cleanupPreview() });
|
|
2104
|
+
if (route === "/cleanup" && method === "POST") {
|
|
2105
|
+
checked(body, []);
|
|
2106
|
+
const results = {};
|
|
2107
|
+
for (const entry of this.cleanupPreview())
|
|
2108
|
+
if (entry.eligible) {
|
|
2109
|
+
try {
|
|
2110
|
+
if (this.ctx.options.expiry?.finalBackup)
|
|
2111
|
+
await this.backup([entry.namespace]);
|
|
2112
|
+
const response = await this.deleteNamespace(entry.namespace);
|
|
2113
|
+
results[entry.namespace] = { status: response.status, result: await response.json() };
|
|
2114
|
+
} catch (error) {
|
|
2115
|
+
results[entry.namespace] = {
|
|
2116
|
+
status: "failed",
|
|
2117
|
+
message: error instanceof Error ? error.message : "cleanup failed"
|
|
2118
|
+
};
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
return Response.json({ results });
|
|
2122
|
+
}
|
|
2123
|
+
return void 0;
|
|
2124
|
+
}
|
|
2125
|
+
namespaceStatus() {
|
|
2126
|
+
return [...this.namespaces].map(([namespace, state]) => ({
|
|
2127
|
+
namespace,
|
|
2128
|
+
...state,
|
|
2129
|
+
status: this.ctx.recovery.has(namespace) ? "failed" : this.ctx.controlling.has(namespace) || this.topology.has(namespace) ? "maintenance" : "ready",
|
|
2130
|
+
operationId: this.ctx.controlling.get(namespace),
|
|
2131
|
+
expiresAt: state.expiresAt ?? (this.ctx.options.expiry ? Math.max(state.activityAt, ...[...this.ctx.children.values()].map((c) => c.lastActivity?.(namespace) ?? 0)) + this.ctx.options.expiry.idleMs : void 0)
|
|
2132
|
+
}));
|
|
2133
|
+
}
|
|
2134
|
+
busy(namespace, selected = this.ctx.children) {
|
|
2135
|
+
return [...selected].filter(([, c]) => {
|
|
2136
|
+
const d = c.diagnostics(namespace);
|
|
2137
|
+
return d.activeRequests + d.blockedCommands + d.pendingWebhooks + (d.activeJobs ?? 0) > 0;
|
|
2138
|
+
}).map(([name]) => name);
|
|
2139
|
+
}
|
|
2140
|
+
async hook(phase, namespace, selected) {
|
|
2141
|
+
const hook = this.ctx.options.workload?.[phase];
|
|
2142
|
+
const op = this.activeOperation(namespace);
|
|
2143
|
+
this.phase(namespace, phase === "prepare" ? "preparing" : phase === "verify" ? "verifying" : "resuming");
|
|
2144
|
+
const controller = op ? this.aborts.get(op.id) : new AbortController();
|
|
2145
|
+
if (controller?.signal.aborted && phase !== "resume")
|
|
2146
|
+
throw new Error("operation cancelled before commit");
|
|
2147
|
+
if (!hook)
|
|
2148
|
+
return;
|
|
2149
|
+
const timeout = AbortSignal.timeout(this.ctx.options.hookTimeoutMs ?? 3e4);
|
|
2150
|
+
const signal = controller && !controller.signal.aborted ? AbortSignal.any([controller.signal, timeout]) : timeout;
|
|
2151
|
+
await Promise.race([
|
|
2152
|
+
hook({
|
|
2153
|
+
namespace,
|
|
2154
|
+
services: [...selected.keys()],
|
|
2155
|
+
signal,
|
|
2156
|
+
operationId: op?.id ?? randomUUID3()
|
|
2157
|
+
}),
|
|
2158
|
+
new Promise((_, reject) => signal.addEventListener("abort", () => reject(new Error(`${phase} hook aborted or timed out`)), { once: true }))
|
|
2159
|
+
]);
|
|
2160
|
+
}
|
|
2161
|
+
async createNamespace(namespace, baseline) {
|
|
2162
|
+
if (this.environment && !this.ownsEnvironment())
|
|
2163
|
+
return fleetError(409, "environment operation in progress");
|
|
2164
|
+
if (this.namespaces.has(namespace) || this.topology.has(namespace))
|
|
2165
|
+
return fleetError(409, "namespace already exists or is provisioning");
|
|
2166
|
+
if (this.ctx.controlling.has(namespace))
|
|
2167
|
+
return fleetError(409, "namespace operation in progress", {
|
|
2168
|
+
operationId: this.ctx.controlling.get(namespace)
|
|
2169
|
+
});
|
|
2170
|
+
const limits = this.ctx.options.limits;
|
|
2171
|
+
if (limits?.maxNamespaces !== void 0 && this.namespaces.size + this.topology.size >= limits.maxNamespaces)
|
|
2172
|
+
return fleetError(429, "maximum namespaces reached");
|
|
2173
|
+
const protocolCount = [...this.ctx.children.values()].filter((c) => c.protocol !== "http").length;
|
|
2174
|
+
const listenerCount = [...this.ctx.children.values()].reduce((n, c) => n + (c.protocol === "external" ? 0 : c.protocol === "http" ? 1 : Object.keys(c.namespaces.endpoints ?? {}).length), 1);
|
|
2175
|
+
if (limits?.maxListeners !== void 0 && listenerCount + (this.topology.size + 1) * protocolCount > limits.maxListeners)
|
|
2176
|
+
return fleetError(429, "maximum listeners reached");
|
|
2177
|
+
for (const [name, c] of this.ctx.children)
|
|
2178
|
+
if (!c.createNamespace || !c.deleteNamespace)
|
|
2179
|
+
throw new Error(`namespace provisioning unsupported for ${name}`);
|
|
2180
|
+
const point = baseline ? this.ctx.checkpoints.get(baseline) : void 0;
|
|
2181
|
+
if (baseline && !point)
|
|
2182
|
+
throw new Error("baseline checkpoint not found");
|
|
2183
|
+
this.topology.add(namespace);
|
|
2184
|
+
const created = [];
|
|
2185
|
+
try {
|
|
2186
|
+
this.phase(namespace, "provisioning");
|
|
2187
|
+
const docs = /* @__PURE__ */ new Map();
|
|
2188
|
+
if (point)
|
|
2189
|
+
for (const [name, value] of point.values) {
|
|
2190
|
+
const child = this.ctx.children.get(name);
|
|
2191
|
+
if (!child?.exportCheckpoint || !child.importCheckpoint)
|
|
2192
|
+
throw new Error(`portable baseline unsupported for ${name}`);
|
|
2193
|
+
docs.set(name, await child.exportCheckpoint(point.namespace, value));
|
|
2194
|
+
}
|
|
2195
|
+
for (const [name, child] of this.ctx.children) {
|
|
2196
|
+
await child.createNamespace?.(namespace);
|
|
2197
|
+
created.push(child);
|
|
2198
|
+
if (docs.has(name))
|
|
2199
|
+
await child.restore(namespace, await child.importCheckpoint?.(namespace, docs.get(name)));
|
|
2200
|
+
}
|
|
2201
|
+
if (point)
|
|
2202
|
+
restoreClock(this.ctx.clock(namespace), point.clock);
|
|
2203
|
+
this.remember(namespace);
|
|
2204
|
+
await this.ctx.publish();
|
|
2205
|
+
return Response.json({
|
|
2206
|
+
namespace,
|
|
2207
|
+
generation: this.generation(namespace),
|
|
2208
|
+
manifest: this.ctx.manifest(),
|
|
2209
|
+
connections: Object.fromEntries([...this.ctx.children].map(([n, c]) => [
|
|
2210
|
+
n,
|
|
2211
|
+
c.connections?.[namespace] ?? `${c.url}${this.ctx.config.adminPrefix ?? "/__admin"}/ns/${encodeURIComponent(namespace)}`
|
|
2212
|
+
]))
|
|
2213
|
+
}, { status: 201 });
|
|
2214
|
+
} catch (error) {
|
|
2215
|
+
const results = await Promise.allSettled(created.reverse().map((c) => c.deleteNamespace?.(namespace)));
|
|
2216
|
+
this.namespaces.delete(namespace);
|
|
2217
|
+
if (results.some((r) => r.status === "rejected"))
|
|
2218
|
+
return fleetError(500, "namespace provisioning cleanup failed", {
|
|
2219
|
+
namespace,
|
|
2220
|
+
recoveryRequired: true
|
|
2221
|
+
});
|
|
2222
|
+
throw error;
|
|
2223
|
+
} finally {
|
|
2224
|
+
this.topology.delete(namespace);
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
async deleteNamespace(namespace) {
|
|
2228
|
+
if (this.environment && !this.ownsEnvironment())
|
|
2229
|
+
return fleetError(409, "environment operation in progress");
|
|
2230
|
+
if (namespace === "default")
|
|
2231
|
+
return fleetError(409, "default namespace cannot be deleted");
|
|
2232
|
+
if (!this.namespaces.has(namespace))
|
|
2233
|
+
return fleetError(404, "namespace not found");
|
|
2234
|
+
if (this.remember(namespace).pinned)
|
|
2235
|
+
return fleetError(409, "namespace is pinned");
|
|
2236
|
+
if (this.topology.has(namespace) || this.ctx.controlling.has(namespace) || this.ctx.recovery.has(namespace))
|
|
2237
|
+
return fleetError(409, "namespace is busy or requires recovery");
|
|
2238
|
+
this.scope(namespace, this.ctx.children);
|
|
2239
|
+
const busy = this.busy(namespace);
|
|
2240
|
+
for (const [name, c] of this.ctx.children)
|
|
2241
|
+
if (c.diagnostics(namespace).activeConnections)
|
|
2242
|
+
busy.push(name);
|
|
2243
|
+
if (busy.length)
|
|
2244
|
+
return fleetError(409, "namespace has active work or clients", {
|
|
2245
|
+
services: [...new Set(busy)]
|
|
2246
|
+
});
|
|
2247
|
+
const selected = this.ctx.children;
|
|
2248
|
+
for (const [name, child] of selected)
|
|
2249
|
+
if (!child.deleteNamespace || !child.createNamespace || !child.exportCheckpoint || !child.importCheckpoint)
|
|
2250
|
+
throw new Error(`transactional namespace deletion unsupported for ${name}`);
|
|
2251
|
+
this.topology.add(namespace);
|
|
2252
|
+
const release = [];
|
|
2253
|
+
const documents = /* @__PURE__ */ new Map();
|
|
2254
|
+
const deleted = /* @__PURE__ */ new Set();
|
|
2255
|
+
const original = { ...this.remember(namespace) };
|
|
2256
|
+
try {
|
|
2257
|
+
for (const child of selected.values())
|
|
2258
|
+
release.push(child.lock(namespace));
|
|
2259
|
+
if (this.busy(namespace).length)
|
|
2260
|
+
return fleetError(409, "namespace acquired active work before deletion");
|
|
2261
|
+
for (const [name, child] of selected)
|
|
2262
|
+
documents.set(name, await child.exportCheckpoint?.(namespace, await child.checkpoint(namespace)));
|
|
2263
|
+
for (const [name, child] of selected) {
|
|
2264
|
+
await child.deleteNamespace?.(namespace);
|
|
2265
|
+
deleted.add(name);
|
|
2266
|
+
}
|
|
2267
|
+
this.namespaces.delete(namespace);
|
|
2268
|
+
await this.ctx.publish();
|
|
2269
|
+
for (const [id, p] of this.ctx.checkpoints)
|
|
2270
|
+
if (p.namespace === namespace)
|
|
2271
|
+
this.ctx.checkpoints.delete(id);
|
|
2272
|
+
return Response.json({ status: "deleted", namespace });
|
|
2273
|
+
} catch (error) {
|
|
2274
|
+
const rollback = {};
|
|
2275
|
+
for (const [name, child] of selected)
|
|
2276
|
+
if (documents.has(name)) {
|
|
2277
|
+
try {
|
|
2278
|
+
if (deleted.has(name) || child.protocol !== "http" && !Object.hasOwn(child.namespaces.endpoints ?? {}, namespace))
|
|
2279
|
+
await child.createNamespace?.(namespace);
|
|
2280
|
+
await child.restore(namespace, await child.importCheckpoint?.(namespace, documents.get(name)));
|
|
2281
|
+
rollback[name] = "restored";
|
|
2282
|
+
} catch {
|
|
2283
|
+
rollback[name] = "failed";
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2286
|
+
this.namespaces.set(namespace, original);
|
|
2287
|
+
if (Object.values(rollback).includes("failed")) {
|
|
2288
|
+
const fences = [];
|
|
2289
|
+
for (const child of selected.values())
|
|
2290
|
+
try {
|
|
2291
|
+
fences.push(child.lock(namespace));
|
|
2292
|
+
} catch {
|
|
2293
|
+
}
|
|
2294
|
+
this.ctx.recovery.set(namespace, fences);
|
|
2295
|
+
}
|
|
2296
|
+
await this.ctx.publish().catch(() => {
|
|
2297
|
+
});
|
|
2298
|
+
return fleetError(500, error instanceof Error ? error.message : "namespace deletion failed", {
|
|
2299
|
+
namespace,
|
|
2300
|
+
rollback,
|
|
2301
|
+
rolledBack: Object.values(rollback).every((v) => v === "restored")
|
|
2302
|
+
});
|
|
2303
|
+
} finally {
|
|
2304
|
+
for (const unlock of release.reverse())
|
|
2305
|
+
unlock();
|
|
2306
|
+
this.topology.delete(namespace);
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
async capture(namespaces, selected = this.ctx.children) {
|
|
2310
|
+
if (namespaces.length > 1 && !this.ownsEnvironment())
|
|
2311
|
+
return this.withEnvironment(namespaces, selected, () => this.capture(namespaces, selected));
|
|
2312
|
+
const contents = {};
|
|
2313
|
+
for (const [name, child] of selected)
|
|
2314
|
+
if (!child.exportCheckpoint || !child.importCheckpoint)
|
|
2315
|
+
throw new Error(`portable snapshots unsupported for ${name}`);
|
|
2316
|
+
for (const namespace of namespaces) {
|
|
2317
|
+
this.scope(namespace, selected);
|
|
2318
|
+
const services = {};
|
|
2319
|
+
const response = await this.ctx.transaction(namespace, selected, async (name, child) => {
|
|
2320
|
+
const point = await child.checkpoint(namespace);
|
|
2321
|
+
services[name] = {
|
|
2322
|
+
protocol: child.protocol,
|
|
2323
|
+
target: child.targetName ?? name,
|
|
2324
|
+
version: 1,
|
|
2325
|
+
...child.packageVersion ? { packageVersion: child.packageVersion } : {},
|
|
2326
|
+
state: await child.exportCheckpoint?.(namespace, point)
|
|
2327
|
+
};
|
|
2328
|
+
});
|
|
2329
|
+
if (!response.ok)
|
|
2330
|
+
throw new Error(`capture ${namespace} refused: ${canonical(await response.json())}`);
|
|
2331
|
+
contents[namespace] = { clock: this.ctx.clock(namespace).state(), services };
|
|
2332
|
+
}
|
|
2333
|
+
return sealArchive({
|
|
2334
|
+
format: "mockingbird.fleet/v1",
|
|
2335
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2336
|
+
sourceId: this.ctx.id,
|
|
2337
|
+
namespaces: contents
|
|
2338
|
+
});
|
|
2339
|
+
}
|
|
2340
|
+
async restoreArchive(input, selectedNamespace) {
|
|
2341
|
+
const archive = validateArchive(input);
|
|
2342
|
+
const entries = Object.entries(archive.namespaces).filter(([ns]) => selectedNamespace === void 0 || ns === selectedNamespace);
|
|
2343
|
+
if (!entries.length)
|
|
2344
|
+
throw new Error("selected namespace absent from archive");
|
|
2345
|
+
if (entries.length > 1 && !this.ownsEnvironment()) {
|
|
2346
|
+
const selected = new Map([...new Set(entries.flatMap(([, ns]) => Object.keys(ns.services)))].map((name) => [
|
|
2347
|
+
name,
|
|
2348
|
+
this.ctx.children.get(name)
|
|
2349
|
+
]));
|
|
2350
|
+
for (const [name, child] of selected)
|
|
2351
|
+
if (!child)
|
|
2352
|
+
throw new Error(`unsupported archive service ${name}`);
|
|
2353
|
+
return this.withEnvironment(entries.map(([ns]) => ns), selected, () => this.restoreArchive(archive, selectedNamespace));
|
|
2354
|
+
}
|
|
2355
|
+
for (const [namespace, ns] of entries)
|
|
2356
|
+
for (const [name, state] of Object.entries(ns.services)) {
|
|
2357
|
+
const child = this.ctx.children.get(name);
|
|
2358
|
+
if (!child || child.protocol !== state.protocol || !child.importCheckpoint || (state.target ?? name) !== (child.targetName ?? name))
|
|
2359
|
+
throw new Error(`unsupported archive service ${name}`);
|
|
2360
|
+
await child.importCheckpoint(namespace, state.state);
|
|
2361
|
+
}
|
|
2362
|
+
const rollback = [];
|
|
2363
|
+
const created = [];
|
|
2364
|
+
try {
|
|
2365
|
+
for (const [namespace, ns] of entries) {
|
|
2366
|
+
if (!this.namespaces.has(namespace)) {
|
|
2367
|
+
const response2 = await this.createNamespace(namespace);
|
|
2368
|
+
if (!response2.ok)
|
|
2369
|
+
throw new Error(`namespace creation refused: ${canonical(await response2.json())}`);
|
|
2370
|
+
created.push(namespace);
|
|
2371
|
+
}
|
|
2372
|
+
const selected = new Map(Object.keys(ns.services).map((name) => [name, this.ctx.children.get(name)]));
|
|
2373
|
+
const values = /* @__PURE__ */ new Map();
|
|
2374
|
+
const oldClock = this.ctx.clock(namespace).state();
|
|
2375
|
+
const response = await this.ctx.transaction(namespace, selected, async (name, child) => {
|
|
2376
|
+
values.set(name, await child.checkpoint(namespace));
|
|
2377
|
+
await child.restore(namespace, await child.importCheckpoint?.(namespace, ns.services[name]?.state));
|
|
2378
|
+
}, true);
|
|
2379
|
+
if (!response.ok)
|
|
2380
|
+
throw new Error(`restore ${namespace} failed: ${canonical(await response.json())}`);
|
|
2381
|
+
rollback.push({ namespace, selected, values, clock: oldClock });
|
|
2382
|
+
restoreClock(this.ctx.clock(namespace), ns.clock);
|
|
2383
|
+
this.remember(namespace).generation = randomUUID3();
|
|
2384
|
+
}
|
|
2385
|
+
} catch (error) {
|
|
2386
|
+
const failures = [];
|
|
2387
|
+
for (const point of rollback.reverse()) {
|
|
2388
|
+
const response = await this.ctx.transaction(point.namespace, point.selected, async (name, child) => child.restore(point.namespace, point.values.get(name)), true);
|
|
2389
|
+
if (!response.ok)
|
|
2390
|
+
failures.push(point.namespace);
|
|
2391
|
+
else
|
|
2392
|
+
restoreClock(this.ctx.clock(point.namespace), point.clock);
|
|
2393
|
+
}
|
|
2394
|
+
for (const namespace of created.reverse()) {
|
|
2395
|
+
const response = await this.deleteNamespace(namespace);
|
|
2396
|
+
if (!response.ok)
|
|
2397
|
+
failures.push(namespace);
|
|
2398
|
+
}
|
|
2399
|
+
if (failures.length)
|
|
2400
|
+
throw new Error(`archive rollback requires recovery for ${failures.join(", ")}`, {
|
|
2401
|
+
cause: error
|
|
2402
|
+
});
|
|
2403
|
+
throw error;
|
|
2404
|
+
}
|
|
2405
|
+
}
|
|
2406
|
+
async applyProfile(namespace, input, extra, seedApplication) {
|
|
2407
|
+
if (!object2(input) || !Object.keys(input).length)
|
|
2408
|
+
throw new Error("expected nonempty service control profile");
|
|
2409
|
+
const selected = this.select({ services: Object.keys(input) });
|
|
2410
|
+
for (const [name, child] of selected) {
|
|
2411
|
+
const controls = input[name];
|
|
2412
|
+
if (!object2(controls))
|
|
2413
|
+
throw new Error(`expected controls for ${name}`);
|
|
2414
|
+
normalizeControls(controls, `profile.${name}`);
|
|
2415
|
+
if (child.protocol !== "http" && Object.keys(controls).some((key) => key !== "clock"))
|
|
2416
|
+
throw new Error(`unsupported protocol controls for ${name}`);
|
|
2417
|
+
}
|
|
2418
|
+
return this.ctx.transaction(namespace, selected, async (name, child) => {
|
|
2419
|
+
const controls = input[name];
|
|
2420
|
+
if (child.configure)
|
|
2421
|
+
await child.configure(namespace, controls);
|
|
2422
|
+
else {
|
|
2423
|
+
const plan = normalizeControls(controls);
|
|
2424
|
+
if (plan.clock?.frozen === true)
|
|
2425
|
+
child.clock(namespace).freeze();
|
|
2426
|
+
if (plan.clock?.now !== void 0)
|
|
2427
|
+
child.clock(namespace).set(plan.clock.now);
|
|
2428
|
+
if (plan.clock?.frozen === false)
|
|
2429
|
+
child.clock(namespace).unfreeze();
|
|
2430
|
+
}
|
|
2431
|
+
await extra?.(name, child);
|
|
2432
|
+
if (name === [...selected.keys()].at(-1) && seedApplication) {
|
|
2433
|
+
const operation = [...this.operations.values()].find((o) => o.namespace === namespace && o.status === "running");
|
|
2434
|
+
const token = randomBytes(32).toString("base64url");
|
|
2435
|
+
this.privateRequests.set(namespace, token);
|
|
2436
|
+
const access = [];
|
|
2437
|
+
const connections = {};
|
|
2438
|
+
try {
|
|
2439
|
+
for (const [service, target] of selected) {
|
|
2440
|
+
if (target.initializationAccess) {
|
|
2441
|
+
const seedAccess = await target.initializationAccess();
|
|
2442
|
+
access.push(seedAccess);
|
|
2443
|
+
const url = seedAccess.connections[namespace];
|
|
2444
|
+
if (url)
|
|
2445
|
+
connections[service] = { url, namespaces: { [namespace]: url } };
|
|
2446
|
+
} else
|
|
2447
|
+
connections[service] = { url: target.url, namespaces: {} };
|
|
2448
|
+
}
|
|
2449
|
+
const signal = AbortSignal.timeout(this.ctx.options.hookTimeoutMs ?? 3e4);
|
|
2450
|
+
await Promise.race([
|
|
2451
|
+
seedApplication({
|
|
2452
|
+
namespace,
|
|
2453
|
+
services: [...selected.keys()],
|
|
2454
|
+
operationId: operation?.id ?? randomUUID3(),
|
|
2455
|
+
signal,
|
|
2456
|
+
manifest: this.ctx.manifest(),
|
|
2457
|
+
connections,
|
|
2458
|
+
headers: { "x-mockingbird-initializer": token, "x-mockingbird-namespace": namespace }
|
|
2459
|
+
}),
|
|
2460
|
+
new Promise((_, reject) => signal.addEventListener("abort", () => reject(new Error("application seed hook timed out")), { once: true }))
|
|
2461
|
+
]);
|
|
2462
|
+
} catch (error) {
|
|
2463
|
+
throw Object.assign(new Error("application seed hook failed; recovery required", { cause: error }), { code: "MOCKINGBIRD_WORKLOAD_UNCERTAIN" });
|
|
2464
|
+
} finally {
|
|
2465
|
+
this.privateRequests.delete(namespace);
|
|
2466
|
+
await Promise.all(access.map((a) => a.close()));
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2469
|
+
});
|
|
2470
|
+
}
|
|
2471
|
+
async backup(namespaces, operationId) {
|
|
2472
|
+
if (!this.ctx.options.repository)
|
|
2473
|
+
throw new Error("archive repository is not configured");
|
|
2474
|
+
if (this.backupRunning)
|
|
2475
|
+
throw new Error("backup is already running; overlapping run skipped");
|
|
2476
|
+
this.backupRunning = true;
|
|
2477
|
+
this.backupStatus.lastAttempt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2478
|
+
try {
|
|
2479
|
+
const archive = await this.capture(namespaces);
|
|
2480
|
+
for (const namespace of namespaces)
|
|
2481
|
+
this.phase(namespace, "uploading");
|
|
2482
|
+
if (operationId)
|
|
2483
|
+
await this.journalPhase(operationId, "uploading", { after: archive.sha256 });
|
|
2484
|
+
const id = await this.ctx.options.repository.put(archive);
|
|
2485
|
+
for (const namespace of namespaces)
|
|
2486
|
+
this.phase(namespace, "verifying-upload");
|
|
2487
|
+
const verified = validateArchive(await this.ctx.options.repository.get(id));
|
|
2488
|
+
if (verified.sha256 !== archive.sha256)
|
|
2489
|
+
throw new Error("backup verification failed");
|
|
2490
|
+
if (operationId)
|
|
2491
|
+
await this.journalPhase(operationId, "publishing", this.ctx.options.repository.writerGeneration !== void 0 ? { writerGeneration: this.ctx.options.repository.writerGeneration } : {});
|
|
2492
|
+
for (const namespace of namespaces)
|
|
2493
|
+
this.phase(namespace, "publishing");
|
|
2494
|
+
await this.ctx.options.repository.publishLatest(id);
|
|
2495
|
+
const publication = await this.ctx.options.repository.publicationMetadata?.();
|
|
2496
|
+
if (operationId && publication)
|
|
2497
|
+
await this.journalPhase(operationId, "publishing", {
|
|
2498
|
+
writerGeneration: publication.generation
|
|
2499
|
+
});
|
|
2500
|
+
this.backupStatus.lastSuccess = (/* @__PURE__ */ new Date()).toISOString();
|
|
2501
|
+
this.backupStatus.archiveId = id;
|
|
2502
|
+
delete this.backupStatus.lastFailure;
|
|
2503
|
+
const keep = this.ctx.options.backupPolicy?.keep;
|
|
2504
|
+
if (keep !== void 0) {
|
|
2505
|
+
const archives = await this.ctx.options.repository.list();
|
|
2506
|
+
for (const old of archives.slice(0, Math.max(0, archives.length - keep)))
|
|
2507
|
+
if (old !== id)
|
|
2508
|
+
await this.ctx.options.repository.delete(old);
|
|
2509
|
+
}
|
|
2510
|
+
return { id, sha256: archive.sha256, verified: true };
|
|
2511
|
+
} catch (error) {
|
|
2512
|
+
this.backupStatus.lastFailure = error instanceof Error ? error.message : "backup failed";
|
|
2513
|
+
throw error;
|
|
2514
|
+
} finally {
|
|
2515
|
+
this.backupRunning = false;
|
|
2516
|
+
}
|
|
2517
|
+
}
|
|
2518
|
+
cleanupPreview() {
|
|
2519
|
+
return this.namespaceStatus().filter((entry) => entry.namespace !== "default").map((entry) => {
|
|
2520
|
+
let busy = true;
|
|
2521
|
+
try {
|
|
2522
|
+
busy = this.busy(entry.namespace).length > 0 || [...this.ctx.children.values()].some((c) => c.diagnostics(entry.namespace).activeConnections > 0);
|
|
2523
|
+
} catch {
|
|
2524
|
+
}
|
|
2525
|
+
return {
|
|
2526
|
+
namespace: entry.namespace,
|
|
2527
|
+
expiresAt: entry.expiresAt,
|
|
2528
|
+
pinned: entry.pinned,
|
|
2529
|
+
eligible: entry.expiresAt !== void 0 && !entry.pinned && !busy && entry.status === "ready" && !this.topology.has(entry.namespace) && Date.now() >= (entry.expiresAt ?? Infinity)
|
|
2530
|
+
};
|
|
2531
|
+
});
|
|
2532
|
+
}
|
|
2533
|
+
async startPolicies() {
|
|
2534
|
+
if (this.ctx.options.repository && this.ctx.options.backupPolicy) {
|
|
2535
|
+
try {
|
|
2536
|
+
const id = await this.ctx.options.repository.latest();
|
|
2537
|
+
if (id) {
|
|
2538
|
+
await this.ctx.options.repository.get(id);
|
|
2539
|
+
this.backupStatus.archiveId = id;
|
|
2540
|
+
this.backupStatus.lastSuccess = (/* @__PURE__ */ new Date()).toISOString();
|
|
2541
|
+
}
|
|
2542
|
+
} catch (error) {
|
|
2543
|
+
this.backupStatus.lastFailure = error instanceof Error ? error.message : "repository recovery failed";
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
this.lifecycle = "ready";
|
|
2547
|
+
const policy = this.ctx.options.backupPolicy;
|
|
2548
|
+
if (policy) {
|
|
2549
|
+
if (!Number.isFinite(policy.intervalMs) || policy.intervalMs < 10)
|
|
2550
|
+
throw new Error("backup intervalMs must be at least 10");
|
|
2551
|
+
const schedule = () => {
|
|
2552
|
+
this.backupStatus.nextRun = new Date(Date.now() + policy.intervalMs).toISOString();
|
|
2553
|
+
if (!this.backupRunning)
|
|
2554
|
+
void this.backup(policy.namespaces ?? [...this.namespaces.keys()]).catch(() => {
|
|
2555
|
+
});
|
|
2556
|
+
};
|
|
2557
|
+
this.backupStatus.nextRun = new Date(Date.now() + policy.intervalMs).toISOString();
|
|
2558
|
+
this.timer = setInterval(schedule, policy.intervalMs);
|
|
2559
|
+
this.timer.unref?.();
|
|
2560
|
+
}
|
|
2561
|
+
const expiry = this.ctx.options.expiry;
|
|
2562
|
+
if (expiry) {
|
|
2563
|
+
if (!Number.isFinite(expiry.idleMs) || expiry.idleMs < 1)
|
|
2564
|
+
throw new Error("expiry idleMs must be positive");
|
|
2565
|
+
this.expiryTimer = setInterval(() => {
|
|
2566
|
+
for (const entry of this.cleanupPreview())
|
|
2567
|
+
if (entry.eligible)
|
|
2568
|
+
void (async () => {
|
|
2569
|
+
if (expiry.finalBackup)
|
|
2570
|
+
await this.backup([entry.namespace]);
|
|
2571
|
+
await this.deleteNamespace(entry.namespace);
|
|
2572
|
+
})().catch(() => {
|
|
2573
|
+
});
|
|
2574
|
+
}, expiry.intervalMs ?? 6e4);
|
|
2575
|
+
this.expiryTimer.unref?.();
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
stopPolicies() {
|
|
2579
|
+
clearInterval(this.timer);
|
|
2580
|
+
clearInterval(this.expiryTimer);
|
|
2581
|
+
}
|
|
2582
|
+
};
|
|
2583
|
+
var fleetConsole = (prefix) => `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Mockingbird Fleet</title><style>body{font:16px system-ui;max-width:1000px;margin:3rem auto;padding:1rem;background:#10151b;color:#e0e9f2}input,select,button{padding:.7rem;margin:.3rem;background:#233142;color:inherit;border:1px solid #60768b;border-radius:5px}pre{white-space:pre-wrap;overflow-wrap:anywhere}a{color:#9fdbff}</style><h1>Mockingbird Fleet</h1><label>Admin key <input id="key" type="password" autocomplete="off"></label><label>Namespace <input id="ns" value="default"></label><button id="refresh">Refresh</button><section id="children"></section><label>Action <select id="action"><option value="snapshots">Capture checkpoint</option><option value="reset">Reset namespace</option></select></label><button id="run">Run</button><h2>Lifecycle and operations</h2><pre id="result"></pre><script type="module">const base=${JSON.stringify(`${prefix}/fleet`)};const key=document.querySelector('#key'),ns=document.querySelector('#ns'),result=document.querySelector('#result');async function api(path,method='GET',body){const r=await fetch(base+path,{method,headers:{'content-type':'application/json','x-mockingbird-admin-key':key.value},...(body?{body:JSON.stringify(body)}:{})});const data=await r.json();result.textContent=JSON.stringify(data,null,2);return data}document.querySelector('#refresh').onclick=async()=>{const data=await api('');const host=document.querySelector('#children');host.replaceChildren();for(const [name,child]of Object.entries(data.manifest?.services??{})){const link=document.createElement('a');link.href=child.adminUrl;link.textContent=name+' ('+child.protocol+') ';host.append(link)}await api('/operations?namespace='+encodeURIComponent(ns.value))};document.querySelector('#run').onclick=()=>api('/namespaces/'+encodeURIComponent(ns.value)+'/'+document.querySelector('#action').value,'POST',{});</script></html>`;
|
|
2584
|
+
|
|
2585
|
+
// ../../adapters/node/dist/fleet-preflight.js
|
|
2586
|
+
import { readFile, realpath } from "node:fs/promises";
|
|
2587
|
+
import { createRequire } from "node:module";
|
|
2588
|
+
import { basename, dirname, resolve } from "node:path";
|
|
2589
|
+
|
|
2590
|
+
// ../../adapters/node/dist/fleet-config.schema.json
|
|
2591
|
+
var fleet_config_schema_default = {
|
|
2592
|
+
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
2593
|
+
$id: "https://mockingbird.chrisvouga.dev/schemas/fleet-v1.json",
|
|
2594
|
+
title: "Mockingbird fleet configuration v1",
|
|
2595
|
+
type: "object",
|
|
2596
|
+
required: ["services"],
|
|
2597
|
+
additionalProperties: false,
|
|
2598
|
+
properties: {
|
|
2599
|
+
$schema: {
|
|
2600
|
+
const: "https://mockingbird.chrisvouga.dev/schemas/fleet-v1.json"
|
|
2601
|
+
},
|
|
2602
|
+
schemaVersion: {
|
|
2603
|
+
const: 1
|
|
2604
|
+
},
|
|
2605
|
+
services: {
|
|
2606
|
+
type: "object",
|
|
2607
|
+
propertyNames: {
|
|
2608
|
+
pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$"
|
|
2609
|
+
},
|
|
2610
|
+
additionalProperties: {
|
|
2611
|
+
$ref: "#/$defs/service"
|
|
2612
|
+
}
|
|
2613
|
+
},
|
|
2614
|
+
log: {
|
|
2615
|
+
enum: ["pretty", "json", "off"]
|
|
2616
|
+
},
|
|
2617
|
+
adminPrefix: {
|
|
2618
|
+
type: "string"
|
|
2619
|
+
},
|
|
2620
|
+
adminKey: {
|
|
2621
|
+
type: "string"
|
|
2622
|
+
},
|
|
2623
|
+
adminControls: {
|
|
2624
|
+
$ref: "#/$defs/controls"
|
|
2625
|
+
},
|
|
2626
|
+
namespace: {
|
|
2627
|
+
type: "string",
|
|
2628
|
+
pattern: "^[A-Za-z0-9_.-]{1,64}$"
|
|
2629
|
+
},
|
|
2630
|
+
control: {
|
|
2631
|
+
type: "object",
|
|
2632
|
+
additionalProperties: false,
|
|
2633
|
+
properties: {
|
|
2634
|
+
port: {
|
|
2635
|
+
type: "integer",
|
|
2636
|
+
minimum: 0,
|
|
2637
|
+
maximum: 65535
|
|
2638
|
+
},
|
|
2639
|
+
host: {
|
|
2640
|
+
type: "string"
|
|
2641
|
+
}
|
|
2642
|
+
}
|
|
2643
|
+
},
|
|
2644
|
+
cors: {
|
|
2645
|
+
type: "object",
|
|
2646
|
+
required: ["origins"],
|
|
2647
|
+
additionalProperties: false,
|
|
2648
|
+
properties: {
|
|
2649
|
+
origins: {
|
|
2650
|
+
type: "array",
|
|
2651
|
+
items: {
|
|
2652
|
+
type: "string"
|
|
2653
|
+
}
|
|
2654
|
+
},
|
|
2655
|
+
methods: {
|
|
2656
|
+
type: "array",
|
|
2657
|
+
items: {
|
|
2658
|
+
enum: ["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"]
|
|
2659
|
+
}
|
|
2660
|
+
},
|
|
2661
|
+
headers: {
|
|
2662
|
+
type: "array",
|
|
2663
|
+
items: {
|
|
2664
|
+
type: "string"
|
|
2665
|
+
}
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
},
|
|
2669
|
+
extensions: {
|
|
2670
|
+
type: "object",
|
|
2671
|
+
propertyNames: {
|
|
2672
|
+
pattern: "^x-[a-z0-9-]+$"
|
|
2673
|
+
},
|
|
2674
|
+
additionalProperties: false
|
|
2675
|
+
}
|
|
2676
|
+
},
|
|
2677
|
+
$defs: {
|
|
2678
|
+
service: {
|
|
2679
|
+
type: "object",
|
|
2680
|
+
additionalProperties: false,
|
|
2681
|
+
properties: {
|
|
2682
|
+
target: {
|
|
2683
|
+
type: "string",
|
|
2684
|
+
pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$"
|
|
2685
|
+
},
|
|
2686
|
+
dependsOn: {
|
|
2687
|
+
type: "array",
|
|
2688
|
+
items: {
|
|
2689
|
+
type: "string"
|
|
2690
|
+
}
|
|
2691
|
+
},
|
|
2692
|
+
protocol: {
|
|
2693
|
+
enum: ["http", "postgres", "redis"]
|
|
2694
|
+
},
|
|
2695
|
+
port: {
|
|
2696
|
+
type: "integer",
|
|
2697
|
+
minimum: 0,
|
|
2698
|
+
maximum: 65535
|
|
2699
|
+
},
|
|
2700
|
+
host: {
|
|
2701
|
+
type: "string"
|
|
2702
|
+
},
|
|
2703
|
+
adminPrefix: {
|
|
2704
|
+
type: "string"
|
|
2705
|
+
},
|
|
2706
|
+
adminKey: {
|
|
2707
|
+
type: "string"
|
|
2708
|
+
},
|
|
2709
|
+
seed: {
|
|
2710
|
+
type: "string"
|
|
2711
|
+
},
|
|
2712
|
+
adminControls: {
|
|
2713
|
+
$ref: "#/$defs/controls"
|
|
2714
|
+
},
|
|
2715
|
+
fixtures: {
|
|
2716
|
+
type: "object"
|
|
2717
|
+
},
|
|
2718
|
+
baseUrl: {
|
|
2719
|
+
type: "string"
|
|
2720
|
+
},
|
|
2721
|
+
password: {
|
|
2722
|
+
type: "string"
|
|
2723
|
+
},
|
|
2724
|
+
user: {
|
|
2725
|
+
type: "string"
|
|
2726
|
+
},
|
|
2727
|
+
database: {
|
|
2728
|
+
type: "string"
|
|
2729
|
+
},
|
|
2730
|
+
namespaces: {
|
|
2731
|
+
type: "object",
|
|
2732
|
+
propertyNames: {
|
|
2733
|
+
pattern: "^[A-Za-z0-9_.-]{1,64}$"
|
|
2734
|
+
},
|
|
2735
|
+
additionalProperties: {
|
|
2736
|
+
anyOf: [
|
|
2737
|
+
{
|
|
2738
|
+
type: "string"
|
|
2739
|
+
},
|
|
2740
|
+
{
|
|
2741
|
+
type: "integer",
|
|
2742
|
+
minimum: 0,
|
|
2743
|
+
maximum: 15
|
|
2744
|
+
}
|
|
2745
|
+
]
|
|
2746
|
+
}
|
|
2747
|
+
},
|
|
2748
|
+
options: {
|
|
2749
|
+
type: "object",
|
|
2750
|
+
additionalProperties: false,
|
|
2751
|
+
description: "Compose the selected target option schema before supplying service-specific flags."
|
|
2752
|
+
},
|
|
2753
|
+
publicOrigin: {
|
|
2754
|
+
type: "string"
|
|
2755
|
+
},
|
|
2756
|
+
publicPath: {
|
|
2757
|
+
type: "string"
|
|
2758
|
+
}
|
|
2759
|
+
}
|
|
2760
|
+
},
|
|
2761
|
+
controls: {
|
|
2762
|
+
type: "object",
|
|
2763
|
+
additionalProperties: false,
|
|
2764
|
+
properties: {
|
|
2765
|
+
seed: {},
|
|
2766
|
+
clock: {
|
|
2767
|
+
type: "object"
|
|
2768
|
+
},
|
|
2769
|
+
latency: {},
|
|
2770
|
+
faults: {
|
|
2771
|
+
type: "array"
|
|
2772
|
+
},
|
|
2773
|
+
snapshot: {
|
|
2774
|
+
type: "object"
|
|
2775
|
+
},
|
|
2776
|
+
virtualTime: {
|
|
2777
|
+
type: "boolean"
|
|
2778
|
+
},
|
|
2779
|
+
credentials: {
|
|
2780
|
+
type: "object"
|
|
2781
|
+
},
|
|
2782
|
+
namespaces: {
|
|
2783
|
+
type: "object"
|
|
2784
|
+
}
|
|
2785
|
+
}
|
|
2786
|
+
}
|
|
2787
|
+
}
|
|
2788
|
+
};
|
|
2789
|
+
|
|
2790
|
+
// ../../adapters/node/dist/fleet-schema.js
|
|
2791
|
+
var object3 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
2792
|
+
function validateFleetConfig(value, targetOptions = {}, extensions = {}) {
|
|
2793
|
+
const composed = composeFleetSchema(value, targetOptions, extensions), issues = [];
|
|
2794
|
+
const walk = (input, rule, path, output) => {
|
|
2795
|
+
if (rule.$ref) {
|
|
2796
|
+
const resolved = composed.$defs?.[rule.$ref.slice("#/$defs/".length)];
|
|
2797
|
+
if (!resolved)
|
|
2798
|
+
output.push({ path, message: "unresolved configuration schema" });
|
|
2799
|
+
else
|
|
2800
|
+
walk(input, resolved, path, output);
|
|
2801
|
+
return;
|
|
2802
|
+
}
|
|
2803
|
+
if (rule.anyOf) {
|
|
2804
|
+
if (!rule.anyOf.some((branch) => {
|
|
2805
|
+
const found = [];
|
|
2806
|
+
walk(input, branch, path, found);
|
|
2807
|
+
return found.length === 0;
|
|
2808
|
+
}))
|
|
2809
|
+
output.push({ path, message: "value does not match an allowed shape" });
|
|
2810
|
+
return;
|
|
2811
|
+
}
|
|
2812
|
+
if ("const" in rule && input !== rule.const) {
|
|
2813
|
+
output.push({
|
|
2814
|
+
path,
|
|
2815
|
+
message: path === "$.schemaVersion" || path === "$.$schema" ? "unsupported fleet schema version; upgrade the consumer/schema together" : "unexpected fixed value"
|
|
2816
|
+
});
|
|
2817
|
+
return;
|
|
2818
|
+
}
|
|
2819
|
+
if (rule.enum && !rule.enum.includes(input))
|
|
2820
|
+
output.push({ path, message: "unsupported enumerated value" });
|
|
2821
|
+
if (rule.type) {
|
|
2822
|
+
const valid = rule.type === "object" ? object3(input) : rule.type === "array" ? Array.isArray(input) : rule.type === "integer" ? typeof input === "number" && Number.isInteger(input) : typeof input === rule.type;
|
|
2823
|
+
if (!valid) {
|
|
2824
|
+
output.push({ path, message: `expected ${rule.type}` });
|
|
2825
|
+
return;
|
|
2826
|
+
}
|
|
2827
|
+
}
|
|
2828
|
+
if (typeof input === "number" && (rule.minimum !== void 0 && input < rule.minimum || rule.maximum !== void 0 && input > rule.maximum))
|
|
2829
|
+
output.push({ path, message: "number outside supported bounds" });
|
|
2830
|
+
if (typeof input === "string" && rule.pattern && !new RegExp(rule.pattern).test(input))
|
|
2831
|
+
output.push({ path, message: "invalid identifier" });
|
|
2832
|
+
if (Array.isArray(input) && rule.items)
|
|
2833
|
+
input.forEach((entry, index) => {
|
|
2834
|
+
walk(entry, rule.items, `${path}[${index}]`, output);
|
|
2835
|
+
});
|
|
2836
|
+
if (object3(input)) {
|
|
2837
|
+
for (const name of rule.required ?? [])
|
|
2838
|
+
if (!Object.hasOwn(input, name))
|
|
2839
|
+
output.push({ path: `${path}.${name}`, message: "required field missing" });
|
|
2840
|
+
for (const [key, entry] of Object.entries(input)) {
|
|
2841
|
+
if (rule.propertyNames)
|
|
2842
|
+
walk(key, rule.propertyNames, `${path}.${key}`, output);
|
|
2843
|
+
const property = rule.properties?.[key];
|
|
2844
|
+
if (property)
|
|
2845
|
+
walk(entry, property, `${path}.${key}`, output);
|
|
2846
|
+
else if (rule.additionalProperties === false)
|
|
2847
|
+
output.push({ path: `${path}.${key}`, message: "unknown configuration field" });
|
|
2848
|
+
else if (object3(rule.additionalProperties))
|
|
2849
|
+
walk(entry, rule.additionalProperties, `${path}.${key}`, output);
|
|
2850
|
+
}
|
|
2851
|
+
}
|
|
2852
|
+
};
|
|
2853
|
+
walk(value, composed, "$", issues);
|
|
2854
|
+
return issues;
|
|
2855
|
+
}
|
|
2856
|
+
function composeFleetSchema(value, targetOptions = {}, extensions = {}) {
|
|
2857
|
+
const composed = structuredClone(fleet_config_schema_default);
|
|
2858
|
+
const serviceRule = composed.$defs?.service;
|
|
2859
|
+
const servicesRule = composed.properties?.services;
|
|
2860
|
+
servicesRule.properties = {};
|
|
2861
|
+
if (object3(value) && object3(value.services))
|
|
2862
|
+
for (const [instance, entry] of Object.entries(value.services)) {
|
|
2863
|
+
if (!object3(entry))
|
|
2864
|
+
continue;
|
|
2865
|
+
const target = typeof entry.target === "string" ? entry.target : instance;
|
|
2866
|
+
const declared = targetOptions[target] ?? {};
|
|
2867
|
+
const configured = structuredClone(serviceRule);
|
|
2868
|
+
configured.properties = {
|
|
2869
|
+
...configured.properties,
|
|
2870
|
+
options: {
|
|
2871
|
+
type: "object",
|
|
2872
|
+
additionalProperties: false,
|
|
2873
|
+
properties: Object.fromEntries(Object.entries(declared).map(([key, option]) => [key, { type: option.type }]))
|
|
2874
|
+
}
|
|
2875
|
+
};
|
|
2876
|
+
servicesRule.properties[instance] = configured;
|
|
2877
|
+
}
|
|
2878
|
+
if (composed.properties?.extensions)
|
|
2879
|
+
composed.properties.extensions.properties = extensions;
|
|
2880
|
+
return composed;
|
|
2881
|
+
}
|
|
2882
|
+
function assertFleetConfig(config, targetOptions = {}) {
|
|
2883
|
+
const issues = validateFleetConfig(config, targetOptions);
|
|
2884
|
+
if (issues.length)
|
|
2885
|
+
throw new Error(issues.slice(0, 20).map((i) => `${i.path}: ${i.message}`).join("; "));
|
|
2886
|
+
}
|
|
2887
|
+
|
|
2888
|
+
// ../../adapters/node/dist/fleet-preflight.js
|
|
2889
|
+
var destination = async (path) => {
|
|
2890
|
+
const absolute = resolve(path);
|
|
2891
|
+
try {
|
|
2892
|
+
return await realpath(absolute);
|
|
2893
|
+
} catch (error) {
|
|
2894
|
+
if (error.code !== "ENOENT")
|
|
2895
|
+
throw error;
|
|
2896
|
+
const parent = dirname(absolute);
|
|
2897
|
+
return parent === absolute ? absolute : resolve(await destination(parent), basename(absolute));
|
|
2898
|
+
}
|
|
2899
|
+
};
|
|
2900
|
+
async function preflightFleet(config, options) {
|
|
2901
|
+
if (options.readyFile && options.connectionsFile && await destination(options.readyFile) === await destination(options.connectionsFile))
|
|
2902
|
+
throw new Error("ready-file and connections-file destinations must differ");
|
|
2903
|
+
if (!config.services || typeof config.services !== "object" || !Object.keys(config.services).length && !Object.keys(options.participants ?? {}).length)
|
|
2904
|
+
throw new Error("config must contain at least one service");
|
|
2905
|
+
validateFleetPolicies(options);
|
|
2906
|
+
if (options.archiveProtection && options.repository && options.repository.protectionPolicy?.format !== options.archiveProtection.policy.format)
|
|
2907
|
+
throw new Error("protected archive policy requires a protected repository; configure its protector before startup");
|
|
2908
|
+
resolveAdminPrefix(config.adminPrefix);
|
|
2909
|
+
normalizeBootControls(config.adminControls);
|
|
2910
|
+
const targets = /* @__PURE__ */ new Map();
|
|
2911
|
+
const ports = /* @__PURE__ */ new Set();
|
|
2912
|
+
for (const [name, entry] of Object.entries(config.services)) {
|
|
2913
|
+
try {
|
|
2914
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name))
|
|
2915
|
+
throw new Error("invalid service name");
|
|
2916
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
2917
|
+
throw new Error("expected service object");
|
|
2918
|
+
resolveAdminPrefix(entry.adminPrefix ?? config.adminPrefix);
|
|
2919
|
+
normalizeBootControls({ ...config.adminControls, ...entry.adminControls }, `services.${name}.adminControls`);
|
|
2920
|
+
if (entry.port !== void 0 && (!Number.isInteger(entry.port) || entry.port < 0 || entry.port > 65535))
|
|
2921
|
+
throw new Error("invalid port");
|
|
2922
|
+
if (entry.target !== void 0 && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(entry.target))
|
|
2923
|
+
throw new Error("target must name a supported service suffix");
|
|
2924
|
+
const service = entry.target ?? name;
|
|
2925
|
+
if (advertisedHttpBase(entry) && service !== "stripe")
|
|
2926
|
+
throw new Error(`public ingress unsupported for ${service}; use a direct endpoint to preserve signed targets`);
|
|
2927
|
+
const target = await options.load(service);
|
|
2928
|
+
const protocol = "protocol" in target ? target.protocol : "http";
|
|
2929
|
+
if (entry.protocol !== void 0 && entry.protocol !== protocol)
|
|
2930
|
+
throw new Error("configured protocol does not match target");
|
|
2931
|
+
if (protocol !== "http") {
|
|
2932
|
+
if (entry.seed !== void 0 && (!String(entry.seed).trim() || !Number.isFinite(Number(entry.seed))))
|
|
2933
|
+
throw new Error("protocol seed must be a finite number");
|
|
2934
|
+
for (const [namespace, selector] of Object.entries(entry.namespaces ?? {})) {
|
|
2935
|
+
if (!/^[A-Za-z0-9_.-]{1,64}$/.test(namespace))
|
|
2936
|
+
throw new Error("invalid namespace");
|
|
2937
|
+
if (protocol === "postgres" ? typeof selector !== "string" || !selector.length : typeof selector !== "number" || !Number.isInteger(selector) || selector < 0 || selector > 15)
|
|
2938
|
+
throw new Error("invalid protocol namespace selector");
|
|
2939
|
+
}
|
|
2940
|
+
}
|
|
2941
|
+
const port = entry.port ?? target.defaultPort;
|
|
2942
|
+
if (port !== 0) {
|
|
2943
|
+
const key = `${entry.host ?? "127.0.0.1"}:${port}`;
|
|
2944
|
+
if (ports.has(key))
|
|
2945
|
+
throw new Error(`duplicate listener ${key}`);
|
|
2946
|
+
ports.add(key);
|
|
2947
|
+
}
|
|
2948
|
+
let packageVersion = target.packageVersion;
|
|
2949
|
+
if (!packageVersion) {
|
|
2950
|
+
for (const from of [
|
|
2951
|
+
createRequire(resolve(process.cwd(), "package.json")),
|
|
2952
|
+
createRequire(import.meta.url)
|
|
2953
|
+
]) {
|
|
2954
|
+
try {
|
|
2955
|
+
let directory = dirname(from.resolve(`@crvouga/mockingbird-service-${service}/server`));
|
|
2956
|
+
for (; ; ) {
|
|
2957
|
+
try {
|
|
2958
|
+
const manifest = JSON.parse(await readFile(resolve(directory, "package.json"), "utf8"));
|
|
2959
|
+
if (manifest.name === `@crvouga/mockingbird-service-${service}`) {
|
|
2960
|
+
packageVersion = manifest.version;
|
|
2961
|
+
break;
|
|
2962
|
+
}
|
|
2963
|
+
} catch {
|
|
2964
|
+
}
|
|
2965
|
+
const parent = dirname(directory);
|
|
2966
|
+
if (parent === directory)
|
|
2967
|
+
break;
|
|
2968
|
+
directory = parent;
|
|
2969
|
+
}
|
|
2970
|
+
} catch {
|
|
2971
|
+
}
|
|
2972
|
+
if (packageVersion)
|
|
2973
|
+
break;
|
|
2974
|
+
}
|
|
2975
|
+
}
|
|
2976
|
+
targets.set(name, { ...target, packageVersion: packageVersion ?? "1.4.0" });
|
|
2977
|
+
} catch (error) {
|
|
2978
|
+
throw new Error(`service ${name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
2979
|
+
}
|
|
2980
|
+
}
|
|
2981
|
+
for (const [name, participant] of Object.entries(options.participants ?? {})) {
|
|
2982
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) || targets.has(name))
|
|
2983
|
+
throw new Error(`external participant identity collision ${name}`);
|
|
2984
|
+
if (participant.protocol !== "external")
|
|
2985
|
+
throw new Error(`registered participant ${name} must declare external protocol`);
|
|
2986
|
+
targets.set(name, {
|
|
2987
|
+
name,
|
|
2988
|
+
protocol: "external",
|
|
2989
|
+
defaultPort: 0,
|
|
2990
|
+
start: async () => participant
|
|
2991
|
+
});
|
|
2992
|
+
}
|
|
2993
|
+
assertFleetConfig(config, Object.fromEntries([...targets].map(([name, target]) => [
|
|
2994
|
+
config.services[name]?.target ?? name,
|
|
2995
|
+
"options" in target ? target.options ?? {} : {}
|
|
2996
|
+
])));
|
|
2997
|
+
const ordered = /* @__PURE__ */ new Map();
|
|
2998
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
2999
|
+
const visit = (name, chain) => {
|
|
3000
|
+
if (ordered.has(name))
|
|
3001
|
+
return;
|
|
3002
|
+
if (!targets.has(name))
|
|
3003
|
+
throw new Error(`unknown dependency ${[...chain, name].join(" -> ")}`);
|
|
3004
|
+
if (visiting.has(name))
|
|
3005
|
+
throw new Error(`dependency cycle ${[...chain, name].join(" -> ")}`);
|
|
3006
|
+
visiting.add(name);
|
|
3007
|
+
const dependencies = config.services[name]?.dependsOn ?? options.participants?.[name]?.dependencies ?? [];
|
|
3008
|
+
if (!Array.isArray(dependencies) || dependencies.some((d) => typeof d !== "string"))
|
|
3009
|
+
throw new Error(`services.${name}.dependsOn must be a list of instance names`);
|
|
3010
|
+
for (const dependency of dependencies)
|
|
3011
|
+
visit(dependency, [...chain, name]);
|
|
3012
|
+
visiting.delete(name);
|
|
3013
|
+
ordered.set(name, targets.get(name));
|
|
3014
|
+
};
|
|
3015
|
+
for (const name of targets.keys())
|
|
3016
|
+
visit(name, []);
|
|
3017
|
+
return ordered;
|
|
3018
|
+
}
|
|
3019
|
+
function validateFleetPolicies(options) {
|
|
3020
|
+
if (options.journal && !options.repository)
|
|
3021
|
+
throw new Error("durable operation journal requires an archive repository");
|
|
3022
|
+
if (options.cors) {
|
|
3023
|
+
if (!Array.isArray(options.cors.origins) || options.cors.origins.some((o) => {
|
|
3024
|
+
try {
|
|
3025
|
+
const u = new URL(o);
|
|
3026
|
+
return !["http:", "https:"].includes(u.protocol) || u.origin !== o;
|
|
3027
|
+
} catch {
|
|
3028
|
+
return true;
|
|
3029
|
+
}
|
|
3030
|
+
}))
|
|
3031
|
+
throw new Error("cors.origins must contain explicit HTTP origins");
|
|
3032
|
+
if (options.cors.methods?.some((m) => !["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"].includes(m)) || options.cors.headers?.some((h) => !/^[a-zA-Z0-9-]+$/.test(h)))
|
|
3033
|
+
throw new Error("invalid CORS methods/headers");
|
|
3034
|
+
}
|
|
3035
|
+
for (const [key, value] of Object.entries(options.limits ?? {})) {
|
|
3036
|
+
if (!["maxNamespaces", "maxListeners", "connections"].includes(key))
|
|
3037
|
+
throw new Error(`unsupported namespace budget ${key}`);
|
|
3038
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
3039
|
+
throw new Error(`invalid limit ${key}`);
|
|
3040
|
+
}
|
|
3041
|
+
for (const [key, value] of Object.entries(options.retention ?? {}))
|
|
3042
|
+
if (!["maxCount", "ttlMs"].includes(key) || !Number.isSafeInteger(value) || value < 1)
|
|
3043
|
+
throw new Error(`invalid retention ${key}`);
|
|
3044
|
+
if (options.backupPolicy && (!options.repository || !Number.isSafeInteger(options.backupPolicy.intervalMs) || options.backupPolicy.intervalMs < 10 || options.backupPolicy.keep !== void 0 && (!Number.isSafeInteger(options.backupPolicy.keep) || options.backupPolicy.keep < 1)))
|
|
3045
|
+
throw new Error("backup policy requires a repository, intervalMs >= 10 and positive retention");
|
|
3046
|
+
if (options.expiry && (!Number.isSafeInteger(options.expiry.idleMs) || options.expiry.idleMs < 1 || options.expiry.intervalMs !== void 0 && (!Number.isSafeInteger(options.expiry.intervalMs) || options.expiry.intervalMs < 10) || options.expiry.finalBackup && !options.repository))
|
|
3047
|
+
throw new Error("invalid expiry policy or missing final-backup repository");
|
|
3048
|
+
for (const duration of [
|
|
3049
|
+
options.hookTimeoutMs,
|
|
3050
|
+
options.initializationTimeoutMs,
|
|
3051
|
+
options.shutdownTimeoutMs
|
|
3052
|
+
])
|
|
3053
|
+
if (duration !== void 0 && (!Number.isSafeInteger(duration) || duration < 1))
|
|
3054
|
+
throw new Error("hook deadlines must be positive integer milliseconds");
|
|
3055
|
+
}
|
|
24
3056
|
|
|
25
3057
|
// ../../adapters/node/dist/serve.js
|
|
26
3058
|
import { createServer } from "node:http";
|
|
3059
|
+
import { Readable } from "node:stream";
|
|
27
3060
|
var serve = async (api, options = {}) => {
|
|
3061
|
+
const maxBytes = options.maxBodyBytes ?? 16 * 1024 * 1024;
|
|
3062
|
+
const timeoutMs = options.requestTimeoutMs ?? 3e4;
|
|
3063
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1)
|
|
3064
|
+
throw new Error("invalid request limits");
|
|
28
3065
|
const server = createServer(async (req, res) => {
|
|
29
|
-
const chunks = [];
|
|
30
|
-
for await (const chunk of req) {
|
|
31
|
-
chunks.push(Buffer.from(chunk));
|
|
32
|
-
}
|
|
33
|
-
const body = Buffer.concat(chunks);
|
|
34
|
-
const address = server.address();
|
|
35
|
-
const port = typeof address === "object" && address !== null ? address.port : void 0;
|
|
36
|
-
const base = `http://${req.headers.host ?? `localhost:${port ?? 80}`}`;
|
|
37
|
-
const raw = req.url ?? "/";
|
|
38
|
-
const url = new URL(raw.replace(/^\/+/, "/"), base);
|
|
39
|
-
const method = req.method ?? "GET";
|
|
40
|
-
const init = { method, headers: req.headers };
|
|
41
|
-
if (method !== "GET" && method !== "HEAD" && body.length > 0) {
|
|
42
|
-
init.body = body;
|
|
43
|
-
}
|
|
44
3066
|
const aborted = new AbortController();
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
3067
|
+
let reader;
|
|
3068
|
+
let timer;
|
|
3069
|
+
const abort = () => {
|
|
3070
|
+
aborted.abort();
|
|
3071
|
+
void reader?.cancel().catch(() => {
|
|
3072
|
+
});
|
|
3073
|
+
};
|
|
3074
|
+
const fail = (status, message) => {
|
|
3075
|
+
if (!res.headersSent && !res.destroyed) {
|
|
3076
|
+
res.writeHead(status, { "content-type": "application/json", connection: "close" });
|
|
3077
|
+
res.end(JSON.stringify({ error: { type: "mockingbird_transport", message } }));
|
|
3078
|
+
}
|
|
3079
|
+
abort();
|
|
3080
|
+
};
|
|
3081
|
+
req.once("aborted", abort);
|
|
3082
|
+
res.once("close", abort);
|
|
3083
|
+
res.once("error", abort);
|
|
52
3084
|
try {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
3085
|
+
const address = server.address();
|
|
3086
|
+
const port = typeof address === "object" && address !== null ? address.port : 80;
|
|
3087
|
+
const url = new URL((req.url ?? "/").replace(/^\/+/, "/"), `http://${req.headers.host ?? `localhost:${port}`}`);
|
|
3088
|
+
const headers = new Headers();
|
|
3089
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
3090
|
+
if (Array.isArray(value))
|
|
3091
|
+
for (const item of value)
|
|
3092
|
+
headers.append(name, item);
|
|
3093
|
+
else if (value !== void 0)
|
|
3094
|
+
headers.set(name, value);
|
|
3095
|
+
}
|
|
3096
|
+
const init = {
|
|
3097
|
+
method: req.method ?? "GET",
|
|
3098
|
+
headers,
|
|
3099
|
+
signal: aborted.signal
|
|
3100
|
+
};
|
|
3101
|
+
if (init.method !== "GET" && init.method !== "HEAD") {
|
|
3102
|
+
if (Number(req.headers["content-length"]) > maxBytes) {
|
|
3103
|
+
fail(413, "request body exceeds byte limit");
|
|
3104
|
+
return;
|
|
3105
|
+
}
|
|
3106
|
+
let bytes = 0;
|
|
3107
|
+
const source = Readable.toWeb(req);
|
|
3108
|
+
init.body = source.pipeThrough(new TransformStream({
|
|
3109
|
+
transform(chunk, controller) {
|
|
3110
|
+
bytes += chunk.byteLength;
|
|
3111
|
+
if (bytes > maxBytes) {
|
|
3112
|
+
fail(413, "request body exceeds byte limit");
|
|
3113
|
+
controller.error(new Error("request body exceeds byte limit"));
|
|
3114
|
+
} else
|
|
3115
|
+
controller.enqueue(chunk);
|
|
3116
|
+
}
|
|
3117
|
+
}));
|
|
3118
|
+
init.duplex = "half";
|
|
3119
|
+
timer = setTimeout(() => fail(408, "request body timed out"), timeoutMs);
|
|
3120
|
+
req.once("end", () => clearTimeout(timer));
|
|
3121
|
+
}
|
|
3122
|
+
const response = await api.fetch(new Request(url, init));
|
|
3123
|
+
if (aborted.signal.aborted || res.destroyed) {
|
|
3124
|
+
await response.body?.cancel();
|
|
57
3125
|
return;
|
|
58
3126
|
}
|
|
59
|
-
|
|
3127
|
+
const output = Object.fromEntries(response.headers);
|
|
3128
|
+
const cookies = response.headers.getSetCookie();
|
|
3129
|
+
if (cookies.length)
|
|
3130
|
+
output["set-cookie"] = cookies;
|
|
3131
|
+
res.writeHead(response.status, output);
|
|
3132
|
+
if (!response.body) {
|
|
3133
|
+
res.end();
|
|
60
3134
|
return;
|
|
61
|
-
|
|
62
|
-
res.
|
|
63
|
-
|
|
64
|
-
type: "mockingbird_internal",
|
|
65
|
-
message: error instanceof Error ? error.message : String(error)
|
|
66
|
-
}
|
|
67
|
-
}));
|
|
68
|
-
return;
|
|
69
|
-
}
|
|
70
|
-
const headers = Object.fromEntries(response.headers);
|
|
71
|
-
const cookies = response.headers.getSetCookie();
|
|
72
|
-
if (cookies.length > 0)
|
|
73
|
-
headers["set-cookie"] = cookies;
|
|
74
|
-
if (!response.body) {
|
|
75
|
-
res.writeHead(response.status, headers);
|
|
76
|
-
res.end();
|
|
77
|
-
return;
|
|
78
|
-
}
|
|
79
|
-
res.writeHead(response.status, headers);
|
|
80
|
-
res.flushHeaders();
|
|
81
|
-
const reader = response.body.getReader();
|
|
82
|
-
try {
|
|
3135
|
+
}
|
|
3136
|
+
res.flushHeaders();
|
|
3137
|
+
reader = response.body.getReader();
|
|
83
3138
|
for (; ; ) {
|
|
84
3139
|
const { done, value } = await reader.read();
|
|
85
|
-
if (done)
|
|
3140
|
+
if (done || aborted.signal.aborted)
|
|
86
3141
|
break;
|
|
87
|
-
if (!res.write(value))
|
|
88
|
-
await new Promise((
|
|
3142
|
+
if (!res.write(value)) {
|
|
3143
|
+
await new Promise((resolve4) => {
|
|
3144
|
+
const finish = () => {
|
|
3145
|
+
res.off("drain", finish);
|
|
3146
|
+
res.off("close", finish);
|
|
3147
|
+
res.off("error", finish);
|
|
3148
|
+
resolve4();
|
|
3149
|
+
};
|
|
3150
|
+
res.once("drain", finish);
|
|
3151
|
+
res.once("close", finish);
|
|
3152
|
+
res.once("error", finish);
|
|
3153
|
+
if (res.destroyed || aborted.signal.aborted)
|
|
3154
|
+
finish();
|
|
3155
|
+
});
|
|
3156
|
+
}
|
|
3157
|
+
}
|
|
3158
|
+
if (!aborted.signal.aborted)
|
|
3159
|
+
res.end();
|
|
3160
|
+
} catch (error) {
|
|
3161
|
+
if (error.code === "MOCKINGBIRD_DROP")
|
|
3162
|
+
req.socket.destroy();
|
|
3163
|
+
else if (!aborted.signal.aborted && !res.destroyed) {
|
|
3164
|
+
if (res.headersSent)
|
|
3165
|
+
res.destroy();
|
|
3166
|
+
else {
|
|
3167
|
+
res.writeHead(500, { "content-type": "application/json" });
|
|
3168
|
+
res.end(JSON.stringify({
|
|
3169
|
+
error: {
|
|
3170
|
+
type: "mockingbird_internal",
|
|
3171
|
+
message: error instanceof Error ? error.message : String(error)
|
|
3172
|
+
}
|
|
3173
|
+
}));
|
|
3174
|
+
}
|
|
89
3175
|
}
|
|
90
|
-
res.end();
|
|
91
|
-
} catch {
|
|
92
|
-
await new Promise((resolve2) => setImmediate(resolve2));
|
|
93
|
-
res.destroy();
|
|
94
3176
|
} finally {
|
|
95
|
-
|
|
3177
|
+
clearTimeout(timer);
|
|
3178
|
+
reader?.releaseLock();
|
|
3179
|
+
req.off("aborted", abort);
|
|
3180
|
+
res.off("close", abort);
|
|
3181
|
+
res.off("error", abort);
|
|
3182
|
+
if (!req.complete)
|
|
3183
|
+
req.resume();
|
|
96
3184
|
}
|
|
97
3185
|
});
|
|
98
|
-
|
|
3186
|
+
server.requestTimeout = timeoutMs;
|
|
3187
|
+
await new Promise((resolve4, reject) => {
|
|
99
3188
|
server.once("error", reject);
|
|
100
|
-
server.listen(options.port ?? 0, options.host,
|
|
3189
|
+
server.listen(options.port ?? 0, options.host, resolve4);
|
|
101
3190
|
});
|
|
102
3191
|
return server;
|
|
103
3192
|
};
|
|
@@ -114,12 +3203,12 @@ var listen = async (api, options = {}) => {
|
|
|
114
3203
|
port,
|
|
115
3204
|
host,
|
|
116
3205
|
server,
|
|
117
|
-
close: () => new Promise((
|
|
3206
|
+
close: () => new Promise((resolve4, reject) => {
|
|
118
3207
|
server.close((error) => {
|
|
119
3208
|
if (error && error.code !== "ERR_SERVER_NOT_RUNNING")
|
|
120
3209
|
reject(error);
|
|
121
3210
|
else
|
|
122
|
-
|
|
3211
|
+
resolve4();
|
|
123
3212
|
});
|
|
124
3213
|
server.closeAllConnections?.();
|
|
125
3214
|
})
|
|
@@ -136,7 +3225,26 @@ var EMPTY = {
|
|
|
136
3225
|
unmatchedRequests: 0
|
|
137
3226
|
};
|
|
138
3227
|
var NS = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
139
|
-
var json = (status, value) =>
|
|
3228
|
+
var json = (status, value) => {
|
|
3229
|
+
if (status >= 400 && isObject(value)) {
|
|
3230
|
+
const message = typeof value.error === "string" ? value.error : typeof value.message === "string" ? value.message : value.status === "failed" ? "fleet operation failed" : "fleet request rejected";
|
|
3231
|
+
return Response.json({
|
|
3232
|
+
...value,
|
|
3233
|
+
error: {
|
|
3234
|
+
type: "mockingbird_admin",
|
|
3235
|
+
code: {
|
|
3236
|
+
400: "invalid_request",
|
|
3237
|
+
401: "unauthorized",
|
|
3238
|
+
404: "not_found",
|
|
3239
|
+
409: "conflict",
|
|
3240
|
+
500: "operation_failed"
|
|
3241
|
+
}[status] ?? "request_failed",
|
|
3242
|
+
message
|
|
3243
|
+
}
|
|
3244
|
+
}, { status });
|
|
3245
|
+
}
|
|
3246
|
+
return Response.json(value, { status });
|
|
3247
|
+
};
|
|
140
3248
|
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
141
3249
|
var pending = (d) => d.activeRequests + d.blockedCommands + d.pendingJobs + d.pendingWebhooks;
|
|
142
3250
|
var publicUrl = (raw) => {
|
|
@@ -145,7 +3253,7 @@ var publicUrl = (raw) => {
|
|
|
145
3253
|
return url.href;
|
|
146
3254
|
};
|
|
147
3255
|
var atomicWrite = async (path, value) => {
|
|
148
|
-
const temp = `${path}.${
|
|
3256
|
+
const temp = `${path}.${randomUUID4()}.tmp`;
|
|
149
3257
|
try {
|
|
150
3258
|
await writeFile(temp, `${JSON.stringify(value, null, 2)}
|
|
151
3259
|
`, { mode: 384, flag: "wx" });
|
|
@@ -159,7 +3267,7 @@ var removeOwned = async (path, id) => {
|
|
|
159
3267
|
if (!path)
|
|
160
3268
|
return;
|
|
161
3269
|
try {
|
|
162
|
-
const value = JSON.parse(await
|
|
3270
|
+
const value = JSON.parse(await readFile2(path, "utf8"));
|
|
163
3271
|
if (isObject(value) && value.id === id)
|
|
164
3272
|
await rm(path, { force: true });
|
|
165
3273
|
} catch (error) {
|
|
@@ -167,29 +3275,114 @@ var removeOwned = async (path, id) => {
|
|
|
167
3275
|
throw error;
|
|
168
3276
|
}
|
|
169
3277
|
};
|
|
170
|
-
var httpChild = async (target, entry, options) => {
|
|
171
|
-
const
|
|
3278
|
+
var httpChild = async (target, entry, options, admission, generation, privateAccess, observer) => {
|
|
3279
|
+
const requestLog = new AsyncLocalStorage2();
|
|
3280
|
+
const created = await target.create(entry.options ?? {}, {
|
|
172
3281
|
adminPrefix: resolveAdminPrefix(entry.adminPrefix),
|
|
173
3282
|
adminKey: entry.adminKey,
|
|
174
3283
|
seed: entry.seed,
|
|
175
|
-
onLog:
|
|
3284
|
+
onLog: (entry2) => {
|
|
3285
|
+
const current = requestLog.getStore();
|
|
3286
|
+
if (current)
|
|
3287
|
+
current.entry = entry2;
|
|
3288
|
+
options.onLog?.(entry2);
|
|
3289
|
+
},
|
|
176
3290
|
...entry.adminControls !== void 0 ? { adminControls: entry.adminControls } : {},
|
|
177
3291
|
...entry.fixtures !== void 0 ? { fixtures: entry.fixtures } : {},
|
|
178
|
-
...entry.baseUrl !== void 0 ? { baseUrl: entry.baseUrl } : {}
|
|
3292
|
+
...(advertisedHttpBase(entry) ?? entry.baseUrl) !== void 0 ? { baseUrl: advertisedHttpBase(entry) ?? entry.baseUrl } : {}
|
|
179
3293
|
});
|
|
3294
|
+
if (!isObject(created) || [
|
|
3295
|
+
"fetch",
|
|
3296
|
+
"fleetSnapshot",
|
|
3297
|
+
"fleetRestore",
|
|
3298
|
+
"fleetExport",
|
|
3299
|
+
"fleetImport",
|
|
3300
|
+
"namespaceOf",
|
|
3301
|
+
"instance",
|
|
3302
|
+
"namespaceClock",
|
|
3303
|
+
"reset",
|
|
3304
|
+
"configure",
|
|
3305
|
+
"dropNamespace"
|
|
3306
|
+
].some((method) => typeof created[method] !== "function"))
|
|
3307
|
+
throw new Error("HTTP target does not implement the fleet runtime protocol; build/install matching supported service versions");
|
|
3308
|
+
const runtime = created;
|
|
3309
|
+
const unobserve = runtime.webhooks?.observeDeliveries(observer.delivery);
|
|
3310
|
+
if (options.outbound && runtime.webhooks)
|
|
3311
|
+
runtime.webhooks.setTransportPolicy(ownedTransport(options.outbound));
|
|
180
3312
|
const adminPrefix = resolveAdminPrefix(entry.adminPrefix);
|
|
181
3313
|
const locked = /* @__PURE__ */ new Set();
|
|
182
3314
|
const active = /* @__PURE__ */ new Map();
|
|
3315
|
+
const activity = /* @__PURE__ */ new Map();
|
|
183
3316
|
const api = {
|
|
184
3317
|
async fetch(request) {
|
|
185
3318
|
const namespace = runtime.namespaceOf(request);
|
|
186
|
-
if (locked.has(namespace))
|
|
3319
|
+
if (locked.has(namespace) && !privateAccess(namespace, request))
|
|
187
3320
|
return json(409, { error: "fleet control in progress", namespace });
|
|
3321
|
+
if (!new URL(request.url).pathname.endsWith(`${adminPrefix}/health`)) {
|
|
3322
|
+
const refused = admission(namespace, request);
|
|
3323
|
+
if (refused)
|
|
3324
|
+
return refused;
|
|
3325
|
+
}
|
|
3326
|
+
activity.set(namespace, Date.now());
|
|
188
3327
|
active.set(namespace, (active.get(namespace) ?? 0) + 1);
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
3328
|
+
let complete = false;
|
|
3329
|
+
const finish = () => {
|
|
3330
|
+
if (complete)
|
|
3331
|
+
return;
|
|
3332
|
+
complete = true;
|
|
192
3333
|
active.set(namespace, (active.get(namespace) ?? 1) - 1);
|
|
3334
|
+
request.signal.removeEventListener("abort", finish);
|
|
3335
|
+
};
|
|
3336
|
+
request.signal.addEventListener("abort", finish, { once: true });
|
|
3337
|
+
try {
|
|
3338
|
+
const log = {}, traceToken = observer.begin(namespace, request), started = performance.now();
|
|
3339
|
+
const response = await requestLog.run(log, () => runtime.fetch(request));
|
|
3340
|
+
await observer.finish(namespace, request, response, log.entry ?? {
|
|
3341
|
+
service: target.name,
|
|
3342
|
+
namespace,
|
|
3343
|
+
operationId: void 0,
|
|
3344
|
+
method: request.method,
|
|
3345
|
+
path: new URL(request.url).pathname,
|
|
3346
|
+
status: response.status,
|
|
3347
|
+
durationMs: performance.now() - started,
|
|
3348
|
+
unmatched: response.status === 404
|
|
3349
|
+
}, traceToken);
|
|
3350
|
+
if (!response.body) {
|
|
3351
|
+
finish();
|
|
3352
|
+
return response;
|
|
3353
|
+
}
|
|
3354
|
+
const reader = response.body.getReader();
|
|
3355
|
+
const headers = new Headers(response.headers);
|
|
3356
|
+
const epoch = generation(namespace);
|
|
3357
|
+
if (epoch)
|
|
3358
|
+
headers.set("x-mockingbird-generation", epoch);
|
|
3359
|
+
return new Response(new ReadableStream({
|
|
3360
|
+
async pull(controller) {
|
|
3361
|
+
try {
|
|
3362
|
+
const next = await reader.read();
|
|
3363
|
+
if (next.done) {
|
|
3364
|
+
finish();
|
|
3365
|
+
controller.close();
|
|
3366
|
+
reader.releaseLock();
|
|
3367
|
+
} else
|
|
3368
|
+
controller.enqueue(next.value);
|
|
3369
|
+
} catch (error) {
|
|
3370
|
+
finish();
|
|
3371
|
+
controller.error(error);
|
|
3372
|
+
}
|
|
3373
|
+
},
|
|
3374
|
+
async cancel(reason) {
|
|
3375
|
+
try {
|
|
3376
|
+
await reader.cancel(reason);
|
|
3377
|
+
} finally {
|
|
3378
|
+
finish();
|
|
3379
|
+
reader.releaseLock();
|
|
3380
|
+
}
|
|
3381
|
+
}
|
|
3382
|
+
}), { status: response.status, statusText: response.statusText, headers });
|
|
3383
|
+
} catch (error) {
|
|
3384
|
+
finish();
|
|
3385
|
+
throw error;
|
|
193
3386
|
}
|
|
194
3387
|
}
|
|
195
3388
|
};
|
|
@@ -201,6 +3394,7 @@ var httpChild = async (target, entry, options) => {
|
|
|
201
3394
|
});
|
|
202
3395
|
target.listening?.(server);
|
|
203
3396
|
} catch (error) {
|
|
3397
|
+
unobserve?.();
|
|
204
3398
|
runtime.stop?.();
|
|
205
3399
|
await server?.close();
|
|
206
3400
|
runtime.webhooks?.clear();
|
|
@@ -209,6 +3403,7 @@ var httpChild = async (target, entry, options) => {
|
|
|
209
3403
|
}
|
|
210
3404
|
return {
|
|
211
3405
|
protocol: "http",
|
|
3406
|
+
outboundPolicy: runtime.webhooks ? "webhook-hub" : "unsupported",
|
|
212
3407
|
url: server.url,
|
|
213
3408
|
healthUrl: `${server.url}${adminPrefix}/health`,
|
|
214
3409
|
adminUrl: `${server.url}${adminPrefix}`,
|
|
@@ -221,6 +3416,7 @@ var httpChild = async (target, entry, options) => {
|
|
|
221
3416
|
}
|
|
222
3417
|
},
|
|
223
3418
|
async close() {
|
|
3419
|
+
unobserve?.();
|
|
224
3420
|
runtime.stop?.();
|
|
225
3421
|
runtime.webhooks?.clear();
|
|
226
3422
|
await server.close();
|
|
@@ -248,30 +3444,141 @@ var httpChild = async (target, entry, options) => {
|
|
|
248
3444
|
},
|
|
249
3445
|
reset: (namespace) => runtime.reset(namespace),
|
|
250
3446
|
clock: (namespace) => runtime.namespaceClock(namespace),
|
|
3447
|
+
unmatched(namespace, limit) {
|
|
3448
|
+
const entries = runtime.metrics.report(namespace).unmatched;
|
|
3449
|
+
return {
|
|
3450
|
+
entries: entries.slice(0, limit).map(({ method, path, count }) => ({
|
|
3451
|
+
method,
|
|
3452
|
+
pathFingerprint: createHash4("sha256").update(path).digest("hex"),
|
|
3453
|
+
count
|
|
3454
|
+
})),
|
|
3455
|
+
truncated: entries.length > limit
|
|
3456
|
+
};
|
|
3457
|
+
},
|
|
3458
|
+
lastActivity: (namespace) => activity.get(namespace) ?? 0,
|
|
3459
|
+
async exportCheckpoint(_namespace, point) {
|
|
3460
|
+
return runtime.fleetExport(point);
|
|
3461
|
+
},
|
|
3462
|
+
async importCheckpoint(namespace, document) {
|
|
3463
|
+
return runtime.fleetImport(namespace, document);
|
|
3464
|
+
},
|
|
3465
|
+
async createNamespace(namespace) {
|
|
3466
|
+
runtime.instance(namespace);
|
|
3467
|
+
},
|
|
3468
|
+
deleteNamespace: (namespace) => runtime.dropNamespace(namespace),
|
|
3469
|
+
async configure(namespace, controls) {
|
|
3470
|
+
return runtime.configure(controls, namespace);
|
|
3471
|
+
},
|
|
3472
|
+
async inspect(namespace, { offset, limit, collection }) {
|
|
3473
|
+
const doc = runtime.fleetExport(runtime.fleetSnapshot(namespace));
|
|
3474
|
+
const rows = collection ? doc.records.filter((row) => row.collection === collection) : doc.records;
|
|
3475
|
+
return {
|
|
3476
|
+
total: rows.length,
|
|
3477
|
+
offset,
|
|
3478
|
+
records: rows.slice(offset, offset + limit),
|
|
3479
|
+
collections: [...new Set(doc.records.map((row) => row.collection))]
|
|
3480
|
+
};
|
|
3481
|
+
},
|
|
3482
|
+
...typeof runtime.instance().nextEvent === "function" ? {
|
|
3483
|
+
nextEvent: (namespace) => runtime.instance(namespace).nextEvent()
|
|
3484
|
+
} : {},
|
|
251
3485
|
async settle(namespace) {
|
|
252
3486
|
const instance = runtime.instance(namespace);
|
|
253
|
-
instance.tick?.();
|
|
254
|
-
await runtime.webhooks?.idle();
|
|
3487
|
+
await instance.tick?.();
|
|
3488
|
+
await runtime.webhooks?.idle(namespace);
|
|
255
3489
|
}
|
|
256
3490
|
};
|
|
257
3491
|
};
|
|
258
3492
|
async function startFleet(config, options) {
|
|
259
|
-
|
|
3493
|
+
if (config.cors && options.cors === void 0)
|
|
3494
|
+
options = { ...options, cors: config.cors };
|
|
3495
|
+
const targets = await preflightFleet(config, options);
|
|
3496
|
+
const id = randomUUID4();
|
|
260
3497
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
261
3498
|
const children = /* @__PURE__ */ new Map();
|
|
262
3499
|
const clocks = /* @__PURE__ */ new Map();
|
|
263
3500
|
const checkpoints = /* @__PURE__ */ new Map();
|
|
264
3501
|
let supervisor;
|
|
265
|
-
let
|
|
266
|
-
let
|
|
267
|
-
const
|
|
268
|
-
|
|
3502
|
+
let management;
|
|
3503
|
+
let manifest;
|
|
3504
|
+
const privateConnections = () => Object.fromEntries([...children].map(([name, child]) => [
|
|
3505
|
+
name,
|
|
3506
|
+
{ url: child.connection ?? child.url, namespaces: child.connections }
|
|
3507
|
+
]));
|
|
3508
|
+
const publish = async () => {
|
|
3509
|
+
if (!manifest || management && management.lifecycle !== "ready")
|
|
269
3510
|
return;
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
3511
|
+
manifest.state = recovery.size ? "recovery-required" : "ready";
|
|
3512
|
+
for (const [name, child] of children)
|
|
3513
|
+
if (manifest.services[name])
|
|
3514
|
+
manifest.services[name].namespaces = child.namespaces;
|
|
3515
|
+
if (options.connectionsFile)
|
|
3516
|
+
await atomicWrite(options.connectionsFile, {
|
|
3517
|
+
version: 1,
|
|
3518
|
+
id,
|
|
3519
|
+
pid: process.pid,
|
|
3520
|
+
services: privateConnections()
|
|
3521
|
+
});
|
|
3522
|
+
if (options.readyFile)
|
|
3523
|
+
await atomicWrite(options.readyFile, manifest);
|
|
3524
|
+
};
|
|
3525
|
+
let stopped = false;
|
|
3526
|
+
const controlling = /* @__PURE__ */ new Map();
|
|
3527
|
+
const recovery = /* @__PURE__ */ new Map();
|
|
3528
|
+
let closing;
|
|
3529
|
+
const close = () => {
|
|
3530
|
+
if (closing)
|
|
3531
|
+
return closing;
|
|
3532
|
+
closing = (async () => {
|
|
3533
|
+
management?.stopPolicies();
|
|
3534
|
+
let gateFailure;
|
|
3535
|
+
if (options.beforeClose && management && ["ready", "failed"].includes(management.lifecycle)) {
|
|
3536
|
+
management.lifecycle = "draining";
|
|
3537
|
+
const signal = AbortSignal.timeout(options.shutdownTimeoutMs ?? 3e4);
|
|
3538
|
+
try {
|
|
3539
|
+
await Promise.race([
|
|
3540
|
+
options.beforeClose({
|
|
3541
|
+
manifest,
|
|
3542
|
+
signal,
|
|
3543
|
+
capture: (namespaces) => management.capture(namespaces)
|
|
3544
|
+
}),
|
|
3545
|
+
new Promise((_, reject) => signal.addEventListener("abort", () => reject(new Error("pre-shutdown hook timed out")), { once: true }))
|
|
3546
|
+
]);
|
|
3547
|
+
} catch (error) {
|
|
3548
|
+
management.lifecycle = "failed";
|
|
3549
|
+
if (options.shutdownFailure !== "close") {
|
|
3550
|
+
closing = void 0;
|
|
3551
|
+
throw error;
|
|
3552
|
+
}
|
|
3553
|
+
gateFailure = error;
|
|
3554
|
+
}
|
|
3555
|
+
}
|
|
3556
|
+
stopped = true;
|
|
3557
|
+
if (management)
|
|
3558
|
+
management.lifecycle = "stopped";
|
|
3559
|
+
const entries = [...children];
|
|
3560
|
+
const results = [];
|
|
3561
|
+
for (const [, child] of [...entries].reverse()) {
|
|
3562
|
+
try {
|
|
3563
|
+
await child.close();
|
|
3564
|
+
results.unshift({ status: "fulfilled", value: void 0 });
|
|
3565
|
+
} catch (reason) {
|
|
3566
|
+
results.unshift({ status: "rejected", reason });
|
|
3567
|
+
}
|
|
3568
|
+
}
|
|
3569
|
+
const cleanup = await Promise.allSettled([
|
|
3570
|
+
supervisor?.close(),
|
|
3571
|
+
removeOwned(options.readyFile, id),
|
|
3572
|
+
removeOwned(options.connectionsFile, id)
|
|
3573
|
+
]);
|
|
3574
|
+
const failures = results.flatMap((r, i) => r.status === "rejected" ? [{ service: entries[i]?.[0], cause: r.reason }] : []);
|
|
3575
|
+
if (gateFailure)
|
|
3576
|
+
failures.push({ service: "pre-shutdown", cause: gateFailure });
|
|
3577
|
+
failures.push(...cleanup.flatMap((r) => r.status === "rejected" ? [{ service: "controller", cause: r.reason }] : []));
|
|
3578
|
+
if (failures.length)
|
|
3579
|
+
throw new AggregateError(failures.map((f) => f.cause), `fleet shutdown failed: ${failures.map((f) => f.service).join(", ")}`);
|
|
3580
|
+
})();
|
|
3581
|
+
return closing;
|
|
275
3582
|
};
|
|
276
3583
|
if (options.readyFile)
|
|
277
3584
|
await rm(options.readyFile, { force: true });
|
|
@@ -281,6 +3588,12 @@ async function startFleet(config, options) {
|
|
|
281
3588
|
let value = clocks.get(namespace);
|
|
282
3589
|
if (!value) {
|
|
283
3590
|
value = createClock();
|
|
3591
|
+
const plan = normalizeBootControls(config.adminControls);
|
|
3592
|
+
const boot = { ...plan.shared.clock, ...plan.namespaces[namespace]?.clock };
|
|
3593
|
+
if (boot.frozen)
|
|
3594
|
+
value.freeze();
|
|
3595
|
+
if (boot.now !== void 0)
|
|
3596
|
+
value.set(boot.now);
|
|
284
3597
|
clocks.set(namespace, value);
|
|
285
3598
|
}
|
|
286
3599
|
return value;
|
|
@@ -298,19 +3611,47 @@ async function startFleet(config, options) {
|
|
|
298
3611
|
}
|
|
299
3612
|
return selected;
|
|
300
3613
|
};
|
|
301
|
-
const diagnostics = (namespace) => Object.fromEntries([...
|
|
302
|
-
const
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
3614
|
+
const diagnostics = (namespace, selected = children) => Object.fromEntries([...selected].map(([name, child]) => [name, child.diagnostics(namespace)]));
|
|
3615
|
+
const missingNamespace = (namespace, selected) => {
|
|
3616
|
+
const missing = [...selected].filter(([, c]) => c.protocol !== "http" && !Object.hasOwn(c.namespaces.endpoints ?? {}, namespace)).map(([name]) => name);
|
|
3617
|
+
return missing.length ? json(404, { error: "namespace is not configured", namespace, services: missing }) : void 0;
|
|
3618
|
+
};
|
|
3619
|
+
const transaction = async (namespace, selected, run, recover = false) => {
|
|
3620
|
+
const unavailable = missingNamespace(namespace, selected);
|
|
3621
|
+
if (unavailable)
|
|
3622
|
+
return unavailable;
|
|
3623
|
+
if (management?.topologyBusy(namespace))
|
|
3624
|
+
return json(409, { error: "namespace topology operation in progress" });
|
|
3625
|
+
if (controlling.has(namespace))
|
|
3626
|
+
return json(409, {
|
|
3627
|
+
error: "another fleet operation is in progress",
|
|
3628
|
+
operationId: controlling.get(namespace)
|
|
3629
|
+
});
|
|
3630
|
+
if (recovery.has(namespace) && !recover)
|
|
3631
|
+
return json(409, {
|
|
3632
|
+
error: "namespace requires explicit reset or restore recovery",
|
|
3633
|
+
namespace
|
|
3634
|
+
});
|
|
3635
|
+
const held = recovery.get(namespace);
|
|
3636
|
+
if (held) {
|
|
3637
|
+
for (const unlock of held.reverse())
|
|
3638
|
+
unlock();
|
|
3639
|
+
recovery.delete(namespace);
|
|
3640
|
+
}
|
|
3641
|
+
controlling.set(namespace, management?.operationId(namespace) ?? randomUUID4());
|
|
306
3642
|
const release = [];
|
|
3643
|
+
let keepFence = false;
|
|
307
3644
|
const before = /* @__PURE__ */ new Map();
|
|
308
3645
|
const results = {};
|
|
309
3646
|
let failure;
|
|
310
3647
|
try {
|
|
3648
|
+
if (![...selected.keys()].every((name) => management?.environmentFence(namespace, name)))
|
|
3649
|
+
await management?.hook("prepare", namespace, selected);
|
|
3650
|
+
management?.phase(namespace, "checkpointing");
|
|
311
3651
|
for (const [name, child] of selected) {
|
|
312
3652
|
failure = name;
|
|
313
|
-
|
|
3653
|
+
if (!management?.environmentFence(namespace, name))
|
|
3654
|
+
release.push(child.lock(namespace));
|
|
314
3655
|
}
|
|
315
3656
|
const busy = Object.fromEntries([...selected].filter(([, child]) => {
|
|
316
3657
|
const state = child.diagnostics(namespace);
|
|
@@ -320,24 +3661,54 @@ async function startFleet(config, options) {
|
|
|
320
3661
|
return json(409, { error: "namespace is not quiescent", services: busy });
|
|
321
3662
|
for (const [name, child] of selected) {
|
|
322
3663
|
failure = name;
|
|
3664
|
+
management?.phase(namespace, "checkpointing", before.size, selected.size, name);
|
|
323
3665
|
before.set(name, await child.checkpoint(namespace));
|
|
324
3666
|
}
|
|
3667
|
+
management?.checkCancelled(namespace);
|
|
3668
|
+
management?.phase(namespace, "committing");
|
|
325
3669
|
for (const [name, child] of selected) {
|
|
326
3670
|
failure = name;
|
|
3671
|
+
management?.phase(namespace, "committing", Object.keys(results).length, selected.size, name);
|
|
327
3672
|
results[name] = { status: "ok", result: await run(name, child) };
|
|
3673
|
+
management?.phase(namespace, "committing", Object.keys(results).length, selected.size);
|
|
3674
|
+
}
|
|
3675
|
+
await management?.hook("verify", namespace, selected);
|
|
3676
|
+
try {
|
|
3677
|
+
await management?.hook("resume", namespace, selected);
|
|
3678
|
+
} catch (error) {
|
|
3679
|
+
keepFence = true;
|
|
3680
|
+
throw error;
|
|
328
3681
|
}
|
|
329
3682
|
return json(200, { status: "ok", namespace, services: results });
|
|
330
|
-
} catch {
|
|
3683
|
+
} catch (error) {
|
|
3684
|
+
if (error.code === "MOCKINGBIRD_WORKLOAD_UNCERTAIN")
|
|
3685
|
+
keepFence = true;
|
|
331
3686
|
const rollback = {};
|
|
332
3687
|
for (const [name, point] of before) {
|
|
333
3688
|
try {
|
|
3689
|
+
management?.phase(namespace, "rolling-back", void 0, void 0, name);
|
|
334
3690
|
await selected.get(name)?.restore(namespace, point);
|
|
335
3691
|
rollback[name] = "restored";
|
|
336
3692
|
} catch {
|
|
337
3693
|
rollback[name] = "failed";
|
|
3694
|
+
management?.phase(namespace, "rollback-failed", void 0, void 0, name);
|
|
338
3695
|
}
|
|
339
3696
|
}
|
|
3697
|
+
keepFence = keepFence || Object.values(rollback).includes("failed") || held !== void 0;
|
|
3698
|
+
if (!keepFence)
|
|
3699
|
+
try {
|
|
3700
|
+
await management?.hook("resume", namespace, selected);
|
|
3701
|
+
} catch {
|
|
3702
|
+
keepFence = true;
|
|
3703
|
+
}
|
|
3704
|
+
if (keepFence && release.length === 0)
|
|
3705
|
+
for (const child of selected.values())
|
|
3706
|
+
try {
|
|
3707
|
+
release.push(child.lock(namespace));
|
|
3708
|
+
} catch {
|
|
3709
|
+
}
|
|
340
3710
|
return json(500, {
|
|
3711
|
+
error: error instanceof Error ? error.message : "fleet operation failed",
|
|
341
3712
|
status: "failed",
|
|
342
3713
|
namespace,
|
|
343
3714
|
failedService: failure,
|
|
@@ -346,12 +3717,15 @@ async function startFleet(config, options) {
|
|
|
346
3717
|
rolledBack: before.size > 0 && Object.values(rollback).every((value) => value === "restored")
|
|
347
3718
|
});
|
|
348
3719
|
} finally {
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
3720
|
+
if (keepFence)
|
|
3721
|
+
recovery.set(namespace, release);
|
|
3722
|
+
else
|
|
3723
|
+
for (const unlock of release.reverse())
|
|
3724
|
+
unlock();
|
|
3725
|
+
controlling.delete(namespace);
|
|
352
3726
|
}
|
|
353
3727
|
};
|
|
354
|
-
const
|
|
3728
|
+
const coreApi = {
|
|
355
3729
|
async fetch(request) {
|
|
356
3730
|
const url = new URL(request.url);
|
|
357
3731
|
const adminPrefix = resolveAdminPrefix(config.adminPrefix);
|
|
@@ -382,13 +3756,20 @@ async function startFleet(config, options) {
|
|
|
382
3756
|
}
|
|
383
3757
|
if (!path.startsWith("/fleet/"))
|
|
384
3758
|
return json(404, { error: "not found" });
|
|
385
|
-
const adminKey = config.adminKey ?? process.env.MOCKINGBIRD_ADMIN_KEY;
|
|
386
|
-
if (adminKey !== void 0 && request.headers.get("x-mockingbird-admin-key") !== adminKey)
|
|
387
|
-
return json(401, { error: "admin key required" });
|
|
388
3759
|
const route = /^\/fleet\/namespaces\/([^/]+)\/(reset|snapshots)(?:\/([^/]+)\/restore)?$/.exec(path);
|
|
389
|
-
|
|
3760
|
+
let namespace;
|
|
3761
|
+
try {
|
|
3762
|
+
namespace = route ? decodeURIComponent(route[1]) : url.searchParams.get("namespace") ?? request.headers.get("x-mockingbird-namespace") ?? config.namespace ?? "default";
|
|
3763
|
+
} catch {
|
|
3764
|
+
return json(400, { error: "invalid namespace encoding" });
|
|
3765
|
+
}
|
|
390
3766
|
if (!NS.test(namespace))
|
|
391
3767
|
return json(400, { error: "invalid namespace" });
|
|
3768
|
+
if (request.method === "GET") {
|
|
3769
|
+
const unavailable2 = missingNamespace(namespace, children);
|
|
3770
|
+
if (unavailable2)
|
|
3771
|
+
return unavailable2;
|
|
3772
|
+
}
|
|
392
3773
|
if (request.method === "GET" && path === "/fleet/metrics")
|
|
393
3774
|
return json(200, { namespace, services: diagnostics(namespace) });
|
|
394
3775
|
if (request.method === "GET" && path === "/fleet/clock")
|
|
@@ -415,13 +3796,27 @@ async function startFleet(config, options) {
|
|
|
415
3796
|
} catch (error) {
|
|
416
3797
|
return json(400, { error: error instanceof Error ? error.message : "bad selection" });
|
|
417
3798
|
}
|
|
3799
|
+
const allowed = route?.[3] ? [] : path === "/fleet/clock" ? ["services", "set", "advance", "freeze"] : route?.[2] === "snapshots" ? ["services", "label"] : ["services"];
|
|
3800
|
+
if (Object.keys(body).some((key) => !allowed.includes(key)))
|
|
3801
|
+
return json(400, { error: "unknown control field" });
|
|
3802
|
+
if (body.label !== void 0 && (typeof body.label !== "string" || body.label.length > 256))
|
|
3803
|
+
return json(400, { error: "label must be a string of at most 256 characters" });
|
|
3804
|
+
const unavailable = missingNamespace(namespace, selected);
|
|
3805
|
+
if (unavailable)
|
|
3806
|
+
return unavailable;
|
|
418
3807
|
if (path === "/fleet/wait-until-idle") {
|
|
419
|
-
const services = diagnostics(namespace);
|
|
3808
|
+
const services = diagnostics(namespace, selected);
|
|
420
3809
|
const idle = Object.values(services).every((d) => pending(d) === 0);
|
|
421
3810
|
return json(idle ? 200 : 409, { status: idle ? "idle" : "busy", namespace, services });
|
|
422
3811
|
}
|
|
423
3812
|
if (path === "/fleet/clock") {
|
|
424
3813
|
const current = clock(namespace);
|
|
3814
|
+
if (body.set === void 0 && body.advance === void 0 && body.freeze === void 0)
|
|
3815
|
+
return json(200, {
|
|
3816
|
+
namespace,
|
|
3817
|
+
...current.state(),
|
|
3818
|
+
services: Object.fromEntries([...selected].map(([name, child]) => [name, child.clock(namespace).state()]))
|
|
3819
|
+
});
|
|
425
3820
|
let target = current.now();
|
|
426
3821
|
if (body.set !== void 0) {
|
|
427
3822
|
target = typeof body.set === "number" ? body.set : typeof body.set === "string" ? Date.parse(body.set) : NaN;
|
|
@@ -439,7 +3834,10 @@ async function startFleet(config, options) {
|
|
|
439
3834
|
return json(400, { error: "freeze must be boolean" });
|
|
440
3835
|
const response2 = await transaction(namespace, selected, async (_name, child) => {
|
|
441
3836
|
const childClock = child.clock(namespace);
|
|
442
|
-
restoreClock(childClock, {
|
|
3837
|
+
restoreClock(childClock, {
|
|
3838
|
+
now: body.set !== void 0 ? target : childClock.now() + (body.advance !== void 0 ? parseDuration(body.advance) ?? 0 : 0),
|
|
3839
|
+
frozen: body.freeze === void 0 ? childClock.state().frozen : frozen
|
|
3840
|
+
});
|
|
443
3841
|
await child.settle?.(namespace);
|
|
444
3842
|
return childClock.state();
|
|
445
3843
|
});
|
|
@@ -452,9 +3850,11 @@ async function startFleet(config, options) {
|
|
|
452
3850
|
if (route[2] === "reset") {
|
|
453
3851
|
if (route[3])
|
|
454
3852
|
return json(404, { error: "not found" });
|
|
455
|
-
const response2 = await transaction(namespace, selected, async (_name, child) => child.reset(namespace));
|
|
456
|
-
if (response2.ok && selected.size === children.size)
|
|
457
|
-
|
|
3853
|
+
const response2 = await transaction(namespace, selected, async (_name, child) => child.reset(namespace), true);
|
|
3854
|
+
if (response2.ok && selected.size === children.size) {
|
|
3855
|
+
clocks.delete(namespace);
|
|
3856
|
+
clock(namespace);
|
|
3857
|
+
}
|
|
458
3858
|
return response2;
|
|
459
3859
|
}
|
|
460
3860
|
if (route[3]) {
|
|
@@ -462,12 +3862,12 @@ async function startFleet(config, options) {
|
|
|
462
3862
|
if (!point || point.namespace !== namespace)
|
|
463
3863
|
return json(404, { error: "no snapshot in this namespace" });
|
|
464
3864
|
const restored = new Map([...point.values].map(([name]) => [name, children.get(name)]));
|
|
465
|
-
const response2 = await transaction(namespace, restored, async (name, child) => child.restore(namespace, point.values.get(name)));
|
|
3865
|
+
const response2 = await transaction(namespace, restored, async (name, child) => child.restore(namespace, point.values.get(name)), true);
|
|
466
3866
|
if (response2.ok)
|
|
467
3867
|
restoreClock(clock(namespace), point.clock);
|
|
468
3868
|
return response2;
|
|
469
3869
|
}
|
|
470
|
-
const snapshotId =
|
|
3870
|
+
const snapshotId = randomUUID4();
|
|
471
3871
|
const values = /* @__PURE__ */ new Map();
|
|
472
3872
|
const response = await transaction(namespace, selected, async (name, child) => {
|
|
473
3873
|
values.set(name, await child.checkpoint(namespace));
|
|
@@ -485,38 +3885,67 @@ async function startFleet(config, options) {
|
|
|
485
3885
|
};
|
|
486
3886
|
try {
|
|
487
3887
|
const adminPrefix = resolveAdminPrefix(config.adminPrefix);
|
|
488
|
-
if (!isObject(config.services) ||
|
|
3888
|
+
if (!isObject(config.services) || targets.size === 0)
|
|
489
3889
|
throw new Error("config must contain at least one service");
|
|
490
|
-
for (const [name,
|
|
3890
|
+
for (const [name, target] of targets) {
|
|
3891
|
+
const entry = config.services[name] ?? {};
|
|
491
3892
|
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name))
|
|
492
3893
|
throw new Error("invalid service name");
|
|
493
3894
|
if (config.adminControls !== void 0 || entry.adminControls !== void 0)
|
|
494
3895
|
normalizeBootControls({ ...config.adminControls, ...entry.adminControls }, `services.${name}.adminControls`);
|
|
495
3896
|
try {
|
|
496
|
-
const target = await options.load(name);
|
|
497
3897
|
if (entry.protocol && entry.protocol !== ("protocol" in target ? target.protocol : "http"))
|
|
498
3898
|
throw new Error("configured protocol does not match target");
|
|
499
3899
|
const adminKey = entry.adminKey ?? config.adminKey ?? process.env.MOCKINGBIRD_ADMIN_KEY;
|
|
500
|
-
const child = "start" in target ? await target.start(
|
|
3900
|
+
const child = "start" in target ? await target.start({
|
|
3901
|
+
...entry,
|
|
3902
|
+
...config.adminControls !== void 0 || entry.adminControls !== void 0 ? { adminControls: { ...config.adminControls, ...entry.adminControls } } : {}
|
|
3903
|
+
}) : await httpChild(target, {
|
|
501
3904
|
...entry,
|
|
502
3905
|
adminPrefix: resolveAdminPrefix(entry.adminPrefix ?? adminPrefix),
|
|
503
3906
|
...adminKey !== void 0 ? { adminKey } : {},
|
|
504
3907
|
// Fleet-wide controls, with the service's own keys replacing them.
|
|
505
3908
|
...config.adminControls !== void 0 || entry.adminControls !== void 0 ? { adminControls: { ...config.adminControls, ...entry.adminControls } } : {}
|
|
506
|
-
}, options)
|
|
3909
|
+
}, options, (namespace, request) => management?.admit(namespace, request), (namespace) => management?.generation(namespace), (namespace, request) => management?.privateRequest(namespace, request) ?? false, {
|
|
3910
|
+
begin: (namespace, request) => management?.beginRequest(name, namespace, request),
|
|
3911
|
+
finish: async (namespace, request, response, log, token) => {
|
|
3912
|
+
await management?.finishRequest(name, namespace, request, response, log, token);
|
|
3913
|
+
},
|
|
3914
|
+
delivery: (event) => management?.observeDelivery(name, event)
|
|
3915
|
+
});
|
|
3916
|
+
child.targetName = entry.target ?? name;
|
|
3917
|
+
if (target.packageVersion)
|
|
3918
|
+
child.packageVersion = target.packageVersion;
|
|
507
3919
|
children.set(name, child);
|
|
508
3920
|
if (!await child.ready())
|
|
509
3921
|
throw new Error("protocol readiness failed");
|
|
510
|
-
} catch {
|
|
511
|
-
throw new Error(`service ${name} failed to start; all started listeners were closed
|
|
3922
|
+
} catch (error) {
|
|
3923
|
+
throw new Error(`service ${name} failed to start; all started listeners were closed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
512
3924
|
}
|
|
513
3925
|
}
|
|
3926
|
+
management = new FleetManagement({
|
|
3927
|
+
id,
|
|
3928
|
+
config: { ...config, adminPrefix },
|
|
3929
|
+
options,
|
|
3930
|
+
children,
|
|
3931
|
+
checkpoints,
|
|
3932
|
+
clock,
|
|
3933
|
+
transaction,
|
|
3934
|
+
manifest: () => manifest,
|
|
3935
|
+
publish,
|
|
3936
|
+
recovery,
|
|
3937
|
+
controlling
|
|
3938
|
+
});
|
|
3939
|
+
const api = {
|
|
3940
|
+
fetch: (request) => management.dispatch(request, () => coreApi.fetch(request))
|
|
3941
|
+
};
|
|
514
3942
|
supervisor = await listen(api, {
|
|
515
3943
|
port: config.control?.port ?? 0,
|
|
516
3944
|
host: config.control?.host ?? "127.0.0.1"
|
|
517
3945
|
});
|
|
518
|
-
|
|
3946
|
+
manifest = {
|
|
519
3947
|
version: 1,
|
|
3948
|
+
capabilityVersion: 1,
|
|
520
3949
|
state: "ready",
|
|
521
3950
|
pid: process.pid,
|
|
522
3951
|
id,
|
|
@@ -527,7 +3956,7 @@ async function startFleet(config, options) {
|
|
|
527
3956
|
name,
|
|
528
3957
|
{
|
|
529
3958
|
protocol: child.protocol,
|
|
530
|
-
url: publicUrl(child.url),
|
|
3959
|
+
url: advertisedHttpBase(config.services[name] ?? {}) ?? publicUrl(child.url),
|
|
531
3960
|
healthUrl: child.healthUrl ?? `${supervisor?.url}${adminPrefix}/health`,
|
|
532
3961
|
adminUrl: child.adminUrl ?? `${supervisor?.url}${adminPrefix}/fleet`,
|
|
533
3962
|
namespaces: child.namespaces,
|
|
@@ -536,26 +3965,395 @@ async function startFleet(config, options) {
|
|
|
536
3965
|
}
|
|
537
3966
|
]))
|
|
538
3967
|
};
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
3968
|
+
await management.recoverOperations();
|
|
3969
|
+
if (options.initialize) {
|
|
3970
|
+
management.lifecycle = "initializing";
|
|
3971
|
+
const access = [];
|
|
3972
|
+
const connections = privateConnections();
|
|
3973
|
+
try {
|
|
3974
|
+
for (const [name, child] of children)
|
|
3975
|
+
if (child.initializationAccess) {
|
|
3976
|
+
const privateAccess = await child.initializationAccess();
|
|
3977
|
+
access.push(privateAccess);
|
|
3978
|
+
connections[name] = {
|
|
3979
|
+
url: privateAccess.connections.default ?? child.connection ?? child.url,
|
|
3980
|
+
namespaces: privateAccess.connections
|
|
3981
|
+
};
|
|
3982
|
+
}
|
|
3983
|
+
const signal = AbortSignal.timeout(options.initializationTimeoutMs ?? 3e4);
|
|
3984
|
+
await Promise.race([
|
|
3985
|
+
options.initialize({
|
|
3986
|
+
manifest,
|
|
3987
|
+
connections,
|
|
3988
|
+
headers: { "x-mockingbird-initializer": management.initializationToken },
|
|
3989
|
+
signal
|
|
3990
|
+
}),
|
|
3991
|
+
new Promise((_, reject) => signal.addEventListener("abort", () => reject(new Error("fleet initialization timed out")), { once: true }))
|
|
3992
|
+
]);
|
|
3993
|
+
} finally {
|
|
3994
|
+
await Promise.all(access.map((entry) => entry.close()));
|
|
3995
|
+
}
|
|
3996
|
+
}
|
|
3997
|
+
await management.startPolicies();
|
|
3998
|
+
await publish();
|
|
3999
|
+
if (manifest.state === "ready")
|
|
4000
|
+
options.onReady?.(manifest);
|
|
552
4001
|
return { manifest, children, fetch: api.fetch, close };
|
|
553
4002
|
} catch (error) {
|
|
554
|
-
|
|
4003
|
+
try {
|
|
4004
|
+
await close();
|
|
4005
|
+
} catch (cleanup) {
|
|
4006
|
+
throw new AggregateError([error, cleanup], `fleet startup and cleanup failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
4007
|
+
}
|
|
555
4008
|
throw error;
|
|
556
4009
|
}
|
|
557
4010
|
}
|
|
558
4011
|
|
|
4012
|
+
// ../../adapters/node/dist/fleet-tools.js
|
|
4013
|
+
import { readFile as readFile4 } from "node:fs/promises";
|
|
4014
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
4015
|
+
import { resolve as resolve2 } from "node:path";
|
|
4016
|
+
|
|
4017
|
+
// ../../adapters/node/dist/fleet-client.js
|
|
4018
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
4019
|
+
import { chmod as chmod2, readFile as readFile3, rename as rename2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
|
|
4020
|
+
var FleetClientError = class extends Error {
|
|
4021
|
+
status;
|
|
4022
|
+
details;
|
|
4023
|
+
constructor(status, details) {
|
|
4024
|
+
super(`fleet control HTTP ${status}: ${canonical(details)}`);
|
|
4025
|
+
this.status = status;
|
|
4026
|
+
this.details = details;
|
|
4027
|
+
}
|
|
4028
|
+
};
|
|
4029
|
+
var FleetClient = class {
|
|
4030
|
+
base;
|
|
4031
|
+
options;
|
|
4032
|
+
constructor(base, options = {}) {
|
|
4033
|
+
this.base = base;
|
|
4034
|
+
this.options = options;
|
|
4035
|
+
}
|
|
4036
|
+
async request(path, options = {}) {
|
|
4037
|
+
const url = new URL(`${this.base.replace(/\/$/, "")}/${path.replace(/^\//, "")}`);
|
|
4038
|
+
if (url.username || url.password)
|
|
4039
|
+
throw new Error("fleet client URL must not contain credentials");
|
|
4040
|
+
url.searchParams.set("namespace", options.namespace ?? this.options.namespace ?? "default");
|
|
4041
|
+
const response = await (this.options.fetch ?? fetch)(url, {
|
|
4042
|
+
method: options.method ?? (options.body === void 0 ? "GET" : "POST"),
|
|
4043
|
+
headers: {
|
|
4044
|
+
"content-type": "application/json",
|
|
4045
|
+
...this.options.adminKey ? { "x-mockingbird-admin-key": this.options.adminKey } : {},
|
|
4046
|
+
...options.idempotencyKey ? { "idempotency-key": options.idempotencyKey } : {}
|
|
4047
|
+
},
|
|
4048
|
+
...options.body !== void 0 ? { body: JSON.stringify(options.body) } : {},
|
|
4049
|
+
signal: options.signal ?? AbortSignal.timeout(this.options.timeoutMs ?? 3e4)
|
|
4050
|
+
});
|
|
4051
|
+
const data = await response.json();
|
|
4052
|
+
if (!response.ok)
|
|
4053
|
+
throw new FleetClientError(response.status, data);
|
|
4054
|
+
return data;
|
|
4055
|
+
}
|
|
4056
|
+
discover() {
|
|
4057
|
+
return this.request("");
|
|
4058
|
+
}
|
|
4059
|
+
namespaces() {
|
|
4060
|
+
return this.request("namespaces");
|
|
4061
|
+
}
|
|
4062
|
+
createNamespace(namespace, baseline) {
|
|
4063
|
+
return this.request(`namespaces/${encodeURIComponent(namespace)}`, {
|
|
4064
|
+
body: baseline ? { baseline } : {}
|
|
4065
|
+
});
|
|
4066
|
+
}
|
|
4067
|
+
deleteNamespace(namespace) {
|
|
4068
|
+
return this.request(`namespaces/${encodeURIComponent(namespace)}`, { method: "DELETE" });
|
|
4069
|
+
}
|
|
4070
|
+
reset(namespace, options = {}) {
|
|
4071
|
+
return this.request(`namespaces/${encodeURIComponent(namespace)}/reset`, {
|
|
4072
|
+
body: options.services ? { services: options.services } : {},
|
|
4073
|
+
...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}
|
|
4074
|
+
});
|
|
4075
|
+
}
|
|
4076
|
+
snapshot(namespace, options = {}) {
|
|
4077
|
+
const { idempotencyKey, ...body } = options;
|
|
4078
|
+
return this.request(`namespaces/${encodeURIComponent(namespace)}/snapshots`, {
|
|
4079
|
+
body,
|
|
4080
|
+
...idempotencyKey ? { idempotencyKey } : {}
|
|
4081
|
+
});
|
|
4082
|
+
}
|
|
4083
|
+
restore(namespace, id, idempotencyKey) {
|
|
4084
|
+
return this.request(`namespaces/${encodeURIComponent(namespace)}/snapshots/${encodeURIComponent(id)}/restore`, { body: {}, ...idempotencyKey ? { idempotencyKey } : {} });
|
|
4085
|
+
}
|
|
4086
|
+
exportArchive(namespace, allNamespaces = false) {
|
|
4087
|
+
return this.request("archives/export", {
|
|
4088
|
+
body: { allNamespaces },
|
|
4089
|
+
...namespace ? { namespace } : {}
|
|
4090
|
+
});
|
|
4091
|
+
}
|
|
4092
|
+
exportProtectedArchive(namespace, allNamespaces = false) {
|
|
4093
|
+
return this.request("archives/export", {
|
|
4094
|
+
body: { allNamespaces },
|
|
4095
|
+
...namespace ? { namespace } : {}
|
|
4096
|
+
});
|
|
4097
|
+
}
|
|
4098
|
+
importArchive(archive, namespace) {
|
|
4099
|
+
if (archive.format !== "mockingbird.jwe/v1")
|
|
4100
|
+
validateArchive(archive);
|
|
4101
|
+
return this.request("archives/import", {
|
|
4102
|
+
body: { archive, ...namespace ? { namespace } : {} }
|
|
4103
|
+
});
|
|
4104
|
+
}
|
|
4105
|
+
operation(id) {
|
|
4106
|
+
return this.request(`operations/${encodeURIComponent(id)}`);
|
|
4107
|
+
}
|
|
4108
|
+
};
|
|
4109
|
+
function renderConnections(manifest, privateManifest, namespace, mapping) {
|
|
4110
|
+
if (!/^[A-Za-z0-9_.-]{1,64}$/.test(namespace))
|
|
4111
|
+
throw new Error("invalid namespace");
|
|
4112
|
+
const result = {};
|
|
4113
|
+
for (const [variable, entry] of Object.entries(mapping)) {
|
|
4114
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(variable))
|
|
4115
|
+
throw new Error(`invalid variable name ${variable}`);
|
|
4116
|
+
const child = manifest.services[entry.service], secret = privateManifest.services[entry.service];
|
|
4117
|
+
if (!child || !secret)
|
|
4118
|
+
throw new Error(`missing service mapping ${entry.service}`);
|
|
4119
|
+
if (child.protocol === "http") {
|
|
4120
|
+
const template = child.namespaces.path;
|
|
4121
|
+
if (typeof template !== "string")
|
|
4122
|
+
throw new Error(`missing HTTP namespace mapping ${entry.service}`);
|
|
4123
|
+
result[variable] = new URL(template.replace("{name}", encodeURIComponent(namespace)), secret.url).href;
|
|
4124
|
+
} else {
|
|
4125
|
+
const endpoint = secret.namespaces?.[namespace];
|
|
4126
|
+
if (!endpoint)
|
|
4127
|
+
throw new Error(`missing namespace mapping ${namespace}/${entry.service}`);
|
|
4128
|
+
result[variable] = endpoint;
|
|
4129
|
+
}
|
|
4130
|
+
}
|
|
4131
|
+
return result;
|
|
4132
|
+
}
|
|
4133
|
+
async function writeConnections(path, values, format = "json") {
|
|
4134
|
+
const temp = `${path}.${randomUUID5()}.tmp`;
|
|
4135
|
+
const text = format === "json" ? `${JSON.stringify(values, null, 2)}
|
|
4136
|
+
` : `${Object.entries(values).map(([key, value]) => `${key}=${JSON.stringify(value)}`).join("\n")}
|
|
4137
|
+
`;
|
|
4138
|
+
try {
|
|
4139
|
+
await writeFile2(temp, text, { mode: 384, flag: "wx" });
|
|
4140
|
+
await chmod2(temp, 384);
|
|
4141
|
+
await rename2(temp, path);
|
|
4142
|
+
} finally {
|
|
4143
|
+
await rm2(temp, { force: true });
|
|
4144
|
+
}
|
|
4145
|
+
}
|
|
4146
|
+
|
|
4147
|
+
// ../../adapters/node/dist/fleet-tools.js
|
|
4148
|
+
async function doctorFleet(config, options, probes = []) {
|
|
4149
|
+
const findings = [];
|
|
4150
|
+
const plan = [];
|
|
4151
|
+
try {
|
|
4152
|
+
const targets = await preflightFleet(config, options);
|
|
4153
|
+
const require2 = createRequire2(resolve2(process.cwd(), "package.json"));
|
|
4154
|
+
for (const [service, target] of targets) {
|
|
4155
|
+
let version = "development";
|
|
4156
|
+
try {
|
|
4157
|
+
version = require2(`@crvouga/mockingbird-service-${service}/package.json`).version;
|
|
4158
|
+
} catch {
|
|
4159
|
+
}
|
|
4160
|
+
plan.push({
|
|
4161
|
+
service,
|
|
4162
|
+
protocol: "protocol" in target ? target.protocol : "http",
|
|
4163
|
+
port: config.services[service]?.port ?? target.defaultPort,
|
|
4164
|
+
version
|
|
4165
|
+
});
|
|
4166
|
+
}
|
|
4167
|
+
findings.push({
|
|
4168
|
+
check: "configuration",
|
|
4169
|
+
ok: true,
|
|
4170
|
+
message: "all targets and control documents validated; no listeners opened"
|
|
4171
|
+
});
|
|
4172
|
+
} catch (error) {
|
|
4173
|
+
findings.push({
|
|
4174
|
+
check: "configuration",
|
|
4175
|
+
ok: false,
|
|
4176
|
+
message: error instanceof Error ? error.message : "configuration failed"
|
|
4177
|
+
});
|
|
4178
|
+
}
|
|
4179
|
+
for (const probe of probes) {
|
|
4180
|
+
try {
|
|
4181
|
+
const url = new URL(probe.url);
|
|
4182
|
+
if (url.username || url.password)
|
|
4183
|
+
throw new Error("probe URLs must not contain credentials");
|
|
4184
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(probe.timeoutMs ?? 2e3) });
|
|
4185
|
+
await response.body?.cancel();
|
|
4186
|
+
findings.push({
|
|
4187
|
+
check: "reachability",
|
|
4188
|
+
ok: response.ok,
|
|
4189
|
+
message: `endpoint returned HTTP ${response.status}`
|
|
4190
|
+
});
|
|
4191
|
+
} catch {
|
|
4192
|
+
findings.push({
|
|
4193
|
+
check: "reachability",
|
|
4194
|
+
ok: false,
|
|
4195
|
+
message: "endpoint unreachable; verify the listener host, port and readiness"
|
|
4196
|
+
});
|
|
4197
|
+
}
|
|
4198
|
+
}
|
|
4199
|
+
return {
|
|
4200
|
+
version: 1,
|
|
4201
|
+
ok: findings.every((f) => f.ok),
|
|
4202
|
+
findings,
|
|
4203
|
+
plan,
|
|
4204
|
+
storageWritesPerformed: false
|
|
4205
|
+
};
|
|
4206
|
+
}
|
|
4207
|
+
async function rehearseFleet(config, options, input, probes = [], timeoutMs = 3e4) {
|
|
4208
|
+
const archive = validateArchive(input);
|
|
4209
|
+
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
4210
|
+
const isolated = {
|
|
4211
|
+
...config,
|
|
4212
|
+
control: { host: "127.0.0.1", port: 0 },
|
|
4213
|
+
services: Object.fromEntries(Object.entries(config.services).map(([name, entry]) => [
|
|
4214
|
+
name,
|
|
4215
|
+
{ ...entry, host: "127.0.0.1", port: 0 }
|
|
4216
|
+
]))
|
|
4217
|
+
};
|
|
4218
|
+
let fleet;
|
|
4219
|
+
try {
|
|
4220
|
+
fleet = await startFleet(isolated, { load: options.load });
|
|
4221
|
+
const client = new FleetClient(fleet.manifest.adminBase, {
|
|
4222
|
+
...config.adminKey ? { adminKey: config.adminKey } : {}
|
|
4223
|
+
});
|
|
4224
|
+
await client.importArchive(archive);
|
|
4225
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
4226
|
+
for (const probe of probes)
|
|
4227
|
+
await Promise.race([
|
|
4228
|
+
probe(fleet, signal),
|
|
4229
|
+
new Promise((_, reject) => signal.addEventListener("abort", () => reject(new Error("rehearsal probe timed out")), {
|
|
4230
|
+
once: true
|
|
4231
|
+
}))
|
|
4232
|
+
]);
|
|
4233
|
+
return {
|
|
4234
|
+
version: 1,
|
|
4235
|
+
ok: true,
|
|
4236
|
+
startedAt,
|
|
4237
|
+
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
4238
|
+
sourceArchive: archive.sha256,
|
|
4239
|
+
rehearsalProcess: fleet.manifest.id,
|
|
4240
|
+
probes: probes.length
|
|
4241
|
+
};
|
|
4242
|
+
} finally {
|
|
4243
|
+
await fleet?.close();
|
|
4244
|
+
}
|
|
4245
|
+
}
|
|
4246
|
+
function fleetCommands(load) {
|
|
4247
|
+
const parse = async (path) => {
|
|
4248
|
+
if (typeof path !== "string")
|
|
4249
|
+
throw new Error("file path required");
|
|
4250
|
+
return JSON.parse(await readFile4(path, "utf8"));
|
|
4251
|
+
};
|
|
4252
|
+
return {
|
|
4253
|
+
"fleet control": {
|
|
4254
|
+
summary: "Call authenticated fleet controls using discovered adminBase",
|
|
4255
|
+
options: {
|
|
4256
|
+
base: { type: "string", description: "Discovered adminBase URL" },
|
|
4257
|
+
action: { type: "string", description: "Relative control route" },
|
|
4258
|
+
method: { type: "string", description: "HTTP method" },
|
|
4259
|
+
body: { type: "string", description: "JSON request file" },
|
|
4260
|
+
namespace: { type: "string", description: "Selected namespace" },
|
|
4261
|
+
"key-env": {
|
|
4262
|
+
type: "string",
|
|
4263
|
+
description: "Admin-key environment variable name",
|
|
4264
|
+
default: "MOCKINGBIRD_ADMIN_KEY"
|
|
4265
|
+
},
|
|
4266
|
+
"idempotency-key": { type: "string", description: "Retry identity" }
|
|
4267
|
+
},
|
|
4268
|
+
async run(values) {
|
|
4269
|
+
try {
|
|
4270
|
+
if (typeof values.base !== "string" || typeof values.action !== "string")
|
|
4271
|
+
throw new Error("--base and --action required");
|
|
4272
|
+
const key = process.env[String(values["key-env"] ?? "MOCKINGBIRD_ADMIN_KEY")];
|
|
4273
|
+
const client = new FleetClient(values.base, {
|
|
4274
|
+
...key ? { adminKey: key } : {},
|
|
4275
|
+
...typeof values.namespace === "string" ? { namespace: values.namespace } : {}
|
|
4276
|
+
});
|
|
4277
|
+
console.log(JSON.stringify(await client.request(values.action, {
|
|
4278
|
+
...typeof values.method === "string" ? { method: values.method } : {},
|
|
4279
|
+
...values.body ? { body: await parse(values.body) } : {},
|
|
4280
|
+
...typeof values["idempotency-key"] === "string" ? { idempotencyKey: values["idempotency-key"] } : {}
|
|
4281
|
+
})));
|
|
4282
|
+
return 0;
|
|
4283
|
+
} catch (error) {
|
|
4284
|
+
console.error(error instanceof Error ? error.message : "fleet control failed");
|
|
4285
|
+
return 1;
|
|
4286
|
+
}
|
|
4287
|
+
}
|
|
4288
|
+
},
|
|
4289
|
+
"fleet doctor": {
|
|
4290
|
+
summary: "Validate fleet configuration without starting or resetting services",
|
|
4291
|
+
options: {
|
|
4292
|
+
config: { type: "string", description: "Fleet configuration file" },
|
|
4293
|
+
json: { type: "boolean", description: "Machine-readable report" },
|
|
4294
|
+
endpoint: { type: "string", description: "Optional read-only reachability probe" },
|
|
4295
|
+
"ready-file": { type: "string", description: "Validate readiness destination" },
|
|
4296
|
+
"connections-file": { type: "string", description: "Validate private destination" }
|
|
4297
|
+
},
|
|
4298
|
+
async run(values) {
|
|
4299
|
+
try {
|
|
4300
|
+
const report = await doctorFleet(await parse(values.config), {
|
|
4301
|
+
load,
|
|
4302
|
+
...typeof values["ready-file"] === "string" ? { readyFile: values["ready-file"] } : {},
|
|
4303
|
+
...typeof values["connections-file"] === "string" ? { connectionsFile: values["connections-file"] } : {}
|
|
4304
|
+
}, typeof values.endpoint === "string" ? [{ url: values.endpoint }] : []);
|
|
4305
|
+
console.log(values.json ? JSON.stringify(report) : report.findings.map((f) => `${f.ok ? "PASS" : "FAIL"} ${f.check}: ${f.message}`).join("\n"));
|
|
4306
|
+
return report.ok ? 0 : 1;
|
|
4307
|
+
} catch (error) {
|
|
4308
|
+
console.error(error instanceof Error ? error.message : "doctor failed");
|
|
4309
|
+
return 1;
|
|
4310
|
+
}
|
|
4311
|
+
}
|
|
4312
|
+
},
|
|
4313
|
+
"fleet render": {
|
|
4314
|
+
summary: "Render explicit application variables from private namespace discovery",
|
|
4315
|
+
options: {
|
|
4316
|
+
manifest: { type: "string", description: "Public ready manifest file" },
|
|
4317
|
+
connections: { type: "string", description: "Private connection manifest file" },
|
|
4318
|
+
mapping: { type: "string", description: "JSON variable-to-service mapping" },
|
|
4319
|
+
namespace: { type: "string", description: "Explicit namespace" },
|
|
4320
|
+
output: { type: "string", description: "Private destination file" },
|
|
4321
|
+
format: { type: "string", description: "json or dotenv", default: "json" }
|
|
4322
|
+
},
|
|
4323
|
+
async run(values) {
|
|
4324
|
+
try {
|
|
4325
|
+
if (typeof values.namespace !== "string" || typeof values.output !== "string" || !["json", "dotenv"].includes(String(values.format)))
|
|
4326
|
+
throw new Error("--namespace, --output and valid --format required");
|
|
4327
|
+
const manifest = await parse(values.manifest), connections = await parse(values.connections);
|
|
4328
|
+
const output = renderConnections(manifest, connections, values.namespace, await parse(values.mapping));
|
|
4329
|
+
await writeConnections(values.output, output, values.format);
|
|
4330
|
+
console.log(JSON.stringify({ written: values.output, variables: Object.keys(output) }));
|
|
4331
|
+
return 0;
|
|
4332
|
+
} catch (error) {
|
|
4333
|
+
console.error(error instanceof Error ? error.message : "render failed");
|
|
4334
|
+
return 1;
|
|
4335
|
+
}
|
|
4336
|
+
}
|
|
4337
|
+
},
|
|
4338
|
+
"fleet rehearse": {
|
|
4339
|
+
summary: "Restore an archive in an isolated ephemeral fleet, then close it",
|
|
4340
|
+
options: {
|
|
4341
|
+
config: { type: "string", description: "Fleet configuration file" },
|
|
4342
|
+
archive: { type: "string", description: "Saved fleet archive file" }
|
|
4343
|
+
},
|
|
4344
|
+
async run(values) {
|
|
4345
|
+
try {
|
|
4346
|
+
console.log(JSON.stringify(await rehearseFleet(await parse(values.config), { load }, await parse(values.archive))));
|
|
4347
|
+
return 0;
|
|
4348
|
+
} catch (error) {
|
|
4349
|
+
console.error(error instanceof Error ? error.message : "rehearsal failed");
|
|
4350
|
+
return 1;
|
|
4351
|
+
}
|
|
4352
|
+
}
|
|
4353
|
+
}
|
|
4354
|
+
};
|
|
4355
|
+
}
|
|
4356
|
+
|
|
559
4357
|
// ../../adapters/node/dist/cli.js
|
|
560
4358
|
var optionHelp = (options) => Object.entries(options).map(([name, option]) => {
|
|
561
4359
|
const flag = `--${name}${option.type === "string" ? ` ${option.value ?? "<value>"}` : ""}`;
|
|
@@ -581,6 +4379,12 @@ var commandHelp = (spec, name, command) => [
|
|
|
581
4379
|
...command.options ? ["", "Options:", ...optionHelp(command.options)] : []
|
|
582
4380
|
].join("\n");
|
|
583
4381
|
var runCli = async (spec, argv) => {
|
|
4382
|
+
const own = spec.commands.serve?.fleetTarget;
|
|
4383
|
+
if (own)
|
|
4384
|
+
spec = {
|
|
4385
|
+
...spec,
|
|
4386
|
+
commands: { ...fleetCommands((name2) => loadTarget(name2, own)), ...spec.commands }
|
|
4387
|
+
};
|
|
584
4388
|
const pair = argv.length >= 2 ? `${argv[0]} ${argv[1]}` : void 0;
|
|
585
4389
|
const words = pair !== void 0 && spec.commands[pair] ? 2 : 1;
|
|
586
4390
|
const name = words === 2 ? pair : argv[0];
|
|
@@ -728,7 +4532,7 @@ var formatLog = (format) => {
|
|
|
728
4532
|
var asString = (value) => typeof value === "string" ? value : void 0;
|
|
729
4533
|
var readJsonFile = async (path, label) => {
|
|
730
4534
|
try {
|
|
731
|
-
return JSON.parse(await
|
|
4535
|
+
return JSON.parse(await readFile5(path, "utf8"));
|
|
732
4536
|
} catch (error) {
|
|
733
4537
|
throw new Error(`${label}: cannot read ${path}: ${error instanceof Error ? error.message : error}`);
|
|
734
4538
|
}
|
|
@@ -797,7 +4601,7 @@ var loadTarget = async (name, own) => {
|
|
|
797
4601
|
try {
|
|
798
4602
|
mod = await import(specifier);
|
|
799
4603
|
} catch {
|
|
800
|
-
const fromProject =
|
|
4604
|
+
const fromProject = createRequire3(resolve3(process.cwd(), "package.json"));
|
|
801
4605
|
mod = await import(pathToFileURL(fromProject.resolve(specifier)).href);
|
|
802
4606
|
}
|
|
803
4607
|
if (!mod.serveTarget)
|
|
@@ -827,18 +4631,22 @@ var start = async (target, values, config) => {
|
|
|
827
4631
|
console.log(`${target.name} ${line.replaceAll("/__admin", adminPrefix)}`);
|
|
828
4632
|
return listening;
|
|
829
4633
|
};
|
|
830
|
-
var untilSignal = async (servers) => new Promise((
|
|
4634
|
+
var untilSignal = async (servers) => new Promise((resolve4) => {
|
|
831
4635
|
const stop = async () => {
|
|
832
4636
|
;
|
|
833
4637
|
process.removeListener("SIGINT", stop);
|
|
834
4638
|
process.removeListener("SIGTERM", stop);
|
|
835
|
-
await Promise.allSettled(servers.map((s) => s.close()));
|
|
836
|
-
|
|
4639
|
+
const results = await Promise.allSettled(servers.map((s) => s.close()));
|
|
4640
|
+
for (const result of results)
|
|
4641
|
+
if (result.status === "rejected")
|
|
4642
|
+
console.error(result.reason instanceof Error ? result.reason.message : String(result.reason));
|
|
4643
|
+
resolve4(results.some((r) => r.status === "rejected") ? 1 : 0);
|
|
837
4644
|
};
|
|
838
4645
|
process.once("SIGINT", stop);
|
|
839
4646
|
process.once("SIGTERM", stop);
|
|
840
4647
|
});
|
|
841
4648
|
var serveCommand = (target) => ({
|
|
4649
|
+
fleetTarget: target,
|
|
842
4650
|
summary: `Serve the ${target.name} emulator or a configured fleet`,
|
|
843
4651
|
options: { ...COMMON_SERVE_OPTIONS, ..."options" in target ? target.options : {} },
|
|
844
4652
|
async run(values) {
|
|
@@ -850,7 +4658,7 @@ var serveCommand = (target) => ({
|
|
|
850
4658
|
const configPath = asString(values.config);
|
|
851
4659
|
if (configPath !== void 0) {
|
|
852
4660
|
try {
|
|
853
|
-
const config = JSON.parse(await
|
|
4661
|
+
const config = JSON.parse(await readFile5(configPath, "utf8"));
|
|
854
4662
|
config.adminPrefix = resolveAdminPrefix(config.adminPrefix ?? asString(values["admin-prefix"]) ?? process.env.MOCKINGBIRD_ADMIN_PREFIX);
|
|
855
4663
|
const adminKey2 = config.adminKey ?? asString(values["admin-key"]) ?? process.env.MOCKINGBIRD_ADMIN_KEY;
|
|
856
4664
|
if (adminKey2 !== void 0)
|