@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 259 lines 8.62 KB
Raw
1 import * as apphub from "@distilled.cloud/gcp/apphub_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 * as Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 GLOBAL_LOCATION,
13 locationParent,
14 parseName,
15 projectIdOf,
16 projectNameOf,
17 replaceOnIdentity,
18 ResourceNotResolved,
19 waitForOperation,
20 waitUntilExists,
21 waitUntilGone,
22 waitUntilReady,
23 } from "./internal.ts";
24
25 export type ServiceProjectAttachmentProps = {
26 /**
27 * Service project to attach, as `projects/{project}` or a bare project
28 * id. Immutable — changing it replaces the attachment. The attachment
29 * id must equal this project's id. Defaults to the stack project.
30 */
31 serviceProject?: string;
32 /**
33 * Attachment id. Must equal the project id of `serviceProject`. If
34 * omitted, that project id is used. Immutable — changing it replaces
35 * the attachment.
36 */
37 serviceProjectAttachmentId?: string;
38 /**
39 * Location of the host project. App Hub only supports `global`.
40 * @default "global"
41 */
42 location?: string;
43 };
44
45 export type ServiceProjectAttachment = Resource<
46 "GCP.AppHub.ServiceProjectAttachment",
47 ServiceProjectAttachmentProps,
48 {
49 /** Full resource name. */
50 name: string;
51 /** Attachment id (last path segment, equal to the service project id). */
52 serviceProjectAttachmentId: string;
53 /** Host project id. */
54 project: string;
55 /** Location id (`global`). */
56 location: string;
57 /** Service project resource name (`projects/{number}` on output). */
58 serviceProject: string | undefined;
59 /** Server-reported state. */
60 state: string | undefined;
61 /** Server-generated resource uid. */
62 uid: string | undefined;
63 /** RFC3339 creation timestamp. */
64 createTime: string | undefined;
65 },
66 never,
67 Providers
68 >;
69
70 /**
71 * An App Hub service project attachment. Service projects hold the
72 * underlying cloud resources and expose them to a host project so App
73 * Hub can provide an aggregated view.
74 *
75 * Attachments have no labels, description, or display name, and the id
76 * is forced to the service project id, so `list` cannot stamp ownership.
77 * Location is always `global`. The resource is existence-only: service
78 * project is identity, and there is nothing mutable to sync.
79 *
80 * ### Creating a Service Project Attachment
81 * **Example:** Attach the stack project
82 * ```typescript
83 * const attachment = yield* GCP.AppHub.ServiceProjectAttachment(
84 * "Host",
85 * {},
86 * );
87 * ```
88 *
89 * **Example:** Attach a specific service project
90 * ```typescript
91 * const attachment = yield* GCP.AppHub.ServiceProjectAttachment(
92 * "Payments",
93 * { serviceProject: "projects/my-service" },
94 * );
95 * ```
96 *
97 * @resource
98 * @category AppHub
99 */
100 export const ServiceProjectAttachment = Resource<ServiceProjectAttachment>(
101 "GCP.AppHub.ServiceProjectAttachment",
102 );
103
104 const resourceName = (project: string, location: string, attachmentId: string) =>
105 `${locationParent(project, location)}/serviceProjectAttachments/${attachmentId}`;
106
107 const toAttrs = (item: apphub.ServiceProjectAttachment, project: string) => {
108 const name = item.name ?? "";
109 const parsed = parseName(name, "serviceProjectAttachments", GLOBAL_LOCATION);
110 return {
111 name,
112 serviceProjectAttachmentId: parsed.id,
113 project: parsed.project || project,
114 location: parsed.location || GLOBAL_LOCATION,
115 serviceProject: item.serviceProject,
116 state: item.state,
117 uid: item.uid,
118 createTime: item.createTime,
119 };
120 };
121
122 const getByName = (name: string) =>
123 name.length === 0
124 ? Effect.undefined
125 : apphub
126 .getProjectsLocationsServiceProjectAttachments({ name })
127 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
128
129 export const ServiceProjectAttachmentProvider = () =>
130 Provider.succeed(ServiceProjectAttachment, {
131 stables: [
132 "name",
133 "serviceProjectAttachmentId",
134 "project",
135 "location",
136 "serviceProject",
137 "uid",
138 "createTime",
139 ],
140
141 diff: Effect.fn(function* ({ news, olds, output }) {
142 if (!isResolved(news)) return undefined;
143 const previousProject = projectIdOf(olds?.serviceProject ?? output?.serviceProject, "");
144 const nextProject = projectIdOf(
145 news.serviceProject ?? olds?.serviceProject ?? output?.serviceProject,
146 previousProject,
147 );
148 return replaceOnIdentity({
149 previousId: olds?.serviceProjectAttachmentId ?? output?.serviceProjectAttachmentId,
150 nextId:
151 news.serviceProjectAttachmentId ??
152 olds?.serviceProjectAttachmentId ??
153 output?.serviceProjectAttachmentId,
154 previousLocation: GLOBAL_LOCATION,
155 nextLocation: GLOBAL_LOCATION,
156 extra:
157 previousProject.length > 0 && nextProject.length > 0 && previousProject !== nextProject,
158 });
159 }),
160
161 read: Effect.fn(function* ({ olds, output }) {
162 const env = yield* GcpEnvironment.current;
163 const serviceProjectId = projectIdOf(
164 olds?.serviceProject ?? output?.serviceProject,
165 env.project,
166 );
167 const attachmentId =
168 olds?.serviceProjectAttachmentId ?? output?.serviceProjectAttachmentId ?? serviceProjectId;
169 const name = output?.name ?? resourceName(env.project, GLOBAL_LOCATION, attachmentId);
170 const existing = yield* getByName(name);
171 if (existing === undefined) return undefined;
172 const attrs = toAttrs(existing, env.project);
173 return attrs.serviceProjectAttachmentId === attachmentId ? attrs : Unowned(attrs);
174 }),
175
176 list: () =>
177 Effect.gen(function* () {
178 const env = yield* GcpEnvironment.current;
179 return yield* apphub.listProjectsLocationsServiceProjectAttachments
180 .pages({
181 parent: locationParent(env.project, GLOBAL_LOCATION),
182 pageSize: 1000,
183 })
184 .pipe(
185 Stream.flatMap((page) => Stream.fromIterable(page.serviceProjectAttachments ?? [])),
186 Stream.filter(
187 (item) =>
188 projectIdOf(item.serviceProject, "") === env.project ||
189 parseName(item.name ?? "", "serviceProjectAttachments", GLOBAL_LOCATION).id ===
190 env.project,
191 ),
192 Stream.map((item) => toAttrs(item, env.project)),
193 Stream.runCollect,
194 Effect.map((chunk) => Array.from(chunk)),
195 // No global location yet: no attachments.
196 Effect.catchTag("NotFound", () => Effect.succeed([])),
197 );
198 }),
199
200 reconcile: Effect.fn(function* ({ news, output }) {
201 const env = yield* GcpEnvironment.current;
202 const serviceProject = projectNameOf(news.serviceProject, env.project);
203 const attachmentId =
204 news.serviceProjectAttachmentId ??
205 output?.serviceProjectAttachmentId ??
206 projectIdOf(serviceProject, env.project);
207 const name = resourceName(env.project, GLOBAL_LOCATION, attachmentId);
208 const parent = locationParent(env.project, GLOBAL_LOCATION);
209
210 let current = yield* getByName(output?.name ?? name);
211
212 if (current === undefined) {
213 const created = yield* apphub
214 .createProjectsLocationsServiceProjectAttachments({
215 parent,
216 serviceProjectAttachmentId: attachmentId,
217 body: {
218 serviceProject,
219 },
220 })
221 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
222 if (created !== undefined) {
223 yield* waitForOperation(created);
224 }
225 current = yield* waitUntilExists(getByName(name), name);
226 }
227
228 if (current === undefined) {
229 return yield* new ResourceNotResolved({ resourceName: name });
230 }
231
232 current = yield* waitUntilReady(
233 getByName(current.name ?? name),
234 current.name ?? name,
235 (item) => item.state,
236 );
237
238 return toAttrs(current, env.project);
239 }),
240
241 delete: Effect.fn(function* ({ output }) {
242 const operation = yield* apphub
243 .deleteProjectsLocationsServiceProjectAttachments({
244 name: output.name,
245 })
246 .pipe(
247 Effect.retry({
248 while: (error) => error._tag === "Conflict",
249 times: 8,
250 schedule: Schedule.spaced("2 seconds"),
251 }),
252 Effect.catchTag("NotFound", () => Effect.undefined),
253 );
254 if (operation !== undefined) {
255 yield* waitForOperation(operation, { notFoundOk: true });
256 }
257 yield* waitUntilGone(getByName(output.name), output.name);
258 }),
259 });