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

main
ts 300 lines 10.9 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, syncIotWirelessTags } from "./internal.ts";
13
14 export class IoTWirelessDestinationUnexpectedResponse extends Data.TaggedError(
15 "IoTWirelessDestinationUnexpectedResponse",
16 )<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export interface DestinationProps {
22 /**
23 * Name of the destination. Names are unique per account/region and may
24 * contain only alphanumerics, dashes, and underscores. If omitted, a
25 * deterministic physical name is generated. Changing the name replaces
26 * the destination.
27 */
28 name?: string;
29 /**
30 * How `expression` is interpreted: `RuleName` routes uplinks to an AWS
31 * IoT rule; `MqttTopic` publishes them to an MQTT topic.
32 */
33 expressionType: iotw.ExpressionType;
34 /**
35 * The IoT rule name or MQTT topic uplink messages are routed to. The
36 * referenced rule does not need to exist when the destination is created.
37 */
38 expression: string;
39 /**
40 * Human-readable description of the destination.
41 */
42 description?: string;
43 /**
44 * ARN of the IAM role IoT Wireless assumes to deliver messages to the
45 * rule or topic. The role's trust policy must allow
46 * `iotwireless.amazonaws.com` to assume it.
47 */
48 roleArn: string;
49 /**
50 * Tags applied to the destination. Alchemy ownership tags are merged in
51 * automatically.
52 */
53 tags?: Record<string, string>;
54 }
55
56 export interface Destination extends Resource<
57 "AWS.IoTWireless.Destination",
58 DestinationProps,
59 {
60 /** Name of the destination (its unique identifier). */
61 destinationName: string;
62 /** ARN of the destination. */
63 destinationArn: string;
64 /** How the expression is interpreted (`RuleName` or `MqttTopic`). */
65 expressionType: iotw.ExpressionType;
66 /** The IoT rule name or MQTT topic uplinks are routed to. */
67 expression: string;
68 /** ARN of the delivery IAM role. */
69 roleArn: string;
70 },
71 never,
72 Providers
73 > {}
74
75 /**
76 * An AWS IoT Core for LoRaWAN destination — the routing rule that delivers
77 * uplink messages from wireless devices to an AWS IoT rule or MQTT topic.
78 *
79 * The destination name is its identity (changing it replaces the
80 * destination); the expression, expression type, description, role, and
81 * tags all update in place.
82 * ### Creating Destinations
83 * **Example:** Route uplinks to an IoT rule
84 * ```typescript
85 * import * as IoTWireless from "@alchemy.run/aws/IoTWireless";
86 *
87 * const destination = yield* IoTWireless.Destination("Uplinks", {
88 * expressionType: "RuleName",
89 * expression: "process_sensor_uplinks",
90 * roleArn: deliveryRole.roleArn,
91 * });
92 * ```
93 *
94 * **Example:** Publish uplinks straight to an MQTT topic
95 * ```typescript
96 * const destination = yield* IoTWireless.Destination("Uplinks", {
97 * expressionType: "MqttTopic",
98 * expression: "sensors/uplinks",
99 * roleArn: deliveryRole.roleArn,
100 * });
101 * ```
102 *
103 * ### Delivery Role
104 * **Example:** IAM role IoT Wireless assumes for delivery
105 * ```typescript
106 * const deliveryRole = yield* IAM.Role("IotWirelessDelivery", {
107 * assumeRolePolicyDocument: {
108 * Version: "2012-10-17",
109 * Statement: [{
110 * Effect: "Allow",
111 * Principal: { Service: "iotwireless.amazonaws.com" },
112 * Action: ["sts:AssumeRole"],
113 * }],
114 * },
115 * policies: [{
116 * policyName: "deliver",
117 * policyDocument: {
118 * Version: "2012-10-17",
119 * Statement: [{
120 * Effect: "Allow",
121 * Action: ["iot:DescribeEndpoint", "iot:Publish"],
122 * Resource: ["*"],
123 * }],
124 * },
125 * }],
126 * });
127 * ```
128 *
129 * ### Consuming Uplinks in a Function
130 * Uplinks are delivered through AWS IoT Core. For a `RuleName` destination,
131 * `IoTWireless.consumeUplinks` (see {@link DestinationEventSource}) creates
132 * the named IoT rule targeting the current Lambda and invokes the handler
133 * for every uplink. Alternatively, point an `MqttTopic` destination at a
134 * topic and consume it with `AWS.IoT.consumeTopicMessages`.
135 * **Example:** Route Device Uplinks into a Lambda
136 * ```typescript
137 * const destination = yield* IoTWireless.Destination("Uplinks", {
138 * expressionType: "RuleName",
139 * expression: "sensor_uplinks",
140 * roleArn: deliveryRole.roleArn,
141 * });
142 *
143 * // inside the Function effect (provide Lambda.WirelessDestinationEventSource):
144 * yield* IoTWireless.consumeUplinks(destination, (uplinks) =>
145 * uplinks.pipe(
146 * Stream.runForEach((uplink) => processUplink(uplink)),
147 * Effect.orDie,
148 * ),
149 * );
150 * ```
151 *
152 * @resource
153 */
154 export const Destination = Resource<Destination>("AWS.IoTWireless.Destination");
155
156 export const DestinationProvider = () =>
157 Provider.effect(
158 Destination,
159 Effect.gen(function* () {
160 const createName = Effect.fn(function* (id: string, props: { name?: string }) {
161 return props.name ?? (yield* createPhysicalName({ id, maxLength: 128 }));
162 });
163
164 const getDestination = (name: string) =>
165 iotw
166 .getDestination({ Name: name })
167 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
168
169 const toAttrs = Effect.fn(function* (destination: iotw.GetDestinationResponse, name: string) {
170 if (destination.Arn === undefined) {
171 return yield* new IoTWirelessDestinationUnexpectedResponse({
172 message: `IoT Wireless destination '${name}' returned without Arn`,
173 });
174 }
175 return {
176 destinationName: destination.Name ?? name,
177 destinationArn: destination.Arn,
178 expressionType: destination.ExpressionType ?? "RuleName",
179 expression: destination.Expression ?? "",
180 roleArn: destination.RoleArn ?? "",
181 };
182 });
183
184 return Destination.Provider.of({
185 stables: ["destinationName", "destinationArn"],
186
187 list: () =>
188 iotw.listDestinations.pages({}).pipe(
189 Stream.runCollect,
190 Effect.map((chunk) =>
191 Array.from(chunk)
192 .flatMap((page) => page.DestinationList ?? [])
193 .flatMap((d) =>
194 d.Name !== undefined && d.Arn !== undefined
195 ? [
196 {
197 destinationName: d.Name,
198 destinationArn: d.Arn,
199 expressionType: d.ExpressionType ?? "RuleName",
200 expression: d.Expression ?? "",
201 roleArn: d.RoleArn ?? "",
202 },
203 ]
204 : [],
205 ),
206 ),
207 ),
208
209 read: Effect.fn(function* ({ id, olds, output }) {
210 const name = output?.destinationName ?? (yield* createName(id, olds ?? {}));
211 const destination = yield* getDestination(name);
212 if (destination === undefined) return undefined;
213 const attrs = yield* toAttrs(destination, name);
214 const tags = yield* readIotWirelessTags(attrs.destinationArn);
215 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
216 }),
217
218 // The name is the destination's identity — changing it replaces the
219 // resource. Everything else updates in place via UpdateDestination.
220 diff: Effect.fn(function* ({ id, news, olds }) {
221 if (!isResolved(news)) return undefined;
222 const oldName = yield* createName(id, olds ?? {});
223 const newName = yield* createName(id, news);
224 if (oldName !== newName) return { action: "replace" } as const;
225 }),
226
227 reconcile: Effect.fn(function* ({ id, news, output, session }) {
228 const name = output?.destinationName ?? (yield* createName(id, news));
229 const internalTags = yield* createInternalTags(id);
230 const desiredTags = { ...news.tags, ...internalTags };
231
232 // 1. OBSERVE — cloud state is authoritative.
233 let destination = yield* getDestination(name);
234
235 // 2. ENSURE — create if missing; a Conflict means a peer created
236 // it concurrently, so fall through to the sync step.
237 if (destination === undefined) {
238 yield* session.note(`creating destination ${name}`);
239 yield* iotw
240 .createDestination({
241 Name: name,
242 ExpressionType: news.expressionType,
243 Expression: news.expression,
244 Description: news.description,
245 RoleArn: news.roleArn,
246 Tags: createTagsList(desiredTags),
247 })
248 .pipe(
249 Effect.asVoid,
250 Effect.catchTag("ConflictException", () => Effect.void),
251 );
252 destination = yield* getDestination(name);
253 }
254 if (destination === undefined) {
255 return yield* new IoTWirelessDestinationUnexpectedResponse({
256 message: `IoT Wireless destination '${name}' not found after create`,
257 });
258 }
259
260 // 3. SYNC — apply the expression/description/role delta from
261 // OBSERVED state; skip the API call entirely on no-op.
262 const expressionDelta =
263 destination.Expression !== news.expression ||
264 destination.ExpressionType !== news.expressionType;
265 const descriptionDelta =
266 news.description !== undefined && destination.Description !== news.description;
267 const roleDelta = destination.RoleArn !== news.roleArn;
268 if (expressionDelta || descriptionDelta || roleDelta) {
269 yield* iotw.updateDestination({
270 Name: name,
271 ExpressionType: news.expressionType,
272 Expression: news.expression,
273 Description: news.description,
274 RoleArn: news.roleArn,
275 });
276 destination = yield* getDestination(name);
277 }
278 if (destination === undefined) {
279 return yield* new IoTWirelessDestinationUnexpectedResponse({
280 message: `IoT Wireless destination '${name}' vanished during update`,
281 });
282 }
283
284 // 3b. SYNC tags — diff against OBSERVED cloud tags.
285 const attrs = yield* toAttrs(destination, name);
286 yield* syncIotWirelessTags(attrs.destinationArn, desiredTags);
287
288 yield* session.note(attrs.destinationArn);
289 return attrs;
290 }),
291
292 delete: Effect.fn(function* ({ output }) {
293 yield* iotw.deleteDestination({ Name: output.destinationName }).pipe(
294 Effect.asVoid,
295 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
296 );
297 }),
298 });
299 }),
300 );