@swirls/looms 0.12.4 → 0.13.1

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.
@@ -14,6 +14,11 @@ export interface LoomsDurableObjectConfig {
14
14
  readonly blobs?: BlobStore;
15
15
  readonly snapshotEvery?: number;
16
16
  readonly maxWakeIterations?: number;
17
+ /**
18
+ * How far ahead the alarm is kept while in-process effects run, in milliseconds. If the isolate
19
+ * is lost mid-effect the run wakes and re-attempts within about this long. Default 30000.
20
+ */
21
+ readonly livenessLeaseMs?: number;
17
22
  readonly maxPendingRunOperations?: number;
18
23
  readonly trimAfterSnapshot?: {
19
24
  readonly keepSnapshots: number;
@@ -41,6 +46,7 @@ export interface LoomsDurableObjectConfig {
41
46
  export declare abstract class LoomsDurableObject<Env = unknown> extends DurableObject<Env> {
42
47
  private cellPromise?;
43
48
  private store?;
49
+ private alarms?;
44
50
  private authorize;
45
51
  abstract configure(env: Env): LoomsDurableObjectConfig | Promise<LoomsDurableObjectConfig>;
46
52
  private getCell;
@@ -15,6 +15,7 @@ import { attachSocketFanout, isRunSocketUpgrade, openRunSocket } from './websock
15
15
  export class LoomsDurableObject extends DurableObject {
16
16
  cellPromise;
17
17
  store;
18
+ alarms;
18
19
  authorize = defaultAuthorize;
19
20
  getCell() {
20
21
  if (this.cellPromise) {
@@ -44,6 +45,7 @@ export class LoomsDurableObject extends DurableObject {
44
45
  blobs: config.blobs,
45
46
  });
46
47
  this.store = store;
48
+ this.alarms = alarms;
47
49
  this.authorize = config.authorize ?? defaultAuthorize;
48
50
  const cell = createActorCell({
49
51
  runId,
@@ -54,6 +56,7 @@ export class LoomsDurableObject extends DurableObject {
54
56
  attributes: config.attributes,
55
57
  snapshotEvery: config.snapshotEvery,
56
58
  maxWakeIterations: config.maxWakeIterations,
59
+ livenessLeaseMs: config.livenessLeaseMs,
57
60
  maxPendingRunOperations: config.maxPendingRunOperations,
58
61
  trimAfterSnapshot: config.trimAfterSnapshot,
59
62
  authorize: config.authorize,
@@ -142,6 +145,7 @@ export class LoomsDurableObject extends DurableObject {
142
145
  return cell.getRun().then((state) => deleteTerminalRunStorage(this.ctx.storage, store, runId, state, options).then(() => {
143
146
  this.cellPromise = undefined;
144
147
  this.store = undefined;
148
+ this.alarms = undefined;
145
149
  }));
146
150
  });
147
151
  }
@@ -157,7 +161,9 @@ export class LoomsDurableObject extends DurableObject {
157
161
  if (delivery) {
158
162
  this.ctx.waitUntil(Effect.runPromise(delivery.deliver(runId)));
159
163
  }
160
- return cell.wake();
164
+ // Otherwise a wake still running here would keep rearming for the deadline that just
165
+ // fired, alongside its liveness deadline, and the alarm would fire again at once.
166
+ return Effect.runPromise(this.alarms?.fired ?? Effect.void).then(() => cell.wake());
161
167
  })
162
168
  .then(() => undefined);
163
169
  }
@@ -3,7 +3,7 @@ export { deleteTerminalRunStorage, ProjectorCoverageError, RunNotTerminalError,
3
3
  export { durableObjectEventStore, type DurableObjectEventStore, type DurableObjectStoreOptions, } from './event-store';
4
4
  export { durableObjectLauncher, durableObjectScheduleHost, LoomsDurableObject, type DurableObjectRunStub, type LoomsDurableObjectConfig, } from './durable-object';
5
5
  export { r2BlobStore, type R2BucketLike, type R2ListResult, type R2ObjectBodyLike, type R2StoredObject, } from './r2-blob-store';
6
- export { routeToDurableObject, type DurableObjectNamespaceLike, type DurableObjectStubLike, } from './router';
6
+ export { routeToDurableObject, type DurableObjectNamespaceLike, type DurableObjectStubLike, type RouteAuthorize, } from './router';
7
7
  export { createMemoryQueue, type MemoryQueue, type MemoryQueueOptions } from './memory-queue';
8
8
  export { processQueueMessage, queueConsumer, QueueTaskError, workerHandlers, type QueueBatchLike, type QueueConsumerOptions, type QueueTask, type QueueTaskHandler, type WorkerCallbackClient, } from './queue-consumer';
9
9
  export { readQueueEffectMessage, type QueueEffectMessage, type QueueMessageLike, } from './queue-message';
@@ -1,15 +1,29 @@
1
1
  import type { AnyRuntimeModule } from '@swirls/looms/core';
2
+ import { type AuthDecision, type RouteInfo } from '@swirls/looms/runtime';
2
3
  export interface DurableObjectStubLike {
3
4
  fetch(request: Request): Promise<Response>;
4
5
  }
5
6
  export interface DurableObjectNamespaceLike<T extends DurableObjectStubLike = DurableObjectStubLike> {
6
7
  getByName(name: string): T;
7
8
  }
9
+ /**
10
+ * Decides, in the Worker, whether a request may be forwarded to a run's Durable Object. `route` is
11
+ * what `describeRoute` says about the request: it has no run attributes, because the Worker does
12
+ * not read the run.
13
+ */
14
+ export type RouteAuthorize = (request: Request, route: RouteInfo) => AuthDecision | Promise<AuthDecision>;
8
15
  /**
9
16
  * Routes incoming HTTP requests to the appropriate Durable Object actor cell.
10
17
  * Handles `/health` locally, returns 501 for global run lists and forks, and forwards
11
18
  * all other run and event-stream requests to `namespace.getByName(runId)`.
19
+ *
20
+ * With `authorize`, every request for a Looms route is checked in the Worker first, and a denied
21
+ * one never reaches a Durable Object. When the decision names an actor, the forwarded request
22
+ * carries it in `ACTOR_HEADER`; give the Durable Object `forwardedActorAuth()` as its `authorize`
23
+ * to record the request's events as sent by that actor. A client can never set the header itself:
24
+ * it is removed from every request that comes through here.
12
25
  */
13
26
  export declare function routeToDurableObject(namespace: DurableObjectNamespaceLike, req: Request, options?: {
14
27
  readonly modules?: readonly AnyRuntimeModule[] | (() => readonly AnyRuntimeModule[]);
28
+ readonly authorize?: RouteAuthorize;
15
29
  }): Promise<Response | null>;
@@ -1,14 +1,46 @@
1
1
  import { crossRunResponse, definitionsResponse, resolveRunTarget, RunTargetError, } from '@swirls/looms/actor';
2
+ import { ACTOR_HEADER, authResponse, describeRoute, } from '@swirls/looms/runtime';
3
+ /** `req` with `ACTOR_HEADER` set to `actorId`, or removed when there is none. */
4
+ function withActor(req, actorId) {
5
+ if (actorId === undefined && !req.headers.has(ACTOR_HEADER)) {
6
+ return req;
7
+ }
8
+ const headers = new Headers(req.headers);
9
+ if (actorId === undefined) {
10
+ headers.delete(ACTOR_HEADER);
11
+ }
12
+ else {
13
+ headers.set(ACTOR_HEADER, actorId);
14
+ }
15
+ return new Request(req, { headers });
16
+ }
2
17
  /**
3
18
  * Routes incoming HTTP requests to the appropriate Durable Object actor cell.
4
19
  * Handles `/health` locally, returns 501 for global run lists and forks, and forwards
5
20
  * all other run and event-stream requests to `namespace.getByName(runId)`.
21
+ *
22
+ * With `authorize`, every request for a Looms route is checked in the Worker first, and a denied
23
+ * one never reaches a Durable Object. When the decision names an actor, the forwarded request
24
+ * carries it in `ACTOR_HEADER`; give the Durable Object `forwardedActorAuth()` as its `authorize`
25
+ * to record the request's events as sent by that actor. A client can never set the header itself:
26
+ * it is removed from every request that comes through here.
6
27
  */
7
28
  export function routeToDurableObject(namespace, req, options) {
8
29
  const url = new URL(req.url);
9
30
  if (url.pathname === '/health') {
10
31
  return Promise.resolve(Response.json({ ok: true }));
11
32
  }
33
+ const route = options?.authorize ? describeRoute(req.method, url.pathname) : null;
34
+ if (options?.authorize && route) {
35
+ return Promise.resolve(options.authorize(req, route)).then((decision) => {
36
+ const denied = authResponse(decision);
37
+ return (denied ??
38
+ forward(namespace, withActor(req, decision.allowed ? decision.actorId : undefined), options));
39
+ });
40
+ }
41
+ return forward(namespace, withActor(req, undefined), options);
42
+ }
43
+ function forward(namespace, req, options) {
12
44
  const definitions = definitionsResponse(req, options?.modules);
13
45
  if (definitions) {
14
46
  return Promise.resolve(definitions);
@@ -2,7 +2,7 @@ export { createRuntime, createTimeoutScheduler, DuplicateEffectDispatchError, Fo
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';
5
- export { serveHttp, createFetchHandler, isLoomsApiPath, type FetchHandlerOptions, authAllowed, authDenied, authResponse, bearerAuth, defaultAuthorize, grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, type GrantAuthOptions, type GrantFailure, type RunGrant, runRouteInfo, type AuthDecision, type AuthorizedAccess, type Authorize, type BearerTokens, type RouteAccess, type RouteInfo, type RunningServer, type LoomsFetchResult, } from './server';
5
+ export { serveHttp, createFetchHandler, isLoomsApiPath, describeRoute, type FetchHandlerOptions, ACTOR_HEADER, authAllowed, authAllowedAs, authDenied, authResponse, bearerAuth, defaultAuthorize, forwardedActorAuth, grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, type GrantAuthOptions, type GrantFailure, type RunGrant, runRouteInfo, type AuthDecision, type AuthorizedAccess, type Authorize, type BearerTokens, type RouteAccess, type RouteInfo, type RunningServer, type LoomsFetchResult, } from './server';
6
6
  export { filesystemBlobStore } from './filesystem-blob-store';
7
7
  export { createEventStreamResponse, type EventStreamOptions } from './sse';
8
8
  export { notifyObserver, type RuntimeObservation, type RuntimeObserver } from './observer';
@@ -2,7 +2,7 @@ export { createRuntime, createTimeoutScheduler, DuplicateEffectDispatchError, Fo
2
2
  export { listEffectPlacements } from './worker-effect-dispatch.js';
3
3
  export { createLooms } from './looms.js';
4
4
  export { loadSubscriptionOpening, readSubscriptionBounds } from './subscription.js';
5
- export { serveHttp, createFetchHandler, isLoomsApiPath, authAllowed, authDenied, authResponse, bearerAuth, defaultAuthorize, grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, runRouteInfo, } from './server.js';
5
+ export { serveHttp, createFetchHandler, isLoomsApiPath, describeRoute, ACTOR_HEADER, authAllowed, authAllowedAs, authDenied, authResponse, bearerAuth, defaultAuthorize, forwardedActorAuth, grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, runRouteInfo, } from './server.js';
6
6
  export { filesystemBlobStore } from './filesystem-blob-store.js';
7
7
  export { createEventStreamResponse } from './sse.js';
8
8
  export { notifyObserver } from './observer.js';
@@ -21,6 +21,8 @@ export interface CreateLoomsOptions<Fields extends RunAttributeFields = RunAttri
21
21
  hostname?: string;
22
22
  };
23
23
  readonly maxWakeIterations?: number;
24
+ /** See `CreateRuntimeOptions.livenessLeaseMs`. Only used when `scheduler` implements `keepAlive`. */
25
+ readonly livenessLeaseMs?: number;
24
26
  /** Maximum active and queued mutation operations per run. Default 256. */
25
27
  readonly maxPendingRunOperations?: number;
26
28
  /** Durable events between mid-wake snapshots. Default 200; `0` disables. Parking always snapshots. */
@@ -41,6 +41,7 @@ export function createLooms(options = {}) {
41
41
  modules,
42
42
  store,
43
43
  maxWakeIterations: options.maxWakeIterations,
44
+ livenessLeaseMs: options.livenessLeaseMs,
44
45
  maxPendingRunOperations: options.maxPendingRunOperations,
45
46
  snapshotEvery: options.snapshotEvery,
46
47
  snapshotStore: options.blobStore
@@ -253,6 +253,7 @@ export function createRuntime(options) {
253
253
  repository,
254
254
  snapshotEvery,
255
255
  maxWakeIterations,
256
+ livenessLeaseMs: options.livenessLeaseMs,
256
257
  maxInFlightWorkerEffects: options.maxInFlightWorkerEffects,
257
258
  worker: options.worker,
258
259
  observer: options.observer,
@@ -12,11 +12,18 @@ export interface RouteInfo {
12
12
  /** Stable route name, such as `runs.signal` or `effects.retry`. */
13
13
  readonly name: string;
14
14
  readonly runId?: string;
15
+ /** The signal a `runs.signal.named` request sends, as `namespace/name`. */
16
+ readonly signal?: string;
15
17
  /** Present when the run has labels. Safe for the authorizer to branch on. */
16
18
  readonly attributes?: RunAttributes;
17
19
  }
18
20
  export type AuthDecision = {
19
21
  readonly allowed: true;
22
+ /**
23
+ * Who the request acts as. Events the request sends are recorded with this as their
24
+ * `origin.actorId`, replacing anything the request claimed for itself.
25
+ */
26
+ readonly actorId?: string;
20
27
  } | {
21
28
  readonly allowed: false;
22
29
  readonly status: number;
@@ -24,6 +31,8 @@ export type AuthDecision = {
24
31
  };
25
32
  export type Authorize = (request: Request, route: RouteInfo) => Effect.Effect<AuthDecision>;
26
33
  export declare const authAllowed: AuthDecision;
34
+ /** Allows the request and names who it acts as; see `AuthDecision`. */
35
+ export declare function authAllowedAs(actorId: string): AuthDecision;
27
36
  export declare function authDenied(status: number, error: string): AuthDecision;
28
37
  export declare function authResponse(decision: AuthDecision): Response | null;
29
38
  /**
@@ -31,6 +40,19 @@ export declare function authResponse(decision: AuthDecision): Response | null;
31
40
  * and operational endpoints are unavailable until a host opts in.
32
41
  */
33
42
  export declare const defaultAuthorize: Authorize;
43
+ /**
44
+ * The header a trusted front (such as `routeToDurableObject` with an `authorize` option) uses to
45
+ * tell the host behind it who a request acts as.
46
+ */
47
+ export declare const ACTOR_HEADER = "x-looms-actor-id";
48
+ /**
49
+ * For a host that only a trusted front can reach, such as a Durable Object behind a Worker that
50
+ * routes with `routeToDurableObject`. Applies `inner`, then records the request as acting for the
51
+ * actor the front named in `ACTOR_HEADER`.
52
+ *
53
+ * Do not use this on a host that clients reach directly: they could name any actor.
54
+ */
55
+ export declare function forwardedActorAuth(inner?: Authorize): Authorize;
34
56
  export interface BearerTokens {
35
57
  readonly read?: string;
36
58
  readonly write?: string;
@@ -1,5 +1,9 @@
1
1
  import { Effect } from 'effect';
2
2
  export const authAllowed = { allowed: true };
3
+ /** Allows the request and names who it acts as; see `AuthDecision`. */
4
+ export function authAllowedAs(actorId) {
5
+ return { allowed: true, actorId };
6
+ }
3
7
  export function authDenied(status, error) {
4
8
  return { allowed: false, status, error };
5
9
  }
@@ -21,6 +25,24 @@ function notConfigured(access) {
21
25
  export const defaultAuthorize = (_request, route) => Effect.succeed(route.access === 'worker' || route.access === 'operations'
22
26
  ? notConfigured(route.access)
23
27
  : authAllowed);
28
+ /**
29
+ * The header a trusted front (such as `routeToDurableObject` with an `authorize` option) uses to
30
+ * tell the host behind it who a request acts as.
31
+ */
32
+ export const ACTOR_HEADER = 'x-looms-actor-id';
33
+ /**
34
+ * For a host that only a trusted front can reach, such as a Durable Object behind a Worker that
35
+ * routes with `routeToDurableObject`. Applies `inner`, then records the request as acting for the
36
+ * actor the front named in `ACTOR_HEADER`.
37
+ *
38
+ * Do not use this on a host that clients reach directly: they could name any actor.
39
+ */
40
+ export function forwardedActorAuth(inner = defaultAuthorize) {
41
+ return (request, route) => inner(request, route).pipe(Effect.map((decision) => {
42
+ const actorId = request.headers.get(ACTOR_HEADER);
43
+ return decision.allowed && actorId ? { ...decision, actorId } : decision;
44
+ }));
45
+ }
24
46
  function constantTimeEquals(actual, expected) {
25
47
  const length = Math.max(actual.length, expected.length);
26
48
  let difference = actual.length ^ expected.length;
@@ -1,6 +1,6 @@
1
1
  import { type EventStore } from '@swirls/looms/core';
2
2
  import type { LoomsRuntime } from '../runtime';
3
- import { type Authorize } from './auth';
3
+ import { type Authorize, type RouteInfo } from './auth';
4
4
  import { type DebuggerMount } from './debugger-host';
5
5
  export interface FetchHandlerOptions {
6
6
  readonly runtime: LoomsRuntime;
@@ -13,6 +13,15 @@ export interface FetchHandlerOptions {
13
13
  /** Debugger UI served beside the API and authorized as `{ access: 'read', name: 'debugger' }`. */
14
14
  readonly debugger?: DebuggerMount;
15
15
  }
16
+ /**
17
+ * Says which Looms route a request is for, without a runtime: the same access level, route name,
18
+ * run id and signal that `authorize` receives, but never the run's attributes. Returns null for a
19
+ * path Looms does not serve and for public routes.
20
+ *
21
+ * A front that forwards requests to a host, such as a Worker in front of Durable Objects, uses
22
+ * this to decide what to let through.
23
+ */
24
+ export declare function describeRoute(method: string, pathname: string): RouteInfo | null;
16
25
  /** Whether the fetch handler answers `pathname`: the HTTP API or the debugger mount. */
17
26
  export declare function handlesPath(pathname: string, mount: DebuggerMount | undefined): boolean;
18
27
  export declare function createFetchHandler(options: FetchHandlerOptions): (req: Request) => Promise<Response | null>;
@@ -1,6 +1,6 @@
1
1
  import { Data, Effect, Option, Predicate, Schema } from 'effect';
2
2
  import { hasEntries, RunAttributesSchema } from '@swirls/looms/core';
3
- import { authResponse, defaultAuthorize } from './auth.js';
3
+ import { authAllowed, authResponse, defaultAuthorize, } from './auth.js';
4
4
  import { debuggerPath, serveDebugger } from './debugger-host.js';
5
5
  import { acceptsEventStream, isLoomsApiPath, toErrorResponse } from './http.js';
6
6
  import { matchRoute } from './route-table.js';
@@ -33,26 +33,54 @@ function readRequestAttributes(req) {
33
33
  onSome: (decoded) => decoded.attributes ?? noAttributes,
34
34
  })), Effect.catchTag('UnreadableStartBody', () => Effect.succeed(noAttributes)));
35
35
  }
36
- function authorizeRoute(req, matched, authorize, runtime, store) {
36
+ const NAMED_SIGNAL_ROUTE = 'runs.signal.named';
37
+ /** What a matched route is about, before the run's attributes are known. */
38
+ function matchedRouteInfo(matched) {
37
39
  const { access, name } = matched.route;
38
40
  if (access === 'public') {
39
- return Effect.succeed(null);
41
+ return null;
42
+ }
43
+ const { runId, namespace, name: signalName } = matched.params;
44
+ if (!Predicate.isString(runId)) {
45
+ return { access, name };
46
+ }
47
+ // Only a run's named signal route has these two parameters.
48
+ return name === NAMED_SIGNAL_ROUTE &&
49
+ Predicate.isString(namespace) &&
50
+ Predicate.isString(signalName)
51
+ ? { access, name, runId, signal: `${namespace}/${signalName}` }
52
+ : { access, name, runId };
53
+ }
54
+ let routeShapes;
55
+ /**
56
+ * Says which Looms route a request is for, without a runtime: the same access level, route name,
57
+ * run id and signal that `authorize` receives, but never the run's attributes. Returns null for a
58
+ * path Looms does not serve and for public routes.
59
+ *
60
+ * A front that forwards requests to a host, such as a Worker in front of Durable Objects, uses
61
+ * this to decide what to let through.
62
+ */
63
+ export function describeRoute(method, pathname) {
64
+ // SAFETY: route handlers are the only code that reads the options, and they are never called
65
+ // here; only each route's method, path, name and access are used.
66
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
67
+ routeShapes ??= createRoutes({});
68
+ const matched = matchRoute(routeShapes, method, pathname);
69
+ return matched ? matchedRouteInfo(matched) : null;
70
+ }
71
+ function authorizeRoute(req, matched, authorize, runtime, store) {
72
+ const info = matchedRouteInfo(matched);
73
+ if (!info) {
74
+ return Effect.succeed(authAllowed);
40
75
  }
41
- const runId = matched.params.runId;
76
+ const { name, runId } = info;
42
77
  return Effect.gen(function* () {
43
78
  const stored = Predicate.isString(runId)
44
79
  ? yield* readStoredAttributes(runtime, store, runId)
45
80
  : noAttributes;
46
81
  const requested = START_ROUTES.has(name) ? yield* readRequestAttributes(req) : noAttributes;
47
82
  const attributes = hasEntries(stored) ? stored : requested;
48
- const route = Predicate.isString(runId)
49
- ? hasEntries(attributes)
50
- ? { access, name, runId, attributes }
51
- : { access, name, runId }
52
- : hasEntries(attributes)
53
- ? { access, name, attributes }
54
- : { access, name };
55
- return yield* authorize(req, route).pipe(Effect.map(authResponse));
83
+ return yield* authorize(req, hasEntries(attributes) ? { ...info, attributes } : info);
56
84
  });
57
85
  }
58
86
  /** Whether the fetch handler answers `pathname`: the HTTP API or the debugger mount. */
@@ -81,11 +109,15 @@ export function createFetchHandler(options) {
81
109
  if (!matched) {
82
110
  return new Response('Not Found', { status: 404 });
83
111
  }
84
- const denied = yield* authorizeRoute(req, matched, authorize, options.runtime, options.store);
112
+ const decision = yield* authorizeRoute(req, matched, authorize, options.runtime, options.store);
113
+ const denied = authResponse(decision);
85
114
  if (denied) {
86
115
  return denied;
87
116
  }
88
- return yield* matched.route.handle({ req, url, params: matched.params });
117
+ const context = { req, url, params: matched.params };
118
+ return yield* matched.route.handle(decision.allowed && decision.actorId
119
+ ? { ...context, actorId: decision.actorId }
120
+ : context);
89
121
  }));
90
122
  };
91
123
  }
@@ -19,6 +19,8 @@ export interface RouteContext<TParams> {
19
19
  readonly req: Request;
20
20
  readonly url: URL;
21
21
  readonly params: TParams;
22
+ /** Who the request acts as, when `authorize` named someone. */
23
+ readonly actorId?: string;
22
24
  }
23
25
  export interface RouteDefinition<TPath extends string, TDecoders extends ParamDecoders<TPath>> {
24
26
  readonly method: 'GET' | 'POST';
@@ -53,6 +53,15 @@ function readStartRunArgs(req) {
53
53
  };
54
54
  });
55
55
  }
56
+ /**
57
+ * Records `events` as sent by `actorId`. Whatever origin the caller wrote on them is replaced: the
58
+ * host's `authorize` decides who a request acts as, not the request.
59
+ */
60
+ function sentBy(events, actorId) {
61
+ return actorId === undefined
62
+ ? events
63
+ : events.map((event) => ({ ...event, origin: { type: 'external', actorId } }));
64
+ }
56
65
  function wantsRunStream(req, url) {
57
66
  return url.searchParams.get('stream') === 'true' || acceptsEventStream(req);
58
67
  }
@@ -208,14 +217,14 @@ export function runRoutes({ runtime, store }) {
208
217
  path: '/runs/:runId/events',
209
218
  name: 'runs.signal',
210
219
  access: 'write',
211
- handle: ({ req, params }) => Effect.gen(function* () {
220
+ handle: ({ req, params, actorId }) => Effect.gen(function* () {
212
221
  const body = yield* readJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(SignalBodySchema)));
213
222
  const events = body.events ??
214
223
  (body.type
215
224
  ? [{ type: body.type, payload: body.payload ?? null, threadId: body.threadId }]
216
225
  : []);
217
226
  const idempotencyKey = extractIdempotencyKey(req, body.idempotencyKey);
218
- const state = yield* provideStore(runtime.signal(params.runId, events, { idempotencyKey }), store);
227
+ const state = yield* provideStore(runtime.signal(params.runId, sentBy(events, actorId), { idempotencyKey }), store);
219
228
  return Response.json({ runId: params.runId, state });
220
229
  }),
221
230
  }),
@@ -224,7 +233,7 @@ export function runRoutes({ runtime, store }) {
224
233
  path: '/runs/:runId/signals/:namespace/:name',
225
234
  name: 'runs.signal.named',
226
235
  access: 'write',
227
- handle: ({ req, params }) =>
236
+ handle: ({ req, params, actorId }) =>
228
237
  // SAFETY: Effect.gen residual R is never here; decode/run errors map to Error via route handlers.
229
238
  Effect.gen(function* () {
230
239
  const definition = findSignal(runtime.registry.modules, params.namespace, params.name);
@@ -234,7 +243,7 @@ export function runRoutes({ runtime, store }) {
234
243
  const body = yield* readJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(NamedSignalBodySchema)));
235
244
  const events = yield* runSignal(definition, body.input ?? null, body.threadId);
236
245
  const idempotencyKey = extractIdempotencyKey(req, body.idempotencyKey);
237
- const state = yield* provideStore(runtime.signal(params.runId, events, { idempotencyKey }), store);
246
+ const state = yield* provideStore(runtime.signal(params.runId, sentBy(events, actorId), { idempotencyKey }), store);
238
247
  return Response.json({ runId: params.runId, state });
239
248
  }),
240
249
  }),
@@ -1,8 +1,8 @@
1
- export { createFetchHandler, handlesPath, type FetchHandlerOptions } from './server/fetch-handler';
1
+ export { createFetchHandler, describeRoute, handlesPath, type FetchHandlerOptions, } from './server/fetch-handler';
2
2
  export { isLoomsApiPath } from './server/http';
3
3
  export { mountDebugger, type DebuggerMount } from './server/debugger-host';
4
4
  export { runRouteInfo } from './server/run-route';
5
- export { authAllowed, authDenied, authResponse, bearerAuth, defaultAuthorize, type AuthDecision, type AuthorizedAccess, type Authorize, type BearerTokens, type RouteAccess, type RouteInfo, } from './server/auth';
5
+ export { ACTOR_HEADER, authAllowed, authAllowedAs, authDenied, authResponse, bearerAuth, defaultAuthorize, forwardedActorAuth, type AuthDecision, type AuthorizedAccess, type Authorize, type BearerTokens, type RouteAccess, type RouteInfo, } from './server/auth';
6
6
  export { grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, type GrantAuthOptions, type GrantFailure, type RunGrant, } from './server/grant';
7
7
  export interface RunningServer {
8
8
  port: number;
@@ -1,8 +1,8 @@
1
- export { createFetchHandler, handlesPath } from './server/fetch-handler.js';
1
+ export { createFetchHandler, describeRoute, handlesPath, } from './server/fetch-handler.js';
2
2
  export { isLoomsApiPath } from './server/http.js';
3
3
  export { mountDebugger } from './server/debugger-host.js';
4
4
  export { runRouteInfo } from './server/run-route.js';
5
- export { authAllowed, authDenied, authResponse, bearerAuth, defaultAuthorize, } from './server/auth.js';
5
+ export { ACTOR_HEADER, authAllowed, authAllowedAs, authDenied, authResponse, bearerAuth, defaultAuthorize, forwardedActorAuth, } from './server/auth.js';
6
6
  export { grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, } from './server/grant.js';
7
7
  export function serveHttp(fetchHandler, options) {
8
8
  const port = options?.port ?? 8787;
@@ -21,6 +21,12 @@ export interface CreateRuntimeOptions<TModules extends readonly AnyRuntimeModule
21
21
  */
22
22
  readonly snapshotEvery?: number;
23
23
  readonly maxWakeIterations?: number;
24
+ /**
25
+ * How far ahead a wake with in-process effects in flight keeps its `WakeScheduler.keepAlive`
26
+ * deadline, in milliseconds. Renewed every third of it. Default 30000. Only used when the
27
+ * scheduler implements `keepAlive`.
28
+ */
29
+ readonly livenessLeaseMs?: number;
24
30
  /** Maximum concurrent in-flight worker effects dispatched per run (fairness guard). */
25
31
  readonly maxInFlightWorkerEffects?: number;
26
32
  /** Maximum active and queued mutation operations per run. Default 256. */
@@ -13,6 +13,7 @@ export interface WakeEngineOptions {
13
13
  readonly repository: RuntimeRepository;
14
14
  readonly snapshotEvery: number;
15
15
  readonly maxWakeIterations: number;
16
+ readonly livenessLeaseMs?: number;
16
17
  readonly maxInFlightWorkerEffects?: number;
17
18
  readonly worker?: EffectWorker;
18
19
  readonly observer?: RuntimeObserver;
@@ -9,6 +9,7 @@ import { executeLocalEffects } from './local-effect-executor.js';
9
9
  import { notifyObserver } from './observer.js';
10
10
  import { requestWakeAgain, } from './run-execution-context.js';
11
11
  import { dispatchWorkerEffect, isWorkerEffect, planWorkerEffects } from './worker-effect-dispatch.js';
12
+ const DEFAULT_LIVENESS_LEASE_MS = 30_000;
12
13
  function currentTimeMillis() {
13
14
  return Math.floor(performance.timeOrigin + performance.now());
14
15
  }
@@ -20,6 +21,8 @@ export function createWakeEngine(options) {
20
21
  set: repository.setCachedCursor,
21
22
  };
22
23
  const observe = (event) => notifyObserver(options.observer, event);
24
+ const livenessLeaseMs = Math.max(1, options.livenessLeaseMs ?? DEFAULT_LIVENESS_LEASE_MS);
25
+ const livenessRenewMs = Math.max(1, Math.floor(livenessLeaseMs / 3));
23
26
  const closeLaunchedRuns = (store, runId, cursor) => Effect.gen(function* () {
24
27
  let next = cursor;
25
28
  const state = next.state;
@@ -74,6 +77,34 @@ export function createWakeEngine(options) {
74
77
  executionContext.resolveWakeCompletion = resolveCompletion;
75
78
  executionContext.waking = true;
76
79
  let released = false;
80
+ // When the liveness deadline is next due for renewal; `null` while this wake holds none.
81
+ let livenessRenewAt = null;
82
+ // In-process effects have no deadline of their own, so nothing would wake the run if this
83
+ // process were lost while they run. Where the scheduler supports it, keep a wake pending a
84
+ // short time ahead for as long as the wake waits on them. Never returns.
85
+ const holdLiveness = Effect.gen(function* () {
86
+ const scheduler = options.scheduler();
87
+ if (!scheduler.keepAlive) {
88
+ return yield* Effect.never;
89
+ }
90
+ while (true) {
91
+ const now = yield* Clock.currentTimeMillis;
92
+ if (livenessRenewAt !== null && now < livenessRenewAt) {
93
+ yield* Effect.sleep(livenessRenewAt - now);
94
+ continue;
95
+ }
96
+ // Claimed before the write so a failed or interrupted write is still cleared on exit.
97
+ livenessRenewAt = now + livenessRenewMs;
98
+ yield* scheduler.keepAlive(runId, now + livenessLeaseMs);
99
+ }
100
+ });
101
+ const releaseLiveness = Effect.suspend(() => {
102
+ if (livenessRenewAt === null) {
103
+ return Effect.void;
104
+ }
105
+ livenessRenewAt = null;
106
+ return options.scheduler().keepAlive?.(runId, null) ?? Effect.void;
107
+ });
77
108
  const releaseWake = () => {
78
109
  released = true;
79
110
  executionContext.waking = false;
@@ -361,11 +392,16 @@ export function createWakeEngine(options) {
361
392
  if (executionContext.wakeAgain) {
362
393
  Deferred.doneUnsafe(wakeGate, Effect.void);
363
394
  }
364
- const progress = yield* Effect.raceFirst(Queue.take(settled).pipe(Effect.map((item) => ({ _tag: 'settled', ...item }))), Deferred.await(wakeGate).pipe(Effect.as({ _tag: 'wake' })));
395
+ const progress = yield* Effect.raceFirst(Effect.raceFirst(Queue.take(settled).pipe(Effect.map((item) => ({ _tag: 'settled', ...item }))), Deferred.await(wakeGate).pipe(Effect.as({ _tag: 'wake' }))), holdLiveness);
365
396
  if (executionContext.wakeSignal === wakeGate) {
366
397
  executionContext.wakeSignal = null;
367
398
  }
368
399
  if (progress._tag === 'wake') {
400
+ // A joined wake may be the host's pending wake firing, which uses it up. Ask again
401
+ // on the next wait instead of at the next renewal.
402
+ if (livenessRenewAt !== null) {
403
+ livenessRenewAt = Number.NEGATIVE_INFINITY;
404
+ }
369
405
  continue;
370
406
  }
371
407
  inFlight.delete(progress.groupKey);
@@ -453,7 +489,10 @@ export function createWakeEngine(options) {
453
489
  return yield* new RuntimeExecutionError(`Wake for run "${runId}" completed without state`);
454
490
  }
455
491
  return finalState;
456
- }).pipe(Effect.onExit((exit) => Effect.sync(() => {
492
+ }).pipe(
493
+ // Before the claim is released, so a wake that starts next takes a fresh deadline after
494
+ // this one is cleared rather than having its own cleared.
495
+ Effect.onExit(() => releaseLiveness), Effect.onExit((exit) => Effect.sync(() => {
457
496
  if (!released) {
458
497
  releaseWake();
459
498
  }
@@ -2,6 +2,14 @@ import { Effect } from 'effect';
2
2
  export interface WakeScheduler {
3
3
  schedule(runId: string, at: number): Effect.Effect<void>;
4
4
  cancel(runId: string): Effect.Effect<void>;
5
+ /**
6
+ * Optional. While a wake has in-process effects in flight it asks to be woken at `until`, renews
7
+ * that before it passes, and clears it with `null` when the wake ends. Implement it only where
8
+ * the wake outlives the process (a Durable Object alarm): if the process is lost mid-effect the
9
+ * deadline fires elsewhere and the run re-attempts the effect. It must not replace the deadline
10
+ * set through `schedule`; the host wakes at the earlier of the two.
11
+ */
12
+ keepAlive?(runId: string, until: number | null): Effect.Effect<void>;
5
13
  dispose?(): void;
6
14
  }
7
15
  export declare function createTimeoutScheduler(wake: (runId: string) => Effect.Effect<void>): WakeScheduler;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swirls/looms",
3
- "version": "0.12.4",
3
+ "version": "0.13.1",
4
4
  "description": "Pluggable event-sourced runtime for durable agents and workflows",
5
5
  "homepage": "https://github.com/ByteSliceHQ/looms#readme",
6
6
  "bugs": {