@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 340 lines 12 KB
Raw
1 import * as sitewise from "@distilled.cloud/aws/iotsitewise";
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, type Tags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as EffectStream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13 import { fetchSiteWiseTags, syncSiteWiseTags } from "./internal.ts";
14
15 export class AssetInvalidProps extends Data.TaggedError("AssetInvalidProps")<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export class AssetUnexpectedResponse extends Data.TaggedError("AssetUnexpectedResponse")<{
21 readonly message: string;
22 readonly cause?: unknown;
23 }> {}
24
25 export type AssetState = sitewise.AssetState;
26
27 export interface AssetProps {
28 /**
29 * A unique name for the asset.
30 * @default ${app}-${stage}-${id}
31 */
32 assetName?: string;
33 /**
34 * The ID of the asset model from which to create the asset.
35 * Changing the model replaces the asset.
36 */
37 assetModelId: string;
38 /**
39 * A description for the asset.
40 */
41 assetDescription?: string;
42 /**
43 * Tags to associate with the asset.
44 */
45 tags?: Record<string, string>;
46 }
47
48 export interface Asset extends Resource<
49 "AWS.IoTSiteWise.Asset",
50 AssetProps,
51 {
52 /**
53 * Service-assigned UUID of the asset.
54 */
55 assetId: string;
56 /**
57 * ARN of the asset.
58 */
59 assetArn: string;
60 /**
61 * The asset's name.
62 */
63 assetName: string;
64 /**
65 * The ID of the asset model the asset was created from.
66 */
67 assetModelId: string;
68 /**
69 * Current lifecycle state of the asset.
70 */
71 state: AssetState;
72 /**
73 * Current tags reported for the asset.
74 */
75 tags: Record<string, string>;
76 },
77 never,
78 Providers
79 > {}
80
81 /**
82 * An AWS IoT SiteWise asset — an instance of an asset model representing
83 * a physical piece of industrial equipment or a logical grouping.
84 *
85 * Asset creation and updates are asynchronous (`CREATING`/`UPDATING` →
86 * `ACTIVE`); the provider waits for the asset to converge to `ACTIVE`
87 * before returning.
88 *
89 * ### Creating Assets
90 * **Example:** Asset from an Asset Model
91 * ```typescript
92 * import * as AWS from "@alchemy.run/aws";
93 *
94 * const model = yield* AWS.IoTSiteWise.AssetModel("PumpModel", {
95 * assetModelProperties: [
96 * { name: "Temperature", dataType: "DOUBLE", type: { measurement: {} } },
97 * ],
98 * });
99 *
100 * const asset = yield* AWS.IoTSiteWise.Asset("Pump1", {
101 * assetModelId: model.assetModelId,
102 * assetDescription: "Pump #1 on the west line",
103 * });
104 * ```
105 *
106 * @resource
107 */
108 export const Asset = Resource<Asset>("AWS.IoTSiteWise.Asset");
109
110 const createAssetName = (id: string, props: { assetName?: string | undefined }) =>
111 props.assetName ? Effect.succeed(props.assetName) : createPhysicalName({ id, maxLength: 256 });
112
113 interface AssetState_ {
114 attrs: Asset["Attributes"];
115 described: sitewise.DescribeAssetResponse;
116 }
117
118 const readAssetById = Effect.fn(function* (assetId: string) {
119 const described = yield* sitewise
120 .describeAsset({ assetId, excludeProperties: true })
121 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
122 if (!described || described.assetStatus.state === "DELETING") {
123 return undefined;
124 }
125 const state: AssetState_ = {
126 described,
127 attrs: {
128 assetId: described.assetId,
129 assetArn: described.assetArn,
130 assetName: described.assetName,
131 assetModelId: described.assetModelId,
132 state: described.assetStatus.state,
133 tags: yield* fetchSiteWiseTags(described.assetArn),
134 },
135 };
136 return state;
137 });
138
139 const findAssetByName = Effect.fn(function* (name: string, assetModelId: string) {
140 const summaries = yield* sitewise.listAssets.pages({ assetModelId }).pipe(
141 EffectStream.runCollect,
142 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.assetSummaries)),
143 // The model itself may not exist yet on a greenfield deploy.
144 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([])),
145 );
146 const match = summaries.find(
147 (summary) => summary.name === name && summary.status.state !== "DELETING",
148 );
149 if (!match) return undefined;
150 return yield* readAssetById(match.id);
151 });
152
153 /**
154 * An asset still transitioning toward the awaited state — retried by
155 * {@link waitForAssetState}'s bounded schedule.
156 */
157 class AssetNotReady extends Data.TaggedError("AssetNotReady")<{
158 readonly assetId: string;
159 readonly state: string | undefined;
160 }> {}
161
162 /**
163 * An asset whose asynchronous provisioning converged to the terminal
164 * `FAILED` state.
165 */
166 export class AssetProvisioningFailed extends Data.TaggedError("AssetProvisioningFailed")<{
167 readonly assetId: string;
168 readonly message: string | undefined;
169 }> {}
170
171 // Explicitly-typed retry wrapper — see AssetModel.ts for why inline
172 // Effect.retry is forbidden in provider lifecycle code.
173 const retryWhileNotReady = <A, E extends { readonly _tag: string }, R>(
174 self: Effect.Effect<A, E, R>,
175 ): Effect.Effect<A, E, R> =>
176 Effect.retry(self, {
177 while: (e) => e._tag === "AssetNotReady",
178 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(30)]),
179 });
180
181 const retryThroughConflictingOperation = <A, E extends { readonly _tag: string }, R>(
182 self: Effect.Effect<A, E, R>,
183 ): Effect.Effect<A, E, R> =>
184 Effect.retry(self, {
185 while: (e) => e._tag === "ConflictingOperationException",
186 schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(10)]),
187 });
188
189 const waitForAssetState = (assetId: string, target: "ACTIVE" | "DELETED") =>
190 retryWhileNotReady(
191 Effect.gen(function* () {
192 const described = yield* sitewise
193 .describeAsset({ assetId, excludeProperties: true })
194 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
195 if (target === "DELETED") {
196 if (described === undefined) return;
197 return yield* new AssetNotReady({ assetId, state: described.assetStatus.state });
198 }
199 if (described?.assetStatus.state === "ACTIVE") return;
200 if (described?.assetStatus.state === "FAILED") {
201 return yield* new AssetProvisioningFailed({
202 assetId,
203 message: described.assetStatus.error?.message,
204 });
205 }
206 return yield* new AssetNotReady({ assetId, state: described?.assetStatus.state });
207 }),
208 );
209
210 export const AssetProvider = () =>
211 Provider.effect(
212 Asset,
213 Effect.gen(function* () {
214 return {
215 stables: ["assetId", "assetArn"],
216 list: () =>
217 Effect.gen(function* () {
218 // ListAssets requires an assetModelId filter — enumerate models
219 // first, then each model's assets.
220 const models = yield* sitewise.listAssetModels.pages({}).pipe(
221 EffectStream.runCollect,
222 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.assetModelSummaries)),
223 );
224 const summaries = yield* Effect.forEach(
225 models.map((model) => model.id),
226 (assetModelId) =>
227 sitewise.listAssets.pages({ assetModelId }).pipe(
228 EffectStream.runCollect,
229 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.assetSummaries)),
230 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([])),
231 ),
232 { concurrency: 3 },
233 );
234 const hydrated = yield* Effect.forEach(
235 summaries.flat().map((summary) => summary.id),
236 (assetId) => readAssetById(assetId),
237 { concurrency: 5 },
238 );
239 return hydrated.flatMap((state) => (state === undefined ? [] : [state.attrs]));
240 }),
241 read: Effect.fn(function* ({ id, olds, output }) {
242 const state = output?.assetId
243 ? yield* readAssetById(output.assetId)
244 : olds?.assetModelId
245 ? yield* findAssetByName(yield* createAssetName(id, olds), olds.assetModelId)
246 : undefined;
247 if (!state) return undefined;
248 return (yield* hasAlchemyTags(id, state.attrs.tags as Tags))
249 ? state.attrs
250 : Unowned(state.attrs);
251 }),
252 diff: Effect.fn(function* ({ news, olds }) {
253 if (!isResolved(news)) return;
254 if (olds === undefined) return;
255 // An asset cannot move to a different model.
256 if (olds.assetModelId !== news.assetModelId) {
257 return { action: "replace" } as const;
258 }
259 }),
260 reconcile: Effect.fn(function* ({ id, news, output, session }) {
261 if (!news) {
262 return yield* new AssetInvalidProps({ message: "IoT SiteWise Asset requires props" });
263 }
264 const name = yield* createAssetName(id, news);
265 const internalTags = yield* createInternalTags(id);
266 const desiredTags = { ...internalTags, ...news.tags };
267
268 // Observe — prefer the cached id; fall back to a name lookup so
269 // a create whose state failed to persist is adopted.
270 let state = output?.assetId
271 ? yield* readAssetById(output.assetId)
272 : yield* findAssetByName(name, news.assetModelId);
273
274 // Ensure — create if missing, then wait for ACTIVE. A model that
275 // just reached ACTIVE can still briefly reject creates with
276 // ConflictingOperationException.
277 if (state === undefined) {
278 const created = yield* retryThroughConflictingOperation(
279 sitewise.createAsset({
280 assetName: name,
281 assetModelId: news.assetModelId,
282 assetDescription: news.assetDescription,
283 tags: desiredTags,
284 }),
285 );
286 yield* session.note(`Creating asset ${name} (${created.assetId})...`);
287 yield* waitForAssetState(created.assetId, "ACTIVE");
288 state = yield* readAssetById(created.assetId);
289 if (state === undefined) {
290 return yield* new AssetUnexpectedResponse({
291 message: `failed to read created asset ${name}`,
292 });
293 }
294 }
295
296 // Sync — name/description drift via UpdateAsset.
297 const described = state.described;
298 if (
299 name !== described.assetName ||
300 (news.assetDescription ?? "") !== (described.assetDescription ?? "")
301 ) {
302 yield* retryThroughConflictingOperation(
303 sitewise.updateAsset({
304 assetId: state.attrs.assetId,
305 assetName: name,
306 assetDescription: news.assetDescription,
307 }),
308 );
309 yield* waitForAssetState(state.attrs.assetId, "ACTIVE");
310 yield* session.note(`Updated asset ${name}`);
311 }
312
313 // Sync tags — diff against observed cloud tags.
314 yield* syncSiteWiseTags(state.attrs.assetArn, state.attrs.tags, desiredTags);
315
316 yield* session.note(state.attrs.assetArn);
317
318 const final = yield* readAssetById(state.attrs.assetId);
319 if (!final) {
320 return yield* new AssetUnexpectedResponse({
321 message: `failed to read reconciled asset ${name}`,
322 });
323 }
324 return final.attrs;
325 }),
326 delete: Effect.fn(function* ({ output }) {
327 // Deleting an asset that is still associated to a parent (or mid
328 // transition) raises ConflictingOperationException — retry
329 // through the window, then wait until fully gone so the asset
330 // model can be deleted after it.
331 yield* retryThroughConflictingOperation(
332 sitewise
333 .deleteAsset({ assetId: output.assetId })
334 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)),
335 );
336 yield* waitForAssetState(output.assetId, "DELETED");
337 }),
338 };
339 }),
340 );