stitchkit 0.59.2 → 0.59.4
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 +7 -1
- package/dist/agent-runtime-openrouter.js +0 -1
- package/dist/agent-runtime.js +0 -1
- package/dist/application/health.d.ts +12 -0
- package/dist/application/health.d.ts.map +1 -1
- package/dist/application/opentelemetry.d.ts +25 -0
- package/dist/application/opentelemetry.d.ts.map +1 -0
- package/dist/application-grammy.js +0 -1
- package/dist/application-opentelemetry.d.ts +2 -0
- package/dist/application-opentelemetry.d.ts.map +1 -0
- package/dist/application-opentelemetry.js +248 -0
- package/dist/application.d.ts +1 -1
- package/dist/application.d.ts.map +1 -1
- package/dist/application.js +58 -1241
- package/dist/cli.js +0 -1
- package/dist/files.js +0 -1
- package/dist/index-2nzpcfbp.js +560 -0
- package/dist/index-5c8n2123.js +617 -0
- package/dist/index-mgf6cdkm.js +66 -0
- package/dist/{index-he4psyve.js → index-s8w2y7kr.js} +7 -8
- package/dist/node.js +8 -9
- package/dist/observability/index.js +0 -1
- package/dist/remote.js +0 -1
- package/dist/server/index.js +8 -9
- package/dist/server/socket-io.d.ts.map +1 -1
- package/dist/testing/managed-resource-conformance-contract.d.ts +114 -0
- package/dist/testing/managed-resource-conformance-contract.d.ts.map +1 -0
- package/dist/testing/managed-resource-conformance-driver.d.ts +20 -0
- package/dist/testing/managed-resource-conformance-driver.d.ts.map +1 -0
- package/dist/testing/managed-resource-conformance-scenarios.d.ts +33 -0
- package/dist/testing/managed-resource-conformance-scenarios.d.ts.map +1 -0
- package/dist/testing/managed-resource-conformance.d.ts +5 -0
- package/dist/testing/managed-resource-conformance.d.ts.map +1 -0
- package/dist/testing.d.ts +1 -0
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +658 -71
- package/dist/tools.js +0 -1
- package/llms-full.txt +290 -1
- package/llms.txt +1 -0
- package/package.json +11 -2
- package/dist/index-1bx83sw4.js +0 -4
|
@@ -0,0 +1,617 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ApplicationIdSchema,
|
|
3
|
+
ApplicationShutdownResultSchema,
|
|
4
|
+
ApplicationSnapshotSchema
|
|
5
|
+
} from "./index-mgf6cdkm.js";
|
|
6
|
+
import {
|
|
7
|
+
ShutdownOptionsSchema
|
|
8
|
+
} from "./index-dk6e56g0.js";
|
|
9
|
+
|
|
10
|
+
// src/application/graph.ts
|
|
11
|
+
function resolveResourceGraph(resources) {
|
|
12
|
+
const entries = resources.map((resource, declarationIndex) => ({
|
|
13
|
+
resource,
|
|
14
|
+
id: ApplicationIdSchema.parse(resource.id),
|
|
15
|
+
dependsOn: [...resource.dependsOn ?? []].map((id) => ApplicationIdSchema.parse(id)),
|
|
16
|
+
required: resource.required ?? true,
|
|
17
|
+
declarationIndex
|
|
18
|
+
}));
|
|
19
|
+
const byId = new Map;
|
|
20
|
+
for (const entry of entries) {
|
|
21
|
+
if (byId.has(entry.id)) {
|
|
22
|
+
throw new Error(`[stitchkit] createApplication: duplicate resource id "${entry.id}"`);
|
|
23
|
+
}
|
|
24
|
+
byId.set(entry.id, entry);
|
|
25
|
+
}
|
|
26
|
+
for (const entry of entries) {
|
|
27
|
+
for (const dependencyId of entry.dependsOn) {
|
|
28
|
+
const dependency = byId.get(dependencyId);
|
|
29
|
+
if (!dependency) {
|
|
30
|
+
throw new Error(`[stitchkit] createApplication: resource "${entry.id}" depends on missing resource "${dependencyId}"`);
|
|
31
|
+
}
|
|
32
|
+
if (entry.required && !dependency.required) {
|
|
33
|
+
throw new Error(`[stitchkit] createApplication: required resource "${entry.id}" cannot depend on optional resource "${dependencyId}"`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const pending = new Map(entries.map((entry) => [entry.id, entry]));
|
|
38
|
+
const resolved = new Set;
|
|
39
|
+
const ordered = [];
|
|
40
|
+
while (pending.size > 0) {
|
|
41
|
+
const ready = [...pending.values()].filter((entry) => entry.dependsOn.every((id) => resolved.has(id))).sort((left, right) => left.declarationIndex - right.declarationIndex);
|
|
42
|
+
if (ready.length === 0) {
|
|
43
|
+
throw new Error(`[stitchkit] createApplication: resource dependency cycle: ${[...pending.keys()].join(", ")}`);
|
|
44
|
+
}
|
|
45
|
+
for (const entry of ready) {
|
|
46
|
+
pending.delete(entry.id);
|
|
47
|
+
resolved.add(entry.id);
|
|
48
|
+
ordered.push(entry);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return ordered;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/application/kernel.ts
|
|
55
|
+
class ResourceCompletionBeforeReadyError extends Error {
|
|
56
|
+
constructor(resourceId, cause) {
|
|
57
|
+
super(`[stitchkit] resource "${resourceId}" completed before reaching readiness`, {
|
|
58
|
+
...cause !== undefined && { cause }
|
|
59
|
+
});
|
|
60
|
+
this.name = "ResourceCompletionBeforeReadyError";
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
class ApplicationAdmissionError extends Error {
|
|
65
|
+
code = "APPLICATION_NOT_ACCEPTING";
|
|
66
|
+
constructor() {
|
|
67
|
+
super("Application is not accepting new operations");
|
|
68
|
+
this.name = "ApplicationAdmissionError";
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function isStartResult(value) {
|
|
72
|
+
return typeof value === "object" && value !== null;
|
|
73
|
+
}
|
|
74
|
+
function waitForAbort(signal) {
|
|
75
|
+
if (signal.aborted)
|
|
76
|
+
return Promise.resolve();
|
|
77
|
+
return new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }));
|
|
78
|
+
}
|
|
79
|
+
async function untilDeadline(work, signal) {
|
|
80
|
+
const result = await Promise.race([
|
|
81
|
+
work.then((value) => ({ settled: true, value }), (error) => ({ settled: true, error })),
|
|
82
|
+
waitForAbort(signal).then(() => ({ settled: false }))
|
|
83
|
+
]);
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
function createApplication(config) {
|
|
87
|
+
const id = ApplicationIdSchema.parse(config.id);
|
|
88
|
+
const ordered = resolveResourceGraph(config.resources ?? []);
|
|
89
|
+
const reverse = [...ordered].reverse();
|
|
90
|
+
const records = new Map;
|
|
91
|
+
for (const entry of ordered) {
|
|
92
|
+
records.set(entry.id, {
|
|
93
|
+
entry,
|
|
94
|
+
state: "registered",
|
|
95
|
+
health: "unknown",
|
|
96
|
+
attempted: false,
|
|
97
|
+
activated: false,
|
|
98
|
+
closeInvoked: false,
|
|
99
|
+
closed: false,
|
|
100
|
+
failures: []
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
const epoch = crypto.randomUUID();
|
|
104
|
+
const listeners = new Set;
|
|
105
|
+
const lifetimeAbort = new AbortController;
|
|
106
|
+
const startupAbort = new AbortController;
|
|
107
|
+
let lifecycle = "created";
|
|
108
|
+
let revision = 0;
|
|
109
|
+
let changedAt = new Date().toISOString();
|
|
110
|
+
let accepting = false;
|
|
111
|
+
let accepted = 0;
|
|
112
|
+
let completed = 0;
|
|
113
|
+
let pending = 0;
|
|
114
|
+
let startPromise;
|
|
115
|
+
let shutdownPromise;
|
|
116
|
+
let shutdownRequested = false;
|
|
117
|
+
let activationComplete = false;
|
|
118
|
+
const pendingWaiters = new Set;
|
|
119
|
+
const aggregateHealth = () => {
|
|
120
|
+
if (lifecycle === "created" || lifecycle === "starting")
|
|
121
|
+
return "unknown";
|
|
122
|
+
let optionalUnhealthy = false;
|
|
123
|
+
for (const record of records.values()) {
|
|
124
|
+
if (record.entry.required && (record.state !== "ready" || record.health !== "healthy")) {
|
|
125
|
+
return "unhealthy";
|
|
126
|
+
}
|
|
127
|
+
if (!record.entry.required && (record.state !== "ready" || record.health !== "healthy")) {
|
|
128
|
+
optionalUnhealthy = true;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return optionalUnhealthy ? "degraded" : "healthy";
|
|
132
|
+
};
|
|
133
|
+
const isReady = () => lifecycle === "ready" && [...records.values()].every((record) => !record.entry.required || record.state === "ready" && record.health === "healthy");
|
|
134
|
+
const snapshot = () => ApplicationSnapshotSchema.parse({
|
|
135
|
+
id,
|
|
136
|
+
epoch,
|
|
137
|
+
revision,
|
|
138
|
+
lifecycle,
|
|
139
|
+
health: aggregateHealth(),
|
|
140
|
+
ready: isReady(),
|
|
141
|
+
capturedAt: new Date().toISOString(),
|
|
142
|
+
changedAt,
|
|
143
|
+
admission: { accepting, accepted, completed, pending },
|
|
144
|
+
resources: ordered.map((entry) => {
|
|
145
|
+
const record = records.get(entry.id);
|
|
146
|
+
if (!record)
|
|
147
|
+
throw new Error("Managed resource record disappeared");
|
|
148
|
+
return {
|
|
149
|
+
id: entry.id,
|
|
150
|
+
required: entry.required,
|
|
151
|
+
dependsOn: entry.dependsOn,
|
|
152
|
+
state: record.state,
|
|
153
|
+
health: record.health,
|
|
154
|
+
ready: record.state === "ready" && record.health === "healthy"
|
|
155
|
+
};
|
|
156
|
+
})
|
|
157
|
+
});
|
|
158
|
+
const publish = () => {
|
|
159
|
+
revision += 1;
|
|
160
|
+
changedAt = new Date().toISOString();
|
|
161
|
+
const value = snapshot();
|
|
162
|
+
for (const listener of listeners) {
|
|
163
|
+
try {
|
|
164
|
+
listener(value);
|
|
165
|
+
} catch {}
|
|
166
|
+
}
|
|
167
|
+
if (config.onSnapshot) {
|
|
168
|
+
Promise.resolve().then(() => config.onSnapshot?.(value)).catch(() => {});
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
const contextFor = (record, options = {}) => ({
|
|
172
|
+
applicationId: id,
|
|
173
|
+
signal: options.signal ?? lifetimeAbort.signal,
|
|
174
|
+
...options.deadlineAt !== undefined && { deadlineAt: options.deadlineAt },
|
|
175
|
+
...options.forceDeadlineAt !== undefined && {
|
|
176
|
+
forceDeadlineAt: options.forceDeadlineAt
|
|
177
|
+
},
|
|
178
|
+
now: () => performance.now(),
|
|
179
|
+
reportHealth(health) {
|
|
180
|
+
if (record.state === "stopped")
|
|
181
|
+
return;
|
|
182
|
+
record.health = health;
|
|
183
|
+
accepting = activationComplete && !shutdownRequested && isReady();
|
|
184
|
+
publish();
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
const markLateCompletion = (record, failure) => {
|
|
188
|
+
if (shutdownRequested || record.state === "stopping" || record.state === "stopped")
|
|
189
|
+
return;
|
|
190
|
+
if (failure)
|
|
191
|
+
record.failures.push("completion");
|
|
192
|
+
record.state = "failed";
|
|
193
|
+
record.health = "unhealthy";
|
|
194
|
+
accepting = activationComplete && isReady();
|
|
195
|
+
publish();
|
|
196
|
+
};
|
|
197
|
+
const closeAttempted = async () => {
|
|
198
|
+
const errors = [];
|
|
199
|
+
for (const entry of reverse) {
|
|
200
|
+
const record = records.get(entry.id);
|
|
201
|
+
if (!record?.attempted || record.closed)
|
|
202
|
+
continue;
|
|
203
|
+
record.state = "stopping";
|
|
204
|
+
try {
|
|
205
|
+
record.closeInvoked = true;
|
|
206
|
+
await entry.resource.close?.(contextFor(record, { signal: startupAbort.signal }));
|
|
207
|
+
record.closed = true;
|
|
208
|
+
record.state = "stopped";
|
|
209
|
+
} catch (error) {
|
|
210
|
+
record.failures.push("close");
|
|
211
|
+
record.state = "failed";
|
|
212
|
+
errors.push(error);
|
|
213
|
+
}
|
|
214
|
+
publish();
|
|
215
|
+
}
|
|
216
|
+
return errors;
|
|
217
|
+
};
|
|
218
|
+
const runStart = async () => {
|
|
219
|
+
lifecycle = "starting";
|
|
220
|
+
publish();
|
|
221
|
+
let startFailure;
|
|
222
|
+
try {
|
|
223
|
+
for (const entry of ordered) {
|
|
224
|
+
if (shutdownRequested || startupAbort.signal.aborted) {
|
|
225
|
+
throw new Error("[stitchkit] application startup interrupted by shutdown");
|
|
226
|
+
}
|
|
227
|
+
const record = records.get(entry.id);
|
|
228
|
+
if (!record)
|
|
229
|
+
throw new Error("Managed resource record disappeared");
|
|
230
|
+
const dependencyFailed = entry.dependsOn.some((dependencyId) => records.get(dependencyId)?.state !== "ready");
|
|
231
|
+
if (dependencyFailed) {
|
|
232
|
+
record.state = "failed";
|
|
233
|
+
record.health = "unhealthy";
|
|
234
|
+
record.failures.push("start");
|
|
235
|
+
publish();
|
|
236
|
+
if (entry.required) {
|
|
237
|
+
throw new Error(`[stitchkit] required resource "${entry.id}" has an unavailable dependency`);
|
|
238
|
+
}
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
record.attempted = true;
|
|
242
|
+
record.state = "starting";
|
|
243
|
+
publish();
|
|
244
|
+
try {
|
|
245
|
+
const started = await entry.resource.start(contextFor(record, { signal: startupAbort.signal }));
|
|
246
|
+
if (shutdownRequested || startupAbort.signal.aborted) {
|
|
247
|
+
throw new Error("[stitchkit] application startup interrupted by shutdown");
|
|
248
|
+
}
|
|
249
|
+
if (isStartResult(started)) {
|
|
250
|
+
record.runtime = started;
|
|
251
|
+
let resourceReady = started.ready === undefined;
|
|
252
|
+
let completionSettled = false;
|
|
253
|
+
let completionFailure;
|
|
254
|
+
const completion = started.completion?.then(() => {
|
|
255
|
+
completionSettled = true;
|
|
256
|
+
if (resourceReady)
|
|
257
|
+
markLateCompletion(record, false);
|
|
258
|
+
}, (error) => {
|
|
259
|
+
completionSettled = true;
|
|
260
|
+
completionFailure = error;
|
|
261
|
+
if (resourceReady)
|
|
262
|
+
markLateCompletion(record, true);
|
|
263
|
+
});
|
|
264
|
+
if (started.ready && completion) {
|
|
265
|
+
const readiness = started.ready.then(() => "ready");
|
|
266
|
+
const completionBeforeReady = completion.then(() => "completion");
|
|
267
|
+
const first = await Promise.race([readiness, completionBeforeReady]);
|
|
268
|
+
if (first === "completion") {
|
|
269
|
+
throw new ResourceCompletionBeforeReadyError(entry.id, completionFailure);
|
|
270
|
+
}
|
|
271
|
+
resourceReady = true;
|
|
272
|
+
if (completionSettled) {
|
|
273
|
+
throw new ResourceCompletionBeforeReadyError(entry.id, completionFailure);
|
|
274
|
+
}
|
|
275
|
+
} else if (started.ready) {
|
|
276
|
+
await started.ready;
|
|
277
|
+
resourceReady = true;
|
|
278
|
+
} else if (completion) {}
|
|
279
|
+
}
|
|
280
|
+
if (shutdownRequested || startupAbort.signal.aborted) {
|
|
281
|
+
throw new Error("[stitchkit] application startup interrupted by shutdown");
|
|
282
|
+
}
|
|
283
|
+
record.state = "ready";
|
|
284
|
+
record.health = "healthy";
|
|
285
|
+
publish();
|
|
286
|
+
} catch (error) {
|
|
287
|
+
if (shutdownRequested || startupAbort.signal.aborted)
|
|
288
|
+
throw error;
|
|
289
|
+
record.failures.push(error instanceof ResourceCompletionBeforeReadyError ? "completion" : record.runtime?.ready ? "ready" : "start");
|
|
290
|
+
record.state = "failed";
|
|
291
|
+
record.health = "unhealthy";
|
|
292
|
+
publish();
|
|
293
|
+
if (entry.required)
|
|
294
|
+
throw error;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
lifecycle = "ready";
|
|
298
|
+
publish();
|
|
299
|
+
for (const entry of ordered) {
|
|
300
|
+
if (shutdownRequested || startupAbort.signal.aborted) {
|
|
301
|
+
throw new Error("[stitchkit] application startup interrupted by shutdown");
|
|
302
|
+
}
|
|
303
|
+
const record = records.get(entry.id);
|
|
304
|
+
if (record?.state !== "ready")
|
|
305
|
+
continue;
|
|
306
|
+
const dependencyUnavailable = entry.dependsOn.some((dependencyId) => {
|
|
307
|
+
const dependency = records.get(dependencyId);
|
|
308
|
+
return dependency?.state !== "ready" || !dependency.activated;
|
|
309
|
+
});
|
|
310
|
+
if (dependencyUnavailable) {
|
|
311
|
+
record.failures.push("start");
|
|
312
|
+
record.state = "failed";
|
|
313
|
+
record.health = "unhealthy";
|
|
314
|
+
publish();
|
|
315
|
+
if (entry.required) {
|
|
316
|
+
throw new Error(`[stitchkit] required resource "${entry.id}" has an unavailable activation dependency`);
|
|
317
|
+
}
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
await entry.resource.activate?.(contextFor(record));
|
|
322
|
+
if (shutdownRequested || startupAbort.signal.aborted) {
|
|
323
|
+
throw new Error("[stitchkit] application startup interrupted by shutdown");
|
|
324
|
+
}
|
|
325
|
+
record.activated = true;
|
|
326
|
+
if (entry.required && (record.state !== "ready" || record.health !== "healthy")) {
|
|
327
|
+
throw new Error(`[stitchkit] required resource "${entry.id}" lost readiness during activation`);
|
|
328
|
+
}
|
|
329
|
+
} catch (error) {
|
|
330
|
+
if (shutdownRequested || startupAbort.signal.aborted)
|
|
331
|
+
throw error;
|
|
332
|
+
record.failures.push("start");
|
|
333
|
+
record.state = "failed";
|
|
334
|
+
record.health = "unhealthy";
|
|
335
|
+
publish();
|
|
336
|
+
if (entry.required)
|
|
337
|
+
throw error;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
if (shutdownRequested) {
|
|
341
|
+
throw new Error("[stitchkit] application startup interrupted by shutdown");
|
|
342
|
+
}
|
|
343
|
+
if (!isReady()) {
|
|
344
|
+
throw new Error("[stitchkit] a required resource lost readiness during startup");
|
|
345
|
+
}
|
|
346
|
+
activationComplete = true;
|
|
347
|
+
accepting = isReady();
|
|
348
|
+
publish();
|
|
349
|
+
return snapshot();
|
|
350
|
+
} catch (error) {
|
|
351
|
+
startFailure = error;
|
|
352
|
+
}
|
|
353
|
+
if (!shutdownRequested) {
|
|
354
|
+
const rollbackErrors = await closeAttempted();
|
|
355
|
+
lifecycle = "failed";
|
|
356
|
+
accepting = false;
|
|
357
|
+
publish();
|
|
358
|
+
if (rollbackErrors.length > 0) {
|
|
359
|
+
throw new AggregateError([startFailure, ...rollbackErrors], "[stitchkit] application startup and rollback failed", { cause: startFailure });
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
throw startFailure;
|
|
363
|
+
};
|
|
364
|
+
const start = () => {
|
|
365
|
+
if (startPromise)
|
|
366
|
+
return startPromise;
|
|
367
|
+
if (lifecycle !== "created") {
|
|
368
|
+
return Promise.reject(new Error(`[stitchkit] application cannot start from lifecycle "${lifecycle}"`));
|
|
369
|
+
}
|
|
370
|
+
startPromise = runStart();
|
|
371
|
+
startPromise.catch(() => {
|
|
372
|
+
return;
|
|
373
|
+
});
|
|
374
|
+
return startPromise;
|
|
375
|
+
};
|
|
376
|
+
const acquire = () => {
|
|
377
|
+
if (!accepting || !isReady())
|
|
378
|
+
return null;
|
|
379
|
+
accepted += 1;
|
|
380
|
+
pending += 1;
|
|
381
|
+
publish();
|
|
382
|
+
let released = false;
|
|
383
|
+
return {
|
|
384
|
+
get released() {
|
|
385
|
+
return released;
|
|
386
|
+
},
|
|
387
|
+
release() {
|
|
388
|
+
if (released)
|
|
389
|
+
return;
|
|
390
|
+
released = true;
|
|
391
|
+
pending -= 1;
|
|
392
|
+
completed += 1;
|
|
393
|
+
if (pending === 0) {
|
|
394
|
+
for (const waiter of pendingWaiters)
|
|
395
|
+
waiter();
|
|
396
|
+
pendingWaiters.clear();
|
|
397
|
+
}
|
|
398
|
+
publish();
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
};
|
|
402
|
+
const run = async (work) => {
|
|
403
|
+
const lease = acquire();
|
|
404
|
+
if (!lease)
|
|
405
|
+
throw new ApplicationAdmissionError;
|
|
406
|
+
try {
|
|
407
|
+
return await work();
|
|
408
|
+
} finally {
|
|
409
|
+
lease.release();
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
const waitForPending = () => {
|
|
413
|
+
if (pending === 0)
|
|
414
|
+
return Promise.resolve();
|
|
415
|
+
return new Promise((resolve) => pendingWaiters.add(resolve));
|
|
416
|
+
};
|
|
417
|
+
const shutdown = (options) => {
|
|
418
|
+
if (shutdownPromise)
|
|
419
|
+
return shutdownPromise;
|
|
420
|
+
const parsed = ShutdownOptionsSchema.parse(options ?? {});
|
|
421
|
+
const startedAt = performance.now();
|
|
422
|
+
const graceDeadlineAt = startedAt + parsed.gracePeriodMs;
|
|
423
|
+
const forceDeadlineAt = graceDeadlineAt + parsed.forceTimeoutMs;
|
|
424
|
+
shutdownRequested = true;
|
|
425
|
+
accepting = false;
|
|
426
|
+
startupAbort.abort();
|
|
427
|
+
lifecycle = lifecycle === "created" ? "stopping" : "draining";
|
|
428
|
+
publish();
|
|
429
|
+
shutdownPromise = (async () => {
|
|
430
|
+
const gracefulAbort = new AbortController;
|
|
431
|
+
let forcedReason;
|
|
432
|
+
let gracefulFailed = [...records.values()].some((record) => record.attempted && record.closeInvoked && !record.closed);
|
|
433
|
+
const force = (reason) => {
|
|
434
|
+
if (forcedReason)
|
|
435
|
+
return;
|
|
436
|
+
forcedReason = reason;
|
|
437
|
+
gracefulAbort.abort();
|
|
438
|
+
lifetimeAbort.abort();
|
|
439
|
+
};
|
|
440
|
+
const graceTimer = setTimeout(() => force("deadline"), Math.max(0, graceDeadlineAt - performance.now()));
|
|
441
|
+
const onExternalAbort = () => force("signal");
|
|
442
|
+
parsed.signal?.addEventListener("abort", onExternalAbort, { once: true });
|
|
443
|
+
if (parsed.signal?.aborted)
|
|
444
|
+
force("signal");
|
|
445
|
+
if (startPromise) {
|
|
446
|
+
await untilDeadline(startPromise.catch(() => {
|
|
447
|
+
return;
|
|
448
|
+
}), gracefulAbort.signal);
|
|
449
|
+
}
|
|
450
|
+
const gracefulContext = (record) => contextFor(record, {
|
|
451
|
+
signal: gracefulAbort.signal,
|
|
452
|
+
deadlineAt: graceDeadlineAt,
|
|
453
|
+
forceDeadlineAt
|
|
454
|
+
});
|
|
455
|
+
for (const entry of reverse) {
|
|
456
|
+
if (gracefulAbort.signal.aborted)
|
|
457
|
+
break;
|
|
458
|
+
const record = records.get(entry.id);
|
|
459
|
+
if (!record?.attempted || record.closed)
|
|
460
|
+
continue;
|
|
461
|
+
try {
|
|
462
|
+
const result = await untilDeadline(Promise.resolve(entry.resource.stopAdmission?.(gracefulContext(record))), gracefulAbort.signal);
|
|
463
|
+
if (!result.settled)
|
|
464
|
+
break;
|
|
465
|
+
if (result.error !== undefined)
|
|
466
|
+
throw result.error;
|
|
467
|
+
} catch {
|
|
468
|
+
record.failures.push("admission");
|
|
469
|
+
gracefulFailed = true;
|
|
470
|
+
lifetimeAbort.abort();
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
if (!gracefulAbort.signal.aborted && !gracefulFailed) {
|
|
474
|
+
const result = await untilDeadline(waitForPending(), gracefulAbort.signal);
|
|
475
|
+
if (!result.settled)
|
|
476
|
+
force("deadline");
|
|
477
|
+
}
|
|
478
|
+
for (const entry of reverse) {
|
|
479
|
+
if (gracefulAbort.signal.aborted || gracefulFailed)
|
|
480
|
+
break;
|
|
481
|
+
const record = records.get(entry.id);
|
|
482
|
+
if (!record?.attempted || record.closed)
|
|
483
|
+
continue;
|
|
484
|
+
record.state = "stopping";
|
|
485
|
+
publish();
|
|
486
|
+
try {
|
|
487
|
+
const drained = await untilDeadline(Promise.resolve(entry.resource.drain?.(gracefulContext(record))), gracefulAbort.signal);
|
|
488
|
+
if (!drained.settled) {
|
|
489
|
+
force("deadline");
|
|
490
|
+
break;
|
|
491
|
+
}
|
|
492
|
+
if (drained.error !== undefined)
|
|
493
|
+
throw drained.error;
|
|
494
|
+
} catch {
|
|
495
|
+
record.failures.push("drain");
|
|
496
|
+
gracefulFailed = true;
|
|
497
|
+
lifetimeAbort.abort();
|
|
498
|
+
break;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
lifecycle = "stopping";
|
|
502
|
+
publish();
|
|
503
|
+
for (const entry of reverse) {
|
|
504
|
+
if (gracefulAbort.signal.aborted || gracefulFailed)
|
|
505
|
+
break;
|
|
506
|
+
const record = records.get(entry.id);
|
|
507
|
+
if (!record?.attempted || record.closed || record.closeInvoked)
|
|
508
|
+
continue;
|
|
509
|
+
try {
|
|
510
|
+
record.closeInvoked = true;
|
|
511
|
+
const closed = await untilDeadline(Promise.resolve(entry.resource.close?.(gracefulContext(record))), gracefulAbort.signal);
|
|
512
|
+
if (!closed.settled) {
|
|
513
|
+
force("deadline");
|
|
514
|
+
break;
|
|
515
|
+
}
|
|
516
|
+
if (closed.error !== undefined)
|
|
517
|
+
throw closed.error;
|
|
518
|
+
record.closed = true;
|
|
519
|
+
record.state = "stopped";
|
|
520
|
+
publish();
|
|
521
|
+
} catch {
|
|
522
|
+
record.failures.push("close");
|
|
523
|
+
record.state = "failed";
|
|
524
|
+
gracefulFailed = true;
|
|
525
|
+
lifetimeAbort.abort();
|
|
526
|
+
publish();
|
|
527
|
+
break;
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
clearTimeout(graceTimer);
|
|
531
|
+
parsed.signal?.removeEventListener("abort", onExternalAbort);
|
|
532
|
+
const mustForce = forcedReason !== undefined || gracefulFailed;
|
|
533
|
+
const pendingOperationsAtForce = mustForce ? pending : 0;
|
|
534
|
+
if (mustForce) {
|
|
535
|
+
lifetimeAbort.abort();
|
|
536
|
+
const forceAbort = new AbortController;
|
|
537
|
+
const forceTimer = setTimeout(() => forceAbort.abort(), Math.max(0, forceDeadlineAt - performance.now()));
|
|
538
|
+
await Promise.all(reverse.map(async (entry) => {
|
|
539
|
+
const record = records.get(entry.id);
|
|
540
|
+
if (!record?.attempted || record.closed)
|
|
541
|
+
return;
|
|
542
|
+
try {
|
|
543
|
+
let cleanup;
|
|
544
|
+
if (entry.resource.force) {
|
|
545
|
+
cleanup = Promise.resolve(entry.resource.force(contextFor(record, {
|
|
546
|
+
signal: forceAbort.signal,
|
|
547
|
+
deadlineAt: graceDeadlineAt,
|
|
548
|
+
forceDeadlineAt
|
|
549
|
+
})));
|
|
550
|
+
} else if (entry.resource.close && !record.closeInvoked) {
|
|
551
|
+
record.closeInvoked = true;
|
|
552
|
+
cleanup = Promise.resolve(entry.resource.close(contextFor(record, {
|
|
553
|
+
signal: forceAbort.signal,
|
|
554
|
+
deadlineAt: graceDeadlineAt,
|
|
555
|
+
forceDeadlineAt
|
|
556
|
+
})));
|
|
557
|
+
} else if (entry.resource.close) {
|
|
558
|
+
record.failures.push("force");
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
const forced = await untilDeadline(cleanup ?? Promise.resolve(), forceAbort.signal);
|
|
562
|
+
if (!forced.settled || forced.error !== undefined) {
|
|
563
|
+
record.failures.push("force");
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
record.closed = true;
|
|
567
|
+
record.state = "stopped";
|
|
568
|
+
} catch {
|
|
569
|
+
record.failures.push("force");
|
|
570
|
+
}
|
|
571
|
+
}));
|
|
572
|
+
clearTimeout(forceTimer);
|
|
573
|
+
}
|
|
574
|
+
const cleanupComplete = [...records.values()].every((record) => !record.attempted || record.closed);
|
|
575
|
+
lifecycle = cleanupComplete ? "stopped" : "failed";
|
|
576
|
+
publish();
|
|
577
|
+
return ApplicationShutdownResultSchema.parse({
|
|
578
|
+
outcome: mustForce ? "forced" : "clean",
|
|
579
|
+
...forcedReason && { reason: forcedReason },
|
|
580
|
+
cleanupComplete,
|
|
581
|
+
acceptedOperations: accepted,
|
|
582
|
+
completedOperations: completed,
|
|
583
|
+
pendingOperations: pending,
|
|
584
|
+
pendingOperationsAtForce,
|
|
585
|
+
resources: ordered.map((entry) => {
|
|
586
|
+
const record = records.get(entry.id);
|
|
587
|
+
if (!record)
|
|
588
|
+
throw new Error("Managed resource record disappeared");
|
|
589
|
+
return {
|
|
590
|
+
id: entry.id,
|
|
591
|
+
state: !record.attempted ? "not-started" : record.closed ? "closed" : "force-failed",
|
|
592
|
+
failures: record.failures
|
|
593
|
+
};
|
|
594
|
+
}),
|
|
595
|
+
durationMs: performance.now() - startedAt
|
|
596
|
+
});
|
|
597
|
+
})();
|
|
598
|
+
shutdownPromise.catch(() => {
|
|
599
|
+
return;
|
|
600
|
+
});
|
|
601
|
+
return shutdownPromise;
|
|
602
|
+
};
|
|
603
|
+
return {
|
|
604
|
+
id,
|
|
605
|
+
admission: { acquire, run },
|
|
606
|
+
start,
|
|
607
|
+
getSnapshot: snapshot,
|
|
608
|
+
subscribe(listener) {
|
|
609
|
+
listeners.add(listener);
|
|
610
|
+
listener(snapshot());
|
|
611
|
+
return () => listeners.delete(listener);
|
|
612
|
+
},
|
|
613
|
+
shutdown
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
export { ApplicationAdmissionError, createApplication };
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// src/application/schemas.ts
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
var ApplicationIdSchema = z.string().min(1).max(128).regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]*$/);
|
|
4
|
+
var ApplicationLifecycleSchema = z.enum([
|
|
5
|
+
"created",
|
|
6
|
+
"starting",
|
|
7
|
+
"ready",
|
|
8
|
+
"draining",
|
|
9
|
+
"stopping",
|
|
10
|
+
"stopped",
|
|
11
|
+
"failed"
|
|
12
|
+
]);
|
|
13
|
+
var ApplicationHealthSchema = z.enum(["unknown", "healthy", "degraded", "unhealthy"]);
|
|
14
|
+
var ManagedResourceStateSchema = z.enum([
|
|
15
|
+
"registered",
|
|
16
|
+
"starting",
|
|
17
|
+
"ready",
|
|
18
|
+
"failed",
|
|
19
|
+
"stopping",
|
|
20
|
+
"stopped"
|
|
21
|
+
]);
|
|
22
|
+
var NonNegativeIntegerSchema = z.number().int().nonnegative();
|
|
23
|
+
var ApplicationAdmissionSnapshotSchema = z.object({
|
|
24
|
+
accepting: z.boolean(),
|
|
25
|
+
accepted: NonNegativeIntegerSchema,
|
|
26
|
+
completed: NonNegativeIntegerSchema,
|
|
27
|
+
pending: NonNegativeIntegerSchema
|
|
28
|
+
}).readonly();
|
|
29
|
+
var ManagedResourceSnapshotSchema = z.object({
|
|
30
|
+
id: ApplicationIdSchema,
|
|
31
|
+
required: z.boolean(),
|
|
32
|
+
dependsOn: z.array(ApplicationIdSchema).readonly(),
|
|
33
|
+
state: ManagedResourceStateSchema,
|
|
34
|
+
health: ApplicationHealthSchema,
|
|
35
|
+
ready: z.boolean()
|
|
36
|
+
}).readonly();
|
|
37
|
+
var ApplicationSnapshotSchema = z.object({
|
|
38
|
+
id: ApplicationIdSchema,
|
|
39
|
+
epoch: z.string().uuid(),
|
|
40
|
+
revision: NonNegativeIntegerSchema,
|
|
41
|
+
lifecycle: ApplicationLifecycleSchema,
|
|
42
|
+
health: ApplicationHealthSchema,
|
|
43
|
+
ready: z.boolean(),
|
|
44
|
+
capturedAt: z.string().datetime({ offset: true }),
|
|
45
|
+
changedAt: z.string().datetime({ offset: true }),
|
|
46
|
+
admission: ApplicationAdmissionSnapshotSchema,
|
|
47
|
+
resources: z.array(ManagedResourceSnapshotSchema).readonly()
|
|
48
|
+
}).readonly();
|
|
49
|
+
var ApplicationResourceShutdownSchema = z.object({
|
|
50
|
+
id: ApplicationIdSchema,
|
|
51
|
+
state: z.enum(["not-started", "closed", "force-failed"]),
|
|
52
|
+
failures: z.array(z.enum(["start", "ready", "completion", "admission", "drain", "close", "force"])).readonly()
|
|
53
|
+
}).readonly();
|
|
54
|
+
var ApplicationShutdownResultSchema = z.object({
|
|
55
|
+
outcome: z.enum(["clean", "forced"]),
|
|
56
|
+
reason: z.enum(["deadline", "signal"]).optional(),
|
|
57
|
+
cleanupComplete: z.boolean(),
|
|
58
|
+
acceptedOperations: NonNegativeIntegerSchema,
|
|
59
|
+
completedOperations: NonNegativeIntegerSchema,
|
|
60
|
+
pendingOperations: NonNegativeIntegerSchema,
|
|
61
|
+
pendingOperationsAtForce: NonNegativeIntegerSchema,
|
|
62
|
+
resources: z.array(ApplicationResourceShutdownSchema).readonly(),
|
|
63
|
+
durationMs: z.number().nonnegative()
|
|
64
|
+
}).readonly();
|
|
65
|
+
|
|
66
|
+
export { ApplicationIdSchema, ApplicationLifecycleSchema, ApplicationHealthSchema, ManagedResourceStateSchema, ApplicationAdmissionSnapshotSchema, ManagedResourceSnapshotSchema, ApplicationSnapshotSchema, ApplicationResourceShutdownSchema, ApplicationShutdownResultSchema };
|