@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 294 lines 10.4 KB
Raw
1 import * as dataexchange from "@distilled.cloud/aws/dataexchange";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Result from "effect/Result";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { readDataExchangeTags, syncDataExchangeTags } from "./internal.ts";
13
14 /**
15 * Server-side encryption for auto-exported revisions.
16 */
17 export interface EventActionEncryption {
18 /**
19 * The encryption type: `aws:kms` (with `kmsKeyArn`) or `AES256`.
20 */
21 type: "aws:kms" | "AES256";
22 /**
23 * The ARN of the KMS key used to encrypt exported objects when `type` is
24 * `aws:kms`.
25 */
26 kmsKeyArn?: string;
27 }
28
29 /**
30 * The auto-export destination of an event action.
31 */
32 export interface EventActionExportRevisionToS3 {
33 /**
34 * The S3 bucket auto-exported revisions are written to. The bucket policy
35 * must allow the AWS Data Exchange service principal to write to it.
36 */
37 bucket: string;
38 /**
39 * Pattern for naming exported objects, built from `${Revision.CreatedAt}`
40 * and `${Asset.Name}` variables.
41 * @default "${Asset.Name}"
42 */
43 keyPattern?: string;
44 /**
45 * Server-side encryption applied to exported objects.
46 */
47 encryption?: EventActionEncryption;
48 }
49
50 export interface EventActionProps {
51 /**
52 * The id of the ENTITLED data set whose `RevisionPublished` event triggers
53 * the action. Event actions can only be created for entitled data sets
54 * (subscriptions or accepted data grants), not for owned data sets.
55 * Immutable — changing it replaces the event action.
56 */
57 dataSetId: string;
58 /**
59 * Where to auto-export newly published revisions. Mutable in place.
60 */
61 exportRevisionToS3: EventActionExportRevisionToS3;
62 /**
63 * Tags to apply to the event action. Merged with internal Alchemy tags.
64 */
65 tags?: Record<string, string>;
66 }
67
68 export interface EventAction extends Resource<
69 "AWS.DataExchange.EventAction",
70 EventActionProps,
71 {
72 /**
73 * The unique identifier of the event action.
74 */
75 eventActionId: string;
76 /**
77 * The ARN of the event action.
78 */
79 eventActionArn: string;
80 /**
81 * The id of the entitled data set the event action watches.
82 */
83 dataSetId: string;
84 },
85 never,
86 Providers
87 > {}
88
89 /**
90 * An AWS Data Exchange event action — an auto-export rule that copies every
91 * newly published revision of an ENTITLED data set into your S3 bucket the
92 * moment the provider publishes it. This is the subscriber-side automation
93 * primitive: subscribe to a product (or accept a data grant), attach an
94 * event action, and fresh data lands in your bucket with no polling.
95 *
96 * Event actions require an entitled data set — creating one against an
97 * owned data set fails with a `ValidationException`.
98 *
99 * ### Auto-Exporting Entitled Data
100 * **Example:** Export new revisions to S3
101 * ```typescript
102 * import * as AWS from "@alchemy.run/aws";
103 *
104 * const landing = yield* AWS.S3.Bucket("Landing", {});
105 *
106 * const autoExport = yield* AWS.DataExchange.EventAction("AutoExport", {
107 * dataSetId: entitledDataSetId,
108 * exportRevisionToS3: { bucket: landing.bucketName },
109 * });
110 * ```
111 *
112 * **Example:** Encrypted export with a key pattern
113 * ```typescript
114 * const autoExport = yield* AWS.DataExchange.EventAction("AutoExport", {
115 * dataSetId: entitledDataSetId,
116 * exportRevisionToS3: {
117 * bucket: landing.bucketName,
118 * keyPattern: "prices/${Revision.CreatedAt}/${Asset.Name}",
119 * encryption: { type: "aws:kms", kmsKeyArn: key.keyArn },
120 * },
121 * });
122 * ```
123 *
124 * @resource
125 */
126 export const EventAction = Resource<EventAction>("AWS.DataExchange.EventAction");
127
128 const toWireAction = (props: EventActionProps): dataexchange.Action => ({
129 ExportRevisionToS3: {
130 RevisionDestination: {
131 Bucket: props.exportRevisionToS3.bucket,
132 KeyPattern: props.exportRevisionToS3.keyPattern,
133 },
134 Encryption: props.exportRevisionToS3.encryption
135 ? {
136 Type: props.exportRevisionToS3.encryption.type,
137 KmsKeyArn: props.exportRevisionToS3.encryption.kmsKeyArn,
138 }
139 : undefined,
140 },
141 });
142
143 const sameAction = (
144 observed: dataexchange.Action | undefined,
145 desired: dataexchange.Action,
146 ): boolean => {
147 const a = observed?.ExportRevisionToS3;
148 const b = desired.ExportRevisionToS3;
149 return (
150 a !== undefined &&
151 b !== undefined &&
152 a.RevisionDestination.Bucket === b.RevisionDestination.Bucket &&
153 (a.RevisionDestination.KeyPattern ?? undefined) ===
154 (b.RevisionDestination.KeyPattern ?? undefined) &&
155 (a.Encryption?.Type ?? undefined) === (b.Encryption?.Type ?? undefined) &&
156 (a.Encryption?.KmsKeyArn ?? undefined) === (b.Encryption?.KmsKeyArn ?? undefined)
157 );
158 };
159
160 export const EventActionProvider = () =>
161 Provider.effect(
162 EventAction,
163 Effect.gen(function* () {
164 /** Get an event action by id; typed not-found → undefined. */
165 const getById = Effect.fn(function* (eventActionId: string) {
166 return yield* dataexchange
167 .getEventAction({ EventActionId: eventActionId })
168 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
169 });
170
171 /**
172 * Scan the data set's event actions for one carrying our ownership
173 * tags. Event action ids are server-generated, so recovery from a
174 * lost output (state-persistence failure) goes through per-action tag
175 * inspection.
176 */
177 const findByTags = Effect.fn(function* (id: string, dataSetId: string) {
178 return yield* dataexchange.listEventActions.items({ EventSourceId: dataSetId }).pipe(
179 Stream.mapEffect(
180 Effect.fn(function* (entry) {
181 const tags = yield* readDataExchangeTags(entry.Arn);
182 return (yield* hasAlchemyTags(id, tags)) ? entry : undefined;
183 }),
184 ),
185 Stream.filter((entry) => entry !== undefined),
186 Stream.runHead,
187 Effect.map((head) => (head._tag === "Some" ? head.value : undefined)),
188 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
189 );
190 });
191
192 return {
193 stables: ["eventActionId", "eventActionArn", "dataSetId"],
194
195 read: Effect.fn(function* ({ id, olds, output }) {
196 const dataSetId = output?.dataSetId ?? olds?.dataSetId;
197 const eventAction = output?.eventActionId
198 ? yield* getById(output.eventActionId)
199 : dataSetId !== undefined
200 ? yield* findByTags(id, dataSetId)
201 : undefined;
202 if (eventAction === undefined) return undefined;
203 const attrs = {
204 eventActionId: eventAction.Id!,
205 eventActionArn: eventAction.Arn!,
206 dataSetId: eventAction.Event?.RevisionPublished?.DataSetId ?? dataSetId!,
207 };
208 const tags = yield* readDataExchangeTags(attrs.eventActionArn);
209 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
210 }),
211
212 diff: Effect.fn(function* ({ news, olds }) {
213 if (!isResolved(news)) return undefined;
214 // The watched data set is the event action's identity.
215 if ((news.dataSetId as string) !== (olds.dataSetId as string)) {
216 return { action: "replace" } as const;
217 }
218 }),
219
220 reconcile: Effect.fn(function* ({ id, news, output, session }) {
221 const dataSetId = news.dataSetId as string;
222 const desiredAction = toWireAction(news);
223 const internalTags = yield* createInternalTags(id);
224 const desiredTags = { ...news.tags, ...internalTags };
225
226 // 1. Observe — output ids are only a cache; fall back to a
227 // tag-ownership scan of the data set's event actions.
228 let eventAction = output?.eventActionId
229 ? yield* getById(output.eventActionId)
230 : undefined;
231 if (eventAction === undefined) {
232 eventAction = yield* findByTags(id, dataSetId);
233 }
234
235 // 2. Ensure — create when missing.
236 if (eventAction === undefined) {
237 eventAction = yield* dataexchange.createEventAction({
238 Action: desiredAction,
239 Event: { RevisionPublished: { DataSetId: dataSetId } },
240 Tags: desiredTags,
241 });
242 }
243
244 // 3. Sync — the export destination is mutable in place. Only call
245 // the API on an actual delta.
246 if (!sameAction(eventAction.Action, desiredAction)) {
247 eventAction = yield* dataexchange.updateEventAction({
248 EventActionId: eventAction.Id!,
249 Action: desiredAction,
250 });
251 }
252
253 // 3b. Sync tags against OBSERVED cloud tags (adoption-safe).
254 yield* syncDataExchangeTags(eventAction.Arn!, desiredTags);
255
256 yield* session.note(eventAction.Arn!);
257 return {
258 eventActionId: eventAction.Id!,
259 eventActionArn: eventAction.Arn!,
260 dataSetId,
261 };
262 }),
263
264 delete: Effect.fn(function* ({ output }) {
265 yield* dataexchange.deleteEventAction({ EventActionId: output.eventActionId }).pipe(
266 // Deletion is idempotent — a missing event action is success.
267 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
268 Effect.retry({
269 while: (e): boolean => e._tag === "ThrottlingException",
270 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(5)]),
271 }),
272 );
273 }),
274
275 list: () =>
276 dataexchange.listEventActions.items({}).pipe(
277 // RevisionPublished is the only event type Data Exchange supports;
278 // entries without it carry no data set identity, so skip them
279 // rather than fabricate a dataSetId.
280 Stream.filterMap((entry) =>
281 entry.Event.RevisionPublished !== undefined
282 ? Result.succeed({
283 eventActionId: entry.Id,
284 eventActionArn: entry.Arn,
285 dataSetId: entry.Event.RevisionPublished.DataSetId,
286 })
287 : Result.failVoid,
288 ),
289 Stream.runCollect,
290 Effect.map((chunk) => Array.from(chunk)),
291 ),
292 };
293 }),
294 );