@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 232 lines 7.49 KB
Raw
1 import { createPhysicalName } from "alchemy/PhysicalName";
2 import { tagRecord } from "alchemy/Tags";
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, stripInternalLabels } from "../Labels.ts";
8
9 export const DEFAULT_GLOBAL = "global";
10 export const DEFAULT_ZONE = "us-central1-a";
11 export const MAX_NAME_LENGTH = 63;
12
13 export class NetworksecurityNotResolved extends Data.TaggedError(
14 "GCP.NetworkSecurity.NotResolved",
15 )<{
16 resourceName: string;
17 }> {}
18
19 export class NetworksecurityStillExists extends Data.TaggedError(
20 "GCP.NetworkSecurity.StillExists",
21 )<{
22 resourceName: string;
23 }> {}
24
25 export class NetworksecurityFailed extends Data.TaggedError("GCP.NetworkSecurity.Failed")<{
26 resourceName: string;
27 state: string | undefined;
28 }> {}
29
30 export const lastSegment = (value: string) => {
31 const trimmed = value.replace(/\/+$/, "");
32 const parts = trimmed.split("/");
33 return parts[parts.length - 1] || trimmed;
34 };
35
36 export const rfc1035 = (name: string, fallback = "resource"): string => {
37 let next = name
38 .toLowerCase()
39 .replace(/[^a-z0-9-]/g, "-")
40 .replace(/-+/g, "-")
41 .replace(/^-+/, "")
42 .replace(/-+$/, "");
43 if (!/^[a-z]/.test(next)) {
44 next = `n${next}`;
45 }
46 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
47 return next.length > 0 ? next : fallback;
48 };
49
50 export const normalizeLocation = (location: string | undefined, fallback: string) =>
51 lastSegment(location ?? fallback).toLowerCase();
52
53 export const parentOf = (project: string, location: string) =>
54 `projects/${project}/locations/${location}`;
55
56 export const parseName = (name: string, collection: string, fallbackLocation: string) => {
57 const parts = name.split("/").filter((part) => part.length > 0);
58 const collectionAt = parts.lastIndexOf(collection);
59 const locationsAt = parts.lastIndexOf("locations");
60 const projectsAt = parts.lastIndexOf("projects");
61 return {
62 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
63 location:
64 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
65 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
66 };
67 };
68
69 export const toPhysicalId = (
70 id: string,
71 explicit: string | undefined,
72 existing: string | undefined,
73 fallback = "resource",
74 ) =>
75 Effect.gen(function* () {
76 if (explicit !== undefined) return rfc1035(explicit, fallback);
77 if (existing !== undefined) return existing;
78 return rfc1035(
79 yield* createPhysicalName({
80 id,
81 maxLength: MAX_NAME_LENGTH,
82 lowercase: true,
83 }),
84 fallback,
85 );
86 });
87
88 export const userLabels = (
89 labels: Record<string, string | undefined> | null | undefined,
90 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
91
92 export const hasAlchemyLabelKeys = (
93 labels: Record<string, string | undefined> | null | undefined,
94 ) => Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
95
96 export const encodeOwnership = (
97 labels: Record<string, string>,
98 text: string | undefined,
99 ): string => {
100 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
101 const trimmed = text?.trim();
102 return trimmed && trimmed.length > 0 ? `${marker}\n${trimmed}` : marker;
103 };
104
105 export const parseOwnership = (
106 text: string | undefined,
107 ): {
108 labels: Record<string, string>;
109 text: string | undefined;
110 } => {
111 if (!text?.startsWith("[alchemy ")) {
112 return { labels: {}, text };
113 }
114 const end = text.indexOf("]");
115 if (end < 0) return { labels: {}, text };
116 const labels: Record<string, string> = {};
117 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
118 const eq = part.indexOf("=");
119 if (eq > 0) {
120 labels[part.slice(0, eq)] = part.slice(eq + 1);
121 }
122 }
123 const rest = text.slice(end + 1).replace(/^\s+/, "");
124 return { labels, text: rest.length > 0 ? rest : undefined };
125 };
126
127 export const hasOwnershipMarker = (text: string | undefined) =>
128 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
129
130 export const sameJson = (left: unknown, right: unknown) =>
131 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
132
133 export const sameStringList = (
134 left: readonly string[] | undefined,
135 right: readonly string[] | undefined,
136 ) =>
137 JSON.stringify([...(left ?? [])].map(canonicalizeLink).sort()) ===
138 JSON.stringify([...(right ?? [])].map(canonicalizeLink).sort());
139
140 export const canonicalizeLink = (value: string | undefined) => {
141 if (value === undefined || value.length === 0) return "";
142 return value
143 .replace(/^https?:\/\/[^/]+\//, "")
144 .replace(/^compute\/v1\//, "")
145 .replace(/\/+$/, "");
146 };
147
148 export const linkKey = (value: string | undefined) =>
149 lastSegment(canonicalizeLink(value)).toLowerCase();
150
151 export const changedFields = (pairs: ReadonlyArray<readonly [string, boolean]>) =>
152 pairs.filter(([, changed]) => changed).map(([field]) => field);
153
154 export const waitUntilPresent = <A, E, R>(get: Effect.Effect<A | undefined, E, R>, name: string) =>
155 get.pipe(
156 Effect.flatMap((value) =>
157 value
158 ? Effect.succeed(value)
159 : Effect.fail(new NetworksecurityNotResolved({ resourceName: name })),
160 ),
161 Effect.retry({
162 while: (error) => error instanceof NetworksecurityNotResolved,
163 times: 8,
164 schedule: Schedule.spaced("1 second"),
165 }),
166 );
167
168 export const waitUntilGone = <A, E, R>(get: Effect.Effect<A | undefined, E, R>, name: string) =>
169 get.pipe(
170 Effect.flatMap((value) =>
171 value === undefined
172 ? Effect.void
173 : Effect.fail(new NetworksecurityStillExists({ resourceName: name })),
174 ),
175 Effect.retry({
176 while: (error) => error instanceof NetworksecurityStillExists,
177 times: 10,
178 schedule: Schedule.spaced("2 seconds"),
179 }),
180 );
181
182 const PENDING_STATES = new Set([
183 "STATE_UNSPECIFIED",
184 "CREATING",
185 "UPDATING",
186 "DELETING",
187 "ACCEPTING",
188 "REJECTING",
189 ]);
190
191 const FAILED_STATES = new Set(["FAILED", "DELETE_FAILED", "OBSOLETE"]);
192
193 export const waitUntilReady = <A extends { state?: string }, E, R>(
194 get: Effect.Effect<A | undefined, E, R>,
195 name: string,
196 ) =>
197 get.pipe(
198 Effect.filterOrFail(
199 (value): value is A => value !== undefined,
200 () => new NetworksecurityNotResolved({ resourceName: name }),
201 ),
202 Effect.filterOrFail(
203 (value) => !FAILED_STATES.has(value.state ?? ""),
204 (value) => new NetworksecurityFailed({ resourceName: name, state: value.state }),
205 ),
206 Effect.filterOrFail(
207 (value) => !PENDING_STATES.has(value.state ?? ""),
208 () => new NetworksecurityNotResolved({ resourceName: name }),
209 ),
210 Effect.retry({
211 while: (error) => error instanceof NetworksecurityNotResolved,
212 times: 10,
213 schedule: Schedule.spaced("4 seconds"),
214 }),
215 );
216
217 /** Collect every page; a missing parent (`NotFound`) lists as empty. */
218 export const collectPages = <Page, Item, E extends { readonly _tag: string }, R>(
219 stream: Stream.Stream<Page, E, R>,
220 pick: (page: Page) => readonly Item[] | undefined,
221 ) =>
222 stream.pipe(
223 Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])),
224 Stream.runCollect,
225 Effect.map((chunk): Item[] => Array.from(chunk)),
226 Effect.catchIf(
227 (error) => error._tag === "NotFound",
228 () => Effect.succeed<Item[]>([]),
229 ),
230 );
231
232 export { waitForOperation } from "./operations.ts";