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

main
ts 229 lines 9.01 KB
Raw
1 import * as mi from "@distilled.cloud/aws/iot-managed-integrations";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { AWSEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import { syncManagedIntegrationsTags, toTagRecord } from "./internal.ts";
13
14 export class IoTManagedIntegrationsNotificationConfigurationUnexpectedResponse extends Data.TaggedError(
15 "IoTManagedIntegrationsNotificationConfigurationUnexpectedResponse",
16 )<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export interface NotificationConfigurationProps {
22 /**
23 * Event type to route, e.g. `DEVICE_STATE`, `DEVICE_LIFE_CYCLE`,
24 * `DEVICE_EVENT`, `DEVICE_COMMAND_REQUEST`, `DEVICE_OTA`,
25 * `CONNECTOR_ASSOCIATION`, `ACCOUNT_ASSOCIATION`,
26 * `CONNECTOR_ERROR_REPORT`. The event type is the configuration's
27 * identifier — at most one configuration exists per event type, and
28 * changing it replaces the configuration.
29 */
30 eventType: mi.EventType;
31 /**
32 * Name of the {@link Destination} that receives events of this type.
33 */
34 destinationName: string;
35 /**
36 * User-defined tags to apply to the notification configuration.
37 */
38 tags?: Record<string, string>;
39 }
40
41 export interface NotificationConfiguration extends Resource<
42 "AWS.IoTManagedIntegrations.NotificationConfiguration",
43 NotificationConfigurationProps,
44 {
45 /** Event type routed by this configuration (its identifier). */
46 eventType: mi.EventType;
47 /** Name of the destination that receives the events. */
48 destinationName: string;
49 /** Constructed ARN of the notification configuration. */
50 notificationConfigurationArn: string;
51 /** Tags applied to the notification configuration (user + internal). */
52 tags: Record<string, string>;
53 },
54 never,
55 Providers
56 > {}
57
58 /**
59 * An AWS IoT Managed Integrations notification configuration — routes one
60 * event type (device state, lifecycle, OTA, discovery, association events)
61 * to a {@link Destination}.
62 *
63 * Managed integrations has no direct Lambda invocation path: events flow
64 * `NotificationConfiguration -> Destination -> Kinesis Data Stream`, so pair
65 * this resource with a Kinesis-backed destination and consume the stream
66 * with the Kinesis stream event source (`Kinesis.consumeStreamRecords`).
67 *
68 * IoT Managed Integrations is a regional service available in a limited set
69 * of regions (e.g. `eu-west-1`, `ca-central-1`).
70 *
71 * ### Routing Events
72 * **Example:** Route Device State Events to a Kinesis Destination
73 * ```typescript
74 * const destination = yield* Destination("EventDestination", {
75 * deliveryDestinationArn: stream.streamArn,
76 * roleArn: role.roleArn,
77 * });
78 * const routing = yield* NotificationConfiguration("DeviceState", {
79 * eventType: "DEVICE_STATE",
80 * destinationName: destination.destinationName,
81 * });
82 * ```
83 *
84 * **Example:** Route Lifecycle Events with Tags
85 * ```typescript
86 * const routing = yield* NotificationConfiguration("Lifecycle", {
87 * eventType: "DEVICE_LIFE_CYCLE",
88 * destinationName: destination.destinationName,
89 * tags: { team: "iot" },
90 * });
91 * ```
92 *
93 * @resource
94 */
95 export const NotificationConfiguration = Resource<NotificationConfiguration>(
96 "AWS.IoTManagedIntegrations.NotificationConfiguration",
97 );
98
99 export const NotificationConfigurationProvider = () =>
100 Provider.effect(
101 NotificationConfiguration,
102 Effect.gen(function* () {
103 const observe = (eventType: mi.EventType) =>
104 mi
105 .getNotificationConfiguration({ EventType: eventType })
106 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
107
108 // GetNotificationConfiguration does not return an ARN; the tag APIs
109 // need one, so construct it from the ambient account/region (same
110 // approach as the Destination provider).
111 const configurationArn = Effect.fn(function* (eventType: mi.EventType) {
112 const { accountId, region } = yield* AWSEnvironment.current;
113 return `arn:aws:iotmanagedintegrations:${region}:${accountId}:notification-configuration/${eventType}`;
114 });
115
116 const toAttributes = Effect.fn(function* (
117 configuration: mi.GetNotificationConfigurationResponse,
118 ) {
119 if (configuration.EventType === undefined || configuration.DestinationName === undefined) {
120 return yield* new IoTManagedIntegrationsNotificationConfigurationUnexpectedResponse({
121 message: "notification configuration response is missing EventType or DestinationName",
122 });
123 }
124 return {
125 eventType: configuration.EventType,
126 destinationName: configuration.DestinationName,
127 notificationConfigurationArn: yield* configurationArn(configuration.EventType),
128 tags: toTagRecord(configuration.Tags),
129 };
130 });
131
132 return {
133 stables: ["eventType", "notificationConfigurationArn"],
134 diff: Effect.fn(function* ({ olds, news }) {
135 if (!isResolved(news)) return;
136 if (olds !== undefined && olds.eventType !== news.eventType) {
137 return { action: "replace" } as const;
138 }
139 }),
140 read: Effect.fn(function* ({ id, olds, output }) {
141 const eventType = output?.eventType ?? olds?.eventType;
142 if (eventType === undefined) return undefined;
143 const configuration = yield* observe(eventType);
144 if (configuration === undefined) return undefined;
145 const attrs = yield* toAttributes(configuration);
146 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
147 }),
148 reconcile: Effect.fn(function* ({ id, news, session }) {
149 const internalTags = yield* createInternalTags(id);
150 const desiredTags = { ...internalTags, ...news.tags };
151
152 // Observe — cloud state is authoritative; the event type is the
153 // identifier so no cached output is needed to find it.
154 let configuration = yield* observe(news.eventType);
155
156 // Ensure — create if missing; tolerate a concurrent-create race.
157 if (configuration === undefined) {
158 yield* mi
159 .createNotificationConfiguration({
160 EventType: news.eventType,
161 DestinationName: news.destinationName,
162 Tags: desiredTags,
163 })
164 .pipe(Effect.catchTag("ConflictException", () => Effect.void));
165 configuration = yield* observe(news.eventType);
166 if (configuration === undefined) {
167 return yield* new IoTManagedIntegrationsNotificationConfigurationUnexpectedResponse({
168 message: `notification configuration '${news.eventType}' vanished after create`,
169 });
170 }
171 }
172
173 // Sync the destination — apply only the delta.
174 if (configuration.DestinationName !== news.destinationName) {
175 yield* mi.updateNotificationConfiguration({
176 EventType: news.eventType,
177 DestinationName: news.destinationName,
178 });
179 configuration = {
180 ...configuration,
181 DestinationName: news.destinationName,
182 };
183 }
184
185 // Sync tags — diff against OBSERVED cloud tags.
186 yield* syncManagedIntegrationsTags(
187 yield* configurationArn(news.eventType),
188 toTagRecord(configuration.Tags),
189 desiredTags,
190 );
191
192 const attrs = yield* toAttributes(configuration);
193 yield* session.note(attrs.eventType);
194 return { ...attrs, tags: desiredTags };
195 }),
196 // Enumerate every notification configuration; fetch each one to
197 // resolve tags (summaries omit them).
198 list: () =>
199 Effect.gen(function* () {
200 const summaries = yield* mi.listNotificationConfigurations.items({}).pipe(
201 Stream.runCollect,
202 Effect.map((chunk) => Array.from(chunk)),
203 );
204 const configurations = yield* Effect.forEach(
205 summaries.filter(
206 (
207 s,
208 ): s is mi.NotificationConfigurationSummary & {
209 EventType: mi.EventType;
210 } => s.EventType !== undefined,
211 ),
212 (summary) => observe(summary.EventType),
213 { concurrency: 5 },
214 );
215 return yield* Effect.forEach(
216 configurations.filter(
217 (c): c is mi.GetNotificationConfigurationResponse => c !== undefined,
218 ),
219 toAttributes,
220 );
221 }),
222 delete: Effect.fn(function* ({ output }) {
223 yield* mi
224 .deleteNotificationConfiguration({ EventType: output.eventType })
225 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
226 }),
227 };
228 }),
229 );