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

main
ts 318 lines 11.2 KB
Raw
1 import * as s3control from "@distilled.cloud/aws/s3-control";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createTagsList, createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { AWSEnvironment } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 export interface StorageLensConfigurationProps {
15 /**
16 * ID of the Storage Lens configuration (1-64 characters: letters,
17 * numbers, `-`, `_` and `.`). If omitted, a unique ID is generated
18 * from the app, stage and logical ID.
19 *
20 * Changing the ID replaces the configuration.
21 * @default ${app}-${stage}-${id}
22 */
23 configId?: string;
24 /**
25 * Whether the S3 Storage Lens configuration is enabled (actively
26 * aggregating metrics).
27 * @default true
28 */
29 isEnabled?: boolean;
30 /**
31 * Account-level metrics configuration (activity metrics, advanced
32 * metrics, prefix-level metrics, ...). Passed through to the S3 Control
33 * API verbatim.
34 * @default { BucketLevel: {} } — free metrics for every bucket
35 */
36 accountLevel?: s3control.AccountLevel;
37 /**
38 * Restrict the dashboard to specific buckets and/or regions. Mutually
39 * exclusive with `exclude`.
40 */
41 include?: s3control.Include;
42 /**
43 * Exclude specific buckets and/or regions from the dashboard. Mutually
44 * exclusive with `include`.
45 */
46 exclude?: s3control.Exclude;
47 /**
48 * Export the daily metrics to an S3 bucket and/or publish them to
49 * CloudWatch.
50 */
51 dataExport?: s3control.StorageLensDataExport;
52 /**
53 * ARN of the AWS Organization to aggregate metrics across member
54 * accounts (requires trusted access / delegated administration).
55 */
56 awsOrg?: string;
57 /**
58 * Tags to apply to the configuration. Merged with internal Alchemy tags.
59 */
60 tags?: Record<string, string>;
61 }
62
63 export interface StorageLensConfiguration extends Resource<
64 "AWS.S3Control.StorageLensConfiguration",
65 StorageLensConfigurationProps,
66 {
67 /**
68 * ID of the Storage Lens configuration.
69 */
70 configId: string;
71 /**
72 * ARN of the Storage Lens configuration.
73 */
74 storageLensArn: string;
75 },
76 never,
77 Providers
78 > {}
79
80 /**
81 * An Amazon S3 Storage Lens configuration — an account-wide (or
82 * organization-wide) storage analytics dashboard aggregating usage and
83 * activity metrics across buckets, with optional daily export to S3 or
84 * CloudWatch.
85 * ### Creating Dashboards
86 * **Example:** Free-metrics dashboard over the whole account
87 * ```typescript
88 * import * as S3Control from "@alchemy.run/aws/S3Control";
89 *
90 * const lens = yield* S3Control.StorageLensConfiguration("account-lens", {});
91 * ```
92 *
93 * **Example:** Dashboard scoped to specific buckets
94 * ```typescript
95 * const lens = yield* S3Control.StorageLensConfiguration("data-lens", {
96 * include: {
97 * Buckets: [bucket.bucketArn],
98 * },
99 * });
100 * ```
101 *
102 * **Example:** Advanced metrics with S3 export
103 * ```typescript
104 * const lens = yield* S3Control.StorageLensConfiguration("advanced-lens", {
105 * accountLevel: {
106 * ActivityMetrics: { IsEnabled: true },
107 * BucketLevel: {
108 * ActivityMetrics: { IsEnabled: true },
109 * },
110 * },
111 * dataExport: {
112 * S3BucketDestination: {
113 * Format: "CSV",
114 * OutputSchemaVersion: "V_1",
115 * AccountId: accountId,
116 * Arn: reportBucket.bucketArn,
117 * },
118 * },
119 * });
120 * ```
121 *
122 * **Example:** Disable a dashboard without deleting it
123 * ```typescript
124 * const lens = yield* S3Control.StorageLensConfiguration("account-lens", {
125 * isEnabled: false,
126 * });
127 * ```
128 *
129 * @resource
130 */
131 export const StorageLensConfiguration = Resource<StorageLensConfiguration>(
132 "AWS.S3Control.StorageLensConfiguration",
133 );
134
135 /**
136 * Retry while a freshly-written Storage Lens configuration has not
137 * propagated to reads yet.
138 *
139 * Explicitly typed at module scope — inlining `Effect.retry` in a lifecycle
140 * op leaks `Retry.Return`'s conditional type into declaration emit, widening
141 * the provider layer to `unknown` and poisoning `AWS.providers()`.
142 */
143 const retryWhileConfigurationPropagates = <A, E extends { _tag: string }, R>(
144 self: Effect.Effect<A, E, R>,
145 ): Effect.Effect<A, E, R> =>
146 Effect.retry(self, {
147 while: (e) => e._tag === "NoSuchConfiguration",
148 schedule: Schedule.max([Schedule.fixed("1 second"), Schedule.recurs(10)]),
149 });
150
151 export const StorageLensConfigurationProvider = () =>
152 Provider.effect(
153 StorageLensConfiguration,
154 Effect.gen(function* () {
155 const createConfigId = Effect.fn(function* (
156 id: string,
157 props: Pick<StorageLensConfigurationProps, "configId">,
158 ) {
159 // Config IDs allow [a-zA-Z0-9-_.], 1-64 characters.
160 return props.configId ?? (yield* createPhysicalName({ id, maxLength: 64 }));
161 });
162
163 const observeConfiguration = (accountId: string, configId: string) =>
164 s3control
165 .getStorageLensConfiguration({
166 AccountId: accountId,
167 ConfigId: configId,
168 })
169 .pipe(
170 Effect.map((r) => r.StorageLensConfiguration),
171 Effect.catchTag("NoSuchConfiguration", () => Effect.undefined),
172 );
173
174 const observedTags = (accountId: string, configId: string) =>
175 s3control
176 .getStorageLensConfigurationTagging({
177 AccountId: accountId,
178 ConfigId: configId,
179 })
180 .pipe(
181 Effect.map((r) => Object.fromEntries((r.Tags ?? []).map((t) => [t.Key, t.Value]))),
182 Effect.catchTag("NoSuchConfiguration", () =>
183 Effect.succeed({} as Record<string, string>),
184 ),
185 );
186
187 const desiredConfiguration = (
188 configId: string,
189 props: StorageLensConfigurationProps,
190 ): s3control.StorageLensConfiguration => ({
191 Id: configId,
192 AccountLevel: props.accountLevel ?? { BucketLevel: {} },
193 Include: props.include,
194 Exclude: props.exclude,
195 DataExport: props.dataExport,
196 IsEnabled: props.isEnabled ?? true,
197 AwsOrg: props.awsOrg ? { Arn: props.awsOrg } : undefined,
198 });
199
200 // Canonical form for observed-vs-desired comparison: only the members
201 // we manage, with `undefined` members normalized away.
202 const canon = (cfg: s3control.StorageLensConfiguration) =>
203 JSON.stringify({
204 id: cfg.Id,
205 // AWS omits an empty <BucketLevel/> from GET responses, so
206 // normalize it to {} to avoid perpetual drift.
207 accountLevel: {
208 ...cfg.AccountLevel,
209 BucketLevel: cfg.AccountLevel?.BucketLevel ?? {},
210 },
211 include: cfg.Include ?? null,
212 exclude: cfg.Exclude ?? null,
213 dataExport: cfg.DataExport ?? null,
214 isEnabled: cfg.IsEnabled,
215 awsOrg: cfg.AwsOrg ?? null,
216 });
217
218 return StorageLensConfiguration.Provider.of({
219 stables: ["configId", "storageLensArn"],
220 list: () =>
221 Effect.gen(function* () {
222 const { accountId } = yield* AWSEnvironment.current;
223 const pages = yield* s3control.listStorageLensConfigurations
224 .pages({ AccountId: accountId })
225 .pipe(Stream.runCollect);
226 return Array.from(pages).flatMap((page) =>
227 (page.StorageLensConfigurationList ?? []).map((entry) => ({
228 configId: entry.Id,
229 storageLensArn: entry.StorageLensArn,
230 })),
231 );
232 }),
233 read: Effect.fn(function* ({ id, olds, output }) {
234 const { accountId } = yield* AWSEnvironment.current;
235 const configId = output?.configId ?? (yield* createConfigId(id, olds ?? {}));
236 const observed = yield* observeConfiguration(accountId, configId);
237 if (observed?.StorageLensArn === undefined) return undefined;
238 const attrs = {
239 configId,
240 storageLensArn: observed.StorageLensArn,
241 };
242 const tags = yield* observedTags(accountId, configId);
243 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
244 }),
245 diff: Effect.fn(function* ({ id, news, olds }) {
246 if (!isResolved(news)) return undefined;
247 const oldConfigId = yield* createConfigId(id, olds ?? {});
248 const newConfigId = yield* createConfigId(id, news);
249 if (oldConfigId !== newConfigId) {
250 return { action: "replace" } as const;
251 }
252 // fall through: everything else converges via PUT (upsert)
253 }),
254 reconcile: Effect.fn(function* ({ id, news, output, session }) {
255 const { accountId } = yield* AWSEnvironment.current;
256 const configId = output?.configId ?? (yield* createConfigId(id, news));
257
258 // 1. OBSERVE — cloud state is authoritative.
259 const observed = yield* observeConfiguration(accountId, configId);
260
261 // 2. ENSURE + SYNC — PutStorageLensConfiguration is a true upsert;
262 // write only when the observed configuration differs.
263 const desired = desiredConfiguration(configId, news);
264 if (observed === undefined || canon(observed) !== canon(desired)) {
265 yield* s3control.putStorageLensConfiguration({
266 AccountId: accountId,
267 ConfigId: configId,
268 StorageLensConfiguration: desired,
269 });
270 }
271
272 // 3. SYNC TAGS — PutStorageLensConfigurationTagging replaces the
273 // whole tag set, so diff against OBSERVED tags only to decide
274 // whether a write is needed.
275 const internalTags = yield* createInternalTags(id);
276 const desiredTags = { ...news.tags, ...internalTags };
277 const currentTags = yield* observedTags(accountId, configId);
278 const { upsert, removed } = diffTags(currentTags, desiredTags);
279 if (upsert.length > 0 || removed.length > 0) {
280 yield* retryWhileConfigurationPropagates(
281 s3control.putStorageLensConfigurationTagging({
282 AccountId: accountId,
283 ConfigId: configId,
284 Tags: createTagsList(desiredTags),
285 }),
286 );
287 }
288
289 // 4. RETURN — re-read for the service-assigned ARN.
290 const final = yield* retryWhileConfigurationPropagates(
291 s3control.getStorageLensConfiguration({
292 AccountId: accountId,
293 ConfigId: configId,
294 }),
295 );
296
297 yield* session.note(configId);
298 return {
299 configId,
300 storageLensArn:
301 final.StorageLensConfiguration?.StorageLensArn ?? output?.storageLensArn ?? "",
302 };
303 }),
304 delete: Effect.fn(function* ({ output }) {
305 const { accountId } = yield* AWSEnvironment.current;
306 yield* s3control
307 .deleteStorageLensConfiguration({
308 AccountId: accountId,
309 ConfigId: output.configId,
310 })
311 .pipe(
312 // Idempotent delete — already gone is success.
313 Effect.catchTag("NoSuchConfiguration", () => Effect.void),
314 );
315 }),
316 });
317 }),
318 );