@serve.zone/interfaces 32.72.0 → 32.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/readme.md CHANGED
@@ -3256,6 +3256,21 @@ Common data contracts include:
3256
3256
  - `IUser`, JWT-only `IIdentityCredential`, full `IIdentity`, and token-related contracts for authentication context. `IIdentity` extends `IIdentityCredential` with server-issued user metadata.
3257
3257
  - `ICloudlyConfig`, `ICloudlySettings`, status, server, bare-metal, BaseOS, backup, and task execution interfaces for control-plane state.
3258
3258
 
3259
+ ### Cloudly Hosting Contract
3260
+
3261
+ What a host (Docker, Kubernetes, Onebox) gives the Cloudly server is stated by constants in
3262
+ `data`: `cloudlyHostRequiredEnvironment` lists the variables Cloudly refuses to start without,
3263
+ naming each missing one, and `cloudlyHostOptionalEnvironment` the ones it reads but starts
3264
+ without; together they are
3265
+ every variable Cloudly reads. The five `cloudlyHostPlatformOidcEnvironment` names are all or
3266
+ none, with the redirect URI `${publicOrigin}/auth/oidc/callback`. Cloudly binds
3267
+ `SERVEZONE_LISTENPORT` (`cloudlyDefaultListenPort`, 3000, when unset) and answers its health
3268
+ on `cloudlyStatusPath` (`/status`). `SERVEZONE_ADMINACCOUNT` is deprecated and read until
3269
+ Cloudly 34.0.0; `SERVEZONE_INSTALL_DEMO_DATA` is outside the contract. No host extras exist:
3270
+ they arrive only through a list the host advertises, so an app never branches on `hostType`.
3271
+ `ICloudlyConfig.letsEncryptEmail`, `letsEncryptPrivateKey`, `jwtKeypair` and the `sslMode`
3272
+ value `'letsencrypt'` are deprecated. The full hosting guide is Cloudly's readme.
3273
+
3259
3274
  ### Cluster Relay Block
3260
3275
 
3261
3276
  `ICluster.data.relay` is the optional `IClusterRelay { origin: string }`
@@ -3768,6 +3783,56 @@ const ingressReasons = data.validateClusterIngressRegistration({
3768
3783
  }); // []
3769
3784
  ```
3770
3785
 
3786
+ ### Locations
3787
+
3788
+ A location (`data.ILocation`) is a room Cloudly's physical objects stand in: one record with a
3789
+ fixed `id`, which every reference uses, and one unique, renamable `name`, one lowercase RFC 1123
3790
+ label (`data.isLocationName`). Every Cloudly database holds exactly one initial location
3791
+ (`data.initialLocationId`, created as `data.initialLocationName`, `initial`); it receives every
3792
+ create that names no location for a cluster without nodes, and `getLocations` marks it
3793
+ `receivesUnnamedCreates`.
3794
+
3795
+ - A node carries its location in `IClusterNode.data.locationId`, optional here because a
3796
+ controller without locations leaves it out; a Cloudly with locations sets it on every node.
3797
+ - A cluster stands where its nodes stand: `data.getClusterLocationId(cluster)` reads the cluster's
3798
+ `data.nodes` copies, answers `undefined` for a cluster without nodes (or one whose copies name no
3799
+ location) and throws `data.ClusterSpansLocationsError` when the copies disagree, a state Cloudly
3800
+ never writes. A cluster moves only whole (`setClusterLocation`), which writes every node to the
3801
+ target in one transaction and so also repairs a cluster that spans locations; it never answers
3802
+ `cluster-spans-locations`.
3803
+ - A BareMetal server stands where the node whose `data.baremetalId` names it stands;
3804
+ `IBareMetal.data.location` stays the provider's datacenter.
3805
+ - The member kinds are the stored kinds `data.locationMemberKinds` (`edge`, `gateway`, `node`,
3806
+ `oneboxHost`); `getLocations` answers which of them the Cloudly records
3807
+ (`recordedMemberKinds`). A cluster is no member and no part of the digest: `getClusters` with a
3808
+ `locationScope` lists the clusters standing in a location.
3809
+ - `data.initialLocationId` (`location-initial`) is fixed; Cloudly generates every other location id
3810
+ with a generator that can never produce it.
3811
+
3812
+ An administrator confirms a location's membership with the digest of the view they read
3813
+ (`confirmLocationMembership`). The location stores the confirmed digest; it is confirmed while that
3814
+ equals the current one (`data.isLocationMembershipConfirmed`), so nothing rewrites it when membership
3815
+ changes, and a confirmation of a stale digest is refused `membership-changed`.
3816
+ `data.computeLocationMembershipDigest(members, recordedKinds)` is `sha256:<hex>` (Web Crypto) of the
3817
+ canonical JSON of the sorted `[kind, id]` pairs and the recorded kinds
3818
+ (`data.createLocationMembershipDigestInput`), independent of the order either is listed in.
3819
+
3820
+ The requests (`requests.location`) are administrator-only, admitted by no delegated-admin scope:
3821
+ `createLocation`, `renameLocation`, `getLocations`, `setClusterLocation` (answers
3822
+ `data.setClusterLocationOutcomes`: `moved`, `unchanged`, or `cluster-empty` for a cluster without
3823
+ nodes) and `confirmLocationMembership`. Every refusal is one of `data.locationRefusals`.
3824
+ `createCluster` and `createNodeJumpCommand` take an optional `locationId`; for a cluster with nodes
3825
+ a named location must be the cluster's (`location-mismatch`). A `createCluster` that names a
3826
+ location but creates no node (`setupMode` `manual` or absent) is refused `location-needs-node`,
3827
+ checked before `location-not-found`: name the location on `createNodeJumpCommand` instead.
3828
+ `getClusters`, `getNodes` and `getBaremetalServers` take an optional `locationScope` and echo it as `appliedLocationScope`: a
3829
+ response without the echo comes from a Cloudly that ignored the scope and is not scoped.
3830
+
3831
+ Cloudly's 0.39.0 → 0.40.0 data step writes one transaction per cluster (the cluster document and
3832
+ all its node documents, setting `locationId` only where it is missing, so a rerun is safe) and one
3833
+ transaction per node whose `clusterId` names no existing cluster. It never calls
3834
+ `data.getClusterLocationId`, which throws for node copies that disagree.
3835
+
3771
3836
  ### Node Uplink Address
3772
3837
 
3773
3838
  A route to a node's published host ports needs the address that node answers on, and only the
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@serve.zone/interfaces',
6
- version: '32.72.0',
6
+ version: '32.74.0',
7
7
  description: 'Shared TypeScript interfaces and TypedRequest contracts for the serve.zone ecosystem.'
8
8
  }
@@ -1,9 +1,22 @@
1
1
  import * as plugins from '../plugins.js';
2
+ import { hostedAppRuntimeIdentityKeys } from './hostedapp.js';
2
3
 
3
4
  export interface ICloudlyConfig {
4
5
  environment?: 'production' | 'integration';
6
+ /**
7
+ * @deprecated Cloudly issues no certificate of its own: TLS is terminated in front of it
8
+ * (`sslMode` `external`) or not at all (`none`). The next major of this package removes it.
9
+ */
5
10
  letsEncryptEmail?: string;
11
+ /**
12
+ * @deprecated Cloudly issues no certificate of its own: TLS is terminated in front of it
13
+ * (`sslMode` `external`) or not at all (`none`). The next major of this package removes it.
14
+ */
6
15
  letsEncryptPrivateKey?: string;
16
+ /**
17
+ * @deprecated Cloudly does not read a JWT keypair from its configuration; it keeps its own.
18
+ * The next major of this package removes it.
19
+ */
7
20
  jwtKeypair?: plugins.tsclass.network.IJwtKeypair;
8
21
  mongoDescriptor?: plugins.tsclass.database.IMongoDescriptor;
9
22
  s3Descriptor?: plugins.tsclass.storage.IS3Descriptor;
@@ -15,6 +28,140 @@ export interface ICloudlyConfig {
15
28
  * Internal port the Cloudly server binds to.
16
29
  */
17
30
  listenPort?: string;
31
+ /**
32
+ * How TLS reaches Cloudly: `external` (terminated in front of it) or `none`.
33
+ *
34
+ * The value `'letsencrypt'` is deprecated: Cloudly refuses to start with it, because it no longer
35
+ * terminates TLS itself, and the next major of this package removes it from this type.
36
+ */
18
37
  sslMode?: 'none' | 'letsencrypt' | 'external';
38
+ /**
39
+ * @deprecated Human sign-in moves into Cloudly itself (AGL-1179): idp.global, Cloudly's own
40
+ * passkeys, and `cloudly login-token` minted inside the Cloudly container for the first admin and
41
+ * break-glass. Cloudly 34.0.0 no longer reads this key, and the next major of this package
42
+ * removes it.
43
+ */
19
44
  servezoneAdminaccount?: string;
20
45
  }
46
+
47
+ /**
48
+ * The environment a host must give the Cloudly server: Cloudly refuses to start when one of these
49
+ * is missing, naming every missing variable (its `qenv.yml` required list). Together with
50
+ * `cloudlyHostOptionalEnvironment` this is every variable Cloudly reads from its environment.
51
+ */
52
+ export const cloudlyHostRequiredEnvironment = Object.freeze([
53
+ /**
54
+ * The deployment environment. Production hosts set `production`; any other value turns on
55
+ * development reloading. The value is fixed for the life of a database: Cloudly binds it into
56
+ * the credentials and sessions it stores.
57
+ */
58
+ 'SERVEZONE_ENVIRONMENT',
59
+ /**
60
+ * The origin clients reach Cloudly under: `http` or `https`, with an optional port, and no path,
61
+ * query or fragment. Ingress passes the request's `Host` unchanged, so it equals this origin's
62
+ * `host[:port]`.
63
+ */
64
+ 'SERVEZONE_PUBLIC_ORIGIN',
65
+ /**
66
+ * `external` (TLS is terminated in front of Cloudly) or `none`. Cloudly terminates no TLS itself.
67
+ */
68
+ 'SERVEZONE_SSLMODE',
69
+ /**
70
+ * The path of the secret keyring file. The host delivers it as a private file: a regular file
71
+ * that is not a symlink, has one hard link, is owned by the process user and grants no group or
72
+ * other permission, in a directory owned by that user that neither group nor others may write.
73
+ * This is the host's obligation; the Cloudly server does not check it yet.
74
+ */
75
+ 'SERVEZONE_SECRET_KEYRING_PATH',
76
+ /** The MongoDB connection URL of Cloudly's database. */
77
+ 'MONGODB_URL',
78
+ /** The S3 endpoint of Cloudly's object storage. */
79
+ 'S3_ENDPOINT',
80
+ /** The S3 access key. */
81
+ 'S3_ACCESSKEY',
82
+ /** The S3 secret key. */
83
+ 'S3_SECRETKEY',
84
+ /** The bucket Cloudly keeps its objects in; Cloudly creates it when it does not exist. */
85
+ 'S3_BUCKET',
86
+ ] as const);
87
+
88
+ /** One variable a host must give the Cloudly server. */
89
+ export type TCloudlyHostRequiredEnvironmentName = typeof cloudlyHostRequiredEnvironment[number];
90
+
91
+ /**
92
+ * The platform OIDC sign-in group (idp.global). It is all or none: Cloudly offers platform sign-in
93
+ * only when all five are set, and reports partial configuration as not configured. The issuer is
94
+ * a canonical `https` origin, the redirect URI is exactly `${publicOrigin}/auth/oidc/callback` of
95
+ * `SERVEZONE_PUBLIC_ORIGIN`, and the audience equals the client ID.
96
+ */
97
+ export const cloudlyHostPlatformOidcEnvironment = Object.freeze([
98
+ 'SERVEZONE_PLATFORM_OIDC_ISSUER',
99
+ 'SERVEZONE_PLATFORM_OIDC_CLIENT_ID',
100
+ 'SERVEZONE_PLATFORM_OIDC_CLIENT_SECRET',
101
+ 'SERVEZONE_PLATFORM_OIDC_REDIRECT_URI',
102
+ 'SERVEZONE_PLATFORM_OIDC_AUDIENCE',
103
+ ] as const);
104
+
105
+ /** One variable of the platform OIDC sign-in group. */
106
+ export type TCloudlyHostPlatformOidcEnvironmentName =
107
+ typeof cloudlyHostPlatformOidcEnvironment[number];
108
+
109
+ /**
110
+ * The environment the Cloudly server reads but starts without. Together with
111
+ * `cloudlyHostRequiredEnvironment` this is every variable Cloudly reads from its environment.
112
+ *
113
+ * Two more names are deliberately outside the contract: `SERVEZONE_ADMINACCOUNT` is deprecated
114
+ * (`ICloudlyConfig.servezoneAdminaccount`) and read until Cloudly 34.0.0, and
115
+ * `SERVEZONE_INSTALL_DEMO_DATA` installs destructive demo data, so a host never sets either.
116
+ */
117
+ export const cloudlyHostOptionalEnvironment = Object.freeze([
118
+ /** The port the server binds; `cloudlyDefaultListenPort` when unset. */
119
+ 'SERVEZONE_LISTENPORT',
120
+ /**
121
+ * The path of the WorkloadInit release approval file, a private file under the same rules as
122
+ * the secret keyring. Unset, the requests that need an approval answer
123
+ * `workloadinit-unconfigured`.
124
+ */
125
+ 'SERVEZONE_WORKLOADINIT_APPROVAL_PATH',
126
+ /** Optional member of the Mongo descriptor (database name). */
127
+ 'MONGODB_NAME',
128
+ /** Optional member of the Mongo descriptor (user). */
129
+ 'MONGODB_USER',
130
+ /** Optional member of the Mongo descriptor (password). */
131
+ 'MONGODB_PASS',
132
+ /** The S3 port. This contract states no default. */
133
+ 'S3_PORT',
134
+ /** Whether S3 is reached over TLS (`true` or `false`). This contract states no default. */
135
+ 'S3_USESSL',
136
+ /**
137
+ * The host channel of a hosted Cloudly, together with `SERVEZONE_APP_CONTROL_TOKEN`
138
+ * (`hostedAppRuntimeIdentityKeys`). Cloudly counts as hosted only while both are set.
139
+ */
140
+ hostedAppRuntimeIdentityKeys.runtimeUrl,
141
+ /** The host's machine JWT for the host channel, delivered as a secret. */
142
+ hostedAppRuntimeIdentityKeys.controlToken,
143
+ ...cloudlyHostPlatformOidcEnvironment,
144
+ /** The schedule of the backup of every service; unset, Cloudly schedules no backup. */
145
+ 'CLOUDLY_BACKUP_CRON',
146
+ /** How many backups of a service the retention keeps; `24` when unset. */
147
+ 'CLOUDLY_BACKUP_KEEP_LAST',
148
+ /**
149
+ * The interval of the periodic BaseOS image build cleanup in milliseconds; 43,200,000 (12 hours)
150
+ * when unset. A value that is not a positive number turns the periodic cleanup off.
151
+ */
152
+ 'CLOUDLY_BASEOS_IMAGE_CLEANUP_INTERVAL_MS',
153
+ ] as const);
154
+
155
+ /** One variable the Cloudly server reads but starts without. */
156
+ export type TCloudlyHostOptionalEnvironmentName = typeof cloudlyHostOptionalEnvironment[number];
157
+
158
+ /**
159
+ * Cloudly's health path on its listen port (`GET` or `HEAD`). It answers 200 with
160
+ * `{ healthy: true, checks }` while Cloudly runs and 503 otherwise; it states no version. Cloudly
161
+ * binds its port only late in its start, after its database migrations, so a host's start grace
162
+ * covers the longest migration. Starting and this path need no outbound network access.
163
+ */
164
+ export const cloudlyStatusPath = '/status' as const;
165
+
166
+ /** The port Cloudly binds when `SERVEZONE_LISTENPORT` is unset. */
167
+ export const cloudlyDefaultListenPort = 3000 as const;
@@ -1734,7 +1734,15 @@ export interface IClusterNode {
1734
1734
  * Reference to the cluster this node belongs to
1735
1735
  */
1736
1736
  clusterId: string;
1737
-
1737
+
1738
+ /**
1739
+ * The location the node stands in (`ILocation.id`). Every Cloudly with locations sets it on
1740
+ * every node it stores and moves it only with the node's whole cluster
1741
+ * (`setClusterLocation`); only a controller without locations leaves it out. The cluster's
1742
+ * copies of its nodes carry it too, which `getClusterLocationId` reads.
1743
+ */
1744
+ locationId?: string;
1745
+
1738
1746
  /**
1739
1747
  * Reference to the physical server (if applicable)
1740
1748
  */
@@ -1,3 +1,8 @@
1
+ /**
2
+ * The kind of host running a hosted app (`onebox`, `cloudly`, or another host's name), for display
3
+ * only: never branch on it. A host's capabilities reach an app only through a list the host
4
+ * advertises, once such a list exists; none exists today.
5
+ */
1
6
  export type THostedAppHostType = 'onebox' | 'cloudly' | string;
2
7
 
3
8
  export const hostedAppOidcRoleClaim = 'roles' as const;
@@ -17,6 +22,7 @@ export const hostedAppMachineAudience = 'serve.zone/hosted-app-lifecycle' as con
17
22
  */
18
23
  export const hostedAppRuntimeIdentityKeys = {
19
24
  appInstanceId: 'SERVEZONE_APP_INSTANCE_ID',
25
+ /** The host's `THostedAppHostType`, for display only: never branch on it. */
20
26
  hostType: 'SERVEZONE_APP_HOST_TYPE',
21
27
  runtimeUrl: 'SERVEZONE_RUNTIME_URL',
22
28
  controlToken: 'SERVEZONE_APP_CONTROL_TOKEN',
@@ -417,6 +423,7 @@ export interface IHostedAppLifecycleReport {
417
423
 
418
424
  export interface IHostedAppLifecycleState extends IHostedAppLifecycleReport {
419
425
  appInstanceId: string;
426
+ /** For display only: never branch on it (`THostedAppHostType`). */
420
427
  hostType: THostedAppHostType;
421
428
  reportedAt?: number;
422
429
  bootstrapAction?: IHostedAppBootstrapAction;
package/ts/data/index.ts CHANGED
@@ -90,6 +90,7 @@ export * from './serviceplatformownership.js';
90
90
  export * from './serviceports.js';
91
91
  export * from './serviceruntime.js';
92
92
  export * from './launchersecretowner.js';
93
+ export * from './location.js';
93
94
  export * from './servicevolumeinitialization.js';
94
95
  export * from './status.js';
95
96
  export * from './taskexecution.js';
@@ -0,0 +1,259 @@
1
+ import { canonicalizeStrictJson, compareWireTokens, createCanonicalJsonSha256Hex } from '../private/canonicaljson.js';
2
+ import type { ICluster } from './cluster.js';
3
+ import type { TSha256Digest } from './immutableimage.js';
4
+
5
+ /**
6
+ * Locations: the rooms Cloudly's physical objects stand in.
7
+ *
8
+ * A location is a record of its own, referenced by its `id` and named by one unique, renamable
9
+ * `name`. Objects carry the id: a cluster node in `IClusterNode.data.locationId`, the records later
10
+ * lanes add (gateway, edge, Onebox host) in a required `locationId` of their own. A cluster has no
11
+ * stored location: it stands where its nodes stand (`getClusterLocationId`), and an empty cluster
12
+ * stands nowhere. A BareMetal server stands where the node whose `data.baremetalId` names it
13
+ * stands; its `data.location` stays the provider's datacenter.
14
+ *
15
+ * Every Cloudly database holds exactly one initial location (`initialLocationId`, named
16
+ * `initialLocationName` until an administrator renames it). It receives every create that names no
17
+ * location for a cluster without nodes; a create for a cluster with nodes takes the cluster's.
18
+ */
19
+ export const locationContract = Object.freeze({
20
+ /** One lowercase RFC 1123 label. */
21
+ maximumNameLength: 63,
22
+ digestDomain: 'serve.zone/location-membership',
23
+ } as const);
24
+
25
+ /**
26
+ * The id of the one location every Cloudly database holds; it never changes. Cloudly generates
27
+ * every other location's id with a generator that can never produce this one.
28
+ */
29
+ export const initialLocationId = 'location-initial';
30
+
31
+ /** The name the initial location is created with; an administrator may rename it. */
32
+ export const initialLocationName = 'initial';
33
+
34
+ const locationNameLabel = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
35
+
36
+ /** True for a location name: one lowercase RFC 1123 label of 1 to 63 characters. */
37
+ export const isLocationName = (valueArg: unknown): valueArg is string => (
38
+ typeof valueArg === 'string'
39
+ && valueArg.length <= locationContract.maximumNameLength
40
+ && locationNameLabel.test(valueArg)
41
+ );
42
+
43
+ /**
44
+ * Every kind of stored object a location can hold, in canonical (`compareWireTokens`) order. A
45
+ * Cloudly records only some of them (`IReq_Any_Cloudly_GetLocations` answers which); a kind it does
46
+ * not record has no members anywhere. A cluster is no member: it stores no location and stands
47
+ * where its nodes stand (`getClusterLocationId`); `getClusters` lists a location's clusters through
48
+ * its `locationScope`.
49
+ */
50
+ export const locationMemberKinds = Object.freeze([
51
+ 'edge', 'gateway', 'node', 'oneboxHost',
52
+ ] as const);
53
+
54
+ export type TLocationMemberKind = typeof locationMemberKinds[number];
55
+
56
+ /** True for one of `locationMemberKinds`. */
57
+ export const isLocationMemberKind = (valueArg: unknown): valueArg is TLocationMemberKind => (
58
+ (locationMemberKinds as readonly unknown[]).includes(valueArg)
59
+ );
60
+
61
+ /** One object a location holds: its kind and its id within that kind. */
62
+ export interface ILocationMember {
63
+ kind: TLocationMemberKind;
64
+ id: string;
65
+ }
66
+
67
+ /**
68
+ * The membership an administrator confirmed complete for one location.
69
+ *
70
+ * Cloudly never rewrites it when membership changes: the location's membership is confirmed while
71
+ * `membershipDigest` equals the digest of its current membership (`isLocationMembershipConfirmed`).
72
+ */
73
+ export interface ILocationMembershipConfirmation {
74
+ /** `computeLocationMembershipDigest` of the membership the administrator saw. */
75
+ membershipDigest: TSha256Digest;
76
+ /** Unix milliseconds on Cloudly's clock when Cloudly accepted the confirmation. */
77
+ confirmedAt: number;
78
+ /** The confirming administrator's user id. */
79
+ confirmedBy: string;
80
+ }
81
+
82
+ /** A location as Cloudly stores it. */
83
+ export interface ILocation {
84
+ /** Fixed for the location's life; every reference uses it. */
85
+ id: string;
86
+ data: {
87
+ /** Unique among locations; `isLocationName`. */
88
+ name: string;
89
+ /** Unix milliseconds on Cloudly's clock. */
90
+ createdAt: number;
91
+ /** The creating administrator's user id; absent for the initial location Cloudly created itself. */
92
+ createdBy?: string;
93
+ /** Absent until an administrator first confirms the location's membership. */
94
+ membershipConfirmation?: ILocationMembershipConfirmation;
95
+ };
96
+ }
97
+
98
+ /** A location with what it holds now, as `getLocations` answers it. */
99
+ export interface ILocationView {
100
+ location: ILocation;
101
+ /** Every stored member of a kind this Cloudly records, sorted by kind and then id. */
102
+ members: ILocationMember[];
103
+ /** `computeLocationMembershipDigest(members, <the kinds this Cloudly records>)`. */
104
+ membershipDigest: TSha256Digest;
105
+ /** `isLocationMembershipConfirmed(location, membershipDigest)`. */
106
+ membershipConfirmed: boolean;
107
+ /**
108
+ * True for exactly one location: the one a create naming no location places the first node of
109
+ * an empty cluster in (the initial location).
110
+ */
111
+ receivesUnnamedCreates: boolean;
112
+ }
113
+
114
+ /**
115
+ * Narrows a list request to the rows of one location. A Cloudly that applied it echoes it as the
116
+ * response's `appliedLocationScope`; a response without the echo comes from a Cloudly that ignored
117
+ * it, and its list must not be shown as scoped.
118
+ */
119
+ export interface ILocationScope {
120
+ locationId: string;
121
+ }
122
+
123
+ /**
124
+ * Every reason Cloudly answers instead of a location request or a create that names a location.
125
+ * Each travels by name as a `TypedResponseError`, and a refused request changes nothing.
126
+ */
127
+ export const locationRefusals = Object.freeze([
128
+ /**
129
+ * A create named a location but creates no node to stand in it (`createCluster` with `setupMode`
130
+ * `manual` or absent); name the location on `createNodeJumpCommand` instead. Checked before
131
+ * `location-not-found`.
132
+ */
133
+ 'location-needs-node',
134
+ /** No location of that id exists. */
135
+ 'location-not-found',
136
+ /** The name is not one lowercase RFC 1123 label (`isLocationName`). */
137
+ 'location-name-invalid',
138
+ /** Another location carries that name. */
139
+ 'location-name-taken',
140
+ /** No cluster of that id exists (`setClusterLocation`). */
141
+ 'cluster-not-found',
142
+ /**
143
+ * A create for a cluster with nodes named a location other than the cluster's:
144
+ * `createNodeJumpCommand` when it is asked, and the jump-code claim when the cluster gained nodes
145
+ * in another location after the code was made.
146
+ */
147
+ 'location-mismatch',
148
+ /**
149
+ * A create or a jump-code claim for a cluster whose nodes already stand in more than one
150
+ * location: a state Cloudly never writes, which `getClusterLocationId` reports by throwing
151
+ * `ClusterSpansLocationsError`. `setClusterLocation` never answers it: it writes every node of the
152
+ * cluster to the target location in one transaction, which also repairs a spanning cluster.
153
+ */
154
+ 'cluster-spans-locations',
155
+ /**
156
+ * The digest a confirmation states is not the location's current membership digest: read the
157
+ * location again and confirm what it holds now.
158
+ */
159
+ 'membership-changed',
160
+ /** A concurrent change to the same records won; nothing changed. Read again and retry. */
161
+ 'conflict',
162
+ ] as const);
163
+
164
+ /** One of the reasons Cloudly answers instead of a location request. */
165
+ export type TLocationRefusal = typeof locationRefusals[number];
166
+
167
+ /** What a `setClusterLocation` did; every outcome is a success. */
168
+ export const setClusterLocationOutcomes = Object.freeze([
169
+ /** Every node of the cluster, and the cluster's copy of each, now names the location. */
170
+ 'moved',
171
+ /** Every node already stood in the location; nothing was written. */
172
+ 'unchanged',
173
+ /** The cluster has no nodes, so it stands nowhere and nothing was moved. */
174
+ 'cluster-empty',
175
+ ] as const);
176
+
177
+ export type TSetClusterLocationOutcome = typeof setClusterLocationOutcomes[number];
178
+
179
+ /** Thrown by `getClusterLocationId` for a cluster whose node copies disagree. */
180
+ export class ClusterSpansLocationsError extends Error {
181
+ public readonly refusal: TLocationRefusal = 'cluster-spans-locations';
182
+ public readonly clusterId: string;
183
+
184
+ public constructor(clusterIdArg: string) {
185
+ super(`Cluster ${clusterIdArg} spans locations.`);
186
+ this.name = 'ClusterSpansLocationsError';
187
+ this.clusterId = clusterIdArg;
188
+ }
189
+ }
190
+
191
+ /**
192
+ * The location a cluster stands in, read from its own `data.nodes` copies.
193
+ *
194
+ * `undefined` when the cluster has no nodes, or when no copy names a location (the cluster came
195
+ * from a controller without locations); such a cluster drops out of every location scope. Throws
196
+ * `ClusterSpansLocationsError` when the copies name different locations, or some name one and
197
+ * others none: Cloudly never writes that state, and no single answer would be true for it.
198
+ */
199
+ export const getClusterLocationId = (clusterArg: ICluster): string | undefined => {
200
+ const locationIds = new Set(clusterArg.data.nodes.map((nodeArg) => nodeArg.data.locationId));
201
+ if (locationIds.size > 1) {
202
+ throw new ClusterSpansLocationsError(clusterArg.id);
203
+ }
204
+ const [locationId] = locationIds;
205
+ return locationId;
206
+ };
207
+
208
+ /** True while the location's confirmed digest equals its current membership digest. */
209
+ export const isLocationMembershipConfirmed = (
210
+ locationArg: ILocation,
211
+ membershipDigestArg: TSha256Digest,
212
+ ): boolean => locationArg.data.membershipConfirmation?.membershipDigest === membershipDigestArg;
213
+
214
+ const fail = (reasonArg: string): never => {
215
+ throw new Error(`Location membership digest input rejected: ${reasonArg}.`);
216
+ };
217
+
218
+ const compareMembers = (leftArg: ILocationMember, rightArg: ILocationMember): number => (
219
+ compareWireTokens(leftArg.kind, rightArg.kind) || compareWireTokens(leftArg.id, rightArg.id)
220
+ );
221
+
222
+ /**
223
+ * The canonical JSON a membership digest hashes: the digest domain, the recorded kinds in
224
+ * canonical order and the members as `[kind, id]` pairs sorted by kind and then id. The order the
225
+ * caller lists either in does not matter. Throws for an unknown or repeated kind, a member of a
226
+ * kind not recorded, an empty id or a repeated member.
227
+ */
228
+ export const createLocationMembershipDigestInput = (
229
+ membersArg: readonly ILocationMember[],
230
+ recordedKindsArg: readonly TLocationMemberKind[],
231
+ ): string => {
232
+ const recordedKinds = [...recordedKindsArg].sort(compareWireTokens);
233
+ recordedKinds.forEach((kindArg, indexArg) => {
234
+ if (!isLocationMemberKind(kindArg)) fail('unknown member kind');
235
+ if (indexArg > 0 && kindArg === recordedKinds[indexArg - 1]) fail('repeated member kind');
236
+ });
237
+ const members = [...membersArg].sort(compareMembers);
238
+ members.forEach((memberArg, indexArg) => {
239
+ if (!recordedKinds.includes(memberArg.kind)) fail('member of a kind not recorded');
240
+ if (typeof memberArg.id !== 'string' || memberArg.id.length === 0) fail('member id empty');
241
+ if (indexArg > 0 && compareMembers(memberArg, members[indexArg - 1]) === 0) fail('repeated member');
242
+ });
243
+ return canonicalizeStrictJson({
244
+ domain: locationContract.digestDomain,
245
+ recordedKinds,
246
+ members: members.map((memberArg) => [memberArg.kind, memberArg.id]),
247
+ }, fail, 'location membership');
248
+ };
249
+
250
+ /**
251
+ * `sha256:<hex>` of `createLocationMembershipDigestInput`, through Web Crypto, so Cloudly and a
252
+ * browser client compute the same value.
253
+ */
254
+ export const computeLocationMembershipDigest = async (
255
+ membersArg: readonly ILocationMember[],
256
+ recordedKindsArg: readonly TLocationMemberKind[],
257
+ ): Promise<TSha256Digest> => `sha256:${await createCanonicalJsonSha256Hex(
258
+ createLocationMembershipDigestInput(membersArg, recordedKindsArg), fail,
259
+ )}`;
@@ -1,5 +1,6 @@
1
1
  import * as plugins from '../plugins.js';
2
2
  import type { IBareMetal } from '../data/baremetal.js';
3
+ import type { ILocationScope } from '../data/location.js';
3
4
  import type { IIdentity } from '../data/user.js';
4
5
 
5
6
  export interface IRequest_Any_Cloudly_GetBaremetalServers
@@ -10,9 +11,20 @@ extends plugins.typedrequestInterfaces.implementsTR<
10
11
  method: 'getBaremetalServers';
11
12
  request: {
12
13
  identity: IIdentity;
14
+ /**
15
+ * Only the servers standing in this location: those a node of the location names in its
16
+ * `data.baremetalId`. A server no node names stands nowhere and is never in a scoped answer;
17
+ * `IBareMetal.data.location` (the provider's datacenter) plays no part.
18
+ */
19
+ locationScope?: ILocationScope;
13
20
  };
14
21
  response: {
15
22
  baremetals: IBareMetal[];
23
+ /**
24
+ * The scope Cloudly applied, echoing `locationScope`. Absent from a Cloudly that ignored the
25
+ * scope (one without locations): its list is unscoped and must not be shown as scoped.
26
+ */
27
+ appliedLocationScope?: ILocationScope;
16
28
  };
17
29
  }
18
30
 
@@ -1,5 +1,6 @@
1
1
  import * as userInterfaces from '../data/user.js';
2
2
  import * as clusterInterfaces from '../data/cluster.js';
3
+ import type * as locationInterfaces from '../data/location.js';
3
4
  import type * as relayCredentialInterfaces from '../data/clusterrelaycredential.js';
4
5
  import type * as clusterVpnInterfaces from '../data/clustervpn.js';
5
6
  import type { IClusterRuntime, TClusterRuntimeBlocker } from '../data/clusterruntime.js';
@@ -17,9 +18,19 @@ export interface IReq_Any_Cloudly_GetClusters extends plugins.typedrequestInterf
17
18
  method: 'getClusters';
18
19
  request: {
19
20
  identity: userInterfaces.IIdentity;
21
+ /**
22
+ * Only the clusters standing in this location (`data.getClusterLocationId`); a cluster without
23
+ * nodes stands nowhere and is never in a scoped answer.
24
+ */
25
+ locationScope?: locationInterfaces.ILocationScope;
20
26
  };
21
27
  response: {
22
28
  clusters: clusterInterfaces.ICluster[];
29
+ /**
30
+ * The scope Cloudly applied, echoing `locationScope`. Absent from a Cloudly that ignored the
31
+ * scope (one without locations): its list is unscoped and must not be shown as scoped.
32
+ */
33
+ appliedLocationScope?: locationInterfaces.ILocationScope;
23
34
  };
24
35
  }
25
36
 
@@ -47,6 +58,15 @@ export interface IRequest_CreateCluster extends plugins.typedrequestInterfaces.i
47
58
  identity: userInterfaces.IIdentity;
48
59
  clusterName: string;
49
60
  setupMode?: 'manual' | 'hetzner' | 'aws' | 'digitalocean';
61
+ /**
62
+ * The location the node a provisioning setup mode creates stands in. Refused
63
+ * `location-needs-node` when the create makes no node to stand in it (`setupMode` `manual` or
64
+ * absent; name the location on `createNodeJumpCommand` instead), checked before
65
+ * `location-not-found`, which answers a location that does not exist. Absent, the created node
66
+ * stands in the location that receives unnamed creates (the initial location); a create that
67
+ * makes no node leaves the cluster empty, standing nowhere.
68
+ */
69
+ locationId?: string;
50
70
  };
51
71
  response: {
52
72
  cluster: clusterInterfaces.ICluster;
@@ -23,6 +23,7 @@ import * as hostedAppRequests from './hostedapp.js';
23
23
  import * as identityRequests from './identity.js';
24
24
  import * as imageRequests from './image.js';
25
25
  import * as informRequests from './inform.js';
26
+ import * as locationRequests from './location.js';
26
27
  import * as logRequests from './log.js';
27
28
  import * as mailRequests from './mail.js';
28
29
  import * as migrationRequests from './migration.js';
@@ -64,6 +65,7 @@ export {
64
65
  identityRequests as identity,
65
66
  imageRequests as image,
66
67
  informRequests as inform,
68
+ locationRequests as location,
67
69
  logRequests as log,
68
70
  mailRequests as mail,
69
71
  migrationRequests as migration,