@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 376 lines 11.9 KB
Raw
1 import * as oracle from "@distilled.cloud/gcp/oracledatabase_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_NETWORK = "default";
12 export const MAX_NAME_LENGTH = 63;
13
14 export class ResourceNotResolved extends Data.TaggedError(
15 "GCP.OracleDatabase.ResourceNotResolved",
16 )<{
17 resourceName: string;
18 }> {}
19
20 export { ResourceNotResolved as OracleDatabaseNotResolved };
21
22 export class ResourceStillExists extends Data.TaggedError(
23 "GCP.OracleDatabase.ResourceStillExists",
24 )<{
25 resourceName: string;
26 }> {}
27
28 export class ResourceNotReady extends Data.TaggedError("GCP.OracleDatabase.ResourceNotReady")<{
29 resourceName: string;
30 state: string;
31 }> {}
32
33 export class ResourceFailed extends Data.TaggedError("GCP.OracleDatabase.ResourceFailed")<{
34 resourceName: string;
35 state: string;
36 details: string | undefined;
37 }> {}
38
39 export type CustomerContact = {
40 /** Email Oracle uses for notifications. */
41 email?: string;
42 };
43
44 export type TimeZone = {
45 /** IANA time zone (e.g. `America/New_York`). */
46 id?: string;
47 /** IANA database version (e.g. `2019a`). */
48 version?: string;
49 };
50
51 export const lastSegment = (value: string | undefined) => {
52 if (value === undefined || value.length === 0) return "";
53 const trimmed = value.replace(/\/+$/, "");
54 const parts = trimmed.split("/");
55 return parts[parts.length - 1] || trimmed;
56 };
57
58 export const rfc1035 = (name: string, fallback = "oracle"): string => {
59 let next = name
60 .toLowerCase()
61 .replace(/[^a-z0-9-]/g, "-")
62 .replace(/-+/g, "-")
63 .replace(/^-+|-+$/g, "");
64 if (!/^[a-z]/.test(next)) next = `o${next}`;
65 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, "");
66 if (next.length === 0) return fallback;
67 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`;
68 return next.slice(0, MAX_NAME_LENGTH);
69 };
70
71 export const alphanumericId = (name: string, maxLength = 32): string => {
72 let next = name.toLowerCase().replace(/[^a-z0-9]/g, "");
73 if (!/^[a-z]/.test(next)) next = `o${next}`;
74 next = next.slice(0, maxLength);
75 if (next.length === 0) return "oggdeploy";
76 return next;
77 };
78
79 export const normalizeLocation = (location: string) => lastSegment(location).toLowerCase();
80
81 export const parentOf = (project: string, location: string) =>
82 `projects/${project}/locations/${normalizeLocation(location)}`;
83
84 export const toPhysicalId = (
85 id: string,
86 explicit: string | undefined,
87 existing: string | undefined,
88 fallback = "oracle",
89 ) =>
90 Effect.gen(function* () {
91 if (explicit !== undefined) return rfc1035(explicit, fallback);
92 if (existing !== undefined) return existing;
93 return rfc1035(
94 yield* createPhysicalName({
95 id,
96 maxLength: MAX_NAME_LENGTH,
97 lowercase: true,
98 }),
99 fallback,
100 );
101 });
102
103 export const parseName = (name: string, collection: string) => {
104 const parts = name.split("/").filter((part) => part.length > 0);
105 const collectionAt = parts.lastIndexOf(collection);
106 const locationsAt = parts.lastIndexOf("locations");
107 const projectsAt = parts.lastIndexOf("projects");
108 return {
109 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
110 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
111 id:
112 collectionAt >= 0 && parts[collectionAt + 1]
113 ? parts.slice(collectionAt + 1).join("/")
114 : lastSegment(name),
115 parent:
116 collectionAt > 0
117 ? parts.slice(0, collectionAt).join("/")
118 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
119 };
120 };
121
122 export const expandParent = (
123 value: string,
124 project: string,
125 location: string,
126 collection: string,
127 ) => {
128 if (value.includes("/")) return value.replace(/\/+$/, "");
129 return `projects/${project}/locations/${location}/${collection}/${value}`;
130 };
131
132 export const networkName = (project: string, network: string | undefined) => {
133 const value = network ?? DEFAULT_NETWORK;
134 if (value.includes("/")) return value;
135 return `projects/${project}/global/networks/${value}`;
136 };
137
138 export const expandNetwork = (project: string, network: string | undefined) => {
139 if (network === undefined || network.length === 0) return undefined;
140 if (network.includes("/")) return network;
141 return `projects/${project}/global/networks/${network}`;
142 };
143
144 export const resourceNameOf = (project: string, location: string, collection: string, id: string) =>
145 `projects/${project}/locations/${location}/${collection}/${id}`;
146
147 export const retryQuota = <A, E extends { _tag: string }, R>(effect: Effect.Effect<A, E, R>) =>
148 effect.pipe(
149 Effect.retry({
150 while: (error) => error._tag === "TooManyRequests",
151 times: 8,
152 schedule: Schedule.exponential("2 seconds"),
153 }),
154 );
155
156 export const retryConflict = <A, E extends { _tag: string }, R>(effect: Effect.Effect<A, E, R>) =>
157 effect.pipe(
158 Effect.retry({
159 while: (error) => error._tag === "Conflict" || error._tag === "TooManyRequests",
160 times: 8,
161 schedule: Schedule.spaced("5 seconds"),
162 }),
163 );
164
165 const canonical = (value: unknown): unknown => {
166 if (value === undefined || value === null) return undefined;
167 if (typeof value === "boolean" || typeof value === "number") return value;
168 if (typeof value === "string") {
169 return value.length === 0 ? undefined : value;
170 }
171 if (Array.isArray(value)) {
172 const items = value.map(canonical).filter((item) => item !== undefined);
173 return items.length === 0 ? undefined : items;
174 }
175 if (typeof value === "object") {
176 const entries = Object.entries(value as Record<string, unknown>)
177 .map(([key, item]) => [key, canonical(item)] as const)
178 .filter(([, item]) => item !== undefined)
179 .sort(([left], [right]) => left.localeCompare(right));
180 if (entries.length === 0) return undefined;
181 return Object.fromEntries(entries);
182 }
183 return undefined;
184 };
185
186 export const specifiedEquals = (desired: unknown, observed: unknown): boolean => {
187 if (desired === undefined) return true;
188 return JSON.stringify(canonical(desired) ?? null) === JSON.stringify(canonical(observed) ?? null);
189 };
190
191 export const userLabels = (
192 labels: Record<string, string | undefined> | null | undefined,
193 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
194
195 export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) =>
196 Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
197
198 export const replaceOnIdentity = (input: {
199 previousId: string | undefined;
200 nextId: string | undefined;
201 previousLocation: string;
202 nextLocation: string;
203 extra?: boolean;
204 previousParent?: string;
205 nextParent?: string;
206 }) => {
207 const parentChanged =
208 (input.previousParent ?? "") !== "" &&
209 (input.nextParent ?? "") !== "" &&
210 (input.previousParent ?? "") !== (input.nextParent ?? "");
211 const replace =
212 (input.extra ?? false) ||
213 parentChanged ||
214 (input.previousId !== undefined &&
215 input.nextId !== undefined &&
216 input.nextId !== input.previousId) ||
217 input.previousLocation !== input.nextLocation;
218 if (!replace) return undefined;
219 const samePhysical =
220 input.previousLocation === input.nextLocation &&
221 !parentChanged &&
222 input.previousId !== undefined &&
223 input.nextId === input.previousId;
224 return {
225 action: "replace" as const,
226 deleteFirst: samePhysical,
227 };
228 };
229
230 const READY_STATES = new Set([
231 "AVAILABLE",
232 "AVAILABLE_NEEDS_ATTENTION",
233 "ACTIVE",
234 "READY",
235 "SUCCEEDED",
236 ]);
237 const FAILED_STATES = new Set(["FAILED", "NEEDS_ATTENTION"]);
238
239 export const isReadyState = (state: string | undefined) =>
240 READY_STATES.has((state ?? "").toUpperCase());
241
242 export const isFailedState = (state: string | undefined) =>
243 FAILED_STATES.has((state ?? "").toUpperCase());
244
245 /** Wait for an operation through the shared GCP waiter. */
246 export const waitForOperation = (
247 operation: oracle.Operation,
248 options?: { notFoundOk?: boolean; alreadyExistsOk?: boolean },
249 ) =>
250 waitForGcpOperation(
251 operation,
252 (name) =>
253 oracle
254 .getProjectsLocationsOperations({ name })
255 .pipe(
256 Effect.catchTag("NotFound", (error) =>
257 options?.notFoundOk === true
258 ? Effect.succeed<oracle.Operation>({ name, done: true })
259 : Effect.fail(error),
260 ),
261 ),
262 { budget: "60 minutes" },
263 ).pipe(
264 // ALREADY_EXISTS (6): a concurrent create won the race. NOT_FOUND (5)
265 // is success for a delete.
266 Effect.catchIf(
267 (error) =>
268 error._tag === "GCP.OperationFailed" &&
269 ((options?.alreadyExistsOk !== false && error.code === 6) ||
270 (options?.notFoundOk === true && error.code === 5)),
271 () => Effect.void,
272 ),
273 // Re-read the finished operation for its typed response and metadata.
274 Effect.flatMap(() =>
275 operation.name === undefined || operation.name.length === 0
276 ? Effect.succeed(operation)
277 : oracle
278 .getProjectsLocationsOperations({ name: operation.name })
279 .pipe(Effect.catchTag("NotFound", () => Effect.succeed(operation))),
280 ),
281 );
282
283 export const waitUntilExists = <A, E extends { _tag: string }, R>(
284 get: Effect.Effect<A | undefined, E, R>,
285 name: string,
286 ) =>
287 get.pipe(
288 Effect.filterOrFail(
289 (value): value is A => value !== undefined,
290 () => new ResourceNotResolved({ resourceName: name }),
291 ),
292 Effect.retry({
293 while: (error) => error._tag === "GCP.OracleDatabase.ResourceNotResolved",
294 times: 8,
295 schedule: Schedule.spaced("1 second"),
296 }),
297 );
298
299 export const waitUntilGone = <A, E extends { _tag: string }, R>(
300 get: Effect.Effect<A | undefined, E, R>,
301 name: string,
302 ) =>
303 get.pipe(
304 Effect.filterOrFail(
305 (value) => value === undefined,
306 () => new ResourceStillExists({ resourceName: name }),
307 ),
308 Effect.retry({
309 while: (error) => error._tag === "GCP.OracleDatabase.ResourceStillExists",
310 times: 10,
311 schedule: Schedule.spaced("5 seconds"),
312 }),
313 Effect.asVoid,
314 );
315
316 export const waitUntilReady = <A, E extends { _tag: string }, R>(
317 get: Effect.Effect<A | undefined, E, R>,
318 name: string,
319 stateOf: (value: A) => string | undefined,
320 detailsOf?: (value: A) => string | undefined,
321 ) =>
322 get.pipe(
323 Effect.filterOrFail(
324 (value): value is A => value !== undefined,
325 () => new ResourceNotResolved({ resourceName: name }),
326 ),
327 Effect.filterOrFail(
328 (value) => !isFailedState(stateOf(value)),
329 (value) =>
330 new ResourceFailed({
331 resourceName: name,
332 state: stateOf(value) ?? "",
333 details: detailsOf?.(value),
334 }),
335 ),
336 Effect.filterOrFail(
337 (value) => {
338 const state = stateOf(value) ?? "";
339 return isReadyState(state) || state.length === 0;
340 },
341 (value) =>
342 new ResourceNotReady({
343 resourceName: name,
344 state: stateOf(value) ?? "",
345 }),
346 ),
347 Effect.retry({
348 while: (error) =>
349 error._tag === "GCP.OracleDatabase.ResourceNotReady" ||
350 error._tag === "GCP.OracleDatabase.ResourceNotResolved",
351 times: 10,
352 schedule: Schedule.spaced("8 seconds"),
353 }),
354 );
355
356 export const listAtLocation = <A, E extends { _tag: string }, R>(
357 project: string,
358 region: string,
359 list: (parent: string) => Effect.Effect<A[], E, R>,
360 ) =>
361 list(`projects/${project}/locations/-`).pipe(
362 Effect.catchIf(
363 (error) => error._tag === "NotFound" || error._tag === "BadRequest",
364 () => list(`projects/${project}/locations/${region}`),
365 ),
366 );
367
368 export const collectPages = <Page, A, E, R>(
369 pages: Stream.Stream<Page, E, R>,
370 items: (page: Page) => readonly A[] | undefined,
371 ) =>
372 pages.pipe(
373 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
374 Stream.runCollect,
375 Effect.map((chunk) => Array.from(chunk)),
376 );