@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 302 lines 11.1 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 StateTemplateUnexpectedResponse extends Data.TaggedError(
22 "StateTemplateUnexpectedResponse",
23 )<{
24 readonly message: string;
25 readonly cause?: unknown;
26 }> {}
27
28 export interface StateTemplateProps {
29 /**
30 * Name of the state template. 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 state template.
33 */
34 stateTemplateName?: string;
35 /**
36 * Human-readable description of the state template. Updated in place.
37 */
38 description?: string;
39 /**
40 * ARN of the {@link SignalCatalog} the state template's signals come
41 * from. Changing it replaces the state template.
42 */
43 signalCatalogArn: string;
44 /**
45 * Fully qualified names of the signals whose last-known state the
46 * template tracks, e.g. `["Vehicle.Speed"]`. Synced in place via
47 * add/remove deltas.
48 */
49 stateTemplateProperties: string[];
50 /**
51 * Vehicle attribute node paths added as extra dimensions on the state
52 * data, e.g. `["Vehicle.VIN"]`. Updated in place.
53 */
54 dataExtraDimensions?: string[];
55 /**
56 * Vehicle attribute node paths added as extra dimensions on the MQTT
57 * message metadata, e.g. `["Vehicle.VIN"]`. Updated in place.
58 */
59 metadataExtraDimensions?: string[];
60 /**
61 * User-defined tags for the state template.
62 */
63 tags?: Record<string, string>;
64 }
65
66 export interface StateTemplate extends Resource<
67 "AWS.IoTFleetWise.StateTemplate",
68 StateTemplateProps,
69 {
70 /** The name of the state template. */
71 stateTemplateName: string;
72 /** The ARN of the state template. */
73 stateTemplateArn: string;
74 /** The unique ID of the state template. */
75 stateTemplateId: string | undefined;
76 /** The signal catalog the state template's signals come from. */
77 signalCatalogArn: string | undefined;
78 /** The signals whose last-known state the template tracks. */
79 stateTemplateProperties: string[];
80 },
81 never,
82 Providers
83 > {}
84
85 /**
86 * An AWS IoT FleetWise state template — a definition of which signals'
87 * last-known state the Edge Agent reports for a {@link Vehicle}
88 * (associated via the vehicle's `stateTemplates` prop).
89 *
90 * Only the description, tracked properties, and extra dimensions are
91 * mutable — changing the name or signal catalog replaces the template.
92 * AWS IoT FleetWise is allowlist-gated and offered in
93 * `us-east-1`/`eu-central-1` only.
94 * ### Creating a State Template
95 * **Example:** Track Last-Known Speed
96 * ```typescript
97 * const template = yield* StateTemplate("SpeedState", {
98 * signalCatalogArn: catalog.signalCatalogArn,
99 * stateTemplateProperties: ["Vehicle.Speed"],
100 * });
101 * ```
102 *
103 * **Example:** Associate with a Vehicle
104 * ```typescript
105 * const vehicle = yield* Vehicle("TestVehicle", {
106 * modelManifestArn: model.modelManifestArn,
107 * decoderManifestArn: decoder.decoderManifestArn,
108 * stateTemplates: [
109 * {
110 * identifier: template.stateTemplateName,
111 * stateTemplateUpdateStrategy: { onChange: {} },
112 * },
113 * ],
114 * });
115 * ```
116 *
117 * @resource
118 */
119 export const StateTemplate = Resource<StateTemplate>("AWS.IoTFleetWise.StateTemplate");
120
121 export const StateTemplateProvider = () =>
122 Provider.effect(
123 StateTemplate,
124 Effect.gen(function* () {
125 const toName = (id: string, props: { stateTemplateName?: string }) =>
126 props.stateTemplateName
127 ? Effect.succeed(props.stateTemplateName)
128 : createPhysicalName({ id, maxLength: 100 });
129
130 const readTemplate = Effect.fn(function* (identifier: string) {
131 return yield* iotfleetwise.getStateTemplate({ identifier }).pipe(
132 inFleetWiseRegion,
133 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
134 );
135 });
136
137 const toAttrs = Effect.fn(function* (template: iotfleetwise.GetStateTemplateResponse) {
138 if (template.name === undefined || template.arn === undefined) {
139 return yield* new StateTemplateUnexpectedResponse({
140 message: `StateTemplate '${template.name}' is missing its ARN`,
141 });
142 }
143 return {
144 stateTemplateName: template.name,
145 stateTemplateArn: template.arn,
146 stateTemplateId: template.id,
147 signalCatalogArn: template.signalCatalogArn,
148 stateTemplateProperties: [...(template.stateTemplateProperties ?? [])],
149 };
150 });
151
152 return {
153 stables: ["stateTemplateName", "stateTemplateArn", "stateTemplateId"],
154
155 diff: Effect.fn(function* ({ id, olds, news }) {
156 if (!isResolved(news)) return undefined;
157 if ((yield* toName(id, olds)) !== (yield* toName(id, news))) {
158 return { action: "replace" } as const;
159 }
160 // The backing signal catalog is fixed at creation.
161 if (olds.signalCatalogArn !== news.signalCatalogArn) {
162 return { action: "replace" } as const;
163 }
164 }),
165
166 read: Effect.fn(function* ({ id, olds, output }) {
167 const name = output?.stateTemplateName ?? (yield* toName(id, olds ?? {}));
168 const found = yield* readTemplate(name);
169 if (found?.arn === undefined) return undefined;
170 const attrs = yield* toAttrs(found);
171 const tags = yield* readFleetWiseTags(found.arn);
172 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
173 }),
174
175 reconcile: Effect.fn(function* ({ id, news, output, session }) {
176 const name = output?.stateTemplateName ?? (yield* toName(id, news));
177 const internalTags = yield* createInternalTags(id);
178 const desiredTags = { ...internalTags, ...news.tags };
179
180 // 1. Observe — cloud state is authoritative.
181 let observed = yield* readTemplate(name);
182
183 // 2. Ensure — create if missing; tolerate the AlreadyExists race.
184 if (observed === undefined) {
185 yield* iotfleetwise
186 .createStateTemplate({
187 name,
188 description: news.description,
189 signalCatalogArn: news.signalCatalogArn,
190 stateTemplateProperties: news.stateTemplateProperties,
191 dataExtraDimensions: news.dataExtraDimensions,
192 metadataExtraDimensions: news.metadataExtraDimensions,
193 tags: toFleetWiseTagList(desiredTags),
194 })
195 .pipe(
196 inFleetWiseRegion,
197 Effect.catchTag("ConflictException", () => Effect.void),
198 );
199 observed = yield* readTemplate(name).pipe(
200 Effect.flatMap((template) =>
201 template === undefined
202 ? Effect.fail(
203 new StateTemplateUnexpectedResponse({
204 message: `StateTemplate '${name}' not found`,
205 }),
206 )
207 : Effect.succeed(template),
208 ),
209 retryObservation,
210 );
211 }
212
213 // 3. Sync mutable aspects against OBSERVED cloud state.
214 const observedProperties = observed.stateTemplateProperties ?? [];
215 const toAdd = news.stateTemplateProperties.filter(
216 (fqn) => !observedProperties.includes(fqn),
217 );
218 const toRemove = observedProperties.filter(
219 (fqn) => !news.stateTemplateProperties.includes(fqn),
220 );
221 const descriptionChanged =
222 news.description !== undefined && news.description !== observed.description;
223 const dataDimensionsChanged =
224 news.dataExtraDimensions !== undefined &&
225 !stableEquals(observed.dataExtraDimensions ?? [], news.dataExtraDimensions);
226 const metadataDimensionsChanged =
227 news.metadataExtraDimensions !== undefined &&
228 !stableEquals(observed.metadataExtraDimensions ?? [], news.metadataExtraDimensions);
229 if (
230 toAdd.length > 0 ||
231 toRemove.length > 0 ||
232 descriptionChanged ||
233 dataDimensionsChanged ||
234 metadataDimensionsChanged
235 ) {
236 yield* iotfleetwise
237 .updateStateTemplate({
238 identifier: name,
239 description: descriptionChanged ? news.description : undefined,
240 stateTemplatePropertiesToAdd: toAdd.length > 0 ? toAdd : undefined,
241 stateTemplatePropertiesToRemove: toRemove.length > 0 ? toRemove : undefined,
242 dataExtraDimensions: dataDimensionsChanged ? news.dataExtraDimensions : undefined,
243 metadataExtraDimensions: metadataDimensionsChanged
244 ? news.metadataExtraDimensions
245 : undefined,
246 })
247 .pipe(inFleetWiseRegion);
248 observed = yield* readTemplate(name).pipe(
249 Effect.flatMap((template) =>
250 template === undefined
251 ? Effect.fail(
252 new StateTemplateUnexpectedResponse({
253 message: `StateTemplate '${name}' not found`,
254 }),
255 )
256 : Effect.succeed(template),
257 ),
258 retryObservation,
259 );
260 }
261
262 // 3b. Sync tags against OBSERVED cloud tags.
263 const arn = observed.arn;
264 if (arn !== undefined) {
265 yield* syncFleetWiseTags(arn, desiredTags);
266 }
267
268 yield* session.note(name);
269 return yield* toAttrs(observed);
270 }),
271
272 delete: Effect.fn(function* ({ output }) {
273 // DeleteStateTemplate is idempotent — deleting a missing template
274 // succeeds (its error union carries no not-found tag).
275 yield* iotfleetwise
276 .deleteStateTemplate({ identifier: output.stateTemplateName })
277 .pipe(inFleetWiseRegion);
278 }),
279
280 list: () =>
281 iotfleetwise.listStateTemplates.items({}).pipe(
282 Stream.runCollect,
283 Effect.map((chunk) =>
284 Array.from(chunk).flatMap((summary) =>
285 summary.name !== undefined && summary.arn !== undefined
286 ? [
287 {
288 stateTemplateName: summary.name,
289 stateTemplateArn: summary.arn,
290 stateTemplateId: summary.id,
291 signalCatalogArn: summary.signalCatalogArn,
292 stateTemplateProperties: [] as string[],
293 },
294 ]
295 : [],
296 ),
297 ),
298 inFleetWiseRegion,
299 ),
300 };
301 }),
302 );