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

main
ts 168 lines 5.38 KB
Raw
1 import * as servicemanagement from "@distilled.cloud/gcp/servicemanagement_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 { waitForOperation as waitForLongRunning, type LongRunningOperation } from "../Operation.ts";
8
9 export const MAX_LABEL_LENGTH = 63;
10 export const GENERATED_LABEL_LENGTH = 40;
11
12 export class ServiceNotResolved extends Data.TaggedError(
13 "GCP.ServiceManagement.ServiceNotResolved",
14 )<{
15 serviceName: string;
16 }> {}
17
18 export class ServiceStillExists extends Data.TaggedError(
19 "GCP.ServiceManagement.ServiceStillExists",
20 )<{
21 serviceName: string;
22 }> {}
23
24 export const endpointsSuffix = (project: string) => `.endpoints.${project}.cloud.goog`;
25
26 export const isGeneratedServiceName = (serviceName: string, project: string) => {
27 const suffix = endpointsSuffix(project);
28 return (
29 serviceName.startsWith("alch-") &&
30 serviceName.endsWith(suffix) &&
31 serviceName.length > suffix.length
32 );
33 };
34
35 const dnsLabel = (value: string) => {
36 const cleaned = value
37 .toLowerCase()
38 .replace(/[^a-z0-9-]/g, "-")
39 .replace(/^-+/, "")
40 .replace(/-+$/g, "")
41 .slice(0, MAX_LABEL_LENGTH)
42 .replace(/-+$/g, "");
43 const named = /^[a-z]/.test(cleaned) ? cleaned : `a${cleaned}`;
44 return named.slice(0, MAX_LABEL_LENGTH).replace(/-+$/g, "");
45 };
46
47 export const toServiceName = (
48 id: string,
49 serviceName: string | undefined,
50 existing: string | undefined,
51 project: string,
52 ) =>
53 Effect.gen(function* () {
54 if (serviceName !== undefined && serviceName.length > 0) {
55 return serviceName;
56 }
57 if (existing !== undefined && existing.length > 0) {
58 return existing;
59 }
60 const generated = yield* createPhysicalName({
61 id,
62 maxLength: GENERATED_LABEL_LENGTH,
63 lowercase: true,
64 });
65 const label = dnsLabel(generated.startsWith("alch-") ? generated : `alch-${generated}`);
66 return `${label}${endpointsSuffix(project)}`;
67 });
68
69 /**
70 * Service Management answers a missing service with HTTP 403 "not found or
71 * permission denied", typed as `ServiceNotFound`.
72 */
73 export const getByName = (serviceName: string) =>
74 servicemanagement
75 .getServices({ serviceName })
76 .pipe(Effect.catchTag(["NotFound", "ServiceNotFound"], () => Effect.undefined));
77
78 /** The newest config version (the list is ordered newest first). */
79 export const getLatestConfig = (serviceName: string) =>
80 servicemanagement.listServicesConfigs({ serviceName, pageSize: 1 }).pipe(
81 Effect.map((page) => page.serviceConfigs?.[0]),
82 Effect.catchTag(["NotFound", "ServiceNotFound"], () => Effect.undefined),
83 );
84
85 export const waitUntilExists = (serviceName: string) =>
86 getByName(serviceName).pipe(
87 Effect.flatMap((service) =>
88 service !== undefined
89 ? Effect.succeed(service)
90 : Effect.fail(new ServiceNotResolved({ serviceName })),
91 ),
92 Effect.retry({
93 while: (error) => error._tag === "GCP.ServiceManagement.ServiceNotResolved",
94 times: 20,
95 schedule: Schedule.spaced("6 seconds"),
96 }),
97 );
98
99 export const waitUntilGone = (serviceName: string) =>
100 getByName(serviceName).pipe(
101 Effect.flatMap((service) =>
102 service === undefined ? Effect.void : Effect.fail(new ServiceStillExists({ serviceName })),
103 ),
104 Effect.retry({
105 while: (error) => error._tag === "GCP.ServiceManagement.ServiceStillExists",
106 times: 10,
107 schedule: Schedule.spaced("4 seconds"),
108 }),
109 );
110
111 export const undeleteService = (serviceName: string) =>
112 Effect.gen(function* () {
113 const operation = yield* servicemanagement
114 .undeleteServices({ serviceName })
115 .pipe(
116 Effect.catchTag(
117 ["NotFound", "ServiceNotFound", "ServiceAlreadyActive"],
118 () => Effect.undefined,
119 ),
120 );
121 if (operation !== undefined) {
122 yield* waitForOperation(operation);
123 }
124 return yield* getByName(serviceName);
125 });
126
127 export const listProducerServices = (project: string) =>
128 servicemanagement.listServices
129 .pages({
130 producerProjectId: project,
131 pageSize: 500,
132 })
133 .pipe(
134 Stream.flatMap((page) => Stream.fromIterable(page.services ?? [])),
135 Stream.runCollect,
136 Effect.map((chunk) => Array.from(chunk)),
137 Effect.catchTag("NotFound", () => Effect.succeed([] as servicemanagement.ManagedService[])),
138 );
139
140 /** Managed-service creates and deletes routinely run past three minutes. */
141 const OPERATION_BUDGET = "10 minutes";
142
143 /**
144 * Wait for a long-running operation. ALREADY_EXISTS (code 6) means a
145 * concurrent create won the race; reconcile observes the resource next.
146 */
147 export const waitForOperation = (operation: LongRunningOperation) =>
148 waitForLongRunning(operation, (name) => servicemanagement.getOperations({ name }), {
149 budget: OPERATION_BUDGET,
150 }).pipe(
151 Effect.catchIf(
152 (error) => error._tag === "GCP.OperationFailed" && error.code === 6,
153 () => Effect.succeed(operation),
154 ),
155 );
156
157 /**
158 * Wait for a delete operation. A vanished operation or NOT_FOUND (code 5)
159 * means the resource is already gone.
160 */
161 export const waitForDeleteOperation = (operation: LongRunningOperation) =>
162 waitForOperation(operation).pipe(
163 Effect.catchIf(
164 (error) =>
165 error._tag === "NotFound" || (error._tag === "GCP.OperationFailed" && error.code === 5),
166 () => Effect.succeed(operation),
167 ),
168 );