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

main
ts 224 lines 7.18 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 deleteTeamFolderTree,
13 encodeOwnershipLine,
14 hasOwnershipMarker,
15 listTeamFolders,
16 locationParent,
17 normalizeLocation,
18 ownedByAlchemy,
19 parseOwnership,
20 parseResourceName,
21 replaceOnIdentity,
22 retryTransient,
23 sameText,
24 updateMaskOf,
25 waitUntilGone,
26 } from "./internal.ts";
27
28 export type TeamProps = {
29 /**
30 * Region (`us-central1`, …). Immutable — changing it replaces the team
31 * folder. `US-CENTRAL1` is accepted and normalized to `us-central1`.
32 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
33 */
34 location?: string;
35 /**
36 * User-friendly display name. Required by the API. Team folders have no
37 * labels field, so Alchemy stamps ownership into a `[alchemy …]`
38 * prefix and strips it from attributes. If omitted, only the ownership
39 * marker is stored.
40 */
41 displayName?: string;
42 };
43
44 export type Team = Resource<
45 "GCP.Dataform.Team",
46 TeamProps,
47 {
48 /** Full resource name `projects/{project}/locations/{location}/teamFolders/{teamFolder}`. */
49 name: string;
50 /** Team folder id (last path segment). */
51 teamFolderId: string;
52 /** Project id. */
53 project: string;
54 /** Location id. */
55 location: string;
56 /** User display name with the Alchemy ownership prefix stripped. */
57 displayName: string | undefined;
58 /** Creator IAM principal. */
59 creatorIamPrincipal: string | undefined;
60 /** RFC3339 creation timestamp. */
61 createTime: string | undefined;
62 /** RFC3339 last-update timestamp. */
63 updateTime: string | undefined;
64 },
65 never,
66 Providers
67 >;
68
69 /**
70 * A Dataform team folder — a project-level container for repositories
71 * and folders with hierarchical access control.
72 *
73 * Team folders have no labels API, so Alchemy stamps ownership into
74 * `displayName` for `list` / nuke. Location is immutable. Display name
75 * updates in place.
76 *
77 * ### Creating a Team Folder
78 * **Example:** Generated display name
79 * ```typescript
80 * const team = yield* GCP.Dataform.Team("Analytics", {});
81 * ```
82 *
83 * **Example:** Named team folder
84 * ```typescript
85 * const team = yield* GCP.Dataform.Team("Analytics", {
86 * location: "us-central1",
87 * displayName: "analytics",
88 * });
89 * ```
90 *
91 * @resource
92 * @category Dataform
93 */
94 export const Team = Resource<Team>("GCP.Dataform.Team");
95
96 export class TeamNotResolved extends Data.TaggedError("GCP.Dataform.TeamNotResolved")<{
97 resourceName: string;
98 }> {}
99
100 const toAttrs = (folder: dataform.TeamFolder, project: string, region: string) => {
101 const name = folder.name ?? "";
102 const parsed = parseResourceName(name, "teamFolders", region);
103 return {
104 name,
105 teamFolderId: parsed.id,
106 project: parsed.project || project,
107 location: parsed.location,
108 displayName: parseOwnership(folder.displayName).text,
109 creatorIamPrincipal: folder.creatorIamPrincipal,
110 createTime: folder.createTime,
111 updateTime: folder.updateTime,
112 };
113 };
114
115 const getByName = (name: string) =>
116 name.length === 0 || name.includes("//")
117 ? Effect.undefined
118 : dataform
119 .getProjectsLocationsTeamFolders({ name })
120 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
121
122 const findOwned = (
123 project: string,
124 location: string,
125 id: string,
126 displayName: string | undefined,
127 ) =>
128 Effect.gen(function* () {
129 const folders = yield* listTeamFolders(project, location);
130 for (const folder of folders) {
131 if (yield* ownedByAlchemy(id, folder.displayName)) return folder;
132 }
133 if (displayName !== undefined) {
134 const match = folders.find(
135 (folder) => parseOwnership(folder.displayName).text === displayName,
136 );
137 if (match) return match;
138 }
139 return undefined;
140 });
141
142 export const TeamProvider = () =>
143 Provider.succeed(Team, {
144 stables: ["name", "teamFolderId", "project", "location", "createTime"],
145
146 diff: Effect.fn(function* ({ news, olds, output }) {
147 if (!isResolved(news)) return undefined;
148 return replaceOnIdentity({
149 previousLocation: olds?.location ?? output?.location,
150 nextLocation: news.location ?? olds?.location ?? output?.location,
151 });
152 }),
153
154 read: Effect.fn(function* ({ id, olds, output }) {
155 const env = yield* GcpEnvironment.current;
156 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
157 const existing = output?.name
158 ? yield* getByName(output.name)
159 : yield* findOwned(env.project, location, id, olds?.displayName);
160 if (existing === undefined) return undefined;
161 const attrs = toAttrs(existing, env.project, env.region);
162 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
163 }),
164
165 list: () =>
166 Effect.gen(function* () {
167 const env = yield* GcpEnvironment.current;
168 const folders = yield* listTeamFolders(env.project, env.region);
169 return folders
170 .filter((folder) => hasOwnershipMarker(folder.displayName))
171 .map((folder) => toAttrs(folder, env.project, env.region));
172 }),
173
174 reconcile: Effect.fn(function* ({ id, news, output }) {
175 const env = yield* GcpEnvironment.current;
176 const location = normalizeLocation(news.location ?? output?.location, env.region);
177 const ownership = yield* createInternalLabels(id);
178 const displayName = encodeOwnershipLine(ownership, news.displayName);
179
180 let current = output?.name
181 ? yield* getByName(output.name)
182 : yield* findOwned(env.project, location, id, news.displayName);
183
184 if (current === undefined) {
185 const created = yield* retryTransient(
186 dataform.createProjectsLocationsTeamFolders({
187 parent: locationParent(env.project, location),
188 body: { displayName },
189 }),
190 ).pipe(
191 Effect.catchTag("Conflict", () => findOwned(env.project, location, id, news.displayName)),
192 );
193 current = created ?? undefined;
194 if (current?.name) {
195 current = (yield* getByName(current.name)) ?? current;
196 }
197 }
198
199 if (current === undefined) {
200 return yield* new TeamNotResolved({
201 resourceName: output?.name ?? locationParent(env.project, location),
202 });
203 }
204
205 const currentName = current.name ?? "";
206 if (!sameText(current.displayName, displayName)) {
207 current = yield* retryTransient(
208 dataform.patchProjectsLocationsTeamFolders({
209 name: currentName,
210 updateMask: updateMaskOf("displayName"),
211 body: { displayName },
212 }),
213 );
214 }
215
216 return toAttrs(current, env.project, env.region);
217 }),
218
219 delete: Effect.fn(function* ({ output }) {
220 if (!output.name) return;
221 yield* retryTransient(deleteTeamFolderTree(output.name));
222 yield* waitUntilGone(getByName(output.name));
223 }),
224 });