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

WriterRegistry.ts

128 lines5.0 KB

1import * as Config from "effect/Config";
2import * as Context from "effect/Context";
3import * as Crypto from "effect/Crypto";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import type * as PlatformError from "effect/PlatformError";
7import * as Layer from "effect/Layer";
8import * as Schema from "effect/Schema";
9​
10const Writers = Schema.fromJsonString(Schema.Record(Schema.String, Schema.String));
11const decodeWriters = Schema.decodeEffect(Writers);
12const encodeWriters = Schema.encodeEffect(Writers);
13​
14const stateDirectory = Config.String("HOME").pipe(
15 Effect.map((home) => `${home}/.config/t3-task-cache`),
16);
17​
18const Credential = Schema.fromJsonString(
19 Schema.Struct({ endpoint: Schema.String, name: Schema.String, token: Schema.String }),
20);
21class ManagementError extends Schema.TaggedError<ManagementError>()("ManagementError", {
22 message: Schema.String,
23}) {}
24export const isWriterName = (name: string) =>
25 /^(?!writers$|credentials$|readers$|ci-reader$)[a-z0-9-]{1,64}$/.test(name);
26​
27const encodeCredential = Schema.encodeEffect(Credential);
28​
29export class WriterRegistry extends Context.Service<
30 WriterRegistry,
31 {
32 readonly read: () => Effect.Effect<
33 Record<string, string>,
34 PlatformError.PlatformError | Schema.SchemaError
35 >;
36 readonly update: (
37 name: string,
38 revoke: boolean,
39 endpoint?: string,
40 initialize?: boolean,
41 ) => Effect.Effect<
42 string | undefined,
43 PlatformError.PlatformError | Schema.SchemaError | ManagementError
44 >;
45 }
46>()("@t3tools/task-cache/WriterRegistry") {}
47​
48const make = Effect.gen(function* () {
49 const fs = yield* FileSystem.FileSystem;
50 const crypto = yield* Crypto.Crypto;
51 const state = yield* stateDirectory;
52 const readWriters = Effect.fn("TaskCache.readWriters")(function* () {
53 return yield* decodeWriters(yield* fs.readFileString(`${state}/writers.json`));
54 });
55​
56 const save = Effect.fn("TaskCache.save")(function* (
57 entries: ReadonlyArray<readonly [string, string]>,
58 ) {
59 yield* fs.makeDirectory(state, { recursive: true, mode: 0o700 });
60 yield* Effect.scoped(
61 Effect.gen(function* () {
62 const directory = yield* fs.makeTempDirectoryScoped({
63 directory: state,
64 prefix: ".writer-",
65 });
66 for (const [name, value] of entries)
67 yield* fs.writeFileString(`${directory}/${name}.json`, value + "\n", { mode: 0o600 });
68 // The registry is the authorization commit point and must publish last.
69 for (const [name] of entries)
70 yield* fs.rename(`${directory}/${name}.json`, `${state}/${name}.json`);
71 }),
72 );
73 });
74​
75 const updateWriter = Effect.fn("TaskCache.updateWriter")(function* (
76 name: string,
77 revoke: boolean,
78 endpoint?: string,
79 initialize = false,
80 ) {
81 if (!isWriterName(name)) return yield* new ManagementError({ message: "Invalid writer name." });
82 if (!revoke && !endpoint)
83 return yield* new ManagementError({ message: "A deployed cache endpoint is required." });
84 return yield* Effect.scoped(
85 Effect.gen(function* () {
86 yield* fs.makeDirectory(state, { recursive: true, mode: 0o700 });
87 // Exclusive creation coordinates separate management processes as well as fibers.
88 yield* Effect.acquireRelease(
89 fs.makeDirectory(`${state}/writers.lock`).pipe(
90 Effect.mapError((error) =>
91 error.reason._tag === "AlreadyExists"
92 ? new ManagementError({
93 message:
94 "Writer registry is locked by another update. Retry after it completes; remove writers.lock only if that process has stopped.",
95 })
96 : error,
97 ),
98 ),
99 () => fs.remove(`${state}/writers.lock`, { recursive: true }).pipe(Effect.orDie),
100 );
101 const exists = yield* fs.exists(`${state}/writers.json`);
102 if (!exists && !initialize)
103 return yield* new ManagementError({
104 message:
105 "Writer registry is missing. Copy the existing private registry from its administrator; use --new-registry only when creating a new cache.",
106 });
107 const writers = { ...(exists || revoke ? yield* readWriters() : {}) };
108 const token = hex(yield* crypto.randomBytes(32));
109 if (revoke) delete writers[name];
110 else {
111 writers[name] = hex(yield* crypto.digest("SHA-256", new TextEncoder().encode(token)));
112 }
113 const entries: Array<readonly [string, string]> = [];
114 if (!revoke && endpoint)
115 entries.push([name, yield* encodeCredential({ endpoint, name, token })]);
116 entries.push(["writers", yield* encodeWriters(writers)]);
117 yield* save(entries);
118 return revoke ? undefined : `${state}/${name}.json`;
119 }),
120 );
121 });
122 return WriterRegistry.of({ read: readWriters, update: updateWriter });
123});
124​
125export const layer = Layer.effect(WriterRegistry, make);
126​
127const hex = (bytes: Uint8Array) =>
128 Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");