@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 556 lines 19.9 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 { toWireMillis, toWireSeconds } from "alchemy/Util/Duration";
9 import * as Data from "effect/Data";
10 import type * as Duration from "effect/Duration";
11 import * as Effect from "effect/Effect";
12 import type * as Redacted from "effect/Redacted";
13 import * as Stream from "effect/Stream";
14 import type { Providers } from "../Providers.ts";
15 import {
16 inFleetWiseRegion,
17 readFleetWiseTags,
18 retryObservation,
19 stableEquals,
20 syncFleetWiseTags,
21 toFleetWiseTagList,
22 } from "./internal.ts";
23
24 export class CampaignNotReady extends Data.TaggedError("CampaignNotReady")<{
25 readonly message: string;
26 readonly cause?: unknown;
27 }> {}
28
29 export class CampaignUnexpectedResponse extends Data.TaggedError("CampaignUnexpectedResponse")<{
30 readonly message: string;
31 readonly cause?: unknown;
32 }> {}
33
34 /**
35 * Time-based collection: collect the signals on a fixed cadence.
36 */
37 export interface TimeBasedCollectionScheme {
38 /**
39 * How often to collect the signals, e.g. `"10 seconds"` or
40 * `Duration.seconds(10)`. A bare number is milliseconds. Sent to
41 * FleetWise as whole milliseconds (`periodMs`, 50 ms - 60 s).
42 */
43 period: Duration.Input;
44 }
45
46 /**
47 * Condition-based collection: collect the signals whenever the expression
48 * evaluates true.
49 */
50 export interface ConditionBasedCollectionScheme {
51 /**
52 * The logical expression that triggers collection, e.g.
53 * `$variable.\`Vehicle.OutsideAirTemperature\` >= 105.0`.
54 */
55 expression: string | Redacted.Redacted<string>;
56 /**
57 * Minimum time between two triggers, e.g. `"1 second"`. A bare number
58 * is milliseconds. Sent to FleetWise as whole milliseconds
59 * (`minimumTriggerIntervalMs`).
60 * @default 0
61 */
62 minimumTriggerInterval?: Duration.Input;
63 /**
64 * Whether to trigger on every evaluation (`"ALWAYS"`) or only when the
65 * expression flips to true (`"RISING_EDGE"`).
66 * @default "ALWAYS"
67 */
68 triggerMode?: iotfleetwise.TriggerMode;
69 /**
70 * Version of the condition language.
71 * @default 1
72 */
73 conditionLanguageVersion?: number;
74 }
75
76 /**
77 * When to collect data — exactly one of a time-based or condition-based
78 * scheme.
79 */
80 export type CollectionScheme =
81 | {
82 timeBasedCollectionScheme: TimeBasedCollectionScheme;
83 conditionBasedCollectionScheme?: never;
84 }
85 | {
86 timeBasedCollectionScheme?: never;
87 conditionBasedCollectionScheme: ConditionBasedCollectionScheme;
88 };
89
90 /** A signal the campaign collects from vehicles. */
91 export interface SignalInformation {
92 /** The name of the signal, e.g. `Vehicle.Speed`. */
93 name: string;
94 /** Maximum number of samples collected per trigger. */
95 maxSampleCount?: number;
96 /**
97 * Minimum time between two samples of this signal, e.g. `"500 millis"`.
98 * A bare number is milliseconds. Sent to FleetWise as whole milliseconds
99 * (`minimumSamplingIntervalMs`).
100 */
101 minimumSamplingInterval?: Duration.Input;
102 /** The ID of the data partition the signal is stored in. */
103 dataPartitionId?: string;
104 }
105
106 /** Time-based on-demand fetch: run the fetch actions on a fixed cadence. */
107 export interface TimeBasedSignalFetchConfig {
108 /**
109 * How often to fetch the signal, e.g. `"1 minute"`. A bare number is
110 * milliseconds. Sent to FleetWise as whole milliseconds
111 * (`executionFrequencyMs`).
112 */
113 executionFrequency: Duration.Input;
114 }
115
116 /** How an on-demand signal fetch is triggered. */
117 export type SignalFetchConfig =
118 | {
119 timeBased: TimeBasedSignalFetchConfig;
120 conditionBased?: never;
121 }
122 | {
123 timeBased?: never;
124 conditionBased: iotfleetwise.ConditionBasedSignalFetchConfig;
125 };
126
127 /** A signal fetched on demand by actuator-triggered fetch configs. */
128 export interface SignalFetchInformation {
129 /** The fully-qualified name of the signal to fetch. */
130 fullyQualifiedName: string;
131 /** When the fetch runs — time-based or condition-based. */
132 signalFetchConfig: SignalFetchConfig;
133 /**
134 * Version of the condition language used by condition-based configs.
135 * @default 1
136 */
137 conditionLanguageVersion?: number;
138 /** The actions (expressions) evaluated when the fetch triggers. */
139 actions: (string | Redacted.Redacted<string>)[];
140 }
141
142 const toWireCollectionScheme = (scheme: CollectionScheme): iotfleetwise.CollectionScheme =>
143 scheme.timeBasedCollectionScheme !== undefined
144 ? {
145 timeBasedCollectionScheme: {
146 periodMs: toWireMillis(scheme.timeBasedCollectionScheme.period)!,
147 },
148 }
149 : {
150 conditionBasedCollectionScheme: {
151 expression: scheme.conditionBasedCollectionScheme.expression,
152 minimumTriggerIntervalMs: toWireMillis(
153 scheme.conditionBasedCollectionScheme.minimumTriggerInterval,
154 ),
155 triggerMode: scheme.conditionBasedCollectionScheme.triggerMode,
156 conditionLanguageVersion: scheme.conditionBasedCollectionScheme.conditionLanguageVersion,
157 },
158 };
159
160 const toWireSignalsToCollect = (
161 signals: SignalInformation[] | undefined,
162 ): iotfleetwise.SignalInformation[] | undefined =>
163 signals?.map((signal) => ({
164 name: signal.name,
165 maxSampleCount: signal.maxSampleCount,
166 minimumSamplingIntervalMs: toWireMillis(signal.minimumSamplingInterval),
167 dataPartitionId: signal.dataPartitionId,
168 }));
169
170 const toWireSignalsToFetch = (
171 signals: SignalFetchInformation[] | undefined,
172 ): iotfleetwise.SignalFetchInformation[] | undefined =>
173 signals?.map((signal) => ({
174 fullyQualifiedName: signal.fullyQualifiedName,
175 signalFetchConfig:
176 signal.signalFetchConfig.timeBased !== undefined
177 ? {
178 timeBased: {
179 executionFrequencyMs: toWireMillis(
180 signal.signalFetchConfig.timeBased.executionFrequency,
181 )!,
182 },
183 }
184 : { conditionBased: signal.signalFetchConfig.conditionBased },
185 conditionLanguageVersion: signal.conditionLanguageVersion,
186 actions: signal.actions,
187 }));
188
189 export interface CampaignProps {
190 /**
191 * Name of the campaign. Must be 1-100 characters of `[a-zA-Z0-9:_-]`.
192 * If omitted, a deterministic physical name is generated. Changing the
193 * name replaces the campaign.
194 */
195 campaignName?: string;
196 /**
197 * Human-readable description of the campaign. Updated in place.
198 */
199 description?: string;
200 /**
201 * ARN of the {@link SignalCatalog} the collected signals come from.
202 * Changing it replaces the campaign.
203 */
204 signalCatalogArn: string;
205 /**
206 * ARN of the {@link Fleet} or {@link Vehicle} the campaign deploys to.
207 * Changing it replaces the campaign.
208 */
209 targetArn: string;
210 /**
211 * When to collect data — a time-based or condition-based scheme.
212 * Changing it replaces the campaign.
213 */
214 collectionScheme: CollectionScheme;
215 /**
216 * Signals to collect from vehicles. Changing them replaces the
217 * campaign.
218 */
219 signalsToCollect?: SignalInformation[];
220 /**
221 * Destinations (S3, Timestream or MQTT topic) the collected data is
222 * delivered to. Changing them replaces the campaign.
223 */
224 dataDestinationConfigs?: iotfleetwise.DataDestinationConfig[];
225 /**
226 * Time the campaign starts collecting data, as an ISO-8601 string.
227 * Changing it replaces the campaign.
228 * @default now
229 */
230 startTime?: string;
231 /**
232 * Time the campaign expires, as an ISO-8601 string. Changing it
233 * replaces the campaign.
234 * @default 253402214400 (9999-12-31)
235 */
236 expiryTime?: string;
237 /**
238 * How long to keep collecting data after a condition-based trigger
239 * fires, e.g. `"30 seconds"` or `Duration.seconds(30)`. Sent to
240 * FleetWise as whole seconds (a bare number is milliseconds).
241 * Changing it replaces the campaign.
242 * @default 0
243 */
244 postTriggerCollectionDuration?: Duration.Input;
245 /**
246 * Whether to send active diagnostic trouble codes — `"OFF"` or
247 * `"SEND_ACTIVE_DTCS"`. Changing it replaces the campaign.
248 * @default "OFF"
249 */
250 diagnosticsMode?: iotfleetwise.DiagnosticsMode;
251 /**
252 * Whether to store collected data offline when a vehicle lacks
253 * connectivity — `"OFF"` or `"TO_DISK"`. Changing it replaces the
254 * campaign.
255 * @default "OFF"
256 */
257 spoolingMode?: iotfleetwise.SpoolingMode;
258 /**
259 * Whether to compress vehicle-to-cloud transmissions — `"OFF"` or
260 * `"SNAPPY"`. Changing it replaces the campaign.
261 * @default "OFF"
262 */
263 compression?: iotfleetwise.Compression;
264 /**
265 * Vehicle attribute node paths added as extra dimensions on the
266 * collected data, e.g. `["Vehicle.VIN"]`. Updated in place.
267 */
268 dataExtraDimensions?: string[];
269 /**
270 * Data partitions for on-vehicle storage (requires spooling to disk).
271 * Changing them replaces the campaign.
272 */
273 dataPartitions?: iotfleetwise.DataPartition[];
274 /**
275 * Signals fetched on demand by actuator-triggered fetch configs.
276 * Changing them replaces the campaign.
277 */
278 signalsToFetch?: SignalFetchInformation[];
279 /**
280 * Whether the provider approves the campaign (transitioning it from
281 * `WAITING_FOR_APPROVAL` to `RUNNING`) after creation.
282 * @default false
283 */
284 autoApprove?: boolean;
285 /**
286 * User-defined tags for the campaign.
287 */
288 tags?: Record<string, string>;
289 }
290
291 export interface Campaign extends Resource<
292 "AWS.IoTFleetWise.Campaign",
293 CampaignProps,
294 {
295 /** The name of the campaign. */
296 campaignName: string;
297 /** The ARN of the campaign. */
298 campaignArn: string;
299 /** The current status of the campaign (`RUNNING`, `SUSPENDED`, ...). */
300 status: string;
301 /** The signal catalog the campaign collects from. */
302 signalCatalogArn: string | undefined;
303 /** The fleet or vehicle the campaign targets. */
304 targetArn: string | undefined;
305 },
306 never,
307 Providers
308 > {}
309
310 /**
311 * An AWS IoT FleetWise campaign — the orchestration of data-collection
312 * rules that the Edge Agent uses to decide which signals to collect from
313 * a {@link Fleet} or {@link Vehicle} and where to deliver them.
314 *
315 * Campaigns are created in `WAITING_FOR_APPROVAL` status; set
316 * `autoApprove: true` to have the provider approve them into `RUNNING`.
317 * Only the description and extra dimensions are mutable — every other
318 * change replaces the campaign. AWS IoT FleetWise is allowlist-gated and
319 * offered in `us-east-1`/`eu-central-1` only.
320 * ### Creating a Campaign
321 * **Example:** Time-Based Collection to S3
322 * ```typescript
323 * const campaign = yield* Campaign("SpeedTelemetry", {
324 * signalCatalogArn: catalog.signalCatalogArn,
325 * targetArn: fleet.fleetArn,
326 * collectionScheme: {
327 * timeBasedCollectionScheme: { period: "10 seconds" },
328 * },
329 * signalsToCollect: [{ name: "Vehicle.Speed" }],
330 * dataDestinationConfigs: [
331 * { s3Config: { bucketArn: bucket.bucketArn } },
332 * ],
333 * autoApprove: true,
334 * });
335 * ```
336 *
337 * **Example:** Condition-Based Collection
338 * ```typescript
339 * const campaign = yield* Campaign("HardBraking", {
340 * signalCatalogArn: catalog.signalCatalogArn,
341 * targetArn: fleet.fleetArn,
342 * collectionScheme: {
343 * conditionBasedCollectionScheme: {
344 * expression: "$variable.`Vehicle.Speed` > 120.0",
345 * minimumTriggerInterval: "5 seconds",
346 * triggerMode: "RISING_EDGE",
347 * },
348 * },
349 * signalsToCollect: [
350 * { name: "Vehicle.Speed", minimumSamplingInterval: "500 millis" },
351 * ],
352 * postTriggerCollectionDuration: "30 seconds",
353 * dataDestinationConfigs: [
354 * { s3Config: { bucketArn: bucket.bucketArn } },
355 * ],
356 * });
357 * ```
358 *
359 * @resource
360 */
361 export const Campaign = Resource<Campaign>("AWS.IoTFleetWise.Campaign");
362
363 export const CampaignProvider = () =>
364 Provider.effect(
365 Campaign,
366 Effect.gen(function* () {
367 const toName = (id: string, props: { campaignName?: string }) =>
368 props.campaignName
369 ? Effect.succeed(props.campaignName)
370 : createPhysicalName({ id, maxLength: 100 });
371
372 const readCampaign = Effect.fn(function* (name: string) {
373 return yield* iotfleetwise.getCampaign({ name }).pipe(
374 inFleetWiseRegion,
375 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
376 );
377 });
378
379 // Campaign provisioning is asynchronous (status CREATING). Bounded
380 // wait until the service settles it into an actionable status.
381 const waitUntilSettled = Effect.fn(function* (name: string) {
382 return yield* readCampaign(name).pipe(
383 Effect.flatMap((campaign) => {
384 if (campaign === undefined) {
385 return Effect.fail(new CampaignNotReady({ message: `Campaign '${name}' not found` }));
386 }
387 if (campaign.status === "CREATING") {
388 return Effect.fail(
389 new CampaignNotReady({ message: `Campaign '${name}' still creating` }),
390 );
391 }
392 return Effect.succeed(campaign);
393 }),
394 retryObservation,
395 );
396 });
397
398 const toAttrs = Effect.fn(function* (campaign: iotfleetwise.GetCampaignResponse) {
399 if (campaign.name === undefined || campaign.arn === undefined) {
400 return yield* new CampaignUnexpectedResponse({
401 message: `Campaign '${campaign.name}' is missing its ARN`,
402 });
403 }
404 return {
405 campaignName: campaign.name,
406 campaignArn: campaign.arn,
407 status: campaign.status ?? "CREATING",
408 signalCatalogArn: campaign.signalCatalogArn,
409 targetArn: campaign.targetArn,
410 };
411 });
412
413 return {
414 stables: ["campaignName", "campaignArn"],
415
416 diff: Effect.fn(function* ({ id, olds, news }) {
417 if (!isResolved(news)) return undefined;
418 if ((yield* toName(id, olds)) !== (yield* toName(id, news))) {
419 return { action: "replace" } as const;
420 }
421 // Only description and dataExtraDimensions are mutable; every
422 // other property is fixed at creation.
423 const createOnly = (props: CampaignProps) => ({
424 signalCatalogArn: props.signalCatalogArn,
425 targetArn: props.targetArn,
426 // Durations are compared in wire units so that equivalent
427 // inputs ("10 seconds" vs 10_000) never force a replacement.
428 collectionScheme: toWireCollectionScheme(props.collectionScheme),
429 signalsToCollect: toWireSignalsToCollect(props.signalsToCollect),
430 dataDestinationConfigs: props.dataDestinationConfigs,
431 startTime: props.startTime,
432 expiryTime: props.expiryTime,
433 postTriggerCollectionDuration: toWireSeconds(props.postTriggerCollectionDuration),
434 diagnosticsMode: props.diagnosticsMode,
435 spoolingMode: props.spoolingMode,
436 compression: props.compression,
437 dataPartitions: props.dataPartitions,
438 signalsToFetch: toWireSignalsToFetch(props.signalsToFetch),
439 });
440 if (!stableEquals(createOnly(olds), createOnly(news))) {
441 return { action: "replace" } as const;
442 }
443 }),
444
445 read: Effect.fn(function* ({ id, olds, output }) {
446 const name = output?.campaignName ?? (yield* toName(id, olds ?? {}));
447 const found = yield* readCampaign(name);
448 if (found?.arn === undefined) return undefined;
449 const attrs = yield* toAttrs(found);
450 const tags = yield* readFleetWiseTags(found.arn);
451 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
452 }),
453
454 reconcile: Effect.fn(function* ({ id, news, output, session }) {
455 const name = output?.campaignName ?? (yield* toName(id, news));
456 const internalTags = yield* createInternalTags(id);
457 const desiredTags = { ...internalTags, ...news.tags };
458
459 // 1. Observe — cloud state is authoritative.
460 let observed = yield* readCampaign(name);
461
462 // 2. Ensure — create if missing; tolerate the AlreadyExists race.
463 if (observed === undefined) {
464 yield* iotfleetwise
465 .createCampaign({
466 name,
467 description: news.description,
468 signalCatalogArn: news.signalCatalogArn,
469 targetArn: news.targetArn,
470 collectionScheme: toWireCollectionScheme(news.collectionScheme),
471 signalsToCollect: toWireSignalsToCollect(news.signalsToCollect),
472 dataDestinationConfigs: news.dataDestinationConfigs,
473 startTime: news.startTime !== undefined ? new Date(news.startTime) : undefined,
474 expiryTime: news.expiryTime !== undefined ? new Date(news.expiryTime) : undefined,
475 postTriggerCollectionDuration: toWireSeconds(news.postTriggerCollectionDuration),
476 diagnosticsMode: news.diagnosticsMode,
477 spoolingMode: news.spoolingMode,
478 compression: news.compression,
479 dataExtraDimensions: news.dataExtraDimensions,
480 dataPartitions: news.dataPartitions,
481 signalsToFetch: toWireSignalsToFetch(news.signalsToFetch),
482 tags: toFleetWiseTagList(desiredTags),
483 })
484 .pipe(
485 inFleetWiseRegion,
486 Effect.catchTag("ConflictException", () => Effect.void),
487 );
488 }
489 observed = yield* waitUntilSettled(name);
490
491 // 3. Sync mutable aspects — description / dataExtraDimensions via
492 // the UPDATE action, applied only on an observed delta.
493 const descriptionChanged =
494 news.description !== undefined && news.description !== observed.description;
495 const dimensionsChanged =
496 news.dataExtraDimensions !== undefined &&
497 !stableEquals(observed.dataExtraDimensions ?? [], news.dataExtraDimensions);
498 if (descriptionChanged || dimensionsChanged) {
499 yield* iotfleetwise
500 .updateCampaign({
501 name,
502 action: "UPDATE",
503 description: descriptionChanged ? news.description : undefined,
504 dataExtraDimensions: dimensionsChanged ? news.dataExtraDimensions : undefined,
505 })
506 .pipe(inFleetWiseRegion);
507 }
508
509 // 3b. Approve a waiting campaign when requested.
510 if (news.autoApprove === true && observed.status === "WAITING_FOR_APPROVAL") {
511 yield* iotfleetwise.updateCampaign({ name, action: "APPROVE" }).pipe(inFleetWiseRegion);
512 }
513
514 // 3c. Sync tags against OBSERVED cloud tags.
515 const arn = observed.arn;
516 if (arn !== undefined) {
517 yield* syncFleetWiseTags(arn, desiredTags);
518 }
519
520 observed = yield* waitUntilSettled(name);
521 yield* session.note(name);
522 return yield* toAttrs(observed);
523 }),
524
525 delete: Effect.fn(function* ({ output }) {
526 // Deleting a campaign suspends data collection and removes it
527 // from vehicles; deleting a missing campaign is success.
528 yield* iotfleetwise.deleteCampaign({ name: output.campaignName }).pipe(
529 inFleetWiseRegion,
530 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
531 );
532 }),
533
534 list: () =>
535 iotfleetwise.listCampaigns.items({}).pipe(
536 Stream.runCollect,
537 Effect.map((chunk) =>
538 Array.from(chunk).flatMap((summary) =>
539 summary.name !== undefined && summary.arn !== undefined
540 ? [
541 {
542 campaignName: summary.name,
543 campaignArn: summary.arn,
544 status: summary.status ?? "CREATING",
545 signalCatalogArn: summary.signalCatalogArn,
546 targetArn: summary.targetArn,
547 },
548 ]
549 : [],
550 ),
551 ),
552 inFleetWiseRegion,
553 ),
554 };
555 }),
556 );