@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 884 lines 30.9 KB
Raw
1 import * as dlm from "@distilled.cloud/aws/dlm";
2 import * as iam from "@distilled.cloud/aws/iam";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import type { Providers } from "../Providers.ts";
12
13 /**
14 * The activation state of a lifecycle policy. `ERROR` is only ever observed
15 * (e.g. when the execution role was deleted out-of-band) — it cannot be set.
16 */
17 export type LifecyclePolicyState = "ENABLED" | "DISABLED" | "ERROR";
18
19 /**
20 * The policy type. `EBS_SNAPSHOT_MANAGEMENT` manages the lifecycle of EBS
21 * snapshots; `IMAGE_MANAGEMENT` manages the lifecycle of EBS-backed AMIs.
22 */
23 export type LifecyclePolicyType = "EBS_SNAPSHOT_MANAGEMENT" | "IMAGE_MANAGEMENT";
24
25 /** Unit for retention intervals. */
26 export type LifecyclePolicyRetentionUnit = "DAYS" | "WEEKS" | "MONTHS" | "YEARS";
27
28 export interface LifecyclePolicyCreateRule {
29 /**
30 * Where snapshots are created for policies targeting resources on an
31 * Outpost or in a Local Zone.
32 * @default "CLOUD"
33 */
34 location?: "CLOUD" | "OUTPOST_LOCAL" | "LOCAL_ZONE";
35 /**
36 * The interval between policy runs, in `intervalUnit` units (`1`, `2`,
37 * `3`, `4`, `6`, `8`, `12` or `24` hours). Mutually exclusive with
38 * `cronExpression`.
39 */
40 interval?: number;
41 /**
42 * The unit for {@link LifecyclePolicyCreateRule.interval}.
43 * @default "HOURS"
44 */
45 intervalUnit?: "HOURS";
46 /**
47 * The time(s) of day (UTC, `HH:MM`) the policy runs when using
48 * interval-based scheduling.
49 */
50 times?: string[];
51 /**
52 * A cron expression (`cron(...)`, intervals of at least 1 hour) that
53 * defines when the policy runs. Mutually exclusive with `interval`.
54 */
55 cronExpression?: string;
56 }
57
58 export interface LifecyclePolicyRetainRule {
59 /**
60 * Number of snapshots/AMIs to retain per volume/instance (`1` - `1000`).
61 * Mutually exclusive with `interval`/`intervalUnit`.
62 */
63 count?: number;
64 /**
65 * Age-based retention interval. Mutually exclusive with `count`.
66 */
67 interval?: number;
68 /**
69 * The unit for {@link LifecyclePolicyRetainRule.interval}.
70 */
71 intervalUnit?: LifecyclePolicyRetentionUnit;
72 }
73
74 export interface LifecyclePolicyFastRestoreRule {
75 /**
76 * Number of snapshots to keep fast-restore enabled for. Mutually
77 * exclusive with `interval`.
78 */
79 count?: number;
80 /**
81 * Age-based fast-restore window. Mutually exclusive with `count`.
82 */
83 interval?: number;
84 /** The unit for `interval`. */
85 intervalUnit?: LifecyclePolicyRetentionUnit;
86 /** Availability Zones in which to enable fast snapshot restore. */
87 availabilityZones?: string[];
88 }
89
90 export interface LifecyclePolicyCrossRegionCopyRule {
91 /**
92 * The target region (e.g. `us-east-1`) or the ARN of a target Outpost
93 * for the snapshot/AMI copies.
94 */
95 target: string;
96 /**
97 * Whether the copies are encrypted. Copies of encrypted sources are
98 * always encrypted regardless of this setting.
99 */
100 encrypted: boolean;
101 /**
102 * The ARN of the KMS key to use for the copies when encryption is
103 * enabled. Defaults to the default EBS KMS key when omitted.
104 */
105 cmkArn?: string;
106 /**
107 * Whether tags on the source are copied to the cross-region copies.
108 * @default false
109 */
110 copyTags?: boolean;
111 /** Retention rule for the cross-region copies. */
112 retainRule?: {
113 /** How long to retain the copies. */
114 interval?: number;
115 /** The unit for `interval`. */
116 intervalUnit?: LifecyclePolicyRetentionUnit;
117 };
118 /**
119 * AMI deprecation rule for the cross-region AMI copies
120 * (`IMAGE_MANAGEMENT` policies only).
121 */
122 deprecateRule?: {
123 /** How long before the AMI copies are deprecated. */
124 interval?: number;
125 /** The unit for `interval`. */
126 intervalUnit?: LifecyclePolicyRetentionUnit;
127 };
128 }
129
130 export interface LifecyclePolicyShareRule {
131 /** IDs of the AWS accounts to share the snapshots with. */
132 targetAccounts: string[];
133 /** Period after which the snapshots are unshared. */
134 unshareInterval?: number;
135 /** The unit for `unshareInterval`. */
136 unshareIntervalUnit?: LifecyclePolicyRetentionUnit;
137 }
138
139 export interface LifecyclePolicySchedule {
140 /** Name of the schedule (`0` - `120` characters). */
141 name?: string;
142 /**
143 * Whether tags are copied from the source volume/instance to the
144 * snapshot/AMI.
145 * @default false
146 */
147 copyTags?: boolean;
148 /** Tags added to every snapshot/AMI created by this schedule. */
149 tagsToAdd?: Record<string, string>;
150 /**
151 * Variable tags added to snapshots (`EBS_SNAPSHOT_MANAGEMENT` policies
152 * targeting instances only). Values may use `$(instance-id)` and
153 * `$(timestamp)`.
154 */
155 variableTags?: Record<string, string>;
156 /** When the schedule creates snapshots/AMIs. */
157 createRule?: LifecyclePolicyCreateRule;
158 /** How long the snapshots/AMIs are retained. */
159 retainRule?: LifecyclePolicyRetainRule;
160 /**
161 * Fast snapshot restore rule (`EBS_SNAPSHOT_MANAGEMENT` policies only).
162 */
163 fastRestoreRule?: LifecyclePolicyFastRestoreRule;
164 /** Cross-region copy rules (up to 3). */
165 crossRegionCopyRules?: LifecyclePolicyCrossRegionCopyRule[];
166 /**
167 * Snapshot sharing rules (`EBS_SNAPSHOT_MANAGEMENT` policies only).
168 */
169 shareRules?: LifecyclePolicyShareRule[];
170 /**
171 * AMI deprecation rule (`IMAGE_MANAGEMENT` policies only). Mutually
172 * exclusive constraints mirror the retain rule (`count` vs `interval`).
173 */
174 deprecateRule?: {
175 /** Number of newest AMIs to keep un-deprecated. */
176 count?: number;
177 /** Age after which AMIs are deprecated. */
178 interval?: number;
179 /** The unit for `interval`. */
180 intervalUnit?: LifecyclePolicyRetentionUnit;
181 };
182 /**
183 * Snapshot archiving rule (`EBS_SNAPSHOT_MANAGEMENT` policies with
184 * count-based retention only).
185 */
186 archiveRule?: {
187 /** Retention for snapshots in the archive tier. */
188 retainRule: {
189 /** Archive-tier retention settings. */
190 retentionArchiveTier: {
191 /** Number of snapshots to retain in the archive tier. */
192 count?: number;
193 /** Age-based archive-tier retention. */
194 interval?: number;
195 /** The unit for `interval`. */
196 intervalUnit?: LifecyclePolicyRetentionUnit;
197 };
198 };
199 };
200 }
201
202 export interface LifecyclePolicyDetails {
203 /**
204 * The policy type. Changing the type triggers a replacement.
205 * @default "EBS_SNAPSHOT_MANAGEMENT"
206 */
207 policyType?: LifecyclePolicyType;
208 /**
209 * The resource type targeted by the policy. `VOLUME` creates snapshots
210 * of individual volumes; `INSTANCE` creates multi-volume snapshot sets
211 * (or AMIs for `IMAGE_MANAGEMENT`).
212 */
213 resourceTypes?: ("VOLUME" | "INSTANCE")[];
214 /**
215 * The location of the targeted resources.
216 * @default ["CLOUD"]
217 */
218 resourceLocations?: ("CLOUD" | "OUTPOST" | "LOCAL_ZONE")[];
219 /**
220 * The resource tags that identify the volumes/instances the policy
221 * applies to.
222 */
223 targetTags?: Record<string, string>;
224 /** The schedules (1 mandatory + up to 3 optional). */
225 schedules?: LifecyclePolicySchedule[];
226 /** Options specific to the policy/resource type. */
227 parameters?: {
228 /**
229 * Exclude the boot volume from multi-volume snapshot sets
230 * (`EBS_SNAPSHOT_MANAGEMENT` targeting instances only).
231 * @default false
232 */
233 excludeBootVolume?: boolean;
234 /**
235 * Skip rebooting the instance when creating AMIs
236 * (`IMAGE_MANAGEMENT` only).
237 * @default true
238 */
239 noReboot?: boolean;
240 /**
241 * Exclude data volumes with these tags from multi-volume snapshot
242 * sets (`EBS_SNAPSHOT_MANAGEMENT` targeting instances only).
243 */
244 excludeDataVolumeTags?: Record<string, string>;
245 };
246 }
247
248 export interface LifecyclePolicyProps {
249 /**
250 * Description of the policy (`0` - `500` characters; letters, digits,
251 * spaces, `_` and `-`). If omitted, a deterministic description is
252 * generated from the app, stage, and logical ID.
253 */
254 description?: string;
255 /**
256 * The activation state of the policy.
257 * @default "ENABLED"
258 */
259 state?: "ENABLED" | "DISABLED";
260 /**
261 * The ARN of an existing IAM role Amazon Data Lifecycle Manager assumes
262 * to run the policy. When omitted, an execution role is created
263 * automatically with `dlm.amazonaws.com` trust and the AWS managed
264 * policy matching the policy type (`AWSDataLifecycleManagerServiceRole`
265 * for snapshot policies, `AWSDataLifecycleManagerServiceRoleForAMIManagement`
266 * for AMI policies).
267 */
268 executionRoleArn?: string;
269 /**
270 * The configuration of the policy: what it targets and when/how it
271 * creates and retains snapshots or AMIs.
272 */
273 policyDetails: LifecyclePolicyDetails;
274 /**
275 * Tags to apply to the lifecycle policy. Merged with internal Alchemy
276 * tags.
277 */
278 tags?: Record<string, string>;
279 }
280
281 export interface LifecyclePolicy extends Resource<
282 "AWS.DLM.LifecyclePolicy",
283 LifecyclePolicyProps,
284 {
285 /** The auto-assigned ID of the policy (e.g. `policy-0123456789abcdef0`). */
286 policyId: string;
287 /** ARN of the policy. */
288 policyArn: string;
289 /** The activation state of the policy. */
290 state: LifecyclePolicyState;
291 /** The ARN of the IAM role the policy runs as. */
292 executionRoleArn: string;
293 /**
294 * Name of the auto-created execution role. `undefined` when an
295 * explicit {@link LifecyclePolicyProps.executionRoleArn} is used.
296 */
297 roleName: string | undefined;
298 },
299 never,
300 Providers
301 > {}
302
303 /**
304 * An Amazon Data Lifecycle Manager (DLM) lifecycle policy that automates the
305 * creation, retention, and deletion of EBS snapshots or EBS-backed AMIs.
306 *
307 * `LifecyclePolicy` owns a custom `EBS_SNAPSHOT_MANAGEMENT` or
308 * `IMAGE_MANAGEMENT` policy. Volumes/instances are targeted by tags, and an
309 * execution role is created automatically unless an explicit
310 * `executionRoleArn` is given.
311 * ### Creating Policies
312 * **Example:** Daily EBS snapshots retained for a week
313 * ```typescript
314 * import * as DLM from "@alchemy.run/aws/DLM";
315 *
316 * const policy = yield* DLM.LifecyclePolicy("DailySnapshots", {
317 * policyDetails: {
318 * resourceTypes: ["VOLUME"],
319 * targetTags: { Backup: "daily" },
320 * schedules: [
321 * {
322 * name: "Daily",
323 * createRule: { interval: 24, intervalUnit: "HOURS", times: ["03:00"] },
324 * retainRule: { count: 7 },
325 * },
326 * ],
327 * },
328 * });
329 * ```
330 *
331 * **Example:** Cron-scheduled snapshots
332 * ```typescript
333 * const policy = yield* DLM.LifecyclePolicy("WeeklySnapshots", {
334 * description: "Weekly volume snapshots",
335 * policyDetails: {
336 * resourceTypes: ["VOLUME"],
337 * targetTags: { Backup: "weekly" },
338 * schedules: [
339 * {
340 * name: "Weekly",
341 * copyTags: true,
342 * createRule: { cronExpression: "cron(0 4 ? * SUN *)" },
343 * retainRule: { interval: 1, intervalUnit: "MONTHS" },
344 * },
345 * ],
346 * },
347 * });
348 * ```
349 *
350 * ### AMI Policies
351 * **Example:** EBS-backed AMIs of tagged instances
352 * ```typescript
353 * const amis = yield* DLM.LifecyclePolicy("NightlyAmis", {
354 * policyDetails: {
355 * policyType: "IMAGE_MANAGEMENT",
356 * resourceTypes: ["INSTANCE"],
357 * targetTags: { Backup: "ami" },
358 * parameters: { noReboot: true },
359 * schedules: [
360 * {
361 * name: "Nightly",
362 * createRule: { interval: 24, intervalUnit: "HOURS", times: ["05:00"] },
363 * retainRule: { count: 3 },
364 * },
365 * ],
366 * },
367 * });
368 * ```
369 *
370 * ### Execution Role
371 * **Example:** Bring your own execution role
372 * ```typescript
373 * const role = yield* IAM.Role("DlmRole", {
374 * assumeRolePolicyDocument: {
375 * Version: "2012-10-17",
376 * Statement: [
377 * {
378 * Effect: "Allow",
379 * Principal: { Service: "dlm.amazonaws.com" },
380 * Action: "sts:AssumeRole",
381 * },
382 * ],
383 * },
384 * managedPolicyArns: [
385 * "arn:aws:iam::aws:policy/service-role/AWSDataLifecycleManagerServiceRole",
386 * ],
387 * });
388 *
389 * const policy = yield* DLM.LifecyclePolicy("Snapshots", {
390 * executionRoleArn: role.roleArn,
391 * state: "DISABLED",
392 * policyDetails: {
393 * resourceTypes: ["VOLUME"],
394 * targetTags: { Backup: "true" },
395 * schedules: [
396 * {
397 * name: "Daily",
398 * createRule: { interval: 24, intervalUnit: "HOURS" },
399 * retainRule: { count: 2 },
400 * },
401 * ],
402 * },
403 * });
404 * ```
405 *
406 * @resource
407 */
408 export const LifecyclePolicy = Resource<LifecyclePolicy>("AWS.DLM.LifecyclePolicy");
409
410 /** AWS managed policy granting DLM the permissions for snapshot policies. */
411 const SNAPSHOT_MANAGED_POLICY_ARN =
412 "arn:aws:iam::aws:policy/service-role/AWSDataLifecycleManagerServiceRole";
413
414 /** AWS managed policy granting DLM the permissions for AMI policies. */
415 const AMI_MANAGED_POLICY_ARN =
416 "arn:aws:iam::aws:policy/service-role/AWSDataLifecycleManagerServiceRoleForAMIManagement";
417
418 /** Convert a tag record to the DLM wire tag list, sorted for stable diffs. */
419 const toWireTagList = (tags: Record<string, string> | undefined): dlm.Tag[] | undefined =>
420 tags === undefined
421 ? undefined
422 : Object.entries(tags)
423 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
424 .map(([Key, Value]) => ({ Key, Value }));
425
426 /** Convert a wire tag map (values possibly undefined) to a plain record. */
427 const fromWireTagMap = (
428 tags: { [key: string]: string | undefined } | undefined,
429 ): Record<string, string> =>
430 Object.fromEntries(
431 Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
432 );
433
434 /** Map the camelCase schedule props to the DLM wire shape. */
435 const toWireSchedule = (schedule: LifecyclePolicySchedule): dlm.Schedule => ({
436 Name: schedule.name,
437 CopyTags: schedule.copyTags,
438 TagsToAdd: toWireTagList(schedule.tagsToAdd),
439 VariableTags: toWireTagList(schedule.variableTags),
440 CreateRule:
441 schedule.createRule === undefined
442 ? undefined
443 : {
444 Location: schedule.createRule.location,
445 Interval: schedule.createRule.interval,
446 IntervalUnit: schedule.createRule.intervalUnit,
447 Times: schedule.createRule.times,
448 CronExpression: schedule.createRule.cronExpression,
449 },
450 RetainRule:
451 schedule.retainRule === undefined
452 ? undefined
453 : {
454 Count: schedule.retainRule.count,
455 Interval: schedule.retainRule.interval,
456 IntervalUnit: schedule.retainRule.intervalUnit,
457 },
458 FastRestoreRule:
459 schedule.fastRestoreRule === undefined
460 ? undefined
461 : {
462 Count: schedule.fastRestoreRule.count,
463 Interval: schedule.fastRestoreRule.interval,
464 IntervalUnit: schedule.fastRestoreRule.intervalUnit,
465 AvailabilityZones: schedule.fastRestoreRule.availabilityZones,
466 },
467 CrossRegionCopyRules: schedule.crossRegionCopyRules?.map((rule) => ({
468 Target: rule.target,
469 Encrypted: rule.encrypted,
470 CmkArn: rule.cmkArn,
471 CopyTags: rule.copyTags,
472 RetainRule:
473 rule.retainRule === undefined
474 ? undefined
475 : {
476 Interval: rule.retainRule.interval,
477 IntervalUnit: rule.retainRule.intervalUnit,
478 },
479 DeprecateRule:
480 rule.deprecateRule === undefined
481 ? undefined
482 : {
483 Interval: rule.deprecateRule.interval,
484 IntervalUnit: rule.deprecateRule.intervalUnit,
485 },
486 })),
487 ShareRules: schedule.shareRules?.map((rule) => ({
488 TargetAccounts: rule.targetAccounts,
489 UnshareInterval: rule.unshareInterval,
490 UnshareIntervalUnit: rule.unshareIntervalUnit,
491 })),
492 DeprecateRule:
493 schedule.deprecateRule === undefined
494 ? undefined
495 : {
496 Count: schedule.deprecateRule.count,
497 Interval: schedule.deprecateRule.interval,
498 IntervalUnit: schedule.deprecateRule.intervalUnit,
499 },
500 ArchiveRule:
501 schedule.archiveRule === undefined
502 ? undefined
503 : {
504 RetainRule: {
505 RetentionArchiveTier: {
506 Count: schedule.archiveRule.retainRule.retentionArchiveTier.count,
507 Interval: schedule.archiveRule.retainRule.retentionArchiveTier.interval,
508 IntervalUnit: schedule.archiveRule.retainRule.retentionArchiveTier.intervalUnit,
509 },
510 },
511 },
512 });
513
514 /** Map the camelCase policy details props to the DLM wire shape. */
515 const toWirePolicyDetails = (details: LifecyclePolicyDetails): dlm.PolicyDetails => ({
516 PolicyType: details.policyType ?? "EBS_SNAPSHOT_MANAGEMENT",
517 ResourceTypes: details.resourceTypes,
518 ResourceLocations: details.resourceLocations,
519 TargetTags: toWireTagList(details.targetTags),
520 Schedules: details.schedules?.map(toWireSchedule),
521 Parameters:
522 details.parameters === undefined
523 ? undefined
524 : {
525 ExcludeBootVolume: details.parameters.excludeBootVolume,
526 NoReboot: details.parameters.noReboot,
527 ExcludeDataVolumeTags: toWireTagList(details.parameters.excludeDataVolumeTags),
528 },
529 });
530
531 /**
532 * Canonicalize a wire value for drift comparison: drop `undefined` members,
533 * sort object keys, and sort `{Key, Value}` tag lists by key so record-order
534 * differences never register as drift.
535 */
536 const canonicalize = (value: unknown): unknown => {
537 if (Array.isArray(value)) {
538 const items = value.map(canonicalize);
539 const isTagList = items.every(
540 (item) =>
541 item !== null &&
542 typeof item === "object" &&
543 !Array.isArray(item) &&
544 Object.keys(item).every((k) => k === "Key" || k === "Value"),
545 );
546 return isTagList
547 ? [...items].sort((a, b) => {
548 const ak = (a as { Key?: string }).Key ?? "";
549 const bk = (b as { Key?: string }).Key ?? "";
550 return ak < bk ? -1 : ak > bk ? 1 : 0;
551 })
552 : items;
553 }
554 if (value !== null && typeof value === "object") {
555 return Object.fromEntries(
556 Object.entries(value as Record<string, unknown>)
557 .filter(([, v]) => v !== undefined)
558 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
559 .map(([k, v]) => [k, canonicalize(v)]),
560 );
561 }
562 return value;
563 };
564
565 /**
566 * Project the observed value down to the keys present in the desired value,
567 * recursively. DLM normalizes policies on read (adding defaults like
568 * `PolicyLanguage`, `ResourceLocations`, or `CopyTags: false`), so comparing
569 * the full observed document against our sparse desired document would flag
570 * drift on every reconcile. Keys we do not manage are ignored.
571 */
572 const projectToDesired = (desired: unknown, observed: unknown): unknown => {
573 if (Array.isArray(desired)) {
574 if (!Array.isArray(observed)) return observed;
575 if (desired.length !== observed.length) return observed;
576 return desired.map((item, i) => projectToDesired(item, observed[i]));
577 }
578 if (
579 desired !== null &&
580 typeof desired === "object" &&
581 observed !== null &&
582 typeof observed === "object" &&
583 !Array.isArray(observed)
584 ) {
585 return Object.fromEntries(
586 Object.entries(desired as Record<string, unknown>)
587 .filter(([, v]) => v !== undefined)
588 .map(([k, v]) => [k, projectToDesired(v, (observed as Record<string, unknown>)[k])]),
589 );
590 }
591 return observed;
592 };
593
594 /** Whether the observed wire document drifted from the desired one. */
595 const policyDetailsDrifted = (
596 desired: dlm.PolicyDetails,
597 observed: dlm.PolicyDetails | undefined,
598 ): boolean =>
599 JSON.stringify(canonicalize(desired)) !==
600 JSON.stringify(canonicalize(projectToDesired(desired, observed ?? {})));
601
602 /**
603 * DLM validates the execution role at create/update time; a freshly created
604 * role can be transiently rejected with `InvalidRequestException` until IAM
605 * propagation completes. Bounded retry, explicitly typed so declaration emit
606 * never widens the provider layer (see PATTERNS §7).
607 */
608 const retryWhileRolePropagates = <A, E extends { _tag: string }, R>(
609 self: Effect.Effect<A, E, R>,
610 ): Effect.Effect<A, E, R> =>
611 Effect.retry(self, {
612 while: (e) => e._tag === "InvalidRequestException",
613 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(5)]),
614 });
615
616 export const LifecyclePolicyProvider = () =>
617 Provider.effect(
618 LifecyclePolicy,
619 Effect.gen(function* () {
620 const createDescription = Effect.fn(function* (
621 id: string,
622 props: Pick<LifecyclePolicyProps, "description">,
623 ) {
624 return props.description ?? (yield* createPhysicalName({ id, maxLength: 500 }));
625 });
626
627 const createRoleName = (id: string) => createPhysicalName({ id, maxLength: 64 });
628
629 const managedPolicyArnFor = (details: LifecyclePolicyDetails) =>
630 (details.policyType ?? "EBS_SNAPSHOT_MANAGEMENT") === "IMAGE_MANAGEMENT"
631 ? AMI_MANAGED_POLICY_ARN
632 : SNAPSHOT_MANAGED_POLICY_ARN;
633
634 const getOrUndefined = Effect.fn(function* (policyId: string) {
635 return yield* dlm.getLifecyclePolicy({ PolicyId: policyId }).pipe(
636 Effect.map((r) => r.Policy),
637 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
638 );
639 });
640
641 const buildAttrs = (policy: dlm.LifecyclePolicy, roleName: string | undefined) => ({
642 policyId: policy.PolicyId!,
643 policyArn: policy.PolicyArn!,
644 state: (policy.State ?? "ENABLED") as LifecyclePolicyState,
645 executionRoleArn: policy.ExecutionRoleArn!,
646 roleName,
647 });
648
649 /**
650 * Ensure the auto-created execution role exists with `dlm.amazonaws.com`
651 * trust and the AWS managed policy matching the policy type. Idempotent:
652 * tolerates the role already existing; attaching an already-attached
653 * managed policy is a no-op.
654 */
655 const ensureExecutionRole = Effect.fn(function* ({
656 id,
657 roleName,
658 managedPolicyArn,
659 }: {
660 id: string;
661 roleName: string;
662 managedPolicyArn: string;
663 }) {
664 const tags = yield* createInternalTags(id);
665 const role = yield* iam
666 .createRole({
667 RoleName: roleName,
668 AssumeRolePolicyDocument: JSON.stringify({
669 Version: "2012-10-17",
670 Statement: [
671 {
672 Effect: "Allow",
673 Principal: { Service: "dlm.amazonaws.com" },
674 Action: "sts:AssumeRole",
675 },
676 ],
677 }),
678 Tags: Object.entries(tags).map(([Key, Value]) => ({ Key, Value })),
679 })
680 .pipe(
681 Effect.catchTag("EntityAlreadyExistsException", () =>
682 iam.getRole({ RoleName: roleName }),
683 ),
684 );
685 yield* iam.attachRolePolicy({
686 RoleName: roleName,
687 PolicyArn: managedPolicyArn,
688 });
689 return role.Role.Arn;
690 });
691
692 return LifecyclePolicy.Provider.of({
693 stables: ["policyId", "policyArn"],
694
695 // Enumerate every lifecycle policy in the ambient account/region.
696 // getLifecyclePolicies is unpaginated; hydrate each summary because
697 // the full attributes (ARN, role) only appear on the detail call. A
698 // policy can vanish between enumeration and hydration — drop it.
699 list: () =>
700 Effect.gen(function* () {
701 const { Policies } = yield* dlm.getLifecyclePolicies({});
702 const items = yield* Effect.forEach(
703 Policies ?? [],
704 (summary) =>
705 summary.PolicyId === undefined
706 ? Effect.undefined
707 : getOrUndefined(summary.PolicyId).pipe(
708 Effect.map((policy) =>
709 policy?.PolicyId !== undefined &&
710 policy.PolicyArn !== undefined &&
711 policy.ExecutionRoleArn !== undefined
712 ? buildAttrs(policy, undefined)
713 : undefined,
714 ),
715 ),
716 { concurrency: 5 },
717 );
718 return items.filter(
719 (item): item is LifecyclePolicy["Attributes"] => item !== undefined,
720 );
721 }),
722
723 read: Effect.fn(function* ({ id, output }) {
724 // Policy ids are server-assigned; without an output cache there is
725 // no deterministic identity to look up. (A tag-based search would
726 // mis-resolve the OLD instance during a replacement, since both
727 // instances share the same logical-id tags.)
728 if (output?.policyId === undefined) return undefined;
729 const policy = yield* getOrUndefined(output.policyId);
730 if (
731 policy?.PolicyId === undefined ||
732 policy.PolicyArn === undefined ||
733 policy.ExecutionRoleArn === undefined
734 ) {
735 return undefined;
736 }
737 const attrs = buildAttrs(policy, output?.roleName);
738 return (yield* hasAlchemyTags(id, fromWireTagMap(policy.Tags))) ? attrs : Unowned(attrs);
739 }),
740
741 diff: Effect.fn(function* ({ news, olds }) {
742 if (!isResolved(news)) return undefined;
743 const oldType = olds?.policyDetails?.policyType ?? "EBS_SNAPSHOT_MANAGEMENT";
744 const newType = news.policyDetails?.policyType ?? "EBS_SNAPSHOT_MANAGEMENT";
745 if (oldType !== newType) {
746 // The policy type of an existing policy cannot be changed.
747 return { action: "replace" } as const;
748 }
749 // description/state/role/details/tags converge via update
750 }),
751
752 reconcile: Effect.fn(function* ({ id, news, output, session }) {
753 const description = yield* createDescription(id, news);
754 const desiredState = news.state ?? "ENABLED";
755 const desiredDetails = toWirePolicyDetails(news.policyDetails ?? {});
756 const internalTags = yield* createInternalTags(id);
757 const desiredTags = { ...news.tags, ...internalTags };
758
759 // Ensure the execution role first — the policy cannot exist
760 // without one. Managed unless an explicit executionRoleArn is
761 // provided.
762 let executionRoleArn = news.executionRoleArn;
763 let roleName: string | undefined;
764 if (executionRoleArn === undefined) {
765 roleName = yield* createRoleName(id);
766 executionRoleArn = yield* ensureExecutionRole({
767 id,
768 roleName,
769 managedPolicyArn: managedPolicyArnFor(news.policyDetails ?? {}),
770 });
771 }
772
773 // 1. OBSERVE — cloud state is authoritative; `output` is only an
774 // id cache. Policy ids are server-assigned, so with no cached
775 // id the policy is (as far as we can know) missing.
776 let policyId = output?.policyId;
777 let observed = policyId === undefined ? undefined : yield* getOrUndefined(policyId);
778
779 if (observed === undefined) {
780 // 2. ENSURE — create. IAM propagation of a fresh role is
781 // eventually consistent; DLM rejects it with a transient
782 // InvalidRequestException, so retry briefly.
783 const created = yield* retryWhileRolePropagates(
784 dlm.createLifecyclePolicy({
785 ExecutionRoleArn: executionRoleArn,
786 Description: description,
787 State: desiredState,
788 PolicyDetails: desiredDetails,
789 Tags: desiredTags,
790 }),
791 );
792 policyId = created.PolicyId!;
793 observed = yield* getOrUndefined(policyId);
794 } else {
795 // 3. SYNC — diff OBSERVED cloud state against desired and issue
796 // a single update only when something actually drifted. DLM
797 // normalizes documents on read (defaults like PolicyLanguage
798 // or ResourceLocations appear), so the comparison projects
799 // the observed document down to the keys we manage.
800 const drifted =
801 observed.Description !== description ||
802 (observed.State ?? "ENABLED") !== desiredState ||
803 observed.ExecutionRoleArn !== executionRoleArn ||
804 policyDetailsDrifted(desiredDetails, observed.PolicyDetails);
805 if (drifted) {
806 yield* retryWhileRolePropagates(
807 dlm.updateLifecyclePolicy({
808 PolicyId: policyId!,
809 ExecutionRoleArn: executionRoleArn,
810 Description: description,
811 State: desiredState,
812 PolicyDetails: desiredDetails,
813 }),
814 );
815 observed = yield* getOrUndefined(policyId!);
816 }
817 }
818
819 if (
820 observed?.PolicyId === undefined ||
821 observed.PolicyArn === undefined ||
822 observed.ExecutionRoleArn === undefined
823 ) {
824 // The policy vanished between create/update and the final read —
825 // surface as a typed not-found so the engine can retry the plan.
826 return yield* dlm.ResourceNotFoundException.make({
827 message: `DLM lifecycle policy ${policyId} disappeared during reconcile`,
828 });
829 }
830
831 // 3b. SYNC TAGS — against OBSERVED cloud tags so adoption
832 // converges (create-time tags only apply on first create).
833 const observedTags = fromWireTagMap(observed.Tags);
834 const { upsert, removed } = diffTags(observedTags, desiredTags);
835 if (upsert.length > 0) {
836 yield* dlm.tagResource({
837 ResourceArn: observed.PolicyArn,
838 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
839 });
840 }
841 if (removed.length > 0) {
842 yield* dlm.untagResource({
843 ResourceArn: observed.PolicyArn,
844 TagKeys: removed,
845 });
846 }
847
848 yield* session.note(observed.PolicyId);
849 return buildAttrs(observed, roleName);
850 }),
851
852 delete: Effect.fn(function* ({ output }) {
853 yield* dlm
854 .deleteLifecyclePolicy({ PolicyId: output.policyId })
855 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
856
857 // Tear down the managed execution role (absent when the user
858 // supplied an explicit executionRoleArn). Every step tolerates
859 // the role being partially or fully gone already.
860 if (output.roleName !== undefined) {
861 const roleName = output.roleName;
862 yield* iam.listAttachedRolePolicies({ RoleName: roleName }).pipe(
863 Effect.flatMap((r) =>
864 Effect.forEach(r.AttachedPolicies ?? [], (policy) =>
865 policy.PolicyArn === undefined
866 ? Effect.void
867 : iam
868 .detachRolePolicy({
869 RoleName: roleName,
870 PolicyArn: policy.PolicyArn,
871 })
872 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)),
873 ),
874 ),
875 Effect.catchTag("NoSuchEntityException", () => Effect.void),
876 );
877 yield* iam
878 .deleteRole({ RoleName: roleName })
879 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
880 }
881 }),
882 });
883 }),
884 );