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

main
ts 302 lines 10.8 KB
Raw
1 import * as iotfleetwise from "@distilled.cloud/aws/iotfleetwise";
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 Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import {
13 inFleetWiseRegion,
14 readFleetWiseTags,
15 retryObservation,
16 retryWhileConflict,
17 syncFleetWiseTags,
18 toFleetWiseTagList,
19 } from "./internal.ts";
20
21 export class ModelManifestUnexpectedResponse extends Data.TaggedError(
22 "ModelManifestUnexpectedResponse",
23 )<{
24 readonly message: string;
25 readonly cause?: unknown;
26 }> {}
27
28 export interface ModelManifestProps {
29 /**
30 * Name of the model manifest. Must be 1-100 characters of
31 * `[a-zA-Z0-9:_-]`. If omitted, a deterministic physical name is
32 * generated. Changing the name replaces the manifest.
33 */
34 modelManifestName?: string;
35 /**
36 * ARN of the {@link SignalCatalog} the manifest's nodes come from.
37 * Changing the signal catalog replaces the manifest.
38 */
39 signalCatalogArn: string;
40 /**
41 * Fully qualified names of the signal-catalog nodes included in the
42 * vehicle model, e.g. `["Vehicle.Speed"]`. Updated in place via
43 * `nodesToAdd`/`nodesToRemove` deltas (only while the manifest is in
44 * `DRAFT` status).
45 */
46 nodes: string[];
47 /**
48 * Human-readable description of the model manifest.
49 */
50 description?: string;
51 /**
52 * Status of the manifest. Vehicles can only be created from an `ACTIVE`
53 * manifest; node changes require `DRAFT`.
54 * @default "DRAFT"
55 */
56 status?: "ACTIVE" | "DRAFT";
57 /**
58 * User-defined tags for the model manifest.
59 */
60 tags?: Record<string, string>;
61 }
62
63 export interface ModelManifest extends Resource<
64 "AWS.IoTFleetWise.ModelManifest",
65 ModelManifestProps,
66 {
67 /** The name of the model manifest. */
68 modelManifestName: string;
69 /** The ARN of the model manifest. */
70 modelManifestArn: string;
71 /** The current status of the manifest (`ACTIVE`, `DRAFT`, ...). */
72 status: string;
73 /** The signal catalog the manifest's nodes come from. */
74 signalCatalogArn: string | undefined;
75 },
76 never,
77 Providers
78 > {}
79
80 /**
81 * An AWS IoT FleetWise model manifest (vehicle model) — the subset of
82 * signal-catalog nodes that describes one vehicle type.
83 *
84 * A manifest is created in `DRAFT` status; set `status: "ACTIVE"` to make
85 * it usable by decoder manifests and vehicles. AWS IoT FleetWise is
86 * allowlist-gated and offered in `us-east-1`/`eu-central-1` only.
87 * ### Creating a Model Manifest
88 * **Example:** Active Vehicle Model
89 * ```typescript
90 * const model = yield* ModelManifest("SedanModel", {
91 * signalCatalogArn: catalog.signalCatalogArn,
92 * nodes: ["Vehicle.Speed"],
93 * status: "ACTIVE",
94 * });
95 * ```
96 *
97 * **Example:** Draft Model with Description
98 * ```typescript
99 * const model = yield* ModelManifest("SedanModel", {
100 * signalCatalogArn: catalog.signalCatalogArn,
101 * nodes: ["Vehicle.Speed", "Vehicle.VIN"],
102 * description: "2026 sedan line",
103 * });
104 * ```
105 *
106 * @resource
107 */
108 export const ModelManifest = Resource<ModelManifest>("AWS.IoTFleetWise.ModelManifest");
109
110 const nodeFqn = (node: iotfleetwise.Node): string =>
111 node.branch?.fullyQualifiedName ??
112 node.sensor?.fullyQualifiedName ??
113 node.actuator?.fullyQualifiedName ??
114 node.attribute?.fullyQualifiedName ??
115 node.struct?.fullyQualifiedName ??
116 node.property?.fullyQualifiedName ??
117 "";
118
119 export const ModelManifestProvider = () =>
120 Provider.effect(
121 ModelManifest,
122 Effect.gen(function* () {
123 const toName = (id: string, props: { modelManifestName?: string }) =>
124 props.modelManifestName
125 ? Effect.succeed(props.modelManifestName)
126 : createPhysicalName({ id, maxLength: 100 });
127
128 const readManifest = Effect.fn(function* (name: string) {
129 return yield* iotfleetwise.getModelManifest({ name }).pipe(
130 inFleetWiseRegion,
131 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
132 );
133 });
134
135 const readNodeFqns = Effect.fn(function* (name: string) {
136 const nodes = yield* iotfleetwise.listModelManifestNodes.items({ name }).pipe(
137 Stream.runCollect,
138 Effect.map((chunk) => Array.from(chunk)),
139 inFleetWiseRegion,
140 );
141 return nodes.map(nodeFqn);
142 });
143
144 const toAttrs = (manifest: iotfleetwise.GetModelManifestResponse) => ({
145 modelManifestName: manifest.name,
146 modelManifestArn: manifest.arn,
147 status: manifest.status ?? "DRAFT",
148 signalCatalogArn: manifest.signalCatalogArn,
149 });
150
151 return {
152 stables: ["modelManifestName", "modelManifestArn"],
153
154 diff: Effect.fn(function* ({ id, olds, news }) {
155 if (!isResolved(news)) return undefined;
156 if ((yield* toName(id, olds)) !== (yield* toName(id, news))) {
157 return { action: "replace" } as const;
158 }
159 // The update API cannot change the signal catalog.
160 if (news.signalCatalogArn !== olds.signalCatalogArn) {
161 return { action: "replace" } as const;
162 }
163 }),
164
165 read: Effect.fn(function* ({ id, olds, output }) {
166 const name = output?.modelManifestName ?? (yield* toName(id, olds ?? {}));
167 const found = yield* readManifest(name);
168 if (found === undefined) return undefined;
169 const attrs = toAttrs(found);
170 const tags = yield* readFleetWiseTags(found.arn);
171 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
172 }),
173
174 reconcile: Effect.fn(function* ({ id, news, output, session }) {
175 const name = output?.modelManifestName ?? (yield* toName(id, news));
176 const internalTags = yield* createInternalTags(id);
177 const desiredTags = { ...internalTags, ...news.tags };
178 const desiredStatus = news.status ?? "DRAFT";
179
180 // 1. Observe — cloud state is authoritative.
181 let observed = yield* readManifest(name);
182
183 // 2. Ensure — create if missing; tolerate the AlreadyExists race.
184 if (observed === undefined) {
185 yield* iotfleetwise
186 .createModelManifest({
187 name,
188 nodes: news.nodes,
189 signalCatalogArn: news.signalCatalogArn,
190 description: news.description,
191 tags: toFleetWiseTagList(desiredTags),
192 })
193 .pipe(
194 inFleetWiseRegion,
195 Effect.catchTag("ConflictException", () => Effect.void),
196 );
197 observed = yield* readManifest(name).pipe(
198 Effect.flatMap((manifest) =>
199 manifest === undefined
200 ? Effect.fail(
201 new ModelManifestUnexpectedResponse({
202 message: `Model manifest '${name}' not found`,
203 }),
204 )
205 : Effect.succeed(manifest),
206 ),
207 retryObservation,
208 );
209 }
210
211 // 3. Sync nodes + description — diff OBSERVED node FQNs against
212 // the desired list. Node changes require DRAFT status, so they
213 // are applied before any DRAFT -> ACTIVE transition.
214 const observedFqns = yield* readNodeFqns(name);
215 const observedSet = new Set(observedFqns);
216 const desiredSet = new Set(news.nodes);
217 const nodesToAdd = news.nodes.filter((n) => !observedSet.has(n));
218 const nodesToRemove = observedFqns.filter((n) => !desiredSet.has(n));
219 const descriptionChanged =
220 news.description !== undefined && news.description !== observed.description;
221 if (nodesToAdd.length > 0 || nodesToRemove.length > 0 || descriptionChanged) {
222 yield* iotfleetwise
223 .updateModelManifest({
224 name,
225 description: descriptionChanged ? news.description : undefined,
226 nodesToAdd: nodesToAdd.length > 0 ? nodesToAdd : undefined,
227 nodesToRemove: nodesToRemove.length > 0 ? nodesToRemove : undefined,
228 })
229 .pipe(inFleetWiseRegion);
230 observed = yield* readManifest(name).pipe(
231 Effect.flatMap((manifest) =>
232 manifest === undefined
233 ? Effect.fail(
234 new ModelManifestUnexpectedResponse({
235 message: `Model manifest '${name}' not found`,
236 }),
237 )
238 : Effect.succeed(manifest),
239 ),
240 retryObservation,
241 );
242 }
243
244 // 3b. Sync status (e.g. activate a draft).
245 if ((observed.status ?? "DRAFT") !== desiredStatus) {
246 yield* iotfleetwise
247 .updateModelManifest({ name, status: desiredStatus })
248 .pipe(inFleetWiseRegion);
249 observed = yield* readManifest(name).pipe(
250 Effect.flatMap((manifest) =>
251 manifest === undefined
252 ? Effect.fail(
253 new ModelManifestUnexpectedResponse({
254 message: `Model manifest '${name}' not found`,
255 }),
256 )
257 : Effect.succeed(manifest),
258 ),
259 retryObservation,
260 );
261 }
262
263 // 3c. Sync tags against OBSERVED cloud tags.
264 yield* syncFleetWiseTags(observed.arn, desiredTags);
265
266 yield* session.note(name);
267 return toAttrs(observed);
268 }),
269
270 delete: Effect.fn(function* ({ output }) {
271 // Idempotent: deleting a missing manifest succeeds. Decoder
272 // manifests still detaching surface as ConflictException — retry
273 // through the window (bounded).
274 yield* iotfleetwise.deleteModelManifest({ name: output.modelManifestName }).pipe(
275 inFleetWiseRegion,
276 retryWhileConflict,
277 Effect.catchTag("ConflictException", () => Effect.void),
278 );
279 }),
280
281 list: () =>
282 iotfleetwise.listModelManifests.items({}).pipe(
283 Stream.runCollect,
284 Effect.map((chunk) =>
285 Array.from(chunk).flatMap((summary) =>
286 summary.name !== undefined && summary.arn !== undefined
287 ? [
288 {
289 modelManifestName: summary.name,
290 modelManifestArn: summary.arn,
291 status: summary.status ?? "DRAFT",
292 signalCatalogArn: summary.signalCatalogArn,
293 },
294 ]
295 : [],
296 ),
297 ),
298 inFleetWiseRegion,
299 ),
300 };
301 }),
302 );