@cadenza.io/service 2.17.32 → 2.17.34

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.mjs CHANGED
@@ -249,7 +249,7 @@ var DatabaseTask = class extends DeputyTask {
249
249
  };
250
250
 
251
251
  // src/registry/ServiceRegistry.ts
252
- import { GraphContext as GraphContext2 } from "@cadenza.io/core";
252
+ import { v4 as uuid3 } from "uuid";
253
253
 
254
254
  // src/utils/environment.ts
255
255
  var isNode = typeof process !== "undefined" && process.versions?.node != null;
@@ -385,16 +385,16 @@ function normalizeServiceTransportConfig(value) {
385
385
  }
386
386
  function normalizeServiceTransportDescriptor(value) {
387
387
  const raw = value ?? {};
388
- const uuid7 = normalizeString(raw.uuid);
388
+ const uuid9 = normalizeString(raw.uuid);
389
389
  const serviceInstanceId = normalizeString(
390
390
  raw.serviceInstanceId ?? raw.service_instance_id
391
391
  );
392
392
  const config = normalizeServiceTransportConfig(raw);
393
- if (!uuid7 || !serviceInstanceId || !config) {
393
+ if (!uuid9 || !serviceInstanceId || !config) {
394
394
  return null;
395
395
  }
396
396
  return {
397
- uuid: uuid7,
397
+ uuid: uuid9,
398
398
  serviceInstanceId,
399
399
  role: config.role,
400
400
  origin: config.origin,
@@ -456,14 +456,14 @@ function normalizeTransportArray(value, serviceInstanceId) {
456
456
  }
457
457
  function normalizeServiceInstanceDescriptor(value) {
458
458
  const raw = value ?? {};
459
- const uuid7 = normalizeString2(raw.uuid);
459
+ const uuid9 = normalizeString2(raw.uuid);
460
460
  const serviceName = normalizeString2(raw.serviceName ?? raw.service_name);
461
- if (!uuid7 || !serviceName) {
461
+ if (!uuid9 || !serviceName) {
462
462
  return null;
463
463
  }
464
- const transports = normalizeTransportArray(raw.transports, uuid7);
464
+ const transports = normalizeTransportArray(raw.transports, uuid9);
465
465
  return {
466
- uuid: uuid7,
466
+ uuid: uuid9,
467
467
  serviceName,
468
468
  numberOfRunningGraphs: Math.max(
469
469
  0,
@@ -723,6 +723,8 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
723
723
  return rawResult;
724
724
  }
725
725
  const result = { ...rawResult };
726
+ delete result.__resolverOriginalContext;
727
+ delete result.__resolverQueryData;
726
728
  const normalizedQueryData = result.queryData && typeof result.queryData === "object" ? { ...result.queryData } : { ...queryData };
727
729
  const resolvedData = result.data ?? normalizedQueryData.data ?? queryData.data ?? ctx.data ?? ctx.__registrationData;
728
730
  if (resolvedData !== void 0 && result.data === void 0) {
@@ -734,12 +736,18 @@ function normalizeServiceRegistryInsertResult(tableName, ctx, queryData, rawResu
734
736
  result.queryData = normalizedQueryData;
735
737
  if (tableName === "service") {
736
738
  const resolvedServiceName = String(
737
- result.__serviceName ?? resolvedData?.name ?? resolvedData?.service_name ?? ctx.__serviceName ?? ""
739
+ ctx.__serviceName ?? result.__serviceName ?? resolvedData?.name ?? resolvedData?.service_name ?? ""
738
740
  ).trim();
739
741
  if (resolvedServiceName) {
740
742
  result.__serviceName = resolvedServiceName;
741
743
  }
742
744
  }
745
+ const resolvedLocalServiceInstanceId = String(
746
+ ctx.__serviceInstanceId ?? resolvedData?.uuid ?? resolvedData?.service_instance_id ?? ""
747
+ ).trim();
748
+ if (resolvedLocalServiceInstanceId) {
749
+ result.__serviceInstanceId = resolvedLocalServiceInstanceId;
750
+ }
743
751
  if (tableName === "service_instance" || tableName === "service_instance_transport") {
744
752
  const resolvedUuid = String(
745
753
  result.uuid ?? resolvedData?.uuid ?? ctx.__serviceInstanceId ?? ""
@@ -756,49 +764,105 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
756
764
  queryData,
757
765
  options
758
766
  );
759
- return CadenzaService.createUniqueMetaTask(
760
- `Resolve service registry insert for ${tableName}`,
761
- (ctx, emit, inquire, progressCallback) => {
767
+ const localExecutionRequestedSignal = `meta.service_registry.insert_execution_requested:${tableName}:local`;
768
+ const remoteExecutionRequestedSignal = `meta.service_registry.insert_execution_requested:${tableName}:remote`;
769
+ const executionResolvedSignal = `meta.service_registry.insert_execution_resolved:${tableName}`;
770
+ const executionFailedSignal = `meta.service_registry.insert_execution_failed:${tableName}`;
771
+ const createPrepareExecutionTask = (signalName) => CadenzaService.createMetaTask(
772
+ `Prepare service registry insert execution for ${tableName} (${signalName})`,
773
+ (ctx) => {
762
774
  const nextQueryData = buildServiceRegistryInsertQueryData(ctx, queryData);
763
- if (tableName === "service" && nextQueryData.data === void 0) {
764
- CadenzaService.log(
765
- "Service registry insert resolver missing service payload.",
766
- {
767
- ctxKeys: ctx && typeof ctx === "object" ? Object.keys(ctx).sort() : [],
768
- hasData: !!ctx && typeof ctx === "object" && (Object.prototype.hasOwnProperty.call(ctx, "data") || ctx.data !== void 0),
769
- hasRegistrationData: !!ctx && typeof ctx === "object" && (Object.prototype.hasOwnProperty.call(ctx, "__registrationData") || ctx.__registrationData !== void 0),
770
- serviceName: ctx?.__serviceName ?? ctx?.data?.name ?? null
771
- },
772
- "warning"
773
- );
774
- }
775
- const targetTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName) ?? remoteInsertTask;
776
775
  const delegationContext = ensureDelegationContextMetadata({
777
776
  ...ctx,
778
777
  queryData: nextQueryData
779
778
  });
780
779
  delegationContext.__metadata.__skipRemoteExecution = delegationContext.__metadata.__skipRemoteExecution ?? delegationContext.__skipRemoteExecution ?? false;
781
780
  delegationContext.__metadata.__blockRemoteExecution = delegationContext.__metadata.__blockRemoteExecution ?? delegationContext.__blockRemoteExecution ?? false;
782
- return Promise.resolve(
783
- targetTask.execute(
784
- new GraphContext2(delegationContext),
785
- emit,
786
- inquire,
787
- progressCallback,
788
- {
789
- nodeId: delegationContext.__previousTaskExecutionId ?? delegationContext.__metadata?.__previousTaskExecutionId ?? `service-registry-${tableName}`,
790
- routineExecId: delegationContext.__routineExecId ?? delegationContext.__metadata?.__routineExecId ?? delegationContext.__metadata?.__localRoutineExecId ?? "service-registry"
791
- }
792
- )
793
- ).then(
794
- (result) => normalizeServiceRegistryInsertResult(
795
- tableName,
796
- ctx,
797
- nextQueryData,
798
- result
799
- )
781
+ return {
782
+ ...delegationContext,
783
+ __resolverOriginalContext: {
784
+ ...ctx
785
+ },
786
+ __resolverQueryData: nextQueryData
787
+ };
788
+ },
789
+ `Prepares ${tableName} service-registry insert payloads for runner execution.`,
790
+ {
791
+ register: false,
792
+ isHidden: true
793
+ }
794
+ ).doOn(signalName).emitsOnFail(executionFailedSignal);
795
+ const prepareLocalExecutionTask = createPrepareExecutionTask(
796
+ localExecutionRequestedSignal
797
+ );
798
+ const prepareRemoteExecutionTask = createPrepareExecutionTask(
799
+ remoteExecutionRequestedSignal
800
+ );
801
+ const finalizeExecutionTask = CadenzaService.createMetaTask(
802
+ `Finalize service registry insert execution for ${tableName}`,
803
+ (ctx, emit) => {
804
+ if (!ctx.__resolverRequestId) {
805
+ return false;
806
+ }
807
+ const normalized = normalizeServiceRegistryInsertResult(
808
+ tableName,
809
+ ctx.__resolverOriginalContext ?? ctx,
810
+ ctx.__resolverQueryData ?? ctx.queryData ?? {},
811
+ ctx
800
812
  );
813
+ if (!normalized || typeof normalized !== "object") {
814
+ return normalized;
815
+ }
816
+ emit(executionResolvedSignal, normalized);
817
+ return normalized;
801
818
  },
819
+ `Normalizes ${tableName} service-registry insert results for resolver callers.`,
820
+ {
821
+ register: false,
822
+ isHidden: true
823
+ }
824
+ );
825
+ const wiredLocalTaskNames = /* @__PURE__ */ new Set();
826
+ const wireExecutionTarget = (targetTask, prepareTask) => {
827
+ targetTask.then(finalizeExecutionTask).emitsOnFail(executionFailedSignal);
828
+ prepareTask.then(targetTask);
829
+ };
830
+ wireExecutionTarget(remoteInsertTask, prepareRemoteExecutionTask);
831
+ return CadenzaService.createUniqueMetaTask(
832
+ `Resolve service registry insert for ${tableName}`,
833
+ (ctx, emit) => new Promise((resolve) => {
834
+ const resolverRequestId = uuid3();
835
+ CadenzaService.createEphemeralMetaTask(
836
+ `Resolve service registry insert execution for ${tableName} (${resolverRequestId})`,
837
+ (resultCtx) => {
838
+ if (resultCtx.__resolverRequestId !== resolverRequestId) {
839
+ return false;
840
+ }
841
+ const normalizedResult = {
842
+ ...resultCtx
843
+ };
844
+ delete normalizedResult.__resolverRequestId;
845
+ delete normalizedResult.__resolverOriginalContext;
846
+ delete normalizedResult.__resolverQueryData;
847
+ resolve(normalizedResult);
848
+ return normalizedResult;
849
+ },
850
+ `Resolves signal-driven ${tableName} service-registry insert execution.`,
851
+ {
852
+ register: false
853
+ }
854
+ ).doOn(executionResolvedSignal, executionFailedSignal);
855
+ const localInsertTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName);
856
+ const executionSignal = localInsertTask ? localExecutionRequestedSignal : remoteExecutionRequestedSignal;
857
+ if (localInsertTask && !wiredLocalTaskNames.has(localInsertTask.name)) {
858
+ wireExecutionTarget(localInsertTask, prepareLocalExecutionTask);
859
+ wiredLocalTaskNames.add(localInsertTask.name);
860
+ }
861
+ emit(executionSignal, {
862
+ ...ctx,
863
+ __resolverRequestId: resolverRequestId
864
+ });
865
+ }),
802
866
  `Resolves ${tableName} inserts through the local CadenzaDB task when available.`,
803
867
  options
804
868
  );
@@ -1036,15 +1100,15 @@ var ServiceRegistry = class _ServiceRegistry {
1036
1100
  if (!serviceInstance) {
1037
1101
  return false;
1038
1102
  }
1039
- const uuid7 = serviceInstance.uuid;
1103
+ const uuid9 = serviceInstance.uuid;
1040
1104
  const serviceName = serviceInstance.serviceName;
1041
1105
  const deleted = Boolean(
1042
1106
  ctx.deleted ?? ctx.serviceInstance?.deleted ?? ctx.data?.deleted
1043
1107
  );
1044
- if (uuid7 === this.serviceInstanceId) return;
1108
+ if (uuid9 === this.serviceInstanceId) return;
1045
1109
  if (deleted) {
1046
- const existingInstance = this.instances.get(serviceName)?.find((instance) => instance.uuid === uuid7);
1047
- const indexToDelete = this.instances.get(serviceName)?.findIndex((i) => i.uuid === uuid7) ?? -1;
1110
+ const existingInstance = this.instances.get(serviceName)?.find((instance) => instance.uuid === uuid9);
1111
+ const indexToDelete = this.instances.get(serviceName)?.findIndex((i) => i.uuid === uuid9) ?? -1;
1048
1112
  if (indexToDelete >= 0 && existingInstance) {
1049
1113
  this.instances.get(serviceName)?.splice(indexToDelete, 1);
1050
1114
  for (const transport of existingInstance.transports) {
@@ -1056,13 +1120,13 @@ var ServiceRegistry = class _ServiceRegistry {
1056
1120
  if (this.instances.get(serviceName)?.length === 0) {
1057
1121
  this.instances.delete(serviceName);
1058
1122
  }
1059
- this.unregisterDependee(uuid7, serviceName);
1123
+ this.unregisterDependee(uuid9, serviceName);
1060
1124
  return;
1061
1125
  }
1062
1126
  if (!this.instances.has(serviceName))
1063
1127
  this.instances.set(serviceName, []);
1064
1128
  const instances = this.instances.get(serviceName);
1065
- const existing = instances.find((i) => i.uuid === uuid7);
1129
+ const existing = instances.find((i) => i.uuid === uuid9);
1066
1130
  if (existing) {
1067
1131
  Object.assign(existing, {
1068
1132
  ...serviceInstance,
@@ -1072,7 +1136,7 @@ var ServiceRegistry = class _ServiceRegistry {
1072
1136
  } else {
1073
1137
  instances.push(serviceInstance);
1074
1138
  }
1075
- const trackedInstance = existing ?? instances.find((instance) => instance.uuid === uuid7);
1139
+ const trackedInstance = existing ?? instances.find((instance) => instance.uuid === uuid9);
1076
1140
  if (trackedInstance) {
1077
1141
  const snapshot = this.resolveRuntimeStatusSnapshot(
1078
1142
  trackedInstance.numberOfRunningGraphs ?? 0,
@@ -1085,16 +1149,19 @@ var ServiceRegistry = class _ServiceRegistry {
1085
1149
  trackedInstance.reportedAt = trackedInstance.reportedAt ?? (/* @__PURE__ */ new Date()).toISOString();
1086
1150
  }
1087
1151
  if (!serviceInstance.isBootstrapPlaceholder) {
1088
- this.reconcileBootstrapPlaceholderInstance(serviceName, uuid7, emit);
1152
+ this.reconcileBootstrapPlaceholderInstance(serviceName, uuid9, emit);
1089
1153
  }
1090
1154
  if (this.serviceName === serviceName) {
1091
1155
  return false;
1092
1156
  }
1157
+ if (trackedInstance?.isFrontend) {
1158
+ return true;
1159
+ }
1093
1160
  const trackedTransport = this.getRouteableTransport(
1094
1161
  trackedInstance,
1095
1162
  this.useSocket ? "socket" : "rest"
1096
1163
  );
1097
- if (!serviceInstance.isFrontend && (this.deputies.has(serviceName) || this.remoteIntents.has(serviceName)) || this.remoteSignals.has(serviceName)) {
1164
+ if (this.deputies.has(serviceName) || this.remoteIntents.has(serviceName) || this.remoteSignals.has(serviceName)) {
1098
1165
  const communicationTypes = Array.from(
1099
1166
  new Set(
1100
1167
  this.deputies.get(serviceName)?.map((d) => d.communicationType) ?? []
@@ -1111,7 +1178,7 @@ var ServiceRegistry = class _ServiceRegistry {
1111
1178
  if (!clientCreated) {
1112
1179
  emit("meta.service_registry.dependee_registered", {
1113
1180
  serviceName,
1114
- serviceInstanceId: uuid7,
1181
+ serviceInstanceId: uuid9,
1115
1182
  serviceTransportId: trackedTransport.uuid,
1116
1183
  serviceOrigin: trackedTransport.origin,
1117
1184
  transportProtocols: trackedTransport.protocols,
@@ -1125,7 +1192,7 @@ var ServiceRegistry = class _ServiceRegistry {
1125
1192
  } else {
1126
1193
  emit("meta.service_registry.routeable_transport_missing", {
1127
1194
  serviceName,
1128
- serviceInstanceId: uuid7,
1195
+ serviceInstanceId: uuid9,
1129
1196
  requiredRole: this.getRoutingTransportRole(),
1130
1197
  isFrontend: this.isFrontend
1131
1198
  });
@@ -1184,7 +1251,7 @@ var ServiceRegistry = class _ServiceRegistry {
1184
1251
  if (ownerInstance.uuid === this.serviceInstanceId) {
1185
1252
  return true;
1186
1253
  }
1187
- const hasRemoteInterest = (!ownerInstance.isFrontend && (this.deputies.has(ownerInstance.serviceName) || this.remoteIntents.has(ownerInstance.serviceName)) || this.remoteSignals.has(ownerInstance.serviceName)) && transport.role === this.getRoutingTransportRole();
1254
+ const hasRemoteInterest = !ownerInstance.isFrontend && (this.deputies.has(ownerInstance.serviceName) || this.remoteIntents.has(ownerInstance.serviceName) || this.remoteSignals.has(ownerInstance.serviceName)) && transport.role === this.getRoutingTransportRole();
1188
1255
  if (!hasRemoteInterest) {
1189
1256
  return true;
1190
1257
  }
@@ -1599,6 +1666,9 @@ var ServiceRegistry = class _ServiceRegistry {
1599
1666
  if (!instance.isActive || instance.isNonResponsive || instance.isBlocked) {
1600
1667
  return false;
1601
1668
  }
1669
+ if (instance.isFrontend) {
1670
+ return true;
1671
+ }
1602
1672
  return Boolean(
1603
1673
  this.selectTransportForInstance(instance, context, preferredRole)
1604
1674
  );
@@ -1632,6 +1702,21 @@ var ServiceRegistry = class _ServiceRegistry {
1632
1702
  }
1633
1703
  if (__broadcast || instances[0].isFrontend) {
1634
1704
  for (const instance of instances) {
1705
+ if (instance.isFrontend) {
1706
+ const fetchId = `browser:${instance.uuid}`;
1707
+ emit(
1708
+ `meta.service_registry.selected_instance_for_socket:${fetchId}`,
1709
+ {
1710
+ ...context,
1711
+ __instance: instance.uuid,
1712
+ __transportId: void 0,
1713
+ __transportOrigin: void 0,
1714
+ __transportProtocols: ["socket"],
1715
+ __fetchId: fetchId
1716
+ }
1717
+ );
1718
+ continue;
1719
+ }
1635
1720
  const selectedTransport2 = this.selectTransportForInstance(
1636
1721
  instance,
1637
1722
  context,
@@ -1673,6 +1758,21 @@ var ServiceRegistry = class _ServiceRegistry {
1673
1758
  if (retries > 0) {
1674
1759
  selected = instancesToTry[Math.floor(Math.random() * instancesToTry.length)];
1675
1760
  }
1761
+ if (selected.isFrontend) {
1762
+ context.__instance = selected.uuid;
1763
+ context.__transportId = void 0;
1764
+ context.__transportOrigin = void 0;
1765
+ context.__transportProtocols = ["socket"];
1766
+ context.__fetchId = `browser:${selected.uuid}`;
1767
+ context.__triedInstances = triedInstances;
1768
+ context.__triedInstances.push(selected.uuid);
1769
+ context.__retries = retries;
1770
+ emit(
1771
+ `meta.service_registry.selected_instance_for_socket:${context.__fetchId}`,
1772
+ context
1773
+ );
1774
+ return context;
1775
+ }
1676
1776
  const selectedTransport = this.selectTransportForInstance(
1677
1777
  selected,
1678
1778
  context,
@@ -2329,7 +2429,7 @@ var ServiceRegistry = class _ServiceRegistry {
2329
2429
  )
2330
2430
  );
2331
2431
  for (const service of services) {
2332
- const instances = this.instances.get(service).filter((i) => i.isActive);
2432
+ const instances = this.instances.get(service).filter((i) => i.isActive && !i.isFrontend);
2333
2433
  for (const instance of instances) {
2334
2434
  const transport = this.getRouteableTransport(
2335
2435
  instance,
@@ -3381,9 +3481,9 @@ var ServiceRegistry = class _ServiceRegistry {
3381
3481
  };
3382
3482
 
3383
3483
  // src/graph/definition/SignalTransmissionTask.ts
3384
- import { Task as Task3 } from "@cadenza.io/core";
3385
- import { v4 as uuid3 } from "uuid";
3386
- var SignalTransmissionTask = class extends Task3 {
3484
+ import { Task as Task2 } from "@cadenza.io/core";
3485
+ import { v4 as uuid4 } from "uuid";
3486
+ var SignalTransmissionTask = class extends Task2 {
3387
3487
  /**
3388
3488
  * Constructs a new instance of the class and initializes it with the provided parameters.
3389
3489
  *
@@ -3411,7 +3511,7 @@ var SignalTransmissionTask = class extends Task3 {
3411
3511
  */
3412
3512
  constructor(name, signalName, serviceName, description = "", concurrency = 0, timeout = 0, register = true, isUnique = false, isMeta = true, isSubMeta = false, isHidden = false, getTagCallback = void 0, inputSchema = void 0, validateInputContext = false, outputSchema = void 0, validateOutputContext = false, retryCount = 0, retryDelay = 0, retryDelayMax = 0, retryDelayFactor = 1) {
3413
3513
  const taskFunction = (context) => {
3414
- context.__routineExecId = uuid3();
3514
+ context.__routineExecId = uuid4();
3415
3515
  return context;
3416
3516
  };
3417
3517
  super(
@@ -3481,7 +3581,7 @@ import http from "http";
3481
3581
  import fs from "fs";
3482
3582
  import https from "https";
3483
3583
  import fetch from "node-fetch";
3484
- import { v4 as uuid4 } from "uuid";
3584
+ import { v4 as uuid5 } from "uuid";
3485
3585
  var RestController = class _RestController {
3486
3586
  /**
3487
3587
  * Constructor for initializing the REST server and related configurations.
@@ -3851,7 +3951,7 @@ var RestController = class _RestController {
3851
3951
  const internalOrigin = httpOrigin ?? httpsOrigin;
3852
3952
  if (internalOrigin) {
3853
3953
  transportData.unshift({
3854
- uuid: uuid4(),
3954
+ uuid: uuid5(),
3855
3955
  service_instance_id: ctx.__serviceInstanceId,
3856
3956
  role: "internal",
3857
3957
  origin: internalOrigin,
@@ -4508,6 +4608,35 @@ var SocketController = class _SocketController {
4508
4608
  },
4509
4609
  { isMeta: true }
4510
4610
  );
4611
+ CadenzaService.registry.getTaskByName.doOn("meta.socket.delegation_requested");
4612
+ CadenzaService.registry.getRoutineByName.doOn("meta.socket.delegation_requested");
4613
+ CadenzaService.createMetaTask(
4614
+ "Forward socket delegations to runner",
4615
+ (context, emit) => {
4616
+ if (!isBrowser && !CadenzaService.serviceRegistry.isFrontend) {
4617
+ return false;
4618
+ }
4619
+ if (context.task || context.routine) {
4620
+ const routine = context.task ?? context.routine;
4621
+ delete context.task;
4622
+ delete context.routine;
4623
+ context.__routineExecId = context.__metadata?.__deputyExecId ?? null;
4624
+ context.__isDeputy = true;
4625
+ CadenzaService.runner.run(routine, context);
4626
+ return true;
4627
+ }
4628
+ const deputyExecId = context.__metadata?.__deputyExecId ?? context.__deputyExecId;
4629
+ const remoteRoutineName = context.__remoteRoutineName ?? context.__name ?? "unknown";
4630
+ context.errored = true;
4631
+ context.__error = `No task or routine registered for delegation target ${remoteRoutineName}.`;
4632
+ if (deputyExecId) {
4633
+ emit(`meta.socket.delegation_target_not_found:${deputyExecId}`, context);
4634
+ }
4635
+ emit("meta.runner.failed", context);
4636
+ return false;
4637
+ },
4638
+ "Forwards socket delegated lookups to the local runner in frontend runtimes."
4639
+ ).attachSignal("meta.runner.failed").doAfter(CadenzaService.registry.getTaskByName, CadenzaService.registry.getRoutineByName);
4511
4640
  this.registerDiagnosticsTasks();
4512
4641
  this.registerSocketServerTasks();
4513
4642
  this.registerSocketClientTasks();
@@ -4751,8 +4880,56 @@ var SocketController = class _SocketController {
4751
4880
  });
4752
4881
  if (ctx.isFrontend) {
4753
4882
  const fetchId = `browser:${ctx.serviceInstanceId}`;
4883
+ const frontendDelegateTaskName = `Delegate flow to frontend ${fetchId}`;
4884
+ const frontendTransmitTaskName = `Transmit signal to ${fetchId}`;
4885
+ CadenzaService.get(frontendDelegateTaskName)?.destroy();
4886
+ CadenzaService.get(frontendTransmitTaskName)?.destroy();
4754
4887
  CadenzaService.createMetaTask(
4755
- `Transmit signal to ${fetchId}`,
4888
+ frontendDelegateTaskName,
4889
+ async (delegateCtx, emitter) => {
4890
+ if (delegateCtx.__remoteRoutineName === void 0) {
4891
+ return;
4892
+ }
4893
+ const normalizedDelegateCtx = ensureDelegationContextMetadata(delegateCtx);
4894
+ delete normalizedDelegateCtx.__isSubMeta;
4895
+ delete normalizedDelegateCtx.__broadcast;
4896
+ const deputyExecId = normalizedDelegateCtx.__metadata?.__deputyExecId;
4897
+ const resultContext = await new Promise((resolve) => {
4898
+ ws.timeout(normalizedDelegateCtx.__timeout ?? 6e4).emit(
4899
+ "delegation",
4900
+ normalizedDelegateCtx,
4901
+ (err, response) => {
4902
+ if (err) {
4903
+ resolve({
4904
+ ...normalizedDelegateCtx,
4905
+ errored: true,
4906
+ __error: `Frontend delegation timed out: ${err.message ?? err}`
4907
+ });
4908
+ return;
4909
+ }
4910
+ resolve(
4911
+ response ?? {
4912
+ errored: true,
4913
+ __error: "Frontend delegation returned no response"
4914
+ }
4915
+ );
4916
+ }
4917
+ );
4918
+ });
4919
+ if (deputyExecId) {
4920
+ const metadata = resultContext.__metadata;
4921
+ delete resultContext.__metadata;
4922
+ emitter(`meta.socket_client.delegated:${deputyExecId}`, {
4923
+ ...resultContext,
4924
+ ...metadata && typeof metadata === "object" ? metadata : {}
4925
+ });
4926
+ }
4927
+ return resultContext;
4928
+ },
4929
+ "Delegates work to a connected frontend runtime through its active websocket."
4930
+ ).doOn(`meta.service_registry.selected_instance_for_socket:${fetchId}`).attachSignal("meta.socket_client.delegated");
4931
+ CadenzaService.createMetaTask(
4932
+ frontendTransmitTaskName,
4756
4933
  (c, emitter) => {
4757
4934
  if (c.__signalName === void 0) {
4758
4935
  return;
@@ -5217,10 +5394,54 @@ var SocketController = class _SocketController {
5217
5394
  delegationCtx
5218
5395
  );
5219
5396
  });
5220
- socket.on("signal", (signalCtx) => {
5397
+ socket.on("delegation", (delegationCtx, callback) => {
5398
+ const normalizedDelegationCtx = ensureDelegationContextMetadata(delegationCtx);
5399
+ const deputyExecId = normalizedDelegationCtx.__metadata.__deputyExecId;
5400
+ const targetNotFoundSignal = `meta.socket.delegation_target_not_found:${deputyExecId}`;
5401
+ CadenzaService.createEphemeralMetaTask(
5402
+ `Resolve frontend socket delegation ${deputyExecId}`,
5403
+ (completedCtx) => {
5404
+ callback(completedCtx);
5405
+ return completedCtx;
5406
+ },
5407
+ "Resolves a server-routed delegation request through the frontend runtime.",
5408
+ {
5409
+ register: false
5410
+ }
5411
+ ).doOn(`meta.node.graph_completed:${deputyExecId}`, targetNotFoundSignal);
5412
+ if (!CadenzaService.get(normalizedDelegationCtx.__remoteRoutineName) && !CadenzaService.registry.routines.get(
5413
+ normalizedDelegationCtx.__remoteRoutineName
5414
+ )) {
5415
+ CadenzaService.emit(targetNotFoundSignal, {
5416
+ ...normalizedDelegationCtx,
5417
+ __error: `No task or routine registered for delegation target ${normalizedDelegationCtx.__remoteRoutineName}.`,
5418
+ errored: true
5419
+ });
5420
+ return;
5421
+ }
5422
+ CadenzaService.emit("meta.socket.delegation_requested", {
5423
+ ...normalizedDelegationCtx,
5424
+ __name: normalizedDelegationCtx.__remoteRoutineName
5425
+ });
5426
+ });
5427
+ socket.on("signal", (signalCtx, callback) => {
5221
5428
  if (CadenzaService.signalBroker.listObservedSignals().includes(signalCtx.__signalName)) {
5429
+ callback?.({
5430
+ __status: "success",
5431
+ __signalName: signalCtx.__signalName
5432
+ });
5222
5433
  CadenzaService.emit(signalCtx.__signalName, signalCtx);
5434
+ return;
5223
5435
  }
5436
+ callback?.({
5437
+ ...signalCtx,
5438
+ __status: "error",
5439
+ __error: `No such signal: ${signalCtx.__signalName}`,
5440
+ errored: true
5441
+ });
5442
+ });
5443
+ socket.on("status_check", (statusCtx, callback) => {
5444
+ callback(CadenzaService.serviceRegistry.resolveLocalStatusCheck(statusCtx));
5224
5445
  });
5225
5446
  socket.on("status_update", (status) => {
5226
5447
  CadenzaService.emit("meta.socket_client.status_received", status);
@@ -8293,13 +8514,13 @@ function tableFieldTypeToSchemaType(type) {
8293
8514
  }
8294
8515
 
8295
8516
  // src/Cadenza.ts
8296
- import { v4 as uuid5 } from "uuid";
8517
+ import { v4 as uuid7 } from "uuid";
8297
8518
 
8298
8519
  // src/graph/controllers/GraphSyncController.ts
8299
8520
  import {
8300
- GraphContext as GraphContext4,
8301
8521
  META_ACTOR_SESSION_STATE_PERSIST_INTENT as META_ACTOR_SESSION_STATE_PERSIST_INTENT2
8302
8522
  } from "@cadenza.io/core";
8523
+ import { v4 as uuid6 } from "uuid";
8303
8524
  var ACTOR_TASK_METADATA = /* @__PURE__ */ Symbol.for("@cadenza.io/core/actor-task-meta");
8304
8525
  function getActorTaskRuntimeMetadata(taskFunction) {
8305
8526
  if (typeof taskFunction !== "function") {
@@ -8433,30 +8654,69 @@ function resolveSyncInsertTask(isCadenzaDBReady, tableName, queryData = {}, opti
8433
8654
  if (!localInsertTask && !remoteInsertTask) {
8434
8655
  return void 0;
8435
8656
  }
8436
- return CadenzaService.createUniqueMetaTask(
8437
- `Resolve graph sync insert for ${tableName}`,
8438
- (ctx, emit, inquire, progressCallback) => {
8439
- const targetTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName) ?? remoteInsertTask;
8440
- if (!targetTask) {
8657
+ const targetTask = localInsertTask ?? remoteInsertTask;
8658
+ const executionRequestedSignal = `meta.sync_controller.insert_execution_requested:${tableName}`;
8659
+ const executionResolvedSignal = `meta.sync_controller.insert_execution_resolved:${tableName}`;
8660
+ const executionFailedSignal = `meta.sync_controller.insert_execution_failed:${tableName}`;
8661
+ const prepareExecutionTask = CadenzaService.createMetaTask(
8662
+ `Prepare graph sync insert execution for ${tableName}`,
8663
+ (ctx) => ({
8664
+ ...ctx,
8665
+ queryData: buildSyncInsertQueryData(
8666
+ ctx,
8667
+ queryData
8668
+ )
8669
+ }),
8670
+ `Prepares ${tableName} graph-sync insert payloads for runner execution.`,
8671
+ {
8672
+ register: false,
8673
+ isHidden: true
8674
+ }
8675
+ ).doOn(executionRequestedSignal).emitsOnFail(executionFailedSignal);
8676
+ const finalizeExecutionTask = CadenzaService.createMetaTask(
8677
+ `Finalize graph sync insert execution for ${tableName}`,
8678
+ (ctx, emit) => {
8679
+ if (!ctx.__resolverRequestId) {
8441
8680
  return false;
8442
8681
  }
8443
- return targetTask.execute(
8444
- new GraphContext4({
8445
- ...ctx,
8446
- queryData: buildSyncInsertQueryData(
8447
- ctx,
8448
- queryData
8449
- )
8450
- }),
8451
- emit,
8452
- inquire,
8453
- progressCallback,
8682
+ emit(executionResolvedSignal, ctx);
8683
+ return ctx;
8684
+ },
8685
+ `Resolves signal-driven ${tableName} graph-sync insert execution.`,
8686
+ {
8687
+ register: false,
8688
+ isHidden: true
8689
+ }
8690
+ );
8691
+ targetTask.then(finalizeExecutionTask).emitsOnFail(executionFailedSignal);
8692
+ prepareExecutionTask.then(targetTask);
8693
+ return CadenzaService.createUniqueMetaTask(
8694
+ `Resolve graph sync insert for ${tableName}`,
8695
+ (ctx, emit) => new Promise((resolve) => {
8696
+ const resolverRequestId = uuid6();
8697
+ CadenzaService.createEphemeralMetaTask(
8698
+ `Resolve graph sync insert execution for ${tableName} (${resolverRequestId})`,
8699
+ (resultCtx) => {
8700
+ if (resultCtx.__resolverRequestId !== resolverRequestId) {
8701
+ return false;
8702
+ }
8703
+ const normalizedResult = {
8704
+ ...resultCtx
8705
+ };
8706
+ delete normalizedResult.__resolverRequestId;
8707
+ resolve(normalizedResult);
8708
+ return normalizedResult;
8709
+ },
8710
+ `Waits for signal-driven ${tableName} graph-sync insert execution.`,
8454
8711
  {
8455
- nodeId: ctx.__previousTaskExecutionId ?? ctx.__metadata?.__previousTaskExecutionId ?? `graph-sync-${tableName}`,
8456
- routineExecId: ctx.__routineExecId ?? ctx.__metadata?.__routineExecId ?? ctx.__metadata?.__localRoutineExecId ?? "graph-sync"
8712
+ register: false
8457
8713
  }
8458
- );
8459
- },
8714
+ ).doOn(executionResolvedSignal, executionFailedSignal);
8715
+ emit(executionRequestedSignal, {
8716
+ ...ctx,
8717
+ __resolverRequestId: resolverRequestId
8718
+ });
8719
+ }),
8460
8720
  `Routes graph sync inserts for ${tableName} through the local authority task when available.`,
8461
8721
  {
8462
8722
  ...options,
@@ -9808,7 +10068,7 @@ var CadenzaService = class {
9808
10068
  (transport) => !!transport
9809
10069
  ).map((transport) => ({
9810
10070
  ...transport,
9811
- uuid: uuid5()
10071
+ uuid: uuid7()
9812
10072
  }));
9813
10073
  }
9814
10074
  static createBootstrapTransport(serviceInstanceId, role, endpoint) {
@@ -10060,7 +10320,7 @@ var CadenzaService = class {
10060
10320
  }
10061
10321
  for (const responder of responders) {
10062
10322
  const { task, descriptor } = responder;
10063
- const inquiryId = uuid5();
10323
+ const inquiryId = uuid7();
10064
10324
  startTimeByTask.set(task, Date.now());
10065
10325
  const resolverTask = this.createEphemeralMetaTask(
10066
10326
  `Resolve inquiry ${inquiry} for ${descriptor.localTaskName}`,
@@ -10568,7 +10828,7 @@ var CadenzaService = class {
10568
10828
  this.bootstrap();
10569
10829
  this.validateName(serviceName);
10570
10830
  this.validateServiceName(serviceName);
10571
- const serviceId = options.customServiceId ?? uuid5();
10831
+ const serviceId = options.customServiceId ?? uuid7();
10572
10832
  this.serviceRegistry.serviceName = serviceName;
10573
10833
  this.serviceRegistry.serviceInstanceId = serviceId;
10574
10834
  this.setHydrationResults(options.hydration);
@@ -10705,7 +10965,7 @@ var CadenzaService = class {
10705
10965
  "global.meta.cadenza_db.gathered_sync_data",
10706
10966
  ctx.serviceName
10707
10967
  );
10708
- }).doOn("meta.rest.handshake");
10968
+ }).doOn("meta.rest.handshake", "meta.socket.handshake");
10709
10969
  }
10710
10970
  this.createMetaTask("Handle service setup completion", () => {
10711
10971
  if (isFrontend) {
@@ -11413,12 +11673,12 @@ import {
11413
11673
  Actor as Actor2,
11414
11674
  DebounceTask as DebounceTask2,
11415
11675
  EphemeralTask as EphemeralTask2,
11416
- GraphRoutine as GraphRoutine3,
11417
- Task as Task6
11676
+ GraphRoutine as GraphRoutine2,
11677
+ Task as Task5
11418
11678
  } from "@cadenza.io/core";
11419
11679
 
11420
11680
  // src/ssr/createSSRInquiryBridge.ts
11421
- import { v4 as uuid6 } from "uuid";
11681
+ import { v4 as uuid8 } from "uuid";
11422
11682
  function ensureFetch() {
11423
11683
  if (typeof globalThis.fetch !== "function") {
11424
11684
  throw new Error("SSR inquiry bridge requires global fetch support.");
@@ -11507,7 +11767,7 @@ function createSSRInquiryBridge(options = {}) {
11507
11767
  __remoteRoutineName: remoteRoutineName,
11508
11768
  __metadata: {
11509
11769
  ...context.__metadata ?? {},
11510
- __deputyExecId: uuid6()
11770
+ __deputyExecId: uuid8()
11511
11771
  }
11512
11772
  }),
11513
11773
  signal
@@ -11697,13 +11957,13 @@ export {
11697
11957
  DeputyTask,
11698
11958
  EphemeralTask2 as EphemeralTask,
11699
11959
  GraphMetadataController,
11700
- GraphRoutine3 as GraphRoutine,
11960
+ GraphRoutine2 as GraphRoutine,
11701
11961
  RestController,
11702
11962
  ServiceRegistry,
11703
11963
  SignalController,
11704
11964
  SignalTransmissionTask,
11705
11965
  SocketController,
11706
- Task6 as Task,
11966
+ Task5 as Task,
11707
11967
  createSSRInquiryBridge,
11708
11968
  index_default as default
11709
11969
  };