@camstack/server 1.2.828 → 1.2.829

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.
Files changed (126) hide show
  1. package/CHANGELOG.md +14 -3
  2. package/dist/agent/agent-boot-mode.js +14 -1
  3. package/dist/agent/agent-http.js +12 -0
  4. package/dist/agent/agent-hub-rediscovery.js +205 -0
  5. package/dist/agent/agent-membership-watch.js +29 -1
  6. package/dist/agent/agent-pairing-store.js +47 -3
  7. package/dist/agent/hubs-found.js +1 -0
  8. package/dist/agent/main.js +64 -6
  9. package/dist/api/core/agent-pairing.router.js +9 -0
  10. package/dist/api/core/cluster-update.provider.js +98 -0
  11. package/dist/api/mesh-membership-routes.js +3 -2
  12. package/dist/api/trpc/generated-cap-mounts.js +2 -1
  13. package/dist/api/trpc/generated-cap-routers.js +2339 -2286
  14. package/dist/api/trpc/server-provided-caps.js +1 -0
  15. package/dist/api/trpc/trpc.router.js +5 -0
  16. package/dist/auth/auth-provider-gate.js +6 -2
  17. package/dist/core/addon/device-meta-mirror.js +1 -0
  18. package/dist/core/cluster-update/cluster-update-job-store.js +106 -0
  19. package/dist/core/cluster-update/cluster-update-plan.js +147 -0
  20. package/dist/core/cluster-update/cluster-update-seams.js +13 -0
  21. package/dist/core/cluster-update/cluster-update-steps.js +293 -0
  22. package/dist/core/cluster-update/cluster-update.service.js +319 -0
  23. package/dist/main.js +3 -0
  24. package/dist/manual-boot.js +19 -0
  25. package/package.json +17 -10
  26. package/system/dist/addon-runner.js +12 -0
  27. package/system/dist/addon-runner.mjs +12 -0
  28. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  29. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  30. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  31. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  32. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  33. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  34. package/system/dist/builtins/autotrack/index.js +1 -1
  35. package/system/dist/builtins/autotrack/index.mjs +1 -1
  36. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  37. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  38. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  39. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  40. package/system/dist/builtins/camera-grid/index.js +1 -1
  41. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  42. package/system/dist/builtins/composer/composer.addon.js +4 -4
  43. package/system/dist/builtins/composer/composer.addon.mjs +4 -4
  44. package/system/dist/builtins/console-logging/index.js +1 -1
  45. package/system/dist/builtins/console-logging/index.mjs +1 -1
  46. package/system/dist/builtins/core-blocks/core-blocks.addon.js +3 -3
  47. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +3 -3
  48. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  49. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  50. package/system/dist/builtins/device-manager/device-aggregation.d.ts +25 -1
  51. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +6 -0
  52. package/system/dist/builtins/device-manager/device-manager.addon.js +354 -7
  53. package/system/dist/builtins/device-manager/device-manager.addon.mjs +354 -7
  54. package/system/dist/builtins/device-manager/device-meta-actions.d.ts +6 -0
  55. package/system/dist/builtins/device-manager/device-meta-types.d.ts +4 -0
  56. package/system/dist/builtins/device-manager/device-row-store.d.ts +2 -1
  57. package/system/dist/builtins/device-manager/device-search.d.ts +42 -0
  58. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  59. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  60. package/system/dist/builtins/keychain/index.js +4 -4
  61. package/system/dist/builtins/keychain/index.mjs +4 -4
  62. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  63. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  64. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  65. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  66. package/system/dist/builtins/local-network/hub-mdns.d.ts +5 -1
  67. package/system/dist/builtins/local-network/local-network.addon.js +24 -13
  68. package/system/dist/builtins/local-network/local-network.addon.mjs +24 -13
  69. package/system/dist/builtins/loki-logging/index.js +1 -1
  70. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  71. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  72. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  73. package/system/dist/builtins/platform-probe/index.js +1 -1
  74. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  75. package/system/dist/builtins/record-entries/index.js +1 -1
  76. package/system/dist/builtins/record-entries/index.mjs +1 -1
  77. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  78. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  79. package/system/dist/builtins/snapshot/index.js +1 -1
  80. package/system/dist/builtins/snapshot/index.mjs +1 -1
  81. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  82. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  83. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  84. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  85. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  86. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  87. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  88. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  89. package/system/dist/builtins/system-config/system-config.addon.js +59 -20
  90. package/system/dist/builtins/system-config/system-config.addon.mjs +48 -10
  91. package/system/dist/builtins/winston-logging/index.js +1 -1
  92. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  93. package/system/dist/{capture-engine-B0yQx6hA.mjs → capture-engine-CsFrmbpC.mjs} +1 -1
  94. package/system/dist/{capture-engine-1A7HAX3x.js → capture-engine-Cvetsl63.js} +1 -1
  95. package/system/dist/{composition-sources-CyJ0d6Sc.mjs → composition-sources-Yw0KDrdI.mjs} +1 -1
  96. package/system/dist/{composition-sources-BzM19ASO.js → composition-sources-wNOckeFb.js} +1 -1
  97. package/system/dist/{constants-B_FLEjP_.mjs → constants-B7-Ccoim.mjs} +1 -1
  98. package/system/dist/{constants-DSO4ZEO3.js → constants-BqrgVNCL.js} +1 -1
  99. package/system/dist/{device-ca-CveuNCHp.mjs → device-ca-BDKMOSKW.mjs} +1 -1
  100. package/system/dist/{device-ca-DLTDsonl.js → device-ca-C9VMoted.js} +1 -1
  101. package/system/dist/{dist-CIyyHwVx.mjs → dist-Bv_ADY4Y.mjs} +385 -20
  102. package/system/dist/{dist-DhbzVygm.js → dist-KJhkakFo.js} +385 -20
  103. package/system/dist/file-host-worker.js +1 -1
  104. package/system/dist/file-host-worker.mjs +1 -1
  105. package/system/dist/{agent-https-BlLVD9hG.js → hub-identity-BS1rzEes.js} +120 -1
  106. package/system/dist/{agent-https-BSxTUzKT.mjs → hub-identity-DSLLzLph.mjs} +97 -2
  107. package/system/dist/{hub-mdns-ciao-C_ITDs0-.js → hub-mdns-ciao-BQh04Eo9.js} +18 -18
  108. package/system/dist/{hub-mdns-ciao-CQdCUsrI.mjs → hub-mdns-ciao-FVifxI5j.mjs} +2 -2
  109. package/system/dist/index.js +61 -44
  110. package/system/dist/index.mjs +22 -10
  111. package/system/dist/kernel/hub-identity.d.ts +17 -0
  112. package/system/dist/kernel/index.d.ts +2 -0
  113. package/system/dist/kernel/moleculer/mesh-mtls/mesh-membership.d.ts +7 -0
  114. package/system/dist/kernel/moleculer/mesh-mtls/pairing/agent-pairing.d.ts +11 -1
  115. package/system/dist/kernel/moleculer/mesh-mtls/pairing/hub-pairing.d.ts +5 -0
  116. package/system/dist/kernel/moleculer/mesh-mtls/pairing/index.d.ts +1 -1
  117. package/system/dist/kernel/moleculer/mesh-mtls/pairing/pairing-protocol.d.ts +2 -0
  118. package/system/dist/{legacy-integration-rows-door-D_tfRhsx.js → legacy-integration-rows-door-B3K3A9JU.js} +1 -1
  119. package/system/dist/{legacy-integration-rows-door-tX6Qktxd.mjs → legacy-integration-rows-door-Cu9uee1R.mjs} +1 -1
  120. package/system/dist/{rename-composition-block-DNhbAonr.js → rename-composition-block-31JmUak2.js} +1 -1
  121. package/system/dist/{rename-composition-block-COaMxshT.mjs → rename-composition-block-BglTrMYB.mjs} +1 -1
  122. package/system/dist/{restore-archive-BMqp_hMT.mjs → restore-archive-5UHNYi4u.mjs} +1 -1
  123. package/system/dist/{restore-archive-Dbzuv5hK.js → restore-archive-BHOc02Fh.js} +1 -1
  124. package/system/dist/{wal-maintenance-CWODOTsa.js → wal-maintenance-At5TeYwr.js} +0 -0
  125. package/system/dist/{wal-maintenance-ITsLGvFA.mjs → wal-maintenance-COJdLp-y.mjs} +0 -0
  126. package/system/package.json +1 -1
@@ -28,6 +28,7 @@ exports.HUB_SERVICE_CAP_NAMES = [
28
28
  'integrations',
29
29
  'nodes',
30
30
  'server-management',
31
+ 'cluster-update',
31
32
  'addons',
32
33
  ];
33
34
  /**
@@ -56,6 +56,7 @@ const logs_router_js_1 = require("../core/logs.router.js");
56
56
  const notifications_router_js_1 = require("../core/notifications.router.js");
57
57
  const preferences_router_js_1 = require("../core/preferences.router.js");
58
58
  const repl_router_js_1 = require("../core/repl.router.js");
59
+ const cluster_update_provider_js_1 = require("../core/cluster-update.provider.js");
59
60
  const server_management_provider_js_1 = require("../core/server-management.provider.js");
60
61
  const stream_probe_router_js_1 = require("../core/stream-probe.router.js");
61
62
  const system_events_router_js_1 = require("../core/system-events.router.js");
@@ -255,6 +256,8 @@ function buildServerProviders(services) {
255
256
  nodes: wrap(() => (0, cap_providers_js_1.buildNodesProvider)(services.agentRegistry, services.moleculer, services.addonRegistry, (0, cap_providers_js_1.createNodeRootPackageLookup)(services.moleculer, services.serverUpdateService), services.loggingService.createLogger('nodes'))),
256
257
  // server-management — runtime-updatable root package (phase 1: hub only).
257
258
  'server-management': wrap(() => (0, server_management_provider_js_1.buildServerManagementProvider)(services.serverUpdateService, path.resolve(process.env['CAMSTACK_DATA'] ?? 'camstack-data'))),
259
+ // cluster-update — backup, hub, agents, addons as one hub-side job.
260
+ 'cluster-update': wrap((ctx) => (0, cluster_update_provider_js_1.buildClusterUpdateProvider)(services.clusterUpdateService ?? null, ctx)),
258
261
  addons: wrap((ctx) => (0, cap_providers_js_1.buildAddonsProvider)(services.addonRegistry, services.addonPackageService, services.loggingService, services.moleculer, services.configService, ctx, services.agentRegistry)),
259
262
  // webrtc-session — the resolved broker singleton, wrapped per request to
260
263
  // inject the server-read User-Agent into signaling attribution (the broker
@@ -361,6 +364,8 @@ function buildCapabilityRouters(services) {
361
364
  registry: services.capabilityRegistry,
362
365
  nodeClient: (nodeId) => (0, node_certificates_client_js_1.createNodeCertificatesClient)(services.moleculer, nodeId),
363
366
  log: services.loggingService.createLogger('agent-pairing'),
367
+ // Same root as local-network's mDNS advertisement reads the hub id from (#494).
368
+ hubDataDir: path.resolve(services.configService.get('server.dataPath') ?? 'camstack-data'),
364
369
  }),
365
370
  auth: (0, auth_router_js_1.createAuthRouter)(services.authService, services.capabilityRegistry, services.moleculer, services.handoffCodeService, services.externalLinkIntents, services.nativeLink ?? null, {
366
371
  ...(services.authNetworkPolicy !== undefined
@@ -4,7 +4,11 @@ exports.AUTH_GOVERNING_CAPS = void 0;
4
4
  exports.isAuthAddonDisabled = isAuthAddonDisabled;
5
5
  exports.bridgeProviderAddonId = bridgeProviderAddonId;
6
6
  /** Capabilities whose per-provider toggle is an auth addon's enable. */
7
- exports.AUTH_GOVERNING_CAPS = ['auth-provider', 'user-passkeys'];
7
+ exports.AUTH_GOVERNING_CAPS = [
8
+ "auth-provider",
9
+ "user-passkeys",
10
+ "login-method",
11
+ ];
8
12
  /** Whether the operator disabled `addonId` on Identity → Authentication. */
9
13
  function isAuthAddonDisabled(registry, addonId) {
10
14
  return exports.AUTH_GOVERNING_CAPS.some((cap) => registry.isProviderDisabled(cap, addonId));
@@ -14,6 +18,6 @@ function isAuthAddonDisabled(registry, addonId) {
14
18
  * is signed by `auth-oidc`, anything else names its addon directly.
15
19
  */
16
20
  function bridgeProviderAddonId(provider) {
17
- const slash = provider.indexOf('/');
21
+ const slash = provider.indexOf("/");
18
22
  return slash === -1 ? provider : provider.slice(0, slash);
19
23
  }
@@ -80,6 +80,7 @@ exports.MIRROR_IRRELEVANT_META_FIELDS = new Set([
80
80
  'linkDeviceId',
81
81
  'primaryChildEntityId',
82
82
  'childLayout',
83
+ 'primaryChildPreference',
83
84
  ]);
84
85
  /**
85
86
  * Classify one device-lifecycle event's payload.
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.FileClusterUpdateJobStore = exports.CLUSTER_UPDATE_JOB_FILE = void 0;
37
+ /**
38
+ * The cluster update job, durable across the hub restart the job itself
39
+ * causes. One small JSON file under the hub's data dir, written atomically
40
+ * (tmp + rename), the same mechanism the neighbouring update state uses — not
41
+ * the settings database, which the hub's own update restarts too.
42
+ */
43
+ const fs = __importStar(require("node:fs"));
44
+ const path = __importStar(require("node:path"));
45
+ const types_1 = require("@camstack/types");
46
+ exports.CLUSTER_UPDATE_JOB_FILE = path.join('cluster-update', 'job.json');
47
+ function isNotFound(error) {
48
+ return error instanceof Error && 'code' in error && error.code === 'ENOENT';
49
+ }
50
+ class FileClusterUpdateJobStore {
51
+ logger;
52
+ filePath;
53
+ constructor(dataDir, logger) {
54
+ this.logger = logger;
55
+ this.filePath = path.join(dataDir, exports.CLUSTER_UPDATE_JOB_FILE);
56
+ }
57
+ /**
58
+ * `null` = no job (file absent, or its content is not a job: nothing to
59
+ * resume). A file that EXISTS but cannot be read THROWS — the caller must
60
+ * not mistake a transient read failure for "no job".
61
+ */
62
+ load() {
63
+ let text;
64
+ try {
65
+ text = fs.readFileSync(this.filePath, 'utf-8');
66
+ }
67
+ catch (error) {
68
+ if (isNotFound(error))
69
+ return null;
70
+ throw error;
71
+ }
72
+ let raw;
73
+ try {
74
+ raw = JSON.parse(text);
75
+ }
76
+ catch (error) {
77
+ this.logger.warn('Cluster update job file does not parse; ignoring it', {
78
+ meta: { path: this.filePath, error: (0, types_1.errMsg)(error) },
79
+ });
80
+ return null;
81
+ }
82
+ const parsed = types_1.ClusterUpdateJobSchema.safeParse(raw);
83
+ if (parsed.success)
84
+ return parsed.data;
85
+ this.logger.warn('Cluster update job file does not parse; ignoring it', {
86
+ meta: { path: this.filePath, error: parsed.error.message },
87
+ });
88
+ return null;
89
+ }
90
+ save(job) {
91
+ try {
92
+ fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
93
+ const tmp = `${this.filePath}.tmp`;
94
+ fs.writeFileSync(tmp, JSON.stringify(job, null, 2));
95
+ fs.renameSync(tmp, this.filePath);
96
+ }
97
+ catch (error) {
98
+ // The job goes on; what is lost is its resume across the hub restart,
99
+ // which the resumed boot then reports as `interrupted`.
100
+ this.logger.error('Failed to persist the cluster update job', {
101
+ meta: { path: this.filePath, jobId: job.id, error: (0, types_1.errMsg)(error) },
102
+ });
103
+ }
104
+ }
105
+ }
106
+ exports.FileClusterUpdateJobStore = FileClusterUpdateJobStore;
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.needsServer = needsServer;
4
+ exports.readClusterUpdatePlan = readClusterUpdatePlan;
5
+ /**
6
+ * What a cluster update WOULD do: read every node from the topology (never
7
+ * from a remembered list), resolve the target, and lay out the steps. Reads
8
+ * only. A read that failed is a reason, never "up to date" (D315, D393).
9
+ */
10
+ const types_1 = require("@camstack/types");
11
+ const cluster_update_seams_js_1 = require("./cluster-update-seams.js");
12
+ /** Does a node running `status` need the target? Unknown running = yes. */
13
+ function needsServer(status, target) {
14
+ if (status.restartRequired === true)
15
+ return true;
16
+ const running = status.runningVersion;
17
+ return running === null || (0, types_1.compareVersions)(running, target) < 0;
18
+ }
19
+ function isBusy(status) {
20
+ return status.updateState === 'staging' || status.updateState === 'pending-restart';
21
+ }
22
+ function blocked(blocker, detail, target, steps = [], skippedOffline = []) {
23
+ return {
24
+ targetVersion: target,
25
+ steps,
26
+ skippedOffline,
27
+ blocker,
28
+ blockerDetail: detail,
29
+ };
30
+ }
31
+ function backupStep(options) {
32
+ return options.backup === false
33
+ ? {
34
+ kind: 'backup',
35
+ status: 'skipped',
36
+ detail: 'backup opted out by the caller',
37
+ }
38
+ : {
39
+ kind: 'backup',
40
+ status: 'pending',
41
+ detail: 'back up before touching any node',
42
+ };
43
+ }
44
+ /** Plan the update. `null` blocker = it can start. */
45
+ async function readClusterUpdatePlan(seams, options) {
46
+ let hubStatus;
47
+ try {
48
+ hubStatus = await seams.readServerStatus(null);
49
+ }
50
+ catch (err) {
51
+ return blocked('status-unreadable', `the hub's status is unreadable: ${(0, cluster_update_seams_js_1.errText)(err)}`, null);
52
+ }
53
+ const target = options.version ?? hubStatus.latestVersion ?? null;
54
+ if (target === null) {
55
+ return blocked('no-target', 'the hub has no registry check yet (latestVersion is null): run a check or pass a version', null);
56
+ }
57
+ let topology;
58
+ try {
59
+ topology = await seams.readTopology();
60
+ }
61
+ catch (err) {
62
+ return blocked('status-unreadable', `the topology is unreadable: ${(0, cluster_update_seams_js_1.errText)(err)}`, target);
63
+ }
64
+ const offline = topology.filter((n) => !n.isHub && !n.isOnline).map((n) => n.id);
65
+ const busy = [];
66
+ if (isBusy(hubStatus))
67
+ busy.push(`hub (${hubStatus.updateState})`);
68
+ const hubStep = needsServer(hubStatus, target)
69
+ ? {
70
+ kind: 'hub-server',
71
+ nodeId: 'hub',
72
+ status: 'pending',
73
+ fromVersion: hubStatus.runningVersion,
74
+ detail: `${hubStatus.runningVersion ?? 'unknown'} -> ${target}`,
75
+ }
76
+ : {
77
+ kind: 'hub-server',
78
+ nodeId: 'hub',
79
+ status: 'skipped',
80
+ fromVersion: hubStatus.runningVersion,
81
+ detail: `already on ${hubStatus.runningVersion ?? target}`,
82
+ };
83
+ const agentSteps = [];
84
+ for (const node of topology) {
85
+ if (node.isHub || !node.isOnline)
86
+ continue;
87
+ let status = null;
88
+ try {
89
+ status = await seams.readServerStatus(node.id);
90
+ }
91
+ catch {
92
+ status = null;
93
+ }
94
+ if (status !== null && isBusy(status))
95
+ busy.push(`${node.id} (${status.updateState})`);
96
+ if (status === null || needsServer(status, target)) {
97
+ agentSteps.push({
98
+ kind: 'agent-server',
99
+ nodeId: node.id,
100
+ status: 'pending',
101
+ fromVersion: status?.runningVersion ?? null,
102
+ detail: status === null
103
+ ? `status unreadable now; read again when its turn comes`
104
+ : `${status.runningVersion ?? 'unknown'} -> ${target}`,
105
+ });
106
+ }
107
+ }
108
+ let addonUpdates = [];
109
+ if (options.addons !== false) {
110
+ try {
111
+ addonUpdates = await seams.listAddonUpdates();
112
+ }
113
+ catch (err) {
114
+ seams.logger.warn('Cluster update plan: addon updates unreadable', {
115
+ meta: { error: (0, cluster_update_seams_js_1.errText)(err) },
116
+ });
117
+ }
118
+ }
119
+ const addonsStep = options.addons === false
120
+ ? {
121
+ kind: 'addons',
122
+ status: 'skipped',
123
+ detail: 'addons opted out by the caller',
124
+ }
125
+ : {
126
+ kind: 'addons',
127
+ status: 'pending',
128
+ detail: addonUpdates.length > 0
129
+ ? `${addonUpdates.length} addon(s) behind; the list is read again after the servers`
130
+ : 'no addon update pending now; read again after the servers',
131
+ packages: addonUpdates.map((u) => `${u.name} ${u.currentVersion} -> ${u.latestVersion}`),
132
+ };
133
+ const steps = [backupStep(options), hubStep, ...agentSteps, addonsStep];
134
+ if (busy.length > 0) {
135
+ return blocked('node-busy', `a node is mid-update: ${busy.join(', ')}; wait for it to settle`, target, steps, offline);
136
+ }
137
+ if (hubStep.status === 'skipped' && agentSteps.length === 0 && addonUpdates.length === 0) {
138
+ return blocked('nothing-to-do', `every online node runs ${target} and no addon update is pending`, target, steps, offline);
139
+ }
140
+ return {
141
+ targetVersion: target,
142
+ steps,
143
+ skippedOffline: offline,
144
+ blocker: null,
145
+ blockerDetail: null,
146
+ };
147
+ }
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_CLUSTER_UPDATE_TIMEOUTS = void 0;
4
+ exports.errText = errText;
5
+ /** 16 min is the apply's own staging bound; a node then has to restart and register. */
6
+ exports.DEFAULT_CLUSTER_UPDATE_TIMEOUTS = {
7
+ serverMs: 30 * 60_000,
8
+ addonsMs: 15 * 60_000,
9
+ pollMs: 5_000,
10
+ };
11
+ function errText(err) {
12
+ return err instanceof Error ? err.message : String(err);
13
+ }
@@ -0,0 +1,293 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runBackupStep = runBackupStep;
4
+ exports.nodeNotReady = nodeNotReady;
5
+ exports.waitForAgentOnline = waitForAgentOnline;
6
+ exports.runServerStep = runServerStep;
7
+ exports.verifyServerStep = verifyServerStep;
8
+ exports.runAddonsStep = runAddonsStep;
9
+ const cluster_update_seams_js_1 = require("./cluster-update-seams.js");
10
+ async function waitUntil(seams, timeoutMs, check) {
11
+ const deadline = seams.now() + timeoutMs;
12
+ for (;;) {
13
+ const notReady = await check();
14
+ if (notReady === null)
15
+ return { ok: true };
16
+ if (seams.now() >= deadline)
17
+ return { ok: false, last: notReady };
18
+ await seams.sleep(seams.timeouts.pollMs);
19
+ }
20
+ }
21
+ function failed(reason, detail) {
22
+ return { status: 'failed', reason, detail };
23
+ }
24
+ // ---------------------------------------------------------------------------
25
+ // backup
26
+ /** The backup addon stamps `requestedAt` with its own clock (same host). */
27
+ const CLOCK_SLACK_MS = 5_000;
28
+ const TERMINAL_RUN = new Set(['succeeded', 'failed', 'cancelled']);
29
+ /**
30
+ * Back up before anything moves. `backup.trigger` resolves when the run ends;
31
+ * a trigger call that drops (timeout across a long archive) is reconciled by
32
+ * finding the run by its unique label, never by guessing from the error.
33
+ */
34
+ async function runBackupStep(seams, label) {
35
+ const backup = seams.getBackup();
36
+ if (backup === null) {
37
+ return failed('backup-unavailable', 'no backup provider is running; start one, or run the update with backup off');
38
+ }
39
+ const startedAt = seams.now();
40
+ try {
41
+ const result = await backup.trigger(label);
42
+ if (result.cancelled)
43
+ return failed('backup-failed', `backup run ${result.runId} was cancelled`);
44
+ if (result.entries.length === 0) {
45
+ return failed('backup-failed', `backup run ${result.runId} landed at no destination`);
46
+ }
47
+ return {
48
+ status: 'ok',
49
+ detail: `backup run ${result.runId} landed at ${result.entries.length} destination(s)`,
50
+ };
51
+ }
52
+ catch (err) {
53
+ return reconcileBackup(seams, backup, label, startedAt, (0, cluster_update_seams_js_1.errText)(err));
54
+ }
55
+ }
56
+ /** The trigger call dropped: find the run by its label and wait for it to end. */
57
+ async function reconcileBackup(seams, backup, label, startedAt, dropped) {
58
+ let run;
59
+ const wait = await waitUntil(seams, seams.timeouts.serverMs, async () => {
60
+ try {
61
+ const runs = await backup.listRuns();
62
+ run = runs.find((r) => r.label === label && r.requestedAt >= startedAt - CLOCK_SLACK_MS);
63
+ }
64
+ catch (readErr) {
65
+ return {
66
+ reason: 'backup-failed',
67
+ why: `runs unreadable: ${(0, cluster_update_seams_js_1.errText)(readErr)}`,
68
+ };
69
+ }
70
+ if (run === undefined)
71
+ return { reason: 'backup-failed', why: `trigger failed: ${dropped}` };
72
+ if (!TERMINAL_RUN.has(run.state)) {
73
+ return {
74
+ reason: 'backup-failed',
75
+ why: `run ${run.id} still ${run.state}`,
76
+ };
77
+ }
78
+ return null;
79
+ });
80
+ if (!wait.ok || run === undefined) {
81
+ return failed('backup-failed', wait.ok ? `trigger failed: ${dropped}` : wait.last.why);
82
+ }
83
+ if (run.state !== 'succeeded' || run.completedDestinationIds.length === 0) {
84
+ return failed('backup-failed', `backup run ${run.id} ended ${run.state}${run.error ? `: ${run.error}` : ''}`);
85
+ }
86
+ return {
87
+ status: 'ok',
88
+ detail: `backup run ${run.id} landed at ${run.completedDestinationIds.length} destination(s)`,
89
+ };
90
+ }
91
+ // ---------------------------------------------------------------------------
92
+ // servers
93
+ /** The node runs `target`, settled, online, with its capabilities registered. */
94
+ async function nodeNotReady(seams, nodeId, target) {
95
+ let status;
96
+ try {
97
+ status = await seams.readServerStatus(nodeId);
98
+ }
99
+ catch (err) {
100
+ return {
101
+ reason: 'status-unreadable',
102
+ why: `status unreadable (${(0, cluster_update_seams_js_1.errText)(err)})`,
103
+ };
104
+ }
105
+ if (status.runningVersion !== target) {
106
+ return {
107
+ reason: 'server-not-on-target',
108
+ why: `still running ${status.runningVersion ?? 'unknown'}, target ${target}`,
109
+ };
110
+ }
111
+ if (status.restartRequired === true) {
112
+ return { reason: 'server-not-on-target', why: 'restart still required' };
113
+ }
114
+ if (status.updateState !== 'idle') {
115
+ return {
116
+ reason: 'server-not-on-target',
117
+ why: `update state ${status.updateState}`,
118
+ };
119
+ }
120
+ if (nodeId === null)
121
+ return null;
122
+ let topology;
123
+ try {
124
+ topology = await seams.readTopology();
125
+ }
126
+ catch (err) {
127
+ return { reason: 'status-unreadable', why: `topology unreadable (${(0, cluster_update_seams_js_1.errText)(err)})` };
128
+ }
129
+ const node = topology.find((n) => n.id === nodeId);
130
+ if (node === undefined)
131
+ return { reason: 'server-not-on-target', why: 'absent from the topology' };
132
+ if (!node.isOnline)
133
+ return { reason: 'server-not-on-target', why: 'not online yet' };
134
+ const capless = node.capabilitiesRegistered === false ||
135
+ (node.capabilitiesRegistered === undefined && node.capabilityCount === 0);
136
+ if (capless) {
137
+ return {
138
+ reason: 'node-capless',
139
+ why: 'online on the target but registered no capabilities',
140
+ };
141
+ }
142
+ return null;
143
+ }
144
+ /**
145
+ * An agent's turn: wait (bounded) for it to be online. Offline at its turn is
146
+ * usually the mesh reconnecting after the hub's restart, not a node to leave
147
+ * behind: expiry FAILS the step, it never skips it.
148
+ */
149
+ async function waitForAgentOnline(seams, nodeId) {
150
+ const wait = await waitUntil(seams, seams.timeouts.serverMs, async () => {
151
+ let topology;
152
+ try {
153
+ topology = await seams.readTopology();
154
+ }
155
+ catch (err) {
156
+ return { reason: 'status-unreadable', why: `topology unreadable (${(0, cluster_update_seams_js_1.errText)(err)})` };
157
+ }
158
+ const node = topology.find((n) => n.id === nodeId);
159
+ if (node === undefined)
160
+ return { reason: 'server-not-on-target', why: 'absent from the topology' };
161
+ return node.isOnline ? null : { reason: 'server-not-on-target', why: 'still offline' };
162
+ });
163
+ return wait.ok
164
+ ? null
165
+ : failed(wait.last.reason, `${nodeId} was not online at its turn: ${wait.last.why}; not updated`);
166
+ }
167
+ /** Did the apply answer say "this will not happen"? */
168
+ function refusal(result) {
169
+ if (result.outcome === 'already-current')
170
+ return null;
171
+ if (result.outcome === 'refused' || result.outcome === 'failed' || !result.accepted) {
172
+ const blockers = (result.blockers ?? []).map((b) => `${b.addonId}: ${b.reason}`).join('; ');
173
+ return `${result.outcome ?? 'not accepted'}: ${result.reason ?? result.error ?? result.message}${blockers ? ` [would refuse to start: ${blockers}]` : ''}`;
174
+ }
175
+ return null;
176
+ }
177
+ /**
178
+ * Apply the target on one node and wait until it RUNS it. A dropped call is
179
+ * the expected path while the node restarts under it — the wait decides.
180
+ * For the hub this wait is normally cut short by the hub's own restart; the
181
+ * resumed job verifies it (`verifyServerStep`).
182
+ */
183
+ async function runServerStep(seams, nodeId, target) {
184
+ const name = nodeId ?? 'hub';
185
+ let note = '';
186
+ try {
187
+ const result = await seams.applyServerUpdate(nodeId, target);
188
+ const refused = refusal(result);
189
+ if (refused !== null)
190
+ return failed('server-refused', `${name} refused the update (${refused})`);
191
+ note = result.outcome ?? '';
192
+ }
193
+ catch (err) {
194
+ note = `no reply (${(0, cluster_update_seams_js_1.errText)(err)}); expected while the node restarts`;
195
+ }
196
+ return verifyServerStep(seams, nodeId, target, note);
197
+ }
198
+ async function verifyServerStep(seams, nodeId, target, note) {
199
+ const name = nodeId ?? 'hub';
200
+ const wait = await waitUntil(seams, seams.timeouts.serverMs, () => nodeNotReady(seams, nodeId, target));
201
+ if (!wait.ok)
202
+ return failed(wait.last.reason, `${name} did not reach ${target}: ${wait.last.why}`);
203
+ return {
204
+ status: 'ok',
205
+ detail: `${name} runs ${target}${nodeId === null ? '' : ', capabilities registered'}${note ? ` (${note})` : ''}`,
206
+ };
207
+ }
208
+ // ---------------------------------------------------------------------------
209
+ // addons
210
+ /**
211
+ * Update every stale addon on the hub, then verify that the hub runs each new
212
+ * version and that every online agent holding the package matches it.
213
+ * `updatePackage` answers `{success:false}` instead of throwing on some
214
+ * failures; that is a failure here too.
215
+ */
216
+ async function runAddonsStep(seams) {
217
+ let updates;
218
+ try {
219
+ updates = await seams.listAddonUpdates();
220
+ }
221
+ catch (err) {
222
+ return failed('addon-update-failed', `addon updates unreadable: ${(0, cluster_update_seams_js_1.errText)(err)}`);
223
+ }
224
+ const packages = updates.map((u) => `${u.name} ${u.currentVersion} -> ${u.latestVersion}`);
225
+ if (updates.length === 0)
226
+ return { status: 'skipped', detail: 'no addon update pending', packages };
227
+ const done = [];
228
+ for (const u of updates) {
229
+ let error;
230
+ try {
231
+ const result = await seams.updateAddon(u.name, u.latestVersion);
232
+ error = result.success ? null : (result.error ?? 'update failed');
233
+ }
234
+ catch (err) {
235
+ error = (0, cluster_update_seams_js_1.errText)(err);
236
+ }
237
+ if (error !== null) {
238
+ const already = done.length > 0 ? `; already updated: ${done.map((d) => d.name).join(', ')}` : '';
239
+ return {
240
+ ...failed('addon-update-failed', `hub failed to update ${u.name} to ${u.latestVersion}: ${error}${already}`),
241
+ packages,
242
+ };
243
+ }
244
+ done.push(u);
245
+ }
246
+ const wait = await waitUntil(seams, seams.timeouts.addonsMs, () => addonsNotConverged(seams, done));
247
+ if (!wait.ok) {
248
+ return {
249
+ ...failed(wait.last.reason, `${done.length} addon(s) updated on the hub; ${wait.last.why}`),
250
+ packages,
251
+ };
252
+ }
253
+ return {
254
+ status: 'ok',
255
+ detail: `${done.length} addon(s) updated on the hub and matched on every online agent`,
256
+ packages,
257
+ };
258
+ }
259
+ async function addonsNotConverged(seams, done) {
260
+ let rows;
261
+ try {
262
+ rows = await seams.readInstallations();
263
+ }
264
+ catch (err) {
265
+ return {
266
+ reason: 'addons-not-converged',
267
+ why: `installations unreadable (${(0, cluster_update_seams_js_1.errText)(err)})`,
268
+ };
269
+ }
270
+ const behind = [];
271
+ for (const u of done) {
272
+ const hub = rows.find((r) => r.isHub && r.packageName === u.name);
273
+ if (hub === undefined || hub.version !== u.latestVersion) {
274
+ return {
275
+ reason: 'addons-not-converged',
276
+ why: `${u.name} is ${hub?.version ?? 'absent'} on the hub, expected ${u.latestVersion}`,
277
+ };
278
+ }
279
+ for (const r of rows) {
280
+ if (r.isHub || !r.isOnline || r.packageName !== u.name)
281
+ continue;
282
+ if (r.version !== u.latestVersion)
283
+ behind.push(`${r.nodeId}/${u.name}=${r.version ?? 'absent'}`);
284
+ }
285
+ }
286
+ if (behind.length > 0) {
287
+ return {
288
+ reason: 'addons-not-converged',
289
+ why: `agents behind the hub: ${behind.join(', ')}`,
290
+ };
291
+ }
292
+ return null;
293
+ }