@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 512 lines 19.7 KB
Raw
1 import * as rbin from "@distilled.cloud/aws/rbin";
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 {
7 createInternalTags,
8 createTagsList,
9 diffTags,
10 hasAlchemyTags,
11 tagRecord,
12 } from "alchemy/Tags";
13 import { toWireDays } from "alchemy/Util/Duration";
14 import * as Data from "effect/Data";
15 import type * as Duration from "effect/Duration";
16 import * as Effect from "effect/Effect";
17 import * as Schedule from "effect/Schedule";
18 import * as Stream from "effect/Stream";
19 import type { Providers } from "../Providers.ts";
20
21 /**
22 * A resource tag used to identify (or exclude) resources covered by a
23 * retention rule.
24 */
25 export interface RuleResourceTag {
26 /**
27 * The tag key.
28 */
29 key: string;
30 /**
31 * The tag value. Omit to match any resource that has the tag key,
32 * regardless of value.
33 */
34 value?: string;
35 }
36
37 /**
38 * Lock configuration for a Region-level retention rule. A locked rule
39 * cannot be modified or deleted until it is unlocked and the unlock delay
40 * period expires.
41 */
42 export interface RuleLockConfiguration {
43 /**
44 * The unlock delay that must expire after the rule is unlocked before it
45 * can be modified or deleted (e.g. `"7 days"`; valid range 7-30 days).
46 * Sent to the API in whole days.
47 */
48 unlockDelay: Duration.Input;
49 }
50
51 export interface RuleProps {
52 /**
53 * The resource type to be retained by the retention rule:
54 * `EBS_SNAPSHOT` for Amazon EBS snapshots, `EC2_IMAGE` for EBS-backed
55 * AMIs, or `EBS_VOLUME` for Amazon EBS volumes.
56 * Changing the resource type replaces the rule.
57 */
58 resourceType: "EBS_SNAPSHOT" | "EC2_IMAGE" | "EBS_VOLUME";
59
60 /**
61 * The period for which the retention rule retains resources after they
62 * are deleted (e.g. `"7 days"` or `Duration.days(7)`; valid range
63 * 1-365 days). Sent to the API in whole days.
64 */
65 retentionPeriod: Duration.Input;
66
67 /**
68 * A brief description of the retention rule.
69 */
70 description?: string;
71
72 /**
73 * Resource tags that identify the resources to retain (a **tag-level**
74 * retention rule). Resources of the specified type that have at least one
75 * of these tag key/value pairs are retained in the Recycle Bin upon
76 * deletion. Omit (along with `excludeResourceTags`) to create a
77 * **Region-level** rule that retains all resources of the type in the
78 * Region.
79 */
80 resourceTags?: RuleResourceTag[];
81
82 /**
83 * Exclusion tags for a Region-level retention rule. Resources that have
84 * any of these tag key/value pairs are NOT retained by the rule. Cannot
85 * be combined with `resourceTags` or `lockConfiguration`.
86 */
87 excludeResourceTags?: RuleResourceTag[];
88
89 /**
90 * Lock configuration for the rule. Only Region-level rules without
91 * exclusion tags can be locked. A locked rule cannot be modified or
92 * deleted; removing this prop unlocks the rule, which then remains in
93 * `pending_unlock` until the unlock delay (7-30 days) expires.
94 */
95 lockConfiguration?: RuleLockConfiguration;
96
97 /**
98 * Tags to apply to the retention rule itself. Merged with internal
99 * Alchemy tags.
100 */
101 tags?: Record<string, string>;
102 }
103
104 export interface Rule extends Resource<
105 "AWS.Rbin.Rule",
106 RuleProps,
107 {
108 /** The unique ID of the retention rule (e.g. `1a2b3c4d-5e6f-...`). */
109 identifier: string;
110 /** The Amazon Resource Name (ARN) of the retention rule. */
111 ruleArn: string;
112 /** The resource type retained by the retention rule. */
113 resourceType: rbin.ResourceType;
114 /** The state of the retention rule (`pending` or `available`). */
115 status: rbin.RuleStatus;
116 /** The lock state of the retention rule, if lockable. */
117 lockState?: rbin.LockState;
118 },
119 never,
120 Providers
121 > {}
122
123 /**
124 * A Recycle Bin retention rule. Recycle Bin retains deleted EBS snapshots,
125 * EBS-backed AMIs, and EBS volumes for a configurable period so they can be
126 * recovered after accidental deletion.
127 *
128 * Rules are either **tag-level** (retain only resources carrying specific
129 * resource tags) or **Region-level** (retain every resource of the type in
130 * the Region, optionally minus exclusion tags). Changing `resourceType`
131 * replaces the rule; every other property updates in place.
132 *
133 * ### Creating Retention Rules
134 * **Example:** Tag-level rule for EBS snapshots
135 * ```typescript
136 * import * as Rbin from "@alchemy.run/aws/Rbin";
137 *
138 * const rule = yield* Rbin.Rule("SnapshotRetention", {
139 * resourceType: "EBS_SNAPSHOT",
140 * retentionPeriod: "7 days",
141 * description: "Retain tagged snapshots for 7 days",
142 * resourceTags: [{ key: "team", value: "data" }],
143 * });
144 * ```
145 *
146 * **Example:** Region-level rule for AMIs
147 * ```typescript
148 * const rule = yield* Rbin.Rule("AmiRetention", {
149 * resourceType: "EC2_IMAGE",
150 * retentionPeriod: "14 days",
151 * description: "Retain all deregistered AMIs in this Region",
152 * });
153 * ```
154 *
155 * **Example:** Region-level rule with exclusion tags
156 * ```typescript
157 * const rule = yield* Rbin.Rule("SnapshotRetention", {
158 * resourceType: "EBS_SNAPSHOT",
159 * retentionPeriod: "30 days",
160 * excludeResourceTags: [{ key: "ephemeral", value: "true" }],
161 * });
162 * ```
163 *
164 * ### Locking
165 * A Region-level rule (without exclusion tags) can be locked so it cannot
166 * be modified or deleted. Removing `lockConfiguration` unlocks the rule,
167 * which stays protected in `pending_unlock` until the unlock delay expires.
168 *
169 * **Example:** Locked Region-level rule
170 * ```typescript
171 * const rule = yield* Rbin.Rule("LockedRetention", {
172 * resourceType: "EBS_SNAPSHOT",
173 * retentionPeriod: "30 days",
174 * lockConfiguration: { unlockDelay: "7 days" },
175 * });
176 * ```
177 *
178 * ### Tagging
179 * **Example:** Tag the rule itself
180 * ```typescript
181 * const rule = yield* Rbin.Rule("SnapshotRetention", {
182 * resourceType: "EBS_SNAPSHOT",
183 * retentionPeriod: "7 days",
184 * resourceTags: [{ key: "team", value: "data" }],
185 * tags: { CostCenter: "storage" },
186 * });
187 * ```
188 *
189 * @resource
190 */
191 export const Rule = Resource<Rule>("AWS.Rbin.Rule");
192
193 /**
194 * Raised when a `Rule` combines `lockConfiguration` with `resourceTags` or
195 * `excludeResourceTags`. Recycle Bin only supports locking Region-level
196 * retention rules that have no exclusion tags.
197 */
198 export class RbinLockUnsupported extends Data.TaggedError("RbinLockUnsupported")<{
199 message: string;
200 }> {}
201
202 const validateLock = (props: RuleProps) =>
203 props.lockConfiguration !== undefined &&
204 ((props.resourceTags?.length ?? 0) > 0 || (props.excludeResourceTags?.length ?? 0) > 0)
205 ? Effect.fail(
206 new RbinLockUnsupported({
207 message:
208 "lockConfiguration is only supported on Region-level retention rules without excludeResourceTags — remove resourceTags/excludeResourceTags or the lock.",
209 }),
210 )
211 : Effect.void;
212
213 /** All resource types a retention rule can cover — used to enumerate rules. */
214 const RULE_RESOURCE_TYPES = ["EBS_SNAPSHOT", "EC2_IMAGE", "EBS_VOLUME"] as const;
215
216 const toRetentionPeriod = (p: Duration.Input): rbin.RetentionPeriod => ({
217 // The wire unit is whole days (`DAYS` is the only supported unit).
218 RetentionPeriodValue: toWireDays(p)!,
219 RetentionPeriodUnit: "DAYS",
220 });
221
222 const toResourceTags = (tags: RuleResourceTag[] | undefined): rbin.ResourceTag[] =>
223 (tags ?? []).map((t) => ({
224 ResourceTagKey: t.key,
225 ...(t.value !== undefined ? { ResourceTagValue: t.value } : {}),
226 }));
227
228 const toLockConfiguration = (lock: RuleLockConfiguration): rbin.LockConfiguration => ({
229 UnlockDelay: {
230 // The wire unit is whole days (`DAYS` is the only supported unit).
231 UnlockDelayValue: toWireDays(lock.unlockDelay)!,
232 UnlockDelayUnit: "DAYS",
233 },
234 });
235
236 /** Order-insensitive fingerprint of a resource-tag set for delta detection. */
237 const resourceTagsKey = (tags: readonly rbin.ResourceTag[] | undefined) =>
238 JSON.stringify(
239 (tags ?? [])
240 .map((t) => [t.ResourceTagKey, t.ResourceTagValue ?? ""])
241 .sort((a, b) => (a[0]! < b[0]! ? -1 : a[0]! > b[0]! ? 1 : 0)),
242 );
243
244 const toAttributes = (live: rbin.GetRuleResponse): Rule["Attributes"] => ({
245 identifier: live.Identifier!,
246 ruleArn: live.RuleArn!,
247 resourceType: live.ResourceType!,
248 status: live.Status ?? "available",
249 lockState: live.LockState,
250 });
251
252 /** Read a rule; a typed RULE_NOT_FOUND becomes `undefined`. */
253 const readRule = (identifier: string) =>
254 rbin
255 .getRule({ Identifier: identifier })
256 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
257
258 /** Observed tags on the rule itself (empty on a NotFound race). */
259 const readRuleTags = (ruleArn: string) =>
260 rbin.listTagsForResource({ ResourceArn: ruleArn }).pipe(
261 Effect.map((r) => tagRecord(r.Tags ?? [])),
262 Effect.catchTag("ResourceNotFoundException", () =>
263 Effect.succeed({} as Record<string, string>),
264 ),
265 );
266
267 /** Collect all rule summaries for one resource type (exhaustive pages). */
268 const listRuleSummaries = (resourceType: rbin.ResourceType) =>
269 rbin.listRules.items({ ResourceType: resourceType }).pipe(
270 Stream.runCollect,
271 Effect.map((chunk) => Array.from(chunk)),
272 // Tolerate a resource type the Region/partition doesn't support yet.
273 Effect.catchTag("ValidationException", () => Effect.succeed([] as rbin.RuleSummary[])),
274 );
275
276 class RuleStillPending extends Data.TaggedError("RuleStillPending")<{
277 identifier: string;
278 }> {}
279
280 class RuleStillExists extends Data.TaggedError("RuleStillExists")<{
281 identifier: string;
282 }> {}
283
284 /**
285 * Bounded retry while a freshly created/updated rule reports `pending`.
286 * Extracted to module scope with an explicit signature so the conditional
287 * `Retry.Return` type never leaks into the provider layer's declaration.
288 */
289 const retryWhileRulePending = <A, E extends { _tag: string }, R>(
290 self: Effect.Effect<A, E | RuleStillPending, R>,
291 ): Effect.Effect<A, E | RuleStillPending, R> =>
292 Effect.retry(self, {
293 while: (e) => e._tag === "RuleStillPending",
294 schedule: Schedule.max([Schedule.fixed("1 second"), Schedule.recurs(30)]),
295 });
296
297 /** Poll a rule until it leaves the transient `pending` status. */
298 const waitForRuleAvailable = (identifier: string) =>
299 retryWhileRulePending(
300 Effect.gen(function* () {
301 const live = yield* rbin.getRule({ Identifier: identifier });
302 if (live.Status === "pending") {
303 return yield* new RuleStillPending({ identifier });
304 }
305 return live;
306 }),
307 );
308
309 /** Bounded retry while the rule is still observable after deletion. */
310 const retryWhileRuleExists = <A, E extends { _tag: string }, R>(
311 self: Effect.Effect<A, E | RuleStillExists, R>,
312 ): Effect.Effect<A, E | RuleStillExists, R> =>
313 Effect.retry(self, {
314 while: (e) => e._tag === "RuleStillExists",
315 schedule: Schedule.max([Schedule.fixed("1 second"), Schedule.recurs(15)]),
316 });
317
318 export const RuleProvider = () =>
319 Provider.effect(
320 Rule,
321 Effect.gen(function* () {
322 return Rule.Provider.of({
323 stables: ["identifier", "ruleArn", "resourceType"],
324
325 // Enumerate every retention rule in the ambient account/region across
326 // all supported resource types, hydrating each summary to the full
327 // Attributes shape. A rule can vanish between enumeration and
328 // hydration, so tolerate the typed NotFound per item and drop it.
329 list: () =>
330 Effect.gen(function* () {
331 const summaries = yield* Effect.forEach(
332 RULE_RESOURCE_TYPES,
333 (resourceType) => listRuleSummaries(resourceType),
334 { concurrency: 3 },
335 ).pipe(Effect.map((groups) => groups.flat()));
336 const items = yield* Effect.forEach(
337 summaries.filter((s) => s.Identifier !== undefined),
338 (summary) =>
339 readRule(summary.Identifier!).pipe(
340 Effect.map((live) => (live === undefined ? undefined : toAttributes(live))),
341 ),
342 { concurrency: 5 },
343 );
344 return items.filter((item): item is Rule["Attributes"] => item !== undefined);
345 }),
346
347 // Rule identifiers are server-generated, so without a cached output
348 // we search for a rule branded with our alchemy ownership tags.
349 read: Effect.fn(function* ({ id, olds, output }) {
350 if (output?.identifier) {
351 const live = yield* readRule(output.identifier);
352 if (!live) return undefined;
353 const attrs = toAttributes(live);
354 const tags = yield* readRuleTags(attrs.ruleArn);
355 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
356 }
357 const resourceTypes = olds?.resourceType ? [olds.resourceType] : RULE_RESOURCE_TYPES;
358 for (const resourceType of resourceTypes) {
359 const summaries = yield* listRuleSummaries(resourceType);
360 for (const summary of summaries) {
361 if (!summary.Identifier || !summary.RuleArn) continue;
362 const tags = yield* readRuleTags(summary.RuleArn);
363 if (yield* hasAlchemyTags(id, tags)) {
364 const live = yield* readRule(summary.Identifier);
365 if (live) return toAttributes(live);
366 }
367 }
368 }
369 return undefined;
370 }),
371
372 diff: Effect.fn(function* ({ news, olds }) {
373 if (!isResolved(news)) return undefined;
374 yield* validateLock(news);
375 // The resource type of a retention rule cannot be changed after
376 // creation — a change requires replacement.
377 if (news.resourceType !== olds.resourceType) {
378 return { action: "replace" } as const;
379 }
380 // Everything else (retention period, description, resource tags,
381 // exclusion tags, lock, tags) updates in place.
382 }),
383
384 reconcile: Effect.fn(function* ({ id, news, output, session }) {
385 yield* validateLock(news);
386 const internalTags = yield* createInternalTags(id);
387 const desiredTags = { ...news.tags, ...internalTags };
388
389 // OBSERVE — `output.identifier` is only a cache; a rule deleted
390 // out-of-band falls through to create.
391 let live = output?.identifier ? yield* readRule(output.identifier) : undefined;
392
393 // ENSURE — create if missing, then wait out the transient
394 // `pending` status so downstream sync reads settled state.
395 if (live === undefined) {
396 const created = yield* rbin.createRule({
397 ResourceType: news.resourceType,
398 RetentionPeriod: toRetentionPeriod(news.retentionPeriod),
399 Description: news.description,
400 ...(news.resourceTags ? { ResourceTags: toResourceTags(news.resourceTags) } : {}),
401 ...(news.excludeResourceTags
402 ? {
403 ExcludeResourceTags: toResourceTags(news.excludeResourceTags),
404 }
405 : {}),
406 ...(news.lockConfiguration
407 ? {
408 LockConfiguration: toLockConfiguration(news.lockConfiguration),
409 }
410 : {}),
411 Tags: createTagsList(desiredTags),
412 });
413 yield* session.note(`Created retention rule ${created.Identifier}`);
414 live = yield* waitForRuleAvailable(created.Identifier!);
415 }
416 const identifier = live.Identifier!;
417 const ruleArn = live.RuleArn!;
418
419 // SYNC mutable settings — diff OBSERVED cloud state against the
420 // desired props and apply only the delta. A no-op skips the API
421 // call entirely (a fresh create always lands here as a no-op).
422 const desiredRetention = toRetentionPeriod(news.retentionPeriod);
423 const desiredResourceTags = toResourceTags(news.resourceTags);
424 const desiredExcludeTags = toResourceTags(news.excludeResourceTags);
425 const retentionChanged =
426 live.RetentionPeriod?.RetentionPeriodValue !== desiredRetention.RetentionPeriodValue ||
427 live.RetentionPeriod?.RetentionPeriodUnit !== desiredRetention.RetentionPeriodUnit;
428 const descriptionChanged = (live.Description ?? "") !== (news.description ?? "");
429 const resourceTagsChanged =
430 resourceTagsKey(live.ResourceTags) !== resourceTagsKey(desiredResourceTags);
431 const excludeTagsChanged =
432 resourceTagsKey(live.ExcludeResourceTags) !== resourceTagsKey(desiredExcludeTags);
433 if (retentionChanged || descriptionChanged || resourceTagsChanged || excludeTagsChanged) {
434 yield* rbin.updateRule({
435 Identifier: identifier,
436 ...(retentionChanged ? { RetentionPeriod: desiredRetention } : {}),
437 ...(descriptionChanged ? { Description: news.description ?? "" } : {}),
438 ...(resourceTagsChanged ? { ResourceTags: desiredResourceTags } : {}),
439 ...(excludeTagsChanged ? { ExcludeResourceTags: desiredExcludeTags } : {}),
440 });
441 live = yield* waitForRuleAvailable(identifier);
442 }
443
444 // SYNC lock state — observed lock state vs desired. Unlocking
445 // starts the unlock delay (`pending_unlock`); re-locking during
446 // that window is allowed and converges back to `locked`.
447 if (news.lockConfiguration !== undefined) {
448 const desiredLock = toLockConfiguration(news.lockConfiguration);
449 const lockDelta =
450 live.LockState !== "locked" ||
451 live.LockConfiguration?.UnlockDelay.UnlockDelayValue !==
452 desiredLock.UnlockDelay.UnlockDelayValue ||
453 live.LockConfiguration?.UnlockDelay.UnlockDelayUnit !==
454 desiredLock.UnlockDelay.UnlockDelayUnit;
455 if (lockDelta) {
456 yield* rbin.lockRule({
457 Identifier: identifier,
458 LockConfiguration: desiredLock,
459 });
460 yield* session.note(`Locked retention rule ${identifier}`);
461 }
462 } else if (live.LockState === "locked") {
463 yield* rbin.unlockRule({ Identifier: identifier });
464 yield* session.note(
465 `Unlock initiated for ${identifier}; rule stays protected (pending_unlock) until the unlock delay expires`,
466 );
467 }
468
469 // SYNC tags — diff against OBSERVED cloud tags (never olds/output)
470 // so adoption converges.
471 const currentTags = yield* readRuleTags(ruleArn);
472 const { upsert, removed } = diffTags(currentTags, desiredTags);
473 if (upsert.length > 0) {
474 yield* rbin.tagResource({ ResourceArn: ruleArn, Tags: upsert });
475 }
476 if (removed.length > 0) {
477 yield* rbin.untagResource({
478 ResourceArn: ruleArn,
479 TagKeys: removed,
480 });
481 }
482
483 // RETURN fresh attributes reflecting all sync steps.
484 const final = yield* rbin.getRule({ Identifier: identifier });
485 yield* session.note(identifier);
486 return toAttributes(final);
487 }),
488
489 // Idempotent: a rule already gone is success. A locked rule fails
490 // with the typed ConflictException (INVALID_RULE_STATE) — it must be
491 // unlocked and its unlock delay must expire before deletion.
492 delete: Effect.fn(function* ({ output }) {
493 yield* rbin
494 .deleteRule({ Identifier: output.identifier })
495 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
496 // Deletion is near-immediate, but confirm the rule is gone so
497 // dependents (and re-creates of the same logical id) never observe
498 // a half-deleted rule.
499 yield* retryWhileRuleExists(
500 Effect.gen(function* () {
501 const live = yield* readRule(output.identifier);
502 if (live !== undefined) {
503 return yield* new RuleStillExists({
504 identifier: output.identifier,
505 });
506 }
507 }),
508 );
509 }),
510 });
511 }),
512 );