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

main
ts 236 lines 8.15 KB
Raw
1 import * as forecast from "@distilled.cloud/aws/forecast";
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 Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { readForecastTags, syncForecastTags, toForecastName } from "./internal.ts";
13
14 export interface SchemaAttribute {
15 /** Name of the field in the dataset (e.g. `item_id`, `timestamp`). */
16 attributeName: string;
17 /** Type of the field: `string`, `integer`, `float`, `timestamp`, or `geolocation`. */
18 attributeType: string;
19 }
20
21 export interface DatasetSchema {
22 /** The ordered list of fields that make up the dataset. */
23 attributes: SchemaAttribute[];
24 }
25
26 export interface DatasetEncryptionConfig {
27 /** ARN of the IAM role Forecast assumes to access the KMS key. */
28 roleArn: string;
29 /** ARN of the customer-managed KMS key. */
30 kmsKeyArn: string;
31 }
32
33 export interface DatasetProps {
34 /**
35 * Name of the dataset. If omitted, a unique name is generated from the app,
36 * stage, and logical ID. Changing the name replaces the dataset.
37 */
38 datasetName?: string;
39 /**
40 * The forecasting domain: `RETAIL`, `CUSTOM`, `INVENTORY_PLANNING`,
41 * `EC2_CAPACITY`, `WORK_FORCE`, `WEB_TRAFFIC`, or `METRICS`. Immutable —
42 * changing it replaces the dataset.
43 */
44 domain: string;
45 /**
46 * The dataset type: `TARGET_TIME_SERIES`, `RELATED_TIME_SERIES`, or
47 * `ITEM_METADATA`. Immutable — changing it replaces the dataset.
48 */
49 datasetType: string;
50 /**
51 * The frequency of data collection (e.g. `D` for daily, `H` for hourly).
52 * Required for time-series datasets. Immutable — changing it replaces the
53 * dataset.
54 */
55 dataFrequency?: string;
56 /**
57 * The schema describing the dataset's fields. Immutable — changing it
58 * replaces the dataset.
59 */
60 schema: DatasetSchema;
61 /**
62 * Customer-managed KMS encryption configuration. Immutable — changing it
63 * replaces the dataset.
64 */
65 encryptionConfig?: DatasetEncryptionConfig;
66 /**
67 * User-defined tags for the dataset.
68 */
69 tags?: Record<string, string>;
70 }
71
72 export interface Dataset extends Resource<
73 "AWS.Forecast.Dataset",
74 DatasetProps,
75 {
76 /** The ARN of the dataset. */
77 datasetArn: string;
78 /** The name of the dataset. */
79 datasetName: string;
80 /** The forecasting domain of the dataset, e.g. `RETAIL` or `CUSTOM`. */
81 domain: string;
82 /** The dataset type, e.g. `TARGET_TIME_SERIES`. */
83 datasetType: string;
84 /** The dataset status, e.g. `ACTIVE`. */
85 status: string;
86 },
87 never,
88 Providers
89 > {}
90
91 /**
92 * An Amazon Forecast dataset — a typed, domain-scoped collection of
93 * time-series (or metadata) records described by a schema. Creating the
94 * dataset is a cheap metadata operation; bulk imports and training happen
95 * through separate import jobs and predictors.
96 *
97 * ### Creating a Dataset
98 * **Example:** Target Time-Series Dataset
99 * ```typescript
100 * const dataset = yield* Forecast.Dataset("Demand", {
101 * domain: "CUSTOM",
102 * datasetType: "TARGET_TIME_SERIES",
103 * dataFrequency: "D",
104 * schema: {
105 * attributes: [
106 * { attributeName: "item_id", attributeType: "string" },
107 * { attributeName: "timestamp", attributeType: "timestamp" },
108 * { attributeName: "target_value", attributeType: "float" },
109 * ],
110 * },
111 * });
112 * ```
113 *
114 * @resource
115 */
116 export const Dataset = Resource<Dataset>("AWS.Forecast.Dataset");
117
118 export const DatasetProvider = () =>
119 Provider.effect(
120 Dataset,
121 Effect.gen(function* () {
122 const createName = Effect.fn(function* (id: string, props: DatasetProps) {
123 return (
124 props.datasetName ?? toForecastName(yield* createPhysicalName({ id, maxLength: 63 }))
125 );
126 });
127
128 const describe = Effect.fn(function* (datasetArn: string) {
129 return yield* forecast
130 .describeDataset({ DatasetArn: datasetArn })
131 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
132 });
133
134 const toAttrs = (dataset: forecast.DescribeDatasetResponse) => ({
135 datasetArn: dataset.DatasetArn!,
136 datasetName: dataset.DatasetName!,
137 domain: dataset.Domain!,
138 datasetType: dataset.DatasetType!,
139 status: dataset.Status!,
140 });
141
142 return {
143 stables: ["datasetArn", "datasetName"],
144
145 diff: Effect.fn(function* ({ id, olds, news }) {
146 if (!isResolved(news)) return undefined;
147 const oldName = yield* createName(id, olds);
148 const newName = yield* createName(id, news);
149 if (
150 oldName !== newName ||
151 (olds.domain ?? undefined) !== (news.domain ?? undefined) ||
152 (olds.datasetType ?? undefined) !== (news.datasetType ?? undefined) ||
153 (olds.dataFrequency ?? undefined) !== (news.dataFrequency ?? undefined) ||
154 JSON.stringify(olds.schema ?? null) !== JSON.stringify(news.schema ?? null)
155 ) {
156 return { action: "replace" } as const;
157 }
158 }),
159
160 read: Effect.fn(function* ({ id, output }) {
161 if (!output?.datasetArn) return undefined;
162 const dataset = yield* describe(output.datasetArn);
163 if (dataset === undefined) return undefined;
164 const attrs = toAttrs(dataset);
165 const tags = yield* readForecastTags(dataset.DatasetArn!);
166 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
167 }),
168
169 reconcile: Effect.fn(function* ({ id, news, output, session }) {
170 const name = yield* createName(id, news);
171 const internalTags = yield* createInternalTags(id);
172 const desiredTags = { ...internalTags, ...news.tags };
173
174 let dataset =
175 output?.datasetArn !== undefined ? yield* describe(output.datasetArn) : undefined;
176
177 if (dataset === undefined) {
178 const created = yield* forecast.createDataset({
179 DatasetName: name,
180 Domain: news.domain,
181 DatasetType: news.datasetType,
182 DataFrequency: news.dataFrequency,
183 Schema: {
184 Attributes: news.schema.attributes.map((a) => ({
185 AttributeName: a.attributeName,
186 AttributeType: a.attributeType,
187 })),
188 },
189 EncryptionConfig: news.encryptionConfig
190 ? {
191 RoleArn: news.encryptionConfig.roleArn,
192 KMSKeyArn: news.encryptionConfig.kmsKeyArn,
193 }
194 : undefined,
195 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
196 Key,
197 Value,
198 })),
199 });
200 dataset = yield* describe(created.DatasetArn!);
201 } else {
202 yield* syncForecastTags(dataset.DatasetArn!, desiredTags);
203 }
204
205 yield* session.note(dataset!.DatasetArn!);
206 return toAttrs(dataset!);
207 }),
208
209 delete: Effect.fn(function* ({ output }) {
210 yield* forecast.deleteDataset({ DatasetArn: output.datasetArn }).pipe(
211 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
212 Effect.retry({
213 while: (e) => e._tag === "ResourceInUseException",
214 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]),
215 }),
216 );
217 }),
218
219 list: () =>
220 forecast.listDatasets.pages({}).pipe(
221 Stream.runCollect,
222 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Datasets ?? [])),
223 Effect.flatMap(
224 Effect.forEach(
225 (summary) =>
226 describe(summary.DatasetArn!).pipe(
227 Effect.map((d) => (d ? toAttrs(d) : undefined)),
228 ),
229 { concurrency: 4 },
230 ),
231 ),
232 Effect.map((items) => items.filter((item) => item !== undefined)),
233 ),
234 };
235 }),
236 );