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

main
ts 254 lines 8.61 KB
Raw
1 import * as macie2 from "@distilled.cloud/aws/macie2";
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 { createInternalTags, diffTags, hasAlchemyTags, tagRecord } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import type { Providers } from "../Providers.ts";
10 import { retryThroughEnablement } from "./common.ts";
11
12 /**
13 * Whether the classification job runs once (`ONE_TIME`) or on a recurring
14 * schedule (`SCHEDULED`).
15 */
16 export type JobType = "ONE_TIME" | "SCHEDULED";
17
18 /**
19 * How Macie selects managed data identifiers for the job.
20 */
21 export type ManagedDataIdentifierSelector = "ALL" | "EXCLUDE" | "INCLUDE" | "NONE" | "RECOMMENDED";
22
23 /**
24 * A set of S3 buckets (within one account) that the job analyzes.
25 */
26 export interface BucketDefinition {
27 /** The account that owns the buckets. */
28 accountId: string;
29 /** The names of the buckets to analyze. */
30 buckets: string[];
31 }
32
33 export interface ClassificationJobProps {
34 /**
35 * Custom name for the job. Must be unique per account. If omitted, a unique
36 * name is generated from the app/stage/logical ID.
37 */
38 name?: string;
39
40 /**
41 * Whether the job runs once (`ONE_TIME`) or on a recurring schedule
42 * (`SCHEDULED`).
43 * @default "ONE_TIME"
44 */
45 jobType?: JobType;
46
47 /**
48 * The S3 buckets to analyze, grouped by owning account. Changing this
49 * replaces the job — classification jobs are immutable once created.
50 */
51 bucketDefinitions: BucketDefinition[];
52
53 /**
54 * Optional description of the job.
55 */
56 description?: string;
57
58 /**
59 * The sampling depth, as a percentage, applied to objects in the buckets.
60 * @default 100
61 */
62 samplingPercentage?: number;
63
64 /**
65 * For a scheduled job, whether Macie analyzes all existing eligible objects
66 * immediately on the first run.
67 */
68 initialRun?: boolean;
69
70 /**
71 * How Macie selects managed data identifiers for the job.
72 */
73 managedDataIdentifierSelector?: ManagedDataIdentifierSelector;
74
75 /**
76 * Tags applied to the job. Alchemy ownership tags are merged in automatically.
77 */
78 tags?: Record<string, string>;
79 }
80
81 /** @resource */
82 export interface ClassificationJob extends Resource<
83 "AWS.Macie2.ClassificationJob",
84 ClassificationJobProps,
85 {
86 /** Generated job ID. */
87 jobId: string;
88 /** ARN of the classification job. */
89 jobArn: string;
90 /** The resolved job name. */
91 name: string;
92 /** Current job status (`RUNNING` / `COMPLETE` / `CANCELLED` / ...). */
93 jobStatus: string | undefined;
94 },
95 never,
96 Providers
97 > {}
98
99 /**
100 * An Amazon Macie classification job — scans one or more S3 buckets for
101 * sensitive data. Requires Macie to be enabled for the account (see
102 * `Macie2.Session`). Jobs are immutable once created; changing the job type,
103 * name, or bucket set replaces the job. Destroy cancels the job.
104 *
105 * ### Creating a classification job
106 * **Example:** One-time job over a bucket
107 * ```typescript
108 * const job = yield* Macie2.ClassificationJob("Scan", {
109 * jobType: "ONE_TIME",
110 * bucketDefinitions: [{ accountId, buckets: ["my-bucket"] }],
111 * });
112 * ```
113 *
114 * **Example:** Sampled scan with a description
115 * ```typescript
116 * const job = yield* Macie2.ClassificationJob("Scan", {
117 * jobType: "ONE_TIME",
118 * bucketDefinitions: [{ accountId, buckets: ["my-bucket"] }],
119 * samplingPercentage: 20,
120 * description: "PII sweep",
121 * });
122 * ```
123 */
124 const ClassificationJobResource = Resource<ClassificationJob>("AWS.Macie2.ClassificationJob");
125
126 export { ClassificationJobResource as ClassificationJob };
127
128 const createName = (id: string, props: Partial<ClassificationJobProps>) =>
129 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 200 });
130
131 // A stable fingerprint of the immutable definition — any change replaces.
132 const fingerprint = (props: Partial<ClassificationJobProps>) =>
133 JSON.stringify({
134 jobType: props.jobType ?? "ONE_TIME",
135 bucketDefinitions: (props.bucketDefinitions ?? [])
136 .map((b) => ({ accountId: b.accountId, buckets: [...b.buckets].sort() }))
137 .sort((a, b) => a.accountId.localeCompare(b.accountId)),
138 });
139
140 const buildAttrs = (jobId: string, d: macie2.DescribeClassificationJobResponse) => ({
141 jobId,
142 jobArn: d.jobArn!,
143 name: d.name!,
144 jobStatus: d.jobStatus,
145 });
146
147 export const ClassificationJobProvider = () =>
148 Provider.effect(
149 ClassificationJobResource,
150 Effect.gen(function* () {
151 const describe = (jobId: string) =>
152 macie2
153 .describeClassificationJob({ jobId })
154 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
155
156 return {
157 stables: ["jobId", "jobArn", "name"],
158
159 read: Effect.fn(function* ({ id, output }) {
160 if (!output?.jobId) return undefined;
161 const d = yield* describe(output.jobId);
162 if (!d) return undefined;
163 const attrs = buildAttrs(output.jobId, d);
164 return (yield* hasAlchemyTags(id, d.tags)) ? attrs : Unowned(attrs);
165 }),
166
167 // Classification jobs are enumerable, but they are per-job resources
168 // (not a singleton); the engine keys them by logical ID, so return the
169 // empty set here and rely on `read` for state refresh.
170 list: () => Effect.succeed([]),
171
172 diff: Effect.fn(function* ({ id, news, olds = {} }) {
173 if (!isResolved(news)) return undefined;
174 const oldName = yield* createName(id, olds);
175 const newName = yield* createName(id, news);
176 if (oldName !== newName) return { action: "replace" } as const;
177 if (fingerprint(olds) !== fingerprint(news)) {
178 return { action: "replace" } as const;
179 }
180 // Jobs are immutable apart from status; nothing else to update.
181 return undefined;
182 }),
183
184 reconcile: Effect.fn(function* ({ id, news, output, session }) {
185 const internalTags = yield* createInternalTags(id);
186 const desiredTags = { ...news.tags, ...internalTags };
187 const name = output?.name ?? (yield* createName(id, news));
188
189 // 1. OBSERVE — cloud state is authoritative; output is an id cache.
190 let jobId = output?.jobId;
191 let live = jobId ? yield* describe(jobId) : undefined;
192
193 // 2. ENSURE — create the job if it does not exist.
194 if (jobId === undefined || live === undefined) {
195 const created = yield* retryThroughEnablement(
196 macie2.createClassificationJob({
197 name,
198 jobType: news.jobType ?? "ONE_TIME",
199 s3JobDefinition: {
200 bucketDefinitions: news.bucketDefinitions.map((b) => ({
201 accountId: b.accountId,
202 buckets: b.buckets,
203 })),
204 },
205 description: news.description,
206 samplingPercentage: news.samplingPercentage,
207 initialRun: news.initialRun,
208 managedDataIdentifierSelector: news.managedDataIdentifierSelector,
209 tags: desiredTags,
210 }),
211 );
212 jobId = created.jobId!;
213 live = yield* macie2.describeClassificationJob({ jobId });
214 } else {
215 // 3. SYNC tags — the definition is immutable; only tags mutate.
216 const { upsert, removed } = diffTags(tagRecord(live.tags), desiredTags);
217 if (upsert.length > 0) {
218 yield* macie2.tagResource({
219 resourceArn: live.jobArn!,
220 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
221 });
222 }
223 if (removed.length > 0) {
224 yield* macie2.untagResource({
225 resourceArn: live.jobArn!,
226 tagKeys: removed,
227 });
228 }
229 }
230
231 // 4. RETURN fresh attributes.
232 const final = yield* macie2.describeClassificationJob({ jobId });
233 yield* session.note(jobId);
234 return buildAttrs(jobId, final);
235 }),
236
237 delete: Effect.fn(function* ({ output }) {
238 // Classification jobs cannot be deleted — only cancelled. Cancelling
239 // an already-terminal job raises ConflictException; treat as done.
240 yield* macie2
241 .updateClassificationJob({
242 jobId: output.jobId,
243 jobStatus: "CANCELLED",
244 })
245 .pipe(
246 Effect.catchTags({
247 ConflictException: () => Effect.void,
248 ResourceNotFoundException: () => Effect.void,
249 }),
250 );
251 }),
252 };
253 }),
254 );