@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, 06:00 UTC

main
ts 288 lines 10.7 KB
Raw
1 import * as b2bi from "@distilled.cloud/aws/b2bi";
2 import { unownedUnlessPrevious } 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 Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import { readB2biTags, syncB2biTags, toWireTags } from "./internal.ts";
12
13 export class TransformerInvalidProps extends Data.TaggedError("TransformerInvalidProps")<{
14 readonly message: string;
15 readonly cause?: unknown;
16 }> {}
17
18 export interface TransformerProps {
19 /**
20 * The name of the transformer.
21 */
22 name: string;
23 /**
24 * The transformer's processing state. Newly created transformers default
25 * to `inactive`; set to `active` to make the transformer usable by a
26 * capability. Activation is one-way: an active transformer rejects every
27 * update (including deactivation), so changing the configuration, name, or
28 * status of an active transformer replaces it.
29 * @default "inactive"
30 */
31 status?: "active" | "inactive";
32 /**
33 * Describes the format of the source document (e.g. X12 EDI) and any
34 * advanced options for parsing it.
35 */
36 inputConversion?: b2bi.InputConversion;
37 /**
38 * The mapping template (JSONATA or XSLT) that transforms the input
39 * document into the output format.
40 */
41 mapping?: b2bi.Mapping;
42 /**
43 * Describes the format of the output document (e.g. X12 EDI) for outbound
44 * transformers.
45 */
46 outputConversion?: b2bi.OutputConversion;
47 /**
48 * Locations of sample input and output documents used to test the
49 * transformer.
50 */
51 sampleDocuments?: b2bi.SampleDocuments;
52 /**
53 * User-defined tags for the transformer.
54 */
55 tags?: Record<string, string>;
56 }
57
58 export interface Transformer extends Resource<
59 "AWS.B2BI.Transformer",
60 TransformerProps,
61 {
62 /**
63 * Service-assigned unique ID of the transformer.
64 */
65 transformerId: string;
66 /**
67 * ARN of the transformer.
68 */
69 transformerArn: string;
70 /**
71 * Name of the transformer.
72 */
73 name: string;
74 /**
75 * Current status (`active` or `inactive`).
76 */
77 status: string;
78 },
79 never,
80 Providers
81 > {}
82
83 /**
84 * An AWS B2B Data Interchange (B2BI) transformer. A transformer describes
85 * how to convert inbound EDI documents to a target format (or the reverse)
86 * using a mapping template. Transformers are credential-free and testable.
87 *
88 * Activation is one-way: B2BI rejects every update to an `active`
89 * transformer, including a status-only deactivation, so changing the
90 * configuration, name, or status of an active transformer replaces it
91 * (delete-first). Deletion works regardless of status.
92 * ### Creating a Transformer
93 * **Example:** Inbound X12 to JSON
94 * ```typescript
95 * const transformer = yield* B2BI.Transformer("X12ToJson", {
96 * name: "x12-to-json",
97 * status: "active",
98 * inputConversion: {
99 * fromFormat: "X12",
100 * formatOptions: { x12: { transactionSet: "X12_850", version: "VERSION_4010" } },
101 * },
102 * mapping: {
103 * templateLanguage: "JSONATA",
104 * template: "{ \"orderId\": transactionSets[0].St.transactionSetControlNumber }",
105 * },
106 * });
107 * ```
108 *
109 * @resource
110 */
111 export const Transformer = Resource<Transformer>("AWS.B2BI.Transformer");
112
113 const toAttrs = (
114 r: b2bi.GetTransformerResponse | b2bi.CreateTransformerResponse | b2bi.UpdateTransformerResponse,
115 ) => ({
116 transformerId: r.transformerId,
117 transformerArn: r.transformerArn,
118 name: r.name,
119 status: r.status,
120 });
121
122 /** JSON fingerprint of the mutable transformer configuration. */
123 const spec = (
124 props: Pick<
125 TransformerProps,
126 "inputConversion" | "mapping" | "outputConversion" | "sampleDocuments"
127 >,
128 ): string =>
129 JSON.stringify({
130 inputConversion: props.inputConversion ?? null,
131 mapping: props.mapping ?? null,
132 outputConversion: props.outputConversion ?? null,
133 sampleDocuments: props.sampleDocuments ?? null,
134 });
135
136 export const TransformerProvider = () =>
137 Provider.effect(
138 Transformer,
139 Effect.gen(function* () {
140 const findByName = (name: string) =>
141 b2bi.listTransformers.items({}).pipe(
142 Stream.filter((s) => s.name === name),
143 Stream.runHead,
144 Effect.flatMap((head) =>
145 head._tag === "Some"
146 ? b2bi
147 .getTransformer({ transformerId: head.value.transformerId })
148 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined))
149 : Effect.undefined,
150 ),
151 );
152
153 return {
154 stables: ["transformerId", "transformerArn"],
155
156 diff: Effect.fn(function* ({ olds, news }) {
157 if (!isResolved(news)) return undefined;
158 // An ACTIVE transformer rejects every update — including a
159 // status-only deactivation ("An active Transformer cannot be
160 // updated", verified live) — so any change away from a deployed
161 // active state forces a replacement. Delete-first: transformer
162 // names are how lost state is recovered (findByName), so the old
163 // instance must be gone before the new one is created.
164 if (olds.status === "active") {
165 const changed =
166 spec(olds) !== spec(news) ||
167 olds.name !== news.name ||
168 (news.status ?? "inactive") !== "active";
169 if (changed) {
170 return { action: "replace", deleteFirst: true } as const;
171 }
172 }
173 }),
174
175 read: Effect.fn(function* ({ id, olds, output, previous }) {
176 const found = output?.transformerId
177 ? yield* b2bi
178 .getTransformer({ transformerId: output.transformerId })
179 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined))
180 : yield* findByName(olds?.name ?? "");
181 if (found === undefined) return undefined;
182 const attrs = toAttrs(found);
183 const tags = yield* readB2biTags(attrs.transformerArn);
184 return (yield* hasAlchemyTags(id, tags))
185 ? attrs
186 : unownedUnlessPrevious(attrs, previous, "transformerId");
187 }),
188
189 reconcile: Effect.fn(function* ({ id, news, output, session }) {
190 const internalTags = yield* createInternalTags(id);
191 const desiredTags = { ...internalTags, ...news.tags };
192 const desiredStatus = news.status ?? "inactive";
193
194 // 1. Observe.
195 let live = output?.transformerId
196 ? yield* b2bi
197 .getTransformer({ transformerId: output.transformerId })
198 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined))
199 : yield* findByName(news.name);
200
201 // 2. Ensure.
202 if (live === undefined) {
203 const created = yield* b2bi.createTransformer({
204 name: news.name,
205 inputConversion: news.inputConversion,
206 mapping: news.mapping,
207 outputConversion: news.outputConversion,
208 sampleDocuments: news.sampleDocuments,
209 tags: toWireTags(desiredTags),
210 });
211 live = yield* b2bi.getTransformer({
212 transformerId: created.transformerId,
213 });
214 }
215
216 // 3. Sync — converge name/config while the transformer is still
217 // inactive, then activate last. An ACTIVE transformer rejects every
218 // update (including a status-only deactivation), so drift against
219 // an active transformer cannot be converged in place — `diff`
220 // reports those changes as a delete-first replacement.
221 const configDrift = spec(live) !== spec(news);
222 const nameDrift = live.name !== news.name;
223 const statusDrift = live.status !== desiredStatus;
224 if (live.status === "active" && (configDrift || nameDrift)) {
225 return yield* new TransformerInvalidProps({
226 message: `Transformer '${live.transformerId}' is active and cannot be updated in place — B2BI rejects every update to an active transformer. Replace it instead.`,
227 });
228 }
229 if (configDrift || nameDrift) {
230 // Config update carries NO status field (a status change in the
231 // same call as a config change is rejected).
232 const updated = yield* b2bi.updateTransformer({
233 transformerId: live.transformerId,
234 name: news.name,
235 inputConversion: news.inputConversion,
236 mapping: news.mapping,
237 outputConversion: news.outputConversion,
238 sampleDocuments: news.sampleDocuments,
239 });
240 live = { ...live, ...updated };
241 }
242 if (statusDrift && desiredStatus === "active") {
243 const updated = yield* b2bi.updateTransformer({
244 transformerId: live.transformerId,
245 status: "active",
246 });
247 live = { ...live, ...updated };
248 }
249
250 // 3b. Sync tags.
251 yield* syncB2biTags(live.transformerArn, desiredTags);
252
253 yield* session.note(live.transformerId);
254 return toAttrs(live);
255 }),
256
257 delete: Effect.fn(function* ({ output }) {
258 // deleteTransformer works on both active and inactive transformers
259 // (verified live) — no deactivation step is needed (nor possible:
260 // an active transformer rejects all updates).
261 yield* b2bi
262 .deleteTransformer({ transformerId: output.transformerId })
263 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
264 // NOTE: transformer creation auto-creates the shared account-level
265 // /aws/vendedlogs/b2bi/transformers log group. That group is a
266 // service-managed singleton (like a service-linked role) and MUST
267 // NOT be reaped here: B2BI's internal log-delivery bookkeeping
268 // references it, and deleting it opens a ~60-90s window where every
269 // subsequent createTransformer in the account fails with
270 // "Unable to perform CreateLogDelivery. Log destination resource
271 // /aws/vendedlogs/b2bi/transformers was not found" (verified live).
272 }),
273
274 list: () =>
275 b2bi.listTransformers.items({}).pipe(
276 Stream.mapEffect((s) =>
277 b2bi.getTransformer({ transformerId: s.transformerId }).pipe(
278 Effect.map(toAttrs),
279 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
280 ),
281 ),
282 Stream.filter((item) => item !== undefined),
283 Stream.runCollect,
284 Effect.map((chunk) => Array.from(chunk)),
285 ),
286 };
287 }),
288 );