@serve.zone/interfaces 32.50.0 → 32.52.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.
@@ -4,15 +4,22 @@ import type {
4
4
  TSha256Digest,
5
5
  } from './immutableimage.js';
6
6
  import { normalizeSha256Digest } from './immutableimage.js';
7
- import { hasExactKeys, isPlainRecord } from '../private/dataproperties.js';
7
+ import {
8
+ hasExactKeys,
9
+ isPlainRecord,
10
+ readDataElements,
11
+ readDataProperties,
12
+ } from '../private/dataproperties.js';
8
13
 
9
14
  /**
10
15
  * Legacy image import: a greenfield deployment whose image is the one a legacy `deployOnPush`
11
16
  * service already runs, instead of one built from a source revision.
12
17
  *
13
18
  * A legacy service without deployable source still has an image in Cloudly's registry and, until
14
- * its runtime is frozen, healthy replicas running it. An administrator captures that fact once as
15
- * a {@link ILegacyServiceRuntimeAttestation} while the replicas still run. A greenfield successor
19
+ * its runtime is frozen, replicas running it. An administrator observes those replicas on the
20
+ * hosts that run them ({@link ILegacyServiceHostObservation}) while they still run, and Cloudly
21
+ * captures that observation once as a {@link ILegacyServiceRuntimeAttestation} after it verified
22
+ * the observed root against its own registry. A greenfield successor
16
23
  * reservation names the attestation in `legacyImport` instead of a `sourceRevision`, and Cloudly
17
24
  * then imports the attested image into the successor's own repository and release tag itself:
18
25
  * the bytes never leave the registry and the release records that it was imported, not built.
@@ -60,19 +67,98 @@ export interface ILegacyServiceImageSource {
60
67
  platforms: ILegacyImagePlatformManifest[];
61
68
  }
62
69
 
63
- /** One healthy replica of the legacy service, observed running the attested digest. */
70
+ /**
71
+ * One replica of the legacy service, observed running the attested digest in its own stated
72
+ * health: healthy, or running with no healthcheck that could state one.
73
+ */
64
74
  export interface ILegacyServiceRuntimeTaskAttestation {
75
+ /** The replica's runtime identity: the Swarm task it was observed as. */
65
76
  deploymentId: string;
77
+ /** The hostname of the node the replica was observed on. */
66
78
  nodeName: string;
67
79
  observedDigest: TSha256Digest;
68
80
  }
69
81
 
82
+ /**
83
+ * Where the runtime part of an attestation comes from. `administrator-host-observation`: an
84
+ * administrator read the legacy Swarm service and its containers on the hosts that run them, and
85
+ * Cloudly judged that observation against its own registry.
86
+ */
87
+ export type TLegacyServiceRuntimeEvidenceSource = 'administrator-host-observation';
88
+
89
+ /** A container's state as the Docker engine reports it (`State.Status`). */
90
+ export type TLegacyHostContainerState =
91
+ | 'created'
92
+ | 'running'
93
+ | 'paused'
94
+ | 'restarting'
95
+ | 'removing'
96
+ | 'exited'
97
+ | 'dead';
98
+
99
+ /**
100
+ * A container's health as the Docker engine reports it (`State.Health.Status`). `none`: no
101
+ * healthcheck applies to the container — the image declares none and the service adds none — so
102
+ * the engine reports no health state at all.
103
+ */
104
+ export type TLegacyHostContainerHealth = 'healthy' | 'unhealthy' | 'starting' | 'none';
105
+
106
+ /**
107
+ * The image store of the Docker engine that runs a container. On the `containerd` store a
108
+ * container's image id is the digest of the root it was pulled as; on the `classic` store it is
109
+ * the image configuration digest of the platform manifest the engine pulled.
110
+ */
111
+ export type TLegacyHostImageStore = 'containerd' | 'classic';
112
+
113
+ /** A Swarm service's mode (`Spec.Mode`): a replicated service states its desired replicas. */
114
+ export type TLegacyHostSwarmServiceMode =
115
+ | { kind: 'replicated'; desiredReplicas: number }
116
+ | { kind: 'global' };
117
+
118
+ /** One replica of a legacy Swarm service, as an administrator read it on the node that runs it. */
119
+ export interface ILegacyHostReplicaObservation {
120
+ /** The hostname of the node the task runs on. */
121
+ nodeHostname: string;
122
+ /** The Swarm task id (25 lowercase base-36 characters). */
123
+ swarmTaskId: string;
124
+ /** The full container id of the task (64 lowercase hex characters). */
125
+ containerId: string;
126
+ imageStore: TLegacyHostImageStore;
127
+ /** The container's image id (`Image`), a sha256 digest. */
128
+ containerImageId: TSha256Digest;
129
+ /** The `RepoDigests` of the container's image, exactly as the engine lists them. */
130
+ imageRepoDigests: string[];
131
+ state: TLegacyHostContainerState;
132
+ health: TLegacyHostContainerHealth;
133
+ }
134
+
135
+ /**
136
+ * An administrator's observation of the legacy Swarm service of one legacy service and of every
137
+ * container its tasks run, read on the hosts while the legacy runtime still runs.
138
+ *
139
+ * It states facts, not conclusions: Cloudly judges it against its own registry
140
+ * ({@link judgeLegacyServiceHostObservation}) before it attests anything.
141
+ */
142
+ export interface ILegacyServiceHostObservation {
143
+ /** The Swarm service name. */
144
+ swarmServiceName: string;
145
+ /** The image reference of the Swarm service spec (`Spec.TaskTemplate.ContainerSpec.Image`). */
146
+ specImage: string;
147
+ mode: TLegacyHostSwarmServiceMode;
148
+ /** When the administrator read the hosts, in milliseconds since the epoch. */
149
+ observedAt: number;
150
+ /** Every running task's replica, sorted by `swarmTaskId`. */
151
+ replicas: ILegacyHostReplicaObservation[];
152
+ }
153
+
70
154
  /**
71
155
  * Durable evidence, captured by an administrator while the legacy runtime still ran, that every
72
- * required replica of a legacy service was healthy and ran exactly the registry root it names.
156
+ * desired replica of a legacy service ran, in its own stated health, exactly the registry root it
157
+ * names.
73
158
  *
74
159
  * Cloudly writes one and never changes it. A capture only succeeds on complete evidence, so a
75
- * stored attestation is by construction one whose runtime digest is its source root digest.
160
+ * stored attestation is by construction one whose runtime digest is its source root digest and
161
+ * whose runtime part is exactly the host observation it records.
76
162
  */
77
163
  export interface ILegacyServiceRuntimeAttestation {
78
164
  id: string;
@@ -81,11 +167,16 @@ export interface ILegacyServiceRuntimeAttestation {
81
167
  organizationId: string;
82
168
  source: ILegacyServiceImageSource;
83
169
  runtime: {
170
+ /** The desired replicas of the observed replicated Swarm service. */
84
171
  requiredReplicaCount: number;
172
+ /** Replicas observed running healthy, or running with no healthcheck (`health: 'none'`). */
85
173
  healthyReplicaCount: number;
86
174
  runtimeDigest: TSha256Digest;
87
- /** Sorted by deploymentId, one per required replica. */
175
+ /** Sorted by deploymentId, one per required replica: the observed replicas. */
88
176
  tasks: ILegacyServiceRuntimeTaskAttestation[];
177
+ evidenceSource: TLegacyServiceRuntimeEvidenceSource;
178
+ /** The observation the runtime part was built from, as the administrator submitted it. */
179
+ hostObservation: ILegacyServiceHostObservation;
89
180
  };
90
181
  capturedByUserId: string;
91
182
  capturedAt: number;
@@ -120,6 +211,31 @@ const legacyImageImportIndexMediaTypes: readonly TLegacyImageImportIndexMediaTyp
120
211
  'application/vnd.docker.distribution.manifest.list.v2+json',
121
212
  ];
122
213
  const legacyImagePlatforms: readonly TImmutableContainerPlatform[] = ['linux/amd64', 'linux/arm64'];
214
+ const legacyHostContainerStates: readonly TLegacyHostContainerState[] = [
215
+ 'created',
216
+ 'running',
217
+ 'paused',
218
+ 'restarting',
219
+ 'removing',
220
+ 'exited',
221
+ 'dead',
222
+ ];
223
+ const legacyHostContainerHealths: readonly TLegacyHostContainerHealth[] = [
224
+ 'healthy',
225
+ 'unhealthy',
226
+ 'starting',
227
+ 'none',
228
+ ];
229
+ /** The health states a replica may be attested in: healthy, or no healthcheck at all. */
230
+ const attestableLegacyHostContainerHealths: readonly TLegacyHostContainerHealth[] = ['healthy', 'none'];
231
+ const legacyHostImageStores: readonly TLegacyHostImageStore[] = ['containerd', 'classic'];
232
+ const swarmTaskIdRegex = /^[a-z0-9]{25}$/;
233
+ const containerIdRegex = /^[0-9a-f]{64}$/;
234
+ const swarmServiceNameRegex = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/;
235
+ const nodeHostnameRegex = /^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
236
+ const imageReferenceRegex = /^\S{1,512}$/;
237
+ const repoDigestRegex = /^[^\s@]{1,440}@sha256:[0-9a-f]{64}$/;
238
+ const maximumRepoDigestCount = 32;
123
239
 
124
240
  const isIdentifier = (valueArg: unknown): valueArg is string => (
125
241
  typeof valueArg === 'string' && identifierRegex.test(valueArg)
@@ -168,6 +284,256 @@ export const validateLegacyImageImportReference = (referenceArg: unknown): strin
168
284
  return errors;
169
285
  };
170
286
 
287
+ const validateHostReplicaObservation = (
288
+ replicaArg: unknown,
289
+ labelArg: string,
290
+ ): string[] => {
291
+ const replica = readDataProperties(replicaArg);
292
+ if (replica === null) return [`${labelArg} must be a plain data object`];
293
+ const errors: string[] = [];
294
+ if (!hasExactKeys(replica, [
295
+ 'nodeHostname',
296
+ 'swarmTaskId',
297
+ 'containerId',
298
+ 'imageStore',
299
+ 'containerImageId',
300
+ 'imageRepoDigests',
301
+ 'state',
302
+ 'health',
303
+ ])) {
304
+ errors.push(`${labelArg} must use its exact schema`);
305
+ }
306
+ if (typeof replica.nodeHostname !== 'string' || !nodeHostnameRegex.test(replica.nodeHostname)) {
307
+ errors.push(`${labelArg}.nodeHostname must be a host name`);
308
+ }
309
+ if (typeof replica.swarmTaskId !== 'string' || !swarmTaskIdRegex.test(replica.swarmTaskId)) {
310
+ errors.push(`${labelArg}.swarmTaskId must be a Swarm task id`);
311
+ }
312
+ if (typeof replica.containerId !== 'string' || !containerIdRegex.test(replica.containerId)) {
313
+ errors.push(`${labelArg}.containerId must be a full container id`);
314
+ }
315
+ if (!legacyHostImageStores.some((storeArg) => storeArg === replica.imageStore)) {
316
+ errors.push(`${labelArg}.imageStore must be containerd or classic`);
317
+ }
318
+ if (!isCanonicalDigest(replica.containerImageId)) {
319
+ errors.push(`${labelArg}.containerImageId must be a canonical sha256 digest`);
320
+ }
321
+ const repoDigests = readDataElements(replica.imageRepoDigests, maximumRepoDigestCount);
322
+ if (repoDigests === null
323
+ || repoDigests.some((entryArg) => typeof entryArg !== 'string' || !repoDigestRegex.test(entryArg))
324
+ || new Set(repoDigests).size !== repoDigests.length) {
325
+ errors.push(`${labelArg}.imageRepoDigests must be unique digested image references`);
326
+ }
327
+ if (!legacyHostContainerStates.some((stateArg) => stateArg === replica.state)) {
328
+ errors.push(`${labelArg}.state must be a Docker container state`);
329
+ }
330
+ if (!legacyHostContainerHealths.some((healthArg) => healthArg === replica.health)) {
331
+ errors.push(`${labelArg}.health must be healthy, unhealthy, starting or none`);
332
+ }
333
+ return errors;
334
+ };
335
+
336
+ const validateHostSwarmServiceMode = (modeArg: unknown, labelArg: string): string[] => {
337
+ const mode = readDataProperties(modeArg);
338
+ if (mode === null) return [`${labelArg} must be a plain data object`];
339
+ if (mode.kind === 'global') {
340
+ return hasExactKeys(mode, ['kind']) ? [] : [`${labelArg} must use its exact schema`];
341
+ }
342
+ if (mode.kind !== 'replicated') return [`${labelArg}.kind must be replicated or global`];
343
+ const errors: string[] = [];
344
+ if (!hasExactKeys(mode, ['kind', 'desiredReplicas'])) {
345
+ errors.push(`${labelArg} must use its exact schema`);
346
+ }
347
+ if (typeof mode.desiredReplicas !== 'number'
348
+ || !Number.isSafeInteger(mode.desiredReplicas)
349
+ || mode.desiredReplicas < 0
350
+ || mode.desiredReplicas > maximumReplicaCount) {
351
+ errors.push(`${labelArg}.desiredReplicas must be a bounded replica count`);
352
+ }
353
+ return errors;
354
+ };
355
+
356
+ /**
357
+ * The shape of a host observation: exact keys at every level, Docker's own value sets, at most 64
358
+ * replicas, unique and sorted by Swarm task id, each container observed once. It judges nothing
359
+ * against a registry; {@link judgeLegacyServiceHostObservation} does.
360
+ */
361
+ export const validateLegacyServiceHostObservation = (
362
+ observationArg: unknown,
363
+ labelArg = 'hostObservation',
364
+ ): string[] => {
365
+ const observation = readDataProperties(observationArg);
366
+ if (observation === null) return [`${labelArg} must be a plain data object`];
367
+ const errors: string[] = [];
368
+ if (!hasExactKeys(observation, ['swarmServiceName', 'specImage', 'mode', 'observedAt', 'replicas'])) {
369
+ errors.push(`${labelArg} must use its exact schema`);
370
+ }
371
+ if (typeof observation.swarmServiceName !== 'string'
372
+ || !swarmServiceNameRegex.test(observation.swarmServiceName)) {
373
+ errors.push(`${labelArg}.swarmServiceName must be a Swarm service name`);
374
+ }
375
+ if (typeof observation.specImage !== 'string' || !imageReferenceRegex.test(observation.specImage)) {
376
+ errors.push(`${labelArg}.specImage must be a bounded image reference`);
377
+ }
378
+ errors.push(...validateHostSwarmServiceMode(observation.mode, `${labelArg}.mode`));
379
+ if (!isPositiveSafeInteger(observation.observedAt, Number.MAX_SAFE_INTEGER)) {
380
+ errors.push(`${labelArg}.observedAt must be a positive timestamp`);
381
+ }
382
+ const replicas = readDataElements(observation.replicas, maximumReplicaCount);
383
+ if (replicas === null) {
384
+ errors.push(`${labelArg}.replicas must be a list of at most ${maximumReplicaCount} replicas`);
385
+ return errors;
386
+ }
387
+ replicas.forEach((replicaArg, indexArg) => {
388
+ errors.push(...validateHostReplicaObservation(replicaArg, `${labelArg}.replicas[${indexArg}]`));
389
+ });
390
+ const readReplicaKey = (replicaArg: unknown, keyArg: string): unknown => (
391
+ readDataProperties(replicaArg)?.[keyArg]
392
+ );
393
+ const taskIds = replicas.map((replicaArg) => readReplicaKey(replicaArg, 'swarmTaskId'));
394
+ const sortedTaskIds = taskIds
395
+ .filter((idArg): idArg is string => typeof idArg === 'string')
396
+ .sort();
397
+ if (new Set(taskIds).size !== taskIds.length
398
+ || JSON.stringify(taskIds) !== JSON.stringify(sortedTaskIds)) {
399
+ errors.push(`${labelArg}.replicas must be unique and sorted by swarmTaskId`);
400
+ }
401
+ const containerIds = replicas.map((replicaArg) => readReplicaKey(replicaArg, 'containerId'));
402
+ if (new Set(containerIds).size !== containerIds.length) {
403
+ errors.push(`${labelArg}.replicas must observe each container once`);
404
+ }
405
+ return errors;
406
+ };
407
+
408
+ /** True when a value is a well-formed host observation. */
409
+ export const isLegacyServiceHostObservation = (
410
+ valueArg: unknown,
411
+ ): valueArg is ILegacyServiceHostObservation => (
412
+ validateLegacyServiceHostObservation(valueArg).length === 0
413
+ );
414
+
415
+ /**
416
+ * The root digest one replica was pulled as from `registryHost/repository`.
417
+ *
418
+ * On the containerd store that is the container's image id, which the image's `RepoDigests` must
419
+ * list for the repository. On the classic store it is the one digest `RepoDigests` lists for the
420
+ * repository; none, or more than one, leaves the root unknown.
421
+ */
422
+ const selectReplicaRootDigest = (
423
+ replicaArg: ILegacyHostReplicaObservation,
424
+ repositoryReferenceArg: string,
425
+ ): TSha256Digest | undefined => {
426
+ const prefix = `${repositoryReferenceArg}@`;
427
+ const repositoryDigests = replicaArg.imageRepoDigests
428
+ .filter((entryArg) => entryArg.startsWith(prefix))
429
+ .map((entryArg) => normalizeSha256Digest(entryArg.slice(prefix.length)))
430
+ .filter((digestArg): digestArg is TSha256Digest => digestArg !== undefined);
431
+ if (replicaArg.imageStore === 'containerd') {
432
+ return repositoryDigests.includes(replicaArg.containerImageId)
433
+ ? replicaArg.containerImageId
434
+ : undefined;
435
+ }
436
+ return repositoryDigests.length === 1 ? repositoryDigests[0] : undefined;
437
+ };
438
+
439
+ /**
440
+ * The one root digest every observed replica runs from the legacy service's own repository, which
441
+ * is the digest Cloudly then inspects in its registry. Refused when a replica's root from that
442
+ * repository is unknown, when the replicas run more than one root, or when nothing was observed.
443
+ */
444
+ export const selectLegacyServiceHostObservationRootDigest = (argsArg: {
445
+ observation: ILegacyServiceHostObservation;
446
+ registryHost: string;
447
+ repository: string;
448
+ }): { rootDigest?: TSha256Digest; errors: string[] } => {
449
+ const repositoryReference = `${argsArg.registryHost}/${argsArg.repository}`;
450
+ const errors: string[] = [];
451
+ const roots = new Set<TSha256Digest>();
452
+ argsArg.observation.replicas.forEach((replicaArg, indexArg) => {
453
+ const root = selectReplicaRootDigest(replicaArg, repositoryReference);
454
+ if (root === undefined) {
455
+ errors.push(replicaArg.imageStore === 'containerd'
456
+ ? `hostObservation.replicas[${indexArg}] image is not listed as ${repositoryReference}@<its image id>`
457
+ : `hostObservation.replicas[${indexArg}] image lists not exactly one digest of ${repositoryReference}`);
458
+ return;
459
+ }
460
+ roots.add(root);
461
+ });
462
+ if (argsArg.observation.replicas.length === 0) {
463
+ errors.push('hostObservation must observe at least one replica');
464
+ }
465
+ if (roots.size > 1) {
466
+ errors.push('hostObservation replicas run more than one root digest');
467
+ }
468
+ const [rootDigest] = [...roots];
469
+ return errors.length === 0 && rootDigest !== undefined ? { rootDigest, errors } : { errors };
470
+ };
471
+
472
+ /**
473
+ * Judges a well-formed host observation against the registry source Cloudly inspected for it.
474
+ * Every rule an attestation's runtime part must meet:
475
+ *
476
+ * - the Swarm service is replicated, with at least one desired replica, and exactly its desired
477
+ * replicas were observed;
478
+ * - its spec image names the source repository by the source tag, by the root digest, or by both;
479
+ * - every replica is `running`, and `healthy` or without a healthcheck (`none`) — `unhealthy` and
480
+ * `starting` are refused;
481
+ * - every replica runs the source root from the source repository: its image lists
482
+ * `registryHost/repository@rootDigest`, and its image id is the root digest on the containerd
483
+ * store or one of the root's platform image configuration digests on the classic store.
484
+ */
485
+ export const judgeLegacyServiceHostObservation = (argsArg: {
486
+ observation: ILegacyServiceHostObservation;
487
+ source: ILegacyServiceImageSource;
488
+ label?: string;
489
+ }): string[] => {
490
+ const label = argsArg.label ?? 'hostObservation';
491
+ const { observation, source } = argsArg;
492
+ const errors: string[] = [];
493
+ if (observation.mode.kind !== 'replicated') {
494
+ errors.push(`${label}.mode must be replicated: a legacy service runs as a replicated Swarm service`);
495
+ } else if (observation.mode.desiredReplicas < 1) {
496
+ errors.push(`${label}.mode must desire at least one replica`);
497
+ } else if (observation.replicas.length !== observation.mode.desiredReplicas) {
498
+ errors.push(`${label} must observe exactly the ${observation.mode.desiredReplicas} desired replicas`);
499
+ }
500
+ const repositoryReference = `${source.registryHost}/${source.repository}`;
501
+ const specImages = [
502
+ `${repositoryReference}:${source.tag}`,
503
+ `${repositoryReference}@${source.rootDigest}`,
504
+ `${repositoryReference}:${source.tag}@${source.rootDigest}`,
505
+ ];
506
+ if (!specImages.includes(observation.specImage)) {
507
+ errors.push(`${label}.specImage must name ${repositoryReference} by its source tag or root digest`);
508
+ }
509
+ const imageConfigDigests = source.platforms.map((platformArg) => platformArg.imageConfigDigest);
510
+ observation.replicas.forEach((replicaArg, indexArg) => {
511
+ const replicaLabel = `${label}.replicas[${indexArg}]`;
512
+ if (replicaArg.state !== 'running') {
513
+ errors.push(`${replicaLabel}.state must be running`);
514
+ }
515
+ if (!attestableLegacyHostContainerHealths.includes(replicaArg.health)) {
516
+ errors.push(`${replicaLabel}.health must be healthy or none`);
517
+ }
518
+ if (!replicaArg.imageRepoDigests.includes(`${repositoryReference}@${source.rootDigest}`)) {
519
+ errors.push(`${replicaLabel} image must be ${repositoryReference}@${source.rootDigest}`);
520
+ }
521
+ if (replicaArg.imageStore === 'containerd') {
522
+ if (replicaArg.containerImageId !== source.rootDigest) {
523
+ errors.push(`${replicaLabel}.containerImageId must be the root digest on the containerd image store`);
524
+ }
525
+ return;
526
+ }
527
+ if (!imageConfigDigests.includes(replicaArg.containerImageId)) {
528
+ errors.push(`${replicaLabel}.containerImageId must be a platform image configuration digest of the root on the classic image store`);
529
+ }
530
+ if (selectReplicaRootDigest(replicaArg, repositoryReference) === undefined) {
531
+ errors.push(`${replicaLabel} image must list exactly one digest of ${repositoryReference} on the classic image store`);
532
+ }
533
+ });
534
+ return errors;
535
+ };
536
+
171
537
  const validatePlatformManifest = (
172
538
  manifestArg: unknown,
173
539
  indexArg: number,
@@ -270,17 +636,54 @@ const validateImageSource = (sourceArg: unknown): string[] => {
270
636
  return errors;
271
637
  };
272
638
 
273
- const validateRuntime = (runtimeArg: unknown, rootDigestArg: unknown): string[] => {
639
+ const isLegacyServiceImageSource = (valueArg: unknown): valueArg is ILegacyServiceImageSource => (
640
+ validateImageSource(valueArg).length === 0
641
+ );
642
+
643
+ const validateRuntime = (runtimeArg: unknown, sourceArg: unknown): string[] => {
274
644
  if (!isPlainRecord(runtimeArg)) return ['runtime must be an object'];
645
+ const rootDigest = isPlainRecord(sourceArg) ? sourceArg.rootDigest : undefined;
275
646
  const errors: string[] = [];
276
647
  if (!hasExactKeys(runtimeArg, [
277
648
  'requiredReplicaCount',
278
649
  'healthyReplicaCount',
279
650
  'runtimeDigest',
280
651
  'tasks',
652
+ 'evidenceSource',
653
+ 'hostObservation',
281
654
  ])) {
282
655
  errors.push('runtime must use its exact schema');
283
656
  }
657
+ if (runtimeArg.evidenceSource !== 'administrator-host-observation') {
658
+ errors.push('runtime.evidenceSource must be administrator-host-observation');
659
+ }
660
+ const hostObservation = runtimeArg.hostObservation;
661
+ const observationErrors = validateLegacyServiceHostObservation(
662
+ hostObservation, 'runtime.hostObservation');
663
+ errors.push(...observationErrors);
664
+ if (observationErrors.length === 0
665
+ && isLegacyServiceHostObservation(hostObservation)
666
+ && isLegacyServiceImageSource(sourceArg)) {
667
+ errors.push(...judgeLegacyServiceHostObservation({
668
+ observation: hostObservation,
669
+ source: sourceArg,
670
+ label: 'runtime.hostObservation',
671
+ }));
672
+ if (hostObservation.mode.kind === 'replicated'
673
+ && runtimeArg.requiredReplicaCount !== hostObservation.mode.desiredReplicas) {
674
+ errors.push('runtime.requiredReplicaCount must be the observed desired replicas');
675
+ }
676
+ const recordedTasks = readDataElements(runtimeArg.tasks, maximumReplicaCount) ?? [];
677
+ if (recordedTasks.length !== hostObservation.replicas.length
678
+ || hostObservation.replicas.some((replicaArg, indexArg) => {
679
+ const task = recordedTasks[indexArg];
680
+ return !isPlainRecord(task)
681
+ || task.deploymentId !== replicaArg.swarmTaskId
682
+ || task.nodeName !== replicaArg.nodeHostname;
683
+ })) {
684
+ errors.push('runtime.tasks must be the observed replicas: each Swarm task on its node');
685
+ }
686
+ }
284
687
  if (!isPositiveSafeInteger(runtimeArg.requiredReplicaCount, maximumReplicaCount)) {
285
688
  errors.push('runtime.requiredReplicaCount must be a positive bounded replica count');
286
689
  }
@@ -289,7 +692,7 @@ const validateRuntime = (runtimeArg: unknown, rootDigestArg: unknown): string[]
289
692
  }
290
693
  if (!isCanonicalDigest(runtimeArg.runtimeDigest)) {
291
694
  errors.push('runtime.runtimeDigest must be a canonical sha256 digest');
292
- } else if (runtimeArg.runtimeDigest !== rootDigestArg) {
695
+ } else if (runtimeArg.runtimeDigest !== rootDigest) {
293
696
  errors.push('runtime.runtimeDigest must be the attested source root digest');
294
697
  }
295
698
  if (!Array.isArray(runtimeArg.tasks) || runtimeArg.tasks.length !== runtimeArg.requiredReplicaCount) {
@@ -363,9 +766,6 @@ export const validateLegacyServiceRuntimeAttestation = (attestationArg: unknown)
363
766
  errors.push('capturedAt must be a positive timestamp');
364
767
  }
365
768
  errors.push(...validateImageSource(data.source));
366
- errors.push(...validateRuntime(
367
- data.runtime,
368
- isPlainRecord(data.source) ? data.source.rootDigest : undefined,
369
- ));
769
+ errors.push(...validateRuntime(data.runtime, data.source));
370
770
  return errors;
371
771
  };
package/ts/data/index.ts CHANGED
@@ -72,6 +72,7 @@ export * from './baremetal.js';
72
72
  export * from './baseos.js';
73
73
  export * from './backup.js';
74
74
  export * from './clusternode.js';
75
+ export * from './clusternodehostname.js';
75
76
  export * from './settings.js';
76
77
  export * from './sparklegacyretirement.js';
77
78
  export * from './sparknodereport.js';
@@ -1,7 +1,8 @@
1
1
  import { isReleaseVersion } from './releaseversion.js';
2
- import { readExactDataRecord } from '../private/dataproperties.js';
2
+ import { readDataProperties, readExactDataRecord } from '../private/dataproperties.js';
3
3
  import { isClusterNodeId } from '../private/nodeidentifier.js';
4
4
  import { protocolRefusalHttpStatus, readProtocolOffer, type IProtocolOffer } from '../protocol.js';
5
+ import { isClusterNodeHostname } from './clusternodehostname.js';
5
6
 
6
7
  /** Host observations only. Container and workload readiness belong to Pallet. */
7
8
  export interface ISparkNodeReport {
@@ -22,8 +23,32 @@ export interface ISparkNodeReport {
22
23
  localRuntimeReady: true;
23
24
  workloadReadiness: 'unverified';
24
25
  };
26
+ /**
27
+ * The outcome of Spark's last attempt to apply a desired hostname (`sparkNodeHostContract`), when
28
+ * it made one since it started. Whether the node carries the hostname is `runtime.hostname`.
29
+ */
30
+ hostApply?: ISparkNodeHostApply;
25
31
  }
26
32
 
33
+ /** Whether Spark applied a desired hostname: `applied` once the host carries it. */
34
+ export type TSparkNodeHostApplyOutcome = 'applied' | 'failed';
35
+
36
+ /** One attempt to apply the desired hostname of one generation. */
37
+ export interface ISparkNodeHostApply {
38
+ /** The `ISparkNodeDesiredHost.generation` the attempt applied. */
39
+ generation: number;
40
+ /** The hostname it applied. */
41
+ hostname: string;
42
+ outcome: TSparkNodeHostApplyOutcome;
43
+ /** `failed` only, and required there: why, as operator text. */
44
+ reason?: string;
45
+ }
46
+
47
+ /** Bounds of `ISparkNodeHostApply.reason`. */
48
+ export const sparkNodeHostApplyContract = Object.freeze({
49
+ maximumReasonLength: 512,
50
+ } as const);
51
+
27
52
  /** HTTPS POST body. Never log, persist, or return nodeToken. */
28
53
  export interface ISparkNodeHeartbeatRequest {
29
54
  nodeId: string;
@@ -101,9 +126,28 @@ const integer = (valueArg: unknown, minimumArg: number): number => {
101
126
  return value;
102
127
  };
103
128
 
129
+ /** One `hostApply`: exactly its keys, a reason exactly when it failed. */
130
+ const snapshotSparkNodeHostApply = (valueArg: unknown): ISparkNodeHostApply => {
131
+ const keys = ['generation', 'hostname', 'outcome'];
132
+ const value = readExactDataRecord(valueArg, keys) ?? record(valueArg, [...keys, 'reason']);
133
+ requireValue(isClusterNodeHostname(value.hostname));
134
+ const generation = integer(value.generation, 1);
135
+ if (value.outcome === 'applied') {
136
+ requireValue(value.reason === undefined);
137
+ return Object.freeze({ generation, hostname: value.hostname, outcome: 'applied' });
138
+ }
139
+ requireValue(value.outcome === 'failed');
140
+ return Object.freeze({ generation, hostname: value.hostname, outcome: 'failed',
141
+ reason: text(value.reason, /^[\x20-\x7e]+$/, sparkNodeHostApplyContract.maximumReasonLength) });
142
+ };
143
+
104
144
  /** Exact inert JSON records; detaches and freezes before any consumer awaits. */
105
145
  export const snapshotSparkNodeReport = (valueArg: unknown): ISparkNodeReport => {
106
- const value = record(valueArg, ['observedAt', 'metrics', 'runtime']);
146
+ const reportKeys = ['observedAt', 'metrics', 'runtime'];
147
+ const properties = readDataProperties(valueArg);
148
+ requireValue(properties !== null);
149
+ const hasHostApply = Object.hasOwn(properties, 'hostApply');
150
+ const value = record(valueArg, hasHostApply ? [...reportKeys, 'hostApply'] : reportKeys);
107
151
  const metrics = record(value.metrics, ['cpuUsagePercent', 'memoryUsedMB', 'memoryAvailableMB',
108
152
  'diskUsedGB', 'diskAvailableGB']);
109
153
  const runtime = record(value.runtime, ['hostname', 'platform', 'arch', 'osRelease', 'bundle',
@@ -130,6 +174,7 @@ export const snapshotSparkNodeReport = (valueArg: unknown): ISparkNodeReport =>
130
174
  }),
131
175
  localRuntimeReady: true, workloadReadiness: 'unverified',
132
176
  }),
177
+ ...(hasHostApply ? { hostApply: snapshotSparkNodeHostApply(value.hostApply) } : {}),
133
178
  });
134
179
  };
135
180
 
@@ -155,3 +200,68 @@ export const snapshotSparkNodeHeartbeatReceipt = (valueArg: unknown): ISparkNode
155
200
  protocol: readProtocolOffer(value),
156
201
  });
157
202
  };
203
+
204
+ /** HTTPS POST body asking for the hostname Cloudly wants the node to carry. Never log, persist, or return nodeToken. */
205
+ export interface ISparkNodeHostRequest {
206
+ nodeId: string;
207
+ nodeToken: string;
208
+ /** Read and negotiated before the node is authenticated; see `sparkNodeHostContract`. */
209
+ protocol: IProtocolOffer;
210
+ }
211
+
212
+ /**
213
+ * The hostname Cloudly wants the node to carry: `IClusterNode.data.hostnameIntent`, as the node
214
+ * applies it.
215
+ *
216
+ * `hostname: null` with `generation: 0` states that Cloudly holds no intent for the node, and Spark
217
+ * leaves the host's hostname as it is. Applying is idempotent: a host that already carries the
218
+ * hostname is left alone, and every answer states the whole desired value rather than a change.
219
+ */
220
+ export interface ISparkNodeDesiredHost {
221
+ nodeId: string;
222
+ hostname: string | null;
223
+ generation: number;
224
+ /** The controller's offer, so the node judges the answer it acts on. */
225
+ protocol: IProtocolOffer;
226
+ }
227
+
228
+ /**
229
+ * The node runtime's desired-host route.
230
+ *
231
+ * Authenticated with the node's Spark credential exactly like `sparkNodeHeartbeatContract`, and
232
+ * judged in the same server order: protocol offer first, against this server's `sparkNode` offer
233
+ * and within `maxRequestBytes`, answered with `protocolRefusalStatus` and an `IProtocolRefusal` body
234
+ * on refusal, before the node is authenticated. Spark reports the outcome of applying the answer as
235
+ * `ISparkNodeReport.hostApply` on its next heartbeat.
236
+ */
237
+ export const sparkNodeHostContract = Object.freeze({
238
+ endpoint: '/spark/nodes/host',
239
+ maxRequestBytes: 1024,
240
+ maxResponseBytes: 1024,
241
+ protocolRefusalStatus: protocolRefusalHttpStatus,
242
+ } as const);
243
+
244
+ export const snapshotSparkNodeHostRequest = (valueArg: unknown): ISparkNodeHostRequest => {
245
+ const value = record(valueArg, ['nodeId', 'nodeToken', 'protocol']);
246
+ return Object.freeze({
247
+ nodeId: nodeId(value.nodeId),
248
+ nodeToken: text(value.nodeToken, /^secureToken[a-f0-9]{64}$/, 75),
249
+ protocol: readProtocolOffer(value),
250
+ });
251
+ };
252
+
253
+ export const snapshotSparkNodeDesiredHost = (valueArg: unknown): ISparkNodeDesiredHost => {
254
+ const value = record(valueArg, ['nodeId', 'hostname', 'generation', 'protocol']);
255
+ const hostname = value.hostname;
256
+ if (hostname === null) {
257
+ requireValue(value.generation === 0);
258
+ } else {
259
+ requireValue(isClusterNodeHostname(hostname));
260
+ }
261
+ return Object.freeze({
262
+ nodeId: nodeId(value.nodeId),
263
+ hostname,
264
+ generation: hostname === null ? 0 : integer(value.generation, 1),
265
+ protocol: readProtocolOffer(value),
266
+ });
267
+ };