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

main
ts 292 lines 10.1 KB
Raw
1 import * as quicksight from "@distilled.cloud/aws/quicksight";
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, 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 { AWSEnvironment } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13 import { readQuickSightTags, syncQuickSightTags, toWireTags, waitForSettled } from "./internal.ts";
14
15 export class QuickSightDataSourceUnexpectedResponse extends Data.TaggedError(
16 "QuickSightDataSourceUnexpectedResponse",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 /**
23 * Properties for an Amazon QuickSight data source — a connection to an
24 * external data store (Athena, S3, Redshift, an RDS engine, etc.) that
25 * datasets read from.
26 */
27 export interface DataSourceProps {
28 /**
29 * Unique id of the data source within the account. Stable — changing it
30 * replaces the data source. If omitted, a unique id is generated.
31 */
32 dataSourceId?: string;
33
34 /**
35 * Display name of the data source.
36 */
37 name: string;
38
39 /**
40 * Type of the underlying data store (e.g. `ATHENA`, `S3`, `REDSHIFT`,
41 * `POSTGRESQL`). Immutable — changing the type replaces the data source.
42 */
43 type: quicksight.DataSourceType;
44
45 /**
46 * Connection parameters specific to the data source `type` (e.g.
47 * `AthenaParameters.WorkGroup`, `S3Parameters.ManifestFileLocation`).
48 */
49 dataSourceParameters?: quicksight.DataSourceParameters;
50
51 /**
52 * Credentials QuickSight uses to connect. Only required for stores that
53 * authenticate with a username/password or a Secrets Manager secret.
54 * Not required for `ATHENA`/`S3` sources that rely on the QuickSight IAM
55 * role.
56 */
57 credentials?: quicksight.DataSourceCredentials;
58
59 /**
60 * Resource-level permissions granting QuickSight principals access to the
61 * data source.
62 */
63 permissions?: quicksight.ResourcePermission[];
64
65 /**
66 * VPC connection used to reach a data store inside a VPC.
67 */
68 vpcConnectionProperties?: quicksight.VpcConnectionProperties;
69
70 /**
71 * SSL options for the connection.
72 */
73 sslProperties?: quicksight.SslProperties;
74
75 /**
76 * Tags to apply to the data source.
77 */
78 tags?: Record<string, string>;
79 }
80
81 export interface DataSource extends Resource<
82 "AWS.QuickSight.DataSource",
83 DataSourceProps,
84 {
85 /** Unique id of the data source within the account. */
86 dataSourceId: string;
87 /** ARN of the data source. */
88 arn: string;
89 /** Display name of the data source. */
90 name: string;
91 /** Type of the underlying data store. */
92 type: quicksight.DataSourceType;
93 /** Current lifecycle status (e.g. `CREATION_SUCCESSFUL`). */
94 status: string;
95 },
96 never,
97 Providers
98 > {}
99
100 /**
101 * An Amazon QuickSight data source — a connection to an external data store
102 * that datasets read from.
103 *
104 * QuickSight requires an active account subscription in the region. Without
105 * one, create operations fail with the typed `QuickSightSubscriptionRequired`
106 * error.
107 *
108 * ### Creating a Data Source
109 * **Example:** Athena Data Source
110 * ```typescript
111 * const source = yield* DataSource("analytics", {
112 * name: "Athena Analytics",
113 * type: "ATHENA",
114 * dataSourceParameters: { AthenaParameters: { WorkGroup: "primary" } },
115 * });
116 * ```
117 *
118 * **Example:** S3 Manifest Data Source
119 * ```typescript
120 * const source = yield* DataSource("s3-source", {
121 * name: "S3 Sales Data",
122 * type: "S3",
123 * dataSourceParameters: {
124 * S3Parameters: {
125 * ManifestFileLocation: { Bucket: "my-bucket", Key: "manifest.json" },
126 * },
127 * },
128 * });
129 * ```
130 *
131 * @resource
132 */
133 export const DataSource = Resource<DataSource>("AWS.QuickSight.DataSource");
134
135 export const DataSourceProvider = () =>
136 Provider.effect(
137 DataSource,
138 Effect.gen(function* () {
139 const toId = (id: string, props: Partial<DataSourceProps>) =>
140 props.dataSourceId
141 ? Effect.succeed(props.dataSourceId)
142 : createPhysicalName({ id, maxLength: 64 });
143
144 const readSource = Effect.fn(function* (accountId: string, dataSourceId: string) {
145 const response = yield* quicksight
146 .describeDataSource({
147 AwsAccountId: accountId,
148 DataSourceId: dataSourceId,
149 })
150 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
151 const source = response?.DataSource;
152 if (source === undefined || source.Status === "DELETED") {
153 return undefined;
154 }
155 return source;
156 });
157
158 const toAttrs = (source: quicksight.DataSource) => ({
159 dataSourceId: source.DataSourceId,
160 arn: source.Arn,
161 name: source.Name,
162 type: source.Type,
163 status: source.Status,
164 });
165
166 return DataSource.Provider.of({
167 stables: ["dataSourceId", "arn"],
168
169 diff: Effect.fn(function* ({ id, olds = {}, news }) {
170 if (!isResolved(news)) return undefined;
171 if ((yield* toId(id, olds)) !== (yield* toId(id, news))) {
172 return { action: "replace" } as const;
173 }
174 if ((olds.type ?? undefined) !== (news.type ?? undefined)) {
175 return { action: "replace" } as const;
176 }
177 }),
178
179 read: Effect.fn(function* ({ id, olds = {}, output }) {
180 const { accountId } = yield* AWSEnvironment.current;
181 const dataSourceId = output?.dataSourceId ?? (yield* toId(id, olds));
182 const source = yield* readSource(accountId, dataSourceId);
183 if (source === undefined) return undefined;
184 const attrs = toAttrs(source);
185 const tags = yield* readQuickSightTags(attrs.arn);
186 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
187 }),
188
189 reconcile: Effect.fn(function* ({ id, news, output, session }) {
190 const { accountId } = yield* AWSEnvironment.current;
191 const dataSourceId = output?.dataSourceId ?? (yield* toId(id, news));
192 const internalTags = yield* createInternalTags(id);
193 const desiredTags = { ...internalTags, ...news.tags };
194
195 // 1. Observe — cloud state is authoritative.
196 let observed = yield* readSource(accountId, dataSourceId);
197
198 // 2. Ensure — create if missing; tolerate an AlreadyExists race.
199 if (observed === undefined) {
200 yield* quicksight
201 .createDataSource({
202 AwsAccountId: accountId,
203 DataSourceId: dataSourceId,
204 Name: news.name,
205 Type: news.type,
206 DataSourceParameters: news.dataSourceParameters,
207 Credentials: news.credentials,
208 Permissions: news.permissions,
209 VpcConnectionProperties: news.vpcConnectionProperties,
210 SslProperties: news.sslProperties,
211 Tags: toWireTags(desiredTags),
212 })
213 .pipe(Effect.catchTag("ResourceExistsException", () => Effect.void));
214 observed = yield* waitForSettled(
215 dataSourceId,
216 readSource(accountId, dataSourceId).pipe(
217 Effect.map((s) => (s === undefined ? undefined : { ...s, status: s.Status })),
218 ),
219 );
220 if (observed === undefined) {
221 return yield* new QuickSightDataSourceUnexpectedResponse({
222 message: `QuickSight data source '${dataSourceId}' disappeared while creating`,
223 });
224 }
225 } else {
226 // 3. Sync — apply mutable settings via an idempotent update.
227 yield* quicksight.updateDataSource({
228 AwsAccountId: accountId,
229 DataSourceId: dataSourceId,
230 Name: news.name,
231 DataSourceParameters: news.dataSourceParameters,
232 Credentials: news.credentials,
233 VpcConnectionProperties: news.vpcConnectionProperties,
234 SslProperties: news.sslProperties,
235 });
236 observed = yield* waitForSettled(
237 dataSourceId,
238 readSource(accountId, dataSourceId).pipe(
239 Effect.map((s) => (s === undefined ? undefined : { ...s, status: s.Status })),
240 ),
241 );
242 if (observed === undefined) {
243 return yield* new QuickSightDataSourceUnexpectedResponse({
244 message: `QuickSight data source '${dataSourceId}' disappeared while updating`,
245 });
246 }
247 }
248
249 // 3b. Sync tags — diff against OBSERVED cloud tags.
250 yield* syncQuickSightTags(observed.Arn, desiredTags);
251
252 yield* session.note(dataSourceId);
253 return toAttrs(observed);
254 }),
255
256 delete: Effect.fn(function* ({ output }) {
257 const { accountId } = yield* AWSEnvironment.current;
258 yield* quicksight
259 .deleteDataSource({
260 AwsAccountId: accountId,
261 DataSourceId: output.dataSourceId,
262 })
263 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
264 }),
265
266 list: () =>
267 Effect.gen(function* () {
268 const { accountId } = yield* AWSEnvironment.current;
269 return yield* quicksight.listDataSources.pages({ AwsAccountId: accountId }).pipe(
270 Stream.runCollect,
271 Effect.map((chunk) =>
272 Array.from(chunk)
273 .flatMap((page) => page.DataSources ?? [])
274 .flatMap((s) =>
275 s.DataSourceId !== undefined && s.Arn !== undefined && s.Status !== "DELETED"
276 ? [
277 {
278 dataSourceId: s.DataSourceId,
279 arn: s.Arn,
280 name: s.Name,
281 type: s.Type,
282 status: s.Status,
283 },
284 ]
285 : [],
286 ),
287 ),
288 );
289 }),
290 });
291 }),
292 );