@moinulmoin/eden-world-cloudflare 0.11.0 → 0.11.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.
@@ -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"]),
@@ -84,6 +84,8 @@ export declare class WorldCore {
84
84
  private listEvents;
85
85
  private attributes;
86
86
  private forceRefusal;
87
+ private rejectStartHook;
88
+ private admitStartHook;
87
89
  private createRun;
88
90
  private create;
89
91
  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',
@@ -69,6 +69,9 @@ export class WorldCore {
69
69
  '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
70
  'CREATE INDEX IF NOT EXISTS workflow_hooks_run ON workflow_hooks(run_id)',
71
71
  'CREATE INDEX IF NOT EXISTS workflow_hooks_token ON workflow_hooks(token)',
72
+ // Decisions outlive Hook disposal and token takeover; retries must never
73
+ // turn a refused candidate into a second run.
74
+ '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
75
  // Routing tombstones outlive invocation-data retention; never store payloads here.
73
76
  '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
77
  'CREATE TABLE IF NOT EXISTS workflow_waits (wait_id TEXT PRIMARY KEY, run_id TEXT NOT NULL, data BLOB NOT NULL)',
@@ -370,6 +373,48 @@ export class WorldCore {
370
373
  }
371
374
  throw new HookNotFoundError(hookId);
372
375
  }
376
+ rejectStartHook(reason) {
377
+ throw new WorkflowWorldError(`Start Hook admission rejected: ${reason}`, { status: 400, code: 'START_HOOK_ADMISSION_REJECTED', reason });
378
+ }
379
+ admitStartHook(id, request) {
380
+ if (request.eventType !== 'run_created' && request.eventType !== 'run_started')
381
+ return { request };
382
+ const input = request.eventData;
383
+ const recorded = this.rows('SELECT * FROM workflow_start_hook_admissions WHERE run_id=?', id)[0];
384
+ if (recorded?.cancelled)
385
+ this.rejectStartHook('expired');
386
+ if (input?.startHook === undefined) {
387
+ if (recorded && !this.rows('SELECT id FROM workflow_runs WHERE id=?', id).length)
388
+ return { request, error: new HookConflictError(String(recorded.token), String(recorded.conflicting_run_id)) };
389
+ return { request };
390
+ }
391
+ const parsed = StartHookSchema.safeParse(input.startHook);
392
+ if (!parsed.success)
393
+ this.rejectStartHook('invalid');
394
+ const startHook = { ...parsed.data, hookId: startHookId(id) };
395
+ if (parsed.data.hookId && parsed.data.hookId !== startHook.hookId)
396
+ this.rejectStartHook('invalid');
397
+ if (startHook.tokenRetentionUntil && startHook.tokenRetentionUntil.getTime() > this.now() + 30 * 86400000)
398
+ this.rejectStartHook('invalid');
399
+ const candidateTime = ulidToDate(id.replace(/^wrun_/, ''))?.getTime();
400
+ 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)))
401
+ this.rejectStartHook('expired');
402
+ if (recorded) {
403
+ if (recorded.token !== startHook.token)
404
+ this.rejectStartHook('token_mismatch');
405
+ if (recorded.conflicting_run_id)
406
+ return { request, error: new HookConflictError(startHook.token, String(recorded.conflicting_run_id)) };
407
+ }
408
+ else {
409
+ if (this.rows('SELECT id FROM workflow_runs WHERE id=?', id).length)
410
+ this.rejectStartHook('ordinary_run');
411
+ const owner = this.findHook(startHook.token, true);
412
+ 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());
413
+ if (owner)
414
+ return { request, error: new HookConflictError(startHook.token, owner.runId) };
415
+ }
416
+ return { request: { ...request, eventData: { ...input, startHook } } };
417
+ }
373
418
  createRun(runId, data) {
374
419
  if ((data.specVersion ?? SPEC_VERSION_CURRENT) > SPEC_VERSION_CURRENT)
375
420
  throw new RunNotSupportedError(data.specVersion, SPEC_VERSION_CURRENT);
@@ -381,6 +426,8 @@ export class WorldCore {
381
426
  const now = new Date(this.now());
382
427
  const run = WorkflowRunSchema.parse(compact({ runId, ...d, status: 'pending', attributes: d.attributes ?? {}, createdAt: now, updatedAt: now, specVersion: data.specVersion ?? SPEC_VERSION_CURRENT }));
383
428
  this.saveRun(run);
429
+ if (d.startHook)
430
+ this.saveHook(HookSchema.parse(compact({ ...d.startHook, runId, hookId: startHookId(runId), ownerId: '', projectId: '', environment: '', createdAt: now, specVersion: run.specVersion, isWebhook: false, isSystem: false })));
384
431
  this.sql.exec('INSERT INTO workflow_event_slots(run_id) VALUES(?)', runId);
385
432
  const event = this.insertEvent(runId, data);
386
433
  return { run, event };
@@ -389,10 +436,14 @@ export class WorldCore {
389
436
  const id = runId || (request.eventType === 'run_created' ? `wrun_${ulid(this.now())}` : '');
390
437
  if (!id)
391
438
  throw new Error('runId is required for non-run_created events');
439
+ const hasStartHook = (request.eventType === 'run_created' || request.eventType === 'run_started') && request.eventData?.startHook !== undefined;
392
440
  if (request.eventType === 'run_created' && runId) {
393
441
  const error = validateUlidTimestamp(id, 'wrun_');
394
- if (error)
442
+ if (error) {
443
+ if (hasStartHook)
444
+ this.rejectStartHook('expired');
395
445
  throw new WorkflowWorldError(error);
446
+ }
396
447
  }
397
448
  let digest;
398
449
  if (request.eventType === 'hook_received' && params?.resumeId) {
@@ -402,7 +453,22 @@ export class WorldCore {
402
453
  if (params.resumePayloadDigest && params.resumePayloadDigest !== digest)
403
454
  throw new WorkflowWorldError('Hook resume digest does not match its payload', { status: 422 });
404
455
  }
405
- return this.atomic(() => this.createSync(id, request, params, digest));
456
+ const result = this.atomic(() => {
457
+ const admission = this.admitStartHook(id, request);
458
+ // A refusal is a durable decision. Throw only after its transaction commits.
459
+ if (admission.error)
460
+ return admission.error;
461
+ 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) {
462
+ this.sql.exec('UPDATE workflow_start_hook_admissions SET cancelled=1 WHERE run_id=?', id);
463
+ return new WorkflowWorldError('Start Hook candidate cancelled', { status: 409, code: 'START_HOOK_CANDIDATE_CANCELLED' });
464
+ }
465
+ if (hasStartHook && request.eventType === 'run_created' && this.rows('SELECT id FROM workflow_runs WHERE id=?', id).length)
466
+ return this.eventResult(id, { run: this.run(id) }, params);
467
+ return this.createSync(id, admission.request, params, digest);
468
+ });
469
+ if (result instanceof Error)
470
+ throw result;
471
+ return result;
406
472
  }
407
473
  createSync(id, request, params, digest) {
408
474
  const now = new Date(this.now());
@@ -416,6 +482,8 @@ export class WorldCore {
416
482
  let stepCreated = false;
417
483
  const type = data.eventType;
418
484
  const correlationId = data.correlationId;
485
+ if (type === 'hook_created' && correlationId && isStartHookId(id, correlationId))
486
+ throw new WorkflowWorldError('The start Hook id is reserved for atomic admission', { status: 400 });
419
487
  if (type === 'run_created') {
420
488
  ({ run, event } = this.createRun(id, data));
421
489
  }
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.1",
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",