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

main
ts 243 lines 8.88 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 Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { readIotWirelessTags, sameShape, syncIotWirelessTags } from "./internal.ts";
13
14 export class DeviceProfileUnexpectedResponse extends Data.TaggedError(
15 "DeviceProfileUnexpectedResponse",
16 )<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export interface DeviceProfileProps {
22 /**
23 * Name of the device profile. If omitted, a deterministic physical name
24 * is generated from the app, stage, and logical ID. Device profiles are
25 * immutable — changing the name replaces the profile.
26 */
27 name?: string;
28 /**
29 * LoRaWAN device profile configuration (MAC version, regional parameters,
30 * RX windows, class B/C support). Immutable — changing any field replaces
31 * the profile.
32 */
33 loRaWAN?: iotw.LoRaWANDeviceProfile;
34 /**
35 * Sidewalk device profile configuration. Set to `{}` to create an Amazon
36 * Sidewalk device profile instead of a LoRaWAN one. Immutable.
37 */
38 sidewalk?: iotw.SidewalkCreateDeviceProfile;
39 /**
40 * Tags applied to the device profile. Alchemy ownership tags are merged
41 * in automatically.
42 */
43 tags?: Record<string, string>;
44 }
45
46 export interface DeviceProfile extends Resource<
47 "AWS.IoTWireless.DeviceProfile",
48 DeviceProfileProps,
49 {
50 /** Server-assigned ID of the device profile. */
51 deviceProfileId: string;
52 /** ARN of the device profile. */
53 deviceProfileArn: string;
54 /** Name of the device profile. */
55 deviceProfileName: string;
56 },
57 never,
58 Providers
59 > {}
60
61 /**
62 * An AWS IoT Core for LoRaWAN device profile — the hardware-level LoRaWAN
63 * parameters (MAC version, regional band, RX windows, device classes) shared
64 * by devices of the same model.
65 *
66 * Device profiles are immutable after creation: any change to `name`,
67 * `loRaWAN`, or `sidewalk` replaces the profile. Only tags update in place.
68 * ### Creating Device Profiles
69 * **Example:** US915 OTAA Device Profile
70 * ```typescript
71 * import * as IoTWireless from "@alchemy.run/aws/IoTWireless";
72 *
73 * const profile = yield* IoTWireless.DeviceProfile("SensorModel", {
74 * loRaWAN: {
75 * MacVersion: "1.0.3",
76 * RegParamsRevision: "RP002-1.0.1",
77 * RfRegion: "US915",
78 * MaxEirp: 10,
79 * SupportsJoin: true,
80 * },
81 * });
82 * ```
83 *
84 * **Example:** Sidewalk Device Profile
85 * ```typescript
86 * const profile = yield* IoTWireless.DeviceProfile("SidewalkModel", {
87 * sidewalk: {},
88 * });
89 * ```
90 *
91 * @resource
92 */
93 export const DeviceProfile = Resource<DeviceProfile>("AWS.IoTWireless.DeviceProfile");
94
95 export const DeviceProfileProvider = () =>
96 Provider.effect(
97 DeviceProfile,
98 Effect.gen(function* () {
99 const createName = Effect.fn(function* (id: string, props: { name?: string }) {
100 return props.name ?? (yield* createPhysicalName({ id, maxLength: 256 }));
101 });
102
103 const getById = (deviceProfileId: string) =>
104 iotw
105 .getDeviceProfile({ Id: deviceProfileId })
106 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
107
108 // Device profiles have no name-keyed Get — enumerate and match. The
109 // physical name is deterministic, so this recovers identity after a
110 // lost state write.
111 const findByName = (name: string) =>
112 iotw.listDeviceProfiles.pages({}).pipe(
113 Stream.runCollect,
114 Effect.map((chunk) =>
115 Array.from(chunk)
116 .flatMap((page) => page.DeviceProfileList ?? [])
117 .find((p) => p.Name === name),
118 ),
119 );
120
121 const observe = Effect.fn(function* (
122 output: DeviceProfile["Attributes"] | undefined,
123 name: string,
124 ) {
125 if (output?.deviceProfileId !== undefined) {
126 const found = yield* getById(output.deviceProfileId);
127 if (found !== undefined) return found;
128 }
129 const summary = yield* findByName(name);
130 if (summary?.Id === undefined) return undefined;
131 return yield* getById(summary.Id);
132 });
133
134 const toAttrs = Effect.fn(function* (profile: iotw.GetDeviceProfileResponse, name: string) {
135 if (profile.Id === undefined || profile.Arn === undefined) {
136 return yield* new DeviceProfileUnexpectedResponse({
137 message: `IoT Wireless device profile '${name}' returned without Id/Arn`,
138 });
139 }
140 return {
141 deviceProfileId: profile.Id,
142 deviceProfileArn: profile.Arn,
143 deviceProfileName: profile.Name ?? name,
144 };
145 });
146
147 return DeviceProfile.Provider.of({
148 stables: ["deviceProfileId", "deviceProfileArn", "deviceProfileName"],
149
150 list: () =>
151 iotw.listDeviceProfiles.pages({}).pipe(
152 Stream.runCollect,
153 Effect.map((chunk) =>
154 Array.from(chunk)
155 .flatMap((page) => page.DeviceProfileList ?? [])
156 .flatMap((p) =>
157 p.Id !== undefined && p.Arn !== undefined
158 ? [
159 {
160 deviceProfileId: p.Id,
161 deviceProfileArn: p.Arn,
162 deviceProfileName: p.Name ?? p.Id,
163 },
164 ]
165 : [],
166 ),
167 ),
168 ),
169
170 read: Effect.fn(function* ({ id, olds, output }) {
171 const name = output?.deviceProfileName ?? (yield* createName(id, olds ?? {}));
172 const profile = yield* observe(output, name);
173 if (profile === undefined) return undefined;
174 const attrs = yield* toAttrs(profile, name);
175 const tags = yield* readIotWirelessTags(attrs.deviceProfileArn);
176 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
177 }),
178
179 // There is no UpdateDeviceProfile API — name and radio config are
180 // create-only, so any change to either replaces the profile. Tags
181 // stay update-in-place.
182 diff: Effect.fn(function* ({ id, news, olds }) {
183 if (!isResolved(news)) return undefined;
184 const oldName = yield* createName(id, olds ?? {});
185 const newName = yield* createName(id, news);
186 if (oldName !== newName) return { action: "replace" } as const;
187 if (!sameShape(olds?.loRaWAN, news.loRaWAN)) {
188 return { action: "replace" } as const;
189 }
190 if ((olds?.sidewalk === undefined) !== (news.sidewalk === undefined)) {
191 return { action: "replace" } as const;
192 }
193 }),
194
195 reconcile: Effect.fn(function* ({ id, news, output, session }) {
196 const name = output?.deviceProfileName ?? (yield* createName(id, news));
197 const internalTags = yield* createInternalTags(id);
198 const desiredTags = { ...news.tags, ...internalTags };
199
200 // 1. OBSERVE — cloud state is authoritative; output is an id cache.
201 let profile = yield* observe(output, name);
202
203 // 2. ENSURE — create if missing. CreateDeviceProfile always mints
204 // a new profile (names are not unique keys), so re-observing by
205 // name after a Conflict race keeps this idempotent.
206 if (profile === undefined) {
207 yield* session.note(`creating device profile ${name}`);
208 const created = yield* iotw
209 .createDeviceProfile({
210 Name: name,
211 LoRaWAN: news.loRaWAN,
212 Sidewalk: news.sidewalk,
213 Tags: createTagsList(desiredTags),
214 })
215 .pipe(Effect.catchTag("ConflictException", () => Effect.undefined));
216 profile =
217 created?.Id !== undefined
218 ? yield* getById(created.Id)
219 : yield* observe(undefined, name);
220 }
221 if (profile === undefined) {
222 return yield* new DeviceProfileUnexpectedResponse({
223 message: `IoT Wireless device profile '${name}' not found after create`,
224 });
225 }
226
227 // 3. SYNC — only tags are mutable; diff against OBSERVED tags.
228 const attrs = yield* toAttrs(profile, name);
229 yield* syncIotWirelessTags(attrs.deviceProfileArn, desiredTags);
230
231 yield* session.note(attrs.deviceProfileId);
232 return attrs;
233 }),
234
235 delete: Effect.fn(function* ({ output }) {
236 yield* iotw.deleteDeviceProfile({ Id: output.deviceProfileId }).pipe(
237 Effect.asVoid,
238 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
239 );
240 }),
241 });
242 }),
243 );