@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, 06:00 UTC

main
ts 217 lines 7.85 KB
Raw
1 import * as athena from "@distilled.cloud/aws/athena";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9
10 export interface PreparedStatementProps {
11 /**
12 * Name of the prepared statement. If omitted, a unique name is generated.
13 * Must start with a letter or underscore and contain only letters, digits,
14 * and underscores. Changing this replaces the prepared statement.
15 */
16 statementName?: string;
17 /**
18 * The SQL statement text, with `?` positional parameters (e.g.
19 * `SELECT * FROM t WHERE id = ?`). Updatable in place.
20 */
21 queryStatement: string;
22 /**
23 * Workgroup the statement is saved in. Changing this replaces the prepared
24 * statement.
25 * @default "primary"
26 */
27 workGroup?: string;
28 /**
29 * Optional human-readable description. Updatable in place.
30 */
31 description?: string;
32 }
33
34 export interface PreparedStatement extends Resource<
35 "AWS.Athena.PreparedStatement",
36 PreparedStatementProps,
37 {
38 /**
39 * Name of the prepared statement (its identity within the workgroup).
40 */
41 statementName: string;
42 /**
43 * Workgroup the statement is saved in.
44 */
45 workGroup: string;
46 /**
47 * The SQL statement text.
48 */
49 queryStatement: string;
50 /**
51 * Description of the prepared statement.
52 */
53 description: string | undefined;
54 },
55 never,
56 Providers
57 > {}
58
59 /**
60 * An Amazon Athena prepared statement — a named, parameterized SQL statement
61 * saved in a workgroup and run with `EXECUTE name USING ...`. Identity is the
62 * `(workGroup, statementName)` pair; the `queryStatement` and `description`
63 * are updatable in place.
64 *
65 * ### Preparing Statements
66 * **Example:** Save a parameterized statement in a workgroup
67 * ```typescript
68 * const stmt = yield* AWS.Athena.PreparedStatement("TopN", {
69 * workGroup: wg.workGroupName,
70 * queryStatement: "SELECT * FROM analytics.orders WHERE customer_id = ?",
71 * });
72 * // then at runtime: EXECUTE <stmt.statementName> USING 'customer-123'
73 * ```
74 *
75 * @resource
76 */
77 export const PreparedStatement = Resource<PreparedStatement>("AWS.Athena.PreparedStatement");
78
79 const toAttributes = (ps: athena.PreparedStatement) => ({
80 statementName: ps.StatementName!,
81 workGroup: ps.WorkGroupName ?? "primary",
82 queryStatement: ps.QueryStatement ?? "",
83 description: ps.Description,
84 });
85
86 export const PreparedStatementProvider = () =>
87 Provider.effect(
88 PreparedStatement,
89 Effect.gen(function* () {
90 // Statement names must match [a-zA-Z_][a-zA-Z0-9_@:]* — generate the
91 // engine name and fold every other character to `_`.
92 const toName = (id: string, props: PreparedStatementProps) =>
93 props.statementName
94 ? Effect.succeed(props.statementName)
95 : createPhysicalName({ id, maxLength: 128 }).pipe(
96 Effect.map((n) => n.replace(/[^a-zA-Z0-9_]/g, "_")),
97 Effect.map((n) => (/^[a-zA-Z_]/.test(n) ? n : `_${n}`)),
98 );
99
100 const getOne = (workGroup: string, statementName: string) =>
101 athena
102 .getPreparedStatement({
103 WorkGroup: workGroup,
104 StatementName: statementName,
105 })
106 .pipe(
107 Effect.map((res) => res.PreparedStatement),
108 Effect.catchTag(
109 ["ResourceNotFoundException", "WorkGroupNotFound"],
110 () => Effect.undefined,
111 ),
112 );
113
114 return {
115 stables: ["statementName", "workGroup"],
116 diff: Effect.fn(function* ({ id, olds, news }) {
117 if (!isResolved(news)) return;
118 if ((yield* toName(id, olds ?? { queryStatement: "" })) !== (yield* toName(id, news))) {
119 return { action: "replace" } as const;
120 }
121 if ((olds?.workGroup ?? "primary") !== (news.workGroup ?? "primary")) {
122 return { action: "replace" } as const;
123 }
124 }),
125 read: Effect.fn(function* ({ id, olds, output }) {
126 const workGroup = output?.workGroup ?? olds?.workGroup ?? "primary";
127 const name = output?.statementName ?? (yield* toName(id, olds ?? { queryStatement: "" }));
128 const ps = yield* getOne(workGroup, name);
129 return ps ? toAttributes(ps) : undefined;
130 }),
131 list: () =>
132 Effect.gen(function* () {
133 const wgPages = yield* athena.listWorkGroups.pages({}).pipe(Stream.runCollect);
134 const workGroups = Array.from(wgPages)
135 .flatMap((page) => page.WorkGroups ?? [])
136 .flatMap((wg) => (wg.Name ? [wg.Name] : []));
137 const attrs: ReturnType<typeof toAttributes>[] = [];
138 for (const wg of workGroups) {
139 const namePages = yield* athena.listPreparedStatements
140 .pages({ WorkGroup: wg })
141 .pipe(Stream.runCollect);
142 const names = Array.from(namePages)
143 .flatMap((page) => page.PreparedStatements ?? [])
144 .flatMap((ps) => (ps.StatementName ? [ps.StatementName] : []));
145 for (let i = 0; i < names.length; i += 256) {
146 const res = yield* athena.batchGetPreparedStatement({
147 WorkGroup: wg,
148 PreparedStatementNames: names.slice(i, i + 256),
149 });
150 for (const ps of res.PreparedStatements ?? []) {
151 if (ps.StatementName) {
152 attrs.push(toAttributes({ ...ps, WorkGroupName: wg }));
153 }
154 }
155 }
156 }
157 return attrs;
158 }),
159 reconcile: Effect.fn(function* ({ id, news, output, session }) {
160 const workGroup = news.workGroup ?? "primary";
161 const name = output?.statementName ?? (yield* toName(id, news));
162
163 // Observe — cloud state is authoritative.
164 const ps = yield* getOne(workGroup, name);
165
166 if (!ps) {
167 // Ensure — create if missing. CreatePreparedStatement upserts on
168 // name collision within the workgroup, so a crash-and-retry race
169 // converges rather than erroring.
170 yield* athena.createPreparedStatement({
171 WorkGroup: workGroup,
172 StatementName: name,
173 QueryStatement: news.queryStatement,
174 Description: news.description,
175 });
176 } else if (
177 ps.QueryStatement !== news.queryStatement ||
178 (news.description !== undefined && ps.Description !== news.description)
179 ) {
180 // Sync — statement text and description are updatable in place.
181 yield* athena.updatePreparedStatement({
182 WorkGroup: workGroup,
183 StatementName: name,
184 QueryStatement: news.queryStatement,
185 Description: news.description,
186 });
187 }
188
189 yield* session.note(`${workGroup}/${name}`);
190 const final = yield* getOne(workGroup, name);
191 return final
192 ? toAttributes(final)
193 : {
194 statementName: name,
195 workGroup,
196 queryStatement: news.queryStatement,
197 description: news.description,
198 };
199 }),
200 delete: Effect.fn(function* ({ output }) {
201 // Idempotent — the statement (or its whole workgroup) may already be
202 // gone; both surface as typed not-found tags.
203 yield* athena
204 .deletePreparedStatement({
205 WorkGroup: output.workGroup,
206 StatementName: output.statementName,
207 })
208 .pipe(
209 Effect.catchTag(
210 ["ResourceNotFoundException", "WorkGroupNotFound"],
211 () => Effect.void,
212 ),
213 );
214 }),
215 };
216 }),
217 );