@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, 04:45 UTC

main
ts 356 lines 12.4 KB
Raw
1 import * as backup from "@distilled.cloud/aws/backup";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
7 import { toWireDays, toWireMinutes } from "alchemy/Util/Duration";
8 import type * as Duration from "effect/Duration";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13
14 /**
15 * Lifecycle policy controlling when a recovery point transitions to cold
16 * storage and when it is deleted.
17 */
18 export interface BackupRuleLifecycle {
19 /**
20 * Time after creation that a recovery point is moved to cold storage,
21 * e.g. `"30 days"` (whole days on the wire). Must be at least 90 days
22 * less than `deleteAfter`.
23 */
24 moveToColdStorageAfter?: Duration.Input;
25 /**
26 * Time after creation that a recovery point is deleted, e.g. `"365 days"`
27 * (whole days on the wire).
28 */
29 deleteAfter?: Duration.Input;
30 /**
31 * Opt recovery points of supported resources into archive-tier storage.
32 */
33 optInToArchiveForSupportedResources?: boolean;
34 }
35
36 /**
37 * A single scheduled backup rule within a backup plan.
38 */
39 export interface BackupPlanRule {
40 /**
41 * Display name for the rule. Must be unique within the plan.
42 */
43 ruleName: string;
44 /**
45 * Name of the target backup vault where recovery points are stored.
46 */
47 targetBackupVaultName: string;
48 /**
49 * CRON expression (in UTC) specifying when the backup is taken, e.g.
50 * `cron(0 5 ? * * *)`. Omit for continuous backup or on-demand plans.
51 */
52 scheduleExpression?: string;
53 /**
54 * Timezone the schedule expression is evaluated in.
55 */
56 scheduleExpressionTimezone?: string;
57 /**
58 * Time after the scheduled time within which a backup must start, or it
59 * is canceled, e.g. `"1 hour"` (whole minutes on the wire).
60 */
61 startWindow?: Duration.Input;
62 /**
63 * Time within which a backup must complete, or it is canceled, e.g.
64 * `"3 hours"` (whole minutes on the wire).
65 */
66 completionWindow?: Duration.Input;
67 /**
68 * Enables continuous backups (point-in-time restore) for supported
69 * resources.
70 */
71 enableContinuousBackup?: boolean;
72 /**
73 * Lifecycle policy for the recovery points created by this rule.
74 */
75 lifecycle?: BackupRuleLifecycle;
76 /**
77 * Tags applied to recovery points created by this rule.
78 */
79 recoveryPointTags?: Record<string, string>;
80 }
81
82 export interface BackupPlanProps {
83 /**
84 * Display name of the backup plan. If omitted, a unique name is generated
85 * from the app, stage, and logical ID.
86 */
87 backupPlanName?: string;
88 /**
89 * One or more scheduled backup rules that make up the plan.
90 */
91 rules: BackupPlanRule[];
92 /**
93 * Tags to apply to the backup plan. Merged with internal Alchemy tags.
94 */
95 tags?: Record<string, string>;
96 }
97
98 export interface BackupPlan extends Resource<
99 "AWS.Backup.BackupPlan",
100 BackupPlanProps,
101 {
102 /**
103 * Service-assigned unique ID of the backup plan.
104 */
105 backupPlanId: string;
106 /**
107 * ARN of the backup plan.
108 */
109 backupPlanArn: string;
110 /**
111 * Name of the backup plan.
112 */
113 backupPlanName: string;
114 /**
115 * Version ID of the plan; updated each time the plan document changes.
116 */
117 versionId: string;
118 },
119 never,
120 Providers
121 > {}
122
123 /**
124 * An AWS Backup plan — a policy expression that defines *when* and *how* you
125 * want to back up your resources, composed of one or more scheduled rules
126 * that each target a backup vault.
127 *
128 * Pair a plan with a {@link BackupSelection} to assign the AWS resources it
129 * protects.
130 *
131 * ### Creating a Plan
132 * **Example:** Daily backups retained for 30 days
133 * ```typescript
134 * import * as Backup from "@alchemy.run/aws/Backup";
135 *
136 * const vault = yield* Backup.BackupVault("AppBackups");
137 *
138 * const plan = yield* Backup.BackupPlan("DailyPlan", {
139 * rules: [
140 * {
141 * ruleName: "DailyBackups",
142 * targetBackupVaultName: vault.backupVaultName,
143 * scheduleExpression: "cron(0 5 ? * * *)",
144 * startWindow: "1 hour",
145 * completionWindow: "3 hours",
146 * lifecycle: { deleteAfter: "30 days" },
147 * },
148 * ],
149 * });
150 * ```
151 *
152 * **Example:** Move to cold storage then delete
153 * ```typescript
154 * const plan = yield* Backup.BackupPlan("ArchivePlan", {
155 * rules: [
156 * {
157 * ruleName: "MonthlyArchive",
158 * targetBackupVaultName: vault.backupVaultName,
159 * scheduleExpression: "cron(0 5 1 * ? *)",
160 * lifecycle: {
161 * moveToColdStorageAfter: "30 days",
162 * deleteAfter: "365 days",
163 * },
164 * },
165 * ],
166 * });
167 * ```
168 *
169 * @resource
170 */
171 export const BackupPlan = Resource<BackupPlan>("AWS.Backup.BackupPlan");
172
173 const toRuleInput = (rule: BackupPlanRule): backup.BackupRuleInput => ({
174 RuleName: rule.ruleName,
175 TargetBackupVaultName: rule.targetBackupVaultName,
176 ScheduleExpression: rule.scheduleExpression,
177 ScheduleExpressionTimezone: rule.scheduleExpressionTimezone,
178 StartWindowMinutes: toWireMinutes(rule.startWindow),
179 CompletionWindowMinutes: toWireMinutes(rule.completionWindow),
180 EnableContinuousBackup: rule.enableContinuousBackup,
181 RecoveryPointTags: rule.recoveryPointTags,
182 Lifecycle: rule.lifecycle
183 ? {
184 MoveToColdStorageAfterDays: toWireDays(rule.lifecycle.moveToColdStorageAfter),
185 DeleteAfterDays: toWireDays(rule.lifecycle.deleteAfter),
186 OptInToArchiveForSupportedResources: rule.lifecycle.optInToArchiveForSupportedResources,
187 }
188 : undefined,
189 });
190
191 export const BackupPlanProvider = () =>
192 Provider.effect(
193 BackupPlan,
194 Effect.gen(function* () {
195 const createName = Effect.fn(function* (
196 id: string,
197 props: { backupPlanName?: string | undefined },
198 ) {
199 return props.backupPlanName ?? (yield* createPhysicalName({ id, maxLength: 50 }));
200 });
201
202 return BackupPlan.Provider.of({
203 stables: ["backupPlanId", "backupPlanArn"],
204 list: () =>
205 backup.listBackupPlans.pages({}).pipe(
206 Stream.runCollect,
207 Effect.map((chunk) =>
208 Array.from(chunk)
209 .flatMap((page) => page.BackupPlansList ?? [])
210 .filter(
211 (p) =>
212 p.BackupPlanId !== undefined &&
213 p.BackupPlanArn !== undefined &&
214 // Service-managed plans (e.g. EFS automatic backups'
215 // `aws/efs/automatic-backup-plan`) reject DeleteBackupPlan
216 // with AccessDenied (verified live) — keep them out of
217 // enumeration for account-wide teardown (nuke).
218 !(p.BackupPlanName ?? "").startsWith("aws/"),
219 )
220 .map((p) => ({
221 backupPlanId: p.BackupPlanId!,
222 backupPlanArn: p.BackupPlanArn!,
223 backupPlanName: p.BackupPlanName ?? "",
224 versionId: p.VersionId ?? "",
225 })),
226 ),
227 ),
228 read: Effect.fn(function* ({ id, output }) {
229 if (!output?.backupPlanId) return undefined;
230 const found = yield* backup
231 .getBackupPlan({ BackupPlanId: output.backupPlanId })
232 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
233 if (!found?.BackupPlanArn) return undefined;
234 const attrs = {
235 backupPlanId: output.backupPlanId,
236 backupPlanArn: found.BackupPlanArn,
237 backupPlanName: found.BackupPlan?.BackupPlanName ?? output.backupPlanName,
238 versionId: found.VersionId ?? output.versionId,
239 };
240 const tags = yield* backup.listTags({ ResourceArn: found.BackupPlanArn }).pipe(
241 Effect.map((r) => r.Tags ?? {}),
242 Effect.orElseSucceed(() => ({}) as Record<string, string | undefined>),
243 );
244 return (yield* hasAlchemyTags(id, tags as Record<string, string>))
245 ? attrs
246 : Unowned(attrs);
247 }),
248 reconcile: Effect.fn(function* ({ id, news = {}, output, session }) {
249 const name = output?.backupPlanName ?? (yield* createName(id, news));
250 const internalTags = yield* createInternalTags(id);
251 const backupPlanInput: backup.BackupPlanInput = {
252 BackupPlanName: name,
253 Rules: (news.rules ?? []).map(toRuleInput),
254 };
255
256 // OBSERVE — resolve the plan by its stable id when we have one.
257 const live = output?.backupPlanId
258 ? yield* backup
259 .getBackupPlan({ BackupPlanId: output.backupPlanId })
260 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined))
261 : undefined;
262
263 let backupPlanId: string;
264 let backupPlanArn: string;
265 let versionId: string;
266
267 if (!live?.BackupPlanArn) {
268 // ENSURE — create.
269 const created = yield* backup.createBackupPlan({
270 BackupPlan: backupPlanInput,
271 BackupPlanTags: { ...internalTags, ...news.tags },
272 });
273 backupPlanId = created.BackupPlanId!;
274 backupPlanArn = created.BackupPlanArn!;
275 versionId = created.VersionId ?? "";
276 } else {
277 // SYNC — a plan is a true upsert via updateBackupPlan; converge
278 // rule/name changes unconditionally (the API is idempotent).
279 backupPlanId = output!.backupPlanId!;
280 const updated = yield* backup.updateBackupPlan({
281 BackupPlanId: backupPlanId,
282 BackupPlan: backupPlanInput,
283 });
284 backupPlanArn = updated.BackupPlanArn ?? live.BackupPlanArn;
285 versionId = updated.VersionId ?? live.VersionId ?? "";
286 }
287
288 // SYNC tags — diff against observed cloud tags.
289 const currentTags = yield* backup.listTags({ ResourceArn: backupPlanArn }).pipe(
290 Effect.map((r) => r.Tags ?? {}),
291 Effect.orElseSucceed(() => ({}) as Record<string, string | undefined>),
292 );
293 const { upsert, removed } = diffTags(currentTags as Record<string, string>, {
294 ...news.tags,
295 ...internalTags,
296 });
297 if (upsert.length > 0) {
298 yield* backup.tagResource({
299 ResourceArn: backupPlanArn,
300 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
301 });
302 }
303 if (removed.length > 0) {
304 yield* backup.untagResource({
305 ResourceArn: backupPlanArn,
306 TagKeyList: removed,
307 });
308 }
309
310 yield* session.note(backupPlanId);
311 return {
312 backupPlanId,
313 backupPlanArn,
314 backupPlanName: name,
315 versionId,
316 };
317 }),
318 delete: Effect.fn(function* ({ output }) {
319 // A plan cannot be deleted while it still has resource selections
320 // attached — delete those first (idempotent: a vanished selection
321 // is already gone).
322 const selections = yield* backup.listBackupSelections
323 .pages({ BackupPlanId: output.backupPlanId })
324 .pipe(
325 Stream.runCollect,
326 Effect.map((chunk) =>
327 Array.from(chunk).flatMap((page) => page.BackupSelectionsList ?? []),
328 ),
329 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([])),
330 );
331 yield* Effect.forEach(
332 selections,
333 (s) =>
334 s.SelectionId
335 ? backup
336 .deleteBackupSelection({
337 BackupPlanId: output.backupPlanId,
338 SelectionId: s.SelectionId,
339 })
340 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void))
341 : Effect.void,
342 { discard: true },
343 );
344 yield* backup.deleteBackupPlan({ BackupPlanId: output.backupPlanId }).pipe(
345 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
346 // Selection deletion is eventually consistent; the plan delete
347 // rejects with InvalidRequestException until it settles.
348 Effect.retry({
349 while: (e) => e._tag === "InvalidRequestException",
350 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
351 }),
352 );
353 }),
354 });
355 }),
356 );