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

main
ts 229 lines 7.91 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 Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import { readDataExchangeTags, syncDataExchangeTags } from "./internal.ts";
12
13 export interface RevisionProps {
14 /**
15 * The unique identifier of the data set the revision belongs to.
16 * Changing it replaces the revision.
17 */
18 dataSetId: string;
19 /**
20 * An optional comment about the revision (up to 16,348 characters).
21 * Mutable in place.
22 */
23 comment?: string;
24 /**
25 * Whether the revision is finalized. A revision can only be finalized once
26 * it contains at least one asset (imported via a DataExchange job) —
27 * finalizing an empty revision fails with a `ValidationException`.
28 * @default false
29 */
30 finalized?: boolean;
31 /**
32 * Tags to apply to the revision. Merged with internal Alchemy tags.
33 */
34 tags?: Record<string, string>;
35 }
36
37 export interface Revision extends Resource<
38 "AWS.DataExchange.Revision",
39 RevisionProps,
40 {
41 /**
42 * The unique identifier of the revision.
43 */
44 revisionId: string;
45 /**
46 * The ARN of the revision.
47 */
48 revisionArn: string;
49 /**
50 * The unique identifier of the data set the revision belongs to.
51 */
52 dataSetId: string;
53 /**
54 * Whether the revision is finalized.
55 */
56 finalized: boolean;
57 },
58 never,
59 Providers
60 > {}
61
62 /**
63 * A revision of an AWS Data Exchange data set — a versioned container of
64 * assets. Providers import assets into a revision (via DataExchange jobs) and
65 * then finalize it to make the snapshot available to subscribers.
66 *
67 * ### Creating Revisions
68 * **Example:** Revision with a comment
69 * ```typescript
70 * import * as AWS from "@alchemy.run/aws";
71 *
72 * const dataSet = yield* AWS.DataExchange.DataSet("Prices", {
73 * description: "Daily commodity price snapshots",
74 * });
75 *
76 * const revision = yield* AWS.DataExchange.Revision("PricesV1", {
77 * dataSetId: dataSet.dataSetId,
78 * comment: "Initial snapshot",
79 * });
80 * ```
81 *
82 * ### Finalizing
83 * Once assets have been imported into the revision (via a DataExchange
84 * import job), flip `finalized` to publish it. Finalizing an empty revision
85 * fails.
86 *
87 * **Example:** Finalize a revision that has assets
88 * ```typescript
89 * const revision = yield* AWS.DataExchange.Revision("PricesV1", {
90 * dataSetId: dataSet.dataSetId,
91 * comment: "Initial snapshot",
92 * finalized: true,
93 * });
94 * ```
95 *
96 * @resource
97 */
98 export const Revision = Resource<Revision>("AWS.DataExchange.Revision");
99
100 export const RevisionProvider = () =>
101 Provider.effect(
102 Revision,
103 Effect.gen(function* () {
104 /** Get a revision by ids; typed not-found → undefined. */
105 const getById = Effect.fn(function* (dataSetId: string, revisionId: string) {
106 return yield* dataexchange
107 .getRevision({ DataSetId: dataSetId, RevisionId: revisionId })
108 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
109 });
110
111 /**
112 * Scan a data set's revisions for one carrying our ownership tags.
113 * Revision ids are server-generated, so recovery from a lost output
114 * (state-persistence failure) goes through per-revision tag inspection.
115 */
116 const findByTags = Effect.fn(function* (id: string, dataSetId: string) {
117 return yield* dataexchange.listDataSetRevisions.items({ DataSetId: dataSetId }).pipe(
118 Stream.mapEffect(
119 Effect.fn(function* (entry) {
120 const tags = yield* readDataExchangeTags(entry.Arn);
121 return (yield* hasAlchemyTags(id, tags)) ? entry : undefined;
122 }),
123 ),
124 Stream.filter((entry) => entry !== undefined),
125 Stream.runHead,
126 Effect.map((head) => (head._tag === "Some" ? head.value : undefined)),
127 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
128 );
129 });
130
131 return {
132 stables: ["revisionId", "revisionArn", "dataSetId"],
133
134 read: Effect.fn(function* ({ id, olds, output }) {
135 const dataSetId = output?.dataSetId ?? olds?.dataSetId;
136 if (dataSetId === undefined) return undefined;
137 const revision = output?.revisionId
138 ? yield* getById(dataSetId, output.revisionId)
139 : yield* findByTags(id, dataSetId);
140 if (revision === undefined) return undefined;
141 const attrs = {
142 revisionId: revision.Id!,
143 revisionArn: revision.Arn!,
144 dataSetId,
145 finalized: revision.Finalized ?? false,
146 };
147 const tags = yield* readDataExchangeTags(attrs.revisionArn);
148 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
149 }),
150
151 diff: Effect.fn(function* ({ news, olds }) {
152 if (!isResolved(news)) return undefined;
153 if ((news.dataSetId as string) !== (olds.dataSetId as string)) {
154 return { action: "replace" } as const;
155 }
156 }),
157
158 reconcile: Effect.fn(function* ({ id, news, output, session }) {
159 const dataSetId = news.dataSetId as string;
160 const internalTags = yield* createInternalTags(id);
161 const desiredTags = { ...news.tags, ...internalTags };
162 const desiredFinalized = news.finalized ?? false;
163
164 // 1. Observe — output ids are only a cache; fall back to a
165 // tag-ownership scan of the data set's revisions.
166 let revision = output?.revisionId
167 ? yield* getById(dataSetId, output.revisionId)
168 : undefined;
169 if (revision === undefined) {
170 revision = yield* findByTags(id, dataSetId);
171 }
172
173 // 2. Ensure — create when missing.
174 if (revision === undefined) {
175 revision = yield* dataexchange.createRevision({
176 DataSetId: dataSetId,
177 Comment: news.comment,
178 Tags: desiredTags,
179 });
180 }
181
182 // 3. Sync — comment and finalized are mutable in one call. Only
183 // call the API on an actual delta.
184 if (
185 (revision.Comment ?? undefined) !== (news.comment ?? undefined) ||
186 (revision.Finalized ?? false) !== desiredFinalized
187 ) {
188 revision = yield* dataexchange.updateRevision({
189 DataSetId: dataSetId,
190 RevisionId: revision.Id!,
191 Comment: news.comment,
192 Finalized: desiredFinalized,
193 });
194 }
195
196 // 3b. Sync tags against OBSERVED cloud tags (adoption-safe).
197 yield* syncDataExchangeTags(revision.Arn!, desiredTags);
198
199 yield* session.note(revision.Arn!);
200 return {
201 revisionId: revision.Id!,
202 revisionArn: revision.Arn!,
203 dataSetId,
204 finalized: revision.Finalized ?? false,
205 };
206 }),
207
208 delete: Effect.fn(function* ({ output }) {
209 yield* dataexchange
210 .deleteRevision({
211 DataSetId: output.dataSetId,
212 RevisionId: output.revisionId,
213 })
214 .pipe(
215 // Asset deletions inside the revision can transiently conflict.
216 Effect.retry({
217 while: (e) => e._tag === "ConflictException",
218 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
219 }),
220 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
221 );
222 }),
223
224 // Revisions are sub-resources keyed by their parent data set; there
225 // is no account-level enumeration into a parentless Attributes shape.
226 list: () => Effect.succeed([]),
227 };
228 }),
229 );