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

main
ts 242 lines 8.91 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 ServiceProfileUnexpectedResponse extends Data.TaggedError(
15 "ServiceProfileUnexpectedResponse",
16 )<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export interface ServiceProfileProps {
22 /**
23 * Name of the service profile. If omitted, a deterministic physical name
24 * is generated from the app, stage, and logical ID. Service profiles are
25 * immutable — changing the name replaces the profile.
26 */
27 name?: string;
28 /**
29 * LoRaWAN service profile configuration (data-rate bounds, gateway
30 * metadata, roaming flags, transmission counts). Immutable — changing any
31 * field replaces the profile.
32 */
33 loRaWAN?: iotw.LoRaWANServiceProfile;
34 /**
35 * Tags applied to the service profile. Alchemy ownership tags are merged
36 * in automatically.
37 */
38 tags?: Record<string, string>;
39 }
40
41 export interface ServiceProfile extends Resource<
42 "AWS.IoTWireless.ServiceProfile",
43 ServiceProfileProps,
44 {
45 /** Server-assigned ID of the service profile. */
46 serviceProfileId: string;
47 /** ARN of the service profile. */
48 serviceProfileArn: string;
49 /** Name of the service profile. */
50 serviceProfileName: string;
51 },
52 never,
53 Providers
54 > {}
55
56 /**
57 * An AWS IoT Core for LoRaWAN service profile — the network-level parameters
58 * (data-rate bounds, gateway metadata reporting, roaming permissions) shared
59 * by a fleet of wireless devices.
60 *
61 * Service profiles are immutable after creation: any change to `name` or
62 * `loRaWAN` replaces the profile. Only tags update in place.
63 * ### Creating Service Profiles
64 * **Example:** Default Service Profile
65 * ```typescript
66 * import * as IoTWireless from "@alchemy.run/aws/IoTWireless";
67 *
68 * const profile = yield* IoTWireless.ServiceProfile("Fleet");
69 * ```
70 *
71 * **Example:** Service Profile with Gateway Metadata
72 * ```typescript
73 * const profile = yield* IoTWireless.ServiceProfile("Fleet", {
74 * loRaWAN: { AddGwMetadata: true, DrMin: 0, DrMax: 10 },
75 * tags: { team: "iot" },
76 * });
77 * ```
78 *
79 * ### Referencing from Devices
80 * **Example:** Wire a device to the profile
81 * ```typescript
82 * const device = yield* IoTWireless.WirelessDevice("Sensor", {
83 * type: "LoRaWAN",
84 * destinationName: destination.destinationName,
85 * loRaWAN: {
86 * DevEui: "1122334455667788",
87 * ServiceProfileId: profile.serviceProfileId,
88 * DeviceProfileId: deviceProfile.deviceProfileId,
89 * OtaaV1_0_x: { AppKey: "...", AppEui: "..." },
90 * },
91 * });
92 * ```
93 *
94 * @resource
95 */
96 export const ServiceProfile = Resource<ServiceProfile>("AWS.IoTWireless.ServiceProfile");
97
98 export const ServiceProfileProvider = () =>
99 Provider.effect(
100 ServiceProfile,
101 Effect.gen(function* () {
102 const createName = Effect.fn(function* (id: string, props: { name?: string }) {
103 return props.name ?? (yield* createPhysicalName({ id, maxLength: 256 }));
104 });
105
106 const getById = (serviceProfileId: string) =>
107 iotw
108 .getServiceProfile({ Id: serviceProfileId })
109 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
110
111 // Service profiles have no name-keyed Get — enumerate and match. The
112 // physical name is deterministic, so this recovers identity after a
113 // lost state write.
114 const findByName = (name: string) =>
115 iotw.listServiceProfiles.pages({}).pipe(
116 Stream.runCollect,
117 Effect.map((chunk) =>
118 Array.from(chunk)
119 .flatMap((page) => page.ServiceProfileList ?? [])
120 .find((p) => p.Name === name),
121 ),
122 );
123
124 const observe = Effect.fn(function* (
125 output: ServiceProfile["Attributes"] | undefined,
126 name: string,
127 ) {
128 if (output?.serviceProfileId !== undefined) {
129 const found = yield* getById(output.serviceProfileId);
130 if (found !== undefined) return found;
131 }
132 const summary = yield* findByName(name);
133 if (summary?.Id === undefined) return undefined;
134 return yield* getById(summary.Id);
135 });
136
137 const toAttrs = Effect.fn(function* (profile: iotw.GetServiceProfileResponse, name: string) {
138 if (profile.Id === undefined || profile.Arn === undefined) {
139 return yield* new ServiceProfileUnexpectedResponse({
140 message: `IoT Wireless service profile '${name}' returned without Id/Arn`,
141 });
142 }
143 return {
144 serviceProfileId: profile.Id,
145 serviceProfileArn: profile.Arn,
146 serviceProfileName: profile.Name ?? name,
147 };
148 });
149
150 return ServiceProfile.Provider.of({
151 stables: ["serviceProfileId", "serviceProfileArn", "serviceProfileName"],
152
153 list: () =>
154 iotw.listServiceProfiles.pages({}).pipe(
155 Stream.runCollect,
156 Effect.map((chunk) =>
157 Array.from(chunk)
158 .flatMap((page) => page.ServiceProfileList ?? [])
159 .flatMap((p) =>
160 p.Id !== undefined && p.Arn !== undefined
161 ? [
162 {
163 serviceProfileId: p.Id,
164 serviceProfileArn: p.Arn,
165 serviceProfileName: p.Name ?? p.Id,
166 },
167 ]
168 : [],
169 ),
170 ),
171 ),
172
173 read: Effect.fn(function* ({ id, olds, output }) {
174 const name = output?.serviceProfileName ?? (yield* createName(id, olds ?? {}));
175 const profile = yield* observe(output, name);
176 if (profile === undefined) return undefined;
177 const attrs = yield* toAttrs(profile, name);
178 const tags = yield* readIotWirelessTags(attrs.serviceProfileArn);
179 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
180 }),
181
182 // There is no UpdateServiceProfile API — name and LoRaWAN config are
183 // create-only, so any change to either replaces the profile. Tags
184 // stay update-in-place.
185 diff: Effect.fn(function* ({ id, news, olds }) {
186 if (!isResolved(news)) return undefined;
187 const oldName = yield* createName(id, olds ?? {});
188 const newName = yield* createName(id, news);
189 if (oldName !== newName) return { action: "replace" } as const;
190 if (!sameShape(olds?.loRaWAN, news.loRaWAN)) {
191 return { action: "replace" } as const;
192 }
193 }),
194
195 reconcile: Effect.fn(function* ({ id, news, output, session }) {
196 const name = output?.serviceProfileName ?? (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. CreateServiceProfile 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 service profile ${name}`);
208 const created = yield* iotw
209 .createServiceProfile({
210 Name: name,
211 LoRaWAN: news.loRaWAN,
212 Tags: createTagsList(desiredTags),
213 })
214 .pipe(Effect.catchTag("ConflictException", () => Effect.undefined));
215 profile =
216 created?.Id !== undefined
217 ? yield* getById(created.Id)
218 : yield* observe(undefined, name);
219 }
220 if (profile === undefined) {
221 return yield* new ServiceProfileUnexpectedResponse({
222 message: `IoT Wireless service profile '${name}' not found after create`,
223 });
224 }
225
226 // 3. SYNC — only tags are mutable; diff against OBSERVED tags.
227 const attrs = yield* toAttrs(profile, name);
228 yield* syncIotWirelessTags(attrs.serviceProfileArn, desiredTags);
229
230 yield* session.note(attrs.serviceProfileId);
231 return attrs;
232 }),
233
234 delete: Effect.fn(function* ({ output }) {
235 yield* iotw.deleteServiceProfile({ Id: output.serviceProfileId }).pipe(
236 Effect.asVoid,
237 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
238 );
239 }),
240 });
241 }),
242 );