@samebase/alchemy-kit 0.0.0-stage → 0.1.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.
@@ -0,0 +1,485 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { REDACTED_MARKER, State, StateStoreError } from "alchemy/State";
3
+ import { makeBucketState } from "alchemy/State/BucketState";
4
+ import * as Data from "effect/Data";
5
+ import * as Deferred from "effect/Deferred";
6
+ import * as Effect from "effect/Effect";
7
+ import * as HttpClient from "effect/http/HttpClient";
8
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
9
+ import * as Layer from "effect/Layer";
10
+ import * as Queue from "effect/Queue";
11
+ import * as Redacted from "effect/Redacted";
12
+ import * as Schedule from "effect/Schedule";
13
+ import * as Schema from "effect/Schema";
14
+ import * as Scope from "effect/Scope";
15
+ import { createHash } from "node:crypto";
16
+ import { decodeFqn } from "alchemy/FQN";
17
+ /** A path with each segment URL-encoded and its slashes kept, for a GitHub API URL. */
18
+ const encodePath = (path) => path.split("/").map(encodeURIComponent).join("/");
19
+ /** The git blob sha of `text`: what GitHub reports as the file's sha. */
20
+ const blobSha = (text) => {
21
+ const bytes = Buffer.from(text, "utf8");
22
+ return createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
23
+ };
24
+ /** What the commit message calls a key: `{stack} {stage}` and the resource. */
25
+ const describeKey = (key) => {
26
+ const parts = key.split("/");
27
+ const file = parts[parts.length - 1] ?? key;
28
+ if (parts.length < 3) return {
29
+ group: "",
30
+ name: file.replace(/\.json$/, "")
31
+ };
32
+ const name = file === "__stack_output__.json" ? "stack output" : file === "__lease__.json" ? "lock" : decodeFqn(file.replace(/\.json$/, ""));
33
+ return {
34
+ group: `${parts.slice(0, -2).join("/")} ${parts[parts.length - 2]}`,
35
+ name
36
+ };
37
+ };
38
+ const listNames = (verb, names) => names.length === 0 ? [] : names.length <= 5 ? [`${verb} ${names.join(", ")}`] : [`${verb} ${names.length} resources`];
39
+ /**
40
+ * One line per stage, such as `app prod: set Worker, Bucket; delete Old`. A lock change carries
41
+ * its `lock` text (`take lock`, `renew lock`, `release lock`) in place of a resource name.
42
+ */
43
+ const commitMessage = (changes) => {
44
+ const groups = /* @__PURE__ */ new Map();
45
+ for (const change of changes) {
46
+ const { group, name } = describeKey(change.key);
47
+ const entry = groups.get(group) ?? {
48
+ set: [],
49
+ deleted: [],
50
+ lock: []
51
+ };
52
+ if (change.lock !== "") entry.lock.push(change.lock);
53
+ else if (change.deleted) entry.deleted.push(name);
54
+ else entry.set.push(name);
55
+ groups.set(group, entry);
56
+ }
57
+ return Array.from(groups, ([group, entry]) => {
58
+ const what = [
59
+ ...entry.lock,
60
+ ...listNames("set", entry.set),
61
+ ...listNames("delete", entry.deleted)
62
+ ].join("; ");
63
+ return group === "" ? `store: ${what}` : `${group}: ${what}`;
64
+ }).join("\n");
65
+ };
66
+ //#endregion
67
+ //#region src/github-state/sealing.ts
68
+ const KEY_VARIABLE = "ALCHEMY_GITHUB_STATE_KEY";
69
+ const SEALED_MARKER = "__sealed__";
70
+ const VERSION = "v1";
71
+ /** A key of 32 bytes in base64 is 43 characters and one `=`. */
72
+ const KEY_TEXT = /^[A-Za-z0-9+/]{43}=$/;
73
+ const encoder = new TextEncoder();
74
+ const decoder = new TextDecoder();
75
+ const fromBase64 = (text) => new Uint8Array(Buffer.from(text, "base64url"));
76
+ const toBase64Url = (bytes) => Buffer.from(bytes).toString("base64url");
77
+ /**
78
+ * The AES-256-GCM key in `text`, base64 of exactly 32 bytes. It fails when the text is missing or
79
+ * malformed. An error never quotes the text.
80
+ */
81
+ const parseKey = (text) => Effect.gen(function* () {
82
+ const make = `Make one with \`openssl rand -base64 32\` and keep it as a secret.`;
83
+ const trimmed = text?.trim();
84
+ if (!trimmed) return yield* new StateStoreError({ message: `GitHub state store: ${KEY_VARIABLE} is not set. ${make}` });
85
+ if (!KEY_TEXT.test(trimmed)) return yield* new StateStoreError({ message: `GitHub state store: ${KEY_VARIABLE} is not base64 of 32 bytes. ${make}` });
86
+ return yield* Effect.promise(() => crypto.subtle.importKey("raw", new Uint8Array(Buffer.from(trimmed, "base64")), "AES-GCM", false, ["encrypt", "decrypt"]));
87
+ });
88
+ /**
89
+ * `value` with `f` applied to each `__redacted__` field in it. Alchemy reads every object with
90
+ * that field as a secret, also when the object has other fields, so every such field is one here.
91
+ */
92
+ const mapSecrets = (value, f) => {
93
+ if (Array.isArray(value)) return Effect.forEach(value, (item) => mapSecrets(item, f));
94
+ if (typeof value !== "object" || value === null) return Effect.succeed(value);
95
+ return Effect.forEach(Object.entries(value), ([name, item]) => (name === REDACTED_MARKER ? f(item) : mapSecrets(item, f)).pipe(Effect.map((mapped) => [name, mapped]))).pipe(Effect.map(Object.fromEntries));
96
+ };
97
+ /**
98
+ * Rewrites the record `text` with `f` applied to each secret. A record without a secret comes back
99
+ * as the same text.
100
+ */
101
+ const rewrite = (objectKey, text, f) => Effect.gen(function* () {
102
+ const value = yield* Effect.try({
103
+ try: () => JSON.parse(text),
104
+ catch: () => new StateStoreError({ message: `GitHub state store: ${objectKey} is not JSON` })
105
+ });
106
+ let secrets = 0;
107
+ const mapped = yield* mapSecrets(value, (inner) => {
108
+ secrets++;
109
+ return f(inner);
110
+ });
111
+ return secrets === 0 ? text : JSON.stringify(mapped, null, 2);
112
+ });
113
+ /** The record `text` with each secret sealed for the record at `objectKey`. */
114
+ const sealRecord = (key, objectKey, text) => rewrite(objectKey, text, (inner) => Effect.promise(async () => {
115
+ const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
116
+ const ciphertext = await crypto.subtle.encrypt({
117
+ name: "AES-GCM",
118
+ iv,
119
+ additionalData: encoder.encode(objectKey)
120
+ }, key, encoder.encode(JSON.stringify(inner)));
121
+ const sealed = `${VERSION}.${toBase64Url(iv)}.${toBase64Url(new Uint8Array(ciphertext))}`;
122
+ return { [SEALED_MARKER]: sealed };
123
+ }));
124
+ /**
125
+ * The record `text` with each sealed secret opened, as Alchemy wrote it. It fails when a secret is
126
+ * not sealed, or does not open with `key` at `objectKey`.
127
+ */
128
+ const openRecord = (key, objectKey, text) => rewrite(objectKey, text, (inner) => Effect.gen(function* () {
129
+ const sealed = typeof inner === "object" && inner !== null && SEALED_MARKER in inner ? inner[SEALED_MARKER] : void 0;
130
+ const [version, iv, ciphertext, ...rest] = typeof sealed === "string" ? sealed.split(".") : [];
131
+ if (version !== VERSION || iv === void 0 || ciphertext === void 0 || rest.length > 0) return yield* new StateStoreError({ message: `GitHub state store: ${objectKey} holds a secret that is not sealed by this store` });
132
+ const plaintext = yield* Effect.tryPromise({
133
+ try: () => crypto.subtle.decrypt({
134
+ name: "AES-GCM",
135
+ iv: fromBase64(iv),
136
+ additionalData: encoder.encode(objectKey)
137
+ }, key, fromBase64(ciphertext)),
138
+ catch: () => new StateStoreError({ message: `GitHub state store: a secret in ${objectKey} does not open. ${KEY_VARIABLE} is not the key that sealed it, or the record was moved from another place.` })
139
+ });
140
+ return JSON.parse(decoder.decode(plaintext));
141
+ }));
142
+ //#endregion
143
+ //#region src/github-state/GitHubState.ts
144
+ const API = "https://api.github.com";
145
+ const MAX_ATTEMPTS = 20;
146
+ const STATE_README = `# Alchemy state
147
+
148
+ This branch holds the Alchemy state of this repository. Alchemy deploys write it; do not edit it
149
+ by hand. Each resource is one file, \`{stack}/{stage}/{resource}.json\`.
150
+
151
+ Each secret value is \`{"__redacted__": {"__sealed__": "v1.<iv>.<ciphertext>"}}\`, sealed with
152
+ AES-256-GCM under the key in ${KEY_VARIABLE}. Every other value is plain JSON.
153
+
154
+ The deploy lock of each stage is on the branch of the same name with \`-lock\` at the end.
155
+ `;
156
+ const LOCK_README = `# Alchemy deploy locks
157
+
158
+ This branch holds the lock (\`{stack}/{stage}/__lease__.json\`) of each stage while a deploy runs.
159
+ The state itself is on the branch without \`-lock\`.
160
+ `;
161
+ const RefResponse = Schema.Struct({ object: Schema.Struct({ sha: Schema.String }) });
162
+ const TreeResponse = Schema.Struct({
163
+ sha: Schema.String,
164
+ truncated: Schema.Boolean,
165
+ tree: Schema.Array(Schema.Struct({
166
+ path: Schema.String,
167
+ type: Schema.String,
168
+ sha: Schema.String
169
+ }))
170
+ });
171
+ const ShaResponse = Schema.Struct({ sha: Schema.String });
172
+ const BlobResponse = Schema.Struct({
173
+ encoding: Schema.String,
174
+ content: Schema.String
175
+ });
176
+ var Retryable = class extends Data.TaggedError("Retryable") {};
177
+ /**
178
+ * The batch applied in order to the files of `base`: the files after it, the new blob sha of each
179
+ * write (`undefined` for a delete or a condition that did not hold), and the paths whose content
180
+ * changes.
181
+ */
182
+ const applyBatch = (base, batch) => {
183
+ const files = new Map(base?.files ?? []);
184
+ const results = [];
185
+ const changed = /* @__PURE__ */ new Map();
186
+ let conditionFailed = false;
187
+ for (const pending of batch) {
188
+ const current = files.get(pending.key);
189
+ const condition = pending.condition;
190
+ if (pending.body === void 0) {
191
+ if (current !== void 0 && (condition === void 0 || "ifVersion" in condition && condition.ifVersion === current)) {
192
+ files.delete(pending.key);
193
+ changed.set(pending.key, {
194
+ body: void 0,
195
+ lock: "release lock"
196
+ });
197
+ } else if (condition !== void 0) conditionFailed = true;
198
+ results.push(void 0);
199
+ continue;
200
+ }
201
+ if (condition !== void 0) {
202
+ if (!("ifAbsent" in condition ? current === void 0 : current === condition.ifVersion)) {
203
+ conditionFailed = true;
204
+ results.push(void 0);
205
+ continue;
206
+ }
207
+ }
208
+ const sha = blobSha(pending.body);
209
+ files.set(pending.key, sha);
210
+ changed.set(pending.key, {
211
+ body: pending.body,
212
+ lock: condition === void 0 ? "" : "ifAbsent" in condition ? "take lock" : "renew lock"
213
+ });
214
+ results.push(sha);
215
+ }
216
+ return {
217
+ files,
218
+ results,
219
+ effective: Array.from(changed).filter(([path, change]) => change.body === void 0 ? base?.files.has(path) === true : base?.files.get(path) !== blobSha(change.body)),
220
+ conditionFailed
221
+ };
222
+ };
223
+ const fail = (message) => new StateStoreError({ message });
224
+ const errorMessage = (json) => typeof json === "object" && json !== null && "message" in json && typeof json.message === "string" ? json.message : "";
225
+ /** `owner/name` from the option, GITHUB_REPOSITORY, or the `origin` remote. */
226
+ const resolveRepository = (explicit) => Effect.try({
227
+ try: () => {
228
+ const fromEnv = explicit ?? process.env["GITHUB_REPOSITORY"];
229
+ if (fromEnv) return fromEnv;
230
+ const url = execFileSync("git", [
231
+ "remote",
232
+ "get-url",
233
+ "origin"
234
+ ], { encoding: "utf8" }).trim();
235
+ const match = /github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(url);
236
+ if (!match?.[1]) throw new Error(`origin is not a GitHub remote: ${url}`);
237
+ return match[1];
238
+ },
239
+ catch: (cause) => fail(`GitHub state store: no repository. Set GITHUB_REPOSITORY or pass { repository }. ${cause instanceof Error ? cause.message : ""}`)
240
+ });
241
+ /** The BucketObjects of one branch (plus its `-lock` branch), bound to the ambient scope. */
242
+ const makeGitHubObjects = (options = {}) => Effect.gen(function* () {
243
+ const client = yield* HttpClient.HttpClient;
244
+ const token = process.env["GITHUB_TOKEN"] || process.env["GH_TOKEN"];
245
+ if (!token) return yield* fail("GitHub state store: set GITHUB_TOKEN or GH_TOKEN");
246
+ const repository = yield* resolveRepository(options.repository);
247
+ const stateBranch = options.branch ?? "alchemy-state-store";
248
+ const repoPath = `/repos/${encodePath(repository)}`;
249
+ const call = (method, path, body) => Effect.gen(function* () {
250
+ const base = HttpClientRequest.make(method)(`${API}${repoPath}${path}`, { headers: {
251
+ authorization: `Bearer ${token}`,
252
+ accept: "application/vnd.github+json",
253
+ "x-github-api-version": "2022-11-28",
254
+ "user-agent": "samebase-alchemy-kit"
255
+ } });
256
+ const request = body === void 0 ? base : HttpClientRequest.bodyJsonUnsafe(base, body);
257
+ const [response, text] = yield* client.execute(request).pipe(Effect.flatMap((answer) => Effect.map(answer.text, (body) => [answer, body])), Effect.mapError((cause) => new Retryable({ message: cause.message })), Effect.timeoutOrElse({
258
+ duration: "60 seconds",
259
+ orElse: () => Effect.fail(new Retryable({ message: `${method} ${path}: no answer in 60 seconds` }))
260
+ }));
261
+ const json = yield* Effect.try({
262
+ try: () => text === "" ? void 0 : JSON.parse(text),
263
+ catch: () => new Retryable({ message: `${method} ${path}: not JSON (${response.status})` })
264
+ });
265
+ const status = response.status;
266
+ const retryAfter = response.headers["retry-after"];
267
+ if ((status === 403 || status === 429) && (retryAfter !== void 0 || response.headers["x-ratelimit-remaining"] === "0" || /rate limit/i.test(errorMessage(json)))) {
268
+ const seconds = Number(retryAfter ?? "60");
269
+ if (!(seconds >= 0 && seconds <= 120)) return yield* fail(`GitHub rate limit on ${method} ${path}: retry after ${retryAfter} (${errorMessage(json)})`);
270
+ yield* Effect.sleep(`${seconds} seconds`);
271
+ return yield* new Retryable({ message: `${method} ${path}: rate limited (${status})` });
272
+ }
273
+ if (status >= 500) return yield* new Retryable({ message: `${method} ${path}: ${status} ${errorMessage(json)}` });
274
+ return {
275
+ status,
276
+ json
277
+ };
278
+ }).pipe(Effect.retry({
279
+ while: (error) => error._tag === "Retryable",
280
+ schedule: Schedule.exponential("500 millis"),
281
+ times: 5
282
+ }), Effect.mapError((error) => error._tag === "Retryable" ? fail(`GitHub state store: ${error.message}`) : error));
283
+ const decode = (schema, what) => (json) => Schema.decodeUnknownEffect(schema)(json).pipe(Effect.mapError((cause) => fail(`GitHub state store: unexpected ${what}: ${cause.message}`)));
284
+ const unexpected = (what, response) => fail(`GitHub state store: ${what} answered ${response.status} ${errorMessage(response.json)}`);
285
+ /** The reads of one branch, and the worker that turns every queued write into one commit. */
286
+ const makeBranch = (branch, readme) => Effect.gen(function* () {
287
+ const queue = yield* Queue.unbounded();
288
+ let known;
289
+ const seen = /* @__PURE__ */ new Set();
290
+ const replaced = /* @__PURE__ */ new Set();
291
+ const blobs = /* @__PURE__ */ new Map();
292
+ /**
293
+ * The branch as GitHub has it now; `undefined` when it does not exist. GitHub can answer
294
+ * with the head from before a write of this process (seen live: 1 read of 40 right after a
295
+ * write). The branch only moves forward, so a head that is behind a commit of this process
296
+ * is an old answer, and the question is asked again.
297
+ */
298
+ const current = Effect.gen(function* () {
299
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
300
+ const ref = yield* call("GET", `/git/ref/heads/${encodePath(branch)}`);
301
+ if (ref.status !== 200 && ref.status !== 404) return yield* unexpected(`GET ref ${branch}`, ref);
302
+ const commit = ref.status === 404 ? void 0 : (yield* decode(RefResponse, "ref")(ref.json)).object.sha;
303
+ if (commit === void 0 ? known !== void 0 : replaced.has(commit)) {
304
+ yield* Effect.sleep("250 millis");
305
+ continue;
306
+ }
307
+ if (commit === void 0) return void 0;
308
+ seen.add(commit);
309
+ if (known?.commit === commit) return known;
310
+ const treeResponse = yield* call("GET", `/git/trees/${commit}?recursive=1`);
311
+ if (treeResponse.status !== 200) return yield* unexpected(`GET tree ${branch}`, treeResponse);
312
+ const tree = yield* decode(TreeResponse, "tree")(treeResponse.json);
313
+ if (tree.truncated) return yield* fail(`GitHub state store: the tree of ${branch} is too large (truncated)`);
314
+ const files = /* @__PURE__ */ new Map();
315
+ for (const entry of tree.tree) if (entry.type === "blob") files.set(entry.path, entry.sha);
316
+ const head = {
317
+ commit,
318
+ tree: tree.sha,
319
+ files
320
+ };
321
+ if (!replaced.has(commit)) known = head;
322
+ return head;
323
+ }
324
+ return yield* fail(`GitHub state store: ${branch} kept answering with a head from before this run's last write`);
325
+ });
326
+ const read = (path) => Effect.gen(function* () {
327
+ const version = (yield* current)?.files.get(path);
328
+ if (version === void 0) return void 0;
329
+ const held = blobs.get(version);
330
+ if (held !== void 0) return {
331
+ text: held,
332
+ version
333
+ };
334
+ const response = yield* call("GET", `/git/blobs/${version}`);
335
+ if (response.status !== 200) return yield* unexpected(`GET blob ${path}`, response);
336
+ const blob = yield* decode(BlobResponse, "blob")(response.json);
337
+ if (blob.encoding !== "base64") return yield* fail(`GitHub state store: ${path} has encoding ${blob.encoding}`);
338
+ const text = Buffer.from(blob.content, "base64").toString("utf8");
339
+ blobs.set(version, text);
340
+ return {
341
+ text,
342
+ version
343
+ };
344
+ });
345
+ const commitBatch = (batch) => Effect.gen(function* () {
346
+ let trusted = known !== void 0;
347
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
348
+ const base = trusted ? known : yield* current;
349
+ const { files, results, effective, conditionFailed } = applyBatch(base, batch);
350
+ if (trusted && (conditionFailed || effective.length === 0)) {
351
+ trusted = false;
352
+ continue;
353
+ }
354
+ if (effective.length === 0) return results;
355
+ const isLock = branch !== stateBranch;
356
+ const message = commitMessage(effective.map(([key, change]) => ({
357
+ key,
358
+ deleted: change.body === void 0,
359
+ lock: isLock ? change.lock : ""
360
+ })));
361
+ const entries = effective.map(([path, change]) => change.body === void 0 ? {
362
+ path,
363
+ mode: "100644",
364
+ type: "blob",
365
+ sha: null
366
+ } : {
367
+ path,
368
+ mode: "100644",
369
+ type: "blob",
370
+ content: change.body
371
+ });
372
+ const treeResponse = yield* call("POST", "/git/trees", base === void 0 ? { tree: [{
373
+ path: "README.md",
374
+ mode: "100644",
375
+ type: "blob",
376
+ content: readme
377
+ }, ...entries.filter((entry) => !("sha" in entry))] } : {
378
+ base_tree: base.tree,
379
+ tree: entries
380
+ });
381
+ if (treeResponse.status !== 201) return yield* unexpected(`POST tree ${branch}`, treeResponse);
382
+ const tree = (yield* decode(ShaResponse, "tree")(treeResponse.json)).sha;
383
+ const commitResponse = yield* call("POST", "/git/commits", {
384
+ message,
385
+ tree,
386
+ parents: base === void 0 ? [] : [base.commit]
387
+ });
388
+ if (commitResponse.status !== 201) return yield* unexpected(`POST commit ${branch}`, commitResponse);
389
+ const commit = (yield* decode(ShaResponse, "commit")(commitResponse.json)).sha;
390
+ const refResponse = base === void 0 ? yield* call("POST", "/git/refs", {
391
+ ref: `refs/heads/${branch}`,
392
+ sha: commit
393
+ }) : yield* call("PATCH", `/git/refs/heads/${encodePath(branch)}`, {
394
+ sha: commit,
395
+ force: false
396
+ });
397
+ if (refResponse.status === 422) {
398
+ trusted = false;
399
+ continue;
400
+ }
401
+ if (refResponse.status !== 200 && refResponse.status !== 201) return yield* unexpected(`update ref ${branch}`, refResponse);
402
+ for (const head of seen) replaced.add(head);
403
+ seen.clear();
404
+ seen.add(commit);
405
+ known = {
406
+ commit,
407
+ tree,
408
+ files
409
+ };
410
+ for (const [, change] of effective) if (change.body !== void 0) blobs.set(blobSha(change.body), change.body);
411
+ return results;
412
+ }
413
+ return yield* fail(`GitHub state store: ${branch} kept moving; gave up after ${MAX_ATTEMPTS} attempts`);
414
+ });
415
+ yield* Queue.takeAll(queue).pipe(Effect.flatMap((batch) => commitBatch(batch).pipe(Effect.flatMap((results) => Effect.forEach(batch, (pending, i) => Deferred.succeed(pending.done, results[i]), { discard: true })), Effect.catchCause((cause) => Effect.forEach(batch, (pending) => Deferred.failCause(pending.done, cause), { discard: true })))), Effect.forever, Effect.forkScoped);
416
+ return {
417
+ read,
418
+ /** Every file path on the branch, with one call when the head is the known one. */
419
+ paths: current.pipe(Effect.map((head) => Array.from(head?.files.keys() ?? []))),
420
+ /** Queue a write or delete; the deferred resolves once its commit is on the branch. */
421
+ enqueue: (key, body, condition) => Effect.gen(function* () {
422
+ const done = yield* Deferred.make();
423
+ yield* Queue.offer(queue, {
424
+ key,
425
+ body,
426
+ condition,
427
+ done
428
+ });
429
+ return done;
430
+ })
431
+ };
432
+ });
433
+ const store = yield* makeBranch(stateBranch, STATE_README);
434
+ const lock = yield* makeBranch(`${stateBranch}-lock`, LOCK_README);
435
+ const branchOf = (key) => key === "__lease__.json" || key.endsWith(`/__lease__.json`) ? lock : store;
436
+ const enqueue = (key, body, condition) => branchOf(key).enqueue(key, body, condition);
437
+ const submit = (key, body, condition) => enqueue(key, body, condition).pipe(Effect.flatMap(Deferred.await), Effect.uninterruptible);
438
+ return {
439
+ listKeys: (prefix) => store.paths.pipe(Effect.map((paths) => paths.filter((path) => path.startsWith(prefix)))),
440
+ listChildren: (prefix) => store.paths.pipe(Effect.map((paths) => {
441
+ const children = /* @__PURE__ */ new Set();
442
+ for (const path of paths) {
443
+ if (!path.startsWith(prefix)) continue;
444
+ const rest = path.slice(prefix.length);
445
+ const slash = rest.indexOf("/");
446
+ if (slash > 0) children.add(rest.slice(0, slash));
447
+ }
448
+ return Array.from(children);
449
+ })),
450
+ read: (key) => branchOf(key).read(key),
451
+ write: (key, body, condition) => submit(key, body, condition),
452
+ delete: (key, ifVersion) => submit(key, void 0, ifVersion === void 0 ? void 0 : { ifVersion }).pipe(Effect.asVoid),
453
+ deleteMany: (keys) => Effect.forEach(keys, (key) => enqueue(key, void 0, void 0)).pipe(Effect.flatMap((pending) => Effect.forEach(pending, Deferred.await, { discard: true })), Effect.uninterruptible)
454
+ };
455
+ });
456
+ /**
457
+ * The State layer. It reads the key and builds the store on the first state operation, bound to
458
+ * this layer's scope, so a missing key fails the run before any read or write.
459
+ */
460
+ const state = (options = {}) => Layer.effect(State, Effect.gen(function* () {
461
+ const scope = yield* Effect.scope;
462
+ const context = yield* Effect.context();
463
+ const make = Effect.gen(function* () {
464
+ const key = yield* parseKey(options.key === void 0 ? process.env[KEY_VARIABLE] : Redacted.value(options.key));
465
+ const objects = yield* makeGitHubObjects(options);
466
+ const sealed = {
467
+ ...objects,
468
+ read: (objectKey) => objects.read(objectKey).pipe(Effect.flatMap((object) => object === void 0 ? Effect.undefined : openRecord(key, objectKey, object.text).pipe(Effect.map((text) => ({
469
+ text,
470
+ version: object.version
471
+ }))))),
472
+ write: (objectKey, body, condition) => sealRecord(key, objectKey, body).pipe(Effect.flatMap((text) => objects.write(objectKey, text, condition)))
473
+ };
474
+ return yield* makeBucketState({
475
+ id: "github",
476
+ label: "GitHub",
477
+ objects: Effect.succeed(sealed)
478
+ });
479
+ });
480
+ return yield* Effect.cached(Scope.provide(make, scope).pipe(Effect.orDie, Effect.provideContext(context)));
481
+ }));
482
+ //#endregion
483
+ export { makeGitHubObjects, state };
484
+
485
+ //# sourceMappingURL=github-state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"github-state.js","names":[],"sources":["../src/github-state/git.ts","../src/github-state/sealing.ts","../src/github-state/GitHubState.ts"],"sourcesContent":["// The paths, blob shas, and commit messages of the state branches.\nimport { createHash } from \"node:crypto\";\nimport { decodeFqn } from \"alchemy/FQN\";\n\n/** The lease of a stage, which Alchemy's BucketState rewrites every 20 seconds during a run. */\nexport const LEASE_FILE = \"__lease__.json\";\n\n/** A path with each segment URL-encoded and its slashes kept, for a GitHub API URL. */\nexport const encodePath = (path: string) => path.split(\"/\").map(encodeURIComponent).join(\"/\");\n\n/** The git blob sha of `text`: what GitHub reports as the file's sha. */\nexport const blobSha = (text: string) => {\n const bytes = Buffer.from(text, \"utf8\");\n return createHash(\"sha1\").update(`blob ${bytes.length}\\0`).update(bytes).digest(\"hex\");\n};\n\n/** What the commit message calls a key: `{stack} {stage}` and the resource. */\nconst describeKey = (key: string) => {\n const parts = key.split(\"/\");\n const file = parts[parts.length - 1] ?? key;\n if (parts.length < 3) return { group: \"\", name: file.replace(/\\.json$/, \"\") };\n const name =\n file === \"__stack_output__.json\"\n ? \"stack output\"\n : file === LEASE_FILE\n ? \"lock\"\n : decodeFqn(file.replace(/\\.json$/, \"\"));\n return { group: `${parts.slice(0, -2).join(\"/\")} ${parts[parts.length - 2]}`, name };\n};\n\nconst listNames = (verb: string, names: ReadonlyArray<string>) =>\n names.length === 0\n ? []\n : names.length <= 5\n ? [`${verb} ${names.join(\", \")}`]\n : [`${verb} ${names.length} resources`];\n\n/**\n * One line per stage, such as `app prod: set Worker, Bucket; delete Old`. A lock change carries\n * its `lock` text (`take lock`, `renew lock`, `release lock`) in place of a resource name.\n */\nexport const commitMessage = (\n changes: ReadonlyArray<{\n readonly key: string;\n readonly deleted: boolean;\n readonly lock: string;\n }>,\n) => {\n const groups = new Map<string, { set: string[]; deleted: string[]; lock: string[] }>();\n for (const change of changes) {\n const { group, name } = describeKey(change.key);\n const entry = groups.get(group) ?? { set: [], deleted: [], lock: [] };\n if (change.lock !== \"\") entry.lock.push(change.lock);\n else if (change.deleted) entry.deleted.push(name);\n else entry.set.push(name);\n groups.set(group, entry);\n }\n return Array.from(groups, ([group, entry]) => {\n const what = [\n ...entry.lock,\n ...listNames(\"set\", entry.set),\n ...listNames(\"delete\", entry.deleted),\n ].join(\"; \");\n return group === \"\" ? `store: ${what}` : `${group}: ${what}`;\n }).join(\"\\n\");\n};\n","// Seals each secret of a state record with AES-256-GCM, with Web Crypto only.\n//\n// Alchemy writes a secret as `{\"__redacted__\": X}` in plain text. On write, X becomes\n// `{\"__sealed__\": \"v1.<iv>.<ciphertext>\"}`: the IV is 12 random bytes, the ciphertext is the\n// AES-GCM output of `JSON.stringify(X)` with its tag, both base64url. The additional authenticated\n// data is the object key of the record, so a sealed value opens only in its own record. Every\n// other field stays readable JSON.\nimport type { webcrypto } from \"node:crypto\";\nimport { REDACTED_MARKER, StateStoreError } from \"alchemy/State\";\nimport * as Effect from \"effect/Effect\";\n\ntype CryptoKey = webcrypto.CryptoKey;\n\nexport const KEY_VARIABLE = \"ALCHEMY_GITHUB_STATE_KEY\";\n\nconst SEALED_MARKER = \"__sealed__\";\nconst VERSION = \"v1\";\n\n/** A key of 32 bytes in base64 is 43 characters and one `=`. */\nconst KEY_TEXT = /^[A-Za-z0-9+/]{43}=$/;\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\nconst fromBase64 = (text: string) => new Uint8Array(Buffer.from(text, \"base64url\"));\nconst toBase64Url = (bytes: Uint8Array) => Buffer.from(bytes).toString(\"base64url\");\n\n/**\n * The AES-256-GCM key in `text`, base64 of exactly 32 bytes. It fails when the text is missing or\n * malformed. An error never quotes the text.\n */\nexport const parseKey = (text: string | undefined) =>\n Effect.gen(function* () {\n const make = `Make one with \\`openssl rand -base64 32\\` and keep it as a secret.`;\n const trimmed = text?.trim();\n if (!trimmed) {\n return yield* new StateStoreError({\n message: `GitHub state store: ${KEY_VARIABLE} is not set. ${make}`,\n });\n }\n if (!KEY_TEXT.test(trimmed)) {\n return yield* new StateStoreError({\n message: `GitHub state store: ${KEY_VARIABLE} is not base64 of 32 bytes. ${make}`,\n });\n }\n return yield* Effect.promise(() =>\n crypto.subtle.importKey(\n \"raw\",\n new Uint8Array(Buffer.from(trimmed, \"base64\")),\n \"AES-GCM\",\n false,\n [\"encrypt\", \"decrypt\"],\n ),\n );\n });\n\n/**\n * `value` with `f` applied to each `__redacted__` field in it. Alchemy reads every object with\n * that field as a secret, also when the object has other fields, so every such field is one here.\n */\nconst mapSecrets = (\n value: unknown,\n f: (inner: unknown) => Effect.Effect<unknown, StateStoreError>,\n): Effect.Effect<unknown, StateStoreError> => {\n if (Array.isArray(value)) return Effect.forEach(value, (item) => mapSecrets(item, f));\n if (typeof value !== \"object\" || value === null) return Effect.succeed(value);\n return Effect.forEach(Object.entries(value), ([name, item]) =>\n (name === REDACTED_MARKER ? f(item) : mapSecrets(item, f)).pipe(\n Effect.map((mapped) => [name, mapped] as const),\n ),\n ).pipe(Effect.map(Object.fromEntries));\n};\n\n/**\n * Rewrites the record `text` with `f` applied to each secret. A record without a secret comes back\n * as the same text.\n */\nconst rewrite = (\n objectKey: string,\n text: string,\n f: (inner: unknown) => Effect.Effect<unknown, StateStoreError>,\n) =>\n Effect.gen(function* () {\n const value: unknown = yield* Effect.try({\n try: (): unknown => JSON.parse(text),\n catch: () => new StateStoreError({ message: `GitHub state store: ${objectKey} is not JSON` }),\n });\n let secrets = 0;\n const mapped = yield* mapSecrets(value, (inner) => {\n secrets++;\n return f(inner);\n });\n return secrets === 0 ? text : JSON.stringify(mapped, null, 2);\n });\n\n/** The record `text` with each secret sealed for the record at `objectKey`. */\nexport const sealRecord = (key: CryptoKey, objectKey: string, text: string) =>\n rewrite(objectKey, text, (inner) =>\n Effect.promise(async () => {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ciphertext = await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv, additionalData: encoder.encode(objectKey) },\n key,\n encoder.encode(JSON.stringify(inner)),\n );\n const sealed = `${VERSION}.${toBase64Url(iv)}.${toBase64Url(new Uint8Array(ciphertext))}`;\n return { [SEALED_MARKER]: sealed };\n }),\n );\n\n/**\n * The record `text` with each sealed secret opened, as Alchemy wrote it. It fails when a secret is\n * not sealed, or does not open with `key` at `objectKey`.\n */\nexport const openRecord = (key: CryptoKey, objectKey: string, text: string) =>\n rewrite(objectKey, text, (inner) =>\n Effect.gen(function* () {\n const sealed =\n typeof inner === \"object\" && inner !== null && SEALED_MARKER in inner\n ? inner[SEALED_MARKER]\n : undefined;\n const [version, iv, ciphertext, ...rest] =\n typeof sealed === \"string\" ? sealed.split(\".\") : [];\n if (version !== VERSION || iv === undefined || ciphertext === undefined || rest.length > 0) {\n return yield* new StateStoreError({\n message: `GitHub state store: ${objectKey} holds a secret that is not sealed by this store`,\n });\n }\n const plaintext = yield* Effect.tryPromise({\n try: () =>\n crypto.subtle.decrypt(\n { name: \"AES-GCM\", iv: fromBase64(iv), additionalData: encoder.encode(objectKey) },\n key,\n fromBase64(ciphertext),\n ),\n catch: () =>\n new StateStoreError({\n message: `GitHub state store: a secret in ${objectKey} does not open. ${KEY_VARIABLE} is not the key that sealed it, or the record was moved from another place.`,\n }),\n });\n // AES-GCM opened it, so it is the JSON text that `sealRecord` sealed.\n const value: unknown = JSON.parse(decoder.decode(plaintext));\n return value;\n }),\n );\n","import { execFileSync } from \"node:child_process\";\nimport { State, StateStoreError } from \"alchemy/State\";\nimport {\n type BucketObjects,\n makeBucketState,\n type WriteCondition,\n} from \"alchemy/State/BucketState\";\nimport * as Data from \"effect/Data\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as HttpClient from \"effect/http/HttpClient\";\nimport * as HttpClientRequest from \"effect/http/HttpClientRequest\";\nimport * as Layer from \"effect/Layer\";\nimport * as Queue from \"effect/Queue\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport { blobSha, commitMessage, encodePath, LEASE_FILE } from \"./git.ts\";\nimport { KEY_VARIABLE, openRecord, parseKey, sealRecord } from \"./sealing.ts\";\n\n/**\n * An Alchemy state store on a branch of a GitHub repository.\n *\n * Built on Alchemy's BucketState, like the S3 and Cloud Storage stores. The \"bucket\" is one Git\n * branch: a key is a path, an object's version is its blob sha. Writes queue up and one worker\n * turns everything queued into one commit through the Git Data API; the ref update with\n * `force: false` is the compare-and-swap, and a lost race starts the batch again on the new head.\n *\n * The lease (`__lease__.json`) lives on a second branch, `<branch>-lock`, so the state branch holds\n * only state.\n */\n\nexport interface GitHubStateOptions {\n /** `owner/name`. @default GITHUB_REPOSITORY, else the `origin` remote */\n readonly repository?: string;\n /** @default \"alchemy-state-store\" */\n readonly branch?: string;\n /** Base64 of 32 bytes that seals each secret. @default ALCHEMY_GITHUB_STATE_KEY */\n readonly key?: Redacted.Redacted<string>;\n}\n\nconst API = \"https://api.github.com\";\nconst MAX_ATTEMPTS = 20;\n\nconst STATE_README = `# Alchemy state\n\nThis branch holds the Alchemy state of this repository. Alchemy deploys write it; do not edit it\nby hand. Each resource is one file, \\`{stack}/{stage}/{resource}.json\\`.\n\nEach secret value is \\`{\"__redacted__\": {\"__sealed__\": \"v1.<iv>.<ciphertext>\"}}\\`, sealed with\nAES-256-GCM under the key in ${KEY_VARIABLE}. Every other value is plain JSON.\n\nThe deploy lock of each stage is on the branch of the same name with \\`-lock\\` at the end.\n`;\n\nconst LOCK_README = `# Alchemy deploy locks\n\nThis branch holds the lock (\\`{stack}/{stage}/__lease__.json\\`) of each stage while a deploy runs.\nThe state itself is on the branch without \\`-lock\\`.\n`;\n\n// GitHub responses, validated.\nconst RefResponse = Schema.Struct({ object: Schema.Struct({ sha: Schema.String }) });\nconst TreeResponse = Schema.Struct({\n sha: Schema.String,\n truncated: Schema.Boolean,\n tree: Schema.Array(\n Schema.Struct({ path: Schema.String, type: Schema.String, sha: Schema.String }),\n ),\n});\nconst ShaResponse = Schema.Struct({ sha: Schema.String });\nconst BlobResponse = Schema.Struct({ encoding: Schema.String, content: Schema.String });\n\nclass Retryable extends Data.TaggedError(\"Retryable\")<{ readonly message: string }> {}\n\ninterface Response {\n readonly status: number;\n readonly json: unknown;\n}\n\n/** A branch head: its commit, its tree, and every file's blob sha. */\ninterface Head {\n readonly commit: string;\n readonly tree: string;\n readonly files: ReadonlyMap<string, string>;\n}\n\n/** A queued write (`body`) or delete (`body` undefined). */\ninterface Pending {\n readonly key: string;\n readonly body: string | undefined;\n readonly condition: WriteCondition | undefined;\n readonly done: Deferred.Deferred<string | undefined, StateStoreError>;\n}\n\n/**\n * The batch applied in order to the files of `base`: the files after it, the new blob sha of each\n * write (`undefined` for a delete or a condition that did not hold), and the paths whose content\n * changes.\n */\nconst applyBatch = (base: Head | undefined, batch: ReadonlyArray<Pending>) => {\n const files = new Map(base?.files ?? []);\n const results: Array<string | undefined> = [];\n const changed = new Map<string, { body: string | undefined; lock: string }>();\n let conditionFailed = false;\n for (const pending of batch) {\n const current = files.get(pending.key);\n const condition = pending.condition;\n if (pending.body === undefined) {\n // A delete of a missing file, or of one at another version, does nothing.\n if (\n current !== undefined &&\n (condition === undefined || (\"ifVersion\" in condition && condition.ifVersion === current))\n ) {\n files.delete(pending.key);\n changed.set(pending.key, { body: undefined, lock: \"release lock\" });\n } else if (condition !== undefined) conditionFailed = true;\n results.push(undefined);\n continue;\n }\n if (condition !== undefined) {\n const holds =\n \"ifAbsent\" in condition ? current === undefined : current === condition.ifVersion;\n if (!holds) {\n conditionFailed = true;\n results.push(undefined);\n continue;\n }\n }\n const sha = blobSha(pending.body);\n files.set(pending.key, sha);\n changed.set(pending.key, {\n body: pending.body,\n lock: condition === undefined ? \"\" : \"ifAbsent\" in condition ? \"take lock\" : \"renew lock\",\n });\n results.push(sha);\n }\n const effective = Array.from(changed).filter(([path, change]) =>\n change.body === undefined\n ? base?.files.has(path) === true\n : base?.files.get(path) !== blobSha(change.body),\n );\n return { files, results, effective, conditionFailed };\n};\n\nconst fail = (message: string) => new StateStoreError({ message });\n\nconst errorMessage = (json: unknown) =>\n typeof json === \"object\" && json !== null && \"message\" in json && typeof json.message === \"string\"\n ? json.message\n : \"\";\n\n/** `owner/name` from the option, GITHUB_REPOSITORY, or the `origin` remote. */\nconst resolveRepository = (explicit: string | undefined) =>\n Effect.try({\n try: () => {\n const fromEnv = explicit ?? process.env[\"GITHUB_REPOSITORY\"];\n if (fromEnv) return fromEnv;\n const url = execFileSync(\"git\", [\"remote\", \"get-url\", \"origin\"], { encoding: \"utf8\" }).trim();\n const match = /github\\.com[:/]([^/]+\\/[^/]+?)(?:\\.git)?$/.exec(url);\n if (!match?.[1]) throw new Error(`origin is not a GitHub remote: ${url}`);\n return match[1];\n },\n catch: (cause) =>\n fail(\n `GitHub state store: no repository. Set GITHUB_REPOSITORY or pass { repository }. ${cause instanceof Error ? cause.message : \"\"}`,\n ),\n });\n\n/** The BucketObjects of one branch (plus its `-lock` branch), bound to the ambient scope. */\nexport const makeGitHubObjects = (options: GitHubStateOptions = {}) =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient;\n const token = process.env[\"GITHUB_TOKEN\"] || process.env[\"GH_TOKEN\"];\n if (!token) return yield* fail(\"GitHub state store: set GITHUB_TOKEN or GH_TOKEN\");\n const repository = yield* resolveRepository(options.repository);\n const stateBranch = options.branch ?? \"alchemy-state-store\";\n const repoPath = `/repos/${encodePath(repository)}`;\n\n const call = (method: \"GET\" | \"POST\" | \"PATCH\", path: string, body?: unknown) =>\n Effect.gen(function* () {\n const base = HttpClientRequest.make(method)(`${API}${repoPath}${path}`, {\n headers: {\n authorization: `Bearer ${token}`,\n accept: \"application/vnd.github+json\",\n \"x-github-api-version\": \"2022-11-28\",\n \"user-agent\": \"samebase-alchemy-kit\",\n },\n });\n const request = body === undefined ? base : HttpClientRequest.bodyJsonUnsafe(base, body);\n // A call with no answer would hold its callers for good: they wait uninterruptibly.\n const [response, text] = yield* client.execute(request).pipe(\n Effect.flatMap((answer) => Effect.map(answer.text, (body) => [answer, body] as const)),\n Effect.mapError((cause) => new Retryable({ message: cause.message })),\n Effect.timeoutOrElse({\n duration: \"60 seconds\",\n orElse: () =>\n Effect.fail(new Retryable({ message: `${method} ${path}: no answer in 60 seconds` })),\n }),\n );\n const json: unknown = yield* Effect.try({\n try: (): unknown => (text === \"\" ? undefined : JSON.parse(text)),\n catch: () =>\n new Retryable({ message: `${method} ${path}: not JSON (${response.status})` }),\n });\n const status = response.status;\n const retryAfter = response.headers[\"retry-after\"];\n const limited =\n (status === 403 || status === 429) &&\n (retryAfter !== undefined ||\n response.headers[\"x-ratelimit-remaining\"] === \"0\" ||\n /rate limit/i.test(errorMessage(json)));\n if (limited) {\n // `retry-after` can also be a date; only a count of at most 120 seconds is waited for.\n const seconds = Number(retryAfter ?? \"60\");\n if (!(seconds >= 0 && seconds <= 120)) {\n return yield* fail(\n `GitHub rate limit on ${method} ${path}: retry after ${retryAfter} (${errorMessage(json)})`,\n );\n }\n yield* Effect.sleep(`${seconds} seconds`);\n return yield* new Retryable({ message: `${method} ${path}: rate limited (${status})` });\n }\n if (status >= 500) {\n return yield* new Retryable({\n message: `${method} ${path}: ${status} ${errorMessage(json)}`,\n });\n }\n const result: Response = { status, json };\n return result;\n }).pipe(\n Effect.retry({\n while: (error) => error._tag === \"Retryable\",\n schedule: Schedule.exponential(\"500 millis\"),\n times: 5,\n }),\n Effect.mapError((error) =>\n error._tag === \"Retryable\" ? fail(`GitHub state store: ${error.message}`) : error,\n ),\n );\n\n const decode =\n <S extends Schema.Codec<unknown, unknown>>(schema: S, what: string) =>\n (json: unknown) =>\n Schema.decodeUnknownEffect(schema)(json).pipe(\n Effect.mapError((cause) =>\n fail(`GitHub state store: unexpected ${what}: ${cause.message}`),\n ),\n );\n\n const unexpected = (what: string, response: Response) =>\n fail(\n `GitHub state store: ${what} answered ${response.status} ${errorMessage(response.json)}`,\n );\n\n /** The reads of one branch, and the worker that turns every queued write into one commit. */\n const makeBranch = (branch: string, readme: string) =>\n Effect.gen(function* () {\n const queue = yield* Queue.unbounded<Pending>();\n // The newest head this process knows, each head it saw since its last commit, the heads\n // that are behind one of its commits, and the text of each blob it wrote or read.\n let known: Head | undefined;\n const seen = new Set<string>();\n const replaced = new Set<string>();\n const blobs = new Map<string, string>();\n\n /**\n * The branch as GitHub has it now; `undefined` when it does not exist. GitHub can answer\n * with the head from before a write of this process (seen live: 1 read of 40 right after a\n * write). The branch only moves forward, so a head that is behind a commit of this process\n * is an old answer, and the question is asked again.\n */\n const current = Effect.gen(function* () {\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n const ref = yield* call(\"GET\", `/git/ref/heads/${encodePath(branch)}`);\n if (ref.status !== 200 && ref.status !== 404) {\n return yield* unexpected(`GET ref ${branch}`, ref);\n }\n const commit =\n ref.status === 404\n ? undefined\n : (yield* decode(RefResponse, \"ref\")(ref.json)).object.sha;\n if (commit === undefined ? known !== undefined : replaced.has(commit)) {\n yield* Effect.sleep(\"250 millis\");\n continue;\n }\n if (commit === undefined) return undefined;\n seen.add(commit);\n if (known?.commit === commit) return known;\n const treeResponse = yield* call(\"GET\", `/git/trees/${commit}?recursive=1`);\n if (treeResponse.status !== 200) {\n return yield* unexpected(`GET tree ${branch}`, treeResponse);\n }\n const tree = yield* decode(TreeResponse, \"tree\")(treeResponse.json);\n if (tree.truncated) {\n return yield* fail(\n `GitHub state store: the tree of ${branch} is too large (truncated)`,\n );\n }\n const files = new Map<string, string>();\n for (const entry of tree.tree) {\n if (entry.type === \"blob\") files.set(entry.path, entry.sha);\n }\n const head: Head = { commit, tree: tree.sha, files };\n // A commit of this process can land while the tree loads.\n if (!replaced.has(commit)) known = head;\n return head;\n }\n return yield* fail(\n `GitHub state store: ${branch} kept answering with a head from before this run's last write`,\n );\n });\n\n const read = (path: string) =>\n Effect.gen(function* () {\n const version = (yield* current)?.files.get(path);\n if (version === undefined) return undefined;\n const held = blobs.get(version);\n if (held !== undefined) return { text: held, version };\n const response = yield* call(\"GET\", `/git/blobs/${version}`);\n if (response.status !== 200) return yield* unexpected(`GET blob ${path}`, response);\n const blob = yield* decode(BlobResponse, \"blob\")(response.json);\n if (blob.encoding !== \"base64\") {\n return yield* fail(`GitHub state store: ${path} has encoding ${blob.encoding}`);\n }\n const text = Buffer.from(blob.content, \"base64\").toString(\"utf8\");\n blobs.set(version, text);\n return { text, version };\n });\n\n const commitBatch = (batch: ReadonlyArray<Pending>) =>\n Effect.gen(function* () {\n // The first attempt builds on the known head without a question to GitHub: the ref\n // update fails if another writer moved the branch since.\n let trusted = known !== undefined;\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n const base = trusted ? known : yield* current;\n const { files, results, effective, conditionFailed } = applyBatch(base, batch);\n // A failed condition or \"nothing to write\" against the known head may be out of\n // date: check against the branch as it is now.\n if (trusted && (conditionFailed || effective.length === 0)) {\n trusted = false;\n continue;\n }\n if (effective.length === 0) return results;\n const isLock = branch !== stateBranch;\n const message = commitMessage(\n effective.map(([key, change]) => ({\n key,\n deleted: change.body === undefined,\n lock: isLock ? change.lock : \"\",\n })),\n );\n const entries = effective.map(([path, change]) =>\n change.body === undefined\n ? { path, mode: \"100644\", type: \"blob\", sha: null }\n : { path, mode: \"100644\", type: \"blob\", content: change.body },\n );\n const treeResponse = yield* call(\n \"POST\",\n \"/git/trees\",\n base === undefined\n ? {\n tree: [\n { path: \"README.md\", mode: \"100644\", type: \"blob\", content: readme },\n ...entries.filter((entry) => !(\"sha\" in entry)),\n ],\n }\n : { base_tree: base.tree, tree: entries },\n );\n if (treeResponse.status !== 201) {\n return yield* unexpected(`POST tree ${branch}`, treeResponse);\n }\n const tree = (yield* decode(ShaResponse, \"tree\")(treeResponse.json)).sha;\n const commitResponse = yield* call(\"POST\", \"/git/commits\", {\n message,\n tree,\n parents: base === undefined ? [] : [base.commit],\n });\n if (commitResponse.status !== 201) {\n return yield* unexpected(`POST commit ${branch}`, commitResponse);\n }\n const commit = (yield* decode(ShaResponse, \"commit\")(commitResponse.json)).sha;\n const refResponse =\n base === undefined\n ? yield* call(\"POST\", \"/git/refs\", { ref: `refs/heads/${branch}`, sha: commit })\n : yield* call(\"PATCH\", `/git/refs/heads/${encodePath(branch)}`, {\n sha: commit,\n force: false,\n });\n // 422: another writer moved (or created) the branch. Start again on its head.\n if (refResponse.status === 422) {\n trusted = false;\n continue;\n }\n if (refResponse.status !== 200 && refResponse.status !== 201) {\n return yield* unexpected(`update ref ${branch}`, refResponse);\n }\n // Each head seen so far was the head at some time before this commit landed, so it\n // is behind this commit: the base, and also an earlier head of this process when\n // another writer's commit came between.\n for (const head of seen) replaced.add(head);\n seen.clear();\n seen.add(commit);\n known = { commit, tree, files };\n for (const [, change] of effective) {\n if (change.body !== undefined) blobs.set(blobSha(change.body), change.body);\n }\n return results;\n }\n return yield* fail(\n `GitHub state store: ${branch} kept moving; gave up after ${MAX_ATTEMPTS} attempts`,\n );\n });\n\n yield* Queue.takeAll(queue).pipe(\n Effect.flatMap((batch) =>\n commitBatch(batch).pipe(\n Effect.flatMap((results) =>\n Effect.forEach(batch, (pending, i) => Deferred.succeed(pending.done, results[i]), {\n discard: true,\n }),\n ),\n // Also a defect goes to the callers: a worker that stops would leave them waiting.\n Effect.catchCause((cause) =>\n Effect.forEach(batch, (pending) => Deferred.failCause(pending.done, cause), {\n discard: true,\n }),\n ),\n ),\n ),\n Effect.forever,\n Effect.forkScoped,\n );\n\n return {\n read,\n /** Every file path on the branch, with one call when the head is the known one. */\n paths: current.pipe(Effect.map((head) => Array.from(head?.files.keys() ?? []))),\n /** Queue a write or delete; the deferred resolves once its commit is on the branch. */\n enqueue: (key: string, body: string | undefined, condition: WriteCondition | undefined) =>\n Effect.gen(function* () {\n const done = yield* Deferred.make<string | undefined, StateStoreError>();\n yield* Queue.offer(queue, { key, body, condition, done });\n return done;\n }),\n };\n });\n\n const store = yield* makeBranch(stateBranch, STATE_README);\n const lock = yield* makeBranch(`${stateBranch}-lock`, LOCK_README);\n const branchOf = (key: string) =>\n key === LEASE_FILE || key.endsWith(`/${LEASE_FILE}`) ? lock : store;\n const enqueue = (\n key: string,\n body: string | undefined,\n condition: WriteCondition | undefined,\n ) => branchOf(key).enqueue(key, body, condition);\n // A queued write lands even when its caller is interrupted, so the caller waits for it.\n // BucketState interrupts a lease renewal before it releases the lease; with an interruptible\n // wait the renewal could land after the release read the lease, and the release then deleted\n // nothing.\n const submit = (key: string, body: string | undefined, condition: WriteCondition | undefined) =>\n enqueue(key, body, condition).pipe(Effect.flatMap(Deferred.await), Effect.uninterruptible);\n\n const objects: BucketObjects = {\n listKeys: (prefix) =>\n store.paths.pipe(Effect.map((paths) => paths.filter((path) => path.startsWith(prefix)))),\n listChildren: (prefix) =>\n store.paths.pipe(\n Effect.map((paths) => {\n const children = new Set<string>();\n for (const path of paths) {\n if (!path.startsWith(prefix)) continue;\n const rest = path.slice(prefix.length);\n const slash = rest.indexOf(\"/\");\n if (slash > 0) children.add(rest.slice(0, slash));\n }\n return Array.from(children);\n }),\n ),\n read: (key) => branchOf(key).read(key),\n write: (key, body, condition) => submit(key, body, condition),\n delete: (key, ifVersion) =>\n submit(key, undefined, ifVersion === undefined ? undefined : { ifVersion }).pipe(\n Effect.asVoid,\n ),\n // Queue every delete before waiting, so they land in one commit.\n deleteMany: (keys) =>\n Effect.forEach(keys, (key) => enqueue(key, undefined, undefined)).pipe(\n Effect.flatMap((pending) => Effect.forEach(pending, Deferred.await, { discard: true })),\n Effect.uninterruptible,\n ),\n };\n\n return objects;\n });\n\n/**\n * The State layer. It reads the key and builds the store on the first state operation, bound to\n * this layer's scope, so a missing key fails the run before any read or write.\n */\nexport const state = (\n options: GitHubStateOptions = {},\n): Layer.Layer<State, never, HttpClient.HttpClient> =>\n Layer.effect(\n State,\n Effect.gen(function* () {\n const scope = yield* Effect.scope;\n const context = yield* Effect.context<HttpClient.HttpClient>();\n const make = Effect.gen(function* () {\n const key = yield* parseKey(\n options.key === undefined ? process.env[KEY_VARIABLE] : Redacted.value(options.key),\n );\n const objects = yield* makeGitHubObjects(options);\n const sealed: BucketObjects = {\n ...objects,\n read: (objectKey) =>\n objects\n .read(objectKey)\n .pipe(\n Effect.flatMap((object) =>\n object === undefined\n ? Effect.undefined\n : openRecord(key, objectKey, object.text).pipe(\n Effect.map((text) => ({ text, version: object.version })),\n ),\n ),\n ),\n write: (objectKey, body, condition) =>\n sealRecord(key, objectKey, body).pipe(\n Effect.flatMap((text) => objects.write(objectKey, text, condition)),\n ),\n };\n return yield* makeBucketState({\n id: \"github\",\n label: \"GitHub\",\n objects: Effect.succeed(sealed),\n });\n });\n return yield* Effect.cached(\n Scope.provide(make, scope).pipe(Effect.orDie, Effect.provideContext(context)),\n );\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;AAQA,MAAa,cAAc,SAAiB,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,kBAAkB,CAAC,CAAC,KAAK,GAAG;;AAG5F,MAAa,WAAW,SAAiB;CACvC,MAAM,QAAQ,OAAO,KAAK,MAAM,MAAM;CACtC,OAAO,WAAW,MAAM,CAAC,CAAC,OAAO,QAAQ,MAAM,OAAO,GAAG,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACvF;;AAGA,MAAM,eAAe,QAAgB;CACnC,MAAM,QAAQ,IAAI,MAAM,GAAG;CAC3B,MAAM,OAAO,MAAM,MAAM,SAAS,MAAM;CACxC,IAAI,MAAM,SAAS,GAAG,OAAO;EAAE,OAAO;EAAI,MAAM,KAAK,QAAQ,WAAW,EAAE;CAAE;CAC5E,MAAM,OACJ,SAAS,0BACL,iBACA,SAAA,mBACE,SACA,UAAU,KAAK,QAAQ,WAAW,EAAE,CAAC;CAC7C,OAAO;EAAE,OAAO,GAAG,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,GAAG,EAAE,GAAG,MAAM,MAAM,SAAS;EAAM;CAAK;AACrF;AAEA,MAAM,aAAa,MAAc,UAC/B,MAAM,WAAW,IACb,CAAC,IACD,MAAM,UAA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CAAC,CAAC,KAC/B,OAAO,SAAS,SAAS,QAAQ,MAAM,WAAW,MAAM,SAAS,CAAC,CACpE;EACJ;EACA,OAAO,OAAO,gBAAgB;GAC5B,IAAI;GACJ,OAAO;GACP,SAAS,OAAO,QAAQ,MAAM;EAChC,CAAC;CACH,CAAC;CACD,OAAO,OAAO,OAAO,OACnB,MAAM,QAAQ,MAAM,KAAK,CAAC,CAAC,KAAK,OAAO,OAAO,OAAO,eAAe,OAAO,CAAC,CAC9E;AACF,CAAC,CACH"}
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@samebase/alchemy-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "A kit of parts for Alchemy v2: a state store on a branch of a GitHub repository, with sealed secrets",
5
+ "keywords": [
6
+ "alchemy",
7
+ "effect",
8
+ "github",
9
+ "infrastructure-as-code",
10
+ "state"
11
+ ],
12
+ "homepage": "https://github.com/samebase/samebase/tree/main/packages/alchemy-kit#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/samebase/samebase/issues"
15
+ },
16
+ "license": "Apache-2.0",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/samebase/samebase.git",
20
+ "directory": "packages/alchemy-kit"
21
+ },
22
+ "files": [
23
+ "lib",
24
+ "src",
25
+ "README.md",
26
+ "LICENSE",
27
+ "NOTICE"
28
+ ],
29
+ "type": "module",
30
+ "sideEffects": false,
31
+ "exports": {
32
+ "./github-state": {
33
+ "types": "./lib/github-state.d.ts",
34
+ "import": "./lib/github-state.js"
35
+ }
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "devDependencies": {
41
+ "@arethetypeswrong/core": "0.18.5",
42
+ "@types/node": "24.19.2",
43
+ "alchemy": "2.0.0-beta.85",
44
+ "effect": "4.1.2",
45
+ "publint": "0.3.25",
46
+ "typescript": "6.0.3",
47
+ "vite-plus": "1.3.0",
48
+ "vitest": "5.0.5"
49
+ },
50
+ "peerDependencies": {
51
+ "alchemy": "2.0.0-beta.85",
52
+ "effect": "^4.1.0"
53
+ },
54
+ "engines": {
55
+ "node": ">=22"
56
+ },
57
+ "scripts": {
58
+ "check": "pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run build",
59
+ "typecheck": "tsc --noEmit",
60
+ "test": "pnpm --dir ../.. exec vp test run --project alchemy-kit",
61
+ "test:live": "vp test run test/github-state/live",
62
+ "lint": "pnpm --dir ../.. exec vp lint --tsconfig packages/alchemy-kit/tsconfig.json --report-unused-disable-directives packages/alchemy-kit",
63
+ "build": "vp pack"
64
+ }
6
65
  }