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

main
ts 200 lines 7.11 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 DatasetGroupProps {
15 /**
16 * Name of the dataset group. If omitted, a unique name is generated from the
17 * app, stage, and logical ID. Changing the name replaces the group.
18 */
19 datasetGroupName?: string;
20 /**
21 * The forecasting domain: `RETAIL`, `CUSTOM`, `INVENTORY_PLANNING`,
22 * `EC2_CAPACITY`, `WORK_FORCE`, `WEB_TRAFFIC`, or `METRICS`. Immutable —
23 * changing it replaces the group.
24 */
25 domain: string;
26 /**
27 * ARNs of the datasets to attach to the group. This is an in-place update —
28 * changing the set re-associates the datasets without replacing the group.
29 */
30 datasetArns?: string[];
31 /**
32 * User-defined tags for the dataset group.
33 */
34 tags?: Record<string, string>;
35 }
36
37 export interface DatasetGroup extends Resource<
38 "AWS.Forecast.DatasetGroup",
39 DatasetGroupProps,
40 {
41 /** The ARN of the dataset group. */
42 datasetGroupArn: string;
43 /** The name of the dataset group. */
44 datasetGroupName: string;
45 /** The forecasting domain of the group, e.g. `RETAIL` or `CUSTOM`. */
46 domain: string;
47 /** The dataset group status, e.g. `ACTIVE`. */
48 status: string;
49 },
50 never,
51 Providers
52 > {}
53
54 /**
55 * An Amazon Forecast dataset group — a domain-scoped container that groups the
56 * datasets used to train predictors. Creating the group is cheap; the
57 * expensive training work lives in predictors and forecasts provisioned
58 * separately.
59 *
60 * ### Creating a Dataset Group
61 * **Example:** Custom Dataset Group
62 * ```typescript
63 * const group = yield* Forecast.DatasetGroup("Sales", {
64 * domain: "CUSTOM",
65 * });
66 * ```
67 *
68 * **Example:** Dataset Group with Attached Datasets
69 * ```typescript
70 * const group = yield* Forecast.DatasetGroup("Sales", {
71 * domain: "RETAIL",
72 * datasetArns: [dataset.datasetArn],
73 * tags: { team: "planning" },
74 * });
75 * ```
76 *
77 * @resource
78 */
79 export const DatasetGroup = Resource<DatasetGroup>("AWS.Forecast.DatasetGroup");
80
81 const sameArns = (a: string[], b: string[]) => {
82 const sa = [...a].sort();
83 const sb = [...b].sort();
84 return sa.length === sb.length && sa.every((v, i) => v === sb[i]);
85 };
86
87 export const DatasetGroupProvider = () =>
88 Provider.effect(
89 DatasetGroup,
90 Effect.gen(function* () {
91 const createName = Effect.fn(function* (id: string, props: DatasetGroupProps) {
92 return (
93 props.datasetGroupName ?? toForecastName(yield* createPhysicalName({ id, maxLength: 63 }))
94 );
95 });
96
97 const describe = Effect.fn(function* (datasetGroupArn: string) {
98 return yield* forecast
99 .describeDatasetGroup({ DatasetGroupArn: datasetGroupArn })
100 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
101 });
102
103 const toAttrs = (group: forecast.DescribeDatasetGroupResponse) => ({
104 datasetGroupArn: group.DatasetGroupArn!,
105 datasetGroupName: group.DatasetGroupName!,
106 domain: group.Domain!,
107 status: group.Status!,
108 });
109
110 return {
111 stables: ["datasetGroupArn", "datasetGroupName"],
112
113 diff: Effect.fn(function* ({ id, olds, news }) {
114 if (!isResolved(news)) return undefined;
115 const oldName = yield* createName(id, olds);
116 const newName = yield* createName(id, news);
117 if (oldName !== newName || (olds.domain ?? undefined) !== (news.domain ?? undefined)) {
118 return { action: "replace" } as const;
119 }
120 }),
121
122 read: Effect.fn(function* ({ id, output }) {
123 if (!output?.datasetGroupArn) return undefined;
124 const group = yield* describe(output.datasetGroupArn);
125 if (group === undefined) return undefined;
126 const attrs = toAttrs(group);
127 const tags = yield* readForecastTags(group.DatasetGroupArn!);
128 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
129 }),
130
131 reconcile: Effect.fn(function* ({ id, news, output, session }) {
132 const name = yield* createName(id, news);
133 const internalTags = yield* createInternalTags(id);
134 const desiredTags = { ...internalTags, ...news.tags };
135 const desiredArns = news.datasetArns ?? [];
136
137 // 1. Observe — cloud state is authoritative; output is an ARN cache.
138 let group =
139 output?.datasetGroupArn !== undefined
140 ? yield* describe(output.datasetGroupArn)
141 : undefined;
142
143 // 2. Ensure — create if missing.
144 if (group === undefined) {
145 const created = yield* forecast.createDatasetGroup({
146 DatasetGroupName: name,
147 Domain: news.domain,
148 DatasetArns: desiredArns,
149 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
150 Key,
151 Value,
152 })),
153 });
154 group = yield* describe(created.DatasetGroupArn!);
155 } else {
156 // 3. Sync attached datasets — in-place update on drift.
157 if (!sameArns(group.DatasetArns ?? [], desiredArns)) {
158 yield* forecast.updateDatasetGroup({
159 DatasetGroupArn: group.DatasetGroupArn!,
160 DatasetArns: desiredArns,
161 });
162 }
163 // 3b. Sync tags — diff against OBSERVED cloud tags.
164 yield* syncForecastTags(group.DatasetGroupArn!, desiredTags);
165 }
166
167 const arn = group!.DatasetGroupArn!;
168 yield* session.note(arn);
169 const fresh = (yield* describe(arn)) ?? group!;
170 return toAttrs(fresh);
171 }),
172
173 delete: Effect.fn(function* ({ output }) {
174 yield* forecast.deleteDatasetGroup({ DatasetGroupArn: output.datasetGroupArn }).pipe(
175 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
176 Effect.retry({
177 while: (e) => e._tag === "ResourceInUseException",
178 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]),
179 }),
180 );
181 }),
182
183 list: () =>
184 forecast.listDatasetGroups.pages({}).pipe(
185 Stream.runCollect,
186 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.DatasetGroups ?? [])),
187 Effect.flatMap(
188 Effect.forEach(
189 (summary) =>
190 describe(summary.DatasetGroupArn!).pipe(
191 Effect.map((g) => (g ? toAttrs(g) : undefined)),
192 ),
193 { concurrency: 4 },
194 ),
195 ),
196 Effect.map((items) => items.filter((item) => item !== undefined)),
197 ),
198 };
199 }),
200 );