stitchkit 0.59.1 → 0.59.2

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.
Files changed (42) hide show
  1. package/README.md +44 -4
  2. package/dist/application/activity.d.ts +70 -0
  3. package/dist/application/activity.d.ts.map +1 -0
  4. package/dist/application/events.d.ts +65 -0
  5. package/dist/application/events.d.ts.map +1 -0
  6. package/dist/application/grammy.d.ts +35 -0
  7. package/dist/application/grammy.d.ts.map +1 -0
  8. package/dist/application/graph.d.ts +11 -0
  9. package/dist/application/graph.d.ts.map +1 -0
  10. package/dist/application/health.d.ts +13 -0
  11. package/dist/application/health.d.ts.map +1 -0
  12. package/dist/application/kernel.d.ts +31 -0
  13. package/dist/application/kernel.d.ts.map +1 -0
  14. package/dist/application/latest-sink.d.ts +39 -0
  15. package/dist/application/latest-sink.d.ts.map +1 -0
  16. package/dist/application/resource.d.ts +30 -0
  17. package/dist/application/resource.d.ts.map +1 -0
  18. package/dist/application/schedule.d.ts +112 -0
  19. package/dist/application/schedule.d.ts.map +1 -0
  20. package/dist/application/schemas.d.ts +160 -0
  21. package/dist/application/schemas.d.ts.map +1 -0
  22. package/dist/application/server-resource.d.ts +12 -0
  23. package/dist/application/server-resource.d.ts.map +1 -0
  24. package/dist/application-grammy.d.ts +2 -0
  25. package/dist/application-grammy.d.ts.map +1 -0
  26. package/dist/application-grammy.js +165 -0
  27. package/dist/application.d.ts +10 -0
  28. package/dist/application.d.ts.map +1 -0
  29. package/dist/application.js +1370 -0
  30. package/dist/index-dk6e56g0.js +211 -0
  31. package/dist/{index-9zn9fb4e.js → index-he4psyve.js} +6 -213
  32. package/dist/index-yr276yz0.js +6 -0
  33. package/dist/internal/fetch-port.d.ts +2 -0
  34. package/dist/internal/fetch-port.d.ts.map +1 -0
  35. package/dist/node.js +115 -13
  36. package/dist/server/index.js +8 -6
  37. package/dist/server/node.d.ts.map +1 -1
  38. package/dist/server/process-signals.d.ts +10 -8
  39. package/dist/server/process-signals.d.ts.map +1 -1
  40. package/llms-full.txt +379 -0
  41. package/llms.txt +1 -0
  42. package/package.json +15 -2
@@ -0,0 +1,1370 @@
1
+ import {
2
+ defineManagedResource
3
+ } from "./index-yr276yz0.js";
4
+ import {
5
+ ShutdownOptionsSchema
6
+ } from "./index-dk6e56g0.js";
7
+ import {
8
+ createBoundedSinkManager
9
+ } from "./index-0nc0cddp.js";
10
+ import"./index-1bx83sw4.js";
11
+
12
+ // src/application/activity.ts
13
+ import { z as z2 } from "zod";
14
+
15
+ // src/application/latest-sink.ts
16
+ import { z } from "zod";
17
+ var SnapshotRevisionSchema = z.number().int().nonnegative();
18
+ var ApplicationSnapshotSinkStatusSchema = z.object({
19
+ accepting: z.boolean(),
20
+ received: z.number().int().nonnegative(),
21
+ accepted: z.number().int().nonnegative(),
22
+ rejected: z.number().int().nonnegative(),
23
+ delivered: z.number().int().nonnegative(),
24
+ coalesced: z.number().int().nonnegative(),
25
+ failed: z.number().int().nonnegative(),
26
+ inFlight: z.boolean(),
27
+ pending: z.boolean(),
28
+ lastAcceptedRevision: SnapshotRevisionSchema.optional(),
29
+ lastDeliveredRevision: SnapshotRevisionSchema.optional()
30
+ }).strict().readonly();
31
+ function createApplicationSnapshotSink(config) {
32
+ let accepting = true;
33
+ let received = 0;
34
+ let accepted = 0;
35
+ let rejected = 0;
36
+ let delivered = 0;
37
+ let coalesced = 0;
38
+ let failed = 0;
39
+ let lastAcceptedRevision;
40
+ let lastDeliveredRevision;
41
+ let inFlight;
42
+ let pending;
43
+ let closePromise;
44
+ let resolveClose;
45
+ const getStatus = () => ApplicationSnapshotSinkStatusSchema.parse({
46
+ accepting,
47
+ received,
48
+ accepted,
49
+ rejected,
50
+ delivered,
51
+ coalesced,
52
+ failed,
53
+ inFlight: inFlight !== undefined,
54
+ pending: pending !== undefined,
55
+ ...lastAcceptedRevision !== undefined && { lastAcceptedRevision },
56
+ ...lastDeliveredRevision !== undefined && { lastDeliveredRevision }
57
+ });
58
+ const reportFailure = (error, snapshot) => {
59
+ if (!config.onSinkError)
60
+ return;
61
+ Promise.resolve().then(() => config.onSinkError?.({ error, snapshot })).catch(() => {
62
+ return;
63
+ });
64
+ };
65
+ const settleCloseIfIdle = () => {
66
+ if (accepting || inFlight || pending || !resolveClose)
67
+ return;
68
+ const resolve = resolveClose;
69
+ resolveClose = undefined;
70
+ resolve(getStatus());
71
+ };
72
+ const startWrite = (snapshot) => {
73
+ const write = Promise.resolve().then(() => config.write(snapshot)).then(() => {
74
+ delivered += 1;
75
+ lastDeliveredRevision = snapshot.revision;
76
+ }).catch((error) => {
77
+ failed += 1;
78
+ reportFailure(error, snapshot);
79
+ }).finally(() => {
80
+ inFlight = undefined;
81
+ const next = pending;
82
+ pending = undefined;
83
+ if (next)
84
+ startWrite(next);
85
+ else
86
+ settleCloseIfIdle();
87
+ });
88
+ inFlight = write;
89
+ };
90
+ return {
91
+ publish(snapshot) {
92
+ received += 1;
93
+ const revision = SnapshotRevisionSchema.parse(snapshot.revision);
94
+ if (!accepting || lastAcceptedRevision !== undefined && revision <= lastAcceptedRevision) {
95
+ rejected += 1;
96
+ return false;
97
+ }
98
+ accepted += 1;
99
+ lastAcceptedRevision = revision;
100
+ if (!inFlight) {
101
+ startWrite(snapshot);
102
+ } else {
103
+ if (pending)
104
+ coalesced += 1;
105
+ pending = snapshot;
106
+ }
107
+ return true;
108
+ },
109
+ getStatus,
110
+ close() {
111
+ if (closePromise)
112
+ return closePromise;
113
+ accepting = false;
114
+ closePromise = new Promise((resolve) => {
115
+ resolveClose = resolve;
116
+ settleCloseIfIdle();
117
+ });
118
+ return closePromise;
119
+ }
120
+ };
121
+ }
122
+
123
+ // src/application/activity.ts
124
+ var BoundedOperationalIdSchema = z2.string().min(1).max(64).regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]*$/);
125
+ var NonNegativeIntegerSchema = z2.number().int().nonnegative();
126
+ var ActivityIdSchema = BoundedOperationalIdSchema;
127
+ var ActivityStageIdSchema = BoundedOperationalIdSchema;
128
+ var ActivityStageSnapshotSchema = z2.object({
129
+ id: ActivityStageIdSchema,
130
+ active: NonNegativeIntegerSchema,
131
+ queued: NonNegativeIntegerSchema,
132
+ completed: NonNegativeIntegerSchema,
133
+ failed: NonNegativeIntegerSchema
134
+ }).strict().readonly();
135
+ var ActivityTotalsSchema = z2.object({
136
+ active: NonNegativeIntegerSchema,
137
+ queued: NonNegativeIntegerSchema,
138
+ completed: NonNegativeIntegerSchema,
139
+ failed: NonNegativeIntegerSchema
140
+ }).strict().readonly();
141
+ var ActivitySnapshotSchema = z2.object({
142
+ id: ActivityIdSchema,
143
+ epoch: z2.string().uuid(),
144
+ revision: NonNegativeIntegerSchema,
145
+ capturedAt: z2.string().datetime({ offset: true }),
146
+ changedAt: z2.string().datetime({ offset: true }),
147
+ stages: z2.array(ActivityStageSnapshotSchema).min(1).max(64).readonly(),
148
+ totals: ActivityTotalsSchema
149
+ }).strict().readonly();
150
+ var ActivityLiveStateSchema = z2.enum(["active", "queued"]);
151
+ var ActivityTokenBrand = Symbol("stitchkit.application.activity");
152
+ function emptyCounters() {
153
+ return { active: 0, queued: 0, completed: 0, failed: 0 };
154
+ }
155
+ function totalsOf(stages) {
156
+ return stages.reduce((totals, stage) => ({
157
+ active: totals.active + stage.active,
158
+ queued: totals.queued + stage.queued,
159
+ completed: totals.completed + stage.completed,
160
+ failed: totals.failed + stage.failed
161
+ }), emptyCounters());
162
+ }
163
+ function createActivityProjection(config) {
164
+ const id = ActivityIdSchema.parse(config.id);
165
+ const declaredStages = z2.array(ActivityStageIdSchema).min(1).max(64).parse(config.stages);
166
+ const uniqueStages = new Set(declaredStages);
167
+ if (uniqueStages.size !== declaredStages.length) {
168
+ throw new Error("[stitchkit] createActivityProjection: stage ids must be unique");
169
+ }
170
+ const epoch = z2.string().uuid().parse(config.epoch ?? crypto.randomUUID());
171
+ const now = config.now ?? (() => new Date);
172
+ const counters = new Map(declaredStages.map((stage) => [stage, emptyCounters()]));
173
+ const activities = new WeakMap;
174
+ const subscribers = new Set;
175
+ let revision = 0;
176
+ let changedAt = now().toISOString();
177
+ const countersFor = (stage) => {
178
+ const value = counters.get(stage);
179
+ if (!value) {
180
+ throw new Error(`[stitchkit] createActivityProjection: undeclared stage "${stage}"`);
181
+ }
182
+ return value;
183
+ };
184
+ const getSnapshot = () => {
185
+ const stages = declaredStages.map((stage) => ({ id: stage, ...countersFor(stage) }));
186
+ return ActivitySnapshotSchema.parse({
187
+ id,
188
+ epoch,
189
+ revision,
190
+ capturedAt: now().toISOString(),
191
+ changedAt,
192
+ stages,
193
+ totals: totalsOf(stages)
194
+ });
195
+ };
196
+ const publishChange = () => {
197
+ revision += 1;
198
+ changedAt = now().toISOString();
199
+ const snapshot = getSnapshot();
200
+ for (const subscriber of subscribers)
201
+ subscriber.publish(snapshot);
202
+ };
203
+ const requireActivity = (token) => {
204
+ const activity = activities.get(token);
205
+ if (!activity) {
206
+ throw new Error("[stitchkit] activity token belongs to another projection");
207
+ }
208
+ return activity;
209
+ };
210
+ const leaveLiveState = (activity) => {
211
+ if (activity.state === "active" || activity.state === "queued") {
212
+ countersFor(activity.stage)[activity.state] -= 1;
213
+ }
214
+ };
215
+ const settle = (token, terminal) => {
216
+ const activity = requireActivity(token);
217
+ if (activity.state === "completed" || activity.state === "failed")
218
+ return false;
219
+ leaveLiveState(activity);
220
+ countersFor(activity.stage)[terminal] += 1;
221
+ activity.state = terminal;
222
+ publishChange();
223
+ return true;
224
+ };
225
+ return {
226
+ open(stage, rawState = "active") {
227
+ const parsedStage = ActivityStageIdSchema.parse(stage);
228
+ const state = ActivityLiveStateSchema.parse(rawState);
229
+ countersFor(parsedStage)[state] += 1;
230
+ const token = Object.freeze({
231
+ get [ActivityTokenBrand]() {
232
+ return true;
233
+ }
234
+ });
235
+ activities.set(token, { stage: parsedStage, state });
236
+ publishChange();
237
+ return token;
238
+ },
239
+ transition(token, input) {
240
+ const activity = requireActivity(token);
241
+ if (activity.state === "completed" || activity.state === "failed") {
242
+ throw new Error("[stitchkit] cannot transition a terminal activity");
243
+ }
244
+ const stage = ActivityStageIdSchema.parse(input.stage);
245
+ const state = ActivityLiveStateSchema.parse(input.state);
246
+ countersFor(stage);
247
+ if (activity.stage === stage && activity.state === state)
248
+ return false;
249
+ leaveLiveState(activity);
250
+ countersFor(stage)[state] += 1;
251
+ activity.stage = stage;
252
+ activity.state = state;
253
+ publishChange();
254
+ return true;
255
+ },
256
+ complete: (token) => settle(token, "completed"),
257
+ fail: (token) => settle(token, "failed"),
258
+ getSnapshot,
259
+ subscribe(listener) {
260
+ const sink = createApplicationSnapshotSink({
261
+ write: listener,
262
+ ...config.onSubscriberError && { onSinkError: config.onSubscriberError }
263
+ });
264
+ subscribers.add(sink);
265
+ sink.publish(getSnapshot());
266
+ return () => {
267
+ subscribers.delete(sink);
268
+ sink.close();
269
+ };
270
+ }
271
+ };
272
+ }
273
+ // src/application/events.ts
274
+ import { z as z4 } from "zod";
275
+
276
+ // src/application/schemas.ts
277
+ import { z as z3 } from "zod";
278
+ var ApplicationIdSchema = z3.string().min(1).max(128).regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]*$/);
279
+ var ApplicationLifecycleSchema = z3.enum([
280
+ "created",
281
+ "starting",
282
+ "ready",
283
+ "draining",
284
+ "stopping",
285
+ "stopped",
286
+ "failed"
287
+ ]);
288
+ var ApplicationHealthSchema = z3.enum(["unknown", "healthy", "degraded", "unhealthy"]);
289
+ var ManagedResourceStateSchema = z3.enum([
290
+ "registered",
291
+ "starting",
292
+ "ready",
293
+ "failed",
294
+ "stopping",
295
+ "stopped"
296
+ ]);
297
+ var NonNegativeIntegerSchema2 = z3.number().int().nonnegative();
298
+ var ApplicationAdmissionSnapshotSchema = z3.object({
299
+ accepting: z3.boolean(),
300
+ accepted: NonNegativeIntegerSchema2,
301
+ completed: NonNegativeIntegerSchema2,
302
+ pending: NonNegativeIntegerSchema2
303
+ }).readonly();
304
+ var ManagedResourceSnapshotSchema = z3.object({
305
+ id: ApplicationIdSchema,
306
+ required: z3.boolean(),
307
+ dependsOn: z3.array(ApplicationIdSchema).readonly(),
308
+ state: ManagedResourceStateSchema,
309
+ health: ApplicationHealthSchema,
310
+ ready: z3.boolean()
311
+ }).readonly();
312
+ var ApplicationSnapshotSchema = z3.object({
313
+ id: ApplicationIdSchema,
314
+ epoch: z3.string().uuid(),
315
+ revision: NonNegativeIntegerSchema2,
316
+ lifecycle: ApplicationLifecycleSchema,
317
+ health: ApplicationHealthSchema,
318
+ ready: z3.boolean(),
319
+ capturedAt: z3.string().datetime({ offset: true }),
320
+ changedAt: z3.string().datetime({ offset: true }),
321
+ admission: ApplicationAdmissionSnapshotSchema,
322
+ resources: z3.array(ManagedResourceSnapshotSchema).readonly()
323
+ }).readonly();
324
+ var ApplicationResourceShutdownSchema = z3.object({
325
+ id: ApplicationIdSchema,
326
+ state: z3.enum(["not-started", "closed", "force-failed"]),
327
+ failures: z3.array(z3.enum(["start", "ready", "completion", "admission", "drain", "close", "force"])).readonly()
328
+ }).readonly();
329
+ var ApplicationShutdownResultSchema = z3.object({
330
+ outcome: z3.enum(["clean", "forced"]),
331
+ reason: z3.enum(["deadline", "signal"]).optional(),
332
+ cleanupComplete: z3.boolean(),
333
+ acceptedOperations: NonNegativeIntegerSchema2,
334
+ completedOperations: NonNegativeIntegerSchema2,
335
+ pendingOperations: NonNegativeIntegerSchema2,
336
+ pendingOperationsAtForce: NonNegativeIntegerSchema2,
337
+ resources: z3.array(ApplicationResourceShutdownSchema).readonly(),
338
+ durationMs: z3.number().nonnegative()
339
+ }).readonly();
340
+
341
+ // src/application/events.ts
342
+ var ApplicationLifecycleEventSchema = z4.object({
343
+ type: z4.literal("application-state"),
344
+ applicationId: ApplicationIdSchema,
345
+ epoch: z4.string().uuid(),
346
+ revision: z4.number().int().nonnegative(),
347
+ lifecycle: ApplicationLifecycleSchema,
348
+ health: ApplicationHealthSchema,
349
+ ready: z4.boolean(),
350
+ capturedAt: z4.string().datetime({ offset: true }),
351
+ resources: z4.array(ManagedResourceSnapshotSchema).readonly()
352
+ }).strict().readonly();
353
+ function applicationLifecycleEvent(snapshot) {
354
+ return ApplicationLifecycleEventSchema.parse({
355
+ type: "application-state",
356
+ applicationId: snapshot.id,
357
+ epoch: snapshot.epoch,
358
+ revision: snapshot.revision,
359
+ lifecycle: snapshot.lifecycle,
360
+ health: snapshot.health,
361
+ ready: snapshot.ready,
362
+ capturedAt: snapshot.capturedAt,
363
+ resources: snapshot.resources
364
+ });
365
+ }
366
+ function createApplicationEventSink(config) {
367
+ const manager = createBoundedSinkManager({
368
+ write: config.write,
369
+ ...config.maxPending !== undefined && { maxPending: config.maxPending },
370
+ ...config.onSinkError && { onSinkError: config.onSinkError }
371
+ });
372
+ return {
373
+ publish(snapshot) {
374
+ manager.submit(() => applicationLifecycleEvent(snapshot));
375
+ },
376
+ flush: () => manager.flush(),
377
+ getStatus: () => manager.getStatus(),
378
+ close: () => manager.close()
379
+ };
380
+ }
381
+ // src/application/health.ts
382
+ import { z as z5 } from "zod";
383
+ var ApplicationHealthHandlerOptionsSchema = z5.object({
384
+ kind: z5.enum(["liveness", "readiness"]),
385
+ retryAfterSeconds: z5.number().int().nonnegative().default(5)
386
+ });
387
+ function createApplicationHealthHandler(application, options) {
388
+ const parsed = ApplicationHealthHandlerOptionsSchema.parse(options);
389
+ return () => {
390
+ const snapshot = application.getSnapshot();
391
+ const healthy = parsed.kind === "readiness" ? snapshot.ready : snapshot.lifecycle !== "failed" && snapshot.lifecycle !== "stopped";
392
+ return Response.json(snapshot, {
393
+ status: healthy ? 200 : 503,
394
+ ...healthy ? {} : { headers: { "Retry-After": String(parsed.retryAfterSeconds) } }
395
+ });
396
+ };
397
+ }
398
+ // src/application/graph.ts
399
+ function resolveResourceGraph(resources) {
400
+ const entries = resources.map((resource, declarationIndex) => ({
401
+ resource,
402
+ id: ApplicationIdSchema.parse(resource.id),
403
+ dependsOn: [...resource.dependsOn ?? []].map((id) => ApplicationIdSchema.parse(id)),
404
+ required: resource.required ?? true,
405
+ declarationIndex
406
+ }));
407
+ const byId = new Map;
408
+ for (const entry of entries) {
409
+ if (byId.has(entry.id)) {
410
+ throw new Error(`[stitchkit] createApplication: duplicate resource id "${entry.id}"`);
411
+ }
412
+ byId.set(entry.id, entry);
413
+ }
414
+ for (const entry of entries) {
415
+ for (const dependencyId of entry.dependsOn) {
416
+ const dependency = byId.get(dependencyId);
417
+ if (!dependency) {
418
+ throw new Error(`[stitchkit] createApplication: resource "${entry.id}" depends on missing resource "${dependencyId}"`);
419
+ }
420
+ if (entry.required && !dependency.required) {
421
+ throw new Error(`[stitchkit] createApplication: required resource "${entry.id}" cannot depend on optional resource "${dependencyId}"`);
422
+ }
423
+ }
424
+ }
425
+ const pending = new Map(entries.map((entry) => [entry.id, entry]));
426
+ const resolved = new Set;
427
+ const ordered = [];
428
+ while (pending.size > 0) {
429
+ const ready = [...pending.values()].filter((entry) => entry.dependsOn.every((id) => resolved.has(id))).sort((left, right) => left.declarationIndex - right.declarationIndex);
430
+ if (ready.length === 0) {
431
+ throw new Error(`[stitchkit] createApplication: resource dependency cycle: ${[...pending.keys()].join(", ")}`);
432
+ }
433
+ for (const entry of ready) {
434
+ pending.delete(entry.id);
435
+ resolved.add(entry.id);
436
+ ordered.push(entry);
437
+ }
438
+ }
439
+ return ordered;
440
+ }
441
+
442
+ // src/application/kernel.ts
443
+ class ResourceCompletionBeforeReadyError extends Error {
444
+ constructor(resourceId, cause) {
445
+ super(`[stitchkit] resource "${resourceId}" completed before reaching readiness`, {
446
+ ...cause !== undefined && { cause }
447
+ });
448
+ this.name = "ResourceCompletionBeforeReadyError";
449
+ }
450
+ }
451
+
452
+ class ApplicationAdmissionError extends Error {
453
+ code = "APPLICATION_NOT_ACCEPTING";
454
+ constructor() {
455
+ super("Application is not accepting new operations");
456
+ this.name = "ApplicationAdmissionError";
457
+ }
458
+ }
459
+ function isStartResult(value) {
460
+ return typeof value === "object" && value !== null;
461
+ }
462
+ function waitForAbort(signal) {
463
+ if (signal.aborted)
464
+ return Promise.resolve();
465
+ return new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }));
466
+ }
467
+ async function untilDeadline(work, signal) {
468
+ const result = await Promise.race([
469
+ work.then((value) => ({ settled: true, value }), (error) => ({ settled: true, error })),
470
+ waitForAbort(signal).then(() => ({ settled: false }))
471
+ ]);
472
+ return result;
473
+ }
474
+ function createApplication(config) {
475
+ const id = ApplicationIdSchema.parse(config.id);
476
+ const ordered = resolveResourceGraph(config.resources ?? []);
477
+ const reverse = [...ordered].reverse();
478
+ const records = new Map;
479
+ for (const entry of ordered) {
480
+ records.set(entry.id, {
481
+ entry,
482
+ state: "registered",
483
+ health: "unknown",
484
+ attempted: false,
485
+ activated: false,
486
+ closeInvoked: false,
487
+ closed: false,
488
+ failures: []
489
+ });
490
+ }
491
+ const epoch = crypto.randomUUID();
492
+ const listeners = new Set;
493
+ const lifetimeAbort = new AbortController;
494
+ const startupAbort = new AbortController;
495
+ let lifecycle = "created";
496
+ let revision = 0;
497
+ let changedAt = new Date().toISOString();
498
+ let accepting = false;
499
+ let accepted = 0;
500
+ let completed = 0;
501
+ let pending = 0;
502
+ let startPromise;
503
+ let shutdownPromise;
504
+ let shutdownRequested = false;
505
+ let activationComplete = false;
506
+ const pendingWaiters = new Set;
507
+ const aggregateHealth = () => {
508
+ if (lifecycle === "created" || lifecycle === "starting")
509
+ return "unknown";
510
+ let optionalUnhealthy = false;
511
+ for (const record of records.values()) {
512
+ if (record.entry.required && (record.state !== "ready" || record.health !== "healthy")) {
513
+ return "unhealthy";
514
+ }
515
+ if (!record.entry.required && (record.state !== "ready" || record.health !== "healthy")) {
516
+ optionalUnhealthy = true;
517
+ }
518
+ }
519
+ return optionalUnhealthy ? "degraded" : "healthy";
520
+ };
521
+ const isReady = () => lifecycle === "ready" && [...records.values()].every((record) => !record.entry.required || record.state === "ready" && record.health === "healthy");
522
+ const snapshot = () => ApplicationSnapshotSchema.parse({
523
+ id,
524
+ epoch,
525
+ revision,
526
+ lifecycle,
527
+ health: aggregateHealth(),
528
+ ready: isReady(),
529
+ capturedAt: new Date().toISOString(),
530
+ changedAt,
531
+ admission: { accepting, accepted, completed, pending },
532
+ resources: ordered.map((entry) => {
533
+ const record = records.get(entry.id);
534
+ if (!record)
535
+ throw new Error("Managed resource record disappeared");
536
+ return {
537
+ id: entry.id,
538
+ required: entry.required,
539
+ dependsOn: entry.dependsOn,
540
+ state: record.state,
541
+ health: record.health,
542
+ ready: record.state === "ready" && record.health === "healthy"
543
+ };
544
+ })
545
+ });
546
+ const publish = () => {
547
+ revision += 1;
548
+ changedAt = new Date().toISOString();
549
+ const value = snapshot();
550
+ for (const listener of listeners) {
551
+ try {
552
+ listener(value);
553
+ } catch {}
554
+ }
555
+ if (config.onSnapshot) {
556
+ Promise.resolve().then(() => config.onSnapshot?.(value)).catch(() => {});
557
+ }
558
+ };
559
+ const contextFor = (record, options = {}) => ({
560
+ applicationId: id,
561
+ signal: options.signal ?? lifetimeAbort.signal,
562
+ ...options.deadlineAt !== undefined && { deadlineAt: options.deadlineAt },
563
+ ...options.forceDeadlineAt !== undefined && {
564
+ forceDeadlineAt: options.forceDeadlineAt
565
+ },
566
+ now: () => performance.now(),
567
+ reportHealth(health) {
568
+ if (record.state === "stopped")
569
+ return;
570
+ record.health = health;
571
+ accepting = activationComplete && !shutdownRequested && isReady();
572
+ publish();
573
+ }
574
+ });
575
+ const markLateCompletion = (record, failure) => {
576
+ if (shutdownRequested || record.state === "stopping" || record.state === "stopped")
577
+ return;
578
+ if (failure)
579
+ record.failures.push("completion");
580
+ record.state = "failed";
581
+ record.health = "unhealthy";
582
+ accepting = activationComplete && isReady();
583
+ publish();
584
+ };
585
+ const closeAttempted = async () => {
586
+ const errors = [];
587
+ for (const entry of reverse) {
588
+ const record = records.get(entry.id);
589
+ if (!record?.attempted || record.closed)
590
+ continue;
591
+ record.state = "stopping";
592
+ try {
593
+ record.closeInvoked = true;
594
+ await entry.resource.close?.(contextFor(record, { signal: startupAbort.signal }));
595
+ record.closed = true;
596
+ record.state = "stopped";
597
+ } catch (error) {
598
+ record.failures.push("close");
599
+ record.state = "failed";
600
+ errors.push(error);
601
+ }
602
+ publish();
603
+ }
604
+ return errors;
605
+ };
606
+ const runStart = async () => {
607
+ lifecycle = "starting";
608
+ publish();
609
+ let startFailure;
610
+ try {
611
+ for (const entry of ordered) {
612
+ if (shutdownRequested || startupAbort.signal.aborted) {
613
+ throw new Error("[stitchkit] application startup interrupted by shutdown");
614
+ }
615
+ const record = records.get(entry.id);
616
+ if (!record)
617
+ throw new Error("Managed resource record disappeared");
618
+ const dependencyFailed = entry.dependsOn.some((dependencyId) => records.get(dependencyId)?.state !== "ready");
619
+ if (dependencyFailed) {
620
+ record.state = "failed";
621
+ record.health = "unhealthy";
622
+ record.failures.push("start");
623
+ publish();
624
+ if (entry.required) {
625
+ throw new Error(`[stitchkit] required resource "${entry.id}" has an unavailable dependency`);
626
+ }
627
+ continue;
628
+ }
629
+ record.attempted = true;
630
+ record.state = "starting";
631
+ publish();
632
+ try {
633
+ const started = await entry.resource.start(contextFor(record, { signal: startupAbort.signal }));
634
+ if (shutdownRequested || startupAbort.signal.aborted) {
635
+ throw new Error("[stitchkit] application startup interrupted by shutdown");
636
+ }
637
+ if (isStartResult(started)) {
638
+ record.runtime = started;
639
+ let resourceReady = started.ready === undefined;
640
+ let completionSettled = false;
641
+ let completionFailure;
642
+ const completion = started.completion?.then(() => {
643
+ completionSettled = true;
644
+ if (resourceReady)
645
+ markLateCompletion(record, false);
646
+ }, (error) => {
647
+ completionSettled = true;
648
+ completionFailure = error;
649
+ if (resourceReady)
650
+ markLateCompletion(record, true);
651
+ });
652
+ if (started.ready && completion) {
653
+ const readiness = started.ready.then(() => "ready");
654
+ const completionBeforeReady = completion.then(() => "completion");
655
+ const first = await Promise.race([readiness, completionBeforeReady]);
656
+ if (first === "completion") {
657
+ throw new ResourceCompletionBeforeReadyError(entry.id, completionFailure);
658
+ }
659
+ resourceReady = true;
660
+ if (completionSettled) {
661
+ throw new ResourceCompletionBeforeReadyError(entry.id, completionFailure);
662
+ }
663
+ } else if (started.ready) {
664
+ await started.ready;
665
+ resourceReady = true;
666
+ } else if (completion) {}
667
+ }
668
+ if (shutdownRequested || startupAbort.signal.aborted) {
669
+ throw new Error("[stitchkit] application startup interrupted by shutdown");
670
+ }
671
+ record.state = "ready";
672
+ record.health = "healthy";
673
+ publish();
674
+ } catch (error) {
675
+ if (shutdownRequested || startupAbort.signal.aborted)
676
+ throw error;
677
+ record.failures.push(error instanceof ResourceCompletionBeforeReadyError ? "completion" : record.runtime?.ready ? "ready" : "start");
678
+ record.state = "failed";
679
+ record.health = "unhealthy";
680
+ publish();
681
+ if (entry.required)
682
+ throw error;
683
+ }
684
+ }
685
+ lifecycle = "ready";
686
+ publish();
687
+ for (const entry of ordered) {
688
+ if (shutdownRequested || startupAbort.signal.aborted) {
689
+ throw new Error("[stitchkit] application startup interrupted by shutdown");
690
+ }
691
+ const record = records.get(entry.id);
692
+ if (record?.state !== "ready")
693
+ continue;
694
+ const dependencyUnavailable = entry.dependsOn.some((dependencyId) => {
695
+ const dependency = records.get(dependencyId);
696
+ return dependency?.state !== "ready" || !dependency.activated;
697
+ });
698
+ if (dependencyUnavailable) {
699
+ record.failures.push("start");
700
+ record.state = "failed";
701
+ record.health = "unhealthy";
702
+ publish();
703
+ if (entry.required) {
704
+ throw new Error(`[stitchkit] required resource "${entry.id}" has an unavailable activation dependency`);
705
+ }
706
+ continue;
707
+ }
708
+ try {
709
+ await entry.resource.activate?.(contextFor(record));
710
+ if (shutdownRequested || startupAbort.signal.aborted) {
711
+ throw new Error("[stitchkit] application startup interrupted by shutdown");
712
+ }
713
+ record.activated = true;
714
+ if (entry.required && (record.state !== "ready" || record.health !== "healthy")) {
715
+ throw new Error(`[stitchkit] required resource "${entry.id}" lost readiness during activation`);
716
+ }
717
+ } catch (error) {
718
+ if (shutdownRequested || startupAbort.signal.aborted)
719
+ throw error;
720
+ record.failures.push("start");
721
+ record.state = "failed";
722
+ record.health = "unhealthy";
723
+ publish();
724
+ if (entry.required)
725
+ throw error;
726
+ }
727
+ }
728
+ if (shutdownRequested) {
729
+ throw new Error("[stitchkit] application startup interrupted by shutdown");
730
+ }
731
+ if (!isReady()) {
732
+ throw new Error("[stitchkit] a required resource lost readiness during startup");
733
+ }
734
+ activationComplete = true;
735
+ accepting = isReady();
736
+ publish();
737
+ return snapshot();
738
+ } catch (error) {
739
+ startFailure = error;
740
+ }
741
+ if (!shutdownRequested) {
742
+ const rollbackErrors = await closeAttempted();
743
+ lifecycle = "failed";
744
+ accepting = false;
745
+ publish();
746
+ if (rollbackErrors.length > 0) {
747
+ throw new AggregateError([startFailure, ...rollbackErrors], "[stitchkit] application startup and rollback failed", { cause: startFailure });
748
+ }
749
+ }
750
+ throw startFailure;
751
+ };
752
+ const start = () => {
753
+ if (startPromise)
754
+ return startPromise;
755
+ if (lifecycle !== "created") {
756
+ return Promise.reject(new Error(`[stitchkit] application cannot start from lifecycle "${lifecycle}"`));
757
+ }
758
+ startPromise = runStart();
759
+ startPromise.catch(() => {
760
+ return;
761
+ });
762
+ return startPromise;
763
+ };
764
+ const acquire = () => {
765
+ if (!accepting || !isReady())
766
+ return null;
767
+ accepted += 1;
768
+ pending += 1;
769
+ publish();
770
+ let released = false;
771
+ return {
772
+ get released() {
773
+ return released;
774
+ },
775
+ release() {
776
+ if (released)
777
+ return;
778
+ released = true;
779
+ pending -= 1;
780
+ completed += 1;
781
+ if (pending === 0) {
782
+ for (const waiter of pendingWaiters)
783
+ waiter();
784
+ pendingWaiters.clear();
785
+ }
786
+ publish();
787
+ }
788
+ };
789
+ };
790
+ const run = async (work) => {
791
+ const lease = acquire();
792
+ if (!lease)
793
+ throw new ApplicationAdmissionError;
794
+ try {
795
+ return await work();
796
+ } finally {
797
+ lease.release();
798
+ }
799
+ };
800
+ const waitForPending = () => {
801
+ if (pending === 0)
802
+ return Promise.resolve();
803
+ return new Promise((resolve) => pendingWaiters.add(resolve));
804
+ };
805
+ const shutdown = (options) => {
806
+ if (shutdownPromise)
807
+ return shutdownPromise;
808
+ const parsed = ShutdownOptionsSchema.parse(options ?? {});
809
+ const startedAt = performance.now();
810
+ const graceDeadlineAt = startedAt + parsed.gracePeriodMs;
811
+ const forceDeadlineAt = graceDeadlineAt + parsed.forceTimeoutMs;
812
+ shutdownRequested = true;
813
+ accepting = false;
814
+ startupAbort.abort();
815
+ lifecycle = lifecycle === "created" ? "stopping" : "draining";
816
+ publish();
817
+ shutdownPromise = (async () => {
818
+ const gracefulAbort = new AbortController;
819
+ let forcedReason;
820
+ let gracefulFailed = [...records.values()].some((record) => record.attempted && record.closeInvoked && !record.closed);
821
+ const force = (reason) => {
822
+ if (forcedReason)
823
+ return;
824
+ forcedReason = reason;
825
+ gracefulAbort.abort();
826
+ lifetimeAbort.abort();
827
+ };
828
+ const graceTimer = setTimeout(() => force("deadline"), Math.max(0, graceDeadlineAt - performance.now()));
829
+ const onExternalAbort = () => force("signal");
830
+ parsed.signal?.addEventListener("abort", onExternalAbort, { once: true });
831
+ if (parsed.signal?.aborted)
832
+ force("signal");
833
+ if (startPromise) {
834
+ await untilDeadline(startPromise.catch(() => {
835
+ return;
836
+ }), gracefulAbort.signal);
837
+ }
838
+ const gracefulContext = (record) => contextFor(record, {
839
+ signal: gracefulAbort.signal,
840
+ deadlineAt: graceDeadlineAt,
841
+ forceDeadlineAt
842
+ });
843
+ for (const entry of reverse) {
844
+ if (gracefulAbort.signal.aborted)
845
+ break;
846
+ const record = records.get(entry.id);
847
+ if (!record?.attempted || record.closed)
848
+ continue;
849
+ try {
850
+ const result = await untilDeadline(Promise.resolve(entry.resource.stopAdmission?.(gracefulContext(record))), gracefulAbort.signal);
851
+ if (!result.settled)
852
+ break;
853
+ if (result.error !== undefined)
854
+ throw result.error;
855
+ } catch {
856
+ record.failures.push("admission");
857
+ gracefulFailed = true;
858
+ lifetimeAbort.abort();
859
+ }
860
+ }
861
+ if (!gracefulAbort.signal.aborted && !gracefulFailed) {
862
+ const result = await untilDeadline(waitForPending(), gracefulAbort.signal);
863
+ if (!result.settled)
864
+ force("deadline");
865
+ }
866
+ for (const entry of reverse) {
867
+ if (gracefulAbort.signal.aborted || gracefulFailed)
868
+ break;
869
+ const record = records.get(entry.id);
870
+ if (!record?.attempted || record.closed)
871
+ continue;
872
+ record.state = "stopping";
873
+ publish();
874
+ try {
875
+ const drained = await untilDeadline(Promise.resolve(entry.resource.drain?.(gracefulContext(record))), gracefulAbort.signal);
876
+ if (!drained.settled) {
877
+ force("deadline");
878
+ break;
879
+ }
880
+ if (drained.error !== undefined)
881
+ throw drained.error;
882
+ } catch {
883
+ record.failures.push("drain");
884
+ gracefulFailed = true;
885
+ lifetimeAbort.abort();
886
+ break;
887
+ }
888
+ }
889
+ lifecycle = "stopping";
890
+ publish();
891
+ for (const entry of reverse) {
892
+ if (gracefulAbort.signal.aborted || gracefulFailed)
893
+ break;
894
+ const record = records.get(entry.id);
895
+ if (!record?.attempted || record.closed || record.closeInvoked)
896
+ continue;
897
+ try {
898
+ record.closeInvoked = true;
899
+ const closed = await untilDeadline(Promise.resolve(entry.resource.close?.(gracefulContext(record))), gracefulAbort.signal);
900
+ if (!closed.settled) {
901
+ force("deadline");
902
+ break;
903
+ }
904
+ if (closed.error !== undefined)
905
+ throw closed.error;
906
+ record.closed = true;
907
+ record.state = "stopped";
908
+ publish();
909
+ } catch {
910
+ record.failures.push("close");
911
+ record.state = "failed";
912
+ gracefulFailed = true;
913
+ lifetimeAbort.abort();
914
+ publish();
915
+ break;
916
+ }
917
+ }
918
+ clearTimeout(graceTimer);
919
+ parsed.signal?.removeEventListener("abort", onExternalAbort);
920
+ const mustForce = forcedReason !== undefined || gracefulFailed;
921
+ const pendingOperationsAtForce = mustForce ? pending : 0;
922
+ if (mustForce) {
923
+ lifetimeAbort.abort();
924
+ const forceAbort = new AbortController;
925
+ const forceTimer = setTimeout(() => forceAbort.abort(), Math.max(0, forceDeadlineAt - performance.now()));
926
+ await Promise.all(reverse.map(async (entry) => {
927
+ const record = records.get(entry.id);
928
+ if (!record?.attempted || record.closed)
929
+ return;
930
+ try {
931
+ let cleanup;
932
+ if (entry.resource.force) {
933
+ cleanup = Promise.resolve(entry.resource.force(contextFor(record, {
934
+ signal: forceAbort.signal,
935
+ deadlineAt: graceDeadlineAt,
936
+ forceDeadlineAt
937
+ })));
938
+ } else if (entry.resource.close && !record.closeInvoked) {
939
+ record.closeInvoked = true;
940
+ cleanup = Promise.resolve(entry.resource.close(contextFor(record, {
941
+ signal: forceAbort.signal,
942
+ deadlineAt: graceDeadlineAt,
943
+ forceDeadlineAt
944
+ })));
945
+ } else if (entry.resource.close) {
946
+ record.failures.push("force");
947
+ return;
948
+ }
949
+ const forced = await untilDeadline(cleanup ?? Promise.resolve(), forceAbort.signal);
950
+ if (!forced.settled || forced.error !== undefined) {
951
+ record.failures.push("force");
952
+ return;
953
+ }
954
+ record.closed = true;
955
+ record.state = "stopped";
956
+ } catch {
957
+ record.failures.push("force");
958
+ }
959
+ }));
960
+ clearTimeout(forceTimer);
961
+ }
962
+ const cleanupComplete = [...records.values()].every((record) => !record.attempted || record.closed);
963
+ lifecycle = cleanupComplete ? "stopped" : "failed";
964
+ publish();
965
+ return ApplicationShutdownResultSchema.parse({
966
+ outcome: mustForce ? "forced" : "clean",
967
+ ...forcedReason && { reason: forcedReason },
968
+ cleanupComplete,
969
+ acceptedOperations: accepted,
970
+ completedOperations: completed,
971
+ pendingOperations: pending,
972
+ pendingOperationsAtForce,
973
+ resources: ordered.map((entry) => {
974
+ const record = records.get(entry.id);
975
+ if (!record)
976
+ throw new Error("Managed resource record disappeared");
977
+ return {
978
+ id: entry.id,
979
+ state: !record.attempted ? "not-started" : record.closed ? "closed" : "force-failed",
980
+ failures: record.failures
981
+ };
982
+ }),
983
+ durationMs: performance.now() - startedAt
984
+ });
985
+ })();
986
+ shutdownPromise.catch(() => {
987
+ return;
988
+ });
989
+ return shutdownPromise;
990
+ };
991
+ return {
992
+ id,
993
+ admission: { acquire, run },
994
+ start,
995
+ getSnapshot: snapshot,
996
+ subscribe(listener) {
997
+ listeners.add(listener);
998
+ listener(snapshot());
999
+ return () => listeners.delete(listener);
1000
+ },
1001
+ shutdown
1002
+ };
1003
+ }
1004
+ // src/application/schedule.ts
1005
+ import { z as z6 } from "zod";
1006
+ var NonNegativeSafeIntegerSchema = z6.number().int().nonnegative().refine(Number.isSafeInteger, "Expected a safe integer");
1007
+ var PositiveSafeIntegerSchema = NonNegativeSafeIntegerSchema.refine((value) => value > 0, "Expected a positive integer");
1008
+ var ManagedScheduleOverlapSchema = z6.discriminatedUnion("mode", [
1009
+ z6.object({ mode: z6.literal("skip") }).readonly(),
1010
+ z6.object({ mode: z6.literal("queue-one") }).readonly(),
1011
+ z6.object({
1012
+ mode: z6.literal("parallel"),
1013
+ maxConcurrent: PositiveSafeIntegerSchema
1014
+ }).readonly()
1015
+ ]);
1016
+ var ManagedScheduleErrorPolicySchema = z6.enum(["continue", "stop-schedule"]);
1017
+ var ManagedScheduleDescriptorSchema = z6.object({
1018
+ id: ApplicationIdSchema,
1019
+ everyMs: PositiveSafeIntegerSchema,
1020
+ startAfterMs: NonNegativeSafeIntegerSchema,
1021
+ overlap: ManagedScheduleOverlapSchema,
1022
+ errorPolicy: ManagedScheduleErrorPolicySchema
1023
+ }).readonly();
1024
+ var ManagedScheduleStatusSchema = z6.object({
1025
+ descriptor: ManagedScheduleDescriptorSchema,
1026
+ state: z6.enum(["inactive", "scheduled", "running", "draining", "stopped"]),
1027
+ revision: NonNegativeSafeIntegerSchema,
1028
+ capturedAt: z6.string().datetime({ offset: true }),
1029
+ changedAt: z6.string().datetime({ offset: true }),
1030
+ accepting: z6.boolean(),
1031
+ active: NonNegativeSafeIntegerSchema,
1032
+ queued: z6.boolean(),
1033
+ runsStarted: NonNegativeSafeIntegerSchema,
1034
+ runsCompleted: NonNegativeSafeIntegerSchema,
1035
+ runsFailed: NonNegativeSafeIntegerSchema,
1036
+ ticksSkipped: NonNegativeSafeIntegerSchema,
1037
+ nextRunAt: z6.string().datetime({ offset: true }).nullable(),
1038
+ lastScheduledAt: z6.string().datetime({ offset: true }).nullable(),
1039
+ lastStartedAt: z6.string().datetime({ offset: true }).nullable(),
1040
+ lastFinishedAt: z6.string().datetime({ offset: true }).nullable()
1041
+ }).readonly();
1042
+ var systemClock = {
1043
+ now: () => performance.now(),
1044
+ wallNow: () => new Date,
1045
+ schedule(callback, delayMs) {
1046
+ const timer = setTimeout(callback, delayMs);
1047
+ return { cancel: () => clearTimeout(timer) };
1048
+ }
1049
+ };
1050
+ var DEFAULT_OVERLAP = { mode: "skip" };
1051
+ function createManagedSchedule(config) {
1052
+ const descriptor = ManagedScheduleDescriptorSchema.parse({
1053
+ id: config.id,
1054
+ everyMs: config.everyMs,
1055
+ startAfterMs: config.startAfterMs ?? config.everyMs,
1056
+ overlap: config.overlap ?? DEFAULT_OVERLAP,
1057
+ errorPolicy: config.errorPolicy ?? "continue"
1058
+ });
1059
+ const dependsOn = config.dependsOn?.map((id) => ApplicationIdSchema.parse(id));
1060
+ const clock = config.clock ?? systemClock;
1061
+ let revision = 0;
1062
+ let accepting = false;
1063
+ let activated = false;
1064
+ let stopped = false;
1065
+ let timer = null;
1066
+ let activationContext = null;
1067
+ let nextRunAt = null;
1068
+ let queuedAt = null;
1069
+ let runsStarted = 0;
1070
+ let runsCompleted = 0;
1071
+ let runsFailed = 0;
1072
+ let ticksSkipped = 0;
1073
+ let lastScheduledAt = null;
1074
+ let lastStartedAt = null;
1075
+ let lastFinishedAt = null;
1076
+ let changedAt = clock.wallNow().toISOString();
1077
+ const active = new Set;
1078
+ const changed = () => {
1079
+ revision += 1;
1080
+ changedAt = clock.wallNow().toISOString();
1081
+ };
1082
+ const cancelFuture = () => {
1083
+ timer?.cancel();
1084
+ timer = null;
1085
+ nextRunAt = null;
1086
+ queuedAt = null;
1087
+ };
1088
+ const stopAdmission = () => {
1089
+ if (!accepting && stopped)
1090
+ return;
1091
+ accepting = false;
1092
+ stopped = true;
1093
+ cancelFuture();
1094
+ changed();
1095
+ };
1096
+ const reportError = (error, context) => {
1097
+ if (!config.onError)
1098
+ return;
1099
+ Promise.resolve().then(() => config.onError?.(error, context)).catch(() => {});
1100
+ };
1101
+ const state = () => {
1102
+ if (!activated)
1103
+ return stopped ? "stopped" : "inactive";
1104
+ if (!accepting)
1105
+ return active.size > 0 ? "draining" : "stopped";
1106
+ return active.size > 0 ? "running" : "scheduled";
1107
+ };
1108
+ const wallAt = (monotonicAt, anchor) => {
1109
+ if (monotonicAt === null)
1110
+ return null;
1111
+ return new Date(anchor.wallNow + monotonicAt - anchor.monotonicNow).toISOString();
1112
+ };
1113
+ const status = () => {
1114
+ const captured = clock.wallNow();
1115
+ const anchor = { monotonicNow: clock.now(), wallNow: captured.getTime() };
1116
+ return ManagedScheduleStatusSchema.parse({
1117
+ descriptor,
1118
+ state: state(),
1119
+ revision,
1120
+ capturedAt: captured.toISOString(),
1121
+ changedAt,
1122
+ accepting,
1123
+ active: active.size,
1124
+ queued: queuedAt !== null,
1125
+ runsStarted,
1126
+ runsCompleted,
1127
+ runsFailed,
1128
+ ticksSkipped,
1129
+ nextRunAt: wallAt(nextRunAt, anchor),
1130
+ lastScheduledAt,
1131
+ lastStartedAt,
1132
+ lastFinishedAt
1133
+ });
1134
+ };
1135
+ let startExecution = () => {
1136
+ return;
1137
+ };
1138
+ const settleExecution = () => {
1139
+ if (!accepting || queuedAt === null || active.size !== 0)
1140
+ return;
1141
+ const successorAt = queuedAt;
1142
+ queuedAt = null;
1143
+ changed();
1144
+ startExecution(successorAt);
1145
+ };
1146
+ startExecution = (scheduledAt) => {
1147
+ const resourceContext = activationContext;
1148
+ if (!accepting || !resourceContext)
1149
+ return;
1150
+ const startedAt = clock.now();
1151
+ const wallStartedAt = clock.wallNow().getTime();
1152
+ const runContext = {
1153
+ applicationId: resourceContext.applicationId,
1154
+ signal: resourceContext.signal,
1155
+ scheduledAt,
1156
+ startedAt,
1157
+ now: () => clock.now()
1158
+ };
1159
+ runsStarted += 1;
1160
+ lastScheduledAt = new Date(wallStartedAt + scheduledAt - startedAt).toISOString();
1161
+ lastStartedAt = new Date(wallStartedAt).toISOString();
1162
+ changed();
1163
+ let tracked;
1164
+ tracked = Promise.resolve().then(() => config.run(runContext)).then(() => {
1165
+ runsCompleted += 1;
1166
+ lastFinishedAt = clock.wallNow().toISOString();
1167
+ if (descriptor.errorPolicy === "continue" && accepting) {
1168
+ resourceContext.reportHealth("healthy");
1169
+ }
1170
+ }, (error) => {
1171
+ runsFailed += 1;
1172
+ lastFinishedAt = clock.wallNow().toISOString();
1173
+ reportError(error, runContext);
1174
+ if (descriptor.errorPolicy === "stop-schedule") {
1175
+ resourceContext.reportHealth("unhealthy");
1176
+ stopAdmission();
1177
+ } else {
1178
+ resourceContext.reportHealth("degraded");
1179
+ }
1180
+ }).finally(() => {
1181
+ active.delete(tracked);
1182
+ changed();
1183
+ settleExecution();
1184
+ });
1185
+ active.add(tracked);
1186
+ };
1187
+ const dispatchTick = (scheduledAt) => {
1188
+ if (!accepting)
1189
+ return;
1190
+ if (descriptor.overlap.mode === "skip") {
1191
+ if (active.size > 0) {
1192
+ ticksSkipped += 1;
1193
+ changed();
1194
+ return;
1195
+ }
1196
+ startExecution(scheduledAt);
1197
+ return;
1198
+ }
1199
+ if (descriptor.overlap.mode === "queue-one") {
1200
+ if (active.size > 0) {
1201
+ queuedAt = scheduledAt;
1202
+ changed();
1203
+ return;
1204
+ }
1205
+ startExecution(scheduledAt);
1206
+ return;
1207
+ }
1208
+ if (active.size >= descriptor.overlap.maxConcurrent) {
1209
+ ticksSkipped += 1;
1210
+ changed();
1211
+ return;
1212
+ }
1213
+ startExecution(scheduledAt);
1214
+ };
1215
+ const arm = () => {
1216
+ if (!accepting || nextRunAt === null)
1217
+ return;
1218
+ const delayMs = Math.max(0, nextRunAt - clock.now());
1219
+ timer = clock.schedule(() => {
1220
+ timer = null;
1221
+ if (!accepting || nextRunAt === null)
1222
+ return;
1223
+ const scheduledAt = nextRunAt;
1224
+ const observedAt = clock.now();
1225
+ const elapsedIntervals = Math.max(1, Math.floor((observedAt - scheduledAt) / descriptor.everyMs) + 1);
1226
+ if (elapsedIntervals > 1) {
1227
+ ticksSkipped += elapsedIntervals - 1;
1228
+ changed();
1229
+ }
1230
+ nextRunAt = scheduledAt + elapsedIntervals * descriptor.everyMs;
1231
+ arm();
1232
+ dispatchTick(scheduledAt);
1233
+ }, delayMs);
1234
+ };
1235
+ const waitForActive = async (context, deadlineAt) => {
1236
+ if (active.size === 0 || context.signal.aborted)
1237
+ return;
1238
+ await new Promise((resolve) => {
1239
+ let settled = false;
1240
+ let deadlineTimer = null;
1241
+ const finish = () => {
1242
+ if (settled)
1243
+ return;
1244
+ settled = true;
1245
+ deadlineTimer?.cancel();
1246
+ context.signal.removeEventListener("abort", finish);
1247
+ resolve();
1248
+ };
1249
+ context.signal.addEventListener("abort", finish, { once: true });
1250
+ if (deadlineAt !== undefined) {
1251
+ deadlineTimer = clock.schedule(finish, Math.max(0, deadlineAt - context.now()));
1252
+ }
1253
+ Promise.allSettled([...active]).then(finish);
1254
+ });
1255
+ };
1256
+ const drain = async (context) => {
1257
+ stopAdmission();
1258
+ await waitForActive(context, context.deadlineAt);
1259
+ };
1260
+ return {
1261
+ id: descriptor.id,
1262
+ ...dependsOn && { dependsOn },
1263
+ ...config.required !== undefined && { required: config.required },
1264
+ get status() {
1265
+ return status();
1266
+ },
1267
+ start() {
1268
+ if (stopped)
1269
+ throw new Error(`[stitchkit] schedule "${descriptor.id}" is stopped`);
1270
+ },
1271
+ activate(context) {
1272
+ if (activated || stopped)
1273
+ return;
1274
+ activated = true;
1275
+ accepting = true;
1276
+ activationContext = context;
1277
+ nextRunAt = clock.now() + descriptor.startAfterMs;
1278
+ context.reportHealth("healthy");
1279
+ changed();
1280
+ arm();
1281
+ },
1282
+ stopAdmission() {
1283
+ stopAdmission();
1284
+ },
1285
+ drain,
1286
+ close() {
1287
+ stopAdmission();
1288
+ },
1289
+ async force(context) {
1290
+ stopAdmission();
1291
+ await waitForActive(context, context.forceDeadlineAt);
1292
+ if (active.size > 0) {
1293
+ throw new Error(`[stitchkit] schedule "${descriptor.id}" still has active executions`);
1294
+ }
1295
+ }
1296
+ };
1297
+ }
1298
+ // src/application/server-resource.ts
1299
+ function managedServerResource(config) {
1300
+ let shutdownPromise;
1301
+ const getServer = () => typeof config.server === "function" ? config.server() : config.server;
1302
+ const ensureShutdown = (context, phase = "graceful") => {
1303
+ if (shutdownPromise)
1304
+ return shutdownPromise;
1305
+ const now = context.now();
1306
+ const gracePeriodMs = phase === "force" ? 0 : Math.max(0, (context.deadlineAt ?? now) - now);
1307
+ const forceTimeoutMs = phase === "force" ? Math.max(0, (context.forceDeadlineAt ?? now) - now) : Math.max(0, (context.forceDeadlineAt ?? context.deadlineAt ?? now) - (context.deadlineAt ?? now));
1308
+ shutdownPromise = getServer().shutdown({
1309
+ gracePeriodMs,
1310
+ forceTimeoutMs,
1311
+ retryAfterSeconds: config.retryAfterSeconds ?? 5,
1312
+ signal: context.signal
1313
+ });
1314
+ shutdownPromise.catch(() => {
1315
+ return;
1316
+ });
1317
+ return shutdownPromise;
1318
+ };
1319
+ return defineManagedResource({
1320
+ id: config.id,
1321
+ ...config.dependsOn && { dependsOn: config.dependsOn },
1322
+ ...config.required !== undefined && { required: config.required },
1323
+ start() {},
1324
+ stopAdmission(context) {
1325
+ ensureShutdown(context);
1326
+ },
1327
+ async drain() {
1328
+ await shutdownPromise;
1329
+ },
1330
+ async close(context) {
1331
+ await ensureShutdown(context);
1332
+ },
1333
+ async force(context) {
1334
+ await ensureShutdown(context, "force");
1335
+ }
1336
+ });
1337
+ }
1338
+ export {
1339
+ ActivityIdSchema,
1340
+ ActivityLiveStateSchema,
1341
+ ActivitySnapshotSchema,
1342
+ ActivityStageIdSchema,
1343
+ ActivityStageSnapshotSchema,
1344
+ ApplicationAdmissionError,
1345
+ ApplicationAdmissionSnapshotSchema,
1346
+ ApplicationHealthHandlerOptionsSchema,
1347
+ ApplicationHealthSchema,
1348
+ ApplicationIdSchema,
1349
+ ApplicationLifecycleEventSchema,
1350
+ ApplicationLifecycleSchema,
1351
+ ApplicationResourceShutdownSchema,
1352
+ ApplicationShutdownResultSchema,
1353
+ ApplicationSnapshotSchema,
1354
+ ApplicationSnapshotSinkStatusSchema,
1355
+ ManagedResourceSnapshotSchema,
1356
+ ManagedResourceStateSchema,
1357
+ ManagedScheduleDescriptorSchema,
1358
+ ManagedScheduleErrorPolicySchema,
1359
+ ManagedScheduleOverlapSchema,
1360
+ ManagedScheduleStatusSchema,
1361
+ applicationLifecycleEvent,
1362
+ createActivityProjection,
1363
+ createApplication,
1364
+ createApplicationEventSink,
1365
+ createApplicationHealthHandler,
1366
+ createApplicationSnapshotSink,
1367
+ createManagedSchedule,
1368
+ defineManagedResource,
1369
+ managedServerResource
1370
+ };