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

main
ts 239 lines 7.62 KB
Raw
1 import * as dataplex from "@distilled.cloud/gcp/dataplex_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 { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import { listAlchemyDataDomains } from "./DataDomain.ts";
11 import {
12 DataplexNotResolved,
13 collectPages,
14 lastSegment,
15 parseName,
16 replaceOnIdentity,
17 retryQuota,
18 toPhysicalId,
19 waitForOperation,
20 waitUntilExists,
21 waitUntilGone,
22 } from "./internal.ts";
23
24 export type DataDomainsBindingProps = {
25 /**
26 * Parent DataDomain resource name
27 * (`projects/{project}/locations/{location}/dataDomains/{dataDomain}`).
28 * Immutable — changing it replaces the binding.
29 */
30 parent: string;
31 /**
32 * Binding id. If omitted, a unique name is generated. Must contain
33 * only lowercase letters, numbers and hyphens, start with a letter,
34 * end with a letter or number, and be 1-63 characters. Immutable —
35 * changing it replaces the binding.
36 */
37 dataDomainBindingId?: string;
38 /**
39 * Immutable IAM full resource name to include in the DataDomain, e.g.
40 * `//cloudresourcemanager.googleapis.com/projects/{project}` or
41 * `//bigquery.googleapis.com/projects/{project}/datasets/{dataset}`.
42 * Changing it replaces the binding.
43 */
44 resource: string;
45 };
46
47 export type DataDomainsBinding = Resource<
48 "GCP.Dataplex.DataDomainsBinding",
49 DataDomainsBindingProps,
50 {
51 /** Full resource name. */
52 name: string;
53 /** Binding id (last path segment). */
54 dataDomainBindingId: string;
55 /** Parent DataDomain resource name. */
56 parent: string;
57 /** Project id. */
58 project: string;
59 /** Location id. */
60 location: string;
61 /** Bound Google Cloud resource. */
62 resource: string;
63 /** System uid. */
64 uid: string | undefined;
65 /** RFC3339 creation timestamp. */
66 createTime: string | undefined;
67 },
68 never,
69 Providers
70 >;
71
72 /**
73 * A Dataplex DataDomainBinding that includes a Google Cloud resource
74 * (and its contents) in a DataDomain.
75 *
76 * Bindings have no labels or description. `list` walks alchemy-labeled
77 * DataDomains and returns their bindings so nuke can find them. Parent,
78 * binding id, and resource are identity — there is no in-place update
79 * API.
80 *
81 * ### Creating a DataDomainBinding
82 * **Example:** Bind a BigQuery dataset
83 * ```typescript
84 * const binding = yield* GCP.Dataplex.DataDomainsBinding("Analytics", {
85 * parent: domain.name,
86 * resource:
87 * "//bigquery.googleapis.com/projects/my-project/datasets/analytics",
88 * });
89 * ```
90 *
91 * @resource
92 * @category Dataplex
93 */
94 export const DataDomainsBinding = Resource<DataDomainsBinding>("GCP.Dataplex.DataDomainsBinding");
95
96 const resourceNameOf = (parent: string, dataDomainBindingId: string) =>
97 `${parent}/bindings/${dataDomainBindingId}`;
98
99 const toAttrs = (binding: dataplex.GoogleCloudDataplexV1DataDomainBinding, project: string) => {
100 const name = binding.name ?? "";
101 const parsed = parseName(name, "bindings");
102 return {
103 name,
104 dataDomainBindingId: parsed.id,
105 parent: parsed.parent,
106 project: parsed.project || project,
107 location: parsed.location,
108 resource: binding.resource ?? "",
109 uid: binding.uid,
110 createTime: binding.createTime,
111 };
112 };
113
114 const getByName = (name: string) =>
115 name.length === 0
116 ? Effect.undefined
117 : retryQuota(dataplex.getProjectsLocationsDataDomainsBindings({ name })).pipe(
118 Effect.catchTag("NotFound", () => Effect.undefined),
119 );
120
121 const listAtParent = (parent: string) =>
122 collectPages(
123 dataplex.listProjectsLocationsDataDomainsBindings.pages({
124 parent,
125 pageSize: 100,
126 }),
127 (page) => page.dataDomainBindings,
128 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([])));
129
130 export const DataDomainsBindingProvider = () =>
131 Provider.succeed(DataDomainsBinding, {
132 stables: [
133 "name",
134 "dataDomainBindingId",
135 "parent",
136 "project",
137 "location",
138 "resource",
139 "uid",
140 "createTime",
141 ],
142
143 diff: Effect.fn(function* ({ news, olds, output }) {
144 if (!isResolved(news)) return undefined;
145 return replaceOnIdentity({
146 previousId: olds?.dataDomainBindingId ?? output?.dataDomainBindingId,
147 nextId:
148 news.dataDomainBindingId ?? olds?.dataDomainBindingId ?? output?.dataDomainBindingId,
149 previousLocation: lastSegment(olds?.parent ?? output?.parent ?? ""),
150 nextLocation: lastSegment(news.parent),
151 previousParent: olds?.parent ?? output?.parent,
152 nextParent: news.parent,
153 extra:
154 (olds?.resource ?? output?.resource) !== undefined &&
155 news.resource !== (olds?.resource ?? output?.resource),
156 });
157 }),
158
159 read: Effect.fn(function* ({ id, olds, output }) {
160 const env = yield* GcpEnvironment.current;
161 const dataDomainBindingId = yield* toPhysicalId(
162 id,
163 olds?.dataDomainBindingId,
164 output?.dataDomainBindingId,
165 "ddbinding",
166 );
167 const name =
168 output?.name ?? (olds?.parent ? resourceNameOf(olds.parent, dataDomainBindingId) : "");
169 const existing = yield* getByName(name);
170 if (existing === undefined) return undefined;
171 const attrs = toAttrs(existing, env.project);
172 return lastSegment(existing.name ?? "") === dataDomainBindingId ? attrs : Unowned(attrs);
173 }),
174
175 list: () =>
176 Effect.gen(function* () {
177 const env = yield* GcpEnvironment.current;
178 const domains = yield* listAlchemyDataDomains(env.project, env.region);
179 const pages = yield* Effect.forEach(
180 domains,
181 (domain) =>
182 domain.name
183 ? listAtParent(domain.name)
184 : Effect.succeed([] as dataplex.GoogleCloudDataplexV1DataDomainBinding[]),
185 { concurrency: 4 },
186 );
187 return pages.flat().map((item) => toAttrs(item, env.project));
188 }),
189
190 reconcile: Effect.fn(function* ({ id, news, output }) {
191 const env = yield* GcpEnvironment.current;
192 const dataDomainBindingId = yield* toPhysicalId(
193 id,
194 news.dataDomainBindingId,
195 output?.dataDomainBindingId,
196 "ddbinding",
197 );
198 const name = resourceNameOf(news.parent, dataDomainBindingId);
199
200 let current = yield* getByName(output?.name ?? name);
201
202 if (current === undefined) {
203 const created = yield* retryQuota(
204 dataplex.createProjectsLocationsDataDomainsBindings({
205 parent: news.parent,
206 dataDomainBindingId,
207 body: { resource: news.resource },
208 }),
209 ).pipe(Effect.catchTag("Conflict", () => Effect.undefined));
210 if (created !== undefined) {
211 yield* waitForOperation(created);
212 }
213 current = yield* waitUntilExists(getByName(name), name);
214 }
215
216 if (current === undefined) {
217 return yield* new DataplexNotResolved({ resourceName: name });
218 }
219
220 return toAttrs(current, env.project);
221 }),
222
223 delete: Effect.fn(function* ({ output }) {
224 const operation = yield* dataplex
225 .deleteProjectsLocationsDataDomainsBindings({ name: output.name })
226 .pipe(
227 Effect.retry({
228 while: (error) => error._tag === "Conflict",
229 times: 8,
230 schedule: Schedule.spaced("2 seconds"),
231 }),
232 Effect.catchTag("NotFound", () => Effect.undefined),
233 );
234 if (operation !== undefined) {
235 yield* waitForOperation(operation, { notFoundOk: true });
236 }
237 yield* waitUntilGone(getByName(output.name), output.name);
238 }),
239 });