@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, 06:00 UTC

main
ts 405 lines 13.9 KB
Raw
1 import * as spanner from "@distilled.cloud/gcp/spanner_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 * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 backupScheduleName,
14 databaseIdOf,
15 databaseName,
16 instanceIdOf,
17 instanceName,
18 listAlchemyDatabases,
19 MAX_BACKUP_SCHEDULE_ID_LENGTH,
20 parentOwned,
21 parseResourceName,
22 retryConcurrentChanges,
23 toPhysicalId,
24 } from "./operations.ts";
25
26 const DEFAULT_CRON = "0 2 * * *";
27 const DEFAULT_RETENTION = "604800s";
28
29 export type BackupScheduleEncryptionConfig = {
30 /**
31 * Encryption type (`USE_DATABASE_ENCRYPTION`,
32 * `GOOGLE_DEFAULT_ENCRYPTION`, `CUSTOMER_MANAGED_ENCRYPTION`).
33 */
34 encryptionType?: spanner.CreateBackupEncryptionConfigEncryptionTypeEnum | (string & {});
35 /** Cloud KMS key. Prefer `kmsKeyNames` for new schedules. */
36 kmsKeyName?: string;
37 /** Cloud KMS keys covering every region of the instance config. */
38 kmsKeyNames?: string[];
39 };
40
41 export type BackupScheduleSpec = {
42 /**
43 * Cron schedule in UTC. Full backups must be at least 12 hours
44 * apart; incremental backups at least 4 hours apart.
45 * @default "0 2 * * *"
46 */
47 cron?: string;
48 };
49
50 export type InstancesDatabasesBackupScheduleProps = {
51 /**
52 * Parent instance id or full name. Immutable — changing it replaces
53 * the schedule.
54 */
55 instance: string;
56 /**
57 * Parent database id or full name. Immutable — changing it replaces
58 * the schedule.
59 */
60 database: string;
61 /**
62 * Backup schedule id (the `{schedule}` segment of
63 * `.../databases/{database}/backupSchedules/{schedule}`). If omitted,
64 * a unique name is generated. Must match `^[a-z][-a-z0-9]*[a-z0-9]$`
65 * (2–60 characters). Immutable — changing it replaces the schedule.
66 */
67 backupScheduleId?: string;
68 /**
69 * Cron-style schedule specification.
70 */
71 spec?: BackupScheduleSpec;
72 /**
73 * Retention duration of created backups (`604800s` is 7 days). Must
74 * be at least 6 hours and at most 366 days.
75 * @default "604800s"
76 */
77 retentionDuration?: string;
78 /**
79 * Encryption applied to backups created by this schedule.
80 */
81 encryptionConfig?: BackupScheduleEncryptionConfig;
82 /**
83 * When true, create incremental backup chains (Enterprise Plus).
84 * Default creates full backups. Immutable — changing it replaces
85 * the schedule.
86 * @default false
87 */
88 incremental?: boolean;
89 };
90
91 export type InstancesDatabasesBackupSchedule = Resource<
92 "GCP.Spanner.InstancesDatabasesBackupSchedule",
93 InstancesDatabasesBackupScheduleProps,
94 {
95 /** Full resource name `.../databases/{database}/backupSchedules/{schedule}`. */
96 name: string;
97 /** Backup schedule id (last path segment). */
98 backupScheduleId: string;
99 /** Parent database id. */
100 databaseId: string;
101 /** Parent instance id. */
102 instanceId: string;
103 /** Project id. */
104 project: string;
105 /** Cron text, if set. */
106 cron: string | undefined;
107 /** Cron time zone (UTC). */
108 timeZone: string | undefined;
109 /** Creation window after the version time. */
110 creationWindow: string | undefined;
111 /** Retention duration. */
112 retentionDuration: string | undefined;
113 /** Encryption configuration. */
114 encryptionConfig: BackupScheduleEncryptionConfig | undefined;
115 /** Whether the schedule creates incremental chains. */
116 incremental: boolean;
117 /** RFC3339 last-update timestamp. */
118 updateTime: string | undefined;
119 },
120 never,
121 Providers
122 >;
123
124 /**
125 * An automated backup schedule on a Cloud Spanner database.
126 *
127 * Schedules have no labels field. Alchemy treats a schedule as owned
128 * when its parent instance carries Alchemy labels, so `list` /
129 * `pnpm nuke:gcp` can find it. Changing `backupScheduleId`, `instance`,
130 * `database`, or `incremental` replaces the schedule. Cron, retention,
131 * and encryption update in place.
132 *
133 * ### Creating a Backup Schedule
134 * **Example:** Daily full backup retained for 7 days
135 * ```typescript
136 * const schedule = yield* GCP.Spanner.InstancesDatabasesBackupSchedule(
137 * "Nightly",
138 * {
139 * instance: instance.instanceId,
140 * database: database.databaseId,
141 * spec: { cron: "0 2 * * *" },
142 * retentionDuration: "604800s",
143 * },
144 * );
145 * ```
146 *
147 * **Example:** Explicit id
148 * ```typescript
149 * const schedule = yield* GCP.Spanner.InstancesDatabasesBackupSchedule(
150 * "Nightly",
151 * {
152 * instance: instance.name,
153 * database: database.name,
154 * backupScheduleId: "nightly",
155 * spec: { cron: "0 2 * * 0" },
156 * retentionDuration: "1209600s",
157 * },
158 * );
159 * ```
160 *
161 * @resource
162 * @category Spanner
163 */
164 export const InstancesDatabasesBackupSchedule = Resource<InstancesDatabasesBackupSchedule>(
165 "GCP.Spanner.InstancesDatabasesBackupSchedule",
166 );
167
168 export class BackupScheduleNotResolved extends Data.TaggedError(
169 "GCP.Spanner.BackupScheduleNotResolved",
170 )<{
171 resourceName: string;
172 }> {}
173
174 const toId = (id: string, backupScheduleId: string | undefined, existing?: string) =>
175 toPhysicalId(id, backupScheduleId, existing, MAX_BACKUP_SCHEDULE_ID_LENGTH);
176
177 const encryptionOf = (
178 config: spanner.CreateBackupEncryptionConfig | undefined,
179 ): BackupScheduleEncryptionConfig | undefined => {
180 if (config === undefined) return undefined;
181 if (
182 config.encryptionType === undefined &&
183 (config.kmsKeyName === undefined || config.kmsKeyName.length === 0) &&
184 (config.kmsKeyNames === undefined || config.kmsKeyNames.length === 0)
185 ) {
186 return undefined;
187 }
188 return {
189 encryptionType: config.encryptionType,
190 kmsKeyName: config.kmsKeyName,
191 kmsKeyNames: config.kmsKeyNames,
192 };
193 };
194
195 const encryptionKey = (config: BackupScheduleEncryptionConfig | undefined) =>
196 JSON.stringify({
197 encryptionType: (config?.encryptionType ?? "").toUpperCase(),
198 kmsKeyName: config?.kmsKeyName ?? "",
199 kmsKeyNames: [...(config?.kmsKeyNames ?? [])].sort(),
200 });
201
202 const toAttrs = (
203 schedule: spanner.BackupSchedule,
204 project: string,
205 ): InstancesDatabasesBackupSchedule["Attributes"] => {
206 const name = schedule.name ?? "";
207 const parsed = parseResourceName(name);
208 return {
209 name,
210 backupScheduleId: parsed.backupScheduleId,
211 databaseId: parsed.databaseId,
212 instanceId: parsed.instanceId,
213 project: parsed.project || project,
214 cron: schedule.spec?.cronSpec?.text,
215 timeZone: schedule.spec?.cronSpec?.timeZone,
216 creationWindow: schedule.spec?.cronSpec?.creationWindow,
217 retentionDuration: schedule.retentionDuration,
218 encryptionConfig: encryptionOf(schedule.encryptionConfig),
219 incremental: schedule.incrementalBackupSpec !== undefined,
220 updateTime: schedule.updateTime,
221 };
222 };
223
224 const getByName = (name: string) =>
225 spanner
226 .getProjectsInstancesDatabasesBackupSchedules({ name })
227 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
228
229 const toBody = (news: InstancesDatabasesBackupScheduleProps): spanner.BackupSchedule => {
230 const incremental = news.incremental === true;
231 const body: spanner.BackupSchedule = {
232 spec: {
233 cronSpec: {
234 text: news.spec?.cron ?? DEFAULT_CRON,
235 },
236 },
237 retentionDuration: news.retentionDuration ?? DEFAULT_RETENTION,
238 encryptionConfig: news.encryptionConfig,
239 };
240 if (incremental) {
241 body.incrementalBackupSpec = {};
242 } else {
243 body.fullBackupSpec = {};
244 }
245 return body;
246 };
247
248 export const InstancesDatabasesBackupScheduleProvider = () =>
249 Provider.succeed(InstancesDatabasesBackupSchedule, {
250 stables: ["name", "backupScheduleId", "databaseId", "instanceId", "project"],
251
252 diff: Effect.fn(function* ({ news, olds, output }) {
253 if (!isResolved(news)) return undefined;
254
255 const previousId = olds?.backupScheduleId ?? output?.backupScheduleId;
256 const nextId = news.backupScheduleId ?? previousId;
257 const previousInstance = instanceIdOf(olds?.instance ?? output?.instanceId ?? "");
258 const nextInstance = instanceIdOf(news.instance);
259 const previousDatabase = databaseIdOf(olds?.database ?? output?.databaseId ?? "");
260 const nextDatabase = databaseIdOf(news.database);
261 const previousIncremental = olds?.incremental ?? output?.incremental;
262 const nextIncremental = news.incremental ?? previousIncremental;
263
264 const replace =
265 (previousId !== undefined && nextId !== undefined && previousId !== nextId) ||
266 (previousInstance.length > 0 && previousInstance !== nextInstance) ||
267 (previousDatabase.length > 0 && previousDatabase !== nextDatabase) ||
268 (previousIncremental !== undefined &&
269 nextIncremental !== undefined &&
270 previousIncremental !== nextIncremental);
271
272 if (!replace) return undefined;
273 return { action: "replace" as const };
274 }),
275
276 read: Effect.fn(function* ({ id, olds, output }) {
277 const env = yield* GcpEnvironment.current;
278 const backupScheduleId = yield* toId(id, olds?.backupScheduleId, output?.backupScheduleId);
279 const instanceId = instanceIdOf(olds?.instance ?? output?.instanceId ?? "");
280 const databaseId = databaseIdOf(olds?.database ?? output?.databaseId ?? "");
281 if (instanceId.length === 0 || databaseId.length === 0) return undefined;
282 const name =
283 output?.name ?? backupScheduleName(env.project, instanceId, databaseId, backupScheduleId);
284 const existing = yield* getByName(name);
285 if (existing === undefined) return undefined;
286 const attrs = toAttrs(existing, env.project);
287 return (yield* parentOwned(instanceName(attrs.project, attrs.instanceId)))
288 ? attrs
289 : Unowned(attrs);
290 }),
291
292 list: () =>
293 Effect.gen(function* () {
294 const env = yield* GcpEnvironment.current;
295 const databases = yield* listAlchemyDatabases(env.project);
296 const pages = yield* Effect.forEach(
297 databases,
298 (database) => {
299 const parent = database.name;
300 if (parent === undefined || parent.length === 0) {
301 return Effect.succeed([] as InstancesDatabasesBackupSchedule["Attributes"][]);
302 }
303 return spanner.listProjectsInstancesDatabasesBackupSchedules
304 .pages({
305 parent,
306 pageSize: 1000,
307 })
308 .pipe(
309 Stream.flatMap((page) => Stream.fromIterable(page.backupSchedules ?? [])),
310 Stream.map((schedule) => toAttrs(schedule, env.project)),
311 Stream.runCollect,
312 Effect.map((chunk) => Array.from(chunk)),
313 Effect.catchTag("NotFound", () =>
314 Effect.succeed([] as InstancesDatabasesBackupSchedule["Attributes"][]),
315 ),
316 );
317 },
318 { concurrency: 4 },
319 );
320 return pages.flat();
321 }),
322
323 reconcile: Effect.fn(function* ({ id, news, output }) {
324 const env = yield* GcpEnvironment.current;
325 const instanceId = instanceIdOf(news.instance);
326 const databaseId = databaseIdOf(news.database);
327 const backupScheduleId = yield* toId(id, news.backupScheduleId, output?.backupScheduleId);
328 const parent = databaseName(env.project, instanceId, databaseId);
329 const name = backupScheduleName(env.project, instanceId, databaseId, backupScheduleId);
330 const desiredCron = news.spec?.cron ?? DEFAULT_CRON;
331 const desiredRetention = news.retentionDuration ?? DEFAULT_RETENTION;
332
333 let current = yield* getByName(output?.name ?? name);
334
335 if (current === undefined) {
336 current = yield* spanner
337 .createProjectsInstancesDatabasesBackupSchedules({
338 parent,
339 backupScheduleId,
340 body: toBody(news),
341 })
342 .pipe(
343 Effect.catchTag("Conflict", () => getByName(name)),
344 Effect.flatMap((schedule) =>
345 schedule
346 ? Effect.succeed(schedule)
347 : Effect.fail(new BackupScheduleNotResolved({ resourceName: name })),
348 ),
349 );
350 }
351
352 const observedCron = current.spec?.cronSpec?.text ?? "";
353 const observedRetention = current.retentionDuration ?? "";
354 const encryptionChanged =
355 news.encryptionConfig !== undefined &&
356 encryptionKey(encryptionOf(current.encryptionConfig)) !==
357 encryptionKey(news.encryptionConfig);
358 const cronChanged = observedCron !== desiredCron;
359 const retentionChanged = observedRetention !== desiredRetention;
360
361 if (cronChanged || retentionChanged || encryptionChanged) {
362 const fieldMask = [
363 cronChanged ? "spec.cron_spec.text" : undefined,
364 retentionChanged ? "retention_duration" : undefined,
365 encryptionChanged ? "encryption_config" : undefined,
366 ].filter((field): field is string => field !== undefined);
367 const patchBody: spanner.BackupSchedule = {
368 name,
369 };
370 if (cronChanged) {
371 patchBody.spec = { cronSpec: { text: desiredCron } };
372 }
373 if (retentionChanged) {
374 patchBody.retentionDuration = desiredRetention;
375 }
376 if (encryptionChanged) {
377 patchBody.encryptionConfig = news.encryptionConfig;
378 }
379 current = yield* retryConcurrentChanges(
380 spanner.patchProjectsInstancesDatabasesBackupSchedules({
381 name,
382 updateMask: fieldMask.join(","),
383 body: patchBody,
384 }),
385 );
386 }
387
388 return toAttrs(current, env.project);
389 }),
390
391 delete: Effect.fn(function* ({ output }) {
392 yield* spanner
393 .deleteProjectsInstancesDatabasesBackupSchedules({
394 name: output.name,
395 })
396 .pipe(
397 Effect.catchTag("NotFound", () => Effect.void),
398 Effect.retry({
399 while: (error) => error._tag === "Conflict",
400 times: 8,
401 schedule: Schedule.spaced("2 seconds"),
402 }),
403 );
404 }),
405 });