The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as re2 from "@distilled.cloud/aws/resource-explorer-2"; |
| 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, diffTags, hasAlchemyTags } 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 Stream from "effect/Stream"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | |
| 14 | export interface ViewProps { |
| 15 | /** |
| 16 | * Name of the view. Can include letters, digits, and the dash character |
| 17 | * (up to 64 characters), and must be unique within the region. |
| 18 | * @default ${app}-${stage}-${id} |
| 19 | */ |
| 20 | viewName?: string; |
| 21 | |
| 22 | /** |
| 23 | * A Resource Explorer search filter that scopes every query made through |
| 24 | * this view, e.g. `"service:s3"` or `"tag:stage=prod"`. Results of a |
| 25 | * search are the intersection of the query and this filter. |
| 26 | * Omit to leave the view unfiltered. |
| 27 | */ |
| 28 | filterString?: string; |
| 29 | |
| 30 | /** |
| 31 | * Additional resource properties to include in search results returned |
| 32 | * by this view. `"tags"` is the only supported property today. |
| 33 | */ |
| 34 | includedProperties?: string[]; |
| 35 | |
| 36 | /** |
| 37 | * The root ARN the view is scoped to. Defaults to the account |
| 38 | * (`arn:aws:iam::<account>:root`). Changing the scope requires |
| 39 | * replacement — the API offers no scope update. |
| 40 | */ |
| 41 | scope?: string; |
| 42 | |
| 43 | /** |
| 44 | * Tags to apply to the view. Merged with internal Alchemy tags. |
| 45 | */ |
| 46 | tags?: Record<string, string>; |
| 47 | } |
| 48 | |
| 49 | /** @resource */ |
| 50 | export interface View extends Resource< |
| 51 | "AWS.ResourceExplorer.View", |
| 52 | ViewProps, |
| 53 | { |
| 54 | /** ARN of the view, e.g. `arn:aws:resource-explorer-2:us-west-2:123456789012:view/my-view/uuid`. */ |
| 55 | viewArn: string; |
| 56 | /** Name of the view. */ |
| 57 | viewName: string; |
| 58 | /** The root ARN the view is scoped to. */ |
| 59 | scope: string | undefined; |
| 60 | }, |
| 61 | never, |
| 62 | Providers |
| 63 | > {} |
| 64 | |
| 65 | /** |
| 66 | * An AWS Resource Explorer view — a saved search lens with an optional |
| 67 | * filter and a set of included properties that `Search` queries run |
| 68 | * through. |
| 69 | * |
| 70 | * Views require an active `AWS.ResourceExplorer.Index` in the region. |
| 71 | * When an index and a view deploy together, the view provider retries |
| 72 | * through the window where the index is still provisioning. |
| 73 | * |
| 74 | * ### Creating Views |
| 75 | * **Example:** Unfiltered view over the whole account |
| 76 | * ```typescript |
| 77 | * const index = yield* AWS.ResourceExplorer.Index("Index", {}); |
| 78 | * const view = yield* AWS.ResourceExplorer.View("AllResources", {}); |
| 79 | * ``` |
| 80 | * |
| 81 | * **Example:** Filtered view with tags included in results |
| 82 | * ```typescript |
| 83 | * const view = yield* AWS.ResourceExplorer.View("S3Only", { |
| 84 | * filterString: "service:s3", |
| 85 | * includedProperties: ["tags"], |
| 86 | * }); |
| 87 | * ``` |
| 88 | * |
| 89 | * ### Searching |
| 90 | * **Example:** Search from a Lambda function |
| 91 | * ```typescript |
| 92 | * // init |
| 93 | * const search = yield* AWS.ResourceExplorer.Search(view); |
| 94 | * |
| 95 | * return { |
| 96 | * fetch: Effect.gen(function* () { |
| 97 | * // runtime |
| 98 | * const results = yield* search({ QueryString: "service:s3" }); |
| 99 | * return HttpServerResponse.json({ count: results.Count }); |
| 100 | * }), |
| 101 | * }; |
| 102 | * ``` |
| 103 | */ |
| 104 | const ViewResource = Resource<View>("AWS.ResourceExplorer.View"); |
| 105 | |
| 106 | export { ViewResource as View }; |
| 107 | |
| 108 | /** |
| 109 | * Raised when a view can neither be created (a peer holds the name) nor |
| 110 | * observed afterwards — i.e. reconciliation raced a concurrent delete. |
| 111 | */ |
| 112 | export class ViewUnobservable extends Data.TaggedError("ResourceExplorerViewUnobservable")<{ |
| 113 | message: string; |
| 114 | }> {} |
| 115 | |
| 116 | /** |
| 117 | * Resource Explorer answers `GetView`/`DeleteView` for a nonexistent or |
| 118 | * deleted view with the typed `UnauthorizedException` (HTTP 401, empty |
| 119 | * message) rather than `ResourceNotFoundException` — both mean "the view |
| 120 | * is not there for you". |
| 121 | */ |
| 122 | const getViewSafe = Effect.fn(function* (viewArn: string) { |
| 123 | return yield* re2.getView({ ViewArn: viewArn }).pipe( |
| 124 | Effect.map((r): re2.GetViewOutput | undefined => r), |
| 125 | Effect.catchTag(["UnauthorizedException", "ResourceNotFoundException"], () => Effect.undefined), |
| 126 | ); |
| 127 | }); |
| 128 | |
| 129 | /** |
| 130 | * Find a view's ARN by its name. View ARNs embed the name as the second |
| 131 | * `/`-segment: `arn:...:view/{name}/{uuid}`. |
| 132 | */ |
| 133 | const findViewArnByName = Effect.fn(function* (name: string) { |
| 134 | const arns = yield* re2.listViews.pages({}).pipe( |
| 135 | Stream.runCollect, |
| 136 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Views ?? [])), |
| 137 | ); |
| 138 | return arns.find((arn) => arn.split("/")[1] === name); |
| 139 | }); |
| 140 | |
| 141 | /** |
| 142 | * Creating a view while the region's index is still provisioning (or |
| 143 | * missing) is rejected with the typed `UnauthorizedException`. When an |
| 144 | * `Index` and a `View` deploy concurrently this is a transient ordering |
| 145 | * race — retry through it on a bounded schedule (an index becomes ACTIVE |
| 146 | * in ~15s). Explicitly-typed helper: an inline `Effect.retry` widens the |
| 147 | * provider layer's declaration-emitted R to `unknown`. |
| 148 | */ |
| 149 | const retryWhileIndexProvisioning = <A, E extends { _tag: string }, R>( |
| 150 | self: Effect.Effect<A, E, R>, |
| 151 | ): Effect.Effect<A, E, R> => |
| 152 | Effect.retry(self, { |
| 153 | while: (e) => e._tag === "UnauthorizedException", |
| 154 | schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]), |
| 155 | }); |
| 156 | |
| 157 | const toTagRecord = ( |
| 158 | tags: { [key: string]: string | undefined } | undefined, |
| 159 | ): Record<string, string> => { |
| 160 | const out: Record<string, string> = {}; |
| 161 | for (const [key, value] of Object.entries(tags ?? {})) { |
| 162 | if (value !== undefined) out[key] = value; |
| 163 | } |
| 164 | return out; |
| 165 | }; |
| 166 | |
| 167 | const includedPropertyNames = (properties: re2.IncludedProperty[] | undefined): string[] => |
| 168 | (properties ?? []).map((p) => p.Name); |
| 169 | |
| 170 | const sameStringSet = (a: string[], b: string[]) => |
| 171 | a.length === b.length && [...a].sort().join(",") === [...b].sort().join(","); |
| 172 | |
| 173 | export const ViewProvider = () => |
| 174 | Provider.effect( |
| 175 | ViewResource, |
| 176 | Effect.gen(function* () { |
| 177 | const createViewName = Effect.fn(function* ( |
| 178 | id: string, |
| 179 | props: { viewName?: string | undefined }, |
| 180 | ) { |
| 181 | return props.viewName ?? (yield* createPhysicalName({ id, maxLength: 64 })); |
| 182 | }); |
| 183 | |
| 184 | const toAttrs = (view: re2.View, name: string): View["Attributes"] => ({ |
| 185 | viewArn: view.ViewArn!, |
| 186 | viewName: name, |
| 187 | scope: view.Scope, |
| 188 | }); |
| 189 | |
| 190 | return ViewResource.Provider.of({ |
| 191 | stables: ["viewArn", "viewName"], |
| 192 | |
| 193 | list: () => |
| 194 | Effect.gen(function* () { |
| 195 | const arns = yield* re2.listViews.pages({}).pipe( |
| 196 | Stream.runCollect, |
| 197 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Views ?? [])), |
| 198 | ); |
| 199 | // A view can vanish between enumeration and hydration — drop it. |
| 200 | const items = yield* Effect.forEach( |
| 201 | arns, |
| 202 | (arn) => |
| 203 | getViewSafe(arn).pipe( |
| 204 | Effect.map((found) => |
| 205 | found?.View?.ViewArn |
| 206 | ? toAttrs(found.View, found.View.ViewName ?? arn.split("/")[1]!) |
| 207 | : undefined, |
| 208 | ), |
| 209 | ), |
| 210 | { concurrency: 10 }, |
| 211 | ); |
| 212 | return items.filter((item): item is View["Attributes"] => item !== undefined); |
| 213 | }), |
| 214 | |
| 215 | read: Effect.fn(function* ({ id, olds, output }) { |
| 216 | // Prefer the cached ARN; fall back to a by-name scan (state may |
| 217 | // have been lost after a persistence failure). |
| 218 | let arn = output?.viewArn; |
| 219 | if (arn === undefined) { |
| 220 | const name = yield* createViewName(id, olds ?? {}); |
| 221 | arn = yield* findViewArnByName(name); |
| 222 | } |
| 223 | if (arn === undefined) return undefined; |
| 224 | const found = yield* getViewSafe(arn); |
| 225 | if (!found?.View?.ViewArn) return undefined; |
| 226 | const attrs = toAttrs(found.View, found.View.ViewName ?? arn.split("/")[1]!); |
| 227 | const tags = toTagRecord(found.Tags); |
| 228 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 229 | }), |
| 230 | |
| 231 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 232 | if (!isResolved(news)) return undefined; |
| 233 | const oldName = yield* createViewName(id, olds ?? {}); |
| 234 | const newName = yield* createViewName(id, news); |
| 235 | if (oldName !== newName) { |
| 236 | return { action: "replace" } as const; |
| 237 | } |
| 238 | // Scope has no update API — a change requires replacement. |
| 239 | if ((olds ?? {}).scope !== news.scope) { |
| 240 | return { action: "replace" } as const; |
| 241 | } |
| 242 | // Fall through: default update path handles filters/properties/tags. |
| 243 | }), |
| 244 | |
| 245 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 246 | const name = output?.viewName ?? (yield* createViewName(id, news)); |
| 247 | const internalTags = yield* createInternalTags(id); |
| 248 | const desiredTags = { ...news.tags, ...internalTags }; |
| 249 | const desiredProperties = news.includedProperties ?? []; |
| 250 | const desiredFilter = news.filterString; |
| 251 | |
| 252 | // 1. OBSERVE — by cached ARN first, then by name (covers |
| 253 | // adoption and lost state). |
| 254 | let found = |
| 255 | output?.viewArn !== undefined ? yield* getViewSafe(output.viewArn) : undefined; |
| 256 | if (!found?.View) { |
| 257 | const arn = yield* findViewArnByName(name); |
| 258 | found = arn !== undefined ? yield* getViewSafe(arn) : undefined; |
| 259 | } |
| 260 | |
| 261 | // 2. ENSURE — create when missing. Retries through the window |
| 262 | // where the region's index is still provisioning, and |
| 263 | // tolerates a duplicate-name Conflict as a race (observe the |
| 264 | // winner and converge below). |
| 265 | if (!found?.View) { |
| 266 | found = yield* retryWhileIndexProvisioning( |
| 267 | re2.createView({ |
| 268 | ViewName: name, |
| 269 | Filters: desiredFilter !== undefined ? { FilterString: desiredFilter } : undefined, |
| 270 | IncludedProperties: desiredProperties.map((Name) => ({ |
| 271 | Name, |
| 272 | })), |
| 273 | Scope: news.scope, |
| 274 | Tags: desiredTags, |
| 275 | }), |
| 276 | ).pipe( |
| 277 | Effect.map( |
| 278 | (r): re2.GetViewOutput | undefined => r.View && { View: r.View, Tags: desiredTags }, |
| 279 | ), |
| 280 | Effect.catchTag("ConflictException", () => |
| 281 | Effect.gen(function* () { |
| 282 | const arn = yield* findViewArnByName(name); |
| 283 | return arn !== undefined ? yield* getViewSafe(arn) : undefined; |
| 284 | }), |
| 285 | ), |
| 286 | ); |
| 287 | } |
| 288 | const view = found?.View; |
| 289 | if (found === undefined || view?.ViewArn === undefined) { |
| 290 | // Unreachable in practice: create either succeeded or the |
| 291 | // conflicting peer exists; observation just raced a delete. |
| 292 | return yield* new ViewUnobservable({ |
| 293 | message: `ResourceExplorer view ${name} could not be created or observed`, |
| 294 | }); |
| 295 | } |
| 296 | |
| 297 | // 3. SYNC — UpdateView REPLACES both Filters and |
| 298 | // IncludedProperties (omitted fields are cleared), so always |
| 299 | // send the full desired shape when either differs. |
| 300 | const observedFilter = view.Filters?.FilterString; |
| 301 | const observedProperties = includedPropertyNames(view.IncludedProperties); |
| 302 | if ( |
| 303 | (observedFilter ?? undefined) !== desiredFilter || |
| 304 | !sameStringSet(observedProperties, desiredProperties) |
| 305 | ) { |
| 306 | yield* re2.updateView({ |
| 307 | ViewArn: view.ViewArn, |
| 308 | Filters: desiredFilter !== undefined ? { FilterString: desiredFilter } : undefined, |
| 309 | IncludedProperties: desiredProperties.map((Name) => ({ Name })), |
| 310 | }); |
| 311 | } |
| 312 | |
| 313 | // 3b. SYNC TAGS — diff against OBSERVED cloud tags. |
| 314 | const observedTags = toTagRecord(found.Tags); |
| 315 | const { upsert, removed } = diffTags(observedTags, desiredTags); |
| 316 | if (upsert.length > 0) { |
| 317 | yield* re2.tagResource({ |
| 318 | resourceArn: view.ViewArn, |
| 319 | Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])), |
| 320 | }); |
| 321 | } |
| 322 | if (removed.length > 0) { |
| 323 | yield* re2.untagResource({ |
| 324 | resourceArn: view.ViewArn, |
| 325 | tagKeys: removed, |
| 326 | }); |
| 327 | } |
| 328 | |
| 329 | yield* session.note(view.ViewArn); |
| 330 | return toAttrs(view, view.ViewName ?? name); |
| 331 | }), |
| 332 | |
| 333 | delete: Effect.fn(function* ({ output }) { |
| 334 | // Idempotent: a missing/deleted view answers with the typed |
| 335 | // UnauthorizedException (Resource Explorer's "not found" for |
| 336 | // views) or ResourceNotFoundException. |
| 337 | yield* re2.deleteView({ ViewArn: output.viewArn }).pipe( |
| 338 | Effect.catchTag( |
| 339 | ["UnauthorizedException", "ResourceNotFoundException"], |
| 340 | () => Effect.undefined, |
| 341 | ), |
| 342 | Effect.asVoid, |
| 343 | ); |
| 344 | }), |
| 345 | }); |
| 346 | }), |
| 347 | ); |