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

main
ts 177 lines 6.66 KB
Raw
1 import * as acm from "@distilled.cloud/aws/acm";
2 import { Region as AwsRegion } from "@distilled.cloud/aws/Region";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { toWireDays } from "alchemy/Util/Duration";
6 import * as Data from "effect/Data";
7 import type * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import type { Providers } from "../Providers.ts";
11
12 export class AccountConfigurationNotReady extends Data.TaggedError("AccountConfigurationNotReady")<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export interface AccountConfigurationProps {
18 /**
19 * How long before certificate expiration ACM starts emitting daily
20 * `ACM Certificate Approaching Expiration` EventBridge events for each
21 * certificate in the account.
22 *
23 * The wire unit is whole days and AWS accepts between 1 and 45 days.
24 * Accepts any `Duration.Input` (e.g. `"30 days"`); the provider converts to
25 * whole days.
26 *
27 * @default "45 days" (the AWS account default)
28 */
29 daysBeforeExpiry?: Duration.Input;
30 }
31
32 export interface AccountConfiguration extends Resource<
33 "AWS.ACM.AccountConfiguration",
34 AccountConfigurationProps,
35 {
36 /**
37 * Days before certificate expiration when ACM starts emitting expiry
38 * events, as currently configured on the account.
39 */
40 daysBeforeExpiry: number;
41 },
42 never,
43 Providers
44 > {}
45
46 /**
47 * Account-level ACM configuration (`AWS::CertificateManager::Account`).
48 *
49 * ACM emits one `ACM Certificate Approaching Expiration` EventBridge event
50 * per day per certificate starting `daysBeforeExpiry` days before each
51 * certificate expires. This account-global singleton manages that threshold
52 * via `acm:PutAccountConfiguration`. Deleting the resource resets the
53 * threshold to the AWS default of 45 days.
54 *
55 * Like the {@link Certificate} resource, the provider pins its API calls to
56 * `us-east-1`.
57 *
58 * ### Configuring Expiry Events
59 * **Example:** Start Expiry Events 30 Days Before Expiration
60 * ```typescript
61 * const config = yield* AccountConfiguration("AcmAccount", {
62 * daysBeforeExpiry: "30 days",
63 * });
64 * ```
65 *
66 * **Example:** Consume the Expiry Events
67 * ```typescript
68 * // The events arrive on the default EventBridge bus with source "aws.acm".
69 * yield* AWS.ACM.consumeExpiryEvents({}, (events) =>
70 * Stream.runForEach(events, (event) =>
71 * Effect.log(
72 * `${event.detail.CommonName} expires in ${event.detail.DaysToExpiry} days`,
73 * ),
74 * ),
75 * );
76 * ```
77 *
78 * @resource
79 */
80 export const AccountConfiguration = Resource<AccountConfiguration>("AWS.ACM.AccountConfiguration");
81
82 /** The AWS account default for `DaysBeforeExpiry`. */
83 const DEFAULT_DAYS_BEFORE_EXPIRY = 45;
84
85 const ACM_REGION = "us-east-1" as const;
86
87 const withAcmRegion = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
88 // `AwsRegion`'s service value is an `Effect<RegionName>`, so it must be
89 // provided as an effect, not a bare string.
90 effect.pipe(Effect.provideService(AwsRegion, Effect.succeed(ACM_REGION)));
91
92 /**
93 * ACM treats a repeated `IdempotencyToken` within one hour as the SAME
94 * request: replaying a token with different parameters is a typed
95 * `ConflictException`, and replaying it with the same parameters returns the
96 * cached original result WITHOUT re-applying it. So the token must vary with
97 * the desired value AND the attempt — the seed is truncated first so the
98 * discriminating suffix always survives.
99 */
100 const idempotencyToken = (seed: string, desiredDays: number, attempt: number) =>
101 `${seed.replaceAll(/[^a-zA-Z0-9]/g, "").slice(0, 20)}d${desiredDays}a${attempt}`;
102
103 export const AccountConfigurationProvider = () =>
104 Provider.effect(
105 AccountConfiguration,
106 Effect.gen(function* () {
107 const observe = withAcmRegion(
108 acm.getAccountConfiguration({}).pipe(
109 Effect.map((response) => ({
110 daysBeforeExpiry: response.ExpiryEvents?.DaysBeforeExpiry ?? DEFAULT_DAYS_BEFORE_EXPIRY,
111 })),
112 ),
113 );
114
115 // Converge the account threshold onto `desiredDays`, verifying the
116 // observed value after each put. The verify loop covers the exotic
117 // idempotency-cache case where ACM accepts a replayed token but does
118 // not re-apply it (see `idempotencyToken`): the next attempt salts a
119 // fresh token. Throttling is retried bounded.
120 const put = Effect.fn(function* (desiredDays: number, tokenSeed: string) {
121 for (let attempt = 0; attempt < 3; attempt++) {
122 yield* withAcmRegion(
123 acm
124 .putAccountConfiguration({
125 ExpiryEvents: { DaysBeforeExpiry: desiredDays },
126 IdempotencyToken: idempotencyToken(tokenSeed, desiredDays, attempt),
127 })
128 .pipe(
129 Effect.retry({
130 while: (e): boolean => e._tag === "ThrottlingException",
131 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(5)]),
132 }),
133 ),
134 );
135 const observed = yield* observe;
136 if (observed.daysBeforeExpiry === desiredDays) {
137 return observed;
138 }
139 }
140 return yield* new AccountConfigurationNotReady({
141 message: `ACM account configuration did not converge to ${desiredDays} days before expiry`,
142 });
143 });
144
145 return {
146 // Account-global singleton setting: nuke must not reset it.
147 nuke: { singleton: true },
148 stables: [],
149 read: Effect.fn(function* () {
150 return yield* observe;
151 }),
152 reconcile: Effect.fn(function* ({ instanceId, news, session }) {
153 const desiredDays = toWireDays(news.daysBeforeExpiry) ?? DEFAULT_DAYS_BEFORE_EXPIRY;
154
155 // Observe the live threshold; only call the API on a real delta.
156 const observed = yield* observe;
157 if (observed.daysBeforeExpiry !== desiredDays) {
158 yield* put(desiredDays, instanceId);
159 }
160
161 yield* session.note(`${desiredDays} days before expiry`);
162 return { daysBeforeExpiry: desiredDays };
163 }),
164 // Account-global singleton: the configuration always exists.
165 list: () => observe.pipe(Effect.map((observed) => [observed])),
166 // Deleting stops managing the threshold and restores the AWS
167 // account default (45 days). Idempotent: a no-op when the account
168 // is already at the default.
169 delete: Effect.fn(function* ({ instanceId }) {
170 const observed = yield* observe;
171 if (observed.daysBeforeExpiry !== DEFAULT_DAYS_BEFORE_EXPIRY) {
172 yield* put(DEFAULT_DAYS_BEFORE_EXPIRY, `${instanceId}reset`);
173 }
174 }),
175 };
176 }),
177 );