@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, 04:45 UTC

main
ts 487 lines 15.7 KB
Raw
1 import * as appengine from "@distilled.cloud/gcp/appengine_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 Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 catchMissing,
12 DEFAULT_SERVICE,
13 envVariablesOf,
14 hasOwnershipMarker,
15 jsonEqual,
16 listServices,
17 listVersions,
18 MAX_VERSION_ID_LENGTH,
19 ownedByAlchemy,
20 ownershipLabels,
21 parseVersionName,
22 resolveAppsId,
23 sameText,
24 stampEnvVariables,
25 toResourceId,
26 updateMaskOf,
27 versionOwnershipText,
28 } from "./internal.ts";
29 import { waitForOperation } from "./operations.ts";
30
31 export type AppsServicesVersionProps = {
32 /**
33 * App Engine application id. Defaults to the current GCP project.
34 * Immutable — changing it replaces the version.
35 */
36 appsId?: string;
37 /**
38 * Service id that owns this version.
39 * @default "default"
40 */
41 serviceId?: string;
42 /**
43 * Version id (lowercase letters, numbers, hyphens). Reserved names
44 * `default`, `latest`, and `ah-*` are rejected. If omitted, a unique
45 * id is generated. Immutable — changing it replaces the version.
46 */
47 versionId?: string;
48 /**
49 * Runtime (for example `python311`, `nodejs20`). Immutable — changing
50 * it replaces the version.
51 */
52 runtime?: string;
53 /**
54 * Execution environment (`standard` or `flexible`).
55 * @default "standard"
56 */
57 env?: string;
58 /**
59 * Serving status. Defaults to `SERVING`.
60 */
61 servingStatus?: appengine.VersionServingStatusEnum | (string & {});
62 /**
63 * Instance class (`F1`, `F2`, `B1`, …).
64 */
65 instanceClass?: string;
66 /**
67 * Application environment variables. App Engine versions have no
68 * labels field, so Alchemy stamps ownership into `ALCHEMY_OWNERSHIP`
69 * and strips it from attributes.
70 */
71 envVariables?: Record<string, string | undefined>;
72 /**
73 * Code and artifacts that make up this version. Immutable — changing
74 * it replaces the version.
75 */
76 deployment?: appengine.Deployment;
77 /**
78 * Application entrypoint.
79 */
80 entrypoint?: appengine.Entrypoint;
81 /**
82 * Automatic scaling configuration.
83 */
84 automaticScaling?: appengine.AutomaticScaling;
85 /**
86 * Basic scaling configuration.
87 */
88 basicScaling?: appengine.BasicScaling;
89 /**
90 * Manual scaling configuration.
91 */
92 manualScaling?: appengine.ManualScaling;
93 /**
94 * URL handlers.
95 */
96 handlers?: appengine.UrlMapList;
97 /**
98 * Whether the runtime is threadsafe.
99 */
100 threadsafe?: boolean;
101 /**
102 * Service account the version runs as.
103 */
104 serviceAccount?: string;
105 /**
106 * Inbound services the version receives.
107 */
108 inboundServices?: appengine.VersionInboundServicesItemEnumList;
109 /**
110 * VPC Access connector.
111 */
112 vpcAccessConnector?: appengine.VpcAccessConnector;
113 /**
114 * Allow second-generation runtimes to use bundled services.
115 */
116 appEngineApis?: boolean;
117 /**
118 * Runtime API version.
119 */
120 runtimeApiVersion?: string;
121 };
122
123 export type AppsServicesVersion = Resource<
124 "GCP.AppEngine.AppsServicesVersion",
125 AppsServicesVersionProps,
126 {
127 /** Full resource name `apps/{appsId}/services/{service}/versions/{id}`. */
128 name: string;
129 /** Version id. */
130 versionId: string;
131 /** Service id. */
132 serviceId: string;
133 /** App Engine application id. */
134 appsId: string;
135 /** Project id. */
136 project: string;
137 /** Runtime. */
138 runtime: string | undefined;
139 /** Execution environment. */
140 env: string | undefined;
141 /** Serving status. */
142 servingStatus: string | undefined;
143 /** Instance class. */
144 instanceClass: string | undefined;
145 /** User environment variables (ownership stamp stripped). */
146 envVariables: Record<string, string>;
147 /** Serving URL for this version. */
148 versionUrl: string | undefined;
149 /** RFC3339 creation timestamp. */
150 createTime: string | undefined;
151 /** Creator email. */
152 createdBy: string | undefined;
153 /** Disk usage in bytes. */
154 diskUsageBytes: string | undefined;
155 /** Automatic scaling, if configured. */
156 automaticScaling: appengine.AutomaticScaling | undefined;
157 /** Basic scaling, if configured. */
158 basicScaling: appengine.BasicScaling | undefined;
159 /** Manual scaling, if configured. */
160 manualScaling: appengine.ManualScaling | undefined;
161 },
162 never,
163 Providers
164 >;
165
166 /**
167 * An App Engine service version.
168 *
169 * App Engine versions have no labels field, so Alchemy stamps ownership
170 * into the `ALCHEMY_OWNERSHIP` environment variable for `list` / nuke.
171 * Application, service, version id, runtime, environment, and
172 * deployment are identity — changing any of them replaces the version.
173 * Serving status, instance class, and scaling update in place.
174 *
175 * ### Creating a Version
176 * **Example:** Python 3 standard environment
177 * ```typescript
178 * const version = yield* GCP.AppEngine.AppsServicesVersion("Api", {
179 * runtime: "python311",
180 * deployment: {
181 * zip: { sourceUrl: "https://storage.googleapis.com/bucket/app.zip" },
182 * },
183 * });
184 * ```
185 *
186 * **Example:** Named version with automatic scaling
187 * ```typescript
188 * const version = yield* GCP.AppEngine.AppsServicesVersion("Api", {
189 * versionId: "v1",
190 * serviceId: "default",
191 * runtime: "nodejs20",
192 * automaticScaling: {
193 * standardSchedulerSettings: { minInstances: 0, maxInstances: 1 },
194 * },
195 * deployment: {
196 * zip: { sourceUrl: "https://storage.googleapis.com/bucket/app.zip" },
197 * },
198 * });
199 * ```
200 *
201 * ### Updating a Version
202 * **Example:** Stop serving
203 * ```typescript
204 * const version = yield* GCP.AppEngine.AppsServicesVersion("Api", {
205 * servingStatus: "STOPPED",
206 * deployment: {
207 * zip: { sourceUrl: "https://storage.googleapis.com/bucket/app.zip" },
208 * },
209 * });
210 * ```
211 *
212 * @resource
213 * @category AppEngine
214 */
215 export const AppsServicesVersion = Resource<AppsServicesVersion>(
216 "GCP.AppEngine.AppsServicesVersion",
217 );
218
219 export class AppsServicesVersionNotResolved extends Data.TaggedError(
220 "GCP.AppEngine.AppsServicesVersionNotResolved",
221 )<{
222 resourceName: string;
223 }> {}
224
225 const toAttrs = (
226 version: appengine.Version,
227 appsId: string,
228 serviceId: string,
229 project: string,
230 ) => {
231 const parsed = parseVersionName(version.name ?? "");
232 const versionId = version.id ?? parsed.versionsId ?? "";
233 return {
234 name: version.name ?? `apps/${appsId}/services/${serviceId}/versions/${versionId}`,
235 versionId,
236 serviceId: parsed.servicesId ?? serviceId,
237 appsId: parsed.appsId ?? appsId,
238 project,
239 runtime: version.runtime,
240 env: version.env,
241 servingStatus: version.servingStatus,
242 instanceClass: version.instanceClass,
243 envVariables: envVariablesOf(version.envVariables),
244 versionUrl: version.versionUrl,
245 createTime: version.createTime,
246 createdBy: version.createdBy,
247 diskUsageBytes: version.diskUsageBytes,
248 automaticScaling: version.automaticScaling,
249 basicScaling: version.basicScaling,
250 manualScaling: version.manualScaling,
251 };
252 };
253
254 const getById = (appsId: string, servicesId: string, versionsId: string) =>
255 versionsId.length === 0
256 ? Effect.undefined
257 : catchMissing(
258 appengine.getAppsServicesVersions({
259 appsId,
260 servicesId,
261 versionsId,
262 view: "FULL",
263 }),
264 );
265
266 const findOwnedVersion = (id: string, versions: readonly appengine.Version[]) =>
267 Effect.gen(function* () {
268 for (const version of versions) {
269 if (yield* ownedByAlchemy(id, versionOwnershipText(version))) {
270 return version;
271 }
272 }
273 return undefined;
274 });
275
276 const desiredBody = (
277 news: AppsServicesVersionProps,
278 versionId: string,
279 envVariables: Record<string, string | undefined>,
280 ): appengine.Version => ({
281 id: versionId,
282 runtime: news.runtime,
283 env: news.env,
284 servingStatus: news.servingStatus,
285 instanceClass: news.instanceClass,
286 envVariables,
287 deployment: news.deployment,
288 entrypoint: news.entrypoint,
289 automaticScaling: news.automaticScaling,
290 basicScaling: news.basicScaling,
291 manualScaling: news.manualScaling,
292 handlers: news.handlers,
293 threadsafe: news.threadsafe,
294 serviceAccount: news.serviceAccount,
295 inboundServices: news.inboundServices,
296 vpcAccessConnector: news.vpcAccessConnector,
297 appEngineApis: news.appEngineApis,
298 runtimeApiVersion: news.runtimeApiVersion,
299 });
300
301 export const AppsServicesVersionProvider = () =>
302 Provider.succeed(AppsServicesVersion, {
303 stables: ["name", "versionId", "serviceId", "appsId", "project", "createTime"],
304
305 diff: Effect.fn(function* ({ news, olds, output }) {
306 if (!isResolved(news)) return undefined;
307 const previousApp = olds?.appsId ?? output?.appsId;
308 const nextApp = news.appsId ?? previousApp;
309 if (previousApp !== undefined && nextApp !== undefined && nextApp !== previousApp) {
310 return { action: "replace" as const, deleteFirst: false };
311 }
312 const previousService = olds?.serviceId ?? output?.serviceId ?? DEFAULT_SERVICE;
313 const nextService = news.serviceId ?? previousService;
314 if (nextService !== previousService) {
315 return { action: "replace" as const, deleteFirst: false };
316 }
317 const previousId = olds?.versionId ?? output?.versionId;
318 if (
319 previousId !== undefined &&
320 news.versionId !== undefined &&
321 news.versionId !== previousId
322 ) {
323 return { action: "replace" as const, deleteFirst: false };
324 }
325 const previousRuntime = olds?.runtime ?? output?.runtime;
326 if (
327 previousRuntime !== undefined &&
328 news.runtime !== undefined &&
329 news.runtime !== previousRuntime
330 ) {
331 return { action: "replace" as const, deleteFirst: false };
332 }
333 const previousEnv = olds?.env ?? output?.env;
334 if (previousEnv !== undefined && news.env !== undefined && news.env !== previousEnv) {
335 return { action: "replace" as const, deleteFirst: false };
336 }
337 if (
338 news.deployment !== undefined &&
339 olds?.deployment !== undefined &&
340 !jsonEqual(news.deployment, olds.deployment)
341 ) {
342 return { action: "replace" as const, deleteFirst: false };
343 }
344 return undefined;
345 }),
346
347 read: Effect.fn(function* ({ id, olds, output }) {
348 const env = yield* GcpEnvironment.current;
349 const appsId = yield* resolveAppsId(olds?.appsId, output?.appsId);
350 const serviceId = olds?.serviceId ?? output?.serviceId ?? DEFAULT_SERVICE;
351 const versionId = yield* toResourceId(
352 id,
353 olds?.versionId,
354 output?.versionId,
355 MAX_VERSION_ID_LENGTH,
356 );
357 let existing = yield* getById(appsId, serviceId, versionId);
358 if (existing === undefined) {
359 existing = yield* findOwnedVersion(id, yield* listVersions(appsId, serviceId));
360 }
361 if (existing === undefined) return undefined;
362 const attrs = toAttrs(existing, appsId, serviceId, env.project);
363 return (yield* ownedByAlchemy(id, versionOwnershipText(existing))) ? attrs : Unowned(attrs);
364 }),
365
366 list: () =>
367 Effect.gen(function* () {
368 const env = yield* GcpEnvironment.current;
369 const services = yield* listServices(env.project);
370 const collected: ReturnType<typeof toAttrs>[] = [];
371 for (const service of services) {
372 const parsed = parseVersionName(service.name ?? "");
373 const serviceId = service.id ?? parsed.servicesId ?? lastServiceId(service.name);
374 const versions = yield* listVersions(env.project, serviceId);
375 for (const version of versions) {
376 if (hasOwnershipMarker(versionOwnershipText(version))) {
377 collected.push(toAttrs(version, env.project, serviceId, env.project));
378 }
379 }
380 }
381 return collected;
382 }),
383
384 reconcile: Effect.fn(function* ({ id, news, output }) {
385 const env = yield* GcpEnvironment.current;
386 const appsId = yield* resolveAppsId(news.appsId, output?.appsId);
387 const serviceId = news.serviceId ?? output?.serviceId ?? DEFAULT_SERVICE;
388 const versionId = yield* toResourceId(
389 id,
390 news.versionId,
391 output?.versionId,
392 MAX_VERSION_ID_LENGTH,
393 );
394 const ownership = yield* ownershipLabels(id);
395 const envVariables = stampEnvVariables(ownership, news.envVariables);
396 const body = desiredBody(news, versionId, envVariables);
397
398 let current = yield* getById(appsId, serviceId, versionId);
399 if (current === undefined) {
400 current = yield* findOwnedVersion(id, yield* listVersions(appsId, serviceId));
401 }
402
403 if (current === undefined) {
404 const operation = yield* appengine
405 .createAppsServicesVersions({
406 appsId,
407 servicesId: serviceId,
408 body,
409 })
410 .pipe(
411 Effect.catchTag("Conflict", () => Effect.succeed<appengine.Operation>({ done: true })),
412 );
413 if (operation.done !== true || operation.name !== undefined) {
414 yield* waitForOperation(operation, { appsId });
415 }
416 current = yield* getById(appsId, serviceId, versionId);
417 }
418
419 if (current === undefined) {
420 return yield* new AppsServicesVersionNotResolved({
421 resourceName: `apps/${appsId}/services/${serviceId}/versions/${versionId}`,
422 });
423 }
424
425 const observedId = current.id ?? versionId;
426 const servingChanged =
427 news.servingStatus !== undefined && !sameText(current.servingStatus, news.servingStatus);
428 const classChanged =
429 news.instanceClass !== undefined && !sameText(current.instanceClass, news.instanceClass);
430 const automaticChanged =
431 news.automaticScaling !== undefined &&
432 !jsonEqual(current.automaticScaling, news.automaticScaling);
433 const basicChanged =
434 news.basicScaling !== undefined && !jsonEqual(current.basicScaling, news.basicScaling);
435 const manualChanged =
436 news.manualScaling !== undefined && !jsonEqual(current.manualScaling, news.manualScaling);
437 const updateMask = updateMaskOf(
438 servingChanged ? "servingStatus" : undefined,
439 classChanged ? "instanceClass" : undefined,
440 automaticChanged ? "automaticScaling" : undefined,
441 basicChanged ? "basicScaling" : undefined,
442 manualChanged ? "manualScaling" : undefined,
443 );
444 if (updateMask.length > 0) {
445 const operation = yield* appengine.patchAppsServicesVersions({
446 appsId,
447 servicesId: serviceId,
448 versionsId: observedId,
449 updateMask,
450 body: {
451 servingStatus: news.servingStatus,
452 instanceClass: news.instanceClass,
453 automaticScaling: news.automaticScaling,
454 basicScaling: news.basicScaling,
455 manualScaling: news.manualScaling,
456 },
457 });
458 yield* waitForOperation(operation, { appsId });
459 current = (yield* getById(appsId, serviceId, observedId)) ?? current;
460 }
461
462 return toAttrs(current, appsId, serviceId, env.project);
463 }),
464
465 delete: Effect.fn(function* ({ output }) {
466 if (output.versionId.length === 0) return;
467 const operation = yield* appengine
468 .deleteAppsServicesVersions({
469 appsId: output.appsId,
470 servicesId: output.serviceId || DEFAULT_SERVICE,
471 versionsId: output.versionId,
472 })
473 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
474 if (operation === undefined) return;
475 yield* waitForOperation(operation, {
476 appsId: output.appsId,
477 notFoundOk: true,
478 });
479 }),
480 });
481
482 const lastServiceId = (name: string | undefined) => {
483 if (name === undefined) return DEFAULT_SERVICE;
484 const parts = name.split("/").filter((part) => part.length > 0);
485 const at = parts.lastIndexOf("services");
486 return at >= 0 ? (parts[at + 1] ?? DEFAULT_SERVICE) : DEFAULT_SERVICE;
487 };