@supacloud/commands 0.7.1 → 0.8.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/README.md CHANGED
@@ -56,6 +56,44 @@ The storage interfaces are owned by contracts and re-exported here as types.
56
56
  Other stores must provide equivalent transaction and receipt guarantees; merely
57
57
  implementing the TypeScript interface does not prove persistence correctness.
58
58
 
59
+ ### Definitive Remote Rejection
60
+
61
+ `createExternalCommand` accepts an optional `rejection` policy alongside the
62
+ existing success `audit`. This is a durable outcome, not just an HTTP error
63
+ mapping. Configure it only when a downstream adapter can prove that the specific
64
+ dispatch was rejected before any business effect:
65
+
66
+ ```ts
67
+ rejection: {
68
+ isDefinitiveWriteFailure: (error) =>
69
+ error instanceof ProviderRefusedBeforeEffect,
70
+ audit: {
71
+ event: "webhook.update.rejected",
72
+ details: (input) => ({ target: input.id }),
73
+ },
74
+ },
75
+ ```
76
+
77
+ `ProviderRefusedBeforeEffect` represents an application-owned, trusted adapter
78
+ error. Do not classify an arbitrary HTTP 401/403/409 as definitive: an upstream
79
+ may already have applied the write before a later audit or response failed.
80
+ Network failures, timeouts and classifier exceptions still use read-only
81
+ reconciliation. An authoritative match can confirm the operation; otherwise its
82
+ outcome stays unknown. There is no automatic redispatch.
83
+
84
+ The store must support `session.reject`; opt-in without that capability fails
85
+ before inserting an intent or sending. The rejection audit and
86
+ `{ status: "rejected", audit: "complete" }` receipt commit atomically. No success
87
+ `result` is present. A failed rejection transaction reports
88
+ `COMMAND_OUTCOME_UNKNOWN`, never a definitive denial. The optional rejection
89
+ audit `write(transaction, input)` must use that same local transaction, not call
90
+ a remote audit service.
91
+
92
+ Repeated execution, lookup and recovery preserve the rejected terminal receipt
93
+ and still enforce authorization and operation identity. A `rejected` receipt is
94
+ distinct from a preflight `COMMAND_REJECTED` exception: it is durable evidence for
95
+ that operation, not permission to generate a new key and blindly retry.
96
+
59
97
  ## Recovery
60
98
 
61
99
  Interactive methods reauthorize the original actor. Worker `recover` requires
@@ -66,13 +104,15 @@ assumes that a cancelled or failed request rolled back.
66
104
  Pass `supacloud.workflows` as the handler's `workflows` port. The existing dispatcher
67
105
  routes reconcile steps to `run(claim)` and other steps to their registered handlers.
68
106
  PGMQ/Workflow owns delivery, visibility, attempts and dead-letter state. Completion
69
- requires confirmed business output and complete audit, not merely a successful
70
- lookup call. Bound lookup duration and monitor failed/unknown operations.
107
+ requires a confirmed or rejected terminal receipt and complete audit, not merely
108
+ a successful lookup call. A completed recovery workflow retains `rejected` in its
109
+ output and does not imply business success. Bound lookup duration and monitor
110
+ failed/unknown operations.
71
111
 
72
112
  Redaction keeps fingerprints and receipts: same-input explicit replay deduplicates;
73
113
  different input conflicts; reference-only lookup returns `COMMAND_INPUT_EXPIRED`.
74
114
  Never issue a new operation just because the old input expired.
75
- Already confirmed/audited receipts can still acknowledge a delayed recovery step
115
+ Already confirmed or rejected, audited receipts can still acknowledge a delayed recovery step
76
116
  after input redaction. Retention is a separate maintenance operation.
77
117
 
78
118
  See [breaking changes, schema upgrade, release and rollback](../../docs/command-migration.md).
@@ -11,6 +11,14 @@ type ExternalCommandDefinition<Input, Result, Store extends CommandStore<unknown
11
11
  send(input: Input, dispatch: ExternalDispatch): Promise<unknown>;
12
12
  lookup(input: Input, dispatch: ExternalDispatch): Promise<unknown>;
13
13
  matches(input: Input, result: Result): boolean;
14
+ rejection?: {
15
+ isDefinitiveWriteFailure(error: unknown): boolean;
16
+ audit: {
17
+ event: string;
18
+ details(input: Input): unknown;
19
+ write?(transaction: TransactionOf<Store>, input: Input): Promise<void>;
20
+ };
21
+ };
14
22
  };
15
23
  export declare function createExternalCommand<Input, Result, Store extends CommandStore<unknown>>(definition: ExternalCommandDefinition<Input, Result, Store>): {
16
24
  kind: "external";
package/dist/index.js CHANGED
@@ -332,9 +332,12 @@ function createTransactionalCommand(definition) {
332
332
  };
333
333
  }
334
334
  // src/external.ts
335
- import { CommandError as CommandError3, canonicalCommandJson as canonicalCommandJson3, decodeDurableCommandReceipt as decodeDurableCommandReceipt2 } from "@supacloud/contracts";
335
+ import { CommandError as CommandError3, canonicalCommandJson as canonicalCommandJson3, commandIdentifier as commandIdentifier2, decodeDurableCommandReceipt as decodeDurableCommandReceipt2 } from "@supacloud/contracts";
336
336
  function createExternalCommand(definition) {
337
337
  const context = commandContext(definition);
338
+ const rejection = definition.rejection;
339
+ if (rejection !== undefined)
340
+ commandIdentifier2(rejection.audit.event);
338
341
  const read = async (identity, key, value, principal) => {
339
342
  const request = await context.prepare(identity, key, value);
340
343
  return context.transaction(async (session) => {
@@ -359,6 +362,8 @@ function createExternalCommand(definition) {
359
362
  const before = await read(identity, key, value, principal);
360
363
  if (before === null)
361
364
  return null;
365
+ if (before.status === "rejected")
366
+ return before;
362
367
  let confirmation;
363
368
  if (before.status !== "confirmed") {
364
369
  try {
@@ -369,6 +374,9 @@ function createExternalCommand(definition) {
369
374
  }
370
375
  const receipt = await context.transaction(async (session) => {
371
376
  await context.lock(session, request, principal);
377
+ const current = await context.find(session, request, "external");
378
+ if (current === null || current.status === "confirmed" || current.status === "rejected")
379
+ return current;
372
380
  if (confirmation !== undefined)
373
381
  await session.confirm(request.reference, confirmation.raw);
374
382
  else if (before.status !== "confirmed")
@@ -396,6 +404,9 @@ function createExternalCommand(definition) {
396
404
  const existing = await context.find(session, request, "external");
397
405
  if (existing !== null)
398
406
  return { fresh: false, receipt: existing };
407
+ if (rejection !== undefined && typeof session.reject !== "function") {
408
+ throw new CommandError3("COMMAND_UNAVAILABLE");
409
+ }
399
410
  await context.insert(session, request, "external");
400
411
  const receipt = await context.find(session, request, "external");
401
412
  if (receipt === null)
@@ -409,7 +420,36 @@ function createExternalCommand(definition) {
409
420
  idempotencyKey: acquired.receipt.dispatchKey,
410
421
  ...signal === undefined ? {} : { signal }
411
422
  });
412
- } catch {}
423
+ } catch (error) {
424
+ let definitive = false;
425
+ try {
426
+ definitive = rejection?.isDefinitiveWriteFailure(error) === true;
427
+ } catch {}
428
+ if (definitive && rejection !== undefined) {
429
+ try {
430
+ return await context.transaction(async (session) => {
431
+ await context.lock(session, request);
432
+ const current = await context.find(session, request, "external");
433
+ if (current === null)
434
+ throw new CommandError3("COMMAND_RECEIPT_INVALID");
435
+ if (current.status === "confirmed" || current.status === "rejected")
436
+ return current;
437
+ if (typeof session.reject !== "function")
438
+ throw new CommandError3("COMMAND_UNAVAILABLE");
439
+ const details = JSON.parse(canonicalCommandJson3(rejection.audit.details(request.input)));
440
+ await rejection.audit.write?.(session.transaction, request.input);
441
+ await session.audit(request.reference, rejection.audit.event, details);
442
+ await session.reject(request.reference);
443
+ const rejected = await context.find(session, request, "external");
444
+ if (rejected?.status !== "rejected")
445
+ throw new CommandError3("COMMAND_RECEIPT_INVALID");
446
+ return rejected;
447
+ });
448
+ } catch {
449
+ throw new CommandError3("COMMAND_OUTCOME_UNKNOWN");
450
+ }
451
+ }
452
+ }
413
453
  try {
414
454
  const receipt = await reconcile(identity, key, request.input);
415
455
  if (receipt === null)
@@ -444,11 +484,16 @@ function createExternalCommand(definition) {
444
484
  throw new CommandError3("COMMAND_REJECTED");
445
485
  await checkAuthorization(() => authorize(principal, reference, session.transaction));
446
486
  const stored = await session.read(reference);
447
- if (stored?.receipt.status !== "confirmed" || stored.receipt.audit !== "complete")
487
+ if (stored === null || stored.receipt.audit !== "complete" || stored.receipt.status !== "confirmed" && stored.receipt.status !== "rejected")
448
488
  return null;
449
489
  if (stored.kind !== "external")
450
490
  throw new CommandError3("COMMAND_RECEIPT_INVALID");
451
- return decodeDurableCommandReceipt2(stored.receipt, definition.result);
491
+ const receipt = decodeDurableCommandReceipt2(stored.receipt, definition.result);
492
+ for (const field of ["tenantId", "actorId", "command", "operationId"]) {
493
+ if (receipt[field] !== reference[field])
494
+ throw new CommandError3("COMMAND_RECEIPT_INVALID");
495
+ }
496
+ return receipt;
452
497
  });
453
498
  if (completed !== null)
454
499
  return completed;
@@ -458,7 +503,7 @@ function createExternalCommand(definition) {
458
503
  };
459
504
  }
460
505
  // src/recovery.ts
461
- import { CommandError as CommandError4, commandIdentifier as commandIdentifier2, decodeCommandJson, decodeDurableCommandReceipt as decodeDurableCommandReceipt3 } from "@supacloud/contracts";
506
+ import { CommandError as CommandError4, commandIdentifier as commandIdentifier3, decodeCommandJson, decodeDurableCommandReceipt as decodeDurableCommandReceipt3 } from "@supacloud/contracts";
462
507
  function decodeClaim(value) {
463
508
  if (!value || typeof value !== "object" || !("status" in value) || value.status !== "claimed" || !("workflowName" in value) || !("workflowVersion" in value) || value.workflowVersion !== "1" || !("stepKey" in value) || value.stepKey !== "reconcile" || !("runId" in value) || !("input" in value) || !("stepId" in value) || !("messageId" in value) || !("attempt" in value) || !("workerId" in value) || typeof value.attempt !== "number" || !Number.isSafeInteger(value.attempt) || value.attempt < 1 || typeof value.messageId !== "string" || !/^[1-9][0-9]*$/.test(value.messageId)) {
464
509
  throw new TypeError("Invalid command recovery claim");
@@ -467,29 +512,29 @@ function decodeClaim(value) {
467
512
  if (!input || typeof input !== "object" || !("tenantId" in input) || !("actorId" in input) || !("command" in input) || !("operationId" in input) || !("commandId" in input)) {
468
513
  throw new TypeError("Invalid command recovery reference");
469
514
  }
470
- const commandId = commandIdentifier2(input.commandId);
515
+ const commandId = commandIdentifier3(input.commandId);
471
516
  if (value.runId !== commandId)
472
517
  throw new TypeError("Mismatched command workflow");
473
518
  const reference = {
474
- tenantId: commandIdentifier2(input.tenantId),
475
- actorId: commandIdentifier2(input.actorId),
476
- command: commandIdentifier2(input.command),
477
- operationId: commandIdentifier2(input.operationId)
519
+ tenantId: commandIdentifier3(input.tenantId),
520
+ actorId: commandIdentifier3(input.actorId),
521
+ command: commandIdentifier3(input.command),
522
+ operationId: commandIdentifier3(input.operationId)
478
523
  };
479
524
  if (value.workflowName !== "supacloud.command.reconcile" && value.workflowName !== `command.${reference.command}`) {
480
525
  throw new TypeError("Invalid recovery workflow");
481
526
  }
482
527
  const attempt = {
483
- stepId: commandIdentifier2(value.stepId),
528
+ stepId: commandIdentifier3(value.stepId),
484
529
  messageId: value.messageId,
485
530
  attempt: value.attempt,
486
- workerId: commandIdentifier2(value.workerId)
531
+ workerId: commandIdentifier3(value.workerId)
487
532
  };
488
533
  return { commandId, reference, attempt };
489
534
  }
490
535
  function createCommandRecoveryHandler(options) {
491
- const tenantId = commandIdentifier2(options.tenantId);
492
- const principal = { subject: commandIdentifier2(options.principal.subject) };
536
+ const tenantId = commandIdentifier3(options.tenantId);
537
+ const principal = { subject: commandIdentifier3(options.principal.subject) };
493
538
  const commands = { ...options.commands }, { workflows, authorize } = options;
494
539
  const observer = options.observer;
495
540
  const delaySeconds = options.retryDelaySeconds;
@@ -552,8 +597,8 @@ function createCommandRecoveryHandler(options) {
552
597
  }), "COMMAND_RECOVERY_FAILED");
553
598
  return "retry";
554
599
  }
555
- if (receipt?.status === "confirmed" && receipt.audit === "complete") {
556
- const output = { commandId, status: "confirmed", audit: "complete" };
600
+ if ((receipt?.status === "confirmed" || receipt?.status === "rejected") && receipt.audit === "complete") {
601
+ const output = { commandId, status: receipt.status, audit: "complete" };
557
602
  await observe("complete", () => workflows.complete({ ...attempt, stepOutput: output, runOutput: output }));
558
603
  return "completed";
559
604
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/commands",
3
- "version": "0.7.1",
3
+ "version": "0.8.0",
4
4
  "description": "Storage-independent durable command execution and recovery",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -31,7 +31,7 @@
31
31
  "prepublishOnly": "bun run build"
32
32
  },
33
33
  "dependencies": {
34
- "@supacloud/contracts": "0.5.1"
34
+ "@supacloud/contracts": "0.6.0"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@sinclair/typebox": "0.34.52",