@intentius/chant-lexicon-terraform 0.124.76 → 0.124.78

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 (45) hide show
  1. package/dist/drift-record.d.ts +24 -0
  2. package/dist/drift-record.d.ts.map +1 -1
  3. package/dist/drift-record.js +52 -0
  4. package/dist/drift-rows.d.ts +49 -4
  5. package/dist/drift-rows.d.ts.map +1 -1
  6. package/dist/drift-rows.js +87 -19
  7. package/dist/integrity.json +2 -2
  8. package/dist/manifest.json +1 -1
  9. package/dist/pr-env.d.ts +138 -0
  10. package/dist/pr-env.d.ts.map +1 -0
  11. package/dist/pr-env.js +248 -0
  12. package/dist/state/gitlab.d.ts +74 -0
  13. package/dist/state/gitlab.d.ts.map +1 -0
  14. package/dist/state/gitlab.js +275 -0
  15. package/dist/state/index.d.ts +2 -0
  16. package/dist/state/index.d.ts.map +1 -1
  17. package/dist/state/index.js +2 -0
  18. package/dist/state/store.d.ts +2 -1
  19. package/dist/state/store.d.ts.map +1 -1
  20. package/dist/state/versions.d.ts +39 -0
  21. package/dist/state/versions.d.ts.map +1 -0
  22. package/dist/state/versions.js +85 -0
  23. package/dist/state-migration.d.ts +85 -0
  24. package/dist/state-migration.d.ts.map +1 -0
  25. package/dist/state-migration.js +296 -0
  26. package/dist/state-ops.d.ts +54 -87
  27. package/dist/state-ops.d.ts.map +1 -1
  28. package/dist/state-ops.js +120 -77
  29. package/package.json +2 -2
  30. package/src/__fixtures__/drift-rows/refresh-plan-module.json +48 -0
  31. package/src/drift-record.test.ts +62 -0
  32. package/src/drift-record.ts +58 -0
  33. package/src/drift-rows.test.ts +90 -1
  34. package/src/drift-rows.ts +89 -18
  35. package/src/pr-env.test.ts +132 -0
  36. package/src/pr-env.ts +312 -0
  37. package/src/state/gitlab.test.ts +226 -0
  38. package/src/state/gitlab.ts +318 -0
  39. package/src/state/index.ts +2 -0
  40. package/src/state/store.ts +2 -1
  41. package/src/state/versions.ts +103 -0
  42. package/src/state-export-unlock.test.ts +230 -0
  43. package/src/state-migration.test.ts +236 -0
  44. package/src/state-migration.ts +353 -0
  45. package/src/state-ops.ts +132 -130
@@ -0,0 +1,318 @@
1
+ /**
2
+ * GitLab-managed Terraform state (#4773): an http backend whose address is a
3
+ * GitLab project's state API, `<api>/projects/<id>/terraform/state/<name>`,
4
+ * with `<address>/lock` as its lock and unlock address.
5
+ *
6
+ * GitLab keeps each version of a state by its serial. `GET <address>` is the
7
+ * current state, `GET <address>/versions/<serial>` one version, and `POST`
8
+ * and `DELETE` on `<address>/lock` (the backend's `LOCK` and `UNLOCK` by
9
+ * default) take and release the lock. A lock that is held answers a take
10
+ * with 409 and the holder's lock info. While a lock is held GitLab takes a
11
+ * write of the state only with the lock's ID (`POST <address>?ID=<id>`), so
12
+ * the binary cannot write with `-lock=false` under chant's lock and the store
13
+ * writes the state itself, as the azurerm store does under its lease.
14
+ *
15
+ * The backend's configuration comes from the block, a `-backend-config` file
16
+ * or flag (which `init` records), or the job's `TF_HTTP_*` variables (which
17
+ * it does not record): each attribute is the recorded value, else its
18
+ * variable (`TF_HTTP_ADDRESS`, `TF_HTTP_LOCK_ADDRESS`,
19
+ * `TF_HTTP_UNLOCK_ADDRESS`, `TF_HTTP_LOCK_METHOD`, `TF_HTTP_UNLOCK_METHOD`),
20
+ * as the binary reads it. Every call is made with the backend's own
21
+ * credentials, `username` and `password` (`TF_HTTP_USERNAME`,
22
+ * `TF_HTTP_PASSWORD`): the job token in a pipeline, a personal access token
23
+ * at a shell.
24
+ *
25
+ * What a run keeps beside the state goes in another state of the same
26
+ * project, named the state's name with the suffix after it, so it is under
27
+ * the project's own access controls.
28
+ *
29
+ * Lifted from terragucci's `gitlab-state.ts` (INTENTIUS/terragucci 70b7509),
30
+ * so terragucci deletes its copy.
31
+ */
32
+ import { randomUUID } from "node:crypto";
33
+ import type { ForgeFetch } from "@intentius/chant/pr-forge";
34
+ import { defaultFetch, StoreError } from "./object-store";
35
+ import type { LockHolder, StateStore } from "./store";
36
+
37
+ /**
38
+ * The HTTP calls the store makes. A StoreFetch, chant's forge fetch and the
39
+ * global fetch all fit.
40
+ */
41
+ export type GitLabFetch = ForgeFetch;
42
+
43
+ /** Where a GitLab-managed state is, and how to call its API. */
44
+ export interface GitLabState {
45
+ backend: "http";
46
+ /** The state's address as the backend has it. */
47
+ address: string;
48
+ /** The state's name, the last part of its address. */
49
+ name: string;
50
+ lockAddress?: string;
51
+ unlockAddress?: string;
52
+ lockMethod: string;
53
+ unlockMethod: string;
54
+ /** The Authorization header the backend's credentials make, when it has any. */
55
+ auth?: string;
56
+ }
57
+
58
+ /** The path of GitLab's state API: `.../api/v4/projects/<id>/terraform/state/<name>`. */
59
+ const STATE_API_PATH = /\/api\/v4\/projects\/[^/]+\/terraform\/state\/([^/]+)\/?$/;
60
+
61
+ const str = (v: unknown): string | undefined => (typeof v === "string" && v !== "" ? v : undefined);
62
+
63
+ /** Whether an http backend's address is a GitLab project's state API. */
64
+ export function isGitLabAddress(address: string | undefined): boolean {
65
+ if (!address) return false;
66
+ try {
67
+ return STATE_API_PATH.test(new URL(address).pathname);
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+
73
+ /** A URL with its credentials and query left out, to print and record. */
74
+ export function shownUrl(raw: string): string {
75
+ try {
76
+ const u = new URL(raw);
77
+ return `${u.protocol}//${u.host}${u.pathname}`;
78
+ } catch {
79
+ return raw;
80
+ }
81
+ }
82
+
83
+ /** The http backend's attribute, as the binary reads it: recorded, else its `TF_HTTP_*` variable. */
84
+ const attribute = (config: Record<string, unknown>, env: NodeJS.ProcessEnv, name: string): string | undefined => str(config[name]) ?? str(env[`TF_HTTP_${name.toUpperCase()}`]);
85
+
86
+ /** The GitLab-managed state an http backend's configuration names, or undefined when its address is not GitLab's state API. */
87
+ export function gitlabState(config: Record<string, unknown>, env: NodeJS.ProcessEnv = process.env): GitLabState | undefined {
88
+ const address = attribute(config, env, "address");
89
+ if (!address || !isGitLabAddress(address)) return undefined;
90
+ const name = decodeURIComponent(new URL(address).pathname.match(STATE_API_PATH)![1]!);
91
+ const username = attribute(config, env, "username");
92
+ const password = attribute(config, env, "password");
93
+ const lockAddress = attribute(config, env, "lock_address");
94
+ const unlockAddress = attribute(config, env, "unlock_address");
95
+ return {
96
+ backend: "http",
97
+ address,
98
+ name,
99
+ ...(lockAddress ? { lockAddress } : {}),
100
+ ...(unlockAddress ? { unlockAddress } : {}),
101
+ lockMethod: attribute(config, env, "lock_method") ?? "LOCK",
102
+ unlockMethod: attribute(config, env, "unlock_method") ?? "UNLOCK",
103
+ ...(username || password ? { auth: `Basic ${Buffer.from(`${username ?? ""}:${password ?? ""}`).toString("base64")}` } : {}),
104
+ };
105
+ }
106
+
107
+ /**
108
+ * A GitLab state address with its state name suffixed `-<suffix>`, and a
109
+ * lock address with the state name before `/lock` suffixed the same way.
110
+ * Undefined when the address is not GitLab's state API (or its lock).
111
+ */
112
+ export function suffixedGitLabAddress(address: string, suffix: string): string | undefined {
113
+ let u: URL;
114
+ try {
115
+ u = new URL(address);
116
+ } catch {
117
+ return undefined;
118
+ }
119
+ const m = u.pathname.match(/^(.*\/api\/v4\/projects\/[^/]+\/terraform\/state\/)([^/]+?)(\/lock)?\/?$/);
120
+ if (!m) return undefined;
121
+ u.pathname = `${m[1]}${m[2]}-${suffix}${m[3] ?? ""}`;
122
+ return u.toString();
123
+ }
124
+
125
+ const headers = (s: GitLabState, json = false): Record<string, string> => ({ ...(s.auth ? { authorization: s.auth } : {}), ...(json ? { "content-type": "application/json" } : {}) });
126
+
127
+ const base = (address: string): string => address.replace(/\/+$/, "");
128
+
129
+ /** An error that names the call and GitLab's answer, never the credentials. */
130
+ function answered(what: string, url: string, status: number, text: string): StoreError {
131
+ const why = status === 401 ? ": the backend's username and password (TF_HTTP_USERNAME, TF_HTTP_PASSWORD) are not a token GitLab accepts" : status === 403 ? ": the token may not read this project's state (reads need Developer)" : "";
132
+ return new StoreError(`GitLab answered ${status} to ${what} ${shownUrl(url)}${why}${text && !why ? `: ${text.trim().slice(0, 200)}` : ""}`);
133
+ }
134
+
135
+ const held = (status: number): boolean => status === 409 || status === 423;
136
+
137
+ /** The URL of one version of the state. */
138
+ export const gitlabVersionUrl = (s: GitLabState, serial: string | number): string => `${base(s.address)}/versions/${encodeURIComponent(String(serial))}`;
139
+
140
+ /** The address of the state beside this one whose name is this one's with `suffix` after it. */
141
+ export function gitlabBesideAddress(s: GitLabState, suffix: string): string {
142
+ const u = new URL(s.address);
143
+ u.pathname = `${u.pathname.replace(/\/+$/, "")}${encodeURIComponent(suffix)}`;
144
+ return u.toString();
145
+ }
146
+
147
+ /** The holder in GitLab's answer to a take of a lock that is held: its ID, its GitLab user and when it was taken. GitLab answers the other fields with the ask's own, so they are left out. */
148
+ function heldBy(text: string): string {
149
+ try {
150
+ const v = JSON.parse(text) as Record<string, unknown>;
151
+ return JSON.stringify(Object.fromEntries(["ID", "Who", "Created"].filter((k) => typeof v[k] === "string").map((k) => [k, v[k]])));
152
+ } catch {
153
+ return text;
154
+ }
155
+ }
156
+
157
+ const idOf = (text: string): string => {
158
+ try {
159
+ const v = JSON.parse(text) as { ID?: unknown };
160
+ return typeof v.ID === "string" ? v.ID : "";
161
+ } catch {
162
+ return "";
163
+ }
164
+ };
165
+
166
+ /** A GitLab-managed state opened as a {@link StateStore}, with the reads GitLab's API has beyond one: its serial, its versions, and a lock released by its ID. */
167
+ export interface GitLabStateStore extends StateStore {
168
+ readonly backend: "http";
169
+ /**
170
+ * The serial and lineage of the state GitLab holds now, or undefined when
171
+ * it holds none. GitLab has no call that answers the serial alone, so this
172
+ * reads the state and keeps those two fields only.
173
+ */
174
+ serial(): Promise<{ serial: number; lineage?: string } | undefined>;
175
+ /** Whether GitLab keeps the version with this serial: a HEAD, so no state is read. */
176
+ hasVersion(serial: string | number): Promise<boolean>;
177
+ /** One version of the state, or undefined when GitLab keeps no version with that serial. */
178
+ readVersion(serial: string | number): Promise<string | undefined>;
179
+ /**
180
+ * Who holds the lock, as lock info text with its ID, its GitLab user and
181
+ * when it was taken, or undefined when nobody does. GitLab has no call that
182
+ * reads a lock, so this asks for it: a held lock answers 409 with its
183
+ * holder, and a free one is taken by the ask and released at once by its
184
+ * own ID.
185
+ */
186
+ probeLock(): Promise<string | undefined>;
187
+ /**
188
+ * Release the lock with this ID. GitLab releases it only while that ID
189
+ * holds it: another lock taken since answers 409, which is thrown.
190
+ */
191
+ releaseLock(id: string): Promise<void>;
192
+ }
193
+
194
+ /**
195
+ * The GitLab-managed state as a store. `who` names the probe's lock info
196
+ * (its `Who`, and the start of its ID), so a holder that reads the lock
197
+ * while the probe has it sees whose it is.
198
+ */
199
+ export function gitlabStore(s: GitLabState, fetchFn: GitLabFetch = defaultFetch, who = "chant"): GitLabStateStore {
200
+ const location = shownUrl(s.address);
201
+ let lockedId: string | undefined;
202
+
203
+ const needLock = (): string => {
204
+ if (!s.lockAddress || !s.unlockAddress) throw new StoreError(`the http backend of ${location} names no ${s.lockAddress ? "unlock_address" : "lock_address"}`);
205
+ return s.lockAddress;
206
+ };
207
+
208
+ /** Take the lock with `info`: true when taken, the held answer's text when another holds it. */
209
+ const take = async (info: string): Promise<true | { heldText: string }> => {
210
+ const at = needLock();
211
+ const r = await fetchFn(at, { method: s.lockMethod, headers: headers(s, true), body: info });
212
+ const text = await r.text();
213
+ if (held(r.status)) return { heldText: text };
214
+ if (!r.ok) throw answered("a lock of", at, r.status, text);
215
+ return true;
216
+ };
217
+
218
+ const releaseLock = async (id: string): Promise<void> => {
219
+ if (!s.unlockAddress) throw new StoreError(`the http backend of ${location} names no unlock_address`);
220
+ const r = await fetchFn(s.unlockAddress, { method: s.unlockMethod, headers: headers(s, true), body: JSON.stringify({ ID: id }) });
221
+ const text = await r.text();
222
+ if (held(r.status)) throw new StoreError(`GitLab did not release lock ${id} on ${shownUrl(s.unlockAddress)}: another lock holds the state now`);
223
+ if (!r.ok) throw answered("a release of", s.unlockAddress, r.status, text);
224
+ };
225
+
226
+ const probeLock = async (): Promise<string | undefined> => {
227
+ const id = `${who}-probe-${randomUUID()}`;
228
+ const info = JSON.stringify({ ID: id, Operation: "OperationTypeInvalid", Info: `${who} reads who holds the lock`, Who: who, Version: "", Created: new Date().toISOString(), Path: "" });
229
+ const got = await take(info);
230
+ if (got !== true) return heldBy(got.heldText);
231
+ await releaseLock(id);
232
+ return undefined;
233
+ };
234
+
235
+ /** The text at `url`, or undefined when GitLab holds no state there. */
236
+ const read = async (url: string): Promise<string | undefined> => {
237
+ const r = await fetchFn(url, { method: "GET", headers: headers(s) });
238
+ if (r.status === 404 || r.status === 204) return undefined;
239
+ const text = await r.text();
240
+ if (!r.ok) throw answered("a read of", url, r.status, text);
241
+ return text;
242
+ };
243
+
244
+ const post = async (url: string, body: string): Promise<void> => {
245
+ const r = await fetchFn(url, { method: "POST", headers: headers(s, true), body });
246
+ const text = await r.text();
247
+ if (held(r.status)) throw new StoreError(`GitLab refused a write of ${shownUrl(url)}: its lock is held by another ID`);
248
+ if (!r.ok) throw answered("a write of", url, r.status, text);
249
+ };
250
+
251
+ return {
252
+ backend: "http",
253
+ location,
254
+ lockLocation: shownUrl(s.lockAddress ?? s.address),
255
+ serial: async () => {
256
+ const text = await read(s.address);
257
+ if (text === undefined) return undefined;
258
+ let doc: { serial?: unknown; lineage?: unknown };
259
+ try {
260
+ doc = JSON.parse(text) as typeof doc;
261
+ } catch {
262
+ throw new StoreError(`GitLab answered ${location} with no state`);
263
+ }
264
+ if (typeof doc.serial !== "number") throw new StoreError(`the state at ${location} has no serial`);
265
+ return { serial: doc.serial, ...(typeof doc.lineage === "string" ? { lineage: doc.lineage } : {}) };
266
+ },
267
+ hasVersion: async (serial) => {
268
+ const url = gitlabVersionUrl(s, serial);
269
+ const r = await fetchFn(url, { method: "HEAD", headers: headers(s) });
270
+ if (r.status === 404) return false;
271
+ if (!r.ok) throw answered("a check of", url, r.status, "");
272
+ return true;
273
+ },
274
+ readVersion: async (serial) => {
275
+ const url = gitlabVersionUrl(s, serial);
276
+ const r = await fetchFn(url, { method: "GET", headers: headers(s) });
277
+ if (r.status === 404) return undefined;
278
+ const text = await r.text();
279
+ if (!r.ok) throw answered("a read of", url, r.status, text);
280
+ return text;
281
+ },
282
+ probeLock,
283
+ releaseLock,
284
+ heldLock: async (): Promise<LockHolder | undefined> => {
285
+ const info = await probeLock();
286
+ return info === undefined ? undefined : { id: idOf(info), info };
287
+ },
288
+ lock: async (info) => {
289
+ if ((await take(info)) !== true) return false;
290
+ lockedId = idOf(info);
291
+ return true;
292
+ },
293
+ unlock: async () => {
294
+ if (lockedId === undefined) return;
295
+ await releaseLock(lockedId);
296
+ lockedId = undefined;
297
+ },
298
+ write: async (body) => {
299
+ if (lockedId === undefined) throw new StoreError(`${location} is written under its lock, and none is held`);
300
+ const u = new URL(s.address);
301
+ u.searchParams.set("ID", lockedId);
302
+ await post(u.toString(), body);
303
+ },
304
+ readBeside: (suffix) => read(gitlabBesideAddress(s, suffix)),
305
+ writeBeside: (suffix, body) => post(gitlabBesideAddress(s, suffix), body),
306
+ removeBeside: async (suffix) => {
307
+ const url = gitlabBesideAddress(s, suffix);
308
+ const r = await fetchFn(url, { method: "DELETE", headers: headers(s) });
309
+ if (r.status === 404) return;
310
+ const text = await r.text();
311
+ if (!r.ok) throw answered("a delete of", url, r.status, text);
312
+ },
313
+ besideLocation: (suffix) => shownUrl(gitlabBesideAddress(s, suffix)),
314
+ adopt: (h) => {
315
+ lockedId = h.id;
316
+ },
317
+ };
318
+ }
@@ -7,9 +7,11 @@
7
7
  export * from "./object-store";
8
8
  export * from "./backend";
9
9
  export * from "./store";
10
+ export * from "./gitlab";
10
11
  export * from "./exec";
11
12
  export * from "./locks";
12
13
  export * from "./root-states";
13
14
  export { S3Client, s3FromEnv, type S3Target } from "./s3";
14
15
  export { GcsClient, type GcsTarget } from "./gcs";
15
16
  export { AzureBlobClient, type AzureTarget } from "./azure-blob";
17
+ export * from "./versions";
@@ -37,7 +37,8 @@ export interface LockHolder {
37
37
 
38
38
  /** A state where it is, for what locks it and keeps beside it. */
39
39
  export interface StateStore {
40
- readonly backend: LockableState["backend"];
40
+ /** The backend's type; `http` is a GitLab-managed state (./gitlab.ts). */
41
+ readonly backend: LockableState["backend"] | "http";
41
42
  /** Where the state is. */
42
43
  readonly location: string;
43
44
  /** Where its lock is: the lock object, or the blob whose lease is the lock. */
@@ -0,0 +1,103 @@
1
+ /**
2
+ * A root's state read by version (#4762), for chant core's state export
3
+ * (`@intentius/chant/state-export`): the version a bucket or container
4
+ * holds now, whether it holds another, and one version's text.
5
+ *
6
+ * s3 bucket versioning: the object's `x-amz-version-id`
7
+ * gcs object versioning: a version is a generation
8
+ * azurerm blob versioning: the blob's `x-ms-version-id`; with none, the
9
+ * snapshots the backend takes when it sets `snapshot = true`, and
10
+ * a request for the current version takes one, whose id names it
11
+ * http a GitLab-managed state (./gitlab.ts): GitLab keeps each version
12
+ * by its serial, so the version id is the serial
13
+ *
14
+ * A local state keeps no versions, and is refused. Nothing here writes a
15
+ * state; the one write is the azurerm snapshot above.
16
+ *
17
+ * Lifted from terragucci's `backend.ts` (`version`, `hasVersion`,
18
+ * `readVersion` of its stores), so terragucci deletes its copy.
19
+ */
20
+ import type { StateVersion, StateVersionSource } from "@intentius/chant/state-export";
21
+ import { AzureBlobClient, type AzureTarget } from "./azure-blob";
22
+ import { isRefused, stateLocation, type StateObject, type StoredState } from "./backend";
23
+ import { GcsClient } from "./gcs";
24
+ import type { GitLabStateStore } from "./gitlab";
25
+ import type { StoreFetch } from "./object-store";
26
+ import { S3Client } from "./s3";
27
+
28
+ /** What the version reads cover, for a refusal. */
29
+ export const READS_VERSIONS = "a state export reads versions of s3, gcs and azurerm states and GitLab-managed state";
30
+
31
+ function s3Versions(o: Extract<StoredState, { backend: "s3" }>, fetchFn?: StoreFetch): StateVersionSource {
32
+ const client = new S3Client(o.target, fetchFn);
33
+ return {
34
+ location: `s3://${o.bucket}/${o.key}`,
35
+ async current(): Promise<StateVersion> {
36
+ const head = await client.head(o.key);
37
+ if (!head.exists) return { exists: false };
38
+ return head.versionId ? { exists: true, versionId: head.versionId } : { exists: true, off: `bucket versioning is off for ${o.bucket}, so it keeps only the latest state` };
39
+ },
40
+ hasVersion: (id) => client.hasVersion(o.key, id),
41
+ readVersion: (id) => client.readVersion(o.key, id),
42
+ };
43
+ }
44
+
45
+ function gcsVersions(o: Extract<StoredState, { backend: "gcs" }>, fetchFn?: StoreFetch): StateVersionSource {
46
+ const client = new GcsClient(o.target, fetchFn);
47
+ return {
48
+ location: `gs://${o.bucket}/${o.key}`,
49
+ async current(): Promise<StateVersion> {
50
+ const head = await client.head(o.key);
51
+ if (!head.exists) return { exists: false };
52
+ if ((await client.versioning()) === false) return { exists: true, off: `object versioning is off for ${o.bucket}, so it keeps only the latest state` };
53
+ return { exists: true, ...(head.generation ? { versionId: head.generation } : {}) };
54
+ },
55
+ hasVersion: async (id) => (await client.head(o.key, id)).exists,
56
+ readVersion: (id) => client.readGeneration(o.key, id),
57
+ };
58
+ }
59
+
60
+ function azureVersions(o: Extract<StoredState, { backend: "azurerm" }>, fetchFn?: StoreFetch, pin = true): StateVersionSource {
61
+ const client = new AzureBlobClient({ account: o.account, container: o.container, endpoint: o.endpoint, ...o.auth } as AzureTarget, fetchFn);
62
+ // A blob that keeps versions names each by its version id; else by a snapshot.
63
+ const at = async (id: string) => ((await client.head(o.key)).versionId ? { versionid: id } : { snapshot: id });
64
+ return {
65
+ location: `az://${o.account}/${o.container}/${o.key}`,
66
+ async current(): Promise<StateVersion> {
67
+ const head = await client.head(o.key);
68
+ if (!head.exists) return { exists: false };
69
+ if (head.versionId) return { exists: true, versionId: head.versionId };
70
+ if (!o.snapshot) return { exists: true, off: `blob versioning is off for ${o.account}, and the backend takes no snapshots (snapshot = true), so it keeps only the latest state` };
71
+ return pin ? { exists: true, versionId: await client.snapshot(o.key) } : { exists: true, off: "the blob keeps no versions, and only a snapshot would name this one" };
72
+ },
73
+ hasVersion: async (id) => (await client.head(o.key, await at(id))).exists,
74
+ readVersion: async (id) => client.readAt(o.key, await at(id)),
75
+ };
76
+ }
77
+
78
+ /**
79
+ * A root's state as a version source, or why it has none: a refused backend,
80
+ * or a local state, which keeps no versions. With `pin: false` an azurerm
81
+ * blob that keeps no versions names none for its current state, where the
82
+ * default takes a snapshot to name it.
83
+ */
84
+ export function stateVersionSource(o: StateObject, fetchFn?: StoreFetch, options: { pin?: boolean } = {}): StateVersionSource | { refused: string } {
85
+ if (isRefused(o)) return { refused: o.reason };
86
+ if (o.backend === "local") return { refused: `the state is a local file, ${stateLocation(o)}, which keeps no versions; ${READS_VERSIONS}` };
87
+ if (o.backend === "s3") return s3Versions(o, fetchFn);
88
+ if (o.backend === "gcs") return gcsVersions(o, fetchFn);
89
+ return azureVersions(o, fetchFn, options.pin ?? true);
90
+ }
91
+
92
+ /** A GitLab-managed state as a version source: the version id is the serial. */
93
+ export function gitlabVersionSource(store: GitLabStateStore): StateVersionSource {
94
+ return {
95
+ location: store.location,
96
+ async current(): Promise<StateVersion> {
97
+ const now = await store.serial();
98
+ return now ? { exists: true, versionId: String(now.serial) } : { exists: false };
99
+ },
100
+ hasVersion: async (id) => /^\d+$/.test(id) && (await store.hasVersion(id)),
101
+ readVersion: (id) => store.readVersion(id),
102
+ };
103
+ }