@swirls/looms 0.16.0 → 0.18.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.
- package/CHANGELOG.md +21 -0
- package/dist/actor/cell.d.ts +5 -1
- package/dist/actor/cell.js +2 -0
- package/dist/actor/host.d.ts +5 -1
- package/dist/actor/host.js +2 -0
- package/dist/agent/effects.d.ts +266 -266
- package/dist/approval/effects.d.ts +26 -26
- package/dist/approval/module.d.ts +52 -52
- package/dist/client/client.d.ts +1 -0
- package/dist/client/client.js +10 -4
- package/dist/cloudflare/durable-object.d.ts +5 -1
- package/dist/cloudflare/durable-object.js +2 -0
- package/dist/cloudflare/queue-consumer.js +11 -3
- package/dist/core/effects.d.ts +1 -1
- package/dist/core/module.d.ts +1 -0
- package/dist/core/run-context.d.ts +6 -2
- package/dist/core/sqlite-store.js +6 -0
- package/dist/core/store.js +5 -0
- package/dist/core/worker-callback.d.ts +5 -2
- package/dist/debugger/app/assets/{index-Br9tGbPI.js → index-BjZn1DuJ.js} +2 -2
- package/dist/debugger/app/assets/{routes-CZ0buqO7.js → routes-B90xnBF1.js} +2 -2
- package/dist/debugger/app/index.html +1 -1
- package/dist/react/index.d.ts +1 -1
- package/dist/react/index.js +1 -1
- package/dist/react/react.d.ts +33 -0
- package/dist/react/react.js +51 -0
- package/dist/runtime/effect-admission.d.ts +8 -3
- package/dist/runtime/effect-admission.js +23 -4
- package/dist/runtime/index.d.ts +2 -0
- package/dist/runtime/index.js +2 -0
- package/dist/runtime/local-effect-executor.d.ts +8 -2
- package/dist/runtime/local-effect-executor.js +21 -8
- package/dist/runtime/looms.d.ts +6 -0
- package/dist/runtime/looms.js +2 -0
- package/dist/runtime/observer.d.ts +15 -0
- package/dist/runtime/run-secrets.d.ts +132 -0
- package/dist/runtime/run-secrets.js +154 -0
- package/dist/runtime/runtime.js +27 -25
- package/dist/runtime/secret-sealer.d.ts +24 -0
- package/dist/runtime/secret-sealer.js +120 -0
- package/dist/runtime/server/routes/runs.js +2 -1
- package/dist/runtime/types.d.ts +20 -7
- package/dist/runtime/wake-engine.d.ts +2 -0
- package/dist/runtime/wake-engine.js +23 -9
- package/dist/runtime/worker-callbacks.d.ts +4 -2
- package/dist/runtime/worker-callbacks.js +15 -2
- package/dist/runtime/worker-effect-dispatch.d.ts +1 -2
- package/dist/runtime/worker-effect-dispatch.js +0 -1
- package/dist/schedule/module.d.ts +36 -36
- package/package.json +1 -1
package/dist/runtime/runtime.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { Clock, Effect, ManagedRuntime, Predicate } from 'effect';
|
|
2
|
-
import { cachedDefinitionResolver, chainDefinitionResolvers, composeModules, createEvent, createThreadId, createRunId, DEFAULT_DEFINITION_VERSION, DEFAULT_SNAPSHOT_EVERY, staticDefinitionResolver, descendantThreadIds, EventStoreTag, foldRun, hasEntries, InvalidRunAttributesError, isRunTerminal, runAttributeIssues, unavailableRunLauncher, planFork, project, readTraceContext, replayTo,
|
|
2
|
+
import { cachedDefinitionResolver, chainDefinitionResolvers, composeModules, createEvent, createThreadId, createRunId, DEFAULT_DEFINITION_VERSION, DEFAULT_SNAPSHOT_EVERY, staticDefinitionResolver, descendantThreadIds, EventStoreTag, foldRun, hasEntries, InvalidRunAttributesError, isRunTerminal, runAttributeIssues, unavailableRunLauncher, planFork, project, readTraceContext, replayTo, summarizeRun, } from '@swirls/looms/core';
|
|
3
3
|
import { createCancellation } from './cancellation.js';
|
|
4
4
|
import { nextRuntimeDeadline } from './deadline-transition-planner.js';
|
|
5
|
-
import { ForkConflictError, RunNotFinishedError, RunNotFoundError, RunTerminalError, RuntimeExecutionError,
|
|
5
|
+
import { ForkConflictError, RunNotFinishedError, RunNotFoundError, RunTerminalError, RuntimeExecutionError, StartRunConflictError, } from './errors.js';
|
|
6
6
|
import { admitExternalEvents, moduleServices, resolveSnapshotStore, RunCursorCache, threadStartedEvents, UnknownDefinitionError, validateAndCreateEvents, waitSatisfiedEvents, } from './helpers.js';
|
|
7
7
|
import { createRunIngress } from './ingress.js';
|
|
8
8
|
import { notifyObserver } from './observer.js';
|
|
9
9
|
import { createRuntimeRepository } from './repository.js';
|
|
10
10
|
import { requestWakeAgain, RunExecutionContexts } from './run-execution-context.js';
|
|
11
|
+
import { createRunSecrets, SEALED_SECRETS_KEY } from './run-secrets.js';
|
|
11
12
|
import { assertSameDurableStart } from './run-start.js';
|
|
12
13
|
import { createWakeEngine } from './wake-engine.js';
|
|
13
14
|
import { createTimeoutScheduler } from './wake-scheduler.js';
|
|
@@ -56,31 +57,16 @@ function startedPayload(input) {
|
|
|
56
57
|
}
|
|
57
58
|
return payload;
|
|
58
59
|
}
|
|
59
|
-
function reconcileRunSecrets(store, runId, requested) {
|
|
60
|
-
const next = requested ?? {};
|
|
61
|
-
return Effect.gen(function* () {
|
|
62
|
-
const stored = store.runSecrets;
|
|
63
|
-
if (!stored) {
|
|
64
|
-
if (hasEntries(next)) {
|
|
65
|
-
return yield* new RuntimeExecutionError('This event store cannot persist a secret context');
|
|
66
|
-
}
|
|
67
|
-
return yield* Effect.void;
|
|
68
|
-
}
|
|
69
|
-
const current = yield* stored.get(runId);
|
|
70
|
-
if (sameStringRecord(current, next) || requested === undefined) {
|
|
71
|
-
return yield* Effect.void;
|
|
72
|
-
}
|
|
73
|
-
if (!hasEntries(current)) {
|
|
74
|
-
return yield* stored.put(runId, next);
|
|
75
|
-
}
|
|
76
|
-
return yield* new SecretContextConflictError(runId);
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
60
|
export function createRuntime(options) {
|
|
80
61
|
if (options.localLauncher && !options.store && !options.launcher) {
|
|
81
62
|
throw new Error('localLauncher requires options.store');
|
|
82
63
|
}
|
|
83
64
|
const registry = composeModules(options.modules);
|
|
65
|
+
const runSecrets = createRunSecrets({
|
|
66
|
+
provider: options.secretProvider,
|
|
67
|
+
sealer: options.secretSealer,
|
|
68
|
+
observer: options.observer,
|
|
69
|
+
});
|
|
84
70
|
assertWorkerConfigured(registry, options.worker);
|
|
85
71
|
assertWorkerClaimsExplicit(registry, options.worker);
|
|
86
72
|
assertWorkerDeadlines(registry, options.worker);
|
|
@@ -214,6 +200,9 @@ export function createRuntime(options) {
|
|
|
214
200
|
if (hasEntries(args.secrets ?? {}) && !store.runSecrets) {
|
|
215
201
|
return yield* new RuntimeExecutionError('This event store cannot persist a secret context');
|
|
216
202
|
}
|
|
203
|
+
if (Object.hasOwn(args.secrets ?? {}, SEALED_SECRETS_KEY)) {
|
|
204
|
+
return yield* new RuntimeExecutionError(`A secret cannot be named "${SEALED_SECRETS_KEY}"`);
|
|
205
|
+
}
|
|
217
206
|
const committed = yield* commit(store, runId, (existing) => existing.seq > 0
|
|
218
207
|
? assertSameDurableStart(runId, existing.state, requestedIdentity).pipe(Effect.map((rootThreadId) => ({
|
|
219
208
|
events: [],
|
|
@@ -235,12 +224,13 @@ export function createRuntime(options) {
|
|
|
235
224
|
},
|
|
236
225
|
idempotencyKey: args.idempotencyKey ? `start:${args.idempotencyKey}` : undefined,
|
|
237
226
|
}))));
|
|
238
|
-
yield* reconcileRunSecrets(store, runId, args.secrets);
|
|
239
227
|
if (!committed.append?.deduplicated) {
|
|
228
|
+
yield* runSecrets.provision(store, runId, committed.value.state, args.secrets);
|
|
240
229
|
return committed.value;
|
|
241
230
|
}
|
|
242
231
|
const durable = yield* loadCursor(store, runId);
|
|
243
232
|
const rootThreadId = yield* assertSameDurableStart(runId, durable.state, requestedIdentity);
|
|
233
|
+
yield* runSecrets.provision(store, runId, durable.state, args.secrets);
|
|
244
234
|
return { threadId: rootThreadId, state: durable.state };
|
|
245
235
|
});
|
|
246
236
|
let scheduler;
|
|
@@ -260,6 +250,7 @@ export function createRuntime(options) {
|
|
|
260
250
|
definitionResolver,
|
|
261
251
|
scheduler: () => scheduler,
|
|
262
252
|
launcher: () => launcher,
|
|
253
|
+
runSecrets,
|
|
263
254
|
});
|
|
264
255
|
const workerCallbacks = createWorkerCallbacks({
|
|
265
256
|
registry,
|
|
@@ -267,6 +258,7 @@ export function createRuntime(options) {
|
|
|
267
258
|
withRunIngress,
|
|
268
259
|
observer: options.observer,
|
|
269
260
|
wake: wakeEngine,
|
|
261
|
+
runSecrets,
|
|
270
262
|
});
|
|
271
263
|
const cancellation = createCancellation({
|
|
272
264
|
registry,
|
|
@@ -447,8 +439,18 @@ export function createRuntime(options) {
|
|
|
447
439
|
? Effect.succeed({ events: [], value: undefined })
|
|
448
440
|
: Effect.fail(new ForkConflictError(runId, sourceRunId));
|
|
449
441
|
});
|
|
450
|
-
|
|
451
|
-
|
|
442
|
+
// The source has finished, so it holds nothing. The provider decides what the fork is
|
|
443
|
+
// supplied with; without one the fork starts with no secrets.
|
|
444
|
+
const fork = yield* loadCursor(store, runId);
|
|
445
|
+
const supplied = forkOptions?.secrets ??
|
|
446
|
+
(yield* runSecrets.forChild(store, sourceRunId, source.state, {
|
|
447
|
+
runId,
|
|
448
|
+
relation: 'fork',
|
|
449
|
+
kind: fork.state.startIdentity?.kind ?? null,
|
|
450
|
+
definitionName: fork.state.startIdentity?.definitionName ?? null,
|
|
451
|
+
attributes: fork.state.attributes,
|
|
452
|
+
}));
|
|
453
|
+
yield* runSecrets.provision(store, runId, fork.state, supplied);
|
|
452
454
|
return plan.rootThreadId;
|
|
453
455
|
})).pipe(Effect.flatMap((threadId) => runtime.wake(runId).pipe(Effect.map((state) => ({ runId, threadId, state })))));
|
|
454
456
|
},
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { SecretSealer } from './run-secrets';
|
|
2
|
+
export interface SecretSealerOptions {
|
|
3
|
+
/** The key new records are sealed with. At least 32 characters of high-entropy text. */
|
|
4
|
+
readonly key: string;
|
|
5
|
+
/** Keys that older records may still be sealed with. They open records and never seal them. */
|
|
6
|
+
readonly previousKeys?: ReadonlyArray<string>;
|
|
7
|
+
}
|
|
8
|
+
declare const SecretSealError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
9
|
+
readonly _tag: "SecretSealError";
|
|
10
|
+
} & Readonly<A>;
|
|
11
|
+
/** A record could not be sealed or opened. The message never includes secret values. */
|
|
12
|
+
export declare class SecretSealError extends SecretSealError_base<{
|
|
13
|
+
readonly message: string;
|
|
14
|
+
}> {
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Seals what a run holds with AES-256-GCM, under a key derived from `key`. The run id is
|
|
18
|
+
* authenticated with each record, so a record copied to another run does not open.
|
|
19
|
+
*
|
|
20
|
+
* This protects a copy of the storage that leaves without the key, such as a backup or an
|
|
21
|
+
* export. It does not protect against code that runs in the host, which has the key.
|
|
22
|
+
*/
|
|
23
|
+
export declare function secretSealer(options: SecretSealerOptions): SecretSealer;
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { Data, Effect, Schema } from 'effect';
|
|
2
|
+
import { SecretContextSchema } from '@swirls/looms/core';
|
|
3
|
+
/** A record could not be sealed or opened. The message never includes secret values. */
|
|
4
|
+
export class SecretSealError extends Data.TaggedError('SecretSealError') {
|
|
5
|
+
}
|
|
6
|
+
const MIN_KEY_LENGTH = 32;
|
|
7
|
+
const VERSION = 'v1';
|
|
8
|
+
const encoder = new TextEncoder();
|
|
9
|
+
const decoder = new TextDecoder();
|
|
10
|
+
const SecretsJson = Schema.fromJsonString(SecretContextSchema);
|
|
11
|
+
const decodeSecrets = Schema.decodeUnknownEffect(SecretsJson);
|
|
12
|
+
const encodeSecrets = Schema.encodeSync(SecretsJson);
|
|
13
|
+
const failed = (message) => () => new SecretSealError({ message });
|
|
14
|
+
function bytes(text) {
|
|
15
|
+
const encoded = encoder.encode(text);
|
|
16
|
+
const copy = new Uint8Array(new ArrayBuffer(encoded.length));
|
|
17
|
+
copy.set(encoded);
|
|
18
|
+
return copy;
|
|
19
|
+
}
|
|
20
|
+
function toBase64Url(value) {
|
|
21
|
+
const view = value instanceof Uint8Array ? value : new Uint8Array(value);
|
|
22
|
+
let binary = '';
|
|
23
|
+
for (const byte of view) {
|
|
24
|
+
binary += String.fromCharCode(byte);
|
|
25
|
+
}
|
|
26
|
+
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
|
|
27
|
+
}
|
|
28
|
+
function fromBase64Url(value) {
|
|
29
|
+
if (!/^[A-Za-z0-9_-]+$/.test(value)) {
|
|
30
|
+
return Effect.fail(new SecretSealError({ message: 'The sealed record is malformed' }));
|
|
31
|
+
}
|
|
32
|
+
const binary = atob(value.replaceAll('-', '+').replaceAll('_', '/'));
|
|
33
|
+
const out = new Uint8Array(new ArrayBuffer(binary.length));
|
|
34
|
+
for (let index = 0; index < binary.length; index += 1) {
|
|
35
|
+
out[index] = binary.charCodeAt(index);
|
|
36
|
+
}
|
|
37
|
+
return Effect.succeed(out);
|
|
38
|
+
}
|
|
39
|
+
function hkdf(info) {
|
|
40
|
+
return {
|
|
41
|
+
name: 'HKDF',
|
|
42
|
+
hash: 'SHA-256',
|
|
43
|
+
salt: new Uint8Array(new ArrayBuffer(0)),
|
|
44
|
+
info: bytes(info),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** Derives the encryption key and a public id for it, so a record names the key that sealed it. */
|
|
48
|
+
function derive(secret) {
|
|
49
|
+
const fail = failed('The sealing key could not be derived');
|
|
50
|
+
return Effect.gen(function* () {
|
|
51
|
+
const material = yield* Effect.tryPromise({
|
|
52
|
+
try: () => crypto.subtle.importKey('raw', bytes(secret), 'HKDF', false, ['deriveBits', 'deriveKey']),
|
|
53
|
+
catch: fail,
|
|
54
|
+
});
|
|
55
|
+
const id = yield* Effect.tryPromise({
|
|
56
|
+
try: () => crypto.subtle.deriveBits(hkdf('looms/run-secrets/v1/id'), material, 64),
|
|
57
|
+
catch: fail,
|
|
58
|
+
});
|
|
59
|
+
const key = yield* Effect.tryPromise({
|
|
60
|
+
try: () => crypto.subtle.deriveKey(hkdf('looms/run-secrets/v1/key'), material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']),
|
|
61
|
+
catch: fail,
|
|
62
|
+
});
|
|
63
|
+
return { id: toBase64Url(id), key };
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Seals what a run holds with AES-256-GCM, under a key derived from `key`. The run id is
|
|
68
|
+
* authenticated with each record, so a record copied to another run does not open.
|
|
69
|
+
*
|
|
70
|
+
* This protects a copy of the storage that leaves without the key, such as a backup or an
|
|
71
|
+
* export. It does not protect against code that runs in the host, which has the key.
|
|
72
|
+
*/
|
|
73
|
+
export function secretSealer(options) {
|
|
74
|
+
const secrets = [options.key, ...(options.previousKeys ?? [])];
|
|
75
|
+
if (secrets.some((secret) => secret.length < MIN_KEY_LENGTH)) {
|
|
76
|
+
throw new Error(`A secret sealing key needs at least ${MIN_KEY_LENGTH} characters`);
|
|
77
|
+
}
|
|
78
|
+
let derived;
|
|
79
|
+
// Derived on first use and kept: deriving is the expensive part of every seal and open.
|
|
80
|
+
const keys = Effect.tryPromise({
|
|
81
|
+
try: () => {
|
|
82
|
+
derived ??= Effect.runPromise(Effect.forEach(secrets, derive));
|
|
83
|
+
return derived;
|
|
84
|
+
},
|
|
85
|
+
catch: failed('The sealing key could not be derived'),
|
|
86
|
+
});
|
|
87
|
+
return {
|
|
88
|
+
seal: (runId, secretContext) => Effect.gen(function* () {
|
|
89
|
+
const [current] = yield* keys;
|
|
90
|
+
if (!current) {
|
|
91
|
+
return yield* new SecretSealError({ message: 'No sealing key' });
|
|
92
|
+
}
|
|
93
|
+
const iv = crypto.getRandomValues(new Uint8Array(new ArrayBuffer(12)));
|
|
94
|
+
const sealed = yield* Effect.tryPromise({
|
|
95
|
+
try: () => crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: bytes(runId) }, current.key, bytes(encodeSecrets(secretContext))),
|
|
96
|
+
catch: failed('The secrets could not be sealed'),
|
|
97
|
+
});
|
|
98
|
+
return [VERSION, current.id, toBase64Url(iv), toBase64Url(sealed)].join('.');
|
|
99
|
+
}),
|
|
100
|
+
open: (runId, sealed) => Effect.gen(function* () {
|
|
101
|
+
const [version, id, iv, body] = sealed.split('.');
|
|
102
|
+
if (version !== VERSION || !id || !iv || !body) {
|
|
103
|
+
return yield* new SecretSealError({ message: 'The sealed record is malformed' });
|
|
104
|
+
}
|
|
105
|
+
const match = (yield* keys).find((candidate) => candidate.id === id);
|
|
106
|
+
if (!match) {
|
|
107
|
+
return yield* new SecretSealError({
|
|
108
|
+
message: 'The sealed record was sealed with a key this runtime does not have',
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
const nonce = yield* fromBase64Url(iv);
|
|
112
|
+
const ciphertext = yield* fromBase64Url(body);
|
|
113
|
+
const opened = yield* Effect.tryPromise({
|
|
114
|
+
try: () => crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce, additionalData: bytes(runId) }, match.key, ciphertext),
|
|
115
|
+
catch: failed('The sealed record does not open for this run with this key'),
|
|
116
|
+
});
|
|
117
|
+
return yield* decodeSecrets(decoder.decode(opened)).pipe(Effect.mapError(failed('The sealed record is malformed')));
|
|
118
|
+
}),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
@@ -40,6 +40,7 @@ const CancelBodySchema = Schema.Struct({
|
|
|
40
40
|
});
|
|
41
41
|
const ForkBodySchema = Schema.Struct({
|
|
42
42
|
runId: Schema.optional(Schema.String),
|
|
43
|
+
secrets: Schema.optional(SecretContextSchema),
|
|
43
44
|
});
|
|
44
45
|
function readStartRunArgs(req) {
|
|
45
46
|
return Effect.gen(function* () {
|
|
@@ -294,7 +295,7 @@ export function runRoutes({ runtime, store }) {
|
|
|
294
295
|
access: 'write',
|
|
295
296
|
handle: ({ req, params }) => Effect.gen(function* () {
|
|
296
297
|
const body = yield* readOptionalJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(ForkBodySchema)));
|
|
297
|
-
const result = yield* provideStore(runtime.fork(params.runId, { runId: body.runId }), store);
|
|
298
|
+
const result = yield* provideStore(runtime.fork(params.runId, { runId: body.runId, secrets: body.secrets }), store);
|
|
298
299
|
return Response.json(result);
|
|
299
300
|
}),
|
|
300
301
|
}),
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { AnyRuntimeModule, ComposedRegistry, DefinitionResolver, EventEnvel
|
|
|
3
3
|
import type { EventStoreTrimmedError } from '@swirls/looms/core';
|
|
4
4
|
import type { DuplicateEffectDispatchError, MaxWakeIterationsError } from './errors';
|
|
5
5
|
import type { RuntimeObserver } from './observer';
|
|
6
|
+
import type { SecretProvider, SecretSealer } from './run-secrets';
|
|
6
7
|
import type { WakeScheduler } from './wake-scheduler';
|
|
7
8
|
export type WakeError = DuplicateEffectDispatchError | MaxWakeIterationsError | EventStoreTruncationError | EventStoreTrimmedError | EventStoreFencedError | EventStoreError | Error;
|
|
8
9
|
export interface CreateRuntimeOptions<TModules extends readonly AnyRuntimeModule[] = readonly AnyRuntimeModule[]> {
|
|
@@ -68,6 +69,13 @@ export interface CreateRuntimeOptions<TModules extends readonly AnyRuntimeModule
|
|
|
68
69
|
* undeclared one fails with `InvalidRunAttributesError` and writes no events.
|
|
69
70
|
*/
|
|
70
71
|
readonly attributes?: RunAttributeFields;
|
|
72
|
+
/**
|
|
73
|
+
* Decides what each run holds and what each attempt receives. Without one, a run holds the
|
|
74
|
+
* `secrets` its start supplied and every attempt receives them.
|
|
75
|
+
*/
|
|
76
|
+
readonly secretProvider?: SecretProvider;
|
|
77
|
+
/** Encrypts what a run holds before it is stored. See `secretSealer`. */
|
|
78
|
+
readonly secretSealer?: SecretSealer;
|
|
71
79
|
}
|
|
72
80
|
export interface EffectWorkerTask {
|
|
73
81
|
readonly runId: string;
|
|
@@ -88,8 +96,8 @@ export interface EffectWorkerTask {
|
|
|
88
96
|
/** The attempt's deadlines from the effect's retry policy, when it sets any. */
|
|
89
97
|
readonly deadlines?: EffectWorkerDeadlines;
|
|
90
98
|
/**
|
|
91
|
-
* Present only on the in-memory dispatch. A transport that persists the
|
|
92
|
-
* and let the worker read
|
|
99
|
+
* This attempt's secrets. Present only on the in-memory dispatch. A transport that persists the
|
|
100
|
+
* task must leave this out and let the worker read them through an authenticated callback.
|
|
93
101
|
*/
|
|
94
102
|
readonly secrets?: SecretContext;
|
|
95
103
|
}
|
|
@@ -134,8 +142,10 @@ export interface StartRunArgs {
|
|
|
134
142
|
/** Immutable labels stored on the start event and the run summary. */
|
|
135
143
|
attributes?: RunAttributes;
|
|
136
144
|
/**
|
|
137
|
-
* Bearer material stored beside the log
|
|
138
|
-
*
|
|
145
|
+
* Bearer material the run holds, stored beside the log and deleted when the run finishes. With
|
|
146
|
+
* a `secretProvider` that has `provision`, this is what `provision` is supplied with. Without
|
|
147
|
+
* one it is stored as given: a retry that sends a different context conflicts, and omitting it
|
|
148
|
+
* on a retry keeps the context already stored.
|
|
139
149
|
*/
|
|
140
150
|
secrets?: SecretContext;
|
|
141
151
|
/**
|
|
@@ -213,10 +223,12 @@ export interface LoomsRuntime<TModules extends readonly AnyRuntimeModule[] = rea
|
|
|
213
223
|
/**
|
|
214
224
|
* Start a new run that continues where a finished run ended. The fork copies the source's
|
|
215
225
|
* history up to the point it finished and re-issues the effects outstanding there. Retrying
|
|
216
|
-
* with the same `runId` returns the existing fork.
|
|
226
|
+
* with the same `runId` returns the existing fork. The source's secrets were deleted when it
|
|
227
|
+
* finished, so the fork holds `secrets` when given, or else what the secret provider decides.
|
|
217
228
|
*/
|
|
218
229
|
fork(sourceRunId: string, options?: {
|
|
219
230
|
runId?: string;
|
|
231
|
+
secrets?: SecretContext;
|
|
220
232
|
}): Effect.Effect<StartResult, Error | EventStoreAppendError | EventStoreError, EventStoreTag>;
|
|
221
233
|
/**
|
|
222
234
|
* Applies a worker's report about one effect attempt. A report for another attempt, or one that
|
|
@@ -224,8 +236,9 @@ export interface LoomsRuntime<TModules extends readonly AnyRuntimeModule[] = rea
|
|
|
224
236
|
*/
|
|
225
237
|
workerCallback(runId: string, input: WorkerCallbackInput): Effect.Effect<WorkerCallbackResult, Error | EventStoreAppendError | EventStoreError, EventStoreTag>;
|
|
226
238
|
/**
|
|
227
|
-
* The
|
|
228
|
-
*
|
|
239
|
+
* The secrets for a worker attempt that has started and not settled. Any other attempt is
|
|
240
|
+
* `stale`, so a redelivered or superseded message never sees them. `unavailable` means the
|
|
241
|
+
* secret provider failed this time.
|
|
229
242
|
*/
|
|
230
243
|
workerSecrets(runId: string, callback: WorkerCallback): Effect.Effect<WorkerSecretsResult, Error | EventStoreTruncationError | EventStoreTrimmedError | EventStoreError, EventStoreTag>;
|
|
231
244
|
readonly listRuns: Effect.Effect<string[], EventStoreError, EventStoreTag>;
|
|
@@ -3,6 +3,7 @@ import { type ComposedRegistry, type DefinitionResolver, type RunLauncher } from
|
|
|
3
3
|
import { type RuntimeObserver } from './observer';
|
|
4
4
|
import type { RuntimeRepository } from './repository';
|
|
5
5
|
import { type RunExecutionContexts } from './run-execution-context';
|
|
6
|
+
import type { RunSecrets } from './run-secrets';
|
|
6
7
|
import type { LoomsRuntime, EffectWorker } from './types';
|
|
7
8
|
import type { WakeScheduler } from './wake-scheduler';
|
|
8
9
|
export interface WakeEngineOptions {
|
|
@@ -19,5 +20,6 @@ export interface WakeEngineOptions {
|
|
|
19
20
|
readonly observer?: RuntimeObserver;
|
|
20
21
|
readonly scheduler: () => WakeScheduler;
|
|
21
22
|
readonly launcher: () => RunLauncher;
|
|
23
|
+
readonly runSecrets: RunSecrets;
|
|
22
24
|
}
|
|
23
25
|
export declare function createWakeEngine(options: WakeEngineOptions): LoomsRuntime['wake'];
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Clock, Deferred, Effect, Exit, Fiber, Option, Queue, } from 'effect';
|
|
2
|
-
import { createEvent, deferredUntil, EventStoreTag, foldRun, isPrimitiveEffect, isRunTerminal, } from '@swirls/looms/core';
|
|
2
|
+
import { createEvent, deferredUntil, EventStoreTag, foldRun, isPrimitiveEffect, hasEntries, isRunTerminal, } from '@swirls/looms/core';
|
|
3
3
|
import { childCloseCancellations, notifyLaunchingParent } from './child-run.js';
|
|
4
4
|
import { nextRuntimeDeadline, planDeadlineTransitions, planTerminalCancellationTransitions, } from './deadline-transition-planner.js';
|
|
5
5
|
import { admitOrFailAttempt } from './effect-admission.js';
|
|
@@ -134,7 +134,6 @@ export function createWakeEngine(options) {
|
|
|
134
134
|
};
|
|
135
135
|
return yield* Effect.gen(function* () {
|
|
136
136
|
const store = yield* EventStoreTag;
|
|
137
|
-
const secrets = store.runSecrets ? yield* store.runSecrets.get(runId) : {};
|
|
138
137
|
const runInContext = Effect.runPromiseWith(yield* Effect.context());
|
|
139
138
|
executionContext.liveStore = store;
|
|
140
139
|
let finalState;
|
|
@@ -158,6 +157,8 @@ export function createWakeEngine(options) {
|
|
|
158
157
|
cursor = yield* applyAppend(store, runId, cursor, stripSeq(events), appended);
|
|
159
158
|
}
|
|
160
159
|
cursor = yield* closeLaunchedRuns(store, runId, cursor);
|
|
160
|
+
// A finished run starts no more attempts, so nothing it holds is needed again.
|
|
161
|
+
yield* options.runSecrets.release(store, runId, cursor.state);
|
|
161
162
|
const nextDeadline = nextRuntimeDeadline(cursor.state, now);
|
|
162
163
|
if (nextDeadline !== undefined) {
|
|
163
164
|
yield* options.scheduler().schedule(runId, nextDeadline);
|
|
@@ -263,7 +264,6 @@ export function createWakeEngine(options) {
|
|
|
263
264
|
worker: options.worker,
|
|
264
265
|
now,
|
|
265
266
|
maxInFlightWorkerEffects: options.maxInFlightWorkerEffects,
|
|
266
|
-
secrets,
|
|
267
267
|
});
|
|
268
268
|
if (workerPlans.length > 0) {
|
|
269
269
|
for (const workerPlan of workerPlans) {
|
|
@@ -274,7 +274,12 @@ export function createWakeEngine(options) {
|
|
|
274
274
|
attempt: workerPlan.attempt,
|
|
275
275
|
now,
|
|
276
276
|
attributes: state.attributes ?? {},
|
|
277
|
-
secrets,
|
|
277
|
+
secrets: options.runSecrets.forAttempt(store, runId, state, {
|
|
278
|
+
effectId: workerPlan.item.effectId,
|
|
279
|
+
attempt: workerPlan.attempt,
|
|
280
|
+
type: workerPlan.item.effect.type,
|
|
281
|
+
threadId: workerPlan.item.threadId,
|
|
282
|
+
}),
|
|
278
283
|
trace: state.startIdentity?.trace ?? null,
|
|
279
284
|
retry: workerPlan.retry,
|
|
280
285
|
});
|
|
@@ -290,7 +295,11 @@ export function createWakeEngine(options) {
|
|
|
290
295
|
const queuedAppend = yield* appendObserved(store, runId, stripSeq([workerPlan.queuedEvent]));
|
|
291
296
|
cursor = yield* applyAppend(store, runId, cursor, stripSeq([workerPlan.queuedEvent]), queuedAppend);
|
|
292
297
|
}
|
|
293
|
-
|
|
298
|
+
// Only an in-memory transport passes these on. One that persists the task drops
|
|
299
|
+
// them, and its worker asks for the attempt's secrets once it has started.
|
|
300
|
+
const dispatchEvent = yield* dispatchWorkerEffect(runId, hasEntries(admission.secrets)
|
|
301
|
+
? { ...workerPlan, task: { ...workerPlan.task, secrets: admission.secrets } }
|
|
302
|
+
: workerPlan, options.worker, now);
|
|
294
303
|
const dispatchAppend = yield* appendObserved(store, runId, stripSeq([dispatchEvent]));
|
|
295
304
|
cursor = yield* applyAppend(store, runId, cursor, stripSeq([dispatchEvent]), dispatchAppend);
|
|
296
305
|
}
|
|
@@ -387,11 +396,13 @@ export function createWakeEngine(options) {
|
|
|
387
396
|
observe,
|
|
388
397
|
launcher: options.launcher(),
|
|
389
398
|
};
|
|
399
|
+
const dispatchState = cursor.state;
|
|
390
400
|
const runContext = {
|
|
391
|
-
correlationId:
|
|
392
|
-
attributes:
|
|
393
|
-
|
|
394
|
-
|
|
401
|
+
correlationId: dispatchState.startIdentity?.correlationId ?? runId,
|
|
402
|
+
attributes: dispatchState.attributes ?? {},
|
|
403
|
+
secretsFor: (attempt) => options.runSecrets.forAttempt(store, runId, dispatchState, attempt),
|
|
404
|
+
secretsForChild: (child) => options.runSecrets.forChild(store, runId, dispatchState, child),
|
|
405
|
+
trace: dispatchState.startIdentity?.trace ?? null,
|
|
395
406
|
};
|
|
396
407
|
// One fiber per (thread, causingSeq) group keeps in-group order and frees the
|
|
397
408
|
// wake loop to plan other threads while a group is still running.
|
|
@@ -484,6 +495,9 @@ export function createWakeEngine(options) {
|
|
|
484
495
|
}
|
|
485
496
|
if (isRunTerminal(cursor.state)) {
|
|
486
497
|
cursor = yield* closeLaunchedRuns(store, runId, cursor);
|
|
498
|
+
// The run finished in this wake. A wake of a run that had already finished does the
|
|
499
|
+
// same above, which covers a host that stopped between the two.
|
|
500
|
+
yield* options.runSecrets.release(store, runId, cursor.state);
|
|
487
501
|
}
|
|
488
502
|
// Snapshot on park: the next wake (on any instance) starts from here.
|
|
489
503
|
cursor = yield* persistSnapshot(store, runId, cursor);
|
|
@@ -3,6 +3,7 @@ import { EventStoreTag, type ComposedRegistry, type WorkerCallback, type WorkerC
|
|
|
3
3
|
import type { RunIngress } from './ingress';
|
|
4
4
|
import { type RuntimeObserver } from './observer';
|
|
5
5
|
import type { RuntimeRepository } from './repository';
|
|
6
|
+
import { type RunSecrets } from './run-secrets';
|
|
6
7
|
import type { LoomsRuntime } from './types';
|
|
7
8
|
export interface WorkerCallbacksOptions {
|
|
8
9
|
readonly registry: ComposedRegistry;
|
|
@@ -10,17 +11,18 @@ export interface WorkerCallbacksOptions {
|
|
|
10
11
|
readonly withRunIngress: RunIngress;
|
|
11
12
|
readonly observer?: RuntimeObserver;
|
|
12
13
|
readonly wake: LoomsRuntime['wake'];
|
|
14
|
+
readonly runSecrets: RunSecrets;
|
|
13
15
|
}
|
|
14
16
|
export declare function createWorkerCallbacks(options: WorkerCallbacksOptions): {
|
|
15
17
|
workerCallback: (runId: string, callback: WorkerCallbackInput) => Effect.Effect<WorkerCallbackResult, import("@swirls/looms/core").DefinitionResolveError | import("./errors").DuplicateEffectDispatchError | Error | import("@swirls/looms/core").EventPayloadTooLargeError | import("@swirls/looms/core").EventStoreConflictError | import("@swirls/looms/core").EventStoreError | import("@swirls/looms/core").EventStoreFencedError | import("@swirls/looms/core").EventStoreTrimmedError | import("@swirls/looms/core").EventStoreTruncationError | import("./errors").MaxWakeIterationsError | import("./ingress").RunOverloadedError | import("./errors").RuntimeExecutionError, EventStoreTag>;
|
|
16
18
|
workerSecrets: (runId: string, callback: WorkerCallback) => Effect.Effect<{
|
|
17
19
|
status: "stale";
|
|
18
|
-
secrets?: undefined;
|
|
19
20
|
} | {
|
|
20
21
|
status: "cancelled";
|
|
21
|
-
secrets?: undefined;
|
|
22
22
|
} | {
|
|
23
23
|
status: "accepted";
|
|
24
24
|
secrets: import("@swirls/looms/core").SecretContext;
|
|
25
|
+
} | {
|
|
26
|
+
status: "unavailable";
|
|
25
27
|
}, Error | import("@swirls/looms/core").EventStoreError, EventStoreTag>;
|
|
26
28
|
};
|
|
@@ -3,6 +3,7 @@ import { createEvent, EventStoreTag, isRunTerminal, } from '@swirls/looms/core';
|
|
|
3
3
|
import { materializeEffectOutcome } from './helpers.js';
|
|
4
4
|
import { notifyObserver } from './observer.js';
|
|
5
5
|
import { planAttemptFailure } from './retry-policy.js';
|
|
6
|
+
import { SecretProviderError } from './run-secrets.js';
|
|
6
7
|
const WORKER_ORIGIN = { type: 'external', actorId: 'worker' };
|
|
7
8
|
/** The earliest of the start-to-close cap and the next heartbeat deadline. */
|
|
8
9
|
function workerDeadline(retry, startedAt, now) {
|
|
@@ -190,8 +191,20 @@ export function createWorkerCallbacks(options) {
|
|
|
190
191
|
if (execution.status !== 'started' && execution.status !== 'heartbeat') {
|
|
191
192
|
return { status: 'stale' };
|
|
192
193
|
}
|
|
193
|
-
const
|
|
194
|
-
|
|
194
|
+
const item = state.outstandingEffects.find((candidate) => candidate.effectId === callback.effectId);
|
|
195
|
+
if (!item) {
|
|
196
|
+
return { status: 'stale' };
|
|
197
|
+
}
|
|
198
|
+
// A provider failure is not a transport failure: the worker fails this attempt and the
|
|
199
|
+
// retry policy decides whether another one asks again.
|
|
200
|
+
return yield* options.runSecrets
|
|
201
|
+
.forAttempt(store, runId, state, {
|
|
202
|
+
effectId: callback.effectId,
|
|
203
|
+
attempt: callback.attempt,
|
|
204
|
+
type: item.effect.type,
|
|
205
|
+
threadId: item.threadId,
|
|
206
|
+
})
|
|
207
|
+
.pipe(Effect.map((secrets) => ({ status: 'accepted', secrets })), Effect.catchIf((error) => error instanceof SecretProviderError, () => Effect.succeed({ status: 'unavailable' })));
|
|
195
208
|
});
|
|
196
209
|
return { workerCallback: applyWorkerCallback, workerSecrets };
|
|
197
210
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Effect } from 'effect';
|
|
2
|
-
import { type ComposedRegistry, type EffectDefinition, type EffectExecutionRecord, type EffectPlacement, type EventEnvelope, type OutstandingEffect, type RetryPolicy, type RunState
|
|
2
|
+
import { type ComposedRegistry, type EffectDefinition, type EffectExecutionRecord, type EffectPlacement, type EventEnvelope, type OutstandingEffect, type RetryPolicy, type RunState } from '@swirls/looms/core';
|
|
3
3
|
import type { EffectWorker, EffectWorkerTask } from './types';
|
|
4
4
|
/** Caps how many times one attempt's unacknowledged dispatch can be deferred before parking as ambiguous. */
|
|
5
5
|
export declare const DEFAULT_MAX_WORKER_DISPATCH_DEFERRALS = 32;
|
|
@@ -32,7 +32,6 @@ export declare function planWorkerEffects(input: {
|
|
|
32
32
|
readonly worker?: EffectWorker;
|
|
33
33
|
readonly now: number;
|
|
34
34
|
readonly maxInFlightWorkerEffects?: number;
|
|
35
|
-
readonly secrets?: SecretContext;
|
|
36
35
|
}): ReadonlyArray<WorkerEffectDispatchPlan>;
|
|
37
36
|
/**
|
|
38
37
|
* Hand a planned attempt to the worker.
|
|
@@ -102,7 +102,6 @@ export function planWorkerEffects(input) {
|
|
|
102
102
|
}),
|
|
103
103
|
task: workerTask(input.runId, item, attempt, {
|
|
104
104
|
details: existing?.heartbeatDetails,
|
|
105
|
-
secrets: input.secrets,
|
|
106
105
|
attributes: input.state.attributes,
|
|
107
106
|
trace: input.state.startIdentity?.trace,
|
|
108
107
|
retry,
|