diff --git a/.agents/skills/alchemy/SKILL.md b/.agents/skills/alchemy/SKILL.md index 6343c245..b2adb4ea 100644 --- a/.agents/skills/alchemy/SKILL.md +++ b/.agents/skills/alchemy/SKILL.md @@ -1,6 +1,6 @@ --- name: alchemy -description: Answers Alchemy (alchemy.run) questions from an indexed local copy of the full documentation. Covers Stacks, Resources, Actions, Outputs, bindings, the Effect-based deploy/runtime phase model, the alchemy CLI, state stores, stages, secret providers (dotenv, Doppler, Infisical), Better Auth, SQL clients (Effect SQL, Drizzle, Prisma ORM), and provider guides for Cloudflare, AWS, Fly, Railway, Hetzner, Neon, PlanetScale, Prisma, Stripe, Docker, and Axiom. Use when the user mentions "alchemy", "alchemy.run", "alchemy.run.ts", "Alchemy.Stack", "Infrastructure-as-Effects", "alchemy deploy", or asks how to define a Resource, bind a resource into a Worker or Lambda, or deploy an Effect program to Cloudflare or AWS with Alchemy. +description: Answers Alchemy (alchemy.run) questions from an indexed local copy of the full documentation. Covers Stacks, Resources, Actions, Outputs, bindings, the Effect-based deploy/runtime phase model, the alchemy CLI, state stores, stages, secret providers (dotenv, Doppler, Infisical), Better Auth, SQL clients (Effect SQL, Drizzle, Prisma ORM), and provider guides for Cloudflare, AWS, GCP, DigitalOcean, Kubernetes, Fly, Railway, Hetzner, Neon, PlanetScale, Prisma, Turso, Rivet, Stripe, Docker, and Axiom, sandbox providers (Modal, Daytona, E2B, Boat, Archil), Effect Cluster, and the Effect domain-driven design framework. Use when the user mentions "alchemy", "alchemy.run", "alchemy.run.ts", "Alchemy.Stack", "Infrastructure-as-Effects", "alchemy deploy", or asks how to define a Resource, bind a resource into a Worker or Lambda, or deploy an Effect program to Cloudflare or AWS with Alchemy. argument-hint: "[topic]" --- @@ -12,7 +12,7 @@ this skill's directory. -Indexed from `alchemy-run/alchemy` @ `e354a45` (2026-09-30), alchemy `2.0.0-beta.79` on `effect@4.0.0-rc.118`: **484 topic files** across 28 areas. +Indexed from `alchemy-run/alchemy` @ `d1f364a` (2026-11-15), alchemy `2.0.0-beta.87` on `effect@4.1.4`: **851 topic files** across 38 areas. Reference paths mirror site URLs exactly, so a path is derivable without searching: `https://alchemy.run/cloudflare/compute/workers` -> @@ -106,7 +106,7 @@ artifact. ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; export default Alchemy.Stack( @@ -192,37 +192,47 @@ yourself. - `references/getting-started.md` -- Install Alchemy and create your first Stack in under two minutes. - `references/migrating-from-v1.md` -- Migrate your Alchemy v1 (async/await) project to Alchemy v2. -- `references/what-is-alchemy.md` -- Alchemy is Infrastructure as Code built in pure Effect, with Infrastructure as Effects on top. Declare your cloud resources and the code that runs on them in one type-safe TypeScript program, and deploy it with one command. +- `references/what-is-alchemy.md` -- Alchemy is a TypeScript framework for building cloud applications with Effects and Layers. Your infrastructure and the code that runs on it are written, type-checked, and deployed together. ### Areas -- `references/acme/` (8) -- Manage TLS certificates independently of your hosting provider, at deploy time or from an application. +- `references/acme/` (9) -- Manage TLS certificates independently of your hosting provider, at deploy time or from an application. - `references/apis/` (4) -- Every Function and Server returns { fetch, ...rpcs } — schemaless typed calls are the default for internal communication; Effect RPC and Effect HTTP add schemas where data crosses a trust boundary. -- `references/aws/` (54) -- Build AWS applications with Alchemy — a runtime (usually Lambda) plus typed resources, wired together by bindings that mint least-privilege IAM policies. -- `references/axiom/` (6) -- Observability as resources — OTEL datasets, ingest tokens, monitors, notifiers, and dashboards declared next to the code that emits the data. -- `references/better-auth/` (28) -- Build authentication with an Effect service, automatic database bindings, and deploy-time migrations. -- `references/cli/` (14) -- Every alchemy command at a glance — the command map, common options, and how the interactive TUI decides when to render. -- `references/cloudflare/` (78) -- Build and deploy full applications on Cloudflare with Alchemy — one Worker runtime plus resources like Durable Objects, D1, R2, Queues, and Hyperdrive, wired together by typed bindings. -- `references/command/` (3) -- Alchemy's cloud-agnostic primitives for local processes in the deploy graph — memoized builds, one-off commands, and dev servers. -- `references/docker/` (5) -- Images, containers, networks, and volumes as Stack resources, driven through your active Docker CLI context. -- `references/environments/` (10) -- Stages, per-environment config, secrets, local dev, and CI. -- `references/fly/` (35) -- Deploy Effect programs to Fly.io as Apps, Machines, Services, and Sprites. -- `references/gcp/` (6) -- Google Cloud in one Effect program — Cloud Run services and jobs, Firestore, Pub/Sub, BigQuery, Secret Manager, and Memorystore, with IAM granted by the bindings themselves. -- `references/git/` (25) -- A pluggable, embeddable, self-hostable git server on Cloudflare Workers, Durable Objects, and R2. Smart HTTP for any client, a typed REST plane with pull requests, and a GitHub-compatible API. -- `references/github/` (5) -- Repositories, Actions secrets and variables, webhooks, and repository event sources as Stack resources — the glue for CI/CD. -- `references/hetzner/` (27) -- Build applications on Hetzner Cloud with Alchemy — Servers running your Effect programs as Services, plus volumes, networks, firewalls, load balancers, and DNS, all in one typed program. -- `references/infrastructure-as-code/` (10) -- The noun graph: Stacks, Resources, Actions, Outputs, references, lifecycle, providers. -- `references/infrastructure-as-effects/` (9) -- One Effect program models runtime code and infrastructure: Runtimes carry code, Bindings wire resources into them, Phases split deploy from runtime, and Layers package it behind typed services. -- `references/kubernetes/` (19) -- Run containers and Effect programs on any Kubernetes cluster with Alchemy. Declare Deployments, Jobs, raw manifests, and Helm charts in the same typed program as the rest of your infrastructure. No YAML, no kubectl apply. -- `references/neon/` (31) -- Declare Neon Postgres, Functions, storage, Auth, AI Gateway and websites together in an Alchemy Stack. -- `references/planetscale/` (9) -- Serverless MySQL (Vitess) and Postgres with database branching — databases, branches, and credentials as Stack resources. -- `references/prisma/` (29) -- Prisma Postgres and Prisma Compute — projects, databases, connections, and deployed apps as Stack resources, with a zero-config local database in dev. +- `references/archil/` (20) -- Run commands, processes and programs serverlessly against durable disks, in Firecracker microVMs, with Alchemy. Declare disks, sandboxes, images and branches in TypeScript. +- `references/aws/` (62) -- Build on AWS with Alchemy. Declare Lambda Functions, containers, tables, buckets and queues in TypeScript, and let bindings write each runtime's IAM policy from the calls its code makes. +- `references/axiom/` (8) -- Observability as resources — OTEL datasets, ingest tokens, monitors, notifiers, and dashboards declared next to the code that emits the data. +- `references/better-auth/` (29) -- Build authentication with an Effect service, automatic database bindings, and deploy-time migrations. +- `references/boat/` (19) -- Run sandboxes on Boat with Alchemy. Declare sandboxes, snapshots, environments and webhooks in TypeScript, and create sandboxes from any Worker or Function. +- `references/cli/` (15) -- Every alchemy command at a glance — the command map, common options, and how the interactive TUI decides when to render. +- `references/cloudflare/` (87) -- Build on Cloudflare with Alchemy. Declare Workers, Durable Objects, R2, D1, KV and Queues in TypeScript, and bind each one into the Worker that uses it with a typed client. +- `references/cluster/` (23) -- Run Effect Cluster entities, workflows, singletons and crons with Alchemy — a Postgres database and a pool of runners on Docker, AWS, GCP, Kubernetes, Fly or Hetzner, or Durable Objects on Cloudflare. +- `references/command/` (4) -- Alchemy's cloud-agnostic primitives for local processes in the deploy graph — memoized builds, one-off commands, and dev servers. +- `references/daytona/` (20) -- Run code you don't fully trust in Daytona sandboxes. Declare snapshots, volumes and secrets in your Stack, and create, drive and delete sandboxes from any Worker or Lambda. +- `references/digitalocean/` (44) -- Run Effect programs on DigitalOcean with Alchemy. Declare Apps, Functions, Droplets, Kubernetes, Spaces, Managed Databases, AI agents and networking in one TypeScript program. +- `references/docker/` (17) -- Docker builds applications into images and runs them as isolated containers on a Docker engine, on your laptop, a CI runner or a server. +- `references/domain/` (44) -- A domain-driven design framework for Effect. Model your business as commands, aggregates, events, views, projections and policies, test it in memory, and run it on Durable Objects on Cloudflare, Rivet or Effect Cluster. +- `references/e2b/` (17) -- Run sandboxes for agents on E2B with Alchemy. Declare templates, warm snapshots, volumes and secrets in TypeScript, and create sandboxes from any Worker or Function. +- `references/environments/` (11) -- Stages, per-environment config, secrets, local dev, and CI. +- `references/fly/` (38) -- Run Effect programs on Fly.io with Alchemy. Declare Services, Machines, Volumes, Postgres, Redis and Tigris in TypeScript, in the regions near your users. +- `references/gcp/` (51) -- Build on Google Cloud with Alchemy. Declare Cloud Run services, jobs, Firestore, Cloud Storage and Pub/Sub in TypeScript, and let bindings grant each runtime's service account the roles its code uses. +- `references/git/` (26) -- A pluggable, embeddable, self-hostable git server on Cloudflare Workers, Durable Objects, and R2. Smart HTTP for any client, a typed REST plane with pull requests, and a GitHub-compatible API. +- `references/github/` (7) -- Repositories, Actions secrets, variables and environments, webhooks, repository event sources and pull request comments as Stack resources — the glue for CI/CD. +- `references/hetzner/` (29) -- Run Effect programs on Hetzner Cloud Servers with Alchemy. Declare Servers, Services, Volumes, networks, firewalls, load balancers and DNS in one TypeScript program. +- `references/infrastructure-as-code/` (12) -- The noun graph: Stacks, Resources, Actions, Outputs, references, lifecycle, providers. +- `references/infrastructure-as-effects/` (10) -- One Effect program models runtime code and infrastructure: Runtimes carry code, Bindings wire resources into them, Phases split deploy from runtime, and Layers package it behind typed services. +- `references/kubernetes/` (20) -- Run containers and Effect programs on any Kubernetes cluster with Alchemy. Declare Deployments, Jobs, raw manifests, and Helm charts in the same typed program as the rest of your infrastructure. No YAML, no kubectl apply. +- `references/modal/` (28) -- Run Functions, Servers and Sandboxes on Modal with Alchemy. Declare apps, images, volumes and secrets in TypeScript, and create sandboxes from any Worker or Lambda. +- `references/neon/` (36) -- Declare Neon Postgres projects, branches and roles, plus Functions, storage, Auth, the Data API and AI Gateway, in an Alchemy Stack, with a branch per preview stage. +- `references/planetscale/` (11) -- Declare PlanetScale Postgres and MySQL databases, branches and credentials in your Stack with Alchemy, apply migrations on deploy, and give every preview stage its own branch. +- `references/prisma/` (31) -- Declare Prisma Postgres databases, connections, branches and Compute apps as Stack resources with Alchemy, and run the same Stack against a local Postgres in dev. - `references/project-structure/` (4) -- How to lay out single-stack and multi-stack repos. -- `references/railway/` (36) -- Deploy Effect programs to Railway as Projects, Services, databases, Volumes, and Buckets. -- `references/sql/` (14) -- Choose a database, connect with Effect SQL, Drizzle, or Prisma ORM, and deploy committed migrations. +- `references/railway/` (38) -- Run Effect programs on Railway with Alchemy. Declare Projects, Services, Functions, Postgres, MySQL, Redis, Volumes and Buckets in one TypeScript program. +- `references/rivet/` (29) -- Build on Rivet with Alchemy. Declare Durable Objects and Durable Streams in TypeScript, run the control plane and its nodes on the cloud you choose or on Rivet Cloud, and call any instance by name from any runtime. +- `references/sql/` (17) -- Choose a database, connect with Effect SQL, Drizzle, or Prisma ORM, and deploy committed migrations. - `references/state-store/` (2) -- How Alchemy persists resource state between deploys to compute diffs and track infrastructure. -- `references/stripe/` (5) -- Sell subscriptions and onboard merchants from a Cloudflare Worker — catalog, Checkout, the Billing Portal, Connect, and webhooks declared next to the code that uses them. +- `references/stripe/` (7) -- Sell subscriptions and onboard merchants from a Cloudflare Worker — catalog, Checkout, the Billing Portal, Connect, and webhooks declared next to the code that uses them. - `references/testing/` (5) -- How Alchemy tests work — real clouds by default, local emulators on demand, one Stack deploy per suite, isolated stages, deploy → assert → destroy. +- `references/turso/` (14) -- Create Turso SQLite databases and query them from your Workers. Each area has an `INDEX.md` listing every page with what it covers. Read it only to disambiguate; read the topic file to answer. @@ -234,12 +244,21 @@ Every page in the corpus. Append `.md` and prefix `references//`. ``` acme/ _overview certificate-authorities dns-validation getting-started renewal runtime troubleshooting - using-certificates + using-certificates what-is-acme apis/ _overview effect-http effect-rpc schemaless -aws/ _overview ai/bedrock apis/api-gateway apis/effect-http-api - apis/effect-rpc apis/schemaless-rpc - compute/choosing-a-runtime compute/ec2 compute/ecs - compute/eks compute/hyperpod compute/lambda compute/microvms +archil/ _overview compute/choosing-a-runtime compute/images + compute/programs compute/sandboxes organization-and-keys + security/credentials security/network setup storage/branches + storage/disks storage/mounting storage/your-own-bucket + tutorial/part-1 tutorial/part-2 tutorial/part-3 + tutorial/part-4 tutorial/part-5 tutorial/part-6 + what-is-archil +aws/ _overview accounts-and-regions ai/bedrock apis/api-gateway + apis/effect-http-api apis/effect-rpc apis/schemaless-rpc + compute/choosing-a-runtime compute/ec2 compute/ecs-sandboxes + compute/ecs compute/effect-workflows compute/eks + compute/hyperpod compute/lambda compute/microvms + compute/nitro-sandboxes compute/web-functions data/drizzle-aurora data/drizzle-dsql data/dynamodb data/rds data/s3 email/receiving email/sending frontend/astro frontend/foldkit frontend/full-stack-tanstack-rpc-drizzle @@ -248,14 +267,16 @@ aws/ _overview ai/bedrock apis/api-gateway apis/effect-htt frontend/static-site frontend/sveltekit frontend/tanstack-start frontend/vinext frontend/vite-spa frontend/vite frontend/vue frontend/waku frontend/websites - local-development messaging/dynamodb-streams + iam local-development messaging/dynamodb-streams messaging/eventbridge messaging/kinesis messaging/s3-events messaging/sns messaging/sqs networking/_overview networking/custom-domains observability/cloudwatch - security/secrets-env setup tutorial/part-1 tutorial/part-2 - tutorial/part-3 tutorial/part-4 tutorial/part-5 + security/federated-identity security/secrets-env setup + tutorial/part-1 tutorial/part-2 tutorial/part-3 + tutorial/part-4 tutorial/part-5 what-is-aws axiom/ _overview data/ingest guides/alerting guides/annotations - guides/dashboards setup + guides/dashboards organizations-and-tokens setup + what-is-axiom better-auth/ _overview databases/_overview databases/aurora-data-api databases/cloudflare-d1 databases/cloudflare-hyperdrive databases/drizzle databases/memory databases/mysql @@ -267,22 +288,32 @@ better-auth/ _overview databases/_overview databases/aurora-data-a sign-in-providers/google sign-in-providers/microsoft tutorial/part-1 tutorial/part-2 tutorial/part-3 tutorial/part-4 tutorial/part-5 tutorial/part-6 - upgrades/from-1-6-to-1-7 -cli/ _overview adopting-resources aws cloudflare deploy destroy - dev drift inspecting-state logs nuke plan profile state -cloudflare/ _overview ai/ai-gateway ai/ai-search ai/effect-ai - ai/release-agent ai/vectorize ai/workers-ai - apis/effect-http-api apis/effect-rpc apis/schemaless-rpc - compute/add-a-workflow compute/browser-rendering - compute/cache compute/containers + upgrades/from-1-6-to-1-7 what-is-better-auth +boat/ _overview account-and-keys sandboxes/choosing-a-runtime + sandboxes/lifecycle-events sandboxes/ports sandboxes/programs + sandboxes/sandboxes sandboxes/snapshots + security/credential-profiles security/credentials + security/environments setup tutorial/part-1 tutorial/part-2 + tutorial/part-3 tutorial/part-4 tutorial/part-5 + tutorial/part-6 what-is-boat +cli/ _overview adopting-resources api aws cloudflare deploy + destroy dev drift inspecting-state logs nuke plan profile + state +cloudflare/ _overview accounts-and-tokens ai/ai-gateway ai/ai-search + ai/effect-ai ai/vectorize ai/workers-ai apis/effect-http-api + apis/effect-rpc apis/schemaless-rpc compute/add-a-workflow + compute/browser-rendering compute/cache compute/code-updates + compute/container-lifecycle compute/containers compute/cross-worker-durable-object compute/durable-objects - compute/gradual-deployments compute/hibernatable-websockets - compute/previews compute/python-workers compute/rate-limiting + compute/effect-workflows compute/gradual-deployments + compute/hibernatable-websockets compute/previews + compute/python-workers compute/rate-limiting compute/run-a-container compute/worker-loader compute/workers-for-platforms compute/workers compute/workflows data/artifacts data/branch-from-shared-database data/d1-drizzle data/d1 - data/drizzle data/hyperdrive data/kv data/prisma + data/drizzle data/hyperdrive-private-database data/hyperdrive + data/iceberg-tables data/kv data/pipelines data/prisma data/r2-presigned-urls data/r2 data/shared-database email/_overview email/email-worker email/send-and-receive frontend/astro frontend/foldkit frontend/frontends @@ -291,32 +322,93 @@ cloudflare/ _overview ai/ai-gateway ai/ai-search ai/effect-ai frontend/solidstart frontend/static-site frontend/sveltekit frontend/tanstack-start frontend/vinext frontend/vite-spa frontend/vite frontend/vue frontend/waku local-development - messaging/cron messaging/github-events messaging/queues - networking/custom-domains networking/domains - networking/tunnel observability/analytics-engine + messaging/cron messaging/github-events messaging/k2 + messaging/queues networking/custom-domains networking/domains + networking/federated-apis networking/tunnel + observability/analytics-engine observability/axiom-observability observability/workers-tracing security/access security/secrets-env security/secrets-store security/turnstile setup tutorial/part-1 tutorial/part-2 tutorial/part-3 tutorial/part-4 tutorial/part-5 - tutorial/part-6 -command/ _overview dev-servers memoization -docker/ _overview build-and-push local-services setup swarm + tutorial/part-6 what-is-cloudflare +cluster/ _overview aws calling cloudflare crons databases docker + entities existing-programs fly gcp hetzner kubernetes + middleware pools setup singletons tutorial/part-1 + tutorial/part-2 tutorial/part-3 tutorial/part-4 + what-is-effect-cluster workflows +command/ _overview dev-servers memoization what-is-command +daytona/ _overview networking/network observability/telemetry + organization/organization organizations-and-keys + sandboxes/programs sandboxes/runners sandboxes/sandboxes + sandboxes/snapshots sandboxes/toolbox sandboxes/volumes + security/secrets setup tutorial/part-1 tutorial/part-2 + tutorial/part-3 tutorial/part-4 tutorial/part-5 + tutorial/part-6 what-is-daytona +digitalocean/ _overview ai/action-gateway ai/agent-harness ai/genai-agents + ai/inference compute/app-platform compute/choosing-a-runtime + compute/droplets compute/functions compute/kubernetes + compute/sandboxes data/managed-databases data/spaces + data/vector-databases data/volumes-nfs frontend/astro + frontend/foldkit frontend/nextjs frontend/nuxt + frontend/octane frontend/react-router frontend/solidstart + frontend/sveltekit frontend/tanstack-start frontend/vinext + frontend/vite frontend/vocs frontend/waku frontend/websites + networking/dns networking/firewalls networking/load-balancers + networking/reserved-ips networking/vpcs + observability/monitoring security/secrets setup + teams-projects-and-tokens tutorial/part-1 tutorial/part-2 + tutorial/part-3 tutorial/part-4 tutorial/part-5 + what-is-digitalocean +docker/ _overview build-caches build-images cloud-runtimes containers + effectful-services engines-and-contexts limits-and-security + local-services networks registries remote-images services + setup swarm volumes what-is-docker +domain/ _overview aggregate annotations api backfill better-auth cli + cloudflare command deadlines effect-cluster event + external-system foldkit http-api in-memory local-first mcp + model observability optimistic-updates policy project-layout + projection query rivet saga sessions story stream + testing-apis testing-models tutorial/part-1 tutorial/part-2 + tutorial/part-3 tutorial/part-4 tutorial/part-5 + tutorial/part-6 tutorial/part-7 tutorial/part-8 unique-values + view-security view what-is-ddd +e2b/ _overview api-keys lifecycle-events network-and-secrets + programs sandboxes setup snapshots templates tutorial/part-1 + tutorial/part-2 tutorial/part-3 tutorial/part-4 + tutorial/part-5 tutorial/part-6 volumes what-is-e2b environments/ auth-providers ci custom-auth-provider doppler infisical local-development profiles secret-providers secrets stages + worktrees fly/ _overview compute/apps compute/connecting-services compute/deployments compute/machines compute/regions compute/services compute/sprites data/drizzle-postgres data/postgres data/redis data/secrets data/tigris - data/volumes frontend/astro frontend/foldkit frontend/nextjs - frontend/nuxt frontend/octane frontend/react-router - frontend/solidstart frontend/static-site frontend/sveltekit + data/volumes federated-identity frontend/astro + frontend/foldkit frontend/nextjs frontend/nuxt + frontend/octane frontend/react-router frontend/solidstart + frontend/static-site frontend/sveltekit frontend/tanstack-start frontend/vinext frontend/vite frontend/vocs frontend/waku frontend/websites networking + organizations-and-tokens setup tutorial/part-1 + tutorial/part-2 tutorial/part-3 tutorial/part-4 what-is-fly +gcp/ _overview ai/vertex-ai apis/effect-http-api apis/effect-rpc + compute/choosing-a-runtime compute/cloud-functions + compute/cloud-run compute/gke compute/jobs compute/sidecars + compute/worker-pools data/bigquery data/cloud-sql + data/firestore data/memorystore data/storage frontend/astro + frontend/foldkit frontend/nextjs frontend/nuxt + frontend/octane frontend/react-router frontend/solidstart + frontend/static-site frontend/sveltekit + frontend/tanstack-start frontend/vinext frontend/vite-spa + frontend/vite frontend/vocs frontend/vue frontend/waku + frontend/websites messaging/eventarc messaging/pubsub + messaging/scheduler messaging/storage-events + networking/private-services networking/vpc + observability/monitoring projects-and-regions + security/federated-identity security/iam security/secrets-kms setup tutorial/part-1 tutorial/part-2 tutorial/part-3 - tutorial/part-4 -gcp/ _overview guides/bindings guides/cloud-run-api - guides/event-pipeline guides/memorystore setup + tutorial/part-4 tutorial/part-5 what-is-gcp git/ _overview blocks/_overview blocks/auth blocks/blob-store blocks/engine blocks/hasher blocks/registry blocks/repositories blocks/server clone-and-push @@ -324,8 +416,9 @@ git/ _overview blocks/_overview blocks/auth blocks/blob-st recipes/cloudflare-aws recipes/cloudflare recipes/scaling recipes/your-own-store repositories tutorial/part-1 tutorial/part-2 tutorial/part-3 tutorial/part-4 - tutorial/part-5 tutorial/part-6 -github/ _overview actions-config events repository setup + tutorial/part-5 tutorial/part-6 what-is-git +github/ _overview accounts-and-tokens actions-config events + repository setup what-is-github hetzner/ _overview compute/servers compute/services data/drizzle-postgres data/volumes frontend/astro frontend/foldkit frontend/nextjs frontend/nuxt @@ -333,32 +426,46 @@ hetzner/ _overview compute/servers compute/services frontend/static-site frontend/sveltekit frontend/tanstack-start frontend/vinext frontend/vite frontend/vocs frontend/waku frontend/websites - networking/_overview networking/dns setup tutorial/part-1 - tutorial/part-2 tutorial/part-3 tutorial/part-4 -infrastructure-as-code/ action custom-provider local-provider outputs provider - references renaming resource-lifecycle resource stack -infrastructure-as-effects/ binding circular-bindings custom-runtime event-sources layers - phases runtime sinks telemetry + networking/_overview networking/dns projects-and-tokens setup + tutorial/part-1 tutorial/part-2 tutorial/part-3 + tutorial/part-4 what-is-hetzner +infrastructure-as-code/ action contributions custom-provider dns-adapters + local-provider outputs provider references renaming + resource-lifecycle resource stack +infrastructure-as-effects/ binding circular-bindings custom-runtime event-sources + identity-federation layers phases runtime sinks telemetry kubernetes/ _overview clusters/cluster-adapters clusters/connecting clusters/eks clusters/local clusters/registries objects/helm-charts objects/manifests setup tutorial/part-1 tutorial/part-2 tutorial/part-3 tutorial/part-4 - tutorial/part-5 workloads/bindings workloads/deployments - workloads/images workloads/jobs workloads/object-lifecycle + tutorial/part-5 what-is-kubernetes workloads/bindings + workloads/deployments workloads/images workloads/jobs + workloads/object-lifecycle +modal/ _overview compute/choosing-a-runtime networking/network + sandboxes/images sandboxes/persistent sandboxes/programs + sandboxes/sandboxes sandboxes/snapshots + security/access-control security/secrets services/autoscaling + services/calling-python services/functions services/operating + services/servers services/web-endpoints setup storage/dicts + storage/queues storage/volumes tutorial/part-1 + tutorial/part-2 tutorial/part-3 tutorial/part-4 + tutorial/part-5 tutorial/part-6 what-is-modal + workspaces-and-tokens neon/ _overview data/branching data/connections data/migrations - frontend/astro frontend/foldkit frontend/nextjs frontend/nuxt - frontend/octane frontend/react-router frontend/solidstart - frontend/static-site frontend/sveltekit + data/roles frontend/astro frontend/foldkit frontend/nextjs + frontend/nuxt frontend/octane frontend/react-router + frontend/solidstart frontend/static-site frontend/sveltekit frontend/tanstack-start frontend/vite frontend/vocs - frontend/waku governance guides/ai-gateway + frontend/waku functions governance guides/ai-gateway guides/custom-domains guides/drizzle guides/preview-branches guides/private-networking guides/production-auth - guides/state-recovery setup tutorial/_overview - tutorial/backend tutorial/frontend tutorial/functions - tutorial/previews + guides/state-recovery organizations-and-keys setup storage + tutorial/_overview tutorial/backend tutorial/frontend + tutorial/functions tutorial/previews what-is-neon planetscale/ _overview data/backups data/credentials data/migrations data/mysql data/postgres guides/drizzle - guides/preview-branches setup + guides/preview-branches organizations-and-tokens setup + what-is-planetscale prisma/ _overview compute/apps compute/deployments data/branches data/buckets data/connections data/drizzle-postgres data/postgres frontend/astro frontend/foldkit frontend/nextjs @@ -368,6 +475,7 @@ prisma/ _overview compute/apps compute/deployments data/branc frontend/vocs frontend/waku frontend/websites guides/cloudflare-workers setup tutorial/part-1 tutorial/part-2 tutorial/part-3 tutorial/part-4 + what-is-prisma workspaces-and-tokens project-structure/ file-layout monorepo-multi-stack monorepo-single-stack monorepo railway/ _overview compute/environments compute/functions @@ -380,17 +488,27 @@ railway/ _overview compute/environments compute/functions frontend/tanstack-start frontend/vinext frontend/vite frontend/vocs frontend/waku frontend/websites networking setup tutorial/part-1 tutorial/part-2 tutorial/part-3 - tutorial/part-4 -sql/ _overview databases drizzle/d1 drizzle/migrations - drizzle/mysql drizzle/postgres effect-sql/d1 - effect-sql/lifecycle effect-sql/migrations effect-sql/mysql - effect-sql/postgres prisma/contracts prisma/migrations - prisma/postgres + tutorial/part-4 what-is-railway workspaces-and-tokens +rivet/ _overview actors aws calling concurrency control-planes + docker durable-objects durable-streams fly gcp hetzner + kubernetes namespaces pools railway rivet-cloud + rivetkit-effect rivetkit-rust rivetkit secrets setup storage + tokens-and-networks tutorial/part-1 tutorial/part-2 + tutorial/part-3 tutorial/part-4 what-is-rivet +sql/ _overview databases drizzle/d1 drizzle/libsql + drizzle/migrations drizzle/mysql drizzle/postgres + effect-sql/d1 effect-sql/libsql effect-sql/lifecycle + effect-sql/migrations effect-sql/mysql effect-sql/postgres + prisma/contracts prisma/migrations prisma/postgres + what-is-sql state-store/ _overview custom-state-store -stripe/ _overview guides/connect guides/subscriptions guides/webhooks - setup +stripe/ _overview accounts-and-keys guides/connect + guides/subscriptions guides/webhooks setup what-is-stripe testing/ _overview observability test-harness testing-a-stack testing-providers +turso/ _overview connections database-per-tenant databases groups + migrations organization preview-databases setup tokens + tutorial/part-1 tutorial/part-2 tutorial/part-3 what-is-turso ``` @@ -494,14 +612,15 @@ from the conceptual pages. ## Version notes -Alchemy v2 is **pre-release** and moving fast. It pins the exact Effect 4 -release candidate named in the corpus stats above (peer range -`>=4.0.0-rc.118 || >=4.0.0`, installed as `effect@rc`); the `effect-ts` skill -documents that same version, so use it for Effect APIs. Since `4.0.0-rc.118`, -unstable modules import without an `unstable` segment (for example -`effect/http/HttpServerResponse` and `effect/http-api/HttpApi`); rewrite any -older `effect/unstable/...` or `effect/httpapi/...` import. Drizzle is pinned to an exact prerelease -build (`drizzle-orm@1.0.0-rc.5-ab785fc`); do not suggest `drizzle-orm@latest`. +Alchemy v2 is **pre-release** and moving fast. It builds against the exact +stable Effect 4 release named in the corpus stats above (peer range `^4.1.4` +for `effect`, `@effect/platform-bun`, and `@effect/platform-node`, installed +from the npm `latest` dist-tag, not `effect@rc`); the `effect-ts` skill +documents that same version, so use it for Effect APIs. Unstable modules import +without an `unstable` segment (for example `effect/http/HttpServerResponse` and +`effect/http-api/HttpApi`); rewrite any older `effect/unstable/...` or +`effect/httpapi/...` import. Drizzle is pinned to an exact prerelease +(`drizzle-orm@1.0.0-rc.5`); do not suggest `drizzle-orm@latest`. Prisma ORM v8 is also a release candidate (`prisma@8.0.0-rc.*`). Better Auth is on the 1.7 line. Node floor is 22+ (the upstream repo develops on Node 24), Bun recommended. diff --git a/.agents/skills/alchemy/package.json b/.agents/skills/alchemy/package.json index 4dc55ff7..a6f15e5e 100644 --- a/.agents/skills/alchemy/package.json +++ b/.agents/skills/alchemy/package.json @@ -8,7 +8,7 @@ "check": "bun scripts/build-skill.ts --check" }, "dependencies": { - "effect": "4.0.0", + "effect": "4.1.4", "yaml": "^2.9.1" } } diff --git a/.agents/skills/alchemy/references/acme/INDEX.md b/.agents/skills/alchemy/references/acme/INDEX.md index e30ef4ab..1cb250b2 100644 --- a/.agents/skills/alchemy/references/acme/INDEX.md +++ b/.agents/skills/alchemy/references/acme/INDEX.md @@ -1,6 +1,6 @@ # acme index -8 pages. Manage TLS certificates independently of your hosting provider, at deploy time or from an application. +9 pages. Manage TLS certificates independently of your hosting provider, at deploy time or from an application. | Page | File | Covers | | --- | --- | --- | @@ -12,3 +12,4 @@ | Runtime issuance | `runtime.md` | Deploy an authenticated Worker that issues and revokes certificates using a bound ACME account. | | Troubleshooting | `troubleshooting.md` | Diagnose failed DNS challenges, rejected orders, rate limits, and runtime certificate operations. | | Using certificates | `using-certificates.md` | Upload an ACME certificate to Fly or pass its chain and private key to another TLS consumer. | +| What is ACME? | `what-is-acme.md` | The concepts behind ACME certificates — certificate authorities, accounts, orders, challenges and DNS-01 validation, certificates and keys, renewal and revocation — and how @alchemy.run/acme models each of them. | diff --git a/.agents/skills/alchemy/references/acme/_overview.md b/.agents/skills/alchemy/references/acme/_overview.md index 36f32b7f..4fce2d21 100644 --- a/.agents/skills/alchemy/references/acme/_overview.md +++ b/.agents/skills/alchemy/references/acme/_overview.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # ACME @@ -12,6 +12,8 @@ certificates. Alchemy manages the account and certificate separately from the service that terminates TLS. You can issue a certificate once and pass its PEM chain and private key to Fly or another consumer. +**New to ACME?** [What is ACME?](/acme/what-is-acme) walks through certificate authorities, accounts, orders, DNS challenges, certificates, renewal and revocation, once each, and shows how Alchemy models every one. + ## Choose when to issue | | During deployment | From an application | @@ -60,7 +62,5 @@ certificate in production. The generated references document each property and method: -- [Account](/providers/acme/account) -- [Certificate](/providers/acme/certificate) -- [IssueCertificate](/providers/acme/issuecertificate) -- [IssueCertificateHttp](/providers/acme/issuecertificatehttp) +- [Account](/providers/acme/reference/account) +- [Certificate](/providers/acme/reference/certificate) diff --git a/.agents/skills/alchemy/references/acme/certificate-authorities.md b/.agents/skills/alchemy/references/acme/certificate-authorities.md index 2dc800df..468bb6fa 100644 --- a/.agents/skills/alchemy/references/acme/certificate-authorities.md +++ b/.agents/skills/alchemy/references/acme/certificate-authorities.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Certificate authorities @@ -61,7 +61,7 @@ account. Obtain a matching key ID and HMAC key from ZeroSSL and put them in your secret configuration as `ZEROSSL_EAB_KID` and `ZEROSSL_EAB_HMAC_KEY`. ```typescript -import * as ACME from "alchemy/ACME"; +import * as ACME from "@alchemy.run/acme"; import * as Config from "effect/Config"; export const Issuer = ACME.Account("Issuer", { @@ -86,7 +86,7 @@ const account = yield* Issuer; const certificate = yield* ACME.Certificate("Api", { account, identifiers: ["api.example.com"], - solver: Cloudflare.DNS.AcmeSolver({ + solver: Cloudflare.ACME.ZoneSolver({ zoneId: Config.String("CLOUDFLARE_ZONE_ID"), }), }); diff --git a/.agents/skills/alchemy/references/acme/dns-validation.md b/.agents/skills/alchemy/references/acme/dns-validation.md index d464223e..30e5de28 100644 --- a/.agents/skills/alchemy/references/acme/dns-validation.md +++ b/.agents/skills/alchemy/references/acme/dns-validation.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # DNS validation @@ -19,15 +19,15 @@ Inside the stack from [Getting started](/acme/getting-started): const certificate = yield* ACME.Certificate("Site", { account, identifiers: ["example.com"], - solver: Cloudflare.DNS.AcmeSolver({ + solver: Cloudflare.ACME.ZoneSolver({ zoneId: Config.String("CLOUDFLARE_ZONE_ID"), }), }); ``` -`AcmeSolver` returns serializable data containing the solver type and zone ID. -Include both `ACME.providers()` and `Cloudflare.providers()` in the stack. The -Cloudflare credentials must allow listing, creating, and deleting TXT records in +`ZoneSolver` returns serializable data containing the solver type and zone ID. +`Cloudflare.providers()` runs it with the profile's Cloudflare credentials, which +must allow listing, creating, and deleting TXT records in that zone. The domain must already be delegated to that zone's nameservers. ## Use a managed zone instead @@ -39,10 +39,10 @@ If your stack already owns a Cloudflare `Zone` resource, pass the resolved zone: const certificate = yield* ACME.Certificate("Site", { account, identifiers: ["example.com"], -- solver: Cloudflare.DNS.AcmeSolver({ +- solver: Cloudflare.ACME.ZoneSolver({ - zoneId: Config.String("CLOUDFLARE_ZONE_ID"), - }), -+ solver: Cloudflare.DNS.AcmeSolver(zone), ++ solver: Cloudflare.ACME.ZoneSolver(zone), }); ``` @@ -80,7 +80,7 @@ possible. const certificate = yield* ACME.Certificate("Site", { account, identifiers: ["example.com", "*.example.com"], - solver: Cloudflare.DNS.AcmeSolver(zone), + solver: Cloudflare.ACME.ZoneSolver(zone), + propagation: { + delay: "60 seconds", + timeout: "90 seconds", @@ -120,11 +120,11 @@ Inside a Worker's initialization Effect: ```typescript const dns = yield* Cloudflare.DNS.WriteDns(Zone); -const solver = Cloudflare.DNS.acmeDnsSolver(dns); +const solver = Cloudflare.ACME.zoneSolver(dns); ``` -The runtime helper is **`acmeDnsSolver`**, while the deploy-time helper is -**`AcmeSolver`**. Provide `Cloudflare.DNS.WriteDnsHttp` on the host Effect. Its +The runtime helper is **`zoneSolver`**, while the deploy-time helper is +**`ZoneSolver`**. Provide `Cloudflare.DNS.WriteDnsHttp` on the host Effect. Its client uses a zone-scoped token created at deployment, rather than exposing the deployer's entire credential set to the application. @@ -149,7 +149,7 @@ hosting and scheduling implications. A custom solver adapts an existing DNS client's idempotent operations: ```typescript -import type * as ACME from "alchemy/ACME"; +import type * as ACME from "@alchemy.run/acme"; import type * as Effect from "effect/Effect"; export const makeSolver = (dns: { @@ -178,7 +178,7 @@ For an adapter whose client has no remaining Effect requirements, register a factory with this shape: ```typescript -import * as ACME from "alchemy/ACME"; +import * as ACME from "@alchemy.run/acme"; import type * as Effect from "effect/Effect"; export const registerExampleDns = ( diff --git a/.agents/skills/alchemy/references/acme/getting-started.md b/.agents/skills/alchemy/references/acme/getting-started.md index 9d8219aa..2944f561 100644 --- a/.agents/skills/alchemy/references/acme/getting-started.md +++ b/.agents/skills/alchemy/references/acme/getting-started.md @@ -1,23 +1,24 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Getting started > Issue a staging TLS certificate with Let's Encrypt and an existing Cloudflare DNS zone. -This guide issues a certificate for a domain you control. It uses Let's Encrypt +Issue a certificate for a domain you control from Let's Encrypt staging, so you can validate the deployment without consuming production issuance limits. The resulting certificate is deliberately **not trusted by browsers**. ## Prepare the project -Install Alchemy and the matching Effect version using [Cloudflare setup](/cloudflare/setup). +Install Alchemy and the matching Effect version using [Cloudflare setup](/cloudflare/setup), +then add `@alchemy.run/acme`. You need an active Cloudflare DNS zone, its zone ID, and credentials that can read, create, and delete DNS records in that zone. The domain's authoritative nameservers must already point to Cloudflare. -Use a domain you own wherever this guide says `example.com`. Set +Use a domain you own wherever the examples say `example.com`. Set `CLOUDFLARE_ZONE_ID` in your project's `.env` to the zone ID from its Cloudflare dashboard. This example references the existing zone by ID; it does not create, adopt, modify the settings of, or delete the zone itself. @@ -47,8 +48,8 @@ shared deployment runner, use a protected [remote state store](/state-store). ## Register the providers ```diff lang="typescript" -+import * as ACME from "alchemy/ACME"; -+import * as Cloudflare from "alchemy/Cloudflare"; ++import * as ACME from "@alchemy.run/acme"; ++import * as Cloudflare from "@alchemy.run/cloudflare"; export default Alchemy.Stack( "Certificates", @@ -59,8 +60,9 @@ shared deployment runner, use a protected [remote state store](/state-store). + }, ``` -`ACME.providers()` manages accounts and certificates. `Cloudflare.providers()` -registers the Cloudflare DNS solver used to prove control of the domain. +`ACME.providers()` manages accounts and certificates, and +`Cloudflare.providers()` includes the Cloudflare DNS solver used to prove +control of the domain. ## Connect Cloudflare @@ -104,7 +106,7 @@ reuses on subsequent deployments. + const certificate = yield* ACME.Certificate("Site", { + account, + identifiers: ["example.com"], -+ solver: Cloudflare.DNS.AcmeSolver({ ++ solver: Cloudflare.ACME.ZoneSolver({ + zoneId: Config.String("CLOUDFLARE_ZONE_ID"), + }), + }); @@ -143,8 +145,8 @@ The steps above produce this `alchemy.run.ts`: ```typescript import * as Alchemy from "alchemy"; -import * as ACME from "alchemy/ACME"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as ACME from "@alchemy.run/acme"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Config from "effect/Config"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -164,7 +166,7 @@ export default Alchemy.Stack( const certificate = yield* ACME.Certificate("Site", { account, identifiers: ["example.com"], - solver: Cloudflare.DNS.AcmeSolver({ + solver: Cloudflare.ACME.ZoneSolver({ zoneId: Config.String("CLOUDFLARE_ZONE_ID"), }), }); diff --git a/.agents/skills/alchemy/references/acme/renewal.md b/.agents/skills/alchemy/references/acme/renewal.md index 1b5eca19..eb416318 100644 --- a/.agents/skills/alchemy/references/acme/renewal.md +++ b/.agents/skills/alchemy/references/acme/renewal.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Renewal & revocation @@ -18,7 +18,7 @@ In the certificate from [Getting started](/acme/getting-started): const certificate = yield* ACME.Certificate("Site", { account, identifiers: ["example.com"], - solver: Cloudflare.DNS.AcmeSolver({ + solver: Cloudflare.ACME.ZoneSolver({ zoneId: Config.String("CLOUDFLARE_ZONE_ID"), }), + renewBefore: "30 days", @@ -73,7 +73,7 @@ process needs explicit revocation after cutover. const certificate = yield* ACME.Certificate("Site", { account, identifiers: ["example.com"], - solver: Cloudflare.DNS.AcmeSolver({ + solver: Cloudflare.ACME.ZoneSolver({ zoneId: Config.String("CLOUDFLARE_ZONE_ID"), }), + revokeOnDelete: true, diff --git a/.agents/skills/alchemy/references/acme/runtime.md b/.agents/skills/alchemy/references/acme/runtime.md index 8be2496b..32220588 100644 --- a/.agents/skills/alchemy/references/acme/runtime.md +++ b/.agents/skills/alchemy/references/acme/runtime.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Runtime issuance @@ -40,7 +40,7 @@ issuance allowance. Create `resources.ts`: ```typescript -import * as ACME from "alchemy/ACME"; +import * as ACME from "@alchemy.run/acme"; import * as Config from "effect/Config"; export const Issuer = ACME.Account("Issuer", { @@ -63,7 +63,7 @@ Add a zone resource to `resources.ts`: ```typescript import { adopt } from "alchemy/AdoptPolicy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import { retain } from "alchemy/RemovalPolicy"; export const Zone = Cloudflare.Zone.Zone("DnsZone", { @@ -117,7 +117,7 @@ serialization; possession of a DNS token alone is not tenant authorization. ```typescript const issued = yield* issuer.issue({ identifiers: ["api.example.com"], - solver: Cloudflare.DNS.acmeDnsSolver(dns), + solver: Cloudflare.ACME.zoneSolver(dns), }); ``` @@ -142,8 +142,8 @@ Create `issuer-worker.ts`. This complete file combines the bindings, authorizati and two operations above: ```typescript -import * as ACME from "alchemy/ACME"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as ACME from "@alchemy.run/acme"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Config from "effect/Config"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -176,7 +176,7 @@ export default class IssuerWorker extends Cloudflare.Worker()( if (pathname === "/issue") { const issued = yield* issuer.issue({ identifiers: ["api.example.com"], - solver: Cloudflare.DNS.acmeDnsSolver(dns), + solver: Cloudflare.ACME.zoneSolver(dns), }); return yield* HttpServerResponse.json( { @@ -242,8 +242,8 @@ Create `alchemy.run.ts`: ```typescript import * as Alchemy from "alchemy"; -import * as ACME from "alchemy/ACME"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as ACME from "@alchemy.run/acme"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import IssuerWorker from "./issuer-worker.ts"; diff --git a/.agents/skills/alchemy/references/acme/troubleshooting.md b/.agents/skills/alchemy/references/acme/troubleshooting.md index 6b8f1cef..e50f2e73 100644 --- a/.agents/skills/alchemy/references/acme/troubleshooting.md +++ b/.agents/skills/alchemy/references/acme/troubleshooting.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Troubleshooting @@ -14,15 +14,10 @@ values, and authorization headers out of logs. ## Missing DNS solver `ACME.DnsSolverNotRegistered` means the descriptor's `type` has no registered -factory in the stack's provider context. For Cloudflare, register both providers: - -```typescript -const providers = Layer.mergeAll(ACME.providers(), Cloudflare.providers()); -``` - -Pass this layer as the stack's `providers`. For runtime issuance, use -`acmeDnsSolver(dns)` with a bound DNS client instead of passing the deploy-time -descriptor returned by `AcmeSolver`. +factory in the stack's provider context. `ACME.providers()` registers the +Cloudflare solver, so include it in the stack's `providers`. For runtime issuance, use +`zoneSolver(dns)` with a bound DNS client instead of passing the deploy-time +descriptor returned by `ZoneSolver`. ## DNS API access fails diff --git a/.agents/skills/alchemy/references/acme/using-certificates.md b/.agents/skills/alchemy/references/acme/using-certificates.md index ce32f10c..1d736995 100644 --- a/.agents/skills/alchemy/references/acme/using-certificates.md +++ b/.agents/skills/alchemy/references/acme/using-certificates.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Using certificates @@ -28,7 +28,7 @@ consumer needs the **certificate's** private key, never the account's key. Start with the [Getting started](/acme/getting-started) stack and add Fly: ```diff lang="typescript" -+import * as Fly from "alchemy/Fly"; ++import * as Fly from "@alchemy.run/fly"; - providers: Layer.mergeAll(ACME.providers(), Cloudflare.providers()), + providers: Layer.mergeAll( @@ -79,9 +79,9 @@ with your own values: ```typescript import * as Alchemy from "alchemy"; -import * as ACME from "alchemy/ACME"; -import * as Cloudflare from "alchemy/Cloudflare"; -import * as Fly from "alchemy/Fly"; +import * as ACME from "@alchemy.run/acme"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Fly from "@alchemy.run/fly"; import * as Config from "effect/Config"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -106,7 +106,7 @@ export default Alchemy.Stack( const certificate = yield* ACME.Certificate("Site", { account, identifiers: ["example.com"], - solver: Cloudflare.DNS.AcmeSolver({ + solver: Cloudflare.ACME.ZoneSolver({ zoneId: Config.String("CLOUDFLARE_ZONE_ID"), }), }); diff --git a/.agents/skills/alchemy/references/acme/what-is-acme.md b/.agents/skills/alchemy/references/acme/what-is-acme.md new file mode 100644 index 00000000..bb5edf6a --- /dev/null +++ b/.agents/skills/alchemy/references/acme/what-is-acme.md @@ -0,0 +1,84 @@ + + +# What is ACME? + +> The concepts behind ACME certificates — certificate authorities, accounts, orders, challenges and DNS-01 validation, certificates and keys, renewal and revocation — and how @alchemy.run/acme models each of them. + +A TLS certificate proves to a browser that a server really is `example.com`. **ACME** is the protocol certificate authorities like Let's Encrypt and ZeroSSL use to issue those certificates automatically: you prove you control a domain, and the authority signs a certificate for it, for free, in under a minute. + +Take one certificate: a wildcard for `*.example.com`, validated through a Cloudflare zone and installed on a Fly app. An account asks the authority for a certificate. The authority sets a challenge, which is answered with a DNS record. Once it sees the record, the authority signs the certificate, which goes to whatever serves the domain. + + + +## Certificate authorities + +A **certificate authority** (CA) is an organization browsers trust to vouch for domains. Let's Encrypt and ZeroSSL issue certificates over ACME for free. Each has a **staging** environment, whose certificates browsers don't trust but whose limits are generous, for testing, and a **production** one, with rate limits on how many certificates you can issue. + +See [Certificate authorities](/acme/certificate-authorities). + +## Accounts + +You talk to a CA as an **account**: a key pair registered with it. Every order is signed with the account's key. Some CAs, like ZeroSSL, also ask for **external account binding**, credentials that tie the ACME account to an account on their website. + +```typescript title="alchemy.run.ts" +const account = yield* ACME.Account("Issuer", { + ca: ACME.LetsEncryptStaging, + contact: ["mailto:ops@example.com"], + termsOfServiceAgreed: true, +}); +``` + +## Orders and challenges + +To get a certificate, the account places an **order** for one or more names. For each name, the CA sets a **challenge**: a task only the domain's owner could complete. Once every challenge passes, the CA signs the certificate. + +**DNS-01** is the challenge Alchemy uses: publish a TXT record at `_acme-challenge.example.com` with a value the CA gives you. It's the only challenge that can prove control of a **wildcard** like `*.example.com`, and it needs no running server. + +See [DNS validation](/acme/dns-validation). + +## Certificates and keys + +A **certificate** is a chain: your certificate, signed by the CA, and the intermediates linking it to a root browsers trust. It's paired with a **private key**, which never leaves your hands. Whatever terminates TLS, a load balancer, a CDN or your own server, needs both. + +```typescript title="alchemy.run.ts" +const cert = yield* ACME.Certificate("Wildcard", { + account, + identifiers: ["example.com", "*.example.com"], + solver: Cloudflare.ACME.ZoneSolver({ zoneId: Config.String("CLOUDFLARE_ZONE_ID") }), +}); +``` + +See [Using certificates](/acme/using-certificates). + +## Renewal and revocation + +Certificates expire, after 90 days for Let's Encrypt, so they must be **renewed** before then. **Revocation** tells the CA to stop vouching for a certificate early, if its key leaked. + +Renewal needs something to run. A certificate declared in your Stack checks its expiry on each deploy, so deploy on a schedule. One issued by your app at runtime renews when your app's scheduler says. + +See [Renewal & revocation](/acme/renewal). + +## How @alchemy.run/acme models these concepts + +An account and a certificate are resources, issued at deploy time and kept in your Stack's state, with the DNS challenge answered by a solver for your DNS host. The certificate's chain and key are outputs, passed to whatever serves TLS, on any provider. When an app must issue certificates itself, for its own customers' domains, the `IssueCertificate` binding does the same at runtime. See [Runtime issuance](/acme/runtime). + +Next, issue one: [Getting started](/acme/getting-started) deploys a staging certificate with a Cloudflare zone. diff --git a/.agents/skills/alchemy/references/apis/_overview.md b/.agents/skills/alchemy/references/apis/_overview.md index 08c35abd..2253d9d2 100644 --- a/.agents/skills/alchemy/references/apis/_overview.md +++ b/.agents/skills/alchemy/references/apis/_overview.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # APIs @@ -13,7 +13,7 @@ half: plain functions returning `Effect` or `Stream`, no schema, no decorators: ```typescript -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import * as HttpServerResponse from "effect/http/HttpServerResponse"; diff --git a/.agents/skills/alchemy/references/apis/effect-http.md b/.agents/skills/alchemy/references/apis/effect-http.md index 5b37b73d..f9f08452 100644 --- a/.agents/skills/alchemy/references/apis/effect-http.md +++ b/.agents/skills/alchemy/references/apis/effect-http.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Effect HTTP diff --git a/.agents/skills/alchemy/references/apis/effect-rpc.md b/.agents/skills/alchemy/references/apis/effect-rpc.md index 5511479c..7f4c9621 100644 --- a/.agents/skills/alchemy/references/apis/effect-rpc.md +++ b/.agents/skills/alchemy/references/apis/effect-rpc.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Effect RPC diff --git a/.agents/skills/alchemy/references/apis/schemaless.md b/.agents/skills/alchemy/references/apis/schemaless.md index 669c7507..b7c9bc77 100644 --- a/.agents/skills/alchemy/references/apis/schemaless.md +++ b/.agents/skills/alchemy/references/apis/schemaless.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Schemaless RPC @@ -35,9 +35,7 @@ export default class Greeter extends Cloudflare.Worker()( ``` The host class here happens to be `Cloudflare.Worker`, but the host -is incidental — the pattern is identical on every runtime. This page -covers what members are allowed, how the typed client arises, what -crosses the wire, and where the limits are. +is incidental — the pattern is identical on every runtime. ## What a member may be diff --git a/.agents/skills/alchemy/references/archil/INDEX.md b/.agents/skills/alchemy/references/archil/INDEX.md new file mode 100644 index 00000000..fce42948 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/INDEX.md @@ -0,0 +1,46 @@ +# archil index + +20 pages. Run commands, processes and programs serverlessly against durable disks, in Firecracker microVMs, with Alchemy. Declare disks, sandboxes, images and branches in TypeScript. + +| Page | File | Covers | +| --- | --- | --- | +| Archil | `_overview.md` | Run commands, processes and programs serverlessly against durable disks, in Firecracker microVMs, with Alchemy. Declare disks, sandboxes, images and branches in TypeScript. | +| Organization and keys | `organization-and-keys.md` | How an Archil account or organization holds your disks, sandboxes and images, how an API key decides where Alchemy deploys, and what access each host gets instead of your key. | +| Setup | `setup.md` | Install the Archil provider, create an API key, and store it in a profile. | +| What is Archil? | `what-is-archil.md` | The concepts behind Archil — organizations and API keys, regions, disks, serverless exec, sandboxes, images, mounts, disk users, branches and egress policy — and how @alchemy.run/archil models each of them. | + +## compute/ + +| Page | File | Covers | +| --- | --- | --- | +| Choosing a runtime | `compute/choosing-a-runtime.md` | Serverless exec, program sandboxes, sandboxes created at run time, and mounts on your own hosts, and when to use each. | +| Images | `compute/images.md` | Boot sandboxes from public images, private registries, or a Dockerfile built on your machine and pushed for Archil to pull. | +| Programs | `compute/programs.md` | Run your program in its own Archil sandbox, in the Effect or async form, at a public https URL. | +| Sandboxes | `compute/sandboxes.md` | Firecracker microVMs with disks mounted, declared as a dev box or created per task. | + +## security/ + +| Page | File | Covers | +| --- | --- | --- | +| Credentials and bindings | `security/credentials.md` | What each host gets to reach Archil, deploy-time resources vs run-time clients, and who owns what your app creates. | +| Network | `security/network.md` | Control what a sandbox can reach, and add credentials to its requests on the way out. | + +## storage/ + +| Page | File | Covers | +| --- | --- | --- | +| Branches and checkpoints | `storage/branches.md` | Seed a disk once, checkpoint it at deploy time, and copy a writable branch per session in milliseconds. | +| Disks | `storage/disks.md` | Create disks per user at run time, share a few at deploy time, run commands against them, and read their files by key. | +| Mounting | `storage/mounting.md` | Mount Archil disks in program sandboxes, your own Containers, and ECS tasks. | +| Your own bucket | `storage/your-own-bucket.md` | Keep a disk's files as ordinary objects in your own S3, R2, GCS or Azure bucket, with no keys for S3. | + +## tutorial/ + +| Page | File | Covers | +| --- | --- | --- | +| Part 1: Set Up a Sandbox | `tutorial/part-1.md` | Install Alchemy, and declare an Archil sandbox that clones a repository onto its disk at deploy time. | +| Part 2: Fork It for Each Request | `tutorial/part-2.md` | A program in its own Archil sandbox that forks the set-up sandbox for each request, runs a command, and deletes the fork. | +| Part 3: A Fork per User | `tutorial/part-3.md` | Give each user an Archil fork of the set-up sandbox, found again by name, which keeps their changes. | +| Part 4: Update the Sandbox | `tutorial/part-4.md` | Change the commands that set up the Archil sandbox, redeploy, and see new forks start from the new one while existing forks keep theirs. | +| Part 5: Testing | `tutorial/part-5.md` | Deploy the Stack in a test, fork the set-up sandbox, and check what the fork contains. | +| Part 6: Stages and CI | `tutorial/part-6.md` | Deploy a stage per environment and per pull request, each with its own set-up Archil sandbox and program, from GitHub Actions. | diff --git a/.agents/skills/alchemy/references/archil/_overview.md b/.agents/skills/alchemy/references/archil/_overview.md new file mode 100644 index 00000000..029a31dd --- /dev/null +++ b/.agents/skills/alchemy/references/archil/_overview.md @@ -0,0 +1,90 @@ + + +# Archil + +> Run commands, processes and programs serverlessly against durable disks, in Firecracker microVMs, with Alchemy. Declare disks, sandboxes, images and branches in TypeScript. + +Archil runs code against your data. A disk is a POSIX filesystem backed by object storage. Archil runs a shell command, a process or a whole program against it serverlessly: each call boots a Firecracker microVM with the disk mounted, runs to completion and shuts down, so you pay only for the call. Sandboxes are the long-lived form: microVMs that keep disks mounted, pause when idle and wake on the next request with their memory intact. + +The same disks mount on your own hosts in about 50 ms, keep recent data on fast storage in front of Archil's bucket or your own, and branch from checkpoints in milliseconds whatever their size. + +**New to Archil?** Start with [What is Archil?](/archil/what-is-archil). + +## A quick example + +A sandbox is set up once, at deploy: Alchemy creates it and runs its `run` commands, here cloning a repository onto its disk: + +```typescript title="src/Golden.ts" +import * as Archil from "@alchemy.run/archil"; + +export const Golden = Archil.Sandbox("Golden", { + run: ["git clone --depth 1 https://github.com/sindresorhus/is /work/is"], +}); +``` + +A Worker forks it on each request, with the repository already there, runs the command it was sent, and deletes the fork when the request ends: + +```typescript title="src/Api.ts" +import * as Archil from "@alchemy.run/archil"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Effect from "effect/Effect"; +import { HttpServerRequest } from "effect/http/HttpServerRequest"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; +import { Golden } from "./Golden.ts"; + +export default class Api extends Cloudflare.Worker()( + "Api", + { main: import.meta.url }, + Effect.gen(function* () { + const sandboxes = yield* Archil.CreateSandbox(Golden); + return { + fetch: Effect.gen(function* () { + const request = yield* HttpServerRequest; + const sandbox = yield* Effect.acquireRelease( + sandboxes.create({ name: `run-${crypto.randomUUID()}` }), + (sandbox) => Effect.ignore(sandbox.delete()), + ); + const result = yield* sandbox.exec(yield* request.text, { cwd: "/work/is" }); + return yield* HttpServerResponse.json(result); + }).pipe(Effect.scoped, Effect.orDie), + }; + }).pipe(Effect.provide(Archil.CreateSandboxHttp)), +) {} +``` + +And the Stack deploys them: + +```typescript title="alchemy.run.ts" +import * as Archil from "@alchemy.run/archil"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Alchemy from "alchemy"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import Api from "./src/Api.ts"; +import { Golden } from "./src/Golden.ts"; + +export default Alchemy.Stack( + "MyApp", + { + providers: Layer.mergeAll(Cloudflare.providers(), Archil.providers()), + state: Cloudflare.state(), + }, + Effect.gen(function* () { + const golden = yield* Golden; + const api = yield* Api; + return { sandbox: golden.name, url: api.url.as() }; + }), +); +``` + +## Where to start + +**Want to build?** Start with [Setup](/archil/setup) to connect your API key, then the [tutorial](/archil/tutorial/part-1), which builds a program on a disk one step at a time. + +**Looking for something specific?** Every section of these docs is listed below, and every resource is in the generated [API reference](/providers). + +## The docs + + diff --git a/.agents/skills/alchemy/references/archil/compute/choosing-a-runtime.md b/.agents/skills/alchemy/references/archil/compute/choosing-a-runtime.md new file mode 100644 index 00000000..10690a04 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/compute/choosing-a-runtime.md @@ -0,0 +1,157 @@ + + +# Choosing a runtime + +> Serverless exec, program sandboxes, sandboxes created at run time, and mounts on your own hosts, and when to use each. + +Archil runs code next to a disk in four ways. Three of them are Firecracker microVMs that Archil runs, and the fourth is a host you already run, with the disk mounted. They differ in how long the code lives and who keeps it running. + +## Archil manages less as you decide more + + + +## Serverless exec: one call, one microVM + +`Archil.ExecDisk` runs one command against a disk. Each call boots a microVM with the disk at `/mnt/archil`, runs the command to completion, and shuts down. Many calls run at once, and each one is a single charge. + +```typescript +const dataset = yield* Archil.ExecDisk(Dataset); +const result = yield* dataset.exec("wc -l /mnt/archil/*.csv"); +``` + +A call runs for at most five minutes and keeps nothing but what it writes to the disk. Choose it for an agent's shell tool, a search, or a batch over a dataset. See [Disks](/archil/storage/disks#run-commands-against-a-disk). + + + +## Program sandboxes: your program at a URL + +An `Archil.Sandbox` with a `main` runs your program. Archil's service manager keeps it running, and its port gets a public `https://` URL. The sandbox pauses when idle, and the next request wakes it. + +```typescript title="src/api.ts" +import * as Archil from "@alchemy.run/archil"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +export default class Api extends Archil.Sandbox()( + "Api", + { main: import.meta.url }, + Effect.gen(function* () { + return { fetch: Effect.succeed(HttpServerResponse.text("hello")) }; + }), +) {} +``` + +Choose it for APIs and websites that live next to their data. See [Programs](/archil/compute/programs). + + + +## Sandboxes created at run time: one per task + +`Archil.CreateSandbox` gives a Worker or Lambda a client that creates sandboxes by name, from an image. Your code drives each one: it runs commands, starts processes, opens terminals and deletes it when the task is done. + +```typescript +const sandboxes = yield* Archil.CreateSandbox(MyImage); +const sandbox = yield* sandboxes.create({ name: `task-${id}` }); +yield* sandbox.exec("npm test"); +``` + +Choose it for agent loops and preview environments, where each user or task needs a machine of its own. See [Sandboxes](/archil/compute/sandboxes). + + + +## Mounts: a disk on your own host + +`Archil.MountDisk` on a Cloudflare Container or an ECS task on EC2 installs Archil's FUSE client in the host's image. The host mounts the disk while it handles a request, with a mount token for that disk only. + +```typescript +const dataset = yield* Archil.MountDisk(Dataset, { path: "/data", mode: "read-only" }); +const path = yield* dataset.mount(); +``` + +Choose it when the code already runs somewhere else and needs the files. See [Mounting](/archil/storage/mounting). + + + +## Mix runtimes in one app + +One disk serves all of them at once. A program serves the files, a Worker runs commands against them, and your Container reads them to build an index: + +```text +Diagram (nodes and edges as authored): + +``` diff --git a/.agents/skills/alchemy/references/archil/compute/images.md b/.agents/skills/alchemy/references/archil/compute/images.md new file mode 100644 index 00000000..881675f2 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/compute/images.md @@ -0,0 +1,110 @@ + + +# Images + +> Boot sandboxes from public images, private registries, or a Dockerfile built on your machine and pushed for Archil to pull. + +A sandbox boots an OCI image for `linux/amd64`. Archil pulls the image once, records the digest it resolved, and every sandbox booted from it starts from that digest. Archil has no builder: it pulls images, so an image from a Dockerfile is built on your machine and pushed to a registry first. + +## Archil pulls, you build + +```text +Diagram (nodes and edges as authored): + +``` + +## Boot a public image directly + +A public image needs no resource. Name it as a sandbox's `baseImage`: + +```typescript title="src/devbox.ts" +export const DevBox = Archil.Sandbox("DevBox", { baseImage: "python:3.13" }); +``` + +A sandbox with neither `baseImage` nor `image` boots `node:24-bookworm`. + +## Pin an image by its digest + +`Archil.Image` pulls an image once and keeps its digest, so every sandbox boots the same bits even after the tag moves: + +```typescript title="src/images.ts" +export const Base = Archil.Image("Base", { image: "node:24-bookworm" }); +``` + +Pass its `imageId` to a sandbox: + +```typescript title="src/devbox.ts" +export const DevBox = Effect.gen(function* () { + const base = yield* Base; + return yield* Archil.Sandbox("DevBox", { image: base.imageId }); +}); +``` + +Changing `image` pulls it again. + +## Pull from a private registry + +Give the registry's credentials. Archil uses them to pull this image and doesn't store them: + +```typescript title="src/images.ts" +export const MyImage = Archil.Image("MyImage", { + image: "ghcr.io/acme/agent:1", + registry: { + server: "ghcr.io", + username: "acme-bot", + password: Config.Redacted("GHCR_TOKEN"), + }, +}); +``` + +## Build a Dockerfile on your machine + +Give a `dockerfile` and where to `push` it. Alchemy builds it with your local Docker, pushes it tagged with the build's hash, and Archil pulls it: + +```typescript title="src/images.ts" +export const MyImage = Archil.Image("MyImage", { + dockerfile: "./agent/Dockerfile", + context: "./agent", + push: { + repository: "ghcr.io/acme/agent", + credentials: { server: "ghcr.io", username: "acme-bot", password: Config.Redacted("GHCR_TOKEN") }, + }, +}); +``` + +The credentials need to push to the repository and pull from it. A change to the Dockerfile or its context builds and pushes a new tag. + +## Pull images while your app runs + +`Archil.CreateImage` pulls images at run time, e.g. one per customer repository, with the same props as `Archil.Image`: + +```typescript +const images = yield* Archil.CreateImage(); +const image = yield* images.build({ image: `ghcr.io/acme/${tenant}:latest` }); +const sandbox = yield* sandboxes.create({ name: tenant, image: image.imageId }); +``` + +## Programs that need a filesystem client + +A [program sandbox](/archil/compute/programs) boots a public image. When one of its bindings installs a filesystem client, like a mount for another storage service, Alchemy builds an image of the base plus that client the same way, so give the sandbox a `push` too. + +## Images stay in your registry + +Archil has no API to delete an image. Destroying an `Archil.Image` removes it from Alchemy's state only, and the image pushed to your registry stays there. diff --git a/.agents/skills/alchemy/references/archil/compute/programs.md b/.agents/skills/alchemy/references/archil/compute/programs.md new file mode 100644 index 00000000..933b5a37 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/compute/programs.md @@ -0,0 +1,178 @@ + + +# Programs + +> Run your program in its own Archil sandbox, in the Effect or async form, at a public https URL. + +Give an [`Archil.Sandbox`](/providers/archil/reference/sandbox) a `main` +and it runs your program. Alchemy bundles the program, uploads it into the +sandbox, and registers it with the sandbox's service manager. The service +manager restarts the program if it crashes and starts it whenever the +sandbox boots. The program's port gets a public `https://` URL. + +## The service manager keeps it running + + + +## Write an Effect program + +The class form takes `main: import.meta.url` and the port. The Effect +returns the handlers: + +```typescript +// src/api.ts +import * as Archil from "@alchemy.run/archil"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +export default class Api extends Archil.Sandbox()( + "Api", + { main: import.meta.url, port: 3000 }, + Effect.gen(function* () { + return { + fetch: Effect.succeed(HttpServerResponse.text("hello")), + }; + }), +) {} +``` + +## Deploy it at a public URL + +Yield the program from your Stack and return its URL: + +```typescript +// alchemy.run.ts +import * as Archil from "@alchemy.run/archil"; +import * as Alchemy from "alchemy"; +import * as Effect from "effect/Effect"; +import Api from "./src/api.ts"; + +export default Alchemy.Stack( + "MyApi", + { providers: Archil.providers(), state: Alchemy.localState() }, + Effect.gen(function* () { + const api = yield* Api; + return { url: api.url }; + }), +); +``` + +Run `alchemy deploy`. `url` is `https://3000-..archil.app`. + +## Mount a disk + +`Archil.MountDisk` adds the disk to the sandbox's own mounts. The disk is +already mounted when the program starts, at the `path` you give: + +```diff lang="typescript" +// src/api.ts +export default class Api extends Archil.Sandbox()( + "Api", + { main: import.meta.url, port: 3000 }, + Effect.gen(function* () { ++ const dataset = yield* Archil.MountDisk(Dataset, { path: "/data", mode: "read-only" }); ++ const fs = yield* FileSystem.FileSystem; + return { +- fetch: Effect.succeed(HttpServerResponse.text("hello")), ++ fetch: Effect.map(fs.readDirectory(dataset.path), (names) => HttpServerResponse.text(names.join("\n"))).pipe(Effect.orDie), + }; +- }), ++ }).pipe(Effect.provide(Archil.MountDiskLive)), +) {} +``` + +## Read a disk as objects + +`Archil.ReadDisk` gives the program a read-only S3 user on one disk, for +reading files by key without a mount: + +```diff lang="typescript" +// src/api.ts + Effect.gen(function* () { ++ const files = yield* Archil.ReadDisk(Dataset); + return { +- fetch: Effect.succeed(HttpServerResponse.text("hello")), ++ fetch: Effect.map(files.getText("README.md"), (text) => HttpServerResponse.text(text)), + }; +- }), ++ }).pipe(Effect.provide(Archil.ReadDiskHttp)), +``` + +## Write an async program + +Point `main` at a plain module whose default export has +`fetch(request, env)`. Alchemy bundles it with no Effect runtime: + +```typescript +// src/infra.ts +import * as Archil from "@alchemy.run/archil"; + +export const Hello = Archil.Sandbox("Hello", { + main: "./src/hello.ts", + env: { GREETING: "hello" }, +}); + +export type HelloEnv = Archil.InferEnv; +``` + +## Type its environment + +`Archil.InferEnv` turns the sandbox's `env` into the handler's `env` +argument: + +```typescript +// src/hello.ts +import type { HelloEnv } from "./infra.ts"; + +export default { + async fetch(request: Request, env: HelloEnv) { + return new Response(`${env.GREETING} from ${new URL(request.url).pathname}`); + }, +}; +``` + +## Install native packages + +Packages in `build.install` are installed next to the program with +`npm install` instead of bundled: + +```typescript +// src/infra.ts +export const Thumbs = Archil.Sandbox("Thumbs", { + main: "./src/thumbs.ts", + build: { install: ["sharp"] }, +}); +``` + +## A deploy changes it in place + +A code change, a new `env`, or a new mount updates the same sandbox. A +code or `env` change uploads the program and restarts it. A mount change +stops the sandbox and starts it with the new mounts. The root filesystem +is kept either way. Changing the image or the size replaces the sandbox. + +## An idle sandbox pauses until the next request + +A sandbox pauses after its idle timeout, 30 minutes by default, and the next request to the program's URL wakes it, usually in a few seconds. Set `idleTtlSeconds` to change it, or `0` to keep it running. + +## Where next + +- [Sandboxes](/archil/compute/sandboxes): sizes, disks, and network policy +- [`Archil.Sandbox` reference](/providers/archil/reference/sandbox) diff --git a/.agents/skills/alchemy/references/archil/compute/sandboxes.md b/.agents/skills/alchemy/references/archil/compute/sandboxes.md new file mode 100644 index 00000000..fc648fe3 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/compute/sandboxes.md @@ -0,0 +1,160 @@ + + +# Sandboxes + +> Firecracker microVMs with disks mounted, declared as a dev box or created per task. + +A sandbox is a Firecracker microVM that stays around between calls. Its root filesystem is a disk of its own, so files and installed packages survive a stop. It can mount other disks, serve ports, and run for up to 24 hours per session. After 30 minutes without a connection it pauses, keeping its memory and processes, and the next connection resumes it. + +## A sandbox pauses when idle and resumes on the next connection + + + +## Declare a long-lived dev box + +Declare a sandbox in your Stack to keep it across deploys. Each `mounts` entry names a disk and a `path`: + +```typescript +export const Workspace = Archil.Disk("Workspace", {}); + +export const DevBox = Archil.Sandbox("DevBox", { + baseImage: "node:24-bookworm", + mounts: [{ disk: Workspace, path: "/workspace" }], + ports: [3000], +}); +``` + +A mount change updates the same sandbox: it stops, then starts with the new mounts. + +## Pick a mount mode + +An entry takes Archil's own options: `mode` (`exclusive`, `conditional`, or `read-only`), `subdirectory`, and `queueMs`: + +```typescript +export const Box = Archil.Sandbox("Box", { + mounts: [ + { disk: Workspace, path: "/workspace", mode: "conditional" }, + { disk: Dataset, path: "/data", mode: "read-only", subdirectory: "exports" }, + ], +}); +``` + +`exclusive` (the default) lets one client write the whole disk. `conditional` lets several write at once. Branches and the `shared` mode belong to the FUSE client, so they work in [mounts on your own hosts](/archil/storage/mounting), not in a sandbox. + +## Create sandboxes at run time + +Bind an image, then create a sandbox per task. A mount's disk is a handle, such as one from `CreateDisk`: + +```typescript +export const MyImage = Archil.Image("MyImage", { image: "node:24-bookworm" }); + +const sandboxes = yield* Archil.CreateSandbox(MyImage); +const sandbox = yield* sandboxes.create({ + name: "task-1", + mounts: [{ disk: home, path: "/home/user" }], + idleTtlSeconds: 300, +}); +``` + +## Run commands + +`exec` runs a command to completion. A non-zero exit comes back in `exitCode`: + +```typescript +const result = yield* sandbox.exec("npm test", { cwd: "/home/user/app" }); +const upper = yield* sandbox.exec(["tr", "a-z", "A-Z"], { stdin: "hello" }); +``` + +## Start a background process + +`start` returns a process whose output you can stream. Closing the scope detaches; the process keeps running, and `attach` picks it up again by id: + +```typescript +const server = yield* sandbox.start("npm run dev", { cwd: "/home/user/app" }); +yield* server.output.pipe(Stream.take(10), Stream.runDrain); +``` + +## Open a terminal + +`pty.open` runs a shell on a pseudo-terminal: + +```typescript +const pty = yield* sandbox.pty.open({ cols: 120, rows: 40 }); +yield* pty.write("ls -la\n"); +yield* pty.resize({ cols: 160, rows: 50 }); +``` + +## Move files in and out + +```typescript +yield* sandbox.files.write("/home/user/app/.env", "MODE=test"); +const env = yield* sandbox.files.readText("/home/user/app/.env"); +``` + +Archil's process API moves whole files. List, remove or create directories with `exec`. + +## Pause, resume or fork it + +```typescript +yield* sandbox.pause(); +yield* sandbox.resume(); +const copy = yield* sandbox.fork({ name: "task-1-retry" }); +``` + +A fork copies the sandbox's memory and disk into a new one. Archil only forks a sandbox with mounts while it is stopped. `stop()` and `boot()` stop and start it. + +## Serve a port + +A declared sandbox's `ports`, or `exposePort` on any sandbox, serves a port at its own `https://-..archil.app` hostname. `getTcpPort` returns that port, and its `fetch` sends a request to it: + +```typescript +yield* sandbox.exposePort(3000); +const port = yield* sandbox.getTcpPort(3000); +const response = yield* port.fetch(HttpClientRequest.get("/health")); +``` + +Pass `fetch` the request a handler received, and it proxies the method, path, query, headers and body, then returns the response: + +```typescript +return yield* port.fetch(yield* HttpServerRequest); +``` + +Anyone with the URL can call a public port. Give a browser a port token instead, which it sends in the `X-Archil-Token` header: + +```typescript +const token = yield* sandbox.createPortToken(3000, "1h"); +``` + +## Drive a declared sandbox from a Worker + +`ConnectSandbox` returns the same handle for a sandbox in your Stack: + +```typescript +const devbox = yield* Archil.ConnectSandbox(DevBox); +yield* devbox.exec("pnpm build", { cwd: "/workspace" }); +``` + +## Boot an image + +A sandbox boots `node:24-bookworm` unless you give it a `baseImage` (any public `linux/amd64` image) or an `image` from [`Archil.Image`](/archil/compute/images), for private registries and Dockerfiles. + +## Run your own program + +Give a sandbox a `main` and it runs your program at a public URL. See [Programs](/archil/compute/programs). diff --git a/.agents/skills/alchemy/references/archil/organization-and-keys.md b/.agents/skills/alchemy/references/archil/organization-and-keys.md new file mode 100644 index 00000000..52c78e7c --- /dev/null +++ b/.agents/skills/alchemy/references/archil/organization-and-keys.md @@ -0,0 +1,80 @@ + + +# Organization and keys + +> How an Archil account or organization holds your disks, sandboxes and images, how an API key decides where Alchemy deploys, and what access each host gets instead of your key. + +Everything you create on Archil belongs to a personal account or an **organization**: its disks, sandboxes and images, and the bill for them. An organization lets a team share disks. Members manage them, and administrators also manage who the members are. + +## A key works in one region of one organization + +Inside it, each region keeps its own disks and sandboxes, and an API key works in one region only. + + + +## Store your key in a profile + +Alchemy calls Archil's control plane with an **API key**. Create one in the [console](https://console.archil.com) under **API Keys**, with the account or organization you deploy to selected. It starts with `key-`. + +Then store it in a [profile](/environments/profiles), with the region your disks live in: + +```sh +alchemy profile edit --add Archil +``` + +The key picks the organization and the profile's region picks where every disk, sandbox and image goes, `aws-us-east-1` by default. Run code against disks only in the AWS regions: `gcp-us-central1` stores disks but has no serverless exec or sandboxes. + +Enter your organization id too if you keep disks on your own bucket. The bucket policy only trusts Archil on behalf of that organization. See [Your own bucket](/archil/storage/your-own-bucket). + +## Give production its own profile + +A [stage](/environments/stages) decides what you deploy. The profile decides where. Give production its own organization, or at least its own key, and its own profile: + +```sh +alchemy profile create prod +alchemy profile edit --profile prod --add Archil +alchemy deploy --stage prod --profile prod +``` + +Archil has no tags, so Alchemy tells stages apart by name. Each stage's disks and sandboxes get names generated from the app, stage and id. + +## Each host gets access to one disk + +Archil can't scope an API key, and only creates new ones from a console session, so a deployed host never gets a key of its own. Bindings that touch one disk give their host a **disk user** instead: an S3 key pair for `ReadDisk`, `WriteDisk` and `ReadWriteDisk`, or a mount token for `MountDisk` on your own hosts. Archil checks each one, and destroying the Stack removes them. + +```typescript +const files = yield* Archil.ReadDisk(Dataset); +``` + +Bindings that call the control plane (`ExecDisk`, `CreateDisk`, `BranchDisk`, `CreateSandbox`, `ConnectSandbox`, `CreateImage`) run with the key you deploy with. Rotate it in the console and redeploy. + +See [Credentials and bindings](/archil/security/credentials). + +## Deploy from CI with a key + +When `ARCHIL_API_KEY` is set, Alchemy uses it instead of the profile. Set `ARCHIL_REGION` too unless you deploy to `aws-us-east-1`, and `ARCHIL_ORGANIZATION` for disks on your own bucket: + +```sh +ARCHIL_API_KEY=key-... ARCHIL_REGION=aws-eu-west-1 alchemy deploy --stage prod +``` + +Use a separate key for CI, so you can delete it without touching yours. See [CI](/environments/ci). + +What each host gets, and who owns what your app creates while it runs, is in [Credentials and bindings](/archil/security/credentials). What a sandbox can reach is in [Network](/archil/security/network). diff --git a/.agents/skills/alchemy/references/archil/security/credentials.md b/.agents/skills/alchemy/references/archil/security/credentials.md new file mode 100644 index 00000000..0b6b6940 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/security/credentials.md @@ -0,0 +1,82 @@ + + +# Credentials and bindings + +> What each host gets to reach Archil, deploy-time resources vs run-time clients, and who owns what your app creates. + +Archil is built for objects your app creates while it runs: a disk per user, a branch per session, a sandbox per task. Alchemy splits the API in two to match. + +## Resources live as long as the Stack + +The few long-lived things an app shares are resources in your Stack: a dataset disk, a seeded base, an image, a dev box. + +```typescript +// src/Storage.ts +export const Dataset = Archil.Disk("Dataset", {}); +export const MyImage = Archil.Image("MyImage", { image: "node:24-bookworm" }); +``` + +They deploy, update, and delete with the Stack like any other resource. + +## Bindings create what your app needs while it runs + +Everything per user or per request comes from a binding. `CreateDisk`, `CreateSandbox`, and `CreateImage` create objects by name, with the same props the resources take: + +```typescript +const disks = yield* Archil.CreateDisk(); +const home = yield* disks.create("user-1"); +``` + +Bindings that take a resource act on it: `ExecDisk(Dataset)`, `ReadDisk(Dataset)`, `BranchDisk(Seed)`, `ConnectSandbox(DevBox)`, `MountDisk(Dataset)`. Both kinds return the same disk and sandbox handles. + +## What your app creates outlives the Stack + +Objects created at run time are tagged with the stack, stage and binding (`alchemy::stack`, `alchemy::stage`, `alchemy::id`) and are not deleted when the stack is destroyed. List them by those tags to clean them up. + +Archil disks and sandboxes have only a name, so the tags are a name prefix: `alc--`. Each `Create…` binding puts its prefix on every name it creates. + + + +The client's `prefix` is the value, and its `list` finds what carries it: + +```typescript +const disks = yield* Archil.CreateDisk(); +for (const disk of yield* disks.list()) { + yield* disks.delete(disk.name.slice(disks.prefix.length + 1)); +} +``` + +## Each host gets access to one disk + +A host that only touches one disk never gets your API key. `ReadDisk`, `WriteDisk` and `ReadWriteDisk` give each host its own S3 user on the bound disk, read-only for `ReadDisk`. `MountDisk(disk)` on your own host gives it a mount token for the disk, read-only with `mode: "read-only"`. In a program sandbox, the sandbox mounts the disk itself and no token is created. + +Archil checks both itself, and destroying the stack revokes them. + +Bindings that call Archil's control plane (`ExecDisk`, `CreateDisk`, +`BranchDisk`, `CreateSandbox`, `ConnectSandbox`, `CreateImage`) run with +the API key you deploy with. Archil only creates API keys from the +console and can't scope them, so rotate yours there and redeploy. + +## Hand out a disk token, never a key + +A disk token opens one disk: `home.createToken(name, { readOnly, +expiresAt, oneUse })` makes one at run time for a machine that mounts with +`MountDisk()`. A port token opens one port of one sandbox, for a browser or +client that shouldn't hold a key: + +```typescript +const token = yield* sandbox.createPortToken(8080, "1h"); +``` diff --git a/.agents/skills/alchemy/references/archil/security/network.md b/.agents/skills/alchemy/references/archil/security/network.md new file mode 100644 index 00000000..09e7f6df --- /dev/null +++ b/.agents/skills/alchemy/references/archil/security/network.md @@ -0,0 +1,169 @@ + + +# Network + +> Control what a sandbox can reach, and add credentials to its requests on the way out. + +Every sandbox has an outbound policy. Archil enforces it outside the microVM, so code inside can't change it, and it can add headers to requests as they leave, so a key the sandbox uses never sits inside it. + +## The policy is enforced outside the microVM + + + +## Deny everything but a list of hosts + +```typescript title="src/agent.ts" +export const MySandbox = Archil.Sandbox("MySandbox", { + network: { + egress: { default: "deny", allow: ["registry.npmjs.org", "*.github.com"] }, + }, +}); +``` + +Deny entries win over allow entries. A wildcard matches subdomains, not the apex domain. + +## Add a credential on the way out + +An allow entry can set headers on matching HTTPS requests. The sandbox never sees the value: + +```typescript title="src/agent.ts" +export const MySandbox = Archil.Sandbox("MySandbox", { + network: { + egress: { + default: "deny", + allow: [ + { target: "api.github.com", headers: { Authorization: Config.Redacted("GITHUB_AUTH") } }, + ], + }, + }, +}); +``` + +Archil has no secret store, so the value lives in the sandbox's policy. + +## Send requests through your own gateway + +An allow entry can also forward matching requests to a URL of yours. Archil decrypts the request, applies the entry's headers, and sends it to `forwardUrl` with the original path and query. It names the original destination and the calling sandbox in `archil-forwarded-host`, `archil-forwarded-scheme`, `archil-forwarded-port`, `archil-forwarded-path` and `archil-sandbox-id` headers. + + + +### Forward the API's requests to the gateway + +```typescript title="alchemy.run.ts" +const gateway = yield* MyGateway; +const sandbox = yield* Archil.Sandbox("MySandbox", { + network: { + egress: { + default: "deny", + allow: [ + { + target: "api.example.com", + headers: { "X-Gateway-Token": Config.Redacted("GATEWAY_TOKEN") }, + forwardUrl: gateway.url.as(), + }, + ], + }, + }, +}); +``` + +Requests for `api.example.com` now go to the gateway. Archil adds the gateway token on the way, so the gateway can tell they came through this policy. + +### Give the gateway its secrets + +```typescript title="src/Gateway.ts" +export default class MyGateway extends Cloudflare.Worker()( + "MyGateway", + { + main: import.meta.url, + env: { + GATEWAY_TOKEN: Config.Redacted("GATEWAY_TOKEN"), + API_KEY: Config.Redacted("API_KEY"), + }, + }, + Effect.succeed({ fetch: forward }), +) {} +``` + +A Cloudflare Worker makes a small gateway. It holds the token it expects and the API key it adds. `forward` is the handler the next steps build. + +### Refuse requests without the token + +```typescript title="src/Gateway.ts" +const request = yield* HttpServerRequest; +const env = yield* Cloudflare.Workers.WorkerEnvironment; +if (request.headers["x-gateway-token"] !== env.GATEWAY_TOKEN) { + return HttpServerResponse.text("forbidden", { status: 403 }); +} +``` + +The gateway's URL is public, so anyone can call it. Only Archil adds the token. + +### Send on only to hosts you list + +```typescript title="src/Gateway.ts" +const host = request.headers["archil-forwarded-host"]; +if (host === undefined || !["api.example.com"].includes(host)) { + return HttpServerResponse.text("host not allowed", { status: 403 }); +} +``` + +Without the list, the gateway would add your key to requests for any host. + +### Add the key and call the real host + +```typescript title="src/Gateway.ts" +const { pathname, search } = new URL(request.originalUrl); +const client = yield* HttpClient.HttpClient; +const upstream = yield* client.execute( + HttpClientRequest.get(`https://${host}${pathname}${search}`).pipe( + HttpClientRequest.setHeader("x-api-key", env.API_KEY), + ), +); +return HttpServerResponse.text(yield* upstream.text, { status: upstream.status }); +``` + +Archil appends the original path and query to `forwardUrl`, so the gateway rebuilds the URL from them. For other methods, bodies and headers, copy them from `request`, leaving out the `archil-` headers and the token. + +The gateway holds the API key, so rotating it changes only the Worker. `archil-sandbox-id` tells it which sandbox called, which it can use to log, rate-limit or pick a key per sandbox. `forwardUrl` must be a public HTTPS URL on a domain name, so a `workers.dev` URL or a custom domain works, and an IP address doesn't. + +## Change the policy while it runs + +```typescript +yield* sandbox.setEgress({ default: "deny", allow: ["api.openai.com"] }); +``` + +The new policy applies at once. On a declared `Archil.Sandbox`, changing `network` updates it in place. + +## Your plan sets the default + +On Archil's Free plan, sandboxes reach only a managed allowlist of package registries, Git hosts and model APIs, and adding headers needs the Developer plan or above. A sandbox created on a paid plan with no policy reaches anything. diff --git a/.agents/skills/alchemy/references/archil/setup.md b/.agents/skills/alchemy/references/archil/setup.md new file mode 100644 index 00000000..5a03512b --- /dev/null +++ b/.agents/skills/alchemy/references/archil/setup.md @@ -0,0 +1,61 @@ + + +# Setup + +> Install the Archil provider, create an API key, and store it in a profile. + +Everything you need before deploying to Archil: the packages, an Archil account, and an API key stored in a profile. + +## Prerequisites + +- [Node.js](https://nodejs.org) 24.11.1+ or [Bun](https://bun.sh) +- An [Archil](https://console.archil.com) account +- [Docker](https://docs.docker.com/get-docker/), only to build an [Image](/archil/compute/images) from a Dockerfile. Programs and public images don't need it. + +## Install + + + +## Add the provider + +Add `Archil.providers()` next to your other providers: + +```typescript title="alchemy.run.ts" +import * as Alchemy from "alchemy"; +import * as Archil from "@alchemy.run/archil"; +import * as Effect from "effect/Effect"; + +export default Alchemy.Stack( + "MyApp", + { providers: Archil.providers(), state: Alchemy.localState() }, + Effect.gen(function* () { + // your resources + }), +); +``` + +With a second cloud, merge them: `Layer.mergeAll(Cloudflare.providers(), Archil.providers())`. + +## Create an API key + +Sign in at [console.archil.com](https://console.archil.com), select the account or organization you deploy to, and create a key under **API Keys**. It starts with `key-`. Archil shows it once. + +## Store it in a profile + +```sh +alchemy profile edit --add Archil +``` + +Paste the key, and pick the region your disks live in (`aws-us-east-1` by default). Enter your organization id only if you keep disks on your own S3 bucket. + +## Deploy from CI + +Set the key in the environment. It takes precedence over any profile: + +```sh +ARCHIL_API_KEY=key-... ARCHIL_REGION=aws-us-east-1 alchemy deploy +``` + +See [Organization and keys](/archil/organization-and-keys) for profiles per environment and what each host gets instead of your key. diff --git a/.agents/skills/alchemy/references/archil/storage/branches.md b/.agents/skills/alchemy/references/archil/storage/branches.md new file mode 100644 index 00000000..39250e37 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/storage/branches.md @@ -0,0 +1,82 @@ + + +# Branches and checkpoints + +> Seed a disk once, checkpoint it at deploy time, and copy a writable branch per session in milliseconds. + +A **checkpoint** is a named snapshot of a disk. It takes about 15 ms whatever the disk's size, and never changes once taken. A **branch** is a writable copy of a disk started from a checkpoint, in about 35 ms. Writes on a branch never reach the disk or its other branches, so each agent, session or CI job can get a copy of its own. + +## Each branch shares the seed until it writes + + + +## Seed a disk and checkpoint it + +`Archil.Checkpoint` runs commands against the disk at deploy time, then takes the checkpoint in the same microVM, so it holds exactly what they produced: + +```typescript title="src/workspace.ts" +import * as Archil from "@alchemy.run/archil"; +import * as Effect from "effect/Effect"; + +export const Seed = Archil.Disk("Seed", {}); + +export const Base = Effect.gen(function* () { + const seed = yield* Seed; + return yield* Archil.Checkpoint("Base", { + disk: seed.diskId, + name: "base", + run: ["git clone --depth 1 https://github.com/acme/app repo"], + }); +}); +``` + +## Branch a disk per session + +`Archil.BranchDisk` gives a Worker or Lambda a client that creates branches while the app runs: + +```typescript +const seeds = yield* Archil.BranchDisk(Seed); +const branch = yield* seeds.branch({ name: "session-42", fromCheckpoint: "base" }); +``` + +Mount it on your own host with `MountDisk` and `branch: "session-42"`. Branches share the disk's credentials, so a disk user that mounts the disk can mount any of its branches. A sandbox can't mount a branch yet. + +## Declare a long-lived branch + +A branch that lives as long as the Stack, like a staging copy, is a resource: + +```typescript title="src/workspace.ts" +export const Staging = Effect.gen(function* () { + const seed = yield* Seed; + const base = yield* Base; + return yield* Archil.Branch("Staging", { disk: seed.diskId, fromCheckpoint: base.name }); +}); +``` + +## Fork a sandbox in milliseconds + +A sandbox's root filesystem is a disk too, so `fork` uses the same checkpoint and branch to copy a sandbox in milliseconds. A sandbox with mounted disks has to be stopped first. + +```typescript +const copy = yield* sandbox.fork({ name: "task-1-retry" }); +``` + +## Branches go when the disk does + +Archil can't delete checkpoints or branches yet. Destroying an `Archil.Checkpoint` or `Archil.Branch` removes it from Alchemy's state only, and deleting the disk deletes them with it. diff --git a/.agents/skills/alchemy/references/archil/storage/disks.md b/.agents/skills/alchemy/references/archil/storage/disks.md new file mode 100644 index 00000000..fbe45fc0 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/storage/disks.md @@ -0,0 +1,83 @@ + + +# Disks + +> Create disks per user at run time, share a few at deploy time, run commands against them, and read their files by key. + +A disk is a POSIX filesystem stored in object storage. The data clients are using sits in Archil's storage layer, in front of the bucket, so reads and writes run at disk speed while the bucket holds everything. A write is durable once `fsync` returns. The bucket is Archil's, or [your own](/archil/storage/your-own-bucket). + +## One disk, three ways in + +One disk is reachable three ways at once: mounted as a filesystem, through serverless exec, and as an S3-style bucket of objects. + + + +Create a disk for each user or session at run time, and declare the few shared ones in your Stack. + +## Create disks at run time + +`Archil.CreateDisk` gives a Worker or Lambda a client that creates disks by name: + +```typescript +const disks = yield* Archil.CreateDisk(); +const home = yield* disks.create(`user-${user}`); +``` + +Calling `create` again with the same name returns the same disk. `get`, `list`, and `delete` work on the disks this client created. + +## Declare a shared disk + +A dataset every user reads is a resource: + +```typescript +// src/Storage.ts +export const Dataset = Archil.Disk("Dataset", {}); +``` + +Restrict where it can be mounted from with `allowedIps`, and stop sandboxes and exec from mounting it with `allowSandboxMount: false`. + +## Run commands against a disk + +```typescript +const dataset = yield* Archil.ExecDisk(Dataset); +const result = yield* dataset.exec("wc -l /mnt/archil/*.csv"); +const hits = yield* dataset.grep({ pattern: "TODO", directory: "src", recursive: true }); +``` + +`ExecDisks` mounts several disks in one call, at paths under `/mnt/archil`. + +## Read and write files without a machine + +Every disk is also an S3-style bucket. `ReadDisk`, `WriteDisk`, and `ReadWriteDisk` use it: + +```typescript +const files = yield* Archil.ReadWriteDisk(Dataset); +yield* files.put("notes/today.md", "# Today"); +const url = yield* files.share("notes/today.md", 3600); +``` + +A write that conflicts with a mounted client's lock fails with `ObjectConflict`. + +## Branch it, or keep it in your bucket + +Copy a disk per session from a checkpoint with [Branches and checkpoints](/archil/storage/branches). Keep a disk's files as ordinary objects in your S3 bucket with [Your own bucket](/archil/storage/your-own-bucket). diff --git a/.agents/skills/alchemy/references/archil/storage/mounting.md b/.agents/skills/alchemy/references/archil/storage/mounting.md new file mode 100644 index 00000000..c8ab4a56 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/storage/mounting.md @@ -0,0 +1,145 @@ + + +# Mounting + +> Mount Archil disks in program sandboxes, your own Containers, and ECS tasks. + +`Archil.MountDisk(disk, { path, mode })` returns a mount reference: the fields of a sandbox `mounts` entry, plus `mount()`. Where it mounts depends on the host it's bound to. + +## Mount it in a program sandbox + +An [`Archil.Sandbox` with `main`](/archil/compute/programs) mounts the disk itself. The binding adds it to the sandbox's mounts, and the disk is there when the program starts: + +```typescript +const dataset = yield* Archil.MountDisk(Dataset, { path: "/data", mode: "read-only" }); +const names = yield* fs.readDirectory(dataset.path); +``` + +## Mount it on your own hosts + +On a Cloudflare Container or an ECS task on EC2, the binding installs the Archil client into the host's image, and the plan fails if the host can't provide FUSE. `mount()` runs the client: + +```typescript +export default class Indexer extends Cloudflare.Container()( + "Indexer", + { main: import.meta.url }, + Effect.gen(function* () { + const dataset = yield* Archil.MountDisk(Dataset, { path: "/data", mode: "read-only" }); + const fs = yield* FileSystem.FileSystem; + return { + fetch: Effect.scoped( + Effect.gen(function* () { + const path = yield* dataset.mount(); + const entries = yield* fs.readDirectory(path); + return yield* HttpServerResponse.json(entries); + }), + ), + }; + }).pipe(Effect.provide(Archil.MountDiskLive)), +) {} +``` + +The mount lasts as long as its scope. Closing the scope flushes writes and unmounts. + +The host gets a disk token for `Dataset` only, so it can't mount any other disk and never holds an API key. With `mode: "read-only"` the token is read-only too. + +## Start the Container with internet access + +The Archil client talks to Archil over the network, and a Cloudflare Container has no outbound network unless the Durable Object that starts it asks for one: + +```typescript +export class IndexerObject extends Cloudflare.DurableObject()( + "IndexerObject", + Effect.gen(function* () { + const indexer = yield* Indexer; + return Effect.gen(function* () { + const { fetch } = yield* indexer.getTcpPort(3000); + return { + list: () => + Effect.gen(function* () { + yield* indexer.start({ enableInternet: true }); + const response = yield* fetch(HttpClientRequest.get("http://container/")); + return yield* response.text; + }), + }; + }); + }), +) {} +``` + +Without `enableInternet: true`, `mount` fails after 60 seconds with the client's output. + +## Mount disks named at run time + +`MountDisk()` takes the disk and its token per call, e.g. from a Worker that created the disk: + +```typescript +const archil = yield* Archil.MountDisk(); +const path = yield* archil.mount({ disk: job.diskId, token: job.token, path: "/work" }); +``` + +The Worker makes the token with `home.createToken(name)` and revokes it with `home.removeToken(id)`. + +## Share a disk between hosts + +`mode` picks how this mount shares the disk. An `exclusive` mount, the default, locks the whole disk for one writer, and every other client can only mount it read-only: + + + +```typescript +const dataset = yield* Archil.MountDisk(Dataset, { path: "/data", mode: "shared" }); +``` + +`exclusive` (the default) owns writes; `shared` lets many clients mount and write only paths they check out; `conditional` lets many clients write anywhere; `read-only` never writes. Mount a branch with `branch: "session-42"`. `shared`, `branch`, and `force` are FUSE-client options: a sandbox mounts with `exclusive`, `conditional`, or `read-only`, and takes `queueMs`. + +## Pass a mount to a sandbox + +A mount reference has the same fields as a sandbox `mounts` entry, so it goes straight into a sandbox created at run time: + +```typescript +const workspace = yield* Archil.MountDisk(Workspace, { path: "/workspace", mode: "conditional" }); +const sandboxes = yield* Archil.CreateSandbox(); +const sandbox = yield* sandboxes.create({ name: `task-${id}`, mounts: [workspace] }); +``` + +## Mount it in an ECS task + +ECS tasks need the EC2 launch type, since Fargate has no FUSE: + +```typescript +export default class Reader extends AWS.ECS.Task()( + "Reader", + { main: import.meta.url, port: 3000, requiresCompatibilities: ["EC2"], networkMode: "bridge" }, + Effect.gen(function* () { + const dataset = yield* Archil.MountDisk(Dataset, { path: "/data", mode: "read-only" }); + const fs = yield* FileSystem.FileSystem; + return { + fetch: Effect.scoped( + Effect.gen(function* () { + const path = yield* dataset.mount(); + const entries = yield* fs.readDirectory(path); + return yield* HttpServerResponse.json(entries); + }), + ), + }; + }).pipe(Effect.provide(Archil.MountDiskLive)), +) {} +``` + +Alchemy adds `/dev/fuse` and `SYS_ADMIN` to the task's container. diff --git a/.agents/skills/alchemy/references/archil/storage/your-own-bucket.md b/.agents/skills/alchemy/references/archil/storage/your-own-bucket.md new file mode 100644 index 00000000..e1c5958e --- /dev/null +++ b/.agents/skills/alchemy/references/archil/storage/your-own-bucket.md @@ -0,0 +1,73 @@ + + +# Your own bucket + +> Keep a disk's files as ordinary objects in your own S3, R2, GCS or Azure bucket, with no keys for S3. + +A disk can keep its files in a bucket you own instead of Archil's. Archil still keeps the data in use in its storage layer, and copies writes to your bucket in the background, where they're ordinary objects any S3 tool can read without Archil. Destroying the disk leaves them there. Archil offers it on its paid plans. + +## Your bucket trusts Archil, no key needed + +On S3, the bucket's policy trusts Archil's IAM role for your region, only on behalf of disks in your organization, so no access key exists anywhere. + + + +## A disk on an S3 bucket + +`ArchilAWS.S3Disk` declares the bucket policy and the disk together: + +```typescript title="src/storage.ts" +import * as AWS from "@alchemy.run/aws"; +import * as ArchilAWS from "@alchemy.run/archil/AWS"; + +export const Store = AWS.S3.Bucket("Store", {}); +export const Dataset = ArchilAWS.S3Disk("Dataset", { bucket: Store, prefix: "datasets/" }); +``` + +The disk's files land under `datasets/` in `Store`. Your Stack needs `AWS.providers()` next to `Archil.providers()`. + +## Set your organization id in the profile + +The policy is scoped to your Archil organization, so Alchemy needs its id. Enter it in your profile: + +```sh +alchemy profile edit --add Archil +``` + +Or set `ARCHIL_ORGANIZATION` in CI. Find the id in the [console](https://console.archil.com). + +## Use another object store + +R2, Google Cloud Storage, Azure Blob and other S3-compatible stores take keys. Give them in `storage` on `Archil.Disk`: + +```typescript title="src/storage.ts" +export const Dataset = Archil.Disk("Dataset", { + storage: { + type: "r2", + bucketName: "datasets", + bucketEndpoint: "https://.r2.cloudflarestorage.com", + accessKeyId: Config.Redacted("R2_ACCESS_KEY_ID"), + secretAccessKey: Config.Redacted("R2_SECRET_ACCESS_KEY"), + }, +}); +``` + +Changing `storage` replaces the disk. + +## The bucket sees writes a little later + +Archil writes to the bucket after the write is durable in its own storage, so a tool reading the bucket directly sees a new file a little later than a client of the disk does. Read through the disk when you need the latest write. diff --git a/.agents/skills/alchemy/references/archil/tutorial/part-1.md b/.agents/skills/alchemy/references/archil/tutorial/part-1.md new file mode 100644 index 00000000..669744a5 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/tutorial/part-1.md @@ -0,0 +1,64 @@ + + +# Part 1: Set Up a Sandbox + +> Install Alchemy, and declare an Archil sandbox that clones a repository onto its disk at deploy time. + +Build an API that gives agents sandboxes. The slow setup runs once, when you deploy: a sandbox with a repository cloned onto its disk. While the app runs, every sandbox is a fork of it, already set up. + +The finished code is in [`examples/archil-sandbox`](https://github.com/alchemy-run/alchemy/tree/main/examples/archil-sandbox). + +## Prerequisites + +- [Node.js](https://nodejs.org) 24.11.1+ or [Bun](https://bun.sh) +- An Archil API key in an Alchemy profile ([Setup](/archil/setup)) + +## Create a project + + + + + +## Declare the sandbox + +```typescript title="src/Golden.ts" +import * as Archil from "@alchemy.run/archil"; + +export const Golden = Archil.Sandbox("Golden", { + run: ["git clone --depth 1 https://github.com/sindresorhus/is /work/is"], +}); +``` + +A sandbox is a Firecracker microVM whose root filesystem is a disk of its own. At deploy, Alchemy creates `Golden` and runs the `run` commands in it, in order. A command that exits non-zero fails the deploy. + +## Create the Stack + +```typescript title="alchemy.run.ts" +import * as Archil from "@alchemy.run/archil"; +import * as Alchemy from "alchemy"; +import * as Effect from "effect/Effect"; +import { Golden } from "./src/Golden.ts"; + +export default Alchemy.Stack( + "ArchilSandboxExample", + { providers: Archil.providers(), state: Alchemy.localState() }, + Effect.gen(function* () { + const golden = yield* Golden; + return { sandbox: golden.name }; + }), +); +``` + +`Archil.providers()` reads your key from your Alchemy profile. + +## Deploy + + + +`Golden` shows up under **Sandboxes** in the [Archil console](https://console.archil.com), with the repository in `/work/is`. A deploy that leaves the commands unchanged leaves it alone. When it's idle, it pauses. + +## Next + +[Part 2](/archil/tutorial/part-2) forks it while the app runs. diff --git a/.agents/skills/alchemy/references/archil/tutorial/part-2.md b/.agents/skills/alchemy/references/archil/tutorial/part-2.md new file mode 100644 index 00000000..400b7368 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/tutorial/part-2.md @@ -0,0 +1,83 @@ + + +# Part 2: Fork It for Each Request + +> A program in its own Archil sandbox that forks the set-up sandbox for each request, runs a command, and deletes the fork. + +## Bind CreateSandbox to the sandbox + +```typescript title="src/Api.ts" +import * as Archil from "@alchemy.run/archil"; +import * as Effect from "effect/Effect"; +import { Golden } from "./Golden.ts"; + +export default class Api extends Archil.Sandbox()( + "Api", + { main: import.meta.url, port: 3000 }, + Effect.gen(function* () { + const sandboxes = yield* Archil.CreateSandbox(Golden); + return {}; + }).pipe(Effect.provide(Archil.CreateSandboxHttp)), +) {} +``` + +`Api` is a program Alchemy runs in an Archil sandbox of its own, at a public URL. Bound to `Golden`, every sandbox this client creates is a fork of it: its memory and disk, with the repository already cloned. + +## Run a command in a fresh fork + +```diff lang="typescript" +// src/Api.ts + const sandboxes = yield* Archil.CreateSandbox(Golden); ++ ++ const run = Effect.fn("run")(function* (command: string) { ++ const id = (yield* Random.nextIntBetween(0, 2 ** 31)).toString(36); ++ const sandbox = yield* Effect.acquireRelease(sandboxes.create({ name: `run-${id}` }), (sandbox) => ++ Effect.ignore(sandbox.delete()), ++ ); ++ return yield* sandbox.exec(command, { cwd: "/work/is" }); ++ }); +``` + +A fork takes a fraction of a second whatever the disk's size, and writes to it never reach `Golden`. `acquireRelease` deletes the fork when the request's scope closes. + +## Serve it + +```diff lang="typescript" +// src/Api.ts +- return {}; ++ return { ++ fetch: Effect.gen(function* () { ++ const request = yield* HttpServerRequest; ++ const url = new URL(request.url, "http://api"); ++ if (request.method === "POST" && url.pathname === "/run") { ++ return yield* HttpServerResponse.json(yield* run(yield* request.text).pipe(Effect.scoped)); ++ } ++ return HttpServerResponse.text("not found", { status: 404 }); ++ }).pipe(Effect.orDie), ++ }; +``` + +## Deploy it + +```diff lang="typescript" +// alchemy.run.ts + Effect.gen(function* () { + const golden = yield* Golden; +- return { sandbox: golden.name }; ++ const api = yield* Api; ++ return { sandbox: golden.name, url: api.url }; + }), +``` + + + +`Golden` is unchanged, so this deploy only adds the program. + +## Next + +[Part 3](/archil/tutorial/part-3) gives each user a fork of their own. diff --git a/.agents/skills/alchemy/references/archil/tutorial/part-3.md b/.agents/skills/alchemy/references/archil/tutorial/part-3.md new file mode 100644 index 00000000..64790720 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/tutorial/part-3.md @@ -0,0 +1,56 @@ + + +# Part 3: A Fork per User + +> Give each user an Archil fork of the set-up sandbox, found again by name, which keeps their changes. + +## Fork Golden for a user + +```diff lang="typescript" +// src/Api.ts ++ const userSandbox = Effect.fn("userSandbox")(function* (user: string) { ++ return (yield* sandboxes.get(`user-${user}`)) ?? (yield* sandboxes.create({ name: `user-${user}` })); ++ }); +``` + +A user's first request forks `Golden`, with the repository already cloned. The fork is named after the user, so `sandboxes.get` finds it again on their next request. + +## Their changes stay in their fork + +```diff lang="typescript" +// src/Api.ts ++ const match = /^\/users\/([a-z0-9-]+)\/files\/(.+)$/.exec(url.pathname); ++ if (match !== null) { ++ const sandbox = yield* userSandbox(match[1]!); ++ const path = `/work/is/${match[2]}`; ++ if (request.method === "PUT") yield* sandbox.files.write(path, yield* request.text); ++ return yield* HttpServerResponse.json({ content: yield* sandbox.files.readText(path) }); ++ } +``` + +Each user edits their own copy of the repository. `Golden` never changes, so the next fork doesn't see their edits. A fork pauses when it's idle, keeping its memory, and resumes on the user's next request. + + + +## Delete a user's fork + +```diff lang="typescript" +// src/Api.ts ++ const user = /^\/users\/([a-z0-9-]+)$/.exec(url.pathname)?.[1]; ++ if (request.method === "DELETE" && user !== undefined) { ++ yield* sandboxes.delete(`user-${user}`); ++ return HttpServerResponse.empty({ status: 204 }); ++ } +``` + +Forks the program creates carry its name prefix and aren't deleted with the Stack, so delete them when their owner goes away. + +## Next + +[Part 4](/archil/tutorial/part-4) changes the sandbox. diff --git a/.agents/skills/alchemy/references/archil/tutorial/part-4.md b/.agents/skills/alchemy/references/archil/tutorial/part-4.md new file mode 100644 index 00000000..8b30753f --- /dev/null +++ b/.agents/skills/alchemy/references/archil/tutorial/part-4.md @@ -0,0 +1,37 @@ + + +# Part 4: Update the Sandbox + +> Change the commands that set up the Archil sandbox, redeploy, and see new forks start from the new one while existing forks keep theirs. + +## Add a command + +Clone a second repository onto `Golden`: + +```diff lang="typescript" +// src/Golden.ts +export const Golden = Archil.Sandbox("Golden", { + run: [ + "git clone --depth 1 https://github.com/sindresorhus/is /work/is", ++ "git clone --depth 1 https://github.com/sindresorhus/slugify /work/slugify", + ], +}); +``` + +## Deploy the new sandbox + + + +The commands changed, so Alchemy replaces `Golden`: it creates a new sandbox, runs every command in it, and deletes the old one. The program forks whatever `Golden` is now, and isn't redeployed. + + + +## Existing forks keep theirs + +A fork is a copy taken when it was created. Users who already have one keep it, with their changes and without `slugify`. Users who arrive after the deploy fork the new `Golden`. To move a user onto it, delete their fork; their next request forks it again. + +## Next + +[Part 5](/archil/tutorial/part-5) tests it. diff --git a/.agents/skills/alchemy/references/archil/tutorial/part-5.md b/.agents/skills/alchemy/references/archil/tutorial/part-5.md new file mode 100644 index 00000000..708841e3 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/tutorial/part-5.md @@ -0,0 +1,80 @@ + + +# Part 5: Testing + +> Deploy the Stack in a test, fork the set-up sandbox, and check what the fork contains. + +## Install the test harness + + + +## Deploy once per test file + +`Test.make` takes the same providers and state as your Stack: + +```typescript title="test/integ.test.ts" +import { expect } from "bun:test"; +import * as Archil from "@alchemy.run/archil"; +import * as Test from "@alchemy.run/test/Bun"; +import * as Alchemy from "alchemy"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; +import * as Schedule from "effect/Schedule"; +import Stack from "../alchemy.run.ts"; + +const { test, beforeAll, afterAll, deploy, destroy } = Test.make({ + providers: Archil.providers(), + state: Alchemy.localState(), + profile: process.env.ALCHEMY_PROFILE, +}); + +const stack = beforeAll(deploy(Stack), { timeout: 300_000 }); +afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack), { timeout: 180_000 }); +``` + +The test deploys the Stack to a stage of its own, `Golden` included, and destroys it afterwards. + +## Retry while the program starts + +A new program sandbox can take a few seconds to answer: + +```typescript title="test/integ.test.ts" +const run = (url: string, command: string) => + Effect.gen(function* () { + const client = yield* HttpClient.HttpClient; + const res = yield* client.execute(HttpClientRequest.post(`${url}/run`).pipe(HttpClientRequest.bodyText(command))).pipe( + Effect.flatMap((res) => (res.status >= 500 ? Effect.fail(new Error(`HTTP ${res.status}`)) : Effect.succeed(res))), + Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 20 }), + ); + return (yield* res.json) as { stdout: string; exitCode: number }; + }); +``` + +## Check a fork starts from Golden + +```typescript title="test/integ.test.ts" +test( + "forks Golden for each request", + Effect.gen(function* () { + const { url } = yield* stack; + const both = yield* run(url, "ls .."); + expect(both.stdout).toContain("slugify"); + }), + { timeout: 300_000 }, +); +``` + +`slugify` is only there if the fork came from the new `Golden`. The program deletes the fork when the request ends, so none is left behind. + +## Run it + + + +Set `NO_DESTROY=1` to keep the deployment between runs while you iterate. + +## Next + +[Part 6](/archil/tutorial/part-6) deploys more copies, from CI. diff --git a/.agents/skills/alchemy/references/archil/tutorial/part-6.md b/.agents/skills/alchemy/references/archil/tutorial/part-6.md new file mode 100644 index 00000000..baf61301 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/tutorial/part-6.md @@ -0,0 +1,95 @@ + + +# Part 6: Stages and CI + +> Deploy a stage per environment and per pull request, each with its own set-up Archil sandbox and program, from GitHub Actions. + +## Deploy another stage + + + +Each stage gets its own `Golden` sandbox, set up by its own commands, and its own program at its own URL, so changing `Golden` in one stage never reaches another. Without `--stage`, Alchemy deploys to `live_$USER`. + +## Move state somewhere CI can read + +A runner can't see your `.alchemy/` directory, and Archil has no state store of its own. Use a remote one, such as a [Postgres](/state-store#postgres-state-store) database you already run (install `@alchemy.run/sql` and `@effect/sql-pg`): + +```diff lang="typescript" +// alchemy.run.ts ++import { postgresState } from "@alchemy.run/sql/PostgresState"; ++import * as Config from "effect/Config"; + +export default Alchemy.Stack( + "ArchilSandboxExample", +- { providers: Archil.providers(), state: Alchemy.localState() }, ++ { ++ providers: Archil.providers(), ++ state: postgresState({ url: Config.Redacted("STATE_DATABASE_URL") }), ++ }, +``` + +`Cloudflare.state()`, `AWS.state()` and `GCP.state()` work too if you already use that cloud. See [State stores](/state-store). + +## Store your key in GitHub + +Archil creates API keys only in the console, so CI uses one you create there. Create a key for CI under **API Keys**, then store it and the state database URL as repository secrets: + + + +`Archil.providers()` reads `ARCHIL_API_KEY` (and `ARCHIL_REGION`, if set) from the environment when no profile is selected. + +## Deploy per pull request + +```yaml +# .github/workflows/deploy.yml +name: Deploy +on: + push: + branches: [main] + pull_request: + types: [opened, reopened, synchronize, closed] + +concurrency: + group: deploy-${{ github.ref }} + cancel-in-progress: false + +env: + STAGE: >- + ${{ github.event_name == 'pull_request' + && format('pr-{0}', github.event.number) + || 'prod' }} + ARCHIL_API_KEY: ${{ secrets.ARCHIL_API_KEY }} + STATE_DATABASE_URL: ${{ secrets.STATE_DATABASE_URL }} + +jobs: + deploy: + if: github.event.action != 'closed' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: oven-sh/setup-bun@v2 + - run: bun install + - run: bun alchemy deploy --stage ${{ env.STAGE }} --yes + + cleanup: + if: github.event_name == 'pull_request' && github.event.action == 'closed' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: oven-sh/setup-bun@v2 + - run: bun install + - name: Refuse to destroy prod + run: test "${{ env.STAGE }}" != "prod" + - run: bun alchemy destroy --stage ${{ env.STAGE }} --yes +``` + +Pull requests deploy to `pr-`, each with its own `Golden`, and `main` deploys to `prod`. The cleanup job destroys a closed pull request's stage, and refuses to destroy `prod`. + +## Rotate the key + +Archil can't scope or expire API keys. To rotate one, create a new key in the console, run `gh secret set ARCHIL_API_KEY` again, redeploy, then delete the old key. diff --git a/.agents/skills/alchemy/references/archil/what-is-archil.md b/.agents/skills/alchemy/references/archil/what-is-archil.md new file mode 100644 index 00000000..3dc10094 --- /dev/null +++ b/.agents/skills/alchemy/references/archil/what-is-archil.md @@ -0,0 +1,149 @@ + + +# What is Archil? + +> The concepts behind Archil — organizations and API keys, regions, disks, serverless exec, sandboxes, images, mounts, disk users, branches and egress policy — and how @alchemy.run/archil models each of them. + +Archil runs code against your data. Your files live on **disks**, POSIX filesystems backed by object storage. Archil runs code against a disk in a Firecracker microVM, either one call at a time (serverless exec) or in a sandbox that stays around. Any other Linux machine can mount the disk too. Every disk, sandbox and image belongs to an organization and lives in one region. + +Take one small app: a `Dataset` disk of CSV files. A Cloudflare Worker counts their rows with a serverless call. An `Api` sandbox serves them at a public URL. A Container you run elsewhere mounts the disk to index it. The disk keeps recent data on Archil's fast storage and the rest in its bucket. + + + +## Organizations: who owns the disks + +A personal account or an **organization** owns your disks, sandboxes and images, and the bill for them. An organization lets a team share disks: its members can manage them, and its administrators manage the members. + +Archil's control plane takes an **API key**, created in the console. A key works for one account or organization in one region, and can call every operation there. Archil can't create narrower keys, so Alchemy deploys with yours. + + + +See [Organization and keys](/archil/organization-and-keys). + +## Regions: where data and code run together + +A **region** is where a disk's data and the microVMs that use it run: `aws-us-east-1`, `aws-us-west-2`, `aws-eu-west-1` or `gcp-us-central1`. Serverless exec and sandboxes run only in the AWS regions, so keep a disk you run code against in one of them. + +Your profile sets the region for everything the Stack deploys, and asks for it when you add Archil. + +## Disks: a local filesystem in object storage + +A **disk** is a filesystem that behaves like a local one (POSIX, git, SQLite), stored in object storage. The data a client is using sits in Archil's storage layer in front of the bucket, so reads and writes are fast, and the bucket holds everything. The bucket is Archil's unless you bring your own. + +```typescript title="src/storage.ts" +export const Dataset = Archil.Disk("Dataset", {}); +``` + +The same disk is also an S3-style bucket, so a host can read and write its files by key without mounting it. + +See [Disks](/archil/storage/disks). + +## Serverless exec: one command, one microVM + +**Serverless exec** runs one command against a disk: Archil boots a microVM with the disk at `/mnt/archil`, runs the command to completion (up to five minutes), and shuts it down. Each call is one charge, and a disk takes many calls at once. Files the command writes stay on the disk. + +```typescript +const dataset = yield* Archil.ExecDisk(Dataset); +const result = yield* dataset.exec("wc -l /mnt/archil/*.csv"); +``` + +That makes it the natural place for an agent's shell tool, or a search across a large dataset. + +See [Choosing a runtime](/archil/compute/choosing-a-runtime). + +## Sandboxes: microVMs that pause and resume + +A **sandbox** is a microVM that stays around between calls. Its root filesystem is a disk of its own, it can mount other disks, and its ports can be public. It pauses when idle, keeping its memory and processes, and resumes on the next connection. A fork copies it, memory and all. + +```typescript title="src/devbox.ts" +export const DevBox = Archil.Sandbox("DevBox", { + mounts: [{ disk: Workspace, path: "/workspace" }], + ports: [3000], +}); +``` + +Give a sandbox a `main`, and it runs your program at a public `https://` URL. + +See [Sandboxes](/archil/compute/sandboxes) and [Programs](/archil/compute/programs). + +## Images: what a sandbox boots + +A sandbox boots an **image**: any public OCI image, or one Archil pulls from your private registry. Archil doesn't build images, so a Dockerfile is built on your machine and pushed to a registry first. `Archil.Image` pins one by digest: + +```typescript +export const Base = Archil.Image("Base", { image: "node:24-bookworm" }); +``` + +See [Images](/archil/compute/images). + +## Mounts: a disk at a path, on any machine + +A **mount** puts a disk at a path, in a sandbox or on any Linux machine running Archil's FUSE client. Its **mode** decides who can write: `exclusive` (the default) gives one client the whole disk, `conditional` lets many write anywhere, `shared` lets many write the paths they check out, and `read-only` never writes. + +```typescript +const dataset = yield* Archil.MountDisk(Dataset, { path: "/data", mode: "read-only" }); +``` + +See [Mounting](/archil/storage/mounting). + +## Disk users: access to one disk + +A **disk user** is access to one disk: a mount token, an S3 key pair, or an AWS role that mounts with its own identity. Archil checks it itself, so a host holding one can't reach any other disk. Alchemy creates one per host for the bindings that need them: + +```typescript +const dataset = yield* Archil.ReadDisk(Dataset); +``` + +See [Credentials and bindings](/archil/security/credentials). + +## Branches: a writable copy in milliseconds + +A **checkpoint** is a named snapshot of a disk, and a **branch** is a writable copy started from one. Both take tens of milliseconds whatever the disk's size, and writes on a branch never reach its source. + +```typescript +const seeds = yield* Archil.BranchDisk(Seed); +const branch = yield* seeds.branch({ name: "session-42", fromCheckpoint: "base" }); +``` + +See [Branches and checkpoints](/archil/storage/branches). + +## Egress policy: what a sandbox can reach + +Every sandbox has an **egress policy** that Archil enforces outside the microVM. It can deny everything but a list of hosts, and add headers, like an API key, to requests on their way out, so code inside never sees the value. + +```typescript +export const MySandbox = Archil.Sandbox("MySandbox", { + network: { egress: { default: "deny", allow: ["registry.npmjs.org", "*.github.com"] } }, +}); +``` + +See [Network](/archil/security/network). + +## State: where Alchemy keeps its record + +Archil has no storage for Alchemy's own record of what each Stack created. Keep it on disk with `Alchemy.localState()`, or share it with your team and CI through `Cloudflare.state()` or `AWS.state()`. + +## How @alchemy.run/archil models these concepts + +Your profile picks the API key and the region, and `Archil.providers()` deploys into them. The few long-lived things an app shares (a dataset disk, a seeded checkpoint, an image, a dev box, a program) are resources in the Stack. Disks, sandboxes, branches and images made per user or task come from run-time bindings (`CreateDisk`, `CreateSandbox`, `BranchDisk`, `CreateImage`). Archil has no tags, so the disks and sandboxes they create carry their stack, stage and binding in a name prefix, and stay when the Stack is destroyed. Bindings that touch one disk give their host its own disk user, never your key. + +Next, build one: the [tutorial](/archil/tutorial/part-1) puts these ideas to work, one step at a time. diff --git a/.agents/skills/alchemy/references/aws/INDEX.md b/.agents/skills/alchemy/references/aws/INDEX.md index cf7c859f..679688ee 100644 --- a/.agents/skills/alchemy/references/aws/INDEX.md +++ b/.agents/skills/alchemy/references/aws/INDEX.md @@ -1,12 +1,15 @@ # aws index -54 pages. Build AWS applications with Alchemy — a runtime (usually Lambda) plus typed resources, wired together by bindings that mint least-privilege IAM policies. +62 pages. Build on AWS with Alchemy. Declare Lambda Functions, containers, tables, buckets and queues in TypeScript, and let bindings write each runtime's IAM policy from the calls its code makes. | Page | File | Covers | | --- | --- | --- | -| AWS | `_overview.md` | Build AWS applications with Alchemy — a runtime (usually Lambda) plus typed resources, wired together by bindings that mint least-privilege IAM policies. | +| AWS | `_overview.md` | Build on AWS with Alchemy. Declare Lambda Functions, containers, tables, buckets and queues in TypeScript, and let bindings write each runtime's IAM policy from the calls its code makes. | +| Accounts and regions | `accounts-and-regions.md` | How AWS accounts isolate resources, how regions and Availability Zones place them, and how profiles and stages choose where each Alchemy deploy goes. | +| IAM and bindings | `iam.md` | How IAM identities, roles, trust, resource-based policies and tag-based access (ABAC) work on AWS, and how Alchemy bindings write each runtime's least-privilege policies from the calls its code makes. | | Local development | `local-development.md` | alchemy dev runs your AWS stack on your machine — Lambda in Docker containers, local S3/DynamoDB/SQS, event sources firing, hot reload — with no AWS account or credentials required. | -| Setup | `setup.md` | Connect Alchemy to AWS with SSO, stored access keys, or CI environment credentials. | +| Setup | `setup.md` | Connect Alchemy to AWS with SSO, console login, stored access keys, or CI environment credentials. | +| What is AWS? | `what-is-aws.md` | The concepts behind AWS — accounts, regions, IAM identities and policies, resources and ARNs, runtimes, event sources, VPCs and the edge — and how @alchemy.run/aws models each of them. | ## ai/ @@ -27,13 +30,17 @@ | Page | File | Covers | | --- | --- | --- | -| Choosing a runtime | `compute/choosing-a-runtime.md` | Lambda vs ECS vs EKS vs EC2 for Alchemy apps — cold starts, cost shape, packaging, and how much of each Alchemy currently covers. | -| EC2 | `compute/ec2.md` | Launch virtual machines with the Instance resource — as a raw compute primitive, or hosting a bundled long-lived Effect program served straight off the box. | -| ECS | `compute/ecs.md` | Run containers on AWS with ECS and Fargate — Task definitions that run to completion, Services that keep containers running behind a load balancer, with images bundled from an Effect program, built from your Dockerfile, or mirrored from a registry. | +| Choosing a runtime | `compute/choosing-a-runtime.md` | How Lambda Functions, Lambda Web Functions, ECS, EKS and EC2 differ in how they run your code, scale and cost, and how to choose one for each part of an app. | +| EC2 | `compute/ec2.md` | How EC2 instances give you a whole virtual machine, how to launch one from an image into a subnet, how to run your Effect program on it as a service, and how to reach it. | +| ECS Sandboxes | `compute/ecs-sandboxes.md` | Create a Nitro Sandbox per user or session on ECS from a Lambda Function, then run commands, use files, open terminals and call ports in it through a typed handle. | +| ECS | `compute/ecs.md` | How ECS runs containers on Fargate through clusters, task definitions, tasks and services, and how to run a server, a one-off job or a scheduled job from an image, a Dockerfile or an Effect program. | +| Effect workflows | `compute/effect-workflows.md` | Run Effect workflows on AWS Lambda durable functions. Host them in an AWS.Lambda.WorkflowFunction, start runs from other functions with AWS.Lambda.DurableFunctionEngine, and let them sleep and wait durably. | | EKS | `compute/eks.md` | Stand up an EKS Auto Mode cluster on a Network and run containers on it — Deployments for servers, Jobs for run-to-completion work, Manifests for everything else. No YAML, no kubectl. | | HyperPod | `compute/hyperpod.md` | Provision SageMaker HyperPod clusters — Slurm or EKS orchestrated — and run ML workloads on them with sbatch, raw manifests, or effectful Jobs with task governance. | -| Lambda | `compute/lambda.md` | Stand up an AWS Lambda Function from a single Effect, expose it over a Function URL, and call it from a test. | +| Lambda | `compute/lambda.md` | How a Lambda Function runs your code per invocation, how it's invoked over a Function URL, by events or by other code, and how construction, timeouts and configuration work. | | Lambda MicroVMs | `compute/microvms.md` | Build a Firecracker MicroVM image from TypeScript or a Dockerfile, then launch and drive isolated stateful instances from a Lambda Function with typed lifecycle bindings and RPC. | +| Nitro Sandboxes | `compute/nitro-sandboxes.md` | How Nitro Sandboxes run each ECS task, EKS pod or self-managed workload in its own lightweight VM on your EC2 instances, the difference between isolated and confidential modes, and how to turn them on for ECS, EKS and EC2. | +| Lambda Web Functions | `compute/web-functions.md` | Run an HTTP server on AWS Lambda Web Functions — an Effect fetch handler or any Node server, with streaming responses, many concurrent requests per environment, and a built-in HTTPS endpoint. | ## data/ @@ -41,9 +48,9 @@ | --- | --- | --- | | Drizzle + Aurora PostgreSQL | `data/drizzle-aurora.md` | Drizzle on Lambda with private Aurora PostgreSQL, IAM authentication, verified TLS, and reviewed SQL migrations. | | Drizzle + Aurora DSQL | `data/drizzle-dsql.md` | Drizzle on Lambda with Aurora DSQL, a non-admin database role, verified TLS, and an explicit DSQL migration boundary. | -| DynamoDB | `data/dynamodb.md` | Add a DynamoDB Table, bind GetItem and PutItem to your Lambda, and serve a typed key/value HTTP API backed by DynamoDB. | -| RDS & Aurora | `data/rds.md` | Stand up an Aurora cluster in one call with the Aurora helper, connect from Lambda over the Connect binding with pg, or skip connections entirely with the Data API. | -| S3 | `data/s3.md` | Add an S3 Bucket to your Stack, bind PutObject and GetObject as runtime capabilities, and let Alchemy mint the IAM policy for you. | +| DynamoDB | `data/dynamodb.md` | How DynamoDB Tables store items under partition and sort keys, how to design keys and indexes for the reads you need, and how runtimes read, write and react to items through bindings. | +| RDS & Aurora | `data/rds.md` | How RDS and Aurora run Postgres and MySQL inside your VPC, how the Aurora helper creates a cluster with its secret, subnets and instances, and how runtimes connect, migrate and scale it. | +| S3 | `data/s3.md` | How S3 Buckets hold objects under keys, how a runtime reads and writes them through bindings, and how to share, react to and serve the objects you store. | ## email/ @@ -56,53 +63,54 @@ | Page | File | Covers | | --- | --- | --- | -| Astro | `frontend/astro.md` | Deploy an Astro app to AWS with AWS.Website.Astro — SSR on a streaming Lambda Function URL, static output on S3 + CloudFront, and Astro's own dev server under alchemy dev. | -| Foldkit | `frontend/foldkit.md` | Deploy a Foldkit app to AWS with AWS.Website.Foldkit — the client build on S3 + CloudFront, SPA deep links by default, and Foldkit's own Vite dev server under alchemy dev. | +| Astro | `frontend/astro.md` | Deploy an Astro app to AWS with AWS.Website.Astro — SSR on a Lambda Web Function, static output on S3 + CloudFront, and Astro's own dev server under alchemy dev. | +| Foldkit | `frontend/foldkit.md` | Deploy Foldkit SPA, SSR, SSG, and hybrid applications to AWS with native local development. | | Full-stack TanStack Start + RPC + Drizzle | `frontend/full-stack-tanstack-rpc-drizzle.md` | Build a reactive full-stack app on AWS — a TanStack Start UI on CloudFront and Lambda that drives an Effect RPC Lambda over Drizzle and Aurora DSQL, with browser state wired through Effect 4's native atom RPC. | -| Next.js | `frontend/nextjs.md` | Deploy a Next.js app to AWS with AWS.Website.Nextjs — the OpenNext serverless topology with streaming SSR, image optimization, and ISR wiring, plus next dev under alchemy dev. | -| Nuxt | `frontend/nuxt.md` | Deploy a Nuxt app to AWS with AWS.Website.Nuxt — nitro's aws-lambda preset on a streaming Lambda Function URL, S3 assets behind CloudFront, and Nuxt's own dev server under alchemy dev. | -| Octane | `frontend/octane.md` | Deploy an OctaneJS app to AWS with AWS.Website.Octane — SSR on a streaming Lambda Function URL, assets on S3 + CloudFront, and Octane's own Vite dev server under alchemy dev. | -| React Router | `frontend/react-router.md` | Deploy React Router v7 (framework mode) to AWS with AWS.Website.ReactRouter — SSR on a streaming Lambda Function URL, client assets on S3 + CloudFront, and React Router's own Vite dev server under alchemy dev. | -| SolidStart | `frontend/solidstart.md` | Deploy a SolidStart app to AWS with AWS.Website.SolidStart — nitro's aws-lambda preset on a streaming Lambda Function URL, S3 assets behind CloudFront, and SolidStart's own Vite dev server under alchemy dev. | +| Next.js | `frontend/nextjs.md` | Deploy a Next.js app to AWS with AWS.Website.Nextjs — Next's own server on a Lambda Web Function with a shared S3 cache, S3 assets behind CloudFront, and next dev under alchemy dev. | +| Nuxt | `frontend/nuxt.md` | Deploy a Nuxt app to AWS with AWS.Website.Nuxt — the nitro server on a Lambda Web Function, S3 assets behind CloudFront, and Nuxt's own dev server under alchemy dev. | +| Octane | `frontend/octane.md` | Deploy an OctaneJS app to AWS with AWS.Website.Octane — SSR on a Lambda Web Function, assets on S3 + CloudFront, and Octane's own Vite dev server under alchemy dev. | +| React Router | `frontend/react-router.md` | Deploy React Router v8 (framework mode) to AWS with AWS.Website.ReactRouter — SSR on a Lambda Web Function, client assets on S3 + CloudFront, and React Router's own Vite dev server under alchemy dev. | +| SolidStart | `frontend/solidstart.md` | Deploy a SolidStart app to AWS with AWS.Website.SolidStart — SSR on a Lambda Web Function, S3 assets behind CloudFront, and SolidStart's own Vite dev server under alchemy dev. | | Static sites | `frontend/static-site.md` | Ship a static site to S3 + CloudFront with AWS.Website.StaticSite — build-step support, Router composition, and cache invalidation on deploy. | -| SvelteKit | `frontend/sveltekit.md` | Deploy a SvelteKit app to AWS with AWS.Website.SvelteKit — SSR on a streaming Lambda Function URL, assets and prerendered pages on S3 + CloudFront, and Kit's own dev server under alchemy dev. | -| TanStack Start | `frontend/tanstack-start.md` | Deploy TanStack Start (React or Solid) to AWS with AWS.Website.TanStackStart — SSR on a streaming Lambda Function URL, client assets on S3 + CloudFront, and TanStack Start's own Vite dev server under alchemy dev. | +| SvelteKit | `frontend/sveltekit.md` | Deploy a SvelteKit app to AWS with AWS.Website.SvelteKit — SSR on a Lambda Web Function, assets and prerendered pages on S3 + CloudFront, and Kit's own dev server under alchemy dev. | +| TanStack Start | `frontend/tanstack-start.md` | Deploy TanStack Start (React or Solid) to AWS with AWS.Website.TanStackStart — SSR on a Lambda Web Function, client assets on S3 + CloudFront, and TanStack Start's own Vite dev server under alchemy dev. | | Vinext | `frontend/vinext.md` | Deploy vinext to AWS with the shared Website API, native local development, and a platform-specific data cache. | | React SPA | `frontend/vite-spa.md` | Deploy a React single-page app to AWS with AWS.Website.Vite — the Vite build on S3 + CloudFront, deep links answered by index.html out of the box, and Vite's own dev server under alchemy dev. | | Vite | `frontend/vite.md` | Deploy a plain Vite app to AWS with AWS.Website.Vite — the vite build output on S3 behind CloudFront, SPA fallback at the edge, and Vite's own dev server under alchemy dev. | | Vue | `frontend/vue.md` | Deploy a Vue single-page app to AWS with AWS.Website.Vite — S3 + CloudFront, deep links that work by default, and Vue's own Vite dev server under alchemy dev. | -| Waku | `frontend/waku.md` | Deploy a Waku app to AWS with AWS.Website.Waku — RSC server on a streaming Lambda Function URL, SSG pages and assets on S3 + CloudFront, and Waku's own dev server under alchemy dev. | +| Waku | `frontend/waku.md` | Deploy a Waku app to AWS with AWS.Website.Waku — RSC server on a Lambda Web Function, SSG pages and assets on S3 + CloudFront, and Waku's own dev server under alchemy dev. | | Websites | `frontend/websites.md` | Deploy Vite, Astro, Next.js, vinext, Nuxt, React Router, SvelteKit, TanStack Start, Waku, Octane, or any static build to AWS with first-class Website resources. | ## messaging/ | Page | File | Covers | | --- | --- | --- | -| Process DynamoDB Streams | `messaging/dynamodb-streams.md` | Enable a DynamoDB Stream on your table and consume change records as a typed Effect Stream from the same Lambda. | -| EventBridge & Scheduler | `messaging/eventbridge.md` | Route application and AWS events through EventBridge buses and rules, consume them in Lambda as typed streams, and run cron/rate schedules against Lambda, SQS, and ECS with EventBridge Scheduler. | -| Kinesis | `messaging/kinesis.md` | Add a Kinesis Data Stream, publish records from one Lambda, and consume them in order from another — wired through the same Stream-shaped event source. | -| React to S3 Events | `messaging/s3-events.md` | Subscribe a Lambda Function to S3 bucket notifications, process them as an Effect Stream, and let Alchemy wire up the IAM and event-source plumbing. | -| SNS | `messaging/sns.md` | Create an SNS Topic, publish to it from a Lambda with the Publish binding, fan messages out to SQS queues, and consume notifications as a typed Stream. | -| SQS | `messaging/sqs.md` | Add an SQS Queue, publish messages from your Lambda, and consume them from a second consumer Lambda — all wired through Alchemy bindings. | +| DynamoDB Streams | `messaging/dynamodb-streams.md` | How a DynamoDB Stream records every change to a table in order, what each change record carries, and how a Function consumes changes and checkpoints at the first failure. | +| EventBridge & Scheduler | `messaging/eventbridge.md` | How EventBridge buses route events to targets by matching their content, how runtimes publish and consume events, and how EventBridge Scheduler runs Functions, Queues and tasks on a schedule. | +| Kinesis | `messaging/kinesis.md` | How Kinesis Data Streams keep records in order per partition key across shards, how runtimes write records and consume them in batches, and how retention, replay and checkpoints work. | +| S3 events | `messaging/s3-events.md` | How a Bucket notifies a Function when objects are created or deleted, what each notification carries, and how to process notifications as an Effect Stream. | +| SNS | `messaging/sns.md` | How SNS Topics broadcast one message to every subscriber, how to publish from a runtime, subscribe Functions and Queues, and filter what each subscriber receives. | +| SQS | `messaging/sqs.md` | How SQS Queues hand work from producers to consumers, how visibility timeouts, retries and dead-letter queues keep messages from being lost, and how runtimes send to and consume from a Queue. | ## networking/ | Page | File | Covers | | --- | --- | --- | -| VPC & networking | `networking/_overview.md` | The Network helper for a production-shaped VPC in one call, and the full set of EC2 networking primitives — VPCs, subnets, gateways, routes, security groups, and endpoints — for explicit control. | -| Custom domains with Route53 + ACM | `networking/custom-domains.md` | Serve your site or API from your own domain — DNS-validated ACM certificates, Route 53 alias records, and the domain prop on Website resources. | +| VPC & networking | `networking/_overview.md` | How a VPC, its subnets, route tables, gateways and security groups decide what can reach what on AWS, which runtimes need one, and how to build one with the Network helper or by hand. | +| Custom domains | `networking/custom-domains.md` | How a domain reaches a site or API on AWS through a hosted zone, a TLS certificate and DNS records, and how the domain prop sets them up on Websites, Lambda Functions and load balancers. | ## observability/ | Page | File | Covers | | --- | --- | --- | -| CloudWatch | `observability/cloudwatch.md` | Declare CloudWatch dashboards as structured widget documents and metric alarms that fire SNS topics — versioned next to the Lambda functions and queues they observe. | +| CloudWatch | `observability/cloudwatch.md` | How CloudWatch collects logs and metrics from every AWS service, and how alarms and dashboards declared next to your resources watch them. | ## security/ | Page | File | Covers | | --- | --- | --- | -| Secrets & env | `security/secrets-env.md` | Deliver API keys from .env to a Lambda with effect/Config, and graduate to AWS Secrets Manager when the secret is a shared, generated, or rotated cloud resource. | +| Federated identity | `security/federated-identity.md` | How Cloud Run services and Fly Services reach AWS, and a Lambda reaches GCP, through workload identity federation instead of long-lived keys. | +| Secrets & env | `security/secrets-env.md` | How configuration and secrets reach a runtime on AWS, as environment variables from effect/Config or as Secrets Manager secrets read through a binding, and when to use each. | ## tutorial/ diff --git a/.agents/skills/alchemy/references/aws/_overview.md b/.agents/skills/alchemy/references/aws/_overview.md index fecfa51a..9f360a70 100644 --- a/.agents/skills/alchemy/references/aws/_overview.md +++ b/.agents/skills/alchemy/references/aws/_overview.md @@ -1,123 +1,72 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # AWS -> Build AWS applications with Alchemy — a runtime (usually Lambda) plus typed resources, wired together by bindings that mint least-privilege IAM policies. - -An Alchemy app on AWS is one **runtime** — usually a Lambda -Function — plus the **resources** it talks to: tables, -buckets, queues, streams. You wire them together with typed -**bindings**: call `S3.PutObject(bucket)` in your code and -Alchemy attaches the matching least-privilege IAM statement to -the function's role. The code is the policy. - -New here? [Set up credentials](/aws/setup) first, then deploy -your first [Lambda](/aws/compute/lambda). - -## Pick your runtime - -- **[Lambda](/aws/compute/lambda)** — serverless, event-driven functions - with public Function URLs. The primary documented path: every - resource and event source in this section is shown - running on Lambda. -- **[ECS](/aws/compute/ecs)** — long-running containers on Fargate. - Alchemy bundles your Effect program into a Docker image and - runs it as a Cluster + Service + Task. -- **[EKS](/aws/compute/eks)** — managed Kubernetes (Auto Mode). - Deployments, Jobs, raw manifests, and Helm charts in the same - TypeScript program as the cluster — no YAML, no kubectl. -- **[EC2](/aws/compute/ec2)** — full-control virtual machines, with the - complete VPC networking toolkit around them. - -Not sure which? See -[Choosing a runtime](/aws/compute/choosing-a-runtime). - -## Data - -- **[DynamoDB](/aws/data/dynamodb)** — key/value tables with - `GetItem`/`PutItem` bindings and change-data-capture Streams. -- **[S3](/aws/data/s3)** — object storage with `GetObject`/`PutObject` - bindings and bucket event notifications. -- **[RDS & Aurora](/aws/data/rds)** — managed Postgres/MySQL: the - `Aurora` helper stands up the whole cluster in one call, with - a `Connect` binding or the Data API at runtime. - -## Messaging & events - -- **[SQS](/aws/messaging/sqs)** — queues with a `SendMessage` binding and a - `Stream`-shaped Lambda consumer. -- **[SNS](/aws/messaging/sns)** — pub/sub topics with a `Publish` binding - and fan-out to queues and functions. -- **[EventBridge & Scheduler](/aws/messaging/eventbridge)** — event buses, - rules, and cron/rate schedules that invoke your functions. -- **[Kinesis](/aws/messaging/kinesis)** — ordered, sharded data streams - with a `PutRecord` binding and the same `Stream` consumer - surface. - -## Email - -- **[Sending & managing email](/aws/email/sending)** — verify an SES - identity, send from a Lambda with the `SendEmail` binding, and - manage identity policies, contact lists, dedicated IP pools, - tenants, account settings, and deliverability insights. -- **[Receiving inbound email](/aws/email/receiving)** — SES receipt - rule sets and rules that store mail in S3, fan out to SNS, invoke - a Lambda, or bounce it. Region-limited to `us-east-1`, - `us-west-2`, and `eu-west-1`. - -## Security & secrets - -- **[Secrets & env](/aws/security/secrets-env)** — .env values via - Config, Secrets Manager when the secret is shared, generated, - or rotated. - -## Observability - -- **[CloudWatch](/aws/observability/cloudwatch)** — dashboards and metric - alarms, declared in the same Stack as the resources they - watch. - -## Frontend & networking - -- **[Websites](/aws/frontend/websites)** — the frontend block: static - sites and built Vite apps on S3 + CloudFront as a single - `StaticSite` resource. -- **[VPC & networking](/aws/networking)** — the `Network` helper - and the VPC primitives, for when ECS, EKS, or EC2 needs - explicit networking. - -## What are you building? - -| You're building | Reach for | -| ------------------------------------- | ----------------------------------------------------------------------------- | -| An HTTP API | [Lambda](/aws/compute/lambda) + Function URL + [DynamoDB](/aws/data/dynamodb) | -| A typed HTTP API | [Effect HTTP API on Lambda](/aws/apis/effect-http-api) | -| A typed API for external clients | [Effect RPC on Lambda](/aws/apis/effect-rpc) | -| Drive a MicroVM from a Lambda (internal RPC) | [MicroVMs](/aws/compute/microvms) + [Schemaless RPC](/apis/schemaless) | -| An ML training fleet | [HyperPod](/aws/compute/hyperpod) — Slurm or EKS orchestrated, with task governance | -| A REST API with stages/custom domains | [API Gateway](/aws/apis/api-gateway) | -| Your own domain on a site or API | [Custom domains with Route53 + ACM](/aws/networking/custom-domains) | -| A static site | [Deploy a static site](/aws/frontend/static-site) on S3 + CloudFront | -| An event pipeline | [Kinesis](/aws/messaging/kinesis) → Lambda | -| Background jobs | [SQS](/aws/messaging/sqs) + Lambda | -| Scheduled jobs | [EventBridge Scheduler](/aws/messaging/eventbridge) → Lambda | -| A Postgres database | [RDS & Aurora](/aws/data/rds) | -| Kubernetes workloads or Helm charts | [EKS](/aws/compute/eks) | -| Object processing | [S3 events](/aws/messaging/s3-events) | -| Sending transactional email | [SES sending](/aws/email/sending) — identity + `SendEmail` binding | -| Inbound email pipelines | [SES email receiving](/aws/email/receiving) → S3 / SNS / Lambda | -| Change data capture | [DynamoDB Streams](/aws/messaging/dynamodb-streams) | -| API keys or credentials for a function | [Secrets & env](/aws/security/secrets-env) | - -## Where next - -- [Setup](/aws/setup) — install Alchemy and connect your AWS - account. -- [Deploy a static site](/aws/frontend/static-site) and - [Effect HTTP API on Lambda](/aws/apis/effect-http-api) — - end-to-end guides for the two most common app shapes. -- [Providers reference](/providers) — generated API docs for - every AWS resource Alchemy ships, well beyond the blocks - documented here (CloudFront, Route53, IAM, and more). +> Build on AWS with Alchemy. Declare Lambda Functions, containers, tables, buckets and queues in TypeScript, and let bindings write each runtime's IAM policy from the calls its code makes. + +Amazon Web Services is a cloud platform with services for compute, storage, databases, networking, analytics, machine learning and security, in regions around the world. + +**New to AWS?** Start with [What is AWS?](/aws/what-is-aws). + +## A quick example + +A Queue is a declaration: + +```typescript title="src/jobs.ts" +import * as AWS from "@alchemy.run/aws"; + +export const Jobs = AWS.SQS.Queue("Jobs"); +``` + +A Lambda Function binds it and sends to it. The binding gives the Function `sqs:SendMessage` on that one Queue, and `SendMessageHttp` is the client that makes the call: + +```typescript title="src/api.ts" +import * as AWS from "@alchemy.run/aws"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; +import { Jobs } from "./jobs.ts"; + +export default class Api extends AWS.Lambda.Function()( + "Api", + { main: import.meta.url }, + Effect.gen(function* () { + const send = yield* AWS.SQS.SendMessage(Jobs); + return { + fetch: send({ MessageBody: "hello" }).pipe( + Effect.as(HttpServerResponse.text("queued")), + Effect.orDie, + ), + }; + }).pipe(Effect.provide(AWS.SQS.SendMessageHttp)), +) {} +``` + +And the Stack deploys it to the account your profile signs in to: + +```typescript title="alchemy.run.ts" +import * as Alchemy from "alchemy"; +import * as AWS from "@alchemy.run/aws"; +import * as Effect from "effect/Effect"; +import Api from "./src/api.ts"; + +export default Alchemy.Stack( + "MyApp", + { providers: AWS.providers(), state: AWS.state() }, + Effect.gen(function* () { + const api = yield* Api; + return { url: api.functionUrl }; + }), +); +``` + +## Where to start + +**Want to build?** Connect your account in [Setup](/aws/setup), then follow the [tutorial](/aws/tutorial/part-1) from a single Bucket to a Lambda Function with tests and CI. + +**Looking for something specific?** Every section of these docs is listed below, and every resource is in the generated [API reference](/providers). + +## The docs + + diff --git a/.agents/skills/alchemy/references/aws/accounts-and-regions.md b/.agents/skills/alchemy/references/aws/accounts-and-regions.md new file mode 100644 index 00000000..d2ce61d7 --- /dev/null +++ b/.agents/skills/alchemy/references/aws/accounts-and-regions.md @@ -0,0 +1,166 @@ + + +# Accounts and regions + +> How AWS accounts isolate resources, how regions and Availability Zones place them, and how profiles and stages choose where each Alchemy deploy goes. + +Every AWS resource lives in one account and, for most services, one region. Before you create anything, you decide which account and which region it goes to. + +## An account is an isolation boundary + +An AWS account holds resources, the identities that may use them, and the bill for both. Two accounts share nothing unless you set it up: a role in one can't read a Bucket in the other, and a runaway Lambda in one never touches the other's quotas. + +So accounts are how you keep environments apart. Put production in an account of its own. Give staging, shared development and, if you like, each engineer their own accounts too. A mistake in development then can't reach production data, because no policy in the development account can name it. + + + +An **organization** groups those accounts under one payer, the **management account**. Under its **root** sit **organizational units** (OUs), which hold accounts and other OUs, so you can shape it like your teams and environments. Declare the tree from a Stack deployed to the management account: + +```typescript title="alchemy.run.ts" +const root = yield* AWS.Organizations.Root("Root", {}); +const workloads = yield* AWS.Organizations.OrganizationalUnit("Workloads", { + parentId: root.rootId, + name: "workloads", +}); +const prod = yield* AWS.Organizations.Account("Prod", { + name: "prod", + email: "aws-prod@example.com", + parentId: workloads.ouId, +}); +``` + +A **service control policy** (SCP) attached to an OU caps what every account below it may do, whatever those accounts' own IAM policies say. Turn SCPs on for the root once, then attach one: + +```typescript title="alchemy.run.ts" +yield* AWS.Organizations.RootPolicyType("ScpEnabled", { + rootId: root.rootId, + policyType: "SERVICE_CONTROL_POLICY", +}); +const denyRegions = yield* AWS.Organizations.Policy("DenyOtherRegions", { + type: "SERVICE_CONTROL_POLICY", + document: { + Version: "2012-10-17", + Statement: [ + { + Effect: "Deny", + NotAction: ["iam:*", "organizations:*", "sts:*"], + Resource: "*", + Condition: { StringNotEquals: { "aws:RequestedRegion": ["us-east-1", "us-west-2"] } }, + }, + ], + }, +}); +yield* AWS.Organizations.PolicyAttachment("DenyRegionsOnWorkloads", { + policyId: denyRegions.policyId, + targetId: workloads.ouId, +}); +``` + +People sign in once, through **IAM Identity Center**, and pick the account and role they want to work in. + +## Connect an account with a profile + +Alchemy reaches an account through a [profile](/environments/profiles). Add AWS to your `default` profile and choose how you sign in: + +```sh +alchemy profile edit --add AWS +``` + +Console login is the simplest choice: you sign in to the AWS Console in your browser, and Alchemy gets short-lived credentials for that identity, with no access keys to store. Organizations that use IAM Identity Center sign in through SSO instead. Either way, Alchemy runs the login for you. See [Setup](/aws/setup). + +Make a profile per account, and name it after the account it reaches: + +```sh +alchemy profile create prod +alchemy profile edit --profile prod --add AWS +``` + +## Choose the stage and the account separately + +A [stage](/environments/stages) decides **what** you deploy: its own state and its own resource names. A profile decides **where**: which account, and the default region. The two are independent. + +```sh +alchemy deploy --stage prod --profile prod +alchemy deploy --stage pr-42 --profile default +``` + +Many stages can share one account. Each pull request gets its own stage, with its own Bucket and its own Function, in the development account. Production gets the `prod` stage in the `prod` account. + +## A region is where a resource runs + +A region is a separate deployment of AWS in one part of the world. A Queue in `us-east-1` and a Queue in `eu-west-1` are two different Queues, with different ARNs, and messages never flow between them unless you send them. + +Your profile sets the default region, and every regional resource in the Stack is created there. Pick the one closest to your users, or the one your data must stay in. To deploy the same Stack to another region, use a profile that points at it. + +In CI, the region comes from the environment instead: + +```sh +export AWS_REGION=eu-west-1 +``` + +Read the current region inside your Stack when another resource needs it: + +```typescript title="alchemy.run.ts" +const region = yield* AWS.Region; +``` + +## Availability Zones spread a region out + +A region is made of several **Availability Zones**: data centers far enough apart to fail independently, close enough to replicate quickly. Their names add a letter to the region: `us-east-1a`, `us-east-1b`. + +Serverless services spread across zones for you. A Bucket, a Table, a Queue or a Function survives the loss of a zone without any setup. Networks don't: a subnet sits in exactly one zone, so anything in a VPC chooses its zones through its subnets. The `Network` helper puts a public and a private subnet in two zones by default. See [VPC & networking](/aws/networking). + +## Some services are global + +IAM, CloudFront and Route 53 aren't regional. A role, a distribution or a hosted zone belongs to the account as a whole, and its ARN has no region in it: + +```text +arn:aws:iam::123456789012:role/myapp-api-role +``` + +One rule follows from this. CloudFront only uses TLS certificates from `us-east-1`, wherever the rest of your Stack runs. A Certificate defaults to that region for you: + +```typescript title="src/site.ts" +export const Cert = AWS.ACM.Certificate("Cert", { domainName: "app.example.com" }); +``` + +Give a certificate for a regional load balancer the load balancer's region instead, with `region`. See [Custom domains](/aws/networking/custom-domains). + +## Keep Alchemy's state in the account + +Each account and region holds its own copy of Alchemy's state: a DynamoDB table named `alchemy-state`, created on the first deploy. A stage's record lives in the account it deploys to, next to its resources. + +```typescript title="alchemy.run.ts" +export default Alchemy.Stack( + "MyApp", + { providers: AWS.providers(), state: AWS.state() }, + Effect.gen(function* () { + return {}; + }), +); +``` + +In CI, create the table once before the first deploy: + +```sh +alchemy state bootstrap --backend aws +``` + +See [State store](/state-store). diff --git a/.agents/skills/alchemy/references/aws/ai/bedrock.md b/.agents/skills/alchemy/references/aws/ai/bedrock.md index 923c43c8..a83f1fe7 100644 --- a/.agents/skills/alchemy/references/aws/ai/bedrock.md +++ b/.agents/skills/alchemy/references/aws/ai/bedrock.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Bedrock & Effect AI @@ -29,7 +29,7 @@ scoped to exactly that model: ```typescript // src/Api.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; import { LanguageModel } from "effect/ai"; import * as HttpServerResponse from "effect/http/HttpServerResponse"; diff --git a/.agents/skills/alchemy/references/aws/apis/api-gateway.md b/.agents/skills/alchemy/references/aws/apis/api-gateway.md index bd897c26..358eb4ef 100644 --- a/.agents/skills/alchemy/references/aws/apis/api-gateway.md +++ b/.agents/skills/alchemy/references/aws/apis/api-gateway.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # REST API (API Gateway v1) @@ -16,8 +16,8 @@ The repo includes **`examples/aws-rest-api`**: a minimal **regional** REST API w ```sh cd examples/aws-rest-api -bun install -bun run deploy +npm install +npm run deploy ``` After deploy, open the printed `invokeUrl` in a browser; you should see the Lambda’s text response. diff --git a/.agents/skills/alchemy/references/aws/apis/effect-http-api.md b/.agents/skills/alchemy/references/aws/apis/effect-http-api.md index ede2be28..89ad28a2 100644 --- a/.agents/skills/alchemy/references/aws/apis/effect-http-api.md +++ b/.agents/skills/alchemy/references/aws/apis/effect-http-api.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Effect HTTP API on Lambda @@ -9,8 +9,7 @@ Effect HTTP defines real REST endpoints — URLs, path params, query strings, typed bodies — behind an RPC-like typed interface, which makes it the natural fit when your consumers aren't Effect (or -aren't TypeScript at all) and want a plain HTTP client. This page is -the Lambda wiring; the concept lives at +aren't TypeScript at all) and want a plain HTTP client. The concept lives at [Effect HTTP](/apis/effect-http), and [RPC](/apis) covers choosing between the RPC styles. @@ -25,7 +24,7 @@ schemas for payloads, responses, and errors, then implement handlers against those schemas. The result is an `HttpEffect` — the same type a Lambda's `fetch` expects — so it plugs in directly. It's the exact same module used in the -[Workers version of this guide](/cloudflare/apis/effect-http-api); +[Workers version](/cloudflare/apis/effect-http-api); the spec and handlers are portable, only the host changes. The mental model: @@ -113,8 +112,7 @@ export const JobApi = HttpApi.make("JobApi").add( ``` Nothing executes yet — `JobApi` is purely a value-level description. -The same constant is what we'll hand to the client at the end of -this guide. +The same constant is what we'll hand to the client at the end. ## 3. Build the Function @@ -123,7 +121,7 @@ phase and a public Function URL: ```typescript // src/JobFunction.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; export default class JobFunction extends AWS.Lambda.Function()( @@ -280,7 +278,7 @@ Here's the complete `src/JobFunction.ts`: ```typescript // src/JobFunction.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Etag from "effect/http/Etag"; @@ -356,7 +354,7 @@ export default class JobFunction extends AWS.Lambda.Function()( ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; import JobFunction from "./src/JobFunction.ts"; @@ -379,9 +377,7 @@ with the two table-scoped statements, and the Function URL. ## 5. Deploy -```sh -bun alchemy deploy -``` + Hit the URL from the deploy output with `curl`: @@ -408,8 +404,8 @@ end-to-end: ```typescript // test/api.test.ts -import * as AWS from "alchemy/AWS"; -import * as Test from "alchemy/Test/Bun"; +import * as AWS from "@alchemy.run/aws"; +import * as Test from "@alchemy.run/test/Bun"; import { expect } from "bun:test"; import * as Effect from "effect/Effect"; import * as Schedule from "effect/Schedule"; diff --git a/.agents/skills/alchemy/references/aws/apis/effect-rpc.md b/.agents/skills/alchemy/references/aws/apis/effect-rpc.md index 98e974de..51df9a30 100644 --- a/.agents/skills/alchemy/references/aws/apis/effect-rpc.md +++ b/.agents/skills/alchemy/references/aws/apis/effect-rpc.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Effect RPC on Lambda @@ -113,7 +113,7 @@ Function URL: ```typescript // src/JobFunction.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; export default class JobFunction extends AWS.Lambda.Function()( @@ -246,7 +246,7 @@ DynamoDB's HTTP API, signed with the Lambda's execution role. ```typescript // src/JobFunction.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { RpcSerialization, RpcServer } from "effect/rpc"; @@ -317,7 +317,7 @@ export default class JobFunction extends AWS.Lambda.Function()( ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; import JobFunction from "./src/JobFunction.ts"; @@ -340,9 +340,7 @@ with the two table-scoped statements, and the Function URL. ## 5. Deploy -```sh -bun alchemy deploy -``` + ## 6. Call it from a typed client @@ -394,7 +392,7 @@ explicitly. ## Choosing an API style -- **External Effect/TypeScript consumers** — this page. +- **External Effect/TypeScript consumers** — Effect RPC, with a typed client. - **External plain-HTTP consumers** (curl, non-TypeScript clients) — [Effect HTTP API on Lambda](/aws/apis/effect-http-api). - **Internal service-to-service calls** — @@ -418,7 +416,7 @@ explains the service-Layer pattern it uses. - [Lambda](/aws/compute/lambda) — how the Function class, Function URLs, and the test harness work. - [Effect HTTP API on Lambda](/aws/apis/effect-http-api) — the - REST-style sibling of this guide, same wiring. + REST-style sibling, with the same wiring. - [Effect RPC on Workers](/cloudflare/apis/effect-rpc) — the same `RpcGroup` deployed to Cloudflare, plus streaming and Durable Object routing. diff --git a/.agents/skills/alchemy/references/aws/apis/schemaless-rpc.md b/.agents/skills/alchemy/references/aws/apis/schemaless-rpc.md index f466223d..cd3bd5f9 100644 --- a/.agents/skills/alchemy/references/aws/apis/schemaless-rpc.md +++ b/.agents/skills/alchemy/references/aws/apis/schemaless-rpc.md @@ -1,14 +1,14 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Schemaless RPC > Typed RPC from a Lambda Function into a MicroVM with no schema — declare the image's Shape, connect, get the client. The pattern — what a Shape member may be, how the typed client arises, what -crosses the wire — lives at [Schemaless RPC](/apis/schemaless). This page -covers the AWS pairings. There is one today: **Lambda → Firecracker MicroVM**, +crosses the wire — lives at [Schemaless RPC](/apis/schemaless). On AWS +there is one pairing today: **Lambda → Firecracker MicroVM**, riding the generic fetch transport — each call is a `POST https:///__rpc__/{name}`. @@ -16,7 +16,7 @@ riding the generic fetch transport — each call is a ```typescript // sandbox.ts — the MicroVM image -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; import * as HttpServerResponse from "effect/http/HttpServerResponse"; diff --git a/.agents/skills/alchemy/references/aws/compute/choosing-a-runtime.md b/.agents/skills/alchemy/references/aws/compute/choosing-a-runtime.md index 149a41ba..4c4ddef8 100644 --- a/.agents/skills/alchemy/references/aws/compute/choosing-a-runtime.md +++ b/.agents/skills/alchemy/references/aws/compute/choosing-a-runtime.md @@ -1,144 +1,184 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Choosing a runtime -> Lambda vs ECS vs EKS vs EC2 for Alchemy apps — cold starts, cost shape, packaging, and how much of each Alchemy currently covers. - -Every Alchemy app on AWS needs somewhere for its code to run. -Alchemy ships four runtimes, all driven by the same pattern — -bundle an Effect program, deploy it as a resource, bind building -blocks to it: - -- **Lambda** — serverless functions. **Use this by default.** -- **ECS** — long-running containers on Fargate. -- **EKS** — containers as Kubernetes workloads on a managed - Auto Mode cluster. -- **EC2** — virtual machines you fully control. - -## At a glance - -| | Lambda | ECS | EKS | EC2 | -| ---------------- | ------------------------------------------ | ------------------------------------------ | -------------------------------------------- | ---------------------------------------- | -| Execution model | Per-request, event-driven | Always-on containers | Kubernetes objects (Deployments, Jobs) | Always-on machine | -| Cost shape | Pay per invocation; scales to zero | Pay per running task | Control plane + Auto Mode nodes | Pay per running instance | -| Startup | Cold starts (ms–s), then warm | Task launch (tens of seconds), then steady | Cluster create (~10 min), Pods in seconds | Instance boot (minutes), then steady | -| Packaging | Bundled zip (Rolldown) | Docker image, built + pushed for you | Docker image, built + pushed for you | Bundled program on an AMI you choose | -| Networking | None required (Function URL) | VPC required (awsvpc), optional ALB | VPC required, `LoadBalancer` Services | VPC required, you own every primitive | -| Alchemy coverage | Fully documented | Cluster/Service/Task resources | Cluster/Deployment/Job/Manifest/Helm | Instance + full VPC primitives | - -## Lambda — the default - -Serverless, event-driven, and the runtime this documentation is -written around. You get the [`Function`](/providers/aws/lambda/function) -resource with a public Function URL, typed bindings that mint -least-privilege IAM policies from your call sites, and -`Stream`-shaped event sources for SQS, Kinesis, DynamoDB -Streams, S3 notifications, SNS, and EventBridge. Cold starts and -the 15-minute execution cap are the trade; per-request pricing -and zero idle cost are the payoff. - -Choose Lambda unless you have a specific reason not to. - -→ [Lambda](/aws/compute/lambda) - -## ECS — long-running containers - -When your workload doesn't fit a request/response window — a -WebSocket server, a worker that holds connections open, anything -that should be always-on — run it as a container. Alchemy models -ECS with three resources: - -- [`Cluster`](/providers/aws/ecs/cluster) — an ECS cluster for - running tasks and services. -- [`Task`](/providers/aws/ecs/task) — bundles an inline Effect - program, builds and pushes a Docker image to a generated ECR - repository, provisions task + execution IAM roles and a - CloudWatch log group, and registers a Fargate task definition. - Tasks can serve HTTP directly and accept the same - binding contract (env + IAM policy statements) as Lambda. -- [`Service`](/providers/aws/ecs/service) — keeps a task - definition running with awsvpc networking; set `public: true` - and Alchemy provisions a public ALB + listener + target group - for you. - -You pay for running tasks whether or not they're serving -traffic, and you bring a VPC (subnets + security groups) — the -[`Network`](/providers/aws/ec2/network) helper builds one in a -single call. - -→ [ECS](/aws/compute/ecs) - -## EKS — when your platform is Kubernetes - -When the workload is container-shaped but you want Kubernetes -itself — Helm charts, operators, raw manifests, or teams already -speaking Deployments and Jobs — Alchemy targets **EKS Auto Mode**, -where AWS manages the control plane, nodes, storage, and -load-balancer integration. Alchemy models it with: - -- [`Cluster`](/providers/aws/eks/cluster) — the control plane; - `compute: "auto"` turns on Auto Mode with sensible defaults. -- [`Deployment`](/providers/kubernetes/deployment) — a replicated - Kubernetes server (the Kubernetes analog of `AWS.ECS.Service`) - with the same three image sources as ECS: a registry `image`, a - Dockerfile `context`, or an inline Effect program via `main`. -- [`Job`](/providers/kubernetes/job) — run-to-completion work, or a - `CronJob` when you set `schedule`. -- [`Manifest`](/providers/kubernetes/manifest) and - [`HelmChart`](/providers/kubernetes/helmchart) — any raw Kubernetes - object or a rendered Helm chart, applied via server-side apply. - -Bindings work the same as on Lambda and ECS — env vars plus IAM -policy statements, delivered through an EKS Pod Identity role — -and there is no YAML and no `kubectl` step. You pay for the -control plane and the nodes Auto Mode provisions, you bring a VPC -(the [`Network`](/providers/aws/ec2/network) helper builds one), -and the control plane takes ~10 minutes to create. - -→ [EKS](/aws/compute/eks) - -For ML training fleets specifically — persistent, health-checked -GPU clusters rather than application containers — EKS pairs with -[SageMaker HyperPod](/aws/compute/hyperpod): the HyperPod nodes -join your EKS cluster, and `Deployment`/`Job` opt onto them with -the `hyperpod` prop. - -## EC2 — when you need the machine - -Full-control VMs for workloads that need an OS, a GPU, custom -daemons, or just predictable dedicated capacity. The -[`Instance`](/providers/aws/ec2/instance) resource can act as a -low-level compute primitive or run a bundled long-lived Effect -program directly on the machine (including serving HTTP), and -Alchemy ships the complete networking toolkit around it: -[`Vpc`](/providers/aws/ec2/vpc), -[`Subnet`](/providers/aws/ec2/subnet), -[`SecurityGroup`](/providers/aws/ec2/securitygroup), NAT and -internet gateways, route tables, EIPs, and VPC endpoints (see -[VPC & networking](/aws/networking)). - -You own patching, scaling, and availability. - -→ [EC2](/aws/compute/ec2) - -## Rule of thumb - -1. Start with **Lambda**. Per-request cost, no servers, and the - whole documented binding/event-source surface. -2. Move a workload to **ECS** when it's long-running, needs more - than 15 minutes, or is already a container. -3. Pick **EKS** over ECS when you want Kubernetes itself — - Helm charts, operators, raw manifests — not just a container - runner. -4. Reach for **EC2** when you need the machine itself — kernel - access, GPUs, custom networking, or software that expects a - host. - -## Where next - -- [Lambda](/aws/compute/lambda) — deploy a function with a public URL. -- [AWS overview](/aws) — resources and recipes. -- [Providers reference](/providers) — generated docs for every - ECS, EKS, and EC2 resource. +> How Lambda Functions, Lambda Web Functions, ECS, EKS and EC2 differ in how they run your code, scale and cost, and how to choose one for each part of an app. + +AWS gives you several places to run code. They differ in one main way: how much of the machine AWS manages for you, and so how much you decide yourself. Every one of them runs the same kind of Alchemy program, takes the same bindings, and gets its IAM role from them. + + + +## The same program on every runtime + +Whichever you pick, you declare it with an id, its configuration and an Effect. Construction binds what it uses, and the handlers it returns do the work. Here it is as an ECS Service: + +```typescript title="alchemy.run.ts" +const api = yield* AWS.ECS.Service( + "Api", + { cluster, main: import.meta.url, port: 3000, loadBalancer: true }, + Effect.gen(function* () { + const getObject = yield* AWS.S3.GetObject(Files); + return { + fetch: Effect.succeed(HttpServerResponse.text("Hello from ECS!")), + }; + }).pipe(Effect.provide(AWS.S3.GetObjectHttp)), +); +``` + +The same Effect, with its bindings and its `fetch`, runs as a Lambda Function or on EC2. + +So moving part of an app from one runtime to another changes its declaration, not its code. Choose by how the work behaves, and change your mind later if it behaves differently than you expected. + +## Lambda Functions: run per invocation + +A [Lambda Function](/aws/compute/lambda) runs when something invokes it: a request, a queue message, a new object, a schedule. AWS starts environments as invocations arrive and stops them when they don't, so an idle Function costs nothing and a busy one scales with no setup. + +That makes it an easy and cheap place to start. Its limits come from the same model: an invocation runs for at most 15 minutes, each environment handles one invocation at a time, and a new environment takes a cold start before its first one. + +Choose it for event handlers, background jobs, scheduled work, and APIs that see uneven traffic. + + + +## Lambda Web Functions: HTTP servers on Lambda + +A [Lambda Web Function](/aws/compute/web-functions) runs an HTTP server on Lambda. One environment serves many requests at once, up to 128, so a spike starts fewer environments and requests share warm connections. Responses stream as your handler produces them. + +It only receives HTTP, runs Node.js, and has a fixed 2 GB of memory per environment. Choose it for APIs and websites, and pair it with a Lambda Function when the API hands work to a queue. + + + +## ECS: containers that keep running + +[ECS](/aws/compute/ecs) runs your program as a container on Fargate, and keeps it running. There's no time limit and no cold start per request, and the program can hold connections, WebSockets or in-memory state for as long as it's up. + +You pay for running tasks whether or not they're busy. They run inside a VPC: your account's default one to start, or one you build with the `Network` helper. Alchemy builds the image from your program, or from a Dockerfile, and pushes it for you. + +Choose it for long-lived servers, workers that hold connections open, and anything that already ships as a container. + + + +## EKS: Kubernetes + +[EKS](/aws/compute/eks) runs a Kubernetes cluster, with AWS managing the control plane and, in Auto Mode, the nodes. You deploy Deployments, Jobs, Helm charts and raw manifests from the same Stack, with the same bindings. + +A cluster takes about ten minutes to create and costs money while it exists. Choose it when you want Kubernetes itself: its tools, its operators, or a team that already runs on it. + + + +## EC2: the whole machine + +[EC2](/aws/compute/ec2) gives you a virtual machine. You pick the instance type, the operating system and the disk, and you own patching and recovery. Alchemy can run your program on it directly, or leave it as a plain machine. + +Choose it for GPUs, custom daemons, software that expects a host, or steady load where a reserved machine is cheapest. + + + +## Mix runtimes in one app + +An app rarely needs just one. A common shape is a Web Function for the API, a Lambda Function consuming the queue it writes to, and an ECS service for the one process that must stay connected: + +```text +Diagram (nodes and edges as authored): + +``` + +Each runtime has its own role, written by its own bindings, so each part of the app can reach only what it uses. diff --git a/.agents/skills/alchemy/references/aws/compute/ec2.md b/.agents/skills/alchemy/references/aws/compute/ec2.md index 0bf34115..6aec7596 100644 --- a/.agents/skills/alchemy/references/aws/compute/ec2.md +++ b/.agents/skills/alchemy/references/aws/compute/ec2.md @@ -1,172 +1,130 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # EC2 -> Launch virtual machines with the Instance resource — as a raw compute primitive, or hosting a bundled long-lived Effect program served straight off the box. +> How EC2 instances give you a whole virtual machine, how to launch one from an image into a subnet, how to run your Effect program on it as a service, and how to reach it. -**EC2** is for when you need the machine itself: an OS you -control, GPUs, custom daemons, software that expects a host, or -predictable dedicated capacity. The -[`Instance`](/providers/aws/ec2/instance) resource plays two -roles — a **low-level compute primitive** (launch an AMI, attach -networking, done), or a **host for a bundled Effect program** -that Alchemy deploys onto the machine and keeps running. +EC2 gives you a virtual machine, called an **instance**. You choose its size, its operating system and its disk, and it runs until you stop it. Everything on it is yours to control: the kernel, the daemons, the GPUs, the software that expects a host. So is everything that keeps it healthy: patching, restarts, and replacing it when it fails. -This is the lowest-level of Alchemy's four runtimes: unlike -[Lambda](/aws/compute/lambda), [ECS](/aws/compute/ecs), and -[EKS](/aws/compute/eks), you own patching, -scaling, and availability. Reach for it deliberately — see -[Choosing a runtime](/aws/compute/choosing-a-runtime). +## An instance is an image, a type and a subnet + +An **image** (AMI) is the disk an instance boots from: an operating system and whatever is installed on it. An **instance type** is its size: `t3.micro` has 2 vCPUs and 1 GB of memory, `g5.xlarge` has a GPU. A **subnet** is where it sits on your [network](/aws/networking), and **security groups** decide what can reach it. + + + +You pay for an instance by the second while it runs, busy or idle. ## Launch an instance -The minimal instance is an AMI plus an instance type. AMI IDs -are per-region, so resolve one with Alchemy's image helpers -instead of hard-coding — `amazonLinux()` finds the latest Amazon -Linux AMI (there are also `amazonLinux2023`, `amazonLinux2`, -`ubuntu2404`, `ubuntu2204`, an id-only `image()` finder, and the -underlying `getAmi()` data source returning the full image -description). Each returns an `Output` resolved at deploy time: +Image ids differ by region, so look one up instead of writing it down. `amazonLinux()` finds the latest Amazon Linux image at deploy time. `ubuntu2404()` and the others work the same way: -```typescript -const instance = yield* AWS.EC2.Instance("AppInstance", { +```typescript title="alchemy.run.ts" +const instance = yield* AWS.EC2.Instance("Box", { imageId: AWS.EC2.amazonLinux(), instanceType: "t3.micro", - subnetId: subnet.subnetId, + subnetId: network.publicSubnetIds[0], }); ``` -The resolved instance exposes `instanceId`, `publicIpAddress`, -`privateIpAddress`, DNS names, and the rest of the observed -state — see the [`Instance` reference](/providers/aws/ec2/instance) -for every prop and attribute. +The instance's `instanceId`, `publicIpAddress` and `privateIpAddress` are on the result. -## Host an Effect program +## Run your program on it -Give the instance a `main` entrypoint and it becomes a runtime, -same class pattern as Lambda and ECS. Because instance props -(the network, the AMI) are resolved by the stack, the props slot -takes an `Effect.gen` block. The composition is also re-executed -inside the deployed instance's bundle — that's safe as-is: -resource yields resolve to references at runtime, and the AMI -helper returns an `Output` that only resolves at deploy time: - -```typescript -// src/server.ts -import * as AWS from "alchemy/AWS"; -import * as Effect from "effect/Effect"; -import { HttpServerRequest } from "effect/http/HttpServerRequest"; -import * as HttpServerResponse from "effect/http/HttpServerResponse"; +Give an instance `main`, and it runs your Effect program as a service. The program serves `fetch` on `port`, and binds what it uses exactly as a Lambda Function or an ECS task does: +```typescript title="src/server.ts" export default class Server extends AWS.EC2.Instance()( "Server", Effect.gen(function* () { - const network = yield* AWS.EC2.Network("AppNetwork", { - cidrBlock: "10.81.0.0/16", - availabilityZones: 1, - }); - const securityGroup = yield* AWS.EC2.SecurityGroup("AppSg", { + const network = yield* AWS.EC2.Network("AppNetwork", { cidrBlock: "10.81.0.0/16", availabilityZones: 1 }); + const web = yield* AWS.EC2.SecurityGroup("Web", { vpcId: network.vpcId, - description: "app ingress", - ingress: [ - { - ipProtocol: "tcp", - fromPort: 3000, - toPort: 3000, - cidrIpv4: "0.0.0.0/0", - description: "app", - }, - ], - egress: [ - { - ipProtocol: "-1", - cidrIpv4: "0.0.0.0/0", - description: "all outbound", - }, - ], + ingress: [{ ipProtocol: "tcp", fromPort: 3000, toPort: 3000, cidrIpv4: "0.0.0.0/0" }], + egress: [{ ipProtocol: "-1", cidrIpv4: "0.0.0.0/0" }], }); - return { main: import.meta.url, imageId: AWS.EC2.amazonLinux(), instanceType: "t3.small", subnetId: network.publicSubnetIds[0], - securityGroupIds: [securityGroup.groupId], + securityGroupIds: [web.groupId], associatePublicIpAddress: true, port: 3000, }; }), Effect.gen(function* () { return { - fetch: Effect.gen(function* () { - const request = yield* HttpServerRequest; - const url = new URL(request.url, "http://instance"); - if (url.pathname === "/health") { - return yield* HttpServerResponse.json({ ok: true }); - } - return HttpServerResponse.text("hello from EC2"); - }), + fetch: Effect.succeed(HttpServerResponse.text("hello from EC2")), }; }), ) {} ``` -At deploy time Alchemy bundles the program, uploads it to S3, -and boots the instance with a user-data script that installs -Bun and writes a **systemd unit**. The unit syncs the bundle and -environment from S3 on every start and runs with -`Restart=always`, so a flaky network install self-heals and the -service survives reboots. The `{ fetch }` handler is served by -the instance's HTTP server on `port`; `ServerHost` + `host.run` -background loops work exactly as they do on [ECS](/aws/compute/ecs). - -Hosted instances also get an Alchemy-managed IAM role and -instance profile. Bindings use the same contract as Lambda — -environment variables plus IAM policy statements attached to -that role — and you can widen it with managed policies: - -```typescript -// e.g. make the instance manageable via SSM Session Manager -roleManagedPolicyArns: [ - "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore", -], +The props are an Effect here because they depend on the network and security group declared inside it. + +Deploy bundles the program, uploads it, and boots the instance with a script that installs Bun and a systemd service. The service fetches the latest bundle and runs it on every start, and restarts it if it exits, so the program survives reboots and crashes. Background loops with `ServerHost` work as they do on [ECS](/aws/compute/ecs#do-work-in-the-background). + +## Give it permissions + +An instance that runs your program gets its own IAM role, attached through an **instance profile**. Each binding adds its statement to that role, and the program's AWS calls use the role's credentials. + +Add AWS managed policies for tools that run on the box, like Session Manager: + +```typescript title="src/server.ts" +roleManagedPolicyArns: ["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"], ``` -## SSH access +## Connect to it -For direct access, create an Alchemy-managed -[`KeyPair`](/providers/aws/ec2/keypair) and pass its name to the -instance. The generated private key comes back as a `Redacted` -output on the resource: +With the Session Manager policy above, open a shell from the AWS console or CLI, with no open port and no key. For SSH, declare a key pair and give its name to the instance: -```typescript -const key = yield* AWS.EC2.KeyPair("AppKeyPair", { - keyType: "ed25519", -}); +```typescript title="alchemy.run.ts" +const key = yield* AWS.EC2.KeyPair("BoxKey", { keyType: "ed25519" }); +``` + +Pass `keyName: key.keyName` in the instance's props. The private key comes back `Redacted` on the key pair, and port 22 must be open in its security group. + +## Place it on the network + +An instance is as reachable as its subnet and security groups make it. In a public subnet with `associatePublicIpAddress`, it has an internet address. In a private subnet, only things inside the VPC can reach it, and it reaches out through a NAT gateway. -// then on the instance props: -// keyName: key.keyName +Open only the ports you serve, to only the sources that need them. See [VPC & networking](/aws/networking). + +## Host Nitro Sandboxes + +An instance can run [Nitro Sandboxes](/aws/compute/nitro-sandboxes): lightweight VMs that the Nitro hypervisor isolates from the instance and from each other, so one machine can host many workloads you don't trust. Sandboxes use the same switch as Nitro Enclaves, set at launch: + +```typescript title="alchemy.run.ts" +const host = yield* AWS.EC2.Instance("SandboxHost", { + imageId: AWS.EC2.amazonLinux2023(), + instanceType: "m6i.xlarge", + subnetId: network.privateSubnetIds[0], + enclaveOptions: { enabled: true }, +}); ``` -## Networking - -An instance is only as reachable as the network you launch it -into. The example above leans on the -[`Network`](/providers/aws/ec2/network) helper for a -public-subnet VPC; when you need explicit control — private -subnets, NAT, VPC endpoints, custom route tables — compose the -primitives directly. [VPC & networking](/aws/networking) walks -through the whole set. - -## Where next - -- [Choosing a runtime](/aws/compute/choosing-a-runtime) — Lambda first, - ECS for containers, EKS for Kubernetes, EC2 when you need the - machine. -- [VPC & networking](/aws/networking) — the `Network` helper and - the VPC primitives an instance lives in. -- [`Instance` reference](/providers/aws/ec2/instance), - [`KeyPair` reference](/providers/aws/ec2/keypair) — every prop - and attribute. +The instance type must support Nitro Enclaves: most current families do, except their smallest size. The setting can't change on a running instance, so changing it replaces the instance. + +Alchemy launches the host. Starting sandboxes on it is up to you: run a virtual machine monitor on the instance, Firecracker being the one AWS supports, and launch each sandbox from a guest image with its vCPUs, memory and devices. See [Launch a Nitro Sandbox](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/amazon-ec2-nitro-sandboxes.html#nitro-sandboxes-launch). + +To have sandboxes started for you, one per container, run them on [ECS](/aws/compute/ecs#isolate-each-task-in-its-own-vm) or [EKS](/aws/compute/eks#run-each-pod-in-its-own-vm) instead. diff --git a/.agents/skills/alchemy/references/aws/compute/ecs-sandboxes.md b/.agents/skills/alchemy/references/aws/compute/ecs-sandboxes.md new file mode 100644 index 00000000..2d5e1113 --- /dev/null +++ b/.agents/skills/alchemy/references/aws/compute/ecs-sandboxes.md @@ -0,0 +1,448 @@ + + +# ECS Sandboxes + +> Create a Nitro Sandbox per user or session on ECS from a Lambda Function, then run commands, use files, open terminals and call ports in it through a typed handle. + +An ECS sandbox is one ECS task in its own [Nitro Sandbox](/aws/compute/nitro-sandboxes): a lightweight VM, with its own kernel, that the Nitro hypervisor isolates from the instance it runs on and from every other task there. Your app starts one while it runs, usually one per user or session, and runs code it doesn't trust inside: a code interpreter, an agent's workspace, a build from a pull request. + +## One task per sandbox, on instances ECS runs + +Sandboxes run on **Managed Instances**: EC2 instances in your account that ECS launches, patches and replaces. A **capacity provider** tells ECS which instances it may launch. ECS launches one when a sandbox needs room and terminates it once it's empty. + +Each sandbox is a task with its own network interface and private address in your VPC. It has 20 GiB of storage, and the vCPUs of all sandboxes on an instance can add up to five times the instance's own. + + + +ECS gives each task its VM and stops there. Its API starts, stops and describes a task. It has no call that runs a command in one and returns the output, reads a file from it, or reaches a port inside it. + +`AWS.ECS.CreateSandbox` is Alchemy's layer on top. An `AWS.ECS.Task` with `isolation: "isolated"` is the sandbox's blueprint, and the binding lets a Function start tasks from it and drive each one through a handle. Isolation doesn't depend on it. An isolated Task also runs as a job or a Service with ECS's own operations and nothing of Alchemy's inside, as in [Run a task with ECS alone](#run-a-task-with-ecs-alone). + +## Give the cluster capacity for sandboxes + +Declare a network, a cluster and a capacity provider with `nitroEnclavesEnabled`: + +```typescript title="src/Infra.ts" +import * as AWS from "@alchemy.run/aws"; +import * as Effect from "effect/Effect"; + +export const Network = AWS.EC2.Network("Network", { + cidrBlock: "10.0.0.0/16", + nat: "single", +}); + +export const Cluster = AWS.ECS.Cluster("Cluster", {}); + +export const Capacity = Effect.gen(function* () { + const cluster = yield* Cluster; + const network = yield* Network; + return yield* AWS.ECS.CapacityProvider("Capacity", { + cluster: cluster.clusterName, + managedInstancesProvider: { + instanceLaunchTemplate: { + networkConfiguration: { subnets: network.privateSubnetIds }, + nitroEnclavesEnabled: true, + }, + }, + }); +}); +``` + +The capacity provider creates the two roles ECS needs, the instance profile, and a security group each for the instances and the sandboxes. It picks from 4 to 16 vCPU `m6i`, `m7i`, `c6i`, `c7i`, `r6i` and `r7i` instance types, which all support Nitro Sandboxes. Set `instanceRequirements` to choose your own. + +The instances sit in private subnets and pull the sandbox's image through the NAT gateway. A Function attached to those subnets calls ECS through it too. Deploying launches no instance. + +## Pick the image each sandbox runs + +A sandbox starts from an image. Declare a Task with the image and the size of each sandbox: + +```typescript title="src/MyImage.ts" +import * as AWS from "@alchemy.run/aws"; + +export const MyImage = AWS.ECS.Task("MyImage", { + image: "python:3.12-slim", + cpu: 1024, + memory: 2048, + isolation: "isolated", +}); +``` + +`isolation: "isolated"` puts every task started from it in its own Nitro Sandbox. The image needs no server and no code of yours, and deploy pushes it to a repository in your account unchanged. + +A small agent answers the handle's calls. It is an image of its own: when a sandbox starts, ECS mounts it read-only at `/opt/alchemy/sandbox`, with its own runtime, so any Linux image works, with or without Bun or Node.js installed. [What CreateSandbox adds to a Task](#what-createsandbox-adds-to-a-task) has the details. + +To install your own tools, build the image from a Dockerfile with `context` in place of `image`: + +```typescript title="src/MyImage.ts" +import * as AWS from "@alchemy.run/aws"; + +export const MyImage = AWS.ECS.Task("MyImage", { + context: "./sandbox", + cpu: 1024, + memory: 2048, + isolation: "isolated", +}); +``` + +## Create a sandbox from a Lambda Function + +`AWS.ECS.CreateSandbox` takes the capacity provider and the Task. This Function starts a sandbox for each request and kills it when the request ends: + +```typescript title="src/Api.ts" +import * as AWS from "@alchemy.run/aws"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; +import { Capacity } from "./Infra.ts"; +import { MyImage } from "./MyImage.ts"; + +export default class Api extends AWS.Lambda.Function()( + "Api", + { + main: import.meta.url, + functionUrl: true, + // The first sandbox waits for ECS to launch an instance. + timeout: Duration.minutes(6), + }, + Effect.gen(function* () { + const sandboxes = yield* AWS.ECS.CreateSandbox(Capacity, MyImage); + + return { + fetch: Effect.gen(function* () { + const sandbox = yield* Effect.acquireRelease(sandboxes.create(), (sandbox) => + Effect.ignore(sandbox.kill()), + ); + const result = yield* sandbox.exec("uname -a"); + return HttpServerResponse.text(result.stdout); + }).pipe(Effect.orDie), + }; + }).pipe(Effect.provide(AWS.ECS.CreateSandboxHttp)), +) {} +``` + +The binding grants the Function's role what it needs to run, stop, describe and list the Task's tasks on this cluster, and attaches the Function to the capacity provider's subnets so it can reach each sandbox at its private address. + +`create` returns once the sandbox answers. On an empty cluster that includes the time ECS takes to launch an instance, so give the Function a `timeout` of a few minutes. `startTimeout` bounds the wait, five minutes by default, and a sandbox that misses it is stopped and fails with `EcsSandboxStartFailed`. + +The Stack only has to yield the Function: + +```typescript title="alchemy.run.ts" +import * as AWS from "@alchemy.run/aws"; +import * as Alchemy from "alchemy"; +import * as Effect from "effect/Effect"; +import Api from "./src/Api.ts"; + +export default Alchemy.Stack( + "MyApp", + { providers: AWS.providers(), state: Alchemy.localState() }, + Effect.gen(function* () { + const api = yield* Api; + return { url: api.functionUrl }; + }), +); +``` + + + +## Keep a sandbox per user + +Tag each sandbox with who it belongs to, then find it again by that tag: + +```typescript +// in fetch +const [existing] = yield* sandboxes.list({ tags: { user } }); +const sandbox = + existing !== undefined + ? yield* sandboxes.connect(existing.taskArn) + : yield* sandboxes.create({ tags: { user }, idleTimeout: "15 minutes" }); +``` + +`list` returns the running sandboxes of this Task that carry every tag you pass. `connect` returns the handle of one by its task ARN, and fails with `EcsSandboxNotFound` when it has stopped. + +With `idleTimeout`, a sandbox stops itself once it has received no call for that long. Without it, a sandbox runs until you kill it. + +## Run commands + +```typescript +yield* sandbox.files.write("/work/main.py", `import sys; print("hi " + sys.argv[1])`); +const result = yield* sandbox.exec("python3 main.py sam", { cwd: "/work" }); +// { exitCode: 0, stdout: "hi sam\n", stderr: "" } +``` + +`exec` runs a command to completion. A non-zero exit code is returned, not failed. A string runs in a shell, and `exec(["python3", "--version"])` runs an argument vector without one. `env` and `stdin` feed the command, and `timeout` kills it and fails with `SandboxExecTimedOut`. + +## Stream a process + +```typescript +const decoder = new TextDecoder(); +const process = yield* sandbox.start("python3 -m unittest", { cwd: "/work" }); +yield* process.output.pipe( + Stream.runForEach((chunk) => Effect.logInfo(chunk.fd, decoder.decode(chunk.data))), +); +const { exitCode } = yield* process.wait; +``` + +`start` returns a `Process` with its `output`, `write`, `kill` and `wait`. Closing the scope detaches; the process keeps running in the sandbox. + +`sandbox.attach(process.id)` returns the same process in a later request. Its `output` replays the most recent output, up to 1 MiB, then follows it live. + +## Read and write files + +```typescript +yield* sandbox.files.write("/work/notes.txt", "remember this"); +const text = yield* sandbox.files.readText("/work/notes.txt"); +const entries = yield* sandbox.files.list("/work"); +yield* sandbox.files.remove("/work/notes.txt"); +``` + +`write` creates the file's parent directories. `files` also has `read` for bytes, `stat` and `makeDir`. Files live on the sandbox's own disk and are gone when it stops. + +## Open a terminal + +```typescript +const decoder = new TextDecoder(); +const pty = yield* sandbox.pty.open({ cols: 80, rows: 24 }); +const output = yield* pty.output.pipe( + Stream.map((chunk) => decoder.decode(chunk)), + Stream.mkString, + Effect.forkScoped, +); +yield* pty.write("ls /work; exit\n"); +const text = yield* Fiber.join(output); +``` + +`pty.output` streams the terminal's bytes until its shell exits, and `pty.resize` changes its size. The shell is `bash` when the image has it, and `sh` otherwise. + +## Call a port + +```typescript +const port = yield* sandbox.getTcpPort(8080); +const response = yield* port.fetch(HttpClientRequest.get("/health")); +``` + +`getTcpPort` reaches any port a process in the sandbox listens on, not only the Task's own. `port.fetch` also takes the request the Function received and proxies it to the port, and `port.url` is the port's address inside the VPC. + +A sandbox has no public URL. To serve one to a browser, proxy through the Function. A Lambda function URL can't carry a WebSocket, so for those put an [ECS Service](/aws/compute/ecs) behind a load balancer in front of the sandboxes instead. + +## Start a process in every sandbox + +A sandbox starts the image's own `ENTRYPOINT` and `CMD`, as the image's user, like any container. Set the Task's `command` to run something else in place of the `CMD`: + +```typescript title="src/MyImage.ts" +import * as AWS from "@alchemy.run/aws"; + +export const MyImage = AWS.ECS.Task("MyImage", { + image: "python:3.12-slim", + command: ["python3", "-m", "http.server", "8080"], + cpu: 1024, + memory: 2048, + isolation: "isolated", +}); +``` + +The agent starts the process when the sandbox does and keeps answering the handle next to it. The sandbox keeps running after the process exits. A `CMD` that waits for a terminal, like this image's `python3`, exits at once, because a sandbox starts without one. + +## Run a program of your own in each sandbox + +A Task can be an Effect program in place of an image. The program runs in every sandbox, answers the handle's calls itself, and adds typed methods of its own: + +```typescript title="src/MySandbox.ts" +import * as AWS from "@alchemy.run/aws"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +export default class MySandbox extends AWS.ECS.Task< + MySandbox, + { hello: (name: string) => Effect.Effect } +>()( + "MySandbox", + { + main: import.meta.url, + port: 3000, + cpu: 1024, + memory: 2048, + isolation: "isolated", + }, + Effect.gen(function* () { + return { + fetch: Effect.succeed(HttpServerResponse.text("ok")), + hello: Effect.fn(function* (name: string) { + return `hello ${name}`; + }), + }; + }), +) {} +``` + +Deploy bundles the program into an image, `oven/bun:1` unless you set `image`, and pushes it to a repository in your account. Pass the class to `CreateSandbox` where `MyImage` went: + +```typescript +const sandboxes = yield* AWS.ECS.CreateSandbox(Capacity, MySandbox); +``` + +The handle then has every method the program returns, with its types: + +```typescript +const greeting = yield* sandbox.hello("sam"); +``` + +Use them for work you'd rather write once inside the sandbox than compose from commands. Terminals need the program to run on Bun, which the default image does. + +## Stop a sandbox + +```typescript +yield* sandbox.kill(); +``` + +`kill` stops the task. `connect` and `list` stop returning it at once, while ECS can take a minute or so to shut the task down. + +A sandbox with an `idleTimeout` also stops by itself. Calls through the handle and open process or terminal streams keep it alive. Traffic to a port from `getTcpPort` doesn't. + +Sandboxes aren't resources in your Stack. Each carries the tags `alchemy::stack`, `alchemy::stage` and `alchemy::id`, and destroying the capacity provider stops every sandbox on it. + +## What CreateSandbox adds to a Task + +A handle needs something inside the sandbox to answer it, and ECS provides nothing. For a Task with an image, the binding adds the agent to the Task's task definition. Your image stays as you built it. + + + +The container `alchemy-sandbox-agent` starts first. It copies the agent and its runtime into a volume of the task, and exits. + +Your image's container then mounts that volume read-only and starts the agent as its entry point. The agent runs the image's `ENTRYPOINT` and `CMD` as its child and listens on port 2468 for the handle's calls. + +A Task that is an Effect program gets neither. The program is the container's process, and it answers the handle itself on the Task's `port`. + +### Other runs of the same Task + +A Task has one task definition, so a task started from it another way, by an [ECS Service](/aws/compute/ecs) or `AWS.ECS.RunTask`, has the agent's container and entry point too. + +Those tasks get no token. Without one the agent doesn't listen. It runs the image's `ENTRYPOINT` and `CMD` and exits with their exit code, as the container would have alone. One thing differs: a `command` override on such a run replaces the image's `ENTRYPOINT` along with its `CMD`. + +## Run a task with ECS alone + +A Task that no `CreateSandbox` binds has nothing of Alchemy's in it. Its task definition holds the container you declare, and `isolation: "isolated"` still gives each run its own Nitro Sandbox: + +```typescript title="src/MyJob.ts" +import * as AWS from "@alchemy.run/aws"; + +export const MyJob = AWS.ECS.Task("MyJob", { + image: "python:3.12-slim", + command: ["python3", "-c", "print('hello from a sandbox')"], + cpu: 1024, + memory: 2048, + isolation: "isolated", +}); +``` + +Start it from a Function with `AWS.ECS.RunTask`, which is ECS's own operation: + +```typescript title="src/Jobs.ts" +import * as AWS from "@alchemy.run/aws"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; +import { Capacity, Cluster } from "./Infra.ts"; +import { MyJob } from "./MyJob.ts"; + +export default class Jobs extends AWS.Lambda.Function()( + "Jobs", + { main: import.meta.url, functionUrl: true }, + Effect.gen(function* () { + const capacity = yield* Capacity; + const runTask = yield* AWS.ECS.RunTask(Cluster, MyJob); + const CapacityName = yield* capacity.name; + const Subnets = yield* capacity.subnets; + + return { + fetch: Effect.gen(function* () { + const { tasks } = yield* runTask({ + capacityProviderStrategy: [{ capacityProvider: yield* CapacityName, weight: 1 }], + networkConfiguration: { awsvpcConfiguration: { subnets: yield* Subnets } }, + }); + return HttpServerResponse.text(tasks?.[0]?.taskArn ?? "no task started"); + }).pipe(Effect.orDie), + }; + }).pipe(Effect.provide(AWS.ECS.RunTaskHttp)), +) {} +``` + +The binding grants the Function's role `ecs:RunTask` on the Task and `iam:PassRole` on its roles, and fills in the cluster and the task definition. The rest of the request is ECS's: you name the capacity provider and the subnets, and the task joins the VPC's default security group unless you pass `securityGroups`. + +The task runs `command` in its sandbox and stops when it exits. It has no token, no tags and no handle. `AWS.ECS.DescribeTasks`, `AWS.ECS.ListTasks` and `AWS.ECS.StopTask` bind the same way to follow it or stop it. + +## Who can reach a sandbox + +Sandboxes join a security group that admits nothing. The binding adds one rule to it, which admits the Function's own security group. A sandbox can't open a connection to the Function or to another sandbox through these groups, and nothing outside the VPC can reach one. + +Each sandbox also gets a random token when it starts. Every call through the handle carries it, and the sandbox refuses `exec`, `files` and a program's methods without it. `connect` reads the token back from the task, so only a role that may describe the cluster's tasks can get a handle. Calls to a port carry no token: whatever listens there, a program's own `fetch` included, answers anything the security groups admit. + +:::caution +The code you run shares the sandbox's VM with the agent or program that answers the handle, and runs as the Task's role. Give the Task only the bindings you'd hand to the code inside, and keep one person's work to one sandbox. +::: + +Only a Lambda Function is attached to the subnets for you. A host that already runs in the VPC, like an ECS Service, reaches sandboxes through a security group of your own that admits it: pass `securityGroups` to `CreateSandbox`, and every sandbox joins them next to the capacity provider's group. + +```typescript +const sandboxes = yield* AWS.ECS.CreateSandbox(Capacity, MyImage, { + securityGroups: [sandboxAccess.groupId], +}); +``` + +## Where next + +- [Nitro Sandboxes](/aws/compute/nitro-sandboxes): how the isolation works, and isolated against confidential mode. +- [ECS](/aws/compute/ecs): Tasks, Services and their images. +- [Lambda MicroVMs](/aws/compute/microvms): sandboxes on AWS's machines, with no instances of your own. +- [CreateSandbox reference](/providers/aws/ecs#createsandbox): every option of `create`, `connect` and `list`. +- [`examples/aws-ecs-sandboxes`](https://github.com/alchemy-run/alchemy/tree/main/examples/aws-ecs-sandboxes): one sandbox per user behind a Function URL. diff --git a/.agents/skills/alchemy/references/aws/compute/ecs.md b/.agents/skills/alchemy/references/aws/compute/ecs.md index c13e387a..29d9687c 100644 --- a/.agents/skills/alchemy/references/aws/compute/ecs.md +++ b/.agents/skills/alchemy/references/aws/compute/ecs.md @@ -1,319 +1,243 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # ECS -> Run containers on AWS with ECS and Fargate — Task definitions that run to completion, Services that keep containers running behind a load balancer, with images bundled from an Effect program, built from your Dockerfile, or mirrored from a registry. - -**ECS** (Elastic Container Service) is AWS's managed container -orchestrator: you describe a container — image, CPU, memory — and -ECS runs it. With **Fargate**, AWS also provides the machines, so -there are no servers to manage. - -ECS has four primitives: - -- A **Cluster** is the space your containers run in. -- A **Task Definition** is the blueprint: which image, how much - CPU and memory, which IAM roles, which ports. -- A **Task** is a running container launched from a Task - Definition. It runs until its process exits. -- A **Service** keeps a set number of Tasks running — restarting - ones that stop, optionally routing traffic to them through a - load balancer. - -Alchemy models these directly: -[`Cluster`](/providers/aws/ecs/cluster), -[`Task`](/providers/aws/ecs/task) — a task definition plus -everything needed to build and publish its image — and -[`Service`](/providers/aws/ecs/service). Each can run a plain -container image, or an Effect program that Alchemy bundles into -one. - -## Run a Task - -The simplest `Task` runs a pre-built registry image — no Effect -runtime in the container: - -```typescript -// alchemy.run.ts -import * as AWS from "alchemy/AWS"; - -const migrate = yield* AWS.ECS.Task("DbMigrate", { - image: "public.ecr.aws/docker/library/busybox:stable", - command: ["sh", "-c", "echo done"], - cpu: 256, - memory: 512, +> How ECS runs containers on Fargate through clusters, task definitions, tasks and services, and how to run a server, a one-off job or a scheduled job from an image, a Dockerfile or an Effect program. + +ECS runs containers. You describe a container, its image, CPU and memory, and ECS keeps it running. With **Fargate**, AWS also provides the machines underneath, so there are no servers to patch or scale. + +A container is a whole process, so it fits work that doesn't fit an invocation: a server that holds WebSockets or database connections open, a worker that loops forever, a job that runs for hours, a program that already ships as an image. + +## Clusters, task definitions, tasks and services + +A **task definition** is a blueprint: which image, how much CPU and memory, which ports, which IAM role. A **task** is a running container started from it, and it runs until its process exits. A **service** keeps a number of tasks running, replaces any that stop, and optionally puts a load balancer in front of them. All of them run in a **cluster**. + +```text +Diagram (nodes and edges as authored): + +``` + +In Alchemy, `AWS.ECS.Task` is a task definition together with everything that builds its image, and `AWS.ECS.Service` keeps tasks running, with or without a Task of its own. + +## Run a server from an image + +Declare a cluster, then a Service that runs an image. `loadBalancer: true` puts a public Application Load Balancer in front of it: + +```typescript title="alchemy.run.ts" +const cluster = yield* AWS.ECS.Cluster("AppCluster", {}); + +const web = yield* AWS.ECS.Service("Web", { + cluster, + image: "public.ecr.aws/nginx/nginx:1.27", + port: 80, + desiredCount: 2, + loadBalancer: true, }); + +return { url: web.url }; ``` -Deploying a `Task` automates the container supply chain: -Alchemy provisions the **task and execution IAM roles**, a -**CloudWatch log group**, and a **generated ECR repository** -holding the image, then registers a Fargate task definition. Each -deploy registers a new immutable revision. - -## Three image sources - -The image comes from exactly one of three sources, flat on the -props: - -- `image` — run a pre-built registry reference, mirrored into ECR - (pull → tag → push, content-addressed). -- `context` — build your own Dockerfile with your - [local Docker](/docker/setup). `dockerfile` is always a **path**, - defaulting to `${context}/Dockerfile`: - - ```typescript - const render = yield* AWS.ECS.Task("RenderJob", { - context: "./render", - dockerfile: "./render/Dockerfile.gpu", - cpu: 1024, - memory: 4096, - }); - ``` - -- `main` — bundle an inline Effect program into a generated image. - Compose with `image` to pick the environment base (default - `oven/bun:1`), or with an inline `dockerfile` - (`Dockerfile.inline`) when the environment needs extra build - steps. - -:::tip -`runtimePlatform.cpuArchitecture` picks the architecture the task -runs on in Fargate (default `X86_64`). Alchemy builds or mirrors -the image for whatever the task definition declares, regardless of -the machine you build on. Declaring `"ARM64"` runs the task on -Graviton — cheaper per vCPU, and image builds happen to be native -(no emulation) on Apple Silicon machines. -::: - -## Run an Effect program in a Task - -Pass `main: import.meta.url` and a constructor Effect whose impl -returns `{ run }` — the program runs to completion when the -container starts, then the container exits. Bindings work exactly -as on Lambda, attaching environment variables and IAM policy -statements to the task: - -```typescript -const drainer = yield* AWS.ECS.Task( - "QueueDrainer", - { main: import.meta.url, image: "oven/bun:1", cpu: 256, memory: 512 }, +Deploy copies the image into a repository in your account, creates the task's roles and log group, registers the task definition, and starts two tasks behind the load balancer. Without `vpcId` and `subnets`, the tasks run in your account's default VPC. Give them a network of your own for production. See [VPC & networking](/aws/networking). + +## Run your own program + +Give the Service `main` and an Effect, and Alchemy builds an image from your program. The program returns a `fetch` handler, and binds what it uses exactly as a Lambda Function does: + +```typescript title="alchemy.run.ts" +const api = yield* AWS.ECS.Service( + "Api", + { cluster, main: import.meta.url, port: 3000, desiredCount: 2, cpu: 256, memory: 512, loadBalancer: true }, Effect.gen(function* () { - const receive = yield* AWS.SQS.ReceiveMessage(queue); + const putItem = yield* AWS.DynamoDB.PutItem(Items); return { - run: Effect.gen(function* () { - // runs to completion, then the container exits - const batch = yield* receive({ MaxNumberOfMessages: 10 }); - }), + fetch: Effect.succeed(HttpServerResponse.json({ ok: true })), }; - }), + }).pipe(Effect.provide(AWS.DynamoDB.PutItemHttp)), ); ``` -The tagged form -(`class Reindexer extends AWS.ECS.Task()("Reindexer") {}` -+ `Reindexer.make(props, impl)`) works exactly as it does on -Lambda and Cloudflare Workers. +Each binding adds its statement to the **task role**, the role the container runs as, and its environment variables to the container. -## Invoke and schedule Tasks +The image comes from one of three places: `image`, an image from any registry, copied into your account; `context`, your own Dockerfile, built with your local Docker; or `main`, your Effect program, bundled into a base image, `oven/bun:1` unless you set `image`. Images are built for the architecture the task runs on. Set `runtimePlatform: { cpuArchitecture: "ARM64" }` to run on Graviton, which costs less per vCPU. -A `Task` is the target of the ECS control-plane bindings. From a -Lambda function, a Service, or any other host, bind -[`RunTask`](/providers/aws/ecs/runtask) in the **Construction phase** — -this grants the host `ecs:RunTask` plus `iam:PassRole` on the -task's roles — then call it from a handler at **runtime**, where -the cluster and task definition ARNs are injected automatically: +## Cache build layers -```typescript -const api = yield* AWS.Lambda.Function( - "Api", - { main: import.meta.url, functionUrl: true }, - Effect.gen(function* () { - // Construction: bind the launch (IAM grants happen here) - const runTask = yield* AWS.ECS.RunTask(cluster, task); +Builds from `context` or `main` reuse the local BuildKit cache of the machine they run on. A fresh CI runner has none and rebuilds every step. Keep the layers in the task's ECR repository with `build.cache`: + +```typescript title="alchemy.run.ts" +const api = yield* AWS.ECS.Service("Api", { + cluster, + context: "./api", + port: 8080, + build: { cache: true }, +}); +``` + +Builds then import and export every stage's layers at the repository's `:buildcache` tag. The cache is off by default and never changes the image, so turning it on doesn't start a deployment. Other backends take BuildKit's cache backends, as in [Docker builds](/docker/build-caches). + +## Run a job to completion +A Task on its own runs until its process exits. Give it a `run` Effect instead of `fetch`: + +```typescript title="alchemy.run.ts" +const reindex = yield* AWS.ECS.Task( + "Reindex", + { main: import.meta.url, cpu: 1024, memory: 2048 }, + Effect.gen(function* () { + const scan = yield* AWS.DynamoDB.Scan(Items); return { - fetch: Effect.gen(function* () { - // runtime: launch a task per request - const response = yield* runTask({ - launchType: "FARGATE", - networkConfiguration: { - awsvpcConfiguration: { subnets: [subnetId] }, - }, - }); - return yield* HttpServerResponse.json({ - taskArn: response.tasks?.[0]?.taskArn, - }); + run: Effect.gen(function* () { + const page = yield* scan({}); + yield* Effect.log(`reindexing ${page.Count} items`); }), }; - }), + }).pipe(Effect.provide(AWS.DynamoDB.ScanHttp)), ); ``` -For cron-style execution, `AWS.ECS.every` provisions an -EventBridge rule (plus the invoke role) that runs the task on a -schedule — plain-English durations normalize to `rate(...)`, and -`cron(...)` expressions pass through as-is: +Start it from another runtime by binding `ECS.RunTask`, which grants permission to run that task and pass its roles: -```typescript -yield* AWS.ECS.every("NightlyJob", "cron(0 3 * * ? *)", { +```typescript title="src/api.ts" +const runTask = yield* AWS.ECS.RunTask(cluster, reindex); +yield* runTask({ + launchType: "FARGATE", + networkConfiguration: { awsvpcConfiguration: { subnets: network.privateSubnetIds } }, +}); +``` + +## Run a job on a schedule + +`ECS.every` runs a Task on a rate or a cron expression, with the role the schedule needs to start it: + +```typescript title="alchemy.run.ts" +yield* AWS.ECS.every("NightlyReindex", "cron(0 3 * * ? *)", { cluster, - task: nightlyTask, - subnets: [privateSubnet1.subnetId, privateSubnet2.subnetId], - securityGroups: [jobSecurityGroup.groupId], + task: reindex, + subnets: network.privateSubnetIds, + securityGroups: [jobs.groupId], }); ``` -## Keep a server running with a Service +See [EventBridge & Scheduler](/aws/messaging/eventbridge#schedule-containers). -A `Service` keeps `desiredCount` copies of a container alive. -It takes the same three image sources as `Task` — synthesizing -its own task definition — and `loadBalancer: true` provisions a -public **Application Load Balancer**, target group, and listener -in front of it: +## Do work in the background -```typescript -const cluster = yield* AWS.ECS.Cluster("AppCluster", {}); +A container is always running, so it can do more than answer requests. Register a loop with `ServerHost`, and it runs alongside the `fetch` handler for the life of the container: -const nginx = yield* AWS.ECS.Service("Edge", { - cluster, - image: "public.ecr.aws/nginx/nginx:1.27", - port: 80, - desiredCount: 2, - loadBalancer: true, +```typescript title="alchemy.run.ts" +Effect.gen(function* () { + const host = yield* ServerHost; + yield* host.run(Effect.log("heartbeat").pipe(Effect.repeat(Schedule.spaced("30 seconds")), Effect.asVoid)); + return { fetch: Effect.succeed(HttpServerResponse.text("ok")) }; }); +``` + +Use it for polling, draining a queue, or a connection that stays open across requests. + +## Process scope and request scope + +A container is a real process. What Construction acquires, a pool or a connection, lives until the process shuts down, and its finalizers run when ECS stops the task gracefully. Each request still gets its own `Scope`, closed when the response is sent. + +This is the main difference from Lambda, where an environment can be frozen between invocations and its finalizers only get a moment at shutdown. See [Instance scope vs request scope](/infrastructure-as-effects/runtime#instance-scope-vs-request-scope). -return { url: nginx.url }; // http:// +## Deploy changes + +Each deploy registers a new revision of the task definition. The Service then replaces its tasks with ones from the new revision, a few at a time, so it keeps serving. Changes to the count, the network, the load balancer and deployment settings apply the same way. + +A few changes can't be applied to a running service, like its name or its cluster. Those replace the Service. + +## Pay less for workers + +Tasks cost the same whether busy or idle. For work that can be interrupted, run on **Fargate Spot**, AWS's spare capacity at a steep discount, with a share on regular Fargate so the service never disappears entirely: + +```typescript title="alchemy.run.ts" +capacityProviderStrategy: [ + { capacityProvider: "FARGATE_SPOT", weight: 3 }, + { capacityProvider: "FARGATE", weight: 1, base: 1 }, +], ``` -Networking is optional to start: when `vpcId`/`subnets` are -omitted the account's **default VPC** (and its per-AZ subnets) is -used, and when `securityGroups` is omitted with -`loadBalancer: true`, Alchemy provisions a security group that -admits the listener port. For a real deployment, build a -dedicated VPC with the [`Network`](/providers/aws/ec2/network) -helper and pass `vpcId` + `subnets` — see -[VPC & networking](/aws/networking). +A Spot task gets two minutes' notice before it's stopped, so keep its work resumable. -An effectful `Service` is the server counterpart: where a `Task` -impl returns `{ run }`, a `Service` impl returns `{ fetch }`: +## Isolate each task in its own VM -```typescript -const api = yield* AWS.ECS.Service( - "Api", - { cluster, main: import.meta.url, port: 3000, desiredCount: 2, cpu: 256, memory: 512 }, - Effect.gen(function* () { - const putItem = yield* AWS.DynamoDB.PutItem(table); - return { - fetch: Effect.gen(function* () { - return yield* HttpServerResponse.json({ ok: true }); - }), - }; - }).pipe(Effect.provide(AWS.DynamoDB.PutItemHttp)), -); +Tasks that share an instance share its kernel. To run code you don't trust, like a tenant's container or an agent's generated code, give each task its own [Nitro Sandbox](/aws/compute/nitro-sandboxes): a lightweight VM that the Nitro hypervisor isolates from the instance and from every other task on it. + +Sandboxes don't run on Fargate. They run on **Managed Instances**, EC2 instances that ECS launches, patches and replaces for you. Give the cluster a capacity provider whose instances can run sandboxes: + +```typescript title="alchemy.run.ts" +const capacity = yield* AWS.ECS.CapacityProvider("Capacity", { + cluster: cluster.clusterName, + managedInstancesProvider: { + instanceLaunchTemplate: { + networkConfiguration: { subnets: network.privateSubnetIds }, + nitroEnclavesEnabled: true, + }, + }, +}); ``` -## Reuse a Task's definition +The capacity provider creates the role ECS assumes to launch instances, the role and instance profile the instances run as, and their security group. Pass `infrastructureRoleArn` and `ec2InstanceProfileArn` to use your own. It picks instance types that support sandboxes unless you set `instanceRequirements`. -A `Service` can also deploy an existing `Task`'s definition -instead of owning an image — shared image, roles, and config; the -Service adds `desiredCount`, load balancing, and deployment -configuration: +Deploy waits until the capacity provider is `ACTIVE`. ECS launches instances only once tasks need them, and terminates them when you destroy the provider. -```typescript -const api = yield* AWS.ECS.Service("Api", { +Then set the isolation mode on the task definition, and run it on that capacity: + +```typescript title="alchemy.run.ts" +const task = yield* AWS.ECS.TaskDefinition("MyTask", { + requiresCompatibilities: ["MANAGED_INSTANCES"], + networkMode: "awsvpc", + cpu: 1024, + memory: 2048, + trustedExecutionConfiguration: { isolationMode: "ISOLATED_SANDBOX" }, + containerDefinitions: [{ name: "app", image: "ghcr.io/acme/app:1", essential: true }], +}); + +yield* AWS.ECS.Service("MyService", { cluster, - task: apiTask, + task, desiredCount: 2, - loadBalancer: true, + capacityProviderStrategy: [{ capacityProvider: capacity.name, weight: 1 }], + vpcId: network.vpcId, + subnets: network.privateSubnetIds, }); ``` -Most service configuration — desired count, task definition -revision, network config, deployment settings, load balancers — -updates **in place** as a rolling deployment; only truly -immutable aspects (service name, cluster, scheduling strategy, -deployment controller type, switching between `launchType` and -`capacityProviderStrategy`) replace the service. For -cost-sensitive workers, swap `launchType` (default `"FARGATE"`) -for a `capacityProviderStrategy` mixing `FARGATE_SPOT` and -`FARGATE` — see the -[`Service` reference](/providers/aws/ecs/service) for the -placement, deployment, and Service Connect knobs. - -## Run background work - -Containers are always-on, so an effectful container can do more -than answer requests. Yield `ServerHost` and register -long-running loops with `host.run` — they execute alongside the -HTTP handler for the life of the container: - -```diff lang="typescript" -import * as AWS from "alchemy/AWS"; -+import { ServerHost } from "alchemy/Server"; -import * as Effect from "effect/Effect"; -+import * as Schedule from "effect/Schedule"; +An `AWS.ECS.Task`, built from an image or from your own program, takes `isolation: "isolated"` instead, which sets both: - Effect.gen(function* () { -+ const host = yield* ServerHost; -+ -+ yield* host.run( -+ Effect.log("heartbeat").pipe( -+ Effect.repeat(Schedule.spaced("30 seconds")), -+ Effect.asVoid, -+ ), -+ ); -+ - return { - fetch: Effect.gen(function* () { - // ... - }), - }; - }), +```typescript title="alchemy.run.ts" +const job = yield* AWS.ECS.Task("MyJob", { + image: "python:3.12-slim", + command: ["python3", "-c", "print('hello from a sandbox')"], + cpu: 1024, + memory: 2048, + isolation: "isolated", +}); ``` -Use this for polling loops, queue drainers, or connections that -stay open across requests. - -## Process scope vs request scope - -An ECS container is a **real process**, and its instance scope -reflects that: the bundled program runs under a root scope that -closes when the process shuts down gracefully, so resources -acquired in the constructor — the connection a `host.run` loop holds open, a -warm pool shared across requests — are genuinely released on exit. -Serverless runtimes only approximate this: workerd never closes -its instance scope at all, and Lambda gets a best-effort 500 ms -SIGTERM window; a server gets a real graceful shutdown (a hard -kill still skips finalizers, as in any process). - -Each HTTP request still gets its own request `Scope`, released when -the response settles — the same per-event contract as every other -runtime. See -[Instance scope vs request scope](/infrastructure-as-effects/runtime#instance-scope-vs-request-scope) -for the model across all runtimes. - -## Bindings - -`Task` and `Service` declare the same binding contract as a -Lambda `Function`: bindings attach **environment variables and -IAM policy statements**, which Alchemy folds into the container -environment and the task role. The ECS control-plane bindings -(`RunTask`, `StopTask`, `ListTasks`, `DescribeTasks`) work from -Lambda functions and from other containers — useful for a -function that fans work out to containers. - -## Where next - -- [Choosing a runtime](/aws/compute/choosing-a-runtime) — when Lambda, - EKS, or EC2 fits better than ECS. -- [VPC & networking](/aws/networking) — what the `Network` - helper creates, and the primitives underneath it. -- [EKS](/aws/compute/eks) — the same platform model on managed - Kubernetes. -- [`Task` reference](/providers/aws/ecs/task), - [`Service` reference](/providers/aws/ecs/service), - [`Cluster` reference](/providers/aws/ecs/cluster) — every prop - and attribute. +To start one on demand with `AWS.ECS.RunTask` rather than keep a Service running, see [Run a task with ECS alone](/aws/compute/ecs-sandboxes#run-a-task-with-ecs-alone). + +Each running task reports `trustedExecutionSummary.isolationMode` as `ISOLATED_SANDBOX`. For `CONFIDENTIAL_SANDBOX`, where the instance can't read the task's memory either, add an `attestationPolicy` that names the containers allowed to run. See [Isolated or confidential](/aws/compute/nitro-sandboxes#isolated-or-confidential). + +Each task boots its own VM, so it starts slower than a shared one. An instance can hold many sandboxes: their vCPUs can add up to five times its own, and their memory must fit in its memory. + +This is ECS as AWS provides it: a task in its own VM that you start, stop and describe. `AWS.ECS.CreateSandbox` is Alchemy's construct on top. It starts a sandbox per user or session while your app runs, and hands back a typed handle that runs commands, uses files and calls ports inside. See [ECS Sandboxes](/aws/compute/ecs-sandboxes). diff --git a/.agents/skills/alchemy/references/aws/compute/effect-workflows.md b/.agents/skills/alchemy/references/aws/compute/effect-workflows.md new file mode 100644 index 00000000..cc56a6c1 --- /dev/null +++ b/.agents/skills/alchemy/references/aws/compute/effect-workflows.md @@ -0,0 +1,255 @@ + + +# Effect workflows + +> Run Effect workflows on AWS Lambda durable functions. Host them in an AWS.Lambda.WorkflowFunction, start runs from other functions with AWS.Lambda.DurableFunctionEngine, and let them sleep and wait durably. + +An Effect workflow is a durable process written with `effect/workflow`: a +series of steps whose results are stored, so a run that's interrupted +resumes after its last finished step, and a run can wait hours or days for +a timer or a signal. On AWS they run on Lambda durable functions: each run +is one durable execution. + +The same workflow code runs on Cloudflare too. See +[Effect workflows on Cloudflare](/cloudflare/compute/effect-workflows). + +## Define a workflow + +`Workflow.make` declares the workflow, and `Workflows.layer` implements it. +Each step is an `Activity`: a named Effect whose result is stored the first +time it completes. + +```typescript +// src/orders.ts +import * as Workflows from "alchemy/Workflows"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import { Activity, Workflow } from "effect/workflow"; + +export const PlaceOrder = Workflow.make("PlaceOrder", { + payload: { orderId: Schema.String }, + success: Schema.String, + idempotencyKey: ({ orderId }) => orderId, +}); + +export const PlaceOrderLive = Workflows.layer( + PlaceOrder, + Effect.fn(function* ({ orderId }) { + return yield* Activity.make({ + name: "charge", + success: Schema.String, + execute: Effect.succeed(`charged ${orderId}`), + }); + }), +); +``` + +## Use bindings in a step + +Pass `Workflows.layer` an Effect that returns the handler instead of the +handler itself. The Effect runs once, when the function starts, so resolve +bindings there and use them in the steps: + +```typescript +// src/receipts.ts +import * as AWS from "@alchemy.run/aws"; +import * as Workflows from "alchemy/Workflows"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import { Activity, Workflow } from "effect/workflow"; + +export const Receipts = AWS.S3.Bucket("Receipts"); + +export const SendReceipt = Workflow.make("SendReceipt", { + payload: { orderId: Schema.String }, + idempotencyKey: ({ orderId }) => orderId, +}); + +export const SendReceiptLive = Workflows.layer( + SendReceipt, + Effect.gen(function* () { + const putObject = yield* AWS.S3.PutObject(Receipts); + return Effect.fn(function* ({ orderId }) { + yield* Activity.make({ + name: "receipt", + execute: putObject({ + Key: `${orderId}.json`, + Body: JSON.stringify({ orderId }), + }).pipe(Effect.orDie), + }); + }); + }), +); +``` + +The binding grants the workflow function `s3:PutObject` on the bucket. +Provide its implementation on the Layer you deploy the function with: +`SendReceiptLive.pipe(Layer.provide(AWS.S3.PutObjectHttp))`. + +## Host it in a workflow function + +`AWS.Lambda.WorkflowFunction` is a durable function that runs workflows. +Declare the workflows it runs, then deploy it with the Layer that +implements them: + +```typescript +// src/OrderWorkflows.ts +import * as AWS from "@alchemy.run/aws"; +import { PlaceOrder, PlaceOrderLive } from "./orders.ts"; + +export class OrderWorkflows extends AWS.Lambda.WorkflowFunction()( + "OrderWorkflows", + { workflows: [PlaceOrder] }, +) {} + +export default OrderWorkflows.make( + { main: import.meta.url, executionTimeout: "7 days" }, + PlaceOrderLive, +); +``` + +Each run is one durable execution of the function. `executionTimeout` caps +how long one run may take in total, waits included, up to a year. + +## Host several workflows + +One function can run many workflows. List them all, and merge their Layers: + +```typescript +// src/OrderWorkflows.ts +import * as AWS from "@alchemy.run/aws"; +import * as Layer from "effect/Layer"; +import { PlaceOrder, PlaceOrderLive, RefundOrder, RefundOrderLive } from "./orders.ts"; + +export class OrderWorkflows extends AWS.Lambda.WorkflowFunction()( + "OrderWorkflows", + { workflows: [PlaceOrder, RefundOrder] }, +) {} + +export default OrderWorkflows.make( + { main: import.meta.url, executionTimeout: "7 days" }, + Layer.mergeAll(PlaceOrderLive, RefundOrderLive), +); +``` + +The Layer must implement every workflow the function lists: leaving one out +is a type error. A workflow's child workflows run in the same function, so +list them too. + +## Start a run from another function + +`AWS.Lambda.DurableFunctionEngine` runs workflows on the functions that host +them. Provide it to the calling function, and get a client with +`Workflows.RunWorkflow`: + +```typescript +// src/Api.ts +import * as AWS from "@alchemy.run/aws"; +import * as Workflows from "alchemy/Workflows"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; +import { OrderWorkflows } from "./OrderWorkflows.ts"; +import { PlaceOrder } from "./orders.ts"; + +export class Api extends AWS.Lambda.Function()("Api") {} + +export default Api.make( + { main: import.meta.url, functionUrl: true }, + Effect.gen(function* () { + const placeOrder = yield* Workflows.RunWorkflow(PlaceOrder); + return { + fetch: Effect.gen(function* () { + const run = yield* placeOrder.start({ orderId: "o-1" }); + return HttpServerResponse.text(run.executionId); + }), + }; + }).pipe(Effect.provide(AWS.Lambda.DurableFunctionEngine(OrderWorkflows))), +); +``` + +The engine grants the caller what it needs on `OrderWorkflows`: invoking it, +and reading and signalling its durable executions. `start` returns as soon +as the run is started. Starting again with the same key returns the run +already started, so a retried request never starts a second one. + +Running a workflow that none of the engine's functions list is a type error. + +## Route across functions + +Pass every function whose workflows the caller runs. Each run goes to the +function that hosts its workflow: + +```typescript +Effect.provide(AWS.Lambda.DurableFunctionEngine(OrderWorkflows, BillingWorkflows)) +``` + +## Read a run + +Store the run's `executionId`, and get the run back with `get`: + +```typescript +const run = placeOrder.get(executionId); +const status = yield* run.status; +``` + +`status` is `NotStarted`, `Running`, `Completed` with its result, `Failed` +with its error, `Interrupted`, or `Died` with a defect. `run.result` waits +for the run to finish, which suits tests and scripts more than requests. + +## Sleep durably + +`DurableClock.sleep` is a durable wait: the invocation ends, nothing is +billed while it waits, and Lambda invokes the function again when it's due. + +```typescript +yield* DurableClock.sleep({ name: "cool-off", duration: "1 hour" }); +``` + +Sleeps of a minute or less run in memory by default. Pass +`inMemoryThreshold: 0` to make a short sleep durable too. Durable sleeps +round up to whole seconds. + +## Wait for a signal + +A `DurableDeferred` is a value a run waits for, delivered from outside. The +run waits on a Lambda callback until it arrives. + +```typescript +export const Approval = DurableDeferred.make("approval", { success: Schema.String }); + +const approvedBy = yield* DurableDeferred.await(Approval); +``` + +Send it with the run's `signal`: + +```typescript +yield* approve.get(executionId).signal(Approval, "agent-7"); +``` + +The engine finds the run's callback in its execution history. A callback +only exists once the run reaches its wait, so `signal` retries for up to a +few minutes while the run gets there. + +## Undo a step when a later one fails + +`withCompensation` attaches what to do if the run fails after the step +succeeded. Compensations run last step first. + +```typescript +yield* Activity.make({ name: "reserve", execute: reserve(order) }).pipe( + Checkout.withCompensation(() => Activity.make({ name: "release", execute: release(order) })), +); +``` + +`run.interrupt` wakes a run that's waiting on a signal, which then +fails where it waits and runs its compensations. A run that's busy in a step +can only be stopped, with `StopDurableExecution`, and its compensations don't +run. + +## See what a run did + +Every step is a named operation in the durable execution, so the Lambda +console and `GetDurableExecutionHistory` show which steps ran, with their +names (`charge/1`: the step and its attempt), results and timings. diff --git a/.agents/skills/alchemy/references/aws/compute/eks.md b/.agents/skills/alchemy/references/aws/compute/eks.md index 00162e26..4e828b48 100644 --- a/.agents/skills/alchemy/references/aws/compute/eks.md +++ b/.agents/skills/alchemy/references/aws/compute/eks.md @@ -1,51 +1,45 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # EKS > Stand up an EKS Auto Mode cluster on a Network and run containers on it — Deployments for servers, Jobs for run-to-completion work, Manifests for everything else. No YAML, no kubectl. -**EKS** (Elastic Kubernetes Service) is AWS's managed Kubernetes: -AWS runs the Kubernetes control plane, and your containers run on -it as Kubernetes objects. Alchemy targets **Auto Mode**, where AWS -also manages the nodes, storage, and load-balancer integration — -no machines to operate. - -The Kubernetes primitives you'll meet here: - -- A **Cluster** is one Kubernetes installation: the API server - plus the Nodes that run your containers. -- A **Pod** is one or more containers running together — the unit - Kubernetes schedules onto Nodes. -- A **Deployment** keeps a set number of identical Pods running, - replacing ones that fail. A **Service** gives them one stable - address — and, as type `LoadBalancer`, a public one. -- A **Job** runs a Pod to completion; a **CronJob** does that on a - schedule. -- Everything in Kubernetes is an object described by a - **manifest** you apply to the Cluster. - -Alchemy models these directly: -[`Cluster`](/providers/aws/eks/cluster) with `compute: "auto"` -stands up the control plane from a VPC, and the cluster-agnostic -`alchemy/Kubernetes` workloads target it by passing the cluster -resource as their `cluster` prop: -[`Kubernetes.Deployment`](/providers/kubernetes/deployment) -synthesizes a Kubernetes `Deployment` + `Service`; -[`Kubernetes.Job`](/providers/kubernetes/job) a `Job` or `CronJob`; -and [`Kubernetes.Manifest`](/providers/kubernetes/manifest) applies -any raw Kubernetes object. The workloads live in the same TypeScript -program as the cluster, with no YAML and no `kubectl apply` step — -and the same workloads run on any other cluster your kubeconfig can -reach (`Kubernetes.KubeConfig(...)`). +EKS is AWS's managed Kubernetes. AWS runs the Kubernetes control plane, and your containers run on it as Kubernetes objects. In **Auto Mode**, AWS also manages the nodes, their storage and their load balancers, so there are no machines to operate. + +Choose EKS when you want Kubernetes itself: Helm charts, operators, raw manifests, or a team that already runs on it. For containers without Kubernetes, [ECS](/aws/compute/ecs) has less to learn and less to pay for. + +## Clusters, Pods, Deployments and Jobs + +A **cluster** is one Kubernetes installation: an API server and the **nodes** that run containers. A **Pod** is one or more containers scheduled together onto a node. A **Deployment** keeps a number of identical Pods running and replaces any that fail, and a **Service** gives them one stable address, public if it's a `LoadBalancer`. A **Job** runs a Pod until it finishes, and a **CronJob** runs one on a schedule. + + + +Every one of these is an object, described by a **manifest** and applied to the cluster. + +In Alchemy, `AWS.EKS.Cluster` creates the cluster from a VPC. The workloads come from `@alchemy.run/kubernetes`: `Kubernetes.Deployment` creates a Deployment and its Service, `Kubernetes.Job` a Job or CronJob, and `Kubernetes.Manifest` any other object. Each takes the cluster as its `cluster` prop, in the same program, with no YAML and no `kubectl`. The same workloads run on any cluster your kubeconfig reaches. The workload providers ship in `Kubernetes.providers()` — compose it with `AWS.providers()` in the Stack: ```typescript -import * as AWS from "alchemy/AWS"; -import * as Kubernetes from "alchemy/Kubernetes"; +import * as AWS from "@alchemy.run/aws"; +import * as Kubernetes from "@alchemy.run/kubernetes"; import * as Layer from "effect/Layer"; export default Alchemy.Stack( @@ -68,7 +62,7 @@ node IAM roles with the standard Auto Mode managed policies: ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; const network = yield* AWS.EC2.Network("Network", { cidrBlock: "10.42.0.0/16", @@ -349,6 +343,40 @@ cluster is still reachable, then deletes the repository and role whether or not the cluster still exists, so destroying a cluster and its workloads together leaves nothing behind in AWS. +## Run each pod in its own VM + +Pods on the same node share its kernel. To run code you don't trust, give each pod its own [Nitro Sandbox](/aws/compute/nitro-sandboxes): a lightweight VM that the Nitro hypervisor isolates from the node and from every other pod on it. Set `runtimeClassName` on a Deployment or a Job: + +```typescript title="alchemy.run.ts" +const agent = yield* Kubernetes.Deployment("Agent", { + cluster, + image: "ghcr.io/acme/agent:1", + port: 8080, + runtimeClassName: "isolated-sandbox", +}); +``` + +On Auto Mode, that's all it takes. Auto Mode provides the `isolated-sandbox` and `confidential-sandbox` RuntimeClasses, launches a node type that supports sandboxes, and starts each pod in its own. Sandboxes need Kubernetes 1.36 or later, so set `version` on an older cluster. Containers in one pod share its sandbox. + +`isolated-sandbox` protects the node and other pods from what runs inside, and keeps `kubectl exec` and logs working. `confidential-sandbox` also hides the pod's memory from the node, and needs a policy that pins its images and arguments. See [Isolated or confidential](/aws/compute/nitro-sandboxes#isolated-or-confidential). + +For code that must not reach the network at all, add the `network-isolated` annotation through `podTemplate`. The sandbox then boots with no network device: + +```typescript title="alchemy.run.ts" +yield* Kubernetes.Job("RunGeneratedCode", { + cluster, + image: "ghcr.io/acme/runner:1", + runtimeClassName: "isolated-sandbox", + podTemplate: { + metadata: { annotations: { "sandbox.amazonaws.com/network-isolated": "true" } }, + }, +}); +``` + +A network-isolated pod can't serve traffic or pass HTTP probes, so it suits Jobs better than Deployments. + +Outside Auto Mode, nodes need an AMI with the Nitro Sandbox runtime and Nitro Enclaves turned on in their launch template, with `enclaveOptions: { enabled: true }` on [`AWS.AutoScaling.LaunchTemplate`](/providers/aws/autoscaling#launchtemplate). See [Run a pod in isolated mode](https://docs.aws.amazon.com/eks/latest/userguide/sandboxing-isolated-setup.html). + ## Target an EKS cluster you don't manage To deploy onto a cluster created elsewhere, name it in a connection. @@ -363,7 +391,7 @@ const cluster: Kubernetes.Connection = { `region` defaults to the Stack's AWS region. The `aws-eks` auth kind is added to the `Kubernetes.Connection` type by importing -`alchemy/AWS`, and it requires `AWS.providers()` in the Stack. Your +`@alchemy.run/aws`, and it requires `AWS.providers()` in the Stack. Your AWS principal needs an access entry on the cluster. Workloads get the same ECR, Pod Identity, and load balancer behavior as on a Stack-managed cluster. @@ -435,6 +463,7 @@ surface. cluster before deploying to EKS. - [VPC & networking](/aws/networking) — what the `Network` helper builds under the cluster. +- [Nitro Sandboxes](/aws/compute/nitro-sandboxes) — the same VM isolation on ECS and EC2. - [HyperPod](/aws/compute/hyperpod) — run training fleets on this cluster's nodes. - [Choosing a runtime](/aws/compute/choosing-a-runtime) — when Lambda or ECS diff --git a/.agents/skills/alchemy/references/aws/compute/hyperpod.md b/.agents/skills/alchemy/references/aws/compute/hyperpod.md index 3d0929d8..eb513391 100644 --- a/.agents/skills/alchemy/references/aws/compute/hyperpod.md +++ b/.agents/skills/alchemy/references/aws/compute/hyperpod.md @@ -1,53 +1,22 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # HyperPod > Provision SageMaker HyperPod clusters — Slurm or EKS orchestrated — and run ML workloads on them with sbatch, raw manifests, or effectful Jobs with task governance. -**SageMaker HyperPod** is AWS's persistent fleet for ML training -and inference: a cluster of accelerated instances with automatic -health checks, faulty-node replacement, and deep health checks -for GPUs. Where ECS and EKS run application containers, HyperPod -runs distributed training — and stays up between jobs. - -The HyperPod primitives: - -- A **Cluster** is the fleet. It is orchestrated by **Slurm** - (the default) or by an **EKS** cluster you attach it to. -- An **instance group** names a set of identical instances — a - controller group, a worker group — each with an instance type, - count, execution role, and lifecycle script. -- A **lifecycle script** (`on_create.sh` in S3) runs on every - node when it boots. This is where real clusters install - schedulers, mount FSx, and wire observability. -- **Task governance** (EKS orchestration only) arbitrates the - fleet between teams: a scheduler policy sets priority classes, - and per-team compute quotas reserve capacity. - -Alchemy models these with -[`Cluster`](/providers/aws/sagemaker/cluster), -[`ClusterSchedulerConfig`](/providers/aws/sagemaker/clusterschedulerconfig), -and [`ComputeQuota`](/providers/aws/sagemaker/computequota), and -Kubernetes workloads opt onto HyperPod nodes by referencing their -attributes (the group's `nodeSelector`, the quota's governed -`namespace` and `queueName`) from plain -[`Kubernetes.Deployment`](/providers/kubernetes/deployment) and -[`Kubernetes.Job`](/providers/kubernetes/job) props. +SageMaker HyperPod is a standing fleet of accelerated instances for ML training and inference. It checks each node's health, including deep checks on its GPUs, replaces nodes that fail, and stays up between jobs. Where [ECS](/aws/compute/ecs) and [EKS](/aws/compute/eks) run application containers, HyperPod runs distributed training. + +## Clusters, instance groups and lifecycle scripts + +A **cluster** is the fleet. It's divided into **instance groups**, each a set of identical instances with one type, count, role and **lifecycle script**: the script every node runs when it boots, which installs the scheduler, mounts shared storage and wires up monitoring. A cluster usually has a controller group and one or more worker groups. -## Choose an orchestrator +Something has to decide which job runs on which nodes. That's the **orchestrator**, and a cluster has one of two. **Slurm**, the default, is the classic HPC scheduler: you submit jobs with `sbatch` from a login node. **EKS** makes the nodes part of a Kubernetes cluster you attach, and you run Deployments and Jobs on them. -| | Slurm (default) | EKS (`orchestrator: { Eks }`) | -| --------------- | ------------------------------------- | ---------------------------------------------------- | -| Workloads | `sbatch` on the login node (over SSM) | Kubernetes objects — `Deployment`, `Job`, `Manifest` | -| High-level DX | — | `Kubernetes.Job` / `Deployment` via HyperPod attributes | -| Governance | Slurm accounting | `ClusterSchedulerConfig` + `ComputeQuota` (Kueue) | -| Extra plumbing | Lifecycle bucket + script | EKS cluster + the HyperPod dependencies Helm chart | +Choose Slurm for HPC-style training queues. Choose EKS when your platform is already Kubernetes, or to share the fleet between teams with **task governance**: a scheduler policy of priority classes, and compute quotas that reserve capacity per team. -Pick Slurm for classic HPC-style training queues. Pick EKS when -your platform is Kubernetes or you want typed workloads and task -governance. +In Alchemy, the fleet is [`SageMaker.Cluster`](/providers/aws/sagemaker/cluster). Governance is [`ClusterSchedulerConfig`](/providers/aws/sagemaker/clusterschedulerconfig) and [`ComputeQuota`](/providers/aws/sagemaker/computequota). On EKS, plain [`Kubernetes.Deployment`](/providers/kubernetes/deployment) and [`Kubernetes.Job`](/providers/kubernetes/job) workloads run on HyperPod nodes by naming the group's `nodeSelector`, and the quota's `namespace` and `queueName`. ## Create a Slurm cluster diff --git a/.agents/skills/alchemy/references/aws/compute/lambda.md b/.agents/skills/alchemy/references/aws/compute/lambda.md index c3e07b74..083b7372 100644 --- a/.agents/skills/alchemy/references/aws/compute/lambda.md +++ b/.agents/skills/alchemy/references/aws/compute/lambda.md @@ -1,87 +1,51 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Lambda -> Stand up an AWS Lambda Function from a single Effect, expose it over a Function URL, and call it from a test. +> How a Lambda Function runs your code per invocation, how it's invoked over a Function URL, by events or by other code, and how construction, timeouts and configuration work. -**Lambda** is Alchemy's default AWS runtime: a class that bundles -an Effect program into a zip, deploys it as a Lambda Function, -and generates its IAM execution role from the bindings you -actually use. Serve HTTP over a public **Function URL**, or -consume events — every building block in this section plugs in -through the same pattern: S3 notifications -(`Lambda.BucketEventSource`), SQS queues -(`Lambda.QueueEventSource`), Kinesis streams -(`Lambda.StreamEventSource`), and DynamoDB Streams -(`Lambda.TableEventSource`). +A Lambda Function is code that AWS runs when something invokes it: an HTTP request, a message on a queue, a new object in a Bucket, a schedule. You don't run a server. AWS starts environments for your code as invocations arrive, and you pay only for the time they spend running. -This page stands up the smallest possible function — a public -HTTP endpoint — which the [S3](/aws/data/s3), -[DynamoDB](/aws/data/dynamodb), [SQS](/aws/messaging/sqs), and -[Kinesis](/aws/messaging/kinesis) pages then grow into a small -event-driven system. +## How Lambda runs your code -## Prerequisites +Lambda runs your code in **execution environments**: small, isolated sandboxes, each holding one copy of your Function. An environment handles one invocation at a time. When invocations arrive faster than the existing environments can finish them, Lambda starts more, and when traffic drops, it stops them. -Install Alchemy and connect your AWS account — see -[Setup](/aws/setup). + -## Create the Stack +Starting a new environment is a **cold start**: Lambda loads your code and runs its setup before the first invocation, which adds tens to hundreds of milliseconds. After that the environment is **warm**, and later invocations skip the setup. -Every Alchemy app has an `alchemy.run.ts` at the root that -declares the resources to deploy. Create one with the AWS -providers wired in: +So a Function scales with no capacity planning, and costs nothing while nothing calls it. In exchange, an invocation can run for at most 15 minutes, and memory, and the CPU that comes with it, is fixed per Function. -```typescript -// alchemy.run.ts -import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; -import * as Effect from "effect/Effect"; - -export default Alchemy.Stack( - "MyApp", - { - providers: AWS.providers(), - state: AWS.state(), - }, - Effect.gen(function* () { - return {}; - }), -); -``` - -`Alchemy.Stack` is the root of every app. The first argument -(`"MyApp"`) doubles as a logical id and as the prefix Alchemy -uses when AWS asks for physical resource names. +## Declare a Function -`providers: AWS.providers()` registers every AWS resource and -IAM policy binding that ships with Alchemy, and resolves -credentials from your Alchemy profile — SSO, environment -variables, or stored keys, whichever you picked in -[Setup](/aws/setup). +A Function is a class. Its first argument is the id, its second the configuration, and its third the program it runs: -`state: AWS.state()` stores deploy state in an account-regional -S3 bucket (`alchemy-state-{accountId}-{region}-an`), created -lazily on the first deploy. Because the state lives in your AWS -account rather than on disk, the same configuration works -locally and in CI. (For purely local iteration you can use -`Alchemy.localState()` instead, which writes state under -`.alchemy/` next to your code.) - -The trailing `Effect.gen` block is where you'll declare the -resources to deploy. It's empty for now. - -## Declare a Lambda Function - -A Lambda Function in Alchemy is a class. Create `src/api.ts` -with the smallest possible declaration — just the class -ceremony, an entrypoint, and an empty runtime: - -```typescript -// src/api.ts -import * as AWS from "alchemy/AWS"; +```typescript title="src/api.ts" +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; export default class Api extends AWS.Lambda.Function()( @@ -93,251 +57,136 @@ export default class Api extends AWS.Lambda.Function()( ) {} ``` -The `` type argument plus the empty `()` is a one-time bit -of ceremony — it lets TypeScript reason about `Api` as a typed -handle that other resources can later bind against. The rest of -your code looks completely normal. +`main: import.meta.url` makes this file the entry point. Deploy bundles it into a zip, uploads it, and creates the Function with its execution role and log group. The role starts with permission to write logs, and each [binding](/aws/iam) adds to it. -`main: import.meta.url` tells Alchemy this same file is the -bundle entrypoint. At deploy time it'll be bundled with Rolldown -into a zip and uploaded as the function's code. +Yield the class in your Stack to deploy it: -## Serve HTTP from a Function URL +```typescript title="alchemy.run.ts" +const api = yield* Api; +``` -The empty function compiles, but it doesn't do anything yet. -Add a `fetch` field — Alchemy treats anything returned from the -`Effect.gen` block as the runtime API, and `fetch` specifically -is wired up to handle incoming HTTP requests: +## Construction runs once per environment -```diff lang="typescript" -// src/api.ts -import * as AWS from "alchemy/AWS"; -import * as Effect from "effect/Effect"; -+import * as HttpServerResponse from "effect/http/HttpServerResponse"; +The program has two parts. The outer `Effect.gen` is the **Construction phase**. It runs once when an environment starts, and again at deploy time, where its bindings become IAM statements. What it returns are the handlers, which run once per invocation: -export default class Api extends AWS.Lambda.Function()( - "Api", - { main: import.meta.url }, - Effect.gen(function* () { -- return {}; -+ return { -+ fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")), -+ }; - }), -) {} +```typescript title="src/api.ts" +Effect.gen(function* () { + const putObject = yield* AWS.S3.PutObject(Files); // once per environment + return { + fetch: putObject({ Key: "hit", Body: "1" }).pipe(/* once per invocation */), + }; +}); ``` -`HttpServerResponse.text(...)` is the same `effect/http` -API used everywhere else — Alchemy adapts it to the Lambda event -envelope under the hood, so your handler never sees the raw -`APIGatewayProxyEvent` shape. +Put clients and bindings in Construction, so every invocation in the environment reuses them. Put per-request work in the handlers. -## Expose a public URL +## Serve HTTP from a Function URL -`fetch` exists, but no one can call it yet. Set `functionUrl: true` on -the props to ask AWS for a public **Function URL** — no API -Gateway, no auth, just a public HTTPS endpoint: +A `fetch` handler answers HTTP requests. It's an Effect that reads the request and returns a response, with the `effect/http` APIs: -```diff lang="typescript" -export default class Api extends AWS.Lambda.Function()( - "Api", -- { main: import.meta.url }, -+ { main: import.meta.url, functionUrl: true }, - Effect.gen(function* () { - return { - fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")), - }; - }), -) {} +```typescript title="src/api.ts" +return { + fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")), +}; ``` -The resolved `Api` resource will now expose a `functionUrl` -field carrying that endpoint — we'll surface it from the Stack -in a moment. +Requests reach it through a **Function URL**, an HTTPS endpoint AWS gives the Function. Choose who may call it with `functionUrl`: -## Customize per stage +```typescript title="src/api.ts" +{ main: import.meta.url, functionUrl: true } +``` -Lambda has knobs you'll want to tune per stage — memory, -timeout, log retention. Swap the static props object for -`Stack.useSync`, which gives you a synchronous accessor for any -value in the surrounding Effect context: +`true` creates a public URL, `{ authType: "AWS_IAM" }` creates one that only accepts requests signed with AWS credentials, and `false` creates none. Leaving it out creates a public URL, so set `functionUrl: false` on a Function that only handles events. -```diff lang="typescript" -// src/api.ts -import * as AWS from "alchemy/AWS"; -+import { Stack } from "alchemy/Stack"; -import * as Effect from "effect/Effect"; -import * as HttpServerResponse from "effect/http/HttpServerResponse"; +Return the URL from your Stack to see it after a deploy: -export default class Api extends AWS.Lambda.Function()( - "Api", -- { main: import.meta.url, functionUrl: true }, -+ Stack.useSync((stack) => ({ -+ main: import.meta.url, -+ functionUrl: true, -+ memory: stack.stage === "prod" ? 1024 : 512, -+ })), - Effect.gen(function* () { - return { - fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")), - }; - }), -) {} +```typescript title="alchemy.run.ts" +const api = yield* Api; +return { url: api.functionUrl }; ``` -`Stack.useSync` is the synchronous accessor for any value in the -surrounding Effect context — handy for stack-level config like -`stage`, `appName`, or anything else you'd want to vary per -environment. +A Lambda Function buffers its whole response, up to 6 MB, before the caller sees any of it. For an API or a website that streams, or that serves many requests at once per environment, use a [Lambda Web Function](/aws/compute/web-functions). -## Wire the function into the Stack +## Be invoked by events -The `Api` class is just a typed identifier — yielding it inside -the Stack's Effect is what registers the resource and starts the -deploy: +Services invoke a Function too. A Queue delivers batches of messages, a Bucket reports new objects, a Table streams its changes, and EventBridge delivers events and schedules. Subscribe to one from Construction: -```diff lang="typescript" -// alchemy.run.ts -import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; -import * as Effect from "effect/Effect"; -+import Api from "./src/api.ts"; - -export default Alchemy.Stack( - "MyApp", - { - providers: AWS.providers(), - state: AWS.state(), - }, - Effect.gen(function* () { -+ const api = yield* Api; -+ return { url: api.functionUrl }; -- return {}; - }), +```typescript title="src/worker.ts" +yield* SQS.consumeQueueMessages(Jobs, { batchSize: 10 }, (event) => + Effect.forEach(event.Records, (record) => Console.log(record.body), { discard: true }), ); ``` -Yielding `Api` returns the resolved Lambda outputs — the function -ARN, role ARN, log group, and the public Function URL we asked -for with `functionUrl: true`. We surface `functionUrl` as the Stack's -`url` so the test harness can find it. +Deploy creates the subscription and the permissions it needs, and provides the event source's layer, here `AWS.Lambda.QueueEventSource`, to the Function. See [SQS](/aws/messaging/sqs), [S3 events](/aws/messaging/s3-events), [DynamoDB Streams](/aws/messaging/dynamodb-streams), [Kinesis](/aws/messaging/kinesis) and [EventBridge](/aws/messaging/eventbridge). -## Deploy +## Be invoked by other code -```sh -bun alchemy deploy -``` +Another runtime can call a Function directly. Bind `Lambda.InvokeFunction` to it, and the caller's role gets `lambda:InvokeFunction` on that Function only: -Alchemy bundles `src/api.ts` with Rolldown, packages it into a -zip, creates the IAM execution role, uploads the function, and -provisions the Function URL. The first deploy takes a moment -because of role propagation; subsequent deploys are seconds. +```typescript title="src/api.ts" +const invoke = yield* AWS.Lambda.InvokeFunction(Worker); +yield* invoke({ InvocationType: "Event", Payload: JSON.stringify({ id }) }); +``` -## Verify +`"Event"` hands the payload over and returns at once. `"RequestResponse"` waits for the result. For typed calls between Functions, see [Effect RPC](/aws/apis/effect-rpc). -Drop a quick integration test that hits the Function URL and -checks the body: +## Configure per stage -```typescript -// test/integ.test.ts -import * as AWS from "alchemy/AWS"; -import * as Test from "alchemy/Test/Bun"; -import { expect } from "bun:test"; -import * as Effect from "effect/Effect"; -import * as HttpClient from "effect/http/HttpClient"; -import Stack from "../alchemy.run.ts"; +Memory, timeout and log retention are props. Memory also sets the CPU: a Function with 1,769 MB gets one full vCPU. -const { test, beforeAll, deploy } = Test.make({ - providers: AWS.providers(), - state: AWS.state(), -}); +```typescript title="src/api.ts" +{ + main: import.meta.url, + memorySize: 1024, + timeout: Duration.seconds(30), + logging: { retention: "2 weeks" }, +} +``` -const stack = beforeAll(deploy(Stack)); +To vary them by stage, compute the props from the Stack: -test( - "Api responds over Function URL", - Effect.gen(function* () { - const { url } = yield* stack; - const response = yield* HttpClient.get(url); - expect(yield* response.text).toBe("Hello from Lambda!"); - }), -); +```typescript title="src/api.ts" +Stack.useSync((stack) => ({ + main: import.meta.url, + memorySize: stack.stage === "prod" ? 1024 : 512, +})) ``` -```sh -bun test test/integ.test.ts +Without `logging`, Lambda creates the log group on the first invocation and keeps its events forever. With it, Alchemy creates the group up front with that retention, and deletes it with the Function. + +## Clean up inside the invocation + +Each invocation runs in a fresh `Scope`, closed before the response is sent. A finalizer you add in a handler runs then: + +```typescript title="src/api.ts" +fetch: Effect.gen(function* () { + yield* Effect.addFinalizer(() => Console.log("request done")); + return HttpServerResponse.text("ok"); +}), ``` -You now have a deployable Lambda with a public URL. - -## Sandbox scope vs invocation scope - -The constructor runs **once per sandbox**, at cold start — -everything it builds (bindings, SDK clients) is reused by every -invocation. Each invocation then runs with a **fresh `Scope`** that -is settled *inline* before the handler returns — so -`Effect.addFinalizer` in a handler runs before the response leaves, -and request finalizers should be fast (closing a pool is -milliseconds). - -:::caution[There is no `waitUntil` on Lambda — request finalizers block the response] -No mechanism delivers post-response work reliably on Lambda. A -buffered invocation's response is not released to the caller until -the entire Invoke phase completes, so deferring cleanup past the -handler (we measured an extension-held post-response window) still -shows up as response latency — and environments whose invoke phase -is held open this way get recycled. Dangling promises resume on a -later thaw at best: TCP connections rarely survive the freeze, and a -crash or timeout reset drops the work entirely — silent data loss -for anything that mattered. - -The contract is blocking and honest: request finalizers run before -the response, keep them cheap, and anything that must not be lost -gets written durably (a queue, a table) inside the handler itself. -::: - -Construction-level finalizers run at **sandbox shutdown**. A Lambda sandbox -with no registered extensions is killed with no signal at all, so -the generated entry registers an internal extension with the -Extensions API — that makes Lambda send `SIGTERM` and allow 500 ms -before `SIGKILL`, and the entry uses the window to close the -instance scope: - -```typescript -Effect.gen(function* () { - // Construction: runs once per sandbox - yield* Effect.addFinalizer(() => - // runs in the 500 ms SIGTERM window at sandbox spin-down - flushTelemetry().pipe(Effect.ignore), - ); - return { fetch: /* per-invocation */ }; -}); +There's no reliable way to do work after the response on Lambda. AWS freezes the environment once the invocation returns, and a frozen environment may never run again. So keep finalizers short, and write anything that must not be lost, to a queue or a table, before you return. + +Finalizers added in Construction run when the environment shuts down, with about half a second to finish, and not at all if the environment crashes. Treat them as best effort. See [Instance scope vs request scope](/infrastructure-as-effects/runtime#instance-scope-vs-request-scope). + +## When an invocation times out + +When a handler runs past its `timeout`, it's interrupted. Its finalizers run and its open spans end, so the trace shows the call that hung, ending with an `AWS.Lambda.InvocationTimeoutError`. + +Lambda itself is given `timeout` plus `timeoutMargin`, one second by default, so cleanup and telemetry finish before Lambda stops the environment. Size the margin for your finalizers and one export to your telemetry backend: + +```typescript title="src/api.ts" +{ + main: import.meta.url, + timeout: Duration.seconds(30), + timeoutMargin: Duration.seconds(2), +} ``` -Treat instance-level cleanup as best-effort: half a second, and not -delivered on hard failures (a timeout reset kills the runtime -without the signal). Flush caches and close connections there; -anything that *must* happen belongs in the handler, scoped to the -invocation. See -[Instance scope vs request scope](/infrastructure-as-effects/runtime#instance-scope-vs-request-scope) -for the model across all runtimes. - -## Where next - -- [Drizzle + Aurora PostgreSQL](/aws/data/drizzle-aurora) — private database access, - IAM authentication, verified TLS, and deployment-time schema setup. -- [Drizzle + Aurora DSQL](/aws/data/drizzle-dsql) — the separate serverless database, - with an IAM-authenticated endpoint and non-admin application role. - -- [S3](/aws/data/s3) — add a bucket and bind read/write operations - into this function; IAM policies generated from the call - sites, no policy JSON to hand-write. -- [Secrets & env](/aws/security/secrets-env) — API keys from .env and - Secrets Manager credentials for this function. -- [REST API (API Gateway v1)](/aws/apis/api-gateway) — put an - API Gateway REST API with stages and custom domains in front - instead of a Function URL. -- [Choosing a runtime](/aws/compute/choosing-a-runtime) — when ECS, - EKS, or EC2 fits better than Lambda. -- [`Function` reference](/providers/aws/lambda/function) — every - prop and attribute. +The two together must fit within Lambda's 15 minutes. Lambda still records the invocation as timed out, retries it like any other failure, and starts a fresh environment, so nothing the interrupted handler left running can resume later. + +## When to choose another runtime + +Lambda is a good place to start: there's nothing to run while idle, and it scales without setup. It fits work that finishes within 15 minutes and arrives as requests or events. + +Reach for something else when the work doesn't fit that shape. An API that streams responses or holds many requests per environment fits a [Lambda Web Function](/aws/compute/web-functions). A process that runs continuously, holds connections open or already ships as a container fits [ECS](/aws/compute/ecs). Kubernetes workloads fit [EKS](/aws/compute/eks), and software that needs the whole machine fits [EC2](/aws/compute/ec2). See [Choosing a runtime](/aws/compute/choosing-a-runtime). diff --git a/.agents/skills/alchemy/references/aws/compute/microvms.md b/.agents/skills/alchemy/references/aws/compute/microvms.md index 1e91e2ef..2e30b769 100644 --- a/.agents/skills/alchemy/references/aws/compute/microvms.md +++ b/.agents/skills/alchemy/references/aws/compute/microvms.md @@ -1,26 +1,16 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Lambda MicroVMs > Build a Firecracker MicroVM image from TypeScript or a Dockerfile, then launch and drive isolated stateful instances from a Lambda Function with typed lifecycle bindings and RPC. -A Lambda **MicroVM image** is a Firecracker snapshot that boots a fully -initialized application in milliseconds. The model is *image-then-launch*: -`AWS.Lambda.MicrovmImage` builds the image once at deploy time, then a Lambda -Function launches isolated, stateful MicroVM instances from it at runtime — -one per end-user or session. That makes MicroVMs a natural fit for per-user -sandboxes: code interpreters, agent workspaces, preview environments. +A Lambda MicroVM is an isolated, stateful virtual machine you start on demand, one per user or session. It boots from a **MicroVM image**: a Firecracker snapshot of your application, already started and initialized, so a new MicroVM is ready in milliseconds. That makes MicroVMs a fit for per-user sandboxes: code interpreters, agent workspaces, preview environments. -The build runs **server-side on AWS** — no local Docker. Alchemy produces the -code artifact in one of three modes, selected by which prop you set: +The model is image, then launch. `AWS.Lambda.MicrovmImage` builds the image once, at deploy time. A Lambda Function then launches MicroVMs from it while it runs, and drives each one over HTTP or typed RPC. -- **Effectful** (`main`) — write the in-VM HTTP server in TypeScript; Alchemy - bundles it, generates a Dockerfile, and uploads the zip. -- **External** (`context`/`dockerfile`) — bring your own Dockerfile and build - context in any language; Alchemy zips and uploads the directory. -- **Prebuilt** (`codeArtifact`) — point at an existing S3 zip or ECR image URI. +The image is built on AWS, so you need no local Docker, from one of three sources. Give it `main`, and Alchemy bundles your TypeScript server and writes its Dockerfile. Give it `context` and a `dockerfile`, and it builds your own app in any language. Or give it `codeArtifact`, a zip in S3 or an image in ECR you've already built. :::caution Lambda MicroVMs are a **preview feature**: your account must be onboarded to @@ -42,7 +32,7 @@ contract every Function and Server returns: ```typescript // sandbox.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; import { HttpServerRequest } from "effect/http/HttpServerRequest"; import * as HttpServerResponse from "effect/http/HttpServerResponse"; @@ -89,7 +79,7 @@ VM, wait for `RUNNING`, mint an auth token, then call the typed RPC stub with ```typescript // api.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -191,7 +181,7 @@ is provided on the Stack so it gets built and deployed alongside: ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; import Api from "./api.ts"; import SandboxLive from "./sandbox.ts"; @@ -217,7 +207,7 @@ the bare build Role and the image live directly in the Stack's `Effect.gen`: ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; export default Alchemy.Stack( @@ -240,7 +230,9 @@ build-affecting prop changes; otherwise the image is left untouched. ## Where next - [Lambda](/aws/compute/lambda) — the Function model the orchestrator is built on. -- [MicrovmImage API reference](/providers/aws/lambda/microvmimage) — all props, +- [Nitro Sandboxes](/aws/compute/nitro-sandboxes) — the same VM isolation for ECS tasks and EKS pods on your own instances. +- [ECS Sandboxes](/aws/compute/ecs-sandboxes) — a sandbox per user or session on instances in your own account. +- [MicrovmImage API reference](/providers/aws/lambda#microvmimage) — all props, build modes, sizing, logging, and VPC egress via `NetworkConnector`. -- [RunMicrovm](/providers/aws/lambda/runmicrovm) and the other per-instance +- [RunMicrovm](/providers/aws/lambda#runmicrovm) and the other per-instance lifecycle bindings. diff --git a/.agents/skills/alchemy/references/aws/compute/nitro-sandboxes.md b/.agents/skills/alchemy/references/aws/compute/nitro-sandboxes.md new file mode 100644 index 00000000..369ec80c --- /dev/null +++ b/.agents/skills/alchemy/references/aws/compute/nitro-sandboxes.md @@ -0,0 +1,108 @@ + + +# Nitro Sandboxes + +> How Nitro Sandboxes run each ECS task, EKS pod or self-managed workload in its own lightweight VM on your EC2 instances, the difference between isolated and confidential modes, and how to turn them on for ECS, EKS and EC2. + +Containers on the same machine share one Linux kernel. A container escape or a kernel bug can let one workload reach another. A **Nitro Sandbox** closes that gap: it is a lightweight virtual machine, with its own kernel, that the Nitro hypervisor isolates from the instance it runs on and from every other sandbox there. + +Sandboxes run on your own EC2 instances, so many of them share one machine. Use them for code you don't trust: a tenant's container, an agent running code an LLM wrote, a CI job from a pull request. + +## One VM per task or pod + +Turn the feature on for an instance, and each task or pod scheduled onto it starts in its own sandbox. The instance gives the sandbox its vCPUs and memory, and Nitro keeps them separate. + + + +The instance must be a type that supports Nitro Enclaves, which is most current general purpose, compute and memory families above their smallest size (`m6i.xlarge` yes, `m6i.large` no). The vCPUs of all sandboxes on an instance can add up to five times the instance's own. Memory is not shared: each sandbox's memory is set aside for it until it stops. See [supported instance types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/amazon-ec2-nitro-sandboxes.html#nitro-sandboxes-considerations). + +## Isolated or confidential + +A sandbox runs in one of two modes, depending on who you trust. + +**Isolated** trusts the instance and distrusts the workload. It protects the instance and its neighbours from what runs inside. The instance can still exec into the container, read its logs and see its processes. + +**Confidential** distrusts the instance too. Nitro moves the sandbox's memory out of the instance's reach, and the sandbox can prove which code it runs through **attestation**. You write a KMS key policy that releases a key only to a sandbox whose measurements match, so secrets reach exactly the code you approved. Confidential workloads need a policy that pins their images, arguments and mounts, and exec is denied. + +Start with isolated. Move to confidential when the people or software operating the instance must not see the data. + +## On ECS + +ECS runs sandboxes on **Managed Instances**: a capacity provider whose instances ECS launches and patches. Enable sandboxes on its instances, then set the isolation mode on the task definition: + +```typescript title="alchemy.run.ts" +const capacity = yield* AWS.ECS.CapacityProvider("Capacity", { + cluster: cluster.clusterName, + managedInstancesProvider: { + instanceLaunchTemplate: { + networkConfiguration: { subnets: network.privateSubnetIds }, + nitroEnclavesEnabled: true, + }, + }, +}); + +const task = yield* AWS.ECS.TaskDefinition("MyTask", { + requiresCompatibilities: ["MANAGED_INSTANCES"], + trustedExecutionConfiguration: { isolationMode: "ISOLATED_SANDBOX" }, + containerDefinitions: [{ name: "app", image: "ghcr.io/acme/app:1" }], +}); +``` + +Running it as a Service is in [ECS: Isolate each task in its own VM](/aws/compute/ecs#isolate-each-task-in-its-own-vm). + +ECS isolates the task and stops there. `AWS.ECS.CreateSandbox` is Alchemy's construct on top: your app starts sandboxes while it runs, one per user or session, and runs commands, uses files and calls ports in each through a handle. See [ECS Sandboxes](/aws/compute/ecs-sandboxes). + +## On EKS + +On an EKS Auto Mode cluster, set `runtimeClassName` on a Deployment or a Job. Auto Mode provisions a node that supports sandboxes and starts each pod in its own: + +```typescript title="alchemy.run.ts" +yield* Kubernetes.Deployment("MyApp", { + cluster, + image: "ghcr.io/acme/app:1", + port: 8080, + runtimeClassName: "isolated-sandbox", // or "confidential-sandbox" +}); +``` + +See [EKS: Run each pod in its own VM](/aws/compute/eks#run-each-pod-in-its-own-vm). + +## On EC2 + +On a plain instance, enable Nitro Enclaves at launch. You then run your own virtual machine monitor on it, usually Firecracker, and start sandboxes yourself: + +```typescript title="alchemy.run.ts" +yield* AWS.EC2.Instance("SandboxHost", { + imageId: AWS.EC2.amazonLinux2023(), + instanceType: "m6i.xlarge", + enclaveOptions: { enabled: true }, +}); +``` + +See [EC2: Host Nitro Sandboxes](/aws/compute/ec2#host-nitro-sandboxes). + +## Nitro Sandboxes or Lambda MicroVMs + +Both give each workload its own VM. They differ in who runs the machines. + +Nitro Sandboxes run on instances in your account, inside ECS or EKS. You keep the cluster and the network, and pay for each instance while it runs, however many sandboxes share it. They suit a fleet you already run on containers, and work that must stay on machines in your own account. + +[Lambda MicroVMs](/aws/compute/microvms) run on AWS's machines. You build an image, launch one MicroVM per user or session from a Function, and drive it over HTTP. There are no instances or cluster to run. They suit sandboxes started on demand when you'd rather not run the machines. diff --git a/.agents/skills/alchemy/references/aws/compute/web-functions.md b/.agents/skills/alchemy/references/aws/compute/web-functions.md new file mode 100644 index 00000000..1e6bae8a --- /dev/null +++ b/.agents/skills/alchemy/references/aws/compute/web-functions.md @@ -0,0 +1,437 @@ + + +# Lambda Web Functions + +> Run an HTTP server on AWS Lambda Web Functions — an Effect fetch handler or any Node server, with streaming responses, many concurrent requests per environment, and a built-in HTTPS endpoint. + +A Lambda Web Function runs an HTTP server on Lambda. Where a [Lambda Function](/aws/compute/lambda) runs one invocation at a time per environment, a Web Function's environment is a long-running server that takes many requests at once, up to 128. Responses stream to the client as your server writes them, and there's nothing to run while nobody calls it. + +## Environments, endpoints and revisions + +Your server runs in **environments**, each a copy of your code with 2 GB of memory and 2 vCPUs. Lambda starts more as traffic grows and stops them as it falls. Because each one serves many requests, a spike starts few environments, and requests share warm connection pools. + + + +Requests arrive through an **endpoint**: an HTTPS URL with its own auth, rate limit and cap on environments. Every Web Function has one, and you can add more. Each deploy publishes a new **revision**, and the endpoint moves its traffic to it, all at once or a share at a time. + +Use a Web Function for anything that answers HTTP: APIs, server-rendered sites, AI responses streamed token by token. The [AWS websites](/aws/frontend/websites) run their servers on one. For queues, streams, schedules and other events, use a [Lambda Function](/aws/compute/lambda). + +:::caution +Web Functions run Node.js 24 on Arm64. They launched in `us-east-1`, +`us-east-2`, `us-west-2`, `eu-west-1`, and `ap-northeast-1`, and AWS is +adding Regions: check the [Lambda pricing page](https://aws.amazon.com/lambda/pricing/) +for where they run today. Code ships through the Alchemy assets bucket, so +run `alchemy provider aws bootstrap` once per account and Region. +::: + +## Declare a Web Function + +Create `src/api.ts` and return a `fetch` handler: + +```typescript +// src/api.ts +import * as AWS from "@alchemy.run/aws"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +export default class Api extends AWS.Lambda.WebFunction()( + "Api", + { main: import.meta.url, authType: "ApplicationManaged" }, + Effect.gen(function* () { + return { + fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")), + }; + }), +) {} +``` + +Your `fetch` handler runs on a Node HTTP server inside the Web Function, so +the same `effect/http` code you'd run anywhere else works unchanged. +`authType: "ApplicationManaged"` makes its endpoint public: every request +reaches your code. + +## Deploy it + +Yield the class in your Stack and return its `url`: + +```typescript +// alchemy.run.ts +import * as Alchemy from "alchemy"; +import * as AWS from "@alchemy.run/aws"; +import * as Effect from "effect/Effect"; +import Api from "./src/api.ts"; + +export default Alchemy.Stack( + "MyApp", + { + providers: AWS.providers(), + state: AWS.state(), + }, + Effect.gen(function* () { + const api = yield* Api; + return { url: api.url }; + }), +); +``` + + + +The `url` looks like `https://..lambda-web.us-west-2.on.aws`. +Every deploy publishes a new revision and moves all traffic to it. + +## Stream a response + +Return a streamed body and the client receives each chunk as soon as you +produce it: + +```diff lang="typescript" +// src/api.ts +import * as AWS from "@alchemy.run/aws"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; ++import * as Stream from "effect/Stream"; + +export default class Api extends AWS.Lambda.WebFunction()( + "Api", + { main: import.meta.url, authType: "ApplicationManaged" }, + Effect.gen(function* () { + return { +- fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")), ++ fetch: Effect.succeed( ++ HttpServerResponse.stream( ++ Stream.make("Hello", " from", " Lambda!").pipe( ++ Stream.tap(() => Effect.sleep("200 millis")), ++ Stream.encodeText, ++ ), ++ { contentType: "text/plain" }, ++ ), ++ ), + }; + }), +) {} +``` + +## Use AWS resources + +Bindings work the same as on a Lambda Function. Binding an operation +grants the function's role exactly that permission: + +```diff lang="typescript" +// src/api.ts +import * as AWS from "@alchemy.run/aws"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +export default class Api extends AWS.Lambda.WebFunction()( + "Api", + { main: import.meta.url, authType: "ApplicationManaged" }, + Effect.gen(function* () { ++ const bucket = yield* AWS.S3.Bucket("Uploads"); ++ const putObject = yield* AWS.S3.PutObject(bucket); + return { +- fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")), ++ fetch: Effect.gen(function* () { ++ yield* putObject({ Key: "hello.txt", Body: "Hello!" }); ++ return HttpServerResponse.text("Saved"); ++ }).pipe(Effect.orDie), + }; +- }), ++ }).pipe(Effect.provide(AWS.S3.PutObjectHttp)), +) {} +``` + +## Bring an existing server + +You don't need Effect. Point `main` at your own Node server, such as a Hono +app. Alchemy bundles it as it is, with no wrapper and no Effect runtime. +Listen on the address Lambda passes in `AWS_LAMBDA_HTTP_ENDPOINT`: + +```typescript +// src/server.ts +import { serve } from "@hono/node-server"; +import { Hono } from "hono"; + +const app = new Hono(); +app.get("/", (c) => c.text(`Hello from ${c.req.path}`)); + +const [hostname, port] = (process.env.AWS_LAMBDA_HTTP_ENDPOINT ?? "localhost:3000").split(":"); +serve({ fetch: app.fetch, hostname, port: Number(port) }); +``` + +```typescript +// alchemy.run.ts +import * as Alchemy from "alchemy"; +import * as AWS from "@alchemy.run/aws"; +import * as Effect from "effect/Effect"; + +export default Alchemy.Stack( + "MyApp", + { providers: AWS.providers(), state: AWS.state() }, + Effect.gen(function* () { + const api = yield* AWS.Lambda.WebFunction("Api", { + main: "./src/server.ts", + authType: "ApplicationManaged", + }); + return { url: api.url }; + }), +); +``` + +Express, Fastify and plain `node:http` work the same way: + +```typescript +// src/server.ts +import express from "express"; + +const app = express(); +app.get("/", (_req, res) => res.send("Hello from Express")); + +const [host, port] = (process.env.AWS_LAMBDA_HTTP_ENDPOINT ?? "localhost:3000").split(":"); +app.listen(Number(port), host); +``` + +For a framework's standalone build output, set `bundle: false` to deploy +the directory as it is. Lambda starts `main`, so it must listen on +`AWS_LAMBDA_HTTP_ENDPOINT` too: + +```typescript +const site = yield* AWS.Lambda.WebFunction("Site", { + main: "./.output/server/index.mjs", + bundle: false, + authType: "ApplicationManaged", +}); +``` + +## Tune concurrency and traffic + +Set how many requests one environment serves, the per-request timeout, +and caps on environments and requests per second: + +```typescript +const api = yield* AWS.Lambda.WebFunction("Api", { + main: "./src/server.ts", + authType: "ApplicationManaged", + maxConcurrencyPerEnvironment: 128, + timeout: Duration.minutes(5), + maxEnvironments: 10, + rateLimit: 500, +}); +``` + +`maxConcurrencyPerEnvironment` is a cap per environment, not a total: at +most `maxEnvironments × maxConcurrencyPerEnvironment` requests are in +flight. Lower it for CPU-heavy servers. Requests beyond `rateLimit` get +HTTP 429. A value Lambda doesn't accept, such as `rateLimit: 1500`, fails +at plan with the allowed range. + +Each environment has 2 GB of memory and 2 vCPUs, and you can't change +that. Node's heap defaults to 1 GB; raise it with +`env: { NODE_OPTIONS: "--max-old-space-size=1536" }`. + +## Roll out gradually + +Set `canary` to send a share of traffic to each new deploy while the +previous revision keeps the rest: + +```typescript +const api = yield* AWS.Lambda.WebFunction("Api", { + main: "./src/server.ts", + authType: "ApplicationManaged", + canary: { weight: 10 }, +}); +``` + +The next deploy that changes code or configuration sends 10% of requests +to the new revision and 90% to the one before. Changing `weight` shifts +traffic without publishing a new revision. Set it to `100`, or remove +`canary`, to promote the new revision. Set it to `0` to roll back: all +traffic returns to the previous revision. + +Deploying again during a canary replaces the canary and keeps the +previous revision, so traffic never lands on more than two revisions. +`api.revisionWeights` shows the current split. Lambda splits each request +on its own, so one client can reach both revisions; keep the two +compatible with each other. + +Each endpoint has its own split. Set `canary` on a `WebFunctionEndpoint` +to roll it out on its own schedule; an endpoint without `canary` moves to +each new revision at once. + +## Serve from several Regions + +List extra Regions to get one global domain that routes each request to +the nearest Region: + +```typescript +const api = yield* AWS.Lambda.WebFunction("Api", { + main: "./src/server.ts", + authType: "ApplicationManaged", + regions: ["us-east-1", "eu-west-1"], +}); +``` + +Changing `regions` gives the endpoint a new URL. + +## Require signed requests + +Set `authType: "IamAuth"` to accept only SigV4-signed requests from +callers allowed to call `lambda:InvokeWebFunctionEndpoint`, such as a +CloudFront distribution: + +```typescript +const internal = yield* AWS.Lambda.WebFunction("Internal", { + main: "./src/server.ts", + authType: "IamAuth", +}); +``` + +To let a specific caller in, such as a role in another account, grant it +access to the endpoint: + +```typescript +yield* AWS.Lambda.WebFunctionPermission("PartnerInvoke", { + endpoint: internal, + principal: "arn:aws:iam::444455556666:role/partner-caller", +}); +``` + +## Put CloudFront in front + +Serve the function through CloudFront for a custom domain, caching, or +AWS WAF. Set `webFunction` on the origin and keep `authType: "IamAuth"`: + +```typescript +const api = yield* AWS.Lambda.WebFunction("Api", { + main: "./src/server.ts", + authType: "IamAuth", +}); + +const cdn = yield* AWS.CloudFront.Distribution("Cdn", { + origins: [{ id: "api", webFunction: api }], + defaultCacheBehavior: { targetOriginId: "api" }, +}); +``` + +CloudFront signs every request to the function, and only this +distribution may call it, so requests to the function's own URL are +refused. Requests pass through uncached with their method, query string, +cookies and headers, including your app's own `Authorization` header. +Set `cachePolicyId` on a behavior to cache a path, such as static assets. +This works for a function with `regions` too: Alchemy signs requests to +its global domain with SigV4A. + +## Reach private resources + +Set `vpc` to send the server's outbound traffic through your VPC, for +example to reach a database in private subnets: + +```typescript +const api = yield* AWS.Lambda.WebFunction("Api", { + main: "./src/server.ts", + authType: "ApplicationManaged", + vpc: { + subnetIds: network.privateSubnetIds, + securityGroupIds: [appSg.groupId], + }, +}); +``` + +Use at least two subnets in different Availability Zones, and allow the +security group on the database. Private subnets need a NAT gateway to +reach the internet. A function with `vpc` can't also use `regions`. +Remove `vpc` and the next deploy deletes the connector once no endpoint +serves through it. + +## Add another endpoint + +Each endpoint is a separate way in, with its own URL, auth, and limits. +Add one with `WebFunctionEndpoint`, for example a public endpoint for +webhooks next to a private one: + +```typescript +const api = yield* AWS.Lambda.WebFunction("Api", { + main: "./src/server.ts", + authType: "IamAuth", + maxEnvironments: 50, +}); + +const webhooks = yield* AWS.Lambda.WebFunctionEndpoint("Webhooks", { + function: api, + authType: "ApplicationManaged", + rateLimit: 100, + maxEnvironments: 2, +}); +``` + +`api.url` is the function's own endpoint and `webhooks.url` is the new +one. Both serve the same code and follow every deploy, but each scales on +its own, so a webhook burst can't use up the other endpoint's capacity. + +For a Web Function declared as a class, like `Api` above, pass the class +itself: + +```typescript +// alchemy.run.ts +import * as Alchemy from "alchemy"; +import * as AWS from "@alchemy.run/aws"; +import * as Effect from "effect/Effect"; +import Api from "./src/api.ts"; + +export default Alchemy.Stack( + "MyApp", + { providers: AWS.providers(), state: AWS.state() }, + Effect.gen(function* () { + const api = yield* Api; + const webhooks = yield* AWS.Lambda.WebFunctionEndpoint("Webhooks", { + function: Api, + authType: "ApplicationManaged", + }); + return { url: api.url, webhooks: webhooks.url }; + }), +); +``` + +Your server sees which endpoint a request came through in the +`lambda-web-endpoint-name` header. Use it to keep each endpoint to its own +routes: + +```typescript +// src/server.ts +app.use(async (c, next) => { + const endpoint = c.req.header("lambda-web-endpoint-name"); + if (endpoint === "Webhooks" && !c.req.path.startsWith("/webhooks/")) { + return c.notFound(); + } + await next(); +}); +``` + +## Shutdown + +Lambda stops idle environments with `SIGTERM` and gives them 1 second. +In-flight responses finish first, then init-level finalizers run, so keep +them short. + +:::note +Every prop and attribute is listed in the +[`WebFunction` reference](/providers/aws/lambda#webfunction). +::: diff --git a/.agents/skills/alchemy/references/aws/data/drizzle-aurora.md b/.agents/skills/alchemy/references/aws/data/drizzle-aurora.md index 538d1ad5..53747b32 100644 --- a/.agents/skills/alchemy/references/aws/data/drizzle-aurora.md +++ b/.agents/skills/alchemy/references/aws/data/drizzle-aurora.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Drizzle + Aurora PostgreSQL @@ -17,7 +17,7 @@ pnpm install cd examples/aws-aurora-drizzle ``` -The example uses `us-west-2`, Aurora PostgreSQL 17.5, and Node.js 22. Change both subnet availability zones if you change region. Application queries use Effect-native Drizzle over `pg`, not the RDS Data API driver; [SQL databases](/sql/databases) compares the integrations. +The example uses `us-west-2`, Aurora PostgreSQL 17.5, and Node.js 22. Change both subnet availability zones if you change region. Application queries use Effect-native Drizzle over `@effect/sql-pg`, not the RDS Data API driver; [SQL databases](/sql/databases) compares the integrations. :::caution Aurora is billable until destroyed. This example is disposable: destroy deletes its database data. @@ -52,7 +52,7 @@ import { bootstrap } from "./bootstrap.ts"; const schemaVersion = yield* bootstrap; ``` -The [deployment Action](https://github.com/alchemy-run/alchemy/blob/main/examples/aws-aurora-drizzle/src/bootstrap.ts) creates `todos` and the restricted `app_iam` login through the Data API. This is initial setup only, not a versioned migration runner. The application role gets table CRUD but cannot create objects in `public`. +The [deployment Action](https://github.com/alchemy-run/alchemy/blob/main/examples/aws-aurora-drizzle/src/bootstrap.ts) creates `todos` and the restricted `app_iam` login through the Data API. This is initial setup only, not a versioned migration runner; to apply versioned migrations on deploy, pass them to Aurora's `migrations` prop (see [Apply the committed SQL](#apply-the-committed-sql)). The application role gets table CRUD but cannot create objects in `public`. ## Bind the application identity @@ -79,7 +79,7 @@ env: { NODE_EXTRA_CA_CERTS: "/var/runtime/ca-cert.pem" } The RDS binding currently emits `sslmode=no-verify`. Override it to require certificate and hostname verification: ```typescript -import * as Drizzle from "alchemy/Drizzle/Postgres"; +import * as Drizzle from "@alchemy.run/drizzle/Postgres"; import * as Effect from "effect/Effect"; import * as Redacted from "effect/Redacted"; @@ -96,19 +96,14 @@ const db = yield* Drizzle.Postgres( The CA path is specific to [managed Lambda Node.js runtimes](https://docs.aws.amazon.com/lambda/latest/dg/lambda-nodejs.html#nodejs-certificate-loading). The connection stays lazy: the first query resolves the redacted URL and opens a pool scoped to that invocation, which closes when its scope ends. -## Package the driver +## Install the driver ```sh -pnpm add alchemy effect@4.0.0-rc.115 @effect/sql-pg@4.0.0-rc.115 \ - drizzle-orm@1.0.0-rc.5-ab785fc pg -pnpm add -D @types/pg +pnpm add alchemy @alchemy.run/aws @alchemy.run/drizzle effect @effect/sql-pg \ + drizzle-orm@1.0.0-rc.5 ``` -```typescript -build: { install: ["pg"] } -``` - -`build.install` keeps the CommonJS `pg` package intact in the Lambda artifact. +`@effect/sql-pg` speaks the Postgres wire protocol itself, so the Lambda bundle needs no native or CommonJS driver. ## Query with Drizzle @@ -137,7 +132,7 @@ The example's bootstrap does not alter existing tables or maintain Drizzle migra ### Configure SQL generation ```sh -pnpm add -D drizzle-kit@1.0.0-rc.5-ab785fc +pnpm add -D drizzle-kit@1.0.0-rc.5 ``` ```typescript @@ -171,36 +166,39 @@ git commit -m "feat(db): update Aurora schema and migration" Review the staged SQL, snapshots, destructive operations, and rename decisions before committing. Commit the entire generated migration directory with the schema. The release process consumes committed SQL; deployment must not generate or silently rewrite it. -### Configure the migration connection - -```typescript -// drizzle.migrate.config.ts -import { defineConfig } from "drizzle-kit"; -import config from "./drizzle.config.ts"; +### Apply the committed SQL -const url = process.env.DATABASE_URL; -if (!url) throw new Error("DATABASE_URL is required for migrations"); +Pass the committed directory to Aurora. `alchemy deploy` applies pending migrations over the Data API once the writer is available, so the deploying machine needs no network route to the private cluster: -export default defineConfig({ - ...config, - dbCredentials: { url }, +```typescript +const aurora = yield* AWS.RDS.Aurora("Database", { + // ... + dataApi: true, + migrations: "./migrations", }); ``` -Inject a migration-role PostgreSQL URL for the `app` database through the runner's secret store, using `sslmode=verify-full` and the RDS CA trust bundle. The runner needs its own network route and security-group access to the private cluster; Lambda's binding grants neither to a laptop or CI job. Keep this DDL-capable identity separate from `app_iam`. +Each migration and its row in `__alchemy_migrations` commit in one transaction, authenticated with the cluster's master secret. The Data API runs one statement per call, so keep drizzle-kit's default `--> statement-breakpoint` separators. A database previously migrated by drizzle-kit is adopted on first deploy. Editing or deleting an applied migration fails the deploy; add a new migration instead. -### Apply the committed SQL +To keep the Data API off, deploy an `AWS.RDS.MigrationRunner` into the cluster's private subnets and pass it as `migrationsTransport`. Alchemy then invokes that Lambda, and it connects to the writer from inside the VPC: -```sh -pnpm exec drizzle-kit migrate --config=drizzle.migrate.config.ts +```typescript +const runner = yield* AWS.RDS.MigrationRunner("MigrationRunner", { + subnetIds: network.privateSubnetIds, + securityGroupIds: [runnerSecurityGroup.groupId], +}); +const aurora = yield* AWS.RDS.Aurora("Database", { + // ... + dataApi: false, + migrations: "./migrations", + migrationsTransport: runner, +}); ``` -Run from the authorized migration runner before releasing code that requires the new schema. Keep an existing `drizzle-kit migrate` workflow; `alchemy deploy` is not its replacement. Neither `AWS.RDS.Aurora` nor `AWS.RDS.DBCluster` accepts a `migrations` prop, and the example's Action only performs its explicit bootstrap SQL. - ## Run the integration test ```sh -AWS_TEST_SLOW=1 ALCHEMY_PROFILE=testing bun test test/integ.test.ts +ALCHEMY_PROFILE=testing bun test test/integ.test.ts ``` This deploys real AWS resources and destroys them afterward; provisioning and cleanup take several minutes. diff --git a/.agents/skills/alchemy/references/aws/data/drizzle-dsql.md b/.agents/skills/alchemy/references/aws/data/drizzle-dsql.md index 0fcdb33f..2f077df8 100644 --- a/.agents/skills/alchemy/references/aws/data/drizzle-dsql.md +++ b/.agents/skills/alchemy/references/aws/data/drizzle-dsql.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Drizzle + Aurora DSQL @@ -17,7 +17,7 @@ pnpm install cd examples/aws-dsql-drizzle ``` -Use a DSQL-supported region such as `us-west-2`. Deployment needs `dsql:DbConnectAdmin` and access to the cluster on port 5432. The example includes Effect 4, Effect-native Drizzle, `@effect/sql-pg`, and `pg`; it is not an RDS Data API integration. +Use a DSQL-supported region such as `us-west-2`. Deployment needs `dsql:DbConnectAdmin` and access to the cluster on port 5432. The example includes Effect 4, Effect-native Drizzle, and `@effect/sql-pg`; it is not an RDS Data API integration. :::caution These resources are billable. Deletion protection is disabled; destroy deletes the database data. @@ -26,7 +26,7 @@ These resources are billable. Deletion protection is disabled; destroy deletes t ## Create the cluster ```typescript -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Database = AWS.DSQL.Cluster("Database", { deletionProtectionEnabled: false, @@ -67,7 +67,7 @@ The [deployment Action](https://github.com/alchemy-run/alchemy/blob/main/example ## Connect from Lambda ```typescript -import * as Drizzle from "alchemy/Drizzle/Postgres"; +import * as Drizzle from "@alchemy.run/drizzle/Postgres"; import * as Effect from "effect/Effect"; import * as Redacted from "effect/Redacted"; @@ -86,7 +86,7 @@ const db = yield* Drizzle.Postgres( Provide `AWS.DSQL.ConnectHttp` on the Lambda Effect. It grants cluster-scoped `dsql:DbConnect`, not `dsql:DbConnectAdmin`, and signs a fresh IAM token locally when the connection effect runs. The binding does not create the database role or SQL grants. -`Drizzle.Postgres` resolves the redacted URL on the first query and scopes its pool to the invocation, rather than retaining a pool with an old token across warm invocations. The [complete handler](https://github.com/alchemy-run/alchemy/blob/main/examples/aws-dsql-drizzle/src/Api.ts) uses `build: { install: ["pg"] }` to package the CommonJS driver intact. [Connection lifecycle](/sql/effect-sql/lifecycle). +`Drizzle.Postgres` resolves the redacted URL on the first query and scopes its pool to the invocation, rather than retaining a pool with an old token across warm invocations. See the [complete handler](https://github.com/alchemy-run/alchemy/blob/main/examples/aws-dsql-drizzle/src/Api.ts). [Connection lifecycle](/sql/effect-sql/lifecycle). ## Query with Drizzle @@ -107,7 +107,7 @@ const [created] = yield* db.insert(Todos).values({ pnpm deploy --profile testing ``` -The example's Action performs the initial bootstrap. Neither `AWS.DSQL.Cluster` nor the runtime `Drizzle.Postgres` wrapper applies generated migration files automatically. +The example's Action performs the initial bootstrap. To apply versioned migrations on deploy instead, pass them to the cluster's `migrations` prop; see [Apply the committed SQL](#apply-the-committed-sql). ## Verify the connection @@ -131,7 +131,7 @@ Initial setup does not alter existing tables. The Action's `version` input is no ### Configure SQL generation ```sh -pnpm add -D drizzle-kit@1.0.0-rc.5-ab785fc +pnpm add -D drizzle-kit@1.0.0-rc.5 ``` ```typescript @@ -185,9 +185,15 @@ This operator connection uses AWS CLI credentials authorized for `dsql:DbConnect ### Apply the committed SQL -Use a validated DSQL-compatible migration runner in the release process before deploying dependent application code. It must record applied versions, handle partial failures, execute DDL as separate autocommit statements, and wait for asynchronous indexes. A plain `psql --file` has no migration history or safe replay; do not wrap the file in `BEGIN` or `--single-transaction`. +Pass the committed directory to the cluster. `alchemy deploy` applies pending migrations before anything that depends on the cluster: -Keep an existing validated DSQL migration workflow separate from `alchemy deploy`; the example's bootstrap Action is not its replacement. Do not expose schema administration through an HTTP `/setup` route. +```typescript +const database = yield* AWS.DSQL.Cluster("Database", { + migrations: "./migrations", +}); +``` + +Each statement runs separately, `CREATE INDEX` becomes `CREATE INDEX ASYNC` and is awaited, and applied migrations are recorded in `__alchemy_migrations`. Editing or deleting an applied migration fails the deploy; add a new migration instead. Don't wrap migration files in `BEGIN`/`COMMIT`, and don't expose schema administration through an HTTP `/setup` route. ## Clean up diff --git a/.agents/skills/alchemy/references/aws/data/dynamodb.md b/.agents/skills/alchemy/references/aws/data/dynamodb.md index cffd1a6e..166605d3 100644 --- a/.agents/skills/alchemy/references/aws/data/dynamodb.md +++ b/.agents/skills/alchemy/references/aws/data/dynamodb.md @@ -1,201 +1,166 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # DynamoDB -> Add a DynamoDB Table, bind GetItem and PutItem to your Lambda, and serve a typed key/value HTTP API backed by DynamoDB. - -**DynamoDB** is AWS's serverless key/value store — structured -records looked up by partition (and optional sort) key, with no -capacity to manage. In Alchemy it's the `Table` resource plus a -binding per operation: `GetItem`, `PutItem`, `UpdateItem`, -`DeleteItem`, `Query`, `Scan`, and the batch/transact variants. -Each binding attaches a least-privilege IAM statement scoped to -the table's ARN. Tables are also an event source: enable -**DynamoDB Streams** and consume change records in a Lambda with -`DynamoDB.consumeTableChanges` (see the -[DynamoDB Streams guide](/aws/messaging/dynamodb-streams)). - -The walkthrough below builds on the [Lambda](/aws/compute/lambda) and -[S3](/aws/data/s3) pages: it adds a **Table** and binds `GetItem` + -`PutItem` to the function — same pattern as S3, different -storage. - -## Define the table - -DynamoDB tables need a partition key (and optionally a sort key) -declared up-front. Yield the `Table` resource in the function's -constructor, mirroring how you added the bucket: - -```diff lang="typescript" -// src/api.ts -import * as AWS from "alchemy/AWS"; -+import * as DynamoDB from "alchemy/AWS/DynamoDB"; -import * as S3 from "alchemy/AWS/S3"; -import { Stack } from "alchemy/Stack"; -import * as Effect from "effect/Effect"; -// ... - -Effect.gen(function* () { - const bucket = yield* S3.Bucket("Blobs"); -+ const table = yield* DynamoDB.Table("Items", { -+ partitionKey: "id", -+ attributes: { -+ id: "S", -+ }, -+ }); - - // ... existing bindings + handler ... +> How DynamoDB Tables store items under partition and sort keys, how to design keys and indexes for the reads you need, and how runtimes read, write and react to items through bindings. + +DynamoDB is a database of **items** looked up by **key**. A read or write by key takes a few milliseconds whether the table holds a hundred items or a billion, and you never size a server for it: by default you pay per request. + +That speed comes from one rule: you can only look items up by their keys. So designing a table starts from the questions you'll ask it. + +## A table is items under keys + +An item is a set of attributes, like a row without a fixed schema. Every item has a **partition key**, and DynamoDB stores items by it: all items with the same partition key live together, and different partition keys spread across many machines. + +A table can also have a **sort key**. Then the partition key and the sort key together identify an item, and the items in one partition are kept in order by the sort key. + + + +Two kinds of read are fast. **Get** one item by its full key. **Query** one partition, optionally narrowing by a range of sort keys: "Sam's orders in 2026". Anything else means a **scan**, which reads the whole table. So list the reads your app needs before you choose the keys, and pick keys that turn each one into a get or a query. + +## Declare a table + +Name the key attributes and their types. `"S"` is a string, `"N"` a number, `"B"` binary: + +```typescript title="src/orders.ts" +import * as AWS from "@alchemy.run/aws"; + +export const Orders = AWS.DynamoDB.Table("Orders", { + partitionKey: "pk", + sortKey: "sk", + attributes: { pk: "S", sk: "S" }, }); ``` -`attributes` only needs to list the attributes used by keys (and -secondary indexes) — DynamoDB itself is schemaless on the rest of -the row. `"S"` is the AWS shorthand for "string"; `"N"` is number -and `"B"` is binary. +`attributes` lists only the attributes used in keys and indexes. Every other attribute of an item is free-form. -## Bind GetItem and PutItem +The table is created on-demand: there's no capacity to set, and you pay per read and write. Alchemy names it from your app, stage and id, so each stage gets its own table. -Same shape as the S3 bindings — `PutItem(table)` returns a callable -Effect and quietly attaches a least-privilege IAM policy scoped to -this table's ARN: +## Write items -```diff lang="typescript" -Effect.gen(function* () { - const bucket = yield* S3.Bucket("Blobs"); - const table = yield* DynamoDB.Table("Items", { /* ... */ }); +Bind `DynamoDB.PutItem` in a runtime. Its role gets `dynamodb:PutItem` on this table only: + +```typescript title="src/api.ts" +const putItem = yield* AWS.DynamoDB.PutItem(Orders); +``` - const putObject = yield* S3.PutObject(bucket); - const getObject = yield* S3.GetObject(bucket); -+ const putItem = yield* DynamoDB.PutItem(table); -+ const getItem = yield* DynamoDB.GetItem(table); +An item is written in DynamoDB's own attribute format, where each value says its type: - return { fetch: /* ... */ }; +```typescript title="src/api.ts" +yield* putItem({ + Item: { + pk: { S: "user#sam" }, + sk: { S: "order#2026-02-11" }, + total: { N: "42" }, + }, }); ``` -## Write items with `PUT /items/:id` - -Add a branch to `fetch` that writes a row keyed by the URL -segment. DynamoDB takes attribute values in their native typed -form — `{ S: "..." }` for strings, `{ N: "42" }` for numbers — -and Alchemy bindings deliberately **don't** auto-marshal so you -stay on the raw SDK shape: - -```diff lang="typescript" -fetch: Effect.gen(function* () { - const request = yield* HttpServerRequest; - const url = new URL(request.url); - const path = url.pathname; - -+ if (path.startsWith("/items/") && request.method === "PUT") { -+ const id = path.slice("/items/".length); -+ const content = yield* request.text; -+ yield* putItem({ -+ Item: { -+ id: { S: id }, -+ content: { S: content }, -+ }, -+ }); -+ return HttpServerResponse.empty({ status: 204 }); -+ } - - // ... existing /:key blob routes ... -}).pipe(Effect.orDie), -``` +The bindings pass this format through unchanged, so what you write is exactly what the API receives. If you'd rather work with plain objects, wrap the client in a function that converts them. + +A put replaces any item with the same key. To change some attributes and keep the rest, use `DynamoDB.UpdateItem`. To write only if the item doesn't exist yet, add a `ConditionExpression`, and catch `ConditionalCheckFailedException` when it does. + +## Read an item + +Bind `DynamoDB.GetItem` and read by the full key: -Skipping marshalling keeps the binding tiny and avoids a -debate over which marshalling layer to use. If you want a -typed-object API across your codebase, build it as a thin -wrapper around `putItem` — the binding won't fight you. - -## Read items with `GET /items/:id` - -The read path uses `getItem` with the same `{ S: id }` key -shape: - -```diff lang="typescript" -if (path.startsWith("/items/") && request.method === "PUT") { - // ... unchanged ... -} - -+if (path.startsWith("/items/") && request.method === "GET") { -+ const id = path.slice("/items/".length); -+ const result = yield* getItem({ Key: { id: { S: id } } }); -+ if (!result.Item) { -+ return HttpServerResponse.text("Not found", { status: 404 }); -+ } -+ return yield* HttpServerResponse.json({ -+ id: result.Item.id?.S, -+ content: result.Item.content?.S, -+ }); -+} +```typescript title="src/api.ts" +const getItem = yield* AWS.DynamoDB.GetItem(Orders); +const { Item } = yield* getItem({ + Key: { pk: { S: "user#sam" }, sk: { S: "profile" } }, +}); ``` -`getItem` returns `result.Item` as `undefined` when the row -doesn't exist — no need for a typed `catchTag` like S3's -`NoSuchKey`. Map the AWS attribute-value shape back to a plain -object at the response boundary. - -## Provide the runtime layers - -Add the DynamoDB lives next to the S3 ones: - -```diff lang="typescript" -}).pipe( - Effect.provide( - Layer.mergeAll( - AWS.Lambda.BucketEventSource, -+ DynamoDB.GetItemHttp, -+ DynamoDB.PutItemHttp, - S3.PutObjectHttp, - S3.GetObjectHttp, - ), - ), -), +A missing item isn't an error: `Item` is just `undefined`. + +Each binding has a client Layer named after it. Provide the ones you bind to the runtime, merged into one: + +```typescript title="src/api.ts" +Effect.provide(Layer.mergeAll(AWS.DynamoDB.GetItemHttp, AWS.DynamoDB.PutItemHttp)) ``` -## Deploy and verify +## Query a partition -```sh -bun alchemy deploy +Bind `DynamoDB.Query` to read many items from one partition. The key condition names the partition and, optionally, a range of sort keys: + +```typescript title="src/api.ts" +const query = yield* AWS.DynamoDB.Query(Orders); +const { Items } = yield* query({ + KeyConditionExpression: "pk = :pk AND begins_with(sk, :prefix)", + ExpressionAttributeValues: { + ":pk": { S: "user#sam" }, + ":prefix": { S: "order#2026" }, + }, +}); ``` -Add a round-trip test that exercises the new routes: +Items come back in sort-key order, a page at a time. This is why the sort key above starts with `order#` and a date: one query returns a user's orders for a year, already sorted. -```typescript -// test/integ.test.ts -test( - "DynamoDB round-trip", - Effect.gen(function* () { - const { url } = yield* stack; +## Add an index for another question - yield* HttpClient.put(`${url}/items/abc`, { - body: HttpBody.text("hello dynamo"), - }); +Some reads don't fit the table's keys: "every order placed today", across all users. A **global secondary index** answers them. It's a copy of the table, kept in sync for you, with its own partition and sort key: - const get = yield* HttpClient.get(`${url}/items/abc`); - expect(yield* get.json).toEqual({ id: "abc", content: "hello dynamo" }); - }), -); +```typescript title="src/orders.ts" +export const Orders = AWS.DynamoDB.Table("Orders", { + partitionKey: "pk", + sortKey: "sk", + attributes: { pk: "S", sk: "S", day: "S" }, + globalSecondaryIndexes: [ + { indexName: "byDay", partitionKey: "day", sortKey: "sk", projection: { ProjectionType: "ALL" } }, + ], +}); ``` -```sh -bun test test/integ.test.ts +Query it by passing `IndexName: "byDay"` to the same `query` client. An index is updated shortly after each write, so a query on it may briefly miss the newest items. + +Each index costs storage and a write for every item it covers. Add one per question that needs it, not one per attribute. + +## Expire items with TTL + +Sessions, caches and one-time codes should disappear on their own. Name an attribute that holds an expiry time, in seconds since 1970, and DynamoDB deletes each item some time after it passes: + +```typescript title="src/sessions.ts" +export const Sessions = AWS.DynamoDB.Table("Sessions", { + partitionKey: "id", + attributes: { id: "S" }, + timeToLiveSpecification: { AttributeName: "expiresAt", Enabled: true }, +}); ``` -The IAM policy attached to your function role now includes -`dynamodb:GetItem` and `dynamodb:PutItem` — both scoped to this -specific table — alongside the S3 grants. +Deletion can lag the expiry by a while, so check `expiresAt` when you read too. + +## React to changes + +A table can publish every change to its items, in order per item, as a **stream**. A Function consumes it to keep a search index current, send notifications or update totals. See [DynamoDB Streams](/aws/messaging/dynamodb-streams). -## Where next +## Deploy changes to a table -- [Process DynamoDB Streams](/aws/messaging/dynamodb-streams) — - fan table changes out into a Lambda-side `Stream` you can - react to. -- [SQS](/aws/messaging/sqs) — a general-purpose queue for background - work, fed from the same Lambda. -- [`Table` reference](/providers/aws/dynamodb/table) — every - prop and attribute, including secondary indexes, TTL, and - point-in-time recovery. +Most settings change in place: indexes, TTL, tags, streams and recovery are updated on the existing table. Changing the partition key, the sort key or a local secondary index replaces the table, because DynamoDB can't change them, and replacing a table loses its items. + +Protect a table that holds data you can't recreate. Turn on point-in-time recovery to restore it to any second in the last 35 days, and deletion protection to refuse a delete until you turn it off: + +```typescript title="src/orders.ts" +export const Orders = AWS.DynamoDB.Table("Orders", { + partitionKey: "pk", + sortKey: "sk", + attributes: { pk: "S", sk: "S" }, + pointInTimeRecoverySpecification: { pointInTimeRecoveryEnabled: true }, + deletionProtectionEnabled: true, +}); +``` diff --git a/.agents/skills/alchemy/references/aws/data/rds.md b/.agents/skills/alchemy/references/aws/data/rds.md index ae2b0667..4890e4e5 100644 --- a/.agents/skills/alchemy/references/aws/data/rds.md +++ b/.agents/skills/alchemy/references/aws/data/rds.md @@ -1,337 +1,147 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # RDS & Aurora -> Stand up an Aurora cluster in one call with the Aurora helper, connect from Lambda over the Connect binding with pg, or skip connections entirely with the Data API. - -Aurora is AWS's managed Postgres/MySQL. Bringing it up by hand -means a secret, a subnet group, a cluster, instances, and -optionally a proxy — alchemy wraps all of that in the -**`Aurora` helper**, one call that returns every underlying -`DB*` resource so you can drop down to the canonical surface -(`DBCluster`, `DBInstance`, `DBProxy`, …) whenever you outgrow -the defaults. - -At runtime there are two ways in: the **`Connect` binding**, -which resolves host, port, and credentials from Secrets Manager -so you can use a normal Postgres driver like `pg`, and the -**Data API** (`AWS.RDSData.*`), which executes SQL over an HTTPS -endpoint with no database connection at all. - -## Network prerequisite - -Aurora lives inside a VPC. If you don't have one, the -[`Network` helper](/aws/networking) builds the standard -public/private layout in one call; two security groups let the -function reach the database on the Postgres port and nothing -else: - -```typescript -const network = yield* AWS.EC2.Network("Network", { - cidrBlock: "10.0.0.0/16", - availabilityZones: 2, - nat: "single", -}); +> How RDS and Aurora run Postgres and MySQL inside your VPC, how the Aurora helper creates a cluster with its secret, subnets and instances, and how runtimes connect, migrate and scale it. + +RDS runs relational databases for you: Postgres, MySQL, MariaDB and others, with backups, patching and failover handled by AWS. **Aurora** is AWS's own engine behind the Postgres and MySQL interfaces. It separates compute from storage, so a cluster's instances share one copy of the data, replicated across three Availability Zones. + +## A cluster is storage plus instances + +An Aurora **cluster** owns the storage: one volume, grown automatically, kept in six copies across three zones. **Instances** are the compute that run queries against it. One instance is the **writer**. Others are **readers**, which serve reads from the same storage and take over if the writer fails. + + + +Instances come in two kinds. **Serverless v2** instances scale their capacity, measured in ACUs, up and down with load. **Provisioned** instances have a fixed size, like `db.r6g.large`. + +## It lives in your VPC + +A database has no public address. Its instances sit in private subnets of a VPC, and a **security group** decides who may connect on the database's port. Its admin password is kept in **Secrets Manager**, never in code. + +So a database starts with a network. The `Network` helper builds one, and a security group lets one other group in on port 5432: + +```typescript title="src/network.ts" +const network = yield* AWS.EC2.Network("Network", { cidrBlock: "10.0.0.0/16", nat: "single" }); + +const appSecurityGroup = yield* AWS.EC2.SecurityGroup("App", { vpcId: network.vpcId }); -const functionSecurityGroup = yield* AWS.EC2.SecurityGroup( - "FunctionSecurityGroup", - { - vpcId: network.vpcId, - description: "Security group for the service function", - }, -); - -const databaseSecurityGroup = yield* AWS.EC2.SecurityGroup( - "DatabaseSecurityGroup", - { - vpcId: network.vpcId, - description: "Security group for the Aurora cluster", - ingress: [ - { - ipProtocol: "tcp", - fromPort: 5432, - toPort: 5432, - referencedGroupId: functionSecurityGroup.groupId, - description: "Allow the function to reach Aurora PostgreSQL", - }, - ], - }, -); +const databaseSecurityGroup = yield* AWS.EC2.SecurityGroup("Database", { + vpcId: network.vpcId, + ingress: [ + { ipProtocol: "tcp", fromPort: 5432, toPort: 5432, referencedGroupId: appSecurityGroup.groupId }, + ], +}); ``` -See [VPC & networking](/aws/networking) for what `Network` -creates and how to build the same layout by hand. +Anything in `appSecurityGroup` can reach the database. Nothing else can. See [VPC & networking](/aws/networking). -## The Aurora helper +## Create a cluster -[`Aurora`](/providers/aws/rds/aurora) needs only the subnets and -security groups the database should live in: +`AWS.RDS.Aurora` creates everything a cluster needs from the subnets and security groups it lives in: -```typescript +```typescript title="src/database.ts" const db = yield* AWS.RDS.Aurora("Database", { subnetIds: network.privateSubnetIds, securityGroupIds: [databaseSecurityGroup.groupId], }); ``` -That one call creates: - -- a **Secrets Manager secret** with a generated 32-character - password for the admin user (`app` by default), -- a **DB subnet group** over the subnets you passed, -- an **Aurora PostgreSQL cluster** (`aurora-postgresql`) with a - database named `app`, storage snapshots tagged, and the - **Data API enabled** (`dataApi: false` to turn it off), -- one **Serverless v2 writer** instance scaling between 0.5 and - 1 ACU. +That's a Secrets Manager secret with a generated password, a subnet group, an Aurora PostgreSQL cluster with a database named `app` and the Data API turned on, and one Serverless v2 writer scaling between 0.5 and 1 ACU. Set `engine: "aurora-mysql"` for MySQL. -The result exposes every underlying resource — `db.secret`, -`db.subnetGroup`, `db.cluster`, `db.writer`, `db.readers`, -and `db.proxy` when enabled — so expanding into the low-level -`AWS.RDS.DB*` surface never means rewriting the stack. +Each part is on the result: `db.secret`, `db.cluster`, `db.writer`, `db.readers`. Configure any of them through the helper's props, or declare the `AWS.RDS.DB*` resources yourself when you need full control. -## Readers, scaling, and a proxy +## Apply migrations on deploy -Grow the same call as needs grow: +Point `migrations` at a directory of `.sql` files. Each deploy applies the new ones once the writer is ready, in order, and records them in an `__alchemy_migrations` table: -```typescript +```typescript title="src/database.ts" const db = yield* AWS.RDS.Aurora("Database", { subnetIds: network.privateSubnetIds, securityGroupIds: [databaseSecurityGroup.groupId], - readers: 2, - proxy: true, - scaling: { minCapacity: 0.5, maxCapacity: 4 }, + migrations: "./migrations", }); ``` -- `readers` adds read replicas alongside the writer, with - promotion tiers set so failover order is deterministic. -- `proxy: true` wires up an RDS Proxy — the IAM role that reads - the secret, the proxy itself (TLS required by default), and a - target group pointed at the cluster. Pass an object instead of - `true` to tune auth, the target group, or add an extra - endpoint. -- `scaling` sets the Serverless v2 ACU range; for provisioned - instances set `instanceClass: "db.r6g.large"` instead of the - default `db.serverless`. - -## Connect from Lambda with pg - -The [`Connect`](/providers/aws/rds/connect) binding resolves -connection settings — host, port, database, username, password — -for a cluster, proxy, or proxy endpoint. Credentials are read -from Secrets Manager **at request time**, so they never land in -environment variables, and the binding attaches the -`secretsmanager:GetSecretValue` IAM statement to the function -automatically. - -Wrap it in an Effect service so the rest of your code depends on -`query`, not on Aurora: - -```typescript -// src/database.ts -import * as AWS from "alchemy/AWS"; -import * as Context from "effect/Context"; -import * as Data from "effect/Data"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import { Client } from "pg"; -import { Network } from "./network.ts"; - -export class SqlError extends Data.TaggedError("SqlError")<{ - readonly message: string; - readonly cause?: unknown; -}> {} - -export class Database extends Context.Service< - Database, - { - query( - statement: string, - ): Effect.Effect>, SqlError>; - } ->()("Database") {} - -export const DatabaseAurora = Layer.effect( - Database, - Effect.gen(function* () { - const { vpc, databaseSecurityGroup } = yield* Network; - - const db = yield* AWS.RDS.Aurora("Database", { - subnetIds: vpc.privateSubnetIds, - securityGroupIds: [databaseSecurityGroup.groupId], - }); - - const connect = yield* AWS.RDS.Connect(db.cluster, { - secret: db.secret, - database: "app", - }); - - return Database.of({ - query: (statement) => - connect.pipe( - Effect.catch((cause) => - Effect.fail( - new SqlError({ message: "Failed to resolve connection", cause }), - ), - ), - Effect.flatMap((connection) => - Effect.tryPromise({ - try: async () => { - const client = new Client({ - host: connection.host, - port: connection.port, - database: connection.database, - user: connection.username, - password: connection.password, - ssl: connection.ssl - ? { rejectUnauthorized: false } - : undefined, - }); - await client.connect(); - try { - return (await client.query(statement)).rows; - } finally { - await client.end(); - } - }, - catch: (cause) => - new SqlError({ message: `Failed to execute: ${statement}`, cause }), - }), - ), - ), - }); - }), -); +Migrations travel over the Data API, so the machine running the deploy needs no route into the VPC. Over the Data API each statement is its own call: put one statement per file, or separate them with `--> statement-breakpoint` as drizzle-kit does. A database already migrated by drizzle-kit or Prisma is picked up where it left off. + +Without the Data API, declare an `AWS.RDS.MigrationRunner`, a Function inside the VPC that applies them, and pass it as `migrationsTransport`. See [SQL migrations](/sql/effect-sql/migrations). + +## Connect with a driver + +A runtime inside the VPC connects with an ordinary Postgres driver. Bind `AWS.RDS.Connect` to the cluster, and it resolves the host, port and credentials from the secret each time you ask, granting the runtime permission to read that secret: + +```typescript title="src/database.ts" +const connect = yield* AWS.RDS.Connect(db.cluster, { secret: db.secret, database: "app" }); + +const sql = yield* SQL.Postgres({ + url: connect.pipe(Effect.map((connection) => connection.url)), +}); ``` -`yield* AWS.RDS.Connect(db.cluster, ...)` runs in the function's -Construction phase and returns an inner Effect; each `yield*` of that -inner Effect at runtime resolves fresh `ConnectionInfo` from the -secret. `Network` here is the same network from the prerequisite -section, wrapped in its own layer (see the -[`examples/aws-rds`](https://github.com/alchemy-run/alchemy/tree/main/examples/aws-rds) -for the full three-file layout). - -The Lambda function provides both layers plus the -`AWS.RDS.ConnectHttp` implementation and serves queries over -HTTP: - -```typescript -// src/api.ts -import * as AWS from "alchemy/AWS"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as HttpServerResponse from "effect/http/HttpServerResponse"; -import { Database, DatabaseAurora } from "./database.ts"; -import { NetworkLive } from "./network.ts"; - -export default class Api extends AWS.Lambda.Function()( - "Api", - { main: import.meta.url, runtime: "nodejs24.x" }, - Effect.gen(function* () { - const db = yield* Database; - - return { - fetch: db.query("select now()::text as now").pipe( - Effect.flatMap((rows) => HttpServerResponse.json(rows[0] ?? null)), - Effect.catchTag("SqlError", (error) => - HttpServerResponse.json({ error: error.message }, { status: 500 }), - ), - ), - }; - }).pipe( - Effect.provide( - Layer.provideMerge( - Layer.mergeAll(DatabaseAurora), - Layer.mergeAll(NetworkLive, AWS.RDS.ConnectHttp), - ), - ), - ), -) {} +The password never lands in an environment variable, and a rotated secret is picked up on the next connection. `SQL.Postgres` opens its pool on the first query of an invocation and closes it when the invocation ends. See [Effect SQL on Postgres](/sql/effect-sql/postgres). + +A Lambda Function joins the VPC with its `vpc` prop: + +```typescript title="src/api.ts" +{ main: import.meta.url, vpc: { subnetIds: network.privateSubnetIds, securityGroupIds: [appSecurityGroup.groupId] } } ``` -The handler only sees `Database` — swap `DatabaseAurora` for a -layer backed by [Neon](/neon) or a local Postgres and nothing -above it changes. - -Yield the function in your Stack as usual: - -```typescript -// alchemy.run.ts -import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; -import * as Effect from "effect/Effect"; -import Api from "./src/api.ts"; - -export default Alchemy.Stack( - "MyApp", - { providers: AWS.providers(), state: AWS.state() }, - Effect.gen(function* () { - const api = yield* Api; - return { url: api.functionUrl }; - }), -); +## Query without a connection + +The **Data API** runs SQL over HTTPS instead. There's no driver, no pool and no VPC to join, so any runtime can use it. Bind `AWS.RDSData.ExecuteStatement`: + +```typescript title="src/api.ts" +const execute = yield* AWS.RDSData.ExecuteStatement(db.cluster, { secret: db.secret, database: "app" }); +const result = yield* execute({ sql: "select now()" }); ``` -To reach a private cluster over a direct connection, the Lambda -function also accepts a `vpc` prop -(`vpc: { subnetIds, securityGroupIds }`) that attaches it to the -VPC and adds the `AWSLambdaVPCAccessExecutionRole` managed -policy for you. +The binding grants `rds-data:ExecuteStatement` on the cluster and read access to the secret. Provide `AWS.RDSData.ExecuteStatementHttp` to the runtime. Transactions use `BeginTransaction`, `CommitTransaction` and `RollbackTransaction`, each a binding of its own. + +Each Data API call adds a little latency over a warm connection. It suits functions that run a few queries per invocation, where opening a connection would cost more. -## The Data API +## Add readers, a proxy and capacity -Aurora's Data API executes SQL over an HTTPS endpoint — no -connection pool, no driver. The `Aurora` helper enables it by -default, and the `AWS.RDSData` bindings expose it the same way -as any other capability: +Grow the same declaration as load grows: -```typescript -// Construction -const execute = yield* AWS.RDSData.ExecuteStatement(db.cluster, { - secret: db.secret, - database: "app", +```typescript title="src/database.ts" +const db = yield* AWS.RDS.Aurora("Database", { + subnetIds: network.privateSubnetIds, + securityGroupIds: [databaseSecurityGroup.groupId], + readers: 2, + scaling: { minCapacity: 0.5, maxCapacity: 8 }, + proxy: true, }); +``` -// runtime -const result = yield* execute({ sql: "select now()" }); +`readers` adds instances that serve reads and take over on failure. `scaling` sets the Serverless v2 range. Use `instanceClass` for a fixed instance size instead. + +`proxy` adds an **RDS Proxy** in front of the cluster. Lambda can start hundreds of environments at once, each opening its own connections, and a database only accepts so many. The proxy holds a shared pool and hands connections out, so a traffic spike doesn't exhaust the database. Bind `AWS.RDS.Connect` to `db.proxy` instead of the cluster to use it. + +## Keep the data across deploys + +Destroying the cluster deletes its data, with no final snapshot. Protect a production database from an accidental destroy with `deletionProtection`, and keep backups for longer than the default day: + +```typescript title="src/database.ts" +const db = yield* AWS.RDS.Aurora("Database", { + subnetIds: network.privateSubnetIds, + securityGroupIds: [databaseSecurityGroup.groupId], + deletionProtection: true, + backupRetentionPeriod: "14 days", +}); ``` -Provide `AWS.RDSData.ExecuteStatementHttp` as a layer on the -function. The binding attaches both the -`rds-data:ExecuteStatement` and secret-read IAM statements — -no policy JSON to write. - -Transactions and batches follow the same shape: -`BatchExecuteStatement`, `BeginTransaction`, `CommitTransaction`, -and `RollbackTransaction`, each with a matching `*Http` layer. - -## Where next - -- [Drizzle + Aurora PostgreSQL](/aws/data/drizzle-aurora) — a standalone Lambda - application with IAM database authentication, verified TLS, and controlled schema setup. -- [Drizzle + Aurora DSQL](/aws/data/drizzle-dsql) — a different database with a - public IAM-authenticated endpoint, no Aurora PostgreSQL cluster or VPC required. - -- [SQL databases](/sql/databases) — database engines, connection paths, and client choices. - -- [VPC & networking](/aws/networking) — the `Network` helper and - the primitives underneath it. -- [Lambda](/aws/compute/lambda) — the runtime this page binds Aurora - into. -- [Secrets & env](/aws/security/secrets-env) — how the generated secret - and GetSecretValue binding this page relies on actually work. -- [Neon](/neon) — serverless Postgres with branching, no VPC - required. -- [PlanetScale](/planetscale) — horizontally sharded MySQL and - Postgres. - -Reference: - -- [`Aurora` reference](/providers/aws/rds/aurora) — every prop - on the helper. -- [`Connect` reference](/providers/aws/rds/connect) -- [`ExecuteStatement` reference](/providers/aws/rdsdata/executestatement) +AWS then refuses to delete the cluster until you turn the protection off. Within the retention period, you can restore the cluster to any point in time. + +For the whole app, from network to Drizzle queries, see [Drizzle + Aurora](/aws/data/drizzle-aurora). For a serverless database with no VPC at all, see [Drizzle + DSQL](/aws/data/drizzle-dsql). diff --git a/.agents/skills/alchemy/references/aws/data/s3.md b/.agents/skills/alchemy/references/aws/data/s3.md index 7f7bbbd3..78484eaf 100644 --- a/.agents/skills/alchemy/references/aws/data/s3.md +++ b/.agents/skills/alchemy/references/aws/data/s3.md @@ -1,311 +1,162 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # S3 -> Add an S3 Bucket to your Stack, bind PutObject and GetObject as runtime capabilities, and let Alchemy mint the IAM policy for you. - -**S3** is AWS's object store — blobs of any size, addressed by -key. In Alchemy it's the `Bucket` resource plus a binding per S3 -operation: `GetObject`, `PutObject`, `DeleteObject`, -`HeadObject`, `CopyObject`, `ListObjectsV2`, and the multipart -upload family. Each binding you call attaches the matching IAM -statement — scoped to that bucket's ARN — to your function's -role. Buckets are also an event source: subscribe a Lambda to -new-object notifications with `S3.consumeBucketEvents` (see the -[S3 events guide](/aws/messaging/s3-events)). - -The walkthrough below builds on the function from -[Lambda](/aws/compute/lambda): it adds a **Bucket** for blob storage and -binds **PutObject** + **GetObject** — Alchemy mints a -least-privilege IAM policy from the bindings you actually use. - -## Add the bucket - -S3 buckets are canonical Alchemy resources, so you create them -the same way as the Lambda — yield the resource inside an Effect -and the Stack captures it. Open `src/api.ts` and add a bucket in -the constructor: - -```diff lang="typescript" -// src/api.ts -import * as AWS from "alchemy/AWS"; -+import * as S3 from "alchemy/AWS/S3"; -import { Stack } from "alchemy/Stack"; -import * as Effect from "effect/Effect"; -+import { HttpServerRequest } from "effect/http/HttpServerRequest"; -import * as HttpServerResponse from "effect/http/HttpServerResponse"; +> How S3 Buckets hold objects under keys, how a runtime reads and writes them through bindings, and how to share, react to and serve the objects you store. -export default class Api extends AWS.Lambda.Function()( - "Api", - Stack.useSync((stack) => ({ - main: import.meta.url, - functionUrl: true, - memory: stack.stage === "prod" ? 1024 : 512, - })), - Effect.gen(function* () { -+ const bucket = yield* S3.Bucket("Blobs"); +S3 stores files, called **objects**, in containers called **Buckets**. An object is any sequence of bytes, from a few characters to five terabytes, stored under a **key** you choose. Buckets hold as many objects as you put in them, and you pay for what you store and transfer. - return { - fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")), - }; - }), -) {} -``` +## A Bucket holds objects under keys -`yield* S3.Bucket("Blobs")` registers the resource with the Stack -under the logical id `Blobs` and returns a typed `Bucket` handle. -Other resources — including this Lambda — can use that handle to -bind operations or grant access. +A Bucket is a flat map from keys to objects. A key is just a string: `avatars/sam.png`, `reports/2026/q1.pdf`, `hello.txt`. -## Bind PutObject and GetObject +There are no real folders. A key with slashes in it looks like a path, and S3 can list every key that starts with a **prefix** like `reports/2026/`, so slashes work like folders when you list. But `reports/2026/q1.pdf` is one key, not a file inside two directories. -S3 operations like `s3:PutObject` and `s3:GetObject` are exposed -as **bindings**. A binding is two things: + -1. A typed runtime function you call from your handler. -2. An IAM policy statement that gets attached to the function - role automatically — scoped to the exact bucket ARN. +Writing a key that already exists replaces its object as a whole. S3 never changes part of an object. To keep the old copy as well, turn on versioning, and each write becomes a new **version** of the key. -Bind them in the constructor, alongside the bucket: +## Declare a Bucket -```diff lang="typescript" -Effect.gen(function* () { - const bucket = yield* S3.Bucket("Blobs"); -+ const putObject = yield* S3.PutObject(bucket); -+ const getObject = yield* S3.GetObject(bucket); +A Bucket is a declaration. Give it an id: - return { - fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")), - }; -}); -``` +```typescript title="src/files.ts" +import * as AWS from "@alchemy.run/aws"; -Both capability calls return a callable Effect: `putObject` -takes a `PutObjectRequest` (the AWS SDK shape, minus the `Bucket` -field Alchemy fills in for you) and `getObject` takes a -`GetObjectRequest`. - -### One binding, one IAM statement - -Each `S3.PutObject(bucket)`-style capability call is **1:1 with an IAM policy statement** -attached to your function's execution role. The mapping is -deterministic: - -| Code | IAM `Action` | IAM `Resource` | -| --------------------------------- | ---------------- | ------------------------ | -| `S3.PutObject(bucket)` | `s3:PutObject` | `bucket.bucketArn` | -| `S3.GetObject(bucket)` | `s3:GetObject` | `bucket.bucketArn/*` | -| `DynamoDB.PutItem(table)` | `dynamodb:PutItem` | `table.tableArn` | -| `SQS.SendMessage(queue)` | `sqs:SendMessage` | `queue.queueArn` | - -So the two capability calls above produce exactly two statements on -the role: - -```json -[ - { - "Sid": "AWSS3PutObjectBlobs", - "Effect": "Allow", - "Action": ["s3:PutObject"], - "Resource": "arn:aws:s3:::myapp-prod-blobs/*" - }, - { - "Sid": "AWSS3GetObjectBlobs", - "Effect": "Allow", - "Action": ["s3:GetObject"], - "Resource": "arn:aws:s3:::myapp-prod-blobs/*" - } -] +export const Files = AWS.S3.Bucket("Files"); ``` -The role is generated, never `"*"`-scoped, and regenerated from -the call sites on every deploy — delete a capability call and the -matching statement disappears next deploy. **The code is the -policy.** - -## Write objects with `PUT /:key` - -Replace the static handler with one that takes the URL path as -the object key and writes the request body to the bucket: - -```diff lang="typescript" -return { -- fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")), -+ fetch: Effect.gen(function* () { -+ const request = yield* HttpServerRequest; -+ const key = new URL(request.url).pathname.slice(1); -+ -+ if (request.method === "PUT") { -+ const body = yield* request.text; -+ yield* putObject({ Key: key, Body: body }); -+ return HttpServerResponse.empty({ status: 204 }); -+ } -+ -+ return HttpServerResponse.text("Method not allowed", { status: 405 }); -+ }), -}; -``` +Bucket names are global: no two Buckets anywhere in AWS share a name. So you don't pick one. Alchemy names it from your app, stage and id, like `myapp-dev-files-a1b2c3`, and your `dev` and `prod` stages each get their own Bucket. -`putObject({ Key, Body })` is the same shape as -`s3:PutObject` in the AWS SDK, minus the `Bucket` field — Alchemy -fills that in from the bucket you bound, so the call site stays -focused on what's actually variable. +A new Bucket is private. Nothing outside your account can read it, and nothing inside can either, until a policy allows it. -## Read objects with `GET /:key` +## Write objects -Add a `GET` branch that fetches the object and pipes it back to -the client: +Bind `S3.PutObject` in a runtime to write to the Bucket. The binding gives the runtime a client, and gives its role `s3:PutObject` on this Bucket's objects and no others: -```diff lang="typescript" -if (request.method === "PUT") { - const body = yield* request.text; - yield* putObject({ Key: key, Body: body }); - return HttpServerResponse.empty({ status: 204 }); -} +```typescript title="src/api.ts" +const putObject = yield* AWS.S3.PutObject(Files); +``` -+if (request.method === "GET") { -+ const result = yield* getObject({ Key: key }); -+ return HttpServerResponse.stream(result.Body!); -+} +Call it with a key and a body: -return HttpServerResponse.text("Method not allowed", { status: 405 }); +```typescript title="src/api.ts" +yield* putObject({ Key: "hello.txt", Body: "Hello, world", ContentType: "text/plain" }); ``` -`result.Body` is an Effect `Stream`, not a buffered -`Buffer`. `HttpServerResponse.stream` flushes each chunk to the -HTTP response as it arrives, so even a multi-gigabyte object -moves through the function without ever being held in memory. - -## Handle missing objects - -If the key doesn't exist, the AWS SDK throws `NoSuchKey`. The -binding surfaces that as a typed error tag on the Effect, so -`Effect.catchTag` recovers from it without inspecting strings: - -```diff lang="typescript" -if (request.method === "GET") { -- const result = yield* getObject({ Key: key }); -+ const result = yield* getObject({ Key: key }).pipe( -+ Effect.catchTag("NoSuchKey", () => Effect.succeed(undefined)), -+ ); -+ if (!result?.Body) { -+ return HttpServerResponse.text("Not found", { status: 404 }); -+ } - return HttpServerResponse.stream(result.Body!); -} -``` +The request is the S3 API's own `PutObject` input without `Bucket`, which the binding fills in. Provide its client, `S3.PutObjectHttp`, to the runtime: -Every binding's failure channel is enumerated this way: the AWS -SDK error names become Effect tags, so the type-checker tells -you which failures the call site needs to handle. +```typescript title="src/api.ts" +export default class Api extends AWS.Lambda.Function()( + "Api", + { main: import.meta.url }, + Effect.gen(function* () { + const putObject = yield* AWS.S3.PutObject(Files); + return { + fetch: Effect.gen(function* () { + const request = yield* HttpServerRequest; + const key = new URL(request.url).pathname.slice(1); + yield* putObject({ Key: key, Body: yield* request.text }); + return HttpServerResponse.empty({ status: 204 }); + }).pipe(Effect.orDie), + }; + }).pipe(Effect.provide(AWS.S3.PutObjectHttp)), +) {} +``` -## Convert unhandled errors to 500s +## Read objects -Any failure you didn't `catchTag` is a programmer error — a -missing IAM grant, a transient AWS outage, a bug. Surface those -as 500s by applying `Effect.orDie` once at the request boundary, -rather than per call: +Bind `S3.GetObject` to read. Its result carries the object's metadata and its `Body`, a stream of bytes: -```diff lang="typescript" -fetch: Effect.gen(function* () { - // ... PUT and GET branches ... - return HttpServerResponse.text("Method not allowed", { status: 405 }); --}), -+}).pipe(Effect.orDie), +```typescript title="src/api.ts" +const getObject = yield* AWS.S3.GetObject(Files); +const object = yield* getObject({ Key: "hello.txt" }); ``` -Applying `orDie` once at the outer layer keeps the inner code -free of repetitive error plumbing — the only errors you handle -explicitly are the ones you actually have a recovery for -(`NoSuchKey`, in this case). +Pass the stream straight to the response. The bytes flow through as they arrive, so an object larger than the Function's memory still downloads: -## Provide the runtime layers +```typescript title="src/api.ts" +return HttpServerResponse.stream(object.Body!); +``` -Bindings declare a capability; **runtime layers** implement it. -For S3 those are `S3.PutObjectHttp` and `S3.GetObjectHttp` — both -ship in `alchemy/AWS/S3` and depend only on the AWS SDK and the -ambient credentials. Provide them at the bottom of the function: +A key with no object fails with `NoSuchKey`. Catch it by name, and every other failure stays in the type: -```diff lang="typescript" -// src/api.ts -+import * as Layer from "effect/Layer"; -// ... -export default class Api extends AWS.Lambda.Function()( - "Api", - /* ... props ... */, - Effect.gen(function* () { - /* ... bindings + fetch ... */ -- }), -+ }).pipe( -+ Effect.provide(Layer.mergeAll(S3.PutObjectHttp, S3.GetObjectHttp)), -+ ), -) {} +```typescript title="src/api.ts" +const object = yield* getObject({ Key: key }).pipe( + Effect.catchTag("NoSuchKey", () => Effect.succeed(undefined)), +); +if (!object?.Body) return HttpServerResponse.text("Not found", { status: 404 }); ``` -`Layer.mergeAll` unions multiple layers into one — no order -required — and `Effect.provide` satisfies the binding requirements -declared by `PutObject` and `GetObject`. +## One binding per operation -## Deploy +Each S3 operation is its own binding, and each binding adds one statement to the role. A runtime that only reads gets `S3.GetObject`. One that also lists gets `S3.ListObjectsV2`: -```sh -bun alchemy deploy +```typescript title="src/api.ts" +const listObjects = yield* AWS.S3.ListObjectsV2(Files); +const page = yield* listObjects({ Prefix: "reports/2026/" }); +const keys = (page.Contents ?? []).map((object) => object.Key); ``` -Alchemy creates the bucket if it doesn't exist, attaches the -generated IAM policy to your Lambda's execution role, and -redeploys the function bundle. +So the role reads like a summary of what the code does with the Bucket. Deleting, copying, tagging and multipart uploads each have a binding of their own, listed in the [Bucket reference](/providers/aws/s3/bucket). + +## Hand out links with presigned URLs -## Verify +A browser can't call S3 with your role's credentials, and you don't want every upload and download to pass through your Function. A **presigned URL** solves both: it's a link, signed by the Function, that allows one operation on one key for a limited time. -```typescript -// test/integ.test.ts -import * as AWS from "alchemy/AWS"; -import * as Test from "alchemy/Test/Bun"; -import { expect } from "bun:test"; -import * as Effect from "effect/Effect"; -import * as HttpBody from "effect/http/HttpBody"; -import * as HttpClient from "effect/http/HttpClient"; -import Stack from "../alchemy.run.ts"; +```typescript title="src/api.ts" +const presignGetObject = yield* AWS.S3.PresignGetObject(Files); +const url = yield* presignGetObject({ key: "reports/2026/q1.pdf", expiresIn: 3600 }); +``` -const { test, beforeAll, deploy } = Test.make({ - providers: AWS.providers(), - state: AWS.state(), -}); +Anyone holding the link can download that object for the next hour, straight from S3. `S3.PresignPutObject` does the same for uploads. Signing makes no network call, but the link can only do what the signer may do, so the binding grants the role the matching permission. -const stack = beforeAll(deploy(Stack)); +See [R2 presigned URLs](/cloudflare/data/r2-presigned-urls) for the same pattern on Cloudflare. -test( - "S3 round-trip", - Effect.gen(function* () { - const { url } = yield* stack; +## React to new objects - const put = yield* HttpClient.put(`${url}/hello.txt`, { - body: HttpBody.text("world"), - }); - expect(put.status).toBe(204); +A Bucket can tell a Function every time an object is created or deleted. Subscribe from the Function's Construction phase: - const get = yield* HttpClient.get(`${url}/hello.txt`); - expect(yield* get.text).toBe("world"); - }), +```typescript title="src/thumbnails.ts" +const files = yield* Files; +yield* AWS.S3.consumeBucketEvents(files, { events: ["s3:ObjectCreated:*"] }, (stream) => + stream.pipe(Stream.runForEach((event) => Console.log(`new object: ${event.key}`))), ); ``` -```sh -bun test test/integ.test.ts +Deploy adds a notification to the Bucket and permission for S3 to invoke the Function. See [S3 events](/aws/messaging/s3-events). + +## Serve files to the public + +Keep the Bucket private even when its files are public. Put CloudFront in front of it instead: the distribution reads from the Bucket, caches near your users and serves your domain over HTTPS. The Website resources set this up for you: + +```typescript title="alchemy.run.ts" +const site = yield* AWS.Website.StaticSite("Site", { path: "./dist" }); ``` -You now have a Lambda that owns a bucket, with no IAM JSON in -sight. +See [Websites](/aws/frontend/websites). + +## Delete a Bucket -## Where next +S3 won't delete a Bucket that still has objects in it, so destroying a Stack with a full Bucket fails. That protects your data from an accidental destroy. -- [React to S3 events](/aws/messaging/s3-events) — notify the same - function whenever a new object lands in the bucket, wired - through the same binding pipeline. -- [DynamoDB](/aws/data/dynamodb) — structured records you can look up - by key, alongside the blobs. -- [`Bucket` reference](/providers/aws/s3/bucket) — every prop - and attribute. +For a Bucket whose contents you can lose, like a cache or a preview stage's uploads, set `forceDestroy`, and destroy empties it first: + +```typescript title="src/files.ts" +export const Files = AWS.S3.Bucket("Files", { forceDestroy: true }); +``` diff --git a/.agents/skills/alchemy/references/aws/email/receiving.md b/.agents/skills/alchemy/references/aws/email/receiving.md index 3460456f..0c86670d 100644 --- a/.agents/skills/alchemy/references/aws/email/receiving.md +++ b/.agents/skills/alchemy/references/aws/email/receiving.md @@ -1,34 +1,36 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Email receiving > Receive inbound email with SES — rule sets and rules that store mail in S3, fan out to SNS, invoke a Lambda, or bounce it, plus IP filters and the active rule set pointer. -**SES email receiving** turns a domain you've verified into an -inbound mail endpoint. Mail arriving at any address on the domain -is matched against an ordered list of **receipt rules**, and each -rule runs a list of **actions**: store the raw message in S3, -publish a notification to SNS, invoke a Lambda, bounce it back to -the sender, add a header, or stop processing. - -The receiving primitives: - -- A **[`ReceiptRuleSet`](/providers/aws/ses/receiptruleset)** is - the ordered container for rules. An account can hold many, but - only one is active at a time. -- A **[`ReceiptRule`](/providers/aws/ses/receiptrule)** matches - inbound mail by recipient and applies an ordered list of - actions. -- The - **[`ActiveReceiptRuleSet`](/providers/aws/ses/activereceiptruleset)** - is the single rule set SES actually evaluates — an account - singleton pointer. -- A **[`ReceiptFilter`](/providers/aws/ses/receiptfilter)** - allows or blocks inbound mail by source IP, before rules run. -- **[`SendBounce`](/providers/aws/ses/sendbounce)** is a runtime - binding for bouncing a received message from inside a Lambda. +SES can receive mail as well as send it. Point your domain's MX record at SES, and every message sent to an address on the domain arrives at AWS, where your **receipt rules** decide what happens to it: store it in S3, notify an SNS Topic, invoke a Function, or bounce it. + +## Rule sets, rules and actions + +Rules live in a **rule set**. An account can hold many rule sets, but SES evaluates only the **active** one. Within it, rules run in order. Each rule matches messages by recipient and runs its **actions** in order: store the raw message in a Bucket, publish to a Topic, invoke a Function, bounce, add a header, or stop. + + + +**Receipt filters** run before any rule, allowing or blocking mail by the sending server's IP address. :::note Email receiving is only available in a subset of AWS regions — @@ -45,8 +47,8 @@ The snippets below run inside a Stack's `Effect.gen` body: ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; -import * as SES from "alchemy/AWS/SES"; +import * as AWS from "@alchemy.run/aws"; +import * as SES from "@alchemy.run/aws/SES"; import * as Effect from "effect/Effect"; export default Alchemy.Stack( diff --git a/.agents/skills/alchemy/references/aws/email/sending.md b/.agents/skills/alchemy/references/aws/email/sending.md index 86851d1e..5b13432f 100644 --- a/.agents/skills/alchemy/references/aws/email/sending.md +++ b/.agents/skills/alchemy/references/aws/email/sending.md @@ -1,42 +1,18 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Sending & managing email > Send email with SES — verify identities, send from a Lambda with the SendEmail binding, manage contact lists, tenants, dedicated IP pools, account settings, and deliverability insights. -**SES sending** starts with a verified **identity** — a domain or -an email address you own — and a runtime **binding** that lets a -Lambda send through it. Around that core, SES v2 adds the pieces -you need to run email at scale: authorization policies, contact -lists, dedicated IP pools, per-tenant isolation, multi-region -endpoints, account-wide settings, and deliverability insights. - -The sending surface: - -- An **[`EmailIdentity`](/providers/aws/ses/emailidentity)** is a - verified domain or address, and - **[`SendEmail`](/providers/aws/ses/sendemail)** is the runtime - binding that sends through it. -- An - **[`EmailIdentityPolicy`](/providers/aws/ses/emailidentitypolicy)** - authorizes other accounts to send as your identity. -- A **[`ContactList`](/providers/aws/ses/contactlist)** and its - **[`Contact`](/providers/aws/ses/contact)** entries model a - managed audience with subscription topics. -- A - **[`DedicatedIpPool`](/providers/aws/ses/dedicatedippool)** - isolates sending reputation onto dedicated IPs. -- A **[`Tenant`](/providers/aws/ses/tenant)** groups identities, - configuration sets, and templates for a customer or business - unit. -- A - **[`MultiRegionEndpoint`](/providers/aws/ses/multiregionendpoint)** - splits sending across regions. -- **[`AccountSettings`](/providers/aws/ses/accountsettings)** - manages account-wide sending status, the suppression list, and - Virtual Deliverability Manager. +SES sends email for you. Before it sends from an address, you prove you own it: the address, or the whole domain, becomes a verified **identity**. A runtime then sends through that identity with a binding, and SES handles delivery, bounces and complaints. + +## Identities and reputation + +An identity is a domain like `mail.example.com` or a single address. A domain identity is verified with **DKIM**: SES gives you three keys to publish as DNS records, and signs every message with them, so receiving servers can check the mail really came from your domain. + +Every message you send builds or spends your **reputation**: how often your mail bounces, is marked as spam, or is opened. Receiving servers use it to decide whether your mail reaches the inbox. Everything after the first send, from contact lists to dedicated IPs, exists to protect it. :::note New SES accounts start in the **sandbox**: you can only send to @@ -53,8 +29,8 @@ body: ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; -import * as SES from "alchemy/AWS/SES"; +import * as AWS from "@alchemy.run/aws"; +import * as SES from "@alchemy.run/aws/SES"; import * as Effect from "effect/Effect"; export default Alchemy.Stack( @@ -95,8 +71,8 @@ returns a callable. Provide its implementation with ```typescript // src/mailer.ts -import * as AWS from "alchemy/AWS"; -import * as SES from "alchemy/AWS/SES"; +import * as AWS from "@alchemy.run/aws"; +import * as SES from "@alchemy.run/aws/SES"; import * as Effect from "effect/Effect"; import * as HttpServerResponse from "effect/http/HttpServerResponse"; diff --git a/.agents/skills/alchemy/references/aws/frontend/astro.md b/.agents/skills/alchemy/references/aws/frontend/astro.md index 398c2d39..0aa6cecb 100644 --- a/.agents/skills/alchemy/references/aws/frontend/astro.md +++ b/.agents/skills/alchemy/references/aws/frontend/astro.md @@ -1,15 +1,16 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Astro -> Deploy an Astro app to AWS with AWS.Website.Astro — SSR on a streaming Lambda Function URL, static output on S3 + CloudFront, and Astro's own dev server under alchemy dev. +> Deploy an Astro app to AWS with AWS.Website.Astro — SSR on a Lambda Web Function, static output on S3 + CloudFront, and Astro's own dev server under alchemy dev. `AWS.Website.Astro` deploys an [Astro](https://astro.build) project -to AWS. It runs Astro's programmatic build with a wrangler-free AWS -Lambda adapter: server-rendered pages stream from a Lambda Function -URL, prerendered pages and client assets are served from a private S3 +to AWS. It runs Astro's programmatic build with a wrangler-free Node +adapter: server-rendered pages stream from a +[Lambda Web Function](/aws/compute/web-functions), prerendered pages +and client assets are served from a private S3 bucket through CloudFront, routed at the edge. Your `astro.config.*` loads natively — there is no adapter to install into it and no CloudFormation to write. @@ -18,19 +19,17 @@ CloudFormation to write. The build integration is not bundled with alchemy. Install `@alchemy.run/frontend-frameworks`; the resource loads its `/astro` -and `/astro/aws` exports from your project at deploy time. It is only +and `/astro/node` exports from your project at deploy time. It is only used at build time, so a dev dependency is enough: -```sh -bun add -d @alchemy.run/frontend-frameworks -``` + ## Configure Astro Your `astro.config.*` file loads natively — integrations, Vite plugins, and any other non-serializable options work exactly as they do outside Alchemy. Alchemy merges a programmatic config *over* it: -the AWS Lambda adapter is injected for you (don't declare an +Alchemy's Node adapter is injected for you (don't declare an `adapter` in your config — that fails the build with an actionable error), and options passed via the `astro` prop override the file's — see [Astro configuration](#astro-configuration) below for the @@ -43,7 +42,7 @@ Stack): ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.Astro("Website"); ``` @@ -93,13 +92,13 @@ export const Website = AWS.Website.Astro("Website", { }); ``` -The values are set on the Lambda at deploy time and injected into the +The values are set on the server at deploy time and injected into the dev server's process environment under `alchemy dev`, so server code reads the same values in both modes. ## Read the environment in server code -The Astro server runs in a plain Node Lambda, so server-rendered +The Astro server is a plain Node server, so server-rendered pages and endpoints read the environment from `process.env`: ```astro @@ -183,14 +182,29 @@ export const Website = AWS.Website.Astro("Website", { Two options are managed for you regardless of the config file: -- `adapter` — Alchemy injects its wrangler-free AWS Lambda adapter. +- `adapter` — Alchemy injects its wrangler-free Node adapter. Declaring an adapter in `astro.config.*` fails the build with an actionable error. - `output` — Alchemy defaults it to `"server"` (superseding a - file-level `output`), so pages render on demand in the Lambda. + file-level `output`), so pages render on demand on the server. Opt into a fully prerendered site with `astro: { output: "static" }` on the resource. +## Run on a Lambda Function + +Web Functions run in a subset of Regions. Elsewhere, set +`server: "function"`: the app builds with the `/astro/aws` deploy target +and runs on a Lambda Function behind a streaming Function URL, tuned with +`memorySize`, `architecture`, and `runtime`: + +```diff lang="typescript" +// alchemy.run.ts +export const Website = AWS.Website.Astro("Website", { ++ server: "function", ++ memorySize: 2048, +}); +``` + ## Local dev `alchemy dev` runs Astro's own dev server (native HMR) instead of diff --git a/.agents/skills/alchemy/references/aws/frontend/foldkit.md b/.agents/skills/alchemy/references/aws/frontend/foldkit.md index 5d6442a3..8c5d612a 100644 --- a/.agents/skills/alchemy/references/aws/frontend/foldkit.md +++ b/.agents/skills/alchemy/references/aws/frontend/foldkit.md @@ -1,33 +1,24 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Foldkit -> Deploy a Foldkit app to AWS with AWS.Website.Foldkit — the client build on S3 + CloudFront, SPA deep links by default, and Foldkit's own Vite dev server under alchemy dev. +> Deploy Foldkit SPA, SSR, SSG, and hybrid applications to AWS with native local development. -[Foldkit](https://foldkit.dev) is an Elm-architecture frontend framework -built on Effect. Its apps are client-only Vite projects — the Foldkit -Vite plugin only adds HMR and devtools wiring — so -`AWS.Website.Foldkit` deploys one with a single declaration: the client -build lands in a private S3 bucket and serves through CloudFront, routed -at the edge. There is no server function, no build command, and no -CloudFormation to write. - -`Foldkit` is [`AWS.Website.Vite`](/aws/frontend/vite) with -Foldkit's defaults applied: client-side routing is assumed, so deep -links fall back to the app shell without you configuring anything. +`AWS.Website.Foldkit` deploys a [Foldkit](https://foldkit.dev) app to +AWS. It supports browser-only SPAs, server-side rendering (SSR), static site +generation (SSG), and hybrid rendering. Foldkit's Vite plugin generates the +handler and assets; Alchemy packages them for deployment. ## Install The build integration is not bundled with alchemy. Install -`@alchemy.run/frontend-frameworks`; the resource loads its `/vite` and -`/vite/aws` exports from your project at deploy time. It is only used at +`@alchemy.run/frontend-frameworks`; the resource loads its `/foldkit` and +`/foldkit/aws` exports from your project at deploy time. It is only used at build time, so a dev dependency is enough: -```sh -bun add -d @alchemy.run/frontend-frameworks -``` + ## Configure Vite @@ -49,12 +40,89 @@ export default defineConfig({ Alchemy runs Vite programmatically on the project root, so the Foldkit plugin and the rest of your setup are preserved as-is. -:::note[Pinned Effect versions] -Foldkit pins its `effect` peer dependency to an exact version. Alchemy -runs your app's own Vite build with your app's own `node_modules`, so -that pin is between Foldkit and your package manager — Alchemy imposes -no Effect version on your frontend. -::: +## Server rendering and prerendering + +Configure rendering in the application's `foldkit(...)` plugin. This example +uses Foldkit 0.167.0, `@foldkit/vite-plugin` 0.27.0 and compatible Effect +dependencies: + +```typescript +// vite.config.ts +import { foldkit } from "@foldkit/vite-plugin"; +import { defineConfig } from "vite"; + +export default defineConfig({ + plugins: [ + foldkit({ + ssr: { + serverEntry: "/src/entry.server.ts", + clientEntry: "/src/entry.ts", + build: true, + }, + }), + ], +}); +``` + +The server entry exports `renderPage` and `renderDocument`. Import stylesheets +from the client entry and use `Runtime.hydrate` to start the browser application. +Remove the source `index.html` for this build: Foldkit generates the complete +HTML document, including the client script, stylesheets and module preload links. + +```typescript +// src/entry.server.ts +import { Server } from "foldkit/experimental"; + +export const renderDocument = Server.renderDocument; +``` + +Keep your application's `renderPage` export alongside the document renderer. +Foldkit currently exposes its server rendering API through `foldkit/experimental`; +see its [server rendering guide](https://foldkit.dev/core/server-rendering) for +the application and hydration contract. + +For static site generation (SSG), change `build` to `{ prerender: true }` and +export the URLs to generate from the server entry: + +```typescript +// src/entry.server.ts +export const prerenderPaths = ["/", "/about"]; +``` + +SSG renders those URLs during the build. SSR renders a page when its request +arrives. A hybrid application prerenders some URLs and renders others on request. +The same `renderPage` and `renderDocument` exports serve both delivery policies. + +AWS chooses its deployment resources before building. Keep the default for a +browser-only SPA; select `output: "server"` for request-time rendering: + +```typescript +// alchemy.run.ts +export const Website = AWS.Website.Foldkit("Website", { + output: "server", +}); +``` + +CloudFront serves assets and prerendered pages from S3. Requests that match no +file, and methods other than GET or HEAD, reach the server: a Lambda Web +Function by default, or a Lambda Function with `server: "function"`. The +application owns its response status and headers through `renderPage`. + +For static-only SSG, deploy the prerendered client output without a server: + +```typescript +// alchemy.run.ts +export const Website = AWS.Website.Foldkit("Website", { + output: "static", + errorPage: "404.html", +}); +``` + +Supply `public/404.html` for this example. URLs that were not generated return +404; browser interaction still works through hydration. `output: "server"` +retains the handler even when all known pages were prerendered. A server build +with no `output` choice fails rather than discarding its handler. +`spa` and `errorPage` apply only to assets-only deployments. ## Declare the Website @@ -63,7 +131,7 @@ Stack): ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.Foldkit("Website"); ``` @@ -102,14 +170,12 @@ One declaration expands into the whole stack — an S3 bucket, the asset upload, a CloudFront KeyValueStore holding the file manifest, a viewer-request CloudFront Function, and the distribution itself. -```sh -bun alchemy deploy -``` + ## Deep links -A Foldkit app that uses URL routing (`Runtime.makeApplication` with -`route`, `onUrlRequest`, and `onUrlChange`) resolves routes on the +A browser-only Foldkit app that uses URL routing (`Runtime.makeApplication` with +`routing`, `onUrlRequest`, and `onUrlChange`) resolves routes on the client, so a deep link like `/counter/42` arrives at the edge as a request for a file that does not exist. @@ -129,40 +195,51 @@ export const Website = AWS.Website.Foldkit("Website", { ## Add environment variables -A Foldkit app has no server, so anything it needs is baked into the -bundle at build time. Vite inlines `VITE_`-prefixed variables from the -environment the build runs in — a `.env` file in the project root, or -the shell that runs `alchemy deploy`: +Set server environment variables through `env` when deploying a server build: -```sh -# .env -VITE_API_URL=https://api.example.com +```typescript +// alchemy.run.ts +export const Website = AWS.Website.Foldkit("Website", { + output: "server", + env: { API_BASE: "https://api.example.com" }, +}); ``` -Type it for your Foldkit code with Vite's standard `ImportMetaEnv` -augmentation: +Server code reads these values from `process.env`. Alchemy applies them to the +native dev server under `alchemy dev` and to the server on deploy. + +An Output from another resource can be passed inside the Stack generator: ```typescript -// src/vite-env.d.ts -/// +Effect.gen(function* () { + const api = yield* Api; + const site = yield* AWS.Website.Foldkit("Website", { + output: "server", + env: { API_BASE: api.url }, + }); + return { url: site.url }; +}); +``` -interface ImportMetaEnv { - readonly VITE_API_URL: string; -} +## Read the environment in client code + +Vite inlines `VITE_*` values as `import.meta.env.VITE_*` during the build. +Set browser configuration in the app's `.env` file or the deployment environment: + +```sh +# .env +VITE_API_URL=https://api.example.com ``` -Client code reads it as `import.meta.env.VITE_API_URL`, e.g. from a -`Command` that fetches your API. +```typescript +const apiUrl = import.meta.env.VITE_API_URL; +``` -A value produced by another resource in the Stack (a Function URL, a -table name) is not known when this build runs, and the resource takes no -`env` prop. Either serve it from an -[API](/aws/apis/effect-http-api) the app fetches at runtime, or deploy -with [`AWS.Website.StaticSite`](/aws/frontend/static-site) instead — -it runs the build as a command and passes `environment` to it, so an -Output can be inlined at build time. +Values forwarded through `env` are also available to the build. A `VITE_*` key +becomes public browser configuration; keep credentials in unprefixed server +variables. Values serialized into Foldkit Flags also reach the browser. -## Deploy-time overrides +## Build configuration Vite configuration — the Foldkit plugin included — lives in your project's own `vite.config.*`. The `vite` bag is for deploy-time @@ -172,23 +249,20 @@ deployment (config files can't consume alchemy `Output`s): ```typescript export const Website = AWS.Website.Foldkit("Docs", { vite: { - base: "/docs/", outDir: "build", }, }); ``` -`base` is the public path the site deploys under (it also applies to -the dev server under `alchemy dev`); `outDir` is the build output -directory, relative to `rootDir`. Leave the bag unset and the resolved -values from your `vite.config.*` are used — Vite's own `outDir` -default is `dist`. `config` selects an alternate config file, relative -to `rootDir`. +`outDir` is relative to `rootDir`. For server builds, Alchemy places client and +server outputs under `client/` and `server/` in this directory. Without an +override, the app's resolved output directories are used. `config` selects an +alternate Vite configuration file relative to `rootDir`. ## Local dev -`alchemy dev` runs the app's own Vite dev server, so Foldkit's HMR with -state preservation and its devtools wiring work unchanged. `site.url` is +`alchemy dev` runs the app's own Vite dev server, so Foldkit's +state-preserving live reload and its devtools wiring work unchanged. `site.url` is the local address and no AWS resources are created. Wrap the site in `Alchemy.remote()` to deploy the real infrastructure even during dev. @@ -229,11 +303,3 @@ Effect.gen(function* () { return { url: site.url }; }); ``` - -:::note[No edge code] -Cloudflare's `Foldkit` accepts a `main` entry that runs a Worker in -front of the assets. AWS has no equivalent: this composite is -assets-only and never creates a server function. Put request-time logic -behind its own [Lambda API](/aws/apis/effect-http-api) and fetch it from -the client. -::: diff --git a/.agents/skills/alchemy/references/aws/frontend/full-stack-tanstack-rpc-drizzle.md b/.agents/skills/alchemy/references/aws/frontend/full-stack-tanstack-rpc-drizzle.md index 99d79b19..337e3ac5 100644 --- a/.agents/skills/alchemy/references/aws/frontend/full-stack-tanstack-rpc-drizzle.md +++ b/.agents/skills/alchemy/references/aws/frontend/full-stack-tanstack-rpc-drizzle.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Full-stack TanStack Start + RPC + Drizzle @@ -30,9 +30,7 @@ The browser calls a same-origin `/rpc` route; the frontend Lambda forwards reque ## Install -```sh -bun add @distilled.cloud/aws @effect/atom-react @effect/sql-pg drizzle-orm effect pg\nbun add -d @alchemy.run/frontend-frameworks -``` + ## 1. The shared RPC contract @@ -82,7 +80,7 @@ Copy `database.ts`, `bootstrap.ts`, and `client.ts` from the [DSQL example](http Copy the example's [`schema.ts`](https://github.com/alchemy-run/alchemy/blob/main/examples/aws-dsql-drizzle/src/schema.ts) into `src/backend/`. It targets `app.todos` with application-generated UUIDs, matching the bootstrap and role grants. Check [DSQL compatibility](/aws/data/drizzle-dsql#define-the-table) before extending it. :::note -`AWS.DSQL.Cluster` has no `migrations` prop. The Action in step 5 bootstraps the database without an HTTP `/setup` route; it is not a versioned migrator. Whenever the schema changes, explicitly generate migration files using the [DSQL migration workflow](/aws/data/drizzle-dsql#evolve-the-schema), with schema path `./src/backend/schema.ts`. Stage the schema, config, SQL, and snapshots, review with `git diff --cached`, and commit before release. The migration step consumes committed SQL, not SQL generated during deployment. +The Action in step 5 bootstraps the database without an HTTP `/setup` route; it is not a versioned migrator. To evolve the schema, generate migration files with the [DSQL migration workflow](/aws/data/drizzle-dsql#evolve-the-schema) (schema path `./src/backend/schema.ts`) and pass the directory to the cluster's `migrations` prop, which applies them on deploy. ::: ## 4. The backend RPC Lambda @@ -91,7 +89,7 @@ Copy the example's [`schema.ts`](https://github.com/alchemy-run/alchemy/blob/mai ```typescript // src/backend/api.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import { eq } from "drizzle-orm"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -105,7 +103,6 @@ export default class Backend extends AWS.Lambda.Function()( { main: import.meta.url, functionUrl: true, - build: { install: ["pg"] }, }, Effect.gen(function* () { const db = yield* connectDatabase; @@ -182,7 +179,7 @@ export default class Backend extends AWS.Lambda.Function()( ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; import Backend from "./src/backend/api.ts"; import { BootstrapDatabase } from "./src/backend/bootstrap.ts"; @@ -378,17 +375,13 @@ function TodoList() { [AWS setup](/aws/setup) -```sh -bun alchemy deploy -``` + Open `websiteUrl` to create, toggle, and delete todos. ## Local dev -```sh -bun alchemy dev -``` + The frontend runs locally; the backend Lambda and DSQL remain on AWS and incur charges. diff --git a/.agents/skills/alchemy/references/aws/frontend/nextjs.md b/.agents/skills/alchemy/references/aws/frontend/nextjs.md index 127457d8..69b71582 100644 --- a/.agents/skills/alchemy/references/aws/frontend/nextjs.md +++ b/.agents/skills/alchemy/references/aws/frontend/nextjs.md @@ -1,57 +1,38 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Next.js -> Deploy a Next.js app to AWS with AWS.Website.Nextjs — the OpenNext serverless topology with streaming SSR, image optimization, and ISR wiring, plus next dev under alchemy dev. +> Deploy a Next.js app to AWS with AWS.Website.Nextjs — Next's own server on a Lambda Web Function with a shared S3 cache, S3 assets behind CloudFront, and next dev under alchemy dev. `AWS.Website.Nextjs` deploys a [Next.js](https://nextjs.org) app to -AWS using the [OpenNext](https://opennext.js.org/aws) serverless -topology: - -- the Next server on a Lambda Function URL with response streaming -- static assets and the prerender cache in S3, served through - CloudFront's edge router -- a dedicated image-optimization Lambda behind `/_next/image` -- ISR wiring: an SQS revalidation queue with a consumer Lambda and a - DynamoDB tag-cache table +AWS. Next runs as its own standalone server on a +[Lambda Web Function](/aws/compute/web-functions), the way it runs under +`next start`: each environment serves many requests, responses stream, and +ISR revalidation and `/_next/image` happen in the server. Static assets are +served from S3 through CloudFront's edge router, and an S3 bucket holds the +cache every environment shares. App Router and Pages Router both work — server components, API routes, middleware, server actions, dynamic segments, streaming SSR, -and `getServerSideProps` pages all run in the Lambda. +and `getServerSideProps` pages all run on the server. ## Install The build integration is not bundled with alchemy. Install -`@alchemy.run/frontend-frameworks` and its OpenNext peer; the -resource loads the package's `/nextjs/aws` export from your project -at deploy time. They are only used at build time, so dev dependencies -are enough: - -```sh -bun add -d @alchemy.run/frontend-frameworks @opennextjs/aws -``` +`@alchemy.run/frontend-frameworks`; the resource loads the package's +`/nextjs/aws` export from your project at deploy time. It is only used at +build time, so a dev dependency is enough: -## Configure OpenNext + -Your `next.config.*` is loaded and honored as-is — the build runs a -real `next build`, and Alchemy never rewrites the file. An -`open-next.config.ts` is optional: when the project has none, a -minimal default with the streaming server wrapper is generated for -you. Keep your own file next to `next.config.*` to customize the -OpenNext build: +## Configure Next.js -```typescript -// open-next.config.ts -export default { - default: { - override: { - wrapper: "aws-lambda-streaming", - }, - }, -}; -``` +Your `next.config.*` is loaded and honored as-is: the build runs a real +`next build`, and Alchemy never rewrites the file. It builds Next's +standalone output for you, so there's no `output` to set; an `output` +other than `"standalone"` fails the build. ## Declare the Website @@ -60,7 +41,7 @@ Stack): ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.Nextjs("Website"); ``` @@ -88,7 +69,7 @@ export default Alchemy.Stack( ``` Statically-rendered pages are served from the S3 prerender cache; -dynamic pages and route handlers stream from the server Lambda; +dynamic pages and route handlers stream from the server; `next/image` requests are handled by the dedicated optimizer. See @@ -110,13 +91,13 @@ export const Website = AWS.Website.Nextjs("Website", { }); ``` -The values are set on the server Lambda at deploy time and injected +The values are set on the server at deploy time and injected into the dev server's process environment under `alchemy dev`, so server code reads the same values in both modes. ## Read the environment in server code -The OpenNext server runs in a plain Node Lambda, so route handlers, +Next's server is a plain Node server, so route handlers, server components, and server actions read the environment from `process.env`: @@ -129,27 +110,50 @@ export function GET() { ## ISR -Incremental Static Regeneration works out of the box — the resource -provisions the OpenNext cache infrastructure for you: +Incremental Static Regeneration works out of the box. Alchemy configures +Next with an S3 `cacheHandler`, so ISR pages, route handlers, the fetch +cache and optimized images live in one bucket that every environment +shares. `revalidatePath` and `revalidateTag` in one environment reach all +of them, and time-based `revalidate` windows regenerate pages in the +background, in the server, as they do under `next start`. -- the ISR/fetch cache lives in a dedicated S3 bucket -- `revalidatePath` / `revalidateTag` purge entries through the - DynamoDB tag-cache table -- time-based `revalidate` windows regenerate pages in the background - through the SQS FIFO revalidation queue and its consumer Lambda +```typescript +// app/api/revalidate/route.ts +import { revalidatePath } from "next/cache"; -There is no cache configuration to write — the resource wires -OpenNext's standard cache environment (`CACHE_BUCKET_NAME`, -`CACHE_DYNAMO_TABLE`, `REVALIDATION_QUEUE_URL`) onto the server -Lambda automatically, so OpenNext's default S3 / DynamoDB / SQS -overrides just work. +export async function POST() { + revalidatePath("/blog"); + return Response.json({ revalidated: true }); +} +``` -## Local dev +`"use cache"` entries stay in each environment's memory. -```sh -bun alchemy dev +## Run on a Lambda Function + +For servers that need more than 2 GB of memory or x86_64, or Regions +without Web Functions, set `server: "function"`. The app then builds with +[OpenNext](https://opennext.js.org/aws): the server and the image optimizer +run on Lambda Functions behind Function URLs, and ISR revalidation runs +through an SQS queue, a consumer Lambda and a DynamoDB tag table. Install +`@opennextjs/aws` as a dev dependency, and tune the server with +`memorySize`, `architecture`, and `runtime`: + +```diff lang="typescript" +// alchemy.run.ts +export const Website = AWS.Website.Nextjs("Website", { ++ server: "function", ++ memorySize: 2048, +}); ``` +An `open-next.config.ts` is optional; without one Alchemy generates a +default with the `aws-lambda-streaming` wrapper. + +## Local dev + + + `alchemy dev` runs `next dev` (native HMR, Turbopack) instead of deploying; `site.url` is the local address and no AWS resources are created. Wrap the site in `Alchemy.remote()` to deploy the real diff --git a/.agents/skills/alchemy/references/aws/frontend/nuxt.md b/.agents/skills/alchemy/references/aws/frontend/nuxt.md index 37ef900e..5eed8677 100644 --- a/.agents/skills/alchemy/references/aws/frontend/nuxt.md +++ b/.agents/skills/alchemy/references/aws/frontend/nuxt.md @@ -1,30 +1,29 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Nuxt -> Deploy a Nuxt app to AWS with AWS.Website.Nuxt — nitro's aws-lambda preset on a streaming Lambda Function URL, S3 assets behind CloudFront, and Nuxt's own dev server under alchemy dev. +> Deploy a Nuxt app to AWS with AWS.Website.Nuxt — the nitro server on a Lambda Web Function, S3 assets behind CloudFront, and Nuxt's own dev server under alchemy dev. `AWS.Website.Nuxt` deploys a [Nuxt](https://nuxt.com) app to AWS. It builds the app through your project's own `@nuxt/kit` with nitro's -`aws-lambda` preset: the nitro server runs on a Lambda Function URL -with response streaming, and client assets plus prerendered pages are -served from a private S3 bucket through CloudFront. A CloudFront -Function routes each request at the edge — uploaded files go to S3, -everything else streams from the Lambda. There is no `nitro.preset` +`node` preset: the nitro server runs on a +[Lambda Web Function](/aws/compute/web-functions) and streams its +responses, and client assets plus prerendered pages are served from a +private S3 bucket through CloudFront. A CloudFront Function routes each +request at the edge — uploaded files go to S3, everything else streams +from the server. There is no `nitro.preset` to edit and no build command to run. ## Install The build integration is not bundled with alchemy. Install `@alchemy.run/frontend-frameworks`; the resource loads its `/nuxt` and -`/nuxt/aws` exports from your project at deploy time. It is only used +`/nuxt/node` exports from your project at deploy time. It is only used at build time, so a dev dependency is enough: -```sh -bun add -d @alchemy.run/frontend-frameworks -``` + ## Configure Nuxt @@ -41,9 +40,9 @@ export default defineNuxtConfig({ }); ``` -Don't set `nitro.preset` — the AWS deploy target owns the preset -(`aws-lambda` with streaming enabled), and a foreign preset is a hard -error. +Don't set `nitro.preset` — the deploy target owns the preset (`node`, +or `aws-lambda` with streaming enabled for `server: "function"`), and a +foreign preset is a hard error. ## Deploy-time overrides @@ -74,7 +73,7 @@ Stack): ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.Nuxt("Website"); ``` @@ -113,21 +112,21 @@ values, or outputs from other resources in the Stack: ```diff lang="typescript" // alchemy.run.ts export const Website = AWS.Website.Nuxt("Website", { -+ memorySize: 2048, + env: { + NUXT_PUBLIC_API_BASE: api.url, + }, }); ``` -`env` values are set on the Lambda on deploy and injected into +`env` values are set on the server on deploy and injected into the dev server's process environment under `alchemy dev`, so server code reads the same values in both modes. Sibling props tune the -Lambda itself (`memorySize`, `timeout`, `architecture`, `runtime`). +server itself (`timeout`, `maxConcurrencyPerEnvironment`, +`maxEnvironments`). ## Read the environment in server code -On AWS the nitro server runs in a plain Node Lambda, so server routes +On AWS the nitro server is a plain Node server, so server routes and SSR read the environment from `process.env` — or, the more idiomatic Nuxt way, through `runtimeConfig` overridden by `NUXT_`-prefixed environment variables: @@ -156,17 +155,31 @@ export default defineNuxtConfig({ ``` Nitro's `isr` route rule is implemented only by the Vercel and -Netlify presets. On AWS Lambda it is silently ignored at build time, -and the route renders on demand in the Lambda like any other SSR +Netlify presets. On AWS it is silently ignored at build time, +and the route renders on demand on the server like any other SSR route. Use `prerender` for build-time static routes, or `cache` route rules for runtime caching. -## Local dev +## Run on a Lambda Function -```sh -bun alchemy dev +Web Functions run in a subset of Regions. Elsewhere, set +`server: "function"`: the app builds with nitro's `aws-lambda` preset +(from the `/nuxt/aws` export) and runs on a Lambda Function behind a +streaming Function URL, tuned with `memorySize`, `architecture`, and +`runtime`: + +```diff lang="typescript" +// alchemy.run.ts +export const Website = AWS.Website.Nuxt("Website", { ++ server: "function", ++ memorySize: 2048, +}); ``` +## Local dev + + + `alchemy dev` runs Nuxt's own dev server (nitro dev, full HMR) instead of deploying anything; `site.url` is the dev server's `http://localhost:` address and no AWS resources are created. diff --git a/.agents/skills/alchemy/references/aws/frontend/octane.md b/.agents/skills/alchemy/references/aws/frontend/octane.md index d88d4893..72619c15 100644 --- a/.agents/skills/alchemy/references/aws/frontend/octane.md +++ b/.agents/skills/alchemy/references/aws/frontend/octane.md @@ -1,30 +1,29 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Octane -> Deploy an OctaneJS app to AWS with AWS.Website.Octane — SSR on a streaming Lambda Function URL, assets on S3 + CloudFront, and Octane's own Vite dev server under alchemy dev. +> Deploy an OctaneJS app to AWS with AWS.Website.Octane — SSR on a Lambda Web Function, assets on S3 + CloudFront, and Octane's own Vite dev server under alchemy dev. `AWS.Website.Octane` deploys an [OctaneJS](https://octanejs.dev) fullstack app to AWS. Octane wraps Vite, so the resource is deliberately thin: it runs your project's own `vite build` — Octane's plugin builds the client bundle and the self-contained SSR server -bundle, and the AWS deploy target's finishing pass wraps its fetch -handler as a streaming Lambda handler. The server deploys on a Lambda -Function URL; `dist/client` is served from a private S3 bucket +bundle, and the deploy target's finishing pass wraps its fetch handler +in a Node server. The server deploys on a +[Lambda Web Function](/aws/compute/web-functions); `dist/client` is +served from a private S3 bucket through CloudFront. No CloudFormation, no build command to run. ## Install The build integration is not bundled with alchemy. Install `@alchemy.run/frontend-frameworks`; the resource loads the package's -`/octane` and `/octane/aws` exports from your project at deploy time. +`/octane` and `/octane/node` exports from your project at deploy time. It is only used at build time, so a dev dependency is enough: -```sh -bun add -d @alchemy.run/frontend-frameworks -``` + ## Configure Octane @@ -43,7 +42,7 @@ export default defineConfig({ ``` `AWS.Website.Octane` selects hosting and automatically wraps Octane's -default native Node output as a streaming Lambda handler. The legacy AWS +default native Node output in a Node server. The legacy AWS marker adapter remains optional for existing projects. ## Declare the Website @@ -53,7 +52,7 @@ Stack): ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.Octane("Website"); ``` @@ -95,13 +94,13 @@ export const Website = AWS.Website.Octane("Website", { }); ``` -The values are set on the Lambda at deploy time and injected into the +The values are set on the server at deploy time and injected into the dev server's process environment under `alchemy dev`, so server code reads the same values in both modes. ## Read the environment in server code -Octane's server runs in a plain Node Lambda, so middleware and +Octane's server is a plain Node server, so middleware and `ServerRoute` handlers read the environment from `process.env`: ```typescript @@ -120,14 +119,27 @@ new ServerRoute({ Octane's intended setup is asset-first with SSR on miss: exact files in `dist/client` serve from S3 via the CloudFront edge router without invoking the server, and every miss streams from Octane SSR on the -Lambda. That is the default — there is nothing to configure. +server. That is the default — there is nothing to configure. -## Local dev +## Run on a Lambda Function + +Web Functions run in a subset of Regions. Elsewhere, set +`server: "function"`: the app builds with the `/octane/aws` deploy target +and runs on a Lambda Function behind a streaming Function URL, tuned with +`memorySize`, `architecture`, and `runtime`: -```sh -bun alchemy dev +```diff lang="typescript" +// alchemy.run.ts +export const Website = AWS.Website.Octane("Website", { ++ server: "function", ++ memorySize: 2048, +}); ``` +## Local dev + + + `alchemy dev` runs Octane's own Vite dev server — the plugin's in-process SSR middleware serves rendering, server routes, and RPC with full HMR. `site.url` is the local address and no AWS resources diff --git a/.agents/skills/alchemy/references/aws/frontend/react-router.md b/.agents/skills/alchemy/references/aws/frontend/react-router.md index e4493429..69ee527f 100644 --- a/.agents/skills/alchemy/references/aws/frontend/react-router.md +++ b/.agents/skills/alchemy/references/aws/frontend/react-router.md @@ -1,30 +1,29 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # React Router -> Deploy React Router v7 (framework mode) to AWS with AWS.Website.ReactRouter — SSR on a streaming Lambda Function URL, client assets on S3 + CloudFront, and React Router's own Vite dev server under alchemy dev. +> Deploy React Router v8 (framework mode) to AWS with AWS.Website.ReactRouter — SSR on a Lambda Web Function, client assets on S3 + CloudFront, and React Router's own Vite dev server under alchemy dev. `AWS.Website.ReactRouter` deploys a -[React Router](https://reactrouter.com) v7 app in framework mode to AWS. +[React Router](https://reactrouter.com) v8 app in framework mode to AWS. React Router builds through Vite, so Alchemy runs your project's own -build: the SSR server runs on a Lambda Function URL with response -streaming, and client assets are served from a private S3 bucket through +build: the SSR server runs on a +[Lambda Web Function](/aws/compute/web-functions) and streams its +responses, and client assets are served from a private S3 bucket through CloudFront. A CloudFront Function routes each request at the edge — -uploaded files go to S3, everything else streams from the Lambda. +uploaded files go to S3, everything else streams from the server. ## Install The build integration is not bundled with alchemy. Install `@alchemy.run/frontend-frameworks`; the resource loads its -`/react-router` and `/react-router/aws` exports from your project at +`/react-router` and `/react-router/node` exports from your project at deploy time. It is only used at build time, so a dev dependency is enough: -```sh -bun add -d @alchemy.run/frontend-frameworks -``` + The React Router side is whatever `npx create-react-router@latest` scaffolds — `react-router`, `@react-router/dev`, `@react-router/node`, @@ -50,8 +49,8 @@ export default defineConfig({ `reactRouter()` owns routing, typegen, and both build environments. Alchemy drives the same two passes `react-router build` runs, forces the -SSR bundle to be self-contained, and wraps its fetch handler as a -streaming Lambda handler. +SSR bundle to be self-contained, and serves its fetch handler from a +Node server. :::caution[Remove @cloudflare/vite-plugin if present] The React Router CLI adds `@cloudflare/vite-plugin` when you pick the @@ -79,7 +78,7 @@ Stack): ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.ReactRouter("Website"); ``` @@ -118,7 +117,7 @@ export default Alchemy.Stack( Requests matching a built client asset are served straight from S3; everything else — SSR routes, loaders, actions, resource routes — falls -through to the Lambda. +through to the server. ## How the two build outputs are deployed @@ -128,14 +127,14 @@ different piece of AWS infrastructure: ``` build/ ├── client/ -> uploaded to S3, served through CloudFront -└── server/ -> the Lambda deployment package +└── server/ -> the Web Function deployment package ``` `build/client` holds the hashed browser bundles plus everything you put in `public/`. `build/server/index.js` is a `ServerBuild` manifest, not a request handler, so Alchemy wraps it with `createRequestHandler` during -the build and emits `build/server/lambda.mjs` beside it — that module is -the deployed Lambda entry. +the build and emits `build/server/serve-node.mjs` beside it — that +module is the deployed server entry. If you set Vite's `base`, set React Router's `basename` to the same prefix: the client directory maps onto the site root one-for-one, so the @@ -148,17 +147,17 @@ The server function's environment is configured under `env`: ```diff lang="typescript" // alchemy.run.ts export const Website = AWS.Website.ReactRouter("Website", { -+ memorySize: 2048, + env: { + API_BASE: "https://api.example.com", + }, }); ``` -`env` values are set on the Lambda on deploy and injected into +`env` values are set on the server on deploy and injected into the dev server's process environment under `alchemy dev`, so server code reads the same values in both modes. Sibling props tune the -Lambda itself (`memorySize`, `timeout`, `architecture`, `runtime`). +server itself (`timeout`, `maxConcurrencyPerEnvironment`, +`maxEnvironments`). An output from another resource only exists once that resource is yielded, so declare the site inside the Stack generator instead: @@ -178,7 +177,7 @@ Effect.gen(function* () { ## Read the environment in a loader -The React Router server runs in a plain Node Lambda, so loaders and +The React Router server is a plain Node server, so loaders and actions read the environment from `process.env`: ```typescript @@ -195,7 +194,7 @@ instead, as `import.meta.env.VITE_*` — set those in the shell that runs ## Read the environment in a resource route A route module with no default export is a resource route, served by the -same Lambda: +same server: ```typescript // app/routes/api.hello.ts @@ -244,12 +243,25 @@ The build runs through your project's own `vite.config.ts` and integration observes the directory from the resolved Vite config, so there is nothing to mirror on the resource. -## Local dev +## Run on a Lambda Function -```sh -bun alchemy dev +Web Functions run in a subset of Regions. Elsewhere, set +`server: "function"`: the app builds with the `/react-router/aws` deploy target +and runs on a Lambda Function behind a streaming Function URL, tuned with +`memorySize`, `architecture`, and `runtime`: + +```diff lang="typescript" +// alchemy.run.ts +export const Website = AWS.Website.ReactRouter("Website", { ++ server: "function", ++ memorySize: 2048, +}); ``` +## Local dev + + + `alchemy dev` runs React Router's own Vite dev server (native HMR) instead of deploying anything; `site.url` is the dev server's `http://localhost:` address and no AWS resources are created. Wrap diff --git a/.agents/skills/alchemy/references/aws/frontend/solidstart.md b/.agents/skills/alchemy/references/aws/frontend/solidstart.md index 021e5335..e2eafe02 100644 --- a/.agents/skills/alchemy/references/aws/frontend/solidstart.md +++ b/.agents/skills/alchemy/references/aws/frontend/solidstart.md @@ -1,22 +1,22 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # SolidStart -> Deploy a SolidStart app to AWS with AWS.Website.SolidStart — nitro's aws-lambda preset on a streaming Lambda Function URL, S3 assets behind CloudFront, and SolidStart's own Vite dev server under alchemy dev. +> Deploy a SolidStart app to AWS with AWS.Website.SolidStart — SSR on a Lambda Web Function, S3 assets behind CloudFront, and SolidStart's own Vite dev server under alchemy dev. `AWS.Website.SolidStart` deploys a [SolidStart](https://start.solidjs.com) app to AWS. It runs your -project's own `vite build` and appends nitro's `aws-lambda` preset: -the SSR server runs on a Lambda Function URL with response streaming, -and client assets plus prerendered pages are served from a private S3 -bucket through CloudFront. A CloudFront Function routes each request -at the edge — uploaded files go to S3, everything else streams from -the Lambda. +project's own `vite build` and appends nitro's `node` preset: the SSR +server runs on a [Lambda Web Function](/aws/compute/web-functions) and +streams its responses, and client assets plus prerendered pages are +served from a private S3 bucket through CloudFront. A CloudFront +Function routes each request at the edge — uploaded files go to S3, +everything else streams from the server. :::note[Verified version line] -This page tracks `@solidjs/start` **2.x** with +Verified with `@solidjs/start` **2.x** and `@solidjs/vite-plugin-nitro-2` — the Vite-native line where `solidStart()` is a plain Vite plugin and nitro is a second plugin. ::: @@ -25,20 +25,16 @@ This page tracks `@solidjs/start` **2.x** with The build integration is not bundled with alchemy. Install `@alchemy.run/frontend-frameworks`; the resource loads its -`/solidstart` and `/solidstart/aws` exports from your project at +`/solidstart` and `/solidstart/node` exports from your project at deploy time. It is only used at build time, so a dev dependency is enough: -```sh -bun add -d @alchemy.run/frontend-frameworks -``` + `@solidjs/vite-plugin-nitro-2` is the server half of a SolidStart build and must be a project dependency too: -```sh -bun add @solidjs/vite-plugin-nitro-2 -``` + ## Configure Vite @@ -56,7 +52,8 @@ export default defineConfig({ ``` Alchemy appends its own `nitroV2Plugin()` instance at build time, -carrying the `aws-lambda` preset with response streaming enabled. +carrying nitro's `node` preset (`aws-lambda`, streaming enabled, with +`server: "function"`). Don't register `nitroV2Plugin()` yourself — the appended instance would discard its options, so the build fails with an actionable error instead. Pass nitro options through the resource's `nitro` @@ -69,7 +66,7 @@ Stack): ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.SolidStart("Website"); ``` @@ -113,17 +110,17 @@ The server function's environment is configured under `env`: ```diff lang="typescript" // alchemy.run.ts export const Website = AWS.Website.SolidStart("Website", { -+ memorySize: 2048, + env: { + API_BASE: "https://api.example.com", + }, }); ``` -`env` values are set on the Lambda on deploy and injected into +`env` values are set on the server on deploy and injected into the dev server's process environment under `alchemy dev`, so server code reads the same values in both modes. Sibling props tune the -Lambda itself (`memorySize`, `timeout`, `architecture`, `runtime`). +server itself (`timeout`, `maxConcurrencyPerEnvironment`, +`maxEnvironments`). An output from another resource only exists once that resource is yielded, so declare the site inside the Stack generator instead: @@ -143,7 +140,7 @@ Effect.gen(function* () { ## Read the environment in server code -The SolidStart server runs in a plain Node Lambda, so API routes, +The SolidStart server is a plain Node server, so API routes, server functions, and SSR read the environment from `process.env`: ```typescript @@ -174,14 +171,27 @@ from prerendered pages to prerender them too (`crawlLinks`). The `nitro` prop is the home for all nitro options (route rules, storage, ...) — the integration owns the plugin instance, so they cannot live in `vite.config.ts`. Values must be JSON-serializable; `preset` is -owned by the AWS deploy target, and a foreign preset is a hard error. +owned by the deploy target, and a foreign preset is a hard error. -## Local dev +## Run on a Lambda Function -```sh -bun alchemy dev +Web Functions run in a subset of Regions. Elsewhere, set +`server: "function"`: the app builds with the `/solidstart/aws` deploy target +and runs on a Lambda Function behind a streaming Function URL, tuned with +`memorySize`, `architecture`, and `runtime`: + +```diff lang="typescript" +// alchemy.run.ts +export const Website = AWS.Website.SolidStart("Website", { ++ server: "function", ++ memorySize: 2048, +}); ``` +## Local dev + + + `alchemy dev` runs SolidStart's own Vite dev server (native HMR) instead of deploying anything; `site.url` is the dev server's `http://localhost:` address and no AWS resources are created. diff --git a/.agents/skills/alchemy/references/aws/frontend/static-site.md b/.agents/skills/alchemy/references/aws/frontend/static-site.md index 3c70f607..ea755429 100644 --- a/.agents/skills/alchemy/references/aws/frontend/static-site.md +++ b/.agents/skills/alchemy/references/aws/frontend/static-site.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Static sites @@ -20,7 +20,7 @@ output: ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; export default Alchemy.Stack( @@ -48,9 +48,7 @@ CloudFront Function, and the distribution itself. `forceDestroy: true` lets `destroy` empty the bucket before deleting it; `site.url` resolves to the CloudFront domain (or `https://` when you pass `domain`). -```sh -bun alchemy deploy -``` + The deployed example lives at [`examples/aws-static-site`](https://github.com/alchemy-run/alchemy/tree/main/examples/aws-static-site) @@ -118,7 +116,9 @@ distribution: ```typescript const router = yield* AWS.Website.Router("WebsiteRouter", { - // hosted zone inferred from the hostname; pass hostedZoneId to pin it + // hosted zone inferred from the hostname; pass hostedZoneId to pin it, or + // dns: Cloudflare.DNS.Adapter() for a domain on Cloudflare DNS + // (see /infrastructure-as-code/dns-adapters) domain: { name: "example.com" }, }); diff --git a/.agents/skills/alchemy/references/aws/frontend/sveltekit.md b/.agents/skills/alchemy/references/aws/frontend/sveltekit.md index 13a7a171..cb67d528 100644 --- a/.agents/skills/alchemy/references/aws/frontend/sveltekit.md +++ b/.agents/skills/alchemy/references/aws/frontend/sveltekit.md @@ -1,17 +1,18 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # SvelteKit -> Deploy a SvelteKit app to AWS with AWS.Website.SvelteKit — SSR on a streaming Lambda Function URL, assets and prerendered pages on S3 + CloudFront, and Kit's own dev server under alchemy dev. +> Deploy a SvelteKit app to AWS with AWS.Website.SvelteKit — SSR on a Lambda Web Function, assets and prerendered pages on S3 + CloudFront, and Kit's own dev server under alchemy dev. `AWS.Website.SvelteKit` deploys a [SvelteKit](https://svelte.dev/docs/kit) app to AWS. It builds the app with SvelteKit's own Vite pipeline and a wrangler-free in-memory -AWS adapter emitting a streaming Lambda handler. Client assets and +Node adapter; the server runs on a +[Lambda Web Function](/aws/compute/web-functions). Client assets and prerendered pages are served from a private S3 bucket through -CloudFront; dynamic routes stream from the Lambda Function URL. Your +CloudFront; dynamic routes stream from the server. Your `vite.config.ts` loads natively; there is no `svelte.config.js` to write (kit v3 dropped it) and no adapter to install. @@ -19,12 +20,10 @@ write (kit v3 dropped it) and no adapter to install. The build integration is not bundled with alchemy. Install `@alchemy.run/frontend-frameworks`; the resource loads its -`/sveltekit` and `/sveltekit/aws` exports from your project at deploy +`/sveltekit` and `/sveltekit/node` exports from your project at deploy time. It is only used at build time, so a dev dependency is enough: -```sh -bun add -d @alchemy.run/frontend-frameworks -``` + ## Configure SvelteKit @@ -45,7 +44,7 @@ Stack): ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.SvelteKit("Website"); ``` @@ -74,7 +73,7 @@ export default Alchemy.Stack( Routes with `export const prerender = true` are uploaded to S3 and served from the edge without invoking the server; server routes -(`+server.ts`) and server load functions stream from the Lambda. +(`+server.ts`) and server load functions stream from the server. See [examples/aws-website-sveltekit](https://github.com/alchemy-run/alchemy/tree/main/examples/aws-website-sveltekit) @@ -95,13 +94,13 @@ export const Website = AWS.Website.SvelteKit("Website", { }); ``` -The values are set on the Lambda at deploy time and injected into the +The values are set on the server at deploy time and injected into the dev server's process environment under `alchemy dev`, so server code reads the same values in both modes. ## Read the environment in server code -The Kit server runs in a plain Node Lambda, so server routes read the +The Kit server is a plain Node server, so server routes read the environment from `process.env` (or kit's `$env/dynamic/private`, which is initialized from it): @@ -127,7 +126,7 @@ export default defineConfig({ plugins: [ tailwindcss(), sveltekit({ - alias: { $lib: "src/lib" }, + prerender: { handleHttpError: "warn" }, }), ], }); @@ -153,12 +152,25 @@ call. Don't set `kit.adapter` — Alchemy injects its own wrangler-free AWS adapter (an adapter declared in your `sveltekit(...)` call is replaced with a warning). -## Local dev +## Run on a Lambda Function + +Web Functions run in a subset of Regions. Elsewhere, set +`server: "function"`: the app builds with the `/sveltekit/aws` deploy target +and runs on a Lambda Function behind a streaming Function URL, tuned with +`memorySize`, `architecture`, and `runtime`: -```sh -bun alchemy dev +```diff lang="typescript" +// alchemy.run.ts +export const Website = AWS.Website.SvelteKit("Website", { ++ server: "function", ++ memorySize: 2048, +}); ``` +## Local dev + + + `alchemy dev` runs SvelteKit's own Vite dev server — Node SSR with full HMR, which is already the AWS Lambda programming model (`process.env` included) — instead of deploying; `site.url` is the diff --git a/.agents/skills/alchemy/references/aws/frontend/tanstack-start.md b/.agents/skills/alchemy/references/aws/frontend/tanstack-start.md index 6958c610..17afc4f6 100644 --- a/.agents/skills/alchemy/references/aws/frontend/tanstack-start.md +++ b/.agents/skills/alchemy/references/aws/frontend/tanstack-start.md @@ -1,30 +1,29 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # TanStack Start -> Deploy TanStack Start (React or Solid) to AWS with AWS.Website.TanStackStart — SSR on a streaming Lambda Function URL, client assets on S3 + CloudFront, and TanStack Start's own Vite dev server under alchemy dev. +> Deploy TanStack Start (React or Solid) to AWS with AWS.Website.TanStackStart — SSR on a Lambda Web Function, client assets on S3 + CloudFront, and TanStack Start's own Vite dev server under alchemy dev. `AWS.Website.TanStackStart` deploys a [TanStack Start](https://tanstack.com/start) app to AWS. TanStack Start is pure Vite, so Alchemy runs your project's own `vite build`: the SSR -server runs on a Lambda Function URL with response streaming, and client -assets are served from a private S3 bucket through CloudFront. A -CloudFront Function routes each request at the edge — uploaded files go -to S3, everything else streams from the Lambda. +server runs on a [Lambda Web Function](/aws/compute/web-functions) and +streams its responses, and client assets are served from a private S3 +bucket through CloudFront. A CloudFront Function routes each request at +the edge — uploaded files go to S3, everything else streams from the +server. ## Install The build integration is not bundled with alchemy. Install `@alchemy.run/frontend-frameworks`; the resource loads its -`/tanstack-start` and `/tanstack-start/aws` exports from your project at +`/tanstack-start` and `/tanstack-start/node` exports from your project at deploy time. It is only used at build time, so a dev dependency is enough: -```sh -bun add -d @alchemy.run/frontend-frameworks -``` + ## Configure Vite @@ -43,8 +42,8 @@ export default defineConfig({ ``` Alchemy drives that config's `builder.buildApp()` and forces the SSR -bundle to be self-contained, then wraps its fetch handler as a streaming -Lambda handler. +bundle to be self-contained, then serves its fetch handler from a Node +server. :::caution[Remove @cloudflare/vite-plugin if present] The TanStack CLI adds `@cloudflare/vite-plugin` when scaffolding a new @@ -76,7 +75,7 @@ Stack): ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.TanStackStart("Website"); ``` @@ -115,7 +114,7 @@ export default Alchemy.Stack( Requests matching a built client asset are served straight from S3; everything else — SSR routes, server routes, server functions — falls -through to the Lambda. +through to the server. ## Add environment variables @@ -124,17 +123,17 @@ The server function's environment is configured under `env`: ```diff lang="typescript" // alchemy.run.ts export const Website = AWS.Website.TanStackStart("Website", { -+ memorySize: 2048, + env: { + API_BASE: "https://api.example.com", + }, }); ``` -`env` values are set on the Lambda on deploy and injected into +`env` values are set on the server on deploy and injected into the dev server's process environment under `alchemy dev`, so server code reads the same values in both modes. Sibling props tune the -Lambda itself (`memorySize`, `timeout`, `architecture`, `runtime`). +server itself (`timeout`, `maxConcurrencyPerEnvironment`, +`maxEnvironments`). An output from another resource only exists once that resource is yielded, so declare the site inside the Stack generator instead: @@ -154,7 +153,7 @@ Effect.gen(function* () { ## Read the environment in a server function -The TanStack Start server runs in a plain Node Lambda, so server +The TanStack Start server is a plain Node server, so server functions read the environment from `process.env`: ```typescript @@ -172,7 +171,7 @@ instead, as `import.meta.env.VITE_*` — set those in the shell that runs ## Read the environment in a server route -Server routes run on the same Lambda and read `process.env` the same +Server routes run on the same server and read `process.env` the same way: ```typescript @@ -231,12 +230,25 @@ The build runs through your project's own `vite.config.ts` — the vite's default `build.outDir` (`dist`); the integration reads the server and client output from `dist/server` and `dist/client`. -## Local dev +## Run on a Lambda Function -```sh -bun alchemy dev +Web Functions run in a subset of Regions. Elsewhere, set +`server: "function"`: the app builds with the `/tanstack-start/aws` deploy target +and runs on a Lambda Function behind a streaming Function URL, tuned with +`memorySize`, `architecture`, and `runtime`: + +```diff lang="typescript" +// alchemy.run.ts +export const Website = AWS.Website.TanStackStart("Website", { ++ server: "function", ++ memorySize: 2048, +}); ``` +## Local dev + + + `alchemy dev` runs TanStack Start's own Vite dev server (native HMR) instead of deploying anything; `site.url` is the dev server's `http://localhost:` address and no AWS resources are created. Wrap diff --git a/.agents/skills/alchemy/references/aws/frontend/vinext.md b/.agents/skills/alchemy/references/aws/frontend/vinext.md index f17bc212..203ee386 100644 --- a/.agents/skills/alchemy/references/aws/frontend/vinext.md +++ b/.agents/skills/alchemy/references/aws/frontend/vinext.md @@ -1,17 +1,19 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Vinext > Deploy vinext to AWS with the shared Website API, native local development, and a platform-specific data cache. `AWS.Website.Vinext` builds with the Vinext Vite API for production and runs native -`vinext dev` locally. The React Server Components handler runs on a streaming Lambda Function URL. -S3 stores assets and CloudFront routes asset requests to S3 and other requests -to Lambda. This uses vinext, not OpenNext. +`vinext dev` locally. The React Server Components handler runs on a +[Lambda Web Function](/aws/compute/web-functions), a Node HTTP server that +serves many requests per environment and streams responses. S3 stores assets +and CloudFront routes asset requests to S3 and other requests to the server. +This uses vinext, not OpenNext. -The Lambda target supports **App Router** applications. Use a Node deployment +The AWS target supports **App Router** applications. Use a Node deployment target such as [Prisma](/prisma/frontend/vinext) or [Fly](/fly/frontend/vinext) for Pages Router applications. @@ -20,12 +22,9 @@ for Pages Router applications. Keep `vinext`, `react`, `react-dom`, and `react-server-dom-webpack` in your application dependencies, with `vite` and `@vitejs/plugin-rsc` for building. Use vinext **1.0.0-beta.10 or newer**. Alchemy uses its standalone packaging -to include external runtime dependencies in the Lambda archive. Add the Alchemy integration: +to include external runtime dependencies in the server archive. Add the Alchemy integration: - - - - + ## Configure vinext @@ -47,7 +46,7 @@ No Alchemy plugin is required in `vite.config.ts`; deployment settings belong on ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.Vinext("Website", { rootDir: ".", @@ -104,15 +103,29 @@ page reflects its build-time inputs instead. ## Configure the data cache The Website provisions an S3 bucket for ISR and `"use cache"`, sets -`CACHE_BUCKET_NAME`, and grants the Lambda access. The build selects the S3 +`CACHE_BUCKET_NAME`, and grants the server access. Every environment shares +the bucket. The build selects the S3 adapter. Local development uses memory and creates no bucket. -## Local development +## Run on a Lambda Function + +Web Functions run in a subset of Regions. Elsewhere, set +`server: "function"` to run the handler on a Lambda Function behind a +streaming Function URL, tuned with `memorySize`, `architecture`, and +`runtime`: -```sh -bun alchemy dev +```diff lang="typescript" +// alchemy.run.ts +export const Website = AWS.Website.Vinext("Website", { ++ server: "function", ++ memorySize: 2048, +}); ``` +## Local development + + + The Website runs `vinext dev` with native HMR and creates no cloud resources. Other resources declared in the Stack retain their own provider behavior. Apply `.pipe(Alchemy.remote())` to the Website for a live deployment during dev. diff --git a/.agents/skills/alchemy/references/aws/frontend/vite-spa.md b/.agents/skills/alchemy/references/aws/frontend/vite-spa.md index 94287bf0..ecc42f1a 100644 --- a/.agents/skills/alchemy/references/aws/frontend/vite-spa.md +++ b/.agents/skills/alchemy/references/aws/frontend/vite-spa.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # React SPA @@ -22,9 +22,7 @@ The build integration is not bundled with alchemy. Install `/vite/aws` exports from your project at deploy time. It is only used at build time, so a dev dependency is enough: -```sh -bun add -d @alchemy.run/frontend-frameworks -``` + ## Scaffold the app @@ -64,7 +62,7 @@ Stack). `rootDir` points at the project directory — the one holding ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.Vite("Website", { rootDir: "./web", @@ -96,9 +94,7 @@ export default Alchemy.Stack( ); ``` -```sh -bun alchemy deploy -``` + Alchemy runs `vite build` in `rootDir`, uploads `dist/` to a private S3 bucket, and serves it through CloudFront. `site.url` is the @@ -113,9 +109,7 @@ and a `200` — the client router then handles the path. Add React Router and route on the client: -```sh -bun add react-router-dom -``` + ```tsx // web/src/main.tsx @@ -245,9 +239,7 @@ pass `lockfile: true` to keep rebuilding when dependencies change. ## Local dev -```sh -bun alchemy dev -``` + `alchemy dev` runs Vite's own dev server — native HMR, instant module updates — instead of deploying. `site.url` is the local address and diff --git a/.agents/skills/alchemy/references/aws/frontend/vite.md b/.agents/skills/alchemy/references/aws/frontend/vite.md index 1246e31d..b5b3f144 100644 --- a/.agents/skills/alchemy/references/aws/frontend/vite.md +++ b/.agents/skills/alchemy/references/aws/frontend/vite.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Vite @@ -20,9 +20,7 @@ The build integration is not bundled with alchemy. Install `/vite/aws` exports from your project at deploy time. It is only used at build time, so a dev dependency is enough: -```sh -bun add -d @alchemy.run/frontend-frameworks -``` + ## Configure Vite @@ -50,7 +48,7 @@ Stack): ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.Vite("Website"); ``` @@ -81,9 +79,7 @@ Deploying uploads the build output to S3, writes the file manifest to a CloudFront KeyValueStore, and creates the distribution that serves it at the edge. -```sh -bun alchemy deploy -``` + See [examples/aws-website-vite](https://github.com/alchemy-run/alchemy/tree/main/examples/aws-website-vite) @@ -225,9 +221,7 @@ it entirely. ## Local dev -```sh -bun alchemy dev -``` + `alchemy dev` runs Vite's own dev server (native HMR) instead of deploying; `site.url` is the local address and no AWS resources are @@ -288,8 +282,8 @@ this resource. Each client-only stack has its own page building on it: - [React SPA](/aws/frontend/vite-spa) — from a bare `index.html` to the `create-vite` template. - [Vue](/aws/frontend/vue) — Vue 3 SPAs with `vue-router` deep links. -- [Foldkit](/aws/frontend/foldkit) — builds through the same Vite - pipeline under its own `AWS.Website.Foldkit` resource. +- [Foldkit](/aws/frontend/foldkit) — deploys SPA, SSR, and prerendered apps + through `AWS.Website.Foldkit`. ## SSR frameworks diff --git a/.agents/skills/alchemy/references/aws/frontend/vue.md b/.agents/skills/alchemy/references/aws/frontend/vue.md index dff59d66..3be8a516 100644 --- a/.agents/skills/alchemy/references/aws/frontend/vue.md +++ b/.agents/skills/alchemy/references/aws/frontend/vue.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Vue @@ -20,9 +20,7 @@ The build integration is not bundled with alchemy. Install `/vite/aws` exports from your project at deploy time. It is only used at build time, so a dev dependency is enough: -```sh -bun add -d @alchemy.run/frontend-frameworks -``` + ## Scaffold the app @@ -61,7 +59,7 @@ name: ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.Vite("Vue"); ``` @@ -88,9 +86,7 @@ export default Alchemy.Stack( ); ``` -```sh -bun alchemy deploy -``` + Alchemy runs `vite build`, uploads `dist` to S3, and serves it from CloudFront at the returned `url`. Input files are content-hashed, so a @@ -104,9 +100,7 @@ deploy that changes nothing skips the build and the upload. so the router resolves the route on the client — that is the `spa` default and there is nothing to configure. -```sh -bun add vue-router -``` + ```typescript // src/main.ts @@ -210,9 +204,7 @@ same S3 + CloudFront stack. ## Local dev -```sh -bun alchemy dev -``` + `alchemy dev` runs Vue's own Vite dev server with native HMR instead of deploying; `site.url` is the local address and no AWS resources are diff --git a/.agents/skills/alchemy/references/aws/frontend/waku.md b/.agents/skills/alchemy/references/aws/frontend/waku.md index e842bb7b..d3fcf888 100644 --- a/.agents/skills/alchemy/references/aws/frontend/waku.md +++ b/.agents/skills/alchemy/references/aws/frontend/waku.md @@ -1,14 +1,15 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Waku -> Deploy a Waku app to AWS with AWS.Website.Waku — RSC server on a streaming Lambda Function URL, SSG pages and assets on S3 + CloudFront, and Waku's own dev server under alchemy dev. +> Deploy a Waku app to AWS with AWS.Website.Waku — RSC server on a Lambda Web Function, SSG pages and assets on S3 + CloudFront, and Waku's own dev server under alchemy dev. `AWS.Website.Waku` deploys a [Waku](https://waku.gg) app (React Server Components) to AWS. It builds the project programmatically: -the RSC server runs on a Lambda Function URL with response streaming, +the RSC server runs on a +[Lambda Web Function](/aws/compute/web-functions) and streams its responses, and the client output — including SSG-prerendered pages — is served from a private S3 bucket through CloudFront. No `waku.config.ts` edits are required — if you have one it loads natively — and there is @@ -18,12 +19,10 @@ no adapter to configure and no build command to run. The build integration is not bundled with alchemy. Install `@alchemy.run/frontend-frameworks`; the resource loads its `/waku` -and `/waku/aws` exports from your project at deploy time. It is only +and `/waku/node` exports from your project at deploy time. It is only used at build time, so a dev dependency is enough: -```sh -bun add -d @alchemy.run/frontend-frameworks -``` + ## Configure Waku @@ -72,7 +71,7 @@ Stack): ```typescript // alchemy.run.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; export const Website = AWS.Website.Waku("Website"); ``` @@ -101,7 +100,7 @@ export default Alchemy.Stack( Pages rendered as `"static"` are generated at build time, uploaded to S3, and served from the edge; dynamic pages and API routes stream -from the Lambda. +from the server. See [examples/aws-website-waku](https://github.com/alchemy-run/alchemy/tree/main/examples/aws-website-waku) @@ -122,14 +121,14 @@ export const Website = AWS.Website.Waku("Website", { }); ``` -The values are set on the Lambda at deploy time and injected into the +The values are set on the server at deploy time and injected into the dev server's process environment under `alchemy dev`, so server code reads the same values in both modes. ## Read the environment in server code Server components and API routes read the environment through waku's -`getEnv` — on AWS it is backed by the Lambda's `process.env` at +`getEnv` — on AWS it is backed by the server's `process.env` at request time, and it keeps page modules portable across deploy targets: @@ -145,12 +144,25 @@ export default async function HomePage() { export const getConfig = async () => ({ render: "dynamic" }) as const; ``` -## Local dev +## Run on a Lambda Function + +Web Functions run in a subset of Regions. Elsewhere, set +`server: "function"`: the app builds with the `/waku/aws` deploy target +and runs on a Lambda Function behind a streaming Function URL, tuned with +`memorySize`, `architecture`, and `runtime`: -```sh -bun alchemy dev +```diff lang="typescript" +// alchemy.run.ts +export const Website = AWS.Website.Waku("Website", { ++ server: "function", ++ memorySize: 2048, +}); ``` +## Local dev + + + `alchemy dev` runs Waku's own dev server (native HMR) instead of deploying; `site.url` is the local address and no AWS resources are created. Wrap the site in `Alchemy.remote()` to deploy the real diff --git a/.agents/skills/alchemy/references/aws/frontend/websites.md b/.agents/skills/alchemy/references/aws/frontend/websites.md index a9820737..8dc844e5 100644 --- a/.agents/skills/alchemy/references/aws/frontend/websites.md +++ b/.agents/skills/alchemy/references/aws/frontend/websites.md @@ -1,63 +1,76 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Websites > Deploy Vite, Astro, Next.js, vinext, Nuxt, React Router, SvelteKit, TanStack Start, Waku, Octane, or any static build to AWS with first-class Website resources. -Alchemy deploys frontends to AWS with a family of `AWS.Website` -resources. Each one builds your project programmatically and deploys -it as a serverless site — the SSR server on a streaming Lambda -Function URL, static assets in a private S3 bucket, and a CloudFront -distribution whose edge router serves uploaded files from S3 and -forwards everything else to the server — with no AWS-specific -configuration: no CDK, no CloudFormation, no adapter setup. Your -framework's own config file (`astro.config.*`, `nuxt.config.ts`, -`vite.config.ts`, ...) loads natively; Alchemy layers its AWS -integration on top. - -- [`Vite`](/aws/frontend/vite) — any client-only Vite project (React, - Vue, Solid, or a plain SPA): assets-only, no Lambda; your - `vite.config.*` loads natively. -- [`Foldkit`](/aws/frontend/foldkit) — Foldkit apps; `Vite` with SPA - deep links on by default. -- [`Astro`](/aws/frontend/astro) — Astro sites, server-rendered or - fully static; your `astro.config.*` loads natively. -- [`Nextjs`](/aws/frontend/nextjs) — Next.js apps built through the - OpenNext (`@opennextjs/aws`) pipeline, with streaming SSR, image - optimization, and ISR wiring; your `next.config.*` is honored - as-is. -- [`Vinext`](/aws/frontend/vinext) — vinext (Next.js API on Vite) - apps on a streaming Lambda; your `vite.config.ts` loads natively. -- [`Nuxt`](/aws/frontend/nuxt) — Nuxt apps built through nitro's - `aws-lambda` preset; your `nuxt.config.ts` loads natively. -- [`ReactRouter`](/aws/frontend/react-router) — React Router v7 in - framework mode, built through your own `vite build`. -- [`SvelteKit`](/aws/frontend/sveltekit) — SvelteKit apps with a - wrangler-free in-memory AWS adapter; your `vite.config.ts` loads - natively. -- [`TanStackStart`](/aws/frontend/tanstack-start) — TanStack Start - (React or Solid), built through your own `vite build`. -- [`Waku`](/aws/frontend/waku) — Waku (React Server Components) - apps. -- [`Octane`](/aws/frontend/octane) — OctaneJS fullstack apps built - through your own `vite build` with the AWS marker adapter. -- [`StaticSite`](/aws/frontend/static-site) — any directory of files, - optionally produced by a build command, for static generators like - Zola and Hugo or pre-built SPAs. -- [`Router`](/aws/frontend/static-site#compose-sites-with-a-router) — - a shared CloudFront front door: one distribution serving several - sites (or a site plus an API), routed at the edge. - -Every resource shares the same surface: `domain` (ACM certificate + -Route 53 records), server configuration (`memorySize`, `timeout`, -`env`), `assets`, `edge` customizations, and `invalidation`. -All builds are memoized by content-hashing the input files — an -unchanged project skips the build and deploy entirely. Under -`alchemy dev`, every resource runs the framework's own dev server -(native HMR) instead of deploying; `Alchemy.remote()` opts back into -the full live deployment. +A website on AWS is three pieces working together. Its static files, the scripts, styles and images, sit in a private S3 Bucket. Its server, if it has one, runs on a [Lambda Web Function](/aws/compute/web-functions). And a CloudFront distribution in front of both serves every request from a location near the visitor: files straight from the Bucket, everything else from the server. + +```text +Diagram (nodes and edges as authored): + +``` + +Each framework has a Website resource that builds your project and creates all three. Your framework's own config file loads as it is, with nothing AWS-specific in it: + +```typescript title="alchemy.run.ts" +const site = yield* AWS.Website.Astro("Website", { domain: "app.example.com" }); +``` + +Every Website resource takes the same props: a `domain`, with its certificate and DNS records (see [Custom domains](/aws/networking/custom-domains)), the server's `timeout`, `env` and scaling, and how assets are uploaded and cached. A build is skipped when no input file has changed. Under `alchemy dev`, each one runs the framework's own dev server instead of deploying. + +A site with no server, a single-page app or a static generator's output, creates no Function at all: just the Bucket and the distribution. + +## Serve from several Regions + +List extra Regions to run the server in each of them behind one global +domain. CloudFront forwards to it, and each request reaches the nearest +Region: + +```typescript +const site = yield* AWS.Website.Nuxt("Website", { + regions: ["us-east-1", "eu-west-1"], +}); +``` + +The site's URL doesn't change when you add or remove Regions. `Nextjs` +and `Vinext` keep their data caches in the home Region, so a server in +another Region reaches back to it for cached pages; `regions` helps most +for sites without a server-side cache. + +## Choose the server + +The SSR server runs on a Lambda Web Function: your framework's own Node +server, serving many requests per environment and streaming each +response. Web Functions run in a subset of Regions. Elsewhere, set +`server: "function"` to run the server on a Lambda Function behind a +streaming Function URL: + +```typescript +const site = yield* AWS.Website.Nuxt("Website", { + server: "function", + memorySize: 2048, +}); +``` + +`memorySize`, `architecture`, and `runtime` apply only to +`server: "function"`; a Web Function has a fixed 2 GB, Arm64 and +Node.js 24. ## What's supported diff --git a/.agents/skills/alchemy/references/aws/iam.md b/.agents/skills/alchemy/references/aws/iam.md new file mode 100644 index 00000000..af3f43d5 --- /dev/null +++ b/.agents/skills/alchemy/references/aws/iam.md @@ -0,0 +1,281 @@ + + +# IAM and bindings + +> How IAM identities, roles, trust, resource-based policies and tag-based access (ABAC) work on AWS, and how Alchemy bindings write each runtime's least-privilege policies from the calls its code makes. + +IAM is the part of AWS that answers one question on every request: may this identity do this action on this resource? Nothing is allowed until a policy says so. + +## Every request has an identity + +When your code calls `s3:PutObject`, AWS first works out who is asking. The caller signs each request with credentials, and the credentials belong to an **identity**. + +There are two kinds. An **IAM user** has long-lived keys of its own. An **IAM role** has none: a trusted principal **assumes** it and receives temporary credentials that expire within hours. + +Prefer roles everywhere. A person signs in through IAM Identity Center and assumes a role in the account they work in. A Lambda Function, an ECS task or an EC2 instance runs as a role AWS assumes for it. CI assumes a role through OIDC. No long-lived key is ever written down. + +## A policy lists what an identity may do + +A **policy** is a JSON document of statements. Each statement names an effect, the actions it covers and the resources it applies to: + +```json +{ + "Effect": "Allow", + "Action": ["sqs:SendMessage"], + "Resource": "arn:aws:sqs:us-east-1:123456789012:myapp-jobs-a1b2c3" +} +``` + +Actions are `service:Operation` pairs, one per API call. Resources are ARNs, and a `*` in one matches many: `arn:aws:s3:::myapp-files-a1b2c3/*` is every object in one Bucket. + +AWS denies by default. A request is allowed only if some statement allows it and no statement denies it. So the safe policy is the smallest one: exactly the actions the code calls, on exactly the resources it calls them on. That's **least privilege**. + +## A role is trusted, then assumed + +A role has two policies. Its **permissions** say what it may do. Its **trust policy** says who may assume it. + +```text +Diagram (nodes and edges as authored): + +``` + +A Lambda Function's execution role trusts `lambda.amazonaws.com`, so the Lambda service can assume it on the Function's behalf. Every time your code runs, it carries the role's temporary credentials, and every call it makes is checked against the role's permissions. + +## A resource can have a policy too + +So far every policy has been attached to an identity, saying what it may do. Many resources carry a policy of their own, saying who may reach them. Buckets, Queues, Topics, KMS keys, Secrets and Lambda Functions all do. This is a **resource-based policy**, and its statements name a **principal**: the account, role or service the statement is about. + +```json +{ + "Effect": "Allow", + "Principal": { "Service": "cloudfront.amazonaws.com" }, + "Action": ["s3:GetObject"], + "Resource": "arn:aws:s3:::myapp-site-a1b2c3/*", + "Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::123456789012:distribution/E1A2B3" } } +} +``` + +This one lets CloudFront read the site's files, but only on behalf of one distribution. The condition matters: without it, any distribution in any account could read the Bucket. + +Within one account, either kind of policy can allow a request. Across accounts, both must: the caller's identity policy has to allow the call, and the resource's policy has to allow the caller's account. + + + +Services that call your resources, like CloudFront, EventBridge, SNS or S3 notifications, have no identity policy in your account. A resource policy is the only way to let them in. + +## Bindings write the policy + +Writing that policy by hand means keeping two lists in step: the calls in the code, and the statements in the role. Add a call and forget the statement, and the call fails in production. Remove a call and forget the statement, and the role keeps a permission nobody uses. + +A **binding** keeps them in step. It's one line in the runtime's Construction phase that returns a typed client and adds the matching statement to the runtime's role: + +```typescript title="src/api.ts" +const sendMessage = yield* SQS.SendMessage(Jobs); +``` + +Deploy adds `sqs:SendMessage` on the `Jobs` Queue's ARN to the Function's role. Call the client while the Function runs: + +```typescript title="src/api.ts" +yield* sendMessage({ MessageBody: JSON.stringify({ id }) }); +``` + +The client comes from the binding's Layer, `SQS.SendMessageHttp`, which the Function provides: + +```typescript title="src/api.ts" +export default class Api extends AWS.Lambda.Function()( + "Api", + { main: import.meta.url }, + Effect.gen(function* () { + const sendMessage = yield* SQS.SendMessage(Jobs); + return { + fetch: sendMessage({ MessageBody: "hello" }).pipe( + Effect.as(HttpServerResponse.text("queued")), + Effect.orDie, + ), + }; + }).pipe(Effect.provide(SQS.SendMessageHttp)), +) {} +``` + +Each binding is one IAM statement. Bind `S3.GetObject` as well, and the role gains `s3:GetObject` on that Bucket's objects. Delete a binding, and the next deploy removes its statement. + +## Bindings are scoped to one resource + +A binding takes the resource it grants access to, so its statement names that resource's ARN and nothing else: + +```typescript title="src/api.ts" +const getObject = yield* S3.GetObject(Files); +const putObject = yield* S3.PutObject(Uploads); +``` + +The Function may read from `Files` and write to `Uploads`. It can't write to `Files`, and it can't touch any other Bucket in the account, even one created by the same Stack. + +## The role comes with the runtime + +You never declare a Lambda Function's execution role. Deploying the Function creates it, with the Lambda trust policy, permission to write its own logs, and one statement per binding. Destroying the Function deletes it. + +The role's name and ARN are on the Function, for anything outside the Function that needs them: + +```typescript title="alchemy.run.ts" +const api = yield* Api; +return { role: api.roleArn }; +``` + +ECS tasks, EKS workloads and EC2 instances work the same way. A binding on any of them adds its statement to the role that runs it. See [Choosing a runtime](/aws/compute/choosing-a-runtime). + +## Bindings write resource policies too + +When the caller is a service rather than your code, the binding writes the resource's policy instead of a role's. You don't declare these statements, and each one carries the condition that limits it to the one caller: + +A Website's CloudFront distribution gets `s3:GetObject` in its Bucket's policy, for that distribution only. An EventBridge rule that targets a Queue gets `sqs:SendMessage` in the Queue's policy, for that rule only. A rule, schedule or Bucket notification that targets a Function gets a **Lambda permission**, the resource policy that lets the service invoke it. An event source that polls, like a Queue or a Stream, instead gets read permissions on the Function's role. + +Remove the website, rule or subscription, and the next deploy removes its statement. + +## Open a resource to another account + +A resource policy is also how you share a resource with another account. Add your own statements to a Bucket's `policy`, and they're merged with the ones bindings contribute: + +```typescript title="src/reports.ts" +export const Reports = AWS.S3.Bucket("Reports", { + bucketName: "acme-reports", + policy: [ + { + Effect: "Allow", + Principal: { AWS: "arn:aws:iam::222222222222:root" }, + Action: ["s3:GetObject"], + Resource: ["arn:aws:s3:::acme-reports/*"], + }, + ], +}); +``` + +Name the Bucket yourself here, so the statement can name its ARN. The other account still has to allow its own roles to make the call. Queues and KMS keys take a `policy` the same way. To let another account or a service invoke a Function, declare a permission: + +```typescript title="alchemy.run.ts" +yield* AWS.Lambda.Permission("PartnerInvoke", { + functionName: api.functionName, + action: "lambda:InvokeFunction", + principal: "222222222222", +}); +``` + +## Grant by tag with ABAC + +Bindings grant access to named resources: this Function may write to this Bucket. That's the right model when the code knows what it calls. Sometimes access follows a rule instead: anyone on the payments team may read the payments team's tables, including ones created next month. + +**Attribute-based access control** (ABAC) writes that rule with tags. A statement's condition compares a tag on the resource with a tag on the caller, so one statement covers every matching resource, current and future: + +```typescript title="alchemy.run.ts" +const analysts = yield* AWS.IAM.Role("PaymentsAnalysts", { + assumeRolePolicyDocument: { + Version: "2012-10-17", + Statement: [ + { + Effect: "Allow", + Principal: { AWS: "arn:aws:iam::123456789012:root" }, + Action: ["sts:AssumeRole", "sts:TagSession"], + }, + ], + }, + tags: { team: "payments" }, + inlinePolicies: { + ReadTeamTables: { + Version: "2012-10-17", + Statement: [ + { + Effect: "Allow", + Action: ["dynamodb:GetItem", "dynamodb:Query"], + Resource: "*", + Condition: { + StringEquals: { "aws:ResourceTag/team": "${aws:PrincipalTag/team}" }, + }, + }, + ], + }, + }, +}); +``` + +Tag the resources the rule should cover: + +```typescript title="src/ledger.ts" +export const Ledger = AWS.DynamoDB.Table("Ledger", { + partitionKey: "id", + attributes: { id: "S" }, + tags: { team: "payments" }, +}); +``` + +Alchemy already tags everything it creates with `alchemy::stack`, `alchemy::stage` and `alchemy::id`, so you can scope a rule to one stage without adding tags of your own: + +```json +{ "StringEquals": { "aws:ResourceTag/alchemy::stage": "prod" } } +``` + +Not every action supports tag conditions. Check the service's entry in the [AWS service authorization reference](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_actions-resources-contextkeys.html) before relying on one. And keep tags under control: whoever can change a tag can change who has access. + +## Declare a role for anything else + +Some identities aren't runtimes: the role CI assumes to deploy, a role another service assumes, a role you hand to a partner account. Declare those with `AWS.IAM.Role`, giving its trust policy and its permissions: + +```typescript title="alchemy.run.ts" +const role = yield* AWS.IAM.Role("DeployRole", { + assumeRolePolicyDocument: { + Version: "2012-10-17", + Statement: [ + { + Effect: "Allow", + Principal: { Federated: oidc.openIDConnectProviderArn }, + Action: ["sts:AssumeRoleWithWebIdentity"], + Condition: { + StringLike: { "token.actions.githubusercontent.com:sub": "repo:your-org/your-repo:*" }, + }, + }, + ], + }, + managedPolicyArns: ["arn:aws:iam::aws:policy/AdministratorAccess"], +}); +``` + +This one lets GitHub Actions in one repository deploy without a stored key. The [CI tutorial](/aws/tutorial/part-5) builds it step by step. + +## Trust another cloud + +A runtime on another cloud can be trusted the same way. A Cloud Run service binds an SQS Queue exactly as a Lambda does, and the binding creates a role that trusts that one Google service account. There's no access key to create, store or rotate. See [Federated identity](/aws/security/federated-identity). + +## Keep secrets out of policies + +IAM decides who may call AWS. It doesn't hold your third-party API keys. Pass those to a runtime from your `.env` through `effect/Config`, or keep them in Secrets Manager when other resources share or rotate them. See [Secrets & env](/aws/security/secrets-env). diff --git a/.agents/skills/alchemy/references/aws/local-development.md b/.agents/skills/alchemy/references/aws/local-development.md index 84fdbfd2..d5513d93 100644 --- a/.agents/skills/alchemy/references/aws/local-development.md +++ b/.agents/skills/alchemy/references/aws/local-development.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Local development @@ -100,6 +100,17 @@ const site = yield* AWS.Website.Vite("Web"); // deploy: site.url = the CloudFront distribution ``` +A bare `AWS.Lambda.WebFunction` runs in the emulator instead. Its +server answers at a local endpoint URL whose certificate the +emulator signs with the authority in `~/.floci/ca.pem`, which +`curl --cacert` or your system keychain can trust: + +```typescript +const api = yield* AWS.Lambda.WebFunction("Api", { main: "./src/server.ts" }); +// dev: api.url = https://.001.lambda-web.us-east-1.localhost:4566 +// deploy: api.url = https://..lambda-web..on.aws +``` + The same stack deploys unchanged: `alchemy deploy` runs `vite build` and serves the output from S3 through CloudFront. For SSR frameworks, `server.environment` is delivered to the dev @@ -156,7 +167,7 @@ local emulator in dev: | Category | Services | | ------------------- | ------------------------------------------------------------------------------------------------------------------- | -| Compute | Lambda (functions, layers, versions, aliases, event source mappings, permissions), ECS, ECR, Batch, Auto Scaling, Application Auto Scaling | +| Compute | Lambda (functions, Web Functions, layers, versions, aliases, event source mappings, permissions), ECS, ECR, Batch, Auto Scaling, Application Auto Scaling | | APIs & delivery | API Gateway (REST), API Gateway v2 (HTTP & WebSocket), AppSync, CloudFront (Distributions, Functions, KeyValueStore), WAFv2, ACM | | Storage & databases | S3, DynamoDB, RDS, Glue, Athena, S3 Vectors | | Messaging & events | SQS, SNS, EventBridge, Kinesis, Firehose, Pipes, Scheduler, Step Functions | @@ -210,9 +221,7 @@ The default image is our patched release To wipe everything inside the emulator without recreating the container, point [`nuke`](/cli/nuke) at the local providers: -```sh -bun alchemy unsafe nuke --local --include 'AWS.*' -``` + `--local` enumerates and deletes through each provider's local implementation, so it only ever sees emulated resources — no diff --git a/.agents/skills/alchemy/references/aws/messaging/dynamodb-streams.md b/.agents/skills/alchemy/references/aws/messaging/dynamodb-streams.md index 4bba224d..3e779eae 100644 --- a/.agents/skills/alchemy/references/aws/messaging/dynamodb-streams.md +++ b/.agents/skills/alchemy/references/aws/messaging/dynamodb-streams.md @@ -1,194 +1,115 @@ - -# Process DynamoDB Streams - -> Enable a DynamoDB Stream on your table and consume change records as a typed Effect Stream from the same Lambda. - -The DynamoDB table from the previous part stores records, but -writes happen in the dark — there's no way for downstream systems -to react. **DynamoDB Streams** fix that: every change to the -table emits a change record (insert / modify / remove) you can -stream into a Lambda. In Alchemy this is one helper call. - -## Subscribe to the stream - -Start with the smallest possible subscription: log just the -event name (`INSERT` / `MODIFY` / `REMOVE`) for each change. -Add it alongside the existing bindings: - -```diff lang="typescript" -// src/api.ts -import * as AWS from "alchemy/AWS"; -import * as DynamoDB from "alchemy/AWS/DynamoDB"; -+import * as Console from "effect/Console"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -+import * as Stream from "effect/Stream"; -// ... - -const table = yield* DynamoDB.Table("Items", { /* ... */ }); -const putItem = yield* DynamoDB.PutItem(table); -const getItem = yield* DynamoDB.GetItem(table); - -+yield* DynamoDB.consumeTableChanges(table, (stream) => -+ stream.pipe( -+ Stream.runForEach((record) => -+ Console.log(`${record.eventName}: ${record.dynamodb.Keys?.id?.S}`), -+ ), -+ ), -+); + alchemy 2.0.0-beta.87 @ d1f364a --> + +# DynamoDB Streams + +> How a DynamoDB Stream records every change to a table in order, what each change record carries, and how a Function consumes changes and checkpoints at the first failure. + +A DynamoDB Stream is a table's own change log. Every insert, update and delete becomes a **change record**, kept for 24 hours, in the order the changes happened to each item. A Function reading the stream sees every change to the table, including ones made by code that never told anyone. + +## Every write becomes a change record + +The table writes the record as part of the change, so there's no second write to forget or to fail. Records for one item stay in order. Records for different items may be read in parallel. + + + +Each record says what happened, `INSERT`, `MODIFY` or `REMOVE`, the item's keys, and, depending on the stream's **view type**, the item as it was before, after, or both. + +## Subscribe to a table + +Subscribe a Function from Construction. Each invocation receives a batch of change records: + +```typescript title="src/indexer.ts" +export default class Indexer extends AWS.Lambda.Function()( + "Indexer", + { main: import.meta.url, functionUrl: false }, + Effect.gen(function* () { + const orders = yield* Orders; + yield* AWS.DynamoDB.consumeTableChanges(orders, (event) => + Effect.forEach( + event.Records, + (record) => Console.log(`${record.eventName}: ${record.dynamodb.Keys?.pk?.S}`), + { discard: true }, + ), + ); + return {}; + }).pipe(Effect.provide(AWS.Lambda.TableEventSource)), +) {} ``` -That single `consumeTableChanges(...)` call enables a stream on the table, -creates a Lambda `EventSourceMapping` that polls it, and adds -the IAM grants for `dynamodb:GetRecords`, `GetShardIterator`, -`DescribeStream`, and `ListStreams` — all from the call site. +There's nothing to turn on first. Deploy enables the stream on the table, creates the event source mapping, and grants the Function read access to the stream. -## Pick the view type +## Choose what each record carries -By default the stream emits keys only. Most handlers want the -full row before and after the change — set `streamViewType` to -`NEW_AND_OLD_IMAGES`: +By default a record carries the item's keys. Ask for the item itself with `streamViewType`: -```diff lang="typescript" --yield* DynamoDB.consumeTableChanges(table, (stream) => -+yield* DynamoDB.consumeTableChanges(table, { -+ streamViewType: "NEW_AND_OLD_IMAGES", -+}, (stream) => - stream.pipe(/* ... */), -); +```typescript title="src/indexer.ts" +yield* AWS.DynamoDB.consumeTableChanges(orders, { streamViewType: "NEW_AND_OLD_IMAGES" }, handle); ``` -The other options (`KEYS_ONLY`, `NEW_IMAGE`, `OLD_IMAGE`) trade -payload size for less detail — pick the smallest one your -handler actually needs. - -## Control where consumption starts - -`startingPosition: "LATEST"` is the default and ignores history; -the consumer only sees records that arrive after the -event-source mapping is enabled. Switch to `"TRIM_HORIZON"` to -replay everything currently in the stream's 24-hour retention -window: - -```diff lang="typescript" -yield* DynamoDB.consumeTableChanges(table, { - streamViewType: "NEW_AND_OLD_IMAGES", -+ startingPosition: "TRIM_HORIZON", -+ batchSize: 10, -}, (stream) => - stream.pipe(/* ... */), -); -``` +`NEW_IMAGE` carries the item after the change, `OLD_IMAGE` before it, and `NEW_AND_OLD_IMAGES` both, which lets a consumer see exactly which attributes changed. Pick the smallest one your consumer needs. -`batchSize` caps the number of records the function sees per -invocation. Larger batches are more efficient; smaller batches -fail in smaller blast radii. - -## Type the row payload - -DynamoDB stream records use the same attribute-value shape as -`GetItem`/`PutItem`. Describe the row inline as a generic on -`consumeTableChanges` and TypeScript will help you destructure -`NewImage`/`OldImage`: - -```diff lang="typescript" --yield* DynamoDB.consumeTableChanges(table, { -+yield* DynamoDB.consumeTableChanges<{ id: { S: string }; content: { S: string } }>(table, { - streamViewType: "NEW_AND_OLD_IMAGES", - startingPosition: "TRIM_HORIZON", - batchSize: 10, -}, (stream) => - stream.pipe( - Stream.runForEach((record) => -- Console.log(`${record.eventName}: ${record.dynamodb.Keys?.id?.S}`), -+ Console.log( -+ `${record.eventName}: ${record.dynamodb.Keys?.id?.S} -> ` + -+ `${record.dynamodb.NewImage?.content.S ?? "(deleted)"}`, -+ ), - ), - ), -); -``` +The images are in DynamoDB's attribute format. Type the event with your item's shape to read them: -## Provide the runtime layer - -The Lambda-specific implementation of `TableEventSource` is in -`Lambda.TableEventSource`. Add it to the merged layer: - -```diff lang="typescript" -}).pipe( - Effect.provide( - Layer.mergeAll( - AWS.Lambda.BucketEventSource, -+ AWS.Lambda.TableEventSource, - DynamoDB.GetItemHttp, - DynamoDB.PutItemHttp, - S3.PutObjectHttp, - S3.GetObjectHttp, - ), - ), -), +```typescript title="src/indexer.ts" +(event: AWS.DynamoDB.StreamEvent<{ pk: { S: string }; total: { N: string } }>) => + Effect.forEach( + event.Records, + (record) => Console.log(record.dynamodb.NewImage?.total.N ?? "(deleted)"), + { discard: true }, + ) ``` -`TableEventSource` is the binding that mutates the table's stream -configuration during deploy and creates the event source mapping. -You don't have to think about either — they're both side effects -of `consumeTableChanges(...)`. +## Start from the right place -## Deploy +A new subscription starts with changes made after it exists, `startingPosition: "LATEST"`. To process what the stream still holds from the last 24 hours, start from `"TRIM_HORIZON"`: -```sh -bun alchemy deploy +```typescript title="src/indexer.ts" +yield* AWS.DynamoDB.consumeTableChanges( + orders, + { streamViewType: "NEW_IMAGE", startingPosition: "TRIM_HORIZON", batchSize: 10 }, + handle, +); ``` -Alchemy enables the stream on the table (takes a few seconds for -the table to settle) then creates the event source mapping. Once -the mapping is `Enabled`, every `PutItem`/`UpdateItem`/`DeleteItem` -shows up in your function's CloudWatch logs. +`batchSize` caps the records per invocation. Larger batches cost fewer invocations. Smaller ones retry less work when one fails. -## Verify +## Checkpoint at the first failure -Reuse the `PUT /items/:id` route to publish changes, then tail -the function logs to confirm they arrive: +Lambda moves its place in the stream forward after each batch succeeds. When a batch fails, the batch is retried, and changes behind it wait, so they're never applied out of order. -```sh -bun alchemy logs Api --tail -``` - -In another terminal: +Report the first record that failed instead, and Lambda keeps everything before it: -```sh -curl -X PUT --data 'first' "$URL/items/one" -curl -X PUT --data 'second' "$URL/items/two" -curl -X PUT --data 'updated' "$URL/items/one" +```typescript title="src/indexer.ts" +(event) => + Effect.gen(function* () { + for (const record of event.Records) { + const ok = yield* writeToIndex(record).pipe( + Effect.as(true), + Effect.catchCause(() => Effect.succeed(false)), + ); + if (!ok) return { batchItemFailures: [{ itemIdentifier: record.dynamodb.SequenceNumber! }] }; + } + }) ``` -You'll see three `MODIFY`/`INSERT` log lines stream past — one -per write. Stream records typically arrive within 1–2 seconds of -the originating change. - -## Why a Stream instead of a callback? +A record that can never succeed blocks the stream for its items until it expires. Catch errors that retrying won't fix, and move on. -The `consumeTableChanges(table, handler)` signature mirrors the S3 -events helper for a reason — once your event source is a typed `Stream`, -back-pressure, batching, retries, parallel side effects, and -in-order processing are all just composition: - -```typescript -stream.pipe( - Stream.groupedWithin(50, "5 seconds"), - Stream.mapEffect((batch) => writeToWarehouse(batch), { concurrency: 4 }), - Stream.runDrain, -); -``` +## What streams are for -The same operators work for DynamoDB Streams, S3 events, SQS -messages, and Kinesis records — the only thing that changes is -the element type. +Use a stream to keep something else in step with the table: a search index, a cache, a copy in a warehouse, a running total. Use it to react to changes, like sending an email when an order's status becomes `shipped`, without the code that changed it having to know. -Next we'll add an [SQS Queue](/aws/messaging/sqs) so the Lambda -can fan changes (or anything else) out to a different consumer -process and pick them up downstream. +To hand changes to other consumers, forward them to a [Queue](/aws/messaging/sqs#send-many-messages-at-once) or a [Topic](/aws/messaging/sns). For an ordered stream your code writes to directly, use [Kinesis](/aws/messaging/kinesis). diff --git a/.agents/skills/alchemy/references/aws/messaging/eventbridge.md b/.agents/skills/alchemy/references/aws/messaging/eventbridge.md index 6ded74f0..6d379146 100644 --- a/.agents/skills/alchemy/references/aws/messaging/eventbridge.md +++ b/.agents/skills/alchemy/references/aws/messaging/eventbridge.md @@ -1,309 +1,147 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # EventBridge & Scheduler -> Route application and AWS events through EventBridge buses and rules, consume them in Lambda as typed streams, and run cron/rate schedules against Lambda, SQS, and ECS with EventBridge Scheduler. +> How EventBridge buses route events to targets by matching their content, how runtimes publish and consume events, and how EventBridge Scheduler runs Functions, Queues and tasks on a schedule. -**EventBridge** is AWS's event router — producers publish events onto -a bus, rules match them by pattern, and targets receive them. -**EventBridge Scheduler** is its time-based sibling: fire an -invocation on a `rate(...)`, `cron(...)`, or one-time `at(...)` -expression. In Alchemy the surface is: +EventBridge routes **events**. A producer puts an event on a **bus**, and **rules** on the bus look at its content and send it to whichever **targets** match. Producers don't know the targets, and targets don't know each other, so new reactions to an event are added as new rules. -- `EventBridge.EventBus` and `EventBridge.Rule` — the raw resources. -- `EventBridge.PutEvents` — a producer binding that grants - `events:PutEvents` on the bus you publish to. -- `EventBridge.consumeBusEvents` — subscribe a Lambda to a pattern as - a typed `Stream`, creating the rule and invoke permission for you. -- `EventBridge.events(bus, pattern).toLambda/.toQueue/.toEcsTask` — - route matching events to a target with no handler code. -- `Scheduler.every/cron/at` — chainable schedule builders that - synthesize the target's IAM role. -- `ECS.every` — run a Fargate task on a schedule. +AWS services publish their own events to every account's default bus: an object created, an instance stopped, a task that failed. **EventBridge Scheduler** is the same idea driven by time: it invokes a target on a rate, a cron expression or a single date. -## Create an event bus +## Rules match events by content -An event bus is a one-line resource. Declare it in a shared module so -producers and consumers can reference the same handle: +Every event has a `source`, a `detail-type` and a JSON `detail`. A rule's **event pattern** lists the values it matches, and a matching event goes to the rule's targets: -```typescript -// src/bus.ts -import * as AWS from "alchemy/AWS"; + -export const Events = AWS.EventBridge.EventBus("Events", {}); +A pattern can match on any field of the event, including fields inside `detail`, so a rule can take only the orders over a certain amount, or only the ones from one region. Events that match no rule are dropped. + +## Declare a bus + +```typescript title="src/bus.ts" +import * as AWS from "@alchemy.run/aws"; + +export const Orders = AWS.EventBridge.EventBus("Orders", {}); ``` -No name required — Alchemy generates one from the app, stage, and -logical ID. The name `default` is reserved: to target the account's -**default bus** (where AWS service events land), simply omit the bus -argument in the APIs below. +Your own events go on a bus of your own. The account's **default bus**, where AWS services publish, needs no declaration: leave the bus out of the calls below to use it. -## Publish events from a Lambda +## Publish events -`EventBridge.PutEvents(bus)` returns a callable Effect and quietly -attaches an `events:PutEvents` policy statement scoped to the bus ARN -(or the default bus, if you pass nothing): +Bind `EventBridge.PutEvents` to the bus. Its role gets `events:PutEvents` on that bus only: -```typescript -// src/api.ts -import * as AWS from "alchemy/AWS"; -import * as Effect from "effect/Effect"; -import * as HttpServerResponse from "effect/http/HttpServerResponse"; -import { Events } from "./bus.ts"; +```typescript title="src/api.ts" +const bus = yield* Orders; +const putEvents = yield* AWS.EventBridge.PutEvents(bus); -export default class Api extends AWS.Lambda.Function()( - "Api", - { main: import.meta.url, functionUrl: true }, - Effect.gen(function* () { - const bus = yield* Events; - const putEvents = yield* AWS.EventBridge.PutEvents(bus); - - return { - fetch: Effect.gen(function* () { - yield* putEvents({ - Entries: [ - { - Source: "app.orders", - DetailType: "OrderPlaced", - Detail: JSON.stringify({ orderId: "o-1" }), - }, - ], - }).pipe(Effect.orDie); - return HttpServerResponse.empty({ status: 202 }); - }), - }; - }).pipe(Effect.provide(AWS.EventBridge.PutEventsHttp)), -) {} +yield* putEvents({ + Entries: [{ Source: "app.orders", DetailType: "OrderPlaced", Detail: JSON.stringify({ orderId }) }], +}); ``` -Entries carry a `Source`, a `DetailType`, and a JSON-encoded `Detail` -— the three fields rules match on. The `EventBusName` is filled in -from the bus you bound, so entries never repeat it. -`AWS.EventBridge.PutEventsHttp` is the runtime layer that implements -the binding over the EventBridge API. - -## Consume events in a Lambda +Provide `AWS.EventBridge.PutEventsHttp` to the runtime. The bus name is filled in from the binding. -`consumeBusEvents` is the consumer-side mirror of -`SQS.consumeQueueMessages`: pass the bus, an event pattern, and a -handler that receives matching events as a typed `Stream`: +## Consume events in a Function -```typescript -// src/worker.ts -import * as AWS from "alchemy/AWS"; -import * as Effect from "effect/Effect"; -import * as Stream from "effect/Stream"; -import { Events } from "./bus.ts"; +Subscribe a Lambda Function to a pattern from Construction. Matching events arrive as a `Stream`: +```typescript title="src/worker.ts" export default class Worker extends AWS.Lambda.Function()( - "OrdersWorker", - { main: import.meta.url }, + "Worker", + { main: import.meta.url, functionUrl: false }, Effect.gen(function* () { - const bus = yield* Events; - + const bus = yield* Orders; yield* AWS.EventBridge.consumeBusEvents( bus, { source: ["app.orders"], "detail-type": ["OrderPlaced"] }, - (events) => - Stream.runForEach(events, (event) => - Effect.log(`order placed: ${JSON.stringify(event.detail)}`), - ), + (events) => Stream.runForEach(events, (event) => Effect.log(event.detail)), ); - return {}; }).pipe(Effect.provide(AWS.Lambda.EventSource)), ) {} ``` -That single call does the infrastructure work at deploy time — an -EventBridge `Rule` with the pattern targeting this function, plus the -Lambda permission that lets `events.amazonaws.com` invoke it — and at -runtime filters incoming invocations against the same pattern before -feeding them into your stream. Omit the `bus` argument to subscribe to -the default bus, which is where AWS service events (S3, EC2, ECS -state changes, …) arrive. +Deploy creates the rule and the Lambda permission that lets EventBridge invoke the Function. Each event's `detail` is `unknown` until you narrow the stream to the type you expect, `AWS.EventBridge.EventRecord`. -`AWS.Lambda.EventSource` is the Lambda runtime implementation of the -EventBridge event source — provide it at the bottom of the function -like any other event source layer. +## Route events without code -### Type the event detail +Some targets need no handler of your own: a Queue to buffer events, an ECS task to process them. `EventBridge.events` builds the rule and sends matches straight to the target: -Events are `EventRecord` with `Detail` defaulting to -`unknown`. Narrow the stream when you know the payload shape: - -```typescript -type OrderPlaced = { orderId: string }; - -yield* AWS.EventBridge.consumeBusEvents( - bus, - { source: ["app.orders"], "detail-type": ["OrderPlaced"] }, - (events) => - Stream.runForEach( - events as Stream.Stream>, - (event) => Effect.log(`order: ${event.detail.orderId}`), - ), -); +```typescript title="alchemy.run.ts" +yield* AWS.EventBridge.events(bus, { source: ["app.orders"] }).toQueue(audit); ``` -## Route events without a handler +`.toQueue` adds a statement to the Queue's policy letting this rule send to it. `.toLambda` adds the invoke permission, and `.toEcsTask` creates a role that may run the task. Each grant is limited to the one rule. -Not every consumer is code you own. `EventBridge.events(bus, pattern)` -builds a route — chain `.toLambda`, `.toQueue`, or `.toEcsTask` to -deliver matching events to a target resource, permissions included: +For input transformers, retry policies, dead-letter queues or several targets on one rule, declare an `AWS.EventBridge.Rule` yourself. A raw rule grants nothing, so give its targets a role or a resource policy. -```typescript -// alchemy.run.ts -yield* AWS.EventBridge.events(bus, { source: ["app.orders"] }) - .toQueue(auditQueue); -``` +## React to AWS's own events -Each target wires its own access: `.toQueue` attaches a queue policy -allowing `events.amazonaws.com` to `sqs:SendMessage` (conditioned on -the rule's ARN), `.toLambda` adds the invoke permission, and -`.toEcsTask` creates an IAM role with `ecs:RunTask` and `iam:PassRole` -for the task's roles. Pass a string as the first argument to name the -backing rule deterministically instead of deriving it from the -pattern hash. - -## Rules directly - -The helpers above all bottom out in the `Rule` resource. Reach for it -directly when you need full control — input transformers, dead-letter -queues, retry policies, or up to five targets per rule: - -```typescript -const rule = yield* AWS.EventBridge.Rule("ObjectCreated", { - eventPattern: { - source: ["aws.s3"], - "detail-type": ["Object Created"], - }, - targets: [{ Id: "Jobs", Arn: queue.queueArn }], -}); -``` +AWS services publish to the default bus whenever something happens in your account. Match their `source` to react to them, leaving the bus out: -A rule needs an `eventPattern` or a `scheduleExpression` (rules also -accept `rate(...)`/`cron(...)` expressions, though Scheduler below is -the better tool for time-based work). Omitting `eventBusName` puts -the rule on the default bus. Unlike the `events(...)` helpers, a raw -`Rule` does **not** grant the target-side permissions — supply a -target `RoleArn` or resource policy yourself. +```typescript title="src/worker.ts" +yield* AWS.EventBridge.consumeBusEvents( + { source: ["aws.ecs"], "detail-type": ["ECS Task State Change"] }, + (events) => Stream.runForEach(events, (event) => Effect.log(event.detail)), +); +``` -## Scheduled jobs with Scheduler +This is how you watch for failed tasks, stopped instances or new objects without polling anything. -`AWS.Scheduler` exposes chainable builders. The simplest form invokes -a Lambda on a fixed rate: +## Run things on a schedule -```typescript -// alchemy.run.ts -const api = yield* Api; +EventBridge Scheduler invokes a target on a schedule. `Scheduler.every` takes a plain duration: -yield* AWS.Scheduler.every("5 minutes").toLambda(api); +```typescript title="alchemy.run.ts" +const report = yield* Report; +yield* AWS.Scheduler.every("5 minutes").toLambda(report); ``` -`every` accepts a plain-English duration (normalized to -`rate(5 minutes)`) or a full `rate(...)`/`cron(...)` expression -as-is. The builder synthesizes the piece Scheduler always demands — -an execution role assumable by `scheduler.amazonaws.com` with -`lambda:InvokeFunction` on exactly that function — then creates the -`Scheduler.Schedule` resource. +The schedule needs a role that Scheduler can assume and that may invoke the Function. The builder creates it, with `lambda:InvokeFunction` on that Function only. -Cron schedules take an options object with a timezone, and `.named` -pins the schedule's name: +For a time of day, use `cron` with a timezone, and pass an input: -```typescript -yield* AWS.Scheduler - .cron("cron(0 3 * * ? *)", { timezone: "America/New_York" }) +```typescript title="alchemy.run.ts" +yield* AWS.Scheduler.cron("cron(0 3 * * ? *)", { timezone: "America/New_York" }) .named("nightly-report") - .toLambda(api, { input: { job: "nightly-report" } }); + .toLambda(report, { input: { job: "nightly-report" } }); ``` -`input` is delivered as the invocation payload (objects are -JSON-stringified for you); `retryPolicy` and `deadLetterConfig` are -also accepted per target. - -One-time schedules use `at(date)`, and `.toQueue` sends a payload to -SQS instead of invoking a function: +For a single moment, use `at`. Schedules can target Queues too: -```typescript -yield* AWS.Scheduler - .at(new Date("2026-08-01T09:00:00Z")) - .toQueue(queue, { type: "launch.reminder" }); +```typescript title="alchemy.run.ts" +yield* AWS.Scheduler.at(new Date("2026-08-01T09:00:00Z")).toQueue(reminders, { type: "launch" }); ``` -Builder options cover the rest of the Scheduler feature set — -`group` (a `Scheduler.ScheduleGroup`), `startDate`/`endDate`, -`flexibleTimeWindow`, `state`, `kmsKeyArn`, and -`actionAfterCompletion` for one-time schedules. - -### The Schedule resource directly - -The builders materialize `Scheduler.Schedule` under the hood. Use it -directly when you bring your own role: - -```typescript -const schedule = yield* AWS.Scheduler.Schedule("Poll", { - scheduleExpression: "rate(1 hour)", - flexibleTimeWindow: { Mode: "OFF" }, - target: { - Arn: queue.queueArn, - RoleArn: role.roleArn, - }, -}); -``` - -The `RoleArn` must trust `scheduler.amazonaws.com`. Alchemy retries -the creation while the freshly-created IAM role propagates, so a role -declared in the same deploy just works. - -## ECS scheduled tasks +## Schedule containers -For jobs too heavy for Lambda, `AWS.ECS.every` runs a Fargate task on -a schedule — cron-as-a-container: +A job that runs too long for Lambda runs as an ECS task on a schedule instead: -```typescript -yield* AWS.ECS.every("HourlyJob", "1 hour", { - cluster, - task: jobTask, - subnets: [privateSubnet1.subnetId, privateSubnet2.subnetId], - securityGroups: [jobSecurityGroup.groupId], -}); -``` - -`cluster` and `task` are the outputs of `AWS.ECS.Cluster` and -`AWS.ECS.Task` (see [ECS](/aws/compute/ecs) for standing those up). Under the -hood this is `Scheduler.every(...).named("HourlyJob").toEcsTask(...)`: -a schedule plus an execution role with `ecs:RunTask` on the task -definition and `iam:PassRole` for its task and execution roles. Plain -durations normalize to `rate(...)`; full `cron(...)` expressions pass -through unchanged: - -```typescript +```typescript title="alchemy.run.ts" yield* AWS.ECS.every("NightlyJob", "cron(0 3 * * ? *)", { cluster, task: nightlyTask, - subnets: [privateSubnet1.subnetId, privateSubnet2.subnetId], + subnets: network.privateSubnetIds, securityGroups: [jobSecurityGroup.groupId], - taskCount: 3, - input: JSON.stringify({ source: "scheduler" }), }); ``` -Tasks launch as Fargate with no public IP by default -(`assignPublicIp: true` to change that), `taskCount` copies per tick, -and an optional static `input` forwarded to the task. - -## Where next - -- [Lambda](/aws/compute/lambda) — the runtime both the consumer and scheduled - targets above deploy to. -- [SNS](/aws/messaging/sns) — pub/sub fan-out when you want subscriptions - rather than pattern-matching rules. -- [ECS](/aws/compute/ecs) — the cluster, task, and networking that - `ECS.every` schedules onto. -- [`EventBus`](/providers/aws/eventbridge/eventbus), - [`Rule`](/providers/aws/eventbridge/rule), and - [`Schedule`](/providers/aws/scheduler/schedule) references — every - prop and attribute. +The schedule gets a role that may run the task and pass its roles. See [ECS](/aws/compute/ecs). + +## EventBridge, SNS or SQS + +Use EventBridge when many kinds of events share one bus and different parts of the app care about different ones, or when you react to AWS's own events and schedules. Use an [SNS Topic](/aws/messaging/sns) for one channel whose every message goes to every subscriber. Use an [SQS Queue](/aws/messaging/sqs) to buffer work for one consumer. diff --git a/.agents/skills/alchemy/references/aws/messaging/kinesis.md b/.agents/skills/alchemy/references/aws/messaging/kinesis.md index 5419c948..8d376ea5 100644 --- a/.agents/skills/alchemy/references/aws/messaging/kinesis.md +++ b/.agents/skills/alchemy/references/aws/messaging/kinesis.md @@ -1,300 +1,111 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Kinesis -> Add a Kinesis Data Stream, publish records from one Lambda, and consume them in order from another — wired through the same Stream-shaped event source. +> How Kinesis Data Streams keep records in order per partition key across shards, how runtimes write records and consume them in batches, and how retention, replay and checkpoints work. -**Kinesis Data Streams** are the tool for **ordered**, sharded, -high-throughput data: delivery in order within a partition, -replay from arbitrary points in time, and multiple independent -consumers reading the same records. In Alchemy it's the `Stream` -resource plus producer bindings (`PutRecord`, `PutRecords`, and -the sink-shaped `StreamSink`) and a consumer side: -`Kinesis.consumeStreamRecords` subscribes a Lambda to the stream -as a typed Effect `Stream`, creating the event source mapping -and granting the read permissions for you. Reach for -[SQS](/aws/messaging/sqs) instead when the work is unordered. +Kinesis Data Streams is an ordered log of **records**. Producers append records, and they stay in the stream for a retention period, 24 hours by default, whether or not anyone has read them. Consumers read the log in order, each keeping its own place, so several consumers can read the same records independently and any of them can go back and read again. -The walkthrough below builds on the [Lambda](/aws/compute/lambda), -[DynamoDB](/aws/data/dynamodb), and [SQS](/aws/messaging/sqs) pages: it adds a -Kinesis stream, publishes to it from the producer Lambda, and -consumes it from a new worker. +## Shards keep records in order -## Add the stream +A stream is split into **shards**. Each record carries a **partition key**, and Kinesis sends every record with the same key to the same shard. Within a shard, records are kept in the order they arrived. -Lift the Kinesis stream into a shared module the same way you -did with the SQS queue, so both producer and consumer can + -```typescript -// src/stream.ts -import * as Kinesis from "alchemy/AWS/Kinesis"; +So the guarantee is per key: every event for `order#1` arrives in the order it happened. Events for different orders may interleave. Choose the partition key as the thing whose history must stay in order, usually an entity's id. -export const Events = Kinesis.Stream("Events", { - streamMode: "ON_DEMAND", -}); -``` - -`"ON_DEMAND"` lets AWS auto-scale the shards based on load — -fine for the example. Switch to `"PROVISIONED"` with an explicit -`shardCount` when you know your throughput. - -## Bind PutRecord on the producer +## Declare a stream -```diff lang="typescript" -// src/api.ts -import * as DynamoDB from "alchemy/AWS/DynamoDB"; -+import * as Kinesis from "alchemy/AWS/Kinesis"; -import * as S3 from "alchemy/AWS/S3"; -import * as SQS from "alchemy/AWS/SQS"; -import { Jobs } from "./queue.ts"; -+import { Events } from "./stream.ts"; -// ... +```typescript title="src/events.ts" +import * as AWS from "@alchemy.run/aws"; -const queue = yield* Jobs; -+const events = yield* Events; -const sendMessage = yield* SQS.SendMessage(queue); -+const putRecord = yield* Kinesis.PutRecord(events); +export const Events = AWS.Kinesis.Stream("Events", { streamMode: "ON_DEMAND" }); ``` -The shape mirrors every other binding you've seen: `PutRecord(stream)` -returns a callable Effect, plus an IAM policy with -`kinesis:PutRecord` scoped to this stream's ARN. - -## Publish a record - -Use `putRecord` inside the `PUT /items/:id` route — alongside -the SQS publish — to send an ordered audit record for each -write: - -```diff lang="typescript" -yield* sendMessage({ - MessageBody: JSON.stringify({ type: "job.created", id, content }), -}); -+yield* putRecord({ -+ PartitionKey: id, -+ Data: new TextEncoder().encode( -+ JSON.stringify({ type: "job.created", id, content, at: Date.now() }), -+ ), -+}); -``` - -`PartitionKey` controls which shard a record lands in. All -records with the same partition key are delivered in order to -the same consumer instance — the entity id is exactly what you -want here. - -`Data` is an arbitrary `Uint8Array`, not a string. JSON-encoded -UTF-8 bytes are the most common payload but you can ship Avro, -protobuf, or raw blobs without changing the binding. - -## Provide the runtime layer - -```diff lang="typescript" -}).pipe( - Effect.provide( - Layer.mergeAll( - // ... existing layers ... -+ Kinesis.PutRecordHttp, - SQS.SendMessageHttp, - ), - ), -), -``` +On-demand streams add and remove shards with load, and you pay for the data you write and read. With `streamMode: "PROVISIONED"` you set `shardCount` yourself, and pay per shard per hour, which is cheaper at steady, known throughput. -## Stand up a consumer Lambda +Keep records longer than a day with `retentionPeriod`, up to a year, so a new consumer or a fixed bug can replay further back. -Create `src/audit.ts` with a bare consumer shell — no event -source yet, just the empty class importing the shared stream -handle: +## Write records -```typescript -// src/audit.ts -import * as AWS from "alchemy/AWS"; -import * as Effect from "effect/Effect"; -import { Events } from "./stream.ts"; +Bind `Kinesis.PutRecord` in the producer. Its role gets `kinesis:PutRecord` on this stream: -export default class Audit extends AWS.Lambda.Function()( - "Audit", - { main: import.meta.url }, - Effect.gen(function* () { - const events = yield* Events; - return {}; - }), -) {} +```typescript title="src/api.ts" +const putRecord = yield* AWS.Kinesis.PutRecord(Events); +yield* putRecord({ + PartitionKey: orderId, + Data: new TextEncoder().encode(JSON.stringify({ type: "order.paid", orderId })), +}); ``` -## Subscribe to records +`Data` is bytes, so JSON, Avro or protobuf all work. Provide `AWS.Kinesis.PutRecordHttp` to the runtime. To write up to 500 records in one call, bind `Kinesis.PutRecords`. To write a whole `Stream`, bind `Kinesis.StreamSink`. -`Kinesis.consumeStreamRecords(stream, ...)` mirrors the -[SQS `consumeQueueMessages(...)`](/aws/messaging/sqs) shape. -Add the smallest possible subscription — log each record's -partition key: +## Consume records -```diff lang="typescript" -// src/audit.ts -import * as AWS from "alchemy/AWS"; -+import * as Kinesis from "alchemy/AWS/Kinesis"; -+import * as Console from "effect/Console"; -import * as Effect from "effect/Effect"; -+import * as Stream from "effect/Stream"; -import { Events } from "./stream.ts"; +A Lambda Function consumes a stream by subscribing from Construction. Lambda reads each shard in order and invokes the Function with batches: +```typescript title="src/audit.ts" export default class Audit extends AWS.Lambda.Function()( "Audit", - { main: import.meta.url }, + { main: import.meta.url, functionUrl: false }, Effect.gen(function* () { const events = yield* Events; -+ -+ yield* Kinesis.consumeStreamRecords(events, { -+ startingPosition: "LATEST", -+ batchSize: 100, -+ }, (stream) => -+ stream.pipe( -+ Stream.runForEach((record) => -+ Console.log(`[${record.kinesis.partitionKey}]`), -+ ), -+ ), -+ ); - + yield* AWS.Kinesis.consumeStreamRecords( + events, + { startingPosition: "LATEST", batchSize: 100 }, + (event) => + Effect.forEach( + event.Records, + (record) => + Console.log(new TextDecoder().decode(Buffer.from(record.kinesis.data, "base64"))), + { discard: true }, + ), + ); return {}; - }), + }).pipe(Effect.provide(AWS.Lambda.StreamEventSource)), ) {} ``` -`batchSize: 100` lets Lambda gather up to 100 records per -invocation; the whole batch is delivered as one stream emission -sequence, then the stream completes and Lambda checkpoints. -`startingPosition: "LATEST"` skips history — switch to -`"TRIM_HORIZON"` to replay the 24-hour retention window. - -## Decode the binary payload +Each record's data arrives base64-encoded in the event, so decode it first. Deploy creates the event source mapping and grants the Function read access to the stream. -Kinesis record data arrives base64-encoded inside the Lambda -envelope (an artifact of the event shape, not the stream -itself). Decode it back to bytes and on to a string, and run -the work as an Effect per record: +`startingPosition: "LATEST"` starts with records written after the subscription exists. `"TRIM_HORIZON"` starts with the oldest record still retained, replaying everything the stream holds. -```diff lang="typescript" -yield* Kinesis.consumeStreamRecords(events, { - startingPosition: "LATEST", - batchSize: 100, -}, (stream) => - stream.pipe( -- Stream.runForEach((record) => -- Console.log(`[${record.kinesis.partitionKey}]`), -- ), -+ Stream.mapEffect((record) => -+ Effect.gen(function* () { -+ const text = new TextDecoder().decode( -+ Buffer.from(record.kinesis.data, "base64"), -+ ); -+ yield* Console.log(`[${record.kinesis.partitionKey}] ${text}`); -+ }), -+ ), -+ Stream.runDrain, - ), -); -``` +## Checkpoint at the first failure -## Provide the runtime layer +Lambda moves a shard's **checkpoint** forward after each batch succeeds. If a batch fails, the whole batch is retried, and the shard waits. Nothing behind it is processed until it succeeds, because skipping ahead would break the order. -`Lambda.StreamEventSource` is the binding that enables the event -source mapping and grants `kinesis:GetRecords`, -`GetShardIterator`, `DescribeStream`, and `ListShards` on the -stream ARN. Provide it at the bottom of the function: +Report the first record that failed instead, and Lambda checkpoints everything before it and retries from there: -```diff lang="typescript" - return {}; -- }), -+ }).pipe(Effect.provide(AWS.Lambda.StreamEventSource)), -) {} -``` - -## Wire the consumer into the Stack - -```diff lang="typescript" -// alchemy.run.ts -import Api from "./src/api.ts"; -+import Audit from "./src/audit.ts"; -import Worker from "./src/worker.ts"; - -Effect.gen(function* () { - const api = yield* Api; - yield* Worker; -+ yield* Audit; - return { url: api.functionUrl }; -}), -``` - -## Deploy - -```sh -bun alchemy deploy -``` - -Three functions now coexist: `Api` produces records, `Worker` -consumes the SQS queue, and `Audit` consumes the Kinesis stream. -Each one gets a least-privilege policy that names exactly the -resources its capability and `consume*` calls touched — no -`"*"`, no IAM JSON to maintain. - -## Verify - -```sh -curl -X PUT --data 'audit me' "$URL/items/k1" -bun alchemy logs Audit --tail -``` - -You'll see a line like: - -``` -[k1] {"type":"job.created","id":"k1","content":"audit me","at":1718000000000} -``` - -Subsequent writes against the same `id` (`k1`) all land in the -same shard and arrive in order at the same `Audit` invocation -context — that's the ordering guarantee Kinesis provides per -partition key. - -## Bonus: in-order side effects - -Because each batch is delivered as a `Stream`, **per-shard ordering -is preserved end-to-end**. If you need strict ordering for side -effects, drop the concurrency to 1 and let the stream do the work: - -```typescript -stream.pipe( - Stream.mapEffect( - (record) => persistInOrder(record).pipe(Effect.orDie), - { concurrency: 1 }, - ), - Stream.runDrain, -); +```typescript title="src/audit.ts" +(event) => + Effect.gen(function* () { + for (const record of event.Records) { + const ok = yield* handleRecord(record).pipe( + Effect.as(true), + Effect.catchCause(() => Effect.succeed(false)), + ); + if (!ok) return { batchItemFailures: [{ itemIdentifier: record.kinesis.sequenceNumber }] }; + } + }), ``` -Or fan out per-partition with `Stream.groupByKey(record => record.kinesis.partitionKey)` -when ordering only matters within a key. - -## What you've built +A record that can never succeed still blocks its shard until it expires. Catch errors that retrying won't fix, record them somewhere you'll see, and move on. -If you followed the whole section, you've gone from a single -Lambda to a small event-driven system: a public HTTP API backed -by S3 blobs and a DynamoDB table, table change events on a -stream, an SQS work queue, and a high-throughput Kinesis -pipeline — all wired through the same binding pattern, with IAM -policies that match exactly the operations you call. The same -`Stream`-shaped consumer surface drives every event source, so -adding more is a matter of declaring the resource and pointing -the matching `consume*` helper at it. +## Stream or queue -## Where next +Both carry work from producers to consumers. Use a stream when order matters per key, when several consumers read the same records, or when you want to replay history. Use an [SQS Queue](/aws/messaging/sqs) when each message is independent work for one consumer: a failed message there is retried on its own, without holding up the rest. -- [Process DynamoDB Streams](/aws/messaging/dynamodb-streams) — - change data capture with the same consumer surface. -- [React to S3 events](/aws/messaging/s3-events) — bucket - notifications as an Effect `Stream`. -- [`Stream` reference](/providers/aws/kinesis/stream) — - provisioned vs on-demand mode, retention, and every other - prop. +A table's own change log is a stream too. See [DynamoDB Streams](/aws/messaging/dynamodb-streams). diff --git a/.agents/skills/alchemy/references/aws/messaging/s3-events.md b/.agents/skills/alchemy/references/aws/messaging/s3-events.md index e91d94ff..2192ecfa 100644 --- a/.agents/skills/alchemy/references/aws/messaging/s3-events.md +++ b/.agents/skills/alchemy/references/aws/messaging/s3-events.md @@ -1,201 +1,104 @@ - -# React to S3 Events - -> Subscribe a Lambda Function to S3 bucket notifications, process them as an Effect Stream, and let Alchemy wire up the IAM and event-source plumbing. - -Reading and writing S3 objects on demand is one half of the story. -The other half is **reacting** to objects as they arrive — for -indexing, virus scanning, thumbnail generation, you name it. In -this part you'll subscribe the same Lambda from the previous part -to bucket notifications and process them as an Effect `Stream`. - -## Subscribe to bucket notifications - -Bucket notifications live behind an Alchemy helper: -`S3.consumeBucketEvents(bucket, process)`. Add the smallest -possible subscription — log every new object's key — alongside -the existing bindings: - -```diff lang="typescript" -// src/api.ts -import * as AWS from "alchemy/AWS"; -import * as S3 from "alchemy/AWS/S3"; -+import * as Console from "effect/Console"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -+import * as Stream from "effect/Stream"; -// ... - -Effect.gen(function* () { - const bucket = yield* S3.Bucket("Blobs"); - const putObject = yield* S3.PutObject(bucket); - const getObject = yield* S3.GetObject(bucket); - -+ yield* S3.consumeBucketEvents(bucket, (stream) => -+ stream.pipe( -+ Stream.runForEach((event) => -+ Console.log(`new object: ${event.key}`), -+ ), -+ ), -+ ); - - return { - fetch: /* ... unchanged ... */, - }; -}); -``` + alchemy 2.0.0-beta.87 @ d1f364a --> -That single `yield*` does three things in one shot: it -configures the bucket's notification settings to push events -into the function, adds the `lambda:InvokeFunction` permission -S3 needs to call you, and registers the stream handler that -runs every time an event batch lands. +# S3 events -## Filter the event types +> How a Bucket notifies a Function when objects are created or deleted, what each notification carries, and how to process notifications as an Effect Stream. -Without a filter you get every notification S3 emits — object -created, deleted, restored, replicated, the lot. Constrain the -subscription to a specific subset with `events`: +A Bucket can tell you when something happens to its objects. Each time an object is created, deleted or restored, S3 sends a **notification** naming the Bucket, the key and the event. A Function that receives them can make a thumbnail of every uploaded image, index every new document or scan every file for viruses, without the uploader doing anything but upload. -```diff lang="typescript" --yield* S3.consumeBucketEvents(bucket, (stream) => -+yield* S3.consumeBucketEvents( -+ bucket, -+ { events: ["s3:ObjectCreated:*"] }, -+ (stream) => - stream.pipe( - Stream.runForEach((event) => - Console.log(`new object: ${event.key}`), - ), - ), -); -``` +## S3 invokes the Function -The `events` filter is type-checked against the AWS S3 event -catalog, so typos surface at the call site rather than at deploy -time. - -## What the stream actually carries - -`stream` is a `Stream.Stream` — a normalized -shape with `type`, `bucket`, `key`, `size`, and `eTag`. Each -Lambda invocation delivers one batch as one stream emission -sequence, then completes; the next invocation starts a fresh -stream. Treating events as a `Stream` means the usual operators -(`mapEffect`, `groupedWithin`, `mapAccum`) work without thinking -about the Lambda payload envelope. - -## Provide the runtime layer - -The runtime side of the subscription lives in -`Lambda.BucketEventSource`. It's the layer that turns the abstract -`BucketEventSource` capability into a concrete Lambda event-source -mapping plus IAM grant. Add it alongside the S3 bindings: - -```diff lang="typescript" -}).pipe( - Effect.provide( -- Layer.mergeAll(S3.PutObjectHttp, S3.GetObjectHttp), -+ Layer.mergeAll( -+ AWS.Lambda.BucketEventSource, -+ S3.PutObjectHttp, -+ S3.GetObjectHttp, -+ ), - ), -), -``` +Notifications are pushed. S3 invokes the Function directly, with a batch of notifications, shortly after each change. -`BucketEventSource` and the `PutObject`/`GetObject` lives are all -peers here — none of them require each other — so a flat -`Layer.mergeAll(...)` is enough. + -## Run an Effect per event +S3 delivers each notification at least once, and occasionally more than once, so processing the same key twice should be safe. Write the thumbnail under a key derived from the original's, and a second run just replaces it. -Logging is a good smoke test, but a real handler usually wants -to do something async per event. Swap `runForEach` for -`mapEffect` so each event runs through a generator block: +## Subscribe a Function -```diff lang="typescript" -yield* S3.consumeBucketEvents( - bucket, - { events: ["s3:ObjectCreated:*"] }, - (stream) => - stream.pipe( -- Stream.runForEach((event) => -- Console.log(`new object: ${event.key}`), -- ), -+ Stream.mapEffect((event) => -+ Console.log(`new object: ${event.key}`), -+ ), -+ Stream.runDrain, -+ ), -); +Subscribe from the Function's Construction phase. Notifications arrive as a `Stream`: + +```typescript title="src/thumbnails.ts" +export default class Thumbnails extends AWS.Lambda.Function()( + "Thumbnails", + { main: import.meta.url, functionUrl: false }, + Effect.gen(function* () { + const uploads = yield* Uploads; + yield* AWS.S3.consumeBucketEvents(uploads, (stream) => + stream.pipe(Stream.runForEach((event) => Console.log(`${event.type}: ${event.key}`))), + ); + return {}; + }).pipe(Effect.provide(AWS.Lambda.BucketEventSource)), +) {} ``` -`Stream.runDrain` consumes the stream without collecting — we -only care about the side effects, not the return values. +Deploy adds the notification to the Bucket and the Lambda permission that lets S3 invoke the Function. Each notification carries its `type`, `bucket`, `key`, `size` and `eTag`. -## Read the object back +## Choose which events -`getObject` is already bound to the bucket, so the per-event -Effect can fetch the new object's contents inline: +Without a filter, the Function receives every kind of notification: created, removed, restored, replicated. Name the ones you want: -```diff lang="typescript" -stream.pipe( - Stream.mapEffect((event) => -- Console.log(`new object: ${event.key}`), -+ Effect.gen(function* () { -+ const result = yield* getObject({ Key: event.key }); -+ const body = yield* result.Body!.pipe( -+ Stream.decodeText, -+ Stream.mkString, -+ ); -+ yield* Console.log(`${event.key} -> ${body}`); -+ }).pipe(Effect.orDie), - ), - Stream.runDrain, -), +```typescript title="src/thumbnails.ts" +yield* AWS.S3.consumeBucketEvents(uploads, { events: ["s3:ObjectCreated:*"] }, (stream) => + stream.pipe(Stream.runForEach((event) => Console.log(event.key))), +); ``` -`Stream.mapEffect` is back-pressured by default — events flow -through one at a time. Pass a `concurrency` option (we'll see it -in later parts) when you want fan-out. +The event names are checked against S3's own list, so a typo fails to compile. -## Deploy and verify +## Process each object -```sh -bun alchemy deploy -``` +To read each new object, bind `S3.GetObject` to the same Bucket and run an Effect per notification: -The CLI applies the new bucket notification configuration and -redeploys the function with the broader IAM policy. Then trigger -the subscription end-to-end by `PUT`ing an object via the HTTP -route from the previous part: +```typescript title="src/thumbnails.ts" +const getObject = yield* AWS.S3.GetObject(uploads); -```typescript -// test/integ.test.ts -test( - "PUT triggers notification handler", - Effect.gen(function* () { - const { url } = yield* stack; - yield* HttpClient.put(`${url}/notify-me.txt`, { - body: HttpBody.text("payload"), - }); - // ...optionally tail CloudWatch logs to assert the message landed - }), +yield* AWS.S3.consumeBucketEvents(uploads, { events: ["s3:ObjectCreated:*"] }, (stream) => + stream.pipe( + Stream.mapEffect( + (event) => + getObject({ Key: event.key }).pipe( + Effect.flatMap((object) => makeThumbnail(event.key, object.Body!)), + Effect.orDie, + ), + { concurrency: 4 }, + ), + Stream.runDrain, + ), ); ``` -You'll see the `notify-me.txt -> payload` line in the function's -log group within a couple of seconds. +Provide `AWS.S3.GetObjectHttp` next to the event source. Here four objects are processed at a time. Leave out `concurrency` to take them one by one. + +A batch is one invocation. The stream ends when the batch is done, and the next invocation starts a new one. + +## Don't trigger yourself -S3 events typically arrive in batches of up to 10 records — the -same `Stream` is fed each batch and completes between invocations, -so you get the same composition story whether the batch is one -event or a hundred. +A Function that writes its output into the Bucket it watches will be notified about its own output. A thumbnail of an upload produces a new object, which produces a notification, which produces a thumbnail of the thumbnail. -Next we'll trade blob storage for structured records and -[add a DynamoDB table](/aws/data/dynamodb). +Write outputs to a second Bucket, or keep inputs and outputs under separate prefixes and ignore the output prefix: + +```typescript title="src/thumbnails.ts" +stream.pipe( + Stream.filter((event) => !event.key.startsWith("thumbnails/")), + Stream.runForEach((event) => Console.log(event.key)), +) +``` diff --git a/.agents/skills/alchemy/references/aws/messaging/sns.md b/.agents/skills/alchemy/references/aws/messaging/sns.md index b460d374..eef381ed 100644 --- a/.agents/skills/alchemy/references/aws/messaging/sns.md +++ b/.agents/skills/alchemy/references/aws/messaging/sns.md @@ -1,242 +1,99 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # SNS -> Create an SNS Topic, publish to it from a Lambda with the Publish binding, fan messages out to SQS queues, and consume notifications as a typed Stream. +> How SNS Topics broadcast one message to every subscriber, how to publish from a runtime, subscribe Functions and Queues, and filter what each subscriber receives. -**SNS** is AWS's pub/sub layer: publishers send a message to a -**topic** once, and SNS pushes a copy to every subscriber — -Lambda functions, SQS queues, HTTPS endpoints, email. In Alchemy -it's the `Topic` and `Subscription` resources, producer bindings -(`Publish`, `PublishBatch`, and the `Stream`-sink-shaped -`TopicSink`), and a consumer side: -`SNS.consumeTopicNotifications` subscribes a Lambda to the topic -as a typed `Stream` of notifications, creating the subscription -and invoke permission for you. +SNS broadcasts messages. A publisher sends a message to a **Topic** once, and SNS pushes a copy to every **subscription**: a Lambda Function, an SQS Queue, an HTTPS endpoint, an email address. The publisher doesn't know who's listening, so adding a subscriber never changes the code that publishes. -## Create a topic +## A Topic delivers a copy to everyone -```typescript -// src/topic.ts -import * as SNS from "alchemy/AWS/SNS"; +A [Queue](/aws/messaging/sqs) hands each message to one consumer. A Topic hands each message to every subscriber, each with its own copy. -export const Orders = SNS.Topic("Orders"); -``` - -No name required — Alchemy generates one from the app, stage, -and logical ID. Raw SNS topic attributes (delivery policies, -KMS keys, display names) go through the `attributes` prop: - -```typescript -export const Orders = SNS.Topic("Orders", { - attributes: { - DisplayName: "Order events", - }, -}); -``` - -FIFO topics are a flag: - -```typescript -export const OrdersFifo = SNS.Topic("OrdersFifo", { - fifo: true, - attributes: { - ContentBasedDeduplication: "true", - }, -}); -``` - -Changing `fifo` or the topic name **replaces** the topic — -everything else updates in place. + -## Publish from a Lambda +SNS pushes each copy as soon as it arrives and retries deliveries that fail. It doesn't store messages for later, so a subscriber that needs to work at its own pace, or survive being down for a while, subscribes through a Queue. -Bind `SNS.Publish(topic)` in the function's Construction phase and call -it from runtime handlers. The binding quietly attaches -`sns:Publish` scoped to the topic ARN to the function's -execution role: +## Declare a Topic -```typescript -// src/api.ts -import * as AWS from "alchemy/AWS"; -import * as SNS from "alchemy/AWS/SNS"; -import * as Effect from "effect/Effect"; -import * as HttpServerResponse from "effect/http/HttpServerResponse"; -import { Orders } from "./topic.ts"; +```typescript title="src/orders.ts" +import * as AWS from "@alchemy.run/aws"; -export default class Api extends AWS.Lambda.Function()( - "Api", - { main: import.meta.url, functionUrl: true }, - Effect.gen(function* () { - const topic = yield* Orders; - const publish = yield* SNS.Publish(topic); - - return { - fetch: Effect.gen(function* () { - const response = yield* publish({ - Message: JSON.stringify({ orderId: "o_123" }), - Subject: "OrderCreated", - }); - return yield* HttpServerResponse.json({ - id: response.MessageId, - }); - }).pipe(Effect.orDie), - }; - }).pipe(Effect.provide(SNS.PublishHttp)), -) {} +export const Orders = AWS.SNS.Topic("Orders"); ``` -`SNS.PublishHttp` is the runtime layer that backs the binding -with the SNS HTTP API — provide it on the function like any -other binding layer. - -## Publish in batches - -`SNS.PublishBatch(topic)` ships up to 10 messages per API call -(runtime layer: `SNS.PublishBatchHttp`): +For messages that must arrive in order and only once, make it a FIFO Topic, and subscribe FIFO Queues to it: -```typescript -const publishBatch = yield* SNS.PublishBatch(topic); - -// runtime -const response = yield* publishBatch({ - PublishBatchRequestEntries: messages.map((message, index) => ({ - Id: `${index}`, - Message: message, - })), +```typescript title="src/orders.ts" +export const Orders = AWS.SNS.Topic("Orders", { + fifo: true, + attributes: { ContentBasedDeduplication: "true" }, }); -// response.Successful / response.Failed ``` -## Forward a stream with `TopicSink` +Changing `fifo` replaces the Topic. Everything else updates in place. -If you have a `Stream` of payloads — DynamoDB change -records, SQS messages, anything — `SNS.TopicSink(topic)` is the -sink-shaped producer: it batches items and publishes each chunk -through `PublishBatch`: +## Publish -```typescript -const sink = yield* SNS.TopicSink(topic); +Bind `SNS.Publish` in the publisher. Its role gets `sns:Publish` on this Topic only: -// runtime -yield* Stream.fromIterable(payloads).pipe(Stream.run(sink)); +```typescript title="src/api.ts" +const publish = yield* AWS.SNS.Publish(Orders); +yield* publish({ Message: JSON.stringify({ orderId }), Subject: "OrderCreated" }); ``` -`TopicSinkHttp` is implemented on top of the `PublishBatch` -binding, so provide it in two tiers with `Layer.provideMerge` — -the sink on top, the batch layer beneath: +Provide `AWS.SNS.PublishHttp` to the runtime. To publish up to ten messages per call, bind `SNS.PublishBatch`. To publish a whole `Stream`, bind `SNS.TopicSink`, which batches it for you, and provide `AWS.SNS.TopicSinkHttp` with `AWS.SNS.PublishBatchHttp` beneath it. -```typescript -Effect.provide( - Layer.provideMerge(SNS.TopicSinkHttp, SNS.PublishBatchHttp), -) -``` +## Subscribe a Function -## Consume notifications on a Lambda - -`SNS.consumeTopicNotifications(topic, ...)` is the consumer-side -mirror of `SQS.consumeQueueMessages`: a typed `Stream` of SNS -notifications you compose with any operator. Behind the scenes -it creates the SNS subscription (protocol `lambda`, endpoint = -this function) and the `lambda:InvokeFunction` permission for -`sns.amazonaws.com`: - -```typescript -// src/worker.ts -import * as AWS from "alchemy/AWS"; -import * as SNS from "alchemy/AWS/SNS"; -import * as Console from "effect/Console"; -import * as Effect from "effect/Effect"; -import * as Stream from "effect/Stream"; -import { Orders } from "./topic.ts"; - -export default class Worker extends AWS.Lambda.Function()( - "OrdersWorker", - { main: import.meta.url }, +A Lambda Function subscribes from Construction and receives each notification in a `Stream`: + +```typescript title="src/audit.ts" +export default class Audit extends AWS.Lambda.Function()( + "Audit", + { main: import.meta.url, functionUrl: false }, Effect.gen(function* () { - const topic = yield* Orders; - - yield* SNS.consumeTopicNotifications(topic, (stream) => - stream.pipe( - Stream.runForEach((notification) => - Console.log( - `${notification.Subject}: ${notification.Message}`, - ), - ), - ), + const orders = yield* Orders; + yield* AWS.SNS.consumeTopicNotifications(orders, (stream) => + stream.pipe(Stream.runForEach((n) => Console.log(`${n.Subject}: ${n.Message}`))), ); - return {}; }).pipe(Effect.provide(AWS.Lambda.TopicEventSource)), ) {} ``` -Each notification carries the SNS message shape — `Message`, -`Subject`, `MessageId`, `TopicArn`, and friends. The -consumer-side machinery ships in `AWS.Lambda.TopicEventSource`; -provide it on the function. +Deploy creates the subscription and the Lambda permission that lets SNS invoke the Function. Each notification carries the `Message`, `Subject`, `MessageId` and `TopicArn`. -## Filter what the consumer sees +## Fan out to Queues -Pass subscription attributes as an optional middle argument — -`FilterPolicy` makes SNS drop non-matching messages before they -ever invoke your function: +The usual shape is one Queue per subscriber. Each Queue gets its own copy and is drained by its own consumer, at its own pace, with its own retries and dead-letter queue. A subscription is a resource of its own: -```typescript -yield* SNS.consumeTopicNotifications( - topic, - { - attributes: { - FilterPolicy: JSON.stringify({ type: ["order.created"] }), - }, - }, - (stream) => - stream.pipe( - Stream.runForEach((notification) => - Console.log(notification.Message), - ), - ), -); -``` - -## Fan out to SQS queues - -The classic SNS pattern is topic-to-queues fan-out: one publish, -one copy per queue, each queue drained by its own consumer at -its own pace. Subscriptions are their own resource, so wiring a -queue to a topic is one declaration: - -```typescript -// alchemy.run.ts (inside the Stack's Effect.gen) -import * as SNS from "alchemy/AWS/SNS"; -import * as SQS from "alchemy/AWS/SQS"; +```typescript title="alchemy.run.ts" +const orders = yield* Orders; +const emails = yield* AWS.SQS.Queue("EmailJobs"); -const topic = yield* Orders; - -const emails = yield* SQS.Queue("EmailJobs"); -const analytics = yield* SQS.Queue("AnalyticsJobs"); - -yield* SNS.Subscription("EmailSubscription", { - topicArn: topic.topicArn, +yield* AWS.SNS.Subscription("EmailSubscription", { + topicArn: orders.topicArn, protocol: "sqs", endpoint: emails.queueArn, -}); - -yield* SNS.Subscription("AnalyticsSubscription", { - topicArn: topic.topicArn, - protocol: "sqs", - endpoint: analytics.queueArn, + attributes: { RawMessageDelivery: "true" }, }); ``` -One AWS-side requirement: the queue's access policy must let SNS -deliver to it. Grant it with the queue's `policy` prop, scoped -to the topic: +SNS needs permission to send to the Queue. Give it in the Queue's own policy, limited to this Topic: -```typescript -const emails = yield* SQS.Queue("EmailJobs", { +```typescript title="alchemy.run.ts" +const emails = yield* AWS.SQS.Queue("EmailJobs", { policy: { Version: "2012-10-17", Statement: [ @@ -245,66 +102,41 @@ const emails = yield* SQS.Queue("EmailJobs", { Principal: { Service: "sns.amazonaws.com" }, Action: "sqs:SendMessage", Resource: "*", - Condition: { - ArnEquals: { "aws:SourceArn": topic.topicArn }, - }, + Condition: { ArnEquals: { "aws:SourceArn": orders.topicArn } }, }, ], }, }); ``` -By default SNS wraps each delivery in a JSON envelope -(`Message`, `Subject`, `TopicArn`, ...). Set -`RawMessageDelivery` on the subscription to receive the bare -message body instead: +`RawMessageDelivery` delivers the message body as is. Without it, each message arrives wrapped in a JSON envelope with the subject and Topic. From here, each Queue is an ordinary [SQS consumer](/aws/messaging/sqs#consume-messages). -```typescript -yield* SNS.Subscription("AnalyticsSubscription", { - topicArn: topic.topicArn, - protocol: "sqs", - endpoint: analytics.queueArn, - attributes: { - RawMessageDelivery: "true", - }, -}); +## Filter what each subscriber sees + +A subscriber rarely wants every message. A **filter policy** tells SNS which ones to deliver, matched on message attributes, so the rest never invoke the subscriber at all: + +```typescript title="src/audit.ts" +yield* AWS.SNS.consumeTopicNotifications( + orders, + { attributes: { FilterPolicy: JSON.stringify({ type: ["order.created"] }) } }, + (stream) => stream.pipe(Stream.runForEach((n) => Console.log(n.Message))), +); ``` -Changing a subscription's `protocol`, `topicArn`, or `endpoint` -**replaces** the subscription; `attributes` update in place. -From here each queue is a normal SQS consumer — -[`SQS.consumeQueueMessages`](/aws/messaging/sqs) picks the messages up on -whatever Lambda you point at it. - -## SNS vs EventBridge vs SQS - -All three move messages; they sit at different points: - -- **[SQS](/aws/messaging/sqs)** is one queue, one consumer group. - Point-to-point work distribution: producers enqueue, a pool of - workers drains. No fan-out — a message is consumed once. -- **SNS** is broadcast. Every subscriber gets its own copy, with - per-subscription filter policies. Reach for it when several - independent systems must react to the same event, or when you - want push delivery (Lambda, HTTPS, email) rather than polling. - Pair it with SQS (fan-out above) when each subscriber also - needs buffering and retries. -- **[EventBridge](/aws/messaging/eventbridge)** is a routed event bus: - rules match on the event *content* and route to targets, with - first-class support for AWS service events, schedules, and - third-party sources. Choose it for event-driven architectures - with many event types on one bus; choose SNS when you have one - well-known channel and want the simplest possible - publish/subscribe with high fan-out. - -## Where next - -- [SQS](/aws/messaging/sqs) — the queue side of the fan-out pattern: - consumers, batching, dead-letter queues. -- [EventBridge](/aws/messaging/eventbridge) — content-based routing when - one topic per channel stops scaling. -- [Lambda](/aws/compute/lambda) — the runtime both the publisher and - consumer above are built on. -- [`Topic` reference](/providers/aws/sns/topic) and - [`Subscription` reference](/providers/aws/sns/subscription) — - every prop and attribute. + + +Publishers set the attributes to match on with `MessageAttributes`. A `Subscription` takes the same `FilterPolicy` in its `attributes`. + +## SNS, SQS or EventBridge + +All three move messages between parts of an app, and each fits a different shape. + +Use an [SQS Queue](/aws/messaging/sqs) when one consumer should do each piece of work, at its own pace, with retries. Use an SNS Topic when several independent subscribers should each react to the same message. Use [EventBridge](/aws/messaging/eventbridge) when many kinds of events share one bus and rules route each one by its content, including events from AWS services themselves and schedules. diff --git a/.agents/skills/alchemy/references/aws/messaging/sqs.md b/.agents/skills/alchemy/references/aws/messaging/sqs.md index 4f812a59..bb39ca54 100644 --- a/.agents/skills/alchemy/references/aws/messaging/sqs.md +++ b/.agents/skills/alchemy/references/aws/messaging/sqs.md @@ -1,378 +1,193 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # SQS -> Add an SQS Queue, publish messages from your Lambda, and consume them from a second consumer Lambda — all wired through Alchemy bindings. - -**SQS** is AWS's general-purpose message queue — anything you can -serialize, dropped into a mailbox and processed asynchronously -somewhere else. In Alchemy it's the `Queue` resource plus -producer bindings (`SendMessage`, `SendMessageBatch`, and the -`Stream`-sink-shaped `QueueSink`) and a consumer side: -`SQS.consumeQueueMessages` subscribes a Lambda to the queue as a -typed `Stream`, creating the event source mapping and -granting the receive/delete permissions for you. - -The walkthrough below builds on the [Lambda](/aws/compute/lambda) and -[DynamoDB](/aws/data/dynamodb) pages: it adds a **Queue**, sends -messages to it from the existing function, and stands up a -**second Lambda** that consumes them. - -## Add the queue - -```diff lang="typescript" -// src/api.ts -import * as AWS from "alchemy/AWS"; -import * as DynamoDB from "alchemy/AWS/DynamoDB"; -+import * as SQS from "alchemy/AWS/SQS"; -// ... - -Effect.gen(function* () { - const bucket = yield* S3.Bucket("Blobs"); - const table = yield* DynamoDB.Table("Items", { /* ... */ }); -+ const queue = yield* SQS.Queue("Jobs"); - - // ... existing bindings ... -}); -``` +> How SQS Queues hand work from producers to consumers, how visibility timeouts, retries and dead-letter queues keep messages from being lost, and how runtimes send to and consume from a Queue. -Calling `SQS.Queue("Jobs")` provisions a standard queue with the -defaults (4-day retention, 30-second visibility timeout, no -delivery delay). FIFO queues, dead-letter targets, and the rest -of the props can be supplied as a second argument when you need -them. +SQS is a message queue. A **producer** puts a message on a Queue and moves on. A **consumer** takes messages off later, does the work, and deletes them. The two never wait for each other, so a slow job doesn't slow down the request that asked for it, and a burst of work waits in the Queue instead of overwhelming whatever does it. -## Bind SendMessage on the producer +## Consumers take messages in any order -`SQS.SendMessage(queue)` returns a callable Effect — same -shape as `S3.PutObject` or `DynamoDB.PutItem` — and quietly -attaches `sqs:SendMessage` scoped to the queue ARN: +A standard Queue doesn't keep messages in a line. It spreads them across many servers, and each receive returns whichever messages it finds, up to 10 at a time. So consumers get messages roughly, but not exactly, in the order they were sent: -```diff lang="typescript" -const putItem = yield* DynamoDB.PutItem(table); -+const sendMessage = yield* SQS.SendMessage(queue); -``` + -Let's hook it into the existing `PUT /items/:id` route so every -new record also drops a `job.created` message onto the queue: - -```diff lang="typescript" -if (request.method === "PUT") { - const content = yield* request.text; - yield* putItem({ - Item: { - id: { S: id }, - content: { S: content }, - }, - }); -+ yield* sendMessage({ -+ MessageBody: JSON.stringify({ -+ type: "job.created", -+ id, -+ content, -+ }), -+ }); - return HttpServerResponse.empty({ status: 204 }); -} -``` +## A message is received, then deleted -The producer also needs the runtime layer for `SendMessage` — -add it to the merged layer alongside the others: - -```diff lang="typescript" -}).pipe( - Effect.provide( - Layer.mergeAll( - AWS.Lambda.BucketEventSource, - AWS.Lambda.TableEventSource, - DynamoDB.GetItemHttp, - DynamoDB.PutItemHttp, - S3.PutObjectHttp, - S3.GetObjectHttp, -+ SQS.SendMessageHttp, - ), - ), -), -``` +A message stays on the Queue until a consumer deletes it. Receiving it doesn't remove it. It only hides it from other consumers for the **visibility timeout**, 30 seconds by default. -## Stand up a consumer Lambda + -Consumers live as their own Lambda Function. Create -`src/worker.ts` — bare shell first, no event source yet: +If the consumer finishes, it deletes the message and it's gone. If the consumer crashes or times out, the message becomes visible again and another consumer receives it. So a message is never lost to a failure, but it can be delivered more than once. Write consumers so that doing a job twice is safe: check whether it's done already, or make the work idempotent. -```typescript -// src/worker.ts -import * as AWS from "alchemy/AWS"; -import * as Effect from "effect/Effect"; +## Declare a Queue -export default class Worker extends AWS.Lambda.Function()( - "JobsWorker", - { main: import.meta.url }, - Effect.gen(function* () { - return {}; - }), -) {} +A Queue is a declaration. Put it in its own module, so the producer and the consumer can both import it: + +```typescript title="src/jobs.ts" +import * as AWS from "@alchemy.run/aws"; + +export const Jobs = AWS.SQS.Queue("Jobs"); ``` -This consumer doesn't need a Function URL — its only entrypoint -is the SQS message poller AWS will configure for it. +Messages are kept for four days by default. Set `messageRetentionPeriod` to keep them longer, up to 14 days, and set `visibilityTimeout` longer than your consumer takes to finish one batch: -## Share the queue between two functions +```typescript title="src/jobs.ts" +export const Jobs = AWS.SQS.Queue("Jobs", { visibilityTimeout: "2 minutes" }); +``` -Both producer and consumer need to reference the same queue — -the cleanest way to do that is to lift the declaration out of -`api.ts` into a small shared module: +## Send messages -```typescript -// src/queue.ts -import * as SQS from "alchemy/AWS/SQS"; +Bind `SQS.SendMessage` in the producer. Its role gets `sqs:SendMessage` on this Queue only: -export const Jobs = SQS.Queue("Jobs"); +```typescript title="src/api.ts" +const sendMessage = yield* AWS.SQS.SendMessage(Jobs); ``` -Now both functions can import `Jobs`. Update the producer to use -the shared handle instead of declaring the queue inline: +A message body is a string, up to 256 KB. Send JSON: -```diff lang="typescript" -// src/api.ts -+import { Jobs } from "./queue.ts"; -// ... --const queue = yield* SQS.Queue("Jobs"); -+const queue = yield* Jobs; +```typescript title="src/api.ts" +yield* sendMessage({ MessageBody: JSON.stringify({ type: "thumbnail", key }) }); ``` -## Resolve the queue in the consumer +Provide `AWS.SQS.SendMessageHttp` to the producer. Sending returns as soon as SQS has stored the message, so the request handler can respond while the work waits. -Yield the same `Jobs` handle in the consumer's constructor to get -a typed `Queue` resource: +## Consume messages -```diff lang="typescript" -// src/worker.ts -import * as AWS from "alchemy/AWS"; -import * as Effect from "effect/Effect"; -+import { Jobs } from "./queue.ts"; +A Lambda Function consumes a Queue by subscribing to it from Construction. Lambda polls the Queue for you and invokes the Function with batches of messages: +```typescript title="src/worker.ts" export default class Worker extends AWS.Lambda.Function()( - "JobsWorker", - { main: import.meta.url }, + "Worker", + { main: import.meta.url, functionUrl: false }, Effect.gen(function* () { -+ const queue = yield* Jobs; + yield* AWS.SQS.consumeQueueMessages(Jobs, { batchSize: 10 }, (event) => + Effect.forEach(event.Records, (record) => Console.log(record.body), { discard: true }), + ); return {}; - }), + }).pipe(Effect.provide(AWS.Lambda.QueueEventSource)), ) {} ``` -## Subscribe to messages +Deploy creates the event source mapping and grants the Function `sqs:ReceiveMessage`, `sqs:DeleteMessage` and `sqs:GetQueueAttributes` on the Queue. When the handler succeeds, Lambda deletes the whole batch. When it fails, the whole batch becomes visible again and is retried. -`SQS.consumeQueueMessages(queue, ...)` is the consumer-side mirror -of `consumeBucketEvents` / `stream`: a typed `Stream` you -can compose with any operator. Add the smallest possible -subscription — log each message body: +A process on ECS or EC2 consumes the same way, with its own event source layer: it long-polls the Queue in a loop instead of being invoked. -```diff lang="typescript" -// src/worker.ts -import * as AWS from "alchemy/AWS"; -+import * as SQS from "alchemy/AWS/SQS"; -+import * as Console from "effect/Console"; -import * as Effect from "effect/Effect"; -+import * as Stream from "effect/Stream"; -import { Jobs } from "./queue.ts"; +## Retry only the messages that failed -export default class Worker extends AWS.Lambda.Function()( - "JobsWorker", - { main: import.meta.url }, - Effect.gen(function* () { - const queue = yield* Jobs; -+ -+ yield* SQS.consumeQueueMessages(queue, { batchSize: 10 }, (stream) => -+ stream.pipe( -+ Stream.runForEach((record) => -+ Console.log(`received: ${record.body}`), -+ ), -+ ), -+ ); +Failing a whole batch for one bad message repeats the work that succeeded. Instead, return the ids of the messages that failed. Lambda deletes the rest and redelivers only those: - return {}; - }), -) {} +```typescript title="src/worker.ts" +yield* AWS.SQS.consumeQueueMessages(Jobs, { batchSize: 10 }, (event) => + Effect.filter( + event.Records, + (record) => + handleJob(record.body).pipe( + Effect.as(false), + Effect.catchCause(() => Effect.succeed(true)), + ), + { concurrency: 4 }, + ).pipe( + Effect.map((failed) => ({ + batchItemFailures: failed.map((record) => ({ itemIdentifier: record.messageId })), + })), + ), +); ``` -That single `consumeQueueMessages(...)` call creates the Lambda event -source mapping pointing at the queue and grants the function -`sqs:ReceiveMessage`, `DeleteMessage`, and `GetQueueAttributes` -on the queue ARN. +Messages in a batch are processed four at a time here, and one failure no longer drags the others back onto the Queue. -## Provide the runtime layer +## Move poison messages aside -The consumer-side machinery for queue subscriptions ships in -`Lambda.QueueEventSource`. Provide it at the bottom of the -function: +Some messages fail every time: malformed input, a bug, a record that no longer exists. Without a limit, they're retried until they expire. A **dead-letter queue** catches them instead. After a message has been received `maxReceiveCount` times, SQS moves it there: -```diff lang="typescript" -+import * as Layer from "effect/Layer"; -// ... - return {}; -- }), -+ }).pipe(Effect.provide(AWS.Lambda.QueueEventSource)), -) {} +```typescript title="alchemy.run.ts" +const deadLetters = yield* AWS.SQS.Queue("JobsDeadLetters", { messageRetentionPeriod: "14 days" }); +const jobs = yield* AWS.SQS.Queue("Jobs", { + redrivePolicy: { deadLetterTargetArn: deadLetters.queueArn, maxReceiveCount: 5 }, +}); ``` -## Wire the worker into the Stack +The work stops failing in a loop, and the failed messages wait for you to look at them. Put an [alarm](/aws/observability/cloudwatch) on the dead-letter queue's depth so you know when one arrives. -The Worker needs to be yielded so Alchemy actually deploys it: +## Keep order with a FIFO queue -```diff lang="typescript" -// alchemy.run.ts -import Api from "./src/api.ts"; -+import Worker from "./src/worker.ts"; +A standard Queue delivers messages roughly in order, at least once. A **FIFO** queue delivers them exactly in order and exactly once, within each **message group**: -export default Alchemy.Stack( - "MyApp", - { providers: AWS.providers(), state: AWS.state() }, - Effect.gen(function* () { - const api = yield* Api; -+ yield* Worker; - return { url: api.functionUrl }; - }), -); +```typescript title="src/ledger.ts" +export const Ledger = AWS.SQS.Queue("Ledger", { fifo: true, contentBasedDeduplication: true }); ``` -## Deploy +Every message names its group, like an account id. Messages in one group are delivered one after another, and different groups are processed in parallel: -```sh -bun alchemy deploy +```typescript title="src/api.ts" +yield* sendMessage({ MessageBody: body, MessageGroupId: accountId }); ``` -Two functions deploy in parallel — `Api` (with `SendMessage` -permissions) and `JobsWorker` (with `ReceiveMessage` permissions -plus an event source mapping pointing at `Jobs`). - -## Verify - -Trigger a write, then watch the consumer's logs: + -```sh -curl -X PUT --data 'hello queue' "$URL/items/q1" -bun alchemy logs JobsWorker --tail -``` - -Within a couple of seconds you'll see: - -``` -received: {"type":"job.created","id":"q1","content":"hello queue"} -``` +FIFO queues trade throughput for that guarantee. Use one when the order of messages for the same thing matters, like the entries in one account's ledger. -## Bonus: process records in parallel +## Send many messages at once -`Stream.mapEffect` accepts a `concurrency` option, so you can -fan out per-record work without rewriting anything: +To forward a `Stream` of messages, like a table's changes or a file's lines, bind `SQS.QueueSink`. It batches messages ten at a time into `sqs:SendMessageBatch` calls: -```typescript -stream.pipe( - Stream.mapEffect( - (record) => doSomethingWith(record.body).pipe(Effect.orDie), - { concurrency: 4 }, - ), - Stream.runDrain, -); -``` - -Up to 4 records process concurrently, and the event source -mapping won't ack them until the stream completes — which is the -same delivery semantics SQS already gives you, just with -controllable concurrency on top. - -## Bonus: forward a stream to SQS with `QueueSink` - -`SendMessage(queue)` is perfect for one-off sends from a -request handler, but if you've got a `Stream` of payloads — -DynamoDB change records, S3 notifications, anything — you don't -want to call `sendMessage` per item. **`SQS.QueueSink`** is the -sink-shaped counterpart: it consumes a `Stream`, batches -items into chunks of up to 10, and ships each chunk through -`sqs:SendMessageBatch` for you. - -Skip the per-write `sendMessage` in `PUT /items/:id` and forward -the existing DynamoDB stream straight into the queue instead: - -```diff lang="typescript" -// src/api.ts -import * as Stream from "effect/Stream"; -import { Jobs } from "./queue.ts"; -// ... - -const queue = yield* Jobs; -const putItem = yield* DynamoDB.PutItem(table); --const sendMessage = yield* SQS.SendMessage(queue); -+const sink = yield* SQS.QueueSink(queue); - -yield* DynamoDB.consumeTableChanges(table, { - streamViewType: "NEW_AND_OLD_IMAGES", -}, (stream) => - stream.pipe( -+ Stream.map((record) => -+ JSON.stringify({ -+ eventName: record.eventName, -+ keys: record.dynamodb.Keys, -+ newImage: record.dynamodb.NewImage, -+ }), -+ ), -+ Stream.run(sink), - ), +```typescript title="src/api.ts" +const sink = yield* AWS.SQS.QueueSink(Jobs); +yield* Stream.fromIterable(keys).pipe( + Stream.map((key) => JSON.stringify({ type: "thumbnail", key })), + Stream.run(sink), ); ``` -`QueueSink(queue)` grants `sqs:SendMessage` and -`sqs:SendMessageBatch` on the queue ARN, then returns a -`Sink` you compose with -`Stream.run`. `QueueSinkHttp` is itself implemented on top of -`SendMessageBatch`, so split the merged layer into two tiers -with `Layer.provideMerge` — sink + event sources on top, -the underlying request layers + policy on the bottom: - -```diff lang="typescript" -}).pipe( - Effect.provide( -- Layer.mergeAll( -- AWS.Lambda.BucketEventSource, -- AWS.Lambda.TableEventSource, -- DynamoDB.GetItemHttp, -- DynamoDB.PutItemHttp, -- S3.PutObjectHttp, -- S3.GetObjectHttp, -- SQS.SendMessageHttp, -- ), -+ Layer.mergeAll( -+ AWS.Lambda.BucketEventSource, -+ AWS.Lambda.TableEventSource, -+ SQS.QueueSinkHttp, -+ ).pipe( -+ Layer.provideMerge( -+ Layer.mergeAll( -+ DynamoDB.GetItemHttp, -+ DynamoDB.PutItemHttp, -+ S3.PutObjectHttp, -+ S3.GetObjectHttp, -+ SQS.SendMessageBatchHttp, -+ ), -+ ), -+ ), - ), -), -``` - -The consumer doesn't change — `JobsWorker` still subscribes via -`SQS.consumeQueueMessages(queue)` and now sees one record per DynamoDB -change, batched ten-at-a-time on the producer side. - -## Where next +`QueueSinkHttp` is built on `SendMessageBatchHttp`, so provide both: `QueueSinkHttp` with `Layer.provideMerge(AWS.SQS.SendMessageBatchHttp)` beneath it. -- [Kinesis](/aws/messaging/kinesis) — stream higher-volume records: - ordered, sharded, and with the same `Stream` consumer surface. -- [Process DynamoDB Streams](/aws/messaging/dynamodb-streams) — the - change-data-capture pipeline the `QueueSink` bonus above - builds on. -- [`Queue` reference](/providers/aws/sqs/queue) — FIFO queues, - dead-letter targets, and every other prop. +When one event should reach several queues or functions, publish it to an [SNS Topic](/aws/messaging/sns) instead, and subscribe each Queue to the Topic. diff --git a/.agents/skills/alchemy/references/aws/networking/_overview.md b/.agents/skills/alchemy/references/aws/networking/_overview.md index 365eb2c1..8c173a59 100644 --- a/.agents/skills/alchemy/references/aws/networking/_overview.md +++ b/.agents/skills/alchemy/references/aws/networking/_overview.md @@ -1,260 +1,162 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # VPC & networking -> The Network helper for a production-shaped VPC in one call, and the full set of EC2 networking primitives — VPCs, subnets, gateways, routes, security groups, and endpoints — for explicit control. - -Most Alchemy apps on AWS never touch a VPC. Lambda functions -serve public traffic from Function URLs, and bindings wire -access to tables, buckets, and queues without a single subnet. -Networking becomes your problem when you run an -[ECS Service](/aws/compute/ecs), an [EKS Cluster](/aws/compute/eks), or an -[EC2 Instance](/aws/compute/ec2) — all -need a VPC, subnets, and security groups — or when you attach to -anything that lives inside one. - -Alchemy gives you two altitudes: the **`Network` helper**, which -builds the standard public/private layout in one call, and the -**canonical primitives** underneath it, for when you need -explicit control. - -## The `Network` helper - -[`Network`](/providers/aws/ec2/network) creates a -production-shaped VPC from the low-level primitives — VPC, -internet gateway, one public and one private subnet per -Availability Zone (2 AZs by default), route tables, routes, and -associations — and returns every underlying resource so you can -keep composing with raw `AWS.EC2.*` APIs: - -```typescript -const network = yield* AWS.EC2.Network("AppNetwork", { - cidrBlock: "10.42.0.0/16", -}); +> How a VPC, its subnets, route tables, gateways and security groups decide what can reach what on AWS, which runtimes need one, and how to build one with the Network helper or by hand. + +A **VPC** is a private network of your own inside an AWS region. Containers, virtual machines, databases and caches run inside one, and the VPC decides what can reach them: from the internet, from each other, and from AWS's own services. + +## Who needs a VPC + +Serverless services don't live in your VPC. A Lambda Function, a Bucket, a Table and a Queue are reached over AWS's own endpoints, and a Function serves HTTP from its Function URL. An app made only of those needs no network at all. + +A VPC comes in when something needs a network interface of its own: an [ECS](/aws/compute/ecs) task, an [EKS](/aws/compute/eks) node, an [EC2](/aws/compute/ec2) instance, an [Aurora](/aws/data/rds) database, a cache. A Lambda Function joins a VPC too when it has to reach one of those privately. + +## Subnets split the network across zones + +A VPC owns a range of private addresses, like `10.42.0.0/16`. **Subnets** divide it into smaller ranges, and each subnet sits in one Availability Zone. Put a subnet in each of at least two zones, so losing a data center leaves the app running in the other. + +```text +Diagram (nodes and edges as authored): + ``` -Subnet CIDRs are derived from the VPC block automatically, and -the outputs you'll reach for most — `vpcId`, `publicSubnetIds`, -`privateSubnetIds` — sit right on the result. +What makes a subnet public or private is its **route table**. A public subnet routes internet traffic to an **internet gateway**, so things in it can have public addresses and be reached from outside. A private subnet has no route in from the internet. If it routes outbound traffic to a **NAT gateway** in a public subnet, things in it can call out, to download packages or call an API, and still can't be reached. Load balancers go in public subnets. Databases, and usually containers, go in private ones. -Turn on NAT and gateway endpoints when private subnets need a -path out: +## Security groups are firewalls around each resource -```typescript -const network = yield* AWS.EC2.Network("AppNetwork", { - cidrBlock: "10.42.0.0/16", - availabilityZones: 2, - nat: "single", - gatewayEndpoints: ["s3"], +A **security group** is a set of rules around each network interface: which ports accept traffic, and from where. It's stateful, so the reply to an allowed request is always allowed back. + +A rule can name another security group instead of an address. "Port 5432, from anything in the `App` group" lets your containers reach the database however many there are and whatever addresses they get: + +```typescript title="src/network.ts" +const database = yield* AWS.EC2.SecurityGroup("Database", { + vpcId: network.vpcId, + ingress: [{ ipProtocol: "tcp", fromPort: 5432, toPort: 5432, referencedGroupId: app.groupId }], }); +``` + +## Build the usual layout + +`AWS.EC2.Network` builds a VPC with an internet gateway, one public and one private subnet in each of two zones, and the route tables between them: + +```typescript title="src/network.ts" +import * as AWS from "@alchemy.run/aws"; + +export const AppNetwork = AWS.EC2.Network("AppNetwork", { cidrBlock: "10.42.0.0/16" }); +``` + +The subnet ranges are worked out from the VPC's. Pass `vpcId`, `publicSubnetIds` and `privateSubnetIds` from the result to whatever runs in it: -yield* AWS.ECS.Service("ApiService", { +```typescript title="alchemy.run.ts" +const network = yield* AppNetwork; + +yield* AWS.ECS.Service("Api", { cluster, - task: { - taskDefinitionArn: apiTask.taskDefinitionArn, - containerName: apiTask.containerName, - port: apiTask.port, - }, + task: apiTask, vpcId: network.vpcId, subnets: network.publicSubnetIds, assignPublicIp: true, + loadBalancer: true, }); ``` -- `nat: "none"` (default) keeps private subnets isolated; - `"single"` shares one NAT gateway; `"per-az"` creates one per - Availability Zone for AZ-fault isolation. -- `gatewayEndpoints` attaches free S3/DynamoDB gateway endpoints - to the private route tables, so that traffic never crosses the - NAT. +The tasks and their load balancer share these subnets. Public subnets with public addresses let the tasks pull their image without a NAT gateway. To keep the tasks private, add NAT, below, and put them in `privateSubnetIds`. + +## Let private subnets reach out + +Private subnets are isolated by default. Add NAT when what runs in them needs the internet: + +```typescript title="src/network.ts" +export const AppNetwork = AWS.EC2.Network("AppNetwork", { + cidrBlock: "10.42.0.0/16", + nat: "single", + gatewayEndpoints: ["s3", "dynamodb"], +}); +``` -If `Network`'s layout fits, use it and stop reading. The rest of -this page is the same network built by hand. +`"single"` shares one NAT gateway between the zones. `"per-az"` puts one in each, so losing a zone doesn't cut the others off, at the cost of a gateway each. NAT gateways are billed by the hour and by the gigabyte. -## Building it by hand +**Gateway endpoints** route traffic for S3 and DynamoDB over AWS's network instead, for free. With them, a private subnet reaches its Buckets and Tables without NAT at all. -### VPC and internet gateway +## Build it by hand -A [`Vpc`](/providers/aws/ec2/vpc) is a private IPv4 range; an -[`InternetGateway`](/providers/aws/ec2/internetgateway) is its -door to the internet: +`Network` returns every resource it creates, so you can keep building on it. When you need a different layout, declare the pieces yourself. A VPC and its internet gateway: -```typescript +```typescript title="src/network.ts" const vpc = yield* AWS.EC2.Vpc("AppVpc", { cidrBlock: "10.80.0.0/16", enableDnsSupport: true, enableDnsHostnames: true, }); - -const igw = yield* AWS.EC2.InternetGateway("AppIgw", { - vpcId: vpc.vpcId, -}); +const igw = yield* AWS.EC2.InternetGateway("AppIgw", { vpcId: vpc.vpcId }); ``` -The two DNS toggles let instances resolve names and receive -public DNS hostnames — you'll want both on for anything serving -public traffic. +A subnet in a zone: -### Subnets - -[`Subnet`](/providers/aws/ec2/subnet)s carve the VPC block into -per-AZ ranges. `mapPublicIpOnLaunch` is what makes a subnet -"public" from the instance's point of view: - -```typescript -const subnetA = yield* AWS.EC2.Subnet("PublicSubnetA", { +```typescript title="src/network.ts" +const publicA = yield* AWS.EC2.Subnet("PublicA", { vpcId: vpc.vpcId, cidrBlock: "10.80.1.0/24", - availabilityZone: az1, - mapPublicIpOnLaunch: true, -}); - -const subnetB = yield* AWS.EC2.Subnet("PublicSubnetB", { - vpcId: vpc.vpcId, - cidrBlock: "10.80.2.0/24", - availabilityZone: az2, + availabilityZone: "us-east-1a", mapPublicIpOnLaunch: true, }); ``` -Two subnets in two AZs is the floor for anything fronted by a -load balancer. - -### Routing +A route table that makes it public: -A subnet is only public once its -[`RouteTable`](/providers/aws/ec2/routetable) sends `0.0.0.0/0` -to the internet gateway. [`Route`](/providers/aws/ec2/route) adds -the rule; -[`RouteTableAssociation`](/providers/aws/ec2/routetableassociation) -attaches the table to each subnet: - -```typescript -const routeTable = yield* AWS.EC2.RouteTable("PublicRouteTable", { - vpcId: vpc.vpcId, -}); +```typescript title="src/network.ts" +const publicRoutes = yield* AWS.EC2.RouteTable("PublicRoutes", { vpcId: vpc.vpcId }); -yield* AWS.EC2.Route("PublicInternetRoute", { - routeTableId: routeTable.routeTableId, +yield* AWS.EC2.Route("PublicInternet", { + routeTableId: publicRoutes.routeTableId, destinationCidrBlock: "0.0.0.0/0", gatewayId: igw.internetGatewayId, }); -yield* AWS.EC2.RouteTableAssociation("PublicAssocA", { - routeTableId: routeTable.routeTableId, - subnetId: subnetA.subnetId, -}); -yield* AWS.EC2.RouteTableAssociation("PublicAssocB", { - routeTableId: routeTable.routeTableId, - subnetId: subnetB.subnetId, -}); -``` - -### Security groups - -A [`SecurityGroup`](/providers/aws/ec2/securitygroup) is the -per-resource firewall — the thing you attach to service ENIs, -load balancers, and instances. Declare ingress and egress rules -inline: - -```typescript -const securityGroup = yield* AWS.EC2.SecurityGroup("AppSg", { - vpcId: vpc.vpcId, - description: "app traffic", - ingress: [ - { - ipProtocol: "tcp", - fromPort: 80, - toPort: 80, - cidrIpv4: "0.0.0.0/0", - description: "HTTP ingress", - }, - ], - egress: [ - { - ipProtocol: "-1", - cidrIpv4: "0.0.0.0/0", - description: "all outbound", - }, - ], +yield* AWS.EC2.RouteTableAssociation("PublicA", { + routeTableId: publicRoutes.routeTableId, + subnetId: publicA.subnetId, }); ``` -Rules can also be managed as standalone -[`SecurityGroupRule`](/providers/aws/ec2/securitygrouprule) -resources when different parts of your stack contribute rules to -one group. - -## Private egress with NAT - -Private subnets reach the internet through a -[`NatGateway`](/providers/aws/ec2/natgateway) living in a -*public* subnet, addressed by an [`EIP`](/providers/aws/ec2/eip), -with the private route table pointing `0.0.0.0/0` at it: - -```typescript -const privateRouteTable = yield* AWS.EC2.RouteTable("PrivateRouteTable", { - vpcId: vpc.vpcId, -}); +And a NAT gateway for the private subnets, with a static address, in a public subnet: +```typescript title="src/network.ts" const eip = yield* AWS.EC2.EIP("NatEip", { domain: "vpc" }); - -const natGateway = yield* AWS.EC2.NatGateway("NatGateway", { - subnetId: subnetA.subnetId, // a public subnet +const nat = yield* AWS.EC2.NatGateway("Nat", { + subnetId: publicA.subnetId, allocationId: eip.allocationId, connectivityType: "public", }); -yield* AWS.EC2.Route("PrivateInternetRoute", { - routeTableId: privateRouteTable.routeTableId, +yield* AWS.EC2.Route("PrivateInternet", { + routeTableId: privateRoutes.routeTableId, destinationCidrBlock: "0.0.0.0/0", - natGatewayId: natGateway.natGatewayId, -}); -``` - -This is exactly what `Network`'s `nat: "single"` option builds -(`"per-az"` repeats it per Availability Zone). - -## Gateway endpoints - -S3 and DynamoDB traffic from private subnets doesn't need NAT at -all — a Gateway [`VpcEndpoint`](/providers/aws/ec2/vpcendpoint) -routes it over AWS's network for free: - -```typescript -yield* AWS.EC2.VpcEndpoint("S3Endpoint", { - vpcId: vpc.vpcId, - serviceName: "com.amazonaws.us-east-1.s3", // match your region - vpcEndpointType: "Gateway", - routeTableIds: [privateRouteTable.routeTableId], + natGatewayId: nat.natGatewayId, }); ``` -`Network`'s `gatewayEndpoints: ["s3", "dynamodb"]` does the same -against its private route tables. - -## The full toolkit - -| Resource | What it does | -| --- | --- | -| [`Vpc`](/providers/aws/ec2/vpc) | The private IPv4 network everything else lives in | -| [`Subnet`](/providers/aws/ec2/subnet) | A per-AZ slice of the VPC's address range | -| [`InternetGateway`](/providers/aws/ec2/internetgateway) | Two-way internet access for public subnets | -| [`EgressOnlyInternetGateway`](/providers/aws/ec2/egressonlyinternetgateway) | Outbound-only IPv6 internet access | -| [`NatGateway`](/providers/aws/ec2/natgateway) | Outbound internet for private subnets | -| [`EIP`](/providers/aws/ec2/eip) | A static public IPv4 address | -| [`RouteTable`](/providers/aws/ec2/routetable) / [`Route`](/providers/aws/ec2/route) / [`RouteTableAssociation`](/providers/aws/ec2/routetableassociation) | Where each subnet's traffic goes | -| [`SecurityGroup`](/providers/aws/ec2/securitygroup) / [`SecurityGroupRule`](/providers/aws/ec2/securitygrouprule) | Stateful per-resource firewall | -| [`VpcEndpoint`](/providers/aws/ec2/vpcendpoint) | Private connectivity to AWS services | -| [`NetworkAcl`](/providers/aws/ec2/networkacl) / [`NetworkAclEntry`](/providers/aws/ec2/networkaclentry) / [`NetworkAclAssociation`](/providers/aws/ec2/networkaclassociation) | Stateless subnet-level packet filtering | - -## Where next - -- [ECS](/aws/compute/ecs) — run containers in the network you just - built, with an Alchemy-managed public ALB. -- [EC2](/aws/compute/ec2) — launch instances into it, raw or hosting an - Effect program. -- [`Network` reference](/providers/aws/ec2/network) — every prop - and everything the helper returns. +Network ACLs, peering, interface endpoints and IPv6 gateways are in the [EC2 reference](/providers/aws/ec2/vpc). diff --git a/.agents/skills/alchemy/references/aws/networking/custom-domains.md b/.agents/skills/alchemy/references/aws/networking/custom-domains.md index 72a22ec2..080e9f8d 100644 --- a/.agents/skills/alchemy/references/aws/networking/custom-domains.md +++ b/.agents/skills/alchemy/references/aws/networking/custom-domains.md @@ -1,195 +1,130 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> -# Custom domains with Route53 + ACM +# Custom domains -> Serve your site or API from your own domain — DNS-validated ACM certificates, Route 53 alias records, and the domain prop on Website resources. +> How a domain reaches a site or API on AWS through a hosted zone, a TLS certificate and DNS records, and how the domain prop sets them up on Websites, Lambda Functions and load balancers. -A custom domain on AWS is three moving parts: a TLS certificate (ACM), DNS -records (Route 53), and wiring both into whatever serves traffic (CloudFront -or API Gateway). For websites, Alchemy collapses all three into a single -`domain` prop; for APIs and anything bespoke, the same primitives — -`AWS.ACM.Certificate` and `AWS.Route53.Record` — are available directly. +A custom domain needs three things. **DNS** has to send the name to the thing serving it. A **certificate** has to prove to browsers that you own the name. And the thing serving it, CloudFront, a load balancer or API Gateway, has to accept the name and present the certificate. -## The one-prop path: `domain` on Website resources +On AWS, DNS is **Route 53** and certificates come from **ACM**. -`AWS.Website.Router`, `AWS.Website.SsrSite`, and a standalone -`AWS.Website.StaticSite` all accept the same `domain` shape: +## Zone, certificate, record -```typescript -const router = yield* AWS.Website.Router("WebsiteRouter", { - domain: { - name: "app.example.com", - hostedZoneId: "Z1234567890", - aliases: ["www.app.example.com"], - }, - routes: { - "/*": site.routeTarget, - }, -}); -``` +A **hosted zone** holds the DNS records for a domain. A **certificate** for a name is issued once you prove you control it, by adding a validation record ACM gives you to the zone. A record for the name then points at the thing serving it. -With `hostedZoneId` set, Alchemy requests a DNS-validated ACM certificate -covering `name` plus every alias, upserts the validation records into your -zone, waits for issuance, attaches the certificate to the CloudFront -distribution, and creates an `A` alias record for each hostname. The -resource's `url` output becomes `https://app.example.com`. When a site is -attached to a `Router`, put `domain` on the Router — passing it to the -attached `StaticSite` as well is an error. - -## Bring your own certificate - -If you already have an ACM certificate, pass its ARN as `cert` and Alchemy -skips certificate creation: - -```typescript -domain: { - name: "app.example.com", - hostedZoneId: "Z1234567890", - cert: existingCertificateArn, -}, +```text +Diagram (nodes and edges as authored): + ``` -DNS records are still managed for you — only the certificate step is -replaced. The certificate must cover the domain name and every alias you -list. +An **alias record** is Route 53's way to point a name at an AWS resource. It works at the zone's apex, `example.com` itself, where an ordinary CNAME can't. -## Manage DNS elsewhere +Certificates for CloudFront must be in `us-east-1`, wherever the rest of the app runs. Certificates for a load balancer or a regional API must be in that resource's region. -Set `dns: false` to skip Route 53 entirely: +## Give a resource a domain -```typescript -domain: { - name: "app.example.com", - cert: existingCertificateArn, - dns: false, -}, -``` +Websites, Lambda Functions and ECS load balancers take a `domain` prop. Name the domain, and Alchemy requests the certificate, validates it, attaches it and creates the records, `A` and `AAAA` aliases for websites and load balancers: -No records are created, so you point your DNS provider at the distribution's -domain name yourself. `dns: false` requires `cert` — without Route 53 access -Alchemy can't complete DNS validation for a new certificate, so you must -bring one. +```typescript title="alchemy.run.ts" +const site = yield* AWS.Website.StaticSite("Site", { + path: "./dist", + domain: { name: "app.example.com", aliases: ["www.app.example.com"] }, +}); +``` -## Create or reference a hosted zone +The zone is found by walking up the name's labels until one matches a hosted zone in the account. Pass `hostedZoneId` to name it yourself. The site's `url` becomes `https://app.example.com`. -The `domain` prop and the primitives below both key off a hosted zone ID. If -the zone lives outside your stack, pass its ID as a plain string; to manage -it in the stack, use `AWS.Route53.HostedZone`: +A Lambda Function's URL can't serve a custom name. Give the Function a `domain`, and Alchemy puts an HTTP API in front of it with a regional certificate. Its `fetch` handler works unchanged: -```typescript -const zone = yield* AWS.Route53.HostedZone("Zone", { - name: "example.com", -}); +```typescript title="alchemy.run.ts" +const api = yield* AWS.Lambda.Function("Api", { main: "./src/handler.ts", domain: "api.example.com" }); ``` -`zone.id` is the hosted zone ID (without the `/hostedzone/` prefix) and -`zone.nameServers` lists the authoritative name servers — set these as `NS` -records at your registrar (or parent zone) to delegate the domain. Set -`forceDestroy: true` if you want `destroy` to delete any remaining records -before deleting the zone. +An ECS Service with `loadBalancer` takes a `domain` too, on its load balancer. -## Request a DNS-validated certificate +## Use DNS hosted somewhere else -`AWS.ACM.Certificate` requests a certificate and, when you give it a -`hostedZoneId`, handles validation end to end: +When the domain's DNS is on Cloudflare or Hetzner, give the `domain` that host's DNS adapter: -```typescript -const cert = yield* AWS.ACM.Certificate("WebsiteCertificate", { - domainName: "app.example.com", - subjectAlternativeNames: ["www.app.example.com"], - hostedZoneId: zone.id, +```typescript title="alchemy.run.ts" +const site = yield* AWS.Website.StaticSite("Site", { + path: "./dist", + domain: { name: "app.example.com", dns: Cloudflare.DNS.Adapter() }, }); ``` -The provider upserts the DNS validation records ACM asks for into the zone, -waits for Route 53 to propagate them, and blocks until the certificate -reaches `ISSUED` — so `cert.certificateArn` is ready to attach the moment -the effect resolves. Certificates are requested in `us-east-1`, the region -CloudFront requires for viewer certificates. ACM certificates are immutable: -changing the domain name, SANs, or validation settings replaces the -certificate with a new one. +The certificate is still issued by ACM, and its validation records and the name's CNAME are written to the other host instead. Add `Cloudflare.providers()` next to `AWS.providers()` in the Stack. See [DNS adapters](/infrastructure-as-code/dns-adapters). -## Alias a record to CloudFront +To manage DNS by hand, set `dns: false` and pass a certificate you already have as `cert`. Without access to the DNS, a new certificate can't be validated. -`AWS.Route53.Record` manages a single record set; an `A` record with -`aliasTarget` points a hostname at a CloudFront distribution: - -```typescript -yield* AWS.Route53.Record("WebsiteAlias", { - hostedZoneId: zone.id, - name: "app.example.com", - type: "A", - aliasTarget: { - hostedZoneId: distribution.hostedZoneId, - dnsName: distribution.domainName, - }, -}); -``` +## Create a hosted zone -Note that `aliasTarget.hostedZoneId` is the *distribution's* hosted zone ID -(an attribute CloudFront exposes), not your own zone's. Records are written -with `UPSERT` — create and update are the same operation — and the provider -waits for the Route 53 change to reach `INSYNC` before returning, so the -record is live when the deploy finishes. +To bring a domain into Route 53, declare its zone: -## Custom domain for API Gateway +```typescript title="alchemy.run.ts" +const zone = yield* AWS.Route53.HostedZone("Zone", { name: "example.com" }); +``` -For a REST API, create an `AWS.ApiGateway.DomainName` with a certificate and -map your API's stage onto it with a `BasePathMapping`: +Then set the zone's `nameServers` as the domain's name servers at your registrar. From then on, Route 53 answers for the domain. -```typescript -const domain = yield* AWS.ApiGateway.DomainName("ApiDomain", { - domainName: "api.example.com", - regionalCertificateArn: cert.certificateArn, - endpointConfiguration: { types: ["REGIONAL"] }, - securityPolicy: "TLS_1_2", -}); +This always creates a new zone, since Route 53 allows several zones with the same name. To manage a zone that already exists, pass its id: -yield* AWS.ApiGateway.BasePathMapping("Root", { - domainName: domain.domainName, - restApiId: api.restApiId, - stage: "prod", +```typescript title="alchemy.run.ts" +const zone = yield* AWS.Route53.HostedZone("Zone", { + name: "example.com", + hostedZoneId: "Z0123456789ABCDEFGHIJ", }); ``` -One region caveat: a `REGIONAL` domain needs its certificate in the API's own -region, while `AWS.ACM.Certificate` always issues in `us-east-1`. Deploying -to `us-east-1` works as written; in any other region, pass the ARN of a -certificate that already exists there as `regionalCertificateArn`. +To only reference it, without managing it, use `AWS.Route53.HostedZone.lookup({ id })`. -## Point DNS at the API +## Build it from the pieces -The `DomainName` resource exposes the regional endpoint to alias to: +The `domain` prop is made of resources you can declare yourself. A certificate, validated in the zone: -```typescript -yield* AWS.Route53.Record("ApiAlias", { +```typescript title="alchemy.run.ts" +const cert = yield* AWS.ACM.Certificate("Cert", { + domainName: "app.example.com", + subjectAlternativeNames: ["www.app.example.com"], hostedZoneId: zone.id, - name: "api.example.com", - type: "A", - aliasTarget: { - hostedZoneId: domain.regionalHostedZoneId.as(), - dnsName: domain.regionalDomainName.as(), - }, }); ``` -`regionalDomainName` / `regionalHostedZoneId` are the alias target for -regional endpoints (edge-optimized domains expose -`distributionDomainName` / `distributionHostedZoneId` instead). The `.as()` -narrows the attribute's type — API Gateway only populates the regional fields -for regional endpoint configurations. - -## Where next - -- [Websites on AWS](/aws/frontend/websites) — the `domain` prop in the context of the - full websites surface -- [Deploy a static site](/aws/frontend/static-site) — Router composition and - cache invalidation -- [REST API (API Gateway v1)](/aws/apis/api-gateway) — the API this - domain fronts -- Reference: [Certificate](/providers/aws/acm/certificate), - [Record](/providers/aws/route53/record), - [HostedZone](/providers/aws/route53/hostedzone), - [DomainName](/providers/aws/apigateway/domainname) +Deploy writes the validation records and waits until the certificate is issued, so `cert.certificateArn` is ready to use. For a regional resource outside `us-east-1`, set `region`. + +Alias records pointing a name at a distribution, one per address family: + +```typescript title="alchemy.run.ts" +for (const type of ["A", "AAAA"] as const) { + yield* AWS.Route53.Record(`Alias-${type}`, { + hostedZoneId: zone.id, + name: "app.example.com", + type, + aliasTarget: { hostedZoneId: distribution.hostedZoneId, dnsName: distribution.domainName }, + }); +} +``` + +CloudFront serves IPv6, so without the `AAAA` record IPv6 clients get no answer for the name. The alias target's `hostedZoneId` is the distribution's own, not your zone's. A REST API on API Gateway takes a `DomainName` with the certificate and a `BasePathMapping` onto its stage. See [API Gateway](/aws/apis/api-gateway). + +## Changing a domain + +Certificates can't be changed in place. Adding a name or changing the domain replaces the certificate: a new one is requested and validated, and the resource is moved onto it. + +Validation records stay in the zone after a certificate is deleted, because ACM uses the same record for every certificate on that name. diff --git a/.agents/skills/alchemy/references/aws/observability/cloudwatch.md b/.agents/skills/alchemy/references/aws/observability/cloudwatch.md index 1a762f01..5b17343d 100644 --- a/.agents/skills/alchemy/references/aws/observability/cloudwatch.md +++ b/.agents/skills/alchemy/references/aws/observability/cloudwatch.md @@ -1,185 +1,135 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # CloudWatch -> Declare CloudWatch dashboards as structured widget documents and metric alarms that fire SNS topics — versioned next to the Lambda functions and queues they observe. - -CloudWatch is AWS's built-in metrics store: every Lambda function, -SQS queue, and DynamoDB table publishes metrics into it -automatically. In alchemy the consuming side is code too — a -`Dashboard` is a structured widget document and an `Alarm` is a -threshold on a metric, both declared in the same Stack as the -resources they watch. A tweaked threshold or a new graph is a diff in -the PR, not a console click. - -## Dashboards as code - -`DashboardBody` is a plain object, not a JSON string — alchemy -serializes it to the document the CloudWatch API expects: - -```typescript -import * as AWS from "alchemy/AWS"; - -const dashboard = yield* AWS.CloudWatch.Dashboard("ApiHealth", { - DashboardBody: { - widgets: [ - { - type: "metric", - width: 12, - height: 6, - properties: { - title: "Lambda invocations and errors", - view: "timeSeries", - stat: "Sum", - period: 300, - metrics: [ - ["AWS/Lambda", "Invocations", "FunctionName", "api"], - ["AWS/Lambda", "Errors", "FunctionName", "api"], - ], - }, - }, - ], - }, -}); -``` +> How CloudWatch collects logs and metrics from every AWS service, and how alarms and dashboards declared next to your resources watch them. -Top-level props are PascalCase because they mirror the -`PutDashboard` API input; the widget document inside follows -CloudWatch's own dashboard-body schema (`type`, `properties`, -`metrics`, ...). Four widget types are supported: `metric` (graphs), -`text` (markdown), `alarm` (alarm status grids), and `log` (Logs -Insights queries). Each takes optional `x`/`y`/`width`/`height` grid -coordinates. +CloudWatch is where AWS reports on itself. Every service publishes **metrics** to it without being asked: a Function's invocations and errors, a Queue's depth, a Table's throttled requests. Every Function writes its **logs** to it. **Alarms** watch metrics and tell you when something crosses a line, and **dashboards** put the metrics you care about on one screen. -If you omit `name`, alchemy generates a unique dashboard name from -the app, stage, and logical ID — so `prod` and `pr-42` each get -their own copy. Renaming a dashboard replaces it. +## Metrics come from every service -## Wire in resource names +A **metric** is a series of numbers over time, identified by a **namespace**, a name and **dimensions**. Lambda reports `Errors` in the `AWS/Lambda` namespace, with a `FunctionName` dimension for each Function. SQS reports `ApproximateNumberOfMessagesVisible` per `QueueName`. -Hard-coding `"api"` works until the function is renamed. Metric rows -reference metrics by dimension value, so build the body from the -function's [Output](/infrastructure-as-code/outputs) instead: +You don't publish these. They exist as soon as the resource does, so an alarm or a dashboard can watch them from the first deploy. -```typescript -import * as Output from "alchemy/Output"; +## Logs go to log groups -const func = yield* Api; // an AWS.Lambda.Function +Everything a Function writes to its output lands in a **log group** named after it, `/aws/lambda/`. ECS tasks get a log group too. Set how long they're kept on the runtime, or they're kept forever: -const dashboard = yield* AWS.CloudWatch.Dashboard("ApiDashboard", { - DashboardBody: func.functionName.pipe( - Output.map((functionName) => ({ - widgets: [ - { - type: "metric", - width: 12, - height: 6, - properties: { - title: "Lambda Duration", - stat: "Average", - period: 300, - metrics: [ - ["AWS/Lambda", "Duration", "FunctionName", functionName], - ], - }, - }, - ], - })), - ), +```typescript title="src/api.ts" +{ main: import.meta.url, logging: { retention: "2 weeks" } } +``` + +Read a runtime's logs from your terminal: + +```sh +alchemy logs Api --tail +``` + +## Alarm on a metric + +An **alarm** watches one metric. When the metric crosses a threshold for long enough, the alarm moves to the `ALARM` state: + +```typescript title="alchemy.run.ts" +const api = yield* Api; + +const errors = yield* AWS.CloudWatch.Alarm("ApiErrors", { + Namespace: "AWS/Lambda", + MetricName: "Errors", + Dimensions: [{ Name: "FunctionName", Value: api.functionName }], + Statistic: "Sum", + Period: 60, + EvaluationPeriods: 1, + Threshold: 1, + ComparisonOperator: "GreaterThanOrEqualToThreshold", + TreatMissingData: "notBreaching", }); ``` -`Output.map` defers building the document -until the function's physical name is known, so the dashboard always -tracks the deployed function — including across replacements. +The dimension comes from the Function itself, so the alarm follows it across renames and stages. `TreatMissingData: "notBreaching"` keeps a Function that nobody's calling out of the `INSUFFICIENT_DATA` state. -## Alarms +## Be told when it fires -An `Alarm` watches one metric and changes state when it crosses a -threshold. Props are PascalCase, extending the `PutMetricAlarm` API -input directly; `AlarmActions` is a list of ARN strings — most -commonly an [SNS](/aws/messaging/sns) topic that fans out to email, Slack, or -PagerDuty: +An alarm acts by publishing to an [SNS Topic](/aws/messaging/sns). Subscribe your email, a chat webhook or a pager to the Topic: -```typescript + + +```typescript title="alchemy.run.ts" const alerts = yield* AWS.SNS.Topic("Alerts"); -const errors = yield* AWS.CloudWatch.Alarm("HighErrors", { - MetricName: "Errors", +const errors = yield* AWS.CloudWatch.Alarm("ApiErrors", { Namespace: "AWS/Lambda", + MetricName: "Errors", + Dimensions: [{ Name: "FunctionName", Value: api.functionName }], Statistic: "Sum", Period: 60, EvaluationPeriods: 1, Threshold: 1, ComparisonOperator: "GreaterThanOrEqualToThreshold", - TreatMissingData: "notBreaching", - Dimensions: [{ Name: "FunctionName", Value: func.functionName }], AlarmActions: [alerts.topicArn], }); ``` -`Dimensions` scopes the alarm to one function, and Output references -like `func.functionName` resolve in place. `TreatMissingData: -"notBreaching"` keeps a quiet function out of the `INSUFFICIENT_DATA` -state. The resolved alarm exposes `alarmName`, `alarmArn`, and its -current `stateValue` as outputs. - -Alarms show up on dashboards too — an `alarm` widget renders a -status grid from ARNs: - -```typescript -{ - type: "alarm", - width: 12, - properties: { - title: "Alarms", - alarms: [errors.alarmArn], - }, -}, -``` +Because alarms are declared in the Stack, each stage gets its own. Point production's at a pager and every other stage's at nothing. + +## Put metrics on a dashboard -To aggregate several alarms into one page-worthy signal, -`CompositeAlarm` combines their states with a boolean rule: +A **dashboard** is a grid of widgets. Its body is a plain object, built from the Function's name once it's known: -```typescript -const composite = yield* AWS.CloudWatch.CompositeAlarm("HighSeverity", { - AlarmRule: 'ALARM("HighErrors") OR ALARM("HighLatency")', +```typescript title="alchemy.run.ts" +yield* AWS.CloudWatch.Dashboard("Api", { + DashboardBody: api.functionName.pipe( + Output.map((functionName) => ({ + widgets: [ + { + type: "metric", + width: 12, + height: 6, + properties: { + title: "Invocations and errors", + stat: "Sum", + period: 300, + metrics: [ + ["AWS/Lambda", "Invocations", "FunctionName", functionName], + ["AWS/Lambda", "Errors", "FunctionName", functionName], + ], + }, + }, + ], + })), + ), }); ``` -Like dashboards, alarms get generated per-stage names when `name` is -omitted, and renaming one replaces it. - -## Where metrics come from +Widgets can also show text, a grid of alarm states, or a Logs Insights query. A change to a dashboard is a change in a pull request, reviewed like any other. -You rarely have to publish anything: AWS services emit metrics on -their own. Every Lambda function reports `Invocations`, `Errors`, -`Duration`, and `Throttles` under the `AWS/Lambda` namespace, keyed -by the `FunctionName` dimension — which is why the snippets above -work against a stock [Lambda](/aws/compute/lambda) function with zero -instrumentation. Other services follow suit (`AWS/SQS`, -`AWS/DynamoDB`, ...). +## Combine alarms -For application-level signals — spans, structured logs, custom -metrics from your Effect code — see -[Observability](/testing/observability): Effect emits OpenTelemetry -natively, and the receiving end (datasets, monitors, notifiers) is -provisioned as resources in the same Stack, exactly like the alarms -here. +One failure often trips several alarms at once. A **composite alarm** combines their states with a rule, so you're paged once: -## Where next +```typescript title="alchemy.run.ts" +yield* AWS.CloudWatch.CompositeAlarm("ApiUnhealthy", { + AlarmRule: Output.interpolate`ALARM("${errors.alarmName}") OR ALARM("${latency.alarmName}")`, + AlarmActions: [alerts.topicArn], +}); +``` -- [Observability](/testing/observability) — OTel exporters as - Layers, plus the cross-cloud version of alerts-in-code. -- [Lambda](/aws/compute/lambda) — the functions these dashboards and alarms - watch. -- [Axiom](/axiom) — datasets, monitors, and notifiers when you want - telemetry outside CloudWatch. +Alarm names are generated per stage, so build the rule from each alarm's `alarmName`. -Reference: +## Your own telemetry -- [`Alarm` reference](/providers/aws/cloudwatch/alarm) -- [`Dashboard` reference](/providers/aws/cloudwatch/dashboard) -- [`CompositeAlarm` reference](/providers/aws/cloudwatch/compositealarm) +CloudWatch's built-in metrics describe your resources from the outside. To see inside your code, its spans, structured logs and custom metrics, export OpenTelemetry from your Effect program. See [Observability](/testing/observability), and [Axiom](/axiom) for a backend declared in the same Stack. diff --git a/.agents/skills/alchemy/references/aws/security/federated-identity.md b/.agents/skills/alchemy/references/aws/security/federated-identity.md new file mode 100644 index 00000000..e7e58952 --- /dev/null +++ b/.agents/skills/alchemy/references/aws/security/federated-identity.md @@ -0,0 +1,194 @@ + + +# Federated identity + +> How Cloud Run services and Fly Services reach AWS, and a Lambda reaches GCP, through workload identity federation instead of long-lived keys. + +A runtime on one cloud often needs a resource on the other: a Cloud Run +service sending to an SQS queue, or a Lambda publishing to a Pub/Sub +topic. When the runtime already runs as an identity of its own cloud, +Alchemy lets the other cloud trust that identity. There is no access +key or service account key to create, store, or rotate. + +You write the binding the same way as on a native runtime. Federation is +what Alchemy picks for you. + +[Identity Federation](/infrastructure-as-effects/identity-federation) +covers how federation works across every cloud. + +## Call AWS from Cloud Run + +A Cloud Run service runs as a Google service account. Bind an SQS queue +to it like you would on a Lambda: + +```typescript +// src/api.ts +import * as AWS from "@alchemy.run/aws"; +import * as GCP from "@alchemy.run/gcp"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +export const Jobs = AWS.SQS.Queue("Jobs"); + +export default class Api extends GCP.Run.Service()( + "Api", + { main: import.meta.url }, + Effect.gen(function* () { + const send = yield* AWS.SQS.SendMessage(Jobs); + return { + fetch: send({ MessageBody: "hello" }).pipe( + Effect.as(HttpServerResponse.text("sent")), + Effect.orDie, + ), + }; + }).pipe(Effect.provide(AWS.SQS.SendMessageHttp)), +) {} +``` + +The binding creates an IAM role that trusts Google's ID tokens for that +one service account, and puts `sqs:SendMessage` on the role. The trust +policy matches the account's unique ID, which the service exposes as +`serviceAccountUniqueId`: + +```json +{ + "Effect": "Allow", + "Principal": { "Federated": "accounts.google.com" }, + "Action": "sts:AssumeRoleWithWebIdentity", + "Condition": { + "StringEquals": { + "accounts.google.com:sub": "104729384756102938475", + "accounts.google.com:aud": "104729384756102938475", + "accounts.google.com:oaud": "sts.amazonaws.com" + } + } +} +``` + +At runtime the service asks its metadata server for an ID token and +trades it for the role's credentials with `AssumeRoleWithWebIdentity`. +The credentials last an hour and are assumed again, with a fresh token, +shortly before they expire. + +## Call AWS from a Fly Service + +A Fly Service runs on Fly Machines, and every Machine can mint an OIDC +token signed by `https://oidc.fly.io/`. Bind a bucket to it the same +way: + +```typescript +// src/api.ts +import * as AWS from "@alchemy.run/aws"; +import * as Fly from "@alchemy.run/fly"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +export const Uploads = AWS.S3.Bucket("Uploads"); + +export default class Api extends Fly.Service()( + "Api", + { main: import.meta.url, port: 3000 }, + Effect.gen(function* () { + const putObject = yield* AWS.S3.PutObject(yield* Uploads); + return { + fetch: putObject({ Key: "hello.txt", Body: "hello" }).pipe( + Effect.as(HttpServerResponse.text("stored")), + Effect.orDie, + ), + }; + }).pipe(Effect.provide(AWS.S3.PutObjectHttp)), +) {} +``` + +The binding registers Fly's issuer for your organization as an IAM OIDC +provider, and creates a role that trusts tokens from that one App. A +token names its Machine as `::`, so the trust policy +matches every Machine of the App and nothing else: + +```json +{ + "Effect": "Allow", + "Principal": { + "Federated": "arn:aws:iam::123456789012:oidc-provider/oidc.fly.io/my-org" + }, + "Action": "sts:AssumeRoleWithWebIdentity", + "Condition": { + "StringEquals": { "oidc.fly.io/my-org:aud": "sts.amazonaws.com" }, + "StringLike": { "oidc.fly.io/my-org:sub": "my-org:api-app:*" } + } +} +``` + +IAM keeps one provider per issuer in an account, so every stack in the +account shares it. Destroying a stack leaves the provider in place. + +At runtime the Machine asks its `/.fly/api` socket for a token and +trades it for the role's credentials. Tokens last 10 minutes; a fresh +one is minted each time the credentials are assumed again. The socket +answers only root, the default user in the images Alchemy builds. +See [Fly federated identity](/fly/federated-identity) for the tokens +themselves and the shared provider. + +## Call GCP from a Lambda + +A Lambda runs as an IAM role. Bind a Pub/Sub topic to it: + +```typescript +// src/worker.ts +import * as AWS from "@alchemy.run/aws"; +import * as GCP from "@alchemy.run/gcp"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +export const Events = GCP.PubSub.Topic("Events", {}); + +export default class Worker extends AWS.Lambda.Function()( + "Worker", + { main: import.meta.url, functionUrl: true }, + Effect.gen(function* () { + const publish = yield* GCP.PubSub.Publish(yield* Events); + return { + fetch: publish({ body: { messages: [{ data: btoa("hello") }] } }).pipe( + Effect.as(HttpServerResponse.text("published")), + Effect.orDie, + ), + }; + }).pipe(Effect.provide(GCP.PubSub.PublishHttp)), +) {} +``` + +The binding creates a service account that holds the publisher role, +and lets the Lambda's role impersonate it. The trust goes through a +workload identity pool with an AWS provider for your account. The stack +shares one pool, so every AWS runtime in the stack uses it. + +At runtime the Lambda signs an STS `GetCallerIdentity` request with its +own role credentials and sends it to Google STS. Google replays the +request against AWS to learn which role is calling, and returns a token +for the service account. The token lasts an hour and is exchanged again +before it expires. + +## Which runtimes federate + +Lambda functions, ECS tasks and services, EC2 instances and launch +templates, App Runner services, Batch jobs, EKS pods, and Fly Services +reach GCP this way. +Cloud Run services, jobs, and worker pools, Cloud Functions, and Fly +Services reach AWS this way. + +Runtimes without an identity the other cloud can trust still get a key: +a Cloudflare Worker, a Railway service, a Fly Sprite, and a GKE pod +calling AWS. The key belongs to an identity that may do only what that +one host needs. The binding code is the same either way. + +## New grants take a few minutes + +A freshly created role or federated grant is not usable right away. AWS +usually accepts a new role's trust within seconds. A GCP grant to a +federated principal can take a few minutes. Until it lands, calls fail +with a permission error, so retry the first call after a deploy. + +See [IAM & bindings](/gcp/security/iam) for the roles each GCP binding +grants. diff --git a/.agents/skills/alchemy/references/aws/security/secrets-env.md b/.agents/skills/alchemy/references/aws/security/secrets-env.md index daaca93b..34571894 100644 --- a/.agents/skills/alchemy/references/aws/security/secrets-env.md +++ b/.agents/skills/alchemy/references/aws/security/secrets-env.md @@ -1,144 +1,74 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Secrets & env -> Deliver API keys from .env to a Lambda with effect/Config, and graduate to AWS Secrets Manager when the secret is a shared, generated, or rotated cloud resource. +> How configuration and secrets reach a runtime on AWS, as environment variables from effect/Config or as Secrets Manager secrets read through a binding, and when to use each. -Secrets on AWS come in two tiers. Values in your `.env` that only -your own code reads travel to the Lambda as environment variables -via `effect/Config` — one line binds at deploy time and resolves at -runtime. When the secret is a cloud resource other things consume, -it belongs in [Secrets Manager](#graduate-to-secrets-manager). The -rule: in your `.env` and read only by your code → `Config`; -shared, generated, or rotated → Secrets Manager. +Your code needs values it shouldn't hard-code: an API key for a payment provider, a database password, a feature flag. On AWS those reach a runtime one of two ways. As an **environment variable**, set on the runtime when it's deployed. Or as a **secret** in Secrets Manager, read by the runtime while it runs. -## Bind a secret from .env +## Environment variables -`yield* Config.Redacted(...)` in the function's Construction phase reads -your `.env` at deploy time and binds the value as a Lambda -environment variable: +Read a value with `effect/Config` in a runtime's Construction phase, and the deploy sets it on the Lambda Function as an environment variable. How `Config` reaches a runtime, on any cloud, is in [Secrets and Config](/environments/secrets). -```typescript -// src/api.ts -import * as AWS from "alchemy/AWS"; -import * as Config from "effect/Config"; -import * as Effect from "effect/Effect"; -import * as HttpServerResponse from "effect/http/HttpServerResponse"; - -export default class Api extends AWS.Lambda.Function()( - "Api", - { main: import.meta.url, functionUrl: true }, - Effect.gen(function* () { - const apiKey = yield* Config.Redacted("OPENAI_API_KEY"); - - return { - fetch: Effect.gen(function* () { - return HttpServerResponse.text("ok"); - }), - }; - }), -) {} -``` - -At runtime the same line resolves from that env var — one line, -both phases. - -## Unwrap at the call site - -The value is `Redacted`; unwrap with `Redacted.value` only -where the raw string is needed: - -```typescript -fetch: Effect.gen(function* () { - return HttpServerResponse.text(`Bearer ${Redacted.value(apiKey)}`); -}), -``` - -Interpolating the wrapper itself (`` `Bearer ${apiKey}` ``) produces -the literal text ``, not the value — that's the point. - -## Plain vars and defaults - -Non-secret config uses the same mechanism with `Config.String` and -`Config.Number`: - -```typescript -const host = yield* Config.String("HOST"); -const port = yield* Config.Number("PORT").pipe(Config.withDefault(3000)); +```typescript title="src/api.ts" +const apiKey = yield* Config.Redacted("STRIPE_API_KEY"); ``` -Values JSON round-trip through the environment, so `port` comes -back as a number. Combinators re-run at runtime against the bound -source, and a default is never bound — see -[Secrets and Config](/environments/secrets) for the full semantics. +On AWS, a Function's environment variables are part of its configuration. Lambda encrypts them at rest, and together they can be at most 4 KB. Larger values go in Secrets Manager. -## Resolve Config in the constructor, not in fetch +## Values from a secrets manager -A `Config` yielded only inside `fetch` is never discovered at -deploy time, so the env var won't exist at runtime: +`.env` is only the default. A Stack's `secrets` option reads the same `Config` values from a secrets manager instead, like Doppler or Infisical, so production keys never sit in a file on anyone's machine. Pick the source per stage: -```typescript -export default class Api extends AWS.Lambda.Function()( - "Api", - { main: import.meta.url, functionUrl: true }, +```typescript title="alchemy.run.ts" +import * as Alchemy from "alchemy"; +import * as AWS from "@alchemy.run/aws"; +import * as Doppler from "@alchemy.run/doppler"; +import * as Effect from "effect/Effect"; +import Api from "./src/api.ts"; + +export default Alchemy.Stack( + "MyApp", + { + providers: AWS.providers(), + state: AWS.state(), + secrets: ({ stage }) => + stage === "prod" + ? Doppler.Secrets({ project: "my-app", config: "prd" }) + : Alchemy.Secrets.DotEnv(), + }, Effect.gen(function* () { - return { - fetch: Effect.gen(function* () { - // 🚫 never bound — API_KEY won't exist at runtime - const apiKey = yield* Config.Redacted("API_KEY"); - }), - }; + const api = yield* Api; + return { url: api.functionUrl }; }), -) {} +); ``` -Resolve in the outer `Effect.gen`, capture in a `const`, reference -that `const` from `fetch`. +Your code doesn't change: `Config.Redacted("STRIPE_API_KEY")` reads from whichever source the stage uses. See [Secret providers](/environments/secret-providers) for Doppler, Infisical, ordering several sources, and writing your own. -## Graduate to Secrets Manager +## When to use Secrets Manager -Reach for Secrets Manager when the secret is an AWS-native concern: +An environment variable is part of the Function's configuration. Anyone who can read the configuration can read the value, and changing it means a deploy. -- **Shared consumers** — other resources reference the secret by - ARN (Aurora clusters and RDS proxies consume password-backed JSON - secrets in exactly the shape `generateSecretString` produces). -- **Generated values** — the plaintext never enters your repo, - `.env`, or deploy logs. -- **Least-privilege reads** — access is an IAM grant on one ARN, - not an env var visible to the whole function config. -- **Rotation without redeploy** — put a new value and running - functions read it on their next call. +A **secret** in Secrets Manager is a resource of its own. Reading it is an IAM permission on one ARN. Other resources, like an Aurora cluster, can use it directly. Its value can be generated by AWS, so you never see it. And putting a new value takes effect on the next read, without a deploy. -## Create a secret +So keep values from your own `.env`, read only by your code, in Config. Put values that are shared with other resources, generated, or rotated in Secrets Manager. -`Secret` owns the metadata and current value; pass the value as -`Redacted` so it never appears in logs or state: +## Create a secret -```typescript -import * as AWS from "alchemy/AWS"; -import * as Redacted from "effect/Redacted"; +Declare a secret and give it a value as `Redacted`, so it stays out of logs and state: -const dbSecret = yield* AWS.SecretsManager.Secret("DbSecret", { - description: "Database credentials", - secretString: Redacted.make( - JSON.stringify({ username: "app", password: "super-secret" }), - ), +```typescript title="alchemy.run.ts" +const webhookSecret = yield* AWS.SecretsManager.Secret("WebhookSecret", { + secretString: yield* Config.Redacted("WEBHOOK_SECRET"), }); ``` -Omit `name` for a deterministic generated name; changing `name` -replaces the secret (new ARN), everything else updates in place. -On destroy alchemy deletes with `ForceDeleteWithoutRecovery` — -removal is immediate, no recovery window. - -## Generate the value instead +Or let Secrets Manager generate the value at deploy time, so it never exists in your repo or your `.env`: -For credentials nothing outside AWS needs to see, let Secrets -Manager mint the password at deploy time: - -```typescript +```typescript title="alchemy.run.ts" const dbSecret = yield* AWS.SecretsManager.Secret("DbSecret", { generateSecretString: { secretStringTemplate: JSON.stringify({ username: "app" }), @@ -148,73 +78,23 @@ const dbSecret = yield* AWS.SecretsManager.Secret("DbSecret", { }); ``` -The stored value is the template merged with the generated password -— `{"username":"app","password":""}` — and the plaintext -never lives in your repo, `.env`, or logs. - -## Read it from a Lambda +The stored value is the template with a random `password` added, the shape Aurora and RDS Proxy expect. Destroying a secret deletes it at once, with no recovery window. -`GetSecretValue` is a binding: yield it in the constructor to grant IAM at -deploy time, call it at runtime for a fresh read: +## Read it from a runtime -```typescript -// src/api.ts -import * as AWS from "alchemy/AWS"; -import * as Effect from "effect/Effect"; -import * as HttpServerResponse from "effect/http/HttpServerResponse"; -import * as Redacted from "effect/Redacted"; +Bind `SecretsManager.GetSecretValue`. The runtime's role gets permission to read this one secret: -export default class Api extends AWS.Lambda.Function()( - "Api", - { main: import.meta.url, functionUrl: true }, - Effect.gen(function* () { - const dbSecret = yield* AWS.SecretsManager.Secret("DbSecret", { - generateSecretString: { - secretStringTemplate: JSON.stringify({ username: "app" }), - generateStringKey: "password", - }, - }); - - const getDbSecret = yield* AWS.SecretsManager.GetSecretValue(dbSecret); - - return { - fetch: Effect.gen(function* () { - const value = yield* getDbSecret(); - const creds = Redacted.isRedacted(value.SecretString) - ? (JSON.parse(Redacted.value(value.SecretString)) as { - username: string; - }) - : undefined; - return yield* HttpServerResponse.json({ user: creds?.username }); - }).pipe(Effect.orDie), - }; - }).pipe(Effect.provide(AWS.SecretsManager.GetSecretValueHttp)), -) {} +```typescript title="src/api.ts" +const getDbSecret = yield* AWS.SecretsManager.GetSecretValue(dbSecret); ``` -The binding adds `secretsmanager:GetSecretValue` and -`secretsmanager:DescribeSecret` to the execution role, scoped to -this secret's ARN only. `SecretString` comes back as `Redacted` — -unwrap with `Redacted.value` at the point of use. The value is -fetched per call, not baked into env, so putting a new version (the -[`PutSecretValue` binding](/providers/aws/secretsmanager/putsecretvalue)) -propagates on the next read. +Call it while the runtime runs. `SecretString` comes back `Redacted`: -## Where next - -Related: - -- [RDS](/aws/data/rds) — Aurora generates a password-backed secret in - exactly the `generateSecretString` shape; the `Connect` binding - reads it at request time. -- [Lambda](/aws/compute/lambda) — the function model env vars and bindings - attach to. -- [Secrets and Config](/environments/secrets) — the Construction/Runtime split - and transformation semantics. -- [Secrets & env on Cloudflare](/cloudflare/security/secrets-env) — the same - spine on Cloudflare. +```typescript title="src/api.ts" +const { SecretString } = yield* getDbSecret(); +const { password } = JSON.parse(Redacted.value(SecretString!)) as { password: string }; +``` -Reference: +Provide `AWS.SecretsManager.GetSecretValueHttp` to the runtime. Each call reads the current value, so a rotated secret is picked up on the next one. Cache it for the life of an environment if you read it on every request. -- [`Secret` reference](/providers/aws/secretsmanager/secret) -- [`GetSecretValue` reference](/providers/aws/secretsmanager/getsecretvalue) +For deploy credentials and CI, see [Setup](/aws/setup). For secrets that come from a provider like Doppler or Infisical, see [Secret providers](/environments/secret-providers). diff --git a/.agents/skills/alchemy/references/aws/setup.md b/.agents/skills/alchemy/references/aws/setup.md index 42063529..1791091f 100644 --- a/.agents/skills/alchemy/references/aws/setup.md +++ b/.agents/skills/alchemy/references/aws/setup.md @@ -1,28 +1,24 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Setup -> Connect Alchemy to AWS with SSO, stored access keys, or CI environment credentials. +> Connect Alchemy to AWS with SSO, console login, stored access keys, or CI environment credentials. ## Prerequisites -- [Bun](https://bun.sh) or Node.js 22+ +- [Node.js](https://nodejs.org) 24.11.1+ or [Bun](https://bun.sh) - An AWS account and an IAM identity with permission to create the resources you plan to deploy ## Create a project -```sh -mkdir my-app && cd my-app && bun init -y -``` + ## Install -```sh -bun add "alchemy@latest" "effect@rc" "@effect/platform-bun@rc" "@effect/platform-node@rc" -``` + ## How Alchemy gets AWS credentials @@ -32,15 +28,19 @@ authentication method. The choice is saved to your **`default`** command; a deploy with nothing configured fails with that exact command to run. Authentication changes only through the `profile` command. -There are two local profile methods: +There are three local profile methods. Start with console login unless your organization already signs in through IAM Identity Center. + +### Console login (recommended) + +Console login is AWS's keyless sign-in for every account. You sign in to the AWS Management Console in your browser, as the root user, an IAM user or through federation, and the AWS CLI receives short-lived credentials for that same identity. There's nothing to set up in the account, and no long-lived access keys on your machine. + +Alchemy runs `aws login --profile ` (AWS CLI v2.32+) for you and loads the session it writes to `~/.aws/config` (`login_session`). When the session expires, run `alchemy profile refresh`. + +### SSO through IAM Identity Center -### SSO (recommended) +SSO is for organizations that have set up **IAM Identity Center**: a single sign-in for many accounts, with users and permission sets managed centrally, often connected to Okta, Google Workspace or Entra ID. It takes setup in an AWS Organization, so it pays off when a team works across several accounts. -Alchemy runs `aws sso login --profile ` for you and loads -credentials from the AWS SSO cache. You pick which profile from -`~/.aws/config` to use; the account ID and region come from that -profile. When the SSO session expires, run -`alchemy profile edit --reconfigure AWS` to refresh it. +Alchemy runs `aws sso login --profile ` for you and loads credentials from the AWS SSO cache. The profile you pick in `~/.aws/config` decides the account and region. When the session expires, run `alchemy profile refresh`. ### Stored access keys @@ -68,7 +68,7 @@ The region is required. The account ID is taken from ## Managing credentials Re-run the setup at any time (e.g. to switch from stored keys to -SSO, or to configure a separate `prod` profile): +SSO or console login, or to configure a separate `prod` profile): ```sh alchemy profile edit --reconfigure AWS @@ -88,12 +88,15 @@ profiles with `--profile` or `$ALCHEMY_PROFILE`. ## State storage For AWS stacks, pass `AWS.state()` as the Stack's `state` -option. Deploy state is stored in an account-regional S3 bucket -(`alchemy-state-{accountId}-{region}-an`), created lazily on the -first deploy — the same configuration works locally and in CI -with no extra setup. For purely local iteration, -`Alchemy.localState()` writes state under `.alchemy/` next to -your code instead. +option. Deploy state is stored in a DynamoDB table +(`alchemy-state`), created lazily on the first deploy. In CI, +provision it once with `alchemy state bootstrap --backend aws`. +For purely local iteration, `Alchemy.localState()` writes state +under `.alchemy/` next to your code instead. + +State from earlier versions lives in an S3 bucket; move it with +`alchemy state migrate`. See +[Migrating from the S3 store](/state-store#migrating-from-the-s3-store). ## Next steps diff --git a/.agents/skills/alchemy/references/aws/tutorial/part-1.md b/.agents/skills/alchemy/references/aws/tutorial/part-1.md index 899cd833..13a77a38 100644 --- a/.agents/skills/alchemy/references/aws/tutorial/part-1.md +++ b/.agents/skills/alchemy/references/aws/tutorial/part-1.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Part 1: Your First Stack @@ -11,7 +11,7 @@ with an AWS S3 Bucket, and deploy it — all in under five minutes. ## Prerequisites -- [Bun](https://bun.sh) or Node.js 22+ +- [Node.js](https://nodejs.org) 24.11.1+ or [Bun](https://bun.sh) - An AWS account and an IAM identity with permission to create the resources you plan to deploy @@ -19,17 +19,13 @@ with an AWS S3 Bucket, and deploy it — all in under five minutes. Start with an empty directory and initialize a `package.json`: -```sh -mkdir my-app && cd my-app && bun init -y -``` + ## Install dependencies -Install alchemy@latest and effect@{effectVersion}: +Install `alchemy@latest`, `@alchemy.run/aws`, and `effect`: -```sh -bun add "alchemy@latest" "effect@rc" "@effect/platform-bun@rc" "@effect/platform-node@rc" -``` + ## Create the Stack @@ -41,7 +37,7 @@ Create an `alchemy.run.ts` file: ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; export default Alchemy.Stack( @@ -70,11 +66,10 @@ keys with `alchemy profile edit --add AWS`. See ## Where state lives -`state: AWS.state()` stores deploy state in an account-regional S3 -bucket (`alchemy-state-{accountId}-{region}-an`), created lazily on +`state: AWS.state()` stores deploy state in a DynamoDB table +(`alchemy-state`) in your account, created lazily on the first deploy. Because the state lives in your AWS account rather -than on disk, the same configuration works locally and in CI with no -extra setup. +than on disk, the same configuration works locally and in CI. :::note[Other state stores] For purely local iteration you can use `Alchemy.localState()` @@ -93,7 +88,7 @@ Add an S3 Bucket: ```diff lang="typescript" // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; export default Alchemy.Stack( @@ -136,21 +131,20 @@ rest of the stack outputs. Run `alchemy deploy` to create the Bucket on AWS: -```sh -bun alchemy deploy -``` + Connect AWS first with `alchemy profile edit --add AWS` and pick a -local authentication method: **SSO** (recommended) or **stored access -keys**. The choice is saved to your **`default`** -[profile](/environments/profiles); the region and account come from -whichever method you pick, and a deploy with nothing configured fails -with that exact command to run. CI instead reads AWS environment -credentials directly. See [Setup](/aws/setup) for the full walkthrough. +local authentication method: **console login** (recommended, +`aws login`), **SSO** through IAM Identity Center, or **stored access keys**. The choice is saved to your +**`default`** [profile](/environments/profiles); the region and account +come from whichever method you pick, and a deploy with nothing +configured fails with that exact command to run. CI instead reads AWS +environment credentials directly. See [Setup](/aws/setup) for the full +walkthrough. :::tip To re-run the credential prompt later (e.g. to switch from stored -keys to SSO), use `alchemy profile edit --reconfigure AWS`. For a +keys to SSO or console login), use `alchemy profile edit --reconfigure AWS`. For a separate profile, run `alchemy profile create prod` followed by `alchemy profile edit --profile prod`. ::: @@ -200,11 +194,9 @@ Alchemy figures out what changed. The inverse of `deploy` is `destroy` — it plans against an empty desired state and deletes everything the stack created: -```sh -bun alchemy destroy -``` + -Try it if you like, then run `bun alchemy deploy` again to bring the +Try it if you like, then run `alchemy deploy` again to bring the bucket back — we'll build on it in Part 2. ## Recap diff --git a/.agents/skills/alchemy/references/aws/tutorial/part-2.md b/.agents/skills/alchemy/references/aws/tutorial/part-2.md index 4f5470c6..35b841ef 100644 --- a/.agents/skills/alchemy/references/aws/tutorial/part-2.md +++ b/.agents/skills/alchemy/references/aws/tutorial/part-2.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Part 2: Add a Lambda @@ -19,7 +19,7 @@ declaration: ```typescript // src/api.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; export default class Api extends AWS.Lambda.Function()( @@ -47,7 +47,7 @@ wired up to handle incoming HTTP requests: ```diff lang="typescript" // src/api.ts -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; @@ -77,9 +77,10 @@ handling a request. ## Expose a public URL -`fetch` exists, but no one can call it yet. Set `functionUrl: true` on the -props to ask AWS for a public **Function URL** — no API Gateway, no -auth, just a public HTTPS endpoint: +Every Lambda Function gets a public **Function URL** by default: +`functionUrl` defaults to `true`, which creates an unauthenticated HTTPS +endpoint (`authType: "NONE"`) and lets anyone invoke it. Spell it out +so the access level is visible in the code: ```diff lang="typescript" export default class Api extends AWS.Lambda.Function()( @@ -94,9 +95,19 @@ export default class Api extends AWS.Lambda.Function()( ) {} ``` -The resolved `Api` resource will now expose a `functionUrl` field +The resolved `Api` resource exposes a `functionUrl` field carrying that endpoint — we'll surface it from the Stack in a moment. +`functionUrl` takes three access choices. `false` creates no URL, +`true` creates a public one, and `{ authType: "AWS_IAM" }` requires +SigV4-signed requests. + +:::caution +Omitting `functionUrl` gives you a public URL. A Function that only +consumes events (SQS, SNS, EventBridge, Kinesis, S3) should set +`functionUrl: false`. +::: + ## Move the Bucket into the function In Part 1 the Bucket lived in `alchemy.run.ts`, but resources can be @@ -106,8 +117,8 @@ everything about the function in one file. Add it to the constructor: ```diff lang="typescript" // src/api.ts -import * as AWS from "alchemy/AWS"; -+import * as S3 from "alchemy/AWS/S3"; +import * as AWS from "@alchemy.run/aws"; ++import * as S3 from "@alchemy.run/aws/S3"; import * as Effect from "effect/Effect"; import * as HttpServerResponse from "effect/http/HttpServerResponse"; @@ -153,7 +164,7 @@ Both capability calls return a callable Effect: `putObject` takes a Alchemy fills in for you) and `getObject` takes a `GetObjectRequest`. Each call is 1:1 with an IAM statement on the execution role — delete a capability call and the matching statement disappears next deploy. -See [S3 → One binding, one IAM statement](/aws/data/s3#one-binding-one-iam-statement) +See [IAM and bindings](/aws/iam#bindings-write-the-policy) for the exact mapping. ## Write objects with `PUT /:key` @@ -163,8 +174,8 @@ object key and writes the request body to the bucket: ```diff lang="typescript" // src/api.ts -import * as AWS from "alchemy/AWS"; -import * as S3 from "alchemy/AWS/S3"; +import * as AWS from "@alchemy.run/aws"; +import * as S3 from "@alchemy.run/aws/S3"; import * as Effect from "effect/Effect"; +import { HttpServerRequest } from "effect/http/HttpServerRequest"; import * as HttpServerResponse from "effect/http/HttpServerResponse"; @@ -264,7 +275,7 @@ case). Bindings declare a capability; **runtime layers** implement it. For S3 those are `S3.PutObjectHttp` and `S3.GetObjectHttp` — both ship in -`alchemy/AWS/S3` and depend only on the AWS SDK and the ambient +`@alchemy.run/aws/S3` and depend only on the AWS SDK and the ambient credentials. Provide them at the bottom of the function: ```diff lang="typescript" @@ -295,7 +306,7 @@ Stack's Effect is what registers the resource and starts the deploy: ```diff lang="typescript" // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; +import Api from "./src/api.ts"; @@ -346,9 +357,7 @@ Construction phase runs — it just isn't surfaced as a stack output anymore. Deploy again. Alchemy detects the new function and the unchanged bucket: -```sh -bun alchemy deploy -``` + ```text Plan: 1 to create diff --git a/.agents/skills/alchemy/references/aws/tutorial/part-3.md b/.agents/skills/alchemy/references/aws/tutorial/part-3.md index bb10b6f0..be36c394 100644 --- a/.agents/skills/alchemy/references/aws/tutorial/part-3.md +++ b/.agents/skills/alchemy/references/aws/tutorial/part-3.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Part 3: Testing @@ -10,6 +10,12 @@ In [Part 2](/aws/tutorial/part-2) you deployed a Lambda with S3 bindings. Now you'll write integration tests that deploy the stack, hit the live Function URL over HTTP, and verify it works. +## Install the test harness + +`Test.make` ships in `@alchemy.run/test`. Add it as a dev dependency: + + + ## Create the test file Alchemy ships test utilities for Bun that wrap `bun:test` with Effect @@ -19,8 +25,8 @@ you used in your `Stack`: ```typescript // test/integ.test.ts -import * as AWS from "alchemy/AWS"; -import * as Test from "alchemy/Test/Bun"; +import * as AWS from "@alchemy.run/aws"; +import * as Test from "@alchemy.run/test/Bun"; import { expect } from "bun:test"; import * as Effect from "effect/Effect"; import Stack from "../alchemy.run.ts"; @@ -35,10 +41,11 @@ const { test, beforeAll, afterAll, deploy, destroy } = Test.make({ `bun:test` directly — `Test.make` only provides the Effect-aware test runner pieces. -:::note[Using Vitest?] -`alchemy/Test/Vitest` exposes the exact same API — swap the import -and take `expect` from `@effect/vitest` instead. See -[Test harness → Bun vs Vitest](/testing/test-harness#bun-vs-vitest). +:::note[Using Vitest or alchemy-test?] +`@alchemy.run/test/Vitest` and `@alchemy.run/test/Alchemy` expose the exact same +API — swap the import and take `expect` from `@effect/vitest` or +`@alchemy.run/test` instead. See +[Test harness → Runners](/testing/test-harness#runners). ::: ## Deploy the stack before tests @@ -105,8 +112,8 @@ function actually handles requests: ```diff lang="typescript" // test/integ.test.ts -import * as AWS from "alchemy/AWS"; -import * as Test from "alchemy/Test/Bun"; +import * as AWS from "@alchemy.run/aws"; +import * as Test from "@alchemy.run/test/Bun"; import { expect } from "bun:test"; import * as Effect from "effect/Effect"; +import * as HttpBody from "effect/http/HttpBody"; diff --git a/.agents/skills/alchemy/references/aws/tutorial/part-4.md b/.agents/skills/alchemy/references/aws/tutorial/part-4.md index 86096462..e50c31f4 100644 --- a/.agents/skills/alchemy/references/aws/tutorial/part-4.md +++ b/.agents/skills/alchemy/references/aws/tutorial/part-4.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Part 4: Stages @@ -18,13 +18,11 @@ the infrastructure. You've been using stages all along. If you don't pass `--stage`, Alchemy deploys to **`live_$USER`** (e.g. `live_sam`): -```sh -$ whoami + Each developer on your team automatically gets a personal sandbox without any config. The resolution order is: @@ -39,9 +37,7 @@ without any config. The resolution order is: Pass `--stage` to deploy a completely separate instance of the same program: -```sh -bun alchemy deploy --stage staging -``` + ```text Plan: 2 to create @@ -92,8 +88,8 @@ to the surrounding Stack context, including the current `stage`: ```diff lang="typescript" // src/api.ts -import * as AWS from "alchemy/AWS"; -import * as S3 from "alchemy/AWS/S3"; +import * as AWS from "@alchemy.run/aws"; +import * as S3 from "@alchemy.run/aws/S3"; +import { Stack } from "alchemy/Stack"; import * as Effect from "effect/Effect"; // ... @@ -104,7 +100,7 @@ export default class Api extends AWS.Lambda.Function()( + Stack.useSync((stack) => ({ + main: import.meta.url, + functionUrl: true, -+ memory: stack.stage === "prod" ? 1024 : 512, ++ memorySize: stack.stage === "prod" ? 1024 : 512, + })), Effect.gen(function* () { /* ... */ @@ -120,9 +116,7 @@ configuration, no separate config files. When you're done with an environment, tear down just that stage: -```sh -bun alchemy destroy --stage staging -``` + The plan lists everything in `staging` for deletion and leaves every other stage alone. diff --git a/.agents/skills/alchemy/references/aws/tutorial/part-5.md b/.agents/skills/alchemy/references/aws/tutorial/part-5.md index 1a6c8298..5107610d 100644 --- a/.agents/skills/alchemy/references/aws/tutorial/part-5.md +++ b/.agents/skills/alchemy/references/aws/tutorial/part-5.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Part 5: CI/CD @@ -22,8 +22,8 @@ assumes the role at runtime and no secret ever exists to leak. CI needs to share state across runs, so a local `.alchemy/` directory won't cut it. You already configured `AWS.state()` back in [Part 1](/aws/tutorial/part-1#where-state-lives), which stores state -in an account-regional S3 bucket. Every deploy — local or from CI — -reads and writes state through that bucket. +in a DynamoDB table in your account. Every deploy — local or from CI — +reads and writes state through that table. Double-check it's still wired up in `alchemy.run.ts`: @@ -90,8 +90,8 @@ profile) to provision the IAM role CI will use. ```typescript // stacks/github.ts import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; -import * as GitHub from "alchemy/GitHub"; +import * as AWS from "@alchemy.run/aws"; +import * as GitHub from "@alchemy.run/github"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -333,8 +333,8 @@ Post the live URL as a comment on every PR. Update `alchemy.run.ts`: ```diff lang="typescript" // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; -+import * as GitHub from "alchemy/GitHub"; +import * as AWS from "@alchemy.run/aws"; ++import * as GitHub from "@alchemy.run/github"; +import * as Output from "alchemy/Output"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; diff --git a/.agents/skills/alchemy/references/aws/what-is-aws.md b/.agents/skills/alchemy/references/aws/what-is-aws.md new file mode 100644 index 00000000..bfd5b937 --- /dev/null +++ b/.agents/skills/alchemy/references/aws/what-is-aws.md @@ -0,0 +1,244 @@ + + +# What is AWS? + +> The concepts behind AWS — accounts, regions, IAM identities and policies, resources and ARNs, runtimes, event sources, VPCs and the edge — and how @alchemy.run/aws models each of them. + +Amazon Web Services (AWS) is a cloud platform with services for databases, queues, object storage, functions, containers, virtual machines, networks, DNS and more. Each service creates **resources** in your **account**, and every call to a resource is checked against **IAM**, the service that decides who may do what. + +Take one small app: a Lambda Function that stores files in an S3 Bucket and queues jobs for a second Function. Your profile signs you in to an account and sets a default region. Inside it, a Function runs as a role, and the role's policy lets it reach the Bucket and the Queue. The Queue in turn invokes the worker. + + + +## Accounts: the boundary around everything + +An **AWS account** is a container for resources, identified by a twelve-digit id like `123456789012`. Everything you create lives in exactly one account, every bill is per account, and by default nothing in one account can see anything in another. + +That makes the account the strongest isolation AWS offers. Most teams run production in its own account and give development, staging and each engineer separate ones. An **organization** groups accounts under one bill and one set of guardrails. + +Alchemy deploys into whichever account your [profile](/environments/profiles) signs in to. You choose it once, in [Setup](/aws/setup): + +```sh +alchemy profile edit --add AWS +``` + +See [Accounts and regions](/aws/accounts-and-regions). + +## Regions: where a resource runs + +A **region** is a geographic location with its own copy of each service: `us-east-1` in Virginia, `eu-west-1` in Ireland, `ap-southeast-2` in Sydney. A Bucket in `us-east-1` is a different resource from one in `eu-west-1`, and most services never move data between regions on their own. + +Each region is built from several **Availability Zones**: separate data centers with independent power and networking. Services like Lambda, DynamoDB and SQS spread across zones for you. Networks and virtual machines make you choose. + +A few services are **global**: IAM, CloudFront and Route 53 have one copy for the whole account. Your profile sets the default region, where every regional resource in your Stack is created. + +See [Accounts and regions](/aws/accounts-and-regions). + +## IAM: who may do what + +Every request to AWS is made by an **identity** and checked by IAM. Nothing is allowed until a policy allows it. + +A **policy** is a list of statements. Each statement allows or denies a set of **actions** on a set of **resources**: + +```json +{ + "Effect": "Allow", + "Action": ["s3:PutObject"], + "Resource": "arn:aws:s3:::myapp-files-a1b2c3/*" +} +``` + +Identities come in two kinds. An **IAM user** is a long-lived identity with its own keys. An **IAM role** has no keys at all: something trusted **assumes** it and gets temporary credentials. People sign in through IAM Identity Center and assume a role in each account. Code runs as a role too: every Lambda Function has an **execution role**, and the role's policies are exactly what the code may call. + +See [IAM and bindings](/aws/iam). + +## Resources and ARNs + +A **resource** is one thing a service manages: a Bucket, a Table, a Queue, a Function. Each one has a name you choose, or Alchemy generates, and an **Amazon Resource Name** (ARN) that identifies it across all of AWS: + +```text +arn:aws:sqs:us-east-1:123456789012:myapp-jobs-a1b2c3 +``` + +The ARN carries the service, the region, the account and the name. IAM statements, event sources and other resources refer to it, so it's the value you pass around most. + +In Alchemy, you declare a resource in your Stack and read its attributes, ARN included, from what it returns: + +```typescript title="src/queue.ts" +export const Jobs = AWS.SQS.Queue("Jobs"); +``` + +Alchemy names it from your app, stage and the id you gave it, so `dev` and `prod` each get their own Queue. It also **tags** it with the Stack, stage and id. Tags are how Alchemy knows a resource is its own, and how you find everything one Stack created. + +## Runtimes: where your code runs + +AWS has several places to run code, from fully managed to fully yours. + +A **Lambda Function** runs your code in response to a request or an event, and costs nothing while idle. A **Lambda Web Function** is the same idea for HTTP servers, serving many requests per environment. **ECS** runs long-lived containers, **EKS** runs Kubernetes, and **EC2** gives you a virtual machine. + +In Alchemy, a runtime is a class. Its code and its infrastructure live in one file: + +```typescript title="src/api.ts" +export default class Api extends AWS.Lambda.Function()( + "Api", + { main: import.meta.url }, + Effect.gen(function* () { + return { + fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")), + }; + }), +) {} +``` + +Deploy bundles the file, uploads it and creates the Function, its execution role and its log group. + +See [Choosing a runtime](/aws/compute/choosing-a-runtime). + +## Bindings: the code is the policy + +A runtime that calls a resource needs two things: a client in the code, and a statement in its role. On AWS those are usually written in two places, and they drift apart. + +A **binding** gives you both from one line. Bind `S3.PutObject` to the Bucket, and the Function gets a typed `putObject` and an `s3:PutObject` statement on exactly that Bucket: + +```typescript title="src/api.ts" +export default class Api extends AWS.Lambda.Function()( + "Api", + { main: import.meta.url }, + Effect.gen(function* () { + const putObject = yield* S3.PutObject(Files); + return { + fetch: putObject({ Key: "hello.txt", Body: "hi" }).pipe( + Effect.as(HttpServerResponse.text("stored")), + Effect.orDie, + ), + }; + }).pipe(Effect.provide(S3.PutObjectHttp)), +) {} +``` + +`S3.PutObjectHttp` is the client the Function provides. It calls S3 with the role's credentials. + +Remove the binding, and the next deploy removes the statement. The role only ever allows what the code actually calls, which is the least privilege IAM asks for. + +See [IAM and bindings](/aws/iam). + +## Event sources: AWS calls your code + +Many services produce events: a message arrives on a Queue, an object lands in a Bucket, a row changes in a Table, a schedule fires. An **event source** connects one of them to a Function, and AWS invokes the Function with each batch. + +```typescript title="src/worker.ts" +yield* SQS.consumeQueueMessages( + Jobs, + { batchSize: 10 }, + Effect.fn(function* (event) { + for (const record of event.Records) { + yield* Console.log(record.body); + } + }), +); +``` + +The Function provides `AWS.Lambda.QueueEventSource`. Deploy creates the event source mapping and grants the role the permissions to receive and delete messages. + +See [SQS](/aws/messaging/sqs), [S3 events](/aws/messaging/s3-events), [DynamoDB Streams](/aws/messaging/dynamodb-streams) and [EventBridge](/aws/messaging/eventbridge). + +## Networks: VPCs, subnets and security groups + +A **VPC** is a private network inside a region. It's divided into **subnets**, one or more per Availability Zone. A **public** subnet routes to the internet through an internet gateway. A **private** one reaches out only through a NAT gateway, if at all. **Security groups** are firewalls around each network interface. + +A Lambda Function needs none of this. It reaches AWS services over AWS's own endpoints and serves HTTP from its Function URL. Containers, Kubernetes and virtual machines run inside a VPC, and so does anything that has to reach a private database. The `Network` helper builds the usual layout in one line: + +```typescript title="src/network.ts" +export const AppNetwork = AWS.EC2.Network("AppNetwork", { cidrBlock: "10.42.0.0/16" }); +``` + +See [VPC & networking](/aws/networking). + +## The edge: CloudFront, Route 53 and certificates + +Traffic from the internet usually arrives through the **edge**. **CloudFront** is AWS's CDN: it caches and serves your site from locations near your users and forwards the rest to an origin, like a Bucket or a Function. **Route 53** hosts your domain's DNS. **ACM** issues the TLS certificates both use. + +A Website resource puts these together: a Bucket for the files, a CloudFront distribution in front of it, and, given a domain, the certificate and the DNS records too. + +See [Websites](/aws/frontend/websites) and [Custom domains](/aws/networking/custom-domains). + +## Observability: CloudWatch + +Every service reports to **CloudWatch**. Your Function's logs go to a **log group**, each service publishes **metrics** like invocations, errors and queue depth, and an **alarm** watches a metric and notifies you when it crosses a line. + +A **dashboard** puts metrics side by side. It's declared next to the Function it watches, so each stage gets its own: + +```typescript title="alchemy.run.ts" +const api = yield* Api; + +yield* AWS.CloudWatch.Dashboard("Api", { + DashboardBody: api.functionName.pipe( + Output.map((functionName) => ({ + widgets: [ + { + type: "metric", + width: 12, + height: 6, + properties: { + title: "Invocations and errors", + stat: "Sum", + period: 300, + metrics: [ + ["AWS/Lambda", "Invocations", "FunctionName", functionName], + ["AWS/Lambda", "Errors", "FunctionName", functionName], + ], + }, + }, + ], + })), + ), +}); +``` + +`functionName` is only known once the Function is deployed, so the body is built from it with `Output.map`. + +See [CloudWatch](/aws/observability/cloudwatch). + +## State: Alchemy's record in your account + +Alchemy remembers what each Stack created, so the next deploy knows what to change. On AWS that record is a DynamoDB table, `alchemy-state`, in your own account. Deploys from your machine and from CI read the same one. + +```typescript title="alchemy.run.ts" +export default Alchemy.Stack( + "MyApp", + { providers: AWS.providers(), state: AWS.state() }, + Effect.gen(function* () { + const api = yield* Api; + return { url: api.functionUrl }; + }), +); +``` + +## How @alchemy.run/aws models these concepts + +Each of these concepts is something your Stack declares or something Alchemy does for you. + +Your profile signs in to the account and sets the default region, and `AWS.providers()` deploys there. Every resource is a declaration like `AWS.SQS.Queue("Jobs")`, named and tagged per stage. Every runtime is a class that holds its own code, and its execution role is generated from the bindings it uses. Event sources are bindings too. Networks, edge and monitoring are resources like any other, declared next to the code that needs them. + +The same Stack runs on your machine under `alchemy dev`, against a local emulator, with no account at all. See [Local development](/aws/local-development). + +Next, build one: the [tutorial](/aws/tutorial/part-1) puts these ideas to work, one step at a time. Or read the concepts in depth, starting with [Accounts and regions](/aws/accounts-and-regions) and [IAM and bindings](/aws/iam). diff --git a/.agents/skills/alchemy/references/axiom/INDEX.md b/.agents/skills/alchemy/references/axiom/INDEX.md index 219c3665..df3f8632 100644 --- a/.agents/skills/alchemy/references/axiom/INDEX.md +++ b/.agents/skills/alchemy/references/axiom/INDEX.md @@ -1,11 +1,13 @@ # axiom index -6 pages. Observability as resources — OTEL datasets, ingest tokens, monitors, notifiers, and dashboards declared next to the code that emits the data. +8 pages. Observability as resources — OTEL datasets, ingest tokens, monitors, notifiers, and dashboards declared next to the code that emits the data. | Page | File | Covers | | --- | --- | --- | | Axiom | `_overview.md` | Observability as resources — OTEL datasets, ingest tokens, monitors, notifiers, and dashboards declared next to the code that emits the data. | +| Organizations and tokens | `organizations-and-tokens.md` | How an Axiom organization holds your datasets, how Alchemy deploys with a personal token, and how your Stack mints API tokens that can only ingest or only query. | | Setup | `setup.md` | Connect alchemy to Axiom — account, credentials, and profiles. | +| What is Axiom? | `what-is-axiom.md` | The concepts behind Axiom — organizations, datasets, OpenTelemetry ingest, API tokens, APL queries, monitors, notifiers, dashboards, views and annotations — and how @alchemy.run/axiom models each of them. | ## data/ diff --git a/.agents/skills/alchemy/references/axiom/_overview.md b/.agents/skills/alchemy/references/axiom/_overview.md index 69465807..9e7da08f 100644 --- a/.agents/skills/alchemy/references/axiom/_overview.md +++ b/.agents/skills/alchemy/references/axiom/_overview.md @@ -1,38 +1,27 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Axiom > Observability as resources — OTEL datasets, ingest tokens, monitors, notifiers, and dashboards declared next to the code that emits the data. -Axiom is an event and observability store for logs, traces, and -metrics. Effect already emits OpenTelemetry, and with alchemy the -receiving end is code too: datasets, ingest tokens, monitors, -notifiers, and dashboards live in the same Stack as the Workers and -Functions they observe, so a threshold change is a reviewable diff. +Axiom is a platform for event data and observability. It stores logs, traces and metrics at any scale, and queries them in seconds. -New here? [Set up credentials](/axiom/setup) first. +You send it OpenTelemetry and query it with APL. Monitors alert you when something crosses a line, and dashboards show what's happening. -## Resources +**New to Axiom?** Start with [What is Axiom?](/axiom/what-is-axiom). -A `Dataset` is the top-level container. Pick a `kind` per OTEL -signal — it exposes the OTLP endpoints as outputs: +## A quick example + +A Dataset holds one kind of telemetry, and exposes its OTLP endpoint: ```typescript -const traces = yield* Axiom.Dataset("traces", { name: "app-traces", kind: "otel:traces:v1" }); -const logs = yield* Axiom.Dataset("logs", { name: "app-logs", kind: "otel:logs:v1" }); -const metrics = yield* Axiom.Dataset("metrics", { name: "app-metrics", kind: "otel:metrics:v1" }); +const traces = yield* Axiom.Dataset("traces", { name: "app-traces", kind: "otel:traces:v1" }); +const logs = yield* Axiom.Dataset("logs", { name: "app-logs", kind: "otel:logs:v1" }); ``` -:::caution -Renaming a dataset or changing its `kind` is a **replacement** — the -old dataset and all its events are deleted. See -[Datasets & Ingest](/axiom/data/ingest) for details. -::: - -An `ApiToken` mints a least-privilege ingest credential for your -runtime to ship with: +An ApiToken gives your runtime ingest access to one dataset, and nothing else: ```typescript const ingest = yield* Axiom.ApiToken("ingest", { @@ -43,15 +32,13 @@ const ingest = yield* Axiom.ApiToken("ingest", { }); ``` -`Monitor` + `Notifier` turn queries into alerts — see -[Monitors & Alerting](/axiom/guides/alerting) for threshold and -anomaly monitors: +A Monitor runs an APL query on a schedule and alerts through a Notifier: ```typescript const slack = yield* Axiom.Notifier("ops-slack", { name: "ops-channel", properties: { - slack: { slackUrl: process.env.SLACK_WEBHOOK_URL! }, + slack: { slackUrl: yield* Config.String("SLACK_WEBHOOK_URL") }, }, }); @@ -65,37 +52,14 @@ yield* Axiom.Monitor("panics", { }); ``` -Beyond alerts, `Dashboard` declares charts as code, `View` saves an -APL query as a virtual dataset, and `Annotation` marks deploys on -your charts — see [Dashboards as Code](/axiom/guides/dashboards). -`VirtualField` derives computed fields on a dataset at query time. - -## Compose with your cloud +Point a Worker or Lambda's OpenTelemetry exporter at the dataset endpoints, and Effect's traces and logs flow into Axiom with no code changes. See [Observability](/testing/observability). -Wire the dataset's OTLP endpoints and the ingest token into your -Worker or Lambda's environment, and Effect's OpenTelemetry output -flows into Axiom with no code changes — see -[Observability](/testing/observability) for the exporter-as-a-Layer -pattern: +## Where to start -```typescript -vars: { - OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: traces.otelTracesEndpoint, - OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: logs.otelLogsEndpoint, -}, -``` +**Want to build?** Connect your organization in [Setup](/axiom/setup), then [Observability with Axiom](/cloudflare/observability/axiom-observability) takes a Worker from no telemetry to a monitor that pages you. -For a full end-to-end walkthrough — dataset, token, Worker wiring, -and a monitor on top — follow -[Observability with Axiom](/cloudflare/observability/axiom-observability). +**Looking for something specific?** Every section of these docs is listed below, and every resource is in the generated [API reference](/providers). -## Reference +## The docs -[Dataset](/providers/axiom/dataset) · -[ApiToken](/providers/axiom/apitoken) · -[Monitor](/providers/axiom/monitor) · -[Notifier](/providers/axiom/notifier) · -[Dashboard](/providers/axiom/dashboard) · -[Annotation](/providers/axiom/annotation) · -[View](/providers/axiom/view) · -[VirtualField](/providers/axiom/virtualfield) + diff --git a/.agents/skills/alchemy/references/axiom/data/ingest.md b/.agents/skills/alchemy/references/axiom/data/ingest.md index 8af9f76e..e34d5068 100644 --- a/.agents/skills/alchemy/references/axiom/data/ingest.md +++ b/.agents/skills/alchemy/references/axiom/data/ingest.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Datasets & ingest @@ -14,7 +14,7 @@ same Stack as the Workers and Functions that emit the data. ## Create a dataset ```typescript -import * as Axiom from "alchemy/Axiom"; +import * as Axiom from "@alchemy.run/axiom"; const logs = yield* Axiom.Dataset("logs", { name: "my-app-logs", @@ -91,7 +91,8 @@ for the full pattern. - `otelEndpoint` — the root; most exporters auto-append the signal path. - `otelHeaders` — the non-secret headers Axiom expects, i.e. - `X-Axiom-Dataset: `. The `Authorization: Bearer` header is + `X-Axiom-Dataset: `, or `X-Axiom-Metrics-Dataset: ` for a + `otel:metrics:v1` dataset. The `Authorization: Bearer` header is deliberately excluded so no secret lives in dataset state — that's what the ingest token below is for. @@ -150,7 +151,7 @@ own. `Stack.useSync` computes props from the resolved stage — handy at module scope where there's no `yield*` available: ```typescript -import * as Axiom from "alchemy/Axiom"; +import * as Axiom from "@alchemy.run/axiom"; import { Stack } from "alchemy/Stack"; export const Traces = Axiom.Dataset( diff --git a/.agents/skills/alchemy/references/axiom/guides/alerting.md b/.agents/skills/alchemy/references/axiom/guides/alerting.md index e8716be9..bf299522 100644 --- a/.agents/skills/alchemy/references/axiom/guides/alerting.md +++ b/.agents/skills/alchemy/references/axiom/guides/alerting.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Alerting: monitors & notifiers @@ -20,7 +20,7 @@ Everything below runs inside your Stack's `Effect.gen` — see ## Create a notifier ```typescript -import * as Axiom from "alchemy/Axiom"; +import * as Axiom from "@alchemy.run/axiom"; const slack = yield* Axiom.Notifier("ops-slack", { name: "ops-channel", @@ -67,6 +67,24 @@ an empty result counts as a problem. attribute of the notifier flowing into the monitor's inputs, so alchemy deploys the notifier first and fills in the real id. + + ## MatchEvent: alert on every matching event ```typescript diff --git a/.agents/skills/alchemy/references/axiom/guides/annotations.md b/.agents/skills/alchemy/references/axiom/guides/annotations.md index f0b20203..de4f7496 100644 --- a/.agents/skills/alchemy/references/axiom/guides/annotations.md +++ b/.agents/skills/alchemy/references/axiom/guides/annotations.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Deploy markers & annotations @@ -18,7 +18,7 @@ and a dataset to annotate ([ingest](/axiom/data/ingest)). ## Drop a point marker ```typescript -import * as Axiom from "alchemy/Axiom"; +import * as Axiom from "@alchemy.run/axiom"; yield* Axiom.Annotation("release-1.2.3", { type: "deploy", diff --git a/.agents/skills/alchemy/references/axiom/guides/dashboards.md b/.agents/skills/alchemy/references/axiom/guides/dashboards.md index 93c96e95..85be5cd9 100644 --- a/.agents/skills/alchemy/references/axiom/guides/dashboards.md +++ b/.agents/skills/alchemy/references/axiom/guides/dashboards.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Dashboards as code @@ -11,15 +11,15 @@ a time window, a refresh interval. In alchemy that document is the input to one `Dashboard` resource, so a chart tweak is a reviewable diff and every stage gets the same dashboard. -This guide builds an ops dashboard chart by chart, then adds the two -resources that round it out: saved `View`s and deploy `Annotation`s. +Take an ops dashboard, built chart by chart, and the two resources +that round it out: saved `View`s and deploy `Annotation`s. You'll need the Axiom provider registered ([setup](/axiom/setup)) and a dataset to query ([ingest](/axiom/data/ingest)). ## Start with an empty dashboard ```typescript -import * as Axiom from "alchemy/Axiom"; +import * as Axiom from "@alchemy.run/axiom"; yield* Axiom.Dashboard("ops", { dashboard: { @@ -44,7 +44,7 @@ place, so the deployed dashboard always matches what's in your code. ## Add a chart ```typescript -import type { Chart, LayoutCell } from "alchemy/Axiom"; +import type { Chart, LayoutCell } from "@alchemy.run/axiom"; const errors: Chart = { id: "errors-5m", diff --git a/.agents/skills/alchemy/references/axiom/organizations-and-tokens.md b/.agents/skills/alchemy/references/axiom/organizations-and-tokens.md new file mode 100644 index 00000000..d9c08c2e --- /dev/null +++ b/.agents/skills/alchemy/references/axiom/organizations-and-tokens.md @@ -0,0 +1,53 @@ + + +# Organizations and tokens + +> How an Axiom organization holds your datasets, how Alchemy deploys with a personal token, and how your Stack mints API tokens that can only ingest or only query. + +Everything on Axiom belongs to an **organization**: datasets, monitors, notifiers, dashboards, and your bill. Two kinds of token reach it. A **personal token** acts as you, with everything you can do. An **API token** can do only what it's granted: ingest into one dataset, query another. + + + +## Deploy with a profile + +Alchemy deploys with the token in your [profile](/environments/profiles), usually a personal token, since it creates datasets, monitors and other tokens: + +```sh +alchemy profile edit --add Axiom +``` + +See [Setup](/axiom/setup). + +## API tokens for your runtimes + +The app that sends telemetry needs only to ingest, and only into its own datasets. Declare that token in your Stack: + +```typescript title="alchemy.run.ts" +const ingest = yield* Axiom.ApiToken("ingest", { + name: "prod-ingest", + datasetCapabilities: { + "my-app-traces": { ingest: ["create"] }, + }, +}); +``` + +`ingest.token` is an output, so it goes straight into your runtime's secrets. A dashboard tool gets a token that can only query. + +Destroying an `ApiToken` revokes it, so removing it from your Stack removes the access too. + +## In CI + +With `CI=true`, Alchemy skips the profile and reads `AXIOM_TOKEN` from the environment, plus `AXIOM_ORG_ID` when the token is a personal one. See [CI](/environments/ci). diff --git a/.agents/skills/alchemy/references/axiom/setup.md b/.agents/skills/alchemy/references/axiom/setup.md index cdf01687..b7a10130 100644 --- a/.agents/skills/alchemy/references/axiom/setup.md +++ b/.agents/skills/alchemy/references/axiom/setup.md @@ -1,18 +1,21 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Setup > Connect alchemy to Axiom — account, credentials, and profiles. Sign up at [axiom.co](https://axiom.co) and create an API token in -the [Axiom app](https://app.axiom.co). Register the provider next to -your cloud's: +the [Axiom app](https://app.axiom.co). Install `@alchemy.run/axiom`: + + + +Register the provider next to your cloud's: ```typescript // alchemy.run.ts -import * as Axiom from "alchemy/Axiom"; +import * as Axiom from "@alchemy.run/axiom"; providers: Layer.mergeAll(Cloudflare.providers(), Axiom.providers()), ``` diff --git a/.agents/skills/alchemy/references/axiom/what-is-axiom.md b/.agents/skills/alchemy/references/axiom/what-is-axiom.md new file mode 100644 index 00000000..b36954f6 --- /dev/null +++ b/.agents/skills/alchemy/references/axiom/what-is-axiom.md @@ -0,0 +1,101 @@ + + +# What is Axiom? + +> The concepts behind Axiom — organizations, datasets, OpenTelemetry ingest, API tokens, APL queries, monitors, notifiers, dashboards, views and annotations — and how @alchemy.run/axiom models each of them. + +Axiom stores the events your systems emit, logs, traces and metrics, and lets you query them fast and cheaply, however many there are. You send it OpenTelemetry, which Effect already produces, and query it with **APL**. On top of the data, **monitors** alert you, and **dashboards** show you what's happening. + +Take one setup: a Worker sending its traces and logs to Axiom, with a monitor that pages you on panics. The Worker sends telemetry with an ingest token. Axiom stores it in datasets. A monitor queries a dataset every minute and notifies Slack when it matches. + + + +## Organizations and tokens + +An **organization** holds your datasets, monitors and dashboards, and your bill. An **API token** grants specific capabilities: ingest into one dataset, query another, manage monitors. A **personal token** acts as you, and is what Alchemy deploys with. + +Connect it once, in [Setup](/axiom/setup). + +## Datasets + +A **dataset** is a collection of events, the unit you send to and query from. An OpenTelemetry dataset has a **kind**, one per signal: traces, logs or metrics. It exposes the endpoint to send that signal to. + +```typescript title="alchemy.run.ts" +const traces = yield* Axiom.Dataset("traces", { name: "app-traces", kind: "otel:traces:v1" }); +``` + +Renaming a dataset or changing its kind replaces it, and its events go with it. + +See [Datasets & ingest](/axiom/data/ingest). + +## Ingest + +Your app sends events over **OTLP**, OpenTelemetry's protocol, to a dataset's endpoint, with a token that may ingest into it. Effect's tracer and logger already speak OpenTelemetry, so connecting them to Axiom is configuration, not code. + +Give your runtime a token that can only ingest, and only into its own datasets: + +```typescript title="alchemy.run.ts" +const ingest = yield* Axiom.ApiToken("ingest", { + name: "prod-ingest", + datasetCapabilities: { "app-traces": { ingest: ["create"] } }, +}); +``` + +See [Observability](/testing/observability) for exporting from Effect. + +## APL: querying events + +**APL**, Axiom's query language, filters, aggregates and charts events, in a pipeline that reads left to right: + +```text +['app-logs'] | where message contains "panic:" | summarize count() by bin(_time, 1m) +``` + +Every monitor, dashboard chart and view is an APL query. + +## Monitors and notifiers + +A **monitor** runs a query on a schedule and fires when its result crosses a line: a count over a threshold, a value outside its usual range, or any event matching at all. A **notifier** is where it sends the alert: Slack, email, PagerDuty, a webhook. + +See [Monitors & alerting](/axiom/guides/alerting). + +## Dashboards, views and annotations + +A **dashboard** is a set of charts, each a query. A **view** saves a query as a virtual dataset, so others can query its results by name. An **annotation** marks a moment on your charts, like a deploy, so you can see what changed when. + +See [Dashboards as code](/axiom/guides/dashboards) and [Annotations](/axiom/guides/annotations). + +## How @alchemy.run/axiom models these concepts + +Each of these concepts is something your Stack declares. + +Your token picks the organization, and `Axiom.providers()` deploys into it. Datasets, tokens, monitors, notifiers, dashboards, views and annotations are resources, in the same Stack as the Workers and Functions they observe. A dataset's endpoints and a token's value are outputs you pass to your runtime's environment. So a new alert, or a changed threshold, is a reviewed change in a pull request. + +Next, follow [Observability with Axiom](/cloudflare/observability/axiom-observability) for a complete setup on Cloudflare. diff --git a/.agents/skills/alchemy/references/better-auth/INDEX.md b/.agents/skills/alchemy/references/better-auth/INDEX.md index de43a435..2a82aa2c 100644 --- a/.agents/skills/alchemy/references/better-auth/INDEX.md +++ b/.agents/skills/alchemy/references/better-auth/INDEX.md @@ -1,10 +1,11 @@ # better-auth index -28 pages. Build authentication with an Effect service, automatic database bindings, and deploy-time migrations. +29 pages. Build authentication with an Effect service, automatic database bindings, and deploy-time migrations. | Page | File | Covers | | --- | --- | --- | | Better Auth | `_overview.md` | Build authentication with an Effect service, automatic database bindings, and deploy-time migrations. | +| What is Better Auth? | `what-is-better-auth.md` | The concepts behind Better Auth — the auth server, users, accounts, sessions and cookies, sign-in providers, the signing secret, the database and its migrations, and middleware — and how @alchemy.run/better-auth models each of them. | ## databases/ diff --git a/.agents/skills/alchemy/references/better-auth/_overview.md b/.agents/skills/alchemy/references/better-auth/_overview.md index 1a00d762..ca29958e 100644 --- a/.agents/skills/alchemy/references/better-auth/_overview.md +++ b/.agents/skills/alchemy/references/better-auth/_overview.md @@ -1,14 +1,20 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Better Auth > Build authentication with an Effect service, automatic database bindings, and deploy-time migrations. -Build sign-in and protected APIs with [Better Auth](https://better-auth.com), using ordinary Effect services and layers. Alchemy supplies database bindings, a stable signing secret, and supported schema migrations. +[Better Auth](https://better-auth.com) is an open-source authentication framework for TypeScript. It runs inside your own app and keeps users and sessions in your own database. -## Start the tutorial +It supports email and password, OAuth providers like GitHub and Google, and plugins for two-factor sign-in, passkeys and organizations. + +**New to Better Auth?** Start with [What is Better Auth?](/better-auth/what-is-better-auth). + +## A quick example + +An Auth service is a Better Auth configuration: ```typescript import { BetterAuth } from "@alchemy.run/better-auth"; @@ -19,31 +25,14 @@ const makeAuth = BetterAuth({ }); ``` -The [six-part tutorial](/better-auth/tutorial/part-1) turns this into a running application with browser sign-in, session middleware, and GitHub authentication. - -| Part | Build | -| --- | --- | -| [1. Create an Auth service](/better-auth/tutorial/part-1) | Install the module and provide a database layer | -| [2. Mount the HTTP API](/better-auth/tutorial/part-2) | Serve authentication and application routes | -| [3. Build sign-in](/better-auth/tutorial/part-3) | Sign up, sign in, read sessions, and sign out | -| [4. Protect API endpoints](/better-auth/tutorial/part-4) | Provide the current user through Effect middleware | -| [5. Add GitHub sign-in](/better-auth/tutorial/part-5) | Register an OAuth app and bind its credentials | -| [6. Deploy and verify](/better-auth/tutorial/part-6) | Configure production callbacks and check persistence | - -## Choose a sign-in provider - -Use [email/password](/better-auth/sign-in-providers/email-password), [GitHub](/better-auth/sign-in-providers/github), [Google](/better-auth/sign-in-providers/google), [Microsoft](/better-auth/sign-in-providers/microsoft), or [custom OAuth](/better-auth/sign-in-providers/custom-oauth). Each guide covers registration, configuration, and browser sign-in. - -## Choose a database - -Keep the Auth service and change the database layer. The [database guides](/better-auth/databases) cover D1, Hyperdrive, Neon, Aurora, Postgres, MySQL, Drizzle, SQLite, and memory. +Alchemy binds its database, applies its migrations on deploy, and serves its routes from your Worker or Lambda. Pick a [sign-in provider](/better-auth/sign-in-providers/email-password) and a [database](/better-auth/databases) to go with it. -## Extend the application +## Where to start -Use [Config and secrets](/better-auth/guides/configuration) for deployment bindings, [HTTP API middleware](/better-auth/guides/http-api-middleware) for Effect handlers, and [secondary storage](/better-auth/guides/secondary-storage) for custom storage layers. +**Want to build?** The [tutorial](/better-auth/tutorial/part-1) builds an app with browser sign-in, session middleware and GitHub sign-in, in six parts. -For Better Auth's authentication features and options, see the [Better Auth documentation](https://better-auth.com/docs). +**Looking for something specific?** Every section of these docs is listed below, and every resource is in the generated [API reference](/providers). -## Upgrade an existing installation +## The docs -The [1.6 → 1.7.5 upgrade guide](/better-auth/upgrades/from-1-6-to-1-7) separates package and API changes from manual data preparation. [Migrations](/better-auth/guides/migrations) explains what deployment applies automatically. + diff --git a/.agents/skills/alchemy/references/better-auth/databases/_overview.md b/.agents/skills/alchemy/references/better-auth/databases/_overview.md index bf8be9dc..505a2458 100644 --- a/.agents/skills/alchemy/references/better-auth/databases/_overview.md +++ b/.agents/skills/alchemy/references/better-auth/databases/_overview.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Choose a database diff --git a/.agents/skills/alchemy/references/better-auth/databases/aurora-data-api.md b/.agents/skills/alchemy/references/better-auth/databases/aurora-data-api.md index 8435b728..7ff9fc63 100644 --- a/.agents/skills/alchemy/references/better-auth/databases/aurora-data-api.md +++ b/.agents/skills/alchemy/references/better-auth/databases/aurora-data-api.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Aurora Data API @@ -10,16 +10,14 @@ This example creates Aurora PostgreSQL and serves Better Auth through a Lambda F ## Install -```sh -bun add @alchemy.run/better-auth better-auth@^1.7.5 kysely @distilled.cloud/aws -``` + Configure AWS through an [Alchemy profile](/environments/profiles) in a region supporting Aurora PostgreSQL's Data API. No `pg` driver or TCP connection pool is required. ## Define the database and network ```typescript title="src/database.ts" -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; export const AuthDb = Effect.gen(function* () { @@ -47,7 +45,7 @@ The Aurora composite creates the cluster, writer, and database-credentials secre ```typescript title="src/function.ts" import { BetterAuth } from "@alchemy.run/better-auth"; import { AuroraDataApi } from "@alchemy.run/better-auth/AuroraDataApi"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import { AuthDb } from "./database.ts"; @@ -76,7 +74,7 @@ The database layer binds cluster and secret identifiers and grants the function ```typescript title="alchemy.run.ts" import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; import AuthApi from "./src/function.ts"; @@ -97,9 +95,7 @@ The auth signing secret is generated and bound automatically, separately from Au ## Deploy and migrate -```sh -bunx alchemy deploy -``` + Automatic migrations wait for the writer and use the Data API with deploy-time AWS credentials. Those credentials need database and secret access too; the function's IAM bindings do not grant permissions to the deployer. diff --git a/.agents/skills/alchemy/references/better-auth/databases/cloudflare-d1.md b/.agents/skills/alchemy/references/better-auth/databases/cloudflare-d1.md index 7b9bf106..b622c146 100644 --- a/.agents/skills/alchemy/references/better-auth/databases/cloudflare-d1.md +++ b/.agents/skills/alchemy/references/better-auth/databases/cloudflare-d1.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Cloudflare D1 @@ -10,9 +10,7 @@ This example creates a D1 database and a Worker serving Better Auth at `/api/aut ## Install -```sh -bun add @alchemy.run/better-auth better-auth@^1.7.5 kysely -``` + `kysely` is the SQL adapter peer; D1 needs no separate database driver. Configure Cloudflare credentials through an [Alchemy profile](/environments/profiles) before deployment. @@ -21,7 +19,7 @@ bun add @alchemy.run/better-auth better-auth@^1.7.5 kysely ```typescript title="src/worker.ts" import { BetterAuth } from "@alchemy.run/better-auth"; import { CloudflareD1 } from "@alchemy.run/better-auth/CloudflareD1"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; const AuthDb = Cloudflare.D1.Database("AuthDb"); @@ -48,7 +46,7 @@ export default class AuthApi extends Cloudflare.Worker()( ```typescript title="alchemy.run.ts" import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import AuthApi from "./src/worker.ts"; @@ -69,15 +67,11 @@ Omitting `secret` provisions and binds a stable signing secret automatically. Pr ## Deploy or develop locally -```sh -bunx alchemy deploy -``` + Deployment creates D1 and applies the auth schema through its HTTP API before updating the Worker. Requests use the native binding and never run migrations. -```sh -bunx alchemy dev -``` + Development uses the local D1 simulator, including migrations; use the URL printed by Alchemy. The Worker still runs in workerd, so replacing this layer with Bun's `SQLite` is not supported. diff --git a/.agents/skills/alchemy/references/better-auth/databases/cloudflare-hyperdrive.md b/.agents/skills/alchemy/references/better-auth/databases/cloudflare-hyperdrive.md index 59ae102a..4c93ed7b 100644 --- a/.agents/skills/alchemy/references/better-auth/databases/cloudflare-hyperdrive.md +++ b/.agents/skills/alchemy/references/better-auth/databases/cloudflare-hyperdrive.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Cloudflare Hyperdrive @@ -10,9 +10,7 @@ This example provisions a Neon Postgres database, a Hyperdrive connection, and a ## Install -```sh -bun add @alchemy.run/better-auth better-auth@^1.7.5 kysely pg -``` + Configure Cloudflare and Neon through [Alchemy profiles](/environments/profiles), or supply `NEON_API_KEY` for Neon. If you only need direct Neon access, the [Neon serverless layer](/better-auth/databases/neon) avoids Hyperdrive and `pg`. @@ -20,8 +18,8 @@ Configure Cloudflare and Neon through [Alchemy profiles](/environments/profiles) ```typescript title="src/auth-database.ts" import { CloudflareHyperdrive } from "@alchemy.run/better-auth/CloudflareHyperdrive"; -import * as Cloudflare from "alchemy/Cloudflare"; -import * as Neon from "alchemy/Neon"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Neon from "@alchemy.run/neon"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -47,7 +45,7 @@ Keep Hyperdrive caching disabled so session and verification reads cannot return ```typescript title="src/worker.ts" import { BetterAuth } from "@alchemy.run/better-auth"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import { AuthDatabase } from "./auth-database.ts"; @@ -73,8 +71,8 @@ The layer registers Hyperdrive's native binding and opens a driver pool inside e ```typescript title="alchemy.run.ts" import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; -import * as Neon from "alchemy/Neon"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Neon from "@alchemy.run/neon"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import AuthApi from "./src/worker.ts"; @@ -96,9 +94,7 @@ Preserve and protect the local `.alchemy` state directory so later deployments r ## Deploy and migrate through the origin -```sh -bunx alchemy deploy -``` + The deployer must reach the origin with schema-changing permissions; the migration completes before the Worker is updated. Set `AUTH_ORIGIN` to the printed URL and verify the endpoint: @@ -112,9 +108,7 @@ Omitting the database layer's `migrate` source disables automatic migration supp For an existing MySQL origin, install its driver instead of `pg`: -```sh -bun add mysql2 -``` + Configure the Hyperdrive resource with that MySQL origin, select `dialect: "mysql"` in `CloudflareHyperdrive`, and supply the origin's deploy-resolvable URL as `migrate`. Keep caching disabled; changing the dialect alone neither converts the Neon origin above nor moves existing auth records. diff --git a/.agents/skills/alchemy/references/better-auth/databases/drizzle.md b/.agents/skills/alchemy/references/better-auth/databases/drizzle.md index db6f6537..9652bd28 100644 --- a/.agents/skills/alchemy/references/better-auth/databases/drizzle.md +++ b/.agents/skills/alchemy/references/better-auth/databases/drizzle.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Drizzle @@ -10,10 +10,7 @@ This example uses an existing Postgres database and serves Better Auth through a ## Install compatible packages -```sh -bun add @alchemy.run/better-auth better-auth@^1.7.5 @better-auth/drizzle-adapter@^1.7.5 pg drizzle-orm@1.0.0-rc.5-ab785fc -bun add -d drizzle-kit@1.0.0-rc.5-ab785fc @types/pg -``` + Keep ORM and Kit versions compatible when upgrading. Configure an [AWS profile](/environments/profiles) and set `DATABASE_URL` to a Postgres database reachable by both your deployer and Lambda. @@ -47,9 +44,7 @@ Keep plugins, additional fields, and model names aligned between this call and t Run the CLI with Node.js 22.12 or newer: -```sh -npx auth@1.7.5 generate --config ./auth.cli.ts --output ./src/auth-schema.ts -``` + This command creates the `src/auth-schema.ts` imported below, including auth tables and `authRelations`. Do not pass `--adapter drizzle`: it selects the legacy Relations v1 generator rather than the configured Relations v2 adapter. @@ -71,15 +66,11 @@ export default defineConfig({ If your application already owns a Drizzle migration history, include the generated auth schema there rather than starting a second history. -```sh -bunx drizzle-kit generate -``` + Review the generated SQL, especially for an existing database, before applying it: -```sh -bunx drizzle-kit migrate -``` + Apply migrations before deploying new auth code. This layer never runs Drizzle migrations for you. @@ -122,7 +113,7 @@ The URL resolves during host construction, while the inner Effect opens and rele ```typescript title="src/function.ts" import { BetterAuth } from "@alchemy.run/better-auth"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import { AuthDatabase } from "./auth-database.ts"; @@ -153,7 +144,7 @@ The function exposes `/api/auth` through a public Function URL and packages `pg` ```typescript title="alchemy.run.ts" import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; import AuthApi from "./src/function.ts"; @@ -174,9 +165,7 @@ Preserve and protect local `.alchemy` state across deployments. This example ass ## Deploy and verify -```sh -bunx alchemy deploy -``` + Set `AUTH_ORIGIN` to the printed Function URL and check the endpoint: diff --git a/.agents/skills/alchemy/references/better-auth/databases/memory.md b/.agents/skills/alchemy/references/better-auth/databases/memory.md index 012af385..7c7612ab 100644 --- a/.agents/skills/alchemy/references/better-auth/databases/memory.md +++ b/.agents/skills/alchemy/references/better-auth/databases/memory.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Memory @@ -10,9 +10,7 @@ Use `Memory` for throwaway development and tests, not production authentication. ## Install -```sh -bun add @alchemy.run/better-auth better-auth@^1.7.5 -``` + No optional database driver or `kysely` peer is required by the memory adapter. @@ -30,7 +28,7 @@ Construct the layer once for the host, not inside `fetch`, so requests in the sa ```typescript title="src/worker.ts" import { BetterAuth } from "@alchemy.run/better-auth"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import { AuthDatabase } from "./auth-database.ts"; @@ -57,7 +55,7 @@ Better Auth instances remain request-scoped, while the layer retains the backing ```typescript title="alchemy.run.ts" import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import AuthApi from "./src/worker.ts"; @@ -78,9 +76,7 @@ Alchemy generates and binds a stable signing secret, persisted in local stack st ## Run locally -```sh -bunx alchemy dev -``` + Use the printed URL rather than assuming a local port. Set `AUTH_ORIGIN` to that URL to check the auth endpoint: diff --git a/.agents/skills/alchemy/references/better-auth/databases/mysql.md b/.agents/skills/alchemy/references/better-auth/databases/mysql.md index bcb21ca6..08c8657c 100644 --- a/.agents/skills/alchemy/references/better-auth/databases/mysql.md +++ b/.agents/skills/alchemy/references/better-auth/databases/mysql.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # MySQL @@ -10,9 +10,7 @@ This example connects a Better Auth Lambda to an existing MySQL database over TC ## Install -```sh -bun add @alchemy.run/better-auth better-auth@^1.7.5 kysely mysql2 -``` + Configure AWS through an [Alchemy profile](/environments/profiles) and set `DATABASE_URL` in the deploying environment. Both the deployer and Lambda must be able to reach that URL. @@ -40,7 +38,7 @@ The URL is bound during host construction; the `mysql2` pool opens per invocatio ```typescript title="src/function.ts" import { BetterAuth } from "@alchemy.run/better-auth"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import { AuthDatabase } from "./auth-database.ts"; @@ -70,7 +68,7 @@ The function exposes Better Auth at `/api/auth` through a public Function URL. T ```typescript title="alchemy.run.ts" import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; import AuthApi from "./src/function.ts"; @@ -91,9 +89,7 @@ Preserve and protect the local `.alchemy` state directory across deployments. Th ## Deploy and migrate -```sh -bunx alchemy deploy -``` + Automatic migrations use the resolved URL and the same pool options before updating the function. The deployer needs schema-changing permissions; migrations create auth tables inside the existing database. diff --git a/.agents/skills/alchemy/references/better-auth/databases/neon.md b/.agents/skills/alchemy/references/better-auth/databases/neon.md index 8cd6d3f3..3a36df68 100644 --- a/.agents/skills/alchemy/references/better-auth/databases/neon.md +++ b/.agents/skills/alchemy/references/better-auth/databases/neon.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Neon @@ -10,9 +10,7 @@ This example provisions Neon and serves Better Auth from a Cloudflare Worker. Th ## Install -```sh -bun add @alchemy.run/better-auth better-auth@^1.7.5 kysely @neondatabase/serverless -``` + Configure Cloudflare and Neon through [Alchemy profiles](/environments/profiles), or supply `NEON_API_KEY` for Neon. You provide account credentials; the project resource creates the database, not the API key. @@ -20,7 +18,7 @@ Configure Cloudflare and Neon through [Alchemy profiles](/environments/profiles) ```typescript title="src/auth-database.ts" import { Neon as NeonDatabase } from "@alchemy.run/better-auth/Neon"; -import * as Neon from "alchemy/Neon"; +import * as Neon from "@alchemy.run/neon"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -37,7 +35,7 @@ The project's `connectionUri` Output is bound into the host environment and also ```typescript title="src/worker.ts" import { BetterAuth } from "@alchemy.run/better-auth"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import { AuthDatabase } from "./auth-database.ts"; @@ -63,8 +61,8 @@ This is an auth-only endpoint, with no frontend or application routes. Alchemy g ```typescript title="alchemy.run.ts" import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; -import * as Neon from "alchemy/Neon"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Neon from "@alchemy.run/neon"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import AuthApi from "./src/worker.ts"; @@ -86,9 +84,7 @@ Keep the local `.alchemy` state directory protected and persistent so subsequent ## Deploy and verify -```sh -bunx alchemy deploy -``` + The deployer must reach Neon with schema-changing permissions; migrations complete before the Worker is updated. Set `AUTH_ORIGIN` to the printed URL to check the endpoint: diff --git a/.agents/skills/alchemy/references/better-auth/databases/postgres.md b/.agents/skills/alchemy/references/better-auth/databases/postgres.md index 9894b843..f8fea810 100644 --- a/.agents/skills/alchemy/references/better-auth/databases/postgres.md +++ b/.agents/skills/alchemy/references/better-auth/databases/postgres.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Postgres @@ -10,9 +10,7 @@ This example serves Better Auth through a Lambda Function URL using an existing ## Install -```sh -bun add @alchemy.run/better-auth better-auth@^1.7.5 kysely pg -``` + Configure AWS through an [Alchemy profile](/environments/profiles) and set `DATABASE_URL` in the deploying environment. The connection layer does not create the database, credentials, or network access. @@ -38,7 +36,7 @@ Configuration resolves during host construction and is bound into the Lambda env ```typescript title="src/function.ts" import { BetterAuth } from "@alchemy.run/better-auth"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import { AuthDatabase } from "./auth-database.ts"; @@ -68,7 +66,7 @@ export default class AuthApi extends AWS.Lambda.Function()( ```typescript title="alchemy.run.ts" import * as Alchemy from "alchemy"; -import * as AWS from "alchemy/AWS"; +import * as AWS from "@alchemy.run/aws"; import * as Effect from "effect/Effect"; import AuthApi from "./src/function.ts"; @@ -89,9 +87,7 @@ Alchemy generates and binds the signing secret automatically. Preserve and prote ## Deploy and migrate -```sh -bunx alchemy deploy -``` + Automatic migrations use the resolved URL before updating the function, so the deployer needs schema-changing permissions. The runtime pool defaults to one connection per invocation; migrations create auth tables, not the database itself. diff --git a/.agents/skills/alchemy/references/better-auth/databases/sqlite.md b/.agents/skills/alchemy/references/better-auth/databases/sqlite.md index 796eda1a..123e5805 100644 --- a/.agents/skills/alchemy/references/better-auth/databases/sqlite.md +++ b/.agents/skills/alchemy/references/better-auth/databases/sqlite.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # SQLite @@ -10,9 +10,7 @@ ## Install -```sh -bun add "@effect/platform-bun@4.0.0-rc.115" @alchemy.run/better-auth better-auth@^1.7.5 kysely -``` + Bun supplies the driver, while `kysely` supports the SQL adapter and schema migration. A standard Node.js Lambda cannot load `bun:sqlite`. @@ -106,9 +104,7 @@ The stack generates a stable signing secret and passes it to the child process a ## Start locally -```sh -bunx alchemy dev -``` + The server asks the OS for an available port and prints its URL, which Alchemy exposes as the stack output. `Command.Dev` runs only during development; `alchemy deploy` does not publish this local server. diff --git a/.agents/skills/alchemy/references/better-auth/guides/configuration.md b/.agents/skills/alchemy/references/better-auth/guides/configuration.md index 92149e17..7802747a 100644 --- a/.agents/skills/alchemy/references/better-auth/guides/configuration.md +++ b/.agents/skills/alchemy/references/better-auth/guides/configuration.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Config and secrets @@ -43,7 +43,7 @@ export class Auth extends Context.Service< ```typescript // worker.ts import { CloudflareD1 } from "@alchemy.run/better-auth/CloudflareD1"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { HttpServerRequest } from "effect/http/HttpServerRequest"; @@ -80,7 +80,7 @@ This host creates its own D1 database, registers migrations, and forwards Better ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import AuthApi from "./worker.ts"; @@ -96,19 +96,15 @@ export default Alchemy.Stack( These three files use Bun, matching releases of `alchemy` and `@alchemy.run/better-auth`, Better Auth 1.7.5, Effect 4, and `kysely`. Configure Cloudflare credentials for deployment; preserve the local Alchemy state directory across runs. -```sh -bunx alchemy dev -``` + Alchemy selects an available port and prints the origin. With `AUTH_BASE_URL` unset, Better Auth derives its origin from the incoming request, so no fixed port is needed. ## Override the origin deliberately -```sh -read -r AUTH_BASE_URL + Enter the actual origin serving this Worker, without a path or trailing slash. `baseURL` does not provision DNS or attach a custom domain; configure that routing separately before sending traffic there. diff --git a/.agents/skills/alchemy/references/better-auth/guides/http-api-middleware.md b/.agents/skills/alchemy/references/better-auth/guides/http-api-middleware.md index 70eb8834..18f6cc9e 100644 --- a/.agents/skills/alchemy/references/better-auth/guides/http-api-middleware.md +++ b/.agents/skills/alchemy/references/better-auth/guides/http-api-middleware.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # HTTP API middleware @@ -13,7 +13,7 @@ import { BetterAuth } from "@alchemy.run/better-auth"; import { CloudflareD1 } from "@alchemy.run/better-auth/CloudflareD1"; import { RuntimeContext } from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Http from "alchemy/Http"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -149,7 +149,7 @@ The private group requires authentication, while the health group and Better Aut ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import AuthApi from "./worker.ts"; @@ -165,9 +165,7 @@ export default Alchemy.Stack( Use Bun, matching `alchemy` and `@alchemy.run/better-auth` releases, Better Auth 1.7.5, Effect 4, and `kysely`, with Cloudflare credentials configured. This stack owns its D1 database, migrations, and stable signing secret; preserve its local state. -```sh -bunx alchemy dev -``` + Alchemy selects an available port and prints the origin. In another shell, enter that origin without a trailing slash after `read`: diff --git a/.agents/skills/alchemy/references/better-auth/guides/migrations.md b/.agents/skills/alchemy/references/better-auth/guides/migrations.md index 4c1759fd..aa6ddee3 100644 --- a/.agents/skills/alchemy/references/better-auth/guides/migrations.md +++ b/.agents/skills/alchemy/references/better-auth/guides/migrations.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Migrations @@ -12,7 +12,7 @@ // worker.ts import { BetterAuth } from "@alchemy.run/better-auth"; import { CloudflareD1 } from "@alchemy.run/better-auth/CloudflareD1"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; const AuthDb = Cloudflare.D1.Database("AuthDb"); @@ -40,7 +40,7 @@ This auth-only Worker declares an optional `timezone` column on the user model. ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import AuthApi from "./worker.ts"; @@ -56,23 +56,17 @@ export default Alchemy.Stack( Use Bun, matching `alchemy` and `@alchemy.run/better-auth` releases, Better Auth 1.7.5, Effect 4, and `kysely`, with Cloudflare credentials configured. This standalone stack creates a new database; applying a change to an existing installation requires retaining its stack, stage, resource identities, and state. -```sh -bunx alchemy deploy -``` + The migration action applies missing tables, columns, and indexes before the updated host deploys, while existing instances may still serve traffic. Migration code does not run on incoming requests or during planning. ## Repeat or force a deployment -```sh -bunx alchemy deploy -``` + An unchanged schema, database identity, and dialect skip the migration action. Plugin fields, model names, and indexes participate in the schema fingerprint. -```sh -bunx alchemy deploy --force -``` + Force reapplies the deployment, including its migration action; an already-current schema remains a no-op. It does not override migration safety checks, merge users, or rewrite account identities. diff --git a/.agents/skills/alchemy/references/better-auth/guides/secondary-storage.md b/.agents/skills/alchemy/references/better-auth/guides/secondary-storage.md index 99a64a88..512af7f8 100644 --- a/.agents/skills/alchemy/references/better-auth/guides/secondary-storage.md +++ b/.agents/skills/alchemy/references/better-auth/guides/secondary-storage.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Secondary storage @@ -88,7 +88,7 @@ Automatic JSON deserialization is disabled because Better Auth stores strings, i // worker.ts import { BetterAuth } from "@alchemy.run/better-auth"; import { CloudflareD1 } from "@alchemy.run/better-auth/CloudflareD1"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { RedisStorage } from "./storage.ts"; @@ -128,7 +128,7 @@ The explicit limiter also runs in development, with a 60-second window and a max ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import AuthApi from "./worker.ts"; @@ -144,9 +144,7 @@ export default Alchemy.Stack( Use Bun, matching `alchemy` and `@alchemy.run/better-auth` releases, Better Auth 1.7.5, Effect 4, and `kysely`, in addition to the Redis SDK. Configure Cloudflare credentials and the external storage inputs before deployment; this stack provisions D1 and a stable signing secret, not the Redis service. -```sh -bunx alchemy deploy -``` + Preserve the local Alchemy state and use the printed URL. A local run must use a separate storage database from production because the REST store is external, not emulated by `alchemy dev`. diff --git a/.agents/skills/alchemy/references/better-auth/sign-in-providers/_overview.md b/.agents/skills/alchemy/references/better-auth/sign-in-providers/_overview.md index 908d2745..daca048c 100644 --- a/.agents/skills/alchemy/references/better-auth/sign-in-providers/_overview.md +++ b/.agents/skills/alchemy/references/better-auth/sign-in-providers/_overview.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Sign-in providers diff --git a/.agents/skills/alchemy/references/better-auth/sign-in-providers/custom-oauth.md b/.agents/skills/alchemy/references/better-auth/sign-in-providers/custom-oauth.md index 01423fa0..baee01ed 100644 --- a/.agents/skills/alchemy/references/better-auth/sign-in-providers/custom-oauth.md +++ b/.agents/skills/alchemy/references/better-auth/sign-in-providers/custom-oauth.md @@ -1,18 +1,16 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Custom OAuth and OIDC > Add Keycloak OIDC sign-in to an Alchemy Worker with D1, one small step at a time. -Start in an existing Alchemy project with [Bun](https://bun.sh) and a [configured Cloudflare profile](/cloudflare/setup). This standalone walkthrough uses Keycloak and Better Auth 1.7.5's `genericOAuth`; all application files are introduced below. +Start in an existing Alchemy project on [Node.js](https://nodejs.org) or [Bun](https://bun.sh) and a [configured Cloudflare profile](/cloudflare/setup). This standalone walkthrough uses Keycloak and Better Auth 1.7.5's `genericOAuth`; all application files are introduced below. ## Add the auth dependencies -```sh -bun add @alchemy.run/better-auth better-auth@1.7.5 kysely -``` + Use an `@alchemy.run/better-auth` release matching your installed Alchemy release. Keep your existing `alchemy` and `effect` dependencies. @@ -100,7 +98,7 @@ In 1.7.5, `genericOAuth` registers a social provider named `company`, using `sig Create `src/database.ts`: ```typescript -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; export const AuthDb = Cloudflare.D1.Database("AuthDb"); ``` @@ -129,7 +127,7 @@ export const AuthLive = Auth.layer.pipe( Create `src/worker.ts`: ```typescript -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import { Auth } from "./auth.ts"; import { AuthLive } from "./auth-layer.ts"; @@ -156,7 +154,7 @@ Use this as `alchemy.run.ts` for the walkthrough: ```typescript import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import AuthWorker from "./src/worker.ts"; @@ -278,9 +276,7 @@ The final client is the initial `src/client.ts` block followed by the three appe ## Discover the local origin -```sh -bunx alchemy dev --stage company-guide -``` + Run without provider credentials or `OIDC_ENABLED=true` for this first start; Alchemy allocates a port and prints the actual origin. Keep OIDC disabled until the registration below is ready, and rebuild the browser bundle whenever you edit `src/client.ts`. @@ -318,9 +314,7 @@ Discovery must be reachable from the Worker and publish the expected issuer, aut ## Enable OIDC locally -```sh -bunx alchemy dev --stage company-guide --env-file .env.local -``` + Stop the first dev process before running this command, and update Keycloak's callback if the newly printed origin changes. Open that origin, select **Sign in with company**, then use **Read session** and **Sign out** to exercise the roundtrip. diff --git a/.agents/skills/alchemy/references/better-auth/sign-in-providers/email-password.md b/.agents/skills/alchemy/references/better-auth/sign-in-providers/email-password.md index d05c3636..bca6b14c 100644 --- a/.agents/skills/alchemy/references/better-auth/sign-in-providers/email-password.md +++ b/.agents/skills/alchemy/references/better-auth/sign-in-providers/email-password.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Email and password @@ -12,9 +12,7 @@ Create each named file when it first appears, append snippets only where instruc ## Add the authentication dependencies -```sh -bun add @alchemy.run/better-auth better-auth@1.7.5 kysely -``` + Keep `@alchemy.run/better-auth` aligned with your existing Alchemy release. @@ -158,7 +156,7 @@ The service retains the inferred Better Auth API while leaving its database and Create `src/database.ts`: ```typescript -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; export const AuthDb = Cloudflare.D1.Database("AuthDb"); ``` @@ -198,7 +196,7 @@ Create `src/worker.ts`: ```typescript import { CloudflareD1 } from "@alchemy.run/better-auth/CloudflareD1"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; @@ -228,7 +226,7 @@ Use this `alchemy.run.ts` for the walkthrough, or add `AuthWorker` to your exist ```typescript import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import AuthWorker from "./src/worker.ts"; @@ -514,9 +512,7 @@ This produces the `/client.js` referenced by the HTML page. Re-run it whenever y ## Start local development -```sh -bunx alchemy dev --stage email-guide --env-file .env.local -``` + Open the URL Alchemy prints, register with an inbox you control, and keep the server running while following verification or recovery links. No fixed port or OAuth application is required; if the origin changes, request fresh messages instead of reusing old links. @@ -542,8 +538,6 @@ Replace the origin with the actual HTTPS Worker origin, without a trailing slash After bundling the browser module, deploy from the project root: -```sh -bunx alchemy deploy --stage production --env-file .env.production -``` + Keep production state and credentials separate from development, and test delivery against the deployed origin. This walkthrough serves the page and API together; a separate browser origin requires explicit trusted origins, credentialed CORS, and compatible cookie settings—never disable origin or CSRF checks to work around a mismatch. diff --git a/.agents/skills/alchemy/references/better-auth/sign-in-providers/github.md b/.agents/skills/alchemy/references/better-auth/sign-in-providers/github.md index 57ab3415..d6961515 100644 --- a/.agents/skills/alchemy/references/better-auth/sign-in-providers/github.md +++ b/.agents/skills/alchemy/references/better-auth/sign-in-providers/github.md @@ -1,18 +1,16 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # GitHub > Add GitHub sign-in to a D1-backed Alchemy Worker, one step at a time. -Start in an existing Alchemy project with [Bun](https://bun.sh) and a [configured Cloudflare profile](/cloudflare/setup). This page supplies every application file; paths are relative to your project root. +Start in an existing Alchemy project on [Node.js](https://nodejs.org) or [Bun](https://bun.sh) and a [configured Cloudflare profile](/cloudflare/setup). Paths are relative to your project root. ## Add the auth dependencies -```sh -bun add @alchemy.run/better-auth better-auth@1.7.5 kysely -``` + Use an integration release matching your installed Alchemy version. @@ -89,7 +87,7 @@ The service exposes the inferred Better Auth instance to the Worker. Its layer c Create `src/database.ts`: ```typescript -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; export const AuthDb = Cloudflare.D1.Database("AuthDb"); ``` @@ -118,7 +116,7 @@ export const AuthLive = Auth.layer.pipe( Create `src/worker.ts`: ```typescript -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import { Auth } from "./auth.ts"; import { AuthLive } from "./auth-live.ts"; @@ -145,7 +143,7 @@ Use this as `alchemy.run.ts`: ```typescript import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import AuthWorker from "./src/worker.ts"; @@ -274,9 +272,7 @@ This creates `public/client.js` for the HTML script tag. Rebuild it after editin ## Discover the local origin -```sh -bunx alchemy dev --stage github-guide -``` + Alchemy allocates an available port and prints the URL; open that exact URL, but leave sign-in alone until GitHub is configured. Keep `GITHUB_ENABLED` and `AUTH_BASE_URL` unset on this first run so OAuth remains disabled and no origin is guessed. @@ -304,9 +300,7 @@ Copy the OAuth App's **Client ID**, generate a **Client secret**, and replace th Stop the first dev process, then run: -```sh -bunx alchemy dev --stage github-guide --env-file .env.local -``` + If the printed origin changed, update the OAuth App's homepage and exact callback URL before signing in. An optional `AUTH_BASE_URL` override must equal that origin without a trailing slash or `/api/auth`; leaving it unset avoids pinning an old dev port. diff --git a/.agents/skills/alchemy/references/better-auth/sign-in-providers/google.md b/.agents/skills/alchemy/references/better-auth/sign-in-providers/google.md index 825e8f3c..dd4931e5 100644 --- a/.agents/skills/alchemy/references/better-auth/sign-in-providers/google.md +++ b/.agents/skills/alchemy/references/better-auth/sign-in-providers/google.md @@ -1,18 +1,16 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Google > Add Google sign-in to a D1-backed Alchemy Worker, one step at a time. -Start in an existing Alchemy project with [Bun](https://bun.sh) and a [configured Cloudflare profile](/cloudflare/setup). This page supplies every application file and uses Google's server-side authorization-code flow, not the Google browser SDK. +Start in an existing Alchemy project on [Node.js](https://nodejs.org) or [Bun](https://bun.sh) and a [configured Cloudflare profile](/cloudflare/setup). The app uses Google's server-side authorization-code flow, not the Google browser SDK. ## Add the auth dependencies -```sh -bun add @alchemy.run/better-auth better-auth@1.7.5 kysely -``` + Use an integration release matching your installed Alchemy version. All file paths below are relative to your project root. @@ -89,7 +87,7 @@ The service exposes the inferred Better Auth instance to the Worker. Its layer c Create `src/database.ts`: ```typescript -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; export const AuthDb = Cloudflare.D1.Database("AuthDb"); ``` @@ -118,7 +116,7 @@ export const AuthLive = Auth.layer.pipe( Create `src/worker.ts`: ```typescript -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import { Auth } from "./auth.ts"; import { AuthLive } from "./auth-live.ts"; @@ -145,7 +143,7 @@ Use this as `alchemy.run.ts`: ```typescript import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import AuthWorker from "./src/worker.ts"; @@ -274,9 +272,7 @@ This creates `public/client.js` for the HTML script tag. Rebuild it after editin ## Discover the local origin -```sh -bunx alchemy dev --stage google-guide -``` + Alchemy allocates an available port and prints the URL; open that exact URL, but leave sign-in alone until Google is configured. Keep `GOOGLE_ENABLED` and `AUTH_BASE_URL` unset on this first run so OAuth remains disabled and no origin is guessed. @@ -316,9 +312,7 @@ Copy the web client's ID and secret into these template values. Keep this file g Stop the first dev process, then run: -```sh -bunx alchemy dev --stage google-guide --env-file .env.local -``` + If the printed origin changed, update Google's exact redirect registration before signing in. An optional `AUTH_BASE_URL` override must equal that origin without a trailing slash or `/api/auth`; leaving it unset avoids pinning an old dev port. diff --git a/.agents/skills/alchemy/references/better-auth/sign-in-providers/microsoft.md b/.agents/skills/alchemy/references/better-auth/sign-in-providers/microsoft.md index c5edd23a..c231497e 100644 --- a/.agents/skills/alchemy/references/better-auth/sign-in-providers/microsoft.md +++ b/.agents/skills/alchemy/references/better-auth/sign-in-providers/microsoft.md @@ -1,18 +1,16 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Microsoft > Add Microsoft sign-in to an Alchemy Worker with D1, one small step at a time. -Start in an existing Alchemy project with [Bun](https://bun.sh) and a [configured Cloudflare profile](/cloudflare/setup). This standalone walkthrough uses Better Auth 1.7.5's built-in Microsoft Entra ID provider; all application files are introduced below. +Start in an existing Alchemy project on [Node.js](https://nodejs.org) or [Bun](https://bun.sh) and a [configured Cloudflare profile](/cloudflare/setup). This standalone walkthrough uses Better Auth 1.7.5's built-in Microsoft Entra ID provider; all application files are introduced below. ## Add the auth dependencies -```sh -bun add @alchemy.run/better-auth better-auth@1.7.5 kysely -``` + Use an `@alchemy.run/better-auth` release matching your installed Alchemy release. Keep your existing `alchemy` and `effect` dependencies. @@ -91,7 +89,7 @@ This sign-in-only setup omits Graph photos and offline access. The provider defa Create `src/database.ts`: ```typescript -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; export const AuthDb = Cloudflare.D1.Database("AuthDb"); ``` @@ -120,7 +118,7 @@ export const AuthLive = Auth.layer.pipe( Create `src/worker.ts`: ```typescript -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import { Auth } from "./auth.ts"; import { AuthLive } from "./auth-layer.ts"; @@ -147,7 +145,7 @@ Use this as `alchemy.run.ts` for the walkthrough: ```typescript import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import AuthWorker from "./src/worker.ts"; @@ -269,9 +267,7 @@ The final client is the initial `src/client.ts` block followed by the three appe ## Discover the local origin -```sh -bunx alchemy dev --stage microsoft-guide -``` + Run without provider credentials or `MICROSOFT_ENABLED=true` for this first start; Alchemy allocates a port and prints the actual origin. Keep Microsoft disabled until the registration below is ready, and rebuild the browser bundle whenever you edit `src/client.ts`. @@ -311,9 +307,7 @@ Under **Certificates & secrets → Client secrets → New client secret**, copy ## Enable Microsoft locally -```sh -bunx alchemy dev --stage microsoft-guide --env-file .env.local -``` + Stop the first dev process before running this command, and update the registered callback if the newly printed origin changes. Open that origin, select **Sign in with Microsoft**, then use **Read session** and **Sign out** to exercise the roundtrip. diff --git a/.agents/skills/alchemy/references/better-auth/tutorial/part-1.md b/.agents/skills/alchemy/references/better-auth/tutorial/part-1.md index c9d8c064..ecc01d86 100644 --- a/.agents/skills/alchemy/references/better-auth/tutorial/part-1.md +++ b/.agents/skills/alchemy/references/better-auth/tutorial/part-1.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Part 1: Create an Auth service @@ -8,13 +8,11 @@ Build one application with email/password authentication, an Effect HTTP API, and GitHub sign-in. This tutorial uses Bun and Cloudflare D1; [other databases](/better-auth/databases) use the same Auth service. -Use your existing Alchemy project with [Bun](https://bun.sh) and a [configured Cloudflare profile](/cloudflare/setup). The examples use Effect 4 and Better Auth 1.7.5. +Use your existing Alchemy project on [Node.js](https://nodejs.org) or [Bun](https://bun.sh) and a [configured Cloudflare profile](/cloudflare/setup). The examples use Effect 4 and Better Auth 1.7.5. ## Install the module -```sh -bun add @alchemy.run/better-auth better-auth@1.7.5 kysely -``` + Use matching Alchemy and Better Auth integration releases. D1 uses Kysely internally; application code does not need to construct a Kysely client. @@ -22,7 +20,7 @@ Use matching Alchemy and Better Auth integration releases. D1 uses Kysely intern ```typescript // src/database.ts -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; export const AuthDb = Cloudflare.D1.Database("AuthDb"); ``` @@ -71,7 +69,7 @@ Handlers and middleware can now request the same typed service with `yield* Auth ```typescript // src/worker.ts -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import * as HttpServerResponse from "effect/http/HttpServerResponse"; @@ -114,7 +112,7 @@ The host supplies the database; the Auth service stays independent of Cloudflare ```typescript // alchemy.run.ts import * as Alchemy from "alchemy"; -import * as Cloudflare from "alchemy/Cloudflare"; +import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Effect from "effect/Effect"; import AuthApi from "./src/worker.ts"; @@ -132,9 +130,7 @@ Local state keeps this walkthrough self-contained. Preserve its state directory ## Start development -```sh -bunx alchemy dev --stage tutorial -``` + In another terminal, paste the printed URL after running `read`, then press Enter: diff --git a/.agents/skills/alchemy/references/better-auth/tutorial/part-2.md b/.agents/skills/alchemy/references/better-auth/tutorial/part-2.md index 584c44d2..1cc83889 100644 --- a/.agents/skills/alchemy/references/better-auth/tutorial/part-2.md +++ b/.agents/skills/alchemy/references/better-auth/tutorial/part-2.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Part 2: Mount the HTTP API diff --git a/.agents/skills/alchemy/references/better-auth/tutorial/part-3.md b/.agents/skills/alchemy/references/better-auth/tutorial/part-3.md index 493a4d20..44128a66 100644 --- a/.agents/skills/alchemy/references/better-auth/tutorial/part-3.md +++ b/.agents/skills/alchemy/references/better-auth/tutorial/part-3.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Part 3: Build sign-in diff --git a/.agents/skills/alchemy/references/better-auth/tutorial/part-4.md b/.agents/skills/alchemy/references/better-auth/tutorial/part-4.md index 4c19061c..125c4534 100644 --- a/.agents/skills/alchemy/references/better-auth/tutorial/part-4.md +++ b/.agents/skills/alchemy/references/better-auth/tutorial/part-4.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Part 4: Protect API endpoints diff --git a/.agents/skills/alchemy/references/better-auth/tutorial/part-5.md b/.agents/skills/alchemy/references/better-auth/tutorial/part-5.md index 8a66ca66..5ff11e2d 100644 --- a/.agents/skills/alchemy/references/better-auth/tutorial/part-5.md +++ b/.agents/skills/alchemy/references/better-auth/tutorial/part-5.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Part 5: Add GitHub sign-in @@ -23,7 +23,7 @@ Use a separate OAuth application for production so its credentials remain indepe ## Keep credentials out of Git -```gitignore +```txt # .gitignore .env .env.* @@ -136,10 +136,8 @@ Better Auth handles failed callbacks on its built-in error page. No custom error Stop the running development command, rebuild the client, and start it again: -```sh -bun build ./src/ui.ts --target browser --outdir ./public -bunx alchemy dev --stage tutorial -``` + Try GitHub sign-in and call the protected API. Then sign out, retry, and cancel at GitHub to check the error path. diff --git a/.agents/skills/alchemy/references/better-auth/tutorial/part-6.md b/.agents/skills/alchemy/references/better-auth/tutorial/part-6.md index 9e38cb83..af25ea5e 100644 --- a/.agents/skills/alchemy/references/better-auth/tutorial/part-6.md +++ b/.agents/skills/alchemy/references/better-auth/tutorial/part-6.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Part 6: Deploy and verify diff --git a/.agents/skills/alchemy/references/better-auth/upgrades/from-1-6-to-1-7.md b/.agents/skills/alchemy/references/better-auth/upgrades/from-1-6-to-1-7.md index 8ff8cab6..c94027b7 100644 --- a/.agents/skills/alchemy/references/better-auth/upgrades/from-1-6-to-1-7.md +++ b/.agents/skills/alchemy/references/better-auth/upgrades/from-1-6-to-1-7.md @@ -1,6 +1,6 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # Upgrading from 1.6 to 1.7.5 or newer @@ -39,9 +39,7 @@ Alchemy delays the new host deployment, but old instances keep running; use a ma Update the Alchemy Better Auth package to a release supporting 1.7.5, then align Better Auth and its synchronized plugins/adapters: -```sh -npx auth@1.7.5 upgrade -``` + Use Node.js 22.12 or newer and the CLI version matching your target release. Review workspace catalogs and overrides. @@ -73,9 +71,7 @@ need no identity conversion when upgrading directly from 1.6. Drizzle users own schema migrations. Generate and review the auth schema: -```sh -npx auth@1.7.5 generate --config ./auth.cli.ts -``` + The CLI configuration exports an upstream Better Auth instance with the same plugins and schema options, using the Relations v2 adapter: diff --git a/.agents/skills/alchemy/references/better-auth/what-is-better-auth.md b/.agents/skills/alchemy/references/better-auth/what-is-better-auth.md new file mode 100644 index 00000000..bbae5e80 --- /dev/null +++ b/.agents/skills/alchemy/references/better-auth/what-is-better-auth.md @@ -0,0 +1,83 @@ + + +# What is Better Auth? + +> The concepts behind Better Auth — the auth server, users, accounts, sessions and cookies, sign-in providers, the signing secret, the database and its migrations, and middleware — and how @alchemy.run/better-auth models each of them. + +[Better Auth](https://better-auth.com) is a TypeScript library that runs sign-in inside your own app. Your users, their sessions and their linked accounts live in your own database, not a third party's, and the routes that sign people in and out are served by your own server. + +Take one small app: a Worker with email and password sign-in, GitHub sign-in, and an API that only signed-in users may call. A browser signs in through the auth routes. Better Auth checks the credentials, stores a session in your database and sets a cookie. Your API's middleware reads the cookie and gives each handler the current user. + + + +## The auth server + +Better Auth is an **auth server** you configure in code: which sign-in methods to offer, where its routes live, which plugins to add. It serves its own routes, under a base path like `/api/auth`, for signing up, signing in, signing out and reading the session. + +In Alchemy, you create it with `BetterAuth` and expose it as an Effect service your handlers can ask for: + +```typescript title="src/auth.ts" +const makeAuth = BetterAuth({ basePath: "/api/auth", emailAndPassword: { enabled: true } }); +``` + +## Users, accounts and sessions + +Better Auth keeps a few tables. A **user** is a person. An **account** links a user to a way of signing in: a password, or a GitHub identity. A **session** records that a user is signed in on one device, until it expires or they sign out. A **verification** row holds short-lived tokens, like an email confirmation. + +Because one user can have several accounts, a person who signed up with a password can later sign in with GitHub and stay the same user. + +## Sessions and cookies + +Signing in creates a session and sets a **cookie** in the browser. Every later request carries the cookie, and the server looks up its session to know who's asking. The cookie is signed with a **secret**, so it can't be forged. + +Alchemy creates that secret for you and keeps it stable across deploys, so sessions survive a redeploy. + +## Sign-in providers + +A **sign-in provider** is a way to prove who you are. **Email and password** keeps the password hash in your database. **OAuth providers**, like GitHub, Google or Microsoft, send the user to that service to sign in and back to your app with their identity. Each OAuth provider needs an app registered with it, whose client id and secret your server holds. + +See [Sign-in providers](/better-auth/sign-in-providers). + +## The database and migrations + +Better Auth needs a database for its tables, and it works with many. In Alchemy, the database is a Layer you provide to the Auth service, so the same service runs on D1, Neon, Postgres, Aurora or SQLite by changing one line. + +Its tables are created and updated on deploy, as migrations, so there's no schema to set up by hand. + +See [Databases](/better-auth/databases) and [Migrations](/better-auth/guides/migrations). + +## Middleware and the current user + +An API that needs a signed-in user asks for one from **middleware**: code that runs before the handler, reads the session from the request, and either provides the user or rejects the request. Handlers then just read the current user. + +See [HTTP API middleware](/better-auth/guides/http-api-middleware). + +## Plugins + +Better Auth grows through **plugins**: two-factor sign-in, passkeys, organizations, API keys and more. A plugin can add routes and tables, and its tables are migrated like the rest. + +## How @alchemy.run/better-auth models these concepts + +The auth server is an Effect service, built by `BetterAuth` with your options. Its database is a Layer you choose. Its secret is created and kept stable for you, its tables are migrated on deploy, and OAuth credentials come in through config bindings. Middleware turns a request into the current user for your Effect HTTP handlers. Everything else, every option and plugin, is Better Auth's own, documented at [better-auth.com](https://better-auth.com/docs). + +Next, build one: the [tutorial](/better-auth/tutorial/part-1) puts these ideas to work, one step at a time. diff --git a/.agents/skills/alchemy/references/boat/INDEX.md b/.agents/skills/alchemy/references/boat/INDEX.md new file mode 100644 index 00000000..1a4aaf0c --- /dev/null +++ b/.agents/skills/alchemy/references/boat/INDEX.md @@ -0,0 +1,40 @@ +# boat index + +19 pages. Run sandboxes on Boat with Alchemy. Declare sandboxes, snapshots, environments and webhooks in TypeScript, and create sandboxes from any Worker or Function. + +| Page | File | Covers | +| --- | --- | --- | +| Boat | `_overview.md` | Run sandboxes on Boat with Alchemy. Declare sandboxes, snapshots, environments and webhooks in TypeScript, and create sandboxes from any Worker or Function. | +| Account & API keys | `account-and-keys.md` | How a Boat account holds your sandboxes, how an API key limits what a caller can do, and the key each host gets instead of yours. | +| Setup | `setup.md` | Install @alchemy.run/boat, sign in to Boat with a profile, and deploy from CI. | +| What is Boat? | `what-is-boat.md` | The concepts behind Boat — accounts and API keys, sandboxes and their lifecycle, snapshots and forks, environments, credential profiles and the AI credentials proxy, ports and webhooks — and how @alchemy.run/boat models each of them. | + +## sandboxes/ + +| Page | File | Covers | +| --- | --- | --- | +| Choosing a runtime | `sandboxes/choosing-a-runtime.md` | Program sandboxes, a declared dev box, and sandboxes created per task, and when to use each. | +| Lifecycle events | `sandboxes/lifecycle-events.md` | Receive Boat's sandbox lifecycle events — ready, stopped, failed, restored — in a Cloudflare Worker, checked against Boat's signature and filtered to your stack's sandboxes. | +| Ports & URLs | `sandboxes/ports.md` | Serve a port of a Boat sandbox at an HTTPS URL, protected by a token or public, and call it or proxy to it from a Worker. | +| Programs | `sandboxes/programs.md` | Run an Effect HTTP program in its own Boat sandbox, served at a URL, restarted in place when its code changes. | +| Sandboxes | `sandboxes/sandboxes.md` | Boat sandboxes — machine sizes, auto-stop, stop and resume, labels — declared as a long-lived dev box or created per task from a Worker or Function. | +| Snapshots & forks | `sandboxes/snapshots.md` | Save a Boat sandbox's disk as a named snapshot, start sandboxes from it, and fork a sandbox into copies. | + +## security/ + +| Page | File | Covers | +| --- | --- | --- | +| Credential profiles | `security/credential-profiles.md` | Boat credential profiles — the AI keys and API secrets a sandbox gets, and the proxy that keeps the real ones out of it. | +| Credentials & bindings | `security/credentials.md` | What each host gets to reach Boat, deploy-time resources vs clients your app runs, and who owns the sandboxes your app creates. | +| Environments & secrets | `security/environments.md` | Boat environments — the variables, secret files and credentials a sandbox starts with, versioned on every change. | + +## tutorial/ + +| Page | File | Covers | +| --- | --- | --- | +| Part 1: Build a Snapshot | `tutorial/part-1.md` | Declare a Boat snapshot that clones a repository and installs tools at deploy time, so every sandbox starts ready. | +| Part 2: Start Sandboxes from It | `tutorial/part-2.md` | A Cloudflare Worker that starts a fresh Boat sandbox from the Golden snapshot for each request. | +| Part 3: A Copy per User | `tutorial/part-3.md` | Give each user a Boat sandbox started from the Golden snapshot, which keeps their changes and resumes when they come back. | +| Part 4: Update the Snapshot | `tutorial/part-4.md` | Change the Golden snapshot, redeploy, and see new sandboxes start from the new disk while existing ones keep theirs. | +| Part 5: Testing | `tutorial/part-5.md` | Deploy the Stack in a test, start sandboxes from the Golden snapshot, and check what they contain. | +| Part 6: Stages and CI | `tutorial/part-6.md` | Deploy a stage per environment and per pull request, each with its own Boat snapshot and Worker. | diff --git a/.agents/skills/alchemy/references/boat/_overview.md b/.agents/skills/alchemy/references/boat/_overview.md new file mode 100644 index 00000000..08b6539e --- /dev/null +++ b/.agents/skills/alchemy/references/boat/_overview.md @@ -0,0 +1,88 @@ + + +# Boat + +> Run sandboxes on Boat with Alchemy. Declare sandboxes, snapshots, environments and webhooks in TypeScript, and create sandboxes from any Worker or Function. + +Boat runs sandboxes: Linux machines with Docker, passwordless `sudo` and a desktop that start in under a second, stop on a timer with their disk saved, and resume, fork or snapshot from where they stopped. Declare sandboxes, snapshots, environments and webhooks in your Stack, and create sandboxes from any Worker or Function. + +**New to Boat?** Start with [What is Boat?](/boat/what-is-boat). + +## A quick example + +A snapshot is built once, at deploy: a sandbox with a repository cloned, saved under a name: + +```typescript title="src/Golden.ts" +import * as Boat from "@alchemy.run/boat"; + +export const Golden = Boat.Snapshot("Golden", { + run: ["git clone --depth 1 https://github.com/sindresorhus/is ~/repo"], +}); +``` + +A Worker starts a sandbox from it on each request, with the repository already there, runs the command it was sent, and deletes the sandbox when the request ends: + +```typescript title="src/Api.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Effect from "effect/Effect"; +import { HttpServerRequest } from "effect/http/HttpServerRequest"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; +import { Golden } from "./Golden.ts"; + +export default class Api extends Cloudflare.Worker()( + "Api", + { main: import.meta.url }, + Effect.gen(function* () { + const sandboxes = yield* Boat.CreateSandbox(Golden); + return { + fetch: Effect.gen(function* () { + const request = yield* HttpServerRequest; + const sandbox = yield* Effect.acquireRelease( + sandboxes.create({ noEnv: true, autoStop: "5 minutes" }), + (sandbox) => Effect.ignore(sandbox.delete()), + ); + const result = yield* sandbox.exec(yield* request.text, { cwd: "/home/user/repo" }); + return yield* HttpServerResponse.json(result); + }).pipe(Effect.scoped, Effect.orDie), + }; + }).pipe(Effect.provide(Boat.CreateSandboxHttp)), +) {} +``` + +And the Stack deploys both: + +```typescript title="alchemy.run.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Alchemy from "alchemy"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import Api from "./src/Api.ts"; +import { Golden } from "./src/Golden.ts"; + +export default Alchemy.Stack( + "MyApp", + { + providers: Layer.mergeAll(Cloudflare.providers(), Boat.providers()), + state: Cloudflare.state(), + }, + Effect.gen(function* () { + const golden = yield* Golden; + const api = yield* Api; + return { snapshot: golden.name, url: api.url.as() }; + }), +); +``` + +## Where to start + +**Want to build?** Start with [Setup](/boat/setup) to sign in to Boat, then the [tutorial](/boat/tutorial/part-1), which builds a code-running API one step at a time. + +**Looking for something specific?** Every section of these docs is listed below, and every resource is in the generated [API reference](/providers). + +## The docs + + diff --git a/.agents/skills/alchemy/references/boat/account-and-keys.md b/.agents/skills/alchemy/references/boat/account-and-keys.md new file mode 100644 index 00000000..99461119 --- /dev/null +++ b/.agents/skills/alchemy/references/boat/account-and-keys.md @@ -0,0 +1,120 @@ + + +# Account & API keys + +> How a Boat account holds your sandboxes, how an API key limits what a caller can do, and the key each host gets instead of yours. + +Everything you create on Boat belongs to your **account**: its sandboxes, snapshots, environments, webhooks and API keys. If you belong to an organization, sandboxes can be billed to it instead, and each one stays private to the person who created it. + +## A key reaches only what it's given + +An **API key** can do only what you give it. It carries the **actions** it may take, and can be limited to some sandboxes or the sandboxes of some environments. The host that runs a Worker below gets a key that reaches one sandbox and can do nothing else. + + + +## Sign in with a profile + +Alchemy deploys with the credentials in a [profile](/environments/profiles): + + + +Pick **Browser sign-in** for most setups. It works with every way you can sign in to Boat: GitHub, Google or an email code. Boat issues an API key that lasts a year, and Alchemy renews it before it runs out. + +Pick **API key** to paste one from the dashboard's **API Keys** tab. Deploying creates keys for your hosts, which takes `account.admin`, so give it the `admin` preset. + +## Work in an organization + +An organization has its own plan, its own wallet, and its own shared environments and credential profiles. You work in one the way the dashboard's organization select or `boat --org` do: the sandboxes you create bill it, and the environments and [credential profiles](/boat/security/credential-profiles) you manage are its shared ones. + +When you sign in, Alchemy picks your organization; it asks only when your account belongs to more than one. It stores the organization's id, so renaming the organization doesn't break the profile. Every call sends it, and so do the hosts Alchemy deploys. + +You can also follow your **active wallet**, the one `boat org switch` picks. Sandboxes then bill whatever it is when they are created, and environments stay personal, so most teams pin the organization. + +A Stack can pick its own organization, which overrides the profile's: + +```typescript title="alchemy.run.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Alchemy from "alchemy"; +import * as Effect from "effect/Effect"; + +export default Alchemy.Stack( + "Team", + { providers: Boat.providers({ org: "acme" }) }, + Effect.gen(function* () { + yield* Boat.Environment("Shared", { env: { REGION: "us" } }); + yield* Boat.Sandbox("TeamBox", { noEnv: true, visibility: "shared" }); + }), +); +``` + +A sandbox's wallet is fixed when it is created, so changing the organization later leaves existing sandboxes where they are; their `org` attribute says which. An environment belongs to one organization for life, so changing the organization replaces it. + +`visibility: "shared"` lets every member use a sandbox. Sharing one that holds your logins wipes them at its next start, so share sandboxes with `noEnv`, or on an environment that passes none of your credentials, which is how a declared one starts. + +Creating organizations, inviting members and buying seats stay on the dashboard and `boat org`. Boat doesn't offer them in its public API. + +## Give production its own profile + +A [stage](/environments/stages) decides what you deploy. The profile decides where. Give production its own Boat account, and its own profile: + + + +## Narrow a key to what it needs + +A key lists the actions it may take, or uses a preset. `read-only` inspects sandboxes, files, snapshots and environments. `full-sandbox` works in sandboxes but can't create, resume, fork or delete them. `ci` adds creating, resuming and forking, and deletes only the sandboxes it created. `admin` can do everything. + +Declare a key for CI or another app: + +```typescript title="src/Keys.ts" +import * as Boat from "@alchemy.run/boat"; + +export const Ci = Boat.ApiKey("Ci", { preset: "ci", ttl: "90d" }); +``` + +Or one that only runs commands in one sandbox: + +```typescript +const box = yield* DevBox; +const key = yield* Boat.ApiKey("BoxExec", { + actions: ["sandbox.read", "exec"], + sandboxIds: [box.sandboxId], +}); +``` + +`key.key` is the key, as a `Redacted` value. Boat shows a key only once, so Alchemy keeps it in state. A key can't be changed: new actions or sandboxes create a new key and delete the old one. + +A key can't do more, or live longer, than the key that creates it. A key your browser sign-in creates lasts at most a year, until your own key expires. Leave `ttl` out to get the longest lifetime Boat allows. + +## Deploy from CI with a key + +When `BOAT_API_KEY` is set, Alchemy uses it instead of the profile: + + + +Give the key the `admin` preset if the Stack has bindings: they create keys. `BOAT_ORG` picks the organization, and `BOAT_API_BASE_URL` overrides Boat's API URL. See [CI](/environments/ci). + +## Your plan caps how many sandboxes start + +Your plan caps how many sandboxes may run at once and how many may start each minute, hour and day. Resumes and forks count as starts. Past the hourly limit, creates fail with `SandboxStartLimitExceeded` until the window reopens; the per-minute limit is retried for you. + +What a sandbox starts with, its variables, secret files and credentials, is in [Environments & secrets](/boat/security/environments). Where to run your code is in [Choosing a runtime](/boat/sandboxes/choosing-a-runtime). diff --git a/.agents/skills/alchemy/references/boat/sandboxes/choosing-a-runtime.md b/.agents/skills/alchemy/references/boat/sandboxes/choosing-a-runtime.md new file mode 100644 index 00000000..b68524ea --- /dev/null +++ b/.agents/skills/alchemy/references/boat/sandboxes/choosing-a-runtime.md @@ -0,0 +1,135 @@ + + +# Choosing a runtime + +> Program sandboxes, a declared dev box, and sandboxes created per task, and when to use each. + +Every way of running code on Boat is a sandbox: a Linux machine that stops on a timer with its disk saved. They differ in who starts the work, and who decides when the machine comes and goes. + +## Boat manages less as you decide more + +Each runtime hands you more of the machine: + + + +## Programs: your server at a URL + +A `Boat.Sandbox` with a `main` runs your Effect program with Node.js. Each deploy that changes the code restarts it in the same sandbox, and its port answers at `https://-3000.on.boat.dev`. + +```typescript title="src/Api.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +export default class Api extends Boat.Sandbox()( + "Api", + { main: import.meta.url, public: true }, + Effect.gen(function* () { + return { fetch: Effect.succeed(HttpServerResponse.text("hello")) }; + }), +) {} +``` + +A program sandbox never stops on its own. Choose it for an API or a service that needs a whole machine: Docker, a desktop, a long-lived process. See [Programs](/boat/sandboxes/programs). + + + +## A dev box: one machine you drive + +A `Boat.Sandbox` without `main` is a machine the Stack keeps. A Worker reaches it with `ConnectSandbox`, runs commands in it, and resumes it when it has stopped. + +```typescript +const devBox = yield* Boat.ConnectSandbox(DevBox); +yield* devBox.resume({ autoStop: "30 minutes" }); +yield* devBox.exec("git pull && npm test", { cwd: "/home/user/app" }); +``` + +It stops after its `autoStop` with its disk saved, so you pay for it only while it works. Choose it for an agent's home, a preview environment, or a build box. See [Sandboxes](/boat/sandboxes/sandboxes#drive-a-declared-sandbox-from-a-worker). + + + +## Sandboxes per task: as many machines as you need + +`CreateSandbox` gives a Worker or Function a client that creates sandboxes, from a snapshot when you bind one. Your code drives each one and deletes it when the task is done. + +```typescript +const sandboxes = yield* Boat.CreateSandbox(Golden); +const sandbox = yield* sandboxes.create({ type: "small", autoStop: "10 minutes" }); +yield* sandbox.exec("npm test"); +yield* sandbox.delete(); +``` + +Choose it for agent loops, code a user sends, and anything that needs a fresh machine each time. See [Sandboxes](/boat/sandboxes/sandboxes#create-sandboxes-while-your-app-runs). + + + +## Mix runtimes in one app + +One account runs all three at once. A Worker creates a sandbox per task from a snapshot, drives a dev box, and calls a program's API: + + diff --git a/.agents/skills/alchemy/references/boat/sandboxes/lifecycle-events.md b/.agents/skills/alchemy/references/boat/sandboxes/lifecycle-events.md new file mode 100644 index 00000000..5020d429 --- /dev/null +++ b/.agents/skills/alchemy/references/boat/sandboxes/lifecycle-events.md @@ -0,0 +1,122 @@ + + +# Lifecycle events + +> Receive Boat's sandbox lifecycle events — ready, stopped, failed, restored — in a Cloudflare Worker, checked against Boat's signature and filtered to your stack's sandboxes. + +A **webhook** is an HTTPS endpoint of yours that Boat calls with each event you subscribe to. Every event is about one sandbox. + +## Each event is a sandbox changing state + +A sandbox fires an event as it becomes ready, gets its files back, stops, fails, or drops out of reach: + + + +## Subscribe a Worker to events + +Subscribe a Worker to the events it needs, with a handler for each one: + +```typescript title="src/Api.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +export default class Api extends Cloudflare.Worker()( + "Api", + { main: import.meta.url }, + Effect.gen(function* () { + yield* Boat.consumeSandboxEvents({ events: ["sandbox.ready", "sandbox.archived"] }, (event) => + Effect.log(`${event.data.sandbox.id} is ${event.data.state}`), + ); + return { fetch: Effect.succeed(HttpServerResponse.text("ok")) }; + }).pipe(Effect.provide(Boat.SandboxEventsLive)), +) {} +``` + +At deploy, Alchemy registers a webhook pointing at the Worker's `/__alchemy/boat/events`, and gives the Worker its signing secret as a Cloudflare secret. Boat retries a delivery that fails, so make the handler safe to repeat, keyed on `event.id`. Destroying the Worker removes the webhook. + +## The Worker checks every delivery + +Boat signs each delivery with the webhook's secret: + +```http +POST /__alchemy/boat/events +X-Ascii-Delivery: dlv_8a2c +X-Ascii-Timestamp: 1762531200 +X-Ascii-Signature: v1= +``` + +The Worker checks every request before your handler runs. It refuses, with 401, a request without Boat's signature, one signed with another secret, one whose body was changed after signing, and one more than five minutes old, so a captured delivery can't be replayed later. The signature covers the delivery id, the timestamp and the body, and the event's `id` must be the signed delivery id. Requests over 1 MB are refused unread, and events you didn't subscribe to are acknowledged without running the handler. + +## The Worker holds two keys + +The Worker holds two keys, both deployed as Cloudflare secrets, never as plain-text variables: + +- **The signing secret** (`whsec_...`). Boat creates it with the webhook and signs every delivery with it; the Worker refuses anything not signed with it. Boat shows it only once, so Alchemy keeps it in state as a `Redacted` value. Destroying the Worker deletes the webhook, and the secret with it. +- **A Boat API key** for the Worker alone, which can only read sandboxes (`sandbox.read`). The Worker uses it to look up which stack a sandbox belongs to. It reads any sandbox in the account, because Boat can't narrow a key by label; it can't create, change or delete anything. Destroying the Worker deletes it. With `scope: "account"` there is no lookup, and no key. + +The signing secret is what keeps others out: nothing reaches your handler without it. + +## Your handler sees only your stack's sandboxes + +Boat sends a webhook the events of every sandbox in the account. The event names only the sandbox's id, so the Worker reads its labels from Boat, with a key that can only read sandboxes, and hands your handler only the ones this stack and stage own: sandboxes the Stack declares, and the ones its bindings create. + + + +The event your handler gets carries the labels, so you can route by your own labels too: + +```typescript +yield* Boat.consumeSandboxEvents({ events: ["sandbox.archived"] }, (event) => + event.data.sandbox.labels?.user === undefined + ? Effect.void + : Effect.log(`${event.data.sandbox.labels.user}'s sandbox stopped`), +); +``` + +The scope is a filter, not an access boundary: anyone in your Boat account who can create sandboxes can label one with your stack's labels. To receive every sandbox's events, pass `scope: "account"`. The Worker then skips the lookup, and `labels` is undefined. A sandbox that was deleted before its event arrived can't be read, so `scope: "stack"` drops its events. When Boat can't be reached for the lookup, the Worker answers 503 and Boat delivers the event again. + +## An account holds 10 webhooks + +An account has at most 10 webhooks, and each Worker that consumes events, in each stage, uses one. Destroy stages you no longer use. Boat delivers only to public HTTPS URLs on port 443, so under `alchemy dev` no webhook is registered. + +## Point a webhook at any endpoint + +For an endpoint that isn't an Alchemy host, declare the webhook directly: + +```typescript title="alchemy.run.ts" +const hook = yield* Boat.Webhook("Events", { + url: "https://example.com/boat", + events: ["sandbox.ready", "sandbox.archived"], +}); +``` + +`hook.secret` is the signing secret, as a `Redacted` value: Boat shows it only when the webhook is created, so Alchemy keeps it in state. Check each delivery's signature, as above, before acting on the event. Changing the URL or the events updates the webhook in place. diff --git a/.agents/skills/alchemy/references/boat/sandboxes/ports.md b/.agents/skills/alchemy/references/boat/sandboxes/ports.md new file mode 100644 index 00000000..b872593d --- /dev/null +++ b/.agents/skills/alchemy/references/boat/sandboxes/ports.md @@ -0,0 +1,78 @@ + + +# Ports & URLs + +> Serve a port of a Boat sandbox at an HTTPS URL, protected by a token or public, and call it or proxy to it from a Worker. + +A server listening on a port inside a sandbox answers at `https://-.on.boat.dev` once Boat hosts the port. A hosted port is **protected** by default: requests need its token. A **public** port answers anyone. + +## A port is protected by its token + +Without the token, the port's URL refuses the request: + + + +## Call a port with its token + +`getTcpPort` hosts the port and returns its URL and token. Its `fetch` sends a request there with the token: + +```typescript +const port = yield* sandbox.getTcpPort(3000); +const response = yield* port.fetch(HttpClientRequest.get("/health")); +``` + +The request's path, query, method, headers and body are kept, and bodies stream both ways. + +## Proxy a Worker's request to it + +Pass the Worker's own request to `fetch` to forward it to the sandbox, and return the response: + +```typescript +fetch: Effect.gen(function* () { + const port = yield* devBox.getTcpPort(3000); + return yield* port.fetch(yield* HttpServerRequest); +}); +``` + +## Open a port to anyone + +```typescript +const port = yield* sandbox.getTcpPort(3000, { public: true }); +``` + +Anyone with the URL can call it. For a program, set `public: true` on its `Boat.Sandbox`. + +## Reach a server bound to localhost + +Boat relays to a server bound to `0.0.0.0`. For one that listens on `127.0.0.1` only, pass `localhost: true`: + +```typescript +const port = yield* sandbox.getTcpPort(5173, { localhost: true }); +``` + +## Hand the URL to a browser + +The token works on the `_token` query parameter as well, which answers with a redirect that sets the cookie, so a browser can open the URL: + +```typescript +const port = yield* sandbox.getTcpPort(3000); +const link = `${port.url}?_token=${Redacted.value(port.token!)}`; +``` + +The token is the same every time for one sandbox and port. Treat it as a secret. + +To hear when sandboxes start and stop, see [Lifecycle events](/boat/sandboxes/lifecycle-events). diff --git a/.agents/skills/alchemy/references/boat/sandboxes/programs.md b/.agents/skills/alchemy/references/boat/sandboxes/programs.md new file mode 100644 index 00000000..c4fd5f82 --- /dev/null +++ b/.agents/skills/alchemy/references/boat/sandboxes/programs.md @@ -0,0 +1,103 @@ + + +# Programs + +> Run an Effect HTTP program in its own Boat sandbox, served at a URL, restarted in place when its code changes. + +A **program** is your own server, run in a sandbox the Stack declares. Alchemy bundles it, uploads it into the sandbox and starts it with Node.js 24, then serves its port at `https://-3000.on.boat.dev`. + +## Give a sandbox a program + +Give `Boat.Sandbox` a `main` and an implementation: + +```typescript title="src/Api.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; + +export default class Api extends Boat.Sandbox()( + "Api", + { main: import.meta.url, type: "small", noEnv: true, public: true }, + Effect.gen(function* () { + return { + fetch: Effect.gen(function* () { + return yield* HttpServerResponse.json({ ok: true }); + }), + }; + }), +) {} +``` + +Add it to the Stack and return its URL: + +```typescript title="alchemy.run.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Alchemy from "alchemy"; +import * as Effect from "effect/Effect"; +import Api from "./src/Api.ts"; + +export default Alchemy.Stack( + "MyApp", + { providers: Boat.providers(), state: Alchemy.localState() }, + Effect.gen(function* () { + const api = yield* Api; + return { url: api.url.as() }; + }), +); +``` + +The program listens on `port` (3000 unless you say otherwise), and reads `PORT` from its environment. + +## A deploy restarts the process, not the sandbox + +A program's sandbox stays the same across deploys; only the process changes. + + + +An unchanged deploy leaves the process alone. A program sandbox never stops on its own unless you set `autoStop`. If it stopped anyway, or rebooted, the next deploy resumes it and starts the program again. + +`env` on a program sandbox is the program's: changing it restarts the process, without replacing the sandbox. + +## Its URL needs a token unless it's public + +A program's URL needs its token unless you set `public: true`. The token is `urlToken`, sent as the `_token` query parameter or the `_port_auth` cookie: + +```typescript +const api = yield* Api; +return { url: api.url, token: api.urlToken }; +``` + +See [Ports & URLs](/boat/sandboxes/ports). + +## Use bindings from the program + +A program uses bindings like any other host. Each gets its own key, which can do only what that binding needs: + +```typescript +Effect.gen(function* () { + const sandboxes = yield* Boat.CreateSandbox(); + return { + fetch: Effect.gen(function* () { + const running = yield* sandboxes.list({ labels: { pool: "agents" } }); + return yield* HttpServerResponse.json({ count: running.length }); + }), + }; +}).pipe(Effect.provide(Boat.CreateSandboxHttp)); +``` + +To start sandboxes with a project already set up, see [Snapshots & forks](/boat/sandboxes/snapshots). diff --git a/.agents/skills/alchemy/references/boat/sandboxes/sandboxes.md b/.agents/skills/alchemy/references/boat/sandboxes/sandboxes.md new file mode 100644 index 00000000..d924207c --- /dev/null +++ b/.agents/skills/alchemy/references/boat/sandboxes/sandboxes.md @@ -0,0 +1,133 @@ + + +# Sandboxes + +> Boat sandboxes — machine sizes, auto-stop, stop and resume, labels — declared as a long-lived dev box or created per task from a Worker or Function. + +A **sandbox** is a Linux machine: Ubuntu with Docker, Node.js, Bun and Python, and `sudo` that needs no password. It comes in four sizes: `small` (2 vCPUs, 4 GB), `default`, `large` and `xlarge`, the last on Boat's $100 plan and up. A sandbox starts in under a second, runs for its `autoStop`, then stops and keeps its disk. + +## A sandbox stops, keeps its disk, and resumes + +Stopping saves the disk, and resuming brings the files back: + + + +Processes don't survive a stop: a resumed sandbox has your files, and nothing running. + +## Declare a sandbox + +A sandbox in the Stack is one that outlives requests: a dev box, an agent's home, a preview environment. + +```typescript title="src/DevBox.ts" +import * as Boat from "@alchemy.run/boat"; + +export const DevBox = Boat.Sandbox("DevBox", { + type: "large", + autoStop: "60 minutes", + setupScript: "git clone https://github.com/alchemy-run/alchemy ~/alchemy", +}); +``` + +`setupScript` runs once, in the background, after the sandbox starts; `setupStatus` says how it went. `autoStop: false` never stops it. Changing the name, subdomain or `autoStop` updates the sandbox in place. A new `type`, `env`, `environment`, `setupScript`, `labels`, or a new or rebuilt `snapshot`, replaces it, and the old sandbox's disk goes with it. + +## Keep the account's secrets out of untrusted code + +A sandbox gets your account's default environment, with its variables, secret files and credentials, unless you say otherwise. For a sandbox that runs someone else's code, pass `noEnv`: + +```typescript +export const Untrusted = Boat.Sandbox("Untrusted", { noEnv: true, env: { TASK: "lint" } }); +``` + +It gets only its own `env`, and it can't act on your account or other sandboxes. See [Environments & secrets](/boat/security/environments) for sandboxes that should get some secrets and not others. + +## Create sandboxes while your app runs + +For a sandbox per user or per task, bind `CreateSandbox` in a Worker or Function, and create sandboxes while it runs: + +```typescript title="src/Api.ts" +const sandboxes = yield* Boat.CreateSandbox(); +// in fetch: +const sandbox = yield* Effect.acquireRelease( + sandboxes.create({ type: "small", noEnv: true, autoStop: "10 minutes" }), + (sandbox) => Effect.ignore(sandbox.delete()), +); +``` + +Provide `Boat.CreateSandboxHttp`. `create` takes Boat's own parameters (`type`, `env`, `environment`, `noEnv`, `setupScript`, `labels`, `from`), and `autoStop`. + +## Find a sandbox again by its labels + +Labels mark a sandbox when it's created. Find it by them on the next request, and resume it with its files: + +```typescript +const [existing] = yield* sandboxes.list({ labels: { user } }); +const sandbox = existing + ? yield* sandboxes.connect(existing.id) + : yield* sandboxes.create({ type: "small", autoStop: "10 minutes", labels: { user } }); +yield* sandbox.resume({ autoStop: "10 minutes" }); +``` + +Sandboxes a binding creates also carry `alchemy.stack`, `alchemy.stage` and `alchemy.id`. They aren't deleted when the Stack is destroyed, so list them by those labels to clean up. + +## Run commands + +`exec` runs to completion and returns `{ exitCode, stdout, stderr }`. A non-zero exit is returned, not failed. A string runs in a shell, an array runs its arguments as given: + +```typescript +const test = yield* sandbox.exec("npm test", { cwd: "/home/user/app" }); +const version = yield* sandbox.exec(["node", "--version"]); +const sorted = yield* sandbox.exec("sort", { stdin: "b\na\n", env: { LC_ALL: "C" } }); +``` + +Boat stops a command after 30 seconds unless you pass a `timeout`, up to 10 minutes; one that runs past it fails with `ExecTimedOut`. For anything longer, or a server, start it in the background and read its output as it comes: + +```typescript +const server = yield* sandbox.start("npm run dev", { cwd: "/home/user/app" }); +yield* server.output.pipe( + Stream.take(5), + Stream.runForEach((chunk) => Effect.log(new TextDecoder().decode(chunk.data))), +); +``` + +A background command keeps running after the request ends; `sandbox.processes.attach(server.processId)` picks it up again. + +## Read and write files + +Paths are relative to `/home/user`. Boat reaches files under `/home/user` and `/tmp`: + +```typescript +yield* sandbox.files.write("app/config.json", JSON.stringify(config)); +const log = yield* sandbox.files.readText("/tmp/build.log"); +const entries = yield* sandbox.files.list("app"); +``` + +A missing path fails with `FileNotFound`. Writing creates the parent directories. + +## Drive a declared sandbox from a Worker + +Bind `ConnectSandbox` to reach a sandbox the Stack declares, from a Worker or Function: + +```typescript +const devBox = yield* Boat.ConnectSandbox(DevBox); +// in fetch: +yield* devBox.resume({ autoStop: "30 minutes" }); +const result = yield* devBox.exec("git pull && npm test", { cwd: "/home/user/alchemy" }); +``` + +Provide `Boat.ConnectSandboxHttp`. A call into a stopped sandbox fails with `SandboxNotRunning`, so resume it first. Resuming one that's running does nothing. + +To run your own server in a sandbox, see [Programs](/boat/sandboxes/programs). diff --git a/.agents/skills/alchemy/references/boat/sandboxes/snapshots.md b/.agents/skills/alchemy/references/boat/sandboxes/snapshots.md new file mode 100644 index 00000000..31d316b0 --- /dev/null +++ b/.agents/skills/alchemy/references/boat/sandboxes/snapshots.md @@ -0,0 +1,95 @@ + + +# Snapshots & forks + +> Save a Boat sandbox's disk as a named snapshot, start sandboxes from it, and fork a sandbox into copies. + +A **snapshot** is a sandbox's disk saved under a name: installed packages, a cloned repository, a warm build cache. A sandbox started from it begins exactly there. A **fork** copies one sandbox into a new one from its last snapshot, which Boat takes now and then while it runs, and every time it stops. + +## Every sandbox starts from the same disk + +The setup runs once, at deploy. Every sandbox after it starts with the work already done, and changes only its own copy: + + + +## Build a snapshot from commands + +List the commands that set it up: + +```typescript title="src/Golden.ts" +import * as Boat from "@alchemy.run/boat"; + +export const Golden = Boat.Snapshot("Golden", { + run: [ + "git clone https://github.com/alchemy-run/alchemy ~/alchemy", + "cd ~/alchemy && pnpm install", + ], +}); +``` + +Alchemy starts a sandbox with none of your account's secrets, runs the commands in order, saves its disk and deletes the sandbox. A command that exits non-zero fails the deploy with `SnapshotSetupFailed`. A deploy runs them again only when the commands, `env`, `cwd`, `type` or `from` change, and saves the new disk under the same name. Destroying the resource deletes it. + +Build one snapshot on another with `from`: + +```typescript +export const Tools = Boat.Snapshot("Tools", { run: ["npm i -g pnpm"] }); +export const Golden = Boat.Snapshot("Golden", { from: Tools, run: ["pnpm dlx playwright install"] }); +``` + +## Start sandboxes from a snapshot + +A declared sandbox starts from a snapshot with `snapshot`: + +```typescript +export const Box = Boat.Sandbox("Box", { snapshot: Golden }); +``` + +When the snapshot is rebuilt, the sandbox is replaced, so it starts from the new disk. + +So do the sandboxes a binding creates, when you bind the snapshot: + +```typescript +const sandboxes = yield* Boat.CreateSandbox(Golden); +const sandbox = yield* sandboxes.create({ autoStop: "10 minutes" }); +``` + +A sandbox from a snapshot takes its machine size unless you pass `type`. + +## Fork a sandbox into a copy + +`fork` starts a copy of a sandbox your code created, from its last snapshot: + +```typescript +yield* sandbox.stop(); // stopping takes a snapshot +const copy = yield* sandbox.fork({ autoStop: "10 minutes" }); +yield* sandbox.resume(); +``` + +Before a sandbox has a snapshot, `fork` fails with `ForkNeedsSnapshot`. Boat never copies labels onto a fork; Alchemy adds the host's `alchemy.*` labels again. + +## Save a running sandbox under a name + +A handle saves its sandbox under a name of your own, and waits until it's ready: + +```typescript +const saved = yield* sandbox.snapshot("after-install"); +``` + +Snapshots your code saves aren't deleted with the Stack. + +To give sandboxes variables, secret files and credentials, see [Environments & secrets](/boat/security/environments). diff --git a/.agents/skills/alchemy/references/boat/security/credential-profiles.md b/.agents/skills/alchemy/references/boat/security/credential-profiles.md new file mode 100644 index 00000000..73f418aa --- /dev/null +++ b/.agents/skills/alchemy/references/boat/security/credential-profiles.md @@ -0,0 +1,151 @@ + + +# Credential profiles + +> Boat credential profiles — the AI keys and API secrets a sandbox gets, and the proxy that keeps the real ones out of it. + +A **credential profile** is a named set of AI credentials that Boat stores encrypted: API keys for Anthropic, OpenAI and other providers, secrets for any other HTTPS API, and the Claude or ChatGPT sign-ins you make on the dashboard. A sandbox gets the profile its [environment](/boat/security/environments) names. Boat never returns a secret once it's stored. + +## Declare a profile + +```typescript title="src/MyProfile.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Config from "effect/Config"; + +export const MyProfile = Boat.CredentialProfile("MyProfile", { + anthropic: Config.Redacted("ANTHROPIC_API_KEY"), + openai: Config.Redacted("OPENAI_API_KEY"), +}); +``` + +Each provider has its own prop: `anthropic`, `openai`, `openrouter`, `llmgateway`, `deepseek`, `moonshot`, `mistral`, `xai` and `opencode`. + +The props are the whole list. A deploy sets a key whose value changed, and removes an API key the props no longer name. Sign-ins and Bedrock are connected on the dashboard's **Agents & Proxying** page, and a deploy leaves them alone. + +## Give sandboxes the profile + +Name the profile on an environment, and start sandboxes on it: + +```typescript title="src/Sandboxes.ts" +import * as Boat from "@alchemy.run/boat"; +import { MyProfile } from "./MyProfile.ts"; + +export const MyEnv = Boat.Environment("MyEnv", { + credentialProfile: MyProfile, +}); + +export const Box = Boat.Sandbox("Box", { environment: MyEnv }); +``` + +`Box` starts with `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` set. An environment that names no profile passes no AI credentials. + +Boat refuses to delete a profile an environment still names, so a destroy deletes the environment first. + +## Add a secret for any other API + +`apis` holds a secret for any HTTPS API, with the base URL it's sent to. The key of each entry is the variable the sandbox gets: + +```typescript title="src/MyProfile.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Config from "effect/Config"; + +export const MyProfile = Boat.CredentialProfile("MyProfile", { + anthropic: Config.Redacted("ANTHROPIC_API_KEY"), + apis: { + STRIPE_KEY: { + key: Config.Redacted("STRIPE_KEY"), + baseUrl: "https://api.stripe.com/v1", + }, + }, +}); +``` + +A sandbox gets `STRIPE_KEY` and `STRIPE_KEY_BASE_URL`. Code in the sandbox sends its requests to `$STRIPE_KEY_BASE_URL`, never to the API's own address: + +```sh +curl "$STRIPE_KEY_BASE_URL/charges" \ + -H "Authorization: Bearer $STRIPE_KEY" +``` + +The name is `A-Z`, `0-9` and `_`, up to 64 characters. Provider names like `ANTHROPIC_*` and `AWS_*`, and names ending in `_BASE_URL`, are reserved. The base URL is HTTPS on the default port, with a public DNS name. + +## Keep real keys out of the sandbox + +A sandbox normally holds the real keys, and anyone with a shell in it can copy them. With Boat's **AI credentials proxy** on, the sandbox gets a placeholder for each key and the proxy's URL for each base URL. Boat swaps the real key in as the request passes through. + + + +A placeholder is worth nothing outside Boat, and a copied one stops working when the sandbox stops: every start gets new ones. The proxy sends each provider key only to its own provider, and only in the `Authorization` or `x-api-key` header. + +The proxy is one switch for a whole account. `Boat.AiProxy` turns it on: + +```typescript title="src/Proxy.ts" +import * as Boat from "@alchemy.run/boat"; + +export const Proxy = Boat.AiProxy("Proxy"); +``` + +Boat bills the proxy: $1 for each day it's on, and $1 per 1,000 proxied requests. With it on, every sandbox on one of the account's profiles gets placeholders from its next start. Destroying the Stack puts the switch back the way it was. + +Bedrock credentials sign each request, so there's nothing to swap. Boat keeps them out of sandboxes while the proxy is on. + +## Give users' sandboxes AI without the keys + +A `safeForThirdParties` environment passes nothing of your account, AI credentials included. `proxyAiCredentials` passes them anyway, as placeholders: + +```typescript title="src/Tenants.ts" +import * as Boat from "@alchemy.run/boat"; +import { MyProfile } from "./MyProfile.ts"; +import { Proxy } from "./Proxy.ts"; + +export const Tenants = Boat.Environment("Tenants", { + safeForThirdParties: true, + credentialProfile: MyProfile, + proxyAiCredentials: Proxy, +}); +``` + +Someone with a shell in a `Tenants` sandbox can run an agent, and can't take your key. Passing the proxy itself means the switch is turned on before the environment asks for it: Boat rejects `proxyAiCredentials` while the proxy is off. + +## Use the profile you set up on the dashboard + +Every account has a profile named `default`, which holds the sign-ins and keys you connect on the dashboard. `lookup` finds it by name, and the Stack never changes or deletes it: + +```typescript title="src/Sandboxes.ts" +import * as Boat from "@alchemy.run/boat"; + +export const MyEnv = Boat.Environment("MyEnv", { + credentialProfile: Boat.CredentialProfile.lookup({ name: "default" }), +}); +``` + +This is how a sandbox gets your Claude or ChatGPT subscription, which only a browser sign-in can connect. + +## Share a profile with an organization + +A profile is yours, or an organization's. When the Stack [works in an organization](/boat/account-and-keys#work-in-an-organization), the profiles it declares belong to the organization: every member's sandboxes can use them, and only owners change them. Name one on an environment of the same organization. + +The proxy follows the same rule. An organization has its own switch, which only an owner changes, and `Boat.AiProxy` in a Stack that works in the organization is that switch. + +## Pull keys from a secrets manager + +`Config.Redacted("ANTHROPIC_API_KEY")` reads `.env` by default. A Stack's `secrets` option reads the same name from a secrets manager like Doppler or Infisical instead, so a production key never sits in a file on anyone's machine. See [Secret providers](/environments/secret-providers). diff --git a/.agents/skills/alchemy/references/boat/security/credentials.md b/.agents/skills/alchemy/references/boat/security/credentials.md new file mode 100644 index 00000000..19a67de0 --- /dev/null +++ b/.agents/skills/alchemy/references/boat/security/credentials.md @@ -0,0 +1,81 @@ + + +# Credentials & bindings + +> What each host gets to reach Boat, deploy-time resources vs clients your app runs, and who owns the sandboxes your app creates. + +Boat is built for sandboxes your app creates while it runs: one per task, per user, per request. Alchemy splits the API in two to match. + +## Resources live as long as the Stack + +The few long-lived things an app shares are resources in your Stack: a dev box, a snapshot to start from, an environment, a webhook. + +```typescript title="src/Sandboxes.ts" +import * as Boat from "@alchemy.run/boat"; + +export const Golden = Boat.Snapshot("Golden", { run: ["npm i -g pnpm"] }); +export const DevBox = Boat.Sandbox("DevBox", { snapshot: Golden, autoStop: "30 minutes" }); +``` + +They deploy, update and delete with the Stack like any other resource. + +## Bindings create sandboxes while your app runs + +Everything per task or per request comes from a binding. `CreateSandbox` creates sandboxes, with Boat's own parameters: + +```typescript +const sandboxes = yield* Boat.CreateSandbox(Golden); +const sandbox = yield* sandboxes.create({ type: "small", autoStop: "10 minutes" }); +``` + +`ConnectSandbox(DevBox)` works in a sandbox the Stack declares, and `consumeSandboxEvents` receives lifecycle events. Both sandbox bindings return the same handle. + +## What your app creates outlives the Stack + +Sandboxes a binding creates are labelled with the stack, stage and host (`alchemy.stack`, `alchemy.stage`, `alchemy.id`) and are not deleted when the stack is destroyed. Boat's label keys can't hold `:`, so they use `.` where Alchemy's tags use `::`. + + + +List them by those labels to clean them up, from the host that created them (its key deletes only its own): + +```typescript +const sandboxes = yield* Boat.CreateSandbox(); +const left = yield* sandboxes.list({ + labels: { "alchemy.stack": "my-app", "alchemy.stage": "prod", "alchemy.id": "Api" }, +}); +yield* Effect.forEach(left, (sandbox) => sandboxes.delete(sandbox.id)); +``` + +## Each host gets a key of its own + +Boat has no workload identity a host could sign in with, so each binding gets an API key of its own: created at deploy, deleted when the host is destroyed, and narrowed to what that binding does. Your own key never reaches the host. + +`ConnectSandbox(box)` gets a key that reaches only `box`. It runs commands, uses files, hosts ports, and stops, resumes and snapshots that one sandbox. `CreateSandbox()` gets a key that creates sandboxes and works in them, and deletes only the sandboxes it created. `consumeSandboxEvents` gets a key that can only read sandboxes, to tell which ones are the stack's, and the webhook's signing secret to check each delivery; see [Lifecycle events](/boat/sandboxes/lifecycle-events#the-worker-holds-two-keys). + +None of them can read your environments, webhooks or other keys. On a Cloudflare Worker, every key and secret deploys as a Cloudflare secret. + +These are the keys your app holds. What a sandbox holds comes from its [environment](/boat/security/environments), and its AI keys from a [credential profile](/boat/security/credential-profiles). + +## Hand out a port's token, never a key + +A port's token opens one port of one sandbox, for a browser or a client that shouldn't hold a key: + +```typescript +const port = yield* sandbox.getTcpPort(3000); +const link = `${port.url}?_token=${Redacted.value(port.token!)}`; +``` + +For another app or CI, declare a key with only the actions it needs. See [Account & API keys](/boat/account-and-keys#narrow-a-key-to-what-it-needs). diff --git a/.agents/skills/alchemy/references/boat/security/environments.md b/.agents/skills/alchemy/references/boat/security/environments.md new file mode 100644 index 00000000..a1b2c78f --- /dev/null +++ b/.agents/skills/alchemy/references/boat/security/environments.md @@ -0,0 +1,138 @@ + + +# Environments & secrets + +> Boat environments — the variables, secret files and credentials a sandbox starts with, versioned on every change. + +An **environment** is what a sandbox starts with: environment variables, secret files, and which of your account's credentials it gets — a GitHub token for your repositories, a Boat key of its own, the AI keys of a [credential profile](/boat/security/credential-profiles). Your account has a default environment, `base`, which sandboxes get unless they name another. + +## Every change makes a new version + +Every change to an environment makes a new **version**. A sandbox keeps the version it started on, so a change reaches new sandboxes, not running ones; the dashboard upgrades running ones. + + + +## Declare an environment with variables and secret files + +```typescript title="src/MyEnv.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Config from "effect/Config"; + +export const MyEnv = Boat.Environment("MyEnv", { + env: { NODE_ENV: "production", TOKEN: Config.Redacted("AGENT_TOKEN") }, + secretFiles: [{ path: ".npmrc", contents: Config.Redacted("NPMRC") }], +}); +``` + +Secret file paths are under the home directory: `.npmrc`, `~/.npmrc` and `/home/user/.npmrc` are the same file. Values stay `Redacted` in state. Boat stores variables as a `.env` file, which can't hold a value with a newline, or with both `'` and `"`; such a value fails with `InvalidEnvironmentValue`. + +An unchanged deploy makes no new version. A changed one updates only what differs. + +## Start sandboxes on an environment + +Pass the environment to a declared sandbox: + +```typescript +export const Box = Boat.Sandbox("Box", { environment: MyEnv }); +``` + +A sandbox your code creates names it: + +```typescript +const env = yield* MyEnv; +const sandbox = yield* sandboxes.create({ environment: env.name, autoStop: "10 minutes" }); +``` + +## Choose which credentials it passes + +An environment you declare passes its own `env` and `secretFiles`, and nothing of your account. Each of your credentials is a flag you turn on: + +```typescript +export const Mine = Boat.Environment("Mine", { + passGithub: true, // your repositories, and a GitHub token + passSandboxCredentials: true, // a Boat key, to run `boat` inside the sandbox +}); +``` + +Boat's own default is to pass everything, which is what `base` does. Alchemy sets each flag explicitly, so a sandbox holds only what its environment asks for. + +AI keys come from a [credential profile](/boat/security/credential-profiles). Name one, and its keys reach the environment's sandboxes: + +```typescript +export const WithAi = Boat.Environment("WithAi", { credentialProfile: MyProfile }); +``` + +## Give sandboxes to your users + +`safeForThirdParties` passes nothing of your account, whatever the flags say. Use it for sandboxes someone else gets a shell in: + +```typescript +export const Tenants = Boat.Environment("Tenants", { safeForThirdParties: true }); +``` + +Such sandboxes can still call AI providers through Boat's proxy, holding placeholders instead of keys. See [Keep real keys out of the sandbox](/boat/security/credential-profiles#keep-real-keys-out-of-the-sandbox). + +A single sandbox with none of the account's secrets doesn't need an environment: pass `noEnv: true` on it. + +## Use an environment the Stack doesn't manage + +`Boat.Environment.lookup` finds an environment by name, like the `base` one every account has. The Stack reads it and never changes or deletes it: + +```typescript +export const Box = Boat.Sandbox("Box", { + environment: Boat.Environment.lookup({ name: "base" }), +}); +``` + +## Pull values from a secrets manager + +`.env` is only the default. A Stack's `secrets` option reads the same `Config` values from a secrets manager instead, like Doppler or Infisical, so production keys never sit in a file on anyone's machine. Pick the source per stage: + +```typescript title="alchemy.run.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Doppler from "@alchemy.run/doppler"; +import * as Alchemy from "alchemy"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { MyEnv } from "./src/MyEnv.ts"; + +export default Alchemy.Stack( + "MyApp", + { + providers: Layer.mergeAll(Cloudflare.providers(), Boat.providers()), + state: Cloudflare.state(), + secrets: ({ stage }) => + stage === "prod" + ? Doppler.Secrets({ project: "my-app", config: "prd" }) + : Alchemy.Secrets.DotEnv(), + }, + Effect.gen(function* () { + const env = yield* MyEnv; + return { environment: env.name }; + }), +); +``` + +`Config.Redacted("AGENT_TOKEN")` doesn't change. See [Secret providers](/environments/secret-providers). + +To call a server running in a sandbox, see [Ports & URLs](/boat/sandboxes/ports). diff --git a/.agents/skills/alchemy/references/boat/setup.md b/.agents/skills/alchemy/references/boat/setup.md new file mode 100644 index 00000000..3a71e389 --- /dev/null +++ b/.agents/skills/alchemy/references/boat/setup.md @@ -0,0 +1,57 @@ + + +# Setup + +> Install @alchemy.run/boat, sign in to Boat with a profile, and deploy from CI. + +You need: + +- [Node.js](https://nodejs.org) 24.11.1+ or [Bun](https://bun.sh) +- A Boat account, from [boat.dev](https://boat.dev) + +## Add the provider + +Install `@alchemy.run/boat`: + + + +Then add `Boat.providers()` next to your cloud's providers: + +```typescript title="alchemy.run.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Alchemy from "alchemy"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +export default Alchemy.Stack( + "MyApp", + { + providers: Layer.mergeAll(Cloudflare.providers(), Boat.providers()), + state: Cloudflare.state(), + }, + Effect.gen(function* () { + return {}; + }), +); +``` + +## Sign in + + + +Pick **Browser sign-in** and enter your Boat account's email. Alchemy opens a Boat page: sign in there the way you signed up (GitHub, Google or an email code), and type the code your terminal shows. Alchemy stores the API key Boat issues, which lasts a year and renews itself before it expires. + +To paste a key from the dashboard's **API Keys** tab instead, pick **API key**. Give it the `admin` preset: deploying creates keys for your Workers and Functions. + +## Deploy from CI + +Set `BOAT_API_KEY`, and Alchemy uses it instead of your profile: + + + +See [Account & API keys](/boat/account-and-keys#deploy-from-ci-with-a-key). + +Next, build the [tutorial](/boat/tutorial/part-1). diff --git a/.agents/skills/alchemy/references/boat/tutorial/part-1.md b/.agents/skills/alchemy/references/boat/tutorial/part-1.md new file mode 100644 index 00000000..b6f35619 --- /dev/null +++ b/.agents/skills/alchemy/references/boat/tutorial/part-1.md @@ -0,0 +1,62 @@ + + +# Part 1: Build a Snapshot + +> Declare a Boat snapshot that clones a repository and installs tools at deploy time, so every sandbox starts ready. + +Build an API that gives agents sandboxes. The slow setup runs once, when you deploy: a snapshot with a repository cloned and its tools installed. While the app runs, every sandbox starts from that snapshot in under a second, already set up. + +The finished code is in [`examples/boat-agent-sandbox`](https://github.com/alchemy-run/alchemy/tree/main/examples/boat-agent-sandbox). + +## Prerequisites + +Finish [Boat setup](/boat/setup) and [Cloudflare setup](/cloudflare/setup). + +## Declare the snapshot + +A `Boat.Snapshot` lists the commands that set it up: + +```typescript title="src/Golden.ts" +import * as Boat from "@alchemy.run/boat"; + +export const Golden = Boat.Snapshot("Golden", { + run: ["git clone --depth 1 https://github.com/sindresorhus/is ~/repo"], +}); +``` + +At deploy, Alchemy starts a sandbox with none of your account's secrets, runs the commands in order, saves its disk as `Golden` and deletes the sandbox. + +## Add it to the Stack + +```typescript title="alchemy.run.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Alchemy from "alchemy"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { Golden } from "./src/Golden.ts"; + +export default Alchemy.Stack( + "BoatAgentSandboxExample", + { + providers: Layer.mergeAll(Cloudflare.providers(), Boat.providers()), + state: Alchemy.localState(), + }, + Effect.gen(function* () { + const golden = yield* Golden; + return { snapshot: golden.name }; + }), +); +``` + +## Deploy + + + +The deploy takes as long as the clone. The snapshot is in your Boat dashboard. A deploy that leaves the commands unchanged leaves it alone. + +## Next + +[Part 2](/boat/tutorial/part-2) starts sandboxes from it while the app runs. diff --git a/.agents/skills/alchemy/references/boat/tutorial/part-2.md b/.agents/skills/alchemy/references/boat/tutorial/part-2.md new file mode 100644 index 00000000..8966cf33 --- /dev/null +++ b/.agents/skills/alchemy/references/boat/tutorial/part-2.md @@ -0,0 +1,85 @@ + + +# Part 2: Start Sandboxes from It + +> A Cloudflare Worker that starts a fresh Boat sandbox from the Golden snapshot for each request. + +## Bind CreateSandbox to the snapshot + +```typescript title="src/Api.ts" +import * as Boat from "@alchemy.run/boat"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Effect from "effect/Effect"; +import { Golden } from "./Golden.ts"; + +export default class Api extends Cloudflare.Worker()( + "Api", + { main: import.meta.url }, + Effect.gen(function* () { + const sandboxes = yield* Boat.CreateSandbox(Golden); + return {}; + }).pipe(Effect.provide(Boat.CreateSandboxHttp)), +) {} +``` + +Every sandbox this client creates starts from `Golden`. At deploy, the Worker gets a Boat key of its own that creates sandboxes, works in them, and deletes only the ones it created. + +## Run a command in a fresh sandbox + +```diff lang="typescript" +// src/Api.ts + Effect.gen(function* () { + const sandboxes = yield* Boat.CreateSandbox(Golden); ++ ++ const run = Effect.fn("run")(function* (command: string) { ++ const sandbox = yield* Effect.acquireRelease( ++ sandboxes.create({ noEnv: true, autoStop: "5 minutes" }), ++ (sandbox) => Effect.ignore(sandbox.delete()), ++ ); ++ return yield* sandbox.exec(command, { cwd: "/home/user/repo", timeout: "1 minute" }); ++ }); +``` + +The repository is already there: the sandbox starts from the snapshot's disk, so nothing clones at request time. `acquireRelease` deletes the sandbox when the request's scope closes, whatever happens. + +## Serve it + +```diff lang="typescript" +// src/Api.ts +- return {}; ++ return { ++ fetch: Effect.gen(function* () { ++ const request = yield* HttpServerRequest; ++ const url = new URL(request.url, "http://api"); ++ if (request.method === "POST" && url.pathname === "/run") { ++ const result = yield* run(yield* request.text).pipe(Effect.scoped); ++ return yield* HttpServerResponse.json(result); ++ } ++ return HttpServerResponse.text("not found", { status: 404 }); ++ }).pipe(Effect.orDie), ++ }; +``` + +## Deploy it + +```diff lang="typescript" +// alchemy.run.ts + Effect.gen(function* () { + const golden = yield* Golden; +- return { snapshot: golden.name }; ++ const api = yield* Api; ++ return { snapshot: golden.name, url: api.url.as() }; + }), +``` + + + +`Golden` is unchanged, so this deploy only adds the Worker. Run a command in the repository: + + + +## Next + +[Part 3](/boat/tutorial/part-3) gives each user a sandbox of their own. diff --git a/.agents/skills/alchemy/references/boat/tutorial/part-3.md b/.agents/skills/alchemy/references/boat/tutorial/part-3.md new file mode 100644 index 00000000..457273bb --- /dev/null +++ b/.agents/skills/alchemy/references/boat/tutorial/part-3.md @@ -0,0 +1,56 @@ + + +# Part 3: A Copy per User + +> Give each user a Boat sandbox started from the Golden snapshot, which keeps their changes and resumes when they come back. + +## Start a user's sandbox from Golden + +```diff lang="typescript" +// src/Api.ts ++ const userSandbox = Effect.fn("userSandbox")(function* (user: string) { ++ const [existing] = yield* sandboxes.list({ labels: { user } }); ++ if (existing === undefined) { ++ return yield* sandboxes.create({ noEnv: true, autoStop: "10 minutes", labels: { user } }); ++ } ++ const sandbox = yield* sandboxes.connect(existing.id); ++ yield* sandbox.resume({ autoStop: "10 minutes" }); ++ return sandbox; ++ }); +``` + +A user's first request starts their sandbox from `Golden`, with the repository already cloned. The label finds it again on their next request. + +## Their changes stay in their copy + +```diff lang="typescript" +// src/Api.ts + if (request.method === "POST" && url.pathname === "/run") { + const result = yield* run(yield* request.text).pipe(Effect.scoped); + return yield* HttpServerResponse.json(result); + } ++ const match = /^\/users\/([a-z0-9-]+)\/files\/(.+)$/.exec(url.pathname); ++ if (match !== null) { ++ const sandbox = yield* userSandbox(match[1]!); ++ if (request.method === "PUT") yield* sandbox.files.write(`repo/${match[2]}`, yield* request.text); ++ return yield* HttpServerResponse.json({ content: yield* sandbox.files.readText(`repo/${match[2]}`) }); ++ } +``` + +Each user edits their own copy of the repository. `Golden` never changes, so the next sandbox started from it doesn't see their edits. + +## Resume where they left off + +The sandbox stops after ten idle minutes and Boat saves its disk. `resume` on their next request brings it back with their files, for up to 14 days. + + + +## Next + +[Part 4](/boat/tutorial/part-4) changes the snapshot. diff --git a/.agents/skills/alchemy/references/boat/tutorial/part-4.md b/.agents/skills/alchemy/references/boat/tutorial/part-4.md new file mode 100644 index 00000000..e44b2b65 --- /dev/null +++ b/.agents/skills/alchemy/references/boat/tutorial/part-4.md @@ -0,0 +1,35 @@ + + +# Part 4: Update the Snapshot + +> Change the Golden snapshot, redeploy, and see new sandboxes start from the new disk while existing ones keep theirs. + +## Add a command + +Install pnpm into the snapshot: + +```diff lang="typescript" +// src/Golden.ts +export const Golden = Boat.Snapshot("Golden", { +- run: ["git clone --depth 1 https://github.com/sindresorhus/is ~/repo"], ++ run: ["git clone --depth 1 https://github.com/sindresorhus/is ~/repo", "npm install -g pnpm"], +}); +``` + +## Deploy the new base + + + +The commands changed, so Alchemy runs them all again in a fresh sandbox and saves the result under the same name. The Worker is unchanged and isn't redeployed. + + + +## Running sandboxes keep their disk + +A sandbox has its own copy of the disk it started from. Users who already have a sandbox keep it, with their changes and without pnpm. Sandboxes started after the deploy get the new base. To move a user onto it, delete their sandbox; their next request starts a new one from `Golden`. + +## Next + +[Part 5](/boat/tutorial/part-5) tests it. diff --git a/.agents/skills/alchemy/references/boat/tutorial/part-5.md b/.agents/skills/alchemy/references/boat/tutorial/part-5.md new file mode 100644 index 00000000..eca10285 --- /dev/null +++ b/.agents/skills/alchemy/references/boat/tutorial/part-5.md @@ -0,0 +1,60 @@ + + +# Part 5: Testing + +> Deploy the Stack in a test, start sandboxes from the Golden snapshot, and check what they contain. + +## Deploy once per test file + +```typescript title="test/integ.test.ts" +import { expect } from "bun:test"; +import * as Boat from "@alchemy.run/boat"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Test from "@alchemy.run/test/Bun"; +import * as Alchemy from "alchemy"; +import * as Effect from "effect/Effect"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; +import * as Layer from "effect/Layer"; +import Stack from "../alchemy.run.ts"; + +const { test, beforeAll, afterAll, deploy, destroy } = Test.make({ + providers: Layer.mergeAll(Cloudflare.providers(), Boat.providers()), + state: Alchemy.localState(), +}); + +const stack = beforeAll(deploy(Stack)); +afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack)); +``` + +The test deploys the Stack to a stage of its own, snapshot included, and destroys it afterwards. + +## Check a sandbox starts from Golden + +```typescript title="test/integ.test.ts" +test( + "starts each sandbox from the Golden snapshot", + Effect.gen(function* () { + const { url } = yield* stack; + const res = yield* Test.executeWhenReady( + HttpClientRequest.post(`${url}/run`).pipe(HttpClientRequest.bodyText("pnpm --version")), + ); + const body = (yield* res.json) as { exitCode: number }; + expect(body.exitCode).toBe(0); + }), + { timeout: 180_000 }, +); +``` + +`pnpm` is only there if the sandbox started from `Golden`. The Worker deletes the sandbox when the request ends, so none is left behind. + +## Run it + + + +Set `NO_DESTROY=1` to keep the deployment, and the snapshot, between runs while you iterate. Each run starts sandboxes, which count against your plan's starts per minute and per hour. + +## Next + +[Part 6](/boat/tutorial/part-6) deploys more copies, from CI. diff --git a/.agents/skills/alchemy/references/boat/tutorial/part-6.md b/.agents/skills/alchemy/references/boat/tutorial/part-6.md new file mode 100644 index 00000000..12c6c93b --- /dev/null +++ b/.agents/skills/alchemy/references/boat/tutorial/part-6.md @@ -0,0 +1,88 @@ + + +# Part 6: Stages and CI + +> Deploy a stage per environment and per pull request, each with its own Boat snapshot and Worker. + +## Deploy another stage + + + +Each stage builds its own `Golden` snapshot and its own Worker, with its own Boat key, so changing the snapshot in one stage never reaches another. Without `--stage`, you deploy to `live_$USER`. + +Stages share your Boat account. Sandboxes a stage's Worker creates carry the stage as a label (`alchemy.stage`), so you can list one stage's sandboxes without touching another's: + +```typescript +const staging = yield* sandboxes.list({ labels: { "alchemy.stage": "staging" } }); +``` + +Destroying a stage deletes its snapshot and its Worker's key, and leaves its sandboxes to stop on their timers. + +## Keep state in Cloudflare + +CI runs start from an empty disk, so store state where every run can read it: + +```diff lang="typescript" +// alchemy.run.ts + { + providers: Layer.mergeAll(Cloudflare.providers(), Boat.providers()), +- state: Alchemy.localState(), ++ state: Cloudflare.state(), + }, +``` + +## Store the key + +Create a key in Boat's dashboard (**API Keys**) with the `admin` preset: deploying creates the Worker's own key. Add it to the repository's secrets as `BOAT_API_KEY`. Alchemy reads it instead of a profile. + +## Deploy per pull request + +```yaml +# .github/workflows/deploy.yml +name: Deploy +on: + pull_request: + push: + branches: [main] + +jobs: + deploy: + runs-on: ubuntu-latest + env: + BOAT_API_KEY: ${{ secrets.BOAT_API_KEY }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + STAGE: ${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.number) || 'prod' }} + steps: + - uses: actions/checkout@v4 + - uses: oven-sh/setup-bun@v2 + - run: bun install + - run: bun alchemy deploy --stage "$STAGE" --yes +``` + +Each pull request gets its own stage, and so its own base: a pull request that changes `Golden` rebuilds it for that stage only. Boat has no keyless CI login, so the workflow uses the API key. + +## Clean up closed pull requests + +```yaml +# .github/workflows/cleanup.yml +name: Cleanup +on: + pull_request: + types: [closed] + +jobs: + destroy: + runs-on: ubuntu-latest + env: + BOAT_API_KEY: ${{ secrets.BOAT_API_KEY }} + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + steps: + - uses: actions/checkout@v4 + - uses: oven-sh/setup-bun@v2 + - run: bun install + - run: bun alchemy destroy --stage "pr-${{ github.event.number }}" --yes +``` + +Destroying the stage deletes its snapshot and the Worker's key. diff --git a/.agents/skills/alchemy/references/boat/what-is-boat.md b/.agents/skills/alchemy/references/boat/what-is-boat.md new file mode 100644 index 00000000..629285c4 --- /dev/null +++ b/.agents/skills/alchemy/references/boat/what-is-boat.md @@ -0,0 +1,170 @@ + + +# What is Boat? + +> The concepts behind Boat — accounts and API keys, sandboxes and their lifecycle, snapshots and forks, environments, credential profiles and the AI credentials proxy, ports and webhooks — and how @alchemy.run/boat models each of them. + +Boat runs sandboxes: Linux machines for agents, untrusted code and dev boxes. A **sandbox** starts in under a second, with Ubuntu, Docker, Node.js, Bun and Python, and `sudo` that needs no password. It runs until its **auto-stop** timer, then Boat stops it and saves its disk, and it picks up where it left off when you resume it. Everything belongs to your **account**, or to an organization you bill to: its sandboxes, snapshots, environments, credential profiles, webhooks and API keys. + +Take one small app: a `MyProfile` credential profile holding an Anthropic key, a `MyEnv` environment that holds an npm token and names the profile, and a `Golden` snapshot of a sandbox with the project's dependencies installed. For each task, a Cloudflare Worker creates a sandbox from `Golden` on the `MyEnv` environment, runs the agent's commands there, and calls the dev server it starts on port 3000. + + + +## Accounts: where everything lives + +Your **account** owns what you create on Boat: its sandboxes, snapshots, environments, credential profiles, webhooks and API keys. An organization's members can bill sandboxes to it instead, and each sandbox stays private to the person who created it. Your profile signs you in to it: + + + +See [Account & API keys](/boat/account-and-keys). + +## API keys: only the actions a caller needs + +An **API key** carries a list of **actions** (create sandboxes, run commands, read files, host a port, …) and can be limited to some sandboxes or environments, and to a lifetime. A key can never do more, or live longer, than the key that created it. + +```typescript +export const Ci = Boat.ApiKey("Ci", { preset: "ci" }); +``` + +See [Account & API keys](/boat/account-and-keys#narrow-a-key-to-what-it-needs). + +## Sandboxes: machines that stop and resume + +A **sandbox** is one machine, in one of four sizes. You run commands in it, read and write its files, and call its ports. It runs for its `autoStop` (an hour unless you say otherwise), then Boat stops it and saves its disk for 14 days. A stopped sandbox resumes with its files. **Labels** tag a sandbox when it's created, so you can find it again. + +```typescript +const sandbox = yield* sandboxes.create({ type: "small", autoStop: "10 minutes", labels: { task } }); +const result = yield* sandbox.exec("npm test"); +``` + +See [Sandboxes](/boat/sandboxes/sandboxes). + +## Programs: your server in a sandbox + +A sandbox can run your own **program**: an Effect HTTP server that Alchemy bundles, uploads and starts with Node.js, served at the sandbox's URL. A code change restarts it in place, in the same sandbox. + +```typescript +export default class Api extends Boat.Sandbox()( + "Api", + { main: import.meta.url, type: "small" }, + Effect.gen(function* () { + return { fetch: HttpServerResponse.json({ ok: true }) }; + }), +) {} +``` + +See [Programs](/boat/sandboxes/programs). + +## Snapshots: a disk to start from + +A **snapshot** saves a sandbox's disk under a name. New sandboxes start from it, with a repository cloned and dependencies installed. A **fork** copies one sandbox from its last snapshot, which Boat takes whenever a sandbox stops. + +```typescript +export const Golden = Boat.Snapshot("Golden", { run: ["npm ci"] }); +``` + +See [Snapshots & forks](/boat/sandboxes/snapshots). + +## Environments: what a sandbox starts with + +An **environment** holds environment variables and secret files, and decides which of your credentials a sandbox gets: a GitHub token, a Boat key of its own, and the AI keys of a credential profile. A sandbox names one environment when it's created, and can add variables of its own on top. Every change makes a new version; a running sandbox keeps the version it started on. + +```typescript +export const MyEnv = Boat.Environment("MyEnv", { env: { NODE_ENV: "production" } }); +``` + +See [Environments & secrets](/boat/security/environments). + +## Credential profiles: the AI keys a sandbox gets + +A **credential profile** holds AI credentials, which Boat stores encrypted and never returns: API keys for Anthropic, OpenAI and other providers, secrets for any other HTTPS API, and the Claude or ChatGPT sign-ins you make on the dashboard. An environment names a profile, and its sandboxes start with the profile's keys as environment variables. + +```typescript +export const MyProfile = Boat.CredentialProfile("MyProfile", { + anthropic: Config.Redacted("ANTHROPIC_API_KEY"), +}); + +export const MyEnv = Boat.Environment("MyEnv", { credentialProfile: MyProfile }); +``` + +See [Credential profiles](/boat/security/credential-profiles). + +## AI credentials proxy: placeholders, not real keys + +A sandbox normally holds a profile's real keys, and anyone with a shell in it can copy them. The **AI credentials proxy** is one switch for a whole account or organization. With it on, a sandbox gets a placeholder for each key and sends its requests through the proxy, which swaps the real key in on the way to the provider. Boat bills the proxy for each day it's on and for each request. + +```typescript +export const Proxy = Boat.AiProxy("Proxy"); +``` + +See [Credential profiles](/boat/security/credential-profiles#keep-real-keys-out-of-the-sandbox). + +## Ports: a URL for each server + +A server that listens on a port inside a sandbox answers at `https://-.on.boat.dev`. Each port needs a token unless you make it public, and a port's `fetch` sends it for you: + +```typescript +const port = yield* sandbox.getTcpPort(3000); +const response = yield* port.fetch(HttpClientRequest.get("/health")); +``` + +See [Ports & URLs](/boat/sandboxes/ports). + +## Webhooks: Boat calls you when a sandbox changes + +Boat reports what happens to each sandbox (ready, stopped, failed, restored) to a **webhook**: a URL you register for the account, called with each event, signed with a secret. A Worker receives them with `consumeSandboxEvents`, which checks the signature and hands it only your stack's sandboxes. + +```typescript +yield* Boat.consumeSandboxEvents({ events: ["sandbox.archived"] }, (event) => + Effect.log(`${event.data.sandbox.id} stopped`), +); +``` + +See [Lifecycle events](/boat/sandboxes/lifecycle-events). + +## State: where Alchemy keeps its record + +Boat has no storage for Alchemy's own record of what each Stack created. Keep it on disk, or share it with your team and CI through another cloud's state store: + +```typescript title="alchemy.run.ts" +export default Alchemy.Stack( + "MyApp", + { providers: Layer.mergeAll(Cloudflare.providers(), Boat.providers()), state: Cloudflare.state() }, + Effect.gen(function* () { + return {}; + }), +); +``` + +## How @alchemy.run/boat models these concepts + +Your profile signs you in, and `Boat.providers()` deploys into your account. What an app shares for its whole life (an environment, a credential profile, a snapshot, a long-lived dev box, a webhook, a key for CI) are resources in the Stack. An environment you declare passes its own variables and secret files, and none of your account's credentials until a prop asks for them. Sandboxes made per user or task come from bindings your Worker or Function uses while it runs (`CreateSandbox`, `ConnectSandbox`). They aren't deleted when the Stack is destroyed, but they carry their stack, stage and host as labels (`alchemy.stack`, `alchemy.stage`, `alchemy.id`), so you can find them again. Each binding gets an API key of its own, created at deploy with only the actions it needs, never yours. + +Next, build one: the [tutorial](/boat/tutorial/part-1) puts these ideas to work, one step at a time. diff --git a/.agents/skills/alchemy/references/cli/INDEX.md b/.agents/skills/alchemy/references/cli/INDEX.md index 324ef758..6212c876 100644 --- a/.agents/skills/alchemy/references/cli/INDEX.md +++ b/.agents/skills/alchemy/references/cli/INDEX.md @@ -1,13 +1,14 @@ # cli index -14 pages. Every alchemy command at a glance — the command map, common options, and how the interactive TUI decides when to render. +15 pages. Every alchemy command at a glance — the command map, common options, and how the interactive TUI decides when to render. | Page | File | Covers | | --- | --- | --- | | CLI | `_overview.md` | Every alchemy command at a glance — the command map, common options, and how the interactive TUI decides when to render. | | Adopting Resources | `adopting-resources.md` | How alchemy takes ownership of pre-existing cloud resources — recovery by default, --adopt for foreign resources, and the programmatic AdoptPolicy. | +| Programmatic API | `api.md` | Run deploy, plan, destroy, drift, nuke, logs, and state from your own scripts with alchemy/Alchemist. | | aws | `aws.md` | AWS provider commands — bootstrap the per-account assets bucket that Lambda deployments rely on. | -| cloudflare | `cloudflare.md` | Cloudflare provider commands — bootstrap the state-store worker, mint API tokens, and inspect state-store logs. | +| cloudflare | `cloudflare.md` | Cloudflare provider commands — mint API tokens. | | deploy | `deploy.md` | Compute a plan, ask for approval, and create/update/delete resources to match the desired state. | | destroy | `destroy.md` | Delete every resource in a stack — plan all existing resources for deletion, ask for approval, and remove them in dependency order. | | dev | `dev.md` | Run your stack in development mode with hot reloading — resources deploy to the cloud while Workers run in the local dev runtime. | diff --git a/.agents/skills/alchemy/references/cli/_overview.md b/.agents/skills/alchemy/references/cli/_overview.md index 95662ae9..b4862373 100644 --- a/.agents/skills/alchemy/references/cli/_overview.md +++ b/.agents/skills/alchemy/references/cli/_overview.md @@ -1,14 +1,12 @@ + alchemy 2.0.0-beta.87 @ d1f364a --> # CLI > Every alchemy command at a glance — the command map, common options, and how the interactive TUI decides when to render. -```sh -bun alchemy [options] -``` + Every command operates on an `alchemy.run.ts` stack file (or a custom entrypoint passed with `--config `, which must exist) and targets a [stage](/environments/stages). @@ -29,14 +27,16 @@ alchemy │ # manage credentials and accounts (bare `profile` opens the dashboard) │ ├─ state list|read|delete # inspect and manage the state store (bare `state` opens the explorer) +├─ state bootstrap|teardown|logs # provision, delete, or debug a provider's state store (--backend) │ └─ provider ├─ check-env # CI preflight: verify required provider env vars are set - ├─ aws bootstrap|teardown - └─ cloudflare bootstrap|teardown|token|state logs + ├─ aws bootstrap|teardown # the deploy assets bucket + ├─ cloudflare token + └─ prisma generate ``` -Each command has its own page: [deploy](/cli/deploy), [plan](/cli/plan), [destroy](/cli/destroy), [drift](/cli/drift), [unsafe nuke](/cli/nuke), [dev](/cli/dev), [logs](/cli/logs), [profile](/cli/profile), [state](/cli/state), [AWS provider commands](/cli/aws), and [Cloudflare provider commands](/cli/cloudflare). The workflow guides cover [adopting resources](/cli/adopting-resources) and [inspecting state](/cli/inspecting-state). +Each command has its own page: [deploy](/cli/deploy), [plan](/cli/plan), [destroy](/cli/destroy), [drift](/cli/drift), [unsafe nuke](/cli/nuke), [dev](/cli/dev), [logs](/cli/logs), [profile](/cli/profile), [state](/cli/state), [AWS provider commands](/cli/aws), and [Cloudflare provider commands](/cli/cloudflare). The workflow guides cover [adopting resources](/cli/adopting-resources) and [inspecting state](/cli/inspecting-state). To run the same operations from a script, see the [Programmatic API](/cli/api). ## Common options @@ -48,6 +48,7 @@ Each command has its own page: [deploy](/cli/deploy), [plan](/cli/plan), [destro | `--yes` | Yes to all prompts. | | `--no-input` | Disable prompts and the interactive TUI. Commands that would need input fail instead of hanging. | | `--config, -c ` | Stack entrypoint. Defaults to `alchemy.run.ts`; must exist. | +| `--fast-distilled` | Under Node, load each distilled SDK operation on first use. This lowers the CLI's memory and startup time for stacks that import whole providers. Same as `ALCHEMY_FAST_DISTILLED=1`. | Use `--profile` with `deploy`, `plan`, `destroy`, `dev`, `logs`, `drift`, or `state`. @@ -68,6 +69,43 @@ Interactive terminals use the animated TUI; redirected and non-interactive runs Plain mode never prompts — it prints the plan, makes no changes, and fails with `error: Cannot approve this operation without terminal input. Pass --yes to continue.` In CI, always pass `--yes`. +## Log output + +Every log line is a record. Output from child processes (dev servers, workerd, the local provider sidecar) is captured as records too, so it can be shown either way: + +| Option | Description | +| --- | --- | +| `--log-format pretty\|json` | `pretty` (default) prints lines; `json` prints one record per line on stderr, with child output as written. Also `$ALCHEMY_LOG_FORMAT`. | +| `--log-level ` | Lowest level printed. Defaults to `info`. Also `$ALCHEMY_LOG_LEVEL`. | + +Every record has the same keys: + +| Key | Value | +| --- | --- | +| `time` | Unix time in milliseconds | +| `level` | `trace`, `debug`, `info`, `warn`, `error` or `fatal` | +| `kind` | `log`, `event`, `output` or `run` (see below) | +| `process` | The alchemy process that produced it: `cli`, `exec` (the `alchemy dev` worker) or `sidecar` | +| `scope` | `project` or `global` | +| `trace` | `{ traceId, spanId }` of the span it was logged in, or of the process outside any span. Child processes and sidecar calls join their caller's trace. | +| `attributes` | Annotations on the record, including `fqn` when it is about a resource | +| `data` | Depends on `kind` | + +| `kind` | `data` | +| --- | --- | +| `log` | `{ message, cause }`: a line alchemy logged | +| `event` | A typed event, as `Alchemist.onEvent` receives it | +| `output` | `{ stream, text }`: a line a child process wrote, exactly as written, ANSI styling included | +| `run` | `{ version, pid, cwd, argv }`: the first line of a run log | + +```json +{"time":1793186948542,"level":"info","kind":"output","process":"sidecar","scope":"project","trace":{"traceId":"4bf92f3577b34da6a3ce929d0e0e4736","spanId":"00f067aa0ba902b7"},"attributes":{"fqn":"Web"},"data":{"stream":"stdout","text":"\u001b[32mready\u001b[39m on http://localhost:4321"}} +``` + +Each run also writes its records at debug level to a run log, one record per line. Project work goes to the project's `.alchemy/log/