@moinulmoin/eden-world-cloudflare 0.11.0 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -90,7 +90,7 @@ export function createWorld(options = {}) {
90
90
  };
91
91
  return {
92
92
  specVersion: SPEC_VERSION_CURRENT,
93
- capabilities: { deploymentAffinity: true, hookForceClaim: true, hookRetention: { active: true } },
93
+ capabilities: { deploymentAffinity: true, hookForceClaim: true, hookRetention: { active: true }, atomicStartHook: { active: true } },
94
94
  runs: methods("runs", ["get", "getMany", "list", "experimentalSetAttributes"]),
95
95
  steps: methods("steps", ["get", "list"]),
96
96
  events: methods("events", ["create", "get", "list", "listByCorrelationId"]),
@@ -45,6 +45,7 @@ export declare class WorldCore {
45
45
  private readonly waitUntil;
46
46
  private readonly retireDeployment;
47
47
  private readonly currentDeploymentId;
48
+ private readonly isDeploymentRemoved;
48
49
  constructor(opts: {
49
50
  sql: SqlExec;
50
51
  delivery: QueueDelivery;
@@ -53,6 +54,7 @@ export declare class WorldCore {
53
54
  waitUntil?: (promise: Promise<void>) => void;
54
55
  retireDeployment?: (deploymentId: string) => Promise<void>;
55
56
  currentDeploymentId?: string;
57
+ isDeploymentRemoved?: (deploymentId: string) => boolean;
56
58
  });
57
59
  private rows;
58
60
  private atomic;
@@ -84,6 +86,8 @@ export declare class WorldCore {
84
86
  private listEvents;
85
87
  private attributes;
86
88
  private forceRefusal;
89
+ private rejectStartHook;
90
+ private admitStartHook;
87
91
  private createRun;
88
92
  private create;
89
93
  private createSync;
@@ -1,8 +1,8 @@
1
1
  // Storage semantics ported from @workflow/world-postgres (Apache-2.0).
2
2
  import { decode, encode } from 'cbor-x';
3
3
  import { monotonicFactory } from 'ulid';
4
- import { EntityConflictError, HookForceClaimedError, HookNotFoundError, RunExpiredError, RunNotSupportedError, TooEarlyError, WorkflowRunNotFoundError, WorkflowWorldError } from '@workflow/errors';
5
- import { EventSchema, HookSchema, StepSchema, WorkflowRunSchema, SPEC_VERSION_CURRENT, SPEC_VERSION_LEGACY, SPEC_VERSION_SUPPORTS_HOOK_FORCE_CLAIM, slotToEventId, eventIdToSlot, stripEventDataRefs, validateAttributeChanges, validateUlidTimestamp, isTerminalWorkflowRunStatus, isTerminalStepStatus, isChildEntityCreationEvent, isTerminalRunEventType, requiresNewerWorld, isLegacySpecVersion } from '@workflow/world';
4
+ import { EntityConflictError, HookConflictError, HookForceClaimedError, HookNotFoundError, RunExpiredError, RunNotSupportedError, TooEarlyError, WorkflowRunNotFoundError, WorkflowWorldError } from '@workflow/errors';
5
+ import { EventSchema, HookSchema, StepSchema, WorkflowRunSchema, StartHookSchema, START_HOOK_CANDIDATE_MAX_AGE_MS, startHookId, isStartHookId, ulidToDate, SPEC_VERSION_CURRENT, SPEC_VERSION_LEGACY, SPEC_VERSION_SUPPORTS_HOOK_FORCE_CLAIM, slotToEventId, eventIdToSlot, stripEventDataRefs, validateAttributeChanges, validateUlidTimestamp, isTerminalWorkflowRunStatus, isTerminalStepStatus, isChildEntityCreationEvent, isTerminalRunEventType, requiresNewerWorld, isLegacySpecVersion } from '@workflow/world';
6
6
  export async function callDeploymentControlRpc(options) {
7
7
  const response = await fetch(new URL('/__eden/world/rpc', options.origin), {
8
8
  method: 'POST',
@@ -43,6 +43,7 @@ export class WorldCore {
43
43
  waitUntil;
44
44
  retireDeployment;
45
45
  currentDeploymentId;
46
+ isDeploymentRemoved;
46
47
  constructor(opts) {
47
48
  this.sql = opts.sql;
48
49
  this.delivery = opts.delivery;
@@ -51,6 +52,7 @@ export class WorldCore {
51
52
  this.waitUntil = opts.waitUntil ?? (() => { });
52
53
  this.retireDeployment = opts.retireDeployment;
53
54
  this.currentDeploymentId = opts.currentDeploymentId;
55
+ this.isDeploymentRemoved = opts.isDeploymentRemoved;
54
56
  }
55
57
  rows(query, ...args) { return this.sql.exec(query, ...args).toArray(); }
56
58
  atomic(fn) { return this.sql.transactionSync ? this.sql.transactionSync(fn) : fn(); }
@@ -69,6 +71,9 @@ export class WorldCore {
69
71
  'CREATE TABLE IF NOT EXISTS workflow_hooks (hook_id TEXT PRIMARY KEY, run_id TEXT NOT NULL, token TEXT NOT NULL, data BLOB NOT NULL)',
70
72
  'CREATE INDEX IF NOT EXISTS workflow_hooks_run ON workflow_hooks(run_id)',
71
73
  'CREATE INDEX IF NOT EXISTS workflow_hooks_token ON workflow_hooks(token)',
74
+ // Decisions outlive Hook disposal and token takeover; retries must never
75
+ // turn a refused candidate into a second run.
76
+ 'CREATE TABLE IF NOT EXISTS workflow_start_hook_admissions (run_id TEXT PRIMARY KEY, token TEXT NOT NULL, conflicting_run_id TEXT, cancelled INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL)',
72
77
  // Routing tombstones outlive invocation-data retention; never store payloads here.
73
78
  'CREATE TABLE IF NOT EXISTS workflow_hook_disposals (run_id TEXT NOT NULL, hook_id TEXT NOT NULL, token TEXT NOT NULL, claimed_run_id TEXT NOT NULL, claimed_hook_id TEXT NOT NULL, PRIMARY KEY(run_id,hook_id))',
74
79
  'CREATE TABLE IF NOT EXISTS workflow_waits (wait_id TEXT PRIMARY KEY, run_id TEXT NOT NULL, data BLOB NOT NULL)',
@@ -113,8 +118,8 @@ export class WorldCore {
113
118
  run(id) { const value = unpack(this.rows('SELECT data FROM workflow_runs WHERE id = ?', id)[0]); if (!value)
114
119
  throw new WorkflowRunNotFoundError(id); return WorkflowRunSchema.parse(value); }
115
120
  assertDeploymentActive(deploymentId) {
116
- if (this.rows('SELECT deployment_id FROM workflow_retired_deployments WHERE deployment_id=?', deploymentId).length)
117
- throw new WorkflowWorldError(`Deployment ${deploymentId} has been retired`, { status: 409 });
121
+ if (this.isDeploymentRemoved?.(deploymentId) || this.rows('SELECT deployment_id FROM workflow_retired_deployments WHERE deployment_id=?', deploymentId).length)
122
+ throw new WorkflowWorldError(`Deployment ${deploymentId} has been retired; its sessions ended. Start a new session.`, { status: 409 });
118
123
  }
119
124
  deliverySettled(messageId, attempt) {
120
125
  // Called by the receiving Container DO through the current World actor.
@@ -370,6 +375,48 @@ export class WorldCore {
370
375
  }
371
376
  throw new HookNotFoundError(hookId);
372
377
  }
378
+ rejectStartHook(reason) {
379
+ throw new WorkflowWorldError(`Start Hook admission rejected: ${reason}`, { status: 400, code: 'START_HOOK_ADMISSION_REJECTED', reason });
380
+ }
381
+ admitStartHook(id, request) {
382
+ if (request.eventType !== 'run_created' && request.eventType !== 'run_started')
383
+ return { request };
384
+ const input = request.eventData;
385
+ const recorded = this.rows('SELECT * FROM workflow_start_hook_admissions WHERE run_id=?', id)[0];
386
+ if (recorded?.cancelled)
387
+ this.rejectStartHook('expired');
388
+ if (input?.startHook === undefined) {
389
+ if (recorded && !this.rows('SELECT id FROM workflow_runs WHERE id=?', id).length)
390
+ return { request, error: new HookConflictError(String(recorded.token), String(recorded.conflicting_run_id)) };
391
+ return { request };
392
+ }
393
+ const parsed = StartHookSchema.safeParse(input.startHook);
394
+ if (!parsed.success)
395
+ this.rejectStartHook('invalid');
396
+ const startHook = { ...parsed.data, hookId: startHookId(id) };
397
+ if (parsed.data.hookId && parsed.data.hookId !== startHook.hookId)
398
+ this.rejectStartHook('invalid');
399
+ if (startHook.tokenRetentionUntil && startHook.tokenRetentionUntil.getTime() > this.now() + 30 * 86400000)
400
+ this.rejectStartHook('invalid');
401
+ const candidateTime = ulidToDate(id.replace(/^wrun_/, ''))?.getTime();
402
+ if (candidateTime === undefined || (this.now() - candidateTime > START_HOOK_CANDIDATE_MAX_AGE_MS && (request.eventType === 'run_created' || !this.rows('SELECT id FROM workflow_runs WHERE id=?', id).length)))
403
+ this.rejectStartHook('expired');
404
+ if (recorded) {
405
+ if (recorded.token !== startHook.token)
406
+ this.rejectStartHook('token_mismatch');
407
+ if (recorded.conflicting_run_id)
408
+ return { request, error: new HookConflictError(startHook.token, String(recorded.conflicting_run_id)) };
409
+ }
410
+ else {
411
+ if (this.rows('SELECT id FROM workflow_runs WHERE id=?', id).length)
412
+ this.rejectStartHook('ordinary_run');
413
+ const owner = this.findHook(startHook.token, true);
414
+ this.sql.exec('INSERT INTO workflow_start_hook_admissions(run_id,token,conflicting_run_id,created_at) VALUES(?,?,?,?)', id, startHook.token, owner?.runId ?? null, this.now());
415
+ if (owner)
416
+ return { request, error: new HookConflictError(startHook.token, owner.runId) };
417
+ }
418
+ return { request: { ...request, eventData: { ...input, startHook } } };
419
+ }
373
420
  createRun(runId, data) {
374
421
  if ((data.specVersion ?? SPEC_VERSION_CURRENT) > SPEC_VERSION_CURRENT)
375
422
  throw new RunNotSupportedError(data.specVersion, SPEC_VERSION_CURRENT);
@@ -381,6 +428,8 @@ export class WorldCore {
381
428
  const now = new Date(this.now());
382
429
  const run = WorkflowRunSchema.parse(compact({ runId, ...d, status: 'pending', attributes: d.attributes ?? {}, createdAt: now, updatedAt: now, specVersion: data.specVersion ?? SPEC_VERSION_CURRENT }));
383
430
  this.saveRun(run);
431
+ if (d.startHook)
432
+ this.saveHook(HookSchema.parse(compact({ ...d.startHook, runId, hookId: startHookId(runId), ownerId: '', projectId: '', environment: '', createdAt: now, specVersion: run.specVersion, isWebhook: false, isSystem: false })));
384
433
  this.sql.exec('INSERT INTO workflow_event_slots(run_id) VALUES(?)', runId);
385
434
  const event = this.insertEvent(runId, data);
386
435
  return { run, event };
@@ -389,10 +438,14 @@ export class WorldCore {
389
438
  const id = runId || (request.eventType === 'run_created' ? `wrun_${ulid(this.now())}` : '');
390
439
  if (!id)
391
440
  throw new Error('runId is required for non-run_created events');
441
+ const hasStartHook = (request.eventType === 'run_created' || request.eventType === 'run_started') && request.eventData?.startHook !== undefined;
392
442
  if (request.eventType === 'run_created' && runId) {
393
443
  const error = validateUlidTimestamp(id, 'wrun_');
394
- if (error)
444
+ if (error) {
445
+ if (hasStartHook)
446
+ this.rejectStartHook('expired');
395
447
  throw new WorkflowWorldError(error);
448
+ }
396
449
  }
397
450
  let digest;
398
451
  if (request.eventType === 'hook_received' && params?.resumeId) {
@@ -402,7 +455,22 @@ export class WorldCore {
402
455
  if (params.resumePayloadDigest && params.resumePayloadDigest !== digest)
403
456
  throw new WorkflowWorldError('Hook resume digest does not match its payload', { status: 422 });
404
457
  }
405
- return this.atomic(() => this.createSync(id, request, params, digest));
458
+ const result = this.atomic(() => {
459
+ const admission = this.admitStartHook(id, request);
460
+ // A refusal is a durable decision. Throw only after its transaction commits.
461
+ if (admission.error)
462
+ return admission.error;
463
+ if (request.eventType === 'run_cancelled' && !this.rows('SELECT id FROM workflow_runs WHERE id=?', id).length && this.rows('SELECT run_id FROM workflow_start_hook_admissions WHERE run_id=?', id).length) {
464
+ this.sql.exec('UPDATE workflow_start_hook_admissions SET cancelled=1 WHERE run_id=?', id);
465
+ return new WorkflowWorldError('Start Hook candidate cancelled', { status: 409, code: 'START_HOOK_CANDIDATE_CANCELLED' });
466
+ }
467
+ if (hasStartHook && request.eventType === 'run_created' && this.rows('SELECT id FROM workflow_runs WHERE id=?', id).length)
468
+ return this.eventResult(id, { run: this.run(id) }, params);
469
+ return this.createSync(id, admission.request, params, digest);
470
+ });
471
+ if (result instanceof Error)
472
+ throw result;
473
+ return result;
406
474
  }
407
475
  createSync(id, request, params, digest) {
408
476
  const now = new Date(this.now());
@@ -416,6 +484,8 @@ export class WorldCore {
416
484
  let stepCreated = false;
417
485
  const type = data.eventType;
418
486
  const correlationId = data.correlationId;
487
+ if (type === 'hook_created' && correlationId && isStartHookId(id, correlationId))
488
+ throw new WorkflowWorldError('The start Hook id is reserved for atomic admission', { status: 400 });
419
489
  if (type === 'run_created') {
420
490
  ({ run, event } = this.createRun(id, data));
421
491
  }
@@ -854,11 +924,23 @@ export class WorldCore {
854
924
  const body = sqlBytes(row.body);
855
925
  const message = this.queueMessage(body);
856
926
  const deploymentId = this.queueTarget(message, row.deployment_id == null ? undefined : String(row.deployment_id));
857
- this.assertDeploymentActive(deploymentId);
858
- this.sql.exec('UPDATE workflow_queue_messages SET deployment_id=? WHERE id=?', deploymentId, id);
859
927
  let transfer = this.rows('SELECT * FROM workflow_sandbox_transfers WHERE message_id=?', id)[0];
860
928
  const sandbox = transfer ? undefined : this.successorSandbox(message);
861
- const sourceDeploymentId = transfer ? String(transfer.source_deployment_id) : sandbox?.sourceDeploymentId ?? (row.source_deployment_id == null ? undefined : String(row.source_deployment_id));
929
+ const source = transfer ? String(transfer.source_deployment_id) : sandbox?.sourceDeploymentId ?? (row.source_deployment_id == null ? undefined : String(row.source_deployment_id));
930
+ if (this.isDeploymentRemoved?.(deploymentId) || (source && this.isDeploymentRemoved?.(source)) ||
931
+ this.rows('SELECT deployment_id FROM workflow_retired_deployments WHERE deployment_id=? OR deployment_id=?', deploymentId, source ?? deploymentId).length) {
932
+ // A removed deployment cannot ever accept this delivery again.
933
+ // Preserve run history, but settle the message instead of retrying.
934
+ this.atomic(() => {
935
+ this.sql.exec('UPDATE workflow_sandbox_transfers SET completed=-1 WHERE message_id=? AND completed=0', id);
936
+ this.deliverySettled(id, attempt);
937
+ this.sql.exec('UPDATE workflow_queue_messages SET completed=1,idempotency_key=NULL,lease_until=0 WHERE id=?', id);
938
+ });
939
+ return;
940
+ }
941
+ this.assertDeploymentActive(deploymentId);
942
+ this.sql.exec('UPDATE workflow_queue_messages SET deployment_id=? WHERE id=?', deploymentId, id);
943
+ const sourceDeploymentId = source;
862
944
  if (sandbox && sourceDeploymentId && sourceDeploymentId !== deploymentId) {
863
945
  this.assertDeploymentActive(sourceDeploymentId);
864
946
  this.sql.exec('UPDATE workflow_queue_messages SET source_deployment_id=? WHERE id=?', sourceDeploymentId, id);
@@ -934,7 +1016,7 @@ export class WorldCore {
934
1016
  if (this.currentDeploymentId && ids.includes(this.currentDeploymentId))
935
1017
  throw new WorkflowWorldError('Cannot retire the current deployment', { status: 409 });
936
1018
  const states = this.drainState(ids);
937
- if (ids.some(id => !states[id].drained))
1019
+ if (ids.some(id => !this.isDeploymentRemoved?.(id) && !states[id].drained))
938
1020
  throw new WorkflowWorldError('Cannot retire a deployment with live runs, queued messages, or unfinished transfers', { status: 409 });
939
1021
  if (!this.retireDeployment)
940
1022
  throw new WorkflowWorldError('Deployment retirement is unavailable', { status: 501 });
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@moinulmoin/eden-world-cloudflare",
3
- "version": "0.11.0",
3
+ "version": "0.11.2",
4
4
  "description": "Cloudflare Durable Object SQLite World for Eve workflows.",
5
5
  "eden": {
6
6
  "capabilities": {
7
7
  "deploymentAffinity": true,
8
- "worldRpcAuth": true
8
+ "worldRpcAuth": true,
9
+ "atomicStartHook": true
9
10
  }
10
11
  },
11
12
  "type": "module",