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

main
ts 258 lines 8.2 KB
Raw
1 import * as servicemanagement from "@distilled.cloud/gcp/servicemanagement_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 getByName,
12 getLatestConfig,
13 isGeneratedServiceName,
14 listProducerServices,
15 ServiceNotResolved,
16 toServiceName,
17 undeleteService,
18 waitForDeleteOperation,
19 waitForOperation,
20 waitUntilExists,
21 waitUntilGone,
22 } from "./internal.ts";
23
24 export { ServiceNotResolved };
25
26 export type ServiceProps = {
27 /**
28 * DNS service name (for example
29 * `hello.endpoints.my-project.cloud.goog`). If omitted, Alchemy
30 * generates `{alch-…}.endpoints.{project}.cloud.goog` from the stack,
31 * stage, and logical id. Immutable — changing it replaces the service.
32 * After delete the name is reserved for 30 days; reconcile undeletes
33 * instead of recreating.
34 */
35 serviceName?: string;
36 /**
37 * Display title stored on the service config. Changing it writes a new
38 * config version.
39 */
40 title?: string;
41 /**
42 * Producer project id. Defaults to the current stack project.
43 * Immutable — changing it replaces the service.
44 */
45 producerProjectId?: string;
46 };
47
48 export type Service = Resource<
49 "GCP.ServiceManagement.Service",
50 ServiceProps,
51 {
52 /** DNS service name. */
53 serviceName: string;
54 /** Producer project id. */
55 producerProjectId: string;
56 /** Project id used when the service was reconciled. */
57 project: string;
58 /** Title of the newest service config. */
59 title: string | undefined;
60 },
61 never,
62 Providers
63 >;
64
65 /**
66 * A Google Service Management managed service (Cloud Endpoints producer
67 * service).
68 *
69 * A managed service is identity-only and immutable. Create and delete
70 * return long-running operations. After delete the name stays reserved
71 * for 30 days — reconcile undeletes rather than recreating. There is no
72 * labels field: `list` / `pnpm nuke:gcp` find services by their generated
73 * `alch-` name, and `read` reports an explicitly named service it has no
74 * state for as unowned. Changing `serviceName` or `producerProjectId`
75 * replaces the service. `title` updates in place by writing a new config
76 * version.
77 *
78 * ### Creating a Service
79 * **Example:** Generated Endpoints name
80 * ```typescript
81 * const api = yield* GCP.ServiceManagement.Service("Hello", {
82 * title: "Hello API",
83 * });
84 * ```
85 *
86 * **Example:** Explicit DNS name
87 * ```typescript
88 * const api = yield* GCP.ServiceManagement.Service("Hello", {
89 * serviceName: "hello.endpoints.my-project.cloud.goog",
90 * title: "Hello API",
91 * });
92 * ```
93 *
94 * ### Updating a Service
95 * **Example:** Change the display title
96 * ```typescript
97 * const api = yield* GCP.ServiceManagement.Service("Hello", {
98 * title: "Hello API v2",
99 * });
100 * ```
101 *
102 * @resource
103 * @category ServiceManagement
104 */
105 export const Service = Resource<Service>("GCP.ServiceManagement.Service");
106
107 const toAttrs = (
108 service: servicemanagement.ManagedService,
109 project: string,
110 title: string | undefined,
111 ) => {
112 const serviceName = service.serviceName ?? "";
113 return {
114 serviceName,
115 producerProjectId: service.producerProjectId ?? project,
116 project,
117 title,
118 };
119 };
120
121 const toAttrsLive = (service: servicemanagement.ManagedService, project: string) =>
122 Effect.gen(function* () {
123 const serviceName = service.serviceName ?? "";
124 const config = serviceName.length > 0 ? yield* getLatestConfig(serviceName) : undefined;
125 return toAttrs(service, project, config?.title);
126 });
127
128 const desiredProducer = (news: ServiceProps, project: string, existing?: string) =>
129 news.producerProjectId ?? existing ?? project;
130
131 export const ServiceProvider = () =>
132 Provider.succeed(Service, {
133 stables: ["serviceName", "producerProjectId", "project"],
134
135 diff: Effect.fn(function* ({ news, olds, output }) {
136 if (!isResolved(news)) return undefined;
137 const previousName = olds?.serviceName ?? output?.serviceName;
138 if (
139 previousName !== undefined &&
140 news.serviceName !== undefined &&
141 news.serviceName !== previousName
142 ) {
143 return { action: "replace" as const, deleteFirst: false };
144 }
145 const previousProducer = olds?.producerProjectId ?? output?.producerProjectId;
146 if (
147 previousProducer !== undefined &&
148 news.producerProjectId !== undefined &&
149 news.producerProjectId !== previousProducer
150 ) {
151 return { action: "replace" as const, deleteFirst: false };
152 }
153 return undefined;
154 }),
155
156 read: Effect.fn(function* ({ id, olds, output }) {
157 const env = yield* GcpEnvironment.current;
158 const serviceName = yield* toServiceName(
159 id,
160 olds?.serviceName,
161 output?.serviceName,
162 env.project,
163 );
164 const existing = yield* getByName(serviceName);
165 if (existing === undefined) return undefined;
166 const attrs = yield* toAttrsLive(existing, env.project);
167 // Managed services have no labels. A generated `alch-` name derives
168 // from this stack, stage and logical id; any other name is only ours
169 // when state already records it.
170 return output !== undefined || isGeneratedServiceName(serviceName, env.project)
171 ? attrs
172 : Unowned(attrs);
173 }),
174
175 list: () =>
176 Effect.gen(function* () {
177 const env = yield* GcpEnvironment.current;
178 const services = yield* listProducerServices(env.project);
179 return yield* Effect.forEach(
180 services.filter((service) =>
181 isGeneratedServiceName(service.serviceName ?? "", env.project),
182 ),
183 (service) => toAttrsLive(service, env.project),
184 { concurrency: 4 },
185 );
186 }),
187
188 reconcile: Effect.fn(function* ({ id, news, output }) {
189 const env = yield* GcpEnvironment.current;
190 const serviceName = yield* toServiceName(
191 id,
192 news.serviceName,
193 output?.serviceName,
194 env.project,
195 );
196 const producerProjectId = desiredProducer(news, env.project, output?.producerProjectId);
197
198 let current = yield* getByName(serviceName);
199
200 if (current === undefined) {
201 // A name deleted in the last 30 days is soft-deleted: undelete it.
202 const created = yield* servicemanagement
203 .createServices({
204 body: {
205 serviceName,
206 producerProjectId,
207 },
208 })
209 .pipe(Effect.catchTag(["Conflict", "ServiceSoftDeleted"], () => Effect.undefined));
210 if (created !== undefined) {
211 yield* waitForOperation(created);
212 current = yield* waitUntilExists(serviceName);
213 } else {
214 current = (yield* undeleteService(serviceName)) ?? (yield* waitUntilExists(serviceName));
215 }
216 }
217
218 const config = yield* getLatestConfig(serviceName);
219 if (news.title !== undefined && (config?.title ?? "") !== news.title) {
220 // A new service is briefly invisible to the config API.
221 yield* servicemanagement
222 .createServicesConfigs({
223 serviceName,
224 body: {
225 name: serviceName,
226 title: news.title,
227 producerProjectId,
228 },
229 })
230 .pipe(
231 Effect.retry({
232 while: (error) => error._tag === "NotFound" || error._tag === "ServiceNotFound",
233 times: 8,
234 schedule: Schedule.spaced("2 seconds"),
235 }),
236 );
237 }
238
239 return yield* toAttrsLive(current, env.project);
240 }),
241
242 delete: Effect.fn(function* ({ output }) {
243 const operation = yield* servicemanagement
244 .deleteServices({ serviceName: output.serviceName })
245 .pipe(
246 Effect.retry({
247 while: (error) => error._tag === "Conflict",
248 times: 8,
249 schedule: Schedule.spaced("1 second"),
250 }),
251 Effect.catchTag(["NotFound", "ServiceNotFound"], () => Effect.undefined),
252 );
253 if (operation !== undefined) {
254 yield* waitForDeleteOperation(operation);
255 }
256 yield* waitUntilGone(output.serviceName);
257 }),
258 });