Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

npmRelease.ts

132 lines5.4 KB

1import {
2 ServerNpmReleaseError,
3 ServerNpmReleaseInput,
4 type ServerNpmRelease,
5} from "@t3tools/contracts";
6import { npmReleaseDatabaseMigration } from "@t3tools/shared/cliRelease";
7import { resolveCommandPath } from "@t3tools/shared/shell";
8import * as Cache from "effect/Cache";
9import * as Context from "effect/Context";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Schema from "effect/Schema";
15import * as Semaphore from "effect/Semaphore";
16import { FetchHttpClient, HttpClient } from "effect/http";
17​
18import * as ProcessRunner from "../processRunner.ts";
19​
20const Version = Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/));
21const Manifest = Schema.Struct({ version: Version, t3code: Schema.optionalKey(Schema.Unknown) });
22// npm prints a bare version string when the release has no `t3code` field.
23const decodeManifest = Schema.decodeUnknownOption(
24 Schema.fromJsonString(Schema.Union([Manifest, Schema.Tuple([Manifest]), Version])),
25);
26const decodeError = Schema.decodeUnknownOption(
27 Schema.fromJsonString(Schema.Struct({ error: Schema.Struct({ code: Schema.String }) })),
28);
29const decodeInput = Schema.decodeUnknownEffect(ServerNpmReleaseInput);
30​
31export class NpmRelease extends Context.Service<
32 NpmRelease,
33 {
34 readonly get: (
35 input: ServerNpmReleaseInput,
36 ) => Effect.Effect<ServerNpmRelease | null, ServerNpmReleaseError>;
37 }
38>()("t3/cloud/npmRelease") {}
39​
40function toRelease(spec: string, json: string) {
41 const decoded = Option.getOrUndefined(decodeManifest(json));
42 const manifest =
43 typeof decoded === "string"
44 ? { version: decoded }
45 : decoded && ("version" in decoded ? decoded : decoded[0]);
46 if (!manifest || (spec !== "latest" && spec !== "nightly" && manifest.version !== spec)) {
47 return Effect.fail(
48 new ServerNpmReleaseError({ reason: "npm returned invalid release metadata." }),
49 );
50 }
51 const databaseMigration = npmReleaseDatabaseMigration(manifest);
52 return Effect.succeed({
53 version: manifest.version,
54 ...(databaseMigration === undefined ? {} : { databaseMigration }),
55 });
57​
58export const make = Effect.fn("NpmRelease.make")(function* () {
59 const runner = yield* ProcessRunner.ProcessRunner;
60 const http = yield* HttpClient.HttpClient;
61 const lookupPublic = Effect.fn("NpmRelease.lookupPublic")(function* (spec: string) {
62 const unreachable = new ServerNpmReleaseError({
63 reason: "npm is not installed and the public npm registry could not be reached.",
64 });
65 const json = yield* Effect.gen(function* () {
66 const response = yield* http.get(`https://registry.npmjs.org/t3/${spec}`);
67 if (response.status === 404) return Option.none<string>();
68 if (response.status < 200 || response.status >= 300) return yield* unreachable;
69 return Option.some(yield* response.text);
70 }).pipe(
71 Effect.timeout(Duration.seconds(15)),
72 Effect.mapError(() => unreachable),
73 );
74 return Option.isNone(json) ? null : yield* toRelease(spec, json.value);
75 });
76 // npm loads the whole package history per lookup, so a burst of specs must not spawn one each.
77 const npmPermits = yield* Semaphore.make(2);
78 const cache = yield* Cache.make({
79 capacity: 32,
80 timeToLive: Duration.minutes(1),
81 lookup: Effect.fn("NpmRelease.lookup")(function* (spec: string) {
82 // Without npm there is no configured registry to honor, so use the public one.
83 const npmPath = yield* resolveCommandPath("npm");
84 if (npmPath === null) return yield* lookupPublic(spec);
85 const output = yield* npmPermits
86 .withPermits(1)(
87 runner.run({
88 command: npmPath,
89 // Named fields keep the output small; the full package document grows with every release.
90 args: ["view", "--global", "--json", `t3@${spec}`, "version", "t3code"],
91 timeout: Duration.seconds(15),
92 maxOutputBytes: 256 * 1024,
93 }),
94 )
95 .pipe(
96 Effect.tapError((error) =>
97 Effect.logInfo("npm release lookup failed", { tag: error._tag }),
98 ),
99 Effect.mapError(
100 () => new ServerNpmReleaseError({ reason: "npm could not complete the lookup." }),
101 ),
102 );
103 if (output.timedOut || output.stdoutTruncated || output.stdoutInvalidUtf8) {
104 return yield* new ServerNpmReleaseError({ reason: "npm returned an incomplete response." });
105 }
106 if (output.code !== 0) {
107 const error = Option.getOrUndefined(decodeError(output.stdout));
108 if (error?.error.code === "E404") return null;
109 yield* Effect.logInfo("npm release lookup failed", {
110 exitCode: output.code,
111 npmErrorCode: error?.error.code,
112 });
113 return yield* new ServerNpmReleaseError({ reason: "npm could not read release metadata." });
114 }
115 return yield* toRelease(spec, output.stdout);
116 }),
117 });
118 return NpmRelease.of({
119 get: Effect.fn("NpmRelease.get")(function* (input) {
120 const { spec } = yield* decodeInput(input).pipe(
121 Effect.mapError(
122 () => new ServerNpmReleaseError({ reason: "Invalid release version or track." }),
123 ),
124 );
125 return yield* Cache.get(cache, spec);
126 }),
127 });
128});
129​
130export const layer = Layer.effect(NpmRelease, make()).pipe(
131 Layer.provide([ProcessRunner.layer, FetchHttpClient.layer]),
132);