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

main
ts 246 lines 8.87 KB
Raw
1 import * as config from "@distilled.cloud/aws/config-service";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import type { Providers } from "../Providers.ts";
9
10 export interface DeliveryChannelProps {
11 /**
12 * Name of the delivery channel. AWS allows only ONE delivery channel per
13 * account per region. Changing the name replaces the channel.
14 * @default ${app}-${stage}-${id}
15 */
16 name?: string;
17 /**
18 * Name of the S3 bucket AWS Config delivers configuration snapshots and
19 * history files to. The bucket needs a policy granting
20 * `config.amazonaws.com` `s3:GetBucketAcl` on the bucket and
21 * `s3:PutObject` on `arn:aws:s3:::{bucket}/AWSLogs/{account}/Config/*`.
22 */
23 s3BucketName: string;
24 /**
25 * Key prefix for the delivered objects.
26 */
27 s3KeyPrefix?: string;
28 /**
29 * ARN of the KMS key AWS Config uses to encrypt objects delivered to the
30 * S3 bucket.
31 */
32 s3KmsKeyArn?: string;
33 /**
34 * ARN of the SNS topic AWS Config sends notifications to.
35 */
36 snsTopicArn?: string;
37 /**
38 * How often AWS Config delivers configuration snapshots to the bucket.
39 */
40 snapshotDeliveryFrequency?:
41 | "One_Hour"
42 | "Three_Hours"
43 | "Six_Hours"
44 | "Twelve_Hours"
45 | "TwentyFour_Hours";
46 }
47
48 export interface DeliveryChannel extends Resource<
49 "AWS.Config.DeliveryChannel",
50 DeliveryChannelProps,
51 {
52 /** Physical name of the delivery channel. */
53 deliveryChannelName: string;
54 /** S3 bucket configuration snapshots and history are delivered to. */
55 s3BucketName: string;
56 },
57 never,
58 Providers
59 > {}
60
61 /**
62 * The AWS Config delivery channel that delivers configuration snapshots and
63 * configuration history to an S3 bucket (and optionally notifies an SNS
64 * topic).
65 *
66 * AWS allows only **one** delivery channel per account per region — treat
67 * this resource as an account-region singleton. A configuration recorder
68 * must exist before the channel can be created (see
69 * `AWS.Config.ConfigurationRecorder`).
70 * ### Creating the Channel
71 * **Example:** Deliver configuration history to S3
72 * ```typescript
73 * import * as Config from "@alchemy.run/aws/Config";
74 *
75 * const channel = yield* Config.DeliveryChannel("Channel", {
76 * s3BucketName: bucket.bucketName,
77 * });
78 * ```
79 *
80 * **Example:** Periodic snapshots with a key prefix
81 * ```typescript
82 * const channel = yield* Config.DeliveryChannel("Channel", {
83 * s3BucketName: bucket.bucketName,
84 * s3KeyPrefix: "config",
85 * snapshotDeliveryFrequency: "TwentyFour_Hours",
86 * });
87 * ```
88 *
89 * @resource
90 */
91 export const DeliveryChannel = Resource<DeliveryChannel>("AWS.Config.DeliveryChannel");
92
93 /**
94 * `PutDeliveryChannel` validates the recorder's existence and the bucket
95 * policy at call time. A recorder or bucket policy created in the same
96 * deploy can take a few seconds to become visible, surfacing as
97 * `NoAvailableConfigurationRecorderException` /
98 * `InsufficientDeliveryPolicyException` / `NoSuchBucketException` — retry
99 * on a bounded schedule (~40s).
100 *
101 * Explicitly typed: inlining `Effect.retry` with options in provider
102 * lifecycle code can widen the provider layer to `unknown` in declaration
103 * emit.
104 *
105 * @internal
106 */
107 const retryChannelPut = <A, E extends { readonly _tag: string }, R>(
108 self: Effect.Effect<A, E, R>,
109 ): Effect.Effect<A, E, R> =>
110 Effect.retry(self, {
111 while: (e) =>
112 e._tag === "NoAvailableConfigurationRecorderException" ||
113 e._tag === "InsufficientDeliveryPolicyException" ||
114 e._tag === "NoSuchBucketException",
115 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]),
116 });
117
118 /**
119 * Deleting the channel while the recorder is still running (or while the
120 * recorder is being stopped/deleted concurrently by the same destroy)
121 * rejects with `LastDeliveryChannelDeleteFailedException` — a dependency
122 * violation, retried on a bounded schedule (~40s).
123 * @internal
124 */
125 const retryChannelDelete = <A, E extends { readonly _tag: string }, R>(
126 self: Effect.Effect<A, E, R>,
127 ): Effect.Effect<A, E, R> =>
128 Effect.retry(self, {
129 while: (e) => e._tag === "LastDeliveryChannelDeleteFailedException",
130 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]),
131 });
132
133 export const DeliveryChannelProvider = () =>
134 Provider.effect(
135 DeliveryChannel,
136 Effect.gen(function* () {
137 const createChannelName = Effect.fn(function* (
138 id: string,
139 props: Pick<DeliveryChannelProps, "name">,
140 ) {
141 return props.name ?? (yield* createPhysicalName({ id, maxLength: 256 }));
142 });
143
144 const toWireChannel = (
145 name: string,
146 props: DeliveryChannelProps,
147 ): config.DeliveryChannel => ({
148 name,
149 s3BucketName: props.s3BucketName,
150 s3KeyPrefix: props.s3KeyPrefix,
151 s3KmsKeyArn: props.s3KmsKeyArn,
152 snsTopicARN: props.snsTopicArn,
153 configSnapshotDeliveryProperties:
154 props.snapshotDeliveryFrequency === undefined
155 ? undefined
156 : { deliveryFrequency: props.snapshotDeliveryFrequency },
157 });
158
159 const observeChannel = Effect.fn(function* (name: string) {
160 const response = yield* config
161 .describeDeliveryChannels({ DeliveryChannelNames: [name] })
162 .pipe(
163 Effect.catchTag("NoSuchDeliveryChannelException", () =>
164 Effect.succeed({ DeliveryChannels: [] }),
165 ),
166 );
167 return (response.DeliveryChannels ?? []).at(0);
168 });
169
170 return DeliveryChannel.Provider.of({
171 stables: ["deliveryChannelName"],
172 list: () =>
173 config.describeDeliveryChannels({}).pipe(
174 Effect.map((response) =>
175 (response.DeliveryChannels ?? []).flatMap((channel) =>
176 channel.name && channel.s3BucketName
177 ? [
178 {
179 deliveryChannelName: channel.name,
180 s3BucketName: channel.s3BucketName,
181 },
182 ]
183 : [],
184 ),
185 ),
186 ),
187 // Delivery channels are not taggable, so there is no ownership
188 // marker to check — an existing channel with our derived name is
189 // treated as ours.
190 read: Effect.fn(function* ({ id, olds, output }) {
191 const name = output?.deliveryChannelName ?? (yield* createChannelName(id, olds ?? {}));
192 const channel = yield* observeChannel(name);
193 if (channel?.name === undefined) return undefined;
194 return {
195 deliveryChannelName: channel.name,
196 s3BucketName: channel.s3BucketName!,
197 };
198 }),
199 diff: Effect.fn(function* ({ id, news, olds }) {
200 if (!isResolved(news)) return undefined;
201 const oldName = yield* createChannelName(id, olds ?? {});
202 const newName = yield* createChannelName(id, news);
203 if (oldName !== newName) {
204 return { action: "replace" } as const;
205 }
206 // fall through: engine default update logic for mutable fields
207 }),
208 reconcile: Effect.fn(function* ({ id, news, output, session }) {
209 const name = output?.deliveryChannelName ?? (yield* createChannelName(id, news));
210 const desired = toWireChannel(name, news);
211
212 // 1. OBSERVE — cloud state is authoritative.
213 const observed = yield* observeChannel(name);
214
215 // 2+3. ENSURE + SYNC — PutDeliveryChannel is a full upsert; apply
216 // when missing or when any declared aspect drifted. Comparing
217 // the full wire shape is safe here: AWS echoes exactly the
218 // members that were put (no server-side defaults).
219 const inSync =
220 observed !== undefined &&
221 observed.s3BucketName === desired.s3BucketName &&
222 (observed.s3KeyPrefix ?? undefined) === desired.s3KeyPrefix &&
223 (observed.s3KmsKeyArn ?? undefined) === desired.s3KmsKeyArn &&
224 (observed.snsTopicARN ?? undefined) === desired.snsTopicARN &&
225 (observed.configSnapshotDeliveryProperties?.deliveryFrequency ?? undefined) ===
226 desired.configSnapshotDeliveryProperties?.deliveryFrequency;
227 if (!inSync) {
228 yield* retryChannelPut(config.putDeliveryChannel({ DeliveryChannel: desired }));
229 }
230
231 yield* session.note(name);
232 return {
233 deliveryChannelName: name,
234 s3BucketName: news.s3BucketName,
235 };
236 }),
237 delete: Effect.fn(function* ({ output }) {
238 yield* retryChannelDelete(
239 config.deleteDeliveryChannel({
240 DeliveryChannelName: output.deliveryChannelName,
241 }),
242 ).pipe(Effect.catchTag("NoSuchDeliveryChannelException", () => Effect.void));
243 }),
244 });
245 }),
246 );