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
| 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, matchesDesired, syncSiteWiseTags } from "./internal.ts"; |
| 14 | |
| 15 | export class AssetModelInvalidProps extends Data.TaggedError("AssetModelInvalidProps")<{ |
| 16 | readonly message: string; |
| 17 | readonly cause?: unknown; |
| 18 | }> {} |
| 19 | |
| 20 | export class AssetModelUnexpectedResponse extends Data.TaggedError("AssetModelUnexpectedResponse")<{ |
| 21 | readonly message: string; |
| 22 | readonly cause?: unknown; |
| 23 | }> {} |
| 24 | |
| 25 | export type AssetModelType = sitewise.AssetModelType; |
| 26 | export type AssetModelState = sitewise.AssetModelState; |
| 27 | export type AssetModelPropertyDefinition = sitewise.AssetModelPropertyDefinition; |
| 28 | export type AssetModelHierarchyDefinition = sitewise.AssetModelHierarchyDefinition; |
| 29 | export type AssetModelCompositeModelDefinition = sitewise.AssetModelCompositeModelDefinition; |
| 30 | |
| 31 | export interface AssetModelProps { |
| 32 | /** |
| 33 | * A unique name for the asset model. |
| 34 | * @default ${app}-${stage}-${id} |
| 35 | */ |
| 36 | assetModelName?: string; |
| 37 | /** |
| 38 | * The type of asset model: `ASSET_MODEL` (default, creates assets), |
| 39 | * `COMPONENT_MODEL` (reusable component), or `INTERFACE`. |
| 40 | * Changing the type replaces the asset model. |
| 41 | * @default "ASSET_MODEL" |
| 42 | */ |
| 43 | assetModelType?: AssetModelType; |
| 44 | /** |
| 45 | * A description for the asset model. |
| 46 | */ |
| 47 | assetModelDescription?: string; |
| 48 | /** |
| 49 | * The property definitions of the asset model (attributes, measurements, |
| 50 | * transforms, and metrics). Assets created from the model inherit these. |
| 51 | */ |
| 52 | assetModelProperties?: AssetModelPropertyDefinition[]; |
| 53 | /** |
| 54 | * The hierarchy definitions of the asset model. Each hierarchy specifies |
| 55 | * an asset model whose assets can be children of assets created from |
| 56 | * this model. |
| 57 | */ |
| 58 | assetModelHierarchies?: AssetModelHierarchyDefinition[]; |
| 59 | /** |
| 60 | * The composite models that are part of this asset model (e.g. alarms |
| 61 | * or component-model references). |
| 62 | */ |
| 63 | assetModelCompositeModels?: AssetModelCompositeModelDefinition[]; |
| 64 | /** |
| 65 | * Tags to associate with the asset model. |
| 66 | */ |
| 67 | tags?: Record<string, string>; |
| 68 | } |
| 69 | |
| 70 | export interface AssetModel extends Resource< |
| 71 | "AWS.IoTSiteWise.AssetModel", |
| 72 | AssetModelProps, |
| 73 | { |
| 74 | /** |
| 75 | * Service-assigned UUID of the asset model. |
| 76 | */ |
| 77 | assetModelId: string; |
| 78 | /** |
| 79 | * ARN of the asset model. |
| 80 | */ |
| 81 | assetModelArn: string; |
| 82 | /** |
| 83 | * The asset model's name. |
| 84 | */ |
| 85 | assetModelName: string; |
| 86 | /** |
| 87 | * The asset model's type. |
| 88 | */ |
| 89 | assetModelType: AssetModelType | undefined; |
| 90 | /** |
| 91 | * Current lifecycle state of the asset model. |
| 92 | */ |
| 93 | state: AssetModelState; |
| 94 | /** |
| 95 | * Current tags reported for the asset model. |
| 96 | */ |
| 97 | tags: Record<string, string>; |
| 98 | }, |
| 99 | never, |
| 100 | Providers |
| 101 | > {} |
| 102 | |
| 103 | /** |
| 104 | * An AWS IoT SiteWise asset model — a standardized definition of |
| 105 | * properties (attributes, measurements, transforms, metrics) and |
| 106 | * hierarchies from which industrial assets are created. |
| 107 | * |
| 108 | * Asset model creation and updates are asynchronous |
| 109 | * (`CREATING`/`UPDATING` → `ACTIVE`); the provider waits for the model to |
| 110 | * converge to `ACTIVE` before returning. |
| 111 | * |
| 112 | * ### Creating Asset Models |
| 113 | * **Example:** Asset Model with a Measurement and an Attribute |
| 114 | * ```typescript |
| 115 | * import * as AWS from "@alchemy.run/aws"; |
| 116 | * |
| 117 | * const model = yield* AWS.IoTSiteWise.AssetModel("PumpModel", { |
| 118 | * assetModelDescription: "A pump on the factory floor", |
| 119 | * assetModelProperties: [ |
| 120 | * { |
| 121 | * name: "SerialNumber", |
| 122 | * dataType: "STRING", |
| 123 | * type: { attribute: { defaultValue: "unknown" } }, |
| 124 | * }, |
| 125 | * { |
| 126 | * name: "Temperature", |
| 127 | * dataType: "DOUBLE", |
| 128 | * unit: "Celsius", |
| 129 | * type: { measurement: {} }, |
| 130 | * }, |
| 131 | * ], |
| 132 | * }); |
| 133 | * ``` |
| 134 | * |
| 135 | * ### Hierarchies |
| 136 | * **Example:** Parent Model with a Child Hierarchy |
| 137 | * ```typescript |
| 138 | * const pump = yield* AWS.IoTSiteWise.AssetModel("PumpModel", { |
| 139 | * assetModelProperties: [ |
| 140 | * { name: "Temperature", dataType: "DOUBLE", type: { measurement: {} } }, |
| 141 | * ], |
| 142 | * }); |
| 143 | * |
| 144 | * const site = yield* AWS.IoTSiteWise.AssetModel("SiteModel", { |
| 145 | * assetModelHierarchies: [ |
| 146 | * { name: "Pumps", childAssetModelId: pump.assetModelId }, |
| 147 | * ], |
| 148 | * }); |
| 149 | * ``` |
| 150 | * |
| 151 | * @resource |
| 152 | */ |
| 153 | export const AssetModel = Resource<AssetModel>("AWS.IoTSiteWise.AssetModel"); |
| 154 | |
| 155 | const createAssetModelName = (id: string, props: { assetModelName?: string | undefined }) => |
| 156 | props.assetModelName |
| 157 | ? Effect.succeed(props.assetModelName) |
| 158 | : createPhysicalName({ id, maxLength: 256 }); |
| 159 | |
| 160 | interface AssetModelState_ { |
| 161 | attrs: AssetModel["Attributes"]; |
| 162 | described: sitewise.DescribeAssetModelResponse; |
| 163 | } |
| 164 | |
| 165 | const readAssetModelById = Effect.fn(function* (assetModelId: string) { |
| 166 | const described = yield* sitewise |
| 167 | .describeAssetModel({ assetModelId, excludeProperties: false }) |
| 168 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 169 | if (!described || described.assetModelStatus.state === "DELETING") { |
| 170 | return undefined; |
| 171 | } |
| 172 | const state: AssetModelState_ = { |
| 173 | described, |
| 174 | attrs: { |
| 175 | assetModelId: described.assetModelId, |
| 176 | assetModelArn: described.assetModelArn, |
| 177 | assetModelName: described.assetModelName, |
| 178 | assetModelType: described.assetModelType, |
| 179 | state: described.assetModelStatus.state, |
| 180 | tags: yield* fetchSiteWiseTags(described.assetModelArn), |
| 181 | }, |
| 182 | }; |
| 183 | return state; |
| 184 | }); |
| 185 | |
| 186 | const findAssetModelByName = Effect.fn(function* (name: string) { |
| 187 | const summaries = yield* sitewise.listAssetModels.pages({}).pipe( |
| 188 | EffectStream.runCollect, |
| 189 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.assetModelSummaries)), |
| 190 | ); |
| 191 | const match = summaries.find( |
| 192 | (summary) => summary.name === name && summary.status.state !== "DELETING", |
| 193 | ); |
| 194 | if (!match) return undefined; |
| 195 | return yield* readAssetModelById(match.id); |
| 196 | }); |
| 197 | |
| 198 | /** |
| 199 | * An asset model still transitioning toward the awaited state — retried |
| 200 | * by {@link waitForAssetModelState}'s bounded schedule. |
| 201 | */ |
| 202 | class AssetModelNotReady extends Data.TaggedError("AssetModelNotReady")<{ |
| 203 | readonly assetModelId: string; |
| 204 | readonly state: string | undefined; |
| 205 | }> {} |
| 206 | |
| 207 | /** |
| 208 | * An asset model whose asynchronous provisioning converged to the |
| 209 | * terminal `FAILED` state. |
| 210 | */ |
| 211 | export class AssetModelProvisioningFailed extends Data.TaggedError("AssetModelProvisioningFailed")<{ |
| 212 | readonly assetModelId: string; |
| 213 | readonly message: string | undefined; |
| 214 | }> {} |
| 215 | |
| 216 | // Explicitly-typed retry wrapper — an inline `Effect.retry` in provider |
| 217 | // lifecycle code leaks `Retry.Return`'s conditional type into declaration |
| 218 | // emit and widens the provider layer to `unknown` for every consumer of |
| 219 | // `AWS.providers()`. |
| 220 | const retryWhileNotReady = <A, E extends { readonly _tag: string }, R>( |
| 221 | self: Effect.Effect<A, E, R>, |
| 222 | ): Effect.Effect<A, E, R> => |
| 223 | Effect.retry(self, { |
| 224 | while: (e) => e._tag === "AssetModelNotReady", |
| 225 | // Asset model provisioning usually converges in seconds; poll every |
| 226 | // 3s up to ~90s total. |
| 227 | schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(30)]), |
| 228 | }); |
| 229 | |
| 230 | // A delete/update racing an in-flight CREATING/UPDATING transition |
| 231 | // surfaces as ConflictingOperationException — bounded retry through it. |
| 232 | const retryThroughConflictingOperation = <A, E extends { readonly _tag: string }, R>( |
| 233 | self: Effect.Effect<A, E, R>, |
| 234 | ): Effect.Effect<A, E, R> => |
| 235 | Effect.retry(self, { |
| 236 | while: (e) => e._tag === "ConflictingOperationException", |
| 237 | schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(10)]), |
| 238 | }); |
| 239 | |
| 240 | const waitForAssetModelState = (assetModelId: string, target: "ACTIVE" | "DELETED") => |
| 241 | retryWhileNotReady( |
| 242 | Effect.gen(function* () { |
| 243 | const described = yield* sitewise |
| 244 | .describeAssetModel({ assetModelId, excludeProperties: true }) |
| 245 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 246 | if (target === "DELETED") { |
| 247 | if (described === undefined) return; |
| 248 | return yield* new AssetModelNotReady({ |
| 249 | assetModelId, |
| 250 | state: described.assetModelStatus.state, |
| 251 | }); |
| 252 | } |
| 253 | if (described?.assetModelStatus.state === "ACTIVE") return; |
| 254 | if (described?.assetModelStatus.state === "FAILED") { |
| 255 | return yield* new AssetModelProvisioningFailed({ |
| 256 | assetModelId, |
| 257 | message: described.assetModelStatus.error?.message, |
| 258 | }); |
| 259 | } |
| 260 | return yield* new AssetModelNotReady({ |
| 261 | assetModelId, |
| 262 | state: described?.assetModelStatus.state, |
| 263 | }); |
| 264 | }), |
| 265 | ); |
| 266 | |
| 267 | /** |
| 268 | * Map desired property/hierarchy definitions onto the observed model so |
| 269 | * an update preserves the service-assigned ids of entries that already |
| 270 | * exist (matched by name). Entries without a match are sent id-less and |
| 271 | * get new ids. |
| 272 | */ |
| 273 | const withObservedIds = <T extends { id?: string; name: string }>( |
| 274 | desired: readonly T[], |
| 275 | observed: readonly { id?: string; name: string }[], |
| 276 | ): T[] => |
| 277 | desired.map((item) => { |
| 278 | if (item.id !== undefined) return item; |
| 279 | const match = observed.find((o) => o.name === item.name); |
| 280 | return match?.id !== undefined ? { ...item, id: match.id } : item; |
| 281 | }); |
| 282 | |
| 283 | export const AssetModelProvider = () => |
| 284 | Provider.effect( |
| 285 | AssetModel, |
| 286 | Effect.gen(function* () { |
| 287 | return { |
| 288 | stables: ["assetModelId", "assetModelArn"], |
| 289 | list: () => |
| 290 | Effect.gen(function* () { |
| 291 | const summaries = yield* sitewise.listAssetModels.pages({}).pipe( |
| 292 | EffectStream.runCollect, |
| 293 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.assetModelSummaries)), |
| 294 | ); |
| 295 | const hydrated = yield* Effect.forEach( |
| 296 | summaries.map((s) => s.id), |
| 297 | (assetModelId) => readAssetModelById(assetModelId), |
| 298 | { concurrency: 5 }, |
| 299 | ); |
| 300 | return hydrated.flatMap((state) => (state === undefined ? [] : [state.attrs])); |
| 301 | }), |
| 302 | read: Effect.fn(function* ({ id, olds, output }) { |
| 303 | const state = output?.assetModelId |
| 304 | ? yield* readAssetModelById(output.assetModelId) |
| 305 | : yield* findAssetModelByName(yield* createAssetModelName(id, olds ?? {})); |
| 306 | if (!state) return undefined; |
| 307 | return (yield* hasAlchemyTags(id, state.attrs.tags as Tags)) |
| 308 | ? state.attrs |
| 309 | : Unowned(state.attrs); |
| 310 | }), |
| 311 | diff: Effect.fn(function* ({ news, olds }) { |
| 312 | if (!isResolved(news)) return; |
| 313 | if (olds === undefined) return; |
| 314 | // The model type is fixed at creation. |
| 315 | if ((olds.assetModelType ?? "ASSET_MODEL") !== (news.assetModelType ?? "ASSET_MODEL")) { |
| 316 | return { action: "replace" } as const; |
| 317 | } |
| 318 | }), |
| 319 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 320 | if (!news) { |
| 321 | return yield* new AssetModelInvalidProps({ |
| 322 | message: "IoT SiteWise AssetModel requires props", |
| 323 | }); |
| 324 | } |
| 325 | const name = yield* createAssetModelName(id, news); |
| 326 | const internalTags = yield* createInternalTags(id); |
| 327 | const desiredTags = { ...internalTags, ...news.tags }; |
| 328 | |
| 329 | // Observe — prefer the cached id; fall back to a name lookup so |
| 330 | // a create whose state failed to persist is adopted, not |
| 331 | // duplicated. |
| 332 | let state = output?.assetModelId |
| 333 | ? yield* readAssetModelById(output.assetModelId) |
| 334 | : yield* findAssetModelByName(name); |
| 335 | |
| 336 | // Ensure — create if missing, then wait for ACTIVE. |
| 337 | if (state === undefined) { |
| 338 | const created = yield* sitewise.createAssetModel({ |
| 339 | assetModelName: name, |
| 340 | assetModelType: news.assetModelType, |
| 341 | assetModelDescription: news.assetModelDescription, |
| 342 | assetModelProperties: news.assetModelProperties, |
| 343 | assetModelHierarchies: news.assetModelHierarchies, |
| 344 | assetModelCompositeModels: news.assetModelCompositeModels, |
| 345 | tags: desiredTags, |
| 346 | }); |
| 347 | yield* session.note(`Creating asset model ${name} (${created.assetModelId})...`); |
| 348 | yield* waitForAssetModelState(created.assetModelId, "ACTIVE"); |
| 349 | state = yield* readAssetModelById(created.assetModelId); |
| 350 | if (state === undefined) { |
| 351 | return yield* new AssetModelUnexpectedResponse({ |
| 352 | message: `failed to read created asset model ${name}`, |
| 353 | }); |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | // Sync — diff observed definition against desired; UpdateAssetModel |
| 358 | // replaces the full definition, so send the complete desired set |
| 359 | // with observed ids preserved by name. |
| 360 | const described = state.described; |
| 361 | const desiredProperties = withObservedIds( |
| 362 | news.assetModelProperties ?? [], |
| 363 | described.assetModelProperties, |
| 364 | ); |
| 365 | const desiredHierarchies = withObservedIds( |
| 366 | news.assetModelHierarchies ?? [], |
| 367 | described.assetModelHierarchies, |
| 368 | ); |
| 369 | const observedDefinition = { |
| 370 | name: described.assetModelName, |
| 371 | description: described.assetModelDescription, |
| 372 | properties: described.assetModelProperties, |
| 373 | hierarchies: described.assetModelHierarchies, |
| 374 | }; |
| 375 | const desiredDefinition = { |
| 376 | name, |
| 377 | description: news.assetModelDescription ?? "", |
| 378 | properties: desiredProperties, |
| 379 | hierarchies: desiredHierarchies, |
| 380 | }; |
| 381 | const definitionDrifted = |
| 382 | name !== described.assetModelName || |
| 383 | (news.assetModelDescription ?? "") !== described.assetModelDescription || |
| 384 | desiredProperties.length !== described.assetModelProperties.length || |
| 385 | desiredHierarchies.length !== described.assetModelHierarchies.length || |
| 386 | !matchesDesired(desiredDefinition, observedDefinition); |
| 387 | if (definitionDrifted) { |
| 388 | yield* retryThroughConflictingOperation( |
| 389 | sitewise.updateAssetModel({ |
| 390 | assetModelId: state.attrs.assetModelId, |
| 391 | assetModelName: name, |
| 392 | assetModelDescription: news.assetModelDescription, |
| 393 | assetModelProperties: desiredProperties, |
| 394 | assetModelHierarchies: desiredHierarchies, |
| 395 | }), |
| 396 | ); |
| 397 | yield* waitForAssetModelState(state.attrs.assetModelId, "ACTIVE"); |
| 398 | yield* session.note(`Updated asset model ${name}`); |
| 399 | } |
| 400 | |
| 401 | // Sync tags — diff against observed cloud tags. |
| 402 | yield* syncSiteWiseTags(state.attrs.assetModelArn, state.attrs.tags, desiredTags); |
| 403 | |
| 404 | yield* session.note(state.attrs.assetModelArn); |
| 405 | |
| 406 | const final = yield* readAssetModelById(state.attrs.assetModelId); |
| 407 | if (!final) { |
| 408 | return yield* new AssetModelUnexpectedResponse({ |
| 409 | message: `failed to read reconciled asset model ${name}`, |
| 410 | }); |
| 411 | } |
| 412 | return final.attrs; |
| 413 | }), |
| 414 | delete: Effect.fn(function* ({ output }) { |
| 415 | // Deleting while assets still reference the model (or while a |
| 416 | // prior transition is settling) raises |
| 417 | // ConflictingOperationException — retry through the window. |
| 418 | yield* retryThroughConflictingOperation( |
| 419 | sitewise |
| 420 | .deleteAssetModel({ assetModelId: output.assetModelId }) |
| 421 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)), |
| 422 | ); |
| 423 | yield* waitForAssetModelState(output.assetModelId, "DELETED"); |
| 424 | }), |
| 425 | }; |
| 426 | }), |
| 427 | ); |