@swirls/looms 0.14.0 → 0.15.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.
@@ -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.15.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": {