The best way to control Claude Code, Codex and more from any computer or phone

main
ts 148 lines 5.22 KB
Raw
1 import * as Config from "effect/Config";
2 import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as HttpApiClient from "effect/http-api/HttpApiClient";
6 import * as Path from "effect/Path";
7 import * as Schedule from "effect/Schedule";
8 import * as Schema from "effect/Schema";
9 import { MANIFEST_FILE, ManifestJson, type Manifest } from "../Manifest.ts";
10 import { PkgApi, type TarballRef } from "../Protocol.ts";
11
12 export class PublishError extends Data.TaggedError("PublishError")<{
13 readonly message: string;
14 }> {}
15
16 export interface PublishOptions {
17 readonly cwd: string;
18 readonly dir: string;
19 readonly registry: string;
20 }
21
22 /**
23 * The GitHub Actions run this job belongs to, from the runner's environment.
24 */
25 const currentRun = Effect.gen(function* () {
26 const repo = yield* Config.String("GITHUB_REPOSITORY");
27 const runId = yield* Config.Int("GITHUB_RUN_ID");
28 const attempt = yield* Config.Int("GITHUB_RUN_ATTEMPT").pipe(Config.withDefault(1));
29 return { repo, runId, attempt };
30 }).pipe(
31 Effect.mapError(
32 () =>
33 new PublishError({
34 message: "pkg publish must run inside a GitHub Actions job",
35 }),
36 ),
37 );
38
39 /** Render a registry or transport failure as a `PublishError`. */
40 const failed = (what: string) => (e: { readonly _tag: string; readonly message?: string }) =>
41 new PublishError({
42 message: `${what}: ${e.message ? `${e._tag}: ${e.message}` : e._tag}`,
43 });
44
45 /**
46 * GitHub reports a run as queued, or as its previous attempt, for a few
47 * seconds after a job starts, and for minutes while Actions is degraded.
48 * The registry answers `RunNotInProgress` until GitHub catches up, so a
49 * request from inside the job waits that out, for up to three minutes.
50 */
51 const whileRunCatchesUp = <A, E extends { readonly _tag: string }, R>(
52 effect: Effect.Effect<A, E, R>,
53 ) =>
54 effect.pipe(
55 Effect.tapError((e) =>
56 e._tag === "RunNotInProgress"
57 ? Effect.logInfo("GitHub does not report this run as in progress yet; retrying")
58 : Effect.void,
59 ),
60 Effect.retry({
61 while: (e) => e._tag === "RunNotInProgress",
62 schedule: Schedule.spaced("5 seconds"),
63 times: 36,
64 }),
65 );
66
67 /**
68 * Publish a `pkg pack` directory from the current GitHub Actions job. The
69 * workflow must first have uploaded the manifest as an artifact of the run
70 * under the name `pkg pack` printed; the registry verifies that artifact
71 * through GitHub, then either reports the tarballs it lacks, which are
72 * uploaded before trying again, or writes the tags.
73 */
74 export const publish = Effect.fn("publish")(function* (options: PublishOptions) {
75 const fs = yield* FileSystem.FileSystem;
76 const path = yield* Path.Path;
77 const registry = options.registry.replace(/\/+$/, "");
78 const run = yield* currentRun;
79 const client = yield* HttpApiClient.make(PkgApi, { baseUrl: registry });
80
81 const dir = path.resolve(options.cwd, options.dir);
82 const manifestText = yield* fs.readFileString(path.join(dir, MANIFEST_FILE));
83 const manifest = yield* Schema.decodeEffect(ManifestJson)(manifestText);
84 if (manifest.registry !== registry) {
85 return yield* new PublishError({
86 message: `artifact was packed for ${manifest.registry}, not ${registry}`,
87 });
88 }
89
90 if (manifest.packages.length === 0) {
91 yield* Effect.logInfo("No affected packages to publish.");
92 return { packages: [] };
93 }
94
95 const upload = (pkg: Manifest["packages"][number]) =>
96 Effect.gen(function* () {
97 const bytes = yield* fs.readFile(path.join(dir, pkg.file));
98 const result = yield* whileRunCatchesUp(
99 client.Registry.uploadTarball({
100 params: { name: pkg.name, sha256: pkg.sha256 },
101 query: run,
102 payload: bytes,
103 }),
104 ).pipe(Effect.mapError(failed(`upload ${pkg.name}`)));
105 yield* Effect.logInfo(
106 `${result.uploaded ? "Uploaded" : "Reused"} ${pkg.name} (${pkg.sha256.slice(0, 12)}, ${pkg.size} bytes)`,
107 );
108 });
109
110 const uploadMissing = (missing: ReadonlyArray<TarballRef>) => {
111 const wanted = new Set(missing.map((ref) => `${ref.name}@${ref.sha256}`));
112 return Effect.logInfo(
113 `${missing.length} of ${manifest.packages.length} tarball(s) to upload`,
114 ).pipe(
115 Effect.andThen(
116 Effect.forEach(
117 manifest.packages.filter((pkg) => wanted.has(`${pkg.name}@${pkg.sha256}`)),
118 upload,
119 { concurrency: 4, discard: true },
120 ),
121 ),
122 );
123 };
124
125 const attempt = whileRunCatchesUp(
126 client.Registry.publish({
127 payload: { run, manifest: manifestText },
128 }),
129 );
130 const published = yield* attempt.pipe(
131 // The first answer is usually the tarballs to upload; publish once more
132 // after uploading them.
133 Effect.catchTag("MissingTarballs", (e) => Effect.andThen(uploadMissing(e.missing), attempt)),
134 Effect.catchTag(
135 "MissingTarballs",
136 (e) =>
137 new PublishError({
138 message: `registry still reports missing tarballs after upload: ${e.missing.map((ref) => ref.name).join(", ")}`,
139 }),
140 ),
141 Effect.mapError((e) => (e._tag === "PublishError" ? e : failed("publish")(e))),
142 );
143
144 for (const pkg of published.packages) {
145 yield* Effect.logInfo(`${pkg.name}: ${pkg.url} [${pkg.tags.join(", ")}]`);
146 }
147 return published;
148 });