@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 498 lines 18.5 KB
Raw
1 import * as iotw from "@distilled.cloud/aws/iot-wireless";
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, createTagsList, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Redacted from "effect/Redacted";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13 import { readIotWirelessTags, sameShape, syncIotWirelessTags } from "./internal.ts";
14
15 export class WirelessDeviceUnexpectedResponse extends Data.TaggedError(
16 "WirelessDeviceUnexpectedResponse",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 /**
23 * LoRaWAN OTAA v1.1 activation keys. The root keys (`AppKey`, `NwkKey`) are
24 * secrets — wrap them with `Redacted.make(...)`.
25 */
26 export interface OtaaV1_1Props {
27 /** The AppKey root key. Secret key material. */
28 AppKey?: Redacted.Redacted<string>;
29 /** The NwkKey root key. Secret key material. */
30 NwkKey?: Redacted.Redacted<string>;
31 /** The JoinEUI identifier (public). */
32 JoinEui?: string;
33 }
34
35 /**
36 * LoRaWAN OTAA v1.0.x activation keys. The root keys (`AppKey`, `GenAppKey`)
37 * are secrets — wrap them with `Redacted.make(...)`.
38 */
39 export interface OtaaV1_0_xProps {
40 /** The AppKey root key. Secret key material. */
41 AppKey?: Redacted.Redacted<string>;
42 /** The AppEUI identifier (public). */
43 AppEui?: string;
44 /** The JoinEUI identifier (public). */
45 JoinEui?: string;
46 /** The GenAppKey root key. Secret key material. */
47 GenAppKey?: Redacted.Redacted<string>;
48 }
49
50 /**
51 * LoRaWAN ABP v1.1 session keys. All four keys are secrets — wrap them with
52 * `Redacted.make(...)`.
53 */
54 export interface SessionKeysAbpV1_1Props {
55 /** The FNwkSIntKey session key. Secret key material. */
56 FNwkSIntKey?: Redacted.Redacted<string>;
57 /** The SNwkSIntKey session key. Secret key material. */
58 SNwkSIntKey?: Redacted.Redacted<string>;
59 /** The NwkSEncKey session key. Secret key material. */
60 NwkSEncKey?: Redacted.Redacted<string>;
61 /** The AppSKey session key. Secret key material. */
62 AppSKey?: Redacted.Redacted<string>;
63 }
64
65 /** LoRaWAN ABP v1.1 activation configuration. */
66 export interface AbpV1_1Props {
67 /** The device address (public). */
68 DevAddr?: string;
69 /** Session keys. Secret key material. */
70 SessionKeys?: SessionKeysAbpV1_1Props;
71 /** The initial FCnt value. */
72 FCntStart?: number;
73 }
74
75 /**
76 * LoRaWAN ABP v1.0.x session keys. Both keys are secrets — wrap them with
77 * `Redacted.make(...)`.
78 */
79 export interface SessionKeysAbpV1_0_xProps {
80 /** The NwkSKey session key. Secret key material. */
81 NwkSKey?: Redacted.Redacted<string>;
82 /** The AppSKey session key. Secret key material. */
83 AppSKey?: Redacted.Redacted<string>;
84 }
85
86 /** LoRaWAN ABP v1.0.x activation configuration. */
87 export interface AbpV1_0_xProps {
88 /** The device address (public). */
89 DevAddr?: string;
90 /** Session keys. Secret key material. */
91 SessionKeys?: SessionKeysAbpV1_0_xProps;
92 /** The initial FCnt value. */
93 FCntStart?: number;
94 }
95
96 /**
97 * LoRaWAN device configuration. Mirrors the wire shape, with the activation
98 * key material typed as `Redacted` so secrets never leak into logs or state
99 * diffs.
100 */
101 export interface LoRaWANDeviceProps {
102 /** The DevEUI radio identifier (public). Changing it replaces the device. */
103 DevEui?: string;
104 /** ID of the device profile the device uses. Updates in place. */
105 DeviceProfileId?: string;
106 /** ID of the service profile the device uses. Updates in place. */
107 ServiceProfileId?: string;
108 /** OTAA v1.1 activation keys. Changing them replaces the device. */
109 OtaaV1_1?: OtaaV1_1Props;
110 /** OTAA v1.0.x activation keys. Changing them replaces the device. */
111 OtaaV1_0_x?: OtaaV1_0_xProps;
112 /** ABP v1.1 activation configuration. Changing it replaces the device. */
113 AbpV1_1?: AbpV1_1Props;
114 /** ABP v1.0.x activation configuration. Changing it replaces the device. */
115 AbpV1_0_x?: AbpV1_0_xProps;
116 /** FPort configuration. Updates in place. */
117 FPorts?: iotw.FPorts;
118 }
119
120 export interface WirelessDeviceProps {
121 /**
122 * The wireless technology the device uses. Changing the type replaces the
123 * device.
124 */
125 type: "LoRaWAN" | "Sidewalk";
126 /**
127 * Name of the destination that routes the device's uplink messages. Can be
128 * changed in place.
129 */
130 destinationName: string;
131 /**
132 * Name of the wireless device. If omitted, a deterministic physical name
133 * is generated from the app, stage, and logical ID. Can be changed in
134 * place.
135 */
136 name?: string;
137 /**
138 * Human-readable description of the device.
139 */
140 description?: string;
141 /**
142 * LoRaWAN device configuration: `DevEui`, the device/service profile IDs,
143 * and the activation keys (`OtaaV1_0_x`, `OtaaV1_1`, `AbpV1_0_x`,
144 * `AbpV1_1`). The `DevEui` and activation keys are the device's radio
145 * identity — changing them replaces the device; the profile IDs and
146 * `FPorts` update in place. Key material is secret — wrap each key with
147 * `Redacted.make(...)`.
148 */
149 loRaWAN?: LoRaWANDeviceProps;
150 /**
151 * Whether position solving is enabled for the device (`Enabled` or
152 * `Disabled`).
153 */
154 positioning?: iotw.PositioningConfigStatus;
155 /**
156 * Amazon Sidewalk device configuration. Changing the manufacturing serial
157 * number replaces the device.
158 */
159 sidewalk?: iotw.SidewalkCreateWirelessDevice;
160 /**
161 * Tags applied to the device. Alchemy ownership tags are merged in
162 * automatically.
163 */
164 tags?: Record<string, string>;
165 }
166
167 export interface WirelessDevice extends Resource<
168 "AWS.IoTWireless.WirelessDevice",
169 WirelessDeviceProps,
170 {
171 /** Server-assigned ID of the wireless device. */
172 wirelessDeviceId: string;
173 /** ARN of the wireless device. */
174 wirelessDeviceArn: string;
175 /** Name of the wireless device. */
176 wirelessDeviceName: string;
177 /** The wireless technology the device uses. */
178 type: iotw.WirelessDeviceType;
179 /** Name of the destination routing the device's uplinks. */
180 destinationName: string;
181 },
182 never,
183 Providers
184 > {}
185
186 /**
187 * An AWS IoT Core for LoRaWAN (or Amazon Sidewalk) wireless device — the
188 * cloud registration of a physical radio, wired to a {@link Destination}
189 * for uplink routing and to a {@link DeviceProfile} / {@link ServiceProfile}
190 * pair for its radio parameters.
191 *
192 * The device's radio identity (`type`, `DevEui`, activation keys) is
193 * immutable — changing it replaces the device. The name, description,
194 * destination, positioning, profile references, and tags update in place.
195 * ### Creating Devices
196 * **Example:** OTAA v1.0.x LoRaWAN Device
197 * ```typescript
198 * import * as IoTWireless from "@alchemy.run/aws/IoTWireless";
199 *
200 * const device = yield* IoTWireless.WirelessDevice("Sensor", {
201 * type: "LoRaWAN",
202 * destinationName: destination.destinationName,
203 * loRaWAN: {
204 * DevEui: "1122334455667788",
205 * DeviceProfileId: deviceProfile.deviceProfileId,
206 * ServiceProfileId: serviceProfile.serviceProfileId,
207 * OtaaV1_0_x: {
208 * AppKey: Redacted.make("00112233445566778899aabbccddeeff"),
209 * AppEui: "8877665544332211",
210 * },
211 * },
212 * });
213 * ```
214 *
215 * **Example:** Repoint a device at a different destination
216 * ```typescript
217 * const device = yield* IoTWireless.WirelessDevice("Sensor", {
218 * type: "LoRaWAN",
219 * destinationName: otherDestination.destinationName, // updates in place
220 * loRaWAN: { ... },
221 * });
222 * ```
223 *
224 * @resource
225 */
226 export const WirelessDevice = Resource<WirelessDevice>("AWS.IoTWireless.WirelessDevice");
227
228 const unwrap = (value: Redacted.Redacted<string> | undefined) =>
229 value === undefined ? undefined : Redacted.value(value);
230
231 /**
232 * Convert the Redacted-keyed LoRaWAN prop shape to the plain wire shape the
233 * IoT Wireless API expects.
234 */
235 const toWireLoRaWAN = (loRaWAN: LoRaWANDeviceProps | undefined): iotw.LoRaWANDevice | undefined =>
236 loRaWAN === undefined
237 ? undefined
238 : {
239 DevEui: loRaWAN.DevEui,
240 DeviceProfileId: loRaWAN.DeviceProfileId,
241 ServiceProfileId: loRaWAN.ServiceProfileId,
242 OtaaV1_1:
243 loRaWAN.OtaaV1_1 === undefined
244 ? undefined
245 : {
246 AppKey: unwrap(loRaWAN.OtaaV1_1.AppKey),
247 NwkKey: unwrap(loRaWAN.OtaaV1_1.NwkKey),
248 JoinEui: loRaWAN.OtaaV1_1.JoinEui,
249 },
250 OtaaV1_0_x:
251 loRaWAN.OtaaV1_0_x === undefined
252 ? undefined
253 : {
254 AppKey: unwrap(loRaWAN.OtaaV1_0_x.AppKey),
255 AppEui: loRaWAN.OtaaV1_0_x.AppEui,
256 JoinEui: loRaWAN.OtaaV1_0_x.JoinEui,
257 GenAppKey: unwrap(loRaWAN.OtaaV1_0_x.GenAppKey),
258 },
259 AbpV1_1:
260 loRaWAN.AbpV1_1 === undefined
261 ? undefined
262 : {
263 DevAddr: loRaWAN.AbpV1_1.DevAddr,
264 FCntStart: loRaWAN.AbpV1_1.FCntStart,
265 SessionKeys:
266 loRaWAN.AbpV1_1.SessionKeys === undefined
267 ? undefined
268 : {
269 FNwkSIntKey: unwrap(loRaWAN.AbpV1_1.SessionKeys.FNwkSIntKey),
270 SNwkSIntKey: unwrap(loRaWAN.AbpV1_1.SessionKeys.SNwkSIntKey),
271 NwkSEncKey: unwrap(loRaWAN.AbpV1_1.SessionKeys.NwkSEncKey),
272 AppSKey: unwrap(loRaWAN.AbpV1_1.SessionKeys.AppSKey),
273 },
274 },
275 AbpV1_0_x:
276 loRaWAN.AbpV1_0_x === undefined
277 ? undefined
278 : {
279 DevAddr: loRaWAN.AbpV1_0_x.DevAddr,
280 FCntStart: loRaWAN.AbpV1_0_x.FCntStart,
281 SessionKeys:
282 loRaWAN.AbpV1_0_x.SessionKeys === undefined
283 ? undefined
284 : {
285 NwkSKey: unwrap(loRaWAN.AbpV1_0_x.SessionKeys.NwkSKey),
286 AppSKey: unwrap(loRaWAN.AbpV1_0_x.SessionKeys.AppSKey),
287 },
288 },
289 FPorts: loRaWAN.FPorts,
290 };
291
292 /** The parts of a LoRaWAN device spec that form its immutable radio identity. */
293 const loRaWANIdentity = (loRaWAN: iotw.LoRaWANDevice | undefined) => ({
294 DevEui: loRaWAN?.DevEui,
295 OtaaV1_0_x: loRaWAN?.OtaaV1_0_x,
296 OtaaV1_1: loRaWAN?.OtaaV1_1,
297 AbpV1_0_x: loRaWAN?.AbpV1_0_x,
298 AbpV1_1: loRaWAN?.AbpV1_1,
299 });
300
301 export const WirelessDeviceProvider = () =>
302 Provider.effect(
303 WirelessDevice,
304 Effect.gen(function* () {
305 const createName = Effect.fn(function* (id: string, props: { name?: string }) {
306 return props.name ?? (yield* createPhysicalName({ id, maxLength: 256 }));
307 });
308
309 const getBy = (identifier: string, type: iotw.WirelessDeviceIdType) =>
310 iotw
311 .getWirelessDevice({ Identifier: identifier, IdentifierType: type })
312 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
313
314 const observe = Effect.fn(function* (
315 output: WirelessDevice["Attributes"] | undefined,
316 props: WirelessDeviceProps,
317 ) {
318 if (output?.wirelessDeviceId !== undefined) {
319 const found = yield* getBy(output.wirelessDeviceId, "WirelessDeviceId");
320 if (found !== undefined) return found;
321 }
322 // Recover identity by the device's radio identifier when state was
323 // lost — the DevEui / Sidewalk serial is unique per account.
324 if (props.loRaWAN?.DevEui !== undefined) {
325 return yield* getBy(props.loRaWAN.DevEui, "DevEui");
326 }
327 if (props.sidewalk?.SidewalkManufacturingSn !== undefined) {
328 return yield* getBy(props.sidewalk.SidewalkManufacturingSn, "SidewalkManufacturingSn");
329 }
330 return undefined;
331 });
332
333 const toAttrs = Effect.fn(function* (device: iotw.GetWirelessDeviceResponse, name: string) {
334 if (device.Id === undefined || device.Arn === undefined) {
335 return yield* new WirelessDeviceUnexpectedResponse({
336 message: `IoT Wireless device '${name}' returned without Id/Arn`,
337 });
338 }
339 return {
340 wirelessDeviceId: device.Id,
341 wirelessDeviceArn: device.Arn,
342 wirelessDeviceName: device.Name ?? name,
343 type: device.Type ?? "LoRaWAN",
344 destinationName: device.DestinationName ?? "",
345 };
346 });
347
348 return WirelessDevice.Provider.of({
349 stables: ["wirelessDeviceId", "wirelessDeviceArn", "type"],
350
351 list: () =>
352 iotw.listWirelessDevices.pages({}).pipe(
353 Stream.runCollect,
354 Effect.map((chunk) =>
355 Array.from(chunk)
356 .flatMap((page) => page.WirelessDeviceList ?? [])
357 .flatMap((d) =>
358 d.Id !== undefined && d.Arn !== undefined
359 ? [
360 {
361 wirelessDeviceId: d.Id,
362 wirelessDeviceArn: d.Arn,
363 wirelessDeviceName: d.Name ?? d.Id,
364 type: d.Type ?? "LoRaWAN",
365 destinationName: d.DestinationName ?? "",
366 },
367 ]
368 : [],
369 ),
370 ),
371 ),
372
373 read: Effect.fn(function* ({ id, olds, output }) {
374 const props = olds ?? { type: "LoRaWAN", destinationName: "" };
375 const name = output?.wirelessDeviceName ?? (yield* createName(id, props));
376 const device = yield* observe(output, props);
377 if (device === undefined) return undefined;
378 const attrs = yield* toAttrs(device, name);
379 const tags = yield* readIotWirelessTags(attrs.wirelessDeviceArn);
380 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
381 }),
382
383 // The wireless technology and the radio identity (DevEui, activation
384 // keys, Sidewalk serial) are create-only. Name, description,
385 // destination, positioning, and profile references update in place.
386 diff: Effect.fn(function* ({ news, olds }) {
387 if (!isResolved(news)) return undefined;
388 if (olds !== undefined && olds.type !== news.type) {
389 return { action: "replace" } as const;
390 }
391 if (
392 !sameShape(
393 loRaWANIdentity(toWireLoRaWAN(olds?.loRaWAN)),
394 loRaWANIdentity(toWireLoRaWAN(news.loRaWAN)),
395 )
396 ) {
397 return { action: "replace" } as const;
398 }
399 if (olds?.sidewalk?.SidewalkManufacturingSn !== news.sidewalk?.SidewalkManufacturingSn) {
400 return { action: "replace" } as const;
401 }
402 }),
403
404 reconcile: Effect.fn(function* ({ id, news, output, session }) {
405 const name = output?.wirelessDeviceName ?? (yield* createName(id, news));
406 const internalTags = yield* createInternalTags(id);
407 const desiredTags = { ...news.tags, ...internalTags };
408
409 // 1. OBSERVE — cloud state is authoritative; output is an id cache.
410 let device = yield* observe(output, news);
411
412 // 2. ENSURE — create if missing; a Conflict means the radio
413 // identity is already registered, so re-observe by it.
414 if (device === undefined) {
415 yield* session.note(`creating wireless device ${name}`);
416 const created = yield* iotw
417 .createWirelessDevice({
418 Type: news.type,
419 Name: name,
420 Description: news.description,
421 DestinationName: news.destinationName,
422 LoRaWAN: toWireLoRaWAN(news.loRaWAN),
423 Positioning: news.positioning,
424 Sidewalk: news.sidewalk,
425 Tags: createTagsList(desiredTags),
426 })
427 .pipe(Effect.catchTag("ConflictException", () => Effect.undefined));
428 device =
429 created?.Id !== undefined
430 ? yield* getBy(created.Id, "WirelessDeviceId")
431 : yield* observe(undefined, news);
432 }
433 if (device === undefined) {
434 return yield* new WirelessDeviceUnexpectedResponse({
435 message: `IoT Wireless device '${name}' not found after create`,
436 });
437 }
438 const attrs = yield* toAttrs(device, name);
439
440 // 3. SYNC — apply the mutable-aspect delta from OBSERVED state.
441 const nameDelta = device.Name !== name;
442 const descriptionDelta =
443 news.description !== undefined && device.Description !== news.description;
444 const destinationDelta = device.DestinationName !== news.destinationName;
445 const positioningDelta =
446 news.positioning !== undefined && device.Positioning !== news.positioning;
447 const profileDelta =
448 news.loRaWAN !== undefined &&
449 (device.LoRaWAN?.DeviceProfileId !== news.loRaWAN.DeviceProfileId ||
450 device.LoRaWAN?.ServiceProfileId !== news.loRaWAN.ServiceProfileId ||
451 !sameShape(device.LoRaWAN?.FPorts, news.loRaWAN.FPorts));
452 if (
453 nameDelta ||
454 descriptionDelta ||
455 destinationDelta ||
456 positioningDelta ||
457 profileDelta
458 ) {
459 yield* iotw.updateWirelessDevice({
460 Id: attrs.wirelessDeviceId,
461 Name: name,
462 Description: news.description,
463 DestinationName: news.destinationName,
464 Positioning: news.positioning,
465 LoRaWAN:
466 news.loRaWAN === undefined
467 ? undefined
468 : {
469 DeviceProfileId: news.loRaWAN.DeviceProfileId,
470 ServiceProfileId: news.loRaWAN.ServiceProfileId,
471 FPorts: news.loRaWAN.FPorts,
472 },
473 });
474 }
475
476 // 3b. SYNC tags — diff against OBSERVED cloud tags.
477 yield* syncIotWirelessTags(attrs.wirelessDeviceArn, desiredTags);
478
479 // 4. RETURN fresh attributes.
480 const final = yield* getBy(attrs.wirelessDeviceId, "WirelessDeviceId");
481 if (final === undefined) {
482 return yield* new WirelessDeviceUnexpectedResponse({
483 message: `IoT Wireless device '${name}' vanished during update`,
484 });
485 }
486 yield* session.note(attrs.wirelessDeviceId);
487 return yield* toAttrs(final, name);
488 }),
489
490 delete: Effect.fn(function* ({ output }) {
491 yield* iotw.deleteWirelessDevice({ Id: output.wirelessDeviceId }).pipe(
492 Effect.asVoid,
493 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
494 );
495 }),
496 });
497 }),
498 );