@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 264 lines 8.72 KB
Raw
1 import * as dataform from "@distilled.cloud/gcp/dataform_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 { createInternalLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 deleteFolderTree,
13 encodeOwnershipLine,
14 expandParent,
15 hasOwnershipMarker,
16 listFolders,
17 locationParent,
18 normalizeLocation,
19 ownedByAlchemy,
20 parseOwnership,
21 parseResourceName,
22 replaceOnIdentity,
23 retryTransient,
24 sameText,
25 updateMaskOf,
26 waitUntilGone,
27 } from "./internal.ts";
28
29 export type ProjectsLocationsFolderProps = {
30 /**
31 * Region (`us-central1`, …). Immutable — changing it replaces the
32 * folder. `US-CENTRAL1` is accepted and normalized to `us-central1`.
33 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
34 */
35 location?: string;
36 /**
37 * User-friendly display name. Dataform folders have no labels field,
38 * so Alchemy stamps ownership into a `[alchemy …]` prefix and strips
39 * it from attributes. If omitted, only the ownership marker is stored.
40 */
41 displayName?: string;
42 /**
43 * Parent folder or team folder
44 * (`projects/{project}/locations/{location}/folders/{folder}` or
45 * `.../teamFolders/{teamFolder}`). Empty or omitted creates a root
46 * user folder. Changing it moves the folder.
47 */
48 containingFolder?: string;
49 };
50
51 export type ProjectsLocationsFolder = Resource<
52 "GCP.Dataform.ProjectsLocationsFolder",
53 ProjectsLocationsFolderProps,
54 {
55 /** Full resource name `projects/{project}/locations/{location}/folders/{folder}`. */
56 name: string;
57 /** Folder id (last path segment). */
58 folderId: string;
59 /** Project id. */
60 project: string;
61 /** Location id. */
62 location: string;
63 /** User display name with the Alchemy ownership prefix stripped. */
64 displayName: string | undefined;
65 /** Parent folder or team folder, if any. */
66 containingFolder: string | undefined;
67 /** Associated team folder, if any. */
68 teamFolderName: string | undefined;
69 /** Creator IAM principal. */
70 creatorIamPrincipal: string | undefined;
71 /** RFC3339 creation timestamp. */
72 createTime: string | undefined;
73 /** RFC3339 last-update timestamp. */
74 updateTime: string | undefined;
75 },
76 never,
77 Providers
78 >;
79
80 /**
81 * A Dataform folder used to organize repositories and nested folders.
82 *
83 * Folders have no labels API, so Alchemy stamps ownership into
84 * `displayName` for `list` / nuke. Location is immutable. Display name
85 * updates in place; `containingFolder` is applied with MoveFolder.
86 *
87 * ### Creating a Folder
88 * **Example:** Root folder
89 * ```typescript
90 * const folder = yield* GCP.Dataform.ProjectsLocationsFolder("Analytics", {
91 * displayName: "analytics",
92 * });
93 * ```
94 *
95 * **Example:** Nested folder
96 * ```typescript
97 * const child = yield* GCP.Dataform.ProjectsLocationsFolder("Models", {
98 * displayName: "models",
99 * containingFolder: folder.name,
100 * });
101 * ```
102 *
103 * @resource
104 * @category Dataform
105 */
106 export const ProjectsLocationsFolder = Resource<ProjectsLocationsFolder>(
107 "GCP.Dataform.ProjectsLocationsFolder",
108 );
109
110 export class ProjectsLocationsFolderNotResolved extends Data.TaggedError(
111 "GCP.Dataform.ProjectsLocationsFolderNotResolved",
112 )<{
113 resourceName: string;
114 }> {}
115
116 const toAttrs = (folder: dataform.Folder, project: string, region: string) => {
117 const name = folder.name ?? "";
118 const parsed = parseResourceName(name, "folders", region);
119 return {
120 name,
121 folderId: parsed.id,
122 project: parsed.project || project,
123 location: parsed.location,
124 displayName: parseOwnership(folder.displayName).text,
125 containingFolder: folder.containingFolder,
126 teamFolderName: folder.teamFolderName,
127 creatorIamPrincipal: folder.creatorIamPrincipal,
128 createTime: folder.createTime,
129 updateTime: folder.updateTime,
130 };
131 };
132
133 const getByName = (name: string) =>
134 name.length === 0 || name.includes("//")
135 ? Effect.undefined
136 : dataform
137 .getProjectsLocationsFolders({ name })
138 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
139
140 const findOwned = (
141 project: string,
142 location: string,
143 id: string,
144 displayName: string | undefined,
145 ) =>
146 Effect.gen(function* () {
147 const folders = yield* listFolders(project, location);
148 for (const folder of folders) {
149 if (yield* ownedByAlchemy(id, folder.displayName)) return folder;
150 }
151 if (displayName !== undefined) {
152 const match = folders.find(
153 (folder) => parseOwnership(folder.displayName).text === displayName,
154 );
155 if (match) return match;
156 }
157 return undefined;
158 });
159
160 export const ProjectsLocationsFolderProvider = () =>
161 Provider.succeed(ProjectsLocationsFolder, {
162 stables: ["name", "folderId", "project", "location", "createTime"],
163
164 diff: Effect.fn(function* ({ news, olds, output }) {
165 if (!isResolved(news)) return undefined;
166 return replaceOnIdentity({
167 previousLocation: olds?.location ?? output?.location,
168 nextLocation: news.location ?? olds?.location ?? output?.location,
169 });
170 }),
171
172 read: Effect.fn(function* ({ id, olds, output }) {
173 const env = yield* GcpEnvironment.current;
174 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
175 const existing = output?.name
176 ? yield* getByName(output.name)
177 : yield* findOwned(env.project, location, id, olds?.displayName);
178 if (existing === undefined) return undefined;
179 const attrs = toAttrs(existing, env.project, env.region);
180 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
181 }),
182
183 list: () =>
184 Effect.gen(function* () {
185 const env = yield* GcpEnvironment.current;
186 const folders = yield* listFolders(env.project, env.region);
187 return folders
188 .filter((folder) => hasOwnershipMarker(folder.displayName))
189 .map((folder) => toAttrs(folder, env.project, env.region));
190 }),
191
192 reconcile: Effect.fn(function* ({ id, news, output }) {
193 const env = yield* GcpEnvironment.current;
194 const location = normalizeLocation(news.location ?? output?.location, env.region);
195 const ownership = yield* createInternalLabels(id);
196 const displayName = encodeOwnershipLine(ownership, news.displayName);
197 const containingFolder =
198 news.containingFolder !== undefined && news.containingFolder.length > 0
199 ? news.containingFolder.includes("/")
200 ? news.containingFolder
201 : expandParent(news.containingFolder, env.project, location, "folders")
202 : undefined;
203
204 let current = output?.name
205 ? yield* getByName(output.name)
206 : yield* findOwned(env.project, location, id, news.displayName);
207
208 if (current === undefined) {
209 const created = yield* retryTransient(
210 dataform.createProjectsLocationsFolders({
211 parent: locationParent(env.project, location),
212 body: {
213 displayName,
214 containingFolder,
215 },
216 }),
217 ).pipe(
218 Effect.catchTag("Conflict", () => findOwned(env.project, location, id, news.displayName)),
219 );
220 current = created ?? undefined;
221 if (current?.name) {
222 current = (yield* getByName(current.name)) ?? current;
223 }
224 }
225
226 if (current === undefined) {
227 return yield* new ProjectsLocationsFolderNotResolved({
228 resourceName: output?.name ?? locationParent(env.project, location),
229 });
230 }
231
232 const currentName = current.name ?? "";
233 const displayChanged = !sameText(current.displayName, displayName);
234 if (displayChanged) {
235 current = yield* retryTransient(
236 dataform.patchProjectsLocationsFolders({
237 name: currentName,
238 updateMask: updateMaskOf("displayName"),
239 body: { displayName },
240 }),
241 );
242 }
243
244 const observedFolder = current.containingFolder ?? "";
245 const desiredFolder = containingFolder ?? "";
246 if (desiredFolder !== observedFolder) {
247 yield* retryTransient(
248 dataform.moveProjectsLocationsFolders({
249 name: currentName,
250 body: { destinationContainingFolder: desiredFolder },
251 }),
252 );
253 current = (yield* getByName(currentName)) ?? current;
254 }
255
256 return toAttrs(current, env.project, env.region);
257 }),
258
259 delete: Effect.fn(function* ({ output }) {
260 if (!output.name) return;
261 yield* retryTransient(deleteFolderTree(output.name));
262 yield* waitUntilGone(getByName(output.name));
263 }),
264 });