@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, 06:00 UTC

main
ts 322 lines 11 KB
Raw
1 import * as storagetransfer from "@distilled.cloud/gcp/storagetransfer_v1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Schedule from "effect/Schedule";
6 import * as Stream from "effect/Stream";
7 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
8
9 export const MAX_AGENT_POOL_ID = 128;
10 export const MAX_AGENT_POOL_DISPLAY_NAME = 127;
11 export const MAX_JOB_ID = 115;
12 export const MAX_JOB_DESCRIPTION = 1024;
13 export const JOB_NAME_PREFIX = "transferJobs/";
14 export const DEFAULT_JOB_STATUS = "ENABLED";
15 export const DEFAULT_AGENT_POOL = "transfer_service_default";
16
17 export class ResourceNotResolved extends Data.TaggedError(
18 "GCP.StorageTransfer.ResourceNotResolved",
19 )<{
20 resourceName: string;
21 }> {}
22
23 export class ResourceNotReady extends Data.TaggedError("GCP.StorageTransfer.ResourceNotReady")<{
24 resourceName: string;
25 state: string;
26 }> {}
27
28 export class ResourceStillExists extends Data.TaggedError(
29 "GCP.StorageTransfer.ResourceStillExists",
30 )<{
31 resourceName: string;
32 }> {}
33
34 export const lastSegment = (value: string) => {
35 const trimmed = value.replace(/\/+$/, "");
36 const parts = trimmed.split("/");
37 return parts[parts.length - 1] || trimmed;
38 };
39
40 export const agentPoolName = (project: string, agentPoolId: string) =>
41 `projects/${project}/agentPools/${agentPoolId}`;
42
43 export const transferJobName = (jobId: string) =>
44 jobId.startsWith(JOB_NAME_PREFIX) ? jobId : `${JOB_NAME_PREFIX}${jobId}`;
45
46 export const jobIdOf = (name: string) =>
47 name.startsWith(JOB_NAME_PREFIX) ? name.slice(JOB_NAME_PREFIX.length) : lastSegment(name);
48
49 export const agentPoolIdOf = (name: string) => lastSegment(name);
50
51 const startsWithLetter = (value: string) => /^[a-z]/.test(value);
52
53 const endsAlnum = (value: string) => /[a-z0-9]$/.test(value);
54
55 export const sanitizeAgentPoolId = (value: string) => {
56 let next = lastSegment(value)
57 .toLowerCase()
58 .replace(/[^a-z0-9-._~]/g, "-")
59 .replace(/^-+|-+$/g, "");
60 if (next.startsWith("goog")) next = `x${next}`;
61 if (!startsWithLetter(next)) next = `p${next}`;
62 next = next.slice(0, MAX_AGENT_POOL_ID);
63 if (next.length > 1 && !endsAlnum(next)) {
64 next = `${next.slice(0, MAX_AGENT_POOL_ID - 1)}0`;
65 }
66 return next.length > 0 ? next : "pool";
67 };
68
69 export const sanitizeJobId = (value: string) => {
70 let next = jobIdOf(value)
71 .replace(/[^A-Za-z0-9-._~]/g, "-")
72 .replace(/^-+|-+$/g, "");
73 if (next.toUpperCase().startsWith("OPI")) next = `x${next}`;
74 next = next.slice(0, MAX_JOB_ID);
75 if (next.length === 0) next = "job";
76 if (!endsAlnum(next.toLowerCase())) {
77 next = `${next.slice(0, MAX_JOB_ID - 1)}0`;
78 }
79 return next;
80 };
81
82 export const toAgentPoolId = (id: string, explicit: string | undefined, existing?: string) =>
83 Effect.gen(function* () {
84 if (explicit !== undefined) return sanitizeAgentPoolId(explicit);
85 if (existing !== undefined) return existing;
86 return sanitizeAgentPoolId(
87 yield* createPhysicalName({
88 id,
89 maxLength: 63,
90 lowercase: true,
91 forbiddenPrefixes: ["goog"],
92 }),
93 );
94 });
95
96 export const toJobId = (id: string, explicit: string | undefined, existing?: string) =>
97 Effect.gen(function* () {
98 if (explicit !== undefined) return sanitizeJobId(explicit);
99 if (existing !== undefined) return existing;
100 return sanitizeJobId(
101 yield* createPhysicalName({
102 id,
103 maxLength: 63,
104 lowercase: true,
105 forbiddenPrefixes: ["opi"],
106 }),
107 );
108 });
109
110 const markerOf = (stack: string, stage: string, id: string) =>
111 `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`;
112
113 const fitMarker = (labels: Record<string, string>, maxLength: number) => {
114 let stack = labels[alchemyLabelKeys.stack] ?? "x";
115 let stage = labels[alchemyLabelKeys.stage] ?? "x";
116 let id = labels[alchemyLabelKeys.id] ?? "x";
117 let marker = markerOf(stack, stage, id);
118 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
119 if (stack.length >= stage.length && stack.length >= id.length) {
120 stack = stack.slice(0, -1);
121 } else if (stage.length >= id.length) {
122 stage = stage.slice(0, -1);
123 } else {
124 id = id.slice(0, -1);
125 }
126 marker = markerOf(stack, stage, id);
127 }
128 return marker.slice(0, Math.max(0, maxLength));
129 };
130
131 export const encodeOwnership = (
132 labels: Record<string, string>,
133 text: string | undefined,
134 maxLength = MAX_JOB_DESCRIPTION,
135 ): string => {
136 const trimmed = text?.replace(/[\r\n]+/g, " ").trim();
137 if (!trimmed) return fitMarker(labels, maxLength);
138 const minMarker = 24;
139 const reserved = Math.min(trimmed.length + 1, Math.max(0, maxLength - minMarker));
140 const marker = fitMarker(labels, maxLength - reserved);
141 return `${marker} ${trimmed}`.slice(0, maxLength);
142 };
143
144 export const parseOwnership = (
145 text: string | undefined,
146 ): {
147 labels: Record<string, string>;
148 text: string | undefined;
149 } => {
150 if (!text?.startsWith("[alchemy ")) {
151 return { labels: {}, text };
152 }
153 const end = text.indexOf("]");
154 if (end < 0) return { labels: {}, text };
155 const labels: Record<string, string> = {};
156 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
157 const eq = part.indexOf("=");
158 if (eq > 0) {
159 labels[part.slice(0, eq)] = part.slice(eq + 1);
160 }
161 }
162 const rest = text.slice(end + 1).replace(/^[\s\n]+/, "");
163 return { labels, text: rest.length > 0 ? rest : undefined };
164 };
165
166 export const hasOwnershipMarker = (text: string | undefined) =>
167 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
168
169 const prefixMatch = (expected: string, observed: string) =>
170 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
171
172 export const ownedByAlchemy = (id: string, text: string | undefined) =>
173 Effect.gen(function* () {
174 const expected = yield* createInternalLabels(id);
175 const { labels } = parseOwnership(text);
176 if (!hasOwnershipMarker(text)) return false;
177 const exact = yield* hasAlchemyLabels(id, labels);
178 if (exact) return true;
179 return (
180 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
181 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
182 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
183 );
184 });
185
186 export const createOwnership = (id: string) => createInternalLabels(id);
187
188 export const canonical = (value: unknown): unknown => {
189 if (value === undefined || value === null) return undefined;
190 if (typeof value === "boolean" || typeof value === "number") return value;
191 if (typeof value === "string") {
192 return value.length === 0 ? undefined : value;
193 }
194 if (Array.isArray(value)) {
195 const items = value.map(canonical).filter((item) => item !== undefined);
196 return items.length === 0 ? undefined : items;
197 }
198 if (typeof value === "object") {
199 const entries = Object.entries(value as Record<string, unknown>)
200 .map(([key, item]) => [key, canonical(item)] as const)
201 .filter(([, item]) => item !== undefined)
202 .sort(([left], [right]) => left.localeCompare(right));
203 if (entries.length === 0) return undefined;
204 return Object.fromEntries(entries);
205 }
206 return undefined;
207 };
208
209 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
210
211 export const sameValue = (left: unknown, right: unknown) =>
212 fingerprint(left) === fingerprint(right);
213
214 export const fieldMask = (fields: Array<string | false | undefined>) =>
215 fields.filter((field): field is string => typeof field === "string").join(",");
216
217 export const retryApiDisabled = <A, E extends { readonly _tag: string }, R>(
218 effect: Effect.Effect<A, E, R>,
219 ) =>
220 effect.pipe(
221 Effect.retry({
222 // The API may still be propagating right after it is enabled.
223 while: (error) => error._tag === "ServiceDisabled",
224 times: 8,
225 schedule: Schedule.spaced("2 seconds"),
226 }),
227 );
228
229 export const collectPages = <Page, Item, E, R>(
230 pages: Stream.Stream<Page, E, R>,
231 items: (page: Page) => readonly Item[] | null | undefined,
232 ) =>
233 pages.pipe(
234 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
235 Stream.runCollect,
236 Effect.map((chunk) => Array.from(chunk)),
237 );
238
239 export const getAgentPool = (name: string) =>
240 name.length === 0
241 ? Effect.undefined
242 : storagetransfer.getProjectsAgentPools({ name }).pipe(
243 retryApiDisabled,
244 Effect.catchTag("NotFound", () => Effect.undefined),
245 );
246
247 export const getTransferJob = (jobName: string, projectId: string) =>
248 jobName.length === 0
249 ? Effect.undefined
250 : storagetransfer.getTransferJobs({ jobName, projectId }).pipe(
251 retryApiDisabled,
252 Effect.catchTag("NotFound", () => Effect.undefined),
253 );
254
255 export const isDeletedJob = (job: storagetransfer.TransferJob | undefined) =>
256 job?.status === "DELETED";
257
258 export const waitAgentPoolCreated = (name: string) =>
259 getAgentPool(name).pipe(
260 Effect.filterOrFail(
261 (pool): pool is storagetransfer.AgentPool => pool !== undefined,
262 () => new ResourceNotResolved({ resourceName: name }),
263 ),
264 Effect.filterOrFail(
265 (pool) => (pool.state ?? "") !== "DELETING",
266 () => new ResourceNotResolved({ resourceName: name }),
267 ),
268 Effect.filterOrFail(
269 (pool) => {
270 const state = pool.state ?? "CREATED";
271 return state === "CREATED" || state === "STATE_UNSPECIFIED";
272 },
273 (pool) =>
274 new ResourceNotReady({
275 resourceName: name,
276 state: pool.state ?? "UNKNOWN",
277 }),
278 ),
279 Effect.retry({
280 while: (error) => error._tag === "GCP.StorageTransfer.ResourceNotReady",
281 times: 10,
282 schedule: Schedule.spaced("1 second"),
283 }),
284 Effect.catchTag("GCP.StorageTransfer.ResourceNotResolved", () => Effect.undefined),
285 );
286
287 export const waitAgentPoolGone = (name: string) =>
288 getAgentPool(name).pipe(
289 Effect.flatMap((pool) =>
290 pool === undefined
291 ? Effect.void
292 : Effect.fail(new ResourceStillExists({ resourceName: name })),
293 ),
294 Effect.retry({
295 while: (error) => error._tag === "GCP.StorageTransfer.ResourceStillExists",
296 times: 10,
297 schedule: Schedule.spaced("1 second"),
298 }),
299 Effect.catchTag("GCP.StorageTransfer.ResourceStillExists", () => Effect.void),
300 );
301
302 export const listAgentPools = (projectId: string) =>
303 retryApiDisabled(
304 collectPages(
305 storagetransfer.listProjectsAgentPools.pages({
306 projectId,
307 pageSize: 256,
308 }),
309 (page) => page.agentPools,
310 ),
311 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as storagetransfer.AgentPool[])));
312
313 export const listTransferJobs = (projectId: string) =>
314 retryApiDisabled(
315 collectPages(
316 storagetransfer.listTransferJobs.pages({
317 filter: JSON.stringify({ projectId }),
318 pageSize: 256,
319 }),
320 (page) => page.transferJobs,
321 ),
322 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as storagetransfer.TransferJob[])));