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

main
ts 210 lines 7.09 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 NamedQueryProps {
11 /**
12 * Display name of the saved query. If omitted, a unique name is generated.
13 * Up to 128 characters.
14 */
15 name?: string;
16 /**
17 * The SQL text of the saved query.
18 */
19 queryString: string;
20 /**
21 * Glue/Athena database the query runs against. Changing this replaces the
22 * named query (Athena cannot re-point a saved query's database in place).
23 */
24 database: string;
25 /**
26 * Optional human-readable description.
27 */
28 description?: string;
29 /**
30 * Workgroup the query is saved in. Changing this replaces the named query.
31 * @default "primary"
32 */
33 workGroup?: string;
34 }
35
36 export interface NamedQuery extends Resource<
37 "AWS.Athena.NamedQuery",
38 NamedQueryProps,
39 {
40 /**
41 * Unique ID of the named query.
42 */
43 namedQueryId: string;
44 /**
45 * Name of the saved query.
46 */
47 name: string;
48 /**
49 * The saved SQL statement.
50 */
51 queryString: string;
52 /**
53 * Database the query runs against.
54 */
55 database: string;
56 /**
57 * Description of the query.
58 */
59 description: string | undefined;
60 /**
61 * Workgroup the query is saved in.
62 */
63 workGroup: string;
64 },
65 never,
66 Providers
67 > {}
68
69 /**
70 * An Amazon Athena named (saved) query — a reusable SQL statement stored
71 * against a Glue database inside a workgroup. Its identity is the
72 * server-assigned `NamedQueryId`; the `name`, `description`, and `queryString`
73 * are updatable in place, while changing `database` or `workGroup` replaces it.
74 *
75 * ### Saving Queries
76 * **Example:** Save a query against a Glue database
77 * ```typescript
78 * const query = yield* AWS.Athena.NamedQuery("TopCustomers", {
79 * database: "analytics",
80 * queryString: "SELECT customer_id, SUM(amount) AS total " +
81 * "FROM orders GROUP BY customer_id ORDER BY total DESC LIMIT 10",
82 * workGroup: wg.workGroupName,
83 * });
84 * ```
85 *
86 * @resource
87 */
88 export const NamedQuery = Resource<NamedQuery>("AWS.Athena.NamedQuery");
89
90 const toAttributes = (nq: athena.NamedQuery) => ({
91 namedQueryId: nq.NamedQueryId!,
92 name: nq.Name,
93 queryString: nq.QueryString,
94 database: nq.Database,
95 description: nq.Description,
96 workGroup: nq.WorkGroup ?? "primary",
97 });
98
99 export const NamedQueryProvider = () =>
100 Provider.effect(
101 NamedQuery,
102 Effect.gen(function* () {
103 const toName = (id: string, props: NamedQueryProps) =>
104 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 128 });
105
106 // Deterministic per-instance idempotency token so a create that crashes
107 // before state persists re-returns the SAME NamedQueryId on re-run
108 // instead of creating a duplicate saved query.
109 const toToken = (id: string) =>
110 createPhysicalName({ id, maxLength: 90 }).pipe(
111 Effect.map((n) => `${n}-alchemy-namedquery-idempotency`),
112 );
113
114 const getOne = (namedQueryId: string) =>
115 athena.getNamedQuery({ NamedQueryId: namedQueryId }).pipe(
116 Effect.map((res) => res.NamedQuery),
117 Effect.catchTag("NamedQueryNotFound", () => Effect.undefined),
118 );
119
120 return {
121 stables: ["namedQueryId"],
122 diff: Effect.fn(function* ({ olds, news }) {
123 if (!isResolved(news)) return;
124 if ((olds?.database ?? undefined) !== news.database) {
125 return { action: "replace" } as const;
126 }
127 if ((olds?.workGroup ?? "primary") !== (news.workGroup ?? "primary")) {
128 return { action: "replace" } as const;
129 }
130 }),
131 read: Effect.fn(function* ({ output }) {
132 // Named queries have no deterministic name-based lookup — identity is
133 // the server-assigned id. Without a cached id there's nothing to read.
134 if (!output?.namedQueryId) return undefined;
135 const nq = yield* getOne(output.namedQueryId);
136 return nq ? toAttributes(nq) : undefined;
137 }),
138 list: () =>
139 Effect.gen(function* () {
140 const wgPages = yield* athena.listWorkGroups.pages({}).pipe(Stream.runCollect);
141 const workGroups = Array.from(wgPages)
142 .flatMap((page) => page.WorkGroups ?? [])
143 .flatMap((wg) => (wg.Name ? [wg.Name] : []));
144 const attrs: ReturnType<typeof toAttributes>[] = [];
145 for (const wg of workGroups) {
146 const idPages = yield* athena.listNamedQueries
147 .pages({ WorkGroup: wg })
148 .pipe(Stream.runCollect);
149 const ids = Array.from(idPages).flatMap((page) => page.NamedQueryIds ?? []);
150 for (let i = 0; i < ids.length; i += 50) {
151 const res = yield* athena.batchGetNamedQuery({
152 NamedQueryIds: ids.slice(i, i + 50),
153 });
154 for (const nq of res.NamedQueries ?? []) {
155 if (nq.NamedQueryId) attrs.push(toAttributes(nq));
156 }
157 }
158 }
159 return attrs;
160 }),
161 reconcile: Effect.fn(function* ({ id, news, output, session }) {
162 const name = yield* toName(id, news);
163 const workGroup = news.workGroup ?? "primary";
164
165 // Observe — cloud state (by cached id) is authoritative.
166 let nq = output?.namedQueryId ? yield* getOne(output.namedQueryId) : undefined;
167
168 if (nq) {
169 // Sync — Name/Description/QueryString are updatable in place.
170 if (
171 nq.Name !== name ||
172 nq.Description !== news.description ||
173 nq.QueryString !== news.queryString
174 ) {
175 yield* athena.updateNamedQuery({
176 NamedQueryId: nq.NamedQueryId!,
177 Name: name,
178 Description: news.description,
179 QueryString: news.queryString,
180 });
181 }
182 } else {
183 // Ensure — create with a deterministic idempotency token.
184 const token = yield* toToken(id);
185 const created = yield* athena.createNamedQuery({
186 Name: name,
187 Description: news.description,
188 Database: news.database,
189 QueryString: news.queryString,
190 WorkGroup: workGroup,
191 ClientRequestToken: token,
192 });
193 nq = yield* getOne(created.NamedQueryId!);
194 }
195
196 if (!nq?.NamedQueryId) {
197 return yield* Effect.die(new Error(`NamedQuery ${name} did not materialize`));
198 }
199
200 yield* session.note(nq.NamedQueryId);
201 return toAttributes(nq);
202 }),
203 delete: Effect.fn(function* ({ output }) {
204 yield* athena
205 .deleteNamedQuery({ NamedQueryId: output.namedQueryId })
206 .pipe(Effect.catchTag("NamedQueryNotFound", () => Effect.void));
207 }),
208 };
209 }),
210 );