@cadenza.io/core 3.25.1 → 3.26.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/dist/index.d.mts CHANGED
@@ -355,6 +355,7 @@ interface InquiryOptions {
355
355
  timeout?: number;
356
356
  rejectOnTimeout?: boolean;
357
357
  includePendingTasks?: boolean;
358
+ requireComplete?: boolean;
358
359
  }
359
360
  declare class InquiryBroker extends SignalEmitter {
360
361
  static instance_: InquiryBroker;
@@ -1070,14 +1071,14 @@ declare class Task extends SignalEmitter implements Graph {
1070
1071
  * @param {...string[]} signals - The array of signal names to observe.
1071
1072
  * @return {this} The current instance after adding the specified signals.
1072
1073
  */
1073
- doOn(...signals: string[]): this;
1074
+ doOn(...signals: SignalDefinitionInput[]): this;
1074
1075
  /**
1075
1076
  * Registers the specified signals to be emitted after the Task executes successfully and attaches them for further processing.
1076
1077
  *
1077
1078
  * @param {...string} signals - The list of signals to be registered for emission.
1078
1079
  * @return {this} The current instance for method chaining.
1079
1080
  */
1080
- emits(...signals: string[]): this;
1081
+ emits(...signals: SignalDefinitionInput[]): this;
1081
1082
  /**
1082
1083
  * Configures the instance to emit specified signals when the task execution fails.
1083
1084
  * A failure is defined as anything that does not return a successful result.
@@ -1085,14 +1086,14 @@ declare class Task extends SignalEmitter implements Graph {
1085
1086
  * @param {...string} signals - The names of the signals to emit upon failure.
1086
1087
  * @return {this} Returns the current instance for chaining.
1087
1088
  */
1088
- emitsOnFail(...signals: string[]): this;
1089
+ emitsOnFail(...signals: SignalDefinitionInput[]): this;
1089
1090
  /**
1090
1091
  * Attaches a signal to the current context and emits metadata if the register flag is set.
1091
1092
  *
1092
1093
  * @param {...string} signals - The names of the signals to attach.
1093
1094
  * @return {void} This method does not return a value.
1094
1095
  */
1095
- attachSignal(...signals: string[]): Task;
1096
+ attachSignal(...signals: SignalDefinitionInput[]): Task;
1096
1097
  /**
1097
1098
  * Unsubscribes the current instance from the specified signals.
1098
1099
  * This method removes the signals from the observedSignals set, unsubscribes
@@ -1485,6 +1486,22 @@ interface EmitOptions {
1485
1486
  throttleBatch?: number;
1486
1487
  flushStrategy?: string;
1487
1488
  }
1489
+ type SignalDeliveryMode = "single" | "broadcast";
1490
+ type SignalReceiverFilter = {
1491
+ serviceNames?: string[];
1492
+ serviceInstanceIds?: string[];
1493
+ origins?: string[];
1494
+ roles?: string[];
1495
+ protocols?: string[];
1496
+ runtimeStates?: string[];
1497
+ };
1498
+ type SignalMetadata = {
1499
+ deliveryMode?: SignalDeliveryMode;
1500
+ broadcastFilter?: SignalReceiverFilter | null;
1501
+ };
1502
+ type SignalDefinitionInput = string | ({
1503
+ name: string;
1504
+ } & SignalMetadata);
1488
1505
  type FlushStrategyName = string;
1489
1506
  interface FlushStrategy {
1490
1507
  intervalMs: number;
@@ -1513,12 +1530,17 @@ declare class SignalBroker {
1513
1530
  registered: boolean;
1514
1531
  }>;
1515
1532
  emittedSignalsRegistry: Set<string>;
1533
+ signalMetadataRegistry: Map<string, SignalMetadata>;
1516
1534
  private flushStrategies;
1517
1535
  private strategyData;
1518
1536
  private strategyTimers;
1519
1537
  private isStrategyFlushing;
1520
1538
  private readonly defaultStrategyName;
1521
1539
  constructor();
1540
+ private resolveSignalMetadataKey;
1541
+ private normalizeSignalMetadata;
1542
+ setSignalMetadata(signal: string, metadata?: SignalMetadata | null): void;
1543
+ getSignalMetadata(signal: string): SignalMetadata | undefined;
1522
1544
  logMemoryFootprint(label?: string): void;
1523
1545
  /**
1524
1546
  * Validates the provided signal name string to ensure it adheres to specific formatting rules.
@@ -1617,15 +1639,15 @@ declare class SignalBroker {
1617
1639
  * @param {string} signal - The name of the signal to be added.
1618
1640
  * @return {void} This method does not return any value.
1619
1641
  */
1620
- addSignal(signal: string): void;
1642
+ addSignal(signal: string, metadata?: SignalMetadata | null): void;
1621
1643
  /**
1622
1644
  * Observes a signal with a routine/task.
1623
1645
  * @param signal The signal (e.g., 'domain.action', 'domain.*' for wildcards).
1624
1646
  * @param routineOrTask The observer.
1625
1647
  * @edge Duplicates ignored; supports wildcards for broad listening.
1626
1648
  */
1627
- observe(signal: string, routineOrTask: Task | GraphRoutine): void;
1628
- registerEmittedSignal(signal: string): void;
1649
+ observe(signal: string, routineOrTask: Task | GraphRoutine, metadata?: SignalMetadata | null): void;
1650
+ registerEmittedSignal(signal: string, metadata?: SignalMetadata | null): void;
1629
1651
  /**
1630
1652
  * Unsubscribes a routine/task from a signal.
1631
1653
  * @param signal The signal.
@@ -2082,6 +2104,7 @@ declare class Actor<D extends Record<string, any> = AnyObject, R = AnyObject> {
2082
2104
  private readonly stateByKey;
2083
2105
  private readonly sessionByKey;
2084
2106
  private readonly idempotencyByKey;
2107
+ private readonly writeQueueByKey;
2085
2108
  private nextTaskBindingIndex;
2086
2109
  /**
2087
2110
  * Creates an actor instance and optionally materializes the default key.
@@ -2133,6 +2156,7 @@ declare class Actor<D extends Record<string, any> = AnyObject, R = AnyObject> {
2133
2156
  private ensureStateRecord;
2134
2157
  private touchSession;
2135
2158
  private runWithOptionalIdempotency;
2159
+ private runWithPerKeyWriteSerialization;
2136
2160
  private getActiveIdempotencyRecord;
2137
2161
  private persistDurableStateIfConfigured;
2138
2162
  private emitActorCreatedSignal;
@@ -2666,4 +2690,4 @@ declare class Cadenza {
2666
2690
  static reset(): void;
2667
2691
  }
2668
2692
 
2669
- export { Actor, type ActorConsistencyProfileName, type ActorDefinition, type ActorFactoryOptions, type ActorInvocationOptions, type ActorKeyDefinition, type ActorKind, type ActorLoadPolicy, type ActorRuntimeReadGuard, type ActorSpec, type ActorStateDefinition, type ActorStateReducer, type ActorStateStore, type ActorTaskBindingDefinition, type ActorTaskBindingOptions, type ActorTaskContext, type ActorTaskHandler, type ActorTaskMode, type ActorTaskRuntimeMetadata, type ActorWriteContract, type AnyObject, type CadenzaMode, type DebounceOptions, DebounceTask, type EmitOptions, EphemeralTask, type EphemeralTaskOptions, GraphContext, GraphRegistry, GraphRoutine, GraphRun, GraphRunner, type IdempotencyPolicy, InquiryBroker, type InquiryOptions, type Intent, META_ACTOR_SESSION_STATE_PERSIST_INTENT, type ResolvedRuntimeValidationPolicy, type RetryPolicy, type RuntimeValidationMode, type RuntimeValidationPolicy, type RuntimeValidationScope, type Schema, type SchemaConstraints, type SchemaDefinition, type SchemaType, type SessionPolicy, SignalBroker, SignalEmitter, Task, type TaskFunction, type TaskOptions, type TaskResult, type ThrottleTagGetter, Cadenza as default, getActorTaskRuntimeMetadata };
2693
+ export { Actor, type ActorConsistencyProfileName, type ActorDefinition, type ActorFactoryOptions, type ActorInvocationOptions, type ActorKeyDefinition, type ActorKind, type ActorLoadPolicy, type ActorRuntimeReadGuard, type ActorSpec, type ActorStateDefinition, type ActorStateReducer, type ActorStateStore, type ActorTaskBindingDefinition, type ActorTaskBindingOptions, type ActorTaskContext, type ActorTaskHandler, type ActorTaskMode, type ActorTaskRuntimeMetadata, type ActorWriteContract, type AnyObject, type CadenzaMode, type DebounceOptions, DebounceTask, type EmitOptions, EphemeralTask, type EphemeralTaskOptions, GraphContext, GraphRegistry, GraphRoutine, GraphRun, GraphRunner, type IdempotencyPolicy, InquiryBroker, type InquiryOptions, type Intent, META_ACTOR_SESSION_STATE_PERSIST_INTENT, type ResolvedRuntimeValidationPolicy, type RetryPolicy, type RuntimeValidationMode, type RuntimeValidationPolicy, type RuntimeValidationScope, type Schema, type SchemaConstraints, type SchemaDefinition, type SchemaType, type SessionPolicy, SignalBroker, type SignalDefinitionInput, type SignalDeliveryMode, SignalEmitter, type SignalMetadata, type SignalReceiverFilter, Task, type TaskFunction, type TaskOptions, type TaskResult, type ThrottleTagGetter, Cadenza as default, getActorTaskRuntimeMetadata };
package/dist/index.d.ts CHANGED
@@ -355,6 +355,7 @@ interface InquiryOptions {
355
355
  timeout?: number;
356
356
  rejectOnTimeout?: boolean;
357
357
  includePendingTasks?: boolean;
358
+ requireComplete?: boolean;
358
359
  }
359
360
  declare class InquiryBroker extends SignalEmitter {
360
361
  static instance_: InquiryBroker;
@@ -1070,14 +1071,14 @@ declare class Task extends SignalEmitter implements Graph {
1070
1071
  * @param {...string[]} signals - The array of signal names to observe.
1071
1072
  * @return {this} The current instance after adding the specified signals.
1072
1073
  */
1073
- doOn(...signals: string[]): this;
1074
+ doOn(...signals: SignalDefinitionInput[]): this;
1074
1075
  /**
1075
1076
  * Registers the specified signals to be emitted after the Task executes successfully and attaches them for further processing.
1076
1077
  *
1077
1078
  * @param {...string} signals - The list of signals to be registered for emission.
1078
1079
  * @return {this} The current instance for method chaining.
1079
1080
  */
1080
- emits(...signals: string[]): this;
1081
+ emits(...signals: SignalDefinitionInput[]): this;
1081
1082
  /**
1082
1083
  * Configures the instance to emit specified signals when the task execution fails.
1083
1084
  * A failure is defined as anything that does not return a successful result.
@@ -1085,14 +1086,14 @@ declare class Task extends SignalEmitter implements Graph {
1085
1086
  * @param {...string} signals - The names of the signals to emit upon failure.
1086
1087
  * @return {this} Returns the current instance for chaining.
1087
1088
  */
1088
- emitsOnFail(...signals: string[]): this;
1089
+ emitsOnFail(...signals: SignalDefinitionInput[]): this;
1089
1090
  /**
1090
1091
  * Attaches a signal to the current context and emits metadata if the register flag is set.
1091
1092
  *
1092
1093
  * @param {...string} signals - The names of the signals to attach.
1093
1094
  * @return {void} This method does not return a value.
1094
1095
  */
1095
- attachSignal(...signals: string[]): Task;
1096
+ attachSignal(...signals: SignalDefinitionInput[]): Task;
1096
1097
  /**
1097
1098
  * Unsubscribes the current instance from the specified signals.
1098
1099
  * This method removes the signals from the observedSignals set, unsubscribes
@@ -1485,6 +1486,22 @@ interface EmitOptions {
1485
1486
  throttleBatch?: number;
1486
1487
  flushStrategy?: string;
1487
1488
  }
1489
+ type SignalDeliveryMode = "single" | "broadcast";
1490
+ type SignalReceiverFilter = {
1491
+ serviceNames?: string[];
1492
+ serviceInstanceIds?: string[];
1493
+ origins?: string[];
1494
+ roles?: string[];
1495
+ protocols?: string[];
1496
+ runtimeStates?: string[];
1497
+ };
1498
+ type SignalMetadata = {
1499
+ deliveryMode?: SignalDeliveryMode;
1500
+ broadcastFilter?: SignalReceiverFilter | null;
1501
+ };
1502
+ type SignalDefinitionInput = string | ({
1503
+ name: string;
1504
+ } & SignalMetadata);
1488
1505
  type FlushStrategyName = string;
1489
1506
  interface FlushStrategy {
1490
1507
  intervalMs: number;
@@ -1513,12 +1530,17 @@ declare class SignalBroker {
1513
1530
  registered: boolean;
1514
1531
  }>;
1515
1532
  emittedSignalsRegistry: Set<string>;
1533
+ signalMetadataRegistry: Map<string, SignalMetadata>;
1516
1534
  private flushStrategies;
1517
1535
  private strategyData;
1518
1536
  private strategyTimers;
1519
1537
  private isStrategyFlushing;
1520
1538
  private readonly defaultStrategyName;
1521
1539
  constructor();
1540
+ private resolveSignalMetadataKey;
1541
+ private normalizeSignalMetadata;
1542
+ setSignalMetadata(signal: string, metadata?: SignalMetadata | null): void;
1543
+ getSignalMetadata(signal: string): SignalMetadata | undefined;
1522
1544
  logMemoryFootprint(label?: string): void;
1523
1545
  /**
1524
1546
  * Validates the provided signal name string to ensure it adheres to specific formatting rules.
@@ -1617,15 +1639,15 @@ declare class SignalBroker {
1617
1639
  * @param {string} signal - The name of the signal to be added.
1618
1640
  * @return {void} This method does not return any value.
1619
1641
  */
1620
- addSignal(signal: string): void;
1642
+ addSignal(signal: string, metadata?: SignalMetadata | null): void;
1621
1643
  /**
1622
1644
  * Observes a signal with a routine/task.
1623
1645
  * @param signal The signal (e.g., 'domain.action', 'domain.*' for wildcards).
1624
1646
  * @param routineOrTask The observer.
1625
1647
  * @edge Duplicates ignored; supports wildcards for broad listening.
1626
1648
  */
1627
- observe(signal: string, routineOrTask: Task | GraphRoutine): void;
1628
- registerEmittedSignal(signal: string): void;
1649
+ observe(signal: string, routineOrTask: Task | GraphRoutine, metadata?: SignalMetadata | null): void;
1650
+ registerEmittedSignal(signal: string, metadata?: SignalMetadata | null): void;
1629
1651
  /**
1630
1652
  * Unsubscribes a routine/task from a signal.
1631
1653
  * @param signal The signal.
@@ -2082,6 +2104,7 @@ declare class Actor<D extends Record<string, any> = AnyObject, R = AnyObject> {
2082
2104
  private readonly stateByKey;
2083
2105
  private readonly sessionByKey;
2084
2106
  private readonly idempotencyByKey;
2107
+ private readonly writeQueueByKey;
2085
2108
  private nextTaskBindingIndex;
2086
2109
  /**
2087
2110
  * Creates an actor instance and optionally materializes the default key.
@@ -2133,6 +2156,7 @@ declare class Actor<D extends Record<string, any> = AnyObject, R = AnyObject> {
2133
2156
  private ensureStateRecord;
2134
2157
  private touchSession;
2135
2158
  private runWithOptionalIdempotency;
2159
+ private runWithPerKeyWriteSerialization;
2136
2160
  private getActiveIdempotencyRecord;
2137
2161
  private persistDurableStateIfConfigured;
2138
2162
  private emitActorCreatedSignal;
@@ -2666,4 +2690,4 @@ declare class Cadenza {
2666
2690
  static reset(): void;
2667
2691
  }
2668
2692
 
2669
- export { Actor, type ActorConsistencyProfileName, type ActorDefinition, type ActorFactoryOptions, type ActorInvocationOptions, type ActorKeyDefinition, type ActorKind, type ActorLoadPolicy, type ActorRuntimeReadGuard, type ActorSpec, type ActorStateDefinition, type ActorStateReducer, type ActorStateStore, type ActorTaskBindingDefinition, type ActorTaskBindingOptions, type ActorTaskContext, type ActorTaskHandler, type ActorTaskMode, type ActorTaskRuntimeMetadata, type ActorWriteContract, type AnyObject, type CadenzaMode, type DebounceOptions, DebounceTask, type EmitOptions, EphemeralTask, type EphemeralTaskOptions, GraphContext, GraphRegistry, GraphRoutine, GraphRun, GraphRunner, type IdempotencyPolicy, InquiryBroker, type InquiryOptions, type Intent, META_ACTOR_SESSION_STATE_PERSIST_INTENT, type ResolvedRuntimeValidationPolicy, type RetryPolicy, type RuntimeValidationMode, type RuntimeValidationPolicy, type RuntimeValidationScope, type Schema, type SchemaConstraints, type SchemaDefinition, type SchemaType, type SessionPolicy, SignalBroker, SignalEmitter, Task, type TaskFunction, type TaskOptions, type TaskResult, type ThrottleTagGetter, Cadenza as default, getActorTaskRuntimeMetadata };
2693
+ export { Actor, type ActorConsistencyProfileName, type ActorDefinition, type ActorFactoryOptions, type ActorInvocationOptions, type ActorKeyDefinition, type ActorKind, type ActorLoadPolicy, type ActorRuntimeReadGuard, type ActorSpec, type ActorStateDefinition, type ActorStateReducer, type ActorStateStore, type ActorTaskBindingDefinition, type ActorTaskBindingOptions, type ActorTaskContext, type ActorTaskHandler, type ActorTaskMode, type ActorTaskRuntimeMetadata, type ActorWriteContract, type AnyObject, type CadenzaMode, type DebounceOptions, DebounceTask, type EmitOptions, EphemeralTask, type EphemeralTaskOptions, GraphContext, GraphRegistry, GraphRoutine, GraphRun, GraphRunner, type IdempotencyPolicy, InquiryBroker, type InquiryOptions, type Intent, META_ACTOR_SESSION_STATE_PERSIST_INTENT, type ResolvedRuntimeValidationPolicy, type RetryPolicy, type RuntimeValidationMode, type RuntimeValidationPolicy, type RuntimeValidationScope, type Schema, type SchemaConstraints, type SchemaDefinition, type SchemaType, type SessionPolicy, SignalBroker, type SignalDefinitionInput, type SignalDeliveryMode, SignalEmitter, type SignalMetadata, type SignalReceiverFilter, Task, type TaskFunction, type TaskOptions, type TaskResult, type ThrottleTagGetter, Cadenza as default, getActorTaskRuntimeMetadata };
package/dist/index.js CHANGED
@@ -1280,6 +1280,7 @@ var SignalBroker = class _SignalBroker {
1280
1280
  // TODO: Signals should be a class with a the observers, registered flag and other data.
1281
1281
  this.signalObservers = /* @__PURE__ */ new Map();
1282
1282
  this.emittedSignalsRegistry = /* @__PURE__ */ new Set();
1283
+ this.signalMetadataRegistry = /* @__PURE__ */ new Map();
1283
1284
  // ── Flush Strategy Management ───────────────────────────────────────
1284
1285
  this.flushStrategies = /* @__PURE__ */ new Map();
1285
1286
  this.strategyData = /* @__PURE__ */ new Map();
@@ -1312,6 +1313,47 @@ var SignalBroker = class _SignalBroker {
1312
1313
  setVerbose(value) {
1313
1314
  this.verbose = value;
1314
1315
  }
1316
+ resolveSignalMetadataKey(signal) {
1317
+ const normalizedSignal = typeof signal === "string" ? signal.trim() : "";
1318
+ if (!normalizedSignal) {
1319
+ return "";
1320
+ }
1321
+ return normalizedSignal.split(":")[0] ?? normalizedSignal;
1322
+ }
1323
+ normalizeSignalMetadata(metadata) {
1324
+ if (!metadata) {
1325
+ return void 0;
1326
+ }
1327
+ const deliveryMode = metadata.deliveryMode === "broadcast" ? "broadcast" : "single";
1328
+ const broadcastFilter = metadata.broadcastFilter && typeof metadata.broadcastFilter === "object" && !Array.isArray(metadata.broadcastFilter) ? merge_default({}, metadata.broadcastFilter) : null;
1329
+ return {
1330
+ deliveryMode,
1331
+ broadcastFilter
1332
+ };
1333
+ }
1334
+ setSignalMetadata(signal, metadata) {
1335
+ const metadataKey = this.resolveSignalMetadataKey(signal);
1336
+ if (!metadataKey) {
1337
+ return;
1338
+ }
1339
+ const normalized = this.normalizeSignalMetadata(metadata);
1340
+ if (!normalized) {
1341
+ this.signalMetadataRegistry.delete(metadataKey);
1342
+ return;
1343
+ }
1344
+ this.signalMetadataRegistry.set(metadataKey, normalized);
1345
+ }
1346
+ getSignalMetadata(signal) {
1347
+ const metadataKey = this.resolveSignalMetadataKey(signal);
1348
+ if (!metadataKey) {
1349
+ return void 0;
1350
+ }
1351
+ const metadata = this.signalMetadataRegistry.get(metadataKey);
1352
+ if (!metadata) {
1353
+ return void 0;
1354
+ }
1355
+ return merge_default({}, metadata);
1356
+ }
1315
1357
  // Dor debugging
1316
1358
  logMemoryFootprint(label = "current") {
1317
1359
  console.log(`[${label}] SignalBroker state sizes:`);
@@ -1396,7 +1438,8 @@ var SignalBroker = class _SignalBroker {
1396
1438
  const processedSignals = uniqueSignals.map((signal) => ({
1397
1439
  signal,
1398
1440
  data: {
1399
- registered: this.signalObservers.get(signal)?.registered ?? false
1441
+ registered: this.signalObservers.get(signal)?.registered ?? false,
1442
+ metadata: this.getSignalMetadata(signal) ?? null
1400
1443
  }
1401
1444
  }));
1402
1445
  return {
@@ -1746,10 +1789,11 @@ var SignalBroker = class _SignalBroker {
1746
1789
  execute(signal, context) {
1747
1790
  const isMeta = signal.includes("meta.");
1748
1791
  const isSubMeta = signal.includes("sub_meta.") || context.__isSubMeta;
1792
+ const isReceivedSignalTransmission = context.__receivedSignalTransmission === true;
1749
1793
  const isMetric = context.__signalEmission?.isMetric;
1794
+ const isNewTrace = !context.__signalEmission?.executionTraceId && !context.__metadata?.__executionTraceId && !context.__executionTraceId;
1750
1795
  const executionTraceId = context.__signalEmission?.executionTraceId ?? context.__metadata?.__executionTraceId ?? context.__executionTraceId ?? (0, import_uuid.v4)();
1751
1796
  if (!isSubMeta && (!isMeta || this.debug)) {
1752
- const isNewTrace = !context.__signalEmission?.executionTraceId && !context.__metadata?.__executionTraceId && !context.__executionTraceId;
1753
1797
  if (isNewTrace) {
1754
1798
  this.emit("sub_meta.signal_broker.new_trace", {
1755
1799
  data: {
@@ -1778,21 +1822,33 @@ var SignalBroker = class _SignalBroker {
1778
1822
  const signalParts = signal.split(":");
1779
1823
  const signalName = signalParts[0];
1780
1824
  const signalTag = signalParts.length > 1 ? signalParts[1] : null;
1825
+ const existingSignalEmission = context.__signalEmission && typeof context.__signalEmission === "object" ? context.__signalEmission : {};
1781
1826
  context.__signalEmission = {
1782
- ...context.__signalEmission ?? {},
1783
- uuid: (0, import_uuid.v4)(),
1784
- executionTraceId,
1785
- signalName,
1786
- signalTag,
1787
- emittedAt: formatTimestamp(emittedAt),
1788
- consumed: false,
1789
- consumedBy: null,
1790
- isMeta
1827
+ ...existingSignalEmission,
1828
+ fullSignalName: existingSignalEmission.fullSignalName ?? signal,
1829
+ uuid: existingSignalEmission.uuid ?? (0, import_uuid.v4)(),
1830
+ executionTraceId: existingSignalEmission.executionTraceId ?? executionTraceId,
1831
+ signalName: existingSignalEmission.signalName ?? signalName,
1832
+ signalTag: existingSignalEmission.signalTag ?? signalTag,
1833
+ emittedAt: existingSignalEmission.emittedAt ?? formatTimestamp(emittedAt),
1834
+ consumed: existingSignalEmission.consumed ?? false,
1835
+ consumedBy: existingSignalEmission.consumedBy ?? null,
1836
+ isMeta: existingSignalEmission.isMeta ?? isMeta,
1837
+ __traceCreatedBySignalBroker: existingSignalEmission.__traceCreatedBySignalBroker ?? isNewTrace
1791
1838
  };
1792
- this.emit("sub_meta.signal_broker.emitting_signal", { ...context });
1839
+ if (!isReceivedSignalTransmission) {
1840
+ if (isNewTrace) {
1841
+ context.__traceCreatedBySignalBroker = true;
1842
+ }
1843
+ this.emit("sub_meta.signal_broker.emitting_signal", { ...context });
1844
+ if (isNewTrace) {
1845
+ delete context.__traceCreatedBySignalBroker;
1846
+ }
1847
+ }
1793
1848
  } else if (isSubMeta) {
1794
1849
  context.__isSubMeta = true;
1795
1850
  }
1851
+ delete context.__receivedSignalTransmission;
1796
1852
  context.__metadata = {
1797
1853
  ...context.__metadata,
1798
1854
  __executionTraceId: executionTraceId
@@ -1856,8 +1912,11 @@ var SignalBroker = class _SignalBroker {
1856
1912
  * @param {string} signal - The name of the signal to be added.
1857
1913
  * @return {void} This method does not return any value.
1858
1914
  */
1859
- addSignal(signal) {
1915
+ addSignal(signal, metadata) {
1860
1916
  let _signal = signal;
1917
+ if (metadata) {
1918
+ this.setSignalMetadata(signal, metadata);
1919
+ }
1861
1920
  if (!this.signalObservers.has(_signal)) {
1862
1921
  this.validateSignalName(_signal);
1863
1922
  this.signalObservers.set(_signal, {
@@ -1887,11 +1946,14 @@ var SignalBroker = class _SignalBroker {
1887
1946
  * @param routineOrTask The observer.
1888
1947
  * @edge Duplicates ignored; supports wildcards for broad listening.
1889
1948
  */
1890
- observe(signal, routineOrTask) {
1891
- this.addSignal(signal);
1949
+ observe(signal, routineOrTask, metadata) {
1950
+ this.addSignal(signal, metadata);
1892
1951
  this.signalObservers.get(signal).tasks.add(routineOrTask);
1893
1952
  }
1894
- registerEmittedSignal(signal) {
1953
+ registerEmittedSignal(signal, metadata) {
1954
+ if (metadata) {
1955
+ this.setSignalMetadata(signal, metadata);
1956
+ }
1895
1957
  this.emittedSignalsRegistry.add(signal);
1896
1958
  }
1897
1959
  /**
@@ -1926,6 +1988,7 @@ var SignalBroker = class _SignalBroker {
1926
1988
  this.clearThrottleState();
1927
1989
  this.signalObservers.clear();
1928
1990
  this.emittedSignalsRegistry.clear();
1991
+ this.signalMetadataRegistry.clear();
1929
1992
  }
1930
1993
  shutdown() {
1931
1994
  this.reset();
@@ -2334,6 +2397,27 @@ var SignalEmitter = class {
2334
2397
  };
2335
2398
 
2336
2399
  // src/graph/execution/GraphNode.ts
2400
+ function normalizeGraphErrorMessage(error) {
2401
+ if (typeof error === "string") {
2402
+ return error;
2403
+ }
2404
+ if (error instanceof Error) {
2405
+ return error.message;
2406
+ }
2407
+ if (error && typeof error === "object") {
2408
+ const record = error;
2409
+ if (typeof record.__error === "string") {
2410
+ return record.__error;
2411
+ }
2412
+ if (typeof record.error === "string") {
2413
+ return record.error;
2414
+ }
2415
+ if (typeof record.message === "string") {
2416
+ return record.message;
2417
+ }
2418
+ }
2419
+ return String(error);
2420
+ }
2337
2421
  var GraphNode = class _GraphNode extends SignalEmitter {
2338
2422
  constructor(task, context, routineExecId, prevNodes = [], debug = false, verbose = false) {
2339
2423
  super(
@@ -2518,7 +2602,8 @@ var GraphNode = class _GraphNode extends SignalEmitter {
2518
2602
  {
2519
2603
  data: {
2520
2604
  taskExecutionId: this.id,
2521
- previousTaskExecutionId: node.id
2605
+ previousTaskExecutionId: node.id,
2606
+ executionTraceId: context.__metadata?.__executionTraceId ?? context.__executionTraceId ?? null
2522
2607
  },
2523
2608
  filter: {
2524
2609
  taskName: this.task.name,
@@ -2536,7 +2621,8 @@ var GraphNode = class _GraphNode extends SignalEmitter {
2536
2621
  {
2537
2622
  data: {
2538
2623
  taskExecutionId: this.id,
2539
- previousTaskExecutionId: context.__previousTaskExecutionId
2624
+ previousTaskExecutionId: context.__previousTaskExecutionId,
2625
+ executionTraceId: context.__metadata?.__executionTraceId ?? context.__executionTraceId ?? null
2540
2626
  },
2541
2627
  filter: {
2542
2628
  taskName: this.task.name,
@@ -2950,11 +3036,12 @@ var GraphNode = class _GraphNode extends SignalEmitter {
2950
3036
  * @return {void} This method does not return any value.
2951
3037
  */
2952
3038
  onError(error, errorData = {}) {
3039
+ const normalizedError = normalizeGraphErrorMessage(error);
2953
3040
  this.result = {
2954
3041
  ...this.context.getFullContext(),
2955
- __error: `Node error: ${error}`,
3042
+ __error: `Node error: ${normalizedError}`,
2956
3043
  __retries: this.retries,
2957
- error: `Node error: ${error}`,
3044
+ error: `Node error: ${normalizedError}`,
2958
3045
  errored: true,
2959
3046
  returnedValue: this.result,
2960
3047
  ...errorData
@@ -3529,8 +3616,16 @@ var GraphRunner = class extends SignalEmitter {
3529
3616
  const isNewTrace = !context.__routineExecId && !context.__metadata?.__executionTraceId && !context.__executionTraceId;
3530
3617
  const executionTraceId = context.__metadata?.__executionTraceId ?? context.__executionTraceId ?? (0, import_uuid5.v4)();
3531
3618
  context.__executionTraceId = executionTraceId;
3619
+ context.__traceCreatedByRunner = isNewTrace;
3620
+ const isNewRoutine = !context.__routineExecId;
3532
3621
  const routineExecId = context.__routineExecId ?? (0, import_uuid5.v4)();
3533
3622
  context.__routineExecId = routineExecId;
3623
+ const routineCreatedAt = formatTimestamp(Date.now());
3624
+ context.__routineCreatedByRunner = isNewRoutine;
3625
+ context.__routineName = routineName;
3626
+ context.__routineVersion = routineVersion;
3627
+ context.__routineCreatedAt = routineCreatedAt;
3628
+ context.__routineIsMeta = isMeta;
3534
3629
  Cadenza.applyRuntimeValidationScopesToContext(
3535
3630
  context,
3536
3631
  routineName,
@@ -3565,8 +3660,7 @@ var GraphRunner = class extends SignalEmitter {
3565
3660
  executionTraceId,
3566
3661
  context: ctx.getContext(),
3567
3662
  metaContext: ctx.getMetadata(),
3568
- previousRoutineExecution: context.__localRoutineExecId ?? context.__metadata?.__routineExecId ?? null,
3569
- created: formatTimestamp(Date.now())
3663
+ created: routineCreatedAt
3570
3664
  },
3571
3665
  __metadata: {
3572
3666
  __executionTraceId: executionTraceId
@@ -3799,6 +3893,7 @@ var Actor = class {
3799
3893
  this.stateByKey = /* @__PURE__ */ new Map();
3800
3894
  this.sessionByKey = /* @__PURE__ */ new Map();
3801
3895
  this.idempotencyByKey = /* @__PURE__ */ new Map();
3896
+ this.writeQueueByKey = /* @__PURE__ */ new Map();
3802
3897
  this.nextTaskBindingIndex = 0;
3803
3898
  if (!spec.name || typeof spec.name !== "string") {
3804
3899
  throw new Error("Actor name must be a non-empty string");
@@ -3980,7 +4075,7 @@ var Actor = class {
3980
4075
  taskBindingId,
3981
4076
  actorKey,
3982
4077
  invocationOptions,
3983
- runTask
4078
+ () => this.runWithPerKeyWriteSerialization(actorKey, mode, runTask)
3984
4079
  );
3985
4080
  };
3986
4081
  wrapped[ACTOR_TASK_METADATA] = {
@@ -4258,6 +4353,24 @@ var Actor = class {
4258
4353
  });
4259
4354
  return promise;
4260
4355
  }
4356
+ runWithPerKeyWriteSerialization(actorKey, mode, runTask) {
4357
+ if (mode === "read") {
4358
+ return runTask();
4359
+ }
4360
+ const previous = this.writeQueueByKey.get(actorKey) ?? Promise.resolve();
4361
+ let releaseCurrent;
4362
+ const currentGate = new Promise((resolve) => {
4363
+ releaseCurrent = resolve;
4364
+ });
4365
+ const currentTail = previous.catch(() => void 0).then(() => currentGate);
4366
+ this.writeQueueByKey.set(actorKey, currentTail);
4367
+ return previous.catch(() => void 0).then(runTask).finally(() => {
4368
+ releaseCurrent();
4369
+ if (this.writeQueueByKey.get(actorKey) === currentTail) {
4370
+ this.writeQueueByKey.delete(actorKey);
4371
+ }
4372
+ });
4373
+ }
4261
4374
  getActiveIdempotencyRecord(compositeKey) {
4262
4375
  const record = this.idempotencyByKey.get(compositeKey);
4263
4376
  if (!record) {
@@ -4275,23 +4388,25 @@ var Actor = class {
4275
4388
  return;
4276
4389
  }
4277
4390
  const timeoutMs = normalizePositiveInteger(this.spec.session?.persistenceTimeoutMs) ?? 5e3;
4391
+ const persistenceContext = {
4392
+ actor_name: this.spec.name,
4393
+ actor_version: 1,
4394
+ actor_key: actorKey,
4395
+ durable_state: cloneForDurableState(durableState),
4396
+ durable_version: durableVersion,
4397
+ expires_at: null
4398
+ };
4278
4399
  const response = await inquire(
4279
4400
  META_ACTOR_SESSION_STATE_PERSIST_INTENT,
4280
- {
4281
- actor_name: this.spec.name,
4282
- actor_version: 1,
4283
- actor_key: actorKey,
4284
- durable_state: cloneForDurableState(durableState),
4285
- durable_version: durableVersion,
4286
- expires_at: null
4287
- },
4401
+ persistenceContext,
4288
4402
  {
4289
4403
  timeout: timeoutMs,
4404
+ requireComplete: true,
4290
4405
  rejectOnTimeout: true
4291
4406
  }
4292
4407
  );
4293
4408
  if (!isObject2(response) || response.__success !== true || response.persisted !== true) {
4294
- const reason = isObject2(response) ? response.__error ?? response.error : void 0;
4409
+ const reason = isObject2(response) ? response.__error ?? response.error ?? response.internalError ?? (response.errored === true ? `errored response keys: ${Object.keys(response).join(",")}` : response.failed === true ? `failed response keys: ${Object.keys(response).join(",")}` : void 0) : void 0;
4295
4410
  throw new Error(
4296
4411
  `Actor "${this.spec.name}" durable state persistence failed for key "${actorKey}"${reason ? `: ${String(reason)}` : ""}`
4297
4412
  );
@@ -4325,6 +4440,20 @@ var Actor = class {
4325
4440
  };
4326
4441
 
4327
4442
  // src/graph/definition/Task.ts
4443
+ function normalizeSignalDefinition(input) {
4444
+ if (typeof input === "string") {
4445
+ return {
4446
+ name: input
4447
+ };
4448
+ }
4449
+ return {
4450
+ name: input.name,
4451
+ metadata: {
4452
+ deliveryMode: input.deliveryMode,
4453
+ broadcastFilter: input.broadcastFilter ?? null
4454
+ }
4455
+ };
4456
+ }
4328
4457
  var Task = class _Task extends SignalEmitter {
4329
4458
  /**
4330
4459
  * Constructs an instance of the task with the specified properties and configuration options.
@@ -5145,9 +5274,10 @@ var Task = class _Task extends SignalEmitter {
5145
5274
  * @return {this} The current instance after adding the specified signals.
5146
5275
  */
5147
5276
  doOn(...signals) {
5148
- signals.forEach((signal) => {
5277
+ signals.forEach((input) => {
5278
+ const { name: signal, metadata } = normalizeSignalDefinition(input);
5149
5279
  if (this.observedSignals.has(signal)) return;
5150
- Cadenza.signalBroker.observe(signal, this);
5280
+ Cadenza.signalBroker.observe(signal, this, metadata);
5151
5281
  this.observedSignals.add(signal);
5152
5282
  if (this.register) {
5153
5283
  this.emitWithMetadata("meta.task.observed_signal", {
@@ -5168,13 +5298,14 @@ var Task = class _Task extends SignalEmitter {
5168
5298
  * @return {this} The current instance for method chaining.
5169
5299
  */
5170
5300
  emits(...signals) {
5171
- signals.forEach((signal) => {
5301
+ signals.forEach((input) => {
5302
+ const { name: signal } = normalizeSignalDefinition(input);
5172
5303
  if (this.observedSignals.has(signal))
5173
5304
  throw new Error(
5174
5305
  `Detected signal loop for task ${this.name}. Signal name: ${signal}`
5175
5306
  );
5176
5307
  this.signalsToEmitAfter.add(signal);
5177
- this.attachSignal(signal);
5308
+ this.attachSignal(input);
5178
5309
  });
5179
5310
  return this;
5180
5311
  }
@@ -5186,9 +5317,10 @@ var Task = class _Task extends SignalEmitter {
5186
5317
  * @return {this} Returns the current instance for chaining.
5187
5318
  */
5188
5319
  emitsOnFail(...signals) {
5189
- signals.forEach((signal) => {
5320
+ signals.forEach((input) => {
5321
+ const { name: signal } = normalizeSignalDefinition(input);
5190
5322
  this.signalsToEmitOnFail.add(signal);
5191
- this.attachSignal(signal);
5323
+ this.attachSignal(input);
5192
5324
  });
5193
5325
  return this;
5194
5326
  }
@@ -5199,9 +5331,10 @@ var Task = class _Task extends SignalEmitter {
5199
5331
  * @return {void} This method does not return a value.
5200
5332
  */
5201
5333
  attachSignal(...signals) {
5202
- signals.forEach((signal) => {
5334
+ signals.forEach((input) => {
5335
+ const { name: signal, metadata } = normalizeSignalDefinition(input);
5203
5336
  this.emitsSignals.add(signal);
5204
- Cadenza.signalBroker.registerEmittedSignal(signal);
5337
+ Cadenza.signalBroker.registerEmittedSignal(signal, metadata);
5205
5338
  if (this.register) {
5206
5339
  const data = {
5207
5340
  signals: {