@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 292 lines 10.2 KB
Raw
1 import * as bne from "@distilled.cloud/gcp/blockchainnodeengine_v1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import { tagRecord } from "alchemy/Tags";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as Schedule from "effect/Schedule";
7 import * as Stream from "effect/Stream";
8 import { stripInternalLabels } from "../Labels.ts";
9 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
10
11 export const DEFAULT_BLOCKCHAIN_TYPE = "ETHEREUM";
12 export const DEFAULT_NETWORK = "TESTNET_SEPOLIA";
13 export const DEFAULT_NODE_TYPE = "FULL";
14 export const DEFAULT_EXECUTION_CLIENT = "GETH";
15 export const DEFAULT_CONSENSUS_CLIENT = "LIGHTHOUSE";
16 export const MAX_NAME_LENGTH = 63;
17 export const COLLECTION = "blockchainNodes";
18
19 export class ResourceNotResolved extends Data.TaggedError("GCP.BlockchainNodeEngine.NotResolved")<{
20 resourceName: string;
21 }> {}
22
23 export class ResourceStillExists extends Data.TaggedError("GCP.BlockchainNodeEngine.StillExists")<{
24 resourceName: string;
25 }> {}
26
27 export class ResourceNotReady extends Data.TaggedError("GCP.BlockchainNodeEngine.NotReady")<{
28 resourceName: string;
29 state: string;
30 }> {}
31
32 export class ResourceFailed extends Data.TaggedError("GCP.BlockchainNodeEngine.Failed")<{
33 resourceName: string;
34 state: string;
35 message: string | undefined;
36 }> {}
37
38 export const lastSegment = (value: string | undefined) => {
39 if (value === undefined || value.length === 0) return "";
40 const trimmed = value.replace(/\/+$/, "");
41 const parts = trimmed.split("/");
42 return parts[parts.length - 1] || trimmed;
43 };
44
45 export const rfc1035 = (name: string, fallback = "node"): string => {
46 let next = name
47 .toLowerCase()
48 .replace(/[^a-z0-9-]/g, "-")
49 .replace(/-+/g, "-")
50 .replace(/^-+|-+$/g, "");
51 if (!/^[a-z]/.test(next)) next = `n${next}`;
52 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
53 if (next.length === 0) return fallback;
54 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
55 return next.slice(0, MAX_NAME_LENGTH);
56 };
57
58 export const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
59 lastSegment(location ?? defaultLocation).toLowerCase();
60
61 export const normalizeEnum = (value: string | undefined, fallback: string) => {
62 const next = (value ?? fallback).toUpperCase();
63 return next.length === 0 || next.endsWith("_UNSPECIFIED") ? fallback : next;
64 };
65
66 export const parentOf = (project: string, location: string) =>
67 `projects/${project}/locations/${lastSegment(location).toLowerCase()}`;
68
69 export const resourceName = (project: string, location: string, blockchainNodeId: string) =>
70 `${parentOf(project, location)}/${COLLECTION}/${blockchainNodeId}`;
71
72 export const toPhysicalId = (
73 id: string,
74 explicit: string | undefined,
75 existing: string | undefined,
76 fallback = "node",
77 ) =>
78 Effect.gen(function* () {
79 if (explicit !== undefined) return rfc1035(explicit, fallback);
80 if (existing !== undefined) return existing;
81 return rfc1035(
82 yield* createPhysicalName({
83 id,
84 maxLength: MAX_NAME_LENGTH,
85 lowercase: true,
86 }),
87 fallback,
88 );
89 });
90
91 export const parseName = (name: string, defaultLocation: string) => {
92 const parts = name.split("/").filter((part) => part.length > 0);
93 const collectionAt = parts.lastIndexOf(COLLECTION);
94 const locationsAt = parts.lastIndexOf("locations");
95 const projectsAt = parts.lastIndexOf("projects");
96 return {
97 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
98 location:
99 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation,
100 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
101 };
102 };
103
104 export const userLabels = (
105 labels: Record<string, string | undefined> | null | undefined,
106 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
107
108 export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) =>
109 Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
110
111 export const canonical = (value: unknown): unknown => {
112 if (value === undefined || value === null) return undefined;
113 if (typeof value === "boolean" || typeof value === "number") return value;
114 if (typeof value === "string") {
115 return value.length === 0 ? undefined : value;
116 }
117 if (Array.isArray(value)) {
118 const items = value.map(canonical).filter((item) => item !== undefined);
119 return items.length === 0 ? undefined : items;
120 }
121 if (typeof value === "object") {
122 const entries = Object.entries(value as Record<string, unknown>)
123 .map(([key, item]) => [key, canonical(item)] as const)
124 .filter(([, item]) => item !== undefined)
125 .sort(([left], [right]) => left.localeCompare(right));
126 if (entries.length === 0) return undefined;
127 return Object.fromEntries(entries);
128 }
129 return undefined;
130 };
131
132 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
133
134 export const fieldMask = (fields: Array<string | false | undefined>) =>
135 fields.filter((field): field is string => typeof field === "string").join(",");
136
137 export const sameText = (left: string | undefined, right: string | undefined) =>
138 (left ?? "") === (right ?? "");
139
140 export const sameEnum = (left: string | undefined, right: string | undefined) =>
141 (left ?? "").toUpperCase() === (right ?? "").toUpperCase();
142
143 export const sameStringList = (
144 left: readonly string[] | undefined,
145 right: readonly string[] | undefined,
146 ) =>
147 fingerprint([...(left ?? [])].map((value) => value.toLowerCase()).sort()) ===
148 fingerprint([...(right ?? [])].map((value) => value.toLowerCase()).sort());
149
150 export const replaceOnIdentity = (input: {
151 previousId: string | undefined;
152 nextId: string | undefined;
153 previousLocation: string;
154 nextLocation: string;
155 extra?: boolean;
156 }) => {
157 const replace =
158 (input.extra ?? false) ||
159 (input.previousId !== undefined &&
160 input.nextId !== undefined &&
161 input.nextId !== input.previousId) ||
162 input.previousLocation !== input.nextLocation;
163 if (!replace) return undefined;
164 const samePhysical =
165 input.previousLocation === input.nextLocation &&
166 input.previousId !== undefined &&
167 input.nextId === input.previousId;
168 return {
169 action: "replace" as const,
170 deleteFirst: samePhysical,
171 };
172 };
173
174 const READY_STATES = new Set(["RUNNING", "SYNCING"]);
175 const FAILED_STATES = new Set(["ERROR", "DELETING"]);
176
177 export const isReadyState = (state: string | undefined) => {
178 const value = (state ?? "").toUpperCase();
179 return value.length === 0 || READY_STATES.has(value);
180 };
181
182 export const isFailedState = (state: string | undefined) =>
183 FAILED_STATES.has((state ?? "").toUpperCase());
184
185 /**
186 * Wait for a Blockchain Node Engine operation; node creation takes up to
187 * ~30 minutes. ALREADY_EXISTS (code 6) counts as success (create race);
188 * with `notFoundOk`, so does NOT_FOUND (code 5, delete race).
189 */
190 export const waitForOperation = (operation: bne.Operation, options?: { notFoundOk?: boolean }) =>
191 waitForGcpOperation(operation, (name) => bne.getProjectsLocationsOperations({ name }), {
192 budget: "45 minutes",
193 interval: "10 seconds",
194 }).pipe(
195 Effect.catchIf(
196 (error) =>
197 error._tag === "GCP.OperationFailed" &&
198 (error.code === 6 || (options?.notFoundOk === true && error.code === 5)),
199 () => Effect.succeed(operation),
200 ),
201 );
202
203 export const waitUntilExists = <A, E, R>(
204 get: Effect.Effect<A | undefined, E, R>,
205 name: string,
206 ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved, R> =>
207 get.pipe(
208 Effect.filterOrFail(
209 (value): value is NonNullable<A> => value != null,
210 () => new ResourceNotResolved({ resourceName: name }),
211 ),
212 Effect.retry({
213 while: (error) => error instanceof ResourceNotResolved,
214 times: 8,
215 schedule: Schedule.spaced("1 second"),
216 }),
217 );
218
219 export const waitUntilGone = <A, E, R>(
220 get: Effect.Effect<A | undefined, E, R>,
221 name: string,
222 ): Effect.Effect<void, E | ResourceStillExists, R> =>
223 get.pipe(
224 Effect.filterOrFail(
225 (value) => value === undefined,
226 () => new ResourceStillExists({ resourceName: name }),
227 ),
228 Effect.retry({
229 while: (error) => error instanceof ResourceStillExists,
230 times: 10,
231 schedule: Schedule.spaced("8 seconds"),
232 }),
233 Effect.asVoid,
234 );
235
236 export const waitUntilReady = <A, E, R>(
237 get: Effect.Effect<A | undefined, E, R>,
238 name: string,
239 stateOf: (value: NonNullable<A>) => string | undefined,
240 messageOf?: (value: NonNullable<A>) => string | undefined,
241 ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved | ResourceFailed | ResourceNotReady, R> =>
242 get.pipe(
243 Effect.filterOrFail(
244 (value): value is NonNullable<A> => value != null,
245 () => new ResourceNotResolved({ resourceName: name }),
246 ),
247 Effect.filterOrFail(
248 (value) => !isFailedState(stateOf(value)),
249 (value) =>
250 new ResourceFailed({
251 resourceName: name,
252 state: stateOf(value) ?? "",
253 message: messageOf?.(value),
254 }),
255 ),
256 Effect.filterOrFail(
257 (value) => isReadyState(stateOf(value)),
258 (value) =>
259 new ResourceNotReady({
260 resourceName: name,
261 state: stateOf(value) ?? "",
262 }),
263 ),
264 Effect.retry({
265 while: (error) => error instanceof ResourceNotReady || error instanceof ResourceNotResolved,
266 times: 10,
267 schedule: Schedule.spaced("8 seconds"),
268 }),
269 );
270
271 export const listAtLocation = <A, E, R>(
272 project: string,
273 region: string,
274 list: (parent: string) => Effect.Effect<A[], E, R>,
275 ): Effect.Effect<A[], E, R> =>
276 // Prefer the all-locations wildcard; fall back to the default region
277 // (whose error, if any, propagates).
278 list(`projects/${project}/locations/-`).pipe(
279 Effect.catch(() => list(`projects/${project}/locations/${region}`)),
280 );
281
282 export const listLabeledPages = <Page, A, E, R>(
283 pages: Stream.Stream<Page, E, R>,
284 items: (page: Page) => readonly A[] | undefined,
285 labelsOf: (item: A) => Record<string, string | undefined> | null | undefined,
286 ): Effect.Effect<A[], E, R> =>
287 pages.pipe(
288 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
289 Stream.filter((item) => hasAlchemyLabelMap(labelsOf(item))),
290 Stream.runCollect,
291 Effect.map((chunk) => Array.from(chunk)),
292 );