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

main
ts 238 lines 8.22 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 type { Providers } from "../Providers.ts";
10 import {
11 expandRepository,
12 forEachOwnedRepository,
13 hasAlchemyLabelMap,
14 listWorkspaces,
15 normalizeLocation,
16 parseResourceName,
17 replaceOnIdentity,
18 retryTransient,
19 toPhysicalId,
20 waitUntilExists,
21 waitUntilGone,
22 } from "./internal.ts";
23
24 export type RepositoriesWorkspaceProps = {
25 /**
26 * Parent repository. Full name
27 * `projects/{project}/locations/{location}/repositories/{repository}`
28 * or the repository id (combined with `location`). Immutable —
29 * changing it replaces the workspace.
30 */
31 repository: string;
32 /**
33 * Region used when `repository` is a bare id.
34 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
35 */
36 location?: string;
37 /**
38 * Workspace id (the `{workspace}` segment). If omitted, a unique
39 * RFC1035 name is generated. Immutable — changing it replaces the
40 * workspace. Workspaces have no labels field; ownership is the
41 * generated physical id and the parent repository's Alchemy labels.
42 */
43 workspaceId?: string;
44 /**
45 * When true, the workspace is deleted instead of moved if its
46 * repository is moved. Immutable after create.
47 * @default false
48 */
49 disableMoves?: boolean;
50 };
51
52 export type RepositoriesWorkspace = Resource<
53 "GCP.Dataform.RepositoriesWorkspace",
54 RepositoriesWorkspaceProps,
55 {
56 /** Full resource name `.../repositories/{repository}/workspaces/{workspace}`. */
57 name: string;
58 /** Workspace id (last path segment). */
59 workspaceId: string;
60 /** Parent repository resource name. */
61 repository: string;
62 /** Project id. */
63 project: string;
64 /** Location id. */
65 location: string;
66 /** Whether the workspace is deleted on repository move. */
67 disableMoves: boolean;
68 /** Whether the workspace is user-scoped. */
69 userScoped: boolean | undefined;
70 /** RFC3339 creation timestamp. */
71 createTime: string | undefined;
72 },
73 never,
74 Providers
75 >;
76
77 /**
78 * A Dataform Git workspace inside a repository.
79 *
80 * Workspaces have no update API. Changing `workspaceId`, `repository`,
81 * `location`, or `disableMoves` replaces the workspace. Ownership for
82 * `list` / nuke is the parent repository's Alchemy labels.
83 *
84 * ### Creating a Workspace
85 * **Example:** Generated name
86 * ```typescript
87 * const workspace = yield* GCP.Dataform.RepositoriesWorkspace("Dev", {
88 * repository: repo.name,
89 * });
90 * ```
91 *
92 * **Example:** Named workspace
93 * ```typescript
94 * const workspace = yield* GCP.Dataform.RepositoriesWorkspace("Dev", {
95 * repository: repo.name,
96 * workspaceId: "dev",
97 * });
98 * ```
99 *
100 * @resource
101 * @category Dataform
102 */
103 export const RepositoriesWorkspace = Resource<RepositoriesWorkspace>(
104 "GCP.Dataform.RepositoriesWorkspace",
105 );
106
107 export class RepositoriesWorkspaceNotResolved extends Data.TaggedError(
108 "GCP.Dataform.RepositoriesWorkspaceNotResolved",
109 )<{
110 resourceName: string;
111 }> {}
112
113 const resourceName = (repository: string, workspaceId: string) =>
114 `${repository}/workspaces/${workspaceId}`;
115
116 const toAttrs = (workspace: dataform.Workspace, project: string, region: string) => {
117 const name = workspace.name ?? "";
118 const parsed = parseResourceName(name, "workspaces", region);
119 return {
120 name,
121 workspaceId: parsed.id,
122 repository: parsed.parent,
123 project: parsed.project || project,
124 location: parsed.location,
125 disableMoves: workspace.disableMoves === true,
126 userScoped: workspace.privateResourceMetadata?.userScoped,
127 createTime: workspace.createTime,
128 };
129 };
130
131 const getByName = (name: string) =>
132 name.length === 0 || name.includes("//")
133 ? Effect.undefined
134 : dataform
135 .getProjectsLocationsRepositoriesWorkspaces({ name })
136 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
137
138 export const RepositoriesWorkspaceProvider = () =>
139 Provider.succeed(RepositoriesWorkspace, {
140 stables: ["name", "workspaceId", "repository", "project", "location", "createTime"],
141
142 diff: Effect.fn(function* ({ news, olds, output }) {
143 if (!isResolved(news)) return undefined;
144 const env = yield* GcpEnvironment.current;
145 const location = normalizeLocation(
146 news.location ?? olds?.location ?? output?.location,
147 env.region,
148 );
149 const previousRepo = olds?.repository ?? output?.repository;
150 const nextRepo = expandRepository(news.repository, env.project, location);
151 const previousMoves = olds?.disableMoves ?? output?.disableMoves;
152 return replaceOnIdentity({
153 previousId: olds?.workspaceId ?? output?.workspaceId,
154 nextId: news.workspaceId ?? olds?.workspaceId ?? output?.workspaceId,
155 previousLocation: olds?.location ?? output?.location,
156 nextLocation: news.location ?? olds?.location ?? output?.location,
157 previousParent: previousRepo,
158 nextParent: nextRepo,
159 extra:
160 previousMoves !== undefined &&
161 news.disableMoves !== undefined &&
162 news.disableMoves !== previousMoves,
163 });
164 }),
165
166 read: Effect.fn(function* ({ id, olds, output }) {
167 const env = yield* GcpEnvironment.current;
168 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
169 const repository = expandRepository(
170 olds?.repository ??
171 output?.repository ??
172 parseResourceName(output?.name ?? "", "workspaces", env.region).parent,
173 env.project,
174 location,
175 );
176 const workspaceId = yield* toPhysicalId(id, olds?.workspaceId, output?.workspaceId);
177 const name = output?.name ?? resourceName(repository, workspaceId);
178 const existing = yield* getByName(name);
179 if (existing === undefined) return undefined;
180 const attrs = toAttrs(existing, env.project, env.region);
181 const parent = yield* dataform
182 .getProjectsLocationsRepositories({ name: attrs.repository })
183 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
184 if (parent === undefined) return Unowned(attrs);
185 return hasAlchemyLabelMap(parent.labels) ? attrs : Unowned(attrs);
186 }),
187
188 list: () =>
189 Effect.gen(function* () {
190 const env = yield* GcpEnvironment.current;
191 const workspaces = yield* forEachOwnedRepository(env.project, env.region, (repo) =>
192 listWorkspaces(repo.name ?? ""),
193 );
194 return workspaces.map((item) => toAttrs(item, env.project, env.region));
195 }),
196
197 reconcile: Effect.fn(function* ({ id, news, output }) {
198 const env = yield* GcpEnvironment.current;
199 const location = normalizeLocation(news.location ?? output?.location, env.region);
200 const repository = expandRepository(news.repository, env.project, location);
201 const workspaceId = yield* toPhysicalId(id, news.workspaceId, output?.workspaceId);
202 const name = resourceName(repository, workspaceId);
203
204 let current = yield* getByName(output?.name ?? name);
205
206 if (current === undefined) {
207 const created = yield* retryTransient(
208 dataform.createProjectsLocationsRepositoriesWorkspaces({
209 parent: repository,
210 workspaceId,
211 body: {
212 disableMoves: news.disableMoves === true ? true : undefined,
213 },
214 }),
215 ).pipe(Effect.catchTag("Conflict", () => getByName(name)));
216 current = created ?? undefined;
217 if (current === undefined) {
218 current = yield* waitUntilExists(getByName(name), name);
219 }
220 }
221
222 if (current === undefined) {
223 return yield* new RepositoriesWorkspaceNotResolved({ resourceName: name });
224 }
225
226 return toAttrs(current, env.project, env.region);
227 }),
228
229 delete: Effect.fn(function* ({ output }) {
230 if (!output.name) return;
231 yield* retryTransient(
232 dataform.deleteProjectsLocationsRepositoriesWorkspaces({
233 name: output.name,
234 }),
235 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
236 yield* waitUntilGone(getByName(output.name));
237 }),
238 });