The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as greengrassv2 from "@distilled.cloud/aws/greengrassv2"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import { AWSEnvironment } from "../Environment.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | |
| 14 | export interface ComponentVersionProps { |
| 15 | /** |
| 16 | * The inline component recipe, as a JSON or YAML string. The recipe defines |
| 17 | * the component's name (`ComponentName`), version (`ComponentVersion`), |
| 18 | * lifecycle, and platform capability. |
| 19 | * |
| 20 | * Component versions are immutable — changing the recipe replaces the |
| 21 | * component version. |
| 22 | */ |
| 23 | recipe: string; |
| 24 | /** |
| 25 | * Tags to apply to the component version. Merged with internal Alchemy tags. |
| 26 | */ |
| 27 | tags?: Record<string, string>; |
| 28 | } |
| 29 | |
| 30 | export interface ComponentVersion extends Resource< |
| 31 | "AWS.GreengrassV2.ComponentVersion", |
| 32 | ComponentVersionProps, |
| 33 | { |
| 34 | /** The ARN of this component version. */ |
| 35 | arn: string; |
| 36 | /** The name of the component. */ |
| 37 | componentName: string; |
| 38 | /** The semantic version of the component. */ |
| 39 | componentVersion: string; |
| 40 | }, |
| 41 | never, |
| 42 | Providers |
| 43 | > {} |
| 44 | |
| 45 | /** |
| 46 | * An IoT Greengrass V2 component version created from an inline recipe. |
| 47 | * Components are software modules that run on Greengrass core devices. |
| 48 | * |
| 49 | * Component versions are immutable in the cloud: any change to the recipe |
| 50 | * replaces the component version (a new name/version pair is registered and |
| 51 | * the previous one is deleted). Only tags are mutable in place. |
| 52 | * |
| 53 | * ### Creating Component Versions |
| 54 | * **Example:** Component from an inline JSON recipe |
| 55 | * ```typescript |
| 56 | * import * as GreengrassV2 from "@alchemy.run/aws/GreengrassV2"; |
| 57 | * |
| 58 | * const component = yield* GreengrassV2.ComponentVersion("Hello", { |
| 59 | * recipe: JSON.stringify({ |
| 60 | * RecipeFormatVersion: "2020-01-25", |
| 61 | * ComponentName: "com.example.Hello", |
| 62 | * ComponentVersion: "1.0.0", |
| 63 | * ComponentDescription: "Prints a greeting", |
| 64 | * ComponentPublisher: "Example", |
| 65 | * Manifests: [ |
| 66 | * { |
| 67 | * Platform: { os: "linux" }, |
| 68 | * Lifecycle: { run: "echo hello" }, |
| 69 | * }, |
| 70 | * ], |
| 71 | * }), |
| 72 | * }); |
| 73 | * ``` |
| 74 | * |
| 75 | * **Example:** Tagged component version |
| 76 | * ```typescript |
| 77 | * const component = yield* GreengrassV2.ComponentVersion("Hello", { |
| 78 | * recipe, |
| 79 | * tags: { team: "edge" }, |
| 80 | * }); |
| 81 | * ``` |
| 82 | * |
| 83 | * @resource |
| 84 | */ |
| 85 | export const ComponentVersion = Resource<ComponentVersion>("AWS.GreengrassV2.ComponentVersion"); |
| 86 | |
| 87 | /** |
| 88 | * Raised when the inline recipe does not declare a `ComponentName` and |
| 89 | * `ComponentVersion` that Alchemy can derive the component identity from. |
| 90 | */ |
| 91 | export class GreengrassInvalidRecipe extends Data.TaggedError("GreengrassInvalidRecipe")<{ |
| 92 | message: string; |
| 93 | }> {} |
| 94 | |
| 95 | /** |
| 96 | * Raised when the cloud reports the component version entered the `FAILED` |
| 97 | * or `DEPRECATED` state instead of becoming `DEPLOYABLE`. |
| 98 | */ |
| 99 | export class GreengrassComponentFailed extends Data.TaggedError("GreengrassComponentFailed")<{ |
| 100 | message: string; |
| 101 | }> {} |
| 102 | |
| 103 | /** |
| 104 | * Internal signal used to poll a freshly created component version until the |
| 105 | * cloud marks it `DEPLOYABLE`. |
| 106 | */ |
| 107 | export class GreengrassComponentNotReady extends Data.TaggedError("GreengrassComponentNotReady")<{ |
| 108 | message: string; |
| 109 | }> {} |
| 110 | |
| 111 | // Explicitly-typed pipeable retry helper — inlining `Effect.retry` in a |
| 112 | // provider lifecycle op leaks `Retry.Return`'s conditional into declaration |
| 113 | // emit and widens the provider layer to `unknown` R for every consumer of |
| 114 | // `AWS.providers()`. |
| 115 | const retryWhileNotReady = <A, E extends { readonly _tag: string }, R>( |
| 116 | self: Effect.Effect<A, E, R>, |
| 117 | ): Effect.Effect<A, E, R> => |
| 118 | Effect.retry(self, { |
| 119 | while: (e) => e._tag === "GreengrassComponentNotReady", |
| 120 | schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(15)]), |
| 121 | }); |
| 122 | |
| 123 | /** |
| 124 | * Derives `{ componentName, componentVersion }` from an inline recipe string. |
| 125 | * JSON recipes are parsed; YAML recipes are scanned for the top-level |
| 126 | * `ComponentName:` / `ComponentVersion:` keys. |
| 127 | */ |
| 128 | const parseRecipeIdentity = Effect.fn(function* (recipe: string) { |
| 129 | const fromJson = yield* Effect.sync(() => { |
| 130 | try { |
| 131 | const parsed = JSON.parse(recipe) as Record<string, unknown>; |
| 132 | const name = parsed.ComponentName; |
| 133 | const version = parsed.ComponentVersion; |
| 134 | return typeof name === "string" && typeof version === "string" |
| 135 | ? { componentName: name, componentVersion: version } |
| 136 | : undefined; |
| 137 | } catch { |
| 138 | return undefined; |
| 139 | } |
| 140 | }); |
| 141 | if (fromJson !== undefined) return fromJson; |
| 142 | const yamlValue = (key: string) => { |
| 143 | const match = recipe.match(new RegExp(`^${key}:[ \\t]*['"]?([^'"#\\s]+)`, "m")); |
| 144 | return match?.[1]; |
| 145 | }; |
| 146 | const componentName = yamlValue("ComponentName"); |
| 147 | const componentVersion = yamlValue("ComponentVersion"); |
| 148 | if (componentName === undefined || componentVersion === undefined) { |
| 149 | return yield* new GreengrassInvalidRecipe({ |
| 150 | message: |
| 151 | "the inline recipe must declare top-level ComponentName and ComponentVersion (JSON or YAML)", |
| 152 | }); |
| 153 | } |
| 154 | return { componentName, componentVersion }; |
| 155 | }); |
| 156 | |
| 157 | const normalizeTags = ( |
| 158 | tags: { [key: string]: string | undefined } | undefined, |
| 159 | ): Record<string, string> => |
| 160 | Object.fromEntries( |
| 161 | Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined), |
| 162 | ); |
| 163 | |
| 164 | export const ComponentVersionProvider = () => |
| 165 | Provider.effect( |
| 166 | ComponentVersion, |
| 167 | Effect.gen(function* () { |
| 168 | // The component version ARN is deterministic from the recipe identity, |
| 169 | // so read/reconcile never depend on persisted output to find it. |
| 170 | const componentArn = Effect.fn(function* (recipe: string) { |
| 171 | const { accountId, region } = yield* AWSEnvironment.current; |
| 172 | const { componentName, componentVersion } = yield* parseRecipeIdentity(recipe); |
| 173 | return { |
| 174 | componentName, |
| 175 | componentVersion, |
| 176 | arn: `arn:aws:greengrass:${region}:${accountId}:components:${componentName}:versions:${componentVersion}`, |
| 177 | }; |
| 178 | }); |
| 179 | |
| 180 | const observeComponent = (arn: string) => |
| 181 | greengrassv2 |
| 182 | .describeComponent({ arn }) |
| 183 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 184 | |
| 185 | return ComponentVersion.Provider.of({ |
| 186 | stables: ["arn", "componentName", "componentVersion"], |
| 187 | list: () => |
| 188 | Effect.gen(function* () { |
| 189 | const components = yield* greengrassv2.listComponents |
| 190 | .items({ scope: "PRIVATE" }) |
| 191 | .pipe(Stream.runCollect); |
| 192 | const results: { |
| 193 | arn: string; |
| 194 | componentName: string; |
| 195 | componentVersion: string; |
| 196 | }[] = []; |
| 197 | for (const component of components) { |
| 198 | if (component.arn === undefined) continue; |
| 199 | const versions = yield* greengrassv2.listComponentVersions |
| 200 | .items({ arn: component.arn }) |
| 201 | .pipe( |
| 202 | Stream.runCollect, |
| 203 | Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([] as const)), |
| 204 | ); |
| 205 | for (const version of versions) { |
| 206 | if ( |
| 207 | version.arn !== undefined && |
| 208 | version.componentName !== undefined && |
| 209 | version.componentVersion !== undefined |
| 210 | ) { |
| 211 | results.push({ |
| 212 | arn: version.arn, |
| 213 | componentName: version.componentName, |
| 214 | componentVersion: version.componentVersion, |
| 215 | }); |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | return results; |
| 220 | }), |
| 221 | read: Effect.fn(function* ({ id, olds, output }) { |
| 222 | const arn = |
| 223 | output?.arn ?? |
| 224 | (olds !== undefined ? (yield* componentArn(olds.recipe)).arn : undefined); |
| 225 | if (arn === undefined) return undefined; |
| 226 | const found = yield* observeComponent(arn); |
| 227 | if ( |
| 228 | found?.arn === undefined || |
| 229 | found.componentName === undefined || |
| 230 | found.componentVersion === undefined |
| 231 | ) { |
| 232 | return undefined; |
| 233 | } |
| 234 | const attrs = { |
| 235 | arn: found.arn, |
| 236 | componentName: found.componentName, |
| 237 | componentVersion: found.componentVersion, |
| 238 | }; |
| 239 | return (yield* hasAlchemyTags(id, normalizeTags(found.tags))) ? attrs : Unowned(attrs); |
| 240 | }), |
| 241 | diff: Effect.fn(function* ({ news, olds }) { |
| 242 | if (!isResolved(news)) return undefined; |
| 243 | // Component versions are immutable — any recipe change replaces. |
| 244 | if (olds !== undefined && news.recipe !== olds.recipe) { |
| 245 | return { action: "replace" } as const; |
| 246 | } |
| 247 | // fall through: engine default update (tags sync in reconcile) |
| 248 | }), |
| 249 | reconcile: Effect.fn(function* ({ id, news, session }) { |
| 250 | const identity = yield* componentArn(news.recipe); |
| 251 | const internalTags = yield* createInternalTags(id); |
| 252 | const desiredTags = { ...news.tags, ...internalTags }; |
| 253 | |
| 254 | // 1. OBSERVE — cloud state is authoritative. |
| 255 | let live = yield* observeComponent(identity.arn); |
| 256 | |
| 257 | // 2. ENSURE — create when missing. A concurrent create surfaces as |
| 258 | // the typed ConflictException / RequestAlreadyInProgressException |
| 259 | // tags, which we treat as races and re-observe. |
| 260 | if (live === undefined) { |
| 261 | yield* greengrassv2 |
| 262 | .createComponentVersion({ |
| 263 | inlineRecipe: new TextEncoder().encode(news.recipe), |
| 264 | tags: desiredTags, |
| 265 | }) |
| 266 | .pipe( |
| 267 | Effect.catchTag( |
| 268 | ["ConflictException", "RequestAlreadyInProgressException"], |
| 269 | () => Effect.undefined, |
| 270 | ), |
| 271 | ); |
| 272 | // Wait until the cloud marks the version DEPLOYABLE (bounded ~30s; |
| 273 | // inline-recipe components typically settle within seconds). |
| 274 | live = yield* Effect.gen(function* () { |
| 275 | const observed = yield* observeComponent(identity.arn); |
| 276 | const state = observed?.status?.componentState; |
| 277 | if (state === "FAILED" || state === "DEPRECATED") { |
| 278 | return yield* new GreengrassComponentFailed({ |
| 279 | message: `component ${identity.componentName}@${identity.componentVersion} entered state ${state}: ${ |
| 280 | observed?.status?.message ?? "no message" |
| 281 | }`, |
| 282 | }); |
| 283 | } |
| 284 | if (observed === undefined || state !== "DEPLOYABLE") { |
| 285 | return yield* new GreengrassComponentNotReady({ |
| 286 | message: `component ${identity.componentName}@${identity.componentVersion} is ${state ?? "missing"}`, |
| 287 | }); |
| 288 | } |
| 289 | return observed; |
| 290 | }).pipe(retryWhileNotReady); |
| 291 | } |
| 292 | |
| 293 | // 3. SYNC TAGS — diff against OBSERVED cloud tags so adoption |
| 294 | // converges (create-time tags only apply on first create). |
| 295 | const observedTags = normalizeTags(live.tags); |
| 296 | const { upsert, removed } = diffTags(observedTags, desiredTags); |
| 297 | if (upsert.length > 0) { |
| 298 | yield* greengrassv2.tagResource({ |
| 299 | resourceArn: identity.arn, |
| 300 | tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])), |
| 301 | }); |
| 302 | } |
| 303 | if (removed.length > 0) { |
| 304 | yield* greengrassv2.untagResource({ |
| 305 | resourceArn: identity.arn, |
| 306 | tagKeys: removed, |
| 307 | }); |
| 308 | } |
| 309 | |
| 310 | yield* session.note(`${identity.componentName}@${identity.componentVersion}`); |
| 311 | return { |
| 312 | arn: identity.arn, |
| 313 | componentName: identity.componentName, |
| 314 | componentVersion: identity.componentVersion, |
| 315 | }; |
| 316 | }), |
| 317 | delete: Effect.fn(function* ({ output }) { |
| 318 | yield* greengrassv2 |
| 319 | .deleteComponent({ arn: output.arn }) |
| 320 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 321 | }), |
| 322 | }); |
| 323 | }), |
| 324 | ); |