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

main
ts 158 lines 5.11 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_v1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Effect from "effect/Effect";
4 import * as Schedule from "effect/Schedule";
5 import { alchemyLabelKeys } from "../Labels.ts";
6 import {
7 waitGlobalOperation,
8 waitOrganizationOperation,
9 waitRegionOperation,
10 } from "./operations.ts";
11
12 export const MAX_NAME_LENGTH = 63;
13
14 export const lastSegment = (value: string | undefined): string => {
15 if (value === undefined || value.length === 0) return "";
16 const parts = value.split("/").filter((part) => part.length > 0);
17 return parts[parts.length - 1] ?? value;
18 };
19
20 export const normalizeRegion = (region: string | undefined, defaultRegion: string) =>
21 lastSegment(region ?? defaultRegion).toLowerCase();
22
23 export const rfc1035 = (name: string, fallback: string): string => {
24 let next = name
25 .toLowerCase()
26 .replace(/[^a-z0-9-]/g, "-")
27 .replace(/-+/g, "-")
28 .replace(/^-+/, "")
29 .replace(/-+$/, "");
30 if (!/^[a-z]/.test(next)) {
31 next = `${fallback[0] ?? "r"}${next}`;
32 }
33 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
34 return next.length > 0 ? next : fallback;
35 };
36
37 export const toPhysicalName = (
38 id: string,
39 name: string | undefined,
40 existing: string | undefined,
41 fallback: string,
42 ) =>
43 Effect.gen(function* () {
44 if (name !== undefined) return name;
45 if (existing !== undefined) return existing;
46 return rfc1035(
47 yield* createPhysicalName({
48 id,
49 maxLength: MAX_NAME_LENGTH,
50 lowercase: true,
51 }),
52 fallback,
53 );
54 });
55
56 export const encodeDescription = (
57 labels: Record<string, string>,
58 description: string | undefined,
59 ): string => {
60 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
61 return description ? `${marker}\n${description}` : marker;
62 };
63
64 export const parseDescription = (
65 description: string | undefined,
66 ): {
67 labels: Record<string, string>;
68 description: string | undefined;
69 } => {
70 if (!description?.startsWith("[alchemy ")) {
71 return { labels: {}, description };
72 }
73 const end = description.indexOf("]");
74 if (end < 0) return { labels: {}, description };
75 const labels: Record<string, string> = {};
76 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
77 const eq = part.indexOf("=");
78 if (eq > 0) {
79 labels[part.slice(0, eq)] = part.slice(eq + 1);
80 }
81 }
82 const rest = description.slice(end + 1).replace(/^\n/, "");
83 return { labels, description: rest.length > 0 ? rest : undefined };
84 };
85
86 export const hasOwnershipMarker = (description: string | undefined) =>
87 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
88
89 export const sameJson = (left: unknown, right: unknown) =>
90 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
91
92 export const sorted = (values: readonly string[] | undefined) => [...(values ?? [])].slice().sort();
93
94 export const sameUrlList = (
95 left: readonly string[] | undefined,
96 right: readonly string[] | undefined,
97 ) => sameJson(sorted((left ?? []).map(lastSegment)), sorted((right ?? []).map(lastSegment)));
98
99 export interface RunOperationOptions {
100 /** Treat `RESOURCE_ALREADY_EXISTS` as success (idempotent insert). */
101 ignoreAlreadyExists?: boolean;
102 /** Treat `RESOURCE_NOT_FOUND` as success (idempotent delete). */
103 ignoreNotFound?: boolean;
104 }
105
106 export const ignoredCodes = (options: RunOperationOptions | undefined) => [
107 ...(options?.ignoreAlreadyExists === true ? ["RESOURCE_ALREADY_EXISTS"] : []),
108 ...(options?.ignoreNotFound === true ? ["RESOURCE_NOT_FOUND"] : []),
109 ];
110
111 /**
112 * Start a Compute operation and wait for it. The insert/delete call itself
113 * is retried while another operation holds the resource (`Conflict`).
114 */
115 const runOp = <E extends { readonly _tag: string }, R, E2, R2>(
116 start: Effect.Effect<compute.Operation, E, R>,
117 wait: (operation: compute.Operation) => Effect.Effect<compute.Operation, E2, R2>,
118 ) =>
119 start.pipe(
120 Effect.retry({
121 while: (error) => error._tag === "Conflict",
122 times: 5,
123 schedule: Schedule.spaced("1 second"),
124 }),
125 Effect.flatMap(wait),
126 );
127
128 export const runRegionOp = <E extends { readonly _tag: string }, R>(
129 project: string,
130 region: string,
131 start: Effect.Effect<compute.Operation, E, R>,
132 options?: RunOperationOptions,
133 ) =>
134 runOp(start, (operation) =>
135 waitRegionOperation(project, region, operation, {
136 ignore: ignoredCodes(options),
137 }),
138 );
139
140 export const runGlobalOp = <E extends { readonly _tag: string }, R>(
141 project: string,
142 start: Effect.Effect<compute.Operation, E, R>,
143 options?: RunOperationOptions,
144 ) =>
145 runOp(start, (operation) =>
146 waitGlobalOperation(project, operation, { ignore: ignoredCodes(options) }),
147 );
148
149 export const runOrgOp = <E extends { readonly _tag: string }, R>(
150 parentId: string,
151 start: Effect.Effect<compute.Operation, E, R>,
152 options?: RunOperationOptions,
153 ) =>
154 runOp(start, (operation) =>
155 waitOrganizationOperation(operation, parentId, {
156 ignore: ignoredCodes(options),
157 }),
158 );