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

main
ts 347 lines 11.9 KB
Raw
1 import * as backupsearch from "@distilled.cloud/aws/backupsearch";
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, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import { readBackupSearchTags, syncBackupSearchTags } from "./internal.ts";
12
13 export interface BackupCreationTimeFilter {
14 /** Only include recovery points created after this ISO-8601 timestamp. */
15 createdAfter?: string;
16 /** Only include recovery points created before this ISO-8601 timestamp. */
17 createdBefore?: string;
18 }
19
20 export interface SearchScope {
21 /**
22 * Resource types of the recovery points to include in the search:
23 * `S3` and/or `EBS`.
24 */
25 backupResourceTypes: string[];
26 /** Filter recovery points by their backup creation time. */
27 backupResourceCreationTime?: BackupCreationTimeFilter;
28 /** Only search backups of these source resources (ARNs). */
29 sourceResourceArns?: string[];
30 /** Only search these recovery points (recovery point ARNs). */
31 backupResourceArns?: string[];
32 /** Only search recovery points carrying these tags. */
33 backupResourceTags?: Record<string, string>;
34 }
35
36 export interface StringCondition {
37 /** The string value to compare against. */
38 value: string;
39 /**
40 * Comparison operator: `EQUALS_TO`, `NOT_EQUALS_TO`, `CONTAINS`,
41 * `DOES_NOT_CONTAIN`, `BEGINS_WITH`, `ENDS_WITH`, `DOES_NOT_BEGIN_WITH`,
42 * or `DOES_NOT_END_WITH`.
43 * @default EQUALS_TO
44 */
45 operator?: string;
46 }
47
48 export interface LongCondition {
49 /** The numeric value to compare against. */
50 value: number;
51 /**
52 * Comparison operator: `EQUALS_TO`, `NOT_EQUALS_TO`,
53 * `LESS_THAN_EQUAL_TO`, or `GREATER_THAN_EQUAL_TO`.
54 * @default EQUALS_TO
55 */
56 operator?: string;
57 }
58
59 export interface TimeCondition {
60 /** The ISO-8601 timestamp to compare against. */
61 value: string;
62 /**
63 * Comparison operator: `EQUALS_TO`, `NOT_EQUALS_TO`,
64 * `LESS_THAN_EQUAL_TO`, or `GREATER_THAN_EQUAL_TO`.
65 * @default EQUALS_TO
66 */
67 operator?: string;
68 }
69
70 export interface S3ItemFilter {
71 /** Match S3 objects by key. */
72 objectKeys?: StringCondition[];
73 /** Match S3 objects by size in bytes. */
74 sizes?: LongCondition[];
75 /** Match S3 objects by creation time. */
76 creationTimes?: TimeCondition[];
77 /** Match S3 objects by version id. */
78 versionIds?: StringCondition[];
79 /** Match S3 objects by ETag. */
80 etags?: StringCondition[];
81 }
82
83 export interface EBSItemFilter {
84 /** Match EBS files by path. */
85 filePaths?: StringCondition[];
86 /** Match EBS files by size in bytes. */
87 sizes?: LongCondition[];
88 /** Match EBS files by creation time. */
89 creationTimes?: TimeCondition[];
90 /** Match EBS files by last-modification time. */
91 lastModificationTimes?: TimeCondition[];
92 }
93
94 export interface ItemFilters {
95 /** Filters applied to items inside S3 recovery points. */
96 s3ItemFilters?: S3ItemFilter[];
97 /** Filters applied to items inside EBS recovery points. */
98 ebsItemFilters?: EBSItemFilter[];
99 }
100
101 export interface SearchJobProps {
102 /**
103 * Display name of the search job. If omitted, a unique name is generated
104 * from the app, stage, and logical ID. Changing the name replaces the job.
105 */
106 name?: string;
107 /**
108 * ARN of the KMS key used to encrypt the search results. Immutable —
109 * changing it replaces the job.
110 */
111 encryptionKeyArn?: string;
112 /**
113 * The recovery points to search. Immutable — changing it replaces the job.
114 */
115 searchScope: SearchScope;
116 /**
117 * Filters applied to the items inside the recovery points. Immutable —
118 * changing them replaces the job.
119 */
120 itemFilters?: ItemFilters;
121 /**
122 * User-defined tags for the search job.
123 */
124 tags?: Record<string, string>;
125 }
126
127 export interface SearchJob extends Resource<
128 "AWS.BackupSearch.SearchJob",
129 SearchJobProps,
130 {
131 /**
132 * Service-assigned unique ID of the search job.
133 */
134 searchJobIdentifier: string;
135 /**
136 * ARN of the search job.
137 */
138 searchJobArn: string;
139 /**
140 * Name of the search job.
141 */
142 name: string | undefined;
143 /**
144 * Current status of the search job (e.g. `RUNNING`, `COMPLETED`).
145 */
146 status: string;
147 },
148 never,
149 Providers
150 > {}
151
152 /**
153 * An AWS Backup Search job — a data-plane search over AWS Backup recovery
154 * points (S3 and EBS) whose backup indexes are active. A search job is
155 * immutable once started: it runs to completion, retains its results for
156 * seven days, and can only be stopped while `RUNNING` (destroying the
157 * resource stops a running job; completed jobs age out server-side).
158 *
159 * ### Creating a Search Job
160 * **Example:** Search All S3 Backups
161 * ```typescript
162 * const search = yield* BackupSearch.SearchJob("FindReports", {
163 * searchScope: { backupResourceTypes: ["S3"] },
164 * itemFilters: {
165 * s3ItemFilters: [
166 * { objectKeys: [{ value: "reports/", operator: "BEGINS_WITH" }] },
167 * ],
168 * },
169 * });
170 * ```
171 *
172 * **Example:** Search Specific Recovery Points
173 * ```typescript
174 * const search = yield* BackupSearch.SearchJob("AuditSearch", {
175 * searchScope: {
176 * backupResourceTypes: ["EBS"],
177 * backupResourceArns: [recoveryPointArn],
178 * backupResourceCreationTime: { createdAfter: "2026-01-01T00:00:00Z" },
179 * },
180 * });
181 * ```
182 *
183 * @resource
184 */
185 export const SearchJob = Resource<SearchJob>("AWS.BackupSearch.SearchJob");
186
187 const encodeTimeCondition = (condition: TimeCondition): backupsearch.TimeCondition => ({
188 Value: new Date(condition.value),
189 Operator: condition.operator,
190 });
191
192 const encodeStringCondition = (condition: StringCondition): backupsearch.StringCondition => ({
193 Value: condition.value,
194 Operator: condition.operator,
195 });
196
197 const encodeLongCondition = (condition: LongCondition): backupsearch.LongCondition => ({
198 Value: condition.value,
199 Operator: condition.operator,
200 });
201
202 const encodeSearchScope = (scope: SearchScope): backupsearch.SearchScope => ({
203 BackupResourceTypes: scope.backupResourceTypes,
204 BackupResourceCreationTime: scope.backupResourceCreationTime
205 ? {
206 CreatedAfter: scope.backupResourceCreationTime.createdAfter
207 ? new Date(scope.backupResourceCreationTime.createdAfter)
208 : undefined,
209 CreatedBefore: scope.backupResourceCreationTime.createdBefore
210 ? new Date(scope.backupResourceCreationTime.createdBefore)
211 : undefined,
212 }
213 : undefined,
214 SourceResourceArns: scope.sourceResourceArns,
215 BackupResourceArns: scope.backupResourceArns,
216 BackupResourceTags: scope.backupResourceTags,
217 });
218
219 const encodeItemFilters = (filters: ItemFilters): backupsearch.ItemFilters => ({
220 S3ItemFilters: filters.s3ItemFilters?.map((filter) => ({
221 ObjectKeys: filter.objectKeys?.map(encodeStringCondition),
222 Sizes: filter.sizes?.map(encodeLongCondition),
223 CreationTimes: filter.creationTimes?.map(encodeTimeCondition),
224 VersionIds: filter.versionIds?.map(encodeStringCondition),
225 ETags: filter.etags?.map(encodeStringCondition),
226 })),
227 EBSItemFilters: filters.ebsItemFilters?.map((filter) => ({
228 FilePaths: filter.filePaths?.map(encodeStringCondition),
229 Sizes: filter.sizes?.map(encodeLongCondition),
230 CreationTimes: filter.creationTimes?.map(encodeTimeCondition),
231 LastModificationTimes: filter.lastModificationTimes?.map(encodeTimeCondition),
232 })),
233 });
234
235 export const SearchJobProvider = () =>
236 Provider.effect(
237 SearchJob,
238 Effect.gen(function* () {
239 const createName = Effect.fn(function* (id: string, props: SearchJobProps) {
240 return props.name ?? (yield* createPhysicalName({ id, maxLength: 60 }));
241 });
242
243 const get = Effect.fn(function* (searchJobIdentifier: string) {
244 return yield* backupsearch
245 .getSearchJob({ SearchJobIdentifier: searchJobIdentifier })
246 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
247 });
248
249 const toAttrs = (job: backupsearch.GetSearchJobOutput) => ({
250 searchJobIdentifier: job.SearchJobIdentifier,
251 searchJobArn: job.SearchJobArn,
252 name: job.Name,
253 status: job.Status as string,
254 });
255
256 return {
257 stables: ["searchJobIdentifier", "searchJobArn", "name"],
258
259 diff: Effect.fn(function* ({ id, olds, news }) {
260 if (!isResolved(news)) return undefined;
261 const oldName = yield* createName(id, olds);
262 const newName = yield* createName(id, news);
263 if (
264 oldName !== newName ||
265 (olds.encryptionKeyArn ?? undefined) !== (news.encryptionKeyArn ?? undefined) ||
266 JSON.stringify(olds.searchScope ?? null) !== JSON.stringify(news.searchScope ?? null) ||
267 JSON.stringify(olds.itemFilters ?? null) !== JSON.stringify(news.itemFilters ?? null)
268 ) {
269 return { action: "replace" } as const;
270 }
271 }),
272
273 read: Effect.fn(function* ({ id, output }) {
274 if (!output?.searchJobIdentifier) return undefined;
275 const job = yield* get(output.searchJobIdentifier);
276 if (job === undefined) return undefined;
277 const attrs = toAttrs(job);
278 const tags = yield* readBackupSearchTags(job.SearchJobArn);
279 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
280 }),
281
282 reconcile: Effect.fn(function* ({ id, news, output, session }) {
283 const name = yield* createName(id, news);
284 const internalTags = yield* createInternalTags(id);
285 const desiredTags = { ...internalTags, ...news.tags };
286
287 // OBSERVE — output is only an identifier cache; the job may be gone.
288 let job =
289 output?.searchJobIdentifier !== undefined
290 ? yield* get(output.searchJobIdentifier)
291 : undefined;
292
293 // ENSURE — a search job is immutable once started; start it if
294 // missing. Any change to the scope/filters is a replacement (diff).
295 if (job === undefined) {
296 const started = yield* backupsearch.startSearchJob({
297 Name: name,
298 EncryptionKeyArn: news.encryptionKeyArn,
299 SearchScope: encodeSearchScope(news.searchScope),
300 ItemFilters: news.itemFilters ? encodeItemFilters(news.itemFilters) : undefined,
301 Tags: desiredTags,
302 });
303 job = yield* backupsearch.getSearchJob({
304 SearchJobIdentifier: started.SearchJobIdentifier!,
305 });
306 } else {
307 // SYNC — tags are the only mutable aspect; diff against OBSERVED.
308 yield* syncBackupSearchTags(job.SearchJobArn, desiredTags);
309 }
310
311 yield* session.note(job.SearchJobIdentifier);
312 return toAttrs(job);
313 }),
314
315 delete: Effect.fn(function* ({ output }) {
316 // A search job cannot be deleted — results age out after 7 days.
317 // Stop it if it is still RUNNING; stopping a job in any other
318 // state is a ConflictException and means there is nothing to do.
319 yield* backupsearch
320 .stopSearchJob({
321 SearchJobIdentifier: output.searchJobIdentifier,
322 })
323 .pipe(
324 Effect.catchTags({
325 ResourceNotFoundException: () => Effect.void,
326 ConflictException: () => Effect.void,
327 }),
328 );
329 }),
330
331 list: () =>
332 backupsearch.listSearchJobs.pages({}).pipe(
333 Stream.runCollect,
334 Effect.map((chunk) =>
335 Array.from(chunk)
336 .flatMap((page) => page.SearchJobs ?? [])
337 .map((summary) => ({
338 searchJobIdentifier: summary.SearchJobIdentifier!,
339 searchJobArn: summary.SearchJobArn!,
340 name: summary.Name,
341 status: (summary.Status ?? "UNKNOWN") as string,
342 })),
343 ),
344 ),
345 };
346 }),
347 );