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

main
ts 300 lines 10.1 KB
Raw
1 import * as gkebackup from "@distilled.cloud/gcp/gkebackup_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 { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 fieldMask,
14 listAtLocation,
15 listLabeledPages,
16 normalizeLocation,
17 parentOf,
18 parseName,
19 projectName,
20 replaceOnIdentity,
21 ResourceNotResolved,
22 sameText,
23 toPhysicalId,
24 userLabels,
25 waitForDeleteOperation,
26 waitForOperation,
27 waitUntilExists,
28 waitUntilGone,
29 } from "./internal.ts";
30
31 export type RestoreChannelProps = {
32 /**
33 * Restore channel id (the `{restoreChannel}` segment of
34 * `projects/{project}/locations/{location}/restoreChannels/{restoreChannel}`).
35 * If omitted, a unique RFC1035 name is generated from the stack, stage,
36 * and logical id. Immutable — changing it replaces the channel.
37 */
38 restoreChannelId?: string;
39 /**
40 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
41 * replaces the channel. `US-CENTRAL1` is accepted and normalized to
42 * `us-central1`.
43 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
44 */
45 location?: string;
46 /**
47 * Project that is allowed to restore backups via this channel. Full
48 * name `projects/{project}` or a project id. Must differ from the
49 * source project. Immutable — changing it replaces the channel.
50 */
51 destinationProject: string;
52 /**
53 * Human-readable description.
54 */
55 description?: string;
56 /**
57 * User labels. Alchemy ownership labels are merged in automatically.
58 */
59 labels?: Record<string, string>;
60 };
61
62 export type RestoreChannel = Resource<
63 "GCP.GKEBackup.RestoreChannel",
64 RestoreChannelProps,
65 {
66 /** Full resource name. */
67 name: string;
68 /** Restore channel id (last path segment). */
69 restoreChannelId: string;
70 /** Project id. */
71 project: string;
72 /** Location id. */
73 location: string;
74 /** Destination project resource name. */
75 destinationProject: string | undefined;
76 /** Destination project id. */
77 destinationProjectId: string | undefined;
78 /** Human-readable description. */
79 description: string | undefined;
80 /** User labels (Alchemy ownership labels stripped). */
81 labels: Record<string, string>;
82 /** Server-generated resource uid. */
83 uid: string | undefined;
84 /** RFC3339 creation timestamp. */
85 createTime: string | undefined;
86 /** RFC3339 last-update timestamp. */
87 updateTime: string | undefined;
88 },
89 never,
90 Providers
91 >;
92
93 /**
94 * A Backup for GKE restore channel that authorizes restoring backups
95 * into a destination project.
96 *
97 * Changing `restoreChannelId`, `location`, or `destinationProject`
98 * replaces the channel. Description and labels update in place.
99 *
100 * ### Creating a Restore Channel
101 * **Example:** Generated name
102 * ```typescript
103 * const channel = yield* GCP.GKEBackup.RestoreChannel("CrossProject", {
104 * destinationProject: "projects/my-restore-project",
105 * });
106 * ```
107 *
108 * **Example:** Explicit id, destination, and labels
109 * ```typescript
110 * const channel = yield* GCP.GKEBackup.RestoreChannel("CrossProject", {
111 * restoreChannelId: "app-restores",
112 * destinationProject: "projects/my-restore-project",
113 * description: "cross-project restores",
114 * labels: { env: "prod" },
115 * });
116 * ```
117 *
118 * ### Updating a Restore Channel
119 * **Example:** Description and labels
120 * ```typescript
121 * const channel = yield* GCP.GKEBackup.RestoreChannel("CrossProject", {
122 * destinationProject: "projects/my-restore-project",
123 * description: "cross-project restores v2",
124 * labels: { env: "prod", team: "platform" },
125 * });
126 * ```
127 *
128 * @resource
129 * @category GKEBackup
130 */
131 export const RestoreChannel = Resource<RestoreChannel>("GCP.GKEBackup.RestoreChannel");
132
133 const resourceName = (project: string, location: string, restoreChannelId: string) =>
134 `projects/${project}/locations/${location}/restoreChannels/${restoreChannelId}`;
135
136 const toAttrs = (item: gkebackup.RestoreChannel, project: string, region: string) => {
137 const name = item.name ?? "";
138 const parsed = parseName(name, "restoreChannels", region);
139 return {
140 name,
141 restoreChannelId: parsed.id,
142 project: parsed.project || project,
143 location: parsed.location,
144 destinationProject: item.destinationProject,
145 destinationProjectId: item.destinationProjectId,
146 description: item.description,
147 labels: userLabels(item.labels),
148 uid: item.uid,
149 createTime: item.createTime,
150 updateTime: item.updateTime,
151 };
152 };
153
154 const getByName = (name: string) =>
155 gkebackup
156 .getProjectsLocationsRestoreChannels({ name })
157 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
158
159 const listOwned = (project: string) =>
160 listAtLocation(project, (parent) =>
161 listLabeledPages(
162 gkebackup.listProjectsLocationsRestoreChannels.pages({
163 parent,
164 pageSize: 1000,
165 }),
166 (page) => page.restoreChannels,
167 (item) => item.labels,
168 ),
169 );
170
171 export const RestoreChannelProvider = () =>
172 Provider.succeed(RestoreChannel, {
173 stables: ["name", "restoreChannelId", "project", "location", "uid", "createTime"],
174
175 diff: Effect.fn(function* ({ news, olds, output }) {
176 if (!isResolved(news)) return undefined;
177 const env = yield* GcpEnvironment.current;
178 const previousDest = olds?.destinationProject ?? output?.destinationProject;
179 const nextDest = news.destinationProject;
180 return replaceOnIdentity({
181 previousId: olds?.restoreChannelId ?? output?.restoreChannelId,
182 nextId: news.restoreChannelId ?? olds?.restoreChannelId ?? output?.restoreChannelId,
183 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
184 nextLocation: normalizeLocation(
185 news.location ?? olds?.location ?? output?.location,
186 env.region,
187 ),
188 extra:
189 previousDest !== undefined &&
190 nextDest !== undefined &&
191 previousDest !== nextDest &&
192 !previousDest.endsWith(`/${nextDest}`) &&
193 previousDest !== `projects/${nextDest}`,
194 });
195 }),
196
197 read: Effect.fn(function* ({ id, olds, output }) {
198 const env = yield* GcpEnvironment.current;
199 const restoreChannelId = yield* toPhysicalId(
200 id,
201 olds?.restoreChannelId,
202 output?.restoreChannelId,
203 "restorechannel",
204 );
205 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
206 const name = output?.name ?? resourceName(env.project, location, restoreChannelId);
207 const existing = yield* getByName(name);
208 if (existing === undefined) return undefined;
209 const attrs = toAttrs(existing, env.project, env.region);
210 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
211 }),
212
213 list: () =>
214 Effect.gen(function* () {
215 const env = yield* GcpEnvironment.current;
216 const items = yield* listOwned(env.project);
217 return items.map((item) => toAttrs(item, env.project, env.region));
218 }),
219
220 reconcile: Effect.fn(function* ({ id, news, output }) {
221 const env = yield* GcpEnvironment.current;
222 const restoreChannelId = yield* toPhysicalId(
223 id,
224 news.restoreChannelId,
225 output?.restoreChannelId,
226 "restorechannel",
227 );
228 const location = normalizeLocation(news.location ?? output?.location, env.region);
229 const name = resourceName(env.project, location, restoreChannelId);
230 const destinationProject = projectName(news.destinationProject, env.project);
231 const desiredLabels = {
232 ...toLabels(news.labels),
233 ...(yield* createInternalLabels(id)),
234 };
235
236 let current = yield* getByName(output?.name ?? name);
237
238 if (current === undefined) {
239 const created = yield* gkebackup
240 .createProjectsLocationsRestoreChannels({
241 parent: parentOf(env.project, location),
242 restoreChannelId,
243 body: {
244 destinationProject,
245 description: news.description,
246 labels: desiredLabels,
247 },
248 })
249 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
250 if (created !== undefined) {
251 yield* waitForOperation(created);
252 }
253 current = yield* waitUntilExists(getByName(name), name);
254 }
255
256 if (current === undefined) {
257 return yield* new ResourceNotResolved({ resourceName: name });
258 }
259
260 const observedLabels = tagRecord(current.labels);
261 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
262 const mask = fieldMask([
263 (upsert.length > 0 || removed.length > 0) && "labels",
264 !sameText(current.description, news.description) && "description",
265 ]);
266
267 if (mask.length > 0) {
268 const operation = yield* gkebackup.patchProjectsLocationsRestoreChannels({
269 name: current.name ?? name,
270 updateMask: mask,
271 body: {
272 etag: current.etag,
273 labels: desiredLabels,
274 description: news.description,
275 },
276 });
277 yield* waitForOperation(operation);
278 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
279 }
280
281 return toAttrs(current, env.project, env.region);
282 }),
283
284 delete: Effect.fn(function* ({ output }) {
285 const operation = yield* gkebackup
286 .deleteProjectsLocationsRestoreChannels({ name: output.name })
287 .pipe(
288 Effect.retry({
289 while: (error) => error._tag === "Conflict",
290 times: 8,
291 schedule: Schedule.spaced("2 seconds"),
292 }),
293 Effect.catchTag("NotFound", () => Effect.undefined),
294 );
295 if (operation !== undefined) {
296 yield* waitForDeleteOperation(operation);
297 }
298 yield* waitUntilGone(getByName(output.name), output.name);
299 }),
300 });