@samebase/alchemy-convex 0.40.0 → 0.40.1

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/src/RunRecord.ts DELETED
@@ -1,271 +0,0 @@
1
- // The run record: what the stage output says about the run that wrote it.
2
- // Alchemy state holds no time, author, commit, branch, or run (measured in
3
- // the Samebase research of 2026-10-21), so the layer `withRunRecord` adds this
4
- // record to the output document under the reserved key `samebase.run`. The
5
- // record depends on no store: it comes from the GitHub Actions variables, or
6
- // from git in the checkout that runs the stack, and holds no secret, and the
7
- // layer goes over any state layer. See docs/design/convex-state.md.
8
- import { execFile } from "node:child_process";
9
- import { readFile, realpath } from "node:fs/promises";
10
- import { relative, sep } from "node:path";
11
- import { promisify } from "node:util";
12
- import { State, type StateService } from "alchemy/State";
13
- import * as Clock from "effect/Clock";
14
- import * as Effect from "effect/Effect";
15
- import * as Layer from "effect/Layer";
16
- import * as Schema from "effect/Schema";
17
-
18
- /** The key of the record in the stage output document. */
19
- export const RUN_RECORD_KEY = "samebase.run";
20
-
21
- /** The name of the stack file. Alchemy resolves `--config` against the working directory and does not expose it to a state layer, so the record assumes the default name. */
22
- export const STACK_FILE_NAME = "alchemy.run.ts";
23
-
24
- /** Version 1 of the record. A reader validates `version` first. */
25
- export interface RunRecord {
26
- readonly version: 1;
27
- /** GitHub `owner/name`. */
28
- readonly repository: string;
29
- /** Path of the stack file from the repository root, POSIX separators, such as `apps/samebase/alchemy.run.ts`. */
30
- readonly stackFile: string;
31
- /** The branch that was deployed: the head branch of a pull request, else the pushed branch. */
32
- readonly branch: string;
33
- /** The pull request whose head was deployed, or null for a push and for a checkout. */
34
- readonly pullRequest: number | null;
35
- /** The commit that was deployed: the head of the pull request, else GITHUB_SHA, else git HEAD. */
36
- readonly headCommit: string;
37
- /** The GitHub Actions run and attempt, or null for a checkout. */
38
- readonly runUrl: string | null;
39
- /**
40
- * Where the record came from: the variables of a GitHub Actions run, or git in a checkout outside
41
- * GitHub Actions, such as a developer's machine, a sandbox, or another CI. It says nothing of the
42
- * stage: a checkout can deploy `prod`.
43
- */
44
- readonly source: "github-actions" | "checkout";
45
- /** ISO 8601, when the record was written. */
46
- readonly recordedAt: string;
47
- }
48
-
49
- export class RunRecordError extends Schema.TaggedError<RunRecordError>()("RunRecordError", {
50
- reason: Schema.String,
51
- }) {
52
- override get message() {
53
- return `The run record of the stage output cannot be made: ${this.reason}`;
54
- }
55
- }
56
-
57
- /** Where the run happens: the working directory of the stack and the process environment. */
58
- export interface RunEnvironment {
59
- readonly cwd: string;
60
- readonly env: Readonly<Record<string, string | undefined>>;
61
- }
62
-
63
- /** The part of the GitHub Actions event payload that the record reads. A push event has no `pull_request`. */
64
- const EventPayload = Schema.Struct({
65
- pull_request: Schema.optionalKey(
66
- Schema.Struct({ number: Schema.Number, head: Schema.Struct({ sha: Schema.String }) }),
67
- ),
68
- });
69
-
70
- /** `owner/name` of an https, ssh, or scp-like git URL with a host. A local path is not one. */
71
- const REMOTE_URL = /^(?:[a-z+]+:\/\/[^/]+\/|[^/@:]+@[^:/]+:)([^/]+)\/([^/]+?)(?:\.git)?\/?$/;
72
-
73
- const execFileAsync = promisify(execFile);
74
-
75
- const now = Clock.currentTimeMillis.pipe(Effect.map((millis) => new Date(millis).toISOString()));
76
-
77
- const git = (cwd: string, args: readonly string[]) =>
78
- Effect.tryPromise({
79
- try: async () =>
80
- (await execFileAsync("git", ["-C", cwd, ...args], { encoding: "utf8" })).stdout.trim(),
81
- catch: (error) =>
82
- new RunRecordError({
83
- reason: `git ${args.join(" ")} failed in ${cwd} (${error instanceof Error ? error.message.split("\n")[0] : String(error)})`,
84
- }),
85
- });
86
-
87
- /** The stack file from the repository root: the working directory below the git top level, plus {@link STACK_FILE_NAME}. */
88
- const stackFileOf = (cwd: string) =>
89
- Effect.gen(function* () {
90
- const top = yield* git(cwd, ["rev-parse", "--show-toplevel"]);
91
- // git prints the real path, and the working directory can hold a symlink, such as macOS /tmp.
92
- const [realTop, realCwd] = yield* Effect.tryPromise({
93
- try: () => Promise.all([realpath(top), realpath(cwd)]),
94
- catch: () => new RunRecordError({ reason: `${cwd} is gone` }),
95
- });
96
- const directory = relative(realTop, realCwd)
97
- .split(sep)
98
- .filter((part) => part !== "");
99
- return [...directory, STACK_FILE_NAME].join("/");
100
- });
101
-
102
- const variable = (env: RunEnvironment["env"], name: string) =>
103
- Effect.suspend(() => {
104
- const value = env[name];
105
- return value === undefined || value === ""
106
- ? Effect.fail(
107
- new RunRecordError({ reason: `GITHUB_ACTIONS is true, and ${name} is not set` }),
108
- )
109
- : Effect.succeed(value);
110
- });
111
-
112
- const fromGitHubActions = (where: RunEnvironment) =>
113
- Effect.gen(function* () {
114
- const { env } = where;
115
- const repository = yield* variable(env, "GITHUB_REPOSITORY");
116
- const refName = yield* variable(env, "GITHUB_REF_NAME");
117
- const sha = yield* variable(env, "GITHUB_SHA");
118
- const serverUrl = yield* variable(env, "GITHUB_SERVER_URL");
119
- const runId = yield* variable(env, "GITHUB_RUN_ID");
120
- const runAttempt = yield* variable(env, "GITHUB_RUN_ATTEMPT");
121
- const eventPath = env["GITHUB_EVENT_PATH"];
122
- const payload =
123
- eventPath === undefined || eventPath === ""
124
- ? undefined
125
- : yield* Effect.tryPromise({
126
- try: () => readFile(eventPath, "utf8"),
127
- catch: () =>
128
- new RunRecordError({ reason: `GITHUB_EVENT_PATH ${eventPath} cannot be read` }),
129
- }).pipe(
130
- Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(EventPayload))),
131
- Effect.mapError((error) =>
132
- error instanceof RunRecordError
133
- ? error
134
- : new RunRecordError({
135
- reason: `GITHUB_EVENT_PATH ${eventPath} is not an event payload`,
136
- }),
137
- ),
138
- );
139
- const pullRequest = payload?.pull_request;
140
- // GITHUB_SHA is the merge commit on a pull request event; the head of the pull request is what a person sees.
141
- const headCommit = pullRequest?.head.sha ?? sha;
142
- const headRef = env["GITHUB_HEAD_REF"];
143
- const mergeRef = /^refs\/pull\/(\d+)\/merge$/.exec(env["GITHUB_REF"] ?? "");
144
- const stackFile = yield* stackFileOf(where.cwd);
145
- const record: RunRecord = {
146
- version: 1,
147
- repository,
148
- stackFile,
149
- branch: headRef === undefined || headRef === "" ? refName : headRef,
150
- pullRequest: pullRequest?.number ?? (mergeRef === null ? null : Number(mergeRef[1])),
151
- headCommit,
152
- runUrl: `${serverUrl}/${repository}/actions/runs/${runId}/attempts/${runAttempt}`,
153
- source: "github-actions",
154
- recordedAt: yield* now,
155
- };
156
- return record;
157
- });
158
-
159
- const fromGit = (where: RunEnvironment) =>
160
- Effect.gen(function* () {
161
- const { cwd } = where;
162
- const origin = yield* git(cwd, ["remote", "get-url", "origin"]);
163
- const match = REMOTE_URL.exec(origin);
164
- if (match === null) {
165
- return yield* new RunRecordError({
166
- reason: `the origin remote of ${cwd} is not a git URL with a host and owner/name: ${origin}`,
167
- });
168
- }
169
- const branch = yield* git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]);
170
- if (branch === "HEAD") {
171
- return yield* new RunRecordError({
172
- reason: `the checkout at ${cwd} is on no branch (detached HEAD)`,
173
- });
174
- }
175
- const record: RunRecord = {
176
- version: 1,
177
- repository: `${match[1]}/${match[2]}`,
178
- stackFile: yield* stackFileOf(cwd),
179
- branch,
180
- pullRequest: null,
181
- headCommit: yield* git(cwd, ["rev-parse", "HEAD"]),
182
- runUrl: null,
183
- source: "checkout",
184
- recordedAt: yield* now,
185
- };
186
- return record;
187
- });
188
-
189
- /**
190
- * The record of this run: from the GitHub Actions variables and the event
191
- * payload when GITHUB_ACTIONS is `true`, else from git in `cwd`, which needs
192
- * a branch and an `origin` remote with `owner/name`. Fails when a value is
193
- * missing; nothing is guessed.
194
- */
195
- export const runRecord = (where: RunEnvironment): Effect.Effect<RunRecord, RunRecordError> =>
196
- where.env["GITHUB_ACTIONS"] === "true" ? fromGitHubActions(where) : fromGit(where);
197
-
198
- /** A plain object, which a spread keeps whole. A Date, a Duration, or a Redacted value is an object too, and a spread loses it. */
199
- // eslint-disable-next-line samebase/no-hand-written-type-predicate -- This published package depends on no app package; the body checks the prototype.
200
- const isPlainObject = (value: unknown): value is Record<string, unknown> => {
201
- if (typeof value !== "object" || value === null) return false;
202
- const prototype: unknown = Object.getPrototypeOf(value);
203
- return prototype === Object.prototype || prototype === null;
204
- };
205
-
206
- /**
207
- * The output document of a stage: the stack's output plus the record under
208
- * {@link RUN_RECORD_KEY}, or undefined for an output with no place for the
209
- * key: a string, an array, null, or an object that is not plain, such as a
210
- * Date. A value that the stack itself put under the key stays.
211
- */
212
- export const outputWithRunRecord = (output: unknown, record: RunRecord): object | undefined =>
213
- isPlainObject(output)
214
- ? RUN_RECORD_KEY in output
215
- ? output
216
- : { ...output, [RUN_RECORD_KEY]: record }
217
- : undefined;
218
-
219
- /**
220
- * The state of `inner`, with the record of this run in each stage output that it writes, under
221
- * {@link RUN_RECORD_KEY}: `state: withRunRecord(Convex.state())`, or the same over another state
222
- * layer, such as the Cloudflare state store of Alchemy. Every other call goes to `inner` as it is.
223
- *
224
- * The record is derived once, at the first use of the state, and `recordedAt` is the time of the
225
- * output write. A checkout that gives no record, such as a tarball without git, a checkout without
226
- * `origin`, or a detached HEAD, still reads, plans, and destroys: its outputs are written without
227
- * the record, and the log says why. The engine writes the output only after a full successful
228
- * apply, so the record names the last full successful deploy of the stage.
229
- */
230
- export const withRunRecord = <E, R>(inner: Layer.Layer<State, E, R>): Layer.Layer<State, E, R> =>
231
- Layer.effect(
232
- State,
233
- Effect.gen(function* () {
234
- const open = yield* State;
235
- return yield* Effect.cached(
236
- Effect.gen(function* () {
237
- const service = yield* open;
238
- const run = yield* runRecord({ cwd: process.cwd(), env: process.env }).pipe(
239
- Effect.catch((error) =>
240
- Effect.logWarning(
241
- `The stage outputs of this run carry no run record. ${error.message}`,
242
- ).pipe(Effect.as(undefined)),
243
- ),
244
- );
245
- const documentOf = (request: { stack: string; stage: string; value: unknown }) =>
246
- Effect.gen(function* () {
247
- if (run === undefined) return request.value;
248
- const document = outputWithRunRecord(request.value, {
249
- ...run,
250
- recordedAt: yield* now,
251
- });
252
- if (document !== undefined) return document;
253
- yield* Effect.logWarning(
254
- `The output of ${request.stack}/${request.stage} is not a plain object, so it carries no run record.`,
255
- );
256
- return request.value;
257
- });
258
- const wrapped: StateService = {
259
- ...service,
260
- setOutput: (request) =>
261
- documentOf(request).pipe(
262
- Effect.flatMap((value) =>
263
- service.setOutput({ stack: request.stack, stage: request.stage, value }),
264
- ),
265
- ),
266
- };
267
- return wrapped;
268
- }),
269
- );
270
- }),
271
- ).pipe(Layer.provide(inner));