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

main
ts 338 lines 12.7 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 stableEquals,
17 syncFleetWiseTags,
18 toFleetWiseTagList,
19 } from "./internal.ts";
20
21 export class VehicleUnexpectedResponse extends Data.TaggedError("VehicleUnexpectedResponse")<{
22 readonly message: string;
23 readonly cause?: unknown;
24 }> {}
25
26 export interface VehicleProps {
27 /**
28 * Name of the vehicle. Must be 1-100 characters of `[a-zA-Z0-9:_-]` and
29 * match the corresponding AWS IoT thing name. If omitted, a
30 * deterministic physical name is generated. Changing the name replaces
31 * the vehicle.
32 */
33 vehicleName?: string;
34 /**
35 * ARN of an `ACTIVE` {@link ModelManifest} the vehicle is modeled by.
36 * Updated in place.
37 */
38 modelManifestArn: string;
39 /**
40 * ARN of an `ACTIVE` {@link DecoderManifest} associated with the model
41 * manifest. Updated in place.
42 */
43 decoderManifestArn: string;
44 /**
45 * Static attribute values (key/value strings) for attributes defined in
46 * the model manifest, e.g. `{ "Vehicle.VIN": "1HGBH..." }`. Synced in
47 * place with `attributeUpdateMode: "Overwrite"`.
48 */
49 attributes?: Record<string, string>;
50 /**
51 * Whether to create a new AWS IoT thing for the vehicle
52 * (`"CreateIotThing"`) or validate an existing thing
53 * (`"ValidateIotThingExists"`). Applied at creation only; changing it
54 * replaces the vehicle.
55 * @default "CreateIotThing"
56 */
57 associationBehavior?: iotfleetwise.VehicleAssociationBehavior;
58 /**
59 * State templates associated with the vehicle — each pairs a
60 * {@link StateTemplate} identifier (name or ARN) with an update strategy
61 * (`{ onChange: {} }` or `{ periodic: { stateTemplateUpdateRate } }`).
62 * Synced in place via add/remove/update deltas.
63 */
64 stateTemplates?: iotfleetwise.StateTemplateAssociation[];
65 /**
66 * User-defined tags for the vehicle.
67 */
68 tags?: Record<string, string>;
69 }
70
71 export interface Vehicle extends Resource<
72 "AWS.IoTFleetWise.Vehicle",
73 VehicleProps,
74 {
75 /** The name of the vehicle (also the backing IoT thing name). */
76 vehicleName: string;
77 /** The ARN of the vehicle. */
78 vehicleArn: string;
79 /** The model manifest the vehicle conforms to. */
80 modelManifestArn: string;
81 /** The decoder manifest the vehicle uses. */
82 decoderManifestArn: string;
83 /** The static attributes stored on the vehicle. */
84 attributes: Record<string, string>;
85 },
86 never,
87 Providers
88 > {}
89
90 /**
91 * An AWS IoT FleetWise vehicle — the digital twin of a physical vehicle,
92 * created from an `ACTIVE` {@link ModelManifest} and
93 * {@link DecoderManifest} pair and backed by an AWS IoT thing.
94 * ### Creating a Vehicle
95 * **Example:** Vehicle with an Auto-Created IoT Thing
96 * ```typescript
97 * const vehicle = yield* Vehicle("TestVehicle", {
98 * modelManifestArn: model.modelManifestArn,
99 * decoderManifestArn: decoder.decoderManifestArn,
100 * });
101 * ```
102 *
103 * **Example:** Vehicle with Attributes
104 * ```typescript
105 * const vehicle = yield* Vehicle("TestVehicle", {
106 * modelManifestArn: model.modelManifestArn,
107 * decoderManifestArn: decoder.decoderManifestArn,
108 * attributes: { "Vehicle.VIN": "1HGBH41JXMN109186" },
109 * tags: { plant: "fremont" },
110 * });
111 * ```
112 *
113 * @resource
114 */
115 export const Vehicle = Resource<Vehicle>("AWS.IoTFleetWise.Vehicle");
116
117 const toAttributeRecord = (
118 attributes: { [key: string]: string | undefined } | undefined,
119 ): Record<string, string> =>
120 Object.fromEntries(
121 Object.entries(attributes ?? {}).flatMap(([key, value]) =>
122 value !== undefined ? [[key, value]] : [],
123 ),
124 );
125
126 export const VehicleProvider = () =>
127 Provider.effect(
128 Vehicle,
129 Effect.gen(function* () {
130 const toName = (id: string, props: { vehicleName?: string }) =>
131 props.vehicleName
132 ? Effect.succeed(props.vehicleName)
133 : createPhysicalName({ id, maxLength: 100 });
134
135 const readVehicle = Effect.fn(function* (vehicleName: string) {
136 return yield* iotfleetwise.getVehicle({ vehicleName }).pipe(
137 inFleetWiseRegion,
138 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
139 );
140 });
141
142 const toAttrs = Effect.fn(function* (vehicle: iotfleetwise.GetVehicleResponse) {
143 if (
144 vehicle.vehicleName === undefined ||
145 vehicle.arn === undefined ||
146 vehicle.modelManifestArn === undefined ||
147 vehicle.decoderManifestArn === undefined
148 ) {
149 return yield* new VehicleUnexpectedResponse({
150 message: `Vehicle '${vehicle.vehicleName}' is missing required fields`,
151 });
152 }
153 return {
154 vehicleName: vehicle.vehicleName,
155 vehicleArn: vehicle.arn,
156 modelManifestArn: vehicle.modelManifestArn,
157 decoderManifestArn: vehicle.decoderManifestArn,
158 attributes: toAttributeRecord(vehicle.attributes),
159 };
160 });
161
162 return {
163 stables: ["vehicleName", "vehicleArn"],
164
165 diff: Effect.fn(function* ({ id, olds, news }) {
166 if (!isResolved(news)) return undefined;
167 if ((yield* toName(id, olds)) !== (yield* toName(id, news))) {
168 return { action: "replace" } as const;
169 }
170 // The IoT-thing association is decided at creation time.
171 if (
172 (news.associationBehavior ?? "CreateIotThing") !==
173 (olds.associationBehavior ?? "CreateIotThing")
174 ) {
175 return { action: "replace" } as const;
176 }
177 }),
178
179 read: Effect.fn(function* ({ id, olds, output }) {
180 const name = output?.vehicleName ?? (yield* toName(id, olds ?? {}));
181 const found = yield* readVehicle(name);
182 if (found?.arn === undefined) return undefined;
183 const attrs = yield* toAttrs(found);
184 const tags = yield* readFleetWiseTags(found.arn);
185 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
186 }),
187
188 reconcile: Effect.fn(function* ({ id, news, output, session }) {
189 const name = output?.vehicleName ?? (yield* toName(id, news));
190 const internalTags = yield* createInternalTags(id);
191 const desiredTags = { ...internalTags, ...news.tags };
192
193 // 1. Observe — cloud state is authoritative.
194 let observed = yield* readVehicle(name);
195
196 // 2. Ensure — create if missing; tolerate the AlreadyExists race.
197 if (observed === undefined) {
198 yield* iotfleetwise
199 .createVehicle({
200 vehicleName: name,
201 modelManifestArn: news.modelManifestArn,
202 decoderManifestArn: news.decoderManifestArn,
203 attributes: news.attributes,
204 associationBehavior: news.associationBehavior ?? "CreateIotThing",
205 stateTemplates: news.stateTemplates,
206 tags: toFleetWiseTagList(desiredTags),
207 })
208 .pipe(
209 inFleetWiseRegion,
210 Effect.catchTag("ConflictException", () => Effect.void),
211 );
212 observed = yield* readVehicle(name).pipe(
213 Effect.flatMap((vehicle) =>
214 vehicle === undefined
215 ? Effect.fail(
216 new VehicleUnexpectedResponse({ message: `Vehicle '${name}' not found` }),
217 )
218 : Effect.succeed(vehicle),
219 ),
220 retryObservation,
221 );
222 }
223
224 // 3. Sync manifests + attributes — apply only the observed delta.
225 const manifestChanged =
226 observed.modelManifestArn !== news.modelManifestArn ||
227 observed.decoderManifestArn !== news.decoderManifestArn;
228 const attributesChanged =
229 news.attributes !== undefined &&
230 !stableEquals(toAttributeRecord(observed.attributes), news.attributes);
231 if (manifestChanged || attributesChanged) {
232 yield* iotfleetwise
233 .updateVehicle({
234 vehicleName: name,
235 modelManifestArn: manifestChanged ? news.modelManifestArn : undefined,
236 decoderManifestArn: manifestChanged ? news.decoderManifestArn : undefined,
237 attributes: attributesChanged ? news.attributes : undefined,
238 attributeUpdateMode: attributesChanged ? "Overwrite" : undefined,
239 })
240 .pipe(inFleetWiseRegion);
241 observed = yield* readVehicle(name).pipe(
242 Effect.flatMap((vehicle) =>
243 vehicle === undefined
244 ? Effect.fail(
245 new VehicleUnexpectedResponse({ message: `Vehicle '${name}' not found` }),
246 )
247 : Effect.succeed(vehicle),
248 ),
249 retryObservation,
250 );
251 }
252
253 // 3b. Sync state-template associations against OBSERVED state.
254 // Associations are keyed by identifier; strategy changes are
255 // applied via stateTemplatesToUpdate. Identifiers are matched
256 // exactly (pass the same name-or-ARN form consistently).
257 if (news.stateTemplates !== undefined) {
258 const desired = news.stateTemplates;
259 const observedAssociations = observed.stateTemplates ?? [];
260 const observedByIdentifier = new Map(
261 observedAssociations.map((a) => [a.identifier, a]),
262 );
263 const desiredIdentifiers = new Set(desired.map((a) => a.identifier));
264 const templatesToAdd = desired.filter((a) => !observedByIdentifier.has(a.identifier));
265 const templatesToUpdate = desired.filter((a) => {
266 const current = observedByIdentifier.get(a.identifier);
267 return (
268 current !== undefined &&
269 !stableEquals(current.stateTemplateUpdateStrategy, a.stateTemplateUpdateStrategy)
270 );
271 });
272 const templatesToRemove = observedAssociations
273 .filter((a) => !desiredIdentifiers.has(a.identifier))
274 .map((a) => a.identifier);
275 if (
276 templatesToAdd.length > 0 ||
277 templatesToUpdate.length > 0 ||
278 templatesToRemove.length > 0
279 ) {
280 yield* iotfleetwise
281 .updateVehicle({
282 vehicleName: name,
283 stateTemplatesToAdd: templatesToAdd.length > 0 ? templatesToAdd : undefined,
284 stateTemplatesToUpdate:
285 templatesToUpdate.length > 0 ? templatesToUpdate : undefined,
286 stateTemplatesToRemove:
287 templatesToRemove.length > 0 ? templatesToRemove : undefined,
288 })
289 .pipe(inFleetWiseRegion);
290 observed = yield* readVehicle(name).pipe(
291 Effect.flatMap((vehicle) =>
292 vehicle === undefined
293 ? Effect.fail(
294 new VehicleUnexpectedResponse({ message: `Vehicle '${name}' not found` }),
295 )
296 : Effect.succeed(vehicle),
297 ),
298 retryObservation,
299 );
300 }
301 }
302
303 // 3c. Sync tags against OBSERVED cloud tags.
304 const arn = observed.arn;
305 if (arn !== undefined) {
306 yield* syncFleetWiseTags(arn, desiredTags);
307 }
308
309 yield* session.note(name);
310 return yield* toAttrs(observed);
311 }),
312
313 delete: Effect.fn(function* ({ output }) {
314 // Idempotent: deleting a missing vehicle succeeds. The backing
315 // IoT thing (if auto-created) is left in place, matching AWS
316 // behavior.
317 yield* iotfleetwise
318 .deleteVehicle({ vehicleName: output.vehicleName })
319 .pipe(inFleetWiseRegion);
320 }),
321
322 list: () =>
323 iotfleetwise.listVehicles.items({}).pipe(
324 Stream.runCollect,
325 Effect.map((chunk) =>
326 Array.from(chunk).map((summary) => ({
327 vehicleName: summary.vehicleName,
328 vehicleArn: summary.arn,
329 modelManifestArn: summary.modelManifestArn,
330 decoderManifestArn: summary.decoderManifestArn,
331 attributes: toAttributeRecord(summary.attributes),
332 })),
333 ),
334 inFleetWiseRegion,
335 ),
336 };
337 }),
338 );