@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 418 lines 14.4 KB
Raw
1 import * as pubsublite from "@distilled.cloud/gcp/pubsublite_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 { GcpEnvironment } from "../Environment.ts";
8 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
9
10 // Zonal default is left fixed: zones are not derivable from `GcpEnvironment.region` without assuming a suffix.
11 export const DEFAULT_ZONE = "us-central1-a";
12 export const MAX_ID_LENGTH = 255;
13 export const DEFAULT_THROUGHPUT_CAPACITY = "4";
14 export const DEFAULT_PARTITION_COUNT = "1";
15 export const DEFAULT_PUBLISH_MIB = 4;
16 export const DEFAULT_SUBSCRIBE_MIB = 4;
17 /** 30 GiB — Pub/Sub Lite minimum storage per partition. */
18 export const DEFAULT_PER_PARTITION_BYTES = "32212254720";
19
20 export const LIST_LOCATIONS = [
21 "us-central1",
22 "us-central1-a",
23 "us-central1-b",
24 "us-central1-c",
25 "us-central1-f",
26 ] as const;
27
28 const OWNERSHIP_MARKER = "+alc.";
29
30 export class ResourceNotResolved extends Data.TaggedError("GCP.PubSubLite.NotResolved")<{
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 normalizeLocation = (location: string | undefined, fallback: string) =>
41 lastSegment(location ?? fallback).toLowerCase();
42
43 export const regionOf = (location: string) => {
44 const parts = location.split("-").filter((part) => part.length > 0);
45 const tail = parts[parts.length - 1] ?? "";
46 if (/^[a-z]$/.test(tail) && parts.length > 1) {
47 return parts.slice(0, -1).join("-");
48 }
49 return location;
50 };
51
52 export const parentOf = (project: string, location: string) =>
53 `projects/${project}/locations/${location}`;
54
55 export const resourceName = (project: string, location: string, collection: string, id: string) =>
56 `${parentOf(project, location)}/${collection}/${id}`;
57
58 export const parseName = (name: string, collection: string) => {
59 const parts = name.split("/").filter((part) => part.length > 0);
60 const collectionAt = parts.lastIndexOf(collection);
61 const locationsAt = parts.lastIndexOf("locations");
62 const projectsAt = parts.lastIndexOf("projects");
63 return {
64 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
65 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
66 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
67 parent:
68 collectionAt > 0
69 ? parts.slice(0, collectionAt).join("/")
70 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
71 };
72 };
73
74 export const expandName = (
75 value: string,
76 project: string,
77 location: string,
78 collection: string,
79 ) => {
80 const trimmed = value.replace(/\/+$/, "");
81 if (trimmed.includes(`/${collection}/`)) return trimmed;
82 if (trimmed.startsWith("projects/")) return trimmed;
83 return resourceName(project, location, collection, lastSegment(trimmed));
84 };
85
86 export const sameText = (left: string | undefined, right: string | undefined) =>
87 (left ?? "") === (right ?? "");
88
89 export const sameRef = (left: string | undefined, right: string | undefined) =>
90 lastSegment(left ?? "") === lastSegment(right ?? "");
91
92 export const jsonEqual = (left: unknown, right: unknown) =>
93 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
94
95 export const fieldMask = (fields: Array<string | false | undefined>) =>
96 fields.filter((field): field is string => typeof field === "string").join(",");
97
98 const sanitizeId = (value: string, maxLength: number) => {
99 let next = value.replace(/[^a-zA-Z0-9._~+%:-]/g, "-").replace(/-+/g, "-");
100 next = next.replace(/^[^a-zA-Z]+/, "");
101 if (next.length === 0) next = "topic";
102 if (!/^[a-zA-Z]/.test(next)) next = `p${next}`;
103 return next.slice(0, maxLength).replace(/[^a-zA-Z0-9._~+%:-]+$/g, "");
104 };
105
106 export const stripOwnershipId = (id: string) => {
107 const index = id.lastIndexOf(OWNERSHIP_MARKER);
108 return index >= 0 ? id.slice(0, index) : id;
109 };
110
111 export const parseOwnershipId = (id: string | undefined): Record<string, string> => {
112 if (!id) return {};
113 const index = id.lastIndexOf(OWNERSHIP_MARKER);
114 if (index < 0) return {};
115 const [stack, stage, ...idParts] = id.slice(index + OWNERSHIP_MARKER.length).split(".");
116 const labels: Record<string, string> = {};
117 if (stack) labels[alchemyLabelKeys.stack] = stack;
118 if (stage) labels[alchemyLabelKeys.stage] = stage;
119 if (idParts.length > 0) {
120 labels[alchemyLabelKeys.id] = idParts.join(".");
121 }
122 return labels;
123 };
124
125 export const hasOwnershipMarker = (id: string | undefined) =>
126 Object.keys(parseOwnershipId(id)).some((key) => key.startsWith("alchemy-"));
127
128 const fitMarker = (labels: Record<string, string>, maxLength: number) => {
129 let stack = labels[alchemyLabelKeys.stack] ?? "x";
130 let stage = labels[alchemyLabelKeys.stage] ?? "x";
131 let id = labels[alchemyLabelKeys.id] ?? "x";
132 let marker = `${OWNERSHIP_MARKER}${stack}.${stage}.${id}`;
133 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
134 if (id.length >= stack.length && id.length >= stage.length) {
135 id = id.slice(0, -1);
136 } else if (stack.length >= stage.length) {
137 stack = stack.slice(0, -1);
138 } else {
139 stage = stage.slice(0, -1);
140 }
141 marker = `${OWNERSHIP_MARKER}${stack}.${stage}.${id}`;
142 }
143 return marker.slice(0, maxLength);
144 };
145
146 export const encodeResourceId = (
147 labels: Record<string, string>,
148 base: string,
149 maxLength = MAX_ID_LENGTH,
150 ) => {
151 const stripped = sanitizeId(stripOwnershipId(base), maxLength);
152 const minMarker = `${OWNERSHIP_MARKER}x.x.x`.length;
153 const marker = fitMarker(labels, Math.max(minMarker, Math.min(120, maxLength - 8)));
154 const room = Math.max(1, maxLength - marker.length);
155 return sanitizeId(`${stripped.slice(0, room)}${marker}`, maxLength);
156 };
157
158 const prefixMatch = (expected: string, observed: string) =>
159 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
160
161 export const ownedByAlchemy = (logicalId: string, resourceId: string) =>
162 Effect.gen(function* () {
163 if (!hasOwnershipMarker(resourceId)) return false;
164 const expected = yield* createInternalLabels(logicalId);
165 const labels = parseOwnershipId(resourceId);
166 const exact = yield* hasAlchemyLabels(logicalId, labels);
167 if (exact) return true;
168 return (
169 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
170 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
171 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
172 );
173 });
174
175 export const toResourceId = (
176 logicalId: string,
177 requested: string | undefined,
178 existing: string | undefined,
179 ) =>
180 Effect.gen(function* () {
181 const labels = yield* createInternalLabels(logicalId);
182 if (requested !== undefined && requested.length > 0) {
183 return encodeResourceId(labels, lastSegment(requested));
184 }
185 if (existing !== undefined && existing.length > 0) {
186 return existing;
187 }
188 const generated = yield* createPhysicalName({
189 id: logicalId,
190 maxLength: 120,
191 lowercase: true,
192 forbiddenPrefixes: ["goog"],
193 });
194 return encodeResourceId(labels, generated);
195 });
196
197 export const replaceOnIdentity = (input: {
198 previousId?: string;
199 nextId?: string;
200 previousLocation?: string;
201 nextLocation?: string;
202 extra?: boolean;
203 }) => {
204 const previousId =
205 input.previousId !== undefined ? stripOwnershipId(lastSegment(input.previousId)) : undefined;
206 const nextId =
207 input.nextId !== undefined ? stripOwnershipId(lastSegment(input.nextId)) : undefined;
208 const idChanged = previousId !== undefined && nextId !== undefined && previousId !== nextId;
209 const locationChanged =
210 input.previousLocation !== undefined &&
211 input.nextLocation !== undefined &&
212 input.previousLocation !== input.nextLocation;
213 if (!idChanged && !locationChanged && input.extra !== true) {
214 return undefined;
215 }
216 const samePhysical = !idChanged && !locationChanged;
217 return {
218 action: "replace" as const,
219 deleteFirst: samePhysical,
220 };
221 };
222
223 export const countOf = (value: number | string | undefined) => {
224 if (value === undefined || value === "") return Number(DEFAULT_PARTITION_COUNT);
225 const parsed = Number(value);
226 return Number.isFinite(parsed) ? parsed : Number(DEFAULT_PARTITION_COUNT);
227 };
228
229 export const partitionBody = (input: {
230 count?: number | string;
231 capacity?: {
232 publishMibPerSec?: number;
233 subscribeMibPerSec?: number;
234 };
235 }): pubsublite.PartitionConfig => ({
236 count: String(countOf(input.count)),
237 capacity: {
238 publishMibPerSec: input.capacity?.publishMibPerSec ?? DEFAULT_PUBLISH_MIB,
239 subscribeMibPerSec: input.capacity?.subscribeMibPerSec ?? DEFAULT_SUBSCRIBE_MIB,
240 },
241 });
242
243 export const retentionBody = (input: {
244 perPartitionBytes?: string;
245 period?: string;
246 }): pubsublite.RetentionConfig => {
247 const body: pubsublite.RetentionConfig = {
248 perPartitionBytes: input.perPartitionBytes ?? DEFAULT_PER_PARTITION_BYTES,
249 };
250 if (input.period !== undefined) body.period = input.period;
251 return body;
252 };
253
254 export const partitionKey = (config: pubsublite.PartitionConfig | undefined) =>
255 JSON.stringify({
256 count: String(countOf(config?.count)),
257 publish: config?.capacity?.publishMibPerSec ?? DEFAULT_PUBLISH_MIB,
258 subscribe: config?.capacity?.subscribeMibPerSec ?? DEFAULT_SUBSCRIBE_MIB,
259 });
260
261 export const retentionKey = (config: pubsublite.RetentionConfig | undefined) =>
262 JSON.stringify({
263 perPartitionBytes: config?.perPartitionBytes ?? DEFAULT_PER_PARTITION_BYTES,
264 period: config?.period ?? "",
265 });
266
267 export const catchMissing = <A, E extends { readonly _tag: string }, R>(
268 effect: Effect.Effect<A, E, R>,
269 ) =>
270 effect.pipe(
271 Effect.catchIf(
272 (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound",
273 () => Effect.undefined,
274 ),
275 );
276
277 export const ignoreMissing = <E extends { readonly _tag: string }, R>(
278 effect: Effect.Effect<unknown, E, R>,
279 ) =>
280 effect.pipe(
281 Effect.catchIf(
282 (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound",
283 () => Effect.void,
284 ),
285 );
286
287 /**
288 * Retry while a delete is blocked by a dependent (a reservation still
289 * referenced by a topic, a topic with attached subscriptions): `409`.
290 */
291 export const retryInUse = <A, E extends { readonly _tag: string }, R>(
292 effect: Effect.Effect<A, E, R>,
293 ) =>
294 effect.pipe(
295 Effect.retry({
296 while: (error) => error._tag === "Conflict",
297 times: 8,
298 schedule: Schedule.exponential("300 millis"),
299 }),
300 );
301
302 export class DeleteNotConfirmed extends Data.TaggedError("GCP.PubSubLite.DeleteNotConfirmed")<{}> {}
303
304 /** Poll until the resource is gone; fails if it is still readable after ~60s. */
305 export const waitUntilGone = <A, E, R>(get: Effect.Effect<A | undefined, E, R>) =>
306 get.pipe(
307 Effect.repeat({
308 schedule: Schedule.spaced("2 seconds"),
309 until: (value) => value === undefined,
310 times: 30,
311 }),
312 Effect.flatMap((value): Effect.Effect<void, DeleteNotConfirmed> =>
313 value === undefined ? Effect.void : Effect.fail(new DeleteNotConfirmed()),
314 ),
315 );
316
317 const emptyList = <A>() => Effect.succeed([] as A[]);
318
319 const collectPages = <Page, Item, E extends { readonly _tag: string }, R>(
320 pages: Stream.Stream<Page, E, R>,
321 items: (page: Page) => readonly Item[] | null | undefined,
322 ) =>
323 pages.pipe(
324 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
325 Stream.runCollect,
326 Effect.map((chunk) => Array.from(chunk) as Item[]),
327 Effect.catchIf(
328 (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound",
329 () => emptyList<Item>(),
330 ),
331 );
332
333 const listParents = (project: string, region: string) =>
334 [...new Set<string>([region, ...LIST_LOCATIONS])].map((location) => parentOf(project, location));
335
336 const listAcross = <Item, E, R>(listAt: (parent: string) => Effect.Effect<readonly Item[], E, R>) =>
337 Effect.gen(function* () {
338 const env = yield* GcpEnvironment.current;
339 const pages = yield* Effect.forEach(
340 listParents(env.project, env.region),
341 (parent) => listAt(parent),
342 { concurrency: 4 },
343 );
344 const seen = new Set<string>();
345 const found: Item[] = [];
346 for (const page of pages) {
347 for (const item of page) {
348 const key =
349 typeof item === "object" &&
350 item !== null &&
351 "name" in item &&
352 typeof (item as { name?: unknown }).name === "string"
353 ? ((item as { name: string }).name ?? "")
354 : JSON.stringify(item);
355 if (seen.has(key)) continue;
356 seen.add(key);
357 found.push(item as Item);
358 }
359 }
360 return found;
361 });
362
363 export const getReservation = (name: string) =>
364 name.length === 0
365 ? Effect.undefined
366 : catchMissing(pubsublite.getAdminProjectsLocationsReservations({ name }));
367
368 export const getTopic = (name: string) =>
369 name.length === 0
370 ? Effect.undefined
371 : catchMissing(pubsublite.getAdminProjectsLocationsTopics({ name }));
372
373 export const getSubscription = (name: string) =>
374 name.length === 0
375 ? Effect.undefined
376 : catchMissing(pubsublite.getAdminProjectsLocationsSubscriptions({ name }));
377
378 export const listReservationsAt = (parent: string) =>
379 collectPages(
380 pubsublite.listAdminProjectsLocationsReservations.pages({
381 parent,
382 pageSize: 1000,
383 }),
384 (page) => page.reservations,
385 );
386
387 export const listTopicsAt = (parent: string) =>
388 collectPages(
389 pubsublite.listAdminProjectsLocationsTopics.pages({
390 parent,
391 pageSize: 1000,
392 }),
393 (page) => page.topics,
394 );
395
396 export const listSubscriptionsAt = (parent: string) =>
397 collectPages(
398 pubsublite.listAdminProjectsLocationsSubscriptions.pages({
399 parent,
400 pageSize: 1000,
401 }),
402 (page) => page.subscriptions,
403 );
404
405 export const listOwnedReservations = () =>
406 listAcross(listReservationsAt).pipe(
407 Effect.map((items) => items.filter((item) => hasOwnershipMarker(lastSegment(item.name ?? "")))),
408 );
409
410 export const listOwnedTopics = () =>
411 listAcross(listTopicsAt).pipe(
412 Effect.map((items) => items.filter((item) => hasOwnershipMarker(lastSegment(item.name ?? "")))),
413 );
414
415 export const listOwnedSubscriptions = () =>
416 listAcross(listSubscriptionsAt).pipe(
417 Effect.map((items) => items.filter((item) => hasOwnershipMarker(lastSegment(item.name ?? "")))),
418 );