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