@swirls/looms 0.14.0 → 0.16.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.
@@ -1,11 +1,27 @@
1
- import { Data, Effect, Fiber, Option, Predicate, Schema } from 'effect';
1
+ import { Data, DateTime, Effect, Fiber, Option, Predicate, Schema } from 'effect';
2
2
  import { absoluteHttpBase } from '@swirls/looms/client';
3
- import { decodeLoomsEvent, readSubscriptionData, stringifyJson, } from '@swirls/looms/core';
3
+ import { createEvent, createEventId, decodeLoomsEvent, readSubscriptionData, stringifyJson, } from '@swirls/looms/core';
4
4
  import { EventIndex, ProjectionCache } from './derived.js';
5
5
  import { materializeEvents } from './materialize.js';
6
6
  import { createNotifyScheduler } from './notify.js';
7
7
  import { consumeSseStreamEffect } from './sse.js';
8
8
  import { emptyTables } from './tables.js';
9
+ /**
10
+ * Sequence numbers at or above this belong to events the store is showing before the host has
11
+ * confirmed them. They sort after every confirmed event.
12
+ */
13
+ const PENDING_SEQ_BASE = 2 ** 52;
14
+ /** How long a commit the host accepted may stay unconfirmed before the store stops showing it. */
15
+ const PENDING_SETTLE_MS = 10_000;
16
+ /** True for an event shown optimistically that the host has not confirmed yet. */
17
+ export function isPendingEvent(event) {
18
+ return event.seq >= PENDING_SEQ_BASE;
19
+ }
20
+ /** How long a filtered subscription's opening replay must be quiet to count as caught up. */
21
+ const SYNC_QUIET_MS = 250;
22
+ function nowMs() {
23
+ return DateTime.toEpochMillis(DateTime.nowUnsafe());
24
+ }
9
25
  class LoomsStoreError extends Data.TaggedError('LoomsStoreError') {
10
26
  constructor(message, cause) {
11
27
  super({ cause, message });
@@ -44,12 +60,34 @@ export function createLoomsStore(options) {
44
60
  const seenIds = new Set();
45
61
  const projectionCache = new ProjectionCache();
46
62
  const eventIndex = new EventIndex();
63
+ const createdAt = nowMs();
64
+ const observe = (observation) => {
65
+ try {
66
+ options.observer?.observe(observation);
67
+ }
68
+ catch {
69
+ // An observer must never break the store it watches.
70
+ }
71
+ };
72
+ // The cache holds a whole view of the run, so a store that starts partway through has none.
73
+ const cache = options.fromSeq === undefined || options.fromSeq <= 1 ? options.cache : undefined;
74
+ const cacheKey = [endpoint, options.storeId, options.threadId ?? ''].join('|');
75
+ let cacheWrites = Promise.resolve();
76
+ let cachedEvents = 0;
77
+ let hydrated = cache === undefined;
78
+ let hydrating;
47
79
  let eventsSnapshot = Object.freeze([]);
48
80
  let eventsSnapshotDirty = false;
49
81
  let version = 0;
50
82
  let status = 'connecting';
51
83
  let tables = emptyTables();
52
- let fromSeq = 1;
84
+ let fromSeq = Math.max(1, Math.trunc(options.fromSeq ?? 1));
85
+ // A filtered subscription may never be sent the event at the tail, so it also counts as caught
86
+ // up once the opening replay goes quiet.
87
+ const filtered = options.threadId !== undefined || options.includeEphemeral === false;
88
+ let synced = false;
89
+ let syncTail;
90
+ let quietFiber;
53
91
  let disposed = false;
54
92
  let live = false;
55
93
  let liveStarted = false;
@@ -58,7 +96,13 @@ export function createLoomsStore(options) {
58
96
  let socket;
59
97
  let reconnectFiber;
60
98
  let syncing = null;
61
- const publishedEvents = () => {
99
+ const pendingCommits = [];
100
+ let pendingEvents = Object.freeze([]);
101
+ let pendingVersion = 0;
102
+ let pendingSeq = PENDING_SEQ_BASE;
103
+ let visible;
104
+ const visibleByThread = new Map();
105
+ const confirmedEvents = () => {
62
106
  if (!eventsSnapshotDirty) {
63
107
  return eventsSnapshot;
64
108
  }
@@ -66,6 +110,52 @@ export function createLoomsStore(options) {
66
110
  eventsSnapshotDirty = false;
67
111
  return eventsSnapshot;
68
112
  };
113
+ /** `base` with the pending events after it. Stable while neither has changed. */
114
+ const withPending = (base, cached, threadId) => {
115
+ if (cached && cached.base === base && cached.pending === pendingVersion) {
116
+ return cached;
117
+ }
118
+ const extra = threadId
119
+ ? pendingEvents.filter((event) => event.threadId === threadId)
120
+ : pendingEvents;
121
+ return {
122
+ base,
123
+ pending: pendingVersion,
124
+ value: extra.length === 0 ? base : Object.freeze([...base, ...extra]),
125
+ };
126
+ };
127
+ /** What readers see: every confirmed event, then the ones still waiting to be confirmed. */
128
+ const publishedEvents = () => {
129
+ visible = withPending(confirmedEvents(), visible);
130
+ return visible.value;
131
+ };
132
+ const setPending = () => {
133
+ pendingEvents = Object.freeze(pendingCommits.flatMap((commit) => commit.events));
134
+ pendingVersion += 1;
135
+ version += 1;
136
+ };
137
+ const dropPending = (commit, confirmed = false) => {
138
+ const index = pendingCommits.indexOf(commit);
139
+ if (index === -1) {
140
+ return false;
141
+ }
142
+ if (confirmed) {
143
+ const at = nowMs();
144
+ observe({
145
+ type: 'commit.confirmed',
146
+ runId: options.storeId,
147
+ at,
148
+ durationMs: at - commit.startedAt,
149
+ });
150
+ }
151
+ pendingCommits.splice(index, 1);
152
+ if (commit.settle !== undefined) {
153
+ Effect.runFork(Fiber.interrupt(commit.settle));
154
+ commit.settle = undefined;
155
+ }
156
+ setPending();
157
+ return true;
158
+ };
69
159
  const notify = createNotifyScheduler(coalesce, () => {
70
160
  publishedEvents();
71
161
  for (const listener of listeners) {
@@ -77,10 +167,49 @@ export function createLoomsStore(options) {
77
167
  return;
78
168
  }
79
169
  status = next;
170
+ observe({ type: 'store.connection', runId: options.storeId, at: nowMs(), status: next });
171
+ version += 1;
172
+ notify.schedule();
173
+ };
174
+ const cancelQuiet = () => {
175
+ if (quietFiber !== undefined) {
176
+ Effect.runFork(Fiber.interrupt(quietFiber));
177
+ quietFiber = undefined;
178
+ }
179
+ };
180
+ const markSynced = () => {
181
+ cancelQuiet();
182
+ if (synced) {
183
+ return;
184
+ }
185
+ synced = true;
186
+ const at = nowMs();
187
+ observe({
188
+ type: 'store.synced',
189
+ runId: options.storeId,
190
+ at,
191
+ durationMs: at - createdAt,
192
+ eventCount: events.length,
193
+ cachedEvents,
194
+ });
80
195
  version += 1;
81
196
  notify.schedule();
82
197
  };
83
- const applyBatch = (batch) => {
198
+ /** Called when the subscription reports its bounds and after each batch that follows. */
199
+ const checkSynced = () => {
200
+ if (synced || syncTail === undefined) {
201
+ return;
202
+ }
203
+ if (fromSeq > syncTail) {
204
+ markSynced();
205
+ return;
206
+ }
207
+ if (filtered) {
208
+ cancelQuiet();
209
+ quietFiber = Effect.runFork(Effect.sleep(SYNC_QUIET_MS).pipe(Effect.andThen(Effect.sync(markSynced))));
210
+ }
211
+ };
212
+ const applyBatch = (batch, fromCache = false) => {
84
213
  const fresh = [];
85
214
  for (const event of batch) {
86
215
  if (event.seq < fromSeq || seenIds.has(event.id)) {
@@ -91,6 +220,7 @@ export function createLoomsStore(options) {
91
220
  fromSeq = Math.max(fromSeq, event.seq + 1);
92
221
  }
93
222
  if (fresh.length === 0) {
223
+ checkSynced();
94
224
  return;
95
225
  }
96
226
  tables = materializeEvents(fresh, tables);
@@ -100,6 +230,39 @@ export function createLoomsStore(options) {
100
230
  eventsSnapshotDirty = true;
101
231
  eventIndex.append(fresh);
102
232
  version += 1;
233
+ // The host's copy of an optimistic commit takes the place of the provisional one.
234
+ for (const event of fresh) {
235
+ const confirmed = event.idempotencyKey
236
+ ? pendingCommits.find((commit) => commit.key === event.idempotencyKey)
237
+ : undefined;
238
+ if (confirmed) {
239
+ dropPending(confirmed, true);
240
+ }
241
+ }
242
+ if (cache && !fromCache) {
243
+ const durable = fresh.filter((event) => !event.ephemeral);
244
+ if (durable.length > 0) {
245
+ cacheWrites = cacheWrites.then(() => cache.append(cacheKey, durable)).catch(() => undefined);
246
+ }
247
+ }
248
+ notify.schedule();
249
+ checkSynced();
250
+ };
251
+ /** Drops everything the store holds, when what the cache supplied is not the host's log. */
252
+ const forgetCache = () => {
253
+ events.length = 0;
254
+ seenIds.clear();
255
+ eventIndex.clear();
256
+ projectionCache.clear();
257
+ tables = emptyTables();
258
+ eventsSnapshotDirty = true;
259
+ cachedEvents = 0;
260
+ synced = false;
261
+ syncTail = undefined;
262
+ version += 1;
263
+ if (cache) {
264
+ cacheWrites = cacheWrites.then(() => cache.clear(cacheKey)).catch(() => undefined);
265
+ }
103
266
  notify.schedule();
104
267
  };
105
268
  const applyLiveData = (data) => {
@@ -112,6 +275,15 @@ export function createLoomsStore(options) {
112
275
  fromSeq = read.head;
113
276
  return 'resync';
114
277
  case 'hello':
278
+ // The cache is ahead of the host's log, so it was kept from a different one.
279
+ if (cachedEvents > 0 && read.tail < fromSeq - 1) {
280
+ forgetCache();
281
+ fromSeq = 1;
282
+ return 'resync';
283
+ }
284
+ syncTail = read.tail;
285
+ checkSynced();
286
+ return 'continue';
115
287
  case 'ignore':
116
288
  return 'continue';
117
289
  default: {
@@ -345,12 +517,39 @@ export function createLoomsStore(options) {
345
517
  liveAbort?.abort();
346
518
  liveAbort = undefined;
347
519
  };
520
+ /** Starts following the run, after first loading whatever the device kept of it. */
521
+ const begin = () => {
522
+ if (hydrated || !cache) {
523
+ startLive();
524
+ return;
525
+ }
526
+ hydrating ??= cache
527
+ .load(cacheKey)
528
+ .then((kept) => {
529
+ if (disposed || events.length > 0) {
530
+ return;
531
+ }
532
+ applyBatch(kept.slice(), true);
533
+ cachedEvents = events.length;
534
+ })
535
+ .catch(() => undefined)
536
+ .then(() => {
537
+ hydrated = true;
538
+ hydrating = undefined;
539
+ if (!disposed) {
540
+ startLive();
541
+ }
542
+ });
543
+ };
348
544
  if (options.storeId) {
349
- startLive();
545
+ begin();
350
546
  }
351
547
  const readEvents = (filterOptions) => {
352
- if (filterOptions?.threadId) {
353
- return eventIndex.getByThread(filterOptions.threadId);
548
+ const threadId = filterOptions?.threadId;
549
+ if (threadId) {
550
+ const slice = withPending(eventIndex.getByThread(threadId), visibleByThread.get(threadId), threadId);
551
+ visibleByThread.set(threadId, slice);
552
+ return slice.value;
354
553
  }
355
554
  return publishedEvents();
356
555
  };
@@ -358,6 +557,7 @@ export function createLoomsStore(options) {
358
557
  storeId: options.storeId,
359
558
  version: () => version,
360
559
  status: () => status,
560
+ synced: () => synced,
361
561
  /**
362
562
  * Live mutable materialized tables. Re-read after each version bump;
363
563
  * do not hold Map/array references across notifies.
@@ -372,46 +572,133 @@ export function createLoomsStore(options) {
372
572
  bySeq: (seq) => eventIndex.getBySeq(seq),
373
573
  startedAt: () => eventIndex.getStartedAt(),
374
574
  latest: (type) => eventIndex.getLatest(type),
375
- fold: (def) => projectionCache.fold(def, publishedEvents()),
575
+ fold: (def) => projectionCache.fold(def, confirmedEvents(), pendingEvents, pendingVersion),
376
576
  },
377
577
  subscribe: (listener) => {
378
578
  listeners.add(listener);
379
579
  listener();
380
580
  if (disposed) {
381
- startLive();
581
+ begin();
382
582
  }
383
583
  return () => {
384
584
  listeners.delete(listener);
385
585
  };
386
586
  },
387
- project: (definition) => projectionCache.project(definition, publishedEvents()),
388
- fold: (definition) => projectionCache.fold(definition, publishedEvents()),
587
+ project: (definition) => projectionCache.project(definition, confirmedEvents(), pendingEvents, pendingVersion),
588
+ fold: (definition) => projectionCache.fold(definition, confirmedEvents(), pendingEvents, pendingVersion),
589
+ pending: () => pendingEvents,
389
590
  flush: notify.flush,
390
591
  sync: () => sync().then(() => {
391
592
  notify.flush();
392
593
  }),
393
- commit: (event) => Effect.runPromise(Effect.gen(function* () {
394
- const res = yield* Effect.tryPromise({
395
- try: (signal) => fetchFn(`${endpoint}/runs/${encodeURIComponent(options.storeId)}/events`, {
594
+ commit: (event, commitOptions) => {
595
+ const inputs = Array.isArray(event) ? event : [event];
596
+ const optimistic = commitOptions?.optimistic ?? options.optimistic ?? false;
597
+ const key = commitOptions?.idempotencyKey ?? (optimistic ? createEventId() : undefined);
598
+ const startedAt = nowMs();
599
+ let shown;
600
+ if (optimistic && key !== undefined && inputs.length > 0) {
601
+ const rootThreadId = tables.runs.get(options.storeId)?.rootThreadId ?? null;
602
+ shown = {
603
+ key,
604
+ startedAt,
605
+ settle: undefined,
606
+ events: inputs.map((input) => {
607
+ pendingSeq += 1;
608
+ return createEvent(options.storeId, {
609
+ ...input,
610
+ threadId: input.threadId === undefined ? rootThreadId : input.threadId,
611
+ origin: input.origin ?? { type: 'external' },
612
+ idempotencyKey: input.idempotencyKey ?? key,
613
+ }, { seq: pendingSeq });
614
+ }),
615
+ };
616
+ pendingCommits.push(shown);
617
+ setPending();
618
+ notify.schedule();
619
+ notify.flush();
620
+ }
621
+ const post = (signal) => {
622
+ if (commitOptions?.send) {
623
+ return commitOptions.send({ events: inputs, idempotencyKey: key, signal });
624
+ }
625
+ const body = key === undefined
626
+ ? Array.isArray(event)
627
+ ? { events: inputs }
628
+ : event
629
+ : { events: inputs, idempotencyKey: key };
630
+ // The log is what the UI renders, so the answer is wanted as soon as the events are
631
+ // committed, not once the run has finished acting on them.
632
+ return fetchFn(`${endpoint}/runs/${encodeURIComponent(options.storeId)}/events?respond=async`, {
396
633
  method: 'POST',
397
634
  headers: { 'content-type': 'application/json' },
398
- body: stringifyJson(Array.isArray(event) ? { events: event } : event),
635
+ body: stringifyJson(body),
399
636
  signal,
400
- }),
401
- catch: (cause) => new LoomsStoreError('Run signal failed', cause),
637
+ }).then((res) => res.ok
638
+ ? undefined
639
+ : res.text().then((text) => {
640
+ throw new LoomsStoreError(`Run signal failed: ${res.status} ${text}`);
641
+ }));
642
+ };
643
+ return Effect.runPromise(Effect.gen(function* () {
644
+ yield* Effect.tryPromise({
645
+ try: post,
646
+ catch: (cause) => cause instanceof LoomsStoreError
647
+ ? cause
648
+ : new LoomsStoreError('Run signal failed', cause),
649
+ });
650
+ if (!live) {
651
+ yield* Effect.promise(sync);
652
+ }
653
+ return undefined;
654
+ }).pipe(Effect.tapError((error) => Effect.sync(() => {
655
+ const at = nowMs();
656
+ observe({
657
+ type: 'commit.failed',
658
+ runId: options.storeId,
659
+ at,
660
+ durationMs: at - startedAt,
661
+ message: error.message,
662
+ });
663
+ // Roll back: the events were never recorded.
664
+ if (shown && dropPending(shown)) {
665
+ notify.schedule();
666
+ notify.flush();
667
+ }
668
+ })))).then(() => {
669
+ const at = nowMs();
670
+ observe({
671
+ type: 'commit.acked',
672
+ runId: options.storeId,
673
+ at,
674
+ durationMs: at - startedAt,
675
+ eventCount: inputs.length,
676
+ optimistic: shown !== undefined,
677
+ });
678
+ const accepted = shown;
679
+ if (accepted && pendingCommits.includes(accepted)) {
680
+ // The host took the commit, so its events are on their way. If none ever carries this
681
+ // key (the host recorded something else, or nothing), stop showing ours.
682
+ accepted.settle = Effect.runFork(Effect.sleep(PENDING_SETTLE_MS).pipe(Effect.andThen(Effect.promise(sync)), Effect.andThen(Effect.sync(() => {
683
+ accepted.settle = undefined;
684
+ if (dropPending(accepted)) {
685
+ notify.schedule();
686
+ }
687
+ }))));
688
+ }
689
+ notify.flush();
402
690
  });
403
- if (!res.ok) {
404
- const text = yield* Effect.promise(() => res.text());
405
- return yield* new LoomsStoreError(`Run signal failed: ${res.status} ${text}`);
406
- }
407
- if (!live) {
408
- yield* Effect.promise(sync);
409
- }
410
- notify.flush();
411
- return undefined;
412
- })),
691
+ },
413
692
  dispose: () => {
414
693
  disposed = true;
694
+ cancelQuiet();
695
+ for (const commit of pendingCommits.splice(0)) {
696
+ if (commit.settle !== undefined) {
697
+ Effect.runFork(Fiber.interrupt(commit.settle));
698
+ }
699
+ }
700
+ pendingEvents = Object.freeze([]);
701
+ visibleByThread.clear();
415
702
  notify.cancel();
416
703
  stopLive();
417
704
  listeners.clear();
@@ -1,4 +1,4 @@
1
- export { createRuntime, createTimeoutScheduler, DuplicateEffectDispatchError, ForkConflictError, MaxWakeIterationsError, RunNotFinishedError, RunNotFoundError, RunOverloadedError, RunTerminalError, StartRunConflictError, type CreateRuntimeOptions, type EffectWorker, type EffectWorkerDeadlines, type EffectWorkerTask, type LoomsRuntime, type RunOperationalStatus, type RegisteredDefinition, type StartRunArgs, type WakeError, type WakeScheduler, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, } from './runtime';
1
+ export { createRuntime, createTimeoutScheduler, DuplicateEffectDispatchError, ForkConflictError, MaxWakeIterationsError, RunNotFinishedError, RunNotFoundError, RunOverloadedError, RunTerminalError, StartRunConflictError, type CreateRuntimeOptions, type EffectWorker, type EffectWorkerDeadlines, type EffectWorkerTask, type LoomsRuntime, type RunSignalOptions, type RunOperationalStatus, type RegisteredDefinition, type StartRunArgs, type WakeError, type WakeScheduler, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, } from './runtime';
2
2
  export { listEffectPlacements } from './worker-effect-dispatch';
3
3
  export { createLooms, type Looms, type CreateLoomsOptions, type StartResult } from './looms';
4
4
  export { loadSubscriptionOpening, readSubscriptionBounds } from './subscription';
@@ -1,6 +1,6 @@
1
1
  import { type AnyRuntimeModule, type DebuggerHost, type DefinitionInput, type DefinitionRef, type DefinitionResolver, type EventEnvelope, type EventInput, type BlobStore, type EventStore, type EventStoreTrimCoverage, type JsonValue, type SnapshotStore, type ProjectionDefinition, type HasRequiredAttributes, type ReplayStep, type RunAttributeFields, type RunAttributesOption, type RunLauncher, type RunState } from '@swirls/looms/core';
2
2
  import type { RuntimeObserver } from './observer';
3
- import { type EffectWorker, type LoomsRuntime, type RunOperationalStatus, type StartRunArgs, type WakeScheduler, type WorkerCallbackInput, type WorkerCallbackResult } from './runtime';
3
+ import { type EffectWorker, type LoomsRuntime, type RunSignalOptions, type RunOperationalStatus, type StartRunArgs, type WakeScheduler, type WorkerCallbackInput, type WorkerCallbackResult } from './runtime';
4
4
  import { type Authorize, type RunningServer } from './server';
5
5
  export interface CreateLoomsOptions<Fields extends RunAttributeFields = RunAttributeFields> {
6
6
  /** Runtime modules to enable. Pass `agent()`, `workflow()`, `approval()`, and/or your own. */
@@ -112,9 +112,7 @@ export interface Looms<Fields extends RunAttributeFields = RunAttributeFields> {
112
112
  fromSeq?: number;
113
113
  limit?: number;
114
114
  }): Promise<EventEnvelope[]>;
115
- signal(runId: string, events: ReadonlyArray<EventInput>, options?: {
116
- idempotencyKey?: string;
117
- }): Promise<RunState>;
115
+ signal(runId: string, events: ReadonlyArray<EventInput>, options?: RunSignalOptions): Promise<RunState>;
118
116
  wake(runId: string): Promise<RunState>;
119
117
  rescanTimers(): Promise<number>;
120
118
  recoverDeadlines(): Promise<number>;
@@ -4,7 +4,7 @@ export type { WakeScheduler } from './wake-scheduler';
4
4
  export { createTimeoutScheduler } from './wake-scheduler';
5
5
  export { DuplicateEffectDispatchError, ForkConflictError, MaxWakeIterationsError, RunNotFinishedError, RunNotFoundError, RunTerminalError, StartRunConflictError, } from './errors';
6
6
  export { RunOverloadedError } from './ingress';
7
- export type { CreateRuntimeOptions, EffectWorker, EffectWorkerDeadlines, EffectWorkerTask, LoomsRuntime, RunOperationalStatus, StartResult, StartRunArgs, WakeError, } from './types';
7
+ export type { CreateRuntimeOptions, EffectWorker, EffectWorkerDeadlines, EffectWorkerTask, LoomsRuntime, RunSignalOptions, RunOperationalStatus, StartResult, StartRunArgs, WakeError, } from './types';
8
8
  export type { WorkerCallback, WorkerCallbackInput, WorkerCallbackResult } from '@swirls/looms/core';
9
9
  import type { CreateRuntimeOptions, LoomsRuntime } from './types';
10
10
  export declare function createRuntime<const TModules extends readonly AnyRuntimeModule[]>(options: CreateRuntimeOptions<TModules>): LoomsRuntime<TModules>;
@@ -279,10 +279,16 @@ export function createRuntime(options) {
279
279
  launcher: () => launcher,
280
280
  });
281
281
  const appendAndWake = (runId, events, signalOpts) => withRunIngress(runId, signalAdmitted(runId, events, signalOpts)).pipe(Effect.flatMap((state) => {
282
- if (signalOpts?.coalesce && executionContexts.get(runId).waking) {
282
+ const waking = executionContexts.get(runId).waking;
283
+ const scheduled = signalOpts?.wake === 'schedule';
284
+ if ((signalOpts?.coalesce || scheduled) && waking) {
283
285
  requestWakeAgain(executionContexts.get(runId));
284
286
  return Effect.succeed(state);
285
287
  }
288
+ if (scheduled) {
289
+ // The caller is answered now. The scheduler owns the wake, so it survives the request.
290
+ return Clock.currentTimeMillis.pipe(Effect.flatMap((now) => scheduler.schedule(runId, now)), Effect.as(state));
291
+ }
286
292
  return runtime.wake(runId);
287
293
  }));
288
294
  runtime = {
@@ -32,6 +32,12 @@ export declare const readJson: (req: Request) => Effect.Effect<JsonValue, Reques
32
32
  /** `readJson` for routes whose body is optional: a request without one reads as `{}`. */
33
33
  export declare const readOptionalJson: (req: Request) => Effect.Effect<JsonValue, RequestBodyError>;
34
34
  export declare function extractIdempotencyKey(req: Request, bodyKey?: string): string | undefined;
35
+ /**
36
+ * Whether the caller wants an answer once the write is committed, not once it has run. Asked with
37
+ * `Prefer: respond-async` (RFC 7240), or with `?respond=async` where a custom header would need
38
+ * a cross-origin allowance.
39
+ */
40
+ export declare function prefersAsyncResponse(req: Request): boolean;
35
41
  export declare function acceptsEventStream(req: Request): boolean;
36
42
  export declare function readIntegerQuery(url: URL, name: string, options: {
37
43
  minimum: number;
@@ -35,6 +35,19 @@ export function extractIdempotencyKey(req, bodyKey) {
35
35
  req.headers.get('x-idempotency-key') ??
36
36
  undefined);
37
37
  }
38
+ /**
39
+ * Whether the caller wants an answer once the write is committed, not once it has run. Asked with
40
+ * `Prefer: respond-async` (RFC 7240), or with `?respond=async` where a custom header would need
41
+ * a cross-origin allowance.
42
+ */
43
+ export function prefersAsyncResponse(req) {
44
+ if (new URL(req.url).searchParams.get('respond') === 'async') {
45
+ return true;
46
+ }
47
+ return (req.headers.get('prefer') ?? '')
48
+ .split(',')
49
+ .some((value) => value.split(';', 1)[0]?.trim().toLowerCase() === 'respond-async');
50
+ }
38
51
  export function acceptsEventStream(req) {
39
52
  return (req.headers.get('accept') ?? '')
40
53
  .split(',')
@@ -1,7 +1,7 @@
1
1
  import { Effect, Schema } from 'effect';
2
2
  import { createRunId, EventStoreTag, findSignal, JsonValueSchema, RunAttributesSchema, readTraceHeaders, runSignal, SecretContextSchema, stringifyJson, subscriptionFilter, subscriptionFromSeq, } from '@swirls/looms/core';
3
3
  import { createEventStreamResponse } from '../../sse.js';
4
- import { acceptsEventStream, EventInputBodySchema, extractIdempotencyKey, provideStore, readIntegerQuery, readJson, readOptionalJson, RequestQueryError, } from '../http.js';
4
+ import { acceptsEventStream, EventInputBodySchema, extractIdempotencyKey, prefersAsyncResponse, provideStore, readIntegerQuery, readJson, readOptionalJson, RequestQueryError, } from '../http.js';
5
5
  import { route } from '../route-table.js';
6
6
  const StartRunBodySchema = Schema.Struct({
7
7
  kind: Schema.optional(Schema.String),
@@ -14,6 +14,15 @@ const StartRunBodySchema = Schema.Struct({
14
14
  attributes: Schema.optional(RunAttributesSchema),
15
15
  secrets: Schema.optional(SecretContextSchema),
16
16
  });
17
+ /**
18
+ * A signal that asks for an async response is answered `202` once its events are committed. The
19
+ * state is the one they were committed against; the run's progress arrives on the event stream.
20
+ */
21
+ function signalResponse(runId, state, deferred) {
22
+ return deferred
23
+ ? Response.json({ runId, state }, { status: 202, headers: { 'preference-applied': 'respond-async' } })
24
+ : Response.json({ runId, state });
25
+ }
17
26
  const SignalBodySchema = Schema.Struct({
18
27
  events: Schema.optional(Schema.Array(EventInputBodySchema)),
19
28
  type: Schema.optional(Schema.String),
@@ -224,8 +233,12 @@ export function runRoutes({ runtime, store }) {
224
233
  ? [{ type: body.type, payload: body.payload ?? null, threadId: body.threadId }]
225
234
  : []);
226
235
  const idempotencyKey = extractIdempotencyKey(req, body.idempotencyKey);
227
- const state = yield* provideStore(runtime.signal(params.runId, sentBy(events, actorId), { idempotencyKey }), store);
228
- return Response.json({ runId: params.runId, state });
236
+ const deferred = prefersAsyncResponse(req);
237
+ const state = yield* provideStore(runtime.signal(params.runId, sentBy(events, actorId), {
238
+ idempotencyKey,
239
+ wake: deferred ? 'schedule' : 'await',
240
+ }), store);
241
+ return signalResponse(params.runId, state, deferred);
229
242
  }),
230
243
  }),
231
244
  route({
@@ -243,8 +256,12 @@ export function runRoutes({ runtime, store }) {
243
256
  const body = yield* readJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(NamedSignalBodySchema)));
244
257
  const events = yield* runSignal(definition, body.input ?? null, body.threadId);
245
258
  const idempotencyKey = extractIdempotencyKey(req, body.idempotencyKey);
246
- const state = yield* provideStore(runtime.signal(params.runId, sentBy(events, actorId), { idempotencyKey }), store);
247
- return Response.json({ runId: params.runId, state });
259
+ const deferred = prefersAsyncResponse(req);
260
+ const state = yield* provideStore(runtime.signal(params.runId, sentBy(events, actorId), {
261
+ idempotencyKey,
262
+ wake: deferred ? 'schedule' : 'await',
263
+ }), store);
264
+ return signalResponse(params.runId, state, deferred);
248
265
  }),
249
266
  }),
250
267
  route({
@@ -166,6 +166,19 @@ export interface RunOperationalStatus {
166
166
  readonly lastError: string | null;
167
167
  }>;
168
168
  }
169
+ /** How a signal's caller learns the run moved on. */
170
+ export interface RunSignalOptions {
171
+ idempotencyKey?: string;
172
+ /** When the run is already waking, ask that wake to continue and return without joining it. */
173
+ coalesce?: boolean;
174
+ /**
175
+ * `await` (the default) resolves once the run parks, so the returned state includes whatever the
176
+ * signal set in motion. `schedule` resolves as soon as the events are committed and leaves the
177
+ * wake to the scheduler, as `launchRun` does. The returned state is the one the events were
178
+ * committed against.
179
+ */
180
+ wake?: 'await' | 'schedule';
181
+ }
169
182
  export interface LoomsRuntime<TModules extends readonly AnyRuntimeModule[] = readonly AnyRuntimeModule[]> {
170
183
  readonly modules: TModules;
171
184
  readonly registry: ComposedRegistry;
@@ -180,18 +193,12 @@ export interface LoomsRuntime<TModules extends readonly AnyRuntimeModule[] = rea
180
193
  * the same identity is a no-op aside from the scheduled wake.
181
194
  */
182
195
  launchRun(args: StartRunArgs): Effect.Effect<StartResult, Error | EventStoreAppendError | EventStoreError, EventStoreTag>;
183
- signal(runId: string, events: ReadonlyArray<EventInput>, options?: {
184
- idempotencyKey?: string;
185
- coalesce?: boolean;
186
- }): Effect.Effect<RunState, Error | EventStoreAppendError | EventStoreError, EventStoreTag>;
196
+ signal(runId: string, events: ReadonlyArray<EventInput>, options?: RunSignalOptions): Effect.Effect<RunState, Error | EventStoreAppendError | EventStoreError, EventStoreTag>;
187
197
  /**
188
198
  * Append events the runtime itself produced for another run. Unlike `signal`, this does not
189
199
  * reject reserved runtime event types or rewrite their origin.
190
200
  */
191
- accept(runId: string, events: ReadonlyArray<EventInput>, options?: {
192
- idempotencyKey?: string;
193
- coalesce?: boolean;
194
- }): Effect.Effect<RunState, Error | EventStoreAppendError | EventStoreError, EventStoreTag>;
201
+ accept(runId: string, events: ReadonlyArray<EventInput>, options?: RunSignalOptions): Effect.Effect<RunState, Error | EventStoreAppendError | EventStoreError, EventStoreTag>;
195
202
  wake(runId: string): Effect.Effect<RunState, WakeError, EventStoreTag>;
196
203
  getRun(runId: string): Effect.Effect<RunState, EventStoreTruncationError | EventStoreTrimmedError | EventStoreError | DefinitionResolveError, EventStoreTag>;
197
204
  getEvents(runId: string, options?: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swirls/looms",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "Pluggable event-sourced runtime for durable agents and workflows",
5
5
  "homepage": "https://github.com/ByteSliceHQ/looms#readme",
6
6
  "bugs": {