@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, 04:45 UTC

main
ts 193 lines 6.2 KB
Raw
1 import * as iot from "@distilled.cloud/aws/iot";
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 { hasAlchemyTags } from "alchemy/Tags";
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 { readIotTags, sanitizeRuleName, syncIotTags } from "./internal.ts";
13
14 export type Action = iot.Action;
15
16 export interface TopicRuleProps {
17 /**
18 * Name of the rule. Rule names may only contain letters, numbers, and
19 * underscores (`[a-zA-Z0-9_]`). If omitted, a unique name is generated.
20 * Changing it replaces the rule.
21 */
22 ruleName?: string;
23
24 /**
25 * The SQL statement used to query the topic, e.g.
26 * `SELECT * FROM 'my/topic'`.
27 */
28 sql: string;
29
30 /**
31 * The actions associated with the rule (Lambda, SQS, SNS, republish, ...).
32 */
33 actions: Action[];
34
35 /**
36 * A textual description of the rule.
37 */
38 description?: string;
39
40 /**
41 * Whether the rule is disabled.
42 * @default false
43 */
44 ruleDisabled?: boolean;
45
46 /**
47 * The version of the SQL rules engine to use (`2015-10-08` or `2016-03-23`).
48 * @default "2016-03-23"
49 */
50 awsIotSqlVersion?: string;
51
52 /**
53 * The action to take when an error occurs.
54 */
55 errorAction?: Action;
56
57 /**
58 * User tags to attach to the rule.
59 */
60 tags?: Record<string, string>;
61 }
62
63 export interface TopicRule extends Resource<
64 "AWS.IoT.TopicRule",
65 TopicRuleProps,
66 {
67 /** The name of the rule. */
68 ruleName: string;
69 /** The ARN of the rule. */
70 ruleArn: string;
71 },
72 never,
73 Providers
74 > {}
75
76 /**
77 * An AWS IoT topic rule — evaluates an SQL statement against messages
78 * published to MQTT topics and routes matching messages to one or more
79 * actions (invoke a Lambda, enqueue to SQS, republish, etc.).
80 *
81 * ### Creating a Rule
82 * **Example:** Route Messages to a Lambda
83 * ```typescript
84 * const rule = yield* TopicRule("ingest", {
85 * sql: "SELECT * FROM 'sensors/+/telemetry'",
86 * actions: [{ lambda: { functionArn: yield* fn.functionArn } }],
87 * });
88 * ```
89 *
90 * @resource
91 */
92 export const TopicRule = Resource<TopicRule>("AWS.IoT.TopicRule");
93
94 export const TopicRuleProvider = () =>
95 Provider.effect(
96 TopicRule,
97 Effect.gen(function* () {
98 const createName = Effect.fn(function* (id: string, props: TopicRuleProps) {
99 return (
100 props.ruleName ??
101 sanitizeRuleName(yield* createPhysicalName({ id, delimiter: "_", maxLength: 128 }))
102 );
103 });
104
105 const ruleArnOf = (accountId: string, region: string, ruleName: string) =>
106 `arn:aws:iot:${region}:${accountId}:rule/${ruleName}`;
107
108 const buildPayload = (props: TopicRuleProps): iot.TopicRulePayload => ({
109 sql: props.sql,
110 description: props.description,
111 actions: props.actions,
112 ruleDisabled: props.ruleDisabled,
113 awsIotSqlVersion: props.awsIotSqlVersion ?? "2016-03-23",
114 errorAction: props.errorAction,
115 });
116
117 return TopicRule.Provider.of({
118 stables: ["ruleName", "ruleArn"],
119 list: () =>
120 iot.listTopicRules.pages({}).pipe(
121 Stream.runCollect,
122 Effect.map((chunk) =>
123 Array.from(chunk).flatMap((page) =>
124 (page.rules ?? [])
125 .filter((r) => r.ruleName != null && r.ruleArn != null)
126 .map((r) => ({
127 ruleName: r.ruleName!,
128 ruleArn: r.ruleArn!,
129 })),
130 ),
131 ),
132 ),
133 read: Effect.fn(function* ({ id, olds, output }) {
134 const { accountId, region } = yield* AWSEnvironment.current;
135 const ruleName = output?.ruleName ?? (yield* createName(id, olds ?? {}));
136 const found = yield* iot
137 .getTopicRule({ ruleName })
138 .pipe(Effect.catchTag("TopicRuleNotFound", () => Effect.undefined));
139 if (!found) return undefined;
140 const ruleArn = found.ruleArn ?? ruleArnOf(accountId, region, ruleName);
141 const attrs = { ruleName, ruleArn };
142 const tags = yield* readIotTags(ruleArn);
143 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
144 }),
145 diff: Effect.fn(function* ({ id, news, olds }) {
146 if (!isResolved(news)) return undefined;
147 const oldName = yield* createName(id, olds);
148 const newName = yield* createName(id, news);
149 if (oldName !== newName) return { action: "replace" } as const;
150 return undefined;
151 }),
152 reconcile: Effect.fn(function* ({ id, news, output, session }) {
153 const { accountId, region } = yield* AWSEnvironment.current;
154 const ruleName = output?.ruleName ?? (yield* createName(id, news));
155 const ruleArn = ruleArnOf(accountId, region, ruleName);
156 const payload = buildPayload(news);
157
158 // OBSERVE
159 const live = yield* iot
160 .getTopicRule({ ruleName })
161 .pipe(Effect.catchTag("TopicRuleNotFound", () => Effect.undefined));
162
163 // ENSURE / SYNC — createTopicRule for a new rule, replaceTopicRule
164 // (a full upsert of the payload) for an existing one.
165 if (live === undefined) {
166 yield* iot
167 .createTopicRule({ ruleName, topicRulePayload: payload })
168 .pipe(
169 Effect.catchTag("ResourceAlreadyExistsException", () =>
170 iot.replaceTopicRule({ ruleName, topicRulePayload: payload }),
171 ),
172 );
173 } else {
174 yield* iot.replaceTopicRule({
175 ruleName,
176 topicRulePayload: payload,
177 });
178 }
179
180 // SYNC tags
181 yield* syncIotTags(ruleArn, id, news.tags);
182
183 yield* session.note(ruleName);
184 return { ruleName, ruleArn };
185 }),
186 delete: Effect.fn(function* ({ output }) {
187 yield* iot
188 .deleteTopicRule({ ruleName: output.ruleName })
189 .pipe(Effect.catchTag("TopicRuleNotFound", () => Effect.void));
190 }),
191 });
192 }),
193 );