From 1e2c828ef5dddbe9541309fd42543bff0bed7bb1 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 1 Sep 2026 16:53:15 +0100 Subject: [PATCH 01/12] chore: add renovate dep management for cli --- .github/workflows/renovate.yml | 42 ++++++++++++++ RENOVATE.md | 100 +++++++++++++++++++++++++++++++++ renovate.json | 19 +++++++ 3 files changed, 161 insertions(+) create mode 100644 .github/workflows/renovate.yml create mode 100644 RENOVATE.md create mode 100644 renovate.json diff --git a/.github/workflows/renovate.yml b/.github/workflows/renovate.yml new file mode 100644 index 00000000..7f70022a --- /dev/null +++ b/.github/workflows/renovate.yml @@ -0,0 +1,42 @@ +name: Renovate + +# Self-hosted Renovate runner. +# Focused rollout: Renovate owns version updates for the CLI's Go modules (the +# Bluelink dependency chain) via `includePaths` in renovate.json. Dependabot still +# handles the Rust/Node/Python runtime ecosystems (version updates) and security +# updates repo-wide. See RENOVATE.md. +on: + schedule: + # Hourly so the internal-cascade rule (which bypasses the weekly schedule) + # can react promptly to upstream Bluelink lib releases. + - cron: "0 * * * *" + workflow_dispatch: + inputs: + logLevel: + description: "Renovate log level" + required: false + default: "info" + dryRun: + description: "Dry run (full|null)" + required: false + default: "null" + +concurrency: + group: renovate + cancel-in-progress: false + +jobs: + renovate: + runs-on: ubuntu-latest + steps: + - name: Run Renovate + uses: renovatebot/github-action@v41.0.0 + with: + token: ${{ secrets.RENOVATE_TOKEN }} + env: + RENOVATE_PLATFORM: github + RENOVATE_REPOSITORIES: ${{ github.repository }} + RENOVATE_ONBOARDING: "false" + RENOVATE_REQUIRE_CONFIG: "required" + RENOVATE_DRY_RUN: ${{ inputs.dryRun || 'null' }} + LOG_LEVEL: ${{ inputs.logLevel || 'info' }} diff --git a/RENOVATE.md b/RENOVATE.md new file mode 100644 index 00000000..c9298c8c --- /dev/null +++ b/RENOVATE.md @@ -0,0 +1,100 @@ +# Dependency automation: Renovate (CLI / Bluelink chain) + Dependabot + +Celerity is a mixed monorepo consisting of a Go CLI (`apps/cli`), local dev helper tools (e.g. `apps/local-events`), the Rust runtime libs +(`libs/runtime`), and the Node.js / Python runtime SDKs and wrappers. This is a +**focused Renovate rollout**: Renovate owns version updates for the **CLI's Go +modules only** which is a part of the Bluelink dependency chain, while Dependabot keeps managing +the Rust/Node/Python ecosystems (and security updates repo-wide) as before. + +`apps/cli` is a **Bluelink consumer**. Its `go.mod` pulls in the core Bluelink +libs and a sibling module that rides the same release cascade: + +- `github.com/newstack-cloud/bluelink/libs/blueprint` +- `github.com/newstack-cloud/bluelink/libs/blueprint-state` +- `github.com/newstack-cloud/bluelink/libs/common` +- `github.com/newstack-cloud/bluelink/libs/deploy-engine-client` +- `github.com/newstack-cloud/deploy-cli-sdk` + +So Celerity joins `bluelink`, `celerity-provider-aws`, and `deploy-cli-sdk` as a +repo in the Bluelink graph, and its config is layered exactly like theirs: + +``` +newstack-cloud/renovate-config//default ← org-wide policy; ALL repos + ▲ + │ extends +newstack-cloud/bluelink//renovate/bluelink-consumers ← Bluelink cascade only + ▲ + │ extends +celerity (scoped to apps/cli via includePaths) +``` + +- **Org layer** ([`newstack-cloud/renovate-config`](https://github.com/newstack-cloud/renovate-config)) + — universal, product-agnostic policy: schedule, the `deps` / `ci(deps)` commit + convention, tiered auto-merge (minor/patch/digest auto-merge, majors held), and + the Dependabot-security-only stance. +- **Bluelink layer** ([`bluelink//renovate/bluelink-consumers`](https://github.com/newstack-cloud/bluelink/blob/main/renovate/bluelink-consumers.json)) + - the cascade rule: auto-merge internal `github.com/newstack-cloud/*` bumps and + let them bypass the weekly schedule so the chain reacts promptly. +- **Repo layer** ([`renovate.json`](renovate.json)) - `includePaths: ["apps/cli/**"]` + keeps Renovate out of the Rust/Node/Python trees, plus a `deps(cli)` commit + scope and a group so a component's simultaneous bumps land in one PR (no go.sum + conflicts). + +## Why scoped to the CLI + +The org preset extends `config:recommended`, which would otherwise enable +Renovate across every ecosystem in the repo (cargo, npm, pip) and produce PRs that +compete with Dependabot's existing version updates for those trees. `includePaths` +narrows Renovate to `apps/cli/**` so this rollout is limited to the Bluelink chain. +The matching `gomod` block was removed from +[`.github/dependabot.yml`](.github/dependabot.yml) so only one tool bumps the CLI. + +Broadening later (Renovate owns the whole repo, Dependabot → security-only, per +the org policy) is a matter of dropping `includePaths` and retiring the remaining +Dependabot version-update blocks. + +## How the cascade works + +- **Bump commits keep the `deps(cli): …` prefix** that release-please expects, so + release behaviour is unchanged and only the tool that opens the PR differs. +- **Auto-merge tiers** (all CI-gated by `platformAutomerge`): + - internal `github.com/newstack-cloud/*` bumps → auto-merge, bypassing the + weekly schedule so the cascade reacts promptly; + - third-party minor/patch/digest → auto-merge + - majors → held for manual review (`major-update` label). +- **The human gate is the release PR.** Renovate lands the `deps(cli)` bump on + `main`; release-please then opens the "release cli" PR for a person to review + and merge. + +``` +bluelink lib (e.g. libs/blueprint) release published + → deps(cli): bump blueprint (+ blueprint-state, common, deploy-engine-client) [auto-merged] + → release-please "release cli" PR [human merges] → cli published +deploy-cli-sdk release published + → deps(cli): bump deploy-cli-sdk [auto-merged] → release PR → ... +``` + +## One-time setup + +1. **`RENOVATE_TOKEN` secret** in this repo, a **GitHub App installation token or + PAT**, *not* `GITHUB_TOKEN`. PRs opened by `GITHUB_TOKEN` don't trigger other + workflows, so CI wouldn't run on Renovate PRs and auto-merge could never + complete. The token needs **read access to `newstack-cloud/renovate-config`** + (org preset) and **`newstack-cloud/bluelink`** (cascade preset). Reuse the + org-level GitHub App already installed on the other Bluelink-graph repos. +2. The [`renovate.yml`](.github/workflows/renovate.yml) workflow runs hourly and on + demand. Trigger a **dry run** first via *Actions → Renovate → Run workflow* with + `dryRun: full` and confirm it only proposes `apps/cli` Go bumps. + +## Validate before changes + +```bash +npx --yes --package renovate renovate-config-validator renovate.json +``` + +## Follow-up + +Two docs in the `bluelink` repo still list the cascade consumers as +`bluelink · celerity-provider-aws · deploy-cli-sdk` (its `RENOVATE.md` diagram and +the `renovate/bluelink-consumers.json` description). Add `celerity` there so the +consumer list stays accurate. diff --git a/renovate.json b/renovate.json new file mode 100644 index 00000000..b2d0eff8 --- /dev/null +++ b/renovate.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": [ + "github>newstack-cloud/renovate-config", + "github>newstack-cloud/bluelink//renovate/bluelink-consumers" + ], + "includePaths": [ + "apps/cli/**" + ], + "packageRules": [ + { + "description": "Focused rollout: Renovate owns only the CLI's Go modules (the Bluelink dependency chain — libs/blueprint, blueprint-state, common, deploy-engine-client, and the sibling deploy-cli-sdk). The Rust/Node/Python runtime ecosystems stay on Dependabot for now, so `includePaths` keeps Renovate out of them. The bluelink-consumers preset supplies the cascade rule that auto-merges internal github.com/newstack-cloud/* bumps and bypasses the weekly schedule.", + "matchFileNames": ["apps/cli/**"], + "matchManagers": ["gomod"], + "semanticCommitScope": "cli", + "groupName": "cli go modules" + } + ] +} From 8289a65a85a5339c19ae31d8054789f4c6f1ec18 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 21 Sep 2026 13:17:58 +0100 Subject: [PATCH 02/12] feat(runtime-core): enable consumer features in the core lib --- apps/runtime/core/Cargo.toml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/apps/runtime/core/Cargo.toml b/apps/runtime/core/Cargo.toml index 5167fda0..a899d86a 100644 --- a/apps/runtime/core/Cargo.toml +++ b/apps/runtime/core/Cargo.toml @@ -23,10 +23,7 @@ tracing = "=0.1.44" [dependencies.celerity_runtime_core] path = "../../../libs/runtime/core" -# Shipped with the image so a deployment turns clustering on with environment -# variables rather than a rebuild. With no Redis deployment configured it stays -# a single node. -features = ["ws_clustering"] +features = ["ws_clustering", "celerity_local_consumers", "aws_consumers", "azure_consumers", "gcloud_consumers"] [dependencies.celerity_helpers] path = "../../../libs/runtime/helpers" From 5fff02883d598480d75fda40a67dce1caec22001 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 14 Oct 2026 16:17:23 +0100 Subject: [PATCH 03/12] fix(runtime-core): update lockfile for the consumer features Enabling the consumer features in the core lib changed Cargo.toml without regenerating the lockfile, so cargo metadata --locked and every build passing --locked failed against it. The runtime image is built with --locked, which made this a release blocker rather than a local inconvenience. --- apps/runtime/core/Cargo.lock | 865 ++++++++++++++++++++++++++++++++++- 1 file changed, 853 insertions(+), 12 deletions(-) diff --git a/apps/runtime/core/Cargo.lock b/apps/runtime/core/Cargo.lock index 2ba67ed3..e084fb2b 100644 --- a/apps/runtime/core/Cargo.lock +++ b/apps/runtime/core/Cargo.lock @@ -44,6 +44,15 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "arc-swap" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +dependencies = [ + "rustversion", +] + [[package]] name = "arraydeque" version = "0.5.1" @@ -95,6 +104,485 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "aws-config" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8d7b388a9fc3a6db15a5ec778c38b354eff1364882c94d08e0252f7a47dcaa4" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-sdk-sso", + "aws-sdk-ssooidc", + "aws-sdk-sts", + "aws-smithy-async", + "aws-smithy-http 0.64.0", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "hex", + "http 1.5.0", + "sha1", + "time", + "tokio", + "tracing", + "url", + "zeroize", +] + +[[package]] +name = "aws-credential-types" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e93964ffdaf57857f544be3666a5f57570bb699e934700f11b49708f61bb556e" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-types", + "zeroize", +] + +[[package]] +name = "aws-lc-rs" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "aws-runtime" +version = "1.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25b43ad47adc2517efe3d706559d94b97e50e80e0321b3cadbc9f77cee88adcd" +dependencies = [ + "aws-credential-types", + "aws-sigv4", + "aws-smithy-async", + "aws-smithy-http 0.64.0", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "bytes-utils", + "fastrand", + "http 1.5.0", + "http-body 1.1.0", + "percent-encoding", + "pin-project-lite", + "tracing", + "uuid", +] + +[[package]] +name = "aws-sdk-account" +version = "1.117.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8c49729e6986c6454aa58ab800dba6f888ef6374381081584c0c2d471c0f0d6" +dependencies = [ + "arc-swap", + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http 0.64.0", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http 0.2.12", + "http 1.5.0", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-sqs" +version = "1.111.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2f03f27e4c84c425cb0aad20f91a55e4a6ef3398e4b380331329a1240ec6595" +dependencies = [ + "arc-swap", + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http 0.64.0", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http 0.2.12", + "http 1.5.0", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-sso" +version = "1.111.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65700d75f6da78c89a61a49f1539979400a4609d3329376b1dc2133d7a1b2b90" +dependencies = [ + "arc-swap", + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http 0.64.0", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http 0.2.12", + "http 1.5.0", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-ssooidc" +version = "1.113.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb1147c254af7b6cee3ace90ae7da6f21366ce9a9b899035fa8a0fdf586eb75a" +dependencies = [ + "arc-swap", + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http 0.64.0", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http 0.2.12", + "http 1.5.0", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-sts" +version = "1.116.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "035c7392e751d20bf1060d625d023587eb14099646110a9cff7c697bfe4b253a" +dependencies = [ + "arc-swap", + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http 0.64.0", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-query", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-smithy-xml", + "aws-types", + "fastrand", + "http 0.2.12", + "http 1.5.0", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sigv4" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31d955e76ff96acd555bf06fa0fa6d5bf9335fa84ae7c64481b20ae61d231f70" +dependencies = [ + "aws-credential-types", + "aws-smithy-http 0.64.0", + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "form_urlencoded", + "hex", + "hmac", + "http 0.2.12", + "http 1.5.0", + "percent-encoding", + "sha2", + "time", + "tracing", +] + +[[package]] +name = "aws-smithy-async" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f02e407fb3b54891734224b9ffac8a71fdd35f542500fa1af95754a6b2beb316" +dependencies = [ + "futures-util", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "aws-smithy-http" +version = "0.62.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "826141069295752372f8203c17f28e30c464d22899a43a0c9fd9c458d469c88b" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "bytes-utils", + "futures-core", + "futures-util", + "http 0.2.12", + "http 1.5.0", + "http-body 0.4.6", + "percent-encoding", + "pin-project-lite", + "pin-utils", + "tracing", +] + +[[package]] +name = "aws-smithy-http" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37843d9add67c3aff5856f409c6dc315d3cdff60f9c0cb5b670dab1e9920306d" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "bytes-utils", + "futures-core", + "futures-util", + "http 1.5.0", + "http-body 1.1.0", + "http-body-util", + "percent-encoding", + "pin-project-lite", + "pin-utils", + "tracing", +] + +[[package]] +name = "aws-smithy-http-client" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bd25384a4e437aa8d8f339afad4b69e786b936a7cb10db668a7aaf66717b1a8" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-types", + "h2 0.3.27", + "h2 0.4.16", + "http 0.2.12", + "http 1.5.0", + "http-body 0.4.6", + "hyper 0.14.32", + "hyper 1.11.0", + "hyper-rustls 0.24.2", + "hyper-rustls 0.27.9", + "hyper-util", + "pin-project-lite", + "rustls 0.21.12", + "rustls 0.23.43", + "rustls-native-certs", + "rustls-pki-types", + "tokio", + "tokio-rustls 0.26.4", + "tower 0.5.3", + "tracing", +] + +[[package]] +name = "aws-smithy-json" +version = "0.63.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3385d469edbe8b60cc72002784652b5efca39178192aa9cc4b44c9875c6bdc18" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", +] + +[[package]] +name = "aws-smithy-observability" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e86338c869539a581bf161247762a6e87f92c5c075060057b5ed6d06632ed0c" +dependencies = [ + "aws-smithy-runtime-api", +] + +[[package]] +name = "aws-smithy-query" +version = "0.62.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1d1d71f6562be974caa85442ecd90194c40fdb5df045f182a6c2e872ce95056" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-smithy-xml", + "urlencoding", +] + +[[package]] +name = "aws-smithy-runtime" +version = "1.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3296253d3a91b3f938a3f2bcce4daebadcb4aa4228153fcec90f9d23532b4484" +dependencies = [ + "aws-smithy-async", + "aws-smithy-http 0.64.0", + "aws-smithy-http-client", + "aws-smithy-observability", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "bytes", + "fastrand", + "http 0.2.12", + "http 1.5.0", + "http-body 0.4.6", + "http-body 1.1.0", + "http-body-util", + "pin-project-lite", + "pin-utils", + "tokio", + "tracing", +] + +[[package]] +name = "aws-smithy-runtime-api" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d881a7b7ad179fd6611680c9de89f716fb00ab40299a9a7b8c6913e8f7511a8" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api-macros", + "aws-smithy-types", + "bytes", + "http 0.2.12", + "http 1.5.0", + "pin-project-lite", + "tokio", + "tracing", + "zeroize", +] + +[[package]] +name = "aws-smithy-runtime-api-macros" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "221eaa237ddf1ca79b60d1372aad77e47f9c0ea5b3ce5099da8c61d027dc77b3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "aws-smithy-schema" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8f395d93304280b64b7632fea798d177e74897fe7f063416ce627cd6fa24829" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-types", + "http 1.5.0", +] + +[[package]] +name = "aws-smithy-types" +version = "1.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b791f3ac597193fe1d08b82366986eb1f5bc31f2ac6c194c0855276116c76cd" +dependencies = [ + "base64-simd", + "bytes", + "bytes-utils", + "futures-core", + "http 0.2.12", + "http 1.5.0", + "http-body 0.4.6", + "http-body 1.1.0", + "http-body-util", + "itoa", + "num-integer", + "pin-project-lite", + "pin-utils", + "ryu", + "serde", + "time", + "tokio", + "tokio-util", +] + +[[package]] +name = "aws-smithy-xml" +version = "0.62.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b932c8d6dc127fc980eecd78f8694ae9b9551b69a93a7def2a199c1c0033daf" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "xmlparser", +] + +[[package]] +name = "aws-types" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "209f3a6d82a6e9e5f94abbed94c7a26e1c052341002bf57a5fb5481f625896fc" +dependencies = [ + "aws-credential-types", + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "rustc_version", + "tracing", +] + [[package]] name = "axum" version = "0.6.20" @@ -254,6 +742,16 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "339abbe78e73178762e23bea9dfd08e697eb3f3301cd4be981c0f78ba5859195" +dependencies = [ + "outref", + "vsimd", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -275,6 +773,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -290,6 +797,16 @@ dependencies = [ "serde", ] +[[package]] +name = "bytes-utils" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dafe3a8757b027e2be6e4e5601ed563c55989fcf1546e933c66c8eb3a058d35" +dependencies = [ + "bytes", + "either", +] + [[package]] name = "cc" version = "1.4.3" @@ -297,6 +814,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -312,6 +831,17 @@ dependencies = [ "tracing", ] +[[package]] +name = "celerity_aws_helpers" +version = "0.1.0" +dependencies = [ + "aws-config", + "aws-sdk-account", + "aws-sdk-sqs", + "aws-types", + "http 1.5.0", +] + [[package]] name = "celerity_blueprint_config_parser" version = "0.1.0" @@ -335,6 +865,68 @@ dependencies = [ "tracing", ] +[[package]] +name = "celerity_consumer_azure_events_hub" +version = "0.1.0" + +[[package]] +name = "celerity_consumer_azure_service_bus" +version = "0.1.0" + +[[package]] +name = "celerity_consumer_gcloud_pubsub" +version = "0.1.0" + +[[package]] +name = "celerity_consumer_gcloud_tasks" +version = "0.1.0" + +[[package]] +name = "celerity_consumer_kinesis" +version = "0.1.0" + +[[package]] +name = "celerity_consumer_redis" +version = "0.1.0" +dependencies = [ + "async-trait", + "base64 0.22.1", + "celerity_helpers", + "futures", + "md5", + "opentelemetry", + "redis", + "serde", + "serde_json", + "tokio", + "tracing", + "tracing-opentelemetry", +] + +[[package]] +name = "celerity_consumer_sqs" +version = "0.1.0" +dependencies = [ + "async-trait", + "aws-config", + "aws-sdk-sqs", + "aws-smithy-http 0.62.6", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "celerity_aws_helpers", + "celerity_helpers", + "futures", + "http 1.5.0", + "opentelemetry", + "serde", + "serde_json", + "tokio", + "tracing", + "tracing-opentelemetry", + "tracing-subscriber", +] + [[package]] name = "celerity_helpers" version = "0.1.0" @@ -360,12 +952,21 @@ name = "celerity_runtime_core" version = "0.1.0" dependencies = [ "async-trait", + "aws-config", + "aws-sdk-sqs", "axum 0.8.9", "axum-client-ip", "axum-extra", "base64 0.22.1", "bytes", "celerity_blueprint_config_parser", + "celerity_consumer_azure_events_hub", + "celerity_consumer_azure_service_bus", + "celerity_consumer_gcloud_pubsub", + "celerity_consumer_gcloud_tasks", + "celerity_consumer_kinesis", + "celerity_consumer_redis", + "celerity_consumer_sqs", "celerity_helpers", "celerity_ws_redis", "celerity_ws_registry", @@ -474,6 +1075,21 @@ dependencies = [ "http 1.5.0", ] +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "combine" version = "4.6.7" @@ -488,6 +1104,12 @@ dependencies = [ "tokio-util", ] +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "cookie" version = "0.18.2" @@ -564,6 +1186,24 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +dependencies = [ + "cmov", +] + [[package]] name = "data-encoding" version = "2.11.1" @@ -588,8 +1228,20 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -603,6 +1255,12 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "either" version = "1.17.0" @@ -634,6 +1292,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.11" @@ -655,6 +1319,12 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "futures" version = "0.3.34" @@ -892,6 +1562,21 @@ dependencies = [ "http 1.5.0", ] +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "0.2.12" @@ -959,6 +1644,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "0.14.32" @@ -1005,6 +1699,21 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-rustls" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590" +dependencies = [ + "futures-util", + "http 0.2.12", + "hyper 0.14.32", + "log", + "rustls 0.21.12", + "tokio", + "tokio-rustls 0.24.1", +] + [[package]] name = "hyper-rustls" version = "0.27.9" @@ -1014,10 +1723,10 @@ dependencies = [ "http 1.5.0", "hyper 1.11.0", "hyper-util", - "rustls", + "rustls 0.23.43", "rustls-native-certs", "tokio", - "tokio-rustls", + "tokio-rustls 0.26.4", "tower-service", ] @@ -1247,6 +1956,16 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.104" @@ -1355,6 +2074,12 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" +[[package]] +name = "md5" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebb8d8732c6a6df3d8f032a82911cfc747e00efb95cc46e8d0acd5b5b88570c" + [[package]] name = "memchr" version = "2.8.3" @@ -1536,6 +2261,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "outref" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + [[package]] name = "parking_lot" version = "0.12.5" @@ -1643,6 +2374,18 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "potential_utf" version = "0.1.6" @@ -1744,7 +2487,7 @@ dependencies = [ "quinn-proto", "quinn-udp", "rustc-hash", - "rustls", + "rustls 0.23.43", "socket2 0.6.5", "thiserror 2.0.20", "tokio", @@ -1765,7 +2508,7 @@ dependencies = [ "rand_pcg", "ring", "rustc-hash", - "rustls", + "rustls 0.23.43", "rustls-pki-types", "slab", "thiserror 2.0.20", @@ -1952,6 +2695,12 @@ dependencies = [ "regex-syntax", ] +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + [[package]] name = "regex-syntax" version = "0.8.11" @@ -1971,14 +2720,14 @@ dependencies = [ "http-body 1.1.0", "http-body-util", "hyper 1.11.0", - "hyper-rustls", + "hyper-rustls 0.27.9", "hyper-util", "js-sys", "log", "percent-encoding", "pin-project-lite", "quinn", - "rustls", + "rustls 0.23.43", "rustls-native-certs", "rustls-pki-types", "serde", @@ -1986,7 +2735,7 @@ dependencies = [ "serde_urlencoded", "sync_wrapper 1.0.2", "tokio", - "tokio-rustls", + "tokio-rustls 0.26.4", "tower 0.5.3", "tower-http", "tower-service", @@ -2016,16 +2765,38 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustls" +version = "0.21.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" +dependencies = [ + "log", + "ring", + "rustls-webpki 0.101.7", + "sct", +] + [[package]] name = "rustls" version = "0.23.43" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" dependencies = [ + "aws-lc-rs", "once_cell", "ring", "rustls-pki-types", - "rustls-webpki", + "rustls-webpki 0.103.14", "subtle", "zeroize", ] @@ -2052,12 +2823,23 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-webpki" +version = "0.101.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" +dependencies = [ + "ring", + "untrusted", +] + [[package]] name = "rustls-webpki" version = "0.103.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0527518605e68109d875e248ea259b6758801cf165e4b2c2733ae3b51f12535a" dependencies = [ + "aws-lc-rs", "ring", "rustls-pki-types", "untrusted", @@ -2090,6 +2872,16 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sct" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" +dependencies = [ + "ring", + "untrusted", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -2113,6 +2905,12 @@ dependencies = [ "libc", ] +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -2187,7 +2985,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", ] [[package]] @@ -2196,6 +2994,17 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -2467,13 +3276,23 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "tokio-rustls" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" +dependencies = [ + "rustls 0.21.12", + "tokio", +] + [[package]] name = "tokio-rustls" version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" dependencies = [ - "rustls", + "rustls 0.23.43", "tokio", ] @@ -2815,6 +3634,16 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "uuid" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "valuable" version = "0.1.1" @@ -2827,6 +3656,12 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + [[package]] name = "want" version = "0.3.1" @@ -3079,6 +3914,12 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "xmlparser" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" + [[package]] name = "yaml-rust2" version = "0.8.1" From e94fb9fa27cf71e1c0fdbe37f72aac679d8fae89 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 14 Oct 2026 16:17:40 +0100 Subject: [PATCH 04/12] feat(lib-rt-helpers): add base64 for the binary frame vectors The binary frame conformance vectors are stored base64 encoded in a JSON fixture, so the test that replays them needs a decoder. Without the dependency declared the helpers test target did not compile at all. --- libs/runtime/Cargo.lock | 3 +- libs/runtime/helpers/Cargo.toml | 1 + .../helpers/tests/binary_frame_vectors.rs | 126 ++++++++++++++++++ .../tests/fixtures/binary-frame-vectors.json | 113 ++++++++++++++++ 4 files changed, 242 insertions(+), 1 deletion(-) create mode 100644 libs/runtime/helpers/tests/binary_frame_vectors.rs create mode 100644 libs/runtime/helpers/tests/fixtures/binary-frame-vectors.json diff --git a/libs/runtime/Cargo.lock b/libs/runtime/Cargo.lock index e7ab49e6..c36b51fb 100644 --- a/libs/runtime/Cargo.lock +++ b/libs/runtime/Cargo.lock @@ -984,7 +984,7 @@ dependencies = [ [[package]] name = "celerity-python-runtime-sdk" -version = "0.2.2" +version = "0.3.0" dependencies = [ "async-trait", "axum 0.8.8", @@ -1157,6 +1157,7 @@ dependencies = [ "async-trait", "axum 0.8.8", "axum-extra 0.10.3", + "base64 0.22.1", "chrono", "coverage-helper", "futures", diff --git a/libs/runtime/helpers/Cargo.toml b/libs/runtime/helpers/Cargo.toml index 7f4f051e..6816b24a 100644 --- a/libs/runtime/helpers/Cargo.toml +++ b/libs/runtime/helpers/Cargo.toml @@ -38,3 +38,4 @@ pretty_assertions = "1.4.0" coverage-helper = "0.2.2" hyper-util = { version = "0.1.6", features = ["client", "client-legacy"] } http-body-util = "0.1.2" +base64 = "0.22.1" diff --git a/libs/runtime/helpers/tests/binary_frame_vectors.rs b/libs/runtime/helpers/tests/binary_frame_vectors.rs new file mode 100644 index 00000000..f3a8000d --- /dev/null +++ b/libs/runtime/helpers/tests/binary_frame_vectors.rs @@ -0,0 +1,126 @@ +//! Conformance vectors for the Celerity Binary Message Format. +//! +//! The format is a published wire contract, and it has two implementations that +//! have to lay out the same bytes for the same clients. +//! +//! This one frames what the runtime sends. The other is the Go SDK's, which +//! exists because Go reaches the runtime over IPC and has no in-process binding +//! to call — unlike the Node and Python SDKs, which hand framing to this crate +//! through their native bindings and so hold no implementation of their own. +//! +//! A frame that differs by a byte still parses, as something other than what was +//! meant, so nothing fails until a client reads a payload short by its own +//! headers. These vectors are what keeps the two honest, and the file is shared: +//! the copy in the Go SDK at `handler/testdata/` is asserted there against the +//! Go encoder. Change the two together. + +use base64::prelude::*; +use celerity_helpers::websockets::{ + encode_binary_message, parse_binary_message, BinaryMessageParts, +}; +use serde::Deserialize; + +const VECTORS: &str = include_str!("fixtures/binary-frame-vectors.json"); + +#[derive(Deserialize)] +struct Vectors { + encodes: Vec, + refusals: Vec, +} + +#[derive(Deserialize)] +struct EncodeVector { + name: String, + route: String, + #[serde(rename = "messageId")] + message_id: Option, + #[serde(rename = "requireAck")] + require_ack: bool, + #[serde(rename = "payloadBase64")] + payload_base64: String, + #[serde(rename = "framedBase64")] + framed_base64: String, +} + +#[derive(Deserialize)] +struct RefusalVector { + name: String, + route: String, + #[serde(rename = "messageId")] + message_id: Option, + #[serde(rename = "requireAck")] + require_ack: bool, +} + +fn vectors() -> Vectors { + serde_json::from_str(VECTORS).expect("the shared vectors should parse") +} + +#[test] +fn test_encoder_agrees_with_the_shared_vectors() { + for vector in vectors().encodes { + let payload = BASE64_STANDARD + .decode(&vector.payload_base64) + .expect("vector payload should be base64"); + let expected = BASE64_STANDARD + .decode(&vector.framed_base64) + .expect("vector frame should be base64"); + + let framed = encode_binary_message(BinaryMessageParts { + route: &vector.route, + message_id: vector.message_id.as_deref(), + require_ack: vector.require_ack, + message: &payload, + }) + .unwrap_or_else(|err| panic!("framing {} should succeed, got {err:?}", vector.name)); + + assert_eq!( + framed, expected, + "the frame for {} differs from the shared vector, so this encoder and the \ + SDK's no longer lay out the same bytes", + vector.name + ); + } +} + +#[test] +fn test_encoder_refuses_what_the_shared_vectors_refuse() { + for vector in vectors().refusals { + let result = encode_binary_message(BinaryMessageParts { + route: &vector.route, + message_id: vector.message_id.as_deref(), + require_ack: vector.require_ack, + message: &[], + }); + + assert!( + result.is_err(), + "framing {} should be refused, since truncating it into a frame would be read \ + as something other than what was meant", + vector.name + ); + } +} + +// The vectors pin the bytes; this pins that those bytes mean what they were +// composed to mean, which a shared fixture alone cannot say. +#[test] +fn test_shared_vectors_round_trip_through_the_parser() { + for vector in vectors().encodes { + let payload = BASE64_STANDARD + .decode(&vector.payload_base64) + .expect("vector payload should be base64"); + let framed = BASE64_STANDARD + .decode(&vector.framed_base64) + .expect("vector frame should be base64"); + + let parsed = parse_binary_message(&framed) + .unwrap_or_else(|err| panic!("parsing {} should succeed, got {err:?}", vector.name)); + + assert_eq!( + parsed.message, payload, + "the payload read back from {} is not the one framed", + vector.name + ); + } +} diff --git a/libs/runtime/helpers/tests/fixtures/binary-frame-vectors.json b/libs/runtime/helpers/tests/fixtures/binary-frame-vectors.json new file mode 100644 index 00000000..a0c73574 --- /dev/null +++ b/libs/runtime/helpers/tests/fixtures/binary-frame-vectors.json @@ -0,0 +1,113 @@ +{ + "$comment": [ + "Conformance vectors for the Celerity Binary Message Format.", + "https://celerityframework.io/docs/framework/applications/resources/celerity-api#celerity-binary-message-format", + "A published wire format has one implementation per language, so parity is asserted", + "against these rather than assumed. Asserted by the TypeScript encoder in", + "packages/types/tests/binary-frame.test.ts and by the Rust encoder that serves the", + "same clients. Both copies of this file must stay identical; change them together.", + "Layout: [routeLength][route][requireAck][messageIdLength][messageId][payload]" + ], + "encodes": [ + { + "name": "a message asking to be acknowledged", + "why": "every field populated, in the order the parser reads them", + "route": "orders", + "messageId": "m-1", + "requireAck": true, + "payloadBase64": "3q0=", + "framedBase64": "Bm9yZGVycwEDbS0x3q0=" + }, + { + "name": "a message asking nothing of its client", + "why": "no id and no ack is the common case, and the one a client must still be able to frame", + "route": "a", + "messageId": null, + "requireAck": false, + "payloadBase64": "AQ==", + "framedBase64": "AWEAAAE=" + }, + { + "name": "an empty payload", + "why": "four bytes, which is the shortest frame the parser accepts", + "route": "a", + "messageId": null, + "requireAck": false, + "payloadBase64": "", + "framedBase64": "AWEAAA==" + }, + { + "name": "a route outside ASCII", + "why": "the length prefix counts bytes, not characters, so a multi-byte route is where a length taken from the string would go wrong", + "route": "caf\u00e9", + "messageId": null, + "requireAck": false, + "payloadBase64": "Bw==", + "framedBase64": "BWNhZsOpAAAH" + }, + { + "name": "a route at the limit of its length byte", + "why": "255 is representable and 256 is not, so the boundary is where truncation would start", + "route": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "messageId": null, + "requireAck": false, + "payloadBase64": "", + "framedBase64": "/3JycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycnJycgAA" + }, + { + "name": "an id at the limit of its length byte", + "why": "same boundary on the other field", + "route": "a", + "messageId": "mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm", + "requireAck": false, + "payloadBase64": "", + "framedBase64": "AWEA/21tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbQ==" + }, + { + "name": "a route beginning with a byte just past the reserved range", + "why": "0x5 is the last reserved byte, so 0x6 must be allowed through", + "route": "\u0006event", + "messageId": null, + "requireAck": false, + "payloadBase64": "Ag==", + "framedBase64": "BgZldmVudAAAAg==" + } + ], + "refusals": [ + { + "name": "no route", + "why": "a route is what the message is delivered by", + "route": "", + "messageId": null, + "requireAck": false + }, + { + "name": "a route longer than its length byte", + "why": "truncating it would frame a message under a route nobody serves", + "route": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "messageId": null, + "requireAck": false + }, + { + "name": "a route beginning with a reserved byte", + "why": "a client would read it as a ping or an acknowledgement rather than as itself", + "route": "\u0004ck", + "messageId": null, + "requireAck": false + }, + { + "name": "an id longer than its length byte", + "why": "a truncated id names a message that does not exist", + "route": "a", + "messageId": "mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm", + "requireAck": false + }, + { + "name": "asking to be acknowledged with no id to name", + "why": "the sender would wait for an answer that can never come", + "route": "a", + "messageId": null, + "requireAck": true + } + ] +} From ae898cc6a7a59d677efd127e856f0d2915e26d36 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 14 Oct 2026 16:17:56 +0100 Subject: [PATCH 05/12] docs(runtime-libs): clarify dispatch ordering and the handler side of the IPC protocol The dispatcher module doc explained the per-tag queues through head-of-line blocking without saying that the finite credit window is what makes queue order decide anything, which read as though a tag waits for its previous event to finish. It now says that several events for one tag are commonly in flight together and that round-robin only chooses which tag is offered a place next. The WsOutbound message id comments now say when leaving the id empty is reasonable and when it leaves an informed client told that a message was lost and unable to say which. The proto README gains the obligations an SDK takes on when it implements the handler side, which a community SDK author previously had to infer from reading the Rust implementation. Handler tag construction, the credit rule and version negotiation are the parts most easily got wrong, so they are spelled out. --- libs/runtime/core/src/dispatcher.rs | 24 ++++-- libs/runtime/proto/README.md | 82 +++++++++++++++++++ .../proto/celerity/runtime/v1/runtime.proto | 33 +++++--- 3 files changed, 120 insertions(+), 19 deletions(-) diff --git a/libs/runtime/core/src/dispatcher.rs b/libs/runtime/core/src/dispatcher.rs index dc4b8958..d63f5178 100644 --- a/libs/runtime/core/src/dispatcher.rs +++ b/libs/runtime/core/src/dispatcher.rs @@ -1,14 +1,18 @@ //! Chooses which queued event goes to which handler stream, and when. //! //! Events arrive on one bounded queue but are not dispatched from it directly. -//! A single line shared by every handler tag is head-of-line blocking waiting -//! to happen, an application with a one millisecond health check and a five -//! second report endpoint puts both in the same queue, so fifty report requests -//! at the head hold up every health check behind them. That is how a slow -//! endpoint takes down a liveness probe. +//! The credit window is finite, so only so many events can be in flight to a +//! stream at once, and on a single line shared by every handler tag the order +//! events were queued in is what decides which of them get those places. Take +//! an application with a one millisecond health check and a five second report +//! endpoint on that line, a health check queued behind fifty reports cannot be +//! dispatched until enough of them have completed and returned their places, so +//! an answer that takes a millisecond to produce is held for seconds waiting +//! for one. That is how a slow endpoint takes down a liveness probe. //! -//! Events are therefore partitioned into one queue per handler tag, and two -//! independent limits decide what may be sent: +//! Events are therefore partitioned into one queue per handler tag, so a tag is +//! offered a place as soon as it can take one however deep another tag's queue +//! is, and two independent limits decide what may be sent: //! //! - **Credit**, which a handler stream grants and the runtime consumes. It //! bounds total in-flight work for that stream and is sized to the handler's @@ -20,6 +24,12 @@ //! single tag monopolising it. Among the tags that can be served, selection is //! round-robin, which is enough while scheduling policy stays runtime-side. //! +//! A queue per tag is about the order events are dispatched in, not about how +//! many run at once. A tag holds as many places in the window as its cap and +//! the reservation for idle tags allow, so several events for the same tag are +//! commonly in flight together. Round-robin decides which tag is offered a +//! place next, it does not make a tag wait for its previous event to finish. +//! //! Nothing here knows about specific transport. A stream is somewhere events can be sent and //! a source of credit, so the dispatcher can be exercised without a transport. diff --git a/libs/runtime/proto/README.md b/libs/runtime/proto/README.md index 8371d352..5de27320 100644 --- a/libs/runtime/proto/README.md +++ b/libs/runtime/proto/README.md @@ -75,3 +75,85 @@ payload against 3.0µs for passthrough. It is also why `google.protobuf.Struct` does not appear anywhere in the event path: its cost scales with field count rather than bytes, making it slower than the JSON in production today, larger on the wire, and lossy for integers, byte strings and non-finite numbers. + +## What an SDK on the handler side must do + +The `.proto` is the authority on message shapes, field numbers and wire +compatibility. What it cannot express is ordering, timing and obligation, and +those are what an SDK author gets wrong. This section is the short form; the +normative specification is the +[Handler IPC Protocol](https://celerityframework.io/docs/framework/runtime/handler-ipc-protocol) +document. + +An implementation must: + +1. **Connect** to `CELERITY_RUNTIME_SOCKET`, inherited from the runtime that + started the process, and open exactly one `EventStream`. +2. **Accept `RuntimeConfig` as the first frame.** It arrives before anything is + asked, so an SDK can check the handlers registered in code against the ones + the blueprint declares, and refuse for itself rather than waiting to be + refused. +3. **Send `Ready` within 30 seconds**, declaring the protocol version it was + built against, every tag it serves, and an initial credit no larger than its + worker pool. The timeout is not configurable. +4. **Stop, reporting why, where `ReadyAck` is not accepted.** Refusal is a tag + mismatch in either direction, or a protocol major version the runtime does + not serve. +5. **Answer every `Dispatch` with a `Result` carrying the same id** — including + where user code panicked, threw, or was cancelled. +6. **Send a `credit_grant` on every result, including on failure.** Credit is + consumed on dispatch and replenished only when the handler says so. A missed + grant drains the window and stalls the stream silently, which is the single + easiest way to write an SDK that works under test and hangs under load. Zero + is for withholding deliberately. +7. **Report failure for a message it did not process**, naming records by the + id they arrived with. For a source that acknowledges, the outcome decides + whether the message is delivered again. +8. **Treat `deadline_unix_ms` as its own deadline.** The runtime enforces it + independently. +9. **Ignore a `Cancel` for an event it no longer holds.** Cancellation is + advisory and races with completion; a cancelled event should still be + answered, because that is what returns the credit. +10. **Stop taking new work on `Drain`** and finish what it holds before the + deadline. +11. **Answer nothing after the stream closes.** + +### Handler tags + +A tag is how the runtime addresses a handler, and it is compared byte for byte +at the handshake. The constructions are in +`libs/runtime/core/src/event_queue.rs`: + +``` +HTTP :: e.g. GET::/orders/{orderId} +WebSocket :: +Consumer source:::: +Schedule source:::: +Custom custom:: +``` + +An SDK does not have to build these. `RuntimeConfig.handlers[].handler_tag` +carries the tag the runtime will address each handler by, so echoing those back +in `Ready.handler_tags` is both simpler and impossible to get wrong by a byte. +Reconstructing them is what the official SDKs do, and it is why their tests pin +the format. + +Two details that catch people out: a blueprint's `/files/{path+}` reaches the +handler as `/files/{*path}`, the router's form and the form the tag is built +from; and a binary WebSocket message must be framed in the Celerity Binary +Message Format or the runtime refuses it. + +### Version negotiation + +`ProtocolVersion` is carried both ways. The runtime serves major version `1`. +A handler declaring no version is refused, as is one declaring a different +major — at the handshake, rather than later on a frame it cannot read. Minor +versions are additive, so a handler built against an earlier minor of the same +major serves here unchanged. + +### A worked reference + +`libs/runtime/core/tests/common/ipc.rs` is a minimal working handler client — +the connect idiom, the config-then-`Ready`-then-`ReadyAck` handshake, the frame +loop, and a credit grant on every result. It is the shortest complete thing to +read before writing an SDK. diff --git a/libs/runtime/proto/celerity/runtime/v1/runtime.proto b/libs/runtime/proto/celerity/runtime/v1/runtime.proto index 63e6d9dc..654d3e18 100644 --- a/libs/runtime/proto/celerity/runtime/v1/runtime.proto +++ b/libs/runtime/proto/celerity/runtime/v1/runtime.proto @@ -380,15 +380,23 @@ message WsOutbound { bool is_binary = 3; repeated string inform_clients_on_loss = 4; // Identifies this message to the runtime, for the acknowledgement between - // nodes when the target connection lives on another one, and in the loss - // event delivered to the clients named in inform_clients_on_loss. Generated - // by the runtime when left empty, which is the right choice unless the - // handler needs to match a loss event back to what it sent. + // nodes when the target connection lives on another one, and as the messageId + // in the loss event delivered to the clients named in inform_clients_on_loss. + // Generated by the runtime when left empty. // - // Not the message id the client sees. The runtime sends `message` to the - // socket exactly as given, so a client-visible id, and the acknowledgement - // and deduplication that depend on it, is something the handler puts in the - // payload it composes. + // The runtime does not put it in the message. `message` is sent to the + // socket exactly as given, so the id a client reads out of a payload, and the + // acknowledgement and deduplication that depend on it, is something the + // handler composes. The two are the same id only where the handler makes + // them so. + // + // That decides whether leaving it empty is reasonable. For a message no + // client is informed about, a generated id is fine, nothing outside the + // runtime sees it. Where inform_clients_on_loss names clients, the id is + // shown to those clients, and a generated one names something they have + // never seen and cannot look up, leaving them told a message was lost and + // unable to say which. Set it to an id the informed client already knows, + // ordinarily the same one the payload carries, or rely on `caller`. string message_id = 5; // The connection that caused this message to be sent, carried through to the // loss event so an informed client can tell who was being replied to. Only @@ -410,10 +418,11 @@ message WsOutbound { // Reports what happened to each message in a WsSend. // -// Failures are per message rather than per batch because a client has no way to -// deduplicate: a message reaches it as a bare text or binary frame with no id, -// so re-sending one that already arrived is visible to the application. A -// handler must therefore be able to retry exactly what failed. +// Failures are per message rather than per batch so a handler can retry exactly +// what failed. Re-sending a whole batch would redeliver the messages that did +// arrive, and whether the client can tell those apart depends on the message +// ID: a client SDK deduplicates by that where a message carries one, and cannot +// where it does not. message WsSendAck { string correlation_id = 1; // True when every message was delivered, equivalent to failures being empty. From 0bac1a55978f6291742b09042772fe9311a5ef52 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 14 Oct 2026 16:18:12 +0100 Subject: [PATCH 06/12] refactor(cli): move the deploy engine and config provider to deploy-cli-sdk The deploy engine client, its interface and the error simplification now live in deploy-cli-sdk, shared with the other CLIs built on it. This package keeps only the re-export seam, so no call site changed. The three local copies were stale leftovers of a move that had already happened, and one of them was a stub pointing at a hardcoded localhost endpoint. The config provider moves to the SDK across the remaining command files, finishing a migration that had been left half done and had the two provider types meeting in the middle. The validate TUI moves with it, picking up the newer engine interface where creating a validation returns a last event id that the stream call needs so it does not replay what already happened. Pins deploy-cli-sdk at v0.9.0, the first release carrying Provider.Set. The pre command step needs Set rather than SetDefault because a default loses to the blueprint flag's own default, which would leave the SDK commands reading a file this step never wrote. --- apps/cli/cmd/commands/init.go | 4 +- apps/cli/cmd/commands/root.go | 5 +- apps/cli/cmd/commands/validate.go | 11 +- apps/cli/go.mod | 134 ++-- apps/cli/go.sum | 382 ++++++---- .../internal/deployconfig/config_values.go | 101 +++ .../deployconfig/config_values_test.go | 125 ++++ apps/cli/internal/deployconfig/convert.go | 347 +++++++++ .../cli/internal/deployconfig/convert_test.go | 309 ++++++++ apps/cli/internal/deployconfig/engine.go | 42 ++ apps/cli/internal/deployconfig/engine_test.go | 72 ++ .../deployconfig/handler_build_test.go | 81 +++ .../internal/deployconfig/pre_command_step.go | 447 ++++++++++++ .../deployconfig/pre_command_step_test.go | 128 ++++ apps/cli/internal/engine/client.go | 17 - apps/cli/internal/engine/engine.go | 26 + apps/cli/internal/engine/errors.go | 26 - apps/cli/internal/engine/interface.go | 174 ----- apps/cli/internal/handlers/validate.go | 8 +- apps/cli/internal/handlers/validate_test.go | 4 +- .../internal/testutils/mock_deploy_engine.go | 152 +++- apps/cli/internal/tui/shared/footer.go | 27 + apps/cli/internal/tui/validateui/commands.go | 7 +- .../internal/tui/validateui/validate_model.go | 2 +- go.work | 4 +- go.work.sum | 671 ++++++++++++++++-- 26 files changed, 2831 insertions(+), 475 deletions(-) create mode 100644 apps/cli/internal/deployconfig/config_values.go create mode 100644 apps/cli/internal/deployconfig/config_values_test.go create mode 100644 apps/cli/internal/deployconfig/convert.go create mode 100644 apps/cli/internal/deployconfig/convert_test.go create mode 100644 apps/cli/internal/deployconfig/engine.go create mode 100644 apps/cli/internal/deployconfig/engine_test.go create mode 100644 apps/cli/internal/deployconfig/handler_build_test.go create mode 100644 apps/cli/internal/deployconfig/pre_command_step.go create mode 100644 apps/cli/internal/deployconfig/pre_command_step_test.go delete mode 100644 apps/cli/internal/engine/client.go create mode 100644 apps/cli/internal/engine/engine.go delete mode 100644 apps/cli/internal/engine/errors.go delete mode 100644 apps/cli/internal/engine/interface.go create mode 100644 apps/cli/internal/tui/shared/footer.go diff --git a/apps/cli/cmd/commands/init.go b/apps/cli/cmd/commands/init.go index d32c7fb4..4c101090 100644 --- a/apps/cli/cmd/commands/init.go +++ b/apps/cli/cmd/commands/init.go @@ -6,10 +6,10 @@ import ( "strings" tea "github.com/charmbracelet/bubbletea" - "github.com/newstack-cloud/celerity/apps/cli/internal/config" + "github.com/newstack-cloud/bluelink/libs/common/core" "github.com/newstack-cloud/celerity/apps/cli/internal/consts" "github.com/newstack-cloud/celerity/apps/cli/internal/tui/initui" - "github.com/newstack-cloud/bluelink/libs/common/core" + "github.com/newstack-cloud/deploy-cli-sdk/config" "github.com/spf13/cobra" ) diff --git a/apps/cli/cmd/commands/root.go b/apps/cli/cmd/commands/root.go index 07f88549..6c6d5b2b 100644 --- a/apps/cli/cmd/commands/root.go +++ b/apps/cli/cmd/commands/root.go @@ -6,7 +6,7 @@ import ( "runtime" "github.com/newstack-cloud/celerity/apps/cli/cmd/utils" - "github.com/newstack-cloud/celerity/apps/cli/internal/config" + "github.com/newstack-cloud/deploy-cli-sdk/config" "github.com/spf13/cobra" "golang.org/x/term" ) @@ -93,6 +93,9 @@ along with blueprints used for Infrastructure as Code.`, setupInitCommand(rootCmd, confProvider) setupValidateCommand(rootCmd, confProvider) setupDevCommand(rootCmd, confProvider) + setupBuildCommand(rootCmd, confProvider) + setupConfigCommand(rootCmd, confProvider) + setupSchemaCommand(rootCmd, confProvider) return rootCmd } diff --git a/apps/cli/cmd/commands/validate.go b/apps/cli/cmd/commands/validate.go index d08e5ee7..9e062d31 100644 --- a/apps/cli/cmd/commands/validate.go +++ b/apps/cli/cmd/commands/validate.go @@ -7,11 +7,11 @@ import ( tea "github.com/charmbracelet/bubbletea" "github.com/newstack-cloud/celerity/apps/cli/cmd/utils" - "github.com/newstack-cloud/celerity/apps/cli/internal/config" "github.com/newstack-cloud/celerity/apps/cli/internal/engine" "github.com/newstack-cloud/celerity/apps/cli/internal/handlers" "github.com/newstack-cloud/celerity/apps/cli/internal/tui/styles" "github.com/newstack-cloud/celerity/apps/cli/internal/tui/validateui" + "github.com/newstack-cloud/deploy-cli-sdk/config" "github.com/spf13/cobra" "golang.org/x/term" ) @@ -43,12 +43,11 @@ func setupValidateCommand(rootCmd *cobra.Command, confProvider *config.Provider) handler := handlers.NewValidateHandler( deployEngine, blueprintFile, - // When not in a terminal, print output - // that is intended primarily for a human to read - // should always go to stdout for the process. + // Outside a terminal, output intended primarily for a + // human to read still goes to the process stdout. os.Stdout, - // Logger is used to for more verbose, technical output - // that is intended primarily for debugging. + // The logger takes the more verbose, technical output + // intended for debugging. logger, ) return handler.Handle(context.TODO()) diff --git a/apps/cli/go.mod b/apps/cli/go.mod index c970e762..d36f83e8 100644 --- a/apps/cli/go.mod +++ b/apps/cli/go.mod @@ -1,75 +1,113 @@ module github.com/newstack-cloud/celerity/apps/cli -go 1.26.0 +go 1.26.4 require ( - github.com/BurntSushi/toml v1.4.0 - github.com/aws/aws-sdk-go-v2 v1.41.3 - github.com/aws/aws-sdk-go-v2/credentials v1.19.11 + ariga.io/atlas v1.3.0 + github.com/BurntSushi/toml v1.6.0 + github.com/aws/aws-lambda-go v1.55.1 + github.com/aws/aws-sdk-go-v2 v1.47.3 + github.com/aws/aws-sdk-go-v2/config v1.33.9 + github.com/aws/aws-sdk-go-v2/credentials v1.20.9 + github.com/aws/aws-sdk-go-v2/feature/rds/auth v1.7.4 github.com/aws/aws-sdk-go-v2/service/dynamodb v1.56.1 - github.com/charmbracelet/bubbles v0.21.0 - github.com/charmbracelet/bubbletea v1.3.5 - github.com/charmbracelet/lipgloss v1.1.0 + github.com/aws/aws-sdk-go-v2/service/lambda v1.110.0 + github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3 + github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.50.1 + github.com/aws/aws-sdk-go-v2/service/ssm v1.79.0 + github.com/aws/aws-sdk-go-v2/service/sts v1.51.4 + github.com/charmbracelet/bubbles v0.21.1 + github.com/charmbracelet/bubbletea v1.3.10 + github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 + github.com/charmbracelet/x/exp/teatest v0.0.0-20261011004359-2acd7e345453 github.com/docker/docker v27.5.1+incompatible github.com/docker/go-connections v0.6.0 github.com/fsnotify/fsnotify v1.9.0 - github.com/jackc/pgx/v5 v5.8.0 + github.com/go-sql-driver/mysql v1.10.1 + github.com/jackc/pgx/v5 v5.11.0 github.com/minio/minio-go/v7 v7.0.99 - github.com/newstack-cloud/bluelink/libs/blueprint v0.24.1 - github.com/newstack-cloud/bluelink/libs/blueprint-state v0.2.6 - github.com/newstack-cloud/bluelink/libs/common v0.3.2 - github.com/newstack-cloud/bluelink/libs/deploy-engine-client v0.0.0-20250624153400-b3cd906a01a8 + github.com/newstack-cloud/bluelink/libs/blueprint v0.54.0 + github.com/newstack-cloud/bluelink/libs/blueprint-state v0.9.1 + github.com/newstack-cloud/bluelink/libs/common v0.4.0 + github.com/newstack-cloud/bluelink/libs/deploy-engine-client v0.5.2 + github.com/newstack-cloud/deploy-cli-sdk v0.9.0 github.com/redis/go-redis/v9 v9.18.0 - github.com/spf13/cobra v1.8.1 - github.com/spf13/pflag v1.0.5 - github.com/stretchr/testify v1.11.1 - go.uber.org/zap v1.27.0 - golang.org/x/term v0.40.0 + github.com/spf13/cobra v1.10.2 + github.com/spf13/pflag v1.0.10 + github.com/stretchr/testify v1.12.1 + go.uber.org/zap v1.28.0 + golang.org/x/term v0.47.0 gopkg.in/yaml.v3 v3.0.1 ) require ( + filippo.io/edwards25519 v1.2.0 // indirect github.com/Microsoft/go-winio v0.4.21 // indirect + github.com/agext/levenshtein v1.2.1 // indirect + github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect + github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect github.com/atotto/clipboard v0.1.4 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.19 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.19 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.6 // indirect + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 // indirect github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.11.19 // indirect - github.com/aws/smithy-go v1.24.2 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.38.4 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 // indirect + github.com/aws/smithy-go v1.28.5 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/aymanbagabas/go-udiff v0.3.1 // indirect + github.com/bmatcuk/doublestar v1.3.4 // indirect + github.com/catppuccin/go v0.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect - github.com/charmbracelet/x/ansi v0.8.0 // indirect - github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect - github.com/charmbracelet/x/term v0.2.1 // indirect + github.com/charmbracelet/colorprofile v0.4.1 // indirect + github.com/charmbracelet/huh v0.8.0 // indirect + github.com/charmbracelet/x/ansi v0.11.5 // indirect + github.com/charmbracelet/x/cellbuf v0.0.15 // indirect + github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 // indirect + github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect + github.com/charmbracelet/x/term v0.2.2 // indirect + github.com/clipperhouse/displaywidth v0.9.0 // indirect + github.com/clipperhouse/stringish v0.1.1 // indirect + github.com/clipperhouse/uax29/v2 v2.7.0 // indirect github.com/containerd/log v0.1.0 // indirect github.com/coreos/go-json v0.0.0-20231102161613-e49c8866685a // indirect - github.com/davecgh/go-spew v1.1.1 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/distribution/reference v0.6.0 // indirect github.com/docker/go-units v0.5.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect - github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/felixge/httpsnoop v1.1.0 // indirect github.com/go-ini/ini v1.67.0 // indirect - github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-openapi/inflect v0.19.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect + github.com/google/go-cmp v0.7.0 // indirect github.com/google/uuid v1.6.0 // indirect + github.com/hashicorp/hcl/v2 v2.13.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect - github.com/klauspost/compress v1.18.2 // indirect - github.com/klauspost/cpuid/v2 v2.2.11 // indirect + github.com/klauspost/compress v1.19.2 // indirect + github.com/klauspost/cpuid/v2 v2.4.0 // indirect github.com/klauspost/crc32 v1.3.0 // indirect - github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/lucasb-eyer/go-colorful v1.3.0 // indirect github.com/matoous/go-nanoid/v2 v2.1.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-localereader v0.0.1 // indirect - github.com/mattn/go-runewidth v0.0.16 // indirect + github.com/mattn/go-runewidth v0.0.20 // indirect github.com/minio/crc64nvme v1.1.1 // indirect github.com/minio/md5-simd v1.1.2 // indirect + github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect + github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect github.com/moby/term v0.5.2 // indirect github.com/morikuni/aec v1.1.0 // indirect @@ -80,33 +118,31 @@ require ( github.com/opencontainers/image-spec v1.1.1 // indirect github.com/philhofer/fwd v1.2.0 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect github.com/r3labs/sse/v2 v2.10.0 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/rs/xid v1.6.0 // indirect github.com/sahilm/fuzzy v0.1.1 // indirect - github.com/tailscale/hujson v0.0.0-20250226034555-ec1d1c113d33 // indirect + github.com/tailscale/hujson v0.0.0-20260718110524-10d7940d4c87 // indirect github.com/tinylib/msgp v1.6.1 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + github.com/zclconf/go-cty v1.14.4 // indirect + github.com/zclconf/go-cty-yaml v1.1.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 // indirect - go.opentelemetry.io/otel v1.41.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 // indirect + go.opentelemetry.io/otel v1.46.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 // indirect - go.opentelemetry.io/otel/metric v1.41.0 // indirect - go.opentelemetry.io/otel/sdk v1.41.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.41.0 // indirect - go.opentelemetry.io/otel/trace v1.41.0 // indirect + go.opentelemetry.io/otel/metric v1.46.0 // indirect + go.opentelemetry.io/otel/trace v1.46.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.10.0 // indirect - go.yaml.in/yaml/v3 v3.0.4 // indirect - golang.org/x/crypto v0.48.0 // indirect - golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect - golang.org/x/net v0.50.0 // indirect - golang.org/x/oauth2 v0.30.0 // indirect - golang.org/x/sync v0.19.0 // indirect - golang.org/x/sys v0.41.0 // indirect - golang.org/x/text v0.34.0 // indirect - golang.org/x/time v0.14.0 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/crypto v0.57.0 // indirect + golang.org/x/mod v0.41.0 // indirect + golang.org/x/net v0.59.0 // indirect + golang.org/x/oauth2 v0.37.0 // indirect + golang.org/x/sync v0.23.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.42.0 // indirect gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect gotest.tools/v3 v3.5.2 // indirect ) diff --git a/apps/cli/go.sum b/apps/cli/go.sum index 3ad09182..5c4cf68e 100644 --- a/apps/cli/go.sum +++ b/apps/cli/go.sum @@ -1,75 +1,146 @@ +ariga.io/atlas v1.3.0 h1:/ZQLypoRURfNO0VJmXUNz8k6lGoeJLDPlSOZOhxG/1U= +ariga.io/atlas v1.3.0/go.mod h1:v8ltuOKxFAU8ZF33HNfQs1iRWKuP3hJfu+dU0VE5O0Y= +filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= +filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0= -github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= +github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60= +github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= +github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= +github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= github.com/Microsoft/go-winio v0.4.21 h1:+6mVbXh4wPzUrl1COX9A+ZCvEpYsOBZ6/+kwDnvLyro= github.com/Microsoft/go-winio v0.4.21/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= +github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8= +github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= +github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw= +github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo= +github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY= +github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= -github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU= -github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0= -github.com/aws/aws-sdk-go-v2/credentials v1.19.9 h1:sWvTKsyrMlJGEuj/WgrwilpoJ6Xa1+KhIpGdzw7mMU8= -github.com/aws/aws-sdk-go-v2/credentials v1.19.9/go.mod h1:+J44MBhmfVY/lETFiKI+klz0Vym2aCmIjqgClMmW82w= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 h1:xOLELNKGp2vsiteLsvLPwxC+mYmO6OZ8PYgiuPJzF8U= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17/go.mod h1:5M5CI3D12dNOtH3/mk6minaRwI2/37ifCURZISxA/IQ= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v3ISRNiv+3KdQoZ6JWyfcsyQik= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM= -github.com/aws/aws-sdk-go-v2/service/dynamodb v1.55.0 h1:CyYoeHWjVSGimzMhlL0Z4l5gLCa++ccnRJKrsaNssxE= -github.com/aws/aws-sdk-go-v2/service/dynamodb v1.55.0/go.mod h1:ctEsEHY2vFQc6i4KU07q4n68v7BAmTbujv2Y+z8+hQY= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow= -github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.11.17 h1:Nhx/OYX+ukejm9t/MkWI8sucnsiroNYNGb5ddI9ungQ= -github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.11.17/go.mod h1:AjmK8JWnlAevq1b1NBtv5oQVG4iqnYXUufdgol+q9wg= -github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk= -github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0= +github.com/aws/aws-lambda-go v1.55.1 h1:We2cCp4BwqqH/JW+bEEo1FhgG71rslvjfi4y7KmlrR0= +github.com/aws/aws-lambda-go v1.55.1/go.mod h1:V+NzkHNR6vBC8C1PDloqSLE+7jYWFiPvJJFiCiTm8nE= +github.com/aws/aws-sdk-go-v2 v1.47.3 h1:HRoT/MkNi3bjO5xF4dCzLzvVmkvRGHj3/cLINDnJejk= +github.com/aws/aws-sdk-go-v2 v1.47.3/go.mod h1:xSl+OSI5ZUw6bSMupWc218zE5Pl+65MCCu3ySWFY99A= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 h1:oiEmPz/YMMeh/JvAE8xSxNCIsvWE6lpFe4ZPlyFykQI= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22/go.mod h1:QWUDuRi9PFjBHIU2iH1Pkldbe7zqLfXJC4wWLbF8nuQ= +github.com/aws/aws-sdk-go-v2/config v1.33.9 h1:Hv6bcQUJVnmuWaKjqD6Ot8sE75NrWsWV20oGT5aWle0= +github.com/aws/aws-sdk-go-v2/config v1.33.9/go.mod h1:ivowmrZNfBQLcg4QkaItgi5wae4Bzot9RzIdbY1hfTg= +github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0= +github.com/aws/aws-sdk-go-v2/credentials v1.20.9/go.mod h1:+2reOTRtdD3VSBqpRDNwrZIYy8yMCYa7oK3WKTJ/I1I= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3 h1:gr3b87OLB29jymWPzp/CAyXwQRJVE+sC4Wm0qBIKHsk= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.3/go.mod h1:BRjf4L/Yx2hY54o+ZibPbLJyMMeSwqYQXwcJfqW66a8= +github.com/aws/aws-sdk-go-v2/feature/rds/auth v1.7.4 h1:DsW6xUKRhy6HhbadXNPIRB2/8CAFk0mSH63RVhR12l0= +github.com/aws/aws-sdk-go-v2/feature/rds/auth v1.7.4/go.mod h1:zhE73dAXSqWCB+He1U5KbCeVbZ7UQoulTU1NR1KfuDk= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 h1:CqL8NN3p4I0JTwwV5MEoatIl4Y2amZ2X9dRD+0hbRL0= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6/go.mod h1:exdJ32hMqXl0Wyo6NwqEC5yIhtua3+PDaKE8P29m4qE= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 h1:FpBq24TG6WVSObTNhQOv7Q0088rounUUlwn3zlNItkM= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6/go.mod h1:ONzdPVYC95oBOu0VWNEsKEntcoemP3xVKjT+qWml1s4= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 h1:Qmn60RWuk9+bd2ddvJJqwf3Cpac3VvGMOdbGemtUhX4= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6/go.mod h1:h/YJhe4AVyQxEUMluph10iqV7mjajH7A9L+BHF5ppis= +github.com/aws/aws-sdk-go-v2/service/dynamodb v1.56.1 h1:EkW4NqA2mwCkL7YCDYh6OpA/bCMhKYbZgpRHt2FD2Ow= +github.com/aws/aws-sdk-go-v2/service/dynamodb v1.56.1/go.mod h1:OQp5333OH1IjmJmJpTU4IwoaOoCMnDrThg0zIx169rE= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 h1:e6YW5uME30TkrElR+4/xcY7NB6CCj2dcv7vtmGXhfhQ= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21/go.mod h1:obpHAMP693+f3/A8PkLhIqfK1C+NWWn8zXzqD3OH520= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 h1:CwvFlKw0uUScfgOMflXSRZa+ayXgOf6wk7lhyMemQYU= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7/go.mod h1:4SbD8BB+p+QEnG0aX6DoWwrtk9SufyYXRsUv0nve8LE= +github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.11.19 h1:jdCj9vbCXwzTcIJX+MVd2UdssFhRJFTrWlPZwZB8Hpk= +github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.11.19/go.mod h1:Dgg2d5WGRr7YB8JJsELskBxLUhgwWppXPwlvmuQKhbc= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 h1:LHHdobjo5le1sjJdolitV7uVvYg3wkaeM1Ju2fDgeZQ= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6/go.mod h1:CBGB0evAiaMD3Lk4wPO7LQCcCZLuhzL5Qf/wfEUHQ5w= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 h1:mYViDr2azcgxOpRrObZOl631bvavqILoE/L+Kxgbwys= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6/go.mod h1:OXVdAo9jNhggB+hJRGOyy7WolGTKB6Rg7IIulDeSzPM= +github.com/aws/aws-sdk-go-v2/service/lambda v1.110.0 h1:fJUTGbCN/EKBq/TIR84MDI0qr4eY9qNaw19dT+S2LCA= +github.com/aws/aws-sdk-go-v2/service/lambda v1.110.0/go.mod h1:jUmFXtUKRVCKTaKap+NgL32pmSkVehamqqMENlGMApk= +github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3 h1:NyeuyXkZL476uoAowNActm4XJO1QPKf7aassgXHpiqA= +github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3/go.mod h1:GfoBeKMDJecgRUsGf/0RGdx0NJAh81ObTd922h8pQys= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.50.1 h1:xYoGDAZtoSXI5wOfjv1jzG1AUOdXZthz4YL9DFvunrQ= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.50.1/go.mod h1:dgXxccOMNsXm/eOkrQbBfxm4a6H8IiRphA7z69RG8hM= +github.com/aws/aws-sdk-go-v2/service/signin v1.10.4 h1:tvpDjuUvgKURf3Yk4hOaGbZ4QdY+070OWcA5d6LUv2A= +github.com/aws/aws-sdk-go-v2/service/signin v1.10.4/go.mod h1:3ibVKg5Ng82Zby8++jELTD2nHxiPk2DJRLEeW/LKp8M= +github.com/aws/aws-sdk-go-v2/service/ssm v1.79.0 h1:q1PpzCnGQqvWowbCR1h3a799hYhaT4l7SHEHwnwhIG0= +github.com/aws/aws-sdk-go-v2/service/ssm v1.79.0/go.mod h1:FLwEDLnpYkC/SwNx9gbsPcG25uMUk7Pxsx8ixaA9xmE= +github.com/aws/aws-sdk-go-v2/service/sso v1.38.4 h1:ChCtagixSFOxltv0o6E3NT8F7ksvZtZGPwUBynO5Nmk= +github.com/aws/aws-sdk-go-v2/service/sso v1.38.4/go.mod h1:+FEO9jrVMpc9oN3CdAxJbtlQEu3z8UddDPSedpeM3PY= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4 h1:j6c+HA4AoS0EBEjArPjavFEBrucJEryfrQU0TffmACk= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.43.4/go.mod h1:RhghaXUk9q66VtOQUX1FdPddQuHnqQZzbB0fEYXmPRA= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.4 h1:OKEfbf2tcfsF2pBk/S9QqNpo6alaAtiBs4hysCsBjPw= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.4/go.mod h1:mCd6qGo9b8hTtfjgsmNkFlzwjyce4owd7HDVFnCLXhM= +github.com/aws/smithy-go v1.28.5 h1:OqbqKtzY9NUnr2yAe9+hiTdFb20tNaK/lI0PMOGXX9k= +github.com/aws/smithy-go v1.28.5/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= -github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8= -github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA= +github.com/aymanbagabas/go-udiff v0.3.1 h1:LV+qyBQ2pqe0u42ZsUEtPiCaUoqgA9gYRDs3vj1nolY= +github.com/aymanbagabas/go-udiff v0.3.1/go.mod h1:G0fsKmG+P6ylD0r6N/KgQD/nWzgfnl8ZBcNLgcbrw8E= +github.com/bmatcuk/doublestar v1.3.4 h1:gPypJ5xD31uhX6Tf54sDPUOBXTqKH4c9aPY66CyQrS0= +github.com/bmatcuk/doublestar v1.3.4/go.mod h1:wiQtGV+rzVYxB7WIlirSN++5HPtPlXEo9MEoZQC/PmE= github.com/bradleyjkemp/cupaloy/v2 v2.8.0 h1:any4BmKE+jGIaMpnU8YgH/I2LPiLBufr6oMMlVBbn9M= github.com/bradleyjkemp/cupaloy/v2 v2.8.0/go.mod h1:bm7JXdkRd4BHJk9HpwqAI8BoAY1lps46Enkdqw6aRX0= github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/catppuccin/go v0.3.0 h1:d+0/YicIq+hSTo5oPuRi5kOpqkVA5tAsU6dNhvRu+aY= +github.com/catppuccin/go v0.3.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc= github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u6mfQdFs= -github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg= -github.com/charmbracelet/bubbletea v1.3.5 h1:JAMNLTbqMOhSwoELIr0qyP4VidFq72/6E9j7HHmRKQc= -github.com/charmbracelet/bubbletea v1.3.5/go.mod h1:TkCnmH+aBd4LrXhXcqrKiYwRs7qyQx5rBgH5fVY3v54= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= -github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= -github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= -github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE= -github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q= -github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8= -github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= +github.com/charmbracelet/bubbles v0.21.1 h1:nj0decPiixaZeL9diI4uzzQTkkz1kYY8+jgzCZXSmW0= +github.com/charmbracelet/bubbles v0.21.1/go.mod h1:HHvIYRCpbkCJw2yo0vNX1O5loCwSr9/mWS8GYSg50Sk= +github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw= +github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4= +github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk= +github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk= +github.com/charmbracelet/huh v0.8.0 h1:Xz/Pm2h64cXQZn/Jvele4J3r7DDiqFCNIVteYukxDvY= +github.com/charmbracelet/huh v0.8.0/go.mod h1:5YVc+SlZ1IhQALxRPpkGwwEKftN/+OlJlnJYlDRFqN4= +github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 h1:ZR7e0ro+SZZiIZD7msJyA+NjkCNNavuiPBLgerbOziE= +github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834/go.mod h1:aKC/t2arECF6rNOnaKaVU6y4t4ZeHQzqfxedE/VkVhA= +github.com/charmbracelet/x/ansi v0.11.5 h1:NBWeBpj/lJPE3Q5l+Lusa4+mH6v7487OP8K0r1IhRg4= +github.com/charmbracelet/x/ansi v0.11.5/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ= +github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI= +github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q= +github.com/charmbracelet/x/conpty v0.1.0 h1:4zc8KaIcbiL4mghEON8D72agYtSeIgq8FSThSPQIb+U= +github.com/charmbracelet/x/conpty v0.1.0/go.mod h1:rMFsDJoDwVmiYM10aD4bH2XiRgwI7NYJtQgl5yskjEQ= +github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA= +github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0= github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ= github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= -github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ= -github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg= -github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= -github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= -github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= -github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= +github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4= +github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ= +github.com/charmbracelet/x/exp/teatest v0.0.0-20261011004359-2acd7e345453 h1:lB0Kde6FDuKvW/QcXLVQ6Cofghsz/rCBSUT6uT8wPx4= +github.com/charmbracelet/x/exp/teatest v0.0.0-20261011004359-2acd7e345453/go.mod h1:aPVjFrBwbJgj5Qz1F0IXsnbcOVJcMKgu1ySUfTAxh7k= +github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= +github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= +github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY= +github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo= +github.com/charmbracelet/x/xpty v0.1.2 h1:Pqmu4TEJ8KeA9uSkISKMU3f+C1F6OGBn8ABuGlqCbtI= +github.com/charmbracelet/x/xpty v0.1.2/go.mod h1:XK2Z0id5rtLWcpeNiMYBccNNBrP2IJnzHI0Lq13Xzq4= +github.com/clipperhouse/displaywidth v0.9.0 h1:Qb4KOhYwRiN3viMv1v/3cTBlz3AcAZX3+y9OLhMtAtA= +github.com/clipperhouse/displaywidth v0.9.0/go.mod h1:aCAAqTlh4GIVkhQnJpbL0T/WfcrJXHcj8C0yjYcjOZA= +github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs= +github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= github.com/coreos/go-json v0.0.0-20231102161613-e49c8866685a h1:QimUZQ6Au5wFKKkPMmdoXen+CNR66lXt/76AQLBltS0= github.com/coreos/go-json v0.0.0-20231102161613-e49c8866685a/go.mod h1:rcFZM3uxVvdyNmsAV2jopgPD1cs5SPWJWU5dOz2LUnw= -github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= +github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= -github.com/docker/docker v28.5.2+incompatible h1:DBX0Y0zAjZbSrm1uzOkdr1onVghKaftjlSWt4AFexzM= -github.com/docker/docker v28.5.2+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker v27.5.1+incompatible h1:4PYU5dnBYqRQi0294d1FBECqT9ECWeQAIfE8q4YnPY8= +github.com/docker/docker v27.5.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/go-connections v0.6.0 h1:LlMG9azAe1TqfR7sO+NJttz1gy6KO7VJBh+pMmjSD94= github.com/docker/go-connections v0.6.0/go.mod h1:AahvXYshr6JgfUJGdDCs2b5EZG/vmaMAntpSFH5BFKE= github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= @@ -78,17 +149,25 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= -github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= -github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= +github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A= github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4= +github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4= +github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME= +github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= +github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= +github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -97,21 +176,25 @@ github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs= github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c= +github.com/hashicorp/hcl/v2 v2.13.0 h1:0Apadu1w6M11dyGFxWnmhhcMjkbAiKCv7G1r/2QgCNc= +github.com/hashicorp/hcl/v2 v2.13.0/go.mod h1:e4z5nxYlWNPdDSNYX+ph14EvWYMFm3eP0zIUqPc2jr0= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI= -github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= +github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg= +github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= -github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk= -github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8= +github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= -github.com/klauspost/cpuid/v2 v2.2.11 h1:0OwqZRYI2rFrjS4kvkDnqJkKHdHaRnCm68/DY4OxRzU= -github.com/klauspost/cpuid/v2 v2.2.11/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= +github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM= github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= @@ -120,28 +203,28 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= -github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag= +github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/matoous/go-nanoid/v2 v2.1.0 h1:P64+dmq21hhWdtvZfEAofnvJULaRR1Yib0+PnU669bE= github.com/matoous/go-nanoid/v2 v2.1.0/go.mod h1:KlbGNQ+FhrUNIHUxZdL63t7tl4LaPkZNpUULS8H4uVM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= -github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= -github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/mattn/go-runewidth v0.0.20 h1:WcT52H91ZUAwy8+HUkdM3THM6gXqXuLJi9O3rjcQQaQ= +github.com/mattn/go-runewidth v0.0.20/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI= github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg= github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= -github.com/minio/minio-go/v7 v7.0.98 h1:MeAVKjLVz+XJ28zFcuYyImNSAh8Mq725uNW4beRisi0= -github.com/minio/minio-go/v7 v7.0.98/go.mod h1:cY0Y+W7yozf0mdIclrttzo1Iiu7mEf9y7nk2uXqMOvM= +github.com/minio/minio-go/v7 v7.0.99 h1:2vH/byrwUkIpFQFOilvTfaUpvAX3fEFhEzO+DR3DlCE= +github.com/minio/minio-go/v7 v7.0.99/go.mod h1:EtGNKtlX20iL2yaYnxEigaIvj0G0GwSDnifnG8ClIdw= +github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM= +github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= +github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4= +github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE= github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= -github.com/moby/sys/atomicwriter v0.1.0 h1:kw5D/EqkBwsBFi0ss9v1VG3wIkVhzGvLklJ+w3A14Sw= -github.com/moby/sys/atomicwriter v0.1.0/go.mod h1:Ul8oqv2ZMNHOceF643P6FKPXeCmYtlQMvpizfsSoaWs= -github.com/moby/sys/sequential v0.6.0 h1:qrx7XFUd/5DxtqcoH1h438hF5TmOvzC/lspjy7zgvCU= -github.com/moby/sys/sequential v0.6.0/go.mod h1:uyv8EUTrca5PnDsdMGXhZe6CCe8U/UiTWd+lL+7b/Ko= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= github.com/morikuni/aec v1.1.0 h1:vBBl0pUnvi/Je71dsRrhMBtreIqNMYErSAbEeb8jrXQ= @@ -152,14 +235,16 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= -github.com/newstack-cloud/bluelink/libs/blueprint v0.24.1 h1:p5PkSw+pbTpOJUooSn8ulMMJ7ZPY3CHdzHD4E8oeeqE= -github.com/newstack-cloud/bluelink/libs/blueprint v0.24.1/go.mod h1:5Unn3mYYUB7WHiuoy+QvHmw8cCQFV0rZY4sK8+dqoBk= -github.com/newstack-cloud/bluelink/libs/blueprint-state v0.2.6 h1:s3pdue0ymM1lESHdLFt2HFQYky8DtSSyVVLoHhDxz58= -github.com/newstack-cloud/bluelink/libs/blueprint-state v0.2.6/go.mod h1:27z3+jPzDlMU2151BT6v9XmEd1FLILSTTvpUWclSf30= -github.com/newstack-cloud/bluelink/libs/common v0.3.2 h1:YqD47176o62SwJyEqpTH/87nlaJJ7uowVrQFi0bJvfc= -github.com/newstack-cloud/bluelink/libs/common v0.3.2/go.mod h1:b18HJMiIRGIFyom6jiweqcxA8vRO6D5Gkfssrq9C+Wc= -github.com/newstack-cloud/bluelink/libs/deploy-engine-client v0.0.0-20250624153400-b3cd906a01a8 h1:fLwYQgMNsLbKvJmOhxCWrs6tmjtIaaj2RjYlCYIiSUY= -github.com/newstack-cloud/bluelink/libs/deploy-engine-client v0.0.0-20250624153400-b3cd906a01a8/go.mod h1:1FL7/gLkiP9iH2dF/5jfEej5C2l8HkFYn/kLmIiOQPk= +github.com/newstack-cloud/bluelink/libs/blueprint v0.54.0 h1:atFcZB+S9g1pZJ+RUwppSv3PtBxFPUy/8hkak00IcyM= +github.com/newstack-cloud/bluelink/libs/blueprint v0.54.0/go.mod h1:IzAGdeIgsxVNhqa6fO0wmkD8xbTviEruMgHgXk33j2k= +github.com/newstack-cloud/bluelink/libs/blueprint-state v0.9.1 h1:WymyISfFNk9C+hO+gDuefOJOnWHaXecPeMHIkG3CxBg= +github.com/newstack-cloud/bluelink/libs/blueprint-state v0.9.1/go.mod h1:3V+FF4CaMMqwdrKv4geYnmzDfkbqG6oNK/BQFm4GDKc= +github.com/newstack-cloud/bluelink/libs/common v0.4.0 h1:E72YAjex+VydpaYJXaAwlqeII7jVugEKsfVjHFLaJJY= +github.com/newstack-cloud/bluelink/libs/common v0.4.0/go.mod h1:09jWAU7PMDJSW0zokebgDZCr59Gg4JpqgF0Yq6kQ8gY= +github.com/newstack-cloud/bluelink/libs/deploy-engine-client v0.5.2 h1:REoQW+smduR0tzb7G8/tu4e8ouLpvcUxh2jn5dsCXCI= +github.com/newstack-cloud/bluelink/libs/deploy-engine-client v0.5.2/go.mod h1:9GboMmne4TYv9cbsenYnqCt4wIu4z1tEf0CxKzoIf8o= +github.com/newstack-cloud/deploy-cli-sdk v0.9.0 h1:ZNg1ic65hcGY66IegGkXNZ/BcjBCk0S7PCWgBs9vZvU= +github.com/newstack-cloud/deploy-cli-sdk v0.9.0/go.mod h1:xQ5eIl/ULYk3KpWCEf+y5X1sGnSlSgLIrDdPGeB81yQ= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= @@ -168,13 +253,13 @@ github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/r3labs/sse/v2 v2.10.0 h1:hFEkLLFY4LDifoHdiCN/LlGBAdVJYsANaLqNYa1l/v0= github.com/r3labs/sse/v2 v2.10.0/go.mod h1:Igau6Whc+F17QUgML1fYe1VPZzTV6EMCnYktEmkNJ7I= -github.com/redis/go-redis/v9 v9.9.0 h1:URbPQ4xVQSQhZ27WMQVmZSo3uT3pL+4IdHVcYq2nVfM= -github.com/redis/go-redis/v9 v9.9.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= -github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs= +github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= @@ -184,89 +269,128 @@ github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA= github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= +github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= -github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= -github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= -github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= +github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/tailscale/hujson v0.0.0-20250226034555-ec1d1c113d33 h1:idh63uw+gsG05HwjZsAENCG4KZfyvjK03bpjxa5qRRk= -github.com/tailscale/hujson v0.0.0-20250226034555-ec1d1c113d33/go.mod h1:EbW0wDK/qEUYI0A5bqq0C2kF8JTQwWONmGDBbzsxxHo= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/tailscale/hujson v0.0.0-20260718110524-10d7940d4c87 h1:kJWZO66xayJEt6jfKHjai8Dtb9iSJWOk09ecczsbeig= +github.com/tailscale/hujson v0.0.0-20260718110524-10d7940d4c87/go.mod h1:EbW0wDK/qEUYI0A5bqq0C2kF8JTQwWONmGDBbzsxxHo= github.com/tinylib/msgp v1.6.1 h1:ESRv8eL3u+DNHUoSAAQRE50Hm162zqAnBoGv9PzScPY= github.com/tinylib/msgp v1.6.1/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/zclconf/go-cty v1.14.4 h1:uXXczd9QDGsgu0i/QFR/hzI5NYCHLf6NQw/atrbnhq8= +github.com/zclconf/go-cty v1.14.4/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE= +github.com/zclconf/go-cty-yaml v1.1.0 h1:nP+jp0qPHv2IhUVqmQSzjvqAWcObN0KBkUl2rWBdig0= +github.com/zclconf/go-cty-yaml v1.1.0/go.mod h1:9YLUH4g7lOhVWqUbctnVlZ5KLpg7JAprQNgxSZ1Gyxs= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 h1:sbiXRNDSWJOTobXh5HyQKjq6wUC5tNybqjIqDpAY4CU= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0/go.mod h1:69uWxva0WgAA/4bu2Yy70SLDBwZXuQ6PbBpbsa5iZrQ= -go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho= -go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 h1:THuZiwpQZuHPul65w4WcwEnkX2QIuMT+UFoOrygtoJw= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 h1:uLXP+3mghfMf7XmV4PkGfFhFKuNWoCvvx5wP/wOXo0o= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0/go.mod h1:v0Tj04armyT59mnURNUJf7RCKcKzq+lgJs6QSjHjaTc= -go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4= -go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI= -go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo= -go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts= -go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA= -go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc= -go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY= -go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU= +go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc= +go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 h1:ao6Oe+wSebTlQ1OEht7jlYTzQKE+pnx/iNywFvTbuuI= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0/go.mod h1:u3T6vz0gh/NVzgDgiwkgLxpsSF6PaPmo2il0apGJbls= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 h1:inYW9ZhgqiDqh6BioM7DVHHzEGVq76Db5897WLGZ5Go= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0/go.mod h1:Izur+Wt8gClgMJqO/cZ8wdeeMryJ/xxiOVgFSSfpDTY= +go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8= +go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o= +go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI= +go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM= +go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE= +go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4= +go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c= +go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI= go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A= go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= -go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= +go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= -golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= -golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g= -golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/exp v0.0.0-20260813180055-c1d0aacb2297 h1:YXnL44eJ77R+ji4/ooy8UsXIhz+lbi2Qgdlc8iRN0gY= +golang.org/x/exp v0.0.0-20260813180055-c1d0aacb2297/go.mod h1:Mkmymgv+uMpSQ/XxJ/7GpdrdYoqm3u72jEbpCLiJmNk= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= +golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191116160921-f9c825593386/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= -golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= -golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= -golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU= -golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= -golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= +golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= +golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= +golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= -golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg= -golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= -golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= -golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= -golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= -google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57 h1:JLQynH/LBHfCTSbDWl+py8C+Rg/k1OVH3xfcaiANuF0= -google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:kSJwQxqmFXeo79zOmbrALdflXQeAYcUbgS7PbpMknCY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57 h1:mWPCjDEyshlQYzBpMNHaEof6UX1PmHcaUODUywQ0uac= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= -google.golang.org/grpc v1.79.2 h1:fRMD94s2tITpyJGtBBn7MkMseNpOZU8ZxgC3MMBaXRU= -google.golang.org/grpc v1.79.2/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= -google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= -google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= +golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/genproto v0.0.0-20260715232425-e75dac1f907d h1:C9v1o0/4quuhOAfmRXA2j+we0PqZIp8traLdeogF3Ms= +google.golang.org/genproto/googleapis/api v0.0.0-20260715232425-e75dac1f907d h1:QwnJwPte4XXAkhPu26LTDIahnsMSUV0kK8HkxbC+Pc4= +google.golang.org/genproto/googleapis/api v0.0.0-20260715232425-e75dac1f907d/go.mod h1:WRrQ7/7N19PypuT0fxLOL5Lq0waoiRri4FbtHDEKrGE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc h1:4bNTbnb44EqGVy9HaQxSY2jnafSUdgV3qHtedvNpDKg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0= +google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/cenkalti/backoff.v1 v1.1.0 h1:Arh75ttbsvlpVA7WtVpH4u9h6Zl46xuptxqLxPiSo4Y= gopkg.in/cenkalti/backoff.v1 v1.1.0/go.mod h1:J6Vskwqd+OMVJl8C33mmtxTBs2gyzfv7UDAkHu8BrjI= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/apps/cli/internal/deployconfig/config_values.go b/apps/cli/internal/deployconfig/config_values.go new file mode 100644 index 00000000..114f52ab --- /dev/null +++ b/apps/cli/internal/deployconfig/config_values.go @@ -0,0 +1,101 @@ +package deployconfig + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/newstack-cloud/bluelink/libs/blueprint/core" + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/newstack-cloud/celerity/apps/cli/internal/seed" +) + +// Fills each celerity/config resource's spec.values from the target +// environment's plaintext config directory, so a first deploy stands the store +// up with values already in it. +// +// Compute reads its configuration as it starts. Creating the store empty and +// importing afterwards leaves a window where it is missing, which a Lambda +// survives and a container does not, since a task that cannot read required +// config crashes and its service never stabilises. Seeding closes that window. +// +// This is a bootstrap, not a source of truth. The store's values are create-only +// on the provider side, so `celerity config set` remains the way configuration +// changes after the first deploy and a later deploy will not revert it. +// +// Secrets are seeded on the same terms, because a workload missing its database +// password is down rather than degraded. The values pass through the merged +// blueprint, which is written 0600 and gitignored, and are held in the deployed +// store from then on. +// +// A value written in the blueprint wins, being the more specific statement. +// +// Directories are per environment with no fallback, since falling back to +// config/local would push a developer's machine values into a deployed +// environment. +func seedConfigValues(bp *schema.Blueprint, appDir string, appEnv string) (int, error) { + if bp == nil || appEnv == "" { + return 0, nil + } + + configDir := existingDir(filepath.Join(appDir, "config", appEnv)) + secretsDir := existingDir(filepath.Join(appDir, "secrets", appEnv)) + if configDir == "" && secretsDir == "" { + return 0, nil + } + + seeded := 0 + for _, info := range seed.CollectConfigResources(bp) { + values, err := seed.LoadAndMergeConfig(configDir, secretsDir, info.StoreName) + if err != nil { + return 0, fmt.Errorf("loading config values for %q: %w", info.StoreName, err) + } + if len(values) == 0 { + continue + } + + resource := bp.Resources.Values[info.ResourceName] + if resource == nil { + continue + } + seeded += applyConfigValues(resource, values) + } + + return seeded, nil +} + +// Writes the loaded values into the resource's spec.values, leaving any key the +// blueprint already states alone. +func applyConfigValues(resource *schema.Resource, values map[string]string) int { + if resource.Spec == nil { + resource.Spec = &core.MappingNode{Fields: map[string]*core.MappingNode{}} + } + if resource.Spec.Fields == nil { + resource.Spec.Fields = map[string]*core.MappingNode{} + } + + existing, ok := resource.Spec.Fields["values"] + if !ok || existing == nil || existing.Fields == nil { + existing = &core.MappingNode{Fields: map[string]*core.MappingNode{}} + resource.Spec.Fields["values"] = existing + } + + applied := 0 + for key, value := range values { + if _, declared := existing.Fields[key]; declared { + continue + } + existing.Fields[key] = core.MappingNodeFromString(value) + applied++ + } + + return applied +} + +func existingDir(path string) string { + info, err := os.Stat(path) + if err != nil || !info.IsDir() { + return "" + } + return path +} diff --git a/apps/cli/internal/deployconfig/config_values_test.go b/apps/cli/internal/deployconfig/config_values_test.go new file mode 100644 index 00000000..ee544555 --- /dev/null +++ b/apps/cli/internal/deployconfig/config_values_test.go @@ -0,0 +1,125 @@ +package deployconfig + +import ( + "os" + "path/filepath" + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/core" + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/stretchr/testify/suite" +) + +type ConfigValuesSuite struct { + suite.Suite +} + +func (s *ConfigValuesSuite) appDir(files map[string]string) string { + dir := s.T().TempDir() + for name, content := range files { + path := filepath.Join(dir, name) + s.Require().NoError(os.MkdirAll(filepath.Dir(path), 0o755)) + s.Require().NoError(os.WriteFile(path, []byte(content), 0o600)) + } + return dir +} + +func configBlueprint(storeName string, values map[string]string) *schema.Blueprint { + spec := &core.MappingNode{ + Fields: map[string]*core.MappingNode{ + "name": core.MappingNodeFromString(storeName), + }, + } + if values != nil { + declared := &core.MappingNode{Fields: map[string]*core.MappingNode{}} + for key, value := range values { + declared.Fields[key] = core.MappingNodeFromString(value) + } + spec.Fields["values"] = declared + } + + return &schema.Blueprint{ + Resources: &schema.ResourceMap{ + Values: map[string]*schema.Resource{ + "appConfig": { + Type: &schema.ResourceTypeWrapper{Value: "celerity/config"}, + Spec: spec, + }, + }, + }, + } +} + +func specValue(bp *schema.Blueprint, key string) string { + values := bp.Resources.Values["appConfig"].Spec.Fields["values"] + if values == nil { + return "" + } + return core.StringValue(values.Fields[key]) +} + +// A store is created holding its values so that compute starting up finds its +// configuration already there. +func (s *ConfigValuesSuite) Test_values_come_from_the_environment_config_directory() { + appDir := s.appDir(map[string]string{ + "config/production/appConfig.yaml": "APP_NAME: \"shop\"\nLOG_LEVEL: \"warn\"\n", + }) + bp := configBlueprint("appConfig", nil) + + seeded, err := seedConfigValues(bp, appDir, "production") + + s.NoError(err) + s.Equal(2, seeded) + s.Equal("shop", specValue(bp, "APP_NAME")) + s.Equal("warn", specValue(bp, "LOG_LEVEL")) +} + +// A workload missing its database password is down, not degraded, so secrets +// are bootstrapped on the same terms as plaintext values. +func (s *ConfigValuesSuite) Test_secrets_are_seeded_alongside_plaintext_values() { + appDir := s.appDir(map[string]string{ + "config/production/appConfig.yaml": "LOG_LEVEL: \"warn\"\n", + "secrets/production/appConfig.yaml": "API_TOKEN: \"from-secrets\"\n", + }) + bp := configBlueprint("appConfig", nil) + + seeded, err := seedConfigValues(bp, appDir, "production") + + s.NoError(err) + s.Equal(2, seeded) + s.Equal("warn", specValue(bp, "LOG_LEVEL")) + s.Equal("from-secrets", specValue(bp, "API_TOKEN")) +} + +// The blueprint is the more specific statement, so it is not overwritten. +func (s *ConfigValuesSuite) Test_a_value_written_in_the_blueprint_wins() { + appDir := s.appDir(map[string]string{ + "config/production/appConfig.yaml": "LOG_LEVEL: \"warn\"\n", + }) + bp := configBlueprint("appConfig", map[string]string{"LOG_LEVEL": "debug"}) + + seeded, err := seedConfigValues(bp, appDir, "production") + + s.NoError(err) + s.Equal(0, seeded) + s.Equal("debug", specValue(bp, "LOG_LEVEL")) +} + +// Falling back to config/local would push a developer's machine values into a +// deployed environment. +func (s *ConfigValuesSuite) Test_another_environments_values_are_not_used() { + appDir := s.appDir(map[string]string{ + "config/local/appConfig.yaml": "LOG_LEVEL: \"debug\"\n", + }) + bp := configBlueprint("appConfig", nil) + + seeded, err := seedConfigValues(bp, appDir, "production") + + s.NoError(err) + s.Equal(0, seeded) + s.Equal("", specValue(bp, "LOG_LEVEL")) +} + +func TestConfigValuesSuite(t *testing.T) { + suite.Run(t, new(ConfigValuesSuite)) +} diff --git a/apps/cli/internal/deployconfig/convert.go b/apps/cli/internal/deployconfig/convert.go new file mode 100644 index 00000000..fb0e9db0 --- /dev/null +++ b/apps/cli/internal/deployconfig/convert.go @@ -0,0 +1,347 @@ +// Package deployconfig handles reading Celerity app deploy configuration +// and converting it to the Bluelink deploy configuration format. +package deployconfig + +import ( + "encoding/json" + "fmt" + "os" + "regexp" + "slices" + "strings" + + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" +) + +// AppDeployConfig represents the structure of app.deploy.jsonc. +type AppDeployConfig struct { + // AppName is the project name. It is a first-class authoring item used for + // resource naming and configuration-store paths (e.g. the SSM path prefix + // "/celerity//"). It is surfaced to the transform as + // the "celerity.appName" context variable. + AppName string `json:"appName"` + // DeployTarget holds the target environment and its configuration. + DeployTarget DeployTarget `json:"deployTarget"` + // ContextVariables are additional context variables passed to the deploy engine. + ContextVariables map[string]any `json:"contextVariables,omitempty"` + // BlueprintVariables are blueprint variable overrides. + BlueprintVariables map[string]any `json:"blueprintVariables,omitempty"` + // HandlerBuild describes how to build the handlers executable for an OS-only + // runtime, where the application is in a language the CLI has no toolchain + // of its own for. + // + // This is not forwarded to the deploy engine. ConvertToBluelinkFormat + // builds its output field by field, and this one describes a local build + // step rather than anything the engine acts on. + HandlerBuild *handlertoolchain.Config `json:"handlerBuild,omitempty"` +} + +// Constrains appName to characters safe for resource names and hierarchical +// store paths, so no slashes, spaces or leading punctuation. +var appNamePattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9-_]*$`) + +// DeployTarget holds the target environment and its configuration. +type DeployTarget struct { + Name string `json:"name"` + AppEnv string `json:"appEnv,omitempty"` + Config map[string]any `json:"config,omitempty"` +} + +// BluelinkDeployConfig is the Bluelink deploy configuration format +// expected by the deploy engine. +type BluelinkDeployConfig struct { + Providers map[string]map[string]any `json:"providers,omitempty"` + Transformers map[string]map[string]any `json:"transformers,omitempty"` + ContextVariables map[string]any `json:"contextVariables,omitempty"` + BlueprintVariables map[string]any `json:"blueprintVariables,omitempty"` + Dependencies map[string]string `json:"dependencies,omitempty"` +} + +var deployTargetToProvider = map[string]string{ + "aws": "aws", + "aws-serverless": "aws", + "gcloud": "gcloud", + "gcloud-serverless": "gcloud", + "azure": "azure", + "azure-serverless": "azure", +} + +var defaultPluginIDs = map[string]string{ + "aws": "newstack-cloud/aws", + "gcloud": "newstack-cloud/gcloud", + "azure": "newstack-cloud/azure", +} + +const defaultTransformerPluginID = "newstack-cloud/celerity" + +// Pins the provider and transformer plugin versions this CLI release is built +// and tested against, keyed by plugin ID. +// +// Constraints use the caret (^major.minor.patch) form, so the deploy engine +// accepts any installed version with the same major and an equal-or-higher +// minor. Non-breaking plugin upgrades flow through automatically while a +// breaking major bump is gated on upgrading the CLI. Compatibility is a +// property of the CLI release, not the Celerity app, so app developers never +// specify plugin versions. +// +// Bump these when the CLI is validated against a new plugin major/minor. +var defaultPluginConstraints = map[string]string{ + "newstack-cloud/aws": "^0.4.0", + "newstack-cloud/gcloud": "^0.1.0", + "newstack-cloud/azure": "^0.1.0", + // TODO: pin once the celerity transformer cuts its first release. Local + // dev builds report 0.0.0-dev, which fails any caret constraint, so the + // transformer is left unconstrained (any installed version) for now. + "newstack-cloud/celerity": "", +} + +// An unknown plugin yields an empty string, which the deploy engine treats as +// any installed version. +func pluginVersionConstraint(pluginID string) string { + return defaultPluginConstraints[pluginID] +} + +// Config key prefixes, keyed by provider namespace, marking a value as +// resource-specific deployment configuration handled by the Celerity +// transformer rather than the provider. +var transformerConfigPrefixes = map[string][]string{ + "aws": {"aws.sqs.", "aws.sns.", "aws.dynamodb.", "aws.s3.", "aws.lambda.", "aws.apigateway.", "aws.ecs.", "aws.eks."}, + "gcloud": {"gcloud.pubsub.", "gcloud.cloudfunctions.", "gcloud.cloudrun.", "gcloud.firestore.", "gcloud.storage."}, + "azure": {"azure.servicebus.", "azure.functions.", "azure.container.", "azure.cosmosdb.", "azure.storage."}, +} + +// The keys, keyed by provider namespace, that describe how to reach the cloud +// account rather than what to deploy into it. They go to the provider and the +// transformer both. +// +// The transformer opens its own session against the same account, reading the +// build manifest from object storage, and a managed celerity/vpc cannot be +// emitted at all without a region. Routing these to the provider alone leaves +// the transformer unable to resolve credentials or a region, which surfaces as +// an emit failure rather than a configuration error. +// +// This is a fixed list rather than every key that is not resource-specific, +// because a plugin rejects configuration fields it does not declare. Provider- +// only keys such as custom service endpoints and the EC2 metadata service +// address would therefore fail validation if they were copied across. Extend +// this only with keys both plugins declare. +var sharedSessionConfigKeys = map[string][]string{ + "aws": { + "aws.accessKeyId", + "aws.secretAccessKey", + "aws.sessionToken", + "aws.profile", + "aws.region", + "aws.assumeRole.roleArn", + "aws.assumeRole.sessionName", + "aws.assumeRole.externalId", + "aws.assumeRole.duration", + "aws.assumeRoleWithWebIdentity.roleArn", + "aws.assumeRoleWithWebIdentity.sessionName", + "aws.assumeRoleWithWebIdentity.webIdentityTokenFile", + "aws.assumeRoleWithWebIdentity.duration", + "aws.sharedConfigFiles", + "aws.sharedCredentialsFiles", + "aws.customCABundle", + "aws.httpProxy", + "aws.httpsProxy", + "aws.insecure", + "aws.maxRetries", + "aws.retryMode", + "aws.useDualStackEndpoint", + "aws.useFIPSEndpoint", + }, +} + +// ReadAppDeployConfig reads and parses an app deploy config file. +// Supports JSONC (strips comments before parsing). +func ReadAppDeployConfig(path string) (*AppDeployConfig, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("reading app deploy config %s: %w", path, err) + } + + cleaned := stripJSONCComments(string(data)) + + var cfg AppDeployConfig + if err := json.Unmarshal([]byte(cleaned), &cfg); err != nil { + return nil, fmt.Errorf("parsing app deploy config %s: %w", path, err) + } + + if cfg.DeployTarget.Name == "" { + return nil, fmt.Errorf("app deploy config %s missing deployTarget.name", path) + } + + if cfg.AppName == "" { + return nil, fmt.Errorf("app deploy config %s missing appName", path) + } + + if !appNamePattern.MatchString(cfg.AppName) { + return nil, fmt.Errorf( + "app deploy config %s has invalid appName %q: must start with a letter or digit and "+ + "contain only letters, digits, hyphens, and underscores", + path, cfg.AppName, + ) + } + + return &cfg, nil +} + +// ConvertToBluelinkFormat converts an app deploy config to the Bluelink +// deploy configuration format expected by the deploy engine. +func ConvertToBluelinkFormat(cfg *AppDeployConfig) (*BluelinkDeployConfig, error) { + providerNamespace, ok := deployTargetToProvider[cfg.DeployTarget.Name] + if !ok { + return nil, fmt.Errorf( + "unsupported deploy target %q, must be one of: aws, aws-serverless, gcloud, gcloud-serverless, azure, azure-serverless", + cfg.DeployTarget.Name, + ) + } + + providerPluginID := defaultPluginIDs[providerNamespace] + transformerPluginID := defaultTransformerPluginID + + providerConfig, transformerConfig := splitConfig(cfg.DeployTarget.Config, providerNamespace) + + blConfig := &BluelinkDeployConfig{ + Providers: map[string]map[string]any{ + providerNamespace: providerConfig, + }, + Transformers: map[string]map[string]any{ + "celerity": transformerConfig, + }, + BlueprintVariables: cfg.BlueprintVariables, + ContextVariables: cfg.ContextVariables, + Dependencies: map[string]string{ + providerPluginID: pluginVersionConstraint(providerPluginID), + transformerPluginID: pluginVersionConstraint(transformerPluginID), + }, + } + + if blConfig.ContextVariables == nil { + blConfig.ContextVariables = map[string]any{} + } + + // The deploy target is read by the Celerity transformer from a context + // variable (the transformerv1 SDK's default "deployTarget" key), not from + // transformer config, so it must be surfaced as a context variable. + blConfig.ContextVariables["deployTarget"] = cfg.DeployTarget.Name + + // Surface the first-class appName as the "celerity.appName" context variable + // the transformer reads. + blConfig.ContextVariables["celerity.appName"] = cfg.AppName + + if cfg.DeployTarget.AppEnv != "" { + blConfig.ContextVariables["appEnv"] = cfg.DeployTarget.AppEnv + } + + return blConfig, nil +} + +// Keys that match a transformer config prefix, such as +// "aws.sqs.messageRetentionPeriod", go to transformer config with the key +// preserved as-is, since the transformer expects the full dotted key. +// +// All other keys go to provider config with the provider namespace prefix +// stripped, so "aws.region" becomes "region", because the provider plugin's +// config definition uses bare field names within its own namespace. +func splitConfig(config map[string]any, providerNamespace string) (providerCfg, transformerCfg map[string]any) { + providerCfg = map[string]any{} + transformerCfg = map[string]any{} + + if config == nil { + return providerCfg, transformerCfg + } + + prefixes := transformerConfigPrefixes[providerNamespace] + sharedKeys := sharedSessionConfigKeys[providerNamespace] + + for key, value := range config { + if isTransformerConfigKey(key, prefixes) { + transformerCfg[key] = value + continue + } + + providerCfg[strings.TrimPrefix(key, providerNamespace+".")] = value + + // The provider matches on the bare key, the transformer on the + // namespaced one, so a shared key is written in both shapes. + if slices.Contains(sharedKeys, key) { + transformerCfg[key] = value + } + } + + return providerCfg, transformerCfg +} + +func isTransformerConfigKey(key string, prefixes []string) bool { + for _, prefix := range prefixes { + if strings.HasPrefix(key, prefix) { + return true + } + } + return false +} + +// WriteBluelinkConfig writes a Bluelink deploy config to a file. +func WriteBluelinkConfig(path string, cfg *BluelinkDeployConfig) error { + data, err := json.MarshalIndent(cfg, "", " ") + if err != nil { + return fmt.Errorf("marshalling bluelink deploy config: %w", err) + } + return os.WriteFile(path, data, 0644) +} + +// Removes single-line (//) and block comments from JSONC, along with trailing +// commas before } or ]. +func stripJSONCComments(s string) string { + // Remove block comments + result := strings.Builder{} + i := 0 + for i < len(s) { + if i+1 < len(s) && s[i] == '/' && s[i+1] == '*' { + // Skip block comment + end := strings.Index(s[i+2:], "*/") + if end == -1 { + break + } + i += end + 4 + continue + } + if i+1 < len(s) && s[i] == '/' && s[i+1] == '/' { + // Skip line comment + end := strings.IndexByte(s[i:], '\n') + if end == -1 { + break + } + i += end + continue + } + if s[i] == '"' { + // Skip string literals (don't strip comments inside strings) + result.WriteByte(s[i]) + i++ + for i < len(s) && s[i] != '"' { + if s[i] == '\\' && i+1 < len(s) { + result.WriteByte(s[i]) + i++ + } + result.WriteByte(s[i]) + i++ + } + if i < len(s) { + result.WriteByte(s[i]) + i++ + } + continue + } + result.WriteByte(s[i]) + i++ + } + + cleaned := result.String() + // Remove trailing commas before } or ] (with optional whitespace/newlines between) + trailingCommaRe := regexp.MustCompile(`,(\s*[}\]])`) + cleaned = trailingCommaRe.ReplaceAllString(cleaned, "$1") + return cleaned +} diff --git a/apps/cli/internal/deployconfig/convert_test.go b/apps/cli/internal/deployconfig/convert_test.go new file mode 100644 index 00000000..b8c3f7db --- /dev/null +++ b/apps/cli/internal/deployconfig/convert_test.go @@ -0,0 +1,309 @@ +package deployconfig + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" +) + +type ConvertTestSuite struct { + suite.Suite +} + +func TestConvertTestSuite(t *testing.T) { + suite.Run(t, new(ConvertTestSuite)) +} + +func (s *ConvertTestSuite) Test_ConvertToBluelinkFormat_aws_serverless() { + cfg := &AppDeployConfig{ + AppName: "orders-service", + DeployTarget: DeployTarget{ + Name: "aws-serverless", + AppEnv: "production", + Config: map[string]any{ + "aws.accessKeyId": "AKIA...", + "aws.secretAccessKey": "secret", + "aws.region": "us-east-1", + }, + }, + BlueprintVariables: map[string]any{ + "region": "us-east-1", + }, + } + + blCfg, err := ConvertToBluelinkFormat(cfg) + s.NoError(err) + + // Provider config should have credentials with the "aws." namespace prefix + // stripped, since the provider plugin uses bare field names. + s.Equal("AKIA...", blCfg.Providers["aws"]["accessKeyId"]) + s.Equal("secret", blCfg.Providers["aws"]["secretAccessKey"]) + s.Equal("us-east-1", blCfg.Providers["aws"]["region"]) + s.NotContains(blCfg.Providers["aws"], "aws.accessKeyId") + + // Deploy target is surfaced as a context variable (read by the transformer + // via the SDK's "deployTarget" key), not as transformer config. + s.Equal("aws-serverless", blCfg.ContextVariables["deployTarget"]) + s.NotContains(blCfg.Transformers["celerity"], "deployTarget") + + // Blueprint variables pass through + s.Equal("us-east-1", blCfg.BlueprintVariables["region"]) + + // AppEnv should be a context variable + s.Equal("production", blCfg.ContextVariables["appEnv"]) + + // AppName should be surfaced as the celerity.appName context variable + s.Equal("orders-service", blCfg.ContextVariables["celerity.appName"]) + + // Default plugin IDs, pinned to the CLI's tested version constraints. + // The transformer is unconstrained for now (see defaultPluginConstraints). + s.Equal("^0.4.0", blCfg.Dependencies["newstack-cloud/aws"]) + s.Contains(blCfg.Dependencies, "newstack-cloud/celerity") + s.Equal("", blCfg.Dependencies["newstack-cloud/celerity"]) +} + +func (s *ConvertTestSuite) Test_ConvertToBluelinkFormat_splits_transformer_config() { + cfg := &AppDeployConfig{ + DeployTarget: DeployTarget{ + Name: "aws", + Config: map[string]any{ + "aws.accessKeyId": "AKIA...", + "aws.sqs.messageRetentionPeriod": 345600, + "aws.sqs.myQueue.maxMessageSize": 65536, + "aws.ecs.some.setting": "value", + }, + }, + } + + blCfg, err := ConvertToBluelinkFormat(cfg) + s.NoError(err) + + // Provider config: only credentials, with the namespace prefix stripped + s.Equal("AKIA...", blCfg.Providers["aws"]["accessKeyId"]) + s.NotContains(blCfg.Providers["aws"], "aws.sqs.messageRetentionPeriod") + + // Transformer config: resource-specific settings + s.Equal(345600, blCfg.Transformers["celerity"]["aws.sqs.messageRetentionPeriod"]) + s.Equal(65536, blCfg.Transformers["celerity"]["aws.sqs.myQueue.maxMessageSize"]) + s.Equal("value", blCfg.Transformers["celerity"]["aws.ecs.some.setting"]) +} + +// The transformer opens its own session against the same account, so how to +// reach the account goes to both plugins. A managed celerity/vpc cannot be +// emitted without a region, and the transformer reads the build manifest from +// object storage under these same credentials. +func (s *ConvertTestSuite) Test_ConvertToBluelinkFormat_shares_session_config_with_transformer() { + cfg := &AppDeployConfig{ + AppName: "test-app", + DeployTarget: DeployTarget{ + Name: "aws-serverless", + Config: map[string]any{ + "aws.profile": "some-profile", + "aws.region": "eu-west-2", + "aws.assumeRole.roleArn": "arn:aws:iam::123456789012:role/deploy", + }, + }, + } + + blCfg, err := ConvertToBluelinkFormat(cfg) + s.NoError(err) + + // The provider matches on the bare key. + s.Equal("some-profile", blCfg.Providers["aws"]["profile"]) + s.Equal("eu-west-2", blCfg.Providers["aws"]["region"]) + s.Equal("arn:aws:iam::123456789012:role/deploy", blCfg.Providers["aws"]["assumeRole.roleArn"]) + + // The transformer matches on the namespaced key. + s.Equal("some-profile", blCfg.Transformers["celerity"]["aws.profile"]) + s.Equal("eu-west-2", blCfg.Transformers["celerity"]["aws.region"]) + s.Equal( + "arn:aws:iam::123456789012:role/deploy", + blCfg.Transformers["celerity"]["aws.assumeRole.roleArn"], + ) +} + +// A plugin rejects configuration fields it does not declare, so a key only the +// provider declares must not be copied across. +func (s *ConvertTestSuite) Test_ConvertToBluelinkFormat_keeps_provider_only_config_off_the_transformer() { + cfg := &AppDeployConfig{ + AppName: "test-app", + DeployTarget: DeployTarget{ + Name: "aws-serverless", + Config: map[string]any{ + "aws.region": "eu-west-2", + "aws.endpoints": "s3=http://localhost:4566", + "aws.ec2MetadataServiceEndpointMode": "IPv6", + }, + }, + } + + blCfg, err := ConvertToBluelinkFormat(cfg) + s.NoError(err) + + s.Equal("s3=http://localhost:4566", blCfg.Providers["aws"]["endpoints"]) + s.Equal("IPv6", blCfg.Providers["aws"]["ec2MetadataServiceEndpointMode"]) + + s.NotContains(blCfg.Transformers["celerity"], "aws.endpoints") + s.NotContains(blCfg.Transformers["celerity"], "aws.ec2MetadataServiceEndpointMode") +} + +func (s *ConvertTestSuite) Test_ConvertToBluelinkFormat_gcloud() { + cfg := &AppDeployConfig{ + DeployTarget: DeployTarget{ + Name: "gcloud-serverless", + Config: map[string]any{ + "gcloud.project": "my-project", + "gcloud.pubsub.topicAsQueue.messageRetentionPeriod": "7d", + }, + }, + } + + blCfg, err := ConvertToBluelinkFormat(cfg) + s.NoError(err) + + s.Equal("my-project", blCfg.Providers["gcloud"]["project"]) + s.Equal("7d", blCfg.Transformers["celerity"]["gcloud.pubsub.topicAsQueue.messageRetentionPeriod"]) + s.Equal("gcloud-serverless", blCfg.ContextVariables["deployTarget"]) + s.NotContains(blCfg.Transformers["celerity"], "deployTarget") + s.Equal("^0.1.0", blCfg.Dependencies["newstack-cloud/gcloud"]) +} + +func (s *ConvertTestSuite) Test_ConvertToBluelinkFormat_default_plugin_ids() { + cfg := &AppDeployConfig{ + DeployTarget: DeployTarget{ + Name: "aws", + }, + } + + blCfg, err := ConvertToBluelinkFormat(cfg) + s.NoError(err) + + s.Equal("^0.4.0", blCfg.Dependencies["newstack-cloud/aws"]) + s.Contains(blCfg.Dependencies, "newstack-cloud/celerity") + s.Equal("", blCfg.Dependencies["newstack-cloud/celerity"]) +} + +func (s *ConvertTestSuite) Test_ConvertToBluelinkFormat_unsupported_target() { + cfg := &AppDeployConfig{ + DeployTarget: DeployTarget{ + Name: "unsupported-target", + }, + } + + _, err := ConvertToBluelinkFormat(cfg) + s.Error(err) + s.Contains(err.Error(), "unsupported deploy target") +} + +func (s *ConvertTestSuite) Test_ConvertToBluelinkFormat_context_variables_pass_through() { + cfg := &AppDeployConfig{ + DeployTarget: DeployTarget{ + Name: "aws", + }, + ContextVariables: map[string]any{ + "myKey": "myValue", + }, + } + + blCfg, err := ConvertToBluelinkFormat(cfg) + s.NoError(err) + + s.Equal("myValue", blCfg.ContextVariables["myKey"]) +} + +func (s *ConvertTestSuite) Test_ReadAppDeployConfig_jsonc() { + content := `{ + // This is a comment + "appName": "orders-service", + "deployTarget": { + "name": "aws", + "appEnv": "production", + "config": { + "accessKeyId": "test-key", + }, + }, + "blueprintVariables": { + "region": "eu-west-1", + } +}` + tmpDir := s.T().TempDir() + path := filepath.Join(tmpDir, "app.deploy.jsonc") + s.NoError(os.WriteFile(path, []byte(content), 0644)) + + cfg, err := ReadAppDeployConfig(path) + s.NoError(err) + s.Equal("orders-service", cfg.AppName) + s.Equal("aws", cfg.DeployTarget.Name) + s.Equal("production", cfg.DeployTarget.AppEnv) + s.Equal("test-key", cfg.DeployTarget.Config["accessKeyId"]) + s.Equal("eu-west-1", cfg.BlueprintVariables["region"]) +} + +func (s *ConvertTestSuite) Test_ReadAppDeployConfig_missing_deploy_target() { + content := `{"appName": "orders-service", "blueprintVariables": {}}` + tmpDir := s.T().TempDir() + path := filepath.Join(tmpDir, "app.deploy.jsonc") + s.NoError(os.WriteFile(path, []byte(content), 0644)) + + _, err := ReadAppDeployConfig(path) + s.Error(err) + s.Contains(err.Error(), "missing deployTarget.name") +} + +func (s *ConvertTestSuite) Test_ReadAppDeployConfig_missing_app_name() { + content := `{"deployTarget": {"name": "aws-serverless"}}` + tmpDir := s.T().TempDir() + path := filepath.Join(tmpDir, "app.deploy.jsonc") + s.NoError(os.WriteFile(path, []byte(content), 0644)) + + _, err := ReadAppDeployConfig(path) + s.Error(err) + s.Contains(err.Error(), "missing appName") +} + +func (s *ConvertTestSuite) Test_ReadAppDeployConfig_invalid_app_name() { + content := `{"appName": "orders/service", "deployTarget": {"name": "aws-serverless"}}` + tmpDir := s.T().TempDir() + path := filepath.Join(tmpDir, "app.deploy.jsonc") + s.NoError(os.WriteFile(path, []byte(content), 0644)) + + _, err := ReadAppDeployConfig(path) + s.Error(err) + s.Contains(err.Error(), "invalid appName") +} + +func (s *ConvertTestSuite) Test_stripJSONCComments_line_comments() { + input := `{ + // comment + "key": "value" // trailing comment +}` + result := stripJSONCComments(input) + s.NotContains(result, "comment") + s.Contains(result, `"key": "value"`) +} + +func (s *ConvertTestSuite) Test_stripJSONCComments_block_comments() { + input := `{ + /* block comment */ + "key": "value" +}` + result := stripJSONCComments(input) + s.NotContains(result, "block comment") + s.Contains(result, `"key": "value"`) +} + +func (s *ConvertTestSuite) Test_stripJSONCComments_preserves_strings() { + input := `{"key": "value // not a comment"}` + result := stripJSONCComments(input) + s.Contains(result, "// not a comment") +} + +func (s *ConvertTestSuite) Test_stripJSONCComments_trailing_commas() { + input := `{ + "key": "value", +}` + result := stripJSONCComments(input) + s.NotContains(result, ",\n}") +} diff --git a/apps/cli/internal/deployconfig/engine.go b/apps/cli/internal/deployconfig/engine.go new file mode 100644 index 00000000..8d478a65 --- /dev/null +++ b/apps/cli/internal/deployconfig/engine.go @@ -0,0 +1,42 @@ +package deployconfig + +import ( + "net" + "net/url" + + "github.com/newstack-cloud/deploy-cli-sdk/config" +) + +// IsRemoteEngine reports whether the deploy engine the CLI will talk to runs +// outside the user's local filesystem and so cannot read files the CLI has +// written to disk. Callers use this to decide whether filesystem paths must be +// replaced with remote URLs, for uploaded build manifests and artifact buckets. +// +// "Remote" requires both a tcp connect-protocol and a non-loopback +// endpoint host. A tcp connection to localhost/127.0.0.1/::1 is still +// a local engine for filesystem-sharing purposes. +func IsRemoteEngine(confProvider *config.Provider) bool { + protocol, _ := confProvider.GetString("connectProtocol") + if protocol != "tcp" { + return false + } + endpoint, _ := confProvider.GetString("engineEndpoint") + if endpoint == "" { + return false + } + u, err := url.Parse(endpoint) + if err != nil { + return false + } + return !isLoopbackHost(u.Hostname()) +} + +func isLoopbackHost(host string) bool { + if host == "" || host == "localhost" { + return true + } + if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() { + return true + } + return false +} diff --git a/apps/cli/internal/deployconfig/engine_test.go b/apps/cli/internal/deployconfig/engine_test.go new file mode 100644 index 00000000..3967a1a8 --- /dev/null +++ b/apps/cli/internal/deployconfig/engine_test.go @@ -0,0 +1,72 @@ +package deployconfig + +import ( + "testing" + + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/stretchr/testify/suite" +) + +type EngineTestSuite struct { + suite.Suite +} + +func TestEngineTestSuite(t *testing.T) { + suite.Run(t, new(EngineTestSuite)) +} + +func (s *EngineTestSuite) newProvider(protocol, endpoint string) *config.Provider { + p := config.NewProvider() + p.BindEnvVar("connectProtocol", "CELERITY_CLI_TEST_CONNECT_PROTOCOL") + p.BindEnvVar("engineEndpoint", "CELERITY_CLI_TEST_ENGINE_ENDPOINT") + s.T().Setenv("CELERITY_CLI_TEST_CONNECT_PROTOCOL", protocol) + s.T().Setenv("CELERITY_CLI_TEST_ENGINE_ENDPOINT", endpoint) + return p +} + +func (s *EngineTestSuite) Test_IsRemoteEngine_unixProtocol_alwaysFalse() { + cases := []string{ + "", + "http://engine.example.com:8325", + "http://localhost:8325", + } + for _, endpoint := range cases { + p := s.newProvider("unix", endpoint) + s.False(IsRemoteEngine(p), "unix protocol with endpoint=%q", endpoint) + } +} + +func (s *EngineTestSuite) Test_IsRemoteEngine_tcp_localhost_isLocal() { + cases := []string{ + "http://localhost:8325", + "http://127.0.0.1:8325", + "http://[::1]:8325", + "https://localhost", + } + for _, endpoint := range cases { + p := s.newProvider("tcp", endpoint) + s.False(IsRemoteEngine(p), "loopback endpoint=%q should be local", endpoint) + } +} + +func (s *EngineTestSuite) Test_IsRemoteEngine_tcp_remoteHost_isRemote() { + cases := []string{ + "http://engine.example.com:8325", + "http://10.0.0.5:8325", + "https://celerity.internal", + } + for _, endpoint := range cases { + p := s.newProvider("tcp", endpoint) + s.True(IsRemoteEngine(p), "non-loopback endpoint=%q should be remote", endpoint) + } +} + +func (s *EngineTestSuite) Test_IsRemoteEngine_tcp_emptyEndpoint_isLocal() { + p := s.newProvider("tcp", "") + s.False(IsRemoteEngine(p)) +} + +func (s *EngineTestSuite) Test_IsRemoteEngine_tcp_unparseableEndpoint_isLocal() { + p := s.newProvider("tcp", "://bad-url") + s.False(IsRemoteEngine(p)) +} diff --git a/apps/cli/internal/deployconfig/handler_build_test.go b/apps/cli/internal/deployconfig/handler_build_test.go new file mode 100644 index 00000000..0c2afe2b --- /dev/null +++ b/apps/cli/internal/deployconfig/handler_build_test.go @@ -0,0 +1,81 @@ +package deployconfig + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" + "github.com/stretchr/testify/suite" +) + +type HandlerBuildConfigSuite struct { + suite.Suite + dir string +} + +func (s *HandlerBuildConfigSuite) SetupTest() { s.dir = s.T().TempDir() } + +func (s *HandlerBuildConfigSuite) writeConfig(contents string) string { + path := filepath.Join(s.dir, "app.deploy.jsonc") + s.Require().NoError(os.WriteFile(path, []byte(contents), 0o644)) + return path +} + +func (s *HandlerBuildConfigSuite) Test_handler_build_is_read_off_the_deploy_config() { + path := s.writeConfig(`{ + "appName": "orders", + "deployTarget": { "name": "aws-serverless" }, + "handlerBuild": { + "command": "cargo build --release", + "binary": "target/release/handlers", + "targets": { + "aws-serverless": { "binary": "target/aarch64-unknown-linux-musl/release/handlers" } + } + } + }`) + + cfg, err := ReadAppDeployConfig(path) + s.Require().NoError(err) + s.Require().NotNil(cfg.HandlerBuild) + s.Assert().Equal("cargo build --release", cfg.HandlerBuild.Command) + s.Assert().Contains(cfg.HandlerBuild.Targets, "aws-serverless") +} + +func (s *HandlerBuildConfigSuite) Test_a_config_without_the_block_leaves_it_nil() { + path := s.writeConfig(`{"appName":"orders","deployTarget":{"name":"aws-serverless"}}`) + + cfg, err := ReadAppDeployConfig(path) + s.Require().NoError(err) + s.Assert().Nil(cfg.HandlerBuild) +} + +// handlerBuild describes a local build step. The deploy engine has no use for +// it, and a build command in engine-bound config would be sent to a remote +// engine on every deploy. +func (s *HandlerBuildConfigSuite) Test_handler_build_is_not_forwarded_to_the_deploy_engine() { + cfg := &AppDeployConfig{ + AppName: "orders", + DeployTarget: DeployTarget{ + Name: "aws-serverless", + AppEnv: "production", + }, + HandlerBuild: &handlertoolchain.Config{ + Command: "cargo build --release", + Binary: "target/release/handlers", + Env: map[string]string{"SECRET_TOKEN": "not-for-the-engine"}, + }, + } + + converted, err := ConvertToBluelinkFormat(cfg) + s.Require().NoError(err) + + encoded, err := json.Marshal(converted) + s.Require().NoError(err) + s.Assert().NotContains(string(encoded), "handlerBuild") + s.Assert().NotContains(string(encoded), "cargo build") + s.Assert().NotContains(string(encoded), "not-for-the-engine") +} + +func TestHandlerBuildConfigSuite(t *testing.T) { suite.Run(t, new(HandlerBuildConfigSuite)) } diff --git a/apps/cli/internal/deployconfig/pre_command_step.go b/apps/cli/internal/deployconfig/pre_command_step.go new file mode 100644 index 00000000..40651d3d --- /dev/null +++ b/apps/cli/internal/deployconfig/pre_command_step.go @@ -0,0 +1,447 @@ +package deployconfig + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "github.com/newstack-cloud/celerity/apps/cli/internal/blueprint" + "github.com/newstack-cloud/celerity/apps/cli/internal/build" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlerresolve" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" + "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/newstack-cloud/deploy-cli-sdk/tui/precommand" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +// CelerityPreCommandStep reads the app deploy config, converts it to +// Bluelink format, optionally runs a build, and sets the deployConfigFile +// config key so the SDK commands use it. +type CelerityPreCommandStep struct{} + +func (s *CelerityPreCommandStep) Run( + ctx context.Context, + confProvider *config.Provider, + commandName string, + progress chan<- precommand.ProgressMsg, +) error { + appConfigFile, _ := confProvider.GetString("appDeployConfigFile") + if appConfigFile == "" { + appConfigFile = "app.deploy.jsonc" + } + + if _, err := os.Stat(appConfigFile); os.IsNotExist(err) { + return nil + } + + sendProgress(progress, "Reading app deploy configuration", appConfigFile) + + appCfg, err := ReadAppDeployConfig(appConfigFile) + if err != nil { + return fmt.Errorf("reading app deploy config: %w", err) + } + + if commandName == "deploy" || commandName == "stage" { + logger := newPreCommandLogger() + + resolved, err := collectHandlersForBuild(ctx, confProvider, appCfg, logger) + if err != nil { + return fmt.Errorf("collecting build info: %w", err) + } + + skipBuild, _ := confProvider.GetBool("skipBuild") + if !skipBuild { + if err := autoBuild(ctx, confProvider, appCfg, resolved, logger, progress); err != nil { + return err + } + } + + seeded, err := seedConfigValues(resolved.MergedBlueprint, ".", appCfg.DeployTarget.AppEnv) + if err != nil { + return err + } + if seeded > 0 { + sendProgress( + progress, + "Seeding config values", + fmt.Sprintf("%d value(s) from %s", seeded, appCfg.DeployTarget.AppEnv), + ) + } + + if err := useMergedBlueprint(confProvider, resolved, progress); err != nil { + return err + } + + if err := ensureManifestUploaded(ctx, confProvider, appCfg, progress); err != nil { + return err + } + } + + if err := injectBuildManifestPointer(appCfg, confProvider); err != nil { + return err + } + + sendProgress(progress, "Converting deploy configuration", "") + + blCfg, err := ConvertToBluelinkFormat(appCfg) + if err != nil { + return fmt.Errorf("converting app deploy config: %w", err) + } + + outputDir := ".celerity" + if err := os.MkdirAll(outputDir, 0755); err != nil { + return fmt.Errorf("creating .celerity directory: %w", err) + } + + outputPath := filepath.Join(outputDir, "deploy-config.json") + if err := WriteBluelinkConfig(outputPath, blCfg); err != nil { + return fmt.Errorf("writing converted deploy config: %w", err) + } + + // Set rather than SetDefault, for the same reason as the blueprint keys + // below. --deploy-config-file carries its own default, which a SetDefault + // loses to, leaving the SDK commands reading a file this step never wrote. + // A path the user named explicitly still wins, because an explicitly-set + // flag beats an override. + confProvider.Set("deployConfigFile", outputPath) + return nil +} + +func autoBuild( + ctx context.Context, + confProvider *config.Provider, + appCfg *AppDeployConfig, + resolved *handlerresolve.ResolvedHandlers, + logger *zap.Logger, + progress chan<- precommand.ProgressMsg, +) error { + // An existing manifest is not grounds for skipping the build. The caller + // has already checked --skip-build, which is the deliberate opt-out, and + // skipping here as well silently deploys whatever was built last, such as + // an old SDK version in the dependency layer or source from before the last + // edit, with the deploy reporting success while running code nobody asked + // for. Artefacts are content-addressed, so an unchanged application + // rebuilds to the same hashes and uploads nothing new. + + deployTarget := appCfg.DeployTarget.Name + sendProgress(progress, "Building application", deployTarget) + + const buildLogPath = ".celerity/build.log" + if err := os.MkdirAll(".celerity", 0755); err != nil { + return fmt.Errorf("creating .celerity directory: %w", err) + } + + logFile, err := os.Create(buildLogPath) + if err != nil { + return fmt.Errorf("creating build log: %w", err) + } + defer logFile.Close() + + runtime := resolved.Runtime + handlers := make([]build.HandlerInfo, len(resolved.Handlers)) + for i, h := range resolved.Handlers { + handlers[i] = build.HandlerInfo{ + ResourceName: h.ResourceName, + HandlerName: h.HandlerName, + CodeLocation: h.CodeLocation, + } + } + + registry := build.NewDefaultRegistry(".") + strategy, err := registry.GetStrategy(deployTarget) + if err != nil { + return fmt.Errorf("no build strategy for target %s: %w", deployTarget, err) + } + + sendProgress(progress, "Resolving handler dependencies", "") + + handlerDeps, err := build.ReadHandlerDependencies(registry, runtime, ".") + if err != nil { + return fmt.Errorf("reading handler dependencies: %w", err) + } + + uploader := build.ResolveUploader(deployTarget, appCfg.DeployTarget.Config) + + sendProgress(progress, "Packaging handlers", fmt.Sprintf("%d handler(s)", len(handlers))) + + manifest, err := strategy.Build(ctx, &build.BuildParams{ + AppDir: ".", + Runtime: runtime, + DeployTarget: deployTarget, + Handlers: handlers, + HandlerDependencies: handlerDeps, + OutputDir: ".celerity/build", + Uploader: uploader, + Logger: logger, + // Without this the build has no blueprint at all, so it bundles an + // empty resource links file and an empty handler scope file and skips + // the maintenance runner, all of it silently, because each of those + // treats a missing blueprint as nothing to do. Every deploy goes + // through here, so this is the path that matters most. + Blueprint: resolved.MergedBlueprint, + ToolOutput: logFile, + Toolchain: resolved.Toolchain, + }) + if err != nil { + sendProgress(progress, "Build failed", "see "+buildLogPath) + return fmt.Errorf("auto-build failed (see %s): %w", buildLogPath, err) + } + + if err := build.WriteManifest(manifest); err != nil { + return fmt.Errorf("writing build manifest: %w", err) + } + + sendProgress(progress, "Build complete", "log: "+buildLogPath) + return nil +} + +// Uploads the local build manifest to cloud storage when the CLI is about to +// contact a remote deploy engine and the manifest has not already been +// uploaded. The resulting s3:// URL is written back to the local manifest so +// subsequent deploys can skip the upload. +// +// This is the single choke point that decouples the standalone build command +// from deploy engine configuration. Build writes a local manifest, and any +// deploy to a remote engine lifts it to cloud storage on the way out. +func ensureManifestUploaded( + ctx context.Context, + confProvider *config.Provider, + appCfg *AppDeployConfig, + progress chan<- precommand.ProgressMsg, +) error { + if !IsRemoteEngine(confProvider) { + return nil + } + + manifest, err := build.ReadManifest() + if err != nil { + return fmt.Errorf("reading build manifest: %w", err) + } + if manifest == nil { + return nil + } + if manifest.RemoteURL != "" { + return nil + } + + uploader := build.ResolveUploader( + appCfg.DeployTarget.Name, + appCfg.DeployTarget.Config, + ) + if uploader == nil { + return fmt.Errorf( + "remote deploy engine configured but deploy target %q "+ + "does not support build manifest upload", + appCfg.DeployTarget.Name, + ) + } + + sendProgress(progress, "Uploading build manifest", "") + + if err := build.UploadManifest(ctx, uploader, manifest, "default"); err != nil { + sendProgress(progress, "Manifest upload failed", err.Error()) + return err + } + + if err := build.WriteManifest(manifest); err != nil { + return fmt.Errorf("writing build manifest after upload: %w", err) + } + + sendProgress(progress, "Build manifest uploaded", manifest.RemoteURL) + return nil +} + +func sendProgress(ch chan<- precommand.ProgressMsg, phase, detail string) { + if ch == nil { + return + } + ch <- precommand.ProgressMsg{Phase: phase, Detail: detail} +} + +// For a local deploy engine the pointer is an absolute file path, and for a +// remote one the cloud storage URL recorded in manifest.RemoteURL by +// ensureManifestUploaded. +func injectBuildManifestPointer(appCfg *AppDeployConfig, confProvider *config.Provider) error { + manifest, _ := build.ReadManifest() + if manifest == nil { + return nil + } + + if appCfg.ContextVariables == nil { + appCfg.ContextVariables = map[string]any{} + } + + if IsRemoteEngine(confProvider) { + if manifest.RemoteURL == "" { + return fmt.Errorf( + "remote deploy engine requires an uploaded build manifest, " + + "but none is recorded; ensure the deploy target supports artifact upload", + ) + } + appCfg.ContextVariables["celerity.buildManifest"] = manifest.RemoteURL + return nil + } + + absPath, err := filepath.Abs(build.ManifestFile) + if err != nil { + absPath = build.ManifestFile + } + appCfg.ContextVariables["celerity.buildManifest"] = absPath + return nil +} + +// Extracts the handlers defined in code and merges them into the blueprint, +// producing what both the build and the deploy engine work from. +// +// Run for stage and deploy whether or not a build happens, because the merge is +// what puts handler resources in the blueprint and skipping it on the grounds +// that artifacts already exist would deploy an application with no handlers in +// it. +func collectHandlersForBuild( + ctx context.Context, + confProvider *config.Provider, + appCfg *AppDeployConfig, + logger *zap.Logger, +) (*handlerresolve.ResolvedHandlers, error) { + blueprintFile := deployBlueprintFile(confProvider) + + // Resolved once here and carried on the result, so the build step uses + // the toolchain the extraction step already prepared the project with + // rather than resolving a second one. + toolchain, err := resolveToolchain(appCfg, blueprintFile, logger) + if err != nil { + return nil, err + } + + resolved, err := handlerresolve.Resolve(ctx, handlerresolve.Options{ + AppDir: ".", + BlueprintFile: blueprintFile, + Toolchain: toolchain, + DeployTarget: appCfg.DeployTarget.Name, + Mode: handlertoolchain.ModeDeploy, + }, logger) + if err != nil { + return nil, err + } + + if len(resolved.Handlers) > 0 { + if err := handlerresolve.RequireRuntimeSDK(".", resolved); err != nil { + return nil, err + } + } + + return resolved, nil +} + +// Resolves the build tooling for an OS-only runtime. +// +// The runtime is read from the blueprint rather than taken from the resolved +// handlers, because resolution is what needs the toolchain. Extraction for a +// compiled language is the toolchain's own job. +func resolveToolchain( + appCfg *AppDeployConfig, + blueprintFile string, + logger *zap.Logger, +) (handlertoolchain.Toolchain, error) { + runtime, err := runtimeForToolchain(blueprintFile) + if err != nil || runtime == "" { + // Not an error worth stopping for, since a blueprint the runtime + // cannot be read from is reported with far better context by Resolve, + // which runs next. + return nil, nil + } + + toolchain, err := handlertoolchain.Resolve(handlertoolchain.Options{ + Runtime: runtime, + AppDir: ".", + Config: appCfg.HandlerBuild, + }) + if err != nil { + return nil, err + } + if toolchain != nil { + logger.Info("resolved handler toolchain", + zap.String("toolchain", toolchain.Name()), + zap.String("runtime", runtime), + ) + } + return toolchain, nil +} + +func runtimeForToolchain(blueprintFile string) (string, error) { + bp, _, err := blueprint.LoadForDev(blueprintFile) + if err != nil { + return "", err + } + if runtime, err := blueprint.DetectRuntime(bp); err == nil { + return runtime, nil + } + return blueprint.DetectRuntimeFromProject(".") +} + +// The blueprint the command was pointed at, before any merged copy replaces it. +// +// stage and deploy each bind their own key, and only the running command's is +// set, so both are consulted. +func deployBlueprintFile(confProvider *config.Provider) string { + for _, key := range []string{"deployBlueprintFile", "stageBlueprintFile"} { + if value, _ := confProvider.GetString(key); value != "" { + return value + } + } + + return "app.blueprint" +} + +// Writes the merged blueprint out and points the command at it. +// +// A decorator-driven application declares no celerity/handler resources in its +// blueprint, so without this the transformer has nothing to expand and the +// deployed application has no handlers, silently. +func useMergedBlueprint( + confProvider *config.Provider, + resolved *handlerresolve.ResolvedHandlers, + progress chan<- precommand.ProgressMsg, +) error { + if resolved.MergedBlueprint == nil { + return nil + } + + sendProgress( + progress, + "Merging handlers into blueprint", + fmt.Sprintf("%d handler(s)", len(resolved.Handlers)), + ) + + // 0600: the merged blueprint carries the environment's configuration values, + // including secrets seeded so a first deploy can stand its store up. + mergedPath, err := preprocess.WriteMergedWithMode( + resolved.MergedBlueprint, + resolved.SpecFormat, + ".celerity", + 0o600, + ) + if err != nil { + return fmt.Errorf("writing merged blueprint: %w", err) + } + + // Set rather than SetDefault, because a default loses to the blueprint + // flag's own default. A blueprint the user named explicitly still wins over + // both. + confProvider.Set("deployBlueprintFile", mergedPath) + confProvider.Set("stageBlueprintFile", mergedPath) + + return nil +} + +func newPreCommandLogger() *zap.Logger { + cfg := zap.NewDevelopmentConfig() + cfg.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder + cfg.OutputPaths = []string{"stdout"} + cfg.ErrorOutputPaths = []string{"stderr"} + logger, _ := cfg.Build() + return logger +} diff --git a/apps/cli/internal/deployconfig/pre_command_step_test.go b/apps/cli/internal/deployconfig/pre_command_step_test.go new file mode 100644 index 00000000..19729f28 --- /dev/null +++ b/apps/cli/internal/deployconfig/pre_command_step_test.go @@ -0,0 +1,128 @@ +package deployconfig + +import ( + "os" + "path/filepath" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/build" + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/stretchr/testify/suite" +) + +type PreCommandStepSuite struct { + suite.Suite + origDir string +} + +func TestPreCommandStepSuite(t *testing.T) { + suite.Run(t, new(PreCommandStepSuite)) +} + +func (s *PreCommandStepSuite) SetupTest() { + dir := s.T().TempDir() + origDir, err := os.Getwd() + s.Require().NoError(err) + s.origDir = origDir + s.Require().NoError(os.Chdir(dir)) +} + +func (s *PreCommandStepSuite) TearDownTest() { + s.Require().NoError(os.Chdir(s.origDir)) +} + +func (s *PreCommandStepSuite) newProvider(protocol, endpoint string) *config.Provider { + p := config.NewProvider() + p.BindEnvVar("connectProtocol", "CELERITY_CLI_TEST_CONNECT_PROTOCOL") + p.BindEnvVar("engineEndpoint", "CELERITY_CLI_TEST_ENGINE_ENDPOINT") + s.T().Setenv("CELERITY_CLI_TEST_CONNECT_PROTOCOL", protocol) + s.T().Setenv("CELERITY_CLI_TEST_ENGINE_ENDPOINT", endpoint) + return p +} + +func (s *PreCommandStepSuite) writeManifest(manifest *build.Manifest) { + s.Require().NoError(build.WriteManifest(manifest)) +} + +func (s *PreCommandStepSuite) Test_injectBuildManifestPointer_localEngine_usesAbsoluteLocalPath() { + s.writeManifest(&build.Manifest{ + Version: build.ManifestVersion, + Runtime: "nodejs24.x", + Target: "aws-serverless", + Handlers: map[string]*build.HandlerArtifacts{}, + }) + + appCfg := &AppDeployConfig{} + provider := s.newProvider("unix", "") + + err := injectBuildManifestPointer(appCfg, provider) + s.Require().NoError(err) + + absPath, _ := filepath.Abs(build.ManifestFile) + s.Equal(absPath, appCfg.ContextVariables["celerity.buildManifest"]) +} + +func (s *PreCommandStepSuite) Test_injectBuildManifestPointer_remoteEngine_usesRemoteURL() { + s.writeManifest(&build.Manifest{ + Version: build.ManifestVersion, + Runtime: "nodejs24.x", + Target: "aws-serverless", + Handlers: map[string]*build.HandlerArtifacts{}, + RemoteURL: "s3://celerity-build-123-us-east-1/default/build-manifest.json", + }) + + appCfg := &AppDeployConfig{} + provider := s.newProvider("tcp", "http://engine.example.com:8325") + + err := injectBuildManifestPointer(appCfg, provider) + s.Require().NoError(err) + + s.Equal( + "s3://celerity-build-123-us-east-1/default/build-manifest.json", + appCfg.ContextVariables["celerity.buildManifest"], + ) +} + +func (s *PreCommandStepSuite) Test_injectBuildManifestPointer_remoteEngine_missingRemoteURL_returnsError() { + s.writeManifest(&build.Manifest{ + Version: build.ManifestVersion, + Runtime: "nodejs24.x", + Target: "aws-serverless", + Handlers: map[string]*build.HandlerArtifacts{}, + }) + + appCfg := &AppDeployConfig{} + provider := s.newProvider("tcp", "http://engine.example.com:8325") + + err := injectBuildManifestPointer(appCfg, provider) + s.Require().Error(err) + s.Contains(err.Error(), "remote deploy engine requires an uploaded build manifest") + s.Nil(appCfg.ContextVariables["celerity.buildManifest"]) +} + +func (s *PreCommandStepSuite) Test_injectBuildManifestPointer_tcpLocalhost_treatedAsLocal() { + s.writeManifest(&build.Manifest{ + Version: build.ManifestVersion, + Runtime: "nodejs24.x", + Target: "aws-serverless", + Handlers: map[string]*build.HandlerArtifacts{}, + }) + + appCfg := &AppDeployConfig{} + provider := s.newProvider("tcp", "http://localhost:8325") + + err := injectBuildManifestPointer(appCfg, provider) + s.Require().NoError(err) + + absPath, _ := filepath.Abs(build.ManifestFile) + s.Equal(absPath, appCfg.ContextVariables["celerity.buildManifest"]) +} + +func (s *PreCommandStepSuite) Test_injectBuildManifestPointer_noManifest_noop() { + appCfg := &AppDeployConfig{} + provider := s.newProvider("tcp", "http://engine.example.com:8325") + + err := injectBuildManifestPointer(appCfg, provider) + s.Require().NoError(err) + s.Nil(appCfg.ContextVariables) +} diff --git a/apps/cli/internal/engine/client.go b/apps/cli/internal/engine/client.go deleted file mode 100644 index d8dd0550..00000000 --- a/apps/cli/internal/engine/client.go +++ /dev/null @@ -1,17 +0,0 @@ -package engine - -import ( - "github.com/newstack-cloud/celerity/apps/cli/internal/config" - deployengine "github.com/newstack-cloud/bluelink/libs/deploy-engine-client" - "go.uber.org/zap" -) - -// Create a new deploy engine client based on how the CLI is configured. -func Create(confProvider *config.Provider, logger *zap.Logger) (DeployEngine, error) { - return deployengine.NewClient( - deployengine.WithClientAuthMethod(deployengine.AuthMethodAPIKey), - deployengine.WithClientEndpoint("http://localhost:8325"), - deployengine.WithClientConnectProtocol(deployengine.ConnectProtocolTCP), - deployengine.WithClientAPIKey("test-api-key"), - ) -} diff --git a/apps/cli/internal/engine/engine.go b/apps/cli/internal/engine/engine.go new file mode 100644 index 00000000..c04e3077 --- /dev/null +++ b/apps/cli/internal/engine/engine.go @@ -0,0 +1,26 @@ +// Package engine gives the CLI its deploy engine client. +// +// The client, its interface and the error simplification all live in +// deploy-cli-sdk now, shared with the other CLIs built on it. This package is +// the seam that remains: it re-exports them under the import path the CLI's +// commands already use, so the move needed no change at any call site. +// +// Creating the client is the part worth not duplicating. It resolves the +// endpoint and connect protocol from configuration, loads the engine auth +// config file and handles all three auth methods -- behaviour every command +// depends on and which is easy to get subtly wrong in a second copy. +package engine + +import ( + sdkengine "github.com/newstack-cloud/deploy-cli-sdk/engine" +) + +// DeployEngine is the deploy engine's v1 API, as implemented by the client. +type DeployEngine = sdkengine.DeployEngine + +// Create builds a deploy engine client from the CLI's configuration. +var Create = sdkengine.Create + +// SimplifyError turns a transport or API error into something an operator can +// act on. +var SimplifyError = sdkengine.SimplifyError diff --git a/apps/cli/internal/engine/errors.go b/apps/cli/internal/engine/errors.go deleted file mode 100644 index d913f351..00000000 --- a/apps/cli/internal/engine/errors.go +++ /dev/null @@ -1,26 +0,0 @@ -package engine - -import ( - "errors" - "fmt" - - deerrors "github.com/newstack-cloud/bluelink/libs/deploy-engine-client/errors" - "go.uber.org/zap" -) - -// SimplifyError deals with simplifying specific deploy engine errors -// that are a part of the deploy engine client library API and -// transforming them into something easier to digest for the user. -// When an error is simplified, the original error will be logged at the debug level with -// the provided logger so there is a traceable record of the original error when debugging. -func SimplifyError(err error, logger *zap.Logger) error { - authPrepErr := &deerrors.AuthPrepError{} - if errors.As(err, &authPrepErr) { - logger.Debug("auth prep error", zap.Error(err)) - return fmt.Errorf( - "failed to prepare authentication headers for the deploy engine, please make sure \n" + - "at least one of the supported authentication methods is configured for the CLI", - ) - } - return err -} diff --git a/apps/cli/internal/engine/interface.go b/apps/cli/internal/engine/interface.go deleted file mode 100644 index fccdc296..00000000 --- a/apps/cli/internal/engine/interface.go +++ /dev/null @@ -1,174 +0,0 @@ -package engine - -import ( - "context" - - "github.com/newstack-cloud/bluelink/libs/blueprint-state/manage" - "github.com/newstack-cloud/bluelink/libs/blueprint/state" - "github.com/newstack-cloud/bluelink/libs/deploy-engine-client/types" -) - -// DeployEngine is an interface used to allow the CLI to interact -// with the deploy engine that implements the v1 API. -type DeployEngine interface { - - // CreateBlueprintValidation creates a new blueprint validation - // for the provided blueprint document and starts the validation process. - // This will return an ID that can be used to stream the validation events - // as they occur. - CreateBlueprintValidation( - ctx context.Context, - payload *types.CreateBlueprintValidationPayload, - query *types.CreateBlueprintValidationQuery, - ) (*manage.BlueprintValidation, error) - - // GetBlueprintValidation retrieves metadata and status information - // about a blueprint validation. - // To get validation events (diagnostics), use the `StreamBlueprintValidationEvents` - // method. - GetBlueprintValidation( - ctx context.Context, - validationID string, - ) (*manage.BlueprintValidation, error) - - // StreamBlueprintValidationEvents streams events from a blueprint - // validation process. - // This will produce a stream of events as they occur or that have - // recently occurred. - // Any HTTP errors that occur when estabilishing a connection will be sent - // to the provided error channel. - StreamBlueprintValidationEvents( - ctx context.Context, - validationID string, - streamTo chan<- types.BlueprintValidationEvent, - errChan chan<- error, - ) error - - // CleanupBlueprintValidations cleans up blueprint validation that are - // older than the retention period configured for the Deploy Engine instance. - CleanupBlueprintValidations( - ctx context.Context, - ) error - - // CreateChangeset creates a change set for a blueprint deployment. - // This will start a change staging process for the provided blueprint - // document and return an ID that can be used to retrieve the change set - // or stream change staging events. - // - // If a valid instance ID or name is provided, a change set will be created - // by comparing the provided blueprint document with the current state of the - // existing blueprint instance. - // - // Creating a change set should be carried out in preparation for deploying new blueprint - // instances or updating existing blueprint instances. - CreateChangeset( - ctx context.Context, - payload *types.CreateChangesetPayload, - ) (*manage.Changeset, error) - - // GetChangeset retrieves a change set for a blueprint deployment. - // This will return the current status of the change staging process. - // If complete, the response will include a full set of changes that - // will be applied when deploying the change set. - GetChangeset( - ctx context.Context, - changesetID string, - ) (*manage.Changeset, error) - - // StreamChangeStagingEvents streams events from the change staging process - // for the given change set ID. - // This will produce a stream of events as they occur or that have recently occurred. - // Any HTTP errors that occur when estabilishing a connection will be sent - // to the provided error channel. - StreamChangeStagingEvents( - ctx context.Context, - changesetID string, - streamTo chan<- types.ChangeStagingEvent, - errChan chan<- error, - ) error - - // CleanupChangesets cleans up change sets that are older than the retention - // period configured for the Deploy Engine instance. - CleanupChangesets( - ctx context.Context, - ) error - - // CreateBlueprintInstance (Deploy New) creates a new blueprint deployment instance. - // This will start the deployment process for the provided blueprint - // document and change set. - // It will return a blueprint instance resource containing an ID that - // can be used to stream deployment events as they occur. - CreateBlueprintInstance( - ctx context.Context, - payload *types.BlueprintInstancePayload, - ) (*state.InstanceState, error) - - // UpdateBlueprintInstance (Deploy Existing) updates an existing blueprint - // deployment instance. - // This will start the deployment process for the provided blueprint - // document and change set. - // It will return the current state of the blueprint instance, - // the same ID provided should be used to stream deployment events as they occur. - UpdateBlueprintInstance( - ctx context.Context, - instanceID string, - payload *types.BlueprintInstancePayload, - ) (*state.InstanceState, error) - - // GetBlueprintInstance retrieves a blueprint deployment instance. - // This will return the current status of the deployment along with - // the current state of the blueprint intance. - GetBlueprintInstance( - ctx context.Context, - instanceID string, - ) (*state.InstanceState, error) - - // GetBlueprintInstanceExports retrieves the exports from a blueprint - // deployment instance. - // This will return the exported fields from the blueprint instance. - GetBlueprintInstanceExports( - ctx context.Context, - instanceID string, - ) (map[string]*state.ExportState, error) - - // DestroyBlueprintInstance destroys a blueprint deployment instance. - // This will start the destroy process for the provided change set. - // It will return the current state of the blueprint instance, - // the same ID provided should be used to stream destroy events as they occur. - DestroyBlueprintInstance( - ctx context.Context, - instanceID string, - payload *types.DestroyBlueprintInstancePayload, - ) (*state.InstanceState, error) - - // StreamBlueprintInstanceEvents streams events from the current deployment - // process for the given blueprint instance ID. - // - // This will stream events for new deployments, updates and for destroying - // a blueprint instance. - // - // This will produce a stream of events as they occur or that have recently occurred. - // - // For a blueprint instance that has been destroyed, this stream will no longer be available - // to new connections once the destroy process has been successfully completed. - // - // Any HTTP errors that occur when estabilishing a connection or unexpected failures - // in the deployment process will be sent to the provided error channel. - StreamBlueprintInstanceEvents( - ctx context.Context, - instanceID string, - streamTo chan<- types.BlueprintInstanceEvent, - errChan chan<- error, - ) error - - // CleanupEvents cleans up events that are older than the retention - // period configured for the Deploy Engine instance. - // - // This will clean up events for all processes including blueprint validations, - // change staging and deployments. This will not clean up the resources themselves, - // only the events that are associated with them. - // You can clean up change sets and blueprint validations using the dedicated methods. - CleanupEvents( - ctx context.Context, - ) error -} diff --git a/apps/cli/internal/handlers/validate.go b/apps/cli/internal/handlers/validate.go index 2d9e8b62..dc1aaaeb 100644 --- a/apps/cli/internal/handlers/validate.go +++ b/apps/cli/internal/handlers/validate.go @@ -5,8 +5,8 @@ import ( "fmt" "io" - "github.com/newstack-cloud/celerity/apps/cli/internal/engine" "github.com/newstack-cloud/bluelink/libs/deploy-engine-client/types" + "github.com/newstack-cloud/celerity/apps/cli/internal/engine" "go.uber.org/zap" ) @@ -33,9 +33,13 @@ func NewValidateHandler( streamTo := make(chan types.BlueprintValidationEvent) errChan := make(chan error) + // LastEventID is exclusive and comes from the create call, so the + // stream starts after whatever had already happened by then rather + // than replaying it. err = deployEngine.StreamBlueprintValidationEvents( ctx, - blueprintValidation.ID, + blueprintValidation.Data.ID, + blueprintValidation.LastEventID, streamTo, errChan, ) diff --git a/apps/cli/internal/handlers/validate_test.go b/apps/cli/internal/handlers/validate_test.go index a17a420f..6a14a31e 100644 --- a/apps/cli/internal/handlers/validate_test.go +++ b/apps/cli/internal/handlers/validate_test.go @@ -81,10 +81,11 @@ func (s *ValidateHandlerTestSuite) Test_context_cancellation_returns_error() { StreamBlueprintValidationEventsFn: func( _ context.Context, _ string, + _ string, streamTo chan<- types.BlueprintValidationEvent, _ chan<- error, ) error { - // Don't close the channel — let the context cancel + // The channel is left open so the context cancellation ends it. return nil }, } @@ -106,6 +107,7 @@ func (s *ValidateHandlerTestSuite) Test_error_from_error_channel_propagates() { StreamBlueprintValidationEventsFn: func( _ context.Context, _ string, + _ string, _ chan<- types.BlueprintValidationEvent, errChan chan<- error, ) error { diff --git a/apps/cli/internal/testutils/mock_deploy_engine.go b/apps/cli/internal/testutils/mock_deploy_engine.go index 489344ce..4afa5126 100644 --- a/apps/cli/internal/testutils/mock_deploy_engine.go +++ b/apps/cli/internal/testutils/mock_deploy_engine.go @@ -2,14 +2,22 @@ package testutils import ( "context" + "time" "github.com/newstack-cloud/bluelink/libs/blueprint-state/manage" + "github.com/newstack-cloud/bluelink/libs/blueprint/container" "github.com/newstack-cloud/bluelink/libs/blueprint/state" "github.com/newstack-cloud/bluelink/libs/deploy-engine-client/types" ) // MockDeployEngine is a test double for engine.DeployEngine. // Set the fields to control return values and inject errors. +// +// The create and destroy calls answer with a response wrapper carrying a +// LastEventID alongside the resource, because that is what the engine returns +// and what a caller has to pass on to the matching stream call. The *Result +// fields hold the resource, and the wrapper is built around it, so a test +// setting one does not have to know the wrapper exists. type MockDeployEngine struct { CreateBlueprintValidationResult *manage.BlueprintValidation CreateBlueprintValidationErr error @@ -20,7 +28,7 @@ type MockDeployEngine struct { // StreamBlueprintValidationEventsFn allows full control over the streaming behaviour. // If set, it is called directly; otherwise the default implementation // sends StubValidationEvents to the streamTo channel and then closes it. - StreamBlueprintValidationEventsFn func(ctx context.Context, validationID string, streamTo chan<- types.BlueprintValidationEvent, errChan chan<- error) error + StreamBlueprintValidationEventsFn func(ctx context.Context, validationID string, lastEventID string, streamTo chan<- types.BlueprintValidationEvent, errChan chan<- error) error StreamBlueprintValidationErr error StubValidationEvents []types.BlueprintValidationEvent @@ -30,7 +38,7 @@ type MockDeployEngine struct { GetChangesetResult *manage.Changeset GetChangesetErr error - StreamChangeStagingEventsFn func(ctx context.Context, changesetID string, streamTo chan<- types.ChangeStagingEvent, errChan chan<- error) error + StreamChangeStagingEventsFn func(ctx context.Context, changesetID string, lastEventID string, streamTo chan<- types.ChangeStagingEvent, errChan chan<- error) error StreamChangeStagingErr error CreateBlueprintInstanceResult *state.InstanceState @@ -42,22 +50,41 @@ type MockDeployEngine struct { GetBlueprintInstanceResult *state.InstanceState GetBlueprintInstanceErr error + ListBlueprintInstancesResult state.ListInstancesResult + ListBlueprintInstancesErr error + GetBlueprintInstanceExportsResult map[string]*state.ExportState GetBlueprintInstanceExportsErr error DestroyBlueprintInstanceResult *state.InstanceState DestroyBlueprintInstanceErr error - StreamBlueprintInstanceEventsFn func(ctx context.Context, instanceID string, streamTo chan<- types.BlueprintInstanceEvent, errChan chan<- error) error + StreamBlueprintInstanceEventsFn func(ctx context.Context, instanceID string, lastEventID string, streamTo chan<- types.BlueprintInstanceEvent, errChan chan<- error) error StreamBlueprintInstanceErr error + + // LastEventID is returned on every create and destroy response, so a test + // can assert that it reaches the stream call that should carry it. + LastEventID string + + CleanupOperationResult *manage.CleanupOperation + CleanupErr error + + ApplyReconciliationResult *container.ApplyReconciliationResult + ApplyReconciliationErr error } func (m *MockDeployEngine) CreateBlueprintValidation( _ context.Context, _ *types.CreateBlueprintValidationPayload, _ *types.CreateBlueprintValidationQuery, -) (*manage.BlueprintValidation, error) { - return m.CreateBlueprintValidationResult, m.CreateBlueprintValidationErr +) (*types.BlueprintValidationResponse, error) { + if m.CreateBlueprintValidationErr != nil { + return nil, m.CreateBlueprintValidationErr + } + return &types.BlueprintValidationResponse{ + LastEventID: m.LastEventID, + Data: m.CreateBlueprintValidationResult, + }, nil } func (m *MockDeployEngine) GetBlueprintValidation(_ context.Context, _ string) (*manage.BlueprintValidation, error) { @@ -67,11 +94,12 @@ func (m *MockDeployEngine) GetBlueprintValidation(_ context.Context, _ string) ( func (m *MockDeployEngine) StreamBlueprintValidationEvents( ctx context.Context, validationID string, + lastEventID string, streamTo chan<- types.BlueprintValidationEvent, errChan chan<- error, ) error { if m.StreamBlueprintValidationEventsFn != nil { - return m.StreamBlueprintValidationEventsFn(ctx, validationID, streamTo, errChan) + return m.StreamBlueprintValidationEventsFn(ctx, validationID, lastEventID, streamTo, errChan) } if m.StreamBlueprintValidationErr != nil { return m.StreamBlueprintValidationErr @@ -85,12 +113,21 @@ func (m *MockDeployEngine) StreamBlueprintValidationEvents( return nil } -func (m *MockDeployEngine) CleanupBlueprintValidations(_ context.Context) error { - return nil +func (m *MockDeployEngine) CleanupBlueprintValidations(_ context.Context) (*manage.CleanupOperation, error) { + return m.CleanupOperationResult, m.CleanupErr } -func (m *MockDeployEngine) CreateChangeset(_ context.Context, _ *types.CreateChangesetPayload) (*manage.Changeset, error) { - return m.CreateChangesetResult, m.CreateChangesetErr +func (m *MockDeployEngine) CreateChangeset( + _ context.Context, + _ *types.CreateChangesetPayload, +) (*types.ChangesetResponse, error) { + if m.CreateChangesetErr != nil { + return nil, m.CreateChangesetErr + } + return &types.ChangesetResponse{ + LastEventID: m.LastEventID, + Data: m.CreateChangesetResult, + }, nil } func (m *MockDeployEngine) GetChangeset(_ context.Context, _ string) (*manage.Changeset, error) { @@ -100,51 +137,122 @@ func (m *MockDeployEngine) GetChangeset(_ context.Context, _ string) (*manage.Ch func (m *MockDeployEngine) StreamChangeStagingEvents( ctx context.Context, changesetID string, + lastEventID string, streamTo chan<- types.ChangeStagingEvent, errChan chan<- error, ) error { if m.StreamChangeStagingEventsFn != nil { - return m.StreamChangeStagingEventsFn(ctx, changesetID, streamTo, errChan) + return m.StreamChangeStagingEventsFn(ctx, changesetID, lastEventID, streamTo, errChan) } return m.StreamChangeStagingErr } -func (m *MockDeployEngine) CleanupChangesets(_ context.Context) error { - return nil +func (m *MockDeployEngine) CleanupChangesets(_ context.Context) (*manage.CleanupOperation, error) { + return m.CleanupOperationResult, m.CleanupErr } -func (m *MockDeployEngine) CreateBlueprintInstance(_ context.Context, _ *types.BlueprintInstancePayload) (*state.InstanceState, error) { - return m.CreateBlueprintInstanceResult, m.CreateBlueprintInstanceErr +func (m *MockDeployEngine) CreateBlueprintInstance( + _ context.Context, + _ *types.BlueprintInstancePayload, +) (*types.BlueprintInstanceResponse, error) { + if m.CreateBlueprintInstanceErr != nil { + return nil, m.CreateBlueprintInstanceErr + } + return m.instanceResponse(m.CreateBlueprintInstanceResult), nil } -func (m *MockDeployEngine) UpdateBlueprintInstance(_ context.Context, _ string, _ *types.BlueprintInstancePayload) (*state.InstanceState, error) { - return m.UpdateBlueprintInstanceResult, m.UpdateBlueprintInstanceErr +func (m *MockDeployEngine) UpdateBlueprintInstance( + _ context.Context, + _ string, + _ *types.BlueprintInstancePayload, +) (*types.BlueprintInstanceResponse, error) { + if m.UpdateBlueprintInstanceErr != nil { + return nil, m.UpdateBlueprintInstanceErr + } + return m.instanceResponse(m.UpdateBlueprintInstanceResult), nil } func (m *MockDeployEngine) GetBlueprintInstance(_ context.Context, _ string) (*state.InstanceState, error) { return m.GetBlueprintInstanceResult, m.GetBlueprintInstanceErr } +func (m *MockDeployEngine) ListBlueprintInstances( + _ context.Context, + _ state.ListInstancesParams, +) (state.ListInstancesResult, error) { + return m.ListBlueprintInstancesResult, m.ListBlueprintInstancesErr +} + func (m *MockDeployEngine) GetBlueprintInstanceExports(_ context.Context, _ string) (map[string]*state.ExportState, error) { return m.GetBlueprintInstanceExportsResult, m.GetBlueprintInstanceExportsErr } -func (m *MockDeployEngine) DestroyBlueprintInstance(_ context.Context, _ string, _ *types.DestroyBlueprintInstancePayload) (*state.InstanceState, error) { - return m.DestroyBlueprintInstanceResult, m.DestroyBlueprintInstanceErr +func (m *MockDeployEngine) DestroyBlueprintInstance( + _ context.Context, + _ string, + _ *types.DestroyBlueprintInstancePayload, +) (*types.BlueprintInstanceResponse, error) { + if m.DestroyBlueprintInstanceErr != nil { + return nil, m.DestroyBlueprintInstanceErr + } + return m.instanceResponse(m.DestroyBlueprintInstanceResult), nil } func (m *MockDeployEngine) StreamBlueprintInstanceEvents( ctx context.Context, instanceID string, + lastEventID string, streamTo chan<- types.BlueprintInstanceEvent, errChan chan<- error, ) error { if m.StreamBlueprintInstanceEventsFn != nil { - return m.StreamBlueprintInstanceEventsFn(ctx, instanceID, streamTo, errChan) + return m.StreamBlueprintInstanceEventsFn(ctx, instanceID, lastEventID, streamTo, errChan) } return m.StreamBlueprintInstanceErr } -func (m *MockDeployEngine) CleanupEvents(_ context.Context) error { - return nil +func (m *MockDeployEngine) CleanupEvents(_ context.Context) (*manage.CleanupOperation, error) { + return m.CleanupOperationResult, m.CleanupErr +} + +func (m *MockDeployEngine) CleanupReconciliationResults(_ context.Context) (*manage.CleanupOperation, error) { + return m.CleanupOperationResult, m.CleanupErr +} + +func (m *MockDeployEngine) GetCleanupOperation( + _ context.Context, + _ manage.CleanupType, + _ string, +) (*manage.CleanupOperation, error) { + return m.CleanupOperationResult, m.CleanupErr +} + +func (m *MockDeployEngine) WaitForCleanupCompletion( + _ context.Context, + _ manage.CleanupType, + _ string, + _ time.Duration, +) (*manage.CleanupOperation, error) { + return m.CleanupOperationResult, m.CleanupErr +} + +func (m *MockDeployEngine) ApplyReconciliation( + _ context.Context, + _ string, + _ *types.ApplyReconciliationPayload, +) (*container.ApplyReconciliationResult, error) { + return m.ApplyReconciliationResult, m.ApplyReconciliationErr +} + +// instanceResponse wraps an instance in the response shape the engine returns. +// +// Data is a value rather than a pointer there, so a nil result -- which is what +// a test that only cares about the error leaves behind -- becomes the zero +// instance rather than a panic. +func (m *MockDeployEngine) instanceResponse(instance *state.InstanceState) *types.BlueprintInstanceResponse { + response := &types.BlueprintInstanceResponse{LastEventID: m.LastEventID} + if instance != nil { + response.Data = *instance + } + return response } diff --git a/apps/cli/internal/tui/shared/footer.go b/apps/cli/internal/tui/shared/footer.go new file mode 100644 index 00000000..b0f90234 --- /dev/null +++ b/apps/cli/internal/tui/shared/footer.go @@ -0,0 +1,27 @@ +package shared + +import ( + "strings" + + stylespkg "github.com/newstack-cloud/deploy-cli-sdk/styles" +) + +// KeyHint represents a keyboard shortcut hint for footer navigation. +type KeyHint struct { + Key string + Desc string +} + +// RenderFooter renders a row of key hints using the Key and Muted styles. +func RenderFooter(s *stylespkg.Styles, hints []KeyHint) string { + var sb strings.Builder + sb.WriteString(" ") + for i, h := range hints { + if i > 0 { + sb.WriteString(" ") + } + sb.WriteString(s.Key.Render(h.Key)) + sb.WriteString(s.Muted.Render(" " + h.Desc)) + } + return sb.String() +} diff --git a/apps/cli/internal/tui/validateui/commands.go b/apps/cli/internal/tui/validateui/commands.go index d449f33e..4864e77c 100644 --- a/apps/cli/internal/tui/validateui/commands.go +++ b/apps/cli/internal/tui/validateui/commands.go @@ -42,13 +42,16 @@ func startValidateStreamCmd(model ValidateModel, logger *zap.Logger) tea.Cmd { &types.CreateBlueprintValidationQuery{}, ) if err != nil { - time.Sleep(10 * time.Second) return ValidateErrMsg{engine.SimplifyError(err, logger)} } + // LastEventID is exclusive and comes from the create call, so the + // stream starts after whatever had already happened by then rather + // than replaying it. err = model.engine.StreamBlueprintValidationEvents( context.TODO(), - blueprintValidation.ID, + blueprintValidation.Data.ID, + blueprintValidation.LastEventID, model.resultStream, model.errStream, ) diff --git a/apps/cli/internal/tui/validateui/validate_model.go b/apps/cli/internal/tui/validateui/validate_model.go index 54b1f5f8..08f570ec 100644 --- a/apps/cli/internal/tui/validateui/validate_model.go +++ b/apps/cli/internal/tui/validateui/validate_model.go @@ -9,9 +9,9 @@ import ( "github.com/charmbracelet/bubbles/spinner" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" - "github.com/newstack-cloud/celerity/apps/cli/internal/engine" bpcore "github.com/newstack-cloud/bluelink/libs/blueprint/core" "github.com/newstack-cloud/bluelink/libs/deploy-engine-client/types" + "github.com/newstack-cloud/celerity/apps/cli/internal/engine" "go.uber.org/zap" ) diff --git a/go.work b/go.work index 813ad429..485da6bd 100644 --- a/go.work +++ b/go.work @@ -1,6 +1,6 @@ -go 1.26.0 +go 1.26.4 -toolchain go1.26.0 +toolchain go1.26.4 use ( ./apps/cli diff --git a/go.work.sum b/go.work.sum index ab4df104..618a9ca9 100644 --- a/go.work.sum +++ b/go.work.sum @@ -1,72 +1,661 @@ +atomicgo.dev/cursor v0.2.0/go.mod h1:Lr4ZJB3U7DfPPOkbH7/6TOtJ4vFGHlgj1nc+n900IpU= +atomicgo.dev/keyboard v0.2.9/go.mod h1:BC4w9g00XkxH/f1HXhW2sXmJFOCWbKn9xrOunSFtExQ= +atomicgo.dev/schedule v0.1.0/go.mod h1:xeUa3oAkiuHYh8bKiQBRojqAMq3PXXbJujjb0hw8pEU= +cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw= +cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.112.2/go.mod h1:iEqjp//KquGIJV/m+Pk3xecgKNhV+ry+vVTsy4TbDms= +cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= +cloud.google.com/go/accessapproval v1.13.0/go.mod h1:7bmInw17bQX+ZPi7YmReC3xKymDrMmxXaUnaI6zQOqI= +cloud.google.com/go/accesscontextmanager v1.15.0/go.mod h1:YjW9urferk8i9ALwBF3bmdcogZeQYRn2yWwR8nkhsBc= +cloud.google.com/go/aiplatform v1.126.0/go.mod h1:iR3za3evdprLe1XL2pLu0cYVCuTbc87QG0pgvcgiJlE= +cloud.google.com/go/analytics v0.35.0/go.mod h1:V9Qef2N0y8GDqQ9FTlmM2XpDEMYonZJRPSUNGZlPCcc= +cloud.google.com/go/apigateway v1.13.0/go.mod h1:pvEpOuuOIw2ev9VCcOyVkDXHHL4lvgMuqIe7XjJ8JoU= +cloud.google.com/go/apigeeconnect v1.12.0/go.mod h1:mYJekCKZHc2ia5yZX5lwtexTn9CzsOfb6+sh/2hi42Q= +cloud.google.com/go/apigeeregistry v1.1.0/go.mod h1:4ZFhQlxMuyfDMz9ORDSV8FPZtf2yPQkKjigsFtrrE4Y= +cloud.google.com/go/appengine v1.15.0/go.mod h1:/8gGZsOX5GDjOo4mAWk8IV59p2991dxTbEtKIlhDjzU= +cloud.google.com/go/area120 v0.15.0/go.mod h1:jD1fw9W4xxIZMY68g7PpbCPleoeGddFs5jPcdhfg3+Y= +cloud.google.com/go/artifactregistry v1.26.0/go.mod h1:c5FPi5GtDBP+OAr5kKhCBNQDT9ZgAyobXQjekx93VWs= +cloud.google.com/go/asset v1.28.0/go.mod h1:Pnvjhay8/FgodOH9uJC8OkfJfRtSnNIIU4WSxg5JfJw= +cloud.google.com/go/assuredworkloads v1.19.0/go.mod h1:/UGGtFCMokM3sGJ4FxjfmLvvFpPa5I/Oz68mwk4Su+0= +cloud.google.com/go/auth v0.3.0/go.mod h1:lBv6NKTWp8E3LPzmO1TbiiRKc4drLOfHsgmlH9ogv5w= +cloud.google.com/go/auth v0.16.4/go.mod h1:j10ncYwjX/g3cdX7GpEzsdM+d+ZNsXAbb6qXA7p1Y5M= +cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M= +cloud.google.com/go/auth v0.20.0/go.mod h1:942/yi/itH1SsmpyrbnTMDgGfdy2BUqIKyd0cyYLc5Q= +cloud.google.com/go/auth v0.24.1-0.20261001053825-dbc26066f70a/go.mod h1:1dmBXa9xfBvBr39ZnDUDkaaA91ccq9CcqENDgJA4d7c= +cloud.google.com/go/auth/oauth2adapt v0.2.2/go.mod h1:wcYjgpZI9+Yu7LyYBg4pqSiaRkfEK3GQcpb7C/uyF1Q= +cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= +cloud.google.com/go/auth/oauth2adapt v0.3.0/go.mod h1:7+2uCm7++XFO+/lN06c2HXpDXb/NMNn2/UwyBPbTnkk= +cloud.google.com/go/automl v1.21.0/go.mod h1:MNbhUevuECzM3jqSOM7hmOedOdRJkm8xbbXW44SU15U= +cloud.google.com/go/baremetalsolution v1.10.0/go.mod h1:xhhT9VQiKPFd2fUs4oeDSRrxV0sb0PGeVmuZoUE2cBA= +cloud.google.com/go/batch v1.20.0/go.mod h1:ABT/5QqsIDsONa+n/8C7XYPjwh/kjOEPXukcRTaMsCg= +cloud.google.com/go/beyondcorp v1.8.0/go.mod h1:aVxzwamO8H4GXWQHowBAmL0KYNfYpW4E6Do2wfP0RYs= +cloud.google.com/go/bigquery v1.79.0/go.mod h1:QTt5tgZxqqvZs3dOZKpvriGqy+CdvY9LyetirFZRPOE= +cloud.google.com/go/bigtable v1.47.0/go.mod h1:GUM6PdkG3rrDse9kugqvX5+ktwo3ldfLtLi1VFn5Wj4= +cloud.google.com/go/billing v1.26.0/go.mod h1:axqDO1uHegh7u5qngkTfqN1djAeLGsWAFAblERgmgEk= +cloud.google.com/go/binaryauthorization v1.16.0/go.mod h1:E+iC5Avu4pdItdzGiSGHnh6TfQrl+KmPxDDg/T/VuHs= +cloud.google.com/go/certificatemanager v1.15.0/go.mod h1:8dfGG2/TbUpCNqsCF/TIMOGV0OVvU6nhkZWTU4MmCXU= +cloud.google.com/go/channel v1.27.0/go.mod h1:9ekufBLXuQ6j1oyqtDSIp29qWU5EwCi8WUi9qkLn3MA= +cloud.google.com/go/cloudbuild v1.32.0/go.mod h1:mYgcM8CMaPmAnO7GxSQ9ADAxVRwS+1b7s6WVkt29OXY= +cloud.google.com/go/clouddms v1.14.0/go.mod h1:qSwET2Q27cJ4wCDsPsbkagXqQqkWfOy+gU3RjMsT/c8= +cloud.google.com/go/cloudtasks v1.18.0/go.mod h1:3KeCxwtGEyaySL7CR3lMmEa2I4mq1ynXdgmfNiO4RYE= +cloud.google.com/go/compute v1.62.0/go.mod h1:Xm6PbsLgBpAg4va77ljbBdpMjzuU+uPp5Ze2dnZq7lw= +cloud.google.com/go/compute v1.63.0 h1:KsBourH0wajM4RhzwPwRMKbxHVdvzGsk7StvACoWXD8= +cloud.google.com/go/compute v1.63.0/go.mod h1:Xm6PbsLgBpAg4va77ljbBdpMjzuU+uPp5Ze2dnZq7lw= cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= -github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= +cloud.google.com/go/compute/metadata v0.8.0/go.mod h1:sYOGTp851OV9bOFJ9CH7elVvyzopvWQFNNghtDQ/Biw= +cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= +cloud.google.com/go/compute/metadata v0.10.0/go.mod h1:rGFHRrIif570kSibjFTMbt6/4/tzgJWFGI/HVol4GIk= +cloud.google.com/go/contactcenterinsights v1.23.0/go.mod h1:uB/kygbfYH/gWEq3NEgq3QRI7/MvpjFyX81ajcW5YAI= +cloud.google.com/go/container v1.51.0/go.mod h1:EvqoT2eXfxLweXXUlhAMGR0sOAB00XPzEjoL01esSDs= +cloud.google.com/go/containeranalysis v0.19.0/go.mod h1:Zq0XHzUIa0oTa7H6aSR8HWqeJnoRI9syUcYJzfozjZQ= +cloud.google.com/go/datacatalog v1.33.0/go.mod h1:/EMN04S73fZcPdtNg86VYLDrhi2HheMehQtMCS86Klk= +cloud.google.com/go/dataflow v0.16.0/go.mod h1:BWhSrIGmsMfuYj3J+nJ2Tw7tplRR6r28kvRiqCD3WlQ= +cloud.google.com/go/dataform v1.2.0/go.mod h1:Lhkjd6L04/nBqsEo7S9Tx7D+Vm0pDDDZuKczewAJuX0= +cloud.google.com/go/datafusion v1.14.0/go.mod h1:2z+uDUKkLPacNNos5lW1Jf1IRDoFyeE+glJ4hmxF2Uc= +cloud.google.com/go/datalabeling v0.15.0/go.mod h1:H8WSRKD9XYCDXDlZE3bPgvV7UYI0F05e+ufKev2AFc8= +cloud.google.com/go/dataplex v1.36.0/go.mod h1:ftgNMXBt+wJ4wPVNvYJ3UY3VTZtKS/i/uFEQppaEbKk= +cloud.google.com/go/dataproc/v2 v2.25.0/go.mod h1:hkiM6kzc8CwLGoquMN1oghyhuI1fE0girmChH4h9W7w= +cloud.google.com/go/dataqna v0.13.0/go.mod h1:XiVVFTOEJLBSvm3ILbyjXngGQYpjb/66MSksqz/56fs= +cloud.google.com/go/datastore v1.25.0/go.mod h1:jvJVNe+S2nHVIndV1H/B4s9K3MLsTMqOKlxSrzHTxB4= +cloud.google.com/go/datastream v1.21.0/go.mod h1:z9AlkQGdXqkeyO5HE+D6sYbOkLJYB4BCZpXFPX/1Vpo= +cloud.google.com/go/deploy v1.33.0/go.mod h1:QdF3plD8D5gV2RmkTXBB6cHrq490WlpFr1SChdOJO2Y= +cloud.google.com/go/dialogflow v1.84.0/go.mod h1:OU8Lj1aw5Vr2hl9ifW+vsKnc2b4iJH+41U7nZ4whg3U= +cloud.google.com/go/dlp v1.34.0/go.mod h1:+haQd/n0QTv5BK7wZnCk2qctd5sfKL50jjh9E6N0d/Q= +cloud.google.com/go/documentai v1.49.0/go.mod h1:VyQA+SxPnCPlVLSJ5UcFx+LQm8JCzK7uUXdkOaAHvG8= +cloud.google.com/go/domains v0.16.0/go.mod h1:O5AhaEyUAgZC2X4M10nSu3dQt2cJLtbjhtrNrdeSPF8= +cloud.google.com/go/edgecontainer v1.10.0/go.mod h1:g4xb11IzVWa9peXNTlnNguKP8uJVvMK4zZeDlGS2Wus= +cloud.google.com/go/errorreporting v0.9.0/go.mod h1:V7ojx7z76JITDZNGyDNkIIa9nNEkQzF6Yj+VHl2YF84= +cloud.google.com/go/essentialcontacts v1.12.0/go.mod h1:W8fTL17jP6vmsPHQaCT5rOjWGohEssuqDUroxnjST0A= +cloud.google.com/go/eventarc v1.25.0/go.mod h1:ncY2NKHKiX+sUjIfxVozrivvmJQ4HWo2znxms7AxlP8= +cloud.google.com/go/filestore v1.16.0/go.mod h1:szr35omqptDEuXgBbJ8PdVdYM3lf/Md96kNufWr1tVs= +cloud.google.com/go/firestore v1.24.0/go.mod h1:5aojyjN4olKUnBZDCRWwM+NsdrrCX3t1qfyERZGOonM= +cloud.google.com/go/functions v1.25.0/go.mod h1:b/tqakoKeAkj9RspEjqswWf5299Lkz9C/742QUD3OEk= +cloud.google.com/go/gkebackup v1.14.0/go.mod h1:kaD4l/s0ONcb3L9iHC8PzG1XkC5ggPwA/KAl6yAyQGs= +cloud.google.com/go/gkeconnect v1.0.0/go.mod h1:5iWSBQzMIRLwUHUWVhxxcNK45ZPE8ntyBgE0MkavlqQ= +cloud.google.com/go/gkehub v0.22.0/go.mod h1:WiXX1w9ZHwKZVUDwL//YQfjfWS7yE0I/ym3smZn9iwE= +cloud.google.com/go/gkemulticloud v1.12.0/go.mod h1:vLNCxGah7pPIoNSX4Yx+hb8klqA0lzzXTWBSut9KzRo= +cloud.google.com/go/grafeas v0.3.17/go.mod h1:MLYFFap01tm1Rbcd0AT6V2NW1ho45dbX+AxNEcprExY= +cloud.google.com/go/gsuiteaddons v1.12.0/go.mod h1:rm/XT7wmwOFGn7jmWtVV65QmZCakzTbHLSojIC4Hskg= +cloud.google.com/go/iam v1.5.2/go.mod h1:SE1vg0N81zQqLzQEwxL2WI6yhetBdbNQuTvIKCSkUHE= +cloud.google.com/go/iam v1.5.3/go.mod h1:MR3v9oLkZCTlaqljW6Eb2d3HGDGK5/bDv93jhfISFvU= +cloud.google.com/go/iam v1.11.0/go.mod h1:KP+nKGugNJW4LcLx1uEZcq1ok5sQHFaQehQNl4QDgV4= +cloud.google.com/go/iam v1.12.0/go.mod h1:FEZ4lXpADAC2AIpQY7LANNjjwyQ2jK439CI2VaD+sLY= +cloud.google.com/go/iap v1.17.0/go.mod h1:b+r+yjrss2WmAEzNrQQjlEdD5E9B8c47mOF7XnqT+z0= +cloud.google.com/go/ids v1.11.0/go.mod h1:+drdvU0pQ4x5uYiWCv364VOeIpTN/PETBrdR51D4Tjk= +cloud.google.com/go/iot v1.13.0/go.mod h1:62W4n2fe/Ct66NWJEfCB5suZ3XsL5Atx+MxFjScr+9s= +cloud.google.com/go/kms v1.32.0/go.mod h1:CSGvW6GnMQbY+1nOHcIzhMtHSbExXlOmCKjWtYVjcpA= +cloud.google.com/go/language v1.18.0/go.mod h1:xSeiVB4UiA9wYmFy2GWjf1Mb1K3uR1Yi/80qoqTxH04= +cloud.google.com/go/lifesciences v0.16.0/go.mod h1:axEwGa3A63+vCXIis+0Zkseu8KecqtNoSn7x0zyjJfM= +cloud.google.com/go/logging v1.18.0/go.mod h1:ZGKnpBaURITh+g/uom2VhbiFoFWvejcrHPDhxFtU/gI= +cloud.google.com/go/longrunning v0.5.6/go.mod h1:vUaDrWYOMKRuhiv6JBnn49YxCPz2Ayn9GqyjaBT8/mA= +cloud.google.com/go/longrunning v1.0.0/go.mod h1:8nqFBPOO1U/XkhWl0I19AMZEphrHi73VNABIpKYaTwM= +cloud.google.com/go/managedidentities v1.13.0/go.mod h1:lUYH5r6QEJTHqjgga0WFeiieqJ0iRwEuQSk20O41Vj0= +cloud.google.com/go/maps v1.37.0/go.mod h1:oalKFBmf2eHmdr3OvfEiiBlOakNlVitYYEPcM3TTUB4= +cloud.google.com/go/mediatranslation v0.13.0/go.mod h1:kjZrowuigFr+Bf1HM1TCtp1a3E3kfG1ovPK5VEuaNAQ= +cloud.google.com/go/memcache v1.17.0/go.mod h1:QQpFWgJvrFaQ6DgmitHejdbkLg8SJfHg5BzltKEWSt0= +cloud.google.com/go/metastore v1.20.0/go.mod h1:/bhZoizjM5iOrqWJeAFDw7c16C783wEftqofnJgKKYI= +cloud.google.com/go/monitoring v1.24.2/go.mod h1:x7yzPWcgDRnPEv3sI+jJGBkwl5qINf+6qY4eq0I9B4U= +cloud.google.com/go/monitoring v1.24.3/go.mod h1:nYP6W0tm3N9H/bOw8am7t62YTzZY+zUeQ+Bi6+2eonI= +cloud.google.com/go/monitoring v1.29.0/go.mod h1:72NOVjJXHY/HBfoLT0+qlCZBT059+9VXLeAnL2PeeVM= +cloud.google.com/go/monitoring v1.30.0/go.mod h1:htlUR0QWVMrjFzZmN4LGnMAve9xB/eduwjmINxVZ8RM= +cloud.google.com/go/networkconnectivity v1.27.0/go.mod h1:pCnczH2W/cnLSlnsnN+VzBoXlM81ZoUGuuacFBGThyw= +cloud.google.com/go/networkmanagement v1.30.0/go.mod h1:3SBf5T7jyGzw5jqJWE7TUDRhIl2E029jggbeoFEgt5E= +cloud.google.com/go/networksecurity v0.19.0/go.mod h1:VWDFX+stDgzZYDsCX1Wy/JO9Tlw7g/V1UHbiORVgqq0= +cloud.google.com/go/notebooks v1.18.0/go.mod h1:fXU6A3TJ2YobFy6fxOr4tKZZ8QgTjdJAqDIykOB85Gk= +cloud.google.com/go/optimization v1.12.0/go.mod h1:28gzCUmeCLcT4vctGEo71QF4b60TYkKQo5y8Gs2KPq8= +cloud.google.com/go/orchestration v1.17.0/go.mod h1:Lf/Czqh4Jfy3IFpvDkKWjfjkYFI+tj6nAjq5ihivrq4= +cloud.google.com/go/orgpolicy v1.20.0/go.mod h1:9LHqEGx5P5dhansdKTNIEXpM+QbebAIOs66+HUID4aQ= +cloud.google.com/go/osconfig v1.22.0/go.mod h1:bUL0FaSR2ahPcFRRYnd6a0LyUzsQYIdUpBq8Tmxg8fE= +cloud.google.com/go/oslogin v1.18.0/go.mod h1:3Oa36T3781Mv+yCSVYlfasi7auHjfPFqvNOd1q92umc= +cloud.google.com/go/phishingprotection v0.13.0/go.mod h1:2gyYqwNjePPEocXDkDve3EuJPaRqN/E7fp28K3arR0k= +cloud.google.com/go/policytroubleshooter v1.16.0/go.mod h1:FZg3IW3exF6wc9eO/iBYijsGqiiCzc9mjZhsxgATXYA= +cloud.google.com/go/privatecatalog v0.16.0/go.mod h1:Dq1bSHRRaDqFr7Rb7UntXVjh1reeY6YdzYicL0EPTrM= +cloud.google.com/go/pubsub v1.51.0/go.mod h1:NERXf11sd82UV3VnflcUj8POIyQUXT/QwrKlxD8di/I= +cloud.google.com/go/pubsub/v2 v2.6.0/go.mod h1:4anqvV/w8Pcgu2tO0qr2XgsF3GXHowzryfQ5gOnVmWY= +cloud.google.com/go/pubsublite v1.10.0/go.mod h1:o9NVNBY4m8LubZqRCJtBdxpjP8DAsYizsxC6Z1vI7Dk= +cloud.google.com/go/recaptchaenterprise/v2 v2.26.0/go.mod h1:+ntF70/j7qBa6G/pwmYA0mkBcDeTCXV6WDqUL7GObfs= +cloud.google.com/go/recommendationengine v0.15.0/go.mod h1:Yx45rCF3A5fLSeXxSkXOCTXSBDBogrQnR7kUTJHwYxw= +cloud.google.com/go/recommender v1.19.0/go.mod h1:LRh+1HJjLx2kDE3S65AIlG/lvwA0llEFWYPD/QtgoaU= +cloud.google.com/go/redis v1.24.0/go.mod h1:ebtw9WLFKswecHO2ifNykuteNJNwoPqMCHz4UI11kF4= +cloud.google.com/go/resourcemanager v1.16.0/go.mod h1:Hn4HPkLRnTuiUhFEFJg736Brt7BwlS84xYU06sc3STc= +cloud.google.com/go/resourcesettings v1.8.3/go.mod h1:BzgfXFHIWOOmHe6ZV9+r3OWfpHJgnqXy8jqwx4zTMLw= +cloud.google.com/go/retail v1.32.0/go.mod h1:t9w9mBarD59BnFHTST2LoiCP5608ZlEfniHLgA6OoH0= +cloud.google.com/go/run v1.22.0/go.mod h1:Wo0aTNrqfftGmbxPPraeOxSUDUZ2c7IVNg2dk8Qm1Bs= +cloud.google.com/go/scheduler v1.16.0/go.mod h1:0hsZg0MZJADyke1lutI0FHAYJR8Dtm8oIivXkmpACkA= +cloud.google.com/go/secretmanager v1.20.0/go.mod h1:9OmSuOeiiUicANglrbdKWSnT3gYkRcXuUQDk7dDW0zU= +cloud.google.com/go/security v1.26.0/go.mod h1:nd0i5OHXtJduMt0n6UnEojy7fiTfnfj/PSDeD7LAD+c= +cloud.google.com/go/securitycenter v1.45.0/go.mod h1:7mAlzsCsKlEVmciAFORl431laDGpoKGFkSQndAzFs30= +cloud.google.com/go/servicedirectory v1.17.0/go.mod h1:CtgjXS1idj3s9Q6tB68021Rzk8Q6decV6+ldXC1BoBk= +cloud.google.com/go/shell v1.13.0/go.mod h1:9WWf3xHQUElP5fL/lB9IJ/MMMnN2W/T86cBp+pXFFWo= +cloud.google.com/go/spanner v1.91.0/go.mod h1:8NB5a7qgwIhGD19Ly+vkpKffPL78vIG9RcrgsuREha0= +cloud.google.com/go/speech v1.36.0/go.mod h1:tiSA8MiX49o1ngq5Ww2JFTvfjKxtAuBKY/UIH6coCPg= +cloud.google.com/go/storage v1.56.0/go.mod h1:Tpuj6t4NweCLzlNbw9Z9iwxEkrSem20AetIeH/shgVU= +cloud.google.com/go/storage v1.61.3/go.mod h1:JtqK8BBB7TWv0HVGHubtUdzYYrakOQIsMLffZ2Z/HWk= +cloud.google.com/go/storage v1.62.3/go.mod h1:cpYz/kRVZ+UQAF1uHeea10/9ewcRbxGoGNKsS9daSXA= +cloud.google.com/go/storage v1.69.0/go.mod h1:PELYsxTYm2peE4mwLEC1+mS1dA/kUSRUxNv56rOy44g= +cloud.google.com/go/storagetransfer v1.19.0/go.mod h1:sy4ImXynHkm9CKmbILtmzLN36PHh7JOhUTpqXf5SvMs= +cloud.google.com/go/talent v1.14.0/go.mod h1:jieYQngp1YqRtqV2t92w3LTrjuLV05kMM4BZMUUneaw= +cloud.google.com/go/texttospeech v1.22.0/go.mod h1:bAksATiWPKaw8r8wVgANa4GkVdsyFE4y9ulRzKyuJec= +cloud.google.com/go/tpu v1.14.0/go.mod h1:1pggTTG5npfxea6vYjyl60Fg09VgbM7efBgVjnFZjpo= +cloud.google.com/go/translate v1.10.3/go.mod h1:GW0vC1qvPtd3pgtypCv4k4U8B7EdgK9/QEF2aJEUovs= +cloud.google.com/go/translate v1.18.0/go.mod h1:aRVIE+P+7fngk8HwwFAgis5QA7wphGpKrFpdNoWtGCM= +cloud.google.com/go/video v1.33.0/go.mod h1:hEx8TNpQT6kdjMVsywePvT8BCb63Ee3F/R0GRa9wnzo= +cloud.google.com/go/videointelligence v1.17.0/go.mod h1:Phxz7AQpvXoOvz+KrrOZEJRo4CDgYXMDVDqhCtdF1jc= +cloud.google.com/go/vision/v2 v2.15.0/go.mod h1:DUdjdFkXqPvEoPC4WDYFvYCn0LlAZ4vVz29A0bXvW90= +cloud.google.com/go/vmmigration v1.16.0/go.mod h1:ILrSjXnHMpdamkkAU8fjMKKMsH27B6FLC5kv/6TkLy0= +cloud.google.com/go/vmwareengine v1.9.0/go.mod h1:zXXuUaIpvDhsV6sR+JdQfcQ4V5+pDarrp7FW7nOdS2I= +cloud.google.com/go/vpcaccess v1.14.0/go.mod h1:MxbVgr+2fpIFIEIdSmgnb8ykNWRPVtslpmWijp7an68= +cloud.google.com/go/webrisk v1.17.0/go.mod h1:ypwCZ+G/SXyUZ+x3ppxn1hu+6tDifGNd/OpwPtCdJHI= +cloud.google.com/go/websecurityscanner v1.12.0/go.mod h1:cZSc9HqoFdccL1mqZtPIInOd4R8PBGwI20wdnrz6AO8= +cloud.google.com/go/workflows v1.20.0/go.mod h1:TC9yx7VpjGdBBeKM8FG2EMtms5Q9nyTqI+2uV9bDNs4= +codeberg.org/go-fonts/liberation v0.5.0/go.mod h1:zS/2e1354/mJ4pGzIIaEtm/59VFCFnYC7YV6YdGl5GU= +codeberg.org/go-latex/latex v0.1.0/go.mod h1:LA0q/AyWIYrqVd+A9Upkgsb+IqPcmSTKc9Dny04MHMw= +codeberg.org/go-pdf/fpdf v0.10.0/go.mod h1:Y0DGRAdZ0OmnZPvjbMp/1bYxmIPxm0ws4tfoPOc4LjU= +contrib.go.opencensus.io/exporter/stackdriver v0.13.15-0.20230702191903-2de6d2748484/go.mod h1:uxw+4/0SiKbbVSD/F2tk5pJTdVcfIBBcsQ8gwcu4X+E= +git.sr.ht/~sbinet/gg v0.6.0/go.mod h1:uucygbfC9wVPQIfrmwM2et0imr8L7KQWywX0xpFMm94= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.20.0/go.mod h1:YD5h/ldMsG0XiIw7PdyNhLxaM317eFh5yNLccNfGdyw= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.0/go.mod h1:G7QVLxw1j1JVyrO1MA95S8m8HStaaleDZYTcfGgjB2o= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1/go.mod h1:iptorS+VYKFL2N6PnebpS91dubG35eAOEERnT4PJbQU= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.2/go.mod h1:iptorS+VYKFL2N6PnebpS91dubG35eAOEERnT4PJbQU= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.3/go.mod h1:XtxD48QPInqoj+GMlcRlXHEYsoOxFnP6w2JgIZ9rDS4= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1/go.mod h1:IYus9qsFobWIc2YVwe/WPjcnyCkPKtnHAqUYeebc8z0= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0/go.mod h1:q0+UTSRvShwUCrR/s5HtyInYphN7Wvxb7snFM3u+SLA= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1/go.mod h1:oXtinPO4OLj9d1DOTrqrL1oRwGhcqadvAmrl6wTeGlk= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2/go.mod h1:XtLgD3ZD34DAaVIIAyG3objl5DynM3CQ/vMcbBNJZGI= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0/go.mod h1:7Ut2Qw9vcwpLW5Q4MBy43uSxXS7tK2yjs94OJ6j5thE= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal/v3 v3.1.0/go.mod h1:AW8VEadnhw9xox+VaVd9sP7NjzOAnaZBLRH6Tq3cJ38= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0/go.mod h1:5kakwfW5CjC9KK+Q4wjXAg+ShuIm2mBMua0ZFj2C8PE= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4/go.mod h1:8mwH4klAm9DUgR2EEHyEEAQlRDvLPyg5fQry3y+cDew= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.2/go.mod h1:kTkpJchXAdO7LGkKZP97a+Ou8TgaF4NT6MHwOIy5uSQ= +github.com/Azure/azure-sdk-for-go/sdk/storage/internal v0.1.0/go.mod h1:+kX7ahyFelQ42F3RScM2CFgHJljp0phc/FieKLYVpFI= +github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk= +github.com/AzureAD/microsoft-authentication-library-for-go v1.8.0/go.mod h1:Y33QHnf0FfdVewFFISOGe20mkZbxX4H839o955/PoeI= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/GoogleCloudPlatform/grpc-gcp-go/grpcgcp v1.6.0/go.mod h1:I7kE2kM3qCr9QPT4cU4cCFYkEpVyVr16YOGUHzy+nR0= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.27.0/go.mod h1:yAZHSGnqScoU556rBOVkwLze6WP5N+U11RHuWaGVxwY= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0/go.mod h1:RD2SsorTmYhF6HkTmDw7KmPYQk8OBYwTkuasChwv7R4= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.34.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0/go.mod h1:Yj5vHEz/aAepZGliRJsA6uvHAVAQyEwajq9ORCHPxzM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0/go.mod h1:ZPpqegjbE99EPKsu3iUWV22A04wzGPcAY/ziSIQEEgs= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0/go.mod h1:IA1C1U7jO/ENqm/vhi7V9YYpBsp+IMyqNrEN94N7tVc= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.57.0/go.mod h1:8lmpHY+1VRoteiOwyrQMDt1YGXOrFKCz+1wJW7n3ODY= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0/go.mod h1:cSgYe11MCNYunTnRXrKiR/tHc0eoKjICUuWpNZoVCOo= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0/go.mod h1:Mf6O40IAyB9zR/1J8nGDDPirZQQPbYJni8Yisy7NTMc= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.57.0/go.mod h1:YqwkQPrWSC7+byyc1VlKbWLBF5JsW5IoL6xUkemYSXk= +github.com/IBM/sarama v1.50.3/go.mod h1:Jo4MSfdDT3ycmQj7/ab8eLZwnvwCKZm/8H7SCbtyo8U= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= +github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b/go.mod h1:1KcenG0jGWcpt8ov532z81sp/kMMUG485J2InIOyADM= +github.com/alecthomas/chroma/v2 v2.20.0/go.mod h1:e7tViK0xh/Nf4BYHl00ycY6rV7b8iXBksI9E359yNmA= +github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= +github.com/apache/arrow-go/v18 v18.7.0/go.mod h1:PM6IigLJkdMwIpeHXnymo+xZ52f42a9EYiLtRel4p/A= +github.com/apache/arrow/go/v15 v15.0.2/go.mod h1:DGXsR3ajT524njufqf95822i+KTh+yea1jass9YXgjA= +github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= +github.com/aws/aws-sdk-go-v2 v1.41.6/go.mod h1:dy0UzBIfwSeot4grGvY1AqFWN5zgziMmWGzysDnHFcQ= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.9/go.mod h1:uOYhgfgThm/ZyAuJGNQ5YgNyOlYfqnGpTHXvk3cpykg= +github.com/aws/aws-sdk-go-v2/config v1.32.16/go.mod h1:duCCnJEFqpt2RC6no1iK6q+8HpwOAkiUua0pY507dQc= +github.com/aws/aws-sdk-go-v2/credentials v1.19.15/go.mod h1:gJiYyMOjNg8OEdRWOf3CrFQxM2a98qmrtjx1zuiQfB8= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.22/go.mod h1:b+hYdbU+jGKfXE8kKM6g1+h+L/Go3vMvzlxBsiuGsxg= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.22/go.mod h1:6sW9iWm9DK9YRpRGga/qzrzNLgKpT2cIxb7Vo2eNOp0= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.22/go.mod h1:KIpEUx0JuRZLO7U6cbV204cWAEco2iC3l061IxlwLtI= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.23/go.mod h1:7J8iGMdRKk6lw2C+cMIphgAnT8uTwBwNOsGkyOCm80U= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.8/go.mod h1:VsK9abqQeGlzPgUr+isNWzPlK2vKe9INMLWnY65f5Xs= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.14/go.mod h1:yS5rNogD8e0Wu9+l3MUwr6eENBzEeGejvINpN5PAYfY= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.22/go.mod h1:nO6egFBoAaoXze24a2C0NjQCvdpk8OueRoYimvEB9jo= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.22/go.mod h1:ES3ynECd7fYeJIL6+oax+uIEljmfps0S70BaQzbMd/o= +github.com/aws/aws-sdk-go-v2/service/s3 v1.100.0/go.mod h1:Fw9aqhJicIVee1VytBBjH+l+5ov6/PhbtIK/u3rt/ls= +github.com/aws/aws-sdk-go-v2/service/signin v1.0.10/go.mod h1:p6+MXNxW7IA6dMgHfTAzljuwSKD0NCm/4lbS4t6+7vI= +github.com/aws/aws-sdk-go-v2/service/sso v1.30.16/go.mod h1:CudnEVKRtLn0+3uMV0yEXZ+YZOKnAtUJ5DmDhilVnIw= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.20/go.mod h1:JHs8/y1f3zY7U5WcuzoJ/yAYGYtNIVPKLIbp61euvmg= +github.com/aws/aws-sdk-go-v2/service/sts v1.42.0/go.mod h1:pFw33T0WLvXU3rw1WBkpMlkgIn54eCB5FYLhjDc9Foo= +github.com/aws/smithy-go v1.25.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= +github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bits-and-blooms/bitset v1.24.4/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= +github.com/campoy/embedmd v1.0.0/go.mod h1:oxyr9RCiSXg0M3VJ3ks0UGfp98BpSSGr0kpiX3MzVl8= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/census-instrumentation/opencensus-proto v0.4.1/go.mod h1:4T9NM4+4Vw91VeyqjLS6ao50K5bOcLKN6Q42XnYaRYw= +github.com/charmbracelet/glamour v1.0.0/go.mod h1:DSdohgOBkMr2ZQNhw4LZxSGpx3SvpeujNoXrQyH2hxo= github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao= +github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE= +github.com/charmbracelet/x/ansi v0.11.3/go.mod h1:yI7Zslym9tCJcedxz5+WBq+eUGMJT0bM06Fqy1/Y4dI= +github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= +github.com/charmbracelet/x/exp/golden v0.0.0-20240806155701-69247e0abc2a/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= +github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf/go.mod h1:B3UgsnsBZS/eX42BlaNiJkD1pPOUa+oF1IYC6Yd2CEU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/clipperhouse/displaywidth v0.6.1/go.mod h1:R+kHuzaYWFkTm7xoMmK1lFydbci4X2CicfbGstSGg0o= +github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/clipperhouse/uax29/v2 v2.3.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g= +github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/xds/go v0.0.0-20250501225837-2ac532fd4443/go.mod h1:W+zGtBO5Y1IgJhy4+A9GOqVhqLpfZi+vwmdNXUehLA8= +github.com/cncf/xds/go v0.0.0-20251110193048-8bfbf64dc13e/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI= +github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI= +github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4= +github.com/cockroachdb/apd/v3 v3.2.1/go.mod h1:klXJcjp+FffLTHlhIG69tezTDvdP065naDsHzKhYSqc= +github.com/containerd/console v1.0.5/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk= github.com/containerd/typeurl/v2 v2.2.0/go.mod h1:8XOOxnyatxSWuG8OfsZXVnAF4iZfedjS/8UHSPJnX4g= github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= -github.com/docker/docker v27.5.1+incompatible h1:4PYU5dnBYqRQi0294d1FBECqT9ECWeQAIfE8q4YnPY8= -github.com/docker/docker v27.5.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/creasty/defaults v1.8.0/go.mod h1:iGzKe6pbEHnpMPtfDXZEr0NVxWnPTjb1bbDy08fPzYM= +github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/eapache/go-resiliency v1.7.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane/envoy v1.32.4/go.mod h1:Gzjc5k8JcJswLjAx1Zm+wSYE20UrLtt7JZMWiWQXQEw= +github.com/envoyproxy/go-control-plane/envoy v1.36.0/go.mod h1:ty89S1YCCVruQAm9OtKeEkQLTb+Lkz0k8v9W0Oxsv98= +github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU= +github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA= +github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0= +github.com/go-jose/go-jose/v4 v4.0.5/go.mod h1:s3P1lRrkT8igV8D9OjyL4WRyHvjB6a4JSllnOrmmBOA= +github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/goccmack/gocc v1.0.2/go.mod h1:LXX2tFVUggS/Zgx/ICPOr3MLyusuM7EcbfkPvNsjdO8= +github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/goccy/go-yaml v1.17.1/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/golang-jwt/jwt/v4 v4.4.3/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.7.0-rc.1/go.mod h1:s42URUywIqd+OcERslBJvOjepvNymP31m3q8d/GkuRs= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= +github.com/google/flatbuffers v25.12.19+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-pkcs11 v0.3.0/go.mod h1:6eQoGcuNJpa7jnd5pMGdkSaQpNDYvPlXWMcjXXThLlY= +github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= +github.com/google/s2a-go v0.1.11/go.mod h1:pz4tyvwXvJLLbyrkh6FW1eS2zPUXMaTmyNhYtyP2tNw= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/cloud-bigtable-clients-test v0.0.4/go.mod h1:NNHPqSxC2OBSLmt1j/qofCRRzL0OYZxk24CsicIe8MA= +github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0= +github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= +github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8= +github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg= +github.com/googleapis/enterprise-certificate-proxy v0.3.15/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg= +github.com/googleapis/enterprise-certificate-proxy v0.3.17/go.mod h1:rSEsBUemEBZEexP2y6jPp16LUmUbjmSbcPMQizR0o4k= +github.com/googleapis/enterprise-certificate-proxy v0.3.22/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w= +github.com/googleapis/gax-go/v2 v2.12.3/go.mod h1:AKloxT6GtNbaLm8QTNSidHUVsHYcBHwWRvkNFJUQcS4= +github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= +github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY= +github.com/googleapis/gax-go/v2 v2.21.0/go.mod h1:But/NJU6TnZsrLai/xBAQLLz+Hc7fHZJt/hsCz3Fih4= +github.com/googleapis/gax-go/v2 v2.22.0/go.mod h1:irWBbALSr0Sk3qlqb9SyJ1h68WjgeFuiOzI4Rqw5+aY= +github.com/googleapis/gax-go/v2 v2.23.0/go.mod h1:rBQKOVJCdb8IFEzg+FCwlt1LP/xMDGuqUXhUG+XMXEg= +github.com/googleapis/gax-go/v2 v2.26.2/go.mod h1:sMKqnMesnKH+3wiRJROcttA+cJoZoGbZl1vDQ8XYtGk= +github.com/gookit/color v1.6.0/go.mod h1:9ACFc7/1IpHGBW8RwuDm/0YEnhg3dwwXpoMsmtyHfjs= +github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= +github.com/hamba/avro/v2 v2.31.0/go.mod h1:t6lJYAGE5Mswfn17zjtyQsssRQgnqO6TXLBCHHWRqrw= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo= -github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw= -github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs= +github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM= +github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo= +github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs= +github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/keybase/dbus v0.0.0-20220506165403-5aa21ea2c23a/go.mod h1:YPNKjjE7Ubp9dTbnWvsP3HT+hYnY6TfXzubYTBeUxc8= +github.com/klauspost/asmfmt v1.3.2/go.mod h1:AG8TuvYojzulgDAMCnYn50l/5QV3Bs/tp6j0HLHbNSE= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/lithammer/fuzzysearch v1.1.8/go.mod h1:IdqeyBClc3FFqSzYq/MXESsS4S0FsZ5ajtkr5xPLts4= +github.com/lyft/protoc-gen-star/v2 v2.0.4/go.mod h1:amey7yeodaJhXSbf/TlLvWiqQfLOSpEk//mLlc+axEk= +github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/mattn/go-sqlite3 v1.14.28/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA= +github.com/minio/asm2plan9s v0.0.0-20200509001527-cdd76441f9d8/go.mod h1:mC1jAcsrzbxHt8iiaC+zU4b1ylILSosueou12R++wfY= +github.com/minio/c2goasm v0.0.0-20190812172519-36a3d3bbc4f3/go.mod h1:RagcQ7I8IeTMnF8JTXieKnO4Z6JCsikNEzj0DwauVzE= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/montanaflynn/stats v0.7.0/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= +github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/pierrec/lz4/v4 v4.1.28/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= +github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= +github.com/prometheus/client_golang v1.21.1/go.mod h1:U9NM32ykUErtVBxdvD3zfi+EuFkkaBvMb09mIfe0Zgg= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/prometheus/common v0.63.0/go.mod h1:VVFF/fBIoToEnWRVkYoXEkq3R3paCoxG9PXP74SnV18= +github.com/prometheus/procfs v0.16.0/go.mod h1:8veyXUu3nGP7oaCxhX6yeaM5u4stL2FeMXnCqhDthZg= +github.com/pterm/pterm v0.12.83/go.mod h1:xlgc6bFWyJIMtmLJvGim+L7jhSReilOlOnodeIYe4Tk= +github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY= github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPOhJotwFIyu2bBVN41fcDUY= +github.com/spiffe/go-spiffe/v2 v2.5.0/go.mod h1:P+NxobPc6wXhVtINNtFjNWGBTreew1GBUCwT2wPmb7g= +github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs= +github.com/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= +github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= +github.com/stoewer/go-strcase v1.3.1/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/stretchr/testify v1.12.0/go.mod h1:bOYBZb5qJ00vPzWfIqBUZPaxK8jWiXc6d3ErP4Ca9Gw= +github.com/substrait-io/substrait v0.87.0/go.mod h1:MPFNw6sToJgpD5Z2rj0rQrdP/Oq8HG7Z2t3CAEHtkHw= +github.com/substrait-io/substrait-go/v8 v8.1.1/go.mod h1:6GLz9k21udB64g4lLKq8632TKfQCRAVfhuU3NSXtZWY= +github.com/substrait-io/substrait-protobuf/go v0.85.0/go.mod h1:hn+Szm1NmZZc91FwWK9EXD/lmuGBSRTJ5IvHhlG1YnQ= +github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= +github.com/vmihailenco/msgpack/v5 v5.3.5/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc= +github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= +github.com/yuin/goldmark v1.7.13/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= +github.com/yuin/goldmark-emoji v1.0.6/go.mod h1:ukxJDKFpdFb5x0a5HqbdlcKtebh086iJpI31LTKmWuA= +github.com/zclconf/go-cty-debug v0.0.0-20191215020915-b22d67c1ba0b/go.mod h1:ZRKQfBXbGkpdV6QMzT3rU1kSTAnfu1dO8dPKjYprgj8= +github.com/zeebo/errs v1.4.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4= +go.einride.tech/aip v0.83.0/go.mod h1:E8+wdTApA70odnpFzJgsGogHozC2JCIhFJBKPr8bVig= +go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/contrib/detectors/gcp v1.36.0/go.mod h1:IbBN8uAIIx734PTonTPxAxnjc2pQTxWNkwfstZ+6H2k= +go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk= +go.opentelemetry.io/contrib/detectors/gcp v1.43.0/go.mod h1:RyaZMFY7yi1kAs45S6mbFGz8O8rqB0dTY14uzvG4LCs= +go.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s= +go.opentelemetry.io/contrib/detectors/gcp v1.45.0/go.mod h1:VSme3o2fvSg5bVg0dRzyHaj4Z5EVhG+g2Fde6LKzmQA= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0/go.mod h1:Mjt1i1INqiaoZOMGR1RIUJN+i3ChKoFRqzrRQhlkbs0= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0/go.mod h1:Sje3i3MjSPKTSPvVWCaL8ugBzJwik3u4smCjUeuupqg= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0/go.mod h1:p8pYQP+m5XfbZm9fxtSKAbM6oIllS7s2AfxrChvc7iw= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI= +go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo= +go.opentelemetry.io/otel v1.36.0/go.mod h1:/TcFMXYjyRNh8khOAO9ybYkqaDBb/70aVwkNML4pP8E= +go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= go.opentelemetry.io/otel v1.41.0 h1:YlEwVsGAlCvczDILpUXpIpPSL/VPugt7zHThEMLce1c= -go.opentelemetry.io/otel v1.41.0/go.mod h1:Yt4UwgEKeT05QbLwbyHXEwhnjxNO6D8L5PQP51/46dE= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0/go.mod h1:u3T6vz0gh/NVzgDgiwkgLxpsSF6PaPmo2il0apGJbls= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0/go.mod h1:Izur+Wt8gClgMJqO/cZ8wdeeMryJ/xxiOVgFSSfpDTY= +go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= +go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= +go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= +go.opentelemetry.io/otel/exporters/prometheus v0.57.0/go.mod h1:QpFWz1QxqevfjwzYdbMb4Y1NnlJvqSGwyuU0B4iuc9c= +go.opentelemetry.io/otel/metric v1.24.0/go.mod h1:VYhLe1rFfxuTXLgj4CBiyz+9WYBA8pNGJgDcSFRKBco= +go.opentelemetry.io/otel/metric v1.36.0/go.mod h1:zC7Ks+yeyJt4xig9DEw9kuUFe5C3zLbVjV2PzT6qzbs= go.opentelemetry.io/otel/metric v1.41.0 h1:rFnDcs4gRzBcsO9tS8LCpgR0dxg4aaxWlJxCno7JlTQ= -go.opentelemetry.io/otel/metric v1.41.0/go.mod h1:xPvCwd9pU0VN8tPZYzDZV/BMj9CM9vs00GuBjeKhJps= -go.opentelemetry.io/otel/sdk v1.41.0/go.mod h1:ahFdU0G5y8IxglBf0QBJXgSe7agzjE4GiTJ6HT9ud90= -go.opentelemetry.io/otel/sdk/metric v1.41.0/go.mod h1:HNBuSvT7ROaGtGI50ArdRLUnvRTRGniSUZbxiWxSO8Y= +go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= +go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= +go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= +go.opentelemetry.io/otel/sdk v1.36.0/go.mod h1:+lC+mTgD+MUWfjJubi2vvXWcVxyr9rmlshZni72pXeY= +go.opentelemetry.io/otel/sdk v1.41.0 h1:YPIEXKmiAwkGl3Gu1huk1aYWwtpRLeskpV+wPisxBp8= +go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg= +go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= +go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= +go.opentelemetry.io/otel/sdk/metric v1.36.0/go.mod h1:qTNOhFDfKRwX0yXOqJYegL5WRaW376QbB7P4Pb0qva4= +go.opentelemetry.io/otel/sdk/metric v1.41.0 h1:siZQIYBAUd1rlIWQT2uCxWJxcCO7q3TriaMlf08rXw8= +go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A= +go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= +go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA= +go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU= +go.opentelemetry.io/otel/trace v1.36.0/go.mod h1:gQ+OnDZzrybY4k4seLzPAWNwVBBVlF2szhehOBB/tGA= +go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= go.opentelemetry.io/otel/trace v1.41.0 h1:Vbk2co6bhj8L59ZJ6/xFTskY+tGAbOnCtQGVVa9TIN0= -go.opentelemetry.io/otel/trace v1.41.0/go.mod h1:U1NU4ULCoxeDKc09yCWdWe+3QoyweJcISEVa1RBzOis= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= +go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= +go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= +golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc= +golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= +golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA= +golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI= +golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q= +golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8= +golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= +golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= +golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= +golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc= golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM= +golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU= +golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= +golang.org/x/mod v0.39.0 h1:UF5zwQdCRRUpHfyPwr7d4UrGiVeldIsogtzWVnczL74= +golang.org/x/mod v0.39.0/go.mod h1:bvIbwjQ0HUFFf5AKukeeYQG4ZBUG9yxQbR9aEweIwYY= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= +golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg= +golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= +golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= +golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA= +golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= +golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.19.0/go.mod h1:vYi7skDa1x015PmRRYZ7+s1cWyPgrPiSYRe4rnsexc8= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI= +golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/telemetry v0.0.0-20260109210033-bd525da824e2/go.mod h1:b7fPSJ0pKZ3ccUh8gnTONJxhn3c/PS6tyzQvyqw4iA8= +golang.org/x/telemetry v0.0.0-20260811182544-a038080d80e5/go.mod h1:LVehoXe41cL5SCVQilsV7Gg6BNG+Js6P9PhSbYTIUkQ= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q= golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY= +golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY= +golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= +golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU= +golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= +golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= +golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= +golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= +golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= +golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164= +golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4= +golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.11.0/go.mod h1:anzJrxPjNtfgiYQYirP2CPGzGLxrH2u2QBhn6Bf3qY8= golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI= +golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= +golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= +golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY= +golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8= +golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= +gonum.org/v1/plot v0.15.2/go.mod h1:DX+x+DWso3LTha+AdkJEv5Txvi+Tql3KAGkehP0/Ubg= +gonum.org/v1/tools v0.0.0-20200318103217-c168b003ce8c/go.mod h1:fy6Otjqbk477ELp8IXTpw1cObQtLbRCBVonY+bTTfcM= +google.golang.org/api v0.177.0/go.mod h1:srbhue4MLjkjbkux5p3dw/ocYOSZTaIEvf7bCOnFQDw= +google.golang.org/api v0.247.0/go.mod h1:r1qZOPmxXffXg6xS5uhx16Fa/UFY8QU/K4bfKrnvovM= +google.golang.org/api v0.274.0/go.mod h1:JbAt7mF+XVmWu6xNP8/+CTiGH30ofmCmk9nM8d8fHew= +google.golang.org/api v0.276.0/go.mod h1:Fnag/EWUPIcJXuIkP1pjoTgS5vdxlk3eeemL7Do6bvw= +google.golang.org/api v0.278.0/go.mod h1:B9TqLBwJqVjp1mtt7WeoQwWRwvu/400y5lETOql+giQ= +google.golang.org/api v0.280.0/go.mod h1:oGKmPZRDoD3vdkf6MA7F4VNkR1rxCiuaPSkhsf3EolU= +google.golang.org/api v0.287.1/go.mod h1:lM2kYRzYUCBY91P9h6VF1PYmvhxii3O5hji37qRvIcY= +google.golang.org/api v0.288.0/go.mod h1:lM2kYRzYUCBY91P9h6VF1PYmvhxii3O5hji37qRvIcY= +google.golang.org/api v0.301.0/go.mod h1:gGUTaOjgsaG/KNyyW1tFO+DSFm3EJw4BwyehlcmDCXs= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= +google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I= +google.golang.org/genproto v0.0.0-20260519071638-aa98bba5eb94/go.mod h1:RRHjglSYABVCWpQ7USCpdfhcd9t4PkajvVwyynZizTc= +google.golang.org/genproto v0.0.0-20260715232425-e75dac1f907d/go.mod h1:Wz2wFJntZFmLGo7pLDXZ3wYk5hyc0Mb+SkHhDDXT+lU= +google.golang.org/genproto/googleapis/api v0.0.0-20240429193739-8cf5692501f6/go.mod h1:10yRODfgim2/T8csjQsMPgZOMvtytXKTDRzH6HRGzRw= +google.golang.org/genproto/googleapis/api v0.0.0-20250721164621-a45f3dfb1074/go.mod h1:vYFwMYFbmA8vl6Z/krj/h7+U/AqpHknwJX4Uqgfyc7I= +google.golang.org/genproto/googleapis/api v0.0.0-20250804133106-a7a43d27e69b/go.mod h1:oDOGiMSXHL4sDTJvFvIB9nRQCGdLP1o/iVaqQK8zB+M= +google.golang.org/genproto/googleapis/api v0.0.0-20251029180050-ab9386a59fda/go.mod h1:fDMmzKV90WSg1NbozdqrE64fkuTv6mlq2zxo9ad+3yo= +google.golang.org/genproto/googleapis/api v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:EIQZ5bFCfRQDV4MhRle7+OgjNtZ6P1PiZBgAKuxXu/Y= +google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:7QBABkRtR8z+TEnmXTqIqwJLlzrZKVfAUm7tY3yGv0M= +google.golang.org/genproto/googleapis/api v0.0.0-20260519071638-aa98bba5eb94/go.mod h1:1dCETSCY2YKZNXQE3h4fun3TYwF5p8jejRKZgfWAgAY= +google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY= +google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7/go.mod h1:KqHwBx2upmfa1XSi1WuRvC+2VGCLtooKkfmyvRbUmqA= +google.golang.org/genproto/googleapis/api v0.0.0-20260706201446-f0a921348800/go.mod h1:FPk7EXUKMtImne7AmknoYjT4QXqKIzzRbeQIXzLk6fQ= +google.golang.org/genproto/googleapis/bytestream v0.0.0-20260819154853-08b0e4226688/go.mod h1:832FQwEl9OKXy5rHqEY2U7uF7Bg+Hs7Zo72IIq+dYZ4= +google.golang.org/genproto/googleapis/bytestream v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:RoCpRfcA27uTJ0TZb3Vyad8eLVakUKdLdV2yMdlm2+w= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240429193739-8cf5692501f6/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250804133106-a7a43d27e69b/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250818200422-3122310a409c/go.mod h1:gw1tLEfykwDz2ET4a12jcXt4couGAm7IwsVaTy0Sflo= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251029180050-ab9386a59fda/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260401001100-f93e5f3e9f0f/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260519071638-aa98bba5eb94/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260715232425-e75dac1f907d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0= +google.golang.org/grpc v1.74.2/go.mod h1:CtQ+BGjaAIXHs/5YS3i473GqwBBa1zGQNevxdeBEXrM= +google.golang.org/grpc v1.76.0/go.mod h1:Ju12QI8M6iQJtbcsV+awF5a4hfJMLi4X0JLo94ULZ6c= +google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U= +google.golang.org/grpc v1.79.1 h1:zGhSi45ODB9/p3VAawt9a+O/MULLl9dpizzNNpq7flY= google.golang.org/grpc v1.79.1/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= +google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= +google.golang.org/grpc v1.80.0/go.mod h1:ho/dLnxwi3EDJA4Zghp7k2Ec1+c2jqup0bFkw07bwF4= +google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I= +google.golang.org/grpc v1.82.0/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA= +google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA= +google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= +google.golang.org/grpc/examples v0.0.0-20250407062114-b368379ef8f6/go.mod h1:6ytKWczdvnpnO+m+JiG9NjEDzR1FJfsnmJdG7B8QVZ8= +google.golang.org/grpc/gcp/observability v1.0.1/go.mod h1:yM0UcrYRMe/B+Nu0mDXeTJNDyIMJRJnzuxqnJMz7Ewk= +google.golang.org/grpc/security/advancedtls v1.0.0/go.mod h1:o+s4go+e1PJ2AjuQMY5hU82W7lDlefjJA6FqEHRVHWk= +google.golang.org/grpc/stats/opencensus v1.0.0/go.mod h1:FhdkeYvN43wLYUnapVuRJJ9JXkNwe403iLUW2LKSnjs= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +google.golang.org/protobuf v1.36.7/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= +google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= From 403df36069ea407c2603eaee07fb6d2821cdd122 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 14 Oct 2026 16:18:27 +0100 Subject: [PATCH 07/12] feat(cli): add build step for deployment artefacts Packages an application into the artefacts a deploy target provisions from, and writes a build manifest the Celerity transformer reads to produce concrete resources such as Lambda function definitions. The manifest wire format lives in its own dependency-free package so the CLI and the transformer share one source of truth rather than each keeping a hand-copied struct that can silently drift. Strategy, dependency installer, source compiler and handler dependency reader are separate interfaces so a language or a deploy target can be added without touching the others. Strategies are keyed by deploy target and the rest by runtime prefix, matched longest first because Go map iteration is unordered and a first match would pick a different registration from run to run. Dependencies are layered rather than bundled per handler. A shared layer covers every handler by default and a handler opts into its own only by declaring handlerDependencies, which keeps the common case to one upload. --- apps/cli/buildmanifest/manifest.go | 170 +++++ apps/cli/cmd/commands/build.go | 260 +++++++ apps/cli/internal/build/adapter_package.go | 78 ++ .../internal/build/adapter_package_test.go | 139 ++++ .../internal/build/bundle_manifest_test.go | 71 ++ apps/cli/internal/build/compile_nodejs.go | 38 + .../cli/internal/build/compile_nodejs_test.go | 92 +++ apps/cli/internal/build/defaults.go | 33 + apps/cli/internal/build/deps_nodejs.go | 127 ++++ apps/cli/internal/build/deps_nodejs_test.go | 143 ++++ apps/cli/internal/build/deps_python.go | 72 ++ apps/cli/internal/build/deps_python_test.go | 105 +++ apps/cli/internal/build/exec.go | 36 + apps/cli/internal/build/exec_test.go | 30 + apps/cli/internal/build/handler_deps.go | 82 ++ apps/cli/internal/build/handler_deps_test.go | 161 ++++ apps/cli/internal/build/lambda.go | 699 ++++++++++++++++++ .../internal/build/lambda_bootstrap_nodejs.go | 73 ++ .../build/lambda_bootstrap_nodejs_test.go | 108 +++ .../internal/build/lambda_bootstrap_python.go | 50 ++ .../build/lambda_bootstrap_python_test.go | 59 ++ apps/cli/internal/build/lambda_compiled.go | 139 ++++ .../internal/build/lambda_compiled_test.go | 225 ++++++ .../internal/build/lambda_layer_path_test.go | 23 + .../build/lambda_maintenance_runner.go | 146 ++++ .../build/lambda_maintenance_runner_test.go | 189 +++++ apps/cli/internal/build/lambda_test.go | 565 ++++++++++++++ apps/cli/internal/build/lambda_types.go | 11 + apps/cli/internal/build/manifest.go | 53 ++ apps/cli/internal/build/manifest_test.go | 200 +++++ apps/cli/internal/build/node_pm.go | 119 +++ apps/cli/internal/build/registry.go | 94 +++ apps/cli/internal/build/registry_test.go | 127 ++++ .../build/reproducible_archive_test.go | 33 + apps/cli/internal/build/types.go | 138 ++++ apps/cli/internal/build/upload.go | 12 + apps/cli/internal/build/upload_s3.go | 246 ++++++ .../build/upload_s3_integration_test.go | 199 +++++ apps/cli/internal/build/upload_s3_test.go | 82 ++ apps/cli/internal/build/upload_test.go | 34 + 40 files changed, 5261 insertions(+) create mode 100644 apps/cli/buildmanifest/manifest.go create mode 100644 apps/cli/cmd/commands/build.go create mode 100644 apps/cli/internal/build/adapter_package.go create mode 100644 apps/cli/internal/build/adapter_package_test.go create mode 100644 apps/cli/internal/build/bundle_manifest_test.go create mode 100644 apps/cli/internal/build/compile_nodejs.go create mode 100644 apps/cli/internal/build/compile_nodejs_test.go create mode 100644 apps/cli/internal/build/defaults.go create mode 100644 apps/cli/internal/build/deps_nodejs.go create mode 100644 apps/cli/internal/build/deps_nodejs_test.go create mode 100644 apps/cli/internal/build/deps_python.go create mode 100644 apps/cli/internal/build/deps_python_test.go create mode 100644 apps/cli/internal/build/exec.go create mode 100644 apps/cli/internal/build/exec_test.go create mode 100644 apps/cli/internal/build/handler_deps.go create mode 100644 apps/cli/internal/build/handler_deps_test.go create mode 100644 apps/cli/internal/build/lambda.go create mode 100644 apps/cli/internal/build/lambda_bootstrap_nodejs.go create mode 100644 apps/cli/internal/build/lambda_bootstrap_nodejs_test.go create mode 100644 apps/cli/internal/build/lambda_bootstrap_python.go create mode 100644 apps/cli/internal/build/lambda_bootstrap_python_test.go create mode 100644 apps/cli/internal/build/lambda_compiled.go create mode 100644 apps/cli/internal/build/lambda_compiled_test.go create mode 100644 apps/cli/internal/build/lambda_layer_path_test.go create mode 100644 apps/cli/internal/build/lambda_maintenance_runner.go create mode 100644 apps/cli/internal/build/lambda_maintenance_runner_test.go create mode 100644 apps/cli/internal/build/lambda_test.go create mode 100644 apps/cli/internal/build/lambda_types.go create mode 100644 apps/cli/internal/build/manifest.go create mode 100644 apps/cli/internal/build/manifest_test.go create mode 100644 apps/cli/internal/build/node_pm.go create mode 100644 apps/cli/internal/build/registry.go create mode 100644 apps/cli/internal/build/registry_test.go create mode 100644 apps/cli/internal/build/reproducible_archive_test.go create mode 100644 apps/cli/internal/build/types.go create mode 100644 apps/cli/internal/build/upload.go create mode 100644 apps/cli/internal/build/upload_s3.go create mode 100644 apps/cli/internal/build/upload_s3_integration_test.go create mode 100644 apps/cli/internal/build/upload_s3_test.go create mode 100644 apps/cli/internal/build/upload_test.go diff --git a/apps/cli/buildmanifest/manifest.go b/apps/cli/buildmanifest/manifest.go new file mode 100644 index 00000000..93cc1ed2 --- /dev/null +++ b/apps/cli/buildmanifest/manifest.go @@ -0,0 +1,170 @@ +// Package buildmanifest defines the on-disk build manifest produced by the +// Celerity CLI build step and consumed by the Celerity transformer plugin when +// producing concrete deploy resources (e.g. AWS Lambda function definitions). +// +// It is deliberately a small, dependency-free package (standard library only) +// so it can be shared as the single source of truth for the manifest wire +// format across the CLI and the transformer, instead of each side keeping a +// hand-copied struct that can silently drift. +package buildmanifest + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" +) + +const ( + // Version is the current build manifest schema version. + Version = "1" + + // FileName is the repo-relative path the CLI writes the manifest to. + FileName = ".celerity/build-manifest.json" + + // ResourceLinksFilename is the name of the blueprint-derived resource + // links JSON file bundled into the Lambda app archive. The SDK reads it + // from the handler's module directory on cold start, removing the need to + // pass the payload through environment variables (which have a tight 4 KB + // total limit on AWS Lambda). + ResourceLinksFilename = "__celerity_resource_links__.json" + + // HandlerScopeFilename is the name of the per-handler resource scope file + // bundled alongside the resource links. Resource links describe every + // resource in the application; this records which of them each handler + // uses, and so which resource layers a given handler initialises. + // + // It is a separate file rather than a change to the resource links format + // because the SDK ships in the runtime layer at its published version while + // the CLI writing these files is whatever the developer has installed, so + // the two are routinely out of step. An SDK that predates this file ignores + // it and behaves as before, and a newer SDK falls back when it is absent. + HandlerScopeFilename = "__celerity_handler_scope__.json" + + // Artifact type discriminators recorded on Artifact.Type. + ArtifactTypeContainerImage = "container-image" + ArtifactTypeLambdaArchive = "lambda-archive" + ArtifactTypeLambdaLayer = "lambda-layer" +) + +// Manifest records build artifacts produced by the build step. Written to +// FileName and referenced by the deploy engine via a context variable pointer. +// +// Target-specific output (AWS Lambda, container, etc.) lives under a dedicated +// typed sub-manifest so adding a new strategy does not require changing the +// top-level shape. +type Manifest struct { + Version string `json:"version"` + Runtime string `json:"runtime"` + Target string `json:"target"` + Handlers map[string]*HandlerArtifacts `json:"handlers"` + // Lambda is populated only when the build target is aws-serverless. + Lambda *LambdaManifest `json:"lambda,omitempty"` + // RemoteURL is the cloud storage URL where the manifest itself has been + // uploaded, set after a successful upload. Populated only in the + // locally-persisted copy; the uploaded object does not contain this field + // (it is set after marshalling for upload). Consumers reading the uploaded + // manifest can ignore it. + RemoteURL string `json:"remoteUrl,omitempty"` +} + +// HandlerArtifacts holds per-handler build metadata. Target-specific overrides +// (e.g. a custom dependency layer for Lambda) live under their own sub-struct +// so each strategy owns the shape of its per-handler data. +type HandlerArtifacts struct { + Lambda *LambdaHandlerArtifacts `json:"lambda,omitempty"` +} + +// Artifact represents a single build artifact (zip archive or image). +type Artifact struct { + Type string `json:"type"` + LocalPath string `json:"localPath,omitempty"` + S3Bucket string `json:"s3Bucket,omitempty"` + S3Key string `json:"s3Key,omitempty"` + ImageURI string `json:"imageUri,omitempty"` + ContentHash string `json:"contentHash,omitempty"` + Size int64 `json:"size,omitempty"` +} + +// LambdaManifest holds AWS Lambda-specific build output referenced by every +// handler's Lambda function. Populated by the CLI's Lambda build strategy and +// read by the Celerity transformer plugin. +type LambdaManifest struct { + // AppCode is the single shared code asset, the whole app source tree plus + // the generated Celerity Lambda entry point file. + AppCode *Artifact `json:"appCode,omitempty"` + // EntryPoint is the Lambda Handler field value, identical for every handler + // in a project (e.g. "__celerity_lambda_entry__.handler"). + EntryPoint string `json:"entryPoint,omitempty"` + // SharedLayer is the production dependency layer used by handlers that do + // not opt into a custom per-handler dep layer. + SharedLayer *Artifact `json:"sharedLayer,omitempty"` + // Architecture is the instruction set the archive's code is built for, + // as a GOARCH name ("arm64", "amd64"). Empty for an interpreted runtime, + // where the code is not built for one. + // + // Recorded because a compiled handlers executable and the function it is + // deployed to have to agree. A mismatch is a valid archive that the kernel + // refuses to exec, surfacing as a bare exit status 126. The transformer + // declares the function's architecture from this field. + Architecture string `json:"architecture,omitempty"` + // LambdaRuntime is the concrete Lambda runtime identifier the functions + // need, where the build has determined it. A compiled executable runs on + // a custom runtime ("provided.al2023") rather than on one named by the + // blueprint's portable runtime identifier. + LambdaRuntime string `json:"lambdaRuntime,omitempty"` + // MaintenanceRunner is the database maintenance runner's archive, built + // only when the blueprint has a celerity/sqlDatabase. + // + // It is a compiled Go binary rather than application code, so it is neither + // the app bundle nor a layer. It shares nothing with them and is versioned + // with the CLI rather than with the user's source. + MaintenanceRunner *Artifact `json:"maintenanceRunner,omitempty"` +} + +// LambdaHandlerArtifacts holds per-handler Lambda overrides. +type LambdaHandlerArtifacts struct { + // Dependencies is the handler's custom dependency layer, populated only + // when the developer has declared handlerDependencies. Nil handlers fall + // back to LambdaManifest.SharedLayer. + Dependencies *Artifact `json:"dependencies,omitempty"` +} + +// Write writes the build manifest to FileName, creating the parent directory +// if needed. +func Write(manifest *Manifest) error { + dir := filepath.Dir(FileName) + if err := os.MkdirAll(dir, 0755); err != nil { + return fmt.Errorf("creating manifest directory: %w", err) + } + + data, err := json.MarshalIndent(manifest, "", " ") + if err != nil { + return fmt.Errorf("marshalling build manifest: %w", err) + } + + if err := os.WriteFile(FileName, data, 0644); err != nil { + return fmt.Errorf("writing build manifest: %w", err) + } + + return nil +} + +// Read reads the build manifest from FileName. Returns (nil, nil) if the file +// does not exist. +func Read() (*Manifest, error) { + data, err := os.ReadFile(FileName) + if err != nil { + if os.IsNotExist(err) { + return nil, nil + } + return nil, fmt.Errorf("reading build manifest: %w", err) + } + + var manifest Manifest + if err := json.Unmarshal(data, &manifest); err != nil { + return nil, fmt.Errorf("parsing build manifest: %w", err) + } + + return &manifest, nil +} diff --git a/apps/cli/cmd/commands/build.go b/apps/cli/cmd/commands/build.go new file mode 100644 index 00000000..0e4915c3 --- /dev/null +++ b/apps/cli/cmd/commands/build.go @@ -0,0 +1,260 @@ +package commands + +import ( + "context" + "fmt" + "io" + "os" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/newstack-cloud/celerity/apps/cli/internal/blueprint" + "github.com/newstack-cloud/celerity/apps/cli/internal/build" + "github.com/newstack-cloud/celerity/apps/cli/internal/deployconfig" + "github.com/newstack-cloud/celerity/apps/cli/internal/devconfig/resolve" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlerresolve" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/spf13/cobra" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +func setupBuildCommand(rootCmd *cobra.Command, confProvider *config.Provider) { + buildCmd := &cobra.Command{ + Use: "build", + Short: "Build application artifacts for deployment", + Long: `Packages the application for the configured deploy target. + +For serverless targets (e.g. aws-serverless), this creates per-handler +deployment archives and a shared dependency layer. Developers can opt-in +to per-handler dependency layers by declaring handlerDependencies in their +package manifest (package.json or pyproject.toml). + +The build output is recorded in .celerity/build-manifest.json, which is +referenced by the deploy and stage commands. + +Examples: + # Build using default app.deploy.jsonc + celerity build + + # Build for a specific environment + celerity build --app-deploy-config-file app.deploy.staging.jsonc`, + RunE: func(cmd *cobra.Command, args []string) error { + return runBuild(cmd.Context(), confProvider, os.Stdout) + }, + } + + buildCmd.Flags().String( + "blueprint-file", "", + "The blueprint file to read handler and runtime information from "+ + "(default: auto-detect).", + ) + confProvider.BindPFlag("buildBlueprintFile", buildCmd.Flags().Lookup("blueprint-file")) + confProvider.BindEnvVar("buildBlueprintFile", "CELERITY_CLI_BUILD_BLUEPRINT_FILE") + + rootCmd.AddCommand(buildCmd) +} + +// defaultBuildInstanceName is the instance a build is attributed to when the +// command is run on its own rather than as part of a deploy. +const defaultBuildInstanceName = "default" + +func runBuild(ctx context.Context, confProvider *config.Provider, w io.Writer) error { + logger := newBuildLogger() + + appConfigFile, _ := confProvider.GetString("appDeployConfigFile") + if appConfigFile == "" { + appConfigFile = "app.deploy.jsonc" + } + + appCfg, err := deployconfig.ReadAppDeployConfig(appConfigFile) + if err != nil { + return fmt.Errorf("reading deploy config: %w", err) + } + + deployTarget := appCfg.DeployTarget.Name + fmt.Fprintf(w, "Build target: %s\n", deployTarget) + + blueprintFile, _ := confProvider.GetString("buildBlueprintFile") + if blueprintFile == "" { + blueprintFile, err = resolve.BlueprintPath(".", "") + if err != nil { + return err + } + } + + info, err := collectBuildInfo(ctx, ".", blueprintFile, deployTarget, appCfg.HandlerBuild, logger) + if err != nil { + return err + } + runtime := info.Runtime + fmt.Fprintf(w, "Runtime: %s\n", runtime) + fmt.Fprintf(w, "Handlers: %d\n\n", len(info.Handlers)) + + registry := build.NewDefaultRegistry(".") + strategy, err := registry.GetStrategy(deployTarget) + if err != nil { + return err + } + + handlerDeps, err := build.ReadHandlerDependencies(registry, runtime, ".") + if err != nil { + return fmt.Errorf("reading handler dependencies: %w", err) + } + + if len(handlerDeps) > 0 { + fmt.Fprintf(w, "Per-handler dependencies declared for %d handler(s)\n", len(handlerDeps)) + } + + uploader := build.ResolveUploader(deployTarget, appCfg.DeployTarget.Config) + + fmt.Fprintf(w, "Building...\n") + + manifest, err := strategy.Build(ctx, &build.BuildParams{ + AppDir: ".", + Runtime: runtime, + DeployTarget: deployTarget, + Handlers: info.Handlers, + HandlerDependencies: handlerDeps, + OutputDir: ".celerity/build", + Uploader: uploader, + Logger: logger, + Blueprint: info.Blueprint, + ToolOutput: w, + Toolchain: info.Toolchain, + }) + if err != nil { + return fmt.Errorf("build failed: %w", err) + } + + // Uploaded before the manifest is written, so the copy on disk records the + // remote URL. A nil uploader makes this a no-op, which is every deploy + // target that does not stage artefacts remotely. + // + // The instance name matches the one the deploy path uses, so a manifest + // pre-built in CI lands at the key a later deploy reads from. + if err := build.UploadManifest(ctx, uploader, manifest, defaultBuildInstanceName); err != nil { + return fmt.Errorf("uploading build manifest: %w", err) + } + + if err := build.WriteManifest(manifest); err != nil { + return err + } + + fmt.Fprintf(w, "\nBuild complete. %d handler(s) packaged.\n", len(manifest.Handlers)) + fmt.Fprintf(w, "Manifest: %s\n", build.ManifestFile) + + printLambdaManifest(w, manifest) + + return nil +} + +func printLambdaManifest(w io.Writer, manifest *build.Manifest) { + if manifest.Lambda == nil { + return + } + if manifest.Lambda.AppCode != nil { + fmt.Fprintf(w, "App code: %s (%d KB)\n", + manifest.Lambda.AppCode.LocalPath, manifest.Lambda.AppCode.Size/1024) + } + if manifest.Lambda.EntryPoint != "" { + fmt.Fprintf(w, "Entry point: %s\n", manifest.Lambda.EntryPoint) + } + if manifest.Lambda.SharedLayer != nil { + fmt.Fprintf(w, "Shared layer: %s (%d KB)\n", + manifest.Lambda.SharedLayer.LocalPath, manifest.Lambda.SharedLayer.Size/1024) + } + + for name, arts := range manifest.Handlers { + if arts.Lambda != nil && arts.Lambda.Dependencies != nil { + fmt.Fprintf(w, " %s: layer=%d KB\n", name, arts.Lambda.Dependencies.Size/1024) + } else { + fmt.Fprintf(w, " %s: uses shared layer\n", name) + } + } +} + +// buildInfo is what a build needs to read off the blueprint and the project +// before it can package anything. +type buildInfo struct { + Runtime string + Handlers []build.HandlerInfo + Blueprint *schema.Blueprint + Toolchain handlertoolchain.Toolchain +} + +func collectBuildInfo( + ctx context.Context, + appDir, blueprintFile, deployTarget string, + handlerBuild *handlertoolchain.Config, + logger *zap.Logger, +) (*buildInfo, error) { + runtime, err := buildRuntime(blueprintFile, appDir) + if err != nil { + return nil, err + } + + toolchain, err := handlertoolchain.Resolve(handlertoolchain.Options{ + Runtime: runtime, + AppDir: appDir, + Config: handlerBuild, + }) + if err != nil { + return nil, err + } + + resolved, err := handlerresolve.Resolve(ctx, handlerresolve.Options{ + AppDir: appDir, + BlueprintFile: blueprintFile, + Toolchain: toolchain, + DeployTarget: deployTarget, + Mode: handlertoolchain.ModeDeploy, + }, logger) + if err != nil { + return nil, err + } + + if len(resolved.Handlers) > 0 { + if err := handlerresolve.RequireRuntimeSDK(appDir, resolved); err != nil { + return nil, err + } + } + + handlers := make([]build.HandlerInfo, len(resolved.Handlers)) + for i, h := range resolved.Handlers { + handlers[i] = build.HandlerInfo{ + ResourceName: h.ResourceName, + HandlerName: h.HandlerName, + CodeLocation: h.CodeLocation, + } + } + return &buildInfo{ + Runtime: resolved.Runtime, + Handlers: handlers, + Blueprint: resolved.MergedBlueprint, + Toolchain: resolved.Toolchain, + }, nil +} + +// buildRuntime reads the runtime identifier the toolchain is resolved against, +// before handler resolution has run and can report it. +func buildRuntime(blueprintFile, appDir string) (string, error) { + bp, _, err := blueprint.LoadForDev(blueprintFile) + if err != nil { + return "", err + } + if runtime, err := blueprint.DetectRuntime(bp); err == nil { + return runtime, nil + } + return blueprint.DetectRuntimeFromProject(appDir) +} + +func newBuildLogger() *zap.Logger { + cfg := zap.NewDevelopmentConfig() + cfg.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder + cfg.OutputPaths = []string{"stderr"} + cfg.ErrorOutputPaths = []string{"stderr"} + cfg.Level = zap.NewAtomicLevelAt(zapcore.WarnLevel) + logger, _ := cfg.Build() + return logger +} diff --git a/apps/cli/internal/build/adapter_package.go b/apps/cli/internal/build/adapter_package.go new file mode 100644 index 00000000..e47c97b1 --- /dev/null +++ b/apps/cli/internal/build/adapter_package.go @@ -0,0 +1,78 @@ +package build + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" +) + +// Reads whichever manifest the runtime uses. Only declaration is checked, not +// installation, because the build installs dependencies from the manifest; a +// declared package reaches the bundle and an undeclared one never will, however +// the local node_modules or virtualenv happens to look. +func appDeclaresPackage(runtime, appDir, pkg string) (bool, error) { + switch { + case strings.HasPrefix(runtime, "nodejs"): + return nodePackageJSONDeclares(appDir, pkg) + case strings.HasPrefix(runtime, "python"): + return pythonProjectDeclares(appDir, pkg) + } + // An unknown runtime has no manifest this can read, so there is nothing to + // contradict the bootstrap. + return true, nil +} + +func nodePackageJSONDeclares(appDir, pkg string) (bool, error) { + data, err := os.ReadFile(filepath.Join(appDir, "package.json")) + if err != nil { + return false, fmt.Errorf("reading package.json: %w", err) + } + + var manifest struct { + Dependencies map[string]string `json:"dependencies"` + DevDependencies map[string]string `json:"devDependencies"` + PeerDependencies map[string]string `json:"peerDependencies"` + } + if err := json.Unmarshal(data, &manifest); err != nil { + return false, fmt.Errorf("parsing package.json: %w", err) + } + + // devDependencies and peerDependencies count as declarations here. The + // runtime container provides the SDK packages as peers in some setups, and + // reporting a package as missing when the manifest names it would send a + // developer looking in the wrong place. + for _, deps := range []map[string]string{ + manifest.Dependencies, + manifest.DevDependencies, + manifest.PeerDependencies, + } { + if _, has := deps[pkg]; has { + return true, nil + } + } + + return false, nil +} + +// Scanned line by line rather than parsed as TOML, matching how the SDK +// presence check reads the same file, since this is only a substring test. +func pythonProjectDeclares(appDir, distribution string) (bool, error) { + data, err := os.ReadFile(filepath.Join(appDir, "pyproject.toml")) + if err != nil { + return false, fmt.Errorf("reading pyproject.toml: %w", err) + } + + for _, line := range strings.Split(string(data), "\n") { + stripped := strings.TrimSpace(line) + if strings.HasPrefix(stripped, "#") { + continue + } + if strings.Contains(stripped, distribution) { + return true, nil + } + } + + return false, nil +} diff --git a/apps/cli/internal/build/adapter_package_test.go b/apps/cli/internal/build/adapter_package_test.go new file mode 100644 index 00000000..91551bfc --- /dev/null +++ b/apps/cli/internal/build/adapter_package_test.go @@ -0,0 +1,139 @@ +package build + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" +) + +type AdapterPackageTestSuite struct { + suite.Suite +} + +func (s *AdapterPackageTestSuite) writeManifest(name, content string) string { + dir := s.T().TempDir() + s.Require().NoError(os.WriteFile(filepath.Join(dir, name), []byte(content), 0644)) + return dir +} + +// The check that existed before this accepted any @celerity-sdk/* package, so an +// app depending on several of them passed while missing the one the entry file +// imports. That is how a project reached a real deployment with every handler +// failing to start on a module resolution error. +func (s *AdapterPackageTestSuite) Test_other_celerity_packages_do_not_satisfy_the_adapter() { + dir := s.writeManifest("package.json", `{ + "dependencies": { + "@celerity-sdk/bucket": "^0.8.4", + "@celerity-sdk/datastore": "^0.8.4", + "@celerity-sdk/sql-database": "^0.8.4" + }, + "devDependencies": {"@celerity-sdk/cli": "^0.8.4"} + }`) + + declared, err := appDeclaresPackage("nodejs22.x", dir, "@celerity-sdk/serverless-aws") + + s.Require().NoError(err) + s.False(declared) +} + +func (s *AdapterPackageTestSuite) Test_adapter_declared_as_a_dependency() { + dir := s.writeManifest("package.json", `{ + "dependencies": {"@celerity-sdk/serverless-aws": "^0.8.4"} + }`) + + declared, err := appDeclaresPackage("nodejs22.x", dir, "@celerity-sdk/serverless-aws") + + s.Require().NoError(err) + s.True(declared) +} + +// The runtime container provides the SDK packages as peers in some setups, so a +// manifest naming the package there has declared it. +func (s *AdapterPackageTestSuite) Test_adapter_declared_as_a_peer_or_dev_dependency() { + for name, manifest := range map[string]string{ + "peer": `{"peerDependencies": {"@celerity-sdk/serverless-aws": "^0.8.4"}}`, + "dev": `{"devDependencies": {"@celerity-sdk/serverless-aws": "^0.8.4"}}`, + } { + dir := s.writeManifest("package.json", manifest) + + declared, err := appDeclaresPackage("nodejs22.x", dir, "@celerity-sdk/serverless-aws") + + s.Require().NoError(err, name) + s.True(declared, "%s dependency should count as declared", name) + } +} + +func (s *AdapterPackageTestSuite) Test_python_distribution_declared() { + dir := s.writeManifest("pyproject.toml", ` +[project] +dependencies = ["celerity-sdk[serverless]>=0.3.0"] +`) + + declared, err := appDeclaresPackage("python3.13", dir, "celerity-sdk") + + s.Require().NoError(err) + s.True(declared) +} + +// A commented-out dependency is not a dependency; the bundle is built from what +// the manifest actually declares. +func (s *AdapterPackageTestSuite) Test_python_commented_dependency_does_not_count() { + dir := s.writeManifest("pyproject.toml", ` +[project] +# dependencies = ["celerity-sdk"] +dependencies = ["boto3"] +`) + + declared, err := appDeclaresPackage("python3.13", dir, "celerity-sdk") + + s.Require().NoError(err) + s.False(declared) +} + +func (s *AdapterPackageTestSuite) Test_missing_manifest_is_reported_as_an_error() { + _, err := appDeclaresPackage("nodejs22.x", s.T().TempDir(), "@celerity-sdk/serverless-aws") + + s.Require().Error(err) +} + +// requireAdapterPackage builds the message a developer acts on, so it has to name +// the package rather than describe the category it belongs to. +func (s *AdapterPackageTestSuite) Test_error_names_the_missing_package() { + dir := s.writeManifest("package.json", `{"dependencies": {"@celerity-sdk/core": "^0.8.4"}}`) + + err := requireAdapterPackage( + &LambdaNodeBootstrap{AppDir: dir}, + "nodejs22.x", + dir, + ) + + s.Require().Error(err) + s.Contains(err.Error(), "@celerity-sdk/serverless-aws") +} + +func (s *AdapterPackageTestSuite) Test_no_error_when_the_adapter_is_present() { + dir := s.writeManifest("package.json", + `{"dependencies": {"@celerity-sdk/serverless-aws": "^0.8.4"}}`) + + err := requireAdapterPackage(&LambdaNodeBootstrap{AppDir: dir}, "nodejs22.x", dir) + + s.Require().NoError(err) +} + +// An unreadable manifest is not proof the dependency is absent, and failing the +// build on it would be worse than the check not running. +func (s *AdapterPackageTestSuite) Test_unreadable_manifest_does_not_fail_the_build() { + err := requireAdapterPackage( + &LambdaNodeBootstrap{AppDir: s.T().TempDir()}, + "nodejs22.x", + s.T().TempDir(), + ) + + s.Require().NoError(err) +} + +func TestAdapterPackageTestSuite(t *testing.T) { + suite.Run(t, new(AdapterPackageTestSuite)) +} diff --git a/apps/cli/internal/build/bundle_manifest_test.go b/apps/cli/internal/build/bundle_manifest_test.go new file mode 100644 index 00000000..d3481757 --- /dev/null +++ b/apps/cli/internal/build/bundle_manifest_test.go @@ -0,0 +1,71 @@ +package build + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func esmProjectDir(t *testing.T) string { + t.Helper() + dir := t.TempDir() + require.NoError(t, os.WriteFile( + filepath.Join(dir, "package.json"), + []byte(`{"type": "module"}`), + 0644, + )) + return dir +} + +// Compiling replaces the copied source tree with the compiler's output, which +// carries no package.json, so Node read the emitted .js files as CommonJS and +// every handler failed on "Cannot use import statement outside a module". +func TestWriteBundleModuleManifest_declaresESMForACompiledBundle(t *testing.T) { + staging := t.TempDir() + + require.NoError(t, writeBundleModuleManifest("nodejs22.x", esmProjectDir(t), staging)) + + written, err := os.ReadFile(filepath.Join(staging, "package.json")) + require.NoError(t, err) + require.Contains(t, string(written), `"type": "module"`) +} + +// A CommonJS project needs no declaration; writing one would change how its own +// files are read. +func TestWriteBundleModuleManifest_leavesCommonJSAlone(t *testing.T) { + appDir := t.TempDir() + require.NoError(t, os.WriteFile( + filepath.Join(appDir, "package.json"), []byte(`{"type": "commonjs"}`), 0644)) + staging := t.TempDir() + + require.NoError(t, writeBundleModuleManifest("nodejs22.x", appDir, staging)) + + _, err := os.Stat(filepath.Join(staging, "package.json")) + require.True(t, os.IsNotExist(err)) +} + +// A manifest already in the bundle came from the project's own source tree, +// where the author decides what it says. +func TestWriteBundleModuleManifest_doesNotOverwriteTheProjectManifest(t *testing.T) { + staging := t.TempDir() + authored := `{"type": "module", "imports": {"#app/*": "./*"}}` + require.NoError(t, os.WriteFile( + filepath.Join(staging, "package.json"), []byte(authored), 0644)) + + require.NoError(t, writeBundleModuleManifest("nodejs22.x", esmProjectDir(t), staging)) + + written, err := os.ReadFile(filepath.Join(staging, "package.json")) + require.NoError(t, err) + require.Equal(t, authored, string(written)) +} + +func TestWriteBundleModuleManifest_leavesNonNodeRuntimesAlone(t *testing.T) { + staging := t.TempDir() + + require.NoError(t, writeBundleModuleManifest("python3.13", esmProjectDir(t), staging)) + + _, err := os.Stat(filepath.Join(staging, "package.json")) + require.True(t, os.IsNotExist(err)) +} diff --git a/apps/cli/internal/build/compile_nodejs.go b/apps/cli/internal/build/compile_nodejs.go new file mode 100644 index 00000000..8e65019c --- /dev/null +++ b/apps/cli/internal/build/compile_nodejs.go @@ -0,0 +1,38 @@ +package build + +import ( + "context" + "io" + "os" + "path/filepath" +) + +// NodeSourceCompiler compiles TypeScript source to JavaScript using tsc, +// preserving the directory structure for readability in cloud provider consoles. +// If no tsconfig.json is found, it assumes the project is plain JavaScript +// and does nothing. +type NodeSourceCompiler struct { + Exec CommandExecutor + PM NodePackageManager +} + +func (c *NodeSourceCompiler) Compile( + ctx context.Context, + srcDir string, + outDir string, + toolOutput io.Writer, +) error { + tsconfig := filepath.Join(srcDir, "tsconfig.json") + if _, err := os.Stat(tsconfig); os.IsNotExist(err) { + return nil + } + + if err := os.MkdirAll(outDir, 0755); err != nil { + return err + } + + cmd := c.PM.ExecPrefix() + cmd = append(cmd, "tsc", "--outDir", outDir, "--declaration", "false", "--sourceMap", "false") + + return c.Exec.Run(ctx, srcDir, toolOutput, cmd[0], cmd[1:]...) +} diff --git a/apps/cli/internal/build/compile_nodejs_test.go b/apps/cli/internal/build/compile_nodejs_test.go new file mode 100644 index 00000000..1960cb75 --- /dev/null +++ b/apps/cli/internal/build/compile_nodejs_test.go @@ -0,0 +1,92 @@ +package build + +import ( + "context" + "io" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" +) + +type CompileNodejsSuite struct { + suite.Suite +} + +func TestCompileNodejsSuite(t *testing.T) { + suite.Run(t, new(CompileNodejsSuite)) +} + +func (s *CompileNodejsSuite) Test_Compile_withTsconfig_invokesLocalTsc_npm() { + stub := &stubExec{} + compiler := &NodeSourceCompiler{Exec: stub, PM: NodePMNpm} + + srcDir := s.T().TempDir() + outDir := s.T().TempDir() + + s.Require().NoError(os.WriteFile( + filepath.Join(srcDir, "tsconfig.json"), []byte(`{"compilerOptions":{}}`), 0644, + )) + + err := compiler.Compile(context.Background(), srcDir, outDir, io.Discard) + s.Require().NoError(err) + + s.Require().Len(stub.calls, 1) + call := stub.calls[0] + s.Equal("npm", call.name) + s.Equal([]string{"exec", "--", "tsc", "--outDir", outDir, "--declaration", "false", "--sourceMap", "false"}, call.args) + s.Equal(srcDir, call.dir) +} + +func (s *CompileNodejsSuite) Test_Compile_withTsconfig_invokesLocalTsc_pnpm() { + stub := &stubExec{} + compiler := &NodeSourceCompiler{Exec: stub, PM: NodePMPnpm} + + srcDir := s.T().TempDir() + outDir := s.T().TempDir() + + s.Require().NoError(os.WriteFile( + filepath.Join(srcDir, "tsconfig.json"), []byte(`{"compilerOptions":{}}`), 0644, + )) + + err := compiler.Compile(context.Background(), srcDir, outDir, io.Discard) + s.Require().NoError(err) + + s.Require().Len(stub.calls, 1) + call := stub.calls[0] + s.Equal("pnpm", call.name) + s.Equal([]string{"exec", "tsc", "--outDir", outDir, "--declaration", "false", "--sourceMap", "false"}, call.args) +} + +func (s *CompileNodejsSuite) Test_Compile_withTsconfig_invokesLocalTsc_yarn() { + stub := &stubExec{} + compiler := &NodeSourceCompiler{Exec: stub, PM: NodePMYarn} + + srcDir := s.T().TempDir() + outDir := s.T().TempDir() + + s.Require().NoError(os.WriteFile( + filepath.Join(srcDir, "tsconfig.json"), []byte(`{"compilerOptions":{}}`), 0644, + )) + + err := compiler.Compile(context.Background(), srcDir, outDir, io.Discard) + s.Require().NoError(err) + + s.Require().Len(stub.calls, 1) + call := stub.calls[0] + s.Equal("yarn", call.name) + s.Equal([]string{"tsc", "--outDir", outDir, "--declaration", "false", "--sourceMap", "false"}, call.args) +} + +func (s *CompileNodejsSuite) Test_Compile_withoutTsconfig_skips() { + stub := &stubExec{} + compiler := &NodeSourceCompiler{Exec: stub, PM: NodePMNpm} + + srcDir := s.T().TempDir() + outDir := s.T().TempDir() + + err := compiler.Compile(context.Background(), srcDir, outDir, io.Discard) + s.NoError(err) + s.Empty(stub.calls) +} diff --git a/apps/cli/internal/build/defaults.go b/apps/cli/internal/build/defaults.go new file mode 100644 index 00000000..2ef0fdba --- /dev/null +++ b/apps/cli/internal/build/defaults.go @@ -0,0 +1,33 @@ +package build + +// NewDefaultRegistry creates a registry pre-populated with the standard +// build strategies and per-runtime components. +// appDir is used to detect the Node.js package manager from the project. +func NewDefaultRegistry(appDir string) *Registry { + return NewRegistryWithExecutor(&ExecCommandExecutor{}, appDir) +} + +// NewRegistryWithExecutor creates a registry using the provided command +// executor. This allows tests to inject a stub executor. +func NewRegistryWithExecutor(exec CommandExecutor, appDir string) *Registry { + r := NewRegistry() + + r.RegisterStrategy("aws-serverless", &LambdaStrategy{ + Registry: r, + Bootstraps: map[string]HandlerBootstrap{ + "nodejs": &LambdaNodeBootstrap{AppDir: appDir}, + "python": &LambdaPythonBootstrap{}, + }, + }) + + nodePM := DetectNodePackageManager(appDir) + r.RegisterDependencyInstaller("nodejs", &NodeDependencyInstaller{Exec: exec, PM: nodePM}) + r.RegisterDependencyInstaller("python", &PythonDependencyInstaller{Exec: exec}) + + r.RegisterSourceCompiler("nodejs", &NodeSourceCompiler{Exec: exec, PM: nodePM}) + + r.RegisterHandlerDependencyReader("nodejs", &NodeHandlerDependencyReader{}) + r.RegisterHandlerDependencyReader("python", &PythonHandlerDependencyReader{}) + + return r +} diff --git a/apps/cli/internal/build/deps_nodejs.go b/apps/cli/internal/build/deps_nodejs.go new file mode 100644 index 00000000..f67614e9 --- /dev/null +++ b/apps/cli/internal/build/deps_nodejs.go @@ -0,0 +1,127 @@ +package build + +import ( + "context" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" +) + +// NodeDependencyInstaller installs Node.js production dependencies +// using the project's package manager. +type NodeDependencyInstaller struct { + Exec CommandExecutor + PM NodePackageManager +} + +func (n *NodeDependencyInstaller) InstallDependencies( + ctx context.Context, + appDir string, + targetDir string, + packages []string, + toolOutput io.Writer, +) error { + if packages != nil { + return n.installSubset(ctx, appDir, targetDir, packages, toolOutput) + } + return n.installAll(ctx, appDir, targetDir, toolOutput) +} + +func (n *NodeDependencyInstaller) installAll( + ctx context.Context, + appDir string, + targetDir string, + toolOutput io.Writer, +) error { + if err := copyFile( + filepath.Join(appDir, "package.json"), + filepath.Join(targetDir, "package.json"), + ); err != nil { + return err + } + for _, lf := range n.PM.LockFiles() { + src := filepath.Join(appDir, lf) + if _, err := os.Stat(src); err == nil { + if err := copyFile(src, filepath.Join(targetDir, lf)); err != nil { + return err + } + } + } + + cmd := n.PM.InstallCommand() + return n.Exec.Run(ctx, targetDir, toolOutput, cmd[0], cmd[1:]...) +} + +func (n *NodeDependencyInstaller) installSubset( + ctx context.Context, + appDir string, + targetDir string, + packages []string, + toolOutput io.Writer, +) error { + origPkgJSON, err := readPackageJSON(filepath.Join(appDir, "package.json")) + if err != nil { + return err + } + + filteredDeps := filterDependencies(origPkgJSON, packages) + + minimalPkg := map[string]any{ + "name": origPkgJSON["name"], + "version": origPkgJSON["version"], + "dependencies": filteredDeps, + } + minimalJSON, err := json.MarshalIndent(minimalPkg, "", " ") + if err != nil { + return fmt.Errorf("marshalling filtered package.json: %w", err) + } + if err := os.WriteFile(filepath.Join(targetDir, "package.json"), minimalJSON, 0644); err != nil { + return err + } + + for _, lf := range n.PM.LockFiles() { + src := filepath.Join(appDir, lf) + if _, err := os.Stat(src); err == nil { + if err := copyFile(src, filepath.Join(targetDir, lf)); err != nil { + return err + } + } + } + + cmd := n.PM.InstallCommand() + return n.Exec.Run(ctx, targetDir, toolOutput, cmd[0], cmd[1:]...) +} + +func readPackageJSON(path string) (map[string]any, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("reading package.json: %w", err) + } + var pkg map[string]any + if err := json.Unmarshal(data, &pkg); err != nil { + return nil, fmt.Errorf("parsing package.json: %w", err) + } + return pkg, nil +} + +func filterDependencies(pkgJSON map[string]any, packages []string) map[string]string { + allDeps := map[string]string{} + if deps, ok := pkgJSON["dependencies"].(map[string]any); ok { + for name, ver := range deps { + if v, ok := ver.(string); ok { + allDeps[name] = v + } + } + } + + filtered := map[string]string{} + for _, pkg := range packages { + if ver, ok := allDeps[pkg]; ok { + filtered[pkg] = ver + } + } + + return filtered +} diff --git a/apps/cli/internal/build/deps_nodejs_test.go b/apps/cli/internal/build/deps_nodejs_test.go new file mode 100644 index 00000000..f82a73fb --- /dev/null +++ b/apps/cli/internal/build/deps_nodejs_test.go @@ -0,0 +1,143 @@ +package build + +import ( + "context" + "encoding/json" + "io" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" +) + +type DepsNodejsSuite struct { + suite.Suite +} + +func TestDepsNodejsSuite(t *testing.T) { + suite.Run(t, new(DepsNodejsSuite)) +} + +// --- filterDependencies --- + +func (s *DepsNodejsSuite) Test_filterDependencies_filtersCorrectDeps() { + pkgJSON := map[string]any{ + "dependencies": map[string]any{ + "express": "^4.18.0", + "lodash": "^4.17.0", + "zod": "^3.0.0", + }, + } + result := filterDependencies(pkgJSON, []string{"express", "zod"}) + s.Equal(map[string]string{"express": "^4.18.0", "zod": "^3.0.0"}, result) +} + +func (s *DepsNodejsSuite) Test_filterDependencies_handlesMissingDeps() { + pkgJSON := map[string]any{ + "dependencies": map[string]any{ + "express": "^4.18.0", + }, + } + result := filterDependencies(pkgJSON, []string{"express", "nonexistent"}) + s.Equal(map[string]string{"express": "^4.18.0"}, result) +} + +func (s *DepsNodejsSuite) Test_filterDependencies_emptyPackageList() { + pkgJSON := map[string]any{ + "dependencies": map[string]any{ + "express": "^4.18.0", + }, + } + result := filterDependencies(pkgJSON, []string{}) + s.Empty(result) +} + +func (s *DepsNodejsSuite) Test_filterDependencies_noDependenciesSection() { + pkgJSON := map[string]any{ + "name": "test-app", + } + result := filterDependencies(pkgJSON, []string{"express"}) + s.Empty(result) +} + +// --- installAll with stub executor --- + +func (s *DepsNodejsSuite) Test_installAll_copiesPackageFilesAndRunsNpmCI() { + stub := &stubExec{} + installer := &NodeDependencyInstaller{Exec: stub, PM: NodePMNpm} + + appDir := s.T().TempDir() + targetDir := s.T().TempDir() + + s.writeJSON(filepath.Join(appDir, "package.json"), map[string]any{ + "name": "test", "version": "1.0.0", "dependencies": map[string]any{}, + }) + s.Require().NoError(os.WriteFile( + filepath.Join(appDir, "package-lock.json"), []byte(`{"lockfileVersion":3}`), 0644, + )) + + err := installer.InstallDependencies(context.Background(), appDir, targetDir, nil, io.Discard) + s.Require().NoError(err) + + s.FileExists(filepath.Join(targetDir, "package.json")) + s.FileExists(filepath.Join(targetDir, "package-lock.json")) + + s.Require().Len(stub.calls, 1) + call := stub.calls[0] + s.Equal("npm", call.name) + s.Equal([]string{"ci", "--omit=dev"}, call.args) + s.Equal(targetDir, call.dir) +} + +// --- installSubset with stub executor --- + +func (s *DepsNodejsSuite) Test_installSubset_createsFilteredPackageJSON() { + stub := &stubExec{} + installer := &NodeDependencyInstaller{Exec: stub, PM: NodePMNpm} + + appDir := s.T().TempDir() + targetDir := s.T().TempDir() + + s.writeJSON(filepath.Join(appDir, "package.json"), map[string]any{ + "name": "test", + "version": "1.0.0", + "dependencies": map[string]any{ + "express": "^4.18.0", + "lodash": "^4.17.0", + "zod": "^3.0.0", + }, + }) + s.Require().NoError(os.WriteFile( + filepath.Join(appDir, "package-lock.json"), []byte(`{"lockfileVersion":3}`), 0644, + )) + + err := installer.InstallDependencies( + context.Background(), appDir, targetDir, []string{"express", "zod"}, io.Discard, + ) + s.Require().NoError(err) + + data, err := os.ReadFile(filepath.Join(targetDir, "package.json")) + s.Require().NoError(err) + + var pkg map[string]any + s.Require().NoError(json.Unmarshal(data, &pkg)) + + deps := pkg["dependencies"].(map[string]any) + s.Equal("^4.18.0", deps["express"]) + s.Equal("^3.0.0", deps["zod"]) + s.NotContains(deps, "lodash") + + s.FileExists(filepath.Join(targetDir, "package-lock.json")) + + s.Require().Len(stub.calls, 1) + s.Equal("npm", stub.calls[0].name) +} + +// --- helpers --- + +func (s *DepsNodejsSuite) writeJSON(path string, v any) { + data, err := json.MarshalIndent(v, "", " ") + s.Require().NoError(err) + s.Require().NoError(os.WriteFile(path, data, 0644)) +} diff --git a/apps/cli/internal/build/deps_python.go b/apps/cli/internal/build/deps_python.go new file mode 100644 index 00000000..b4596688 --- /dev/null +++ b/apps/cli/internal/build/deps_python.go @@ -0,0 +1,72 @@ +package build + +import ( + "context" + "fmt" + "io" + "os" + "path/filepath" + "strings" +) + +// PythonDependencyInstaller installs Python production dependencies using pip. +type PythonDependencyInstaller struct { + Exec CommandExecutor +} + +func (p *PythonDependencyInstaller) InstallDependencies( + ctx context.Context, + appDir string, + targetDir string, + packages []string, + toolOutput io.Writer, +) error { + if packages != nil { + return p.installSubset(ctx, targetDir, packages, toolOutput) + } + return p.installAll(ctx, appDir, targetDir, toolOutput) +} + +func (p *PythonDependencyInstaller) installAll( + ctx context.Context, + appDir string, + targetDir string, + toolOutput io.Writer, +) error { + requirementsTxt := filepath.Join(appDir, "requirements.txt") + pyprojectToml := filepath.Join(appDir, "pyproject.toml") + + if _, err := os.Stat(requirementsTxt); err == nil { + return p.Exec.Run(ctx, appDir, toolOutput, + "pip", "install", "-r", requirementsTxt, "-t", targetDir, "--no-user") + } + + if _, err := os.Stat(pyprojectToml); err == nil { + return p.Exec.Run(ctx, appDir, toolOutput, + "pip", "install", appDir, "-t", targetDir, "--no-user") + } + + return nil +} + +func (p *PythonDependencyInstaller) installSubset( + ctx context.Context, + targetDir string, + packages []string, + toolOutput io.Writer, +) error { + if len(packages) == 0 { + return nil + } + + args := []string{"install", "-t", targetDir, "--no-user"} + args = append(args, packages...) + + err := p.Exec.Run(ctx, "", toolOutput, "pip", args...) + if err != nil { + return fmt.Errorf("pip install failed for packages [%s]: %w", + strings.Join(packages, ", "), err) + } + + return nil +} diff --git a/apps/cli/internal/build/deps_python_test.go b/apps/cli/internal/build/deps_python_test.go new file mode 100644 index 00000000..f4a2097d --- /dev/null +++ b/apps/cli/internal/build/deps_python_test.go @@ -0,0 +1,105 @@ +package build + +import ( + "context" + "io" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" +) + +type DepsPythonSuite struct { + suite.Suite +} + +func TestDepsPythonSuite(t *testing.T) { + suite.Run(t, new(DepsPythonSuite)) +} + +func (s *DepsPythonSuite) Test_installAll_fromRequirementsTxt() { + stub := &stubExec{} + installer := &PythonDependencyInstaller{Exec: stub} + + appDir := s.T().TempDir() + targetDir := s.T().TempDir() + + s.Require().NoError(os.WriteFile( + filepath.Join(appDir, "requirements.txt"), []byte("boto3>=1.34.0\n"), 0644, + )) + + err := installer.InstallDependencies(context.Background(), appDir, targetDir, nil, io.Discard) + s.Require().NoError(err) + + s.Require().Len(stub.calls, 1) + call := stub.calls[0] + s.Equal("pip", call.name) + s.Contains(call.args, "-r") + s.Contains(call.args, filepath.Join(appDir, "requirements.txt")) + s.Contains(call.args, "-t") + s.Contains(call.args, targetDir) +} + +func (s *DepsPythonSuite) Test_installAll_fromPyprojectToml() { + stub := &stubExec{} + installer := &PythonDependencyInstaller{Exec: stub} + + appDir := s.T().TempDir() + targetDir := s.T().TempDir() + + s.Require().NoError(os.WriteFile( + filepath.Join(appDir, "pyproject.toml"), []byte("[project]\nname = \"test\"\n"), 0644, + )) + + err := installer.InstallDependencies(context.Background(), appDir, targetDir, nil, io.Discard) + s.Require().NoError(err) + + s.Require().Len(stub.calls, 1) + call := stub.calls[0] + s.Equal("pip", call.name) + s.Contains(call.args, appDir) + s.Contains(call.args, "-t") +} + +func (s *DepsPythonSuite) Test_installAll_noManifest_skips() { + stub := &stubExec{} + installer := &PythonDependencyInstaller{Exec: stub} + + appDir := s.T().TempDir() + targetDir := s.T().TempDir() + + err := installer.InstallDependencies(context.Background(), appDir, targetDir, nil, io.Discard) + s.NoError(err) + s.Empty(stub.calls) +} + +func (s *DepsPythonSuite) Test_installSubset_invokesCorrectPackages() { + stub := &stubExec{} + installer := &PythonDependencyInstaller{Exec: stub} + + targetDir := s.T().TempDir() + + err := installer.InstallDependencies( + context.Background(), "", targetDir, []string{"boto3", "pydantic"}, io.Discard, + ) + s.Require().NoError(err) + + s.Require().Len(stub.calls, 1) + call := stub.calls[0] + s.Equal("pip", call.name) + s.Contains(call.args, "boto3") + s.Contains(call.args, "pydantic") + s.Contains(call.args, "-t") +} + +func (s *DepsPythonSuite) Test_installSubset_emptyList_skips() { + stub := &stubExec{} + installer := &PythonDependencyInstaller{Exec: stub} + + err := installer.InstallDependencies( + context.Background(), "", s.T().TempDir(), []string{}, io.Discard, + ) + s.NoError(err) + s.Empty(stub.calls) +} diff --git a/apps/cli/internal/build/exec.go b/apps/cli/internal/build/exec.go new file mode 100644 index 00000000..4e5abd86 --- /dev/null +++ b/apps/cli/internal/build/exec.go @@ -0,0 +1,36 @@ +package build + +import ( + "context" + "fmt" + "io" + "os/exec" +) + +// ExecCommandExecutor is the default CommandExecutor that shells out +// to external tools via os/exec. +type ExecCommandExecutor struct{} + +// Run invokes a sub-process and writes all output to the provided toolOutput writer. +// The command is resolved to an absolute path via PATH and an error +// is returned if it cannot be found. +func (e *ExecCommandExecutor) Run( + ctx context.Context, + dir string, + toolOutput io.Writer, + name string, + args ...string, +) error { + bin, err := exec.LookPath(name) + if err != nil { + return fmt.Errorf("%s not found on PATH: %w", name, err) + } + cmd := exec.CommandContext(ctx, bin, args...) + cmd.Dir = dir + cmd.Stdout = toolOutput + cmd.Stderr = toolOutput + if err := cmd.Run(); err != nil { + return fmt.Errorf("%s failed: %w", name, err) + } + return nil +} diff --git a/apps/cli/internal/build/exec_test.go b/apps/cli/internal/build/exec_test.go new file mode 100644 index 00000000..e2851b8b --- /dev/null +++ b/apps/cli/internal/build/exec_test.go @@ -0,0 +1,30 @@ +package build + +import ( + "context" + "io" + "os" + "path/filepath" +) + +// stubExec records all command invocations without executing them. +// It writes a dummy file to the target directory so zips aren't empty. +type stubExec struct { + calls []execCall +} + +type execCall struct { + dir string + name string + args []string +} + +func (s *stubExec) Run(_ context.Context, dir string, _ io.Writer, name string, args ...string) error { + s.calls = append(s.calls, execCall{dir: dir, name: name, args: args}) + // Write a dummy file so downstream zip creation has something to archive. + if dir != "" { + _ = os.MkdirAll(dir, 0755) + _ = os.WriteFile(filepath.Join(dir, "stub-output"), []byte("stub"), 0644) + } + return nil +} diff --git a/apps/cli/internal/build/handler_deps.go b/apps/cli/internal/build/handler_deps.go new file mode 100644 index 00000000..8663d4b9 --- /dev/null +++ b/apps/cli/internal/build/handler_deps.go @@ -0,0 +1,82 @@ +package build + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + + "github.com/BurntSushi/toml" +) + +// ReadHandlerDependencies reads per-handler dependency declarations from the +// language-appropriate manifest in appDir. Returns nil if no declarations exist. +func ReadHandlerDependencies(registry *Registry, runtime, appDir string) (map[string][]string, error) { + reader := registry.GetHandlerDependencyReader(runtime) + if reader == nil { + return nil, nil + } + return reader.ReadHandlerDependencies(appDir) +} + +// NodeHandlerDependencyReader reads celerity.handlerDependencies from package.json. +type NodeHandlerDependencyReader struct{} + +func (r *NodeHandlerDependencyReader) ReadHandlerDependencies(appDir string) (map[string][]string, error) { + path := filepath.Join(appDir, "package.json") + data, err := os.ReadFile(path) + if err != nil { + if os.IsNotExist(err) { + return nil, nil + } + return nil, fmt.Errorf("reading package.json: %w", err) + } + + var pkg struct { + Celerity *struct { + HandlerDependencies map[string][]string `json:"handlerDependencies"` + } `json:"celerity"` + } + if err := json.Unmarshal(data, &pkg); err != nil { + return nil, fmt.Errorf("parsing package.json: %w", err) + } + + if pkg.Celerity == nil { + return nil, nil + } + + return pkg.Celerity.HandlerDependencies, nil +} + +// PythonHandlerDependencyReader reads [tool.celerity.handlerDependencies] +// from pyproject.toml. +type PythonHandlerDependencyReader struct{} + +func (r *PythonHandlerDependencyReader) ReadHandlerDependencies(appDir string) (map[string][]string, error) { + path := filepath.Join(appDir, "pyproject.toml") + data, err := os.ReadFile(path) + if err != nil { + if os.IsNotExist(err) { + return nil, nil + } + return nil, fmt.Errorf("reading pyproject.toml: %w", err) + } + + var pyproject struct { + Tool struct { + Celerity struct { + HandlerDependencies map[string][]string `toml:"handlerDependencies"` + } `toml:"celerity"` + } `toml:"tool"` + } + if err := toml.Unmarshal(data, &pyproject); err != nil { + return nil, fmt.Errorf("parsing pyproject.toml: %w", err) + } + + deps := pyproject.Tool.Celerity.HandlerDependencies + if len(deps) == 0 { + return nil, nil + } + + return deps, nil +} diff --git a/apps/cli/internal/build/handler_deps_test.go b/apps/cli/internal/build/handler_deps_test.go new file mode 100644 index 00000000..1129b65e --- /dev/null +++ b/apps/cli/internal/build/handler_deps_test.go @@ -0,0 +1,161 @@ +package build + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" +) + +type HandlerDepsSuite struct { + suite.Suite +} + +func TestHandlerDepsSuite(t *testing.T) { + suite.Run(t, new(HandlerDepsSuite)) +} + +// --- NodeHandlerDependencyReader --- + +func (s *HandlerDepsSuite) Test_NodeHandlerDependencyReader_ReadHandlerDependencies_returnsDeps() { + dir := s.T().TempDir() + pkgJSON := `{ + "name": "my-app", + "version": "1.0.0", + "celerity": { + "handlerDependencies": { + "orderHandler": ["stripe", "lodash"], + "emailHandler": ["nodemailer"] + } + } + }` + s.Require().NoError(os.WriteFile(filepath.Join(dir, "package.json"), []byte(pkgJSON), 0644)) + + reader := &NodeHandlerDependencyReader{} + deps, err := reader.ReadHandlerDependencies(dir) + + s.Require().NoError(err) + s.Require().NotNil(deps) + s.Equal([]string{"stripe", "lodash"}, deps["orderHandler"]) + s.Equal([]string{"nodemailer"}, deps["emailHandler"]) +} + +func (s *HandlerDepsSuite) Test_NodeHandlerDependencyReader_ReadHandlerDependencies_returnsNilWhenSectionAbsent() { + dir := s.T().TempDir() + pkgJSON := `{"name": "my-app", "version": "1.0.0"}` + s.Require().NoError(os.WriteFile(filepath.Join(dir, "package.json"), []byte(pkgJSON), 0644)) + + reader := &NodeHandlerDependencyReader{} + deps, err := reader.ReadHandlerDependencies(dir) + + s.NoError(err) + s.Nil(deps) +} + +func (s *HandlerDepsSuite) Test_NodeHandlerDependencyReader_ReadHandlerDependencies_returnsNilWhenFileDoesNotExist() { + dir := s.T().TempDir() + + reader := &NodeHandlerDependencyReader{} + deps, err := reader.ReadHandlerDependencies(dir) + + s.NoError(err) + s.Nil(deps) +} + +// --- PythonHandlerDependencyReader --- + +func (s *HandlerDepsSuite) Test_PythonHandlerDependencyReader_ReadHandlerDependencies_returnsDeps() { + dir := s.T().TempDir() + pyproject := ` +[tool.celerity.handlerDependencies] +orderHandler = ["stripe", "requests"] +emailHandler = ["boto3"] +` + s.Require().NoError(os.WriteFile(filepath.Join(dir, "pyproject.toml"), []byte(pyproject), 0644)) + + reader := &PythonHandlerDependencyReader{} + deps, err := reader.ReadHandlerDependencies(dir) + + s.Require().NoError(err) + s.Require().NotNil(deps) + s.Equal([]string{"stripe", "requests"}, deps["orderHandler"]) + s.Equal([]string{"boto3"}, deps["emailHandler"]) +} + +func (s *HandlerDepsSuite) Test_PythonHandlerDependencyReader_ReadHandlerDependencies_returnsNilWhenSectionAbsent() { + dir := s.T().TempDir() + pyproject := ` +[project] +name = "my-app" +version = "1.0.0" +` + s.Require().NoError(os.WriteFile(filepath.Join(dir, "pyproject.toml"), []byte(pyproject), 0644)) + + reader := &PythonHandlerDependencyReader{} + deps, err := reader.ReadHandlerDependencies(dir) + + s.NoError(err) + s.Nil(deps) +} + +func (s *HandlerDepsSuite) Test_PythonHandlerDependencyReader_ReadHandlerDependencies_returnsNilWhenFileDoesNotExist() { + dir := s.T().TempDir() + + reader := &PythonHandlerDependencyReader{} + deps, err := reader.ReadHandlerDependencies(dir) + + s.NoError(err) + s.Nil(deps) +} + +// --- ReadHandlerDependencies (registry delegation) --- + +func (s *HandlerDepsSuite) Test_ReadHandlerDependencies_delegatesToNodeReader() { + dir := s.T().TempDir() + pkgJSON := `{ + "name": "my-app", + "celerity": { + "handlerDependencies": { + "handler1": ["express"] + } + } + }` + s.Require().NoError(os.WriteFile(filepath.Join(dir, "package.json"), []byte(pkgJSON), 0644)) + + registry := NewRegistry() + registry.RegisterHandlerDependencyReader("nodejs", &NodeHandlerDependencyReader{}) + + deps, err := ReadHandlerDependencies(registry, "nodejs24.x", dir) + + s.Require().NoError(err) + s.Require().NotNil(deps) + s.Equal([]string{"express"}, deps["handler1"]) +} + +func (s *HandlerDepsSuite) Test_ReadHandlerDependencies_delegatesToPythonReader() { + dir := s.T().TempDir() + pyproject := ` +[tool.celerity.handlerDependencies] +handler1 = ["boto3"] +` + s.Require().NoError(os.WriteFile(filepath.Join(dir, "pyproject.toml"), []byte(pyproject), 0644)) + + registry := NewRegistry() + registry.RegisterHandlerDependencyReader("python", &PythonHandlerDependencyReader{}) + + deps, err := ReadHandlerDependencies(registry, "python3.12", dir) + + s.Require().NoError(err) + s.Require().NotNil(deps) + s.Equal([]string{"boto3"}, deps["handler1"]) +} + +func (s *HandlerDepsSuite) Test_ReadHandlerDependencies_returnsNilWhenNoReaderRegistered() { + registry := NewRegistry() + + deps, err := ReadHandlerDependencies(registry, "rust1.x", "/tmp/nodir") + + s.NoError(err) + s.Nil(deps) +} diff --git a/apps/cli/internal/build/lambda.go b/apps/cli/internal/build/lambda.go new file mode 100644 index 00000000..60dc7af7 --- /dev/null +++ b/apps/cli/internal/build/lambda.go @@ -0,0 +1,699 @@ +package build + +import ( + "archive/zip" + "context" + "crypto/sha256" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/newstack-cloud/celerity/apps/cli/internal/seed" + "go.uber.org/zap" +) + +// LambdaStrategy packages a Celerity application for AWS Lambda as a +// single shared app code bundle (referenced by every handler's Lambda +// function) plus a shared or per-handler dependency layer. Per-handler +// dep layers are opt-in via handlerDependencies declarations in the +// developer's package manifest. +type LambdaStrategy struct { + Registry *Registry + // Bootstraps maps runtime prefixes (e.g. "nodejs", "python") to the + // Lambda-specific handler bootstrap for that language. Kept on the + // strategy rather than the shared registry because bootstraps are + // deploy-target-specific, and a future GCP strategy would ship its own + // mapping with different SDK imports. + Bootstraps map[string]HandlerBootstrap +} + +// Matched by prefix so a versioned identifier like "nodejs24.x" resolves to +// the "nodejs" entry. Returns nil for a runtime with no registered bootstrap, +// which leaves the build working for runtimes without SDK wrapping. +func (s *LambdaStrategy) bootstrapFor(runtime string) HandlerBootstrap { + for prefix, bootstrap := range s.Bootstraps { + if strings.HasPrefix(runtime, prefix) { + return bootstrap + } + } + return nil +} + +func (s *LambdaStrategy) Build(ctx context.Context, params *BuildParams) (*Manifest, error) { + if err := os.MkdirAll(params.OutputDir, 0755); err != nil { + return nil, fmt.Errorf("creating output directory: %w", err) + } + + // Checked before the dependency installer is looked up, which errors for a + // runtime nothing is registered for. A compiled language needs no installer + // because its dependencies are linked into the executable. + if params.Toolchain != nil { + return s.buildCompiledManifest(ctx, params) + } + + installer, err := s.Registry.GetDependencyInstaller(params.Runtime) + if err != nil { + return nil, err + } + compiler := s.Registry.GetSourceCompiler(params.Runtime) + + compiledDir, err := compileSource(ctx, params, compiler) + if err != nil { + return nil, err + } + if compiledDir != "" { + defer os.RemoveAll(compiledDir) + } + + manifest := &Manifest{ + Version: ManifestVersion, + Runtime: params.Runtime, + Target: params.DeployTarget, + Handlers: map[string]*HandlerArtifacts{}, + Lambda: &LambdaManifest{}, + } + + params.Logger.Info("building shared app code bundle") + appCode, entryPoint, err := s.buildAppArchive(params, compiledDir) + if err != nil { + return nil, fmt.Errorf("building app code bundle: %w", err) + } + manifest.Lambda.AppCode = appCode + manifest.Lambda.EntryPoint = entryPoint + + if err := s.buildDependencyLayers(ctx, installer, params, manifest); err != nil { + return nil, err + } + + runner, err := s.buildMaintenanceRunner(params) + if err != nil { + return nil, fmt.Errorf("building the database maintenance runner: %w", err) + } + manifest.Lambda.MaintenanceRunner = runner + + if params.Uploader != nil { + if err := uploadAllArtifacts(ctx, params, manifest); err != nil { + return nil, fmt.Errorf("uploading artifacts: %w", err) + } + } + + return manifest, nil +} + +func (s *LambdaStrategy) buildDependencyLayers( + ctx context.Context, + installer DependencyInstaller, + params *BuildParams, + manifest *Manifest, +) error { + sharedHandlers, customHandlers := partitionHandlers(params.Handlers, params.HandlerDependencies) + + if len(sharedHandlers) > 0 { + params.Logger.Info("building shared dependency layer") + layer, err := buildLayer(ctx, installer, params, nil, "shared-layer") + if err != nil { + return fmt.Errorf("building shared layer: %w", err) + } + if err := checkLayerSize(layer, "shared", params.Logger); err != nil { + return err + } + manifest.Lambda.SharedLayer = layer + } + + customLayers, err := buildCustomLayers(ctx, installer, params, customHandlers) + if err != nil { + return err + } + + for _, handler := range params.Handlers { + arts := &HandlerArtifacts{Lambda: &LambdaHandlerArtifacts{}} + if layer, ok := customLayers[handler.ResourceName]; ok { + arts.Lambda.Dependencies = layer + } + manifest.Handlers[handler.ResourceName] = arts + } + return nil +} + +// The bundle is the whole source tree, compiled if applicable, plus the +// per-runtime Celerity SDK bootstrap file. The entry point comes back empty for +// a runtime with no registered bootstrap. +func (s *LambdaStrategy) buildAppArchive( + params *BuildParams, + compiledDir string, +) (*Artifact, string, error) { + stagingDir, err := os.MkdirTemp("", "celerity-app-*") + if err != nil { + return nil, "", err + } + defer os.RemoveAll(stagingDir) + + sourceDir := params.AppDir + if compiledDir != "" { + sourceDir = compiledDir + } + if err := copySourceForLambda(sourceDir, stagingDir); err != nil { + return nil, "", err + } + + if err := writeBundleModuleManifest(params.Runtime, params.AppDir, stagingDir); err != nil { + return nil, "", err + } + + entryPoint, err := s.writeHandlerBootstrap(params.Runtime, params.AppDir, stagingDir) + if err != nil { + return nil, "", err + } + + if err := writeResourceLinksFile(stagingDir, params.Blueprint); err != nil { + return nil, "", err + } + + art, err := writeArtifact(ArtifactTypeLambdaArchive, stagingDir, params.OutputDir, "app") + if err != nil { + return nil, "", err + } + return art, entryPoint, nil +} + +// The blueprint-derived links JSON rides in the Lambda app archive so the SDK +// can read it on cold start rather than through a large env var. It is written +// even when the blueprint has no qualifying resources, which keeps the SDK +// contract to a file that is always present. +func writeResourceLinksFile(stagingDir string, bp *schema.Blueprint) error { + linksJSON, err := seed.ResourceLinksJSON(bp) + if err != nil { + return fmt.Errorf("generating resource links JSON: %w", err) + } + if linksJSON == "" { + linksJSON = "{}" + } + target := filepath.Join(stagingDir, ResourceLinksFilename) + if err := os.WriteFile(target, []byte(linksJSON), 0644); err != nil { + return fmt.Errorf("writing resource links file: %w", err) + } + + return writeHandlerScopeFile(stagingDir, bp) +} + +// The per-handler resource scope rides alongside the resource links so a +// handler initialises only the resources it uses rather than every resource the +// application declares. +// +// Written unconditionally, like the links file, so the SDK always has a file to +// parse. An empty payload means no handler declared a scope, which the SDK +// treats as absent scope information and falls back from, rather than as no +// handler using anything. +func writeHandlerScopeFile(stagingDir string, bp *schema.Blueprint) error { + scopeJSON, err := seed.HandlerScopeJSON(bp) + if err != nil { + return fmt.Errorf("generating handler scope JSON: %w", err) + } + if scopeJSON == "" { + scopeJSON = "{}" + } + target := filepath.Join(stagingDir, HandlerScopeFilename) + if err := os.WriteFile(target, []byte(scopeJSON), 0644); err != nil { + return fmt.Errorf("writing handler scope file: %w", err) + } + return nil +} + +func (s *LambdaStrategy) writeHandlerBootstrap( + runtime string, + appDir string, + stagingDir string, +) (string, error) { + bootstrap := s.bootstrapFor(runtime) + if bootstrap == nil { + return "", nil + } + + // Checked before the file is written rather than after the deploy. The entry + // file imports this package, and a bundle without it produces handlers that + // provision cleanly and then fail on their first invocation with a module + // resolution error, a long way from the missing dependency that caused it. + if err := requireAdapterPackage(bootstrap, runtime, appDir); err != nil { + return "", err + } + + entryPoint, err := bootstrap.Generate(stagingDir) + if err != nil { + return "", fmt.Errorf("generating Lambda bootstrap: %w", err) + } + return entryPoint, nil +} + +// A check for "some Celerity SDK package" is not enough, because an app can +// depend on several of them and still be missing the serverless adapter. That +// is how a project reached a real deployment with every handler unable to +// start. +func requireAdapterPackage(bootstrap HandlerBootstrap, runtime, appDir string) error { + required := bootstrap.RequiredPackage() + if required == "" || appDir == "" { + return nil + } + + declared, err := appDeclaresPackage(runtime, appDir, required) + if err != nil { + // An unreadable manifest is not proof the dependency is absent, and + // failing the build on it would be worse than the check not running. + return nil + } + if declared { + return nil + } + + return fmt.Errorf( + "the generated Lambda entry file imports %q, but it is not a dependency of the "+ + "application; add %q to the project's dependencies so it is included in the "+ + "deployment bundle", + required, required, + ) +} + +func partitionHandlers( + handlers []HandlerInfo, + handlerDeps map[string][]string, +) (shared, custom []HandlerInfo) { + if len(handlerDeps) == 0 { + return handlers, nil + } + for _, h := range handlers { + if _, ok := handlerDeps[h.ResourceName]; ok { + custom = append(custom, h) + } else { + shared = append(shared, h) + } + } + return shared, custom +} + +func buildCustomLayers( + ctx context.Context, + installer DependencyInstaller, + params *BuildParams, + handlers []HandlerInfo, +) (map[string]*Artifact, error) { + if len(handlers) == 0 { + return nil, nil + } + + layers := map[string]*Artifact{} + // Deduplicate identical dep sets. + type dedupEntry struct { + key string + packages []string + artifact *Artifact + } + seen := map[string]*dedupEntry{} + + for _, h := range handlers { + packages := params.HandlerDependencies[h.ResourceName] + key := depSetKey(packages) + if entry, exists := seen[key]; exists { + layers[h.ResourceName] = entry.artifact + continue + } + + params.Logger.Info("building handler layer", + zap.String("handler", h.ResourceName), + zap.Int("packages", len(packages)), + ) + prefix := h.ResourceName + "-layer" + layer, err := buildLayer(ctx, installer, params, packages, prefix) + if err != nil { + return nil, fmt.Errorf("building layer for %s: %w", h.ResourceName, err) + } + if err := checkLayerSize(layer, h.ResourceName, params.Logger); err != nil { + return nil, err + } + + seen[key] = &dedupEntry{key: key, packages: packages, artifact: layer} + layers[h.ResourceName] = layer + } + + return layers, nil +} + +func buildLayer( + ctx context.Context, + installer DependencyInstaller, + params *BuildParams, + packages []string, + prefix string, +) (*Artifact, error) { + stagingDir, err := os.MkdirTemp("", "celerity-layer-*") + if err != nil { + return nil, err + } + defer os.RemoveAll(stagingDir) + + installDir := filepath.Join(stagingDir, lambdaLayerSubdir(params.Runtime)) + if err := os.MkdirAll(installDir, 0755); err != nil { + return nil, err + } + + if err := installer.InstallDependencies(ctx, params.AppDir, installDir, packages, params.ToolOutput); err != nil { + return nil, err + } + + return writeArtifact(ArtifactTypeLambdaLayer, stagingDir, params.OutputDir, prefix) +} + +func compileSource( + ctx context.Context, + params *BuildParams, + compiler SourceCompiler, +) (string, error) { + if compiler == nil { + return "", nil + } + + params.Logger.Info("compiling source", zap.String("runtime", params.Runtime)) + outDir, err := os.MkdirTemp("", "celerity-compiled-*") + if err != nil { + return "", err + } + + if err := compiler.Compile(ctx, params.AppDir, outDir, params.ToolOutput); err != nil { + os.RemoveAll(outDir) + return "", fmt.Errorf("compiling source: %w", err) + } + + return outDir, nil +} + +func uploadAllArtifacts(ctx context.Context, params *BuildParams, manifest *Manifest) error { + if manifest.Lambda == nil { + return nil + } + prefix := params.InstanceName + if prefix == "" { + prefix = "default" + } + + if manifest.Lambda.AppCode != nil { + key := fmt.Sprintf("%s/app/%s.zip", prefix, trimHashPrefix(manifest.Lambda.AppCode.ContentHash)) + if err := params.Uploader.Upload(ctx, manifest.Lambda.AppCode, key); err != nil { + return fmt.Errorf("uploading app code: %w", err) + } + } + + if manifest.Lambda.SharedLayer != nil { + key := fmt.Sprintf("%s/shared-layer/%s.zip", prefix, trimHashPrefix(manifest.Lambda.SharedLayer.ContentHash)) + if err := params.Uploader.Upload(ctx, manifest.Lambda.SharedLayer, key); err != nil { + return fmt.Errorf("uploading shared layer: %w", err) + } + } + + if manifest.Lambda.MaintenanceRunner != nil { + key := fmt.Sprintf("%s/maintenance-runner/%s.zip", + prefix, trimHashPrefix(manifest.Lambda.MaintenanceRunner.ContentHash)) + if err := params.Uploader.Upload(ctx, manifest.Lambda.MaintenanceRunner, key); err != nil { + return fmt.Errorf("uploading the maintenance runner: %w", err) + } + } + + for name, arts := range manifest.Handlers { + if arts.Lambda == nil || arts.Lambda.Dependencies == nil { + continue + } + key := fmt.Sprintf("%s/%s/layer/%s.zip", prefix, name, trimHashPrefix(arts.Lambda.Dependencies.ContentHash)) + if err := params.Uploader.Upload(ctx, arts.Lambda.Dependencies, key); err != nil { + return fmt.Errorf("uploading handler %s layer: %w", name, err) + } + } + + return nil +} + +// Writes to a temp name, hashes, then renames to "-.zip", so the +// on-disk filename always matches the content and a stale build cannot hide +// behind a stable name. +func writeArtifact( + artifactType string, + stagingDir string, + outputDir string, + prefix string, +) (*Artifact, error) { + tempPath := filepath.Join(outputDir, prefix+"-tmp.zip") + if err := createZipArchive(stagingDir, tempPath); err != nil { + return nil, err + } + + hash, err := fileContentHash(tempPath) + if err != nil { + os.Remove(tempPath) + return nil, fmt.Errorf("hashing artifact: %w", err) + } + + finalPath := filepath.Join(outputDir, fmt.Sprintf("%s-%s.zip", prefix, hash)) + if err := os.Rename(tempPath, finalPath); err != nil { + return nil, fmt.Errorf("renaming artifact: %w", err) + } + + info, err := os.Stat(finalPath) + if err != nil { + return nil, fmt.Errorf("stat artifact: %w", err) + } + + return &Artifact{ + Type: artifactType, + LocalPath: finalPath, + ContentHash: "sha256:" + hash, + Size: info.Size(), + }, nil +} + +func checkLayerSize(layer *Artifact, name string, logger *zap.Logger) error { + if layer.Size > LayerSizeLimit { + return fmt.Errorf( + "layer %q is %d bytes (%d MB), exceeding the Lambda 250MB limit", + name, layer.Size, layer.Size/(1024*1024), + ) + } + if layer.Size > LayerSizeWarning { + logger.Warn("layer approaching Lambda size limit", + zap.String("layer", name), + zap.Int64("sizeBytes", layer.Size), + zap.Int64("limitBytes", LayerSizeLimit), + ) + } + return nil +} + +func depSetKey(packages []string) string { + sorted := make([]string, len(packages)) + copy(sorted, packages) + sort.Strings(sorted) + return strings.Join(sorted, "\n") +} + +func trimHashPrefix(hash string) string { + return strings.TrimPrefix(hash, "sha256:") +} + +// The directory within the layer archive that dependencies are installed into. +// +// Node stops at "nodejs" because npm creates node_modules inside whatever +// directory it installs into, so naming node_modules here put every package at +// /opt/nodejs/node_modules/node_modules/, one level below where the runtime +// looks, and nothing in the layer resolved. Python keeps the full path because +// pip installs into the directory it is given rather than creating one. +func lambdaLayerSubdir(runtime string) string { + switch { + case strings.HasPrefix(runtime, "nodejs"): + return "nodejs" + case strings.HasPrefix(runtime, "python"): + version := strings.TrimPrefix(runtime, "python") + return fmt.Sprintf("python/lib/python%s/site-packages", version) + default: + return "lib" + } +} + +func copySourceForLambda(appDir, stagingDir string) error { + return filepath.WalkDir(appDir, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + + rel, err := filepath.Rel(appDir, path) + if err != nil { + return err + } + + if shouldSkipForLambda(rel, d) { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + + dest := filepath.Join(stagingDir, rel) + if d.IsDir() { + return os.MkdirAll(dest, 0755) + } + + return copyFile(path, dest) + }) +} + +var lambdaSkipDirs = map[string]bool{ + "node_modules": true, ".git": true, ".celerity": true, + "__pycache__": true, ".pytest_cache": true, ".mypy_cache": true, + ".venv": true, "venv": true, + "test": true, "tests": true, "__tests__": true, + "coverage": true, ".nyc_output": true, +} + +func shouldSkipForLambda(rel string, d fs.DirEntry) bool { + if d.IsDir() && lambdaSkipDirs[d.Name()] { + return true + } + if strings.HasPrefix(rel, "app.blueprint") || strings.HasPrefix(rel, "app.deploy") { + return true + } + return false +} + +// Stamped on every archive entry so builds are byte-for-byte reproducible. +var reproducibleArchiveTime = time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC) + +func createZipArchive(sourceDir, outputPath string) error { + outFile, err := os.Create(outputPath) + if err != nil { + return err + } + defer outFile.Close() + + w := zip.NewWriter(outFile) + defer w.Close() + + return filepath.WalkDir(sourceDir, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + return nil + } + + rel, err := filepath.Rel(sourceDir, path) + if err != nil { + return err + } + + info, err := d.Info() + if err != nil { + return err + } + + header, err := zip.FileInfoHeader(info) + if err != nil { + return err + } + header.Name = rel + header.Method = zip.Deflate + + // A fixed timestamp keeps the same inputs producing the same archive. + // Modification times would otherwise feed the content hash, and a + // dependency layer is rebuilt by re-running the package manager, which + // rewrites every mtime. That yields a new hash, a new layer resource + // name, and a deploy whose blueprint no longer matches the change set + // staged from the previous build. The date is arbitrary and only has to + // be stable and after 1980, the earliest a zip entry can express. + header.Modified = reproducibleArchiveTime + + if info.Mode()&0111 != 0 { + header.SetMode(info.Mode()) + } + + writer, err := w.CreateHeader(header) + if err != nil { + return err + } + + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + _, err = io.Copy(writer, file) + return err + }) +} + +func copyFile(src, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + + if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil { + return err + } + + out, err := os.Create(dst) + if err != nil { + return err + } + defer out.Close() + + _, err = io.Copy(out, in) + return err +} + +func fileContentHash(path string) (string, error) { + f, err := os.Open(path) + if err != nil { + return "", err + } + defer f.Close() + + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return "", err + } + + return fmt.Sprintf("%x", h.Sum(nil)), nil +} + +// Declares the bundle's module system to the Node runtime. +// +// Compiling replaces the copied source tree with the compiler's output +// directory, which holds emitted JavaScript and nothing else, so the project's +// package.json never reached the archive. Without one, Node reads every .js +// file as CommonJS, and importing the app's own module from the generated .mjs +// entry fails with "Cannot use import statement outside a module". +// +// Only the module type is written, not a copy of the project manifest. A +// manifest carrying dependencies, main and exports describes a package that is +// installed, and this bundle is unpacked rather than installed. +const bundleModuleManifest = `{"type": "module"}` + "\n" + +func writeBundleModuleManifest(runtime, appDir, stagingDir string) error { + if !strings.HasPrefix(runtime, "nodejs") || !isESMProject(appDir) { + return nil + } + + target := filepath.Join(stagingDir, "package.json") + // A manifest already in the bundle came from the project's own source tree, + // where the author decides what it says. + if _, err := os.Stat(target); err == nil { + return nil + } + + if err := os.WriteFile(target, []byte(bundleModuleManifest), 0644); err != nil { + return fmt.Errorf("writing the bundle module manifest: %w", err) + } + return nil +} diff --git a/apps/cli/internal/build/lambda_bootstrap_nodejs.go b/apps/cli/internal/build/lambda_bootstrap_nodejs.go new file mode 100644 index 00000000..f0686149 --- /dev/null +++ b/apps/cli/internal/build/lambda_bootstrap_nodejs.go @@ -0,0 +1,73 @@ +package build + +import ( + "os" + "path/filepath" +) + +// LambdaNodeBootstrap is the Lambda-specific HandlerBootstrap for Node.js. +// It wraps the developer's app in the Celerity Node SDK's AWS Lambda adapter. +// +// The generated file imports from the `/handler` subpath of +// @celerity-sdk/serverless-aws rather than the package root so only the +// lean entry module is pulled in at cold start, not the full package index. +type LambdaNodeBootstrap struct { + AppDir string +} + +const ( + lambdaNodeBootstrapHandler = "__celerity_lambda_entry__.handler" + lambdaNodeESMFilename = "__celerity_lambda_entry__.mjs" + lambdaNodeCJSFilename = "__celerity_lambda_entry__.js" +) + +// lambdaNodeAdapterPackage is the package the generated entry file imports. The +// app has to depend on it, since the bundle only carries what the app declares. +const lambdaNodeAdapterPackage = "@celerity-sdk/serverless-aws" + +// RequiredPackage returns the adapter package the generated entry file imports. +func (n *LambdaNodeBootstrap) RequiredPackage() string { + return lambdaNodeAdapterPackage +} + +const lambdaNodeESMBootstrapContent = `// Auto-generated by Celerity CLI. Do not edit. +export { handler } from "@celerity-sdk/serverless-aws/handler"; +` + +const lambdaNodeCJSBootstrapContent = `// Auto-generated by Celerity CLI. Do not edit. +const { handler } = require("@celerity-sdk/serverless-aws/handler"); +module.exports = { handler }; +` + +// Generate respects an existing entry file of either variant in stagingDir +// so developers can opt out of the generated bootstrap regardless of the +// project's module system. +func (n *LambdaNodeBootstrap) Generate(stagingDir string) (string, error) { + filename, content := n.selectTemplate() + + if n.hasExistingEntryFile(stagingDir) { + return lambdaNodeBootstrapHandler, nil + } + + target := filepath.Join(stagingDir, filename) + if err := os.WriteFile(target, []byte(content), 0644); err != nil { + return "", err + } + return lambdaNodeBootstrapHandler, nil +} + +func (n *LambdaNodeBootstrap) selectTemplate() (string, string) { + if isESMProject(n.AppDir) { + return lambdaNodeESMFilename, lambdaNodeESMBootstrapContent + } + return lambdaNodeCJSFilename, lambdaNodeCJSBootstrapContent +} + +func (n *LambdaNodeBootstrap) hasExistingEntryFile(stagingDir string) bool { + for _, name := range []string{lambdaNodeESMFilename, lambdaNodeCJSFilename} { + if _, err := os.Stat(filepath.Join(stagingDir, name)); err == nil { + return true + } + } + return false +} diff --git a/apps/cli/internal/build/lambda_bootstrap_nodejs_test.go b/apps/cli/internal/build/lambda_bootstrap_nodejs_test.go new file mode 100644 index 00000000..12c822c5 --- /dev/null +++ b/apps/cli/internal/build/lambda_bootstrap_nodejs_test.go @@ -0,0 +1,108 @@ +package build + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" +) + +type BootstrapNodejsSuite struct { + suite.Suite +} + +func TestBootstrapNodejsSuite(t *testing.T) { + suite.Run(t, new(BootstrapNodejsSuite)) +} + +func (s *BootstrapNodejsSuite) Test_Generate_writes_mjs_for_esm_project() { + appDir := s.newProject(`{"name":"x","type":"module"}`) + staging := s.T().TempDir() + bootstrap := &LambdaNodeBootstrap{AppDir: appDir} + + entryPoint, err := bootstrap.Generate(staging) + s.Require().NoError(err) + s.Equal("__celerity_lambda_entry__.handler", entryPoint) + + content, err := os.ReadFile(filepath.Join(staging, "__celerity_lambda_entry__.mjs")) + s.Require().NoError(err) + s.Contains(string(content), `export { handler } from "@celerity-sdk/serverless-aws/handler"`) + + _, err = os.Stat(filepath.Join(staging, "__celerity_lambda_entry__.js")) + s.True(os.IsNotExist(err)) +} + +func (s *BootstrapNodejsSuite) Test_Generate_writes_js_for_cjs_project() { + appDir := s.newProject(`{"name":"x"}`) + staging := s.T().TempDir() + bootstrap := &LambdaNodeBootstrap{AppDir: appDir} + + entryPoint, err := bootstrap.Generate(staging) + s.Require().NoError(err) + s.Equal("__celerity_lambda_entry__.handler", entryPoint) + + content, err := os.ReadFile(filepath.Join(staging, "__celerity_lambda_entry__.js")) + s.Require().NoError(err) + s.Contains(string(content), `require("@celerity-sdk/serverless-aws/handler")`) + s.Contains(string(content), "module.exports = { handler }") + + _, err = os.Stat(filepath.Join(staging, "__celerity_lambda_entry__.mjs")) + s.True(os.IsNotExist(err)) +} + +func (s *BootstrapNodejsSuite) Test_Generate_writes_js_when_package_json_missing() { + appDir := s.T().TempDir() + staging := s.T().TempDir() + bootstrap := &LambdaNodeBootstrap{AppDir: appDir} + + entryPoint, err := bootstrap.Generate(staging) + s.Require().NoError(err) + s.Equal("__celerity_lambda_entry__.handler", entryPoint) + + _, err = os.Stat(filepath.Join(staging, "__celerity_lambda_entry__.js")) + s.NoError(err) +} + +func (s *BootstrapNodejsSuite) Test_Generate_skips_when_user_supplies_mjs() { + appDir := s.newProject(`{"name":"x","type":"module"}`) + staging := s.T().TempDir() + existing := []byte("// user's custom entry\nexport const handler = async () => ({});\n") + existingPath := filepath.Join(staging, "__celerity_lambda_entry__.mjs") + s.Require().NoError(os.WriteFile(existingPath, existing, 0644)) + + bootstrap := &LambdaNodeBootstrap{AppDir: appDir} + entryPoint, err := bootstrap.Generate(staging) + s.Require().NoError(err) + s.Equal("__celerity_lambda_entry__.handler", entryPoint) + + content, err := os.ReadFile(existingPath) + s.Require().NoError(err) + s.Equal(existing, content) +} + +func (s *BootstrapNodejsSuite) Test_Generate_skips_when_user_supplies_cjs() { + appDir := s.newProject(`{"name":"x"}`) + staging := s.T().TempDir() + existing := []byte("// user's custom entry\nexports.handler = async () => ({});\n") + existingPath := filepath.Join(staging, "__celerity_lambda_entry__.js") + s.Require().NoError(os.WriteFile(existingPath, existing, 0644)) + + bootstrap := &LambdaNodeBootstrap{AppDir: appDir} + _, err := bootstrap.Generate(staging) + s.Require().NoError(err) + + content, err := os.ReadFile(existingPath) + s.Require().NoError(err) + s.Equal(existing, content) +} + +func (s *BootstrapNodejsSuite) newProject(packageJSON string) string { + appDir := s.T().TempDir() + s.Require().NoError(os.WriteFile( + filepath.Join(appDir, "package.json"), + []byte(packageJSON), + 0644, + )) + return appDir +} diff --git a/apps/cli/internal/build/lambda_bootstrap_python.go b/apps/cli/internal/build/lambda_bootstrap_python.go new file mode 100644 index 00000000..094ffd30 --- /dev/null +++ b/apps/cli/internal/build/lambda_bootstrap_python.go @@ -0,0 +1,50 @@ +package build + +import ( + "os" + "path/filepath" +) + +// LambdaPythonBootstrap is the Lambda-specific HandlerBootstrap for Python. +// It wraps the developer's app in the Celerity Python SDK's AWS Lambda +// adapter (celerity.serverless.aws.create_lambda_handler). +type LambdaPythonBootstrap struct{} + +// lambdaPythonAdapterDistribution is the distribution providing the +// celerity.serverless.aws module the generated entry file imports. +// +// The bare distribution is enough. The SDK wheel ships the whole celerity +// package tree, the adapter included, and the adapter imports nothing beyond +// the standard library and its own siblings, so no optional extra gates it. +// Unlike Node, where the adapter is a separate package the project has to +// depend on explicitly. +const lambdaPythonAdapterDistribution = "celerity-sdk" + +// RequiredPackage returns the distribution the generated entry file imports from. +func (p *LambdaPythonBootstrap) RequiredPackage() string { + return lambdaPythonAdapterDistribution +} + +const ( + lambdaPythonBootstrapFilename = "__celerity_lambda_entry__.py" + lambdaPythonBootstrapHandler = "__celerity_lambda_entry__.handler" +) + +const lambdaPythonBootstrapContent = `"""Auto-generated by Celerity CLI. Do not edit.""" +from celerity.serverless.aws import create_lambda_handler + +handler = create_lambda_handler() +` + +// Generate respects an existing entry file in stagingDir so developers +// can opt out of the generated bootstrap by writing their own. +func (p *LambdaPythonBootstrap) Generate(stagingDir string) (string, error) { + target := filepath.Join(stagingDir, lambdaPythonBootstrapFilename) + if _, err := os.Stat(target); err == nil { + return lambdaPythonBootstrapHandler, nil + } + if err := os.WriteFile(target, []byte(lambdaPythonBootstrapContent), 0644); err != nil { + return "", err + } + return lambdaPythonBootstrapHandler, nil +} diff --git a/apps/cli/internal/build/lambda_bootstrap_python_test.go b/apps/cli/internal/build/lambda_bootstrap_python_test.go new file mode 100644 index 00000000..a2828b2f --- /dev/null +++ b/apps/cli/internal/build/lambda_bootstrap_python_test.go @@ -0,0 +1,59 @@ +package build + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" +) + +type BootstrapPythonSuite struct { + suite.Suite +} + +func TestBootstrapPythonSuite(t *testing.T) { + suite.Run(t, new(BootstrapPythonSuite)) +} + +func (s *BootstrapPythonSuite) Test_Generate_writes_expected_file() { + staging := s.T().TempDir() + bootstrap := &LambdaPythonBootstrap{} + + entryPoint, err := bootstrap.Generate(staging) + s.Require().NoError(err) + s.Equal("__celerity_lambda_entry__.handler", entryPoint) + + content, err := os.ReadFile(filepath.Join(staging, "__celerity_lambda_entry__.py")) + s.Require().NoError(err) + s.Contains(string(content), "from celerity.serverless.aws import create_lambda_handler") + s.Contains(string(content), "handler = create_lambda_handler()") +} + +func (s *BootstrapPythonSuite) Test_Generate_skips_when_file_already_exists() { + staging := s.T().TempDir() + existingContent := []byte("# user's own entry file\nhandler = custom_handler\n") + existingPath := filepath.Join(staging, "__celerity_lambda_entry__.py") + s.Require().NoError(os.WriteFile(existingPath, existingContent, 0644)) + + bootstrap := &LambdaPythonBootstrap{} + entryPoint, err := bootstrap.Generate(staging) + s.Require().NoError(err) + s.Equal("__celerity_lambda_entry__.handler", entryPoint) + + content, err := os.ReadFile(existingPath) + s.Require().NoError(err) + s.Equal(existingContent, content) +} + +func (s *BootstrapPythonSuite) Test_Generate_fails_when_staging_dir_unwritable() { + staging := s.T().TempDir() + s.Require().NoError(os.Chmod(staging, 0500)) + s.T().Cleanup(func() { + _ = os.Chmod(staging, 0755) + }) + + bootstrap := &LambdaPythonBootstrap{} + _, err := bootstrap.Generate(staging) + s.Require().Error(err) +} diff --git a/apps/cli/internal/build/lambda_compiled.go b/apps/cli/internal/build/lambda_compiled.go new file mode 100644 index 00000000..a5c5a06d --- /dev/null +++ b/apps/cli/internal/build/lambda_compiled.go @@ -0,0 +1,139 @@ +package build + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" + "go.uber.org/zap" +) + +const ( + // compiledBootstrapName is what a custom-runtime Lambda executes. The + // name is fixed by the platform, not chosen here. + compiledBootstrapName = "bootstrap" + + // compiledLambdaRuntime is the custom runtime a compiled executable runs + // on. The blueprint's portable identifier (os-only.debian13) names a base + // OS, and this is what it maps to for AWS. + compiledLambdaRuntime = "provided.al2023" + + // compiledLambdaArch is the architecture a compiled handlers executable + // is built for by default. Graviton costs less per millisecond and Go + // cross-compiles to it at no toolchain cost, and it matches what the + // maintenance runner already ships as. + compiledLambdaArch = "arm64" +) + +// Packages a compiled handlers executable for AWS Lambda. +// +// Almost none of the interpreted path applies. Dependencies are linked into the +// executable, the archive carries a binary rather than the source it was built +// from, and a custom runtime executes `bootstrap` and dispatches on an +// environment variable instead of calling a named function. +// +// One binary serves every handler. Each function gets the same archive and a +// different CELERITY_HANDLER_ID, which the runtime's handler tag is built +// from. +func (s *LambdaStrategy) buildCompiled( + ctx context.Context, + params *BuildParams, + manifest *Manifest, +) error { + toolchain := params.Toolchain + arch := compiledLambdaArch + + params.Logger.Info("building the handlers executable", + zap.String("toolchain", toolchain.Name()), + zap.String("arch", arch), + ) + + stagingDir, err := os.MkdirTemp("", "celerity-handlers-*") + if err != nil { + return err + } + defer os.RemoveAll(stagingDir) + + bootstrap := filepath.Join(stagingDir, compiledBootstrapName) + err = toolchain.BuildBinary(ctx, handlertoolchain.BinaryParams{ + AppDir: params.AppDir, + OS: "linux", + Arch: arch, + OutputPath: bootstrap, + DeployTarget: params.DeployTarget, + Mode: handlertoolchain.ModeDeploy, + }) + if err != nil { + return fmt.Errorf("building the handlers executable: %w", err) + } + + if _, err := os.Stat(bootstrap); err != nil { + return fmt.Errorf( + "the %s toolchain reported success but left no executable at %s: %w", + toolchain.Name(), compiledBootstrapName, err, + ) + } + + // Checked here as well as in the toolchain, because a custom build command + // is free to produce whatever it likes and this is the last point before + // the archive is sealed. + if err := handlertoolchain.CheckArchitecture(bootstrap, arch); err != nil { + return err + } + + if err := writeResourceLinksFile(stagingDir, params.Blueprint); err != nil { + return err + } + + appCode, err := writeArtifact(ArtifactTypeLambdaArchive, stagingDir, params.OutputDir, "handlers") + if err != nil { + return err + } + + manifest.Lambda.AppCode = appCode + manifest.Lambda.EntryPoint = compiledBootstrapName + manifest.Lambda.Architecture = arch + manifest.Lambda.LambdaRuntime = compiledLambdaRuntime + + params.Logger.Info("packaged the handlers executable", + zap.String("artifact", appCode.LocalPath), + zap.Int64("size", appCode.Size), + ) + return nil +} + +// The whole of Build for a compiled language. The maintenance runner and the +// upload are shared with the interpreted path, since neither has anything to do +// with how the application itself was built. +func (s *LambdaStrategy) buildCompiledManifest( + ctx context.Context, + params *BuildParams, +) (*Manifest, error) { + manifest := &Manifest{ + Version: ManifestVersion, + Runtime: params.Runtime, + Target: params.DeployTarget, + Handlers: map[string]*HandlerArtifacts{}, + Lambda: &LambdaManifest{}, + } + + if err := s.buildCompiled(ctx, params, manifest); err != nil { + return nil, err + } + + runner, err := s.buildMaintenanceRunner(params) + if err != nil { + return nil, fmt.Errorf("building the database maintenance runner: %w", err) + } + manifest.Lambda.MaintenanceRunner = runner + + if params.Uploader != nil { + if err := uploadAllArtifacts(ctx, params, manifest); err != nil { + return nil, fmt.Errorf("uploading artifacts: %w", err) + } + } + + return manifest, nil +} diff --git a/apps/cli/internal/build/lambda_compiled_test.go b/apps/cli/internal/build/lambda_compiled_test.go new file mode 100644 index 00000000..5d840907 --- /dev/null +++ b/apps/cli/internal/build/lambda_compiled_test.go @@ -0,0 +1,225 @@ +package build + +import ( + "archive/zip" + "context" + "debug/elf" + "encoding/binary" + "errors" + "os" + "path/filepath" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" + "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +// compiledStubToolchain stands in for a toolchain that writes a binary. +type compiledStubToolchain struct { + built []handlertoolchain.BinaryParams + // machine, when set, makes the stub write an ELF header declaring it. + machine elf.Machine + // skipOutput makes the stub report success without writing anything. + skipOutput bool + buildErr error +} + +func (t *compiledStubToolchain) Name() string { return "stub" } +func (t *compiledStubToolchain) Validate(string) error { return nil } +func (t *compiledStubToolchain) TestCommand(string) ([]string, bool) { return nil, false } + +func (t *compiledStubToolchain) Prepare(context.Context, handlertoolchain.PrepareParams) error { + return nil +} + +func (t *compiledStubToolchain) Extract( + context.Context, handlertoolchain.ExtractParams, +) (*preprocess.HandlerManifest, error) { + return nil, nil +} + +func (t *compiledStubToolchain) WatchPaths() handlertoolchain.WatchPaths { + return handlertoolchain.WatchPaths{} +} + +func (t *compiledStubToolchain) BuildBinary( + _ context.Context, p handlertoolchain.BinaryParams, +) error { + t.built = append(t.built, p) + if t.buildErr != nil { + return t.buildErr + } + if t.skipOutput { + return nil + } + return os.WriteFile(p.OutputPath, elfHeader(t.machineOr(elf.EM_AARCH64)), 0o755) +} + +func (t *compiledStubToolchain) machineOr(fallback elf.Machine) elf.Machine { + if t.machine != 0 { + return t.machine + } + return fallback +} + +// elfHeader is a 64-byte ELF64 header declaring the given machine, which is +// all the architecture check reads. +func elfHeader(machine elf.Machine) []byte { + header := make([]byte, 64) + copy(header, []byte{0x7f, 'E', 'L', 'F'}) + header[4] = 2 + header[5] = 1 + header[6] = 1 + binary.LittleEndian.PutUint16(header[16:], uint16(elf.ET_EXEC)) + binary.LittleEndian.PutUint16(header[18:], uint16(machine)) + binary.LittleEndian.PutUint32(header[20:], 1) + binary.LittleEndian.PutUint16(header[52:], 64) + return header +} + +type LambdaCompiledSuite struct { + suite.Suite + appDir string + outputDir string + toolchain *compiledStubToolchain +} + +func (s *LambdaCompiledSuite) SetupTest() { + s.appDir = s.T().TempDir() + s.outputDir = s.T().TempDir() + s.toolchain = &compiledStubToolchain{} +} + +func (s *LambdaCompiledSuite) build() (*Manifest, error) { + strategy := &LambdaStrategy{Registry: NewRegistry()} + return strategy.Build(context.Background(), &BuildParams{ + AppDir: s.appDir, + Runtime: "os-only.debian13", + DeployTarget: "aws-serverless", + OutputDir: s.outputDir, + Logger: zap.NewNop(), + Toolchain: s.toolchain, + }) +} + +// zipEntries reports the archive's entries and whether each is executable. +func (s *LambdaCompiledSuite) zipEntries(path string) map[string]bool { + r, err := zip.OpenReader(path) + s.Require().NoError(err) + defer r.Close() + + entries := map[string]bool{} + for _, f := range r.File { + entries[f.Name] = f.Mode()&0o111 != 0 + } + return entries +} + +// Nothing is registered for an OS-only runtime, and the interpreted path errors +// when its dependency installer lookup finds none, so the compiled branch has +// to be taken before that lookup. +func (s *LambdaCompiledSuite) Test_Build_does_not_need_a_dependency_installer() { + manifest, err := s.build() + s.Require().NoError(err) + s.Require().NotNil(manifest.Lambda) + s.Assert().Nil(manifest.Lambda.SharedLayer, "a compiled language has no dependency layer") +} + +func (s *LambdaCompiledSuite) Test_Build_archives_only_the_bootstrap_and_the_sdk_files() { + manifest, err := s.build() + s.Require().NoError(err) + + entries := s.zipEntries(manifest.Lambda.AppCode.LocalPath) + s.Assert().Len(entries, 3) + s.Assert().Contains(entries, "bootstrap") + s.Assert().Contains(entries, ResourceLinksFilename) + s.Assert().Contains(entries, HandlerScopeFilename) +} + +// The platform executes the file, so the bit has to survive the archive. +func (s *LambdaCompiledSuite) Test_Build_keeps_the_bootstrap_executable_in_the_archive() { + manifest, err := s.build() + s.Require().NoError(err) + + entries := s.zipEntries(manifest.Lambda.AppCode.LocalPath) + s.Assert().True(entries["bootstrap"], "expected bootstrap to be executable inside the archive") +} + +// Source is not copied, because the archive carries a binary rather than the +// code it was built from. +func (s *LambdaCompiledSuite) Test_Build_does_not_copy_application_source() { + s.Require().NoError(os.WriteFile(filepath.Join(s.appDir, "main.go"), []byte("package main"), 0o644)) + + manifest, err := s.build() + s.Require().NoError(err) + + entries := s.zipEntries(manifest.Lambda.AppCode.LocalPath) + s.Assert().NotContains(entries, "main.go") +} + +// A custom runtime executes bootstrap and dispatches on an environment +// variable, so the transformer needs the runtime and architecture rather than +// a function name. +func (s *LambdaCompiledSuite) Test_Build_records_what_the_transformer_declares_the_function_from() { + manifest, err := s.build() + s.Require().NoError(err) + + s.Assert().Equal("bootstrap", manifest.Lambda.EntryPoint) + s.Assert().Equal("arm64", manifest.Lambda.Architecture) + s.Assert().Equal("provided.al2023", manifest.Lambda.LambdaRuntime) + s.Assert().Equal("os-only.debian13", manifest.Runtime) + s.Assert().Equal("aws-serverless", manifest.Target) +} + +func (s *LambdaCompiledSuite) Test_Build_asks_for_a_linux_binary_of_the_lambda_architecture() { + _, err := s.build() + s.Require().NoError(err) + + s.Require().Len(s.toolchain.built, 1) + built := s.toolchain.built[0] + s.Assert().Equal("linux", built.OS) + s.Assert().Equal("arm64", built.Arch) + s.Assert().Equal("bootstrap", filepath.Base(built.OutputPath)) + s.Assert().Equal(handlertoolchain.ModeDeploy, built.Mode) +} + +// A custom build command is free to produce whatever it likes, and this is the +// last point before the archive is sealed. +func (s *LambdaCompiledSuite) Test_Build_refuses_a_binary_of_the_wrong_architecture() { + s.toolchain.machine = elf.EM_X86_64 + + _, err := s.build() + s.Require().Error(err) + s.Assert().Contains(err.Error(), "arm64") +} + +func (s *LambdaCompiledSuite) Test_Build_reports_a_toolchain_that_produced_no_executable() { + s.toolchain.skipOutput = true + + _, err := s.build() + s.Require().Error(err) + s.Assert().Contains(err.Error(), "left no executable") +} + +func (s *LambdaCompiledSuite) Test_Build_propagates_a_build_failure() { + s.toolchain.buildErr = errors.New("go build failed") + + _, err := s.build() + s.Require().Error(err) + s.Assert().Contains(err.Error(), "go build failed") +} + +func (s *LambdaCompiledSuite) Test_Build_artifact_is_content_hashed_and_sized() { + manifest, err := s.build() + s.Require().NoError(err) + + art := manifest.Lambda.AppCode + s.Assert().Equal(ArtifactTypeLambdaArchive, art.Type) + s.Assert().Regexp(`^sha256:[0-9a-f]{8,}$`, art.ContentHash) + s.Assert().Positive(art.Size) + s.Assert().Contains(filepath.Base(art.LocalPath), "handlers-") +} + +func TestLambdaCompiledSuite(t *testing.T) { suite.Run(t, new(LambdaCompiledSuite)) } diff --git a/apps/cli/internal/build/lambda_layer_path_test.go b/apps/cli/internal/build/lambda_layer_path_test.go new file mode 100644 index 00000000..237f623a --- /dev/null +++ b/apps/cli/internal/build/lambda_layer_path_test.go @@ -0,0 +1,23 @@ +package build + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// Lambda mounts a layer at /opt and Node resolves packages from +// /opt/nodejs/node_modules. npm creates node_modules inside whatever directory +// it installs into, so the install target must stop at "nodejs". Naming +// node_modules here put every package one level too deep, nothing in the layer +// resolved, and every handler failed during init on a module resolution error. +func TestLambdaLayerSubdir_nodeStopsAboveNodeModules(t *testing.T) { + assert.Equal(t, "nodejs", lambdaLayerSubdir("nodejs22.x")) + assert.Equal(t, "nodejs", lambdaLayerSubdir("nodejs24.x")) +} + +// pip installs into the directory it is given rather than creating one, so the +// Python path is the full site-packages location. +func TestLambdaLayerSubdir_pythonKeepsTheFullSitePackagesPath(t *testing.T) { + assert.Equal(t, "python/lib/python3.13/site-packages", lambdaLayerSubdir("python3.13")) +} diff --git a/apps/cli/internal/build/lambda_maintenance_runner.go b/apps/cli/internal/build/lambda_maintenance_runner.go new file mode 100644 index 00000000..707a1bab --- /dev/null +++ b/apps/cli/internal/build/lambda_maintenance_runner.go @@ -0,0 +1,146 @@ +package build + +import ( + "debug/elf" + "fmt" + "os" + "path/filepath" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "go.uber.org/zap" +) + +const ( + // MaintenanceRunnerBinaryEnvVar names a prebuilt maintenance runner binary + // to package. + // + // Until releases publish the runner, this is how one is supplied. The + // resolver is written to take a second source without anything downstream + // changing, since the build manifest records an artefact either way. + MaintenanceRunnerBinaryEnvVar = "CELERITY_MAINTENANCE_RUNNER_BINARY" + + // maintenanceRunnerEntryName is what the binary must be called inside the + // archive. Lambda's provided.al2 runtimes execute a file named bootstrap, + // and nothing else. + maintenanceRunnerEntryName = "bootstrap" + + // sqlDatabaseResourceType is the abstract resource whose presence calls for + // a runner. + sqlDatabaseResourceType = "celerity/sqlDatabase" + + // maintenanceRunnerGoArch is the GOARCH the runner must be built for, and + // must match the architecture the transformer declares on the function. + maintenanceRunnerGoArch = "arm64" +) + +// maintenanceRunnerGoArch as it appears in an ELF header. +const maintenanceRunnerELFMachine = elf.EM_AARCH64 + +// Returns nil when the application has no SQL database to maintain. +// +// The runner is a compiled Go binary versioned with the CLI rather than with +// the user's source, so it is neither the app bundle nor a dependency layer but +// its own artefact with its own content hash. +func (s *LambdaStrategy) buildMaintenanceRunner(params *BuildParams) (*Artifact, error) { + if !blueprintHasSQLDatabase(params.Blueprint) { + return nil, nil + } + + binaryPath, err := resolveMaintenanceRunnerBinary() + if err != nil { + return nil, err + } + + params.Logger.Info("packaging the database maintenance runner", + zap.String("binary", binaryPath)) + + stagingDir, err := os.MkdirTemp("", "celerity-maintenance-runner-*") + if err != nil { + return nil, fmt.Errorf("creating maintenance runner staging directory: %w", err) + } + defer os.RemoveAll(stagingDir) + + staged := filepath.Join(stagingDir, maintenanceRunnerEntryName) + if err := copyFile(binaryPath, staged); err != nil { + return nil, fmt.Errorf("staging the maintenance runner binary: %w", err) + } + // The archive must carry the executable bit or the function fails at start + // with a permission error that says nothing about the cause. copyFile does + // not preserve modes, so it is set here rather than assumed. + if err := os.Chmod(staged, 0755); err != nil { + return nil, fmt.Errorf("making the maintenance runner binary executable: %w", err) + } + + return writeArtifact(ArtifactTypeLambdaArchive, stagingDir, params.OutputDir, "maintenance-runner") +} + +func resolveMaintenanceRunnerBinary() (string, error) { + path := os.Getenv(MaintenanceRunnerBinaryEnvVar) + if path == "" { + return "", fmt.Errorf( + "this application has a %s, which needs the database maintenance runner, "+ + "but no runner binary was found.\n"+ + "Build one and point %s at it:\n"+ + " GOOS=linux GOARCH=arm64 go build -o bootstrap ./cmd/maintenance-runner", + sqlDatabaseResourceType, MaintenanceRunnerBinaryEnvVar) + } + + info, err := os.Stat(path) + if err != nil { + return "", fmt.Errorf("%s points at %s, which cannot be read: %w", + MaintenanceRunnerBinaryEnvVar, path, err) + } + if info.IsDir() { + return "", fmt.Errorf("%s points at %s, which is a directory, not a binary", + MaintenanceRunnerBinaryEnvVar, path) + } + if err := checkMaintenanceRunnerArchitecture(path); err != nil { + return "", err + } + return path, nil +} + +// Rejects a binary Lambda will not be able to execute. +// +// The transformer declares the runner function as arm64, and a binary built for +// anything else is deployed without complaint and then fails on first +// invocation with "Runtime exited with error: exit status 126". That message +// names neither the architecture nor the file, and reads the same as a binary +// missing its executable bit, so the mismatch is caught here, while the +// packaging step still has the file in hand. +func checkMaintenanceRunnerArchitecture(path string) error { + file, err := elf.Open(path) + if err != nil { + return fmt.Errorf( + "%s points at %s, which is not a Linux executable: %w.\n"+ + "Build the runner for Lambda with:\n"+ + " GOOS=linux GOARCH=%s go build -o bootstrap ./cmd/maintenance-runner", + MaintenanceRunnerBinaryEnvVar, path, err, maintenanceRunnerGoArch) + } + defer file.Close() + + if file.Machine != maintenanceRunnerELFMachine { + return fmt.Errorf( + "%s points at %s, which is built for %s, but the runner function is "+ + "deployed as %s.\n"+ + "Rebuild it with:\n"+ + " GOOS=linux GOARCH=%s go build -o bootstrap ./cmd/maintenance-runner", + MaintenanceRunnerBinaryEnvVar, path, file.Machine, maintenanceRunnerGoArch, + maintenanceRunnerGoArch) + } + return nil +} + +// An application with no SQL database gets no runner, and so no function to pay +// for, patch or reason about. +func blueprintHasSQLDatabase(bp *schema.Blueprint) bool { + if bp == nil || bp.Resources == nil { + return false + } + for _, resource := range bp.Resources.Values { + if resource != nil && resource.Type != nil && resource.Type.Value == sqlDatabaseResourceType { + return true + } + } + return false +} diff --git a/apps/cli/internal/build/lambda_maintenance_runner_test.go b/apps/cli/internal/build/lambda_maintenance_runner_test.go new file mode 100644 index 00000000..d29aef3a --- /dev/null +++ b/apps/cli/internal/build/lambda_maintenance_runner_test.go @@ -0,0 +1,189 @@ +package build + +import ( + "archive/zip" + "debug/elf" + "encoding/binary" + "os" + "path/filepath" + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +func blueprintWith(types ...string) *schema.Blueprint { + resources := map[string]*schema.Resource{} + for i, typ := range types { + resources[string(rune('a'+i))] = &schema.Resource{ + Type: &schema.ResourceTypeWrapper{Value: typ}, + } + } + return &schema.Blueprint{Resources: &schema.ResourceMap{Values: resources}} +} + +func runnerParams(t *testing.T, bp *schema.Blueprint) *BuildParams { + t.Helper() + return &BuildParams{ + Blueprint: bp, + OutputDir: t.TempDir(), + Logger: zap.NewNop(), + } +} + +// A prebuilt binary, standing in for the cross-compiled runner. +// +// The header has to be a real one rather than a marker string, because +// packaging checks the architecture. Lambda cannot execute a binary built for +// the wrong one and reports that only as "exit status 126" at invocation. +func fakeRunnerBinary(t *testing.T) string { + t.Helper() + return runnerBinaryFor(t, elf.EM_AARCH64, "fake runner") +} + +// Writes a file with a valid 64-bit little-endian ELF header for the given machine, +// followed by arbitrary content so that distinct binaries hash differently. +func runnerBinaryFor(t *testing.T, machine elf.Machine, content string) string { + t.Helper() + + header := make([]byte, 64) + copy(header, []byte{0x7f, 'E', 'L', 'F'}) + header[4] = byte(elf.ELFCLASS64) + header[5] = byte(elf.ELFDATA2LSB) + header[6] = byte(elf.EV_CURRENT) + binary.LittleEndian.PutUint16(header[16:], uint16(elf.ET_EXEC)) + binary.LittleEndian.PutUint16(header[18:], uint16(machine)) + binary.LittleEndian.PutUint32(header[20:], uint32(elf.EV_CURRENT)) + // Section and program header tables are absent, which debug/elf accepts. + binary.LittleEndian.PutUint16(header[52:], 64) + + path := filepath.Join(t.TempDir(), "bootstrap") + require.NoError(t, os.WriteFile(path, append(header, []byte(content)...), 0755)) + return path +} + +// An application with no database gets no runner, and so nothing to pay for, +// patch or reason about. +func TestNoRunnerWithoutASQLDatabase(t *testing.T) { + params := runnerParams(t, blueprintWith("celerity/handler", "celerity/bucket")) + + artifact, err := (&LambdaStrategy{}).buildMaintenanceRunner(params) + + require.NoError(t, err) + assert.Nil(t, artifact) +} + +// And crucially, no error either. The missing-binary error must not fire for +// the applications that will never need one. +func TestNoDatabaseMeansNoMissingBinaryError(t *testing.T) { + t.Setenv(MaintenanceRunnerBinaryEnvVar, "") + params := runnerParams(t, blueprintWith("celerity/handler")) + + _, err := (&LambdaStrategy{}).buildMaintenanceRunner(params) + + require.NoError(t, err) +} + +func TestPackagesTheRunnerForADatabaseBackedApp(t *testing.T) { + t.Setenv(MaintenanceRunnerBinaryEnvVar, fakeRunnerBinary(t)) + params := runnerParams(t, blueprintWith("celerity/handler", "celerity/sqlDatabase")) + + artifact, err := (&LambdaStrategy{}).buildMaintenanceRunner(params) + + require.NoError(t, err) + require.NotNil(t, artifact) + assert.Equal(t, ArtifactTypeLambdaArchive, artifact.Type) + assert.Contains(t, artifact.ContentHash, "sha256:") + assert.FileExists(t, artifact.LocalPath) +} + +// Lambda's provided.al2 runtimes execute a file named bootstrap and nothing +// else, and only if it is executable. Neither is visible until the function is +// invoked, where it surfaces as a start-up error that names neither cause. +func TestTheArchiveHoldsAnExecutableBootstrap(t *testing.T) { + t.Setenv(MaintenanceRunnerBinaryEnvVar, fakeRunnerBinary(t)) + params := runnerParams(t, blueprintWith("celerity/sqlDatabase")) + + artifact, err := (&LambdaStrategy{}).buildMaintenanceRunner(params) + require.NoError(t, err) + + reader, err := zip.OpenReader(artifact.LocalPath) + require.NoError(t, err) + defer reader.Close() + + require.Len(t, reader.File, 1, "the archive holds the binary and nothing else") + entry := reader.File[0] + assert.Equal(t, "bootstrap", entry.Name) + assert.NotZero(t, entry.Mode()&0111, "bootstrap must be executable in the archive") +} + +// A rebuilt binary must produce a different artefact, or a deploy silently +// keeps the old runner. +func TestTheArtefactIsContentAddressed(t *testing.T) { + first := fakeRunnerBinary(t) + t.Setenv(MaintenanceRunnerBinaryEnvVar, first) + params := runnerParams(t, blueprintWith("celerity/sqlDatabase")) + + before, err := (&LambdaStrategy{}).buildMaintenanceRunner(params) + require.NoError(t, err) + + require.NoError(t, os.WriteFile(first, mustReadFile(t, runnerBinaryFor(t, elf.EM_AARCH64, "a newer runner")), 0755)) + after, err := (&LambdaStrategy{}).buildMaintenanceRunner(params) + require.NoError(t, err) + + assert.NotEqual(t, before.ContentHash, after.ContentHash) +} + +// The error an operator is most likely to hit names the command to run. +func TestAMissingBinaryExplainsHowToBuildOne(t *testing.T) { + t.Setenv(MaintenanceRunnerBinaryEnvVar, "") + params := runnerParams(t, blueprintWith("celerity/sqlDatabase")) + + _, err := (&LambdaStrategy{}).buildMaintenanceRunner(params) + + require.Error(t, err) + assert.Contains(t, err.Error(), MaintenanceRunnerBinaryEnvVar) + assert.Contains(t, err.Error(), "go build -o bootstrap ./cmd/maintenance-runner") +} + +func TestAnUnreadableBinaryIsReported(t *testing.T) { + t.Setenv(MaintenanceRunnerBinaryEnvVar, filepath.Join(t.TempDir(), "absent")) + params := runnerParams(t, blueprintWith("celerity/sqlDatabase")) + + _, err := (&LambdaStrategy{}).buildMaintenanceRunner(params) + + require.Error(t, err) + assert.Contains(t, err.Error(), "cannot be read") +} + +func TestADirectoryIsNotABinary(t *testing.T) { + t.Setenv(MaintenanceRunnerBinaryEnvVar, t.TempDir()) + params := runnerParams(t, blueprintWith("celerity/sqlDatabase")) + + _, err := (&LambdaStrategy{}).buildMaintenanceRunner(params) + + require.Error(t, err) + assert.Contains(t, err.Error(), "a directory, not a binary") +} + +func mustReadFile(t *testing.T, path string) []byte { + t.Helper() + data, err := os.ReadFile(path) + require.NoError(t, err) + return data +} + +// A binary for the wrong architecture deploys without complaint and fails only when +// the function is first invoked, as "exit status 126", which names neither the +// architecture nor the file. +func TestPackagingRejectsARunnerBuiltForTheWrongArchitecture(t *testing.T) { + t.Setenv(MaintenanceRunnerBinaryEnvVar, runnerBinaryFor(t, elf.EM_X86_64, "amd64 runner")) + + _, err := resolveMaintenanceRunnerBinary() + + require.Error(t, err) + assert.Contains(t, err.Error(), "built for") + assert.Contains(t, err.Error(), "GOARCH=arm64") +} diff --git a/apps/cli/internal/build/lambda_test.go b/apps/cli/internal/build/lambda_test.go new file mode 100644 index 00000000..6e77ea0a --- /dev/null +++ b/apps/cli/internal/build/lambda_test.go @@ -0,0 +1,565 @@ +package build + +import ( + "archive/zip" + "context" + "encoding/json" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +// --- mock implementations --- + +type installCall struct { + appDir string + targetDir string + packages []string +} + +type mockInstaller struct { + installed []installCall +} + +func (m *mockInstaller) InstallDependencies(_ context.Context, appDir, targetDir string, packages []string, _ io.Writer) error { + m.installed = append(m.installed, installCall{appDir, targetDir, packages}) + // Write a dummy file so the zip layer is not empty. + return os.WriteFile(filepath.Join(targetDir, "dummy.js"), []byte("module.exports = {}"), 0644) +} + +type mockCompiler struct { + compileCalled bool +} + +func (m *mockCompiler) Compile(_ context.Context, srcDir, outDir string, _ io.Writer) error { + m.compileCalled = true + // Copy .js files from srcDir to outDir to simulate compilation. + entries, err := os.ReadDir(srcDir) + if err != nil { + return err + } + for _, e := range entries { + if !e.IsDir() && strings.HasSuffix(e.Name(), ".js") { + data, readErr := os.ReadFile(filepath.Join(srcDir, e.Name())) + if readErr != nil { + return readErr + } + if writeErr := os.WriteFile(filepath.Join(outDir, e.Name()), data, 0644); writeErr != nil { + return writeErr + } + } + } + return nil +} + +// --- test suite --- + +type LambdaSuite struct { + suite.Suite +} + +func TestLambdaSuite(t *testing.T) { + suite.Run(t, new(LambdaSuite)) +} + +func (s *LambdaSuite) newTestRegistry(installer DependencyInstaller, compiler SourceCompiler) *Registry { + r := NewRegistry() + r.RegisterDependencyInstaller("nodejs", installer) + if compiler != nil { + r.RegisterSourceCompiler("nodejs", compiler) + } + return r +} + +func (s *LambdaSuite) newBuildParams(appDir, outputDir string, handlers []HandlerInfo, handlerDeps map[string][]string) *BuildParams { + return &BuildParams{ + AppDir: appDir, + Runtime: "nodejs24.x", + DeployTarget: "aws-serverless", + Handlers: handlers, + HandlerDependencies: handlerDeps, + OutputDir: outputDir, + Logger: zap.NewNop(), + ToolOutput: io.Discard, + } +} + +func (s *LambdaSuite) setupAppDir() string { + dir := s.T().TempDir() + // Write a simple JS file to act as handler source. + s.Require().NoError(os.WriteFile( + filepath.Join(dir, "handler.js"), + []byte("exports.handler = async () => ({ statusCode: 200 })"), + 0644, + )) + return dir +} + +func (s *LambdaSuite) Test_Build_noHandlerDependencies_sharedLayerBuiltNoPerHandlerLayers() { + inst := &mockInstaller{} + reg := s.newTestRegistry(inst, nil) + strategy := &LambdaStrategy{Registry: reg} + + appDir := s.setupAppDir() + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + {ResourceName: "handlerB", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, nil) + + manifest, err := strategy.Build(context.Background(), params) + + s.Require().NoError(err) + s.NotNil(manifest.Lambda.SharedLayer, "shared layer should be built when there are no per-handler deps") + s.Nil(manifest.Handlers["handlerA"].Lambda.Dependencies, "handlerA should not have a custom layer") + s.Nil(manifest.Handlers["handlerB"].Lambda.Dependencies, "handlerB should not have a custom layer") +} + +func (s *LambdaSuite) Test_Build_handlerDepsForSubset_sharedLayerPlusCustomLayers() { + inst := &mockInstaller{} + reg := s.newTestRegistry(inst, nil) + strategy := &LambdaStrategy{Registry: reg} + + appDir := s.setupAppDir() + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + {ResourceName: "handlerB", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + handlerDeps := map[string][]string{ + "handlerB": {"stripe"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, handlerDeps) + + manifest, err := strategy.Build(context.Background(), params) + + s.Require().NoError(err) + s.NotNil(manifest.Lambda.SharedLayer, "shared layer should be built for handlers without custom deps") + s.Nil(manifest.Handlers["handlerA"].Lambda.Dependencies, "handlerA uses shared layer") + s.NotNil(manifest.Handlers["handlerB"].Lambda.Dependencies, "handlerB should have a custom layer") +} + +func (s *LambdaSuite) Test_Build_handlerDepsForAllHandlers_noSharedLayer() { + inst := &mockInstaller{} + reg := s.newTestRegistry(inst, nil) + strategy := &LambdaStrategy{Registry: reg} + + appDir := s.setupAppDir() + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + {ResourceName: "handlerB", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + handlerDeps := map[string][]string{ + "handlerA": {"express"}, + "handlerB": {"stripe"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, handlerDeps) + + manifest, err := strategy.Build(context.Background(), params) + + s.Require().NoError(err) + s.Nil(manifest.Lambda.SharedLayer, "no shared layer when all handlers have custom deps") + s.NotNil(manifest.Handlers["handlerA"].Lambda.Dependencies) + s.NotNil(manifest.Handlers["handlerB"].Lambda.Dependencies) +} + +func (s *LambdaSuite) Test_Build_deduplication_identicalDepsSetsShareOneLayerArtifact() { + inst := &mockInstaller{} + reg := s.newTestRegistry(inst, nil) + strategy := &LambdaStrategy{Registry: reg} + + appDir := s.setupAppDir() + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + {ResourceName: "handlerB", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + // Both handlers declare the same deps (order may differ). + handlerDeps := map[string][]string{ + "handlerA": {"stripe", "lodash"}, + "handlerB": {"lodash", "stripe"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, handlerDeps) + + manifest, err := strategy.Build(context.Background(), params) + + s.Require().NoError(err) + s.Nil(manifest.Lambda.SharedLayer, "no shared layer when all handlers have custom deps") + + layerA := manifest.Handlers["handlerA"].Lambda.Dependencies + layerB := manifest.Handlers["handlerB"].Lambda.Dependencies + s.Require().NotNil(layerA) + s.Require().NotNil(layerB) + // Deduplicated, so both must point to the same artifact with the same local + // path and hash. + s.Equal(layerA.LocalPath, layerB.LocalPath) + s.Equal(layerA.ContentHash, layerB.ContentHash) +} + +func (s *LambdaSuite) Test_Build_contentHashesAreSha256Prefixed() { + inst := &mockInstaller{} + reg := s.newTestRegistry(inst, nil) + strategy := &LambdaStrategy{Registry: reg} + + appDir := s.setupAppDir() + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, nil) + + manifest, err := strategy.Build(context.Background(), params) + + s.Require().NoError(err) + s.True(strings.HasPrefix(manifest.Lambda.SharedLayer.ContentHash, "sha256:")) + s.True(strings.HasPrefix(manifest.Lambda.AppCode.ContentHash, "sha256:")) +} + +func (s *LambdaSuite) Test_Build_sizeIsRecordedOnAllArtifacts() { + inst := &mockInstaller{} + reg := s.newTestRegistry(inst, nil) + strategy := &LambdaStrategy{Registry: reg} + + appDir := s.setupAppDir() + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, nil) + + manifest, err := strategy.Build(context.Background(), params) + + s.Require().NoError(err) + s.Greater(manifest.Lambda.SharedLayer.Size, int64(0)) + s.Greater(manifest.Lambda.AppCode.Size, int64(0)) +} + +func (s *LambdaSuite) Test_checkLayerSize_exceedsLimit_returnsError() { + logger, _ := zap.NewDevelopment() + layer := &Artifact{Size: LayerSizeLimit + 1} + err := checkLayerSize(layer, "test-layer", logger) + s.Require().Error(err) + s.Contains(err.Error(), "250MB") +} + +func (s *LambdaSuite) Test_checkLayerSize_underLimit_noError() { + logger, _ := zap.NewDevelopment() + layer := &Artifact{Size: LayerSizeWarning - 1} + err := checkLayerSize(layer, "test-layer", logger) + s.NoError(err) +} + +func (s *LambdaSuite) Test_Build_withCompiler_compilesSource() { + inst := &mockInstaller{} + comp := &mockCompiler{} + reg := s.newTestRegistry(inst, comp) + strategy := &LambdaStrategy{Registry: reg} + + appDir := s.setupAppDir() + // Also create a tsconfig.json so the real compiler would trigger, + // but our mock just copies .js files regardless. + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, nil) + + manifest, err := strategy.Build(context.Background(), params) + + s.Require().NoError(err) + s.True(comp.compileCalled) + s.NotNil(manifest.Lambda.AppCode) +} + +// --- single shared app bundle + bootstrap behaviour --- + +// stubBootstrap writes a marker file so tests can verify the bootstrap ran. +type stubBootstrap struct { + markerName string + entryPoint string + generated bool + err error + // requiredPackage is empty by default so existing cases exercise bootstrap + // generation without also asserting on the adapter dependency check. + requiredPackage string +} + +func (b *stubBootstrap) RequiredPackage() string { + return b.requiredPackage +} + +func (b *stubBootstrap) Generate(stagingDir string) (string, error) { + b.generated = true + if b.err != nil { + return "", b.err + } + if b.markerName != "" { + marker := filepath.Join(stagingDir, b.markerName) + if err := os.WriteFile(marker, []byte("marker"), 0644); err != nil { + return "", err + } + } + return b.entryPoint, nil +} + +func (s *LambdaSuite) newLambdaStrategyWithBootstrap( + installer DependencyInstaller, + bootstrap HandlerBootstrap, +) *LambdaStrategy { + r := NewRegistry() + r.RegisterDependencyInstaller("nodejs", installer) + return &LambdaStrategy{ + Registry: r, + Bootstraps: map[string]HandlerBootstrap{ + "nodejs": bootstrap, + }, + } +} + +func (s *LambdaSuite) Test_Build_producesSingleAppBundleNotPerHandlerZips() { + inst := &mockInstaller{} + reg := s.newTestRegistry(inst, nil) + strategy := &LambdaStrategy{Registry: reg} + + appDir := s.setupAppDir() + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + {ResourceName: "handlerB", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + {ResourceName: "handlerC", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, nil) + + manifest, err := strategy.Build(context.Background(), params) + + s.Require().NoError(err) + s.Require().NotNil(manifest.Lambda.AppCode, "manifest should have a shared AppCode artifact") + s.Len(manifest.Handlers, 3, "all handlers should still appear in the manifest") + + entries, err := os.ReadDir(outputDir) + s.Require().NoError(err) + appZipCount := 0 + for _, e := range entries { + if strings.HasPrefix(e.Name(), "app-") && strings.HasSuffix(e.Name(), ".zip") { + appZipCount += 1 + } + s.False(strings.HasSuffix(e.Name(), "-handler.zip"), + "per-handler code zips should not be produced in the new shape") + } + s.Equal(1, appZipCount, "exactly one app-.zip should exist") +} + +func (s *LambdaSuite) Test_Build_runsBootstrapAndRecordsEntryPoint() { + inst := &mockInstaller{} + bootstrap := &stubBootstrap{ + markerName: "__celerity_lambda_entry__.mjs", + entryPoint: "__celerity_lambda_entry__.handler", + } + strategy := s.newLambdaStrategyWithBootstrap(inst, bootstrap) + + appDir := s.setupAppDir() + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, nil) + + manifest, err := strategy.Build(context.Background(), params) + + s.Require().NoError(err) + s.True(bootstrap.generated, "bootstrap.Generate should have been called") + s.Equal("__celerity_lambda_entry__.handler", manifest.Lambda.EntryPoint) +} + +func (s *LambdaSuite) Test_Build_noBootstrapRegistered_entryPointIsEmpty() { + inst := &mockInstaller{} + reg := s.newTestRegistry(inst, nil) + strategy := &LambdaStrategy{Registry: reg} + + appDir := s.setupAppDir() + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, nil) + + manifest, err := strategy.Build(context.Background(), params) + + s.Require().NoError(err) + s.Equal("", manifest.Lambda.EntryPoint, "no bootstrap → empty entry point (backward compatible)") + s.NotNil(manifest.Lambda.AppCode, "app code should still be produced") +} + +func (s *LambdaSuite) Test_Build_artifactFilenamesIncludeContentHash() { + inst := &mockInstaller{} + reg := s.newTestRegistry(inst, nil) + strategy := &LambdaStrategy{Registry: reg} + + appDir := s.setupAppDir() + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, nil) + + manifest, err := strategy.Build(context.Background(), params) + s.Require().NoError(err) + + appFilename := filepath.Base(manifest.Lambda.AppCode.LocalPath) + hashPart := strings.TrimPrefix(manifest.Lambda.AppCode.ContentHash, "sha256:") + s.Equal("app-"+hashPart+".zip", appFilename) + + s.Require().NotNil(manifest.Lambda.SharedLayer) + layerFilename := filepath.Base(manifest.Lambda.SharedLayer.LocalPath) + layerHash := strings.TrimPrefix(manifest.Lambda.SharedLayer.ContentHash, "sha256:") + s.Equal("shared-layer-"+layerHash+".zip", layerFilename) +} + +func (s *LambdaSuite) Test_Build_deterministic_secondBuildProducesSameHashes() { + inst := &mockInstaller{} + reg := s.newTestRegistry(inst, nil) + strategy := &LambdaStrategy{Registry: reg} + + appDir := s.setupAppDir() + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, nil) + + first, err := strategy.Build(context.Background(), params) + s.Require().NoError(err) + + second, err := strategy.Build(context.Background(), params) + s.Require().NoError(err) + + s.Equal(first.Lambda.AppCode.ContentHash, second.Lambda.AppCode.ContentHash, + "identical source should produce the same app code hash") +} + +// --- resource links bundling --- + +func (s *LambdaSuite) loadBlueprint(yamlContent string) *schema.Blueprint { + bp, err := schema.LoadString(yamlContent, schema.YAMLSpecFormat) + s.Require().NoError(err, "failed to load test blueprint") + return bp +} + +func readFileFromZip(t interface { + Helper() + Fatalf(format string, args ...interface{}) +}, zipPath, fileName string) []byte { + t.Helper() + r, err := zip.OpenReader(zipPath) + if err != nil { + t.Fatalf("opening zip: %v", err) + } + defer r.Close() + for _, f := range r.File { + if f.Name == fileName { + rc, err := f.Open() + if err != nil { + t.Fatalf("opening zipped file: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("reading zipped file: %v", err) + } + return data + } + } + t.Fatalf("file %q not found in zip", fileName) + return nil +} + +func (s *LambdaSuite) Test_Build_bundlesResourceLinksFromBlueprint() { + bp := s.loadBlueprint(` +version: 2025-11-02 +resources: + usersDatastore: + type: "celerity/datastore" + spec: + name: users + imagesBucket: + type: "celerity/bucket" + spec: + name: images + orderQueue: + type: "celerity/queue" + spec: + name: orders +`) + + inst := &mockInstaller{} + reg := s.newTestRegistry(inst, nil) + strategy := &LambdaStrategy{Registry: reg} + + appDir := s.setupAppDir() + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, nil) + params.Blueprint = bp + + manifest, err := strategy.Build(context.Background(), params) + s.Require().NoError(err) + s.Require().NotNil(manifest.Lambda.AppCode) + + data := readFileFromZip(s.T(), manifest.Lambda.AppCode.LocalPath, ResourceLinksFilename) + + var links map[string]struct { + Type string `json:"type"` + ConfigKey string `json:"configKey"` + } + s.Require().NoError(json.Unmarshal(data, &links)) + + s.Assert().Equal("datastore", links["usersDatastore"].Type) + s.Assert().Equal("users", links["usersDatastore"].ConfigKey) + s.Assert().Equal("bucket", links["imagesBucket"].Type) + s.Assert().Equal("images", links["imagesBucket"].ConfigKey) + s.Assert().Equal("queue", links["orderQueue"].Type) + s.Assert().Equal("orders", links["orderQueue"].ConfigKey) +} + +func (s *LambdaSuite) Test_Build_bundlesEmptyResourceLinksFileWhenBlueprintNil() { + inst := &mockInstaller{} + reg := s.newTestRegistry(inst, nil) + strategy := &LambdaStrategy{Registry: reg} + + appDir := s.setupAppDir() + outputDir := s.T().TempDir() + + handlers := []HandlerInfo{ + {ResourceName: "handlerA", HandlerName: "handler.handler", CodeLocation: "handler.js"}, + } + params := s.newBuildParams(appDir, outputDir, handlers, nil) + + manifest, err := strategy.Build(context.Background(), params) + s.Require().NoError(err) + + data := readFileFromZip(s.T(), manifest.Lambda.AppCode.LocalPath, ResourceLinksFilename) + s.Assert().JSONEq("{}", string(data)) +} diff --git a/apps/cli/internal/build/lambda_types.go b/apps/cli/internal/build/lambda_types.go new file mode 100644 index 00000000..8cb84617 --- /dev/null +++ b/apps/cli/internal/build/lambda_types.go @@ -0,0 +1,11 @@ +package build + +import "github.com/newstack-cloud/celerity/apps/cli/buildmanifest" + +const ( + ArtifactTypeLambdaArchive = buildmanifest.ArtifactTypeLambdaArchive + ArtifactTypeLambdaLayer = buildmanifest.ArtifactTypeLambdaLayer + + LayerSizeWarning int64 = 200 * 1024 * 1024 // 200MB + LayerSizeLimit int64 = 250 * 1024 * 1024 // 250MB +) diff --git a/apps/cli/internal/build/manifest.go b/apps/cli/internal/build/manifest.go new file mode 100644 index 00000000..02ca4821 --- /dev/null +++ b/apps/cli/internal/build/manifest.go @@ -0,0 +1,53 @@ +package build + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/newstack-cloud/celerity/apps/cli/buildmanifest" +) + +// WriteManifest writes the build manifest to buildmanifest.FileName. +// Thin re-export of buildmanifest.Write so internal/build call sites are +// unchanged. +func WriteManifest(manifest *Manifest) error { + return buildmanifest.Write(manifest) +} + +// ReadManifest reads the build manifest from buildmanifest.FileName, returning +// nil if the file does not exist. Thin re-export of buildmanifest.Read. +func ReadManifest() (*Manifest, error) { + return buildmanifest.Read() +} + +// UploadManifest serialises the manifest and uploads it via the given +// uploader, stamping the returned URL onto manifest.RemoteURL. +// +// Callers must call this before persisting the manifest locally with +// WriteManifest so the RemoteURL is part of the on-disk copy but not of the +// uploaded bytes. The upload happens before the stamping, so the S3 object +// holds no self-reference. +// +// A nil uploader is a no-op that leaves manifest.RemoteURL empty, which lets +// deploy targets without artifact upload share the same call site. +func UploadManifest( + ctx context.Context, + uploader ArtifactUploader, + manifest *Manifest, + instanceName string, +) error { + if uploader == nil { + return nil + } + data, err := json.MarshalIndent(manifest, "", " ") + if err != nil { + return fmt.Errorf("marshalling build manifest: %w", err) + } + url, err := uploader.UploadManifest(ctx, data, instanceName) + if err != nil { + return fmt.Errorf("uploading build manifest: %w", err) + } + manifest.RemoteURL = url + return nil +} diff --git a/apps/cli/internal/build/manifest_test.go b/apps/cli/internal/build/manifest_test.go new file mode 100644 index 00000000..0b69b819 --- /dev/null +++ b/apps/cli/internal/build/manifest_test.go @@ -0,0 +1,200 @@ +package build + +import ( + "context" + "encoding/json" + "errors" + "os" + "testing" + + "github.com/stretchr/testify/suite" +) + +type ManifestSuite struct { + suite.Suite + origDir string +} + +func TestManifestSuite(t *testing.T) { + suite.Run(t, new(ManifestSuite)) +} + +func (s *ManifestSuite) SetupTest() { + // WriteManifest and ReadManifest use the relative path ManifestFile, + // so we chdir into a temp directory for each test. + dir := s.T().TempDir() + origDir, err := os.Getwd() + s.Require().NoError(err) + s.origDir = origDir + s.Require().NoError(os.Chdir(dir)) +} + +func (s *ManifestSuite) TearDownTest() { + s.Require().NoError(os.Chdir(s.origDir)) +} + +func (s *ManifestSuite) Test_WriteManifest_thenReadManifest_roundTrip() { + original := &Manifest{ + Version: ManifestVersion, + Runtime: "nodejs24.x", + Target: "aws-serverless", + Lambda: &LambdaManifest{ + EntryPoint: "__celerity_lambda_entry__.handler", + AppCode: &Artifact{ + Type: ArtifactTypeLambdaArchive, + LocalPath: "/tmp/app-abc123.zip", + ContentHash: "sha256:abc123", + Size: 8192, + }, + SharedLayer: &Artifact{ + Type: ArtifactTypeLambdaLayer, + LocalPath: "/tmp/shared-layer-def456.zip", + ContentHash: "sha256:def456", + Size: 4096, + }, + }, + Handlers: map[string]*HandlerArtifacts{ + "orderHandler": { + Lambda: &LambdaHandlerArtifacts{ + Dependencies: &Artifact{ + Type: ArtifactTypeLambdaLayer, + LocalPath: "/tmp/orderHandler-layer-ghi789.zip", + ContentHash: "sha256:ghi789", + Size: 2048, + }, + }, + }, + "userHandler": {Lambda: &LambdaHandlerArtifacts{}}, + }, + } + + err := WriteManifest(original) + s.Require().NoError(err) + + loaded, err := ReadManifest() + s.Require().NoError(err) + s.Require().NotNil(loaded) + + s.Equal(original.Version, loaded.Version) + s.Equal(original.Runtime, loaded.Runtime) + s.Equal(original.Target, loaded.Target) + + s.Require().NotNil(loaded.Lambda) + s.Equal(original.Lambda.EntryPoint, loaded.Lambda.EntryPoint) + + s.Require().NotNil(loaded.Lambda.AppCode) + s.Equal(original.Lambda.AppCode.ContentHash, loaded.Lambda.AppCode.ContentHash) + s.Equal(original.Lambda.AppCode.LocalPath, loaded.Lambda.AppCode.LocalPath) + + s.Require().NotNil(loaded.Lambda.SharedLayer) + s.Equal(original.Lambda.SharedLayer.ContentHash, loaded.Lambda.SharedLayer.ContentHash) + s.Equal(original.Lambda.SharedLayer.Size, loaded.Lambda.SharedLayer.Size) + + s.Require().Contains(loaded.Handlers, "orderHandler") + s.Require().NotNil(loaded.Handlers["orderHandler"].Lambda) + s.Require().NotNil(loaded.Handlers["orderHandler"].Lambda.Dependencies) + s.Equal( + original.Handlers["orderHandler"].Lambda.Dependencies.ContentHash, + loaded.Handlers["orderHandler"].Lambda.Dependencies.ContentHash, + ) + + s.Require().Contains(loaded.Handlers, "userHandler") + userLambda := loaded.Handlers["userHandler"].Lambda + if userLambda != nil { + s.Nil(userLambda.Dependencies, "userHandler uses shared layer") + } +} + +func (s *ManifestSuite) Test_ReadManifest_returnsNilForMissingFile() { + loaded, err := ReadManifest() + + s.NoError(err) + s.Nil(loaded) +} + +func (s *ManifestSuite) Test_WriteManifest_createsCelerityDirectory() { + manifest := &Manifest{ + Version: ManifestVersion, + Runtime: "python3.12", + Target: "aws-serverless", + Handlers: map[string]*HandlerArtifacts{}, + } + + err := WriteManifest(manifest) + s.Require().NoError(err) + + info, err := os.Stat(".celerity") + s.Require().NoError(err) + s.True(info.IsDir()) +} + +func (s *ManifestSuite) Test_WriteManifest_persistsRemoteURL() { + manifest := &Manifest{ + Version: ManifestVersion, + Runtime: "nodejs24.x", + Target: "aws-serverless", + Handlers: map[string]*HandlerArtifacts{}, + RemoteURL: "s3://celerity-build-123-us-east-1/default/build-manifest.json", + } + + s.Require().NoError(WriteManifest(manifest)) + + loaded, err := ReadManifest() + s.Require().NoError(err) + s.Require().NotNil(loaded) + s.Equal(manifest.RemoteURL, loaded.RemoteURL) +} + +func (s *ManifestSuite) Test_UploadManifest_setsRemoteURLOnSuccess() { + manifest := &Manifest{ + Version: ManifestVersion, + Runtime: "nodejs24.x", + Target: "aws-serverless", + Handlers: map[string]*HandlerArtifacts{}, + } + uploader := &fakeUploader{ + manifestURL: "s3://test-bucket/default/build-manifest.json", + } + + err := UploadManifest(context.Background(), uploader, manifest, "default") + s.Require().NoError(err) + + s.Equal("s3://test-bucket/default/build-manifest.json", manifest.RemoteURL) + s.Equal("default", uploader.lastInstance) + s.Len(uploader.lastData, len(uploader.lastData)) + + // The uploaded bytes must NOT self-reference. RemoteURL is set after + // marshalling, so the S3 object has an empty field. + var uploaded Manifest + s.Require().NoError(json.Unmarshal(uploader.lastData, &uploaded)) + s.Empty(uploaded.RemoteURL) +} + +func (s *ManifestSuite) Test_UploadManifest_wrapsUploaderError() { + manifest := &Manifest{ + Version: ManifestVersion, + Runtime: "nodejs24.x", + Target: "aws-serverless", + Handlers: map[string]*HandlerArtifacts{}, + } + boom := errors.New("boom") + uploader := &fakeUploader{manifestErr: boom} + + err := UploadManifest(context.Background(), uploader, manifest, "default") + s.Require().Error(err) + s.ErrorIs(err, boom) + s.Empty(manifest.RemoteURL) +} + +func (s *ManifestSuite) Test_UploadManifest_nilUploader_noop() { + manifest := &Manifest{ + Version: ManifestVersion, + Runtime: "nodejs24.x", + Target: "aws-serverless", + Handlers: map[string]*HandlerArtifacts{}, + } + + err := UploadManifest(context.Background(), nil, manifest, "default") + s.NoError(err) + s.Empty(manifest.RemoteURL) +} diff --git a/apps/cli/internal/build/node_pm.go b/apps/cli/internal/build/node_pm.go new file mode 100644 index 00000000..691c9e1c --- /dev/null +++ b/apps/cli/internal/build/node_pm.go @@ -0,0 +1,119 @@ +package build + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" +) + +func isESMProject(appDir string) bool { + data, err := os.ReadFile(filepath.Join(appDir, "package.json")) + if err != nil { + return false + } + var pkg struct { + Type string `json:"type"` + } + if err := json.Unmarshal(data, &pkg); err != nil { + return false + } + return pkg.Type == "module" +} + +// NodePackageManager represents a detected Node.js package manager. +type NodePackageManager string + +const ( + NodePMNpm NodePackageManager = "npm" + NodePMYarn NodePackageManager = "yarn" + NodePMPnpm NodePackageManager = "pnpm" +) + +// DetectNodePackageManager determines the Node.js package manager +// from the packageManager field in package.json or lock files on disk. +func DetectNodePackageManager(appDir string) NodePackageManager { + if pm := detectFromPackageJSON(appDir); pm != "" { + return pm + } + return detectFromLockFile(appDir) +} + +func detectFromPackageJSON(appDir string) NodePackageManager { + data, err := os.ReadFile(filepath.Join(appDir, "package.json")) + if err != nil { + return "" + } + var pkg struct { + PackageManager string `json:"packageManager"` + } + if err := json.Unmarshal(data, &pkg); err != nil || pkg.PackageManager == "" { + return "" + } + pm := strings.Split(pkg.PackageManager, "@")[0] + switch pm { + case "yarn": + return NodePMYarn + case "pnpm": + return NodePMPnpm + case "npm": + return NodePMNpm + default: + return "" + } +} + +func detectFromLockFile(appDir string) NodePackageManager { + lockFiles := []struct { + file string + pm NodePackageManager + }{ + {"yarn.lock", NodePMYarn}, + {"pnpm-lock.yaml", NodePMPnpm}, + {"package-lock.json", NodePMNpm}, + } + for _, lf := range lockFiles { + if _, err := os.Stat(filepath.Join(appDir, lf.file)); err == nil { + return lf.pm + } + } + return NodePMNpm +} + +// ExecPrefix returns the command prefix for running a locally installed +// binary via the package manager (e.g. ["pnpm", "exec"] or ["yarn"]). +func (pm NodePackageManager) ExecPrefix() []string { + switch pm { + case NodePMYarn: + return []string{"yarn"} + case NodePMPnpm: + return []string{"pnpm", "exec"} + default: + return []string{"npm", "exec", "--"} + } +} + +// InstallCommand returns the command to install production dependencies +// in a clean, reproducible way. +func (pm NodePackageManager) InstallCommand() []string { + switch pm { + case NodePMYarn: + return []string{"yarn", "install", "--production"} + case NodePMPnpm: + return []string{"pnpm", "install", "--prod"} + default: + return []string{"npm", "ci", "--omit=dev"} + } +} + +// LockFiles returns the lock file names to copy for reproducible installs. +func (pm NodePackageManager) LockFiles() []string { + switch pm { + case NodePMYarn: + return []string{"yarn.lock"} + case NodePMPnpm: + return []string{"pnpm-lock.yaml"} + default: + return []string{"package-lock.json"} + } +} diff --git a/apps/cli/internal/build/registry.go b/apps/cli/internal/build/registry.go new file mode 100644 index 00000000..d272caea --- /dev/null +++ b/apps/cli/internal/build/registry.go @@ -0,0 +1,94 @@ +package build + +import ( + "fmt" + "strings" +) + +// Registry holds build components keyed by deploy target or runtime prefix. +type Registry struct { + strategies map[string]Strategy + installers map[string]DependencyInstaller + compilers map[string]SourceCompiler + depReaders map[string]HandlerDependencyReader +} + +func NewRegistry() *Registry { + return &Registry{ + strategies: map[string]Strategy{}, + installers: map[string]DependencyInstaller{}, + compilers: map[string]SourceCompiler{}, + depReaders: map[string]HandlerDependencyReader{}, + } +} + +func (r *Registry) RegisterStrategy(deployTarget string, s Strategy) { + r.strategies[deployTarget] = s +} + +func (r *Registry) RegisterDependencyInstaller(runtimePrefix string, i DependencyInstaller) { + r.installers[runtimePrefix] = i +} + +func (r *Registry) RegisterSourceCompiler(runtimePrefix string, c SourceCompiler) { + r.compilers[runtimePrefix] = c +} + +func (r *Registry) RegisterHandlerDependencyReader(runtimePrefix string, reader HandlerDependencyReader) { + r.depReaders[runtimePrefix] = reader +} + +func (r *Registry) GetStrategy(deployTarget string) (Strategy, error) { + s, ok := r.strategies[deployTarget] + if !ok { + return nil, fmt.Errorf("no build strategy registered for deploy target %q", deployTarget) + } + return s, nil +} + +func (r *Registry) GetDependencyInstaller(runtime string) (DependencyInstaller, error) { + return findByPrefix(r.installers, runtime, "dependency installer") +} + +// GetSourceCompiler returns nil if no compiler is registered (source is +// deployed as-is, e.g. Python). +func (r *Registry) GetSourceCompiler(runtime string) SourceCompiler { + c, _ := longestPrefixMatch(r.compilers, runtime) + return c +} + +func (r *Registry) GetHandlerDependencyReader(runtime string) HandlerDependencyReader { + reader, _ := longestPrefixMatch(r.depReaders, runtime) + return reader +} + +func findByPrefix[T any](m map[string]T, runtime, label string) (T, error) { + v, ok := longestPrefixMatch(m, runtime) + if !ok { + var zero T + return zero, fmt.Errorf("no %s registered for runtime %q", label, runtime) + } + return v, nil +} + +// Returns the value whose key is the longest prefix of runtime. Longest rather +// than first, because Go map iteration is unordered and a first-match loop +// returns a different value from run to run wherever two registered prefixes +// both match. Nothing registered today overlaps, which is what would make such +// a bug so slow to find. +func longestPrefixMatch[T any](m map[string]T, runtime string) (T, bool) { + var ( + best T + found bool + longest int + ) + for prefix, value := range m { + if !strings.HasPrefix(runtime, prefix) { + continue + } + if !found || len(prefix) > longest { + best, found, longest = value, true, len(prefix) + } + } + return best, found +} diff --git a/apps/cli/internal/build/registry_test.go b/apps/cli/internal/build/registry_test.go new file mode 100644 index 00000000..166c2517 --- /dev/null +++ b/apps/cli/internal/build/registry_test.go @@ -0,0 +1,127 @@ +package build + +import ( + "context" + "io" + "testing" + + "github.com/stretchr/testify/suite" +) + +type RegistrySuite struct { + suite.Suite +} + +func TestRegistrySuite(t *testing.T) { + suite.Run(t, new(RegistrySuite)) +} + +// --- stub implementations --- + +type stubStrategy struct{} + +func (s *stubStrategy) Build(_ context.Context, _ *BuildParams) (*Manifest, error) { + return &Manifest{}, nil +} + +type stubInstaller struct{} + +func (s *stubInstaller) InstallDependencies(_ context.Context, _, _ string, _ []string, _ io.Writer) error { + return nil +} + +type stubCompiler struct{} + +func (s *stubCompiler) Compile(_ context.Context, _, _ string, _ io.Writer) error { + return nil +} + +type stubDepReader struct{} + +func (s *stubDepReader) ReadHandlerDependencies(_ string) (map[string][]string, error) { + return map[string][]string{"h": {"dep"}}, nil +} + +// --- GetStrategy --- + +func (s *RegistrySuite) Test_GetStrategy_returnsRegisteredStrategy() { + r := NewRegistry() + strat := &stubStrategy{} + r.RegisterStrategy("aws-serverless", strat) + + got, err := r.GetStrategy("aws-serverless") + + s.NoError(err) + s.Equal(strat, got) +} + +func (s *RegistrySuite) Test_GetStrategy_returnsErrorForUnregisteredTarget() { + r := NewRegistry() + + _, err := r.GetStrategy("gcp-cloud-run") + + s.Error(err) + s.Contains(err.Error(), "gcp-cloud-run") +} + +// --- GetDependencyInstaller --- + +func (s *RegistrySuite) Test_GetDependencyInstaller_matchesByRuntimePrefix() { + r := NewRegistry() + inst := &stubInstaller{} + r.RegisterDependencyInstaller("nodejs", inst) + + got, err := r.GetDependencyInstaller("nodejs24.x") + + s.NoError(err) + s.Equal(inst, got) +} + +func (s *RegistrySuite) Test_GetDependencyInstaller_returnsErrorForUnregisteredRuntime() { + r := NewRegistry() + + _, err := r.GetDependencyInstaller("ruby3.3") + + s.Error(err) + s.Contains(err.Error(), "ruby3.3") +} + +// --- GetSourceCompiler --- + +func (s *RegistrySuite) Test_GetSourceCompiler_returnsNilForUnregisteredRuntime() { + r := NewRegistry() + + got := r.GetSourceCompiler("python3.12") + + s.Nil(got) +} + +func (s *RegistrySuite) Test_GetSourceCompiler_returnsCompilerByPrefix() { + r := NewRegistry() + comp := &stubCompiler{} + r.RegisterSourceCompiler("nodejs", comp) + + got := r.GetSourceCompiler("nodejs24.x") + + s.Equal(comp, got) +} + +// --- GetHandlerDependencyReader --- + +func (s *RegistrySuite) Test_GetHandlerDependencyReader_returnsNilForUnregisteredRuntime() { + r := NewRegistry() + + got := r.GetHandlerDependencyReader("rust1.x") + + s.Nil(got) +} + +func (s *RegistrySuite) Test_GetHandlerDependencyReader_returnsReaderByPrefix() { + r := NewRegistry() + reader := &stubDepReader{} + r.RegisterHandlerDependencyReader("python", reader) + + got := r.GetHandlerDependencyReader("python3.12") + + s.Equal(reader, got) +} diff --git a/apps/cli/internal/build/reproducible_archive_test.go b/apps/cli/internal/build/reproducible_archive_test.go new file mode 100644 index 00000000..91b1ccae --- /dev/null +++ b/apps/cli/internal/build/reproducible_archive_test.go @@ -0,0 +1,33 @@ +package build + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The determinism the build already claimed was only ever tested with a mocked +// installer over unchanged files. A dependency layer is built by re-running the +// package manager, which rewrites every mtime, so the real question is whether +// identical content with different timestamps hashes the same. +func TestArchiveHashIgnoresModificationTimes(t *testing.T) { + build := func(mtime time.Time) string { + src := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(src, "index.js"), []byte("module.exports = 1\n"), 0644)) + require.NoError(t, os.Chtimes(filepath.Join(src, "index.js"), mtime, mtime)) + + art, err := writeArtifact(ArtifactTypeLambdaLayer, src, t.TempDir(), "layer") + require.NoError(t, err) + return art.ContentHash + } + + first := build(time.Date(2021, 3, 4, 5, 6, 7, 0, time.UTC)) + second := build(time.Date(2024, 11, 12, 13, 14, 15, 0, time.UTC)) + + assert.Equal(t, first, second, + "a rebuild must hash the same, or the deploy references a layer the change set never created") +} diff --git a/apps/cli/internal/build/types.go b/apps/cli/internal/build/types.go new file mode 100644 index 00000000..4200ebb9 --- /dev/null +++ b/apps/cli/internal/build/types.go @@ -0,0 +1,138 @@ +// Package build provides application build and packaging logic for +// Celerity application deployments. +package build + +import ( + "context" + "io" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/newstack-cloud/celerity/apps/cli/buildmanifest" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" + "go.uber.org/zap" +) + +// The build manifest wire types are defined once in the public buildmanifest +// package (the single source of truth shared with the Celerity transformer) +// and re-exported here as aliases so existing internal/build call sites are +// unchanged. +type ( + Manifest = buildmanifest.Manifest + HandlerArtifacts = buildmanifest.HandlerArtifacts + Artifact = buildmanifest.Artifact + LambdaManifest = buildmanifest.LambdaManifest + LambdaHandlerArtifacts = buildmanifest.LambdaHandlerArtifacts +) + +const ( + ManifestVersion = buildmanifest.Version + ManifestFile = buildmanifest.FileName + + ArtifactTypeContainerImage = buildmanifest.ArtifactTypeContainerImage + + // ResourceLinksFilename is the name of the blueprint-derived resource + // links JSON file bundled into the Lambda app archive. The SDK reads + // it from the handler's module directory on cold start, removing the + // need to pass the payload through environment variables (which have + // a tight 4 KB total limit on AWS Lambda). + ResourceLinksFilename = buildmanifest.ResourceLinksFilename + + // HandlerScopeFilename is the per-handler resource scope file bundled + // alongside the resource links. + HandlerScopeFilename = buildmanifest.HandlerScopeFilename +) + +// HandlerInfo describes a handler to be built. +type HandlerInfo struct { + ResourceName string + HandlerName string + CodeLocation string +} + +// BuildParams holds the inputs needed to execute a build. +type BuildParams struct { + AppDir string + Runtime string + DeployTarget string + Handlers []HandlerInfo + HandlerDependencies map[string][]string + OutputDir string + Uploader ArtifactUploader + InstanceName string + Logger *zap.Logger + // Blueprint is the merged blueprint used to derive build-time artifacts + // like the resource links file bundled into the Lambda app archive. + Blueprint *schema.Blueprint + // ToolOutput is the writer for tool output (npm, pip, tsc). + // In interactive mode this should be a log file; in headless/standalone + // mode it should be os.Stdout. + ToolOutput io.Writer + // Toolchain builds the handlers executable for an OS-only runtime, and is + // nil for a runtime that hosts the language itself. Its presence is what + // selects the compiled packaging path. + Toolchain handlertoolchain.Toolchain +} + +// Strategy determines how an application is packaged for a given deploy target. +type Strategy interface { + Build(ctx context.Context, params *BuildParams) (*Manifest, error) +} + +// DependencyInstaller installs dependencies into a target directory. +// When packages is nil, all production dependencies are installed. +// When packages is non-nil, only those packages are installed. +// toolOutput receives tool stdout/stderr (npm, pip output). +type DependencyInstaller interface { + InstallDependencies(ctx context.Context, appDir, targetDir string, packages []string, toolOutput io.Writer) error +} + +// SourceCompiler compiles or transpiles source code for deployment, +// preserving the directory structure for readability. +// toolOutput receives compiler stdout/stderr (tsc output). +type SourceCompiler interface { + Compile(ctx context.Context, srcDir, outDir string, toolOutput io.Writer) error +} + +// CommandExecutor runs external commands. The default implementation +// uses os/exec; tests can substitute a stub. +type CommandExecutor interface { + Run(ctx context.Context, dir string, toolOutput io.Writer, name string, args ...string) error +} + +// ArtifactUploader uploads build artifacts to remote storage. +type ArtifactUploader interface { + Upload(ctx context.Context, artifact *Artifact, key string) error + UploadManifest(ctx context.Context, data []byte, instanceName string) (string, error) +} + +// HandlerDependencyReader reads per-handler dependency declarations +// from a language-specific manifest file. +type HandlerDependencyReader interface { + ReadHandlerDependencies(appDir string) (map[string][]string, error) +} + +// HandlerBootstrap writes a per-language entry point file that wraps the +// developer's app in the appropriate Celerity SDK serverless adapter for +// the deploy target. Returns the entry point string that the strategy +// should record on its target-specific sub-manifest. +// +// Generate is called once per build rather than once per handler, since the +// bootstrap is identical across all handlers in a project and the shared app +// code bundle contains a single copy of it. +// +// Implementations are strategy-specific (e.g. LambdaNodeBootstrap wraps +// the app for AWS Lambda). A future GCP strategy would ship its own +// implementations targeting the GCP serverless adapter. +type HandlerBootstrap interface { + Generate(stagingDir string) (entryPoint string, err error) + + // RequiredPackage names the adapter package the generated entry file + // imports, so the build can check the app actually depends on it. + // + // Declared here rather than checked elsewhere because the import and the + // requirement have to move together. A bootstrap whose import changed + // while a check somewhere else kept naming the old package would produce + // handlers that provision cleanly and then fail on their first + // invocation, a long way from the mistake. + RequiredPackage() string +} diff --git a/apps/cli/internal/build/upload.go b/apps/cli/internal/build/upload.go new file mode 100644 index 00000000..f1bd44c2 --- /dev/null +++ b/apps/cli/internal/build/upload.go @@ -0,0 +1,12 @@ +package build + +// ResolveUploader returns the appropriate artifact uploader for the deploy +// target, or nil if the target doesn't require pre-upload (e.g. Azure). +func ResolveUploader(deployTarget string, providerConfig map[string]any) ArtifactUploader { + switch deployTarget { + case "aws-serverless": + return newS3Uploader(providerConfig) + default: + return nil + } +} diff --git a/apps/cli/internal/build/upload_s3.go b/apps/cli/internal/build/upload_s3.go new file mode 100644 index 00000000..acb34774 --- /dev/null +++ b/apps/cli/internal/build/upload_s3.go @@ -0,0 +1,246 @@ +package build + +import ( + "bytes" + "context" + "fmt" + "os" + + "github.com/aws/aws-sdk-go-v2/aws" + awsconfig "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/s3" + s3types "github.com/aws/aws-sdk-go-v2/service/s3/types" + "github.com/aws/aws-sdk-go-v2/service/sts" +) + +// S3ArtifactUploader uploads build artifacts to an S3 bucket. +// The bucket is auto-created with a conventional name if it doesn't exist. +type S3ArtifactUploader struct { + client *s3.Client + bucket string + bucketEnsured bool + region string + providerConfig map[string]any +} + +func newS3Uploader(providerConfig map[string]any) *S3ArtifactUploader { + return &S3ArtifactUploader{ + providerConfig: providerConfig, + region: awsConfigValue(providerConfig, "region", "us-east-1"), + } +} + +func (u *S3ArtifactUploader) Upload(ctx context.Context, artifact *Artifact, key string) error { + client, err := u.getClient(ctx) + if err != nil { + return err + } + + bucket, err := u.ensureBucket(ctx, client) + if err != nil { + return err + } + + // Check if object already exists (hash-based dedup). + _, err = client.HeadObject(ctx, &s3.HeadObjectInput{ + Bucket: aws.String(bucket), + Key: aws.String(key), + }) + if err == nil { + artifact.S3Bucket = bucket + artifact.S3Key = key + return nil + } + + file, err := os.Open(artifact.LocalPath) + if err != nil { + return fmt.Errorf("opening artifact for upload: %w", err) + } + defer file.Close() + + _, err = client.PutObject(ctx, &s3.PutObjectInput{ + Bucket: aws.String(bucket), + Key: aws.String(key), + Body: file, + }) + if err != nil { + return fmt.Errorf("uploading to s3://%s/%s: %w", bucket, key, err) + } + + artifact.S3Bucket = bucket + artifact.S3Key = key + return nil +} + +// UploadManifest uploads the serialised build manifest JSON to the +// same bucket used for artifacts and returns the s3:// URL. Unlike +// Upload, this always overwrites the existing object. The manifest at a +// fixed per-instance key is mutable by design, since every build supersedes +// the previous one. +func (u *S3ArtifactUploader) UploadManifest( + ctx context.Context, data []byte, instanceName string, +) (string, error) { + client, err := u.getClient(ctx) + if err != nil { + return "", err + } + bucket, err := u.ensureBucket(ctx, client) + if err != nil { + return "", err + } + + key := fmt.Sprintf("%s/build-manifest.json", instanceName) + _, err = client.PutObject(ctx, &s3.PutObjectInput{ + Bucket: aws.String(bucket), + Key: aws.String(key), + Body: bytes.NewReader(data), + ContentType: aws.String("application/json"), + }) + if err != nil { + return "", fmt.Errorf("uploading build manifest to s3://%s/%s: %w", bucket, key, err) + } + return fmt.Sprintf("s3://%s/%s", bucket, key), nil +} + +func (u *S3ArtifactUploader) getClient(ctx context.Context) (*s3.Client, error) { + if u.client != nil { + return u.client, nil + } + + cfg, err := awsconfig.LoadDefaultConfig(ctx, u.awsConfigOptions()...) + if err != nil { + return nil, fmt.Errorf("loading AWS config: %w", err) + } + + s3Opts := []func(*s3.Options){} + + endpoint := awsConfigValue(u.providerConfig, "endpoint.s3", "") + if endpoint != "" { + s3Opts = append(s3Opts, func(o *s3.Options) { + o.BaseEndpoint = aws.String(endpoint) + }) + } + + if awsConfigValue(u.providerConfig, "s3UsePathStyle", "") == "true" { + s3Opts = append(s3Opts, func(o *s3.Options) { + o.UsePathStyle = true + }) + } + + u.client = s3.NewFromConfig(cfg, s3Opts...) + return u.client, nil +} + +func (u *S3ArtifactUploader) ensureBucket(ctx context.Context, client *s3.Client) (string, error) { + if u.bucketEnsured { + return u.bucket, nil + } + + // Allow bucket override from deploy config. + if override := awsConfigValue(u.providerConfig, "build.artifactBucket", ""); override != "" { + u.bucket = override + u.bucketEnsured = true + return u.bucket, nil + } + + accountID, err := u.resolveAccountID(ctx) + if err != nil { + return "", fmt.Errorf("resolving AWS account ID for bucket name: %w", err) + } + + u.bucket = fmt.Sprintf("celerity-build-%s-%s", accountID, u.region) + + _, err = client.HeadBucket(ctx, &s3.HeadBucketInput{ + Bucket: aws.String(u.bucket), + }) + if err == nil { + u.bucketEnsured = true + return u.bucket, nil + } + + createInput := &s3.CreateBucketInput{ + Bucket: aws.String(u.bucket), + } + if u.region != "us-east-1" { + createInput.CreateBucketConfiguration = &s3types.CreateBucketConfiguration{ + LocationConstraint: s3types.BucketLocationConstraint(u.region), + } + } + + _, err = client.CreateBucket(ctx, createInput) + if err != nil { + return "", fmt.Errorf("creating build artifact bucket %s: %w", u.bucket, err) + } + + u.bucketEnsured = true + return u.bucket, nil +} + +func (u *S3ArtifactUploader) resolveAccountID(ctx context.Context) (string, error) { + cfg, err := awsconfig.LoadDefaultConfig(ctx, u.awsConfigOptions()...) + if err != nil { + return "", err + } + + stsClient := sts.NewFromConfig(cfg) + identity, err := stsClient.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{}) + if err != nil { + return "", fmt.Errorf("getting caller identity: %w", err) + } + + return *identity.Account, nil +} + +// Artifacts have to land in the account the blueprint deploys to, so every +// client the uploader builds resolves credentials exactly as the deployment +// does. Building one of them differently, as the account lookup used to, sends +// that call down the ambient credential chain and names the artifact bucket +// after whatever account that chain resolves to. +func (u *S3ArtifactUploader) awsConfigOptions() []func(*awsconfig.LoadOptions) error { + opts := []func(*awsconfig.LoadOptions) error{ + awsconfig.WithRegion(u.region), + } + + accessKey := awsConfigValue(u.providerConfig, "accessKeyId", "") + secretKey := awsConfigValue(u.providerConfig, "secretAccessKey", "") + if accessKey != "" && secretKey != "" { + sessionToken := awsConfigValue(u.providerConfig, "sessionToken", "") + opts = append(opts, awsconfig.WithCredentialsProvider( + credentials.NewStaticCredentialsProvider(accessKey, secretKey, sessionToken), + )) + } + + if profile := awsConfigValue(u.providerConfig, "profile", ""); profile != "" { + opts = append(opts, awsconfig.WithSharedConfigProfile(profile)) + } + + return opts +} + +// Deploy target settings are written namespaced in app.deploy.jsonc +// ("aws.region") and reach the uploader in that form. The bare key is still +// accepted so a caller holding an already-stripped config keeps working. +// Looking up only the bare key, as this once did, matched none of the deploy +// target's AWS settings, so the region silently defaulted to us-east-1, +// artifacts were uploaded to a bucket in the wrong region, and Lambda then +// refused to read them across regions. +func awsConfigValue(config map[string]any, key, defaultVal string) string { + if value := stringFromConfig(config, "aws."+key, ""); value != "" { + return value + } + + return stringFromConfig(config, key, defaultVal) +} + +func stringFromConfig(config map[string]any, key, defaultVal string) string { + if config == nil { + return defaultVal + } + if v, ok := config[key]; ok { + if s, ok := v.(string); ok { + return s + } + } + return defaultVal +} diff --git a/apps/cli/internal/build/upload_s3_integration_test.go b/apps/cli/internal/build/upload_s3_integration_test.go new file mode 100644 index 00000000..d0c9ac1b --- /dev/null +++ b/apps/cli/internal/build/upload_s3_integration_test.go @@ -0,0 +1,199 @@ +package build + +import ( + "context" + "fmt" + "io" + "net" + "os" + "path/filepath" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + awsconfig "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/stretchr/testify/suite" +) + +const ( + testMinioEndpoint = "http://localhost:49000" + testMinioBucket = "celerity-build-test" + testMinioRegion = "us-east-1" +) + +type S3UploadIntegrationSuite struct { + suite.Suite + s3Client *s3.Client +} + +func TestS3UploadIntegrationSuite(t *testing.T) { + if !isMinioAvailable() { + t.Skip("MinIO not available on port 49000, run docker-compose.test-deps.yml") + } + suite.Run(t, new(S3UploadIntegrationSuite)) +} + +func (s *S3UploadIntegrationSuite) SetupSuite() { + cfg, err := awsconfig.LoadDefaultConfig(context.Background(), + awsconfig.WithRegion(testMinioRegion), + awsconfig.WithCredentialsProvider( + credentials.NewStaticCredentialsProvider("minioadmin", "minioadmin", ""), + ), + ) + s.Require().NoError(err) + + s.s3Client = s3.NewFromConfig(cfg, func(o *s3.Options) { + o.BaseEndpoint = aws.String(testMinioEndpoint) + o.UsePathStyle = true + }) + + _, err = s.s3Client.CreateBucket(context.Background(), &s3.CreateBucketInput{ + Bucket: aws.String(testMinioBucket), + }) + // Ignore "bucket already exists" errors from previous test runs. + if err != nil { + s.T().Logf("CreateBucket: %v (may already exist)", err) + } +} + +func (s *S3UploadIntegrationSuite) TestUpload_uploadsArtifactToMinio() { + uploader := s.newUploader() + + artifact := s.createTestArtifact("test-handler.zip", "handler code content") + key := "test-instance/handler/abc123.zip" + + err := uploader.Upload(context.Background(), artifact, key) + s.Require().NoError(err) + s.Equal(testMinioBucket, artifact.S3Bucket) + s.Equal(key, artifact.S3Key) + + s.assertObjectExists(key) +} + +func (s *S3UploadIntegrationSuite) TestUpload_skipsIfKeyAlreadyExists() { + uploader := s.newUploader() + + artifact := s.createTestArtifact("dedup-test.zip", "some content") + key := "test-instance/dedup/sha256-dedup.zip" + + err := uploader.Upload(context.Background(), artifact, key) + s.Require().NoError(err) + + // Upload again with a different local file, which should skip the upload + // and still set the S3 fields. + artifact2 := s.createTestArtifact("dedup-test-2.zip", "different content") + err = uploader.Upload(context.Background(), artifact2, key) + s.Require().NoError(err) + s.Equal(testMinioBucket, artifact2.S3Bucket) + s.Equal(key, artifact2.S3Key) +} + +func (s *S3UploadIntegrationSuite) TestUpload_ensuresBucketFromConfig() { + customBucket := fmt.Sprintf("celerity-build-custom-%d", os.Getpid()) + + uploader := newS3Uploader(map[string]any{ + "accessKeyId": "minioadmin", + "secretAccessKey": "minioadmin", + "region": testMinioRegion, + "endpoint.s3": testMinioEndpoint, + "s3UsePathStyle": "true", + "aws.build.artifactBucket": customBucket, + }) + + // Create the custom bucket first. + _, err := s.s3Client.CreateBucket(context.Background(), &s3.CreateBucketInput{ + Bucket: aws.String(customBucket), + }) + if err != nil { + s.T().Logf("CreateBucket: %v (may already exist)", err) + } + + artifact := s.createTestArtifact("custom-bucket.zip", "custom content") + key := "test/custom.zip" + + err = uploader.Upload(context.Background(), artifact, key) + s.Require().NoError(err) + s.Equal(customBucket, artifact.S3Bucket) +} + +func (s *S3UploadIntegrationSuite) TestUploadManifest_writesJSONBlobToS3() { + uploader := s.newUploader() + + data := []byte(`{"version":"1","target":"aws-serverless"}`) + url, err := uploader.UploadManifest(context.Background(), data, "my-app") + s.Require().NoError(err) + s.Equal(fmt.Sprintf("s3://%s/my-app/build-manifest.json", testMinioBucket), url) + + got, err := s.s3Client.GetObject(context.Background(), &s3.GetObjectInput{ + Bucket: aws.String(testMinioBucket), + Key: aws.String("my-app/build-manifest.json"), + }) + s.Require().NoError(err) + defer got.Body.Close() + body, err := io.ReadAll(got.Body) + s.Require().NoError(err) + s.Equal(data, body) + s.NotNil(got.ContentType) + s.Equal("application/json", aws.ToString(got.ContentType)) +} + +func (s *S3UploadIntegrationSuite) TestUploadManifest_overwritesExistingObject() { + uploader := s.newUploader() + + first := []byte(`{"version":"1","target":"first"}`) + _, err := uploader.UploadManifest(context.Background(), first, "overwrite-test") + s.Require().NoError(err) + + second := []byte(`{"version":"1","target":"second"}`) + _, err = uploader.UploadManifest(context.Background(), second, "overwrite-test") + s.Require().NoError(err) + + got, err := s.s3Client.GetObject(context.Background(), &s3.GetObjectInput{ + Bucket: aws.String(testMinioBucket), + Key: aws.String("overwrite-test/build-manifest.json"), + }) + s.Require().NoError(err) + defer got.Body.Close() + body, err := io.ReadAll(got.Body) + s.Require().NoError(err) + s.Equal(second, body) +} + +func (s *S3UploadIntegrationSuite) newUploader() *S3ArtifactUploader { + return newS3Uploader(map[string]any{ + "accessKeyId": "minioadmin", + "secretAccessKey": "minioadmin", + "region": testMinioRegion, + "endpoint.s3": testMinioEndpoint, + "s3UsePathStyle": "true", + "aws.build.artifactBucket": testMinioBucket, + }) +} + +func (s *S3UploadIntegrationSuite) createTestArtifact(name, content string) *Artifact { + dir := s.T().TempDir() + path := filepath.Join(dir, name) + s.Require().NoError(os.WriteFile(path, []byte(content), 0644)) + return &Artifact{ + Type: ArtifactTypeLambdaArchive, + LocalPath: path, + } +} + +func (s *S3UploadIntegrationSuite) assertObjectExists(key string) { + _, err := s.s3Client.HeadObject(context.Background(), &s3.HeadObjectInput{ + Bucket: aws.String(testMinioBucket), + Key: aws.String(key), + }) + s.Require().NoError(err, "expected object %s to exist in bucket %s", key, testMinioBucket) +} + +func isMinioAvailable() bool { + conn, err := net.Dial("tcp", "localhost:49000") + if err != nil { + return false + } + conn.Close() + return true +} diff --git a/apps/cli/internal/build/upload_s3_test.go b/apps/cli/internal/build/upload_s3_test.go new file mode 100644 index 00000000..3dbce904 --- /dev/null +++ b/apps/cli/internal/build/upload_s3_test.go @@ -0,0 +1,82 @@ +package build + +import ( + "testing" + + awsconfig "github.com/aws/aws-sdk-go-v2/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Deploy target settings are written namespaced in app.deploy.jsonc and reach +// the uploader in that form, so a bare-key lookup never matches. With the +// region unmatched it defaulted to us-east-1, artifacts were uploaded to a +// bucket in that region, and Lambda refused to read them from the region the +// blueprint deploys to. +func Test_aws_config_value_reads_the_namespaced_key(t *testing.T) { + config := map[string]any{ + "aws.region": "eu-west-2", + "aws.profile": "some-profile", + } + + assert.Equal(t, "eu-west-2", awsConfigValue(config, "region", "us-east-1")) + assert.Equal(t, "some-profile", awsConfigValue(config, "profile", "")) +} + +// A caller holding an already-stripped config keeps working. +func Test_aws_config_value_falls_back_to_the_bare_key(t *testing.T) { + config := map[string]any{"region": "eu-west-1"} + + assert.Equal(t, "eu-west-1", awsConfigValue(config, "region", "us-east-1")) +} + +func Test_aws_config_value_prefers_the_namespaced_key(t *testing.T) { + config := map[string]any{ + "aws.region": "eu-west-2", + "region": "ap-southeast-1", + } + + assert.Equal(t, "eu-west-2", awsConfigValue(config, "region", "us-east-1")) +} + +func Test_aws_config_value_uses_the_default_when_absent(t *testing.T) { + assert.Equal(t, "us-east-1", awsConfigValue(map[string]any{}, "region", "us-east-1")) + assert.Equal(t, "us-east-1", awsConfigValue(nil, "region", "us-east-1")) +} + +// Every client the uploader builds must resolve credentials the same way, or +// the account lookup that names the bucket resolves a different account from +// the one the artifacts are uploaded to. +func Test_uploader_applies_the_profile_to_its_aws_config(t *testing.T) { + uploader := newS3Uploader(map[string]any{ + "aws.region": "eu-west-2", + "aws.profile": "some-profile", + }) + + loadOptions := awsconfig.LoadOptions{} + for _, apply := range uploader.awsConfigOptions() { + require.NoError(t, apply(&loadOptions)) + } + + assert.Equal(t, "some-profile", loadOptions.SharedConfigProfile) + assert.Equal(t, "eu-west-2", loadOptions.Region) +} + +func Test_uploader_omits_the_profile_when_none_is_configured(t *testing.T) { + uploader := newS3Uploader(map[string]any{"aws.region": "eu-west-2"}) + + loadOptions := awsconfig.LoadOptions{} + for _, apply := range uploader.awsConfigOptions() { + require.NoError(t, apply(&loadOptions)) + } + + assert.Empty(t, loadOptions.SharedConfigProfile) +} + +// The bucket is per account and region, so a region that was never read sends +// artifacts somewhere the deployment cannot use them. +func Test_uploader_takes_its_region_from_the_deploy_target(t *testing.T) { + uploader := newS3Uploader(map[string]any{"aws.region": "eu-west-2"}) + + assert.Equal(t, "eu-west-2", uploader.region) +} diff --git a/apps/cli/internal/build/upload_test.go b/apps/cli/internal/build/upload_test.go new file mode 100644 index 00000000..d89f1ee2 --- /dev/null +++ b/apps/cli/internal/build/upload_test.go @@ -0,0 +1,34 @@ +package build + +import "context" + +// fakeUploader is a test-only ArtifactUploader that records the last +// call without touching any network. Used by manifest_test.go and any +// future unit-level test that needs an uploader without MinIO. +type fakeUploader struct { + artifacts []uploadedArtifact + + manifestURL string + manifestErr error + lastData []byte + lastInstance string +} + +type uploadedArtifact struct { + artifact *Artifact + key string +} + +func (f *fakeUploader) Upload(_ context.Context, artifact *Artifact, key string) error { + f.artifacts = append(f.artifacts, uploadedArtifact{artifact: artifact, key: key}) + return nil +} + +func (f *fakeUploader) UploadManifest(_ context.Context, data []byte, instanceName string) (string, error) { + f.lastData = append([]byte(nil), data...) + f.lastInstance = instanceName + if f.manifestErr != nil { + return "", f.manifestErr + } + return f.manifestURL, nil +} From d03b0e00e290abfd45d4d219920d9009d304d376 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 14 Oct 2026 16:18:41 +0100 Subject: [PATCH 08/12] feat(cli): add config commands for deployed environments Reads and writes the configuration and secrets a deployed application resolves at runtime. Each celerity/config resource in the blueprint maps to one store in the cloud, and the deploy engine prefixes store names with the environment, so the commands resolve a store the same way the running application does. Provider selection is encapsulated behind a config store interface, so the command layer never imports a cloud SDK directly and a new provider is added in one place. AWS arrives first with Parameter Store for plaintext and Secrets Manager for sensitive values. An environment is a deploy config file rather than anything the CLI tracks of its own, so adding one is adding a file. Discovery lists the base config as default alongside any per environment file, which is what the interactive picker offers. --- apps/cli/cmd/commands/config.go | 243 +++++++++++++ apps/cli/cmd/commands/config_delete.go | 71 ++++ apps/cli/cmd/commands/config_export.go | 88 +++++ apps/cli/cmd/commands/config_get.go | 45 +++ apps/cli/cmd/commands/config_import.go | 70 ++++ apps/cli/cmd/commands/config_list.go | 111 ++++++ apps/cli/cmd/commands/config_set.go | 100 ++++++ apps/cli/internal/appconfig/aws.go | 47 +++ .../internal/appconfig/aws_parameter_store.go | 141 ++++++++ .../appconfig/aws_parameter_store_test.go | 251 ++++++++++++++ .../internal/appconfig/aws_secrets_manager.go | 152 ++++++++ .../appconfig/aws_secrets_manager_test.go | 197 +++++++++++ apps/cli/internal/appconfig/blueprint.go | 100 ++++++ apps/cli/internal/appconfig/blueprint_test.go | 157 +++++++++ apps/cli/internal/appconfig/provider.go | 24 ++ apps/cli/internal/appconfig/store.go | 13 + .../internal/appconfig/testhelpers_test.go | 5 + apps/cli/internal/appconfig/types.go | 33 ++ apps/cli/internal/devconfig/environments.go | 199 +++++++++++ apps/cli/internal/tui/configui/commands.go | 67 ++++ apps/cli/internal/tui/configui/env_select.go | 134 +++++++ .../internal/tui/configui/env_select_test.go | 99 ++++++ apps/cli/internal/tui/configui/key_table.go | 327 ++++++++++++++++++ .../internal/tui/configui/key_table_test.go | 177 ++++++++++ apps/cli/internal/tui/configui/list_model.go | 105 ++++++ apps/cli/internal/tui/configui/messages.go | 61 ++++ apps/cli/internal/tui/configui/output.go | 138 ++++++++ apps/cli/internal/tui/configui/output_test.go | 89 +++++ .../cli/internal/tui/configui/store_select.go | 123 +++++++ .../tui/configui/store_select_test.go | 97 ++++++ .../testdata/app.deploy.production.jsonc | 10 + .../testdata/app.deploy.staging.jsonc | 10 + .../internal/tui/configui/testutil_test.go | 63 ++++ apps/cli/internal/tui/configui/tui.go | 298 ++++++++++++++++ 34 files changed, 3845 insertions(+) create mode 100644 apps/cli/cmd/commands/config.go create mode 100644 apps/cli/cmd/commands/config_delete.go create mode 100644 apps/cli/cmd/commands/config_export.go create mode 100644 apps/cli/cmd/commands/config_get.go create mode 100644 apps/cli/cmd/commands/config_import.go create mode 100644 apps/cli/cmd/commands/config_list.go create mode 100644 apps/cli/cmd/commands/config_set.go create mode 100644 apps/cli/internal/appconfig/aws.go create mode 100644 apps/cli/internal/appconfig/aws_parameter_store.go create mode 100644 apps/cli/internal/appconfig/aws_parameter_store_test.go create mode 100644 apps/cli/internal/appconfig/aws_secrets_manager.go create mode 100644 apps/cli/internal/appconfig/aws_secrets_manager_test.go create mode 100644 apps/cli/internal/appconfig/blueprint.go create mode 100644 apps/cli/internal/appconfig/blueprint_test.go create mode 100644 apps/cli/internal/appconfig/provider.go create mode 100644 apps/cli/internal/appconfig/store.go create mode 100644 apps/cli/internal/appconfig/testhelpers_test.go create mode 100644 apps/cli/internal/appconfig/types.go create mode 100644 apps/cli/internal/devconfig/environments.go create mode 100644 apps/cli/internal/tui/configui/commands.go create mode 100644 apps/cli/internal/tui/configui/env_select.go create mode 100644 apps/cli/internal/tui/configui/env_select_test.go create mode 100644 apps/cli/internal/tui/configui/key_table.go create mode 100644 apps/cli/internal/tui/configui/key_table_test.go create mode 100644 apps/cli/internal/tui/configui/list_model.go create mode 100644 apps/cli/internal/tui/configui/messages.go create mode 100644 apps/cli/internal/tui/configui/output.go create mode 100644 apps/cli/internal/tui/configui/output_test.go create mode 100644 apps/cli/internal/tui/configui/store_select.go create mode 100644 apps/cli/internal/tui/configui/store_select_test.go create mode 100644 apps/cli/internal/tui/configui/testdata/app.deploy.production.jsonc create mode 100644 apps/cli/internal/tui/configui/testdata/app.deploy.staging.jsonc create mode 100644 apps/cli/internal/tui/configui/testutil_test.go create mode 100644 apps/cli/internal/tui/configui/tui.go diff --git a/apps/cli/cmd/commands/config.go b/apps/cli/cmd/commands/config.go new file mode 100644 index 00000000..c376e6a5 --- /dev/null +++ b/apps/cli/cmd/commands/config.go @@ -0,0 +1,243 @@ +package commands + +import ( + "context" + "fmt" + "os" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/newstack-cloud/celerity/apps/cli/internal/appconfig" + "github.com/newstack-cloud/celerity/apps/cli/internal/blueprint" + "github.com/newstack-cloud/celerity/apps/cli/internal/devconfig" + "github.com/newstack-cloud/celerity/apps/cli/internal/tui/configui" + "github.com/newstack-cloud/deploy-cli-sdk/config" + styles "github.com/newstack-cloud/deploy-cli-sdk/styles" + "github.com/spf13/cobra" + "golang.org/x/term" +) + +func setupConfigCommand(rootCmd *cobra.Command, confProvider *config.Provider) { + configCmd := &cobra.Command{ + Use: "config", + Short: "Manage deployed application config and secrets", + Long: `Manage runtime configuration and secrets for deployed Celerity applications. + +Running without a subcommand opens an interactive session for browsing and +managing config values across environments and stores. + +Subcommands are available for direct operations: + celerity config set [value] + celerity config get + celerity config list [store] + celerity config delete + celerity config import + celerity config export `, + RunE: func(cmd *cobra.Command, args []string) error { + inTerminal := term.IsTerminal(int(os.Stdout.Fd())) + if !inTerminal { + return fmt.Errorf( + "interactive config management requires a terminal. Use a subcommand " + + "instead (e.g. 'celerity config list --env staging')", + ) + } + + appDir, _ := confProvider.GetString("configAppDir") + blueprintFile, _ := confProvider.GetString("configBlueprintFile") + celerityStyles := styles.NewStyles(lipgloss.NewRenderer(os.Stdout), styles.NewCelerityPalette()) + + app := configui.NewMainModel(configui.MainModelOptions{ + Context: cmd.Context(), + AppDir: appDir, + BlueprintFile: blueprintFile, + Styles: celerityStyles, + }) + + options := []tea.ProgramOption{ + tea.WithContext(cmd.Context()), + tea.WithAltScreen(), + tea.WithMouseCellMotion(), + } + finalModel, err := tea.NewProgram(app, options...).Run() + if err != nil { + return err + } + + final := finalModel.(configui.MainModel) + if final.Error != nil { + return final.Error + } + return nil + }, + } + + configCmd.PersistentFlags().StringP( + "env", "e", "", + "Environment name. Loads app.deploy.{env}.jsonc if it exists, "+ + "otherwise falls back to app.deploy.jsonc with {env} as the store name prefix.", + ) + confProvider.BindPFlag("configEnv", configCmd.PersistentFlags().Lookup("env")) + confProvider.BindEnvVar("configEnv", "CELERITY_CLI_CONFIG_ENV") + + configCmd.PersistentFlags().String( + "app-dir", ".", + "Application root directory.", + ) + confProvider.BindPFlag("configAppDir", configCmd.PersistentFlags().Lookup("app-dir")) + confProvider.BindEnvVar("configAppDir", "CELERITY_CLI_CONFIG_APP_DIR") + + configCmd.PersistentFlags().StringP( + "blueprint-file", "b", "", + "Blueprint file path. Auto-detected if not specified.", + ) + confProvider.BindPFlag("configBlueprintFile", configCmd.PersistentFlags().Lookup("blueprint-file")) + confProvider.BindEnvVar("configBlueprintFile", "CELERITY_CLI_CONFIG_BLUEPRINT_FILE") + + configCmd.PersistentFlags().String( + "region", "", + "Cloud provider region override.", + ) + confProvider.BindPFlag("configRegion", configCmd.PersistentFlags().Lookup("region")) + confProvider.BindEnvVar("configRegion", "CELERITY_CLI_CONFIG_REGION") + + setupConfigSetCommand(configCmd, confProvider) + setupConfigGetCommand(configCmd, confProvider) + setupConfigListCommand(configCmd, confProvider) + setupConfigDeleteCommand(configCmd, confProvider) + setupConfigImportCommand(configCmd, confProvider) + setupConfigExportCommand(configCmd, confProvider) + + rootCmd.AddCommand(configCmd) +} + +func resolveEnv( + confProvider *config.Provider, + appDir string, + inTerminal bool, +) (*devconfig.EnvironmentInfo, error) { + envName, isDefault := confProvider.GetString("configEnv") + + if !isDefault && envName != "" { + return resolveNamedEnv(appDir, envName) + } + + if !inTerminal { + return nil, fmt.Errorf("--env is required in non-interactive mode") + } + + return nil, fmt.Errorf( + "--env is required. Specify the target environment " + + "(e.g. --env staging)", + ) +} + +func resolveNamedEnv( + appDir, envName string, +) (*devconfig.EnvironmentInfo, error) { + envPath := devconfig.FindEnvDeployConfig(appDir, envName) + if envPath != "" { + result, err := devconfig.ReadDeployConfig(envPath) + if err != nil { + return nil, fmt.Errorf("reading deploy config for env %q: %w", envName, err) + } + info := &devconfig.EnvironmentInfo{ + Name: envName, + FilePath: envPath, + DeployTarget: result.DeployTarget, + AppEnv: result.AppEnv, + } + if result.Config != nil { + info.Region = result.Config["aws.region"] + info.Profile = result.Config["aws.profile"] + } + return info, nil + } + + basePath := devconfig.FindDeployConfig(appDir) + if basePath == "" { + return nil, fmt.Errorf( + "no deploy config found in %s. Create app.deploy.jsonc or app.deploy.%s.jsonc", + appDir, envName, + ) + } + + result, err := devconfig.ReadDeployConfig(basePath) + if err != nil { + return nil, fmt.Errorf("reading deploy config: %w", err) + } + + return &devconfig.EnvironmentInfo{ + Name: envName, + FilePath: basePath, + DeployTarget: result.DeployTarget, + AppEnv: envName, + }, nil +} + +func resolveConfigStore( + ctx context.Context, + envInfo *devconfig.EnvironmentInfo, + storeName string, + confProvider *config.Provider, +) (appconfig.ConfigStore, *appconfig.StoreInfo, error) { + appDir, _ := confProvider.GetString("configAppDir") + bpFile, bpIsDefault := confProvider.GetString("configBlueprintFile") + + if bpIsDefault || bpFile == "" { + bpFile = appDir + "/app.blueprint.yaml" + } + + bp, _, err := blueprint.LoadForDev(bpFile) + if err != nil { + return nil, nil, fmt.Errorf("loading blueprint: %w", err) + } + + stores := appconfig.CollectStoreInfo(bp) + info := appconfig.FindStoreInfo(stores, storeName) + if info == nil { + return nil, nil, fmt.Errorf( + "store %q not found in blueprint. The available stores are %s", + storeName, storeNames(stores), + ) + } + + appEnv := envInfo.AppEnv + if appEnv == "" { + appEnv = envInfo.Name + } + resolved := appconfig.StoreInfo{ + ResourceName: info.ResourceName, + StoreName: appEnv + "-" + info.StoreName, + StoreKind: info.StoreKind, + PlaintextKeys: info.PlaintextKeys, + } + + regionOverride, regionIsDefault := confProvider.GetString("configRegion") + region := envInfo.Region + if !regionIsDefault && regionOverride != "" { + region = regionOverride + } + + opts := appconfig.ProviderOpts{ + Region: region, + Profile: envInfo.Profile, + } + + store, err := appconfig.NewConfigStore(ctx, envInfo.DeployTarget, resolved, opts) + if err != nil { + return nil, nil, err + } + + return store, &resolved, nil +} + +func storeNames(stores []appconfig.StoreInfo) string { + if len(stores) == 0 { + return "(none)" + } + names := make([]string, len(stores)) + for i, s := range stores { + names[i] = s.StoreName + } + return fmt.Sprintf("%v", names) +} diff --git a/apps/cli/cmd/commands/config_delete.go b/apps/cli/cmd/commands/config_delete.go new file mode 100644 index 00000000..2dd9f8c4 --- /dev/null +++ b/apps/cli/cmd/commands/config_delete.go @@ -0,0 +1,71 @@ +package commands + +import ( + "bufio" + "fmt" + "os" + "strings" + + "github.com/newstack-cloud/celerity/apps/cli/internal/tui/configui" + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/spf13/cobra" + "golang.org/x/term" +) + +func setupConfigDeleteCommand(configCmd *cobra.Command, confProvider *config.Provider) { + deleteCmd := &cobra.Command{ + Use: "delete ", + Short: "Delete a config value", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + storeName, key := args[0], args[1] + inTerminal := term.IsTerminal(int(os.Stdout.Fd())) + appDir, _ := confProvider.GetString("configAppDir") + output := configui.NewConfigOutput(os.Stdout, inTerminal) + + envInfo, err := resolveEnv(confProvider, appDir, inTerminal) + if err != nil { + return err + } + + store, storeInfo, err := resolveConfigStore( + cmd.Context(), envInfo, storeName, confProvider, + ) + if err != nil { + return err + } + + yesFlag, _ := confProvider.GetBool("configDeleteYes") + if !yesFlag { + if !inTerminal { + return fmt.Errorf("--yes is required in non-interactive mode") + } + fmt.Fprintf(os.Stderr, + "Delete key %q from %s? [y/N]: ", key, storeInfo.StoreName, + ) + reader := bufio.NewReader(os.Stdin) + answer, _ := reader.ReadString('\n') + if !strings.HasPrefix(strings.ToLower(strings.TrimSpace(answer)), "y") { + output.PrintInfo("Cancelled") + return nil + } + } + + if err := store.Delete(cmd.Context(), key); err != nil { + return err + } + + output.PrintSuccess(fmt.Sprintf( + "Deleted key %q from store %q", key, storeInfo.StoreName, + )) + return nil + }, + } + + deleteCmd.Flags().BoolP("yes", "y", false, + "Skip confirmation (required in headless mode).") + confProvider.BindPFlag("configDeleteYes", deleteCmd.Flags().Lookup("yes")) + confProvider.BindEnvVar("configDeleteYes", "CELERITY_CLI_CONFIG_DELETE_YES") + + configCmd.AddCommand(deleteCmd) +} diff --git a/apps/cli/cmd/commands/config_export.go b/apps/cli/cmd/commands/config_export.go new file mode 100644 index 00000000..eae7e981 --- /dev/null +++ b/apps/cli/cmd/commands/config_export.go @@ -0,0 +1,88 @@ +package commands + +import ( + "encoding/json" + "fmt" + "os" + + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/spf13/cobra" + "golang.org/x/term" + "gopkg.in/yaml.v3" +) + +func setupConfigExportCommand(configCmd *cobra.Command, confProvider *config.Provider) { + exportCmd := &cobra.Command{ + Use: "export ", + Short: "Export config values to stdout or file", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + storeName := args[0] + inTerminal := term.IsTerminal(int(os.Stdout.Fd())) + appDir, _ := confProvider.GetString("configAppDir") + + envInfo, err := resolveEnv(confProvider, appDir, inTerminal) + if err != nil { + return err + } + + store, _, err := resolveConfigStore( + cmd.Context(), envInfo, storeName, confProvider, + ) + if err != nil { + return err + } + + entries, err := store.List(cmd.Context()) + if err != nil { + return err + } + + data := make(map[string]string, len(entries)) + for _, e := range entries { + data[e.Key] = e.Value + } + + format, _ := confProvider.GetString("configExportFormat") + outFile, outIsDefault := confProvider.GetString("configExportOut") + + var encoded []byte + switch format { + case "json": + encoded, err = json.MarshalIndent(data, "", " ") + if err != nil { + return fmt.Errorf("encoding JSON: %w", err) + } + encoded = append(encoded, '\n') + default: + encoded, err = yaml.Marshal(data) + if err != nil { + return fmt.Errorf("encoding YAML: %w", err) + } + } + + if !outIsDefault && outFile != "" { + if err := os.WriteFile(outFile, encoded, 0o644); err != nil { + return fmt.Errorf("writing to %s: %w", outFile, err) + } + fmt.Fprintf(os.Stderr, "Exported %d values to %s\n", len(data), outFile) + return nil + } + + _, err = os.Stdout.Write(encoded) + return err + }, + } + + exportCmd.Flags().String("format", "yaml", + "Output format: yaml (default) or json.") + confProvider.BindPFlag("configExportFormat", exportCmd.Flags().Lookup("format")) + confProvider.BindEnvVar("configExportFormat", "CELERITY_CLI_CONFIG_EXPORT_FORMAT") + + exportCmd.Flags().StringP("out", "o", "", + "Output file path. Defaults to stdout.") + confProvider.BindPFlag("configExportOut", exportCmd.Flags().Lookup("out")) + confProvider.BindEnvVar("configExportOut", "CELERITY_CLI_CONFIG_EXPORT_OUT") + + configCmd.AddCommand(exportCmd) +} diff --git a/apps/cli/cmd/commands/config_get.go b/apps/cli/cmd/commands/config_get.go new file mode 100644 index 00000000..06609bd3 --- /dev/null +++ b/apps/cli/cmd/commands/config_get.go @@ -0,0 +1,45 @@ +package commands + +import ( + "fmt" + "os" + + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/spf13/cobra" + "golang.org/x/term" +) + +func setupConfigGetCommand(configCmd *cobra.Command, confProvider *config.Provider) { + getCmd := &cobra.Command{ + Use: "get ", + Short: "Get a config value", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + storeName, key := args[0], args[1] + inTerminal := term.IsTerminal(int(os.Stdout.Fd())) + appDir, _ := confProvider.GetString("configAppDir") + + envInfo, err := resolveEnv(confProvider, appDir, inTerminal) + if err != nil { + return err + } + + store, _, err := resolveConfigStore( + cmd.Context(), envInfo, storeName, confProvider, + ) + if err != nil { + return err + } + + entry, err := store.Get(cmd.Context(), key) + if err != nil { + return err + } + + fmt.Fprintln(os.Stdout, entry.Value) + return nil + }, + } + + configCmd.AddCommand(getCmd) +} diff --git a/apps/cli/cmd/commands/config_import.go b/apps/cli/cmd/commands/config_import.go new file mode 100644 index 00000000..3fa3df07 --- /dev/null +++ b/apps/cli/cmd/commands/config_import.go @@ -0,0 +1,70 @@ +package commands + +import ( + "fmt" + "os" + + "github.com/newstack-cloud/celerity/apps/cli/internal/appconfig" + "github.com/newstack-cloud/celerity/apps/cli/internal/seed" + "github.com/newstack-cloud/celerity/apps/cli/internal/tui/configui" + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/spf13/cobra" + "golang.org/x/term" +) + +func setupConfigImportCommand(configCmd *cobra.Command, confProvider *config.Provider) { + importCmd := &cobra.Command{ + Use: "import ", + Short: "Import config values from a YAML/JSON file", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + storeName, filePath := args[0], args[1] + inTerminal := term.IsTerminal(int(os.Stdout.Fd())) + appDir, _ := confProvider.GetString("configAppDir") + output := configui.NewConfigOutput(os.Stdout, inTerminal) + + envInfo, err := resolveEnv(confProvider, appDir, inTerminal) + if err != nil { + return err + } + + store, storeInfo, err := resolveConfigStore( + cmd.Context(), envInfo, storeName, confProvider, + ) + if err != nil { + return err + } + + values, err := seed.LoadConfigYAML(filePath) + if err != nil { + return fmt.Errorf("reading import file: %w", err) + } + + if len(values) == 0 { + output.PrintWarning("No values found in import file") + return nil + } + + entries := make([]appconfig.ConfigEntry, 0, len(values)) + for k, v := range values { + sensitive := !storeInfo.PlaintextKeys[k] + entries = append(entries, appconfig.ConfigEntry{ + Key: k, + Value: v, + Sensitive: sensitive, + }) + } + + if err := store.Import(cmd.Context(), entries); err != nil { + return err + } + + output.PrintSuccess(fmt.Sprintf( + "Imported %d values into store %q", len(entries), storeInfo.StoreName, + )) + return nil + }, + } + + configCmd.AddCommand(importCmd) +} diff --git a/apps/cli/cmd/commands/config_list.go b/apps/cli/cmd/commands/config_list.go new file mode 100644 index 00000000..6e646a1c --- /dev/null +++ b/apps/cli/cmd/commands/config_list.go @@ -0,0 +1,111 @@ +package commands + +import ( + "os" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/newstack-cloud/celerity/apps/cli/internal/appconfig" + "github.com/newstack-cloud/celerity/apps/cli/internal/blueprint" + "github.com/newstack-cloud/celerity/apps/cli/internal/tui/configui" + "github.com/newstack-cloud/deploy-cli-sdk/config" + styles "github.com/newstack-cloud/deploy-cli-sdk/styles" + "github.com/spf13/cobra" + "golang.org/x/term" +) + +func setupConfigListCommand(configCmd *cobra.Command, confProvider *config.Provider) { + listCmd := &cobra.Command{ + Use: "list [store]", + Short: "List config stores or keys", + Long: `Without a store argument, lists all config stores from the blueprint. +With a store argument, lists all keys in that store.`, + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + inTerminal := term.IsTerminal(int(os.Stdout.Fd())) + appDir, _ := confProvider.GetString("configAppDir") + + if len(args) == 0 { + return listStores(confProvider, appDir, inTerminal) + } + return listKeys(cmd, confProvider, args[0], appDir, inTerminal) + }, + } + + listCmd.Flags().Bool("show-secrets", false, + "Reveal masked values.") + confProvider.BindPFlag("configListShowSecrets", listCmd.Flags().Lookup("show-secrets")) + confProvider.BindEnvVar("configListShowSecrets", "CELERITY_CLI_CONFIG_LIST_SHOW_SECRETS") + + configCmd.AddCommand(listCmd) +} + +func listStores( + confProvider *config.Provider, + appDir string, + inTerminal bool, +) error { + bpFile, bpIsDefault := confProvider.GetString("configBlueprintFile") + if bpIsDefault || bpFile == "" { + bpFile = appDir + "/app.blueprint.yaml" + } + + bp, _, err := blueprint.LoadForDev(bpFile) + if err != nil { + return err + } + + stores := appconfig.CollectStoreInfo(bp) + headless := !inTerminal + + if headless { + output := configui.NewConfigOutput(os.Stdout, false) + output.PrintStoreList(stores) + return nil + } + + celerityStyles := styles.NewStyles(lipgloss.NewRenderer(os.Stdout), styles.NewCelerityPalette()) + app := configui.NewListModel(configui.ListModelOptions{ + Stores: stores, + Styles: celerityStyles, + Headless: false, + HeadlessWriter: os.Stdout, + }) + + options := []tea.ProgramOption{ + tea.WithAltScreen(), + tea.WithMouseCellMotion(), + } + _, err = tea.NewProgram(app, options...).Run() + return err +} + +func listKeys( + cmd *cobra.Command, + confProvider *config.Provider, + storeName string, + appDir string, + inTerminal bool, +) error { + envInfo, err := resolveEnv(confProvider, appDir, inTerminal) + if err != nil { + return err + } + + store, _, err := resolveConfigStore( + cmd.Context(), envInfo, storeName, confProvider, + ) + if err != nil { + return err + } + + entries, err := store.List(cmd.Context()) + if err != nil { + return err + } + + showSecrets, _ := confProvider.GetBool("configListShowSecrets") + output := configui.NewConfigOutput(os.Stdout, inTerminal) + output.PrintEntryTable(entries, showSecrets) + return nil +} diff --git a/apps/cli/cmd/commands/config_set.go b/apps/cli/cmd/commands/config_set.go new file mode 100644 index 00000000..ea44b3bf --- /dev/null +++ b/apps/cli/cmd/commands/config_set.go @@ -0,0 +1,100 @@ +package commands + +import ( + "bufio" + "fmt" + "os" + "strings" + "syscall" + + "github.com/newstack-cloud/celerity/apps/cli/internal/tui/configui" + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/spf13/cobra" + "golang.org/x/term" +) + +func setupConfigSetCommand(configCmd *cobra.Command, confProvider *config.Provider) { + setCmd := &cobra.Command{ + Use: "set [value]", + Short: "Set a config value", + Long: `Set a config value in a deployed store. + +If value is omitted and the key is sensitive, you will be prompted for +masked input in interactive mode, or the value is read from stdin in +headless mode.`, + Args: cobra.RangeArgs(2, 3), + RunE: func(cmd *cobra.Command, args []string) error { + storeName, key := args[0], args[1] + inTerminal := term.IsTerminal(int(os.Stdout.Fd())) + appDir, _ := confProvider.GetString("configAppDir") + output := configui.NewConfigOutput(os.Stdout, inTerminal) + + envInfo, err := resolveEnv(confProvider, appDir, inTerminal) + if err != nil { + return err + } + + store, storeInfo, err := resolveConfigStore( + cmd.Context(), envInfo, storeName, confProvider, + ) + if err != nil { + return err + } + + secretFlag, _ := confProvider.GetBool("configSetSecret") + sensitive := secretFlag || !storeInfo.PlaintextKeys[key] + + value, err := resolveValue(args, sensitive, inTerminal) + if err != nil { + return err + } + + if err := store.Set(cmd.Context(), key, value, sensitive); err != nil { + return err + } + + output.PrintSuccess(fmt.Sprintf( + "Set key %q in store %q", key, storeInfo.StoreName, + )) + return nil + }, + } + + setCmd.Flags().BoolP("secret", "s", false, + "Mark value as sensitive (SecureString in Parameter Store).") + confProvider.BindPFlag("configSetSecret", setCmd.Flags().Lookup("secret")) + confProvider.BindEnvVar("configSetSecret", "CELERITY_CLI_CONFIG_SET_SECRET") + + configCmd.AddCommand(setCmd) +} + +func resolveValue( + args []string, + sensitive bool, + inTerminal bool, +) (string, error) { + if len(args) >= 3 { + return args[2], nil + } + + if !sensitive { + return "", fmt.Errorf("value argument is required for non-sensitive keys") + } + + if inTerminal { + fmt.Fprint(os.Stderr, "Enter secret value: ") + bytes, err := term.ReadPassword(int(syscall.Stdin)) + fmt.Fprintln(os.Stderr) + if err != nil { + return "", fmt.Errorf("reading secret input: %w", err) + } + return string(bytes), nil + } + + reader := bufio.NewReader(os.Stdin) + value, err := reader.ReadString('\n') + if err != nil { + return "", fmt.Errorf("reading value from stdin: %w", err) + } + return strings.TrimRight(value, "\n\r"), nil +} diff --git a/apps/cli/internal/appconfig/aws.go b/apps/cli/internal/appconfig/aws.go new file mode 100644 index 00000000..07e08a73 --- /dev/null +++ b/apps/cli/internal/appconfig/aws.go @@ -0,0 +1,47 @@ +package appconfig + +import ( + "context" + "fmt" + + awsconfig "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/secretsmanager" + "github.com/aws/aws-sdk-go-v2/service/ssm" +) + +func newAWSConfigStore( + ctx context.Context, + info StoreInfo, + opts ProviderOpts, +) (ConfigStore, error) { + cfgOpts := []func(*awsconfig.LoadOptions) error{} + if opts.Region != "" { + cfgOpts = append(cfgOpts, awsconfig.WithRegion(opts.Region)) + } + if opts.Profile != "" { + cfgOpts = append(cfgOpts, awsconfig.WithSharedConfigProfile(opts.Profile)) + } + + cfg, err := awsconfig.LoadDefaultConfig(ctx, cfgOpts...) + if err != nil { + return nil, fmt.Errorf("loading AWS config: %w", err) + } + + switch info.StoreKind { + case StoreKindSecretsManager: + return &secretsManagerStore{ + client: secretsmanager.NewFromConfig(cfg), + secretID: info.StoreName, + logger: opts.Logger, + }, nil + case StoreKindParameterStore: + return ¶meterStoreStore{ + client: ssm.NewFromConfig(cfg), + pathPrefix: "/" + info.StoreName + "/", + plaintextKeys: info.PlaintextKeys, + logger: opts.Logger, + }, nil + default: + return nil, fmt.Errorf("unsupported store kind %q", info.StoreKind) + } +} diff --git a/apps/cli/internal/appconfig/aws_parameter_store.go b/apps/cli/internal/appconfig/aws_parameter_store.go new file mode 100644 index 00000000..66618b20 --- /dev/null +++ b/apps/cli/internal/appconfig/aws_parameter_store.go @@ -0,0 +1,141 @@ +package appconfig + +import ( + "context" + "fmt" + "strings" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ssm" + ssmtypes "github.com/aws/aws-sdk-go-v2/service/ssm/types" + "go.uber.org/zap" +) + +// ssmAPI is the subset of the SSM client used by this store. +type ssmAPI interface { + GetParameter( + ctx context.Context, + params *ssm.GetParameterInput, + optFns ...func(*ssm.Options), + ) (*ssm.GetParameterOutput, error) + PutParameter( + ctx context.Context, + params *ssm.PutParameterInput, + optFns ...func(*ssm.Options), + ) (*ssm.PutParameterOutput, error) + DeleteParameter( + ctx context.Context, + params *ssm.DeleteParameterInput, + optFns ...func(*ssm.Options), + ) (*ssm.DeleteParameterOutput, error) + GetParametersByPath( + ctx context.Context, + params *ssm.GetParametersByPathInput, + optFns ...func(*ssm.Options), + ) (*ssm.GetParametersByPathOutput, error) +} + +type parameterStoreStore struct { + client ssmAPI + pathPrefix string + plaintextKeys map[string]bool + logger *zap.Logger +} + +func (p *parameterStoreStore) Get(ctx context.Context, key string) (*ConfigEntry, error) { + paramName := p.pathPrefix + key + + out, err := p.client.GetParameter(ctx, &ssm.GetParameterInput{ + Name: aws.String(paramName), + WithDecryption: aws.Bool(true), + }) + if err != nil { + return nil, fmt.Errorf("getting parameter %q: %w", paramName, err) + } + + return &ConfigEntry{ + Key: key, + Value: aws.ToString(out.Parameter.Value), + Sensitive: out.Parameter.Type == ssmtypes.ParameterTypeSecureString, + }, nil +} + +func (p *parameterStoreStore) Set( + ctx context.Context, + key, value string, + sensitive bool, +) error { + paramName := p.pathPrefix + key + paramType := ssmtypes.ParameterTypeSecureString + if p.plaintextKeys[key] && !sensitive { + paramType = ssmtypes.ParameterTypeString + } + + _, err := p.client.PutParameter(ctx, &ssm.PutParameterInput{ + Name: aws.String(paramName), + Value: aws.String(value), + Type: paramType, + Overwrite: aws.Bool(true), + }) + if err != nil { + return fmt.Errorf("setting parameter %q: %w", paramName, err) + } + return nil +} + +func (p *parameterStoreStore) Delete(ctx context.Context, key string) error { + paramName := p.pathPrefix + key + + _, err := p.client.DeleteParameter(ctx, &ssm.DeleteParameterInput{ + Name: aws.String(paramName), + }) + if err != nil { + return fmt.Errorf("deleting parameter %q: %w", paramName, err) + } + return nil +} + +func (p *parameterStoreStore) List(ctx context.Context) ([]ConfigEntry, error) { + var entries []ConfigEntry + var nextToken *string + + for { + out, err := p.client.GetParametersByPath(ctx, &ssm.GetParametersByPathInput{ + Path: aws.String(p.pathPrefix), + Recursive: aws.Bool(true), + WithDecryption: aws.Bool(true), + NextToken: nextToken, + }) + if err != nil { + return nil, fmt.Errorf("listing parameters under %q: %w", p.pathPrefix, err) + } + + for _, param := range out.Parameters { + key := strings.TrimPrefix(aws.ToString(param.Name), p.pathPrefix) + entries = append(entries, ConfigEntry{ + Key: key, + Value: aws.ToString(param.Value), + Sensitive: param.Type == ssmtypes.ParameterTypeSecureString, + }) + } + + if out.NextToken == nil { + break + } + nextToken = out.NextToken + } + + return entries, nil +} + +func (p *parameterStoreStore) Import( + ctx context.Context, + entries []ConfigEntry, +) error { + for _, e := range entries { + if err := p.Set(ctx, e.Key, e.Value, e.Sensitive); err != nil { + return err + } + } + return nil +} diff --git a/apps/cli/internal/appconfig/aws_parameter_store_test.go b/apps/cli/internal/appconfig/aws_parameter_store_test.go new file mode 100644 index 00000000..c7d5f6f0 --- /dev/null +++ b/apps/cli/internal/appconfig/aws_parameter_store_test.go @@ -0,0 +1,251 @@ +package appconfig + +import ( + "context" + "fmt" + "strings" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/ssm" + ssmtypes "github.com/aws/aws-sdk-go-v2/service/ssm/types" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +type ParameterStoreSuite struct { + suite.Suite +} + +func TestParameterStoreSuite(t *testing.T) { + suite.Run(t, new(ParameterStoreSuite)) +} + +func (s *ParameterStoreSuite) newStore(mock *mockSSMClient) *parameterStoreStore { + return ¶meterStoreStore{ + client: mock, + pathPrefix: "/staging-my-store/", + plaintextKeys: map[string]bool{ + "TIMEOUT": true, + "LOG_LEVEL": true, + }, + logger: zap.NewNop(), + } +} + +func (s *ParameterStoreSuite) Test_get_string_parameter() { + mock := &mockSSMClient{ + params: map[string]ssmtypes.Parameter{ + "/staging-my-store/TIMEOUT": { + Name: aws.String("/staging-my-store/TIMEOUT"), + Value: aws.String("5000"), + Type: ssmtypes.ParameterTypeString, + }, + }, + } + store := s.newStore(mock) + + entry, err := store.Get(context.Background(), "TIMEOUT") + s.Require().NoError(err) + s.Equal("TIMEOUT", entry.Key) + s.Equal("5000", entry.Value) + s.False(entry.Sensitive) +} + +func (s *ParameterStoreSuite) Test_get_secure_string_parameter() { + mock := &mockSSMClient{ + params: map[string]ssmtypes.Parameter{ + "/staging-my-store/API_KEY": { + Name: aws.String("/staging-my-store/API_KEY"), + Value: aws.String("secret123"), + Type: ssmtypes.ParameterTypeSecureString, + }, + }, + } + store := s.newStore(mock) + + entry, err := store.Get(context.Background(), "API_KEY") + s.Require().NoError(err) + s.True(entry.Sensitive) +} + +func (s *ParameterStoreSuite) Test_get_string_not_in_plaintext_list_is_not_sensitive() { + mock := &mockSSMClient{ + params: map[string]ssmtypes.Parameter{ + "/staging-my-store/CUSTOM_FLAG": { + Name: aws.String("/staging-my-store/CUSTOM_FLAG"), + Value: aws.String("enabled"), + Type: ssmtypes.ParameterTypeString, + }, + }, + } + store := s.newStore(mock) + + // CUSTOM_FLAG is not in the plaintext list but is stored as String + entry, err := store.Get(context.Background(), "CUSTOM_FLAG") + s.Require().NoError(err) + s.False(entry.Sensitive) +} + +func (s *ParameterStoreSuite) Test_set_plaintext_uses_string_type() { + mock := &mockSSMClient{params: map[string]ssmtypes.Parameter{}} + store := s.newStore(mock) + + err := store.Set(context.Background(), "TIMEOUT", "3000", false) + s.Require().NoError(err) + s.Equal(ssmtypes.ParameterTypeString, mock.lastPutType) +} + +func (s *ParameterStoreSuite) Test_set_sensitive_uses_secure_string_type() { + mock := &mockSSMClient{params: map[string]ssmtypes.Parameter{}} + store := s.newStore(mock) + + err := store.Set(context.Background(), "API_KEY", "secret", true) + s.Require().NoError(err) + s.Equal(ssmtypes.ParameterTypeSecureString, mock.lastPutType) +} + +func (s *ParameterStoreSuite) Test_set_plaintext_key_with_secret_flag_uses_secure_string() { + mock := &mockSSMClient{params: map[string]ssmtypes.Parameter{}} + store := s.newStore(mock) + + // Even though TIMEOUT is in plaintext list, --secret flag forces SecureString + err := store.Set(context.Background(), "TIMEOUT", "val", true) + s.Require().NoError(err) + s.Equal(ssmtypes.ParameterTypeSecureString, mock.lastPutType) +} + +func (s *ParameterStoreSuite) Test_delete_parameter() { + mock := &mockSSMClient{params: map[string]ssmtypes.Parameter{}} + store := s.newStore(mock) + + err := store.Delete(context.Background(), "OLD_KEY") + s.Require().NoError(err) + s.Equal("/staging-my-store/OLD_KEY", mock.lastDeleteName) +} + +func (s *ParameterStoreSuite) Test_list_parameters_uses_backend_type() { + mock := &mockSSMClient{ + pathParams: []ssmtypes.Parameter{ + {Name: aws.String("/staging-my-store/TIMEOUT"), Value: aws.String("5000"), Type: ssmtypes.ParameterTypeString}, + {Name: aws.String("/staging-my-store/API_KEY"), Value: aws.String("secret"), Type: ssmtypes.ParameterTypeSecureString}, + {Name: aws.String("/staging-my-store/LOG_LEVEL"), Value: aws.String("info"), Type: ssmtypes.ParameterTypeString}, + {Name: aws.String("/staging-my-store/CUSTOM"), Value: aws.String("val"), Type: ssmtypes.ParameterTypeString}, + }, + } + store := s.newStore(mock) + + entries, err := store.List(context.Background()) + s.Require().NoError(err) + s.Len(entries, 4) + + keyMap := map[string]ConfigEntry{} + for _, e := range entries { + keyMap[e.Key] = e + } + s.False(keyMap["TIMEOUT"].Sensitive) + s.True(keyMap["API_KEY"].Sensitive) + s.False(keyMap["LOG_LEVEL"].Sensitive) + // CUSTOM is not in the plaintext list but is stored as String, so it must + // not come back as sensitive. + s.False(keyMap["CUSTOM"].Sensitive) +} + +func (s *ParameterStoreSuite) Test_import_sets_each_entry() { + mock := &mockSSMClient{params: map[string]ssmtypes.Parameter{}} + store := s.newStore(mock) + + err := store.Import(context.Background(), []ConfigEntry{ + {Key: "TIMEOUT", Value: "3000", Sensitive: false}, + {Key: "API_KEY", Value: "secret", Sensitive: true}, + }) + s.Require().NoError(err) + s.Equal(2, mock.putCount) +} + +func (s *ParameterStoreSuite) Test_get_error_from_aws() { + mock := &mockSSMClient{getErr: errMockAWS} + store := s.newStore(mock) + + _, err := store.Get(context.Background(), "KEY") + s.Error(err) + s.Contains(err.Error(), "getting parameter") +} + +// mockSSMClient implements ssmAPI for testing. +type mockSSMClient struct { + params map[string]ssmtypes.Parameter + pathParams []ssmtypes.Parameter + getErr error + putErr error + deleteErr error + listErr error + lastPutType ssmtypes.ParameterType + lastDeleteName string + putCount int +} + +func (m *mockSSMClient) GetParameter( + ctx context.Context, + params *ssm.GetParameterInput, + optFns ...func(*ssm.Options), +) (*ssm.GetParameterOutput, error) { + if m.getErr != nil { + return nil, m.getErr + } + name := aws.ToString(params.Name) + p, ok := m.params[name] + if !ok { + return nil, fmt.Errorf("parameter %q not found", name) + } + return &ssm.GetParameterOutput{Parameter: &p}, nil +} + +func (m *mockSSMClient) PutParameter( + ctx context.Context, + params *ssm.PutParameterInput, + optFns ...func(*ssm.Options), +) (*ssm.PutParameterOutput, error) { + if m.putErr != nil { + return nil, m.putErr + } + m.lastPutType = params.Type + m.putCount++ + name := aws.ToString(params.Name) + m.params[name] = ssmtypes.Parameter{ + Name: params.Name, + Value: params.Value, + } + return &ssm.PutParameterOutput{}, nil +} + +func (m *mockSSMClient) DeleteParameter( + ctx context.Context, + params *ssm.DeleteParameterInput, + optFns ...func(*ssm.Options), +) (*ssm.DeleteParameterOutput, error) { + if m.deleteErr != nil { + return nil, m.deleteErr + } + m.lastDeleteName = aws.ToString(params.Name) + return &ssm.DeleteParameterOutput{}, nil +} + +func (m *mockSSMClient) GetParametersByPath( + ctx context.Context, + params *ssm.GetParametersByPathInput, + optFns ...func(*ssm.Options), +) (*ssm.GetParametersByPathOutput, error) { + if m.listErr != nil { + return nil, m.listErr + } + + prefix := aws.ToString(params.Path) + var filtered []ssmtypes.Parameter + for _, p := range m.pathParams { + if strings.HasPrefix(aws.ToString(p.Name), prefix) { + filtered = append(filtered, p) + } + } + return &ssm.GetParametersByPathOutput{Parameters: filtered}, nil +} diff --git a/apps/cli/internal/appconfig/aws_secrets_manager.go b/apps/cli/internal/appconfig/aws_secrets_manager.go new file mode 100644 index 00000000..a989945d --- /dev/null +++ b/apps/cli/internal/appconfig/aws_secrets_manager.go @@ -0,0 +1,152 @@ +package appconfig + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/secretsmanager" + "go.uber.org/zap" +) + +// secretsManagerAPI is the subset of the Secrets Manager client used by this store. +type secretsManagerAPI interface { + GetSecretValue( + ctx context.Context, + params *secretsmanager.GetSecretValueInput, + optFns ...func(*secretsmanager.Options), + ) (*secretsmanager.GetSecretValueOutput, error) + PutSecretValue( + ctx context.Context, + params *secretsmanager.PutSecretValueInput, + optFns ...func(*secretsmanager.Options), + ) (*secretsmanager.PutSecretValueOutput, error) +} + +type secretsManagerStore struct { + client secretsManagerAPI + secretID string + logger *zap.Logger +} + +func (s *secretsManagerStore) Get(ctx context.Context, key string) (*ConfigEntry, error) { + data, err := s.readSecret(ctx) + if err != nil { + return nil, err + } + + value, ok := data[key] + if !ok { + return nil, fmt.Errorf("key %q not found in store %q", key, s.secretID) + } + + return &ConfigEntry{ + Key: key, + Value: value, + Sensitive: true, + }, nil +} + +func (s *secretsManagerStore) Set( + ctx context.Context, + key, value string, + sensitive bool, +) error { + data, err := s.readSecret(ctx) + if err != nil { + return err + } + + data[key] = value + return s.writeSecret(ctx, data) +} + +func (s *secretsManagerStore) Delete(ctx context.Context, key string) error { + data, err := s.readSecret(ctx) + if err != nil { + return err + } + + if _, ok := data[key]; !ok { + return fmt.Errorf("key %q not found in store %q", key, s.secretID) + } + + delete(data, key) + return s.writeSecret(ctx, data) +} + +func (s *secretsManagerStore) List(ctx context.Context) ([]ConfigEntry, error) { + data, err := s.readSecret(ctx) + if err != nil { + return nil, err + } + + entries := make([]ConfigEntry, 0, len(data)) + for k, v := range data { + entries = append(entries, ConfigEntry{ + Key: k, + Value: v, + Sensitive: true, + }) + } + return entries, nil +} + +func (s *secretsManagerStore) Import( + ctx context.Context, + entries []ConfigEntry, +) error { + data, err := s.readSecret(ctx) + if err != nil { + return err + } + + for _, e := range entries { + data[e.Key] = e.Value + } + return s.writeSecret(ctx, data) +} + +func (s *secretsManagerStore) readSecret( + ctx context.Context, +) (map[string]string, error) { + out, err := s.client.GetSecretValue(ctx, &secretsmanager.GetSecretValueInput{ + SecretId: aws.String(s.secretID), + }) + if err != nil { + return nil, fmt.Errorf( + "reading store %q. Deploy your application first if the store does not exist: %w", + s.secretID, err, + ) + } + + if out.SecretString == nil { + return map[string]string{}, nil + } + + var data map[string]string + if err := json.Unmarshal([]byte(*out.SecretString), &data); err != nil { + return nil, fmt.Errorf("parsing secret JSON for store %q: %w", s.secretID, err) + } + return data, nil +} + +func (s *secretsManagerStore) writeSecret( + ctx context.Context, + data map[string]string, +) error { + encoded, err := json.Marshal(data) + if err != nil { + return fmt.Errorf("encoding secret JSON for store %q: %w", s.secretID, err) + } + + _, err = s.client.PutSecretValue(ctx, &secretsmanager.PutSecretValueInput{ + SecretId: aws.String(s.secretID), + SecretString: aws.String(string(encoded)), + }) + if err != nil { + return fmt.Errorf("writing store %q: %w", s.secretID, err) + } + return nil +} diff --git a/apps/cli/internal/appconfig/aws_secrets_manager_test.go b/apps/cli/internal/appconfig/aws_secrets_manager_test.go new file mode 100644 index 00000000..85a81512 --- /dev/null +++ b/apps/cli/internal/appconfig/aws_secrets_manager_test.go @@ -0,0 +1,197 @@ +package appconfig + +import ( + "context" + "encoding/json" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/secretsmanager" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +type SecretsManagerSuite struct { + suite.Suite +} + +func TestSecretsManagerSuite(t *testing.T) { + suite.Run(t, new(SecretsManagerSuite)) +} + +func (s *SecretsManagerSuite) newStore(mock *mockSecretsManagerClient) *secretsManagerStore { + return &secretsManagerStore{ + client: mock, + secretID: "staging-my-store", + logger: zap.NewNop(), + } +} + +func (s *SecretsManagerSuite) Test_get_existing_key() { + mock := &mockSecretsManagerClient{ + secretJSON: `{"DB_HOST":"localhost","DB_PASS":"secret"}`, + } + store := s.newStore(mock) + + entry, err := store.Get(context.Background(), "DB_HOST") + s.Require().NoError(err) + s.Equal("DB_HOST", entry.Key) + s.Equal("localhost", entry.Value) + s.True(entry.Sensitive) +} + +func (s *SecretsManagerSuite) Test_get_missing_key() { + mock := &mockSecretsManagerClient{ + secretJSON: `{"DB_HOST":"localhost"}`, + } + store := s.newStore(mock) + + _, err := store.Get(context.Background(), "MISSING") + s.Error(err) + s.Contains(err.Error(), "not found") +} + +func (s *SecretsManagerSuite) Test_set_adds_key_to_existing() { + mock := &mockSecretsManagerClient{ + secretJSON: `{"EXISTING":"val"}`, + } + store := s.newStore(mock) + + err := store.Set(context.Background(), "NEW_KEY", "new_val", true) + s.Require().NoError(err) + s.Require().NotNil(mock.lastPutValue) + + var data map[string]string + s.Require().NoError(json.Unmarshal([]byte(*mock.lastPutValue), &data)) + s.Equal("val", data["EXISTING"]) + s.Equal("new_val", data["NEW_KEY"]) +} + +func (s *SecretsManagerSuite) Test_set_overwrites_existing_key() { + mock := &mockSecretsManagerClient{ + secretJSON: `{"KEY":"old"}`, + } + store := s.newStore(mock) + + err := store.Set(context.Background(), "KEY", "new", false) + s.Require().NoError(err) + + var data map[string]string + s.Require().NoError(json.Unmarshal([]byte(*mock.lastPutValue), &data)) + s.Equal("new", data["KEY"]) +} + +func (s *SecretsManagerSuite) Test_delete_removes_key() { + mock := &mockSecretsManagerClient{ + secretJSON: `{"KEEP":"a","REMOVE":"b"}`, + } + store := s.newStore(mock) + + err := store.Delete(context.Background(), "REMOVE") + s.Require().NoError(err) + + var data map[string]string + s.Require().NoError(json.Unmarshal([]byte(*mock.lastPutValue), &data)) + s.Equal("a", data["KEEP"]) + _, exists := data["REMOVE"] + s.False(exists) +} + +func (s *SecretsManagerSuite) Test_delete_missing_key_returns_error() { + mock := &mockSecretsManagerClient{ + secretJSON: `{"KEY":"val"}`, + } + store := s.newStore(mock) + + err := store.Delete(context.Background(), "MISSING") + s.Error(err) + s.Contains(err.Error(), "not found") +} + +func (s *SecretsManagerSuite) Test_list_returns_all_entries() { + mock := &mockSecretsManagerClient{ + secretJSON: `{"A":"1","B":"2","C":"3"}`, + } + store := s.newStore(mock) + + entries, err := store.List(context.Background()) + s.Require().NoError(err) + s.Len(entries, 3) + + keyMap := map[string]string{} + for _, e := range entries { + keyMap[e.Key] = e.Value + s.True(e.Sensitive) + } + s.Equal("1", keyMap["A"]) + s.Equal("2", keyMap["B"]) + s.Equal("3", keyMap["C"]) +} + +func (s *SecretsManagerSuite) Test_import_merges_entries() { + mock := &mockSecretsManagerClient{ + secretJSON: `{"EXISTING":"old"}`, + } + store := s.newStore(mock) + + err := store.Import(context.Background(), []ConfigEntry{ + {Key: "NEW1", Value: "v1"}, + {Key: "NEW2", Value: "v2"}, + {Key: "EXISTING", Value: "updated"}, + }) + s.Require().NoError(err) + + var data map[string]string + s.Require().NoError(json.Unmarshal([]byte(*mock.lastPutValue), &data)) + s.Equal("updated", data["EXISTING"]) + s.Equal("v1", data["NEW1"]) + s.Equal("v2", data["NEW2"]) +} + +func (s *SecretsManagerSuite) Test_get_error_from_aws() { + mock := &mockSecretsManagerClient{ + getErr: errMockAWS, + } + store := s.newStore(mock) + + _, err := store.Get(context.Background(), "KEY") + s.Error(err) + s.Contains(err.Error(), "reading store") +} + +// mockSecretsManagerClient implements secretsManagerAPI for testing. +type mockSecretsManagerClient struct { + secretJSON string + getErr error + putErr error + lastPutValue *string +} + +func (m *mockSecretsManagerClient) GetSecretValue( + ctx context.Context, + params *secretsmanager.GetSecretValueInput, + optFns ...func(*secretsmanager.Options), +) (*secretsmanager.GetSecretValueOutput, error) { + if m.getErr != nil { + return nil, m.getErr + } + return &secretsmanager.GetSecretValueOutput{ + SecretString: aws.String(m.secretJSON), + }, nil +} + +func (m *mockSecretsManagerClient) PutSecretValue( + ctx context.Context, + params *secretsmanager.PutSecretValueInput, + optFns ...func(*secretsmanager.Options), +) (*secretsmanager.PutSecretValueOutput, error) { + if m.putErr != nil { + return nil, m.putErr + } + m.lastPutValue = params.SecretString + // Update stored JSON so subsequent reads reflect the write + if params.SecretString != nil { + m.secretJSON = *params.SecretString + } + return &secretsmanager.PutSecretValueOutput{}, nil +} diff --git a/apps/cli/internal/appconfig/blueprint.go b/apps/cli/internal/appconfig/blueprint.go new file mode 100644 index 00000000..b8e48bf4 --- /dev/null +++ b/apps/cli/internal/appconfig/blueprint.go @@ -0,0 +1,100 @@ +package appconfig + +import ( + "github.com/newstack-cloud/bluelink/libs/blueprint/core" + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" +) + +const resourceTypeConfig = "celerity/config" + +// CollectStoreInfo extracts StoreInfo from celerity/config resources in the blueprint. +// Determines StoreKind based on the presence of the plaintext field. +func CollectStoreInfo(bp *schema.Blueprint) []StoreInfo { + if bp.Resources == nil { + return nil + } + + var stores []StoreInfo + for name, resource := range bp.Resources.Values { + if resource.Type == nil || resource.Type.Value != resourceTypeConfig { + continue + } + + storeName := extractSpecStringField(resource, "name") + if storeName == "" { + storeName = name + } + + plaintextKeys := extractSpecStringArray(resource, "plaintext") + storeKind := StoreKindSecretsManager + if len(plaintextKeys) > 0 { + storeKind = StoreKindParameterStore + } + + keyMap := make(map[string]bool, len(plaintextKeys)) + for _, k := range plaintextKeys { + keyMap[k] = true + } + + stores = append(stores, StoreInfo{ + ResourceName: name, + StoreName: storeName, + StoreKind: storeKind, + PlaintextKeys: keyMap, + }) + } + + return stores +} + +// FindStoreInfo looks up a store by spec.name first, then by resource name. +func FindStoreInfo(stores []StoreInfo, name string) *StoreInfo { + for i := range stores { + if stores[i].StoreName == name { + return &stores[i] + } + } + for i := range stores { + if stores[i].ResourceName == name { + return &stores[i] + } + } + return nil +} + +func extractSpecStringField(resource *schema.Resource, field string) string { + if resource.Spec == nil || resource.Spec.Fields == nil { + return "" + } + return extractScalarString(resource.Spec.Fields[field]) +} + +func extractSpecStringArray(resource *schema.Resource, field string) []string { + if resource.Spec == nil || resource.Spec.Fields == nil { + return nil + } + + node := resource.Spec.Fields[field] + if node == nil || node.Items == nil { + return nil + } + + var result []string + for _, item := range node.Items { + s := extractScalarString(item) + if s != "" { + result = append(result, s) + } + } + return result +} + +func extractScalarString(node *core.MappingNode) string { + if node == nil || node.Scalar == nil { + return "" + } + if node.Scalar.StringValue != nil { + return *node.Scalar.StringValue + } + return node.Scalar.ToString() +} diff --git a/apps/cli/internal/appconfig/blueprint_test.go b/apps/cli/internal/appconfig/blueprint_test.go new file mode 100644 index 00000000..e6cade5e --- /dev/null +++ b/apps/cli/internal/appconfig/blueprint_test.go @@ -0,0 +1,157 @@ +package appconfig + +import ( + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/stretchr/testify/suite" +) + +type BlueprintTestSuite struct { + suite.Suite +} + +func TestBlueprintTestSuite(t *testing.T) { + suite.Run(t, new(BlueprintTestSuite)) +} + +func (s *BlueprintTestSuite) loadBlueprint(yamlContent string) *schema.Blueprint { + bp, err := schema.LoadString(yamlContent, schema.YAMLSpecFormat) + s.Require().NoError(err, "failed to load test blueprint") + return bp +} + +func (s *BlueprintTestSuite) Test_collect_store_info_secrets_manager() { + bp := s.loadBlueprint(` +version: 2025-11-02 +resources: + appSecrets: + type: "celerity/config" + spec: + name: my-app-secrets +`) + stores := CollectStoreInfo(bp) + s.Require().Len(stores, 1) + s.Equal("appSecrets", stores[0].ResourceName) + s.Equal("my-app-secrets", stores[0].StoreName) + s.Equal(StoreKindSecretsManager, stores[0].StoreKind) + s.Empty(stores[0].PlaintextKeys) +} + +func (s *BlueprintTestSuite) Test_collect_store_info_parameter_store_with_plaintext() { + bp := s.loadBlueprint(` +version: 2025-11-02 +resources: + appConfig: + type: "celerity/config" + spec: + name: my-app-config + plaintext: + - FETCH_TIMEOUT + - LOG_LEVEL + - POOL_MAX +`) + stores := CollectStoreInfo(bp) + s.Require().Len(stores, 1) + s.Equal("appConfig", stores[0].ResourceName) + s.Equal("my-app-config", stores[0].StoreName) + s.Equal(StoreKindParameterStore, stores[0].StoreKind) + s.Len(stores[0].PlaintextKeys, 3) + s.True(stores[0].PlaintextKeys["FETCH_TIMEOUT"]) + s.True(stores[0].PlaintextKeys["LOG_LEVEL"]) + s.True(stores[0].PlaintextKeys["POOL_MAX"]) +} + +func (s *BlueprintTestSuite) Test_collect_store_info_defaults_name_to_resource_name() { + bp := s.loadBlueprint(` +version: 2025-11-02 +resources: + myConfig: + type: "celerity/config" + spec: {} +`) + stores := CollectStoreInfo(bp) + s.Require().Len(stores, 1) + s.Equal("myConfig", stores[0].StoreName) + s.Equal(StoreKindSecretsManager, stores[0].StoreKind) +} + +func (s *BlueprintTestSuite) Test_collect_store_info_multiple_stores() { + bp := s.loadBlueprint(` +version: 2025-11-02 +resources: + appConfig: + type: "celerity/config" + spec: + name: app-config + plaintext: + - TIMEOUT + appSecrets: + type: "celerity/config" + spec: + name: app-secrets + usersTable: + type: "celerity/datastore" + spec: + name: users +`) + stores := CollectStoreInfo(bp) + s.Require().Len(stores, 2) +} + +func (s *BlueprintTestSuite) Test_collect_store_info_nil_resources() { + bp := s.loadBlueprint(` +version: 2025-11-02 +resources: {} +`) + s.Empty(CollectStoreInfo(bp)) +} + +func (s *BlueprintTestSuite) Test_collect_store_info_no_config_resources() { + bp := s.loadBlueprint(` +version: 2025-11-02 +resources: + usersTable: + type: "celerity/datastore" + spec: + name: users +`) + s.Empty(CollectStoreInfo(bp)) +} + +func (s *BlueprintTestSuite) Test_find_store_info_by_spec_name() { + stores := []StoreInfo{ + {ResourceName: "appConfig", StoreName: "my-app-config", StoreKind: StoreKindParameterStore}, + {ResourceName: "appSecrets", StoreName: "my-app-secrets", StoreKind: StoreKindSecretsManager}, + } + found := FindStoreInfo(stores, "my-app-secrets") + s.Require().NotNil(found) + s.Equal("appSecrets", found.ResourceName) +} + +func (s *BlueprintTestSuite) Test_find_store_info_by_resource_name() { + stores := []StoreInfo{ + {ResourceName: "appConfig", StoreName: "my-app-config", StoreKind: StoreKindParameterStore}, + } + found := FindStoreInfo(stores, "appConfig") + s.Require().NotNil(found) + s.Equal("my-app-config", found.StoreName) +} + +func (s *BlueprintTestSuite) Test_find_store_info_spec_name_takes_precedence() { + stores := []StoreInfo{ + {ResourceName: "cfg", StoreName: "cfg", StoreKind: StoreKindSecretsManager}, + } + // "cfg" matches both the spec name and the resource name, and the spec name + // match comes first. + found := FindStoreInfo(stores, "cfg") + s.Require().NotNil(found) + s.Equal("cfg", found.StoreName) +} + +func (s *BlueprintTestSuite) Test_find_store_info_not_found() { + stores := []StoreInfo{ + {ResourceName: "appConfig", StoreName: "my-app-config"}, + } + s.Nil(FindStoreInfo(stores, "nonexistent")) +} diff --git a/apps/cli/internal/appconfig/provider.go b/apps/cli/internal/appconfig/provider.go new file mode 100644 index 00000000..29c1e0c1 --- /dev/null +++ b/apps/cli/internal/appconfig/provider.go @@ -0,0 +1,24 @@ +package appconfig + +import ( + "context" + "fmt" +) + +// NewConfigStore selects the right provider based on deploy target +// and creates a ConfigStore for the given store info. +func NewConfigStore( + ctx context.Context, + deployTarget string, + info StoreInfo, + opts ProviderOpts, +) (ConfigStore, error) { + switch deployTarget { + case "aws", "aws-serverless": + return newAWSConfigStore(ctx, info, opts) + default: + return nil, fmt.Errorf( + "config management not yet supported for deploy target %q", deployTarget, + ) + } +} diff --git a/apps/cli/internal/appconfig/store.go b/apps/cli/internal/appconfig/store.go new file mode 100644 index 00000000..3eefc544 --- /dev/null +++ b/apps/cli/internal/appconfig/store.go @@ -0,0 +1,13 @@ +package appconfig + +import "context" + +// ConfigStore provides CRUD operations for a cloud config/secret store. +// Each cloud provider implements this interface. +type ConfigStore interface { + Get(ctx context.Context, key string) (*ConfigEntry, error) + Set(ctx context.Context, key, value string, sensitive bool) error + Delete(ctx context.Context, key string) error + List(ctx context.Context) ([]ConfigEntry, error) + Import(ctx context.Context, entries []ConfigEntry) error +} diff --git a/apps/cli/internal/appconfig/testhelpers_test.go b/apps/cli/internal/appconfig/testhelpers_test.go new file mode 100644 index 00000000..86819046 --- /dev/null +++ b/apps/cli/internal/appconfig/testhelpers_test.go @@ -0,0 +1,5 @@ +package appconfig + +import "errors" + +var errMockAWS = errors.New("mock AWS error") diff --git a/apps/cli/internal/appconfig/types.go b/apps/cli/internal/appconfig/types.go new file mode 100644 index 00000000..20119ea4 --- /dev/null +++ b/apps/cli/internal/appconfig/types.go @@ -0,0 +1,33 @@ +package appconfig + +import "go.uber.org/zap" + +// StoreKind identifies the cloud provider storage backend for a config store. +type StoreKind string + +const ( + StoreKindSecretsManager StoreKind = "secrets-manager" + StoreKindParameterStore StoreKind = "parameter-store" +) + +// StoreInfo describes a config store extracted from a blueprint's celerity/config resource. +type StoreInfo struct { + ResourceName string + StoreName string + StoreKind StoreKind + PlaintextKeys map[string]bool +} + +// ConfigEntry represents a single config key/value with metadata. +type ConfigEntry struct { + Key string + Value string + Sensitive bool +} + +// ProviderOpts holds provider-specific options for creating a ConfigStore. +type ProviderOpts struct { + Region string + Profile string + Logger *zap.Logger +} diff --git a/apps/cli/internal/devconfig/environments.go b/apps/cli/internal/devconfig/environments.go new file mode 100644 index 00000000..7b009807 --- /dev/null +++ b/apps/cli/internal/devconfig/environments.go @@ -0,0 +1,199 @@ +package devconfig + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "strconv" + "strings" +) + +// EnvironmentInfo describes one deployed environment the CLI can target. +// +// An environment is a deploy config file rather than anything the CLI tracks +// of its own: app.deploy.jsonc is the default one, and app.deploy..jsonc +// adds another. Nothing has to be registered, so adding an environment is +// adding a file. +type EnvironmentInfo struct { + // Name is the environment's name, which is the one in the file name, or + // "default" for the base config. + Name string + // FilePath is the deploy config the environment was read from. + FilePath string + // DeployTarget is deployTarget.name. + DeployTarget string + // AppEnv is deployTarget.appEnv, which the deploy engine prefixes config + // store names with. Falls back to Name where the file does not set one. + AppEnv string + // Region and Profile are the cloud settings worth showing next to an + // environment when choosing between them, pulled from deployTarget.config. + Region string + Profile string +} + +// DeployConfigResult is what a deploy config file says about its environment. +type DeployConfigResult struct { + DeployTarget string + AppEnv string + // Config is deployTarget.config with its values rendered as strings. + Config map[string]string +} + +// defaultEnvName is the environment of the base deploy config, which names no +// environment of its own. +const defaultEnvName = "default" + +// envConfigPrefix and envConfigSuffixes bracket an environment name in a +// per-environment deploy config file name. +const envConfigPrefix = "app.deploy." + +var envConfigSuffixes = []string{".jsonc", ".json"} + +// ReadDeployConfig reads the deploy target settings from a deploy config file. +func ReadDeployConfig(path string) (*DeployConfigResult, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("reading deploy config %s: %w", path, err) + } + + var cfg struct { + DeployTarget struct { + Name string `json:"name"` + AppEnv string `json:"appEnv"` + Config map[string]any `json:"config"` + } `json:"deployTarget"` + } + if err := json.Unmarshal([]byte(stripJSONCComments(string(data))), &cfg); err != nil { + return nil, fmt.Errorf("parsing deploy config %s: %w", path, err) + } + + return &DeployConfigResult{ + DeployTarget: cfg.DeployTarget.Name, + AppEnv: cfg.DeployTarget.AppEnv, + Config: stringValues(cfg.DeployTarget.Config), + }, nil +} + +// FindEnvDeployConfig returns the path of the deploy config for a named +// environment, or an empty string where the environment has no file of its own. +func FindEnvDeployConfig(appDir, envName string) string { + for _, suffix := range envConfigSuffixes { + path := filepath.Join(appDir, envConfigPrefix+envName+suffix) + if _, err := os.Stat(path); err == nil { + return path + } + } + return "" +} + +// DiscoverEnvironments returns every environment the application declares, in +// name order with the base config first. +// +// The base config is listed as "default" rather than left out. It is the one +// an application starts with and often the only one, so an application with no +// per-environment files would otherwise have nothing to choose from. +func DiscoverEnvironments(appDir string) ([]EnvironmentInfo, error) { + entries, err := os.ReadDir(appDir) + if err != nil { + return nil, fmt.Errorf("reading %s: %w", appDir, err) + } + + var envs []EnvironmentInfo + for _, entry := range entries { + if entry.IsDir() { + continue + } + name, ok := environmentNameOf(entry.Name()) + if !ok { + continue + } + info, err := readEnvironment(filepath.Join(appDir, entry.Name()), name) + if err != nil { + // A file that does not parse is reported rather than skipped: it + // is an environment the author meant to have, and silently + // omitting it reads as the environment not existing. + return nil, err + } + envs = append(envs, *info) + } + + sort.Slice(envs, func(i, j int) bool { + // The base config first, then by name, so the list is stable and the + // one an application always has is the one it opens on. + if (envs[i].Name == defaultEnvName) != (envs[j].Name == defaultEnvName) { + return envs[i].Name == defaultEnvName + } + return envs[i].Name < envs[j].Name + }) + return envs, nil +} + +// environmentNameOf reports the environment a deploy config file name belongs +// to. +func environmentNameOf(fileName string) (string, bool) { + for _, suffix := range envConfigSuffixes { + if fileName == "app.deploy"+suffix { + return defaultEnvName, true + } + if strings.HasPrefix(fileName, envConfigPrefix) && strings.HasSuffix(fileName, suffix) { + name := strings.TrimSuffix(strings.TrimPrefix(fileName, envConfigPrefix), suffix) + if name != "" { + return name, true + } + } + } + return "", false +} + +func readEnvironment(path, name string) (*EnvironmentInfo, error) { + result, err := ReadDeployConfig(path) + if err != nil { + return nil, err + } + + appEnv := result.AppEnv + if appEnv == "" { + // The deploy engine prefixes config store names with appEnv, so an + // environment without one would share its stores with every other. + appEnv = name + } + + return &EnvironmentInfo{ + Name: name, + FilePath: path, + DeployTarget: result.DeployTarget, + AppEnv: appEnv, + Region: result.Config["aws.region"], + Profile: result.Config["aws.profile"], + }, nil +} + +// stringValues renders a deploy target's config as strings. +// +// The field is free-form, so a value that is written unquoted in the file +// arrives as a number or a bool. Rendering rather than dropping those keeps a +// region or profile readable whatever it was written as. +func stringValues(config map[string]any) map[string]string { + if len(config) == 0 { + return nil + } + out := make(map[string]string, len(config)) + for key, value := range config { + switch v := value.(type) { + case string: + out[key] = v + case bool: + out[key] = strconv.FormatBool(v) + case float64: + out[key] = strconv.FormatFloat(v, 'f', -1, 64) + case nil: + // Absent rather than the string "null", so a caller's empty check + // means what it looks like. + default: + out[key] = fmt.Sprintf("%v", v) + } + } + return out +} diff --git a/apps/cli/internal/tui/configui/commands.go b/apps/cli/internal/tui/configui/commands.go new file mode 100644 index 00000000..5935aa2b --- /dev/null +++ b/apps/cli/internal/tui/configui/commands.go @@ -0,0 +1,67 @@ +package configui + +import ( + "context" + + tea "github.com/charmbracelet/bubbletea" + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/newstack-cloud/celerity/apps/cli/internal/appconfig" + "github.com/newstack-cloud/celerity/apps/cli/internal/devconfig" +) + +// LoadEnvsCmd discovers available environments from deploy config files. +func LoadEnvsCmd(appDir string) tea.Cmd { + return func() tea.Msg { + envs, err := devconfig.DiscoverEnvironments(appDir) + if err != nil { + return EnvsLoadErrorMsg{Err: err} + } + return EnvsLoadedMsg{Envs: envs} + } +} + +// LoadStoresCmd extracts config stores from a loaded blueprint. +func LoadStoresCmd(bp *schema.Blueprint) tea.Cmd { + return func() tea.Msg { + stores := appconfig.CollectStoreInfo(bp) + return StoresLoadedMsg{Stores: stores} + } +} + +// LoadKeysCmd lists all entries from a config store. +func LoadKeysCmd(ctx context.Context, store appconfig.ConfigStore) tea.Cmd { + return func() tea.Msg { + entries, err := store.List(ctx) + if err != nil { + return KeysLoadErrorMsg{Err: err} + } + return KeysLoadedMsg{Entries: entries} + } +} + +// SetKeyCmd sets a key/value in a config store. +func SetKeyCmd( + ctx context.Context, + store appconfig.ConfigStore, + key, value string, + sensitive bool, +) tea.Cmd { + return func() tea.Msg { + err := store.Set(ctx, key, value, sensitive) + if err != nil { + return OperationErrorMsg{Err: err} + } + return KeySetMsg{Key: key} + } +} + +// DeleteKeyCmd deletes a key from a config store. +func DeleteKeyCmd(ctx context.Context, store appconfig.ConfigStore, key string) tea.Cmd { + return func() tea.Msg { + err := store.Delete(ctx, key) + if err != nil { + return OperationErrorMsg{Err: err} + } + return KeyDeletedMsg{Key: key} + } +} diff --git a/apps/cli/internal/tui/configui/env_select.go b/apps/cli/internal/tui/configui/env_select.go new file mode 100644 index 00000000..6a90462c --- /dev/null +++ b/apps/cli/internal/tui/configui/env_select.go @@ -0,0 +1,134 @@ +package configui + +import ( + "fmt" + "io" + "strings" + + "github.com/charmbracelet/bubbles/list" + tea "github.com/charmbracelet/bubbletea" + "github.com/newstack-cloud/celerity/apps/cli/internal/devconfig" + "github.com/newstack-cloud/celerity/apps/cli/internal/tui/shared" + styles "github.com/newstack-cloud/deploy-cli-sdk/styles" +) + +// EnvSelectModel presents a selectable list of discovered environments. +type EnvSelectModel struct { + list list.Model + styles *styles.Styles + selected bool + choice devconfig.EnvironmentInfo +} + +type envItem struct { + env devconfig.EnvironmentInfo +} + +func (e envItem) FilterValue() string { return e.env.Name } +func (e envItem) Title() string { return e.env.Name } +func (e envItem) Description() string { + parts := []string{e.env.DeployTarget} + if e.env.Region != "" { + parts = append(parts, e.env.Region) + } + return strings.Join(parts, ", ") +} + +// NewEnvSelectModel creates a new environment selection model. +func NewEnvSelectModel( + envs []devconfig.EnvironmentInfo, + s *styles.Styles, +) EnvSelectModel { + items := make([]list.Item, len(envs)) + for i, env := range envs { + items[i] = envItem{env: env} + } + + delegate := list.NewDefaultDelegate() + l := list.New(items, delegate, 60, 14) + l.Title = "Select Environment" + l.SetShowStatusBar(false) + l.SetFilteringEnabled(len(items) > 5) + l.SetShowHelp(false) + l.Styles.Title = s.Title + + return EnvSelectModel{list: l, styles: s} +} + +// Init implements tea.Model. +func (m EnvSelectModel) Init() tea.Cmd { + return nil +} + +// Update implements tea.Model. +func (m EnvSelectModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.list.SetWidth(msg.Width) + m.list.SetHeight(msg.Height - 6) + return m, nil + case tea.KeyMsg: + switch msg.String() { + case "ctrl+c": + return m, tea.Quit + case "q": + // Only while the list is not filtering, where a q is a character + // the developer is typing into the filter rather than a command. + if m.list.FilterState() != list.Filtering { + return m, tea.Quit + } + case "enter": + item, ok := m.list.SelectedItem().(envItem) + if ok { + m.selected = true + m.choice = item.env + return m, func() tea.Msg { + return EnvSelectedMsg{Env: item.env} + } + } + } + } + + var cmd tea.Cmd + m.list, cmd = m.list.Update(msg) + return m, cmd +} + +// View implements tea.Model. +func (m EnvSelectModel) View() string { + if m.selected { + return "" + } + + footer := shared.RenderFooter(m.styles, []shared.KeyHint{ + {Key: "↑/↓", Desc: "navigate"}, + {Key: "enter", Desc: "select"}, + {Key: "q", Desc: "quit"}, + }) + + return "\n" + m.list.View() + "\n" + footer + "\n" +} + +// DispatchHeadlessEnvOutput writes the environment list to a writer. +func DispatchHeadlessEnvOutput( + w io.Writer, + envs []devconfig.EnvironmentInfo, + err error, +) { + if err != nil { + fmt.Fprintf(w, "Error discovering environments: %v\n", err) + return + } + if len(envs) == 0 { + fmt.Fprintln(w, "No environments found.") + return + } + fmt.Fprintln(w, "Available Environments:") + for _, env := range envs { + region := env.Region + if region == "" { + region = "default" + } + fmt.Fprintf(w, " %s (%s, %s)\n", env.Name, env.DeployTarget, region) + } +} diff --git a/apps/cli/internal/tui/configui/env_select_test.go b/apps/cli/internal/tui/configui/env_select_test.go new file mode 100644 index 00000000..b9082d35 --- /dev/null +++ b/apps/cli/internal/tui/configui/env_select_test.go @@ -0,0 +1,99 @@ +package configui + +import ( + "bytes" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/exp/teatest" + "github.com/newstack-cloud/celerity/apps/cli/internal/devconfig" + styles "github.com/newstack-cloud/deploy-cli-sdk/styles" + "github.com/stretchr/testify/suite" +) + +type EnvSelectSuite struct { + suite.Suite + testEnvs []devconfig.EnvironmentInfo +} + +func TestEnvSelectSuite(t *testing.T) { + suite.Run(t, new(EnvSelectSuite)) +} + +func (s *EnvSelectSuite) SetupTest() { + s.testEnvs = []devconfig.EnvironmentInfo{ + { + Name: "staging", + DeployTarget: "aws", + AppEnv: "staging", + Region: "us-east-1", + Profile: "staging-acct", + }, + { + Name: "production", + DeployTarget: "aws", + AppEnv: "production", + Region: "eu-west-1", + Profile: "prod-acct", + }, + } +} + +func (s *EnvSelectSuite) Test_renders_environment_list() { + model := NewEnvSelectModel(s.testEnvs, styles.NewDefaultStyles(styles.NewCelerityPalette())) + + testModel := teatest.NewTestModel( + s.T(), model, + teatest.WithInitialTermSize(120, 40), + ) + + waitForContainsAll(s.T(), testModel.Output(), "staging", "production") + + keyQ(testModel) + testModel.WaitFinished(s.T(), teatest.WithFinalTimeout(5*time.Second)) +} + +func (s *EnvSelectSuite) Test_selecting_env_sets_choice() { + model := NewEnvSelectModel(s.testEnvs, styles.NewDefaultStyles(styles.NewCelerityPalette())) + + testModel := teatest.NewTestModel( + s.T(), model, + teatest.WithInitialTermSize(120, 40), + ) + + waitForContains(s.T(), testModel.Output(), "staging") + + // Selecting the first env (staging) emits EnvSelectedMsg without quitting, + // which the parent model handles, so quit manually here. + keyEnter(testModel) + + // Give time for the selection to be processed + time.Sleep(100 * time.Millisecond) + + // Quit the program + testModel.Send(tea.KeyMsg{Type: tea.KeyCtrlC}) + testModel.WaitFinished(s.T(), teatest.WithFinalTimeout(5*time.Second)) + + finalModel := testModel.FinalModel(s.T()).(EnvSelectModel) + s.True(finalModel.selected) + s.Equal("staging", finalModel.choice.Name) +} + +func (s *EnvSelectSuite) Test_headless_env_output() { + buf := &bytes.Buffer{} + DispatchHeadlessEnvOutput(buf, s.testEnvs, nil) + + output := buf.String() + s.Contains(output, "staging") + s.Contains(output, "production") + s.Contains(output, "us-east-1") + s.Contains(output, "eu-west-1") + s.NotContains(output, "\033[") +} + +func (s *EnvSelectSuite) Test_headless_env_output_empty() { + buf := &bytes.Buffer{} + DispatchHeadlessEnvOutput(buf, nil, nil) + s.Contains(buf.String(), "No environments found") +} diff --git a/apps/cli/internal/tui/configui/key_table.go b/apps/cli/internal/tui/configui/key_table.go new file mode 100644 index 00000000..f4c4bb97 --- /dev/null +++ b/apps/cli/internal/tui/configui/key_table.go @@ -0,0 +1,327 @@ +package configui + +import ( + "context" + "fmt" + "io" + "strings" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + "github.com/newstack-cloud/celerity/apps/cli/internal/appconfig" + "github.com/newstack-cloud/celerity/apps/cli/internal/tui/shared" + styles "github.com/newstack-cloud/deploy-cli-sdk/styles" +) + +type keyTableState uint32 + +const ( + keyTableViewing keyTableState = iota + keyTableAdding + keyTableEditing + keyTableConfirmDelete +) + +// KeyTableModel displays and manages config entries with inline editing. +type KeyTableModel struct { + state keyTableState + ctx context.Context + entries []appconfig.ConfigEntry + store appconfig.ConfigStore + storeName string + styles *styles.Styles + cursor int + showSecrets bool + + keyInput textinput.Model + valueInput textinput.Model + + width int +} + +// Defaults to context.Background() when no context was supplied, which happens +// when the model is constructed directly in tests. +func (m KeyTableModel) reqCtx() context.Context { + if m.ctx != nil { + return m.ctx + } + return context.Background() +} + +// NewKeyTableModel creates a new key table model. +func NewKeyTableModel( + ctx context.Context, + entries []appconfig.ConfigEntry, + store appconfig.ConfigStore, + storeName string, + s *styles.Styles, +) KeyTableModel { + ki := textinput.New() + ki.Placeholder = "key name" + ki.CharLimit = 128 + + vi := textinput.New() + vi.Placeholder = "value" + vi.CharLimit = 4096 + + return KeyTableModel{ + ctx: ctx, + state: keyTableViewing, + entries: entries, + store: store, + storeName: storeName, + styles: s, + keyInput: ki, + valueInput: vi, + } +} + +// Init implements tea.Model. +func (m KeyTableModel) Init() tea.Cmd { + return nil +} + +// Update implements tea.Model. +func (m KeyTableModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch m.state { + case keyTableViewing: + return m.updateViewing(msg) + case keyTableAdding: + return m.updateInputting(msg, true) + case keyTableEditing: + return m.updateInputting(msg, false) + case keyTableConfirmDelete: + return m.updateConfirmDelete(msg) + } + return m, nil +} + +func (m KeyTableModel) updateViewing(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.width = msg.Width + return m, nil + case KeysLoadedMsg: + m.entries = msg.Entries + return m, nil + case tea.KeyMsg: + return m.handleViewingKey(msg) + } + return m, nil +} + +func (m KeyTableModel) handleViewingKey( + msg tea.KeyMsg, +) (tea.Model, tea.Cmd) { + switch msg.String() { + case "ctrl+c", "q": + return m, tea.Quit + case "up", "k": + if m.cursor > 0 { + m.cursor-- + } + case "down", "j": + if m.cursor < len(m.entries)-1 { + m.cursor++ + } + case "s": + m.showSecrets = !m.showSecrets + case "a": + m.state = keyTableAdding + m.keyInput.Reset() + m.valueInput.Reset() + m.keyInput.Focus() + return m, m.keyInput.Cursor.BlinkCmd() + case "e": + if len(m.entries) > 0 { + entry := m.entries[m.cursor] + m.state = keyTableEditing + m.keyInput.SetValue(entry.Key) + m.valueInput.SetValue(entry.Value) + m.valueInput.Focus() + return m, m.valueInput.Cursor.BlinkCmd() + } + case "d": + if len(m.entries) > 0 { + m.state = keyTableConfirmDelete + } + case "b": + return m, func() tea.Msg { return backToStoresMsg{} } + } + return m, nil +} + +type backToStoresMsg struct{} + +func (m KeyTableModel) updateInputting( + msg tea.Msg, + isAdd bool, +) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.KeyMsg: + switch msg.String() { + case "esc": + m.state = keyTableViewing + return m, nil + case "tab": + if m.keyInput.Focused() { + m.keyInput.Blur() + m.valueInput.Focus() + return m, m.valueInput.Cursor.BlinkCmd() + } + case "enter": + key := m.keyInput.Value() + value := m.valueInput.Value() + if key == "" || value == "" { + return m, nil + } + m.state = keyTableViewing + sensitive := !isPlaintext(key, m.entries) + return m, SetKeyCmd(m.reqCtx(), m.store, key, value, sensitive) + } + case KeySetMsg: + return m, LoadKeysCmd(m.reqCtx(), m.store) + } + + var cmd tea.Cmd + if m.keyInput.Focused() { + m.keyInput, cmd = m.keyInput.Update(msg) + } else { + m.valueInput, cmd = m.valueInput.Update(msg) + } + return m, cmd +} + +func (m KeyTableModel) updateConfirmDelete( + msg tea.Msg, +) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.KeyMsg: + switch msg.String() { + case "y", "Y": + key := m.entries[m.cursor].Key + m.state = keyTableViewing + return m, DeleteKeyCmd(m.reqCtx(), m.store, key) + default: + m.state = keyTableViewing + } + case KeyDeletedMsg: + return m, LoadKeysCmd(m.reqCtx(), m.store) + } + return m, nil +} + +// View implements tea.Model. +func (m KeyTableModel) View() string { + var b strings.Builder + + title := m.styles.Title.Render(fmt.Sprintf("Keys in %s", m.storeName)) + b.WriteString("\n" + title + "\n\n") + + if len(m.entries) == 0 { + b.WriteString(m.styles.Muted.Render(" No keys found.") + "\n") + } else { + for i, e := range m.entries { + cursor := " " + if i == m.cursor { + cursor = m.styles.Key.Render("> ") + } + value := e.Value + if e.Sensitive && !m.showSecrets { + value = "********" + } + entryType := "String" + if e.Sensitive { + entryType = "SecureString" + } + b.WriteString(fmt.Sprintf( + "%s%-20s %-20s %s\n", + cursor, e.Key, value, m.styles.Muted.Render(entryType), + )) + } + } + + b.WriteString("\n") + b.WriteString(m.renderFooter()) + b.WriteString("\n") + + return b.String() +} + +func (m KeyTableModel) renderFooter() string { + switch m.state { + case keyTableAdding: + var sb strings.Builder + sb.WriteString(fmt.Sprintf( + " Add key: %s Value: %s\n", + m.keyInput.View(), m.valueInput.View(), + )) + sb.WriteString(shared.RenderFooter(m.styles, []shared.KeyHint{ + {Key: "tab", Desc: "switch field"}, + {Key: "enter", Desc: "save"}, + {Key: "esc", Desc: "cancel"}, + })) + return sb.String() + + case keyTableEditing: + var sb strings.Builder + sb.WriteString(fmt.Sprintf( + " Edit %s: %s\n", + m.keyInput.Value(), m.valueInput.View(), + )) + sb.WriteString(shared.RenderFooter(m.styles, []shared.KeyHint{ + {Key: "enter", Desc: "save"}, + {Key: "esc", Desc: "cancel"}, + })) + return sb.String() + + case keyTableConfirmDelete: + return fmt.Sprintf( + " Delete %s? %s/%s", + m.styles.Key.Render(m.entries[m.cursor].Key), + m.styles.Key.Render("y"), + m.styles.Muted.Render("N"), + ) + + default: + secretsHint := shared.KeyHint{Key: "s", Desc: "show secrets"} + if m.showSecrets { + secretsHint.Desc = "hide secrets" + } + return shared.RenderFooter(m.styles, []shared.KeyHint{ + {Key: "↑/↓", Desc: "navigate"}, + {Key: "a", Desc: "add"}, + {Key: "e", Desc: "edit"}, + {Key: "d", Desc: "delete"}, + secretsHint, + {Key: "b", Desc: "back"}, + {Key: "q", Desc: "quit"}, + }) + } +} + +// DispatchHeadlessKeyOutput writes key entries to a writer. +func DispatchHeadlessKeyOutput( + w io.Writer, + storeName string, + entries []appconfig.ConfigEntry, + showSecrets bool, + err error, +) { + if err != nil { + fmt.Fprintf(w, "Error loading keys: %v\n", err) + return + } + output := NewConfigOutput(w, false) + fmt.Fprintf(w, "Keys in %s:\n", storeName) + output.PrintEntryTable(entries, showSecrets) +} + +func isPlaintext(key string, entries []appconfig.ConfigEntry) bool { + for _, e := range entries { + if e.Key == key { + return !e.Sensitive + } + } + return false +} diff --git a/apps/cli/internal/tui/configui/key_table_test.go b/apps/cli/internal/tui/configui/key_table_test.go new file mode 100644 index 00000000..9cd483ba --- /dev/null +++ b/apps/cli/internal/tui/configui/key_table_test.go @@ -0,0 +1,177 @@ +package configui + +import ( + "bytes" + "context" + "testing" + "time" + + "github.com/charmbracelet/x/exp/teatest" + "github.com/newstack-cloud/celerity/apps/cli/internal/appconfig" + styles "github.com/newstack-cloud/deploy-cli-sdk/styles" + "github.com/stretchr/testify/suite" +) + +type KeyTableSuite struct { + suite.Suite + testEntries []appconfig.ConfigEntry +} + +func TestKeyTableSuite(t *testing.T) { + suite.Run(t, new(KeyTableSuite)) +} + +func (s *KeyTableSuite) SetupTest() { + s.testEntries = []appconfig.ConfigEntry{ + {Key: "TIMEOUT", Value: "5000", Sensitive: false}, + {Key: "LOG_LEVEL", Value: "info", Sensitive: false}, + {Key: "API_KEY", Value: "secret123", Sensitive: true}, + {Key: "DB_PASSWORD", Value: "dbpass", Sensitive: true}, + } +} + +func (s *KeyTableSuite) Test_renders_keys_with_masked_secrets() { + mock := &mockConfigStore{entries: s.testEntries} + model := NewKeyTableModel(context.Background(), s.testEntries, mock, "staging-app-config", styles.NewDefaultStyles(styles.NewCelerityPalette())) + + testModel := teatest.NewTestModel( + s.T(), model, + teatest.WithInitialTermSize(120, 40), + ) + + waitForContainsAll( + s.T(), testModel.Output(), + "TIMEOUT", "5000", + "API_KEY", "********", + ) + + keyQ(testModel) + testModel.WaitFinished(s.T(), teatest.WithFinalTimeout(5*time.Second)) +} + +func (s *KeyTableSuite) Test_toggle_show_secrets() { + mock := &mockConfigStore{entries: s.testEntries} + model := NewKeyTableModel(context.Background(), s.testEntries, mock, "staging-app-config", styles.NewDefaultStyles(styles.NewCelerityPalette())) + + testModel := teatest.NewTestModel( + s.T(), model, + teatest.WithInitialTermSize(120, 40), + ) + + waitForContains(s.T(), testModel.Output(), "********") + + // Press 's' to toggle secrets + keyRune(testModel, 's') + + waitForContains(s.T(), testModel.Output(), "secret123") + + keyQ(testModel) + testModel.WaitFinished(s.T(), teatest.WithFinalTimeout(5*time.Second)) +} + +func (s *KeyTableSuite) Test_navigate_down() { + mock := &mockConfigStore{entries: s.testEntries} + model := NewKeyTableModel(context.Background(), s.testEntries, mock, "staging-app-config", styles.NewDefaultStyles(styles.NewCelerityPalette())) + + testModel := teatest.NewTestModel( + s.T(), model, + teatest.WithInitialTermSize(120, 40), + ) + + waitForContains(s.T(), testModel.Output(), "> TIMEOUT") + + keyDown(testModel) + waitForContains(s.T(), testModel.Output(), "> LOG_LEVEL") + + keyQ(testModel) + testModel.WaitFinished(s.T(), teatest.WithFinalTimeout(5*time.Second)) +} + +func (s *KeyTableSuite) Test_headless_key_output() { + buf := &bytes.Buffer{} + DispatchHeadlessKeyOutput( + buf, "staging-app-config", s.testEntries, false, nil, + ) + + output := buf.String() + s.Contains(output, "TIMEOUT") + s.Contains(output, "5000") + s.Contains(output, "********") + s.NotContains(output, "secret123") + s.NotContains(output, "\033[") +} + +func (s *KeyTableSuite) Test_headless_key_output_show_secrets() { + buf := &bytes.Buffer{} + DispatchHeadlessKeyOutput( + buf, "staging-app-config", s.testEntries, true, nil, + ) + + output := buf.String() + s.Contains(output, "secret123") + s.NotContains(output, "********") +} + +// mockConfigStore implements appconfig.ConfigStore for testing. +type mockConfigStore struct { + entries []appconfig.ConfigEntry + getErr error + setErr error + deleteErr error + listErr error + importErr error + setCalls []setCall +} + +type setCall struct { + Key, Value string + Sensitive bool +} + +func (m *mockConfigStore) Get( + ctx context.Context, key string, +) (*appconfig.ConfigEntry, error) { + if m.getErr != nil { + return nil, m.getErr + } + for _, e := range m.entries { + if e.Key == key { + return &e, nil + } + } + return nil, nil +} + +func (m *mockConfigStore) Set( + ctx context.Context, + key, value string, + sensitive bool, +) error { + if m.setErr != nil { + return m.setErr + } + m.setCalls = append(m.setCalls, setCall{key, value, sensitive}) + return nil +} + +func (m *mockConfigStore) Delete( + ctx context.Context, key string, +) error { + return m.deleteErr +} + +func (m *mockConfigStore) List( + ctx context.Context, +) ([]appconfig.ConfigEntry, error) { + if m.listErr != nil { + return nil, m.listErr + } + return m.entries, nil +} + +func (m *mockConfigStore) Import( + ctx context.Context, + entries []appconfig.ConfigEntry, +) error { + return m.importErr +} diff --git a/apps/cli/internal/tui/configui/list_model.go b/apps/cli/internal/tui/configui/list_model.go new file mode 100644 index 00000000..589f4c13 --- /dev/null +++ b/apps/cli/internal/tui/configui/list_model.go @@ -0,0 +1,105 @@ +package configui + +import ( + "fmt" + "io" + + tea "github.com/charmbracelet/bubbletea" + "github.com/newstack-cloud/celerity/apps/cli/internal/appconfig" + styles "github.com/newstack-cloud/deploy-cli-sdk/styles" +) + +type listState uint32 + +const ( + listStateLoading listState = iota + listStateBrowsing + listStateDone +) + +// ListModelOptions configures the standalone list model. +type ListModelOptions struct { + Stores []appconfig.StoreInfo + Styles *styles.Styles + Headless bool + HeadlessWriter io.Writer +} + +// ListModel is a standalone model for `config list` (no store argument). +// It shows available stores and allows selection for key browsing. +type ListModel struct { + state listState + stores []appconfig.StoreInfo + storeSelect tea.Model + headless bool + writer io.Writer + Error error +} + +// NewListModel creates a new list model for browsing stores. +func NewListModel(opts ListModelOptions) ListModel { + model := ListModel{ + stores: opts.Stores, + headless: opts.Headless, + writer: opts.HeadlessWriter, + } + + if opts.Headless { + model.state = listStateDone + } else { + model.state = listStateBrowsing + model.storeSelect = NewStoreSelectModel(opts.Stores, opts.Styles) + } + + return model +} + +// Init implements tea.Model. +func (m ListModel) Init() tea.Cmd { + if m.headless { + return func() tea.Msg { + DispatchHeadlessStoreOutput(m.writer, m.stores, nil) + return tea.Quit() + } + } + if m.storeSelect != nil { + return m.storeSelect.Init() + } + return nil +} + +// Update implements tea.Model. +func (m ListModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.KeyMsg: + if msg.String() == "ctrl+c" || msg.String() == "q" { + return m, tea.Quit + } + case StoreSelectedMsg: + // The standalone list has nowhere to navigate to, so a selection ends + // the session. + if m.headless && m.writer != nil { + fmt.Fprintf(m.writer, "Selected: %s (%s)\n", + msg.Store.StoreName, msg.Store.StoreKind) + } + return m, tea.Quit + } + + if m.storeSelect != nil { + var cmd tea.Cmd + m.storeSelect, cmd = m.storeSelect.Update(msg) + return m, cmd + } + return m, nil +} + +// View implements tea.Model. +func (m ListModel) View() string { + if m.headless { + return "" + } + if m.storeSelect != nil { + return m.storeSelect.View() + } + return "" +} diff --git a/apps/cli/internal/tui/configui/messages.go b/apps/cli/internal/tui/configui/messages.go new file mode 100644 index 00000000..549b0b13 --- /dev/null +++ b/apps/cli/internal/tui/configui/messages.go @@ -0,0 +1,61 @@ +package configui + +import ( + "github.com/newstack-cloud/celerity/apps/cli/internal/appconfig" + "github.com/newstack-cloud/celerity/apps/cli/internal/devconfig" +) + +// EnvsLoadedMsg is sent when environments have been discovered. +type EnvsLoadedMsg struct { + Envs []devconfig.EnvironmentInfo +} + +// EnvsLoadErrorMsg is sent when environment discovery fails. +type EnvsLoadErrorMsg struct { + Err error +} + +// EnvSelectedMsg is sent when the user selects an environment. +type EnvSelectedMsg struct { + Env devconfig.EnvironmentInfo +} + +// StoresLoadedMsg is sent when stores have been extracted from the blueprint. +type StoresLoadedMsg struct { + Stores []appconfig.StoreInfo +} + +// StoresLoadErrorMsg is sent when store extraction fails. +type StoresLoadErrorMsg struct { + Err error +} + +// StoreSelectedMsg is sent when the user selects a store. +type StoreSelectedMsg struct { + Store appconfig.StoreInfo +} + +// KeysLoadedMsg is sent when keys are loaded from the config store. +type KeysLoadedMsg struct { + Entries []appconfig.ConfigEntry +} + +// KeysLoadErrorMsg is sent when key loading fails. +type KeysLoadErrorMsg struct { + Err error +} + +// KeySetMsg is sent after a key has been set successfully. +type KeySetMsg struct { + Key string +} + +// KeyDeletedMsg is sent after a key has been deleted successfully. +type KeyDeletedMsg struct { + Key string +} + +// OperationErrorMsg is sent when a config operation fails. +type OperationErrorMsg struct { + Err error +} diff --git a/apps/cli/internal/tui/configui/output.go b/apps/cli/internal/tui/configui/output.go new file mode 100644 index 00000000..d87c395b --- /dev/null +++ b/apps/cli/internal/tui/configui/output.go @@ -0,0 +1,138 @@ +package configui + +import ( + "fmt" + "io" + "strings" + + "github.com/newstack-cloud/celerity/apps/cli/internal/appconfig" +) + +const ( + colorReset = "\033[0m" + colorGreen = "\033[32m" + colorRed = "\033[31m" + colorYellow = "\033[33m" + colorBlue = "\033[34m" + colorGray = "\033[90m" + colorBold = "\033[1m" +) + +// ConfigOutput handles formatted stdout for config commands. +type ConfigOutput struct { + writer io.Writer + isColor bool +} + +// NewConfigOutput creates a new ConfigOutput writer. +func NewConfigOutput(writer io.Writer, isColor bool) *ConfigOutput { + return &ConfigOutput{writer: writer, isColor: isColor} +} + +// PrintSuccess prints a completed step with a green checkmark. +func (o *ConfigOutput) PrintSuccess(message string) { + icon := o.color(colorGreen, "✓") + fmt.Fprintf(o.writer, " %s %s\n", icon, message) +} + +// PrintError prints a failed step with a red X and error detail. +func (o *ConfigOutput) PrintError(message string, err error) { + icon := o.color(colorRed, "✗") + fmt.Fprintf(o.writer, " %s %s: %v\n", icon, message, err) +} + +// PrintInfo prints an informational message. +func (o *ConfigOutput) PrintInfo(message string) { + icon := o.color(colorBlue, "●") + fmt.Fprintf(o.writer, " %s %s\n", icon, message) +} + +// PrintWarning prints a warning message. +func (o *ConfigOutput) PrintWarning(message string) { + icon := o.color(colorYellow, "!") + fmt.Fprintf(o.writer, " %s %s\n", icon, message) +} + +// PrintTable prints a formatted table with headers and rows. +func (o *ConfigOutput) PrintTable(headers []string, rows [][]string) { + if len(headers) == 0 { + return + } + + widths := make([]int, len(headers)) + for i, h := range headers { + widths[i] = len(h) + } + for _, row := range rows { + for i, col := range row { + if i < len(widths) && len(col) > widths[i] { + widths[i] = len(col) + } + } + } + + o.printTableRow(headers, widths, true) + sep := make([]string, len(widths)) + for i, w := range widths { + sep[i] = strings.Repeat("─", w) + } + fmt.Fprintf(o.writer, " %s\n", strings.Join(sep, " ")) + for _, row := range rows { + o.printTableRow(row, widths, false) + } +} + +func (o *ConfigOutput) printTableRow( + cols []string, + widths []int, + isHeader bool, +) { + parts := make([]string, len(cols)) + for i, col := range cols { + w := widths[i] + padded := col + strings.Repeat(" ", max(0, w-len(col))) + if isHeader { + padded = o.color(colorBold, padded) + } + parts[i] = padded + } + fmt.Fprintf(o.writer, " %s\n", strings.Join(parts, " ")) +} + +// PrintStoreList prints a summary table of config stores. +func (o *ConfigOutput) PrintStoreList(stores []appconfig.StoreInfo) { + headers := []string{"Store", "Kind", "Resource"} + rows := make([][]string, len(stores)) + for i, s := range stores { + rows[i] = []string{s.StoreName, string(s.StoreKind), s.ResourceName} + } + o.PrintTable(headers, rows) +} + +// PrintEntryTable prints a table of config entries. +func (o *ConfigOutput) PrintEntryTable( + entries []appconfig.ConfigEntry, + showSecrets bool, +) { + headers := []string{"Key", "Value", "Type"} + rows := make([][]string, len(entries)) + for i, e := range entries { + value := e.Value + if e.Sensitive && !showSecrets { + value = "********" + } + entryType := "String" + if e.Sensitive { + entryType = "SecureString" + } + rows[i] = []string{e.Key, value, entryType} + } + o.PrintTable(headers, rows) +} + +func (o *ConfigOutput) color(code string, text string) string { + if !o.isColor { + return text + } + return code + text + colorReset +} diff --git a/apps/cli/internal/tui/configui/output_test.go b/apps/cli/internal/tui/configui/output_test.go new file mode 100644 index 00000000..d06fcabc --- /dev/null +++ b/apps/cli/internal/tui/configui/output_test.go @@ -0,0 +1,89 @@ +package configui + +import ( + "bytes" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/appconfig" + "github.com/stretchr/testify/assert" +) + +func TestPrintSuccess(t *testing.T) { + buf := &bytes.Buffer{} + o := NewConfigOutput(buf, false) + o.PrintSuccess("done") + assert.Contains(t, buf.String(), "✓") + assert.Contains(t, buf.String(), "done") +} + +func TestPrintError(t *testing.T) { + buf := &bytes.Buffer{} + o := NewConfigOutput(buf, false) + o.PrintError("failed", assert.AnError) + assert.Contains(t, buf.String(), "✗") + assert.Contains(t, buf.String(), "failed") +} + +func TestPrintTable(t *testing.T) { + buf := &bytes.Buffer{} + o := NewConfigOutput(buf, false) + o.PrintTable( + []string{"Name", "Value"}, + [][]string{ + {"KEY", "val"}, + {"LONGER_KEY", "longer_value"}, + }, + ) + output := buf.String() + assert.Contains(t, output, "Name") + assert.Contains(t, output, "KEY") + assert.Contains(t, output, "LONGER_KEY") + assert.Contains(t, output, "───") +} + +func TestPrintEntryTable_masks_secrets(t *testing.T) { + buf := &bytes.Buffer{} + o := NewConfigOutput(buf, false) + entries := []appconfig.ConfigEntry{ + {Key: "PUBLIC", Value: "visible", Sensitive: false}, + {Key: "SECRET", Value: "hidden", Sensitive: true}, + } + o.PrintEntryTable(entries, false) + output := buf.String() + assert.Contains(t, output, "visible") + assert.Contains(t, output, "********") + assert.NotContains(t, output, "hidden") +} + +func TestPrintEntryTable_shows_secrets(t *testing.T) { + buf := &bytes.Buffer{} + o := NewConfigOutput(buf, false) + entries := []appconfig.ConfigEntry{ + {Key: "SECRET", Value: "revealed", Sensitive: true}, + } + o.PrintEntryTable(entries, true) + assert.Contains(t, buf.String(), "revealed") + assert.NotContains(t, buf.String(), "********") +} + +func TestPrintStoreList(t *testing.T) { + buf := &bytes.Buffer{} + o := NewConfigOutput(buf, false) + stores := []appconfig.StoreInfo{ + {ResourceName: "appConfig", StoreName: "app-config", StoreKind: appconfig.StoreKindParameterStore}, + {ResourceName: "appSecrets", StoreName: "app-secrets", StoreKind: appconfig.StoreKindSecretsManager}, + } + o.PrintStoreList(stores) + output := buf.String() + assert.Contains(t, output, "app-config") + assert.Contains(t, output, "parameter-store") + assert.Contains(t, output, "app-secrets") + assert.Contains(t, output, "secrets-manager") +} + +func TestNoAnsiInNonColorMode(t *testing.T) { + buf := &bytes.Buffer{} + o := NewConfigOutput(buf, false) + o.PrintSuccess("test") + assert.NotContains(t, buf.String(), "\033[") +} diff --git a/apps/cli/internal/tui/configui/store_select.go b/apps/cli/internal/tui/configui/store_select.go new file mode 100644 index 00000000..1f2da56a --- /dev/null +++ b/apps/cli/internal/tui/configui/store_select.go @@ -0,0 +1,123 @@ +package configui + +import ( + "fmt" + "io" + + "github.com/charmbracelet/bubbles/list" + tea "github.com/charmbracelet/bubbletea" + "github.com/newstack-cloud/celerity/apps/cli/internal/appconfig" + "github.com/newstack-cloud/celerity/apps/cli/internal/tui/shared" + styles "github.com/newstack-cloud/deploy-cli-sdk/styles" +) + +// StoreSelectModel presents a selectable list of config stores. +type StoreSelectModel struct { + list list.Model + styles *styles.Styles + selected bool + choice appconfig.StoreInfo +} + +type storeItem struct { + store appconfig.StoreInfo +} + +func (s storeItem) FilterValue() string { return s.store.StoreName } +func (s storeItem) Title() string { return s.store.StoreName } +func (s storeItem) Description() string { + return fmt.Sprintf("%s (%s)", string(s.store.StoreKind), s.store.ResourceName) +} + +// NewStoreSelectModel creates a new store selection model. +func NewStoreSelectModel( + stores []appconfig.StoreInfo, + s *styles.Styles, +) StoreSelectModel { + items := make([]list.Item, len(stores)) + for i, store := range stores { + items[i] = storeItem{store: store} + } + + delegate := list.NewDefaultDelegate() + l := list.New(items, delegate, 60, 14) + l.Title = "Select Store" + l.SetShowStatusBar(false) + l.SetFilteringEnabled(len(items) > 5) + l.SetShowHelp(false) + l.Styles.Title = s.Title + + return StoreSelectModel{list: l, styles: s} +} + +// Init implements tea.Model. +func (m StoreSelectModel) Init() tea.Cmd { + return nil +} + +// Update implements tea.Model. +func (m StoreSelectModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.list.SetWidth(msg.Width) + m.list.SetHeight(msg.Height - 6) + return m, nil + case tea.KeyMsg: + switch msg.String() { + case "ctrl+c": + return m, tea.Quit + case "q": + // Only while the list is not filtering, where a q is a character + // the developer is typing into the filter rather than a command. + if m.list.FilterState() != list.Filtering { + return m, tea.Quit + } + case "enter": + item, ok := m.list.SelectedItem().(storeItem) + if ok { + m.selected = true + m.choice = item.store + return m, func() tea.Msg { + return StoreSelectedMsg{Store: item.store} + } + } + } + } + + var cmd tea.Cmd + m.list, cmd = m.list.Update(msg) + return m, cmd +} + +// View implements tea.Model. +func (m StoreSelectModel) View() string { + if m.selected { + return "" + } + + footer := shared.RenderFooter(m.styles, []shared.KeyHint{ + {Key: "↑/↓", Desc: "navigate"}, + {Key: "enter", Desc: "select"}, + {Key: "q", Desc: "quit"}, + }) + + return "\n" + m.list.View() + "\n" + footer + "\n" +} + +// DispatchHeadlessStoreOutput writes the store list to a writer. +func DispatchHeadlessStoreOutput( + w io.Writer, + stores []appconfig.StoreInfo, + err error, +) { + if err != nil { + fmt.Fprintf(w, "Error loading stores: %v\n", err) + return + } + if len(stores) == 0 { + fmt.Fprintln(w, "No config stores found in blueprint.") + return + } + output := NewConfigOutput(w, false) + output.PrintStoreList(stores) +} diff --git a/apps/cli/internal/tui/configui/store_select_test.go b/apps/cli/internal/tui/configui/store_select_test.go new file mode 100644 index 00000000..f7791a11 --- /dev/null +++ b/apps/cli/internal/tui/configui/store_select_test.go @@ -0,0 +1,97 @@ +package configui + +import ( + "bytes" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/exp/teatest" + "github.com/newstack-cloud/celerity/apps/cli/internal/appconfig" + styles "github.com/newstack-cloud/deploy-cli-sdk/styles" + "github.com/stretchr/testify/suite" +) + +type StoreSelectSuite struct { + suite.Suite + testStores []appconfig.StoreInfo +} + +func TestStoreSelectSuite(t *testing.T) { + suite.Run(t, new(StoreSelectSuite)) +} + +func (s *StoreSelectSuite) SetupTest() { + s.testStores = []appconfig.StoreInfo{ + { + ResourceName: "appConfig", + StoreName: "app-config", + StoreKind: appconfig.StoreKindParameterStore, + PlaintextKeys: map[string]bool{ + "TIMEOUT": true, + "LOG_LEVEL": true, + }, + }, + { + ResourceName: "appSecrets", + StoreName: "app-secrets", + StoreKind: appconfig.StoreKindSecretsManager, + }, + } +} + +func (s *StoreSelectSuite) Test_renders_store_list() { + model := NewStoreSelectModel(s.testStores, styles.NewDefaultStyles(styles.NewCelerityPalette())) + + testModel := teatest.NewTestModel( + s.T(), model, + teatest.WithInitialTermSize(120, 40), + ) + + waitForContainsAll( + s.T(), testModel.Output(), + "app-config", "app-secrets", + ) + + keyQ(testModel) + testModel.WaitFinished(s.T(), teatest.WithFinalTimeout(5*time.Second)) +} + +func (s *StoreSelectSuite) Test_selecting_store_sets_choice() { + model := NewStoreSelectModel(s.testStores, styles.NewDefaultStyles(styles.NewCelerityPalette())) + + testModel := teatest.NewTestModel( + s.T(), model, + teatest.WithInitialTermSize(120, 40), + ) + + waitForContains(s.T(), testModel.Output(), "app-config") + + keyEnter(testModel) + time.Sleep(100 * time.Millisecond) + + testModel.Send(tea.KeyMsg{Type: tea.KeyCtrlC}) + testModel.WaitFinished(s.T(), teatest.WithFinalTimeout(5*time.Second)) + + finalModel := testModel.FinalModel(s.T()).(StoreSelectModel) + s.True(finalModel.selected) + s.Equal("app-config", finalModel.choice.StoreName) +} + +func (s *StoreSelectSuite) Test_headless_store_output() { + buf := &bytes.Buffer{} + DispatchHeadlessStoreOutput(buf, s.testStores, nil) + + output := buf.String() + s.Contains(output, "app-config") + s.Contains(output, "app-secrets") + s.Contains(output, "parameter-store") + s.Contains(output, "secrets-manager") + s.NotContains(output, "\033[") +} + +func (s *StoreSelectSuite) Test_headless_store_output_empty() { + buf := &bytes.Buffer{} + DispatchHeadlessStoreOutput(buf, nil, nil) + s.Contains(buf.String(), "No config stores found") +} diff --git a/apps/cli/internal/tui/configui/testdata/app.deploy.production.jsonc b/apps/cli/internal/tui/configui/testdata/app.deploy.production.jsonc new file mode 100644 index 00000000..868cae5a --- /dev/null +++ b/apps/cli/internal/tui/configui/testdata/app.deploy.production.jsonc @@ -0,0 +1,10 @@ +{ + "deployTarget": { + "name": "aws", + "appEnv": "production", + "config": { + "aws.profile": "prod-account", + "aws.region": "eu-west-1" + } + } +} diff --git a/apps/cli/internal/tui/configui/testdata/app.deploy.staging.jsonc b/apps/cli/internal/tui/configui/testdata/app.deploy.staging.jsonc new file mode 100644 index 00000000..17a82aa3 --- /dev/null +++ b/apps/cli/internal/tui/configui/testdata/app.deploy.staging.jsonc @@ -0,0 +1,10 @@ +{ + "deployTarget": { + "name": "aws", + "appEnv": "staging", + "config": { + "aws.profile": "staging-account", + "aws.region": "us-east-1" + } + } +} diff --git a/apps/cli/internal/tui/configui/testutil_test.go b/apps/cli/internal/tui/configui/testutil_test.go new file mode 100644 index 00000000..3e351ae9 --- /dev/null +++ b/apps/cli/internal/tui/configui/testutil_test.go @@ -0,0 +1,63 @@ +package configui + +import ( + "io" + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/exp/teatest" +) + +func keyEnter(model *teatest.TestModel) { + model.Send(tea.KeyMsg{Type: tea.KeyEnter}) +} + +func keyDown(model *teatest.TestModel) { + model.Send(tea.KeyMsg{Type: tea.KeyDown}) +} + +func keyQ(model *teatest.TestModel) { + model.Send(tea.KeyMsg{ + Type: tea.KeyRunes, + Runes: []rune("q"), + }) +} + +func keyRune(model *teatest.TestModel, r rune) { + model.Send(tea.KeyMsg{ + Type: tea.KeyRunes, + Runes: []rune{r}, + }) +} + +func waitForContains(t *testing.T, output io.Reader, text string) { + t.Helper() + teatest.WaitFor( + t, output, + func(bts []byte) bool { + return strings.Contains(string(bts), text) + }, + teatest.WithCheckInterval(20*time.Millisecond), + teatest.WithDuration(10*time.Second), + ) +} + +func waitForContainsAll(t *testing.T, output io.Reader, texts ...string) { + t.Helper() + teatest.WaitFor( + t, output, + func(bts []byte) bool { + s := string(bts) + for _, text := range texts { + if !strings.Contains(s, text) { + return false + } + } + return true + }, + teatest.WithCheckInterval(20*time.Millisecond), + teatest.WithDuration(10*time.Second), + ) +} diff --git a/apps/cli/internal/tui/configui/tui.go b/apps/cli/internal/tui/configui/tui.go new file mode 100644 index 00000000..796ae344 --- /dev/null +++ b/apps/cli/internal/tui/configui/tui.go @@ -0,0 +1,298 @@ +package configui + +import ( + "context" + "fmt" + "io" + + tea "github.com/charmbracelet/bubbletea" + "github.com/newstack-cloud/celerity/apps/cli/internal/appconfig" + "github.com/newstack-cloud/celerity/apps/cli/internal/blueprint" + "github.com/newstack-cloud/celerity/apps/cli/internal/devconfig" + styles "github.com/newstack-cloud/deploy-cli-sdk/styles" +) + +type sessionState uint32 + +const ( + stateLoadingEnvs sessionState = iota + stateSelectEnv + stateLoadingStores + stateSelectStore + stateLoadingKeys + stateViewKeys + stateDone +) + +// MainModelOptions configures the interactive config TUI session. +type MainModelOptions struct { + // Context is bound to the store operations the session performs so they are + // cancelled when the command context is cancelled (e.g. on Ctrl+C). + Context context.Context + AppDir string + BlueprintFile string + Styles *styles.Styles + Headless bool + HeadlessWriter io.Writer + // StoreFactory allows injecting a mock ConfigStore for testing. + // When nil, the real provider factory is used. + StoreFactory func(ctx context.Context, target string, info appconfig.StoreInfo, opts appconfig.ProviderOpts) (appconfig.ConfigStore, error) +} + +// MainModel is the top-level bubbletea model for the interactive config session. +type MainModel struct { + state sessionState + options MainModelOptions + quitting bool + + // Discovered data + envs []devconfig.EnvironmentInfo + stores []appconfig.StoreInfo + + // Sub-models + envSelect tea.Model + storeSelect tea.Model + keyTable tea.Model + + // Selected state + selectedEnv devconfig.EnvironmentInfo + selectedStore appconfig.StoreInfo + configStore appconfig.ConfigStore + + Error error +} + +// NewMainModel creates a new interactive config session model. +func NewMainModel(opts MainModelOptions) MainModel { + return MainModel{ + state: stateLoadingEnvs, + options: opts, + } +} + +// Defaults to context.Background() when no context was supplied, which happens +// when the model is constructed directly in tests. +func (m MainModel) reqCtx() context.Context { + if m.options.Context != nil { + return m.options.Context + } + return context.Background() +} + +// Init implements tea.Model. +func (m MainModel) Init() tea.Cmd { + if m.options.Headless { + return nil + } + return LoadEnvsCmd(m.options.AppDir) +} + +// Update implements tea.Model. +func (m MainModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.KeyMsg: + if msg.String() == "ctrl+c" || msg.String() == "q" { + if m.state == stateSelectEnv || m.state == stateSelectStore { + m.quitting = true + return m, tea.Quit + } + } + case EnvsLoadedMsg: + return m.handleEnvsLoaded(msg) + case EnvsLoadErrorMsg: + m.Error = msg.Err + return m, tea.Quit + case EnvSelectedMsg: + return m.handleEnvSelected(msg) + case StoresLoadedMsg: + return m.handleStoresLoaded(msg) + case StoresLoadErrorMsg: + m.Error = msg.Err + return m, tea.Quit + case StoreSelectedMsg: + return m.handleStoreSelected(msg) + case KeysLoadedMsg: + return m.handleKeysLoaded(msg) + case KeysLoadErrorMsg: + m.Error = msg.Err + return m, tea.Quit + case backToStoresMsg: + return m.handleBackToStores() + } + + return m.updateCurrentModel(msg) +} + +func (m MainModel) handleEnvsLoaded( + msg EnvsLoadedMsg, +) (tea.Model, tea.Cmd) { + m.envs = msg.Envs + if len(m.envs) == 0 { + m.Error = fmt.Errorf("no deploy config files found in %s", m.options.AppDir) + return m, tea.Quit + } + m.state = stateSelectEnv + m.envSelect = NewEnvSelectModel(m.envs, m.options.Styles) + return m, m.envSelect.Init() +} + +func (m MainModel) handleEnvSelected( + msg EnvSelectedMsg, +) (tea.Model, tea.Cmd) { + m.selectedEnv = msg.Env + m.state = stateLoadingStores + return m, m.loadBlueprintAndStoresCmd() +} + +func (m MainModel) handleStoresLoaded( + msg StoresLoadedMsg, +) (tea.Model, tea.Cmd) { + m.stores = msg.Stores + if len(m.stores) == 0 { + m.Error = fmt.Errorf("no celerity/config resources found in blueprint") + return m, tea.Quit + } + m.state = stateSelectStore + m.storeSelect = NewStoreSelectModel(m.stores, m.options.Styles) + return m, m.storeSelect.Init() +} + +func (m MainModel) handleStoreSelected( + msg StoreSelectedMsg, +) (tea.Model, tea.Cmd) { + m.selectedStore = msg.Store + m.state = stateLoadingKeys + + store, err := m.createConfigStore(msg.Store) + if err != nil { + m.Error = err + return m, tea.Quit + } + m.configStore = store + return m, LoadKeysCmd(m.reqCtx(), store) +} + +func (m MainModel) handleKeysLoaded( + msg KeysLoadedMsg, +) (tea.Model, tea.Cmd) { + resolvedName := m.resolvedStoreName() + m.state = stateViewKeys + m.keyTable = NewKeyTableModel(m.reqCtx(), msg.Entries, m.configStore, resolvedName, m.options.Styles) + return m, nil +} + +func (m MainModel) handleBackToStores() (tea.Model, tea.Cmd) { + m.state = stateSelectStore + m.storeSelect = NewStoreSelectModel(m.stores, m.options.Styles) + return m, m.storeSelect.Init() +} + +func (m MainModel) updateCurrentModel( + msg tea.Msg, +) (tea.Model, tea.Cmd) { + switch m.state { + case stateSelectEnv: + if m.envSelect != nil { + var cmd tea.Cmd + m.envSelect, cmd = m.envSelect.Update(msg) + return m, cmd + } + case stateSelectStore: + if m.storeSelect != nil { + var cmd tea.Cmd + m.storeSelect, cmd = m.storeSelect.Update(msg) + return m, cmd + } + case stateViewKeys: + if m.keyTable != nil { + var cmd tea.Cmd + m.keyTable, cmd = m.keyTable.Update(msg) + return m, cmd + } + } + return m, nil +} + +// View implements tea.Model. +func (m MainModel) View() string { + if m.options.Headless { + return "" + } + if m.quitting { + return "" + } + if m.Error != nil { + return fmt.Sprintf("\n Error: %v\n", m.Error) + } + + switch m.state { + case stateLoadingEnvs: + return "\n Discovering environments...\n" + case stateSelectEnv: + if m.envSelect != nil { + return m.envSelect.View() + } + case stateLoadingStores: + return "\n Loading stores from blueprint...\n" + case stateSelectStore: + if m.storeSelect != nil { + return m.storeSelect.View() + } + case stateLoadingKeys: + return "\n Loading keys...\n" + case stateViewKeys: + if m.keyTable != nil { + return m.keyTable.View() + } + } + return "" +} + +func (m MainModel) loadBlueprintAndStoresCmd() tea.Cmd { + return func() tea.Msg { + bpPath := m.options.BlueprintFile + if bpPath == "" { + bpPath = "app.blueprint.yaml" + } + bp, _, err := blueprint.LoadForDev(bpPath) + if err != nil { + return StoresLoadErrorMsg{Err: err} + } + stores := appconfig.CollectStoreInfo(bp) + return StoresLoadedMsg{Stores: stores} + } +} + +func (m MainModel) createConfigStore( + info appconfig.StoreInfo, +) (appconfig.ConfigStore, error) { + resolvedName := m.resolvedStoreName() + resolved := appconfig.StoreInfo{ + ResourceName: info.ResourceName, + StoreName: resolvedName, + StoreKind: info.StoreKind, + PlaintextKeys: info.PlaintextKeys, + } + + opts := appconfig.ProviderOpts{ + Region: m.selectedEnv.Region, + Profile: m.selectedEnv.Profile, + } + + if m.options.StoreFactory != nil { + return m.options.StoreFactory( + m.reqCtx(), m.selectedEnv.DeployTarget, resolved, opts, + ) + } + return appconfig.NewConfigStore( + m.reqCtx(), m.selectedEnv.DeployTarget, resolved, opts, + ) +} + +func (m MainModel) resolvedStoreName() string { + appEnv := m.selectedEnv.AppEnv + if appEnv == "" { + appEnv = m.selectedEnv.Name + } + return appEnv + "-" + m.selectedStore.StoreName +} From 74d48b8f60b2f0d90db1a3558c1c7918aa372bcc Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 14 Oct 2026 16:18:56 +0100 Subject: [PATCH 09/12] feat(cli): add SQL schema management Declarative schema management for celerity/sqlDatabase resources, built on Atlas for inspection, diffing and migration planning. Schema YAML is the desired state, migrations are the committed history, and the two are reconciled by replaying the history into a scratch database and diffing the result. Covers generating migrations from a schema change, applying them with a risk gate so a destructive change needs an explicit opt in, detecting drift between the declared schema and a live database, generating types for application code, exporting an existing database into schema YAML, and evaluating the contracts a data team depends on. Reaching a database inside a VPC is the problem a deployed application has and an operator's machine does not, so privileged SQL runs through a maintenance runner deployed alongside the application rather than over a connection from outside. The application also gets a database role of its own rather than borrowing the instance's master credentials, which would hand every handler superuser. MySQL is implemented behind a flag and left off for v0, so Postgres is the only engine the dialect resolver accepts. Replaces ddl.go and migrations.go, whose hand-rolled DDL generation and migration tracking the Atlas integration supersedes. --- apps/cli/cmd/commands/schema.go | 209 ++++++++ apps/cli/cmd/commands/schema_apply.go | 338 ++++++++++++ apps/cli/cmd/commands/schema_apply_runner.go | 168 ++++++ apps/cli/cmd/commands/schema_codegen.go | 129 +++++ apps/cli/cmd/commands/schema_devdb.go | 120 +++++ apps/cli/cmd/commands/schema_diff.go | 118 ++++ apps/cli/cmd/commands/schema_drift.go | 123 +++++ apps/cli/cmd/commands/schema_export.go | 73 +++ apps/cli/cmd/commands/schema_hash.go | 46 ++ apps/cli/cmd/commands/schema_history.go | 56 ++ apps/cli/cmd/commands/schema_new.go | 41 ++ apps/cli/cmd/commands/schema_provision.go | 204 +++++++ .../commands/schema_provision_wait_test.go | 115 ++++ apps/cli/cmd/commands/schema_show.go | 56 ++ apps/cli/cmd/commands/schema_validate.go | 96 ++++ apps/cli/cmd/maintenance-runner/main.go | 36 ++ apps/cli/internal/dbconn/awscreds/awscreds.go | 131 +++++ apps/cli/internal/dbconn/dbconn.go | 110 ++++ apps/cli/internal/deploydb/aws.go | 174 ++++++ apps/cli/internal/deploydb/aws_test.go | 188 +++++++ apps/cli/internal/deploydb/resolve.go | 128 +++++ .../maintenancerunner/awsrunner/awsrunner.go | 190 +++++++ .../awsrunner/awsrunner_region_test.go | 66 +++ .../awsrunner/awsrunner_test.go | 116 ++++ .../maintenancerunner/awsrunner/serve.go | 47 ++ .../cli/internal/maintenancerunner/execute.go | 304 +++++++++++ .../maintenancerunner/execute_test.go | 413 ++++++++++++++ apps/cli/internal/maintenancerunner/host.go | 108 ++++ .../internal/maintenancerunner/host_test.go | 145 +++++ apps/cli/internal/maintenancerunner/invoke.go | 56 ++ .../internal/maintenancerunner/protocol.go | 262 +++++++++ .../seed/config_keys_contract_test.go | 126 +++++ apps/cli/internal/seed/config_seeder.go | 27 +- apps/cli/internal/seed/dynamodb.go | 1 - apps/cli/internal/seed/handler_scope.go | 103 ++++ apps/cli/internal/seed/handler_scope_test.go | 117 ++++ apps/cli/internal/seed/hooks.go | 3 +- apps/cli/internal/seed/loader.go | 11 +- apps/cli/internal/seed/minio.go | 2 - apps/cli/internal/seed/resource_links.go | 11 +- apps/cli/internal/sqlschema/applier.go | 450 ++++++++++------ .../sqlschema/applier_integration_test.go | 341 +++++++----- apps/cli/internal/sqlschema/blueprint.go | 14 +- apps/cli/internal/sqlschema/classify.go | 255 +++++++++ apps/cli/internal/sqlschema/classify_test.go | 126 +++++ apps/cli/internal/sqlschema/codegen.go | 340 ++++++++++++ apps/cli/internal/sqlschema/codegen_test.go | 169 ++++++ apps/cli/internal/sqlschema/contracts.go | 241 +++++++++ apps/cli/internal/sqlschema/contracts_test.go | 146 +++++ apps/cli/internal/sqlschema/ddl.go | 279 ---------- apps/cli/internal/sqlschema/ddl_test.go | 238 -------- apps/cli/internal/sqlschema/dialect.go | 83 ++- apps/cli/internal/sqlschema/dialect_mysql.go | 116 ++++ .../internal/sqlschema/dialect_postgres.go | 102 +++- apps/cli/internal/sqlschema/dialect_test.go | 48 ++ apps/cli/internal/sqlschema/drift.go | 432 +++++++++++++++ .../sqlschema/drift_integration_test.go | 194 +++++++ apps/cli/internal/sqlschema/drift_test.go | 132 +++++ apps/cli/internal/sqlschema/exclude.go | 38 ++ apps/cli/internal/sqlschema/exclude_test.go | 45 ++ apps/cli/internal/sqlschema/export.go | 282 ++++++++++ apps/cli/internal/sqlschema/export_test.go | 115 ++++ apps/cli/internal/sqlschema/inspect.go | 156 ++++++ apps/cli/internal/sqlschema/migrationdir.go | 506 ++++++++++++++++++ .../migrationdir_integration_test.go | 269 ++++++++++ .../internal/sqlschema/migrationdir_test.go | 124 +++++ apps/cli/internal/sqlschema/migrations.go | 107 ---- .../cli/internal/sqlschema/migrations_test.go | 132 ----- .../sqlschema/mysql_integration_test.go | 186 +++++++ apps/cli/internal/sqlschema/provision.go | 171 ++++++ .../sqlschema/provision_integration_test.go | 201 +++++++ .../cli/internal/sqlschema/provision_mysql.go | 134 +++++ .../internal/sqlschema/provision_postgres.go | 157 ++++++ apps/cli/internal/sqlschema/provision_test.go | 80 +++ apps/cli/internal/sqlschema/realm.go | 165 ++++++ apps/cli/internal/sqlschema/realm_test.go | 196 +++++++ apps/cli/internal/sqlschema/revisions.go | 201 +++++++ .../cli/internal/sqlschema/revisions_mysql.go | 138 +++++ apps/cli/internal/sqlschema/types.go | 49 +- apps/cli/internal/sqlschema/validate.go | 52 ++ apps/cli/internal/sqlschema/validate_test.go | 92 ++++ 81 files changed, 10920 insertions(+), 1149 deletions(-) create mode 100644 apps/cli/cmd/commands/schema.go create mode 100644 apps/cli/cmd/commands/schema_apply.go create mode 100644 apps/cli/cmd/commands/schema_apply_runner.go create mode 100644 apps/cli/cmd/commands/schema_codegen.go create mode 100644 apps/cli/cmd/commands/schema_devdb.go create mode 100644 apps/cli/cmd/commands/schema_diff.go create mode 100644 apps/cli/cmd/commands/schema_drift.go create mode 100644 apps/cli/cmd/commands/schema_export.go create mode 100644 apps/cli/cmd/commands/schema_hash.go create mode 100644 apps/cli/cmd/commands/schema_history.go create mode 100644 apps/cli/cmd/commands/schema_new.go create mode 100644 apps/cli/cmd/commands/schema_provision.go create mode 100644 apps/cli/cmd/commands/schema_provision_wait_test.go create mode 100644 apps/cli/cmd/commands/schema_show.go create mode 100644 apps/cli/cmd/commands/schema_validate.go create mode 100644 apps/cli/cmd/maintenance-runner/main.go create mode 100644 apps/cli/internal/dbconn/awscreds/awscreds.go create mode 100644 apps/cli/internal/dbconn/dbconn.go create mode 100644 apps/cli/internal/deploydb/aws.go create mode 100644 apps/cli/internal/deploydb/aws_test.go create mode 100644 apps/cli/internal/deploydb/resolve.go create mode 100644 apps/cli/internal/maintenancerunner/awsrunner/awsrunner.go create mode 100644 apps/cli/internal/maintenancerunner/awsrunner/awsrunner_region_test.go create mode 100644 apps/cli/internal/maintenancerunner/awsrunner/awsrunner_test.go create mode 100644 apps/cli/internal/maintenancerunner/awsrunner/serve.go create mode 100644 apps/cli/internal/maintenancerunner/execute.go create mode 100644 apps/cli/internal/maintenancerunner/execute_test.go create mode 100644 apps/cli/internal/maintenancerunner/host.go create mode 100644 apps/cli/internal/maintenancerunner/host_test.go create mode 100644 apps/cli/internal/maintenancerunner/invoke.go create mode 100644 apps/cli/internal/maintenancerunner/protocol.go create mode 100644 apps/cli/internal/seed/config_keys_contract_test.go create mode 100644 apps/cli/internal/seed/handler_scope.go create mode 100644 apps/cli/internal/seed/handler_scope_test.go create mode 100644 apps/cli/internal/sqlschema/classify.go create mode 100644 apps/cli/internal/sqlschema/classify_test.go create mode 100644 apps/cli/internal/sqlschema/codegen.go create mode 100644 apps/cli/internal/sqlschema/codegen_test.go create mode 100644 apps/cli/internal/sqlschema/contracts.go create mode 100644 apps/cli/internal/sqlschema/contracts_test.go delete mode 100644 apps/cli/internal/sqlschema/ddl.go delete mode 100644 apps/cli/internal/sqlschema/ddl_test.go create mode 100644 apps/cli/internal/sqlschema/dialect_mysql.go create mode 100644 apps/cli/internal/sqlschema/dialect_test.go create mode 100644 apps/cli/internal/sqlschema/drift.go create mode 100644 apps/cli/internal/sqlschema/drift_integration_test.go create mode 100644 apps/cli/internal/sqlschema/drift_test.go create mode 100644 apps/cli/internal/sqlschema/exclude.go create mode 100644 apps/cli/internal/sqlschema/exclude_test.go create mode 100644 apps/cli/internal/sqlschema/export.go create mode 100644 apps/cli/internal/sqlschema/export_test.go create mode 100644 apps/cli/internal/sqlschema/inspect.go create mode 100644 apps/cli/internal/sqlschema/migrationdir.go create mode 100644 apps/cli/internal/sqlschema/migrationdir_integration_test.go create mode 100644 apps/cli/internal/sqlschema/migrationdir_test.go delete mode 100644 apps/cli/internal/sqlschema/migrations.go delete mode 100644 apps/cli/internal/sqlschema/migrations_test.go create mode 100644 apps/cli/internal/sqlschema/mysql_integration_test.go create mode 100644 apps/cli/internal/sqlschema/provision.go create mode 100644 apps/cli/internal/sqlschema/provision_integration_test.go create mode 100644 apps/cli/internal/sqlschema/provision_mysql.go create mode 100644 apps/cli/internal/sqlschema/provision_postgres.go create mode 100644 apps/cli/internal/sqlschema/provision_test.go create mode 100644 apps/cli/internal/sqlschema/realm.go create mode 100644 apps/cli/internal/sqlschema/realm_test.go create mode 100644 apps/cli/internal/sqlschema/revisions.go create mode 100644 apps/cli/internal/sqlschema/revisions_mysql.go create mode 100644 apps/cli/internal/sqlschema/validate.go create mode 100644 apps/cli/internal/sqlschema/validate_test.go diff --git a/apps/cli/cmd/commands/schema.go b/apps/cli/cmd/commands/schema.go new file mode 100644 index 00000000..1795b8c2 --- /dev/null +++ b/apps/cli/cmd/commands/schema.go @@ -0,0 +1,209 @@ +package commands + +import ( + "fmt" + "path/filepath" + + "github.com/newstack-cloud/celerity/apps/cli/internal/blueprint" + "github.com/newstack-cloud/celerity/apps/cli/internal/devconfig/resolve" + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/spf13/cobra" +) + +func setupSchemaCommand(rootCmd *cobra.Command, confProvider *config.Provider) { + schemaCmd := &cobra.Command{ + Use: "schema", + Short: "Manage SQL database schemas and migrations", + Long: `Manage SQL database schemas for celerity/sqlDatabase resources. + +Schema definitions are declarative YAML files describing the desired state of a +database. celerity schema diff generates versioned SQL migration files from +changes to those files, which you review, commit, and apply. + +Subcommands: + celerity schema new Create an empty migration file for hand-written SQL + celerity schema hash Recompute atlas.sum after hand-editing a migration + celerity schema diff Generate a migration file from schema YAML changes + celerity schema apply Apply pending migrations to a database + celerity schema validate Validate schema files and migration integrity + celerity schema drift Check a live database for out-of-band changes + celerity schema codegen Generate type-safe code from schema definitions + celerity schema export Export a schema as SQL, markdown, JSON Schema or Mermaid + celerity schema show Show the current schema of a deployed database + celerity schema history Show the applied migration history of a database`, + } + + schemaCmd.PersistentFlags().String( + "blueprint-file", "", + "The blueprint file to read celerity/sqlDatabase resources from (default: auto-detect).", + ) + schemaCmd.PersistentFlags().String( + "database", "", + "The celerity/sqlDatabase resource to target (required when the blueprint defines more than one).", + ) + + setupSchemaNewCommand(schemaCmd) + setupSchemaHashCommand(schemaCmd) + setupSchemaDiffCommand(schemaCmd) + setupSchemaApplyCommand(schemaCmd, confProvider) + setupSchemaValidateCommand(schemaCmd) + setupSchemaDriftCommand(schemaCmd, confProvider) + setupSchemaCodegenCommand(schemaCmd) + setupSchemaExportCommand(schemaCmd) + setupSchemaShowCommand(schemaCmd, confProvider) + setupSchemaHistoryCommand(schemaCmd, confProvider) + + rootCmd.AddCommand(schemaCmd) +} + +// loadDatabaseResources loads the blueprint and returns all celerity/sqlDatabase +// resources it defines. +func loadDatabaseResources(cmd *cobra.Command) ([]sqlschema.DatabaseResource, error) { + blueprintFlag, _ := cmd.Flags().GetString("blueprint-file") + + bpPath, err := resolve.BlueprintPath(".", blueprintFlag) + if err != nil { + return nil, err + } + bp, _, err := blueprint.LoadForDev(bpPath) + if err != nil { + return nil, fmt.Errorf("loading blueprint: %w", err) + } + resources := sqlschema.CollectDatabaseResources(bp, ".") + if len(resources) == 0 { + return nil, fmt.Errorf("no celerity/sqlDatabase resources found in %s", bpPath) + } + return resources, nil +} + +// loadSchemaContracts finds and loads the schema-contracts.yaml alongside the +// blueprint, returning nil (no error) when there is none. +func loadSchemaContracts(cmd *cobra.Command) (*sqlschema.ContractsFile, error) { + blueprintFlag, _ := cmd.Flags().GetString("blueprint-file") + bpPath, err := resolve.BlueprintPath(".", blueprintFlag) + if err != nil { + return nil, err + } + path, ok := sqlschema.FindContractsFile(filepath.Dir(bpPath)) + if !ok { + return nil, nil + } + return sqlschema.LoadContractsFile(path) +} + +// resolveTargetConnection resolves the target database for a read-only command +// from its --url / --instance-name flags, returning the connection string and a +// display label for the target. +func resolveTargetConnection( + cmd *cobra.Command, + confProvider *config.Provider, + resource sqlschema.DatabaseResource, +) (connString, target string, err error) { + url, _ := cmd.Flags().GetString("url") + instanceName, _ := cmd.Flags().GetString("instance-name") + + if url == "" && instanceName == "" { + return "", "", fmt.Errorf("provide a target database with --url or --instance-name") + } + if url != "" && instanceName != "" { + return "", "", fmt.Errorf("--url and --instance-name are mutually exclusive") + } + if url != "" { + return url, "url", nil + } + resolved, err := resolveDeployedConnection(cmd.Context(), confProvider, resource, instanceName) + if err != nil { + return "", "", err + } + return resolved.ConnectionString, resolved.Target, nil +} + +// evaluateResourceContracts evaluates the schema contracts (if any) against a set +// of changed tables for a single database resource. +func evaluateResourceContracts( + cmd *cobra.Command, + resource sqlschema.DatabaseResource, + changed []string, +) ([]sqlschema.ContractImpact, error) { + if len(changed) == 0 { + return nil, nil + } + contracts, err := loadSchemaContracts(cmd) + if err != nil { + return nil, err + } + if contracts == nil { + return nil, nil + } + changedByName := map[string][]string{resource.ResourceName: changed} + if resource.Name != "" { + changedByName[resource.Name] = changed + } + return sqlschema.EvaluateContracts(contracts, changedByName), nil +} + +// resourceSchemas parses every resource's schema YAML, keyed by both resource +// name and configured database name so contracts can reference either. Resources +// whose schema fails to parse are skipped (schema validation reports those +// separately). +func resourceSchemas(resources []sqlschema.DatabaseResource) map[string]*sqlschema.Schema { + schemas := map[string]*sqlschema.Schema{} + for _, r := range resources { + if r.SchemaPath == "" { + continue + } + parsed, err := sqlschema.ParseSchemaFile(r.SchemaPath) + if err != nil { + continue + } + schemas[r.ResourceName] = parsed + if r.Name != "" { + schemas[r.Name] = parsed + } + } + return schemas +} + +// resolveDatabaseResource loads the blueprint and returns the target +// celerity/sqlDatabase resource, selected by the --database flag when the +// blueprint defines more than one. +func resolveDatabaseResource(cmd *cobra.Command) (sqlschema.DatabaseResource, error) { + blueprintFlag, _ := cmd.Flags().GetString("blueprint-file") + databaseFlag, _ := cmd.Flags().GetString("database") + + bpPath, err := resolve.BlueprintPath(".", blueprintFlag) + if err != nil { + return sqlschema.DatabaseResource{}, err + } + + bp, _, err := blueprint.LoadForDev(bpPath) + if err != nil { + return sqlschema.DatabaseResource{}, fmt.Errorf("loading blueprint: %w", err) + } + + resources := sqlschema.CollectDatabaseResources(bp, ".") + if len(resources) == 0 { + return sqlschema.DatabaseResource{}, fmt.Errorf("no celerity/sqlDatabase resources found in %s", bpPath) + } + + if databaseFlag != "" { + for _, r := range resources { + if r.ResourceName == databaseFlag || r.Name == databaseFlag { + return r, nil + } + } + return sqlschema.DatabaseResource{}, fmt.Errorf("no celerity/sqlDatabase resource named %q", databaseFlag) + } + + if len(resources) > 1 { + names := make([]string, len(resources)) + for i, r := range resources { + names[i] = r.ResourceName + } + return sqlschema.DatabaseResource{}, fmt.Errorf( + "blueprint defines multiple SQL databases (%v); specify one with --database", names) + } + + return resources[0], nil +} diff --git a/apps/cli/cmd/commands/schema_apply.go b/apps/cli/cmd/commands/schema_apply.go new file mode 100644 index 00000000..409f019f --- /dev/null +++ b/apps/cli/cmd/commands/schema_apply.go @@ -0,0 +1,338 @@ +package commands + +import ( + "bufio" + "context" + "fmt" + "io" + "os" + "strings" + + "github.com/newstack-cloud/bluelink/libs/blueprint/state" + "github.com/newstack-cloud/celerity/apps/cli/internal/deployconfig" + "github.com/newstack-cloud/celerity/apps/cli/internal/deploydb" + "github.com/newstack-cloud/celerity/apps/cli/internal/engine" + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/spf13/cobra" + "go.uber.org/zap" + "golang.org/x/term" +) + +func setupSchemaApplyCommand(schemaCmd *cobra.Command, confProvider *config.Provider) { + applyCmd := &cobra.Command{ + Use: "apply", + Short: "Apply pending migrations to a database", + Long: `Apply pending migration files from the resource's migrationsPath to a database, +in timestamp order, skipping migrations already recorded in the +atlas_schema_revisions table. + +Choose the target database with one of: + --url an explicit connection string (local or any reachable database) + --instance-name a deployed blueprint instance; the connection is resolved from + its deployed state and the credential is fetched from the + provider's secret store (AWS today) + +Examples: + celerity schema apply --url postgres://user:pass@localhost:5432/orders?sslmode=disable + celerity schema apply --instance-name production-orders`, + RunE: func(cmd *cobra.Command, args []string) error { + url, _ := cmd.Flags().GetString("url") + instanceName, _ := cmd.Flags().GetString("instance-name") + via, _ := cmd.Flags().GetString("via") + + if err := validateVia(via); err != nil { + return err + } + if url == "" && instanceName == "" { + return fmt.Errorf("provide a target database with --url or --instance-name") + } + if url != "" && instanceName != "" { + return fmt.Errorf("--url and --instance-name are mutually exclusive") + } + + resource, err := resolveDatabaseResource(cmd) + if err != nil { + return err + } + if resource.MigrationsPath == "" { + return fmt.Errorf("resource %q has no migrationsPath configured", resource.ResourceName) + } + + target := "the target database" + if url == "" { + // A deployed/live database must be migrated from a committed, + // verified directory, so a valid atlas.sum is required rather + // than auto-generated. + if err := sqlschema.ValidateMigrationDir(resource.MigrationsPath); err != nil { + return err + } + deployed, err := resolveDeployedInstance(cmd.Context(), confProvider, instanceName) + if err != nil { + return err + } + + // This runs before migrating rather than after. Migrations run as + // the owner and do not need the application user, but a database + // that was restored or replaced has an application credential + // authenticating as nobody, and this is the command an operator + // reaches for. + if via != viaDirect { + if err := provisionAppUser( + cmd.Context(), cmd.OutOrStdout(), deployed.State, + deployed.DeployTarget, resource.ResourceName, via, + ); err != nil { + return err + } + } + + // Migrations move to the database rather than the other way + // round, when there is a runner to move them to. A private + // database cannot be reached from here at all, so this is not an + // optimisation. The direct path below only works for a database + // the operator can actually open a connection to. + maxRisk := maxRiskFromFlags(cmd) + handled, err := applyMigrationsViaRunner( + cmd.Context(), cmd.OutOrStdout(), deployed.State, deployed.DeployTarget, + resource, via, maxRisk, applyConfirmation(cmd), + ) + if err != nil { + return err + } + if handled { + return nil + } + + resolved, err := deployed.connection(cmd.Context(), resource) + if err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "Applying to %s\n", resolved.Target) + target = resolved.Target + url = resolved.ConnectionString + } + + applier, err := sqlschema.NewApplier(resource.Engine, url, zap.NewNop()) + if err != nil { + return err + } + defer applier.Close() + + out := cmd.OutOrStdout() + + // The database state is guarded before applying, because drift means + // the live database is not in the state the pending migrations assume + // and even correct migrations can then do the wrong thing. History + // drift (a revision applied out-of-band or a migration deleted from + // the directory) is always checked. Structural drift additionally + // needs a dev database to reconstruct the expected state, which is + // either a throwaway container or --dev-url, falling back to + // history-only when neither is available. --allow-drift skips the + // whole check. + if allowDrift, _ := cmd.Flags().GetBool("allow-drift"); !allowDrift { + devURL, _ := cmd.Flags().GetString("dev-url") + if devURL == "" && (resource.Engine == "" || resource.Engine == "postgres") { + fmt.Fprintln(out, "Checking for drift before applying...") + u, cleanup, provErr := provisionDevPostgres(cmd.Context(), zap.NewNop()) + if provErr != nil { + fmt.Fprintf(out, + "Note: structural drift check skipped (no dev database: %v); running history-only. Pass --dev-url for the full check.\n", + provErr) + } else { + defer cleanup() + devURL = u + } + } + + report, err := sqlschema.DetectDrift(cmd.Context(), applier, devURL, resource.MigrationsPath, resource.Engine) + if err != nil { + return err + } + if report.HasDrift() { + report.Resource = resource.ResourceName + report.Target = target + report.Contracts, _ = evaluateResourceContracts(cmd, resource, report.StructuralTables) + report.Render(out) + return fmt.Errorf( + "drift detected for %s; run `celerity schema drift` to inspect it, then reconcile or re-run with --allow-drift once understood", + resource.ResourceName) + } + } + + maxRisk := maxRiskFromFlags(cmd) + + pending, err := applier.PendingMigrations(cmd.Context(), resource.MigrationsPath) + if err != nil { + return err + } + if len(pending) == 0 { + fmt.Fprintf(out, "No pending migrations for %s.\n", resource.ResourceName) + return nil + } + + fmt.Fprintf(out, "%d pending migration(s) for %s → %s:\n", len(pending), resource.ResourceName, target) + for _, p := range pending { + fmt.Fprintf(out, " - %s [risk: %s]\n", p.Name, p.Risk) + } + + // Applying to a named deployed instance is confirmed interactively + // unless --auto-approve is passed (e.g. in CI). Explicit --url targets + // apply directly. + if instanceName != "" { + autoApprove, _ := cmd.Flags().GetBool("auto-approve") + if !autoApprove { + if err := confirmApply(cmd, out); err != nil { + return err + } + } + } + + if err := applier.ApplyMigrationDir(cmd.Context(), resource.MigrationsPath, maxRisk); err != nil { + return err + } + fmt.Fprintf(out, "Applied pending migrations for %s.\n", resource.ResourceName) + return nil + }, + } + + applyCmd.Flags().String("url", "", "Connection string of the target database.") + applyCmd.Flags().String("instance-name", "", "Deployed blueprint instance whose database to migrate.") + applyCmd.Flags().Bool("allow-risky", false, "Apply data-dependent (risky) migrations (e.g. NOT NULL, unique, foreign key).") + applyCmd.Flags().Bool("allow-breaking", false, "Apply breaking (destructive) migrations (e.g. drop table/column). Implies --allow-risky.") + applyCmd.Flags().Bool("allow-drift", false, "Skip the pre-apply drift check.") + applyCmd.Flags().String("dev-url", "", "Empty dev database for the structural drift check (default: start a throwaway container).") + applyCmd.Flags().BoolP("auto-approve", "y", false, "Skip the interactive confirmation when applying to a deployed instance.") + applyCmd.Flags().String("via", viaAuto, + "How to reach the database: auto (use the deployed maintenance runner when there is one), runner (require it), direct (connect from here).") + schemaCmd.AddCommand(applyCmd) +} + +// confirmApply prompts for confirmation before applying migrations to a deployed +// database. It fails when there is no terminal to prompt on (e.g. CI), directing +// the user to --auto-approve. +func confirmApply(cmd *cobra.Command, out io.Writer) error { + if !term.IsTerminal(int(os.Stdin.Fd())) { + return fmt.Errorf("refusing to apply to a deployed instance without confirmation; re-run with --auto-approve") + } + fmt.Fprint(out, "Proceed? [y/N]: ") + line, _ := bufio.NewReader(cmd.InOrStdin()).ReadString('\n') + switch strings.ToLower(strings.TrimSpace(line)) { + case "y", "yes": + return nil + default: + return fmt.Errorf("apply aborted") + } +} + +// deployedInstance is a resolved deployment, holding its state and the deploy +// target that determines how anything provider-specific is done against it. +// +// It is resolved once and reused, because both halves of an apply against a +// deployed database need it: provisioning the application user through the +// maintenance runner, and building the migration connection. +type deployedInstance struct { + State *state.InstanceState + DeployTarget string +} + +// resolveDeployedInstance reads the deploy target from config and fetches the +// named instance's state from the deploy engine. +func resolveDeployedInstance( + ctx context.Context, + confProvider *config.Provider, + instanceName string, +) (*deployedInstance, error) { + appConfigFile, _ := confProvider.GetString("appDeployConfigFile") + if appConfigFile == "" { + appConfigFile = "app.deploy.jsonc" + } + appCfg, err := deployconfig.ReadAppDeployConfig(appConfigFile) + if err != nil { + return nil, fmt.Errorf("reading deploy config: %w", err) + } + + engineClient, err := engine.Create(confProvider, zap.NewNop()) + if err != nil { + return nil, fmt.Errorf("connecting to deploy engine: %w", err) + } + + instanceState, err := getInstanceByName(ctx, engineClient, instanceName) + if err != nil { + return nil, err + } + + return &deployedInstance{State: instanceState, DeployTarget: appCfg.DeployTarget.Name}, nil +} + +// resolveDeployedConnection resolves a migration connection for a deployed +// instance in one step, for the read-only commands that have no reason to +// provision anything. +func resolveDeployedConnection( + ctx context.Context, + confProvider *config.Provider, + resource sqlschema.DatabaseResource, + instanceName string, +) (*deploydb.ResolvedConnection, error) { + deployed, err := resolveDeployedInstance(ctx, confProvider, instanceName) + if err != nil { + return nil, err + } + return deployed.connection(ctx, resource) +} + +// connection derives a migration connection (credentials included) from the +// instance's state, using the provider-specific resolver for its deploy target. +func (d *deployedInstance) connection( + ctx context.Context, + resource sqlschema.DatabaseResource, +) (*deploydb.ResolvedConnection, error) { + resolver, err := deploydb.ResolverFor(d.DeployTarget) + if err != nil { + return nil, err + } + return resolver.Resolve(ctx, d.State, deploydb.ResolveInput{ + SQLDatabaseName: resource.ResourceName, + Engine: resource.Engine, + FallbackDatabase: resource.Name, + }) +} + +// getInstanceByName finds a deployed blueprint instance by its exact name and +// returns its full state. +func getInstanceByName(ctx context.Context, engineClient engine.DeployEngine, name string) (*state.InstanceState, error) { + list, err := engineClient.ListBlueprintInstances(ctx, state.ListInstancesParams{Search: name}) + if err != nil { + return nil, fmt.Errorf("listing deployed instances: %w", err) + } + for _, summary := range list.Instances { + if summary.InstanceName == name { + return engineClient.GetBlueprintInstance(ctx, summary.InstanceID) + } + } + return nil, fmt.Errorf("no deployed instance named %q found", name) +} + +// maxRiskFromFlags reads the highest migration risk the operator authorised. +// Breaking implies risky, which is why it is checked second. +func maxRiskFromFlags(cmd *cobra.Command) sqlschema.RiskLevel { + maxRisk := sqlschema.RiskSafe + if allowRisky, _ := cmd.Flags().GetBool("allow-risky"); allowRisky { + maxRisk = sqlschema.RiskRisky + } + if allowBreaking, _ := cmd.Flags().GetBool("allow-breaking"); allowBreaking { + maxRisk = sqlschema.RiskBreaking + } + return maxRisk +} + +// applyConfirmation returns the interactive confirmation to run before applying +// to a deployed instance, or nil when none is needed. +// +// Applying through the runner reaches a deployed database just as the direct +// path does, so it asks the same question. --auto-approve skips it for CI. +func applyConfirmation(cmd *cobra.Command) func() error { + if autoApprove, _ := cmd.Flags().GetBool("auto-approve"); autoApprove { + return nil + } + return func() error { return confirmApply(cmd, cmd.OutOrStdout()) } +} diff --git a/apps/cli/cmd/commands/schema_apply_runner.go b/apps/cli/cmd/commands/schema_apply_runner.go new file mode 100644 index 00000000..1c088457 --- /dev/null +++ b/apps/cli/cmd/commands/schema_apply_runner.go @@ -0,0 +1,168 @@ +package commands + +import ( + "context" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/newstack-cloud/bluelink/libs/blueprint/state" + "github.com/newstack-cloud/celerity/apps/cli/internal/maintenancerunner" + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" +) + +// maxRunnerMigrationPayload bounds what is sent in one invocation. +// +// A synchronous Lambda invocation caps its request at 6MB. Checking here means +// an oversized migration set is reported as one, rather than as whatever the +// provider reports when it truncates or rejects the payload. The margin leaves +// room for the rest of the request and the JSON encoding of the files. +const maxRunnerMigrationPayload = 5 << 20 + +// applyMigrationsViaRunner applies pending migrations through the deployed +// maintenance runner, returning whether it handled the operation. +// +// A database on a private network cannot be reached from the operator's machine, +// which is the whole reason the runner exists. The CLI moves the operation rather +// than the connection. When there is no runner, this reports that it did nothing +// and the caller falls back to connecting directly, except under --via runner, +// where being unable to use it is the error. +func applyMigrationsViaRunner( + ctx context.Context, + out io.Writer, + instance *state.InstanceState, + deployTarget string, + resource sqlschema.DatabaseResource, + via string, + maxRisk sqlschema.RiskLevel, + confirm func() error, +) (bool, error) { + if via == viaDirect { + return false, nil + } + + invoker, err := maintenancerunner.InvokerFor(deployTarget) + if err != nil { + if via == viaRunner { + return false, err + } + return false, nil + } + if !invoker.Deployed(instance) { + if via == viaRunner { + return false, fmt.Errorf( + "--via runner was requested but this instance has no deployed maintenance runner") + } + return false, nil + } + + files, err := readMigrationDir(resource.MigrationsPath) + if err != nil { + return false, err + } + if len(files) == 0 { + fmt.Fprintf(out, "No migration files for %s.\n", resource.ResourceName) + return true, nil + } + + // What is pending can only be known by the side that can reach the database, + // so unlike the direct path there is no list to show before confirming. The + // report afterwards names exactly what ran. + fmt.Fprintf(out, + "Applying migrations for %s through the maintenance runner (risk up to: %s).\n", + resource.ResourceName, maxRisk) + if confirm != nil { + if err := confirm(); err != nil { + return false, err + } + } + + resp, err := invoker.Invoke(ctx, instance, maintenancerunner.Request{ + Operation: maintenancerunner.OpApply, + Database: resource.ResourceName, + Migrations: files, + MaxRisk: string(maxRisk), + }) + if err != nil { + return false, err + } + if !resp.OK { + return false, fmt.Errorf("applying migrations for %s: %s", resource.ResourceName, resp.Error) + } + + renderRunnerApplyReport(out, resource.ResourceName, resp.Apply) + return true, nil +} + +// renderRunnerApplyReport prints what the runner did, in the same terms the +// local path uses. +func renderRunnerApplyReport(out io.Writer, resourceName string, report *maintenancerunner.ApplyReport) { + if report == nil || (len(report.Applied) == 0 && len(report.Blocked) == 0) { + fmt.Fprintf(out, "No pending migrations for %s.\n", resourceName) + return + } + + for _, name := range report.Applied { + fmt.Fprintf(out, " - %s applied\n", name) + } + for _, blocked := range report.Blocked { + fmt.Fprintf(out, " - %s held back [risk: %s]\n", blocked.Name, blocked.Risk) + } + + if len(report.Applied) > 0 { + fmt.Fprintf(out, "Applied %d migration(s) for %s.\n", len(report.Applied), resourceName) + } + if len(report.Blocked) > 0 { + fmt.Fprintf(out, + "%d migration(s) were held back by their risk level; re-run with --allow-risky or --allow-breaking once understood.\n", + len(report.Blocked)) + } +} + +// readMigrationDir reads the migration files to send to the runner. +// +// Only the top level is read, and only the files a migration directory is made +// of, which are the .sql migrations and atlas.sum. Sending anything else would +// put files on the runner that the migration machinery does not expect, and the +// checksum covers exactly this set. +func readMigrationDir(dir string) ([]maintenancerunner.MigrationFile, error) { + entries, err := os.ReadDir(dir) + if err != nil { + return nil, fmt.Errorf("reading the migration directory %s: %w", dir, err) + } + + files := make([]maintenancerunner.MigrationFile, 0, len(entries)) + total := 0 + for _, entry := range entries { + if entry.IsDir() || !isMigrationDirFile(entry.Name()) { + continue + } + content, err := os.ReadFile(filepath.Join(dir, entry.Name())) + if err != nil { + return nil, fmt.Errorf("reading migration %s: %w", entry.Name(), err) + } + total += len(content) + if total > maxRunnerMigrationPayload { + return nil, fmt.Errorf( + "the migration directory is larger than %dMB, which is more than one runner invocation can carry; "+ + "apply the older migrations from inside the network, or squash them", + maxRunnerMigrationPayload>>20) + } + files = append(files, maintenancerunner.MigrationFile{ + Name: entry.Name(), + Content: string(content), + }) + } + + // Sorted so the payload is stable between runs, which makes two invocations + // of the same directory comparable in a log. + sort.Slice(files, func(i, j int) bool { return files[i].Name < files[j].Name }) + return files, nil +} + +func isMigrationDirFile(name string) bool { + return strings.HasSuffix(name, ".sql") || name == "atlas.sum" +} diff --git a/apps/cli/cmd/commands/schema_codegen.go b/apps/cli/cmd/commands/schema_codegen.go new file mode 100644 index 00000000..bf05dbdd --- /dev/null +++ b/apps/cli/cmd/commands/schema_codegen.go @@ -0,0 +1,129 @@ +package commands + +import ( + "fmt" + "io" + "os" + "path/filepath" + + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "github.com/spf13/cobra" +) + +func setupSchemaCodegenCommand(schemaCmd *cobra.Command) { + codegenCmd := &cobra.Command{ + Use: "codegen", + Short: "Generate type-safe code from schema definitions", + Long: `Generate row types and column/table constants from the schema YAML of every +celerity/sqlDatabase resource, written into the --out directory (one file per +database). There is no ORM coupling, so the types combine with any library. + +Supported languages (v0): typescript (interfaces + constants), python (Pydantic +models). + +In --check mode nothing is written; the command exits non-zero if the generated +code on disk is out of date, so it can gate CI. + +Examples: + celerity schema codegen --lang typescript --out ./src/generated + celerity schema codegen --lang python --out ./src/generated + celerity schema codegen --lang typescript --out ./src/generated --check`, + RunE: func(cmd *cobra.Command, args []string) error { + langFlag, _ := cmd.Flags().GetString("lang") + out, _ := cmd.Flags().GetString("out") + check, _ := cmd.Flags().GetBool("check") + + lang := sqlschema.CodegenLanguage(langFlag) + if lang != sqlschema.LangTypeScript && lang != sqlschema.LangPython { + return fmt.Errorf("--lang must be one of: typescript, python") + } + if out == "" { + return fmt.Errorf("--out is required (the directory to write generated code into)") + } + + resources, err := loadDatabaseResources(cmd) + if err != nil { + return err + } + + stdout := cmd.OutOrStdout() + var stale []string + for _, r := range resources { + file, err := generateResourceCode(r, lang) + if err != nil { + return err + } + target := filepath.Join(out, file.Name) + + if check { + fresh, err := codegenUpToDate(target, file.Content) + if err != nil { + return err + } + if !fresh { + stale = append(stale, target) + } + continue + } + + if err := writeGeneratedFile(target, file.Content); err != nil { + return err + } + fmt.Fprintf(stdout, "Generated %s\n", target) + } + + if check { + return reportCodegenCheck(stdout, stale) + } + return nil + }, + } + + codegenCmd.Flags().String("lang", "", "Target language: typescript or python.") + codegenCmd.Flags().String("out", "", "Directory to write generated code into (required).") + codegenCmd.Flags().Bool("check", false, "Do not write; exit non-zero if generated code is out of date (CI gate).") + schemaCmd.AddCommand(codegenCmd) +} + +func generateResourceCode(r sqlschema.DatabaseResource, lang sqlschema.CodegenLanguage) (*sqlschema.GeneratedFile, error) { + if r.SchemaPath == "" { + return nil, fmt.Errorf("resource %q has no schemaPath configured", r.ResourceName) + } + parsed, err := sqlschema.ParseSchemaFile(r.SchemaPath) + if err != nil { + return nil, fmt.Errorf("parsing schema for %s: %w", r.ResourceName, err) + } + return sqlschema.GenerateCode(parsed, lang, r.ResourceName) +} + +func writeGeneratedFile(target, content string) error { + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return fmt.Errorf("creating output directory: %w", err) + } + if err := os.WriteFile(target, []byte(content), 0o644); err != nil { + return fmt.Errorf("writing %s: %w", target, err) + } + return nil +} + +func codegenUpToDate(target, content string) (bool, error) { + existing, err := os.ReadFile(target) + if err != nil { + if os.IsNotExist(err) { + return false, nil + } + return false, fmt.Errorf("reading %s: %w", target, err) + } + return string(existing) == content, nil +} + +func reportCodegenCheck(out io.Writer, stale []string) error { + if len(stale) > 0 { + for _, path := range stale { + fmt.Fprintf(out, "✗ %s is out of date\n", path) + } + return fmt.Errorf("%d generated file(s) out of date; run `celerity schema codegen` and commit the result", len(stale)) + } + fmt.Fprintln(out, "Generated code is up to date.") + return nil +} diff --git a/apps/cli/cmd/commands/schema_devdb.go b/apps/cli/cmd/commands/schema_devdb.go new file mode 100644 index 00000000..2372ac07 --- /dev/null +++ b/apps/cli/cmd/commands/schema_devdb.go @@ -0,0 +1,120 @@ +package commands + +import ( + "context" + "database/sql" + "fmt" + "net" + "time" + + _ "github.com/jackc/pgx/v5/stdlib" + "github.com/newstack-cloud/celerity/apps/cli/internal/docker" + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "go.uber.org/zap" +) + +const ( + devPostgresImage = "postgres:17-alpine" + devPostgresContainer = "celerity-schema-devdb" + devPostgresUser = "celerity" + devPostgresPassword = "celerity" + devPostgresDatabase = "celerity_devdb" +) + +// Starts a throwaway PostgreSQL container for the Atlas migration planner to +// replay the migration directory into, and returns its connection string plus a +// cleanup function that removes the container. +// +// Used by the commands that need a dev database when no --dev-url is supplied. +func provisionDevPostgres(ctx context.Context, logger *zap.Logger) (string, func(), error) { + mgr, err := docker.NewRuntimeContainer(logger) + if err != nil { + return "", nil, fmt.Errorf("creating docker client: %w", err) + } + if err := mgr.CheckAvailability(ctx); err != nil { + return "", nil, fmt.Errorf("docker is required for `schema diff` (or pass --dev-url): %w", err) + } + + // Clean up any container left behind by a previous interrupted run. + _ = mgr.CleanupStale(ctx, devPostgresContainer) + + // EnsureImage closes the progress channel itself (defer close), so it is + // only drained here. Closing it again would panic. + progress := make(chan docker.ImagePullProgress) + go func() { + for range progress { // drain + } + }() + if err := mgr.EnsureImage(ctx, devPostgresImage, progress); err != nil { + return "", nil, fmt.Errorf("pulling %s: %w", devPostgresImage, err) + } + + hostPort, err := freePort() + if err != nil { + return "", nil, err + } + + id, err := mgr.CreateAndStart(ctx, &docker.ContainerConfig{ + Image: devPostgresImage, + ContainerName: devPostgresContainer, + HostPort: hostPort, + ContainerPort: "5432", + EnvVars: map[string]string{ + "POSTGRES_USER": devPostgresUser, + "POSTGRES_PASSWORD": devPostgresPassword, + "POSTGRES_DB": devPostgresDatabase, + }, + }) + if err != nil { + return "", nil, err + } + + cleanup := func() { _ = mgr.Stop(context.WithoutCancel(ctx), id) } + + connStr := sqlschema.FormatConnectionString( + "localhost", hostPort, devPostgresUser, devPostgresPassword, devPostgresDatabase, + ) + if err := waitForPostgres(ctx, connStr, 30*time.Second); err != nil { + cleanup() + return "", nil, fmt.Errorf("dev database did not become ready: %w", err) + } + + return connStr, cleanup, nil +} + +// Polls until the database accepts connections or the timeout elapses. +func waitForPostgres(ctx context.Context, connStr string, timeout time.Duration) error { + db, err := sql.Open("pgx", connStr) + if err != nil { + return err + } + defer db.Close() + + deadline := time.Now().Add(timeout) + for { + if err := db.PingContext(ctx); err == nil { + return nil + } + if time.Now().After(deadline) { + return fmt.Errorf("timed out after %s", timeout) + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(500 * time.Millisecond): + } + } +} + +func freePort() (string, error) { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + return "", fmt.Errorf("finding a free port: %w", err) + } + defer l.Close() + _, port, err := net.SplitHostPort(l.Addr().String()) + if err != nil { + return "", err + } + return port, nil +} diff --git a/apps/cli/cmd/commands/schema_diff.go b/apps/cli/cmd/commands/schema_diff.go new file mode 100644 index 00000000..2c588c11 --- /dev/null +++ b/apps/cli/cmd/commands/schema_diff.go @@ -0,0 +1,118 @@ +package commands + +import ( + "fmt" + + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "github.com/spf13/cobra" + "go.uber.org/zap" +) + +func setupSchemaDiffCommand(schemaCmd *cobra.Command) { + diffCmd := &cobra.Command{ + Use: "diff", + Short: "Generate a migration file from schema YAML changes", + Long: `Compute the difference between the schema YAML (desired state) and the current +state, which is obtained by replaying the existing migration directory on a temporary +dev database, and then writing it as a new timestamped migration file. + +By default a throwaway PostgreSQL container is started for the replay (requires +Docker). Pass --dev-url to use an existing empty database instead. + +In --check mode, no migration is written; the command instead exits non-zero if +a migration *would* be generated. Use it in CI to prove the committed migrations +are complete for the committed schema (the counterpart to committing migration +files and atlas.sum alongside the schema change). + +Examples: + celerity schema diff --name add_customer_tier + celerity schema diff --check + celerity schema diff --dev-url postgres://user:pass@localhost:5432/dev?sslmode=disable`, + RunE: func(cmd *cobra.Command, args []string) error { + name, _ := cmd.Flags().GetString("name") + devURL, _ := cmd.Flags().GetString("dev-url") + check, _ := cmd.Flags().GetBool("check") + + resource, err := resolveDatabaseResource(cmd) + if err != nil { + return err + } + if resource.SchemaPath == "" { + return fmt.Errorf("resource %q has no schemaPath configured", resource.ResourceName) + } + if resource.MigrationsPath == "" { + return fmt.Errorf("resource %q has no migrationsPath configured", resource.ResourceName) + } + + ctx := cmd.Context() + out := cmd.OutOrStdout() + + if devURL == "" { + fmt.Fprintln(out, "Starting dev database for schema replay...") + url, cleanup, err := provisionDevPostgres(ctx, zap.NewNop()) + if err != nil { + return err + } + defer cleanup() + devURL = url + } + + // The tables the pending change touches, and any schema contracts + // they affect. Computed before generating, so the migration + // directory does not yet include the new migration. + changed, err := sqlschema.ChangedTables(ctx, devURL, resource.SchemaPath, resource.MigrationsPath, resource.Engine) + if err != nil { + return err + } + impacts, err := evaluateResourceContracts(cmd, resource, changed) + if err != nil { + return err + } + + if check { + pending, err := sqlschema.CheckPendingMigration( + ctx, devURL, resource.SchemaPath, resource.MigrationsPath, resource.Engine, + ) + if err != nil { + return err + } + if pending { + sqlschema.RenderContractImpacts(out, impacts) + return fmt.Errorf( + "schema for %q has changes with no committed migration; run `celerity schema diff` and commit the generated file and atlas.sum", + resource.ResourceName) + } + fmt.Fprintf(out, "%s: migrations are up to date with the schema.\n", resource.ResourceName) + return nil + } + + path, err := sqlschema.GenerateMigration( + ctx, devURL, resource.SchemaPath, resource.MigrationsPath, resource.Engine, name, + ) + if err != nil { + return err + } + if path == "" { + fmt.Fprintf(out, "No schema changes for %s, so no migration was generated.\n", resource.ResourceName) + return nil + } + risk, _ := sqlschema.ReadMigrationRisk(path) + fmt.Fprintf(out, "Generated %s [risk: %s]\n", path, risk) + if risk != sqlschema.RiskSafe { + fmt.Fprintf(out, "This migration is %s, so `schema apply` will not auto-apply it without --allow-%s.\n", risk, risk) + } + sqlschema.RenderContractImpacts(out, impacts) + fmt.Fprintln(out, "Review the file, then apply it with: celerity schema apply") + return nil + }, + } + + diffCmd.Flags().String("name", "", "Description used in the generated migration file name.") + diffCmd.Flags().String( + "dev-url", "", + "Connection string for an empty dev database to replay migrations into "+ + "(default: start a throwaway container).", + ) + diffCmd.Flags().Bool("check", false, "Do not write; exit non-zero if a migration would be generated (CI completeness gate).") + schemaCmd.AddCommand(diffCmd) +} diff --git a/apps/cli/cmd/commands/schema_drift.go b/apps/cli/cmd/commands/schema_drift.go new file mode 100644 index 00000000..1f0e999f --- /dev/null +++ b/apps/cli/cmd/commands/schema_drift.go @@ -0,0 +1,123 @@ +package commands + +import ( + "fmt" + + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/spf13/cobra" + "go.uber.org/zap" +) + +func setupSchemaDriftCommand(schemaCmd *cobra.Command, confProvider *config.Provider) { + driftCmd := &cobra.Command{ + Use: "drift", + Short: "Check a live database for out-of-band changes", + Long: `Check a live database against the state its committed migrations should have +produced, at three layers: + + History the atlas_schema_revisions table vs the migration directory + (migrations applied out-of-band, missing, or applied out of order) + Structural live tables/columns/indexes/keys/constraints vs the expected state + Advanced triggers, functions, views and RLS policies fingerprinted from the + catalog (created / changed / missing out-of-band) + +Choose the target database with one of: + --url an explicit connection string + --instance-name a deployed blueprint instance (connection resolved from state) + +Structural and advanced-object drift are reconstructed by replaying the applied +migrations into a temporary dev database (a throwaway container by default, or +--dev-url). Pass --history-only to skip that and check history drift alone (no +Docker or dev database required). + +The command exits non-zero when drift is found, so it can run as a scheduled CI +job for continuous checking. + +Examples: + celerity schema drift --instance-name production-orders + celerity schema drift --url postgres://user:pass@localhost:5432/orders?sslmode=disable + celerity schema drift --instance-name production-orders --history-only`, + RunE: func(cmd *cobra.Command, args []string) error { + url, _ := cmd.Flags().GetString("url") + instanceName, _ := cmd.Flags().GetString("instance-name") + devURL, _ := cmd.Flags().GetString("dev-url") + historyOnly, _ := cmd.Flags().GetBool("history-only") + + if url == "" && instanceName == "" { + return fmt.Errorf("provide a target database with --url or --instance-name") + } + if url != "" && instanceName != "" { + return fmt.Errorf("--url and --instance-name are mutually exclusive") + } + + resource, err := resolveDatabaseResource(cmd) + if err != nil { + return err + } + if resource.MigrationsPath == "" { + return fmt.Errorf("resource %q has no migrationsPath configured", resource.ResourceName) + } + + ctx := cmd.Context() + out := cmd.OutOrStdout() + + target := "url" + if url == "" { + resolved, err := resolveDeployedConnection(ctx, confProvider, resource, instanceName) + if err != nil { + return err + } + target = resolved.Target + url = resolved.ConnectionString + } + + devConn := devURL + if !historyOnly && devConn == "" { + fmt.Fprintln(out, "Starting dev database for drift comparison...") + u, cleanup, err := provisionDevPostgres(ctx, zap.NewNop()) + if err != nil { + return err + } + defer cleanup() + devConn = u + } + if historyOnly { + devConn = "" + } + + applier, err := sqlschema.NewApplier(resource.Engine, url, zap.NewNop()) + if err != nil { + return err + } + defer applier.Close() + + report, err := sqlschema.DetectDrift(ctx, applier, devConn, resource.MigrationsPath, resource.Engine) + if err != nil { + return err + } + report.Resource = resource.ResourceName + report.Target = target + report.Contracts, err = evaluateResourceContracts(cmd, resource, report.StructuralTables) + if err != nil { + return err + } + report.Render(out) + + if report.HasDrift() { + return fmt.Errorf("drift detected for %s", resource.ResourceName) + } + return nil + }, + } + + driftCmd.Flags().String("url", "", "Connection string of the target database.") + driftCmd.Flags().String("instance-name", "", "Deployed blueprint instance whose database to check.") + driftCmd.Flags().String( + "dev-url", "", + "Connection string for an empty dev database used to reconstruct the expected "+ + "state (default: start a throwaway container).", + ) + driftCmd.Flags().Bool("history-only", false, "Only check history drift (no dev database or Docker required).") + schemaCmd.AddCommand(driftCmd) +} diff --git a/apps/cli/cmd/commands/schema_export.go b/apps/cli/cmd/commands/schema_export.go new file mode 100644 index 00000000..d5568d17 --- /dev/null +++ b/apps/cli/cmd/commands/schema_export.go @@ -0,0 +1,73 @@ +package commands + +import ( + "fmt" + "os" + + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "github.com/spf13/cobra" +) + +func setupSchemaExportCommand(schemaCmd *cobra.Command) { + exportCmd := &cobra.Command{ + Use: "export", + Short: "Export a schema as SQL DDL, markdown, JSON Schema or Mermaid ERD", + Long: `Render a celerity/sqlDatabase resource's schema in a data-team-friendly format. +The export is derived from the schema YAML, so no database connection is needed. + +Formats: + sql CREATE TABLE / INDEX DDL + markdown human-readable tables (columns, keys, classification, descriptions) + json-schema a JSON Schema document (one object definition per table) + mermaid a Mermaid erDiagram of tables and relationships + +Writes to stdout by default, or to --out. + +Examples: + celerity schema export --format markdown + celerity schema export --format mermaid --out ./docs/orders-erd.mmd + celerity schema export --format json-schema --out ./schema.json`, + RunE: func(cmd *cobra.Command, args []string) error { + formatFlag, _ := cmd.Flags().GetString("format") + out, _ := cmd.Flags().GetString("out") + + format := sqlschema.ExportFormat(formatFlag) + switch format { + case sqlschema.ExportSQL, sqlschema.ExportMarkdown, sqlschema.ExportJSONSchema, sqlschema.ExportMermaid: + default: + return fmt.Errorf("--format must be one of: sql, markdown, json-schema, mermaid") + } + + resource, err := resolveDatabaseResource(cmd) + if err != nil { + return err + } + if resource.SchemaPath == "" { + return fmt.Errorf("resource %q has no schemaPath configured", resource.ResourceName) + } + + parsed, err := sqlschema.ParseSchemaFile(resource.SchemaPath) + if err != nil { + return fmt.Errorf("parsing schema: %w", err) + } + content, err := sqlschema.ExportSchema(parsed, format, resource.ResourceName) + if err != nil { + return err + } + + if out == "" { + fmt.Fprint(cmd.OutOrStdout(), content) + return nil + } + if err := os.WriteFile(out, []byte(content), 0o644); err != nil { + return fmt.Errorf("writing %s: %w", out, err) + } + fmt.Fprintf(cmd.OutOrStdout(), "Exported %s (%s) to %s\n", resource.ResourceName, format, out) + return nil + }, + } + + exportCmd.Flags().String("format", "", "Output format: sql, markdown, json-schema or mermaid.") + exportCmd.Flags().String("out", "", "File to write the export to (default: stdout).") + schemaCmd.AddCommand(exportCmd) +} diff --git a/apps/cli/cmd/commands/schema_hash.go b/apps/cli/cmd/commands/schema_hash.go new file mode 100644 index 00000000..4c65c9fc --- /dev/null +++ b/apps/cli/cmd/commands/schema_hash.go @@ -0,0 +1,46 @@ +package commands + +import ( + "fmt" + + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "github.com/spf13/cobra" +) + +func setupSchemaHashCommand(schemaCmd *cobra.Command) { + hashCmd := &cobra.Command{ + Use: "hash", + Short: "Recompute the migration directory integrity file", + Long: `Recompute atlas.sum from the migration files currently on disk. + +Run this after editing a migration file by hand, typically the empty file that +` + "`celerity schema new`" + ` created, so the integrity file matches its +contents again. Every other command treats a mismatch as an error, because on a +migration that has already been applied it means the recorded history no longer +matches what actually ran. + +Only re-hash migrations that have not been applied anywhere. Editing an applied +migration and re-hashing hides the divergence rather than fixing it; add a new +forward migration instead. + +Example: + celerity schema hash`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + resource, err := resolveDatabaseResource(cmd) + if err != nil { + return err + } + if resource.MigrationsPath == "" { + return fmt.Errorf("resource %q has no migrationsPath configured", resource.ResourceName) + } + + if err := sqlschema.RehashMigrationDir(resource.MigrationsPath); err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "Updated %s/atlas.sum\n", resource.MigrationsPath) + return nil + }, + } + schemaCmd.AddCommand(hashCmd) +} diff --git a/apps/cli/cmd/commands/schema_history.go b/apps/cli/cmd/commands/schema_history.go new file mode 100644 index 00000000..2d160ad2 --- /dev/null +++ b/apps/cli/cmd/commands/schema_history.go @@ -0,0 +1,56 @@ +package commands + +import ( + "fmt" + + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/spf13/cobra" + "go.uber.org/zap" +) + +func setupSchemaHistoryCommand(schemaCmd *cobra.Command, confProvider *config.Provider) { + historyCmd := &cobra.Command{ + Use: "history", + Short: "Show the applied migration history of a database", + Long: `List the migrations applied to a database, in order, from its +atlas_schema_revisions table. + +Choose the target database with --url or --instance-name (a deployed instance, +resolved from its state). + +Examples: + celerity schema history --instance-name production-orders + celerity schema history --url postgres://user:pass@localhost:5432/orders?sslmode=disable`, + RunE: func(cmd *cobra.Command, args []string) error { + resource, err := resolveDatabaseResource(cmd) + if err != nil { + return err + } + url, target, err := resolveTargetConnection(cmd, confProvider, resource) + if err != nil { + return err + } + + applier, err := sqlschema.NewApplier(resource.Engine, url, zap.NewNop()) + if err != nil { + return err + } + defer applier.Close() + + records, err := sqlschema.ReadMigrationHistory(cmd.Context(), applier) + if err != nil { + return err + } + + out := cmd.OutOrStdout() + fmt.Fprintf(out, "Migration history for %s (%s)\n\n", resource.ResourceName, target) + sqlschema.RenderMigrationHistory(out, records) + return nil + }, + } + + historyCmd.Flags().String("url", "", "Connection string of the target database.") + historyCmd.Flags().String("instance-name", "", "Deployed blueprint instance whose database to read.") + schemaCmd.AddCommand(historyCmd) +} diff --git a/apps/cli/cmd/commands/schema_new.go b/apps/cli/cmd/commands/schema_new.go new file mode 100644 index 00000000..3cfeb94f --- /dev/null +++ b/apps/cli/cmd/commands/schema_new.go @@ -0,0 +1,41 @@ +package commands + +import ( + "fmt" + + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "github.com/spf13/cobra" +) + +func setupSchemaNewCommand(schemaCmd *cobra.Command) { + newCmd := &cobra.Command{ + Use: "new ", + Short: "Create an empty migration file for hand-written SQL", + Long: `Create an empty, timestamped migration file in the resource's migrationsPath +and update the atlas.sum integrity file. + +Use this for structural SQL the schema YAML cannot express, such as triggers, +functions, stored procedures, partitioning and row-level security policies. + +Example: + celerity schema new add_audit_trigger`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + resource, err := resolveDatabaseResource(cmd) + if err != nil { + return err + } + if resource.MigrationsPath == "" { + return fmt.Errorf("resource %q has no migrationsPath configured", resource.ResourceName) + } + + path, err := sqlschema.ScaffoldMigration(resource.MigrationsPath, args[0]) + if err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "Created %s\n", path) + return nil + }, + } + schemaCmd.AddCommand(newCmd) +} diff --git a/apps/cli/cmd/commands/schema_provision.go b/apps/cli/cmd/commands/schema_provision.go new file mode 100644 index 00000000..9b4ff973 --- /dev/null +++ b/apps/cli/cmd/commands/schema_provision.go @@ -0,0 +1,204 @@ +package commands + +import ( + "context" + "fmt" + "io" + "strings" + "time" + + "github.com/newstack-cloud/bluelink/libs/blueprint/state" + "github.com/newstack-cloud/celerity/apps/cli/internal/maintenancerunner" + + // Registers the AWS maintenance runner invoker. Providers are wired in here + // rather than in the maintenancerunner package so it stays cloud-neutral. + _ "github.com/newstack-cloud/celerity/apps/cli/internal/maintenancerunner/awsrunner" +) + +// provisionAppUser makes sure the application's database role exists before +// migrations run. +// +// It runs on every apply rather than once, because it is idempotent and cheap +// and the alternative is a class of failure nobody can diagnose. A database that +// was restored from a snapshot, replaced, or deployed before this existed has an +// application credential that authenticates as nobody, and the symptom is every +// handler failing to connect long after the deploy reported success. +// +// A missing runner is not an error. An instance whose database is reachable +// without one, or one deployed before runners existed, still migrates. It +// provisions nothing and reports as much. +func provisionAppUser( + ctx context.Context, + out io.Writer, + instance *state.InstanceState, + deployTarget string, + sqlDatabaseName string, + via string, +) error { + invoker, err := maintenancerunner.InvokerFor(deployTarget) + if err != nil { + if via == viaRunner { + return err + } + return nil + } + + if !invoker.Deployed(instance) { + if via == viaRunner { + return fmt.Errorf( + "--via runner was requested but this instance has no deployed maintenance runner") + } + return nil + } + + if err := waitForDatabaseReady(ctx, out, invoker, instance, sqlDatabaseName); err != nil { + return err + } + + fmt.Fprintf(out, "Checking the application database user on %s...\n", sqlDatabaseName) + + resp, err := invoker.Invoke(ctx, instance, maintenancerunner.Request{ + Operation: maintenancerunner.OpProvisionUser, + Database: sqlDatabaseName, + }) + if err != nil { + return err + } + if !resp.OK { + return fmt.Errorf("provisioning the application database user: %s", resp.Error) + } + + if resp.Provision.Changed() { + resp.Provision.Render(out) + } else { + fmt.Fprintf(out, " Application user %q is already provisioned.\n", resp.Provision.User) + } + return nil +} + +// How a maintenance operation reaches the database. +const ( + // viaAuto uses the runner when the instance has one, and connects directly + // otherwise. The default, and right for nearly everyone. + viaAuto = "auto" + + // viaRunner insists on the runner, and fails when there is none. Useful in + // CI, where silently falling back to a direct connection that then times out + // is a worse failure than saying so. + viaRunner = "runner" + + // viaDirect ignores any runner and connects from here. + viaDirect = "direct" +) + +func validateVia(via string) error { + switch via { + case viaAuto, viaRunner, viaDirect: + return nil + default: + return fmt.Errorf("invalid --via %q (expected %s, %s or %s)", + via, viaAuto, viaRunner, viaDirect) + } +} + +// How long to wait for a database to start accepting connections, and how often +// to ask. +// +// A connection pool provisioned moments earlier is the case this exists for. An +// AWS RDS proxy reports itself available while its target is still +// PENDING_PROXY_CAPACITY, and connections through it fail with a TLS error that +// mentions nothing about capacity. Five minutes covers the scaling seen in +// practice, which is two to three. +// +// These are variables rather than constants so tests can drive the loop without +// waiting on real time. Nothing outside tests reassigns them. +var ( + databaseReadyTimeout = 5 * time.Minute + databaseReadyPollInterval = 15 * time.Second +) + +// waitForDatabaseReady blocks until the runner can reach and authenticate to the +// database, or the wait is exhausted. +// +// Running `celerity schema apply` straight after a deploy is the normal thing to +// do, and it failed against a database whose connection pool had not finished +// scaling. That reads as a broken deployment rather than as one that is not +// ready yet, so the wait exists to tell the two apart. +// +// The check is the runner's own ping, which connects exactly as the operations +// that follow do. Anything waiting cannot fix, such as a missing target or an +// unreadable credential, fails on the first attempt rather than being retried +// for five minutes. +func waitForDatabaseReady( + ctx context.Context, + out io.Writer, + invoker maintenancerunner.Invoker, + instance *state.InstanceState, + sqlDatabaseName string, +) error { + deadline := time.Now().Add(databaseReadyTimeout) + announced := false + + for attempt := 1; ; attempt++ { + resp, err := invoker.Invoke(ctx, instance, maintenancerunner.Request{ + Operation: maintenancerunner.OpPing, + Database: sqlDatabaseName, + }) + if err != nil { + return err + } + if resp.OK { + if announced { + fmt.Fprintf(out, " %s is accepting connections.\n", sqlDatabaseName) + } + return nil + } + + if !isDatabaseNotReadyYet(resp.Error) { + return fmt.Errorf("reaching %s: %s", sqlDatabaseName, resp.Error) + } + if time.Now().After(deadline) { + return fmt.Errorf( + "%s did not start accepting connections within %s; the last attempt reported: %s", + sqlDatabaseName, databaseReadyTimeout, resp.Error) + } + + if !announced { + fmt.Fprintf(out, + "Waiting for %s to accept connections (a connection pool provisioned with the deployment can take a few minutes to scale)...\n", + sqlDatabaseName) + announced = true + } + + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(databaseReadyPollInterval): + } + } +} + +// isDatabaseNotReadyYet reports whether a failure to reach the database is one +// that waiting can resolve. +// +// A pool that is still scaling refuses the connection at the TLS layer, so the +// error names neither capacity nor readiness; matching the shape of the failure +// is the only signal available. A credential or configuration problem produces a +// different error and is not retried, because waiting cannot fix it. +func isDatabaseNotReadyYet(message string) bool { + lowered := strings.ToLower(message) + for _, fragment := range []string{ + "tls error", + "eof", + "connection refused", + "connection reset", + "i/o timeout", + "dial tcp", + "no such host", + } { + if strings.Contains(lowered, fragment) { + return true + } + } + return false +} diff --git a/apps/cli/cmd/commands/schema_provision_wait_test.go b/apps/cli/cmd/commands/schema_provision_wait_test.go new file mode 100644 index 00000000..c1cc67b9 --- /dev/null +++ b/apps/cli/cmd/commands/schema_provision_wait_test.go @@ -0,0 +1,115 @@ +package commands + +import ( + "bytes" + "context" + "errors" + "testing" + "time" + + "github.com/newstack-cloud/bluelink/libs/blueprint/state" + "github.com/newstack-cloud/celerity/apps/cli/internal/maintenancerunner" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Replays a scripted sequence of responses, so a test can describe a database +// that is not ready and then becomes ready. +type scriptedInvoker struct { + responses []*maintenancerunner.Response + err error + requests []maintenancerunner.Request +} + +func (s *scriptedInvoker) Invoke( + _ context.Context, + _ *state.InstanceState, + req maintenancerunner.Request, +) (*maintenancerunner.Response, error) { + s.requests = append(s.requests, req) + if s.err != nil { + return nil, s.err + } + next := s.responses[0] + if len(s.responses) > 1 { + s.responses = s.responses[1:] + } + return next, nil +} + +func (s *scriptedInvoker) Deployed(_ *state.InstanceState) bool { return true } + +func notReady(message string) *maintenancerunner.Response { + return &maintenancerunner.Response{Operation: maintenancerunner.OpPing, OK: false, Error: message} +} + +func ready() *maintenancerunner.Response { + return &maintenancerunner.Response{Operation: maintenancerunner.OpPing, OK: true} +} + +func withFastReadyPolling(t *testing.T) { + t.Helper() + previous := databaseReadyPollInterval + databaseReadyPollInterval = time.Millisecond + t.Cleanup(func() { databaseReadyPollInterval = previous }) +} + +// A connection pool provisioned with the deployment reports itself available +// while it is still scaling, and connections through it fail at the TLS layer. +// Running schema apply straight after a deploy is the normal thing to do, so +// this waits rather than reporting a broken deployment. +func TestWaitsForAConnectionPoolThatIsStillScaling(t *testing.T) { + withFastReadyPolling(t) + invoker := &scriptedInvoker{responses: []*maintenancerunner.Response{ + notReady("pinging postgres: tls error: EOF"), + notReady("pinging postgres: tls error: EOF"), + ready(), + }} + out := &bytes.Buffer{} + + err := waitForDatabaseReady(context.Background(), out, invoker, &state.InstanceState{}, "ordersDb") + + require.NoError(t, err) + assert.Len(t, invoker.requests, 3) + assert.Contains(t, out.String(), "Waiting for ordersDb") + assert.Contains(t, out.String(), "accepting connections") +} + +// A database that answers immediately must not announce a wait that did not +// happen, which is the common case and should be silent. +func TestSaysNothingWhenTheDatabaseIsAlreadyReady(t *testing.T) { + withFastReadyPolling(t) + invoker := &scriptedInvoker{responses: []*maintenancerunner.Response{ready()}} + out := &bytes.Buffer{} + + err := waitForDatabaseReady(context.Background(), out, invoker, &state.InstanceState{}, "ordersDb") + + require.NoError(t, err) + assert.Len(t, invoker.requests, 1) + assert.Empty(t, out.String()) +} + +// Waiting cannot fix a credential or configuration problem, so it fails on the +// first attempt instead of retrying for five minutes and then saying the same +// thing. +func TestDoesNotWaitOutAFailureWaitingCannotFix(t *testing.T) { + withFastReadyPolling(t) + invoker := &scriptedInvoker{responses: []*maintenancerunner.Response{ + notReady("reading the database owner's credentials: access denied"), + }} + + err := waitForDatabaseReady(context.Background(), &bytes.Buffer{}, invoker, &state.InstanceState{}, "ordersDb") + + require.Error(t, err) + assert.Contains(t, err.Error(), "access denied") + assert.Len(t, invoker.requests, 1, "a failure waiting cannot fix must not be retried") +} + +func TestAnUnreachableRunnerIsReportedImmediately(t *testing.T) { + withFastReadyPolling(t) + invoker := &scriptedInvoker{err: errors.New("lambda: access denied")} + + err := waitForDatabaseReady(context.Background(), &bytes.Buffer{}, invoker, &state.InstanceState{}, "ordersDb") + + assert.ErrorContains(t, err, "lambda: access denied") +} diff --git a/apps/cli/cmd/commands/schema_show.go b/apps/cli/cmd/commands/schema_show.go new file mode 100644 index 00000000..ab5acf78 --- /dev/null +++ b/apps/cli/cmd/commands/schema_show.go @@ -0,0 +1,56 @@ +package commands + +import ( + "fmt" + + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "github.com/newstack-cloud/deploy-cli-sdk/config" + "github.com/spf13/cobra" + "go.uber.org/zap" +) + +func setupSchemaShowCommand(schemaCmd *cobra.Command, confProvider *config.Provider) { + showCmd := &cobra.Command{ + Use: "show", + Short: "Show the current schema of a deployed database", + Long: `Inspect a live database and print its current schema (tables, columns, keys) +as it actually exists, which is useful for confirming what is deployed. + +Choose the target database with --url or --instance-name (a deployed instance, +resolved from its state). + +Examples: + celerity schema show --instance-name production-orders + celerity schema show --url postgres://user:pass@localhost:5432/orders?sslmode=disable`, + RunE: func(cmd *cobra.Command, args []string) error { + resource, err := resolveDatabaseResource(cmd) + if err != nil { + return err + } + url, target, err := resolveTargetConnection(cmd, confProvider, resource) + if err != nil { + return err + } + + applier, err := sqlschema.NewApplier(resource.Engine, url, zap.NewNop()) + if err != nil { + return err + } + defer applier.Close() + + rendered, err := sqlschema.InspectCurrentSchema(cmd.Context(), applier) + if err != nil { + return err + } + + out := cmd.OutOrStdout() + fmt.Fprintf(out, "%s (%s)\n\n", resource.ResourceName, target) + fmt.Fprint(out, rendered) + return nil + }, + } + + showCmd.Flags().String("url", "", "Connection string of the target database.") + showCmd.Flags().String("instance-name", "", "Deployed blueprint instance whose database to read.") + schemaCmd.AddCommand(showCmd) +} diff --git a/apps/cli/cmd/commands/schema_validate.go b/apps/cli/cmd/commands/schema_validate.go new file mode 100644 index 00000000..7cfa3e2a --- /dev/null +++ b/apps/cli/cmd/commands/schema_validate.go @@ -0,0 +1,96 @@ +package commands + +import ( + "fmt" + "io" + + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "github.com/spf13/cobra" +) + +func setupSchemaValidateCommand(schemaCmd *cobra.Command) { + validateCmd := &cobra.Command{ + Use: "validate", + Short: "Validate schema files and migration integrity", + Long: `Validate every celerity/sqlDatabase resource in the blueprint: + + - the schema YAML parses + - foreign keys reference existing tables and columns + - column types are understood by the engine + - the migration directory's atlas.sum integrity file is present and matches + +This runs without a database connection, so it is suitable as a CI gate. + +Example: + celerity schema validate`, + RunE: func(cmd *cobra.Command, args []string) error { + if checkCodegen, _ := cmd.Flags().GetBool("check-codegen"); checkCodegen { + // Codegen freshness depends on the output directory and language, + // which validate is not given, so the freshness gate lives on + // the codegen command, which has --out and --lang. + return fmt.Errorf("check generated code with `celerity schema codegen --check --lang --out `") + } + + resources, err := loadDatabaseResources(cmd) + if err != nil { + return err + } + + out := cmd.OutOrStdout() + var problems int + for _, r := range resources { + problems += reportValidation(out, r.ResourceName, "schema", validateResourceSchema(r)) + problems += reportValidation(out, r.ResourceName, "migrations", sqlschema.ValidateMigrationDir(r.MigrationsPath)) + } + + problems += validateContracts(cmd, out, resources) + + if problems > 0 { + return fmt.Errorf("%d schema validation problem(s) found", problems) + } + fmt.Fprintf(out, "All %d SQL database schema(s) valid.\n", len(resources)) + return nil + }, + } + + validateCmd.Flags().Bool("check-codegen", false, "Verify generated code is up to date (points you to `schema codegen --check`).") + schemaCmd.AddCommand(validateCmd) +} + +// validateContracts checks the schema-contracts.yaml (if present) references only +// known databases and tables. It reports one line per contract file checked and +// returns the number of problems found. +func validateContracts(cmd *cobra.Command, out io.Writer, resources []sqlschema.DatabaseResource) int { + contracts, err := loadSchemaContracts(cmd) + if err != nil { + return reportValidation(out, sqlschema.ContractsFileName, "contracts", err) + } + if contracts == nil { + return 0 + } + + schemaProblems := sqlschema.ValidateContracts(contracts, resourceSchemas(resources)) + if len(schemaProblems) == 0 { + return reportValidation(out, sqlschema.ContractsFileName, "contracts", nil) + } + for _, p := range schemaProblems { + fmt.Fprintf(out, "✗ %s (contracts): %s\n", sqlschema.ContractsFileName, p) + } + return len(schemaProblems) +} + +func validateResourceSchema(r sqlschema.DatabaseResource) error { + if r.SchemaPath == "" { + return nil + } + return sqlschema.ValidateSchema(r.SchemaPath, r.Engine) +} + +func reportValidation(out io.Writer, resourceName, check string, err error) int { + if err != nil { + fmt.Fprintf(out, "✗ %s (%s): %v\n", resourceName, check, err) + return 1 + } + fmt.Fprintf(out, "✓ %s (%s)\n", resourceName, check) + return 0 +} diff --git a/apps/cli/cmd/maintenance-runner/main.go b/apps/cli/cmd/maintenance-runner/main.go new file mode 100644 index 00000000..9f419914 --- /dev/null +++ b/apps/cli/cmd/maintenance-runner/main.go @@ -0,0 +1,36 @@ +// Command maintenance-runner is the in-network half of Celerity's database +// maintenance path. +// +// It is deployed alongside a celerity/sqlDatabase, on the same private network, +// and performs operations the CLI cannot perform from outside it. +// +// The only platform-specific thing here is which host packages are linked in. +// Each registers itself, the runner serves on whichever one it detects at +// startup, and adding a platform means adding an import. +package main + +import ( + "fmt" + "os" + + "github.com/newstack-cloud/celerity/apps/cli/internal/maintenancerunner" + "go.uber.org/zap" + + // Host platforms. AWS runs the runner on Lambda, so its binary must be named + // bootstrap in the deployed archive. + _ "github.com/newstack-cloud/celerity/apps/cli/internal/maintenancerunner/awsrunner" +) + +func main() { + logger, err := zap.NewProduction() + if err != nil { + fmt.Fprintf(os.Stderr, "creating logger: %v\n", err) + os.Exit(1) + } + defer func() { _ = logger.Sync() }() + + if err := maintenancerunner.Run(logger); err != nil { + logger.Error("the maintenance runner could not start", zap.Error(err)) + os.Exit(1) + } +} diff --git a/apps/cli/internal/dbconn/awscreds/awscreds.go b/apps/cli/internal/dbconn/awscreds/awscreds.go new file mode 100644 index 00000000..ee276919 --- /dev/null +++ b/apps/cli/internal/dbconn/awscreds/awscreds.go @@ -0,0 +1,131 @@ +// Package awscreds resolves database credentials on AWS: Secrets Manager for +// stored credentials, RDS IAM for short-lived tokens. +// +// It is the AWS implementation of dbconn.CredentialSource. A provider added +// later supplies its own, and nothing above this line changes. +package awscreds + +import ( + "context" + "encoding/json" + "fmt" + "net" + "strings" + + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/feature/rds/auth" + "github.com/aws/aws-sdk-go-v2/service/secretsmanager" + "github.com/newstack-cloud/celerity/apps/cli/internal/dbconn" +) + +// Source resolves credentials from Secrets Manager and RDS IAM. +type Source struct{} + +// New returns the AWS credential source. +func New() *Source { return &Source{} } + +// Secret is the credential JSON in a Secrets Manager secret. +// +// RDS-managed secrets carry the full connection detail, where the secrets +// Celerity generates carry username and password only. Connection detail is +// parsed but treated as a fallback, because an endpoint derived from deployed +// state points at the proxy while the secret names the database behind it. +type Secret struct { + Username string `json:"username"` + Password string `json:"password"` + Host string `json:"host"` + Port json.Number `json:"port"` + DBName string `json:"dbname"` +} + +// Resolve reads a credential from Secrets Manager. The reference is a secret +// ARN or name. +func (s *Source) Resolve(ctx context.Context, reference string) (dbconn.Credentials, error) { + secret, err := FetchSecret(ctx, reference) + if err != nil { + return dbconn.Credentials{}, err + } + return dbconn.Credentials{Username: secret.Username, Password: secret.Password}, nil +} + +// Token builds a short-lived RDS IAM authentication token to use in place of a +// password. +func (s *Source) Token( + ctx context.Context, + endpoint dbconn.Endpoint, + user string, + region string, +) (dbconn.Credentials, error) { + if user == "" { + return dbconn.Credentials{}, fmt.Errorf( + "IAM authentication needs a database user, and none was resolved") + } + + opts := []func(*config.LoadOptions) error{} + if region != "" { + opts = append(opts, config.WithRegion(region)) + } + awsCfg, err := config.LoadDefaultConfig(ctx, opts...) + if err != nil { + return dbconn.Credentials{}, fmt.Errorf("loading AWS config: %w", err) + } + if region == "" { + region = awsCfg.Region + } + if region == "" { + return dbconn.Credentials{}, fmt.Errorf( + "could not determine an AWS region for IAM authentication") + } + + token, err := auth.BuildAuthToken( + ctx, net.JoinHostPort(endpoint.Host, endpoint.Port), region, user, awsCfg.Credentials) + if err != nil { + return dbconn.Credentials{}, fmt.Errorf("building RDS IAM auth token: %w", err) + } + return dbconn.Credentials{Username: user, Password: token}, nil +} + +// FetchSecret reads and parses a Secrets Manager secret, including the +// connection detail an RDS-managed secret carries. +// +// The region comes from the ARN so this works from a machine whose default +// region is somewhere else, which is the normal case for an operator with +// several environments. +func FetchSecret(ctx context.Context, secretARN string) (*Secret, error) { + opts := []func(*config.LoadOptions) error{} + if region := RegionFromARN(secretARN); region != "" { + opts = append(opts, config.WithRegion(region)) + } + awsCfg, err := config.LoadDefaultConfig(ctx, opts...) + if err != nil { + return nil, fmt.Errorf("loading AWS config: %w", err) + } + + client := secretsmanager.NewFromConfig(awsCfg) + out, err := client.GetSecretValue(ctx, &secretsmanager.GetSecretValueInput{SecretId: &secretARN}) + if err != nil { + return nil, fmt.Errorf("fetching secret %s: %w", secretARN, err) + } + if out.SecretString == nil { + return nil, fmt.Errorf("secret %s has no string value", secretARN) + } + + var secret Secret + if err := json.Unmarshal([]byte(*out.SecretString), &secret); err != nil { + return nil, fmt.Errorf("parsing secret %s value as JSON: %w", secretARN, err) + } + if secret.Username == "" || secret.Password == "" { + return nil, fmt.Errorf("secret %s is missing username/password", secretARN) + } + return &secret, nil +} + +// RegionFromARN extracts the region from an ARN +// (arn:aws:secretsmanager:::secret:). +func RegionFromARN(arn string) string { + parts := strings.Split(arn, ":") + if len(parts) < 4 { + return "" + } + return parts[3] +} diff --git a/apps/cli/internal/dbconn/dbconn.go b/apps/cli/internal/dbconn/dbconn.go new file mode 100644 index 00000000..69363baf --- /dev/null +++ b/apps/cli/internal/dbconn/dbconn.go @@ -0,0 +1,110 @@ +// Package dbconn turns an endpoint plus a resolved credential into a +// connection string for a SQL engine. +// +// It exists because two places need exactly this and must not drift: the CLI +// connecting directly to a reachable database, and the maintenance runner +// connecting from inside the network to one that is not. A difference between +// them, a missing sslmode or a MySQL DSN built like a URL, would show up only on +// deployed infrastructure, and only on one of the paths. +// +// Nothing here is cloud-specific. Where a credential comes from is a provider +// concern, behind the CredentialSource interface; the AWS implementation is in +// the awscreds sub-package. +package dbconn + +import ( + "context" + "fmt" + "net" + "net/url" + + gomysql "github.com/go-sql-driver/mysql" +) + +// Endpoint is where a database is and which database on it to open. +type Endpoint struct { + // Engine is "postgres" (the default when empty) or "mysql". + Engine string + + Host string + Port string + Database string + + // TLS requires an encrypted connection. Always true against a managed + // database, and false against a local container, so it is explicit rather + // than assumed. + TLS bool +} + +// Credentials are a resolved username and password. In token-based +// authentication (AWS IAM, GCP's IAM database authentication) the token takes +// the password's place. The wire protocol is the same either way, which is why +// there is one type here rather than two. +type Credentials struct { + Username string + Password string +} + +// CredentialSource resolves the credential a reference points at. +// +// A reference is whatever the provider's secret store calls one, be it an ARN, a +// projects/…/secrets/… resource name or a Key Vault URI, and it is opaque here. +// Implementations live per provider so this package, and everything built on it, +// stays cloud-neutral. +type CredentialSource interface { + // Resolve reads the credential a reference points at. + Resolve(ctx context.Context, reference string) (Credentials, error) + + // Token issues a short-lived database token for a user, for providers whose + // databases accept the platform's own identity in place of a password. It + // returns an error where the provider has no such mechanism. + Token(ctx context.Context, endpoint Endpoint, user string, region string) (Credentials, error) +} + +// URL builds a connection string for the endpoint's engine. +func URL(endpoint Endpoint, creds Credentials) (string, error) { + switch endpoint.Engine { + case "postgres", "": + return postgresURL(endpoint, creds), nil + case "mysql": + return mysqlDSN(endpoint, creds), nil + default: + return "", fmt.Errorf("unsupported SQL engine %q", endpoint.Engine) + } +} + +func postgresURL(endpoint Endpoint, creds Credentials) string { + sslMode := "disable" + if endpoint.TLS { + sslMode = "require" + } + u := url.URL{ + Scheme: "postgres", + // A generated password can contain anything, and url.UserPassword + // percent-encodes where a formatted string would not. + User: url.UserPassword(creds.Username, creds.Password), + Host: net.JoinHostPort(endpoint.Host, endpoint.Port), + Path: "/" + endpoint.Database, + RawQuery: "sslmode=" + sslMode, + } + return u.String() +} + +func mysqlDSN(endpoint Endpoint, creds Credentials) string { + cfg := gomysql.NewConfig() + cfg.User = creds.Username + cfg.Passwd = creds.Password + cfg.Net = "tcp" + cfg.Addr = net.JoinHostPort(endpoint.Host, endpoint.Port) + cfg.DBName = endpoint.Database + cfg.ParseTime = true + if endpoint.TLS { + cfg.TLSConfig = "true" + // A token authenticates in cleartext, which is what the encrypted + // connection above makes acceptable. Password authentication does not + // need it but is unharmed by it, so the flag follows TLS rather than the + // authentication mode. + cfg.AllowCleartextPasswords = true + } + return cfg.FormatDSN() +} diff --git a/apps/cli/internal/deploydb/aws.go b/apps/cli/internal/deploydb/aws.go new file mode 100644 index 00000000..a0fc1b44 --- /dev/null +++ b/apps/cli/internal/deploydb/aws.go @@ -0,0 +1,174 @@ +package deploydb + +import ( + "context" + "fmt" + + "github.com/newstack-cloud/bluelink/libs/blueprint/state" + "github.com/newstack-cloud/celerity/apps/cli/internal/dbconn" + "github.com/newstack-cloud/celerity/apps/cli/internal/dbconn/awscreds" +) + +// Concrete AWS resource types the transformer emits for a celerity/sqlDatabase. +const ( + typeDBInstance = "aws/rds/dbInstance" + typeDBCluster = "aws/rds/dbCluster" + typeDBProxy = "aws/rds/dbProxy" + typeSecret = "aws/secretsmanager/secret" + + defaultPort = "5432" + defaultDatabase = "postgres" +) + +// awsResolver resolves connections for the aws / aws-serverless deploy targets. +type awsResolver struct{} + +func (awsResolver) Resolve( + ctx context.Context, + instance *state.InstanceState, + input ResolveInput, +) (*ResolvedConnection, error) { + sqlDatabaseName := input.SQLDatabaseName + target, err := resolveAWSTarget(instance, sqlDatabaseName, input.FallbackDatabase) + if err != nil { + return nil, err + } + + displayTarget := fmt.Sprintf("%s:%s/%s", target.Host, target.Port, target.Database) + + // Connection building is shared with the maintenance runner (see + // internal/dbconn), because the two paths reach the same databases and a + // difference between them would only ever show up on deployed + // infrastructure. + endpoint := dbconn.Endpoint{ + Engine: input.Engine, + Host: target.Host, + Port: target.Port, + Database: target.Database, + // A managed database always speaks TLS, and IAM authentication requires + // it. + TLS: true, + } + source := awscreds.New() + + var creds dbconn.Credentials + if target.IAMAuth { + creds, err = source.Token(ctx, endpoint, target.DBUser, target.Region) + if err != nil { + return nil, fmt.Errorf( + "authenticating to database %q by IAM: %w; run migrations with --url if this cannot be resolved", + sqlDatabaseName, err) + } + } else { + if target.SecretARN == "" { + return nil, fmt.Errorf("no credential secret found in state for database %q", sqlDatabaseName) + } + secret, secretErr := awscreds.FetchSecret(ctx, target.SecretARN) + if secretErr != nil { + return nil, secretErr + } + creds = dbconn.Credentials{Username: secret.Username, Password: secret.Password} + // State-derived host/port point at the proxy and win; the secret's own + // connection detail names the database behind it, and is only a + // fallback. + endpoint.Host = firstNonEmpty(endpoint.Host, secret.Host) + endpoint.Port = firstNonEmpty(endpoint.Port, secret.Port.String()) + endpoint.Database = firstNonEmpty(endpoint.Database, secret.DBName, defaultDatabase) + } + + connStr, err := dbconn.URL(endpoint, creds) + if err != nil { + return nil, err + } + return &ResolvedConnection{ConnectionString: connStr, Target: displayTarget}, nil +} + +// The AWS-specific connection information extracted from deployed state, before +// credentials are fetched. +type connectionTarget struct { + Host string + Port string + Database string + SecretARN string + IAMAuth bool + // DBUser and Region are used for IAM authentication (no secret involved). + DBUser string + Region string +} + +// Finds the concrete AWS resources generated for a celerity/sqlDatabase and +// derives the connection target. It makes no AWS calls. +func resolveAWSTarget(instance *state.InstanceState, sqlDatabaseName, fallbackDatabase string) (*connectionTarget, error) { + if instance == nil { + return nil, fmt.Errorf("no instance state available") + } + + var proxy, cluster, dbInstance, secret *state.ResourceState + for _, resource := range instance.Resources { + if abstractName(resource) != sqlDatabaseName { + continue + } + switch resource.Type { + case typeDBProxy: + proxy = resource + case typeDBCluster: + cluster = resource + case typeDBInstance: + dbInstance = resource + case typeSecret: + // Migrations run as the owner. The application user's secret carries + // the same abstract name, so it has to be filtered out here or the + // migration path connects as a role with no rights to alter anything. + if secretRole(resource) != secretRoleAppUser { + secret = resource + } + } + } + + db, dbNameField := cluster, "databaseName" + if db == nil { + db, dbNameField = dbInstance, "dbName" + } + if db == nil && proxy == nil { + return nil, fmt.Errorf("no deployed RDS database found for %q in instance state", sqlDatabaseName) + } + + target := &connectionTarget{Port: defaultPort, Database: fallbackDatabase} + + // Prefer the proxy endpoint (a flat string); fall back to the DB endpoint. + if proxy != nil { + target.Host = nodeString(proxy.SpecData, "endpoint") + } + if db != nil { + if target.Host == "" { + target.Host = nodeString(db.SpecData, "endpoint", "address") + } + if port := firstNonEmpty(nodeString(db.SpecData, "endpoint", "port"), nodeString(db.SpecData, "port")); port != "" { + target.Port = port + } + if name := nodeString(db.SpecData, dbNameField); name != "" { + target.Database = name + } + target.IAMAuth = nodeString(db.SpecData, "enableIAMDatabaseAuthentication") == "true" || + nodeString(db.SpecData, "masterUserAuthenticationType") == "iam-db-auth" + target.DBUser = nodeString(db.SpecData, "masterUsername") + target.Region = awscreds.RegionFromARN(nodeString(db.SpecData, "arn")) + } + if target.Database == "" { + target.Database = defaultDatabase + } + + // Password auth: prefer the transformer-created secret; fall back to an + // RDS-managed master-user secret on the database resource. + if secret != nil { + target.SecretARN = nodeString(secret.SpecData, "id") + } + if target.SecretARN == "" && db != nil { + target.SecretARN = nodeString(db.SpecData, "masterUserSecret", "secretArn") + } + + if target.Host == "" { + return nil, fmt.Errorf("could not resolve a database endpoint for %q from instance state", sqlDatabaseName) + } + return target, nil +} diff --git a/apps/cli/internal/deploydb/aws_test.go b/apps/cli/internal/deploydb/aws_test.go new file mode 100644 index 00000000..ea74823e --- /dev/null +++ b/apps/cli/internal/deploydb/aws_test.go @@ -0,0 +1,188 @@ +package deploydb + +import ( + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/core" + "github.com/newstack-cloud/bluelink/libs/blueprint/state" + "github.com/stretchr/testify/suite" +) + +type AWSResolveSuite struct { + suite.Suite +} + +func TestAWSResolveSuite(t *testing.T) { + suite.Run(t, new(AWSResolveSuite)) +} + +func scalar(s string) *core.MappingNode { + return &core.MappingNode{Scalar: core.ScalarFromString(s)} +} + +func obj(fields map[string]*core.MappingNode) *core.MappingNode { + return &core.MappingNode{Fields: fields} +} + +func resource(typ, abstractName string, spec *core.MappingNode) *state.ResourceState { + return &state.ResourceState{ + Type: typ, + SpecData: spec, + Metadata: &state.ResourceMetadataState{ + Annotations: map[string]*core.MappingNode{ + abstractNameAnnotation: scalar(abstractName), + }, + }, + } +} + +func instance(resources ...*state.ResourceState) *state.InstanceState { + m := map[string]*state.ResourceState{} + for i, r := range resources { + m[string(rune('a'+i))] = r + } + return &state.InstanceState{Resources: m} +} + +func (s *AWSResolveSuite) Test_db_instance_with_custom_secret() { + inst := instance( + resource(typeDBInstance, "ordersDb", obj(map[string]*core.MappingNode{ + "endpoint": obj(map[string]*core.MappingNode{"address": scalar("orders.abc.rds.amazonaws.com"), "port": scalar("5432")}), + "dbName": scalar("orders"), + })), + resource(typeSecret, "ordersDb", obj(map[string]*core.MappingNode{ + "id": scalar("arn:aws:secretsmanager:eu-west-2:123:secret:orders-x"), + })), + ) + + target, err := resolveAWSTarget(inst, "ordersDb", "") + s.Require().NoError(err) + s.Assert().Equal("orders.abc.rds.amazonaws.com", target.Host) + s.Assert().Equal("5432", target.Port) + s.Assert().Equal("orders", target.Database) + s.Assert().Equal("arn:aws:secretsmanager:eu-west-2:123:secret:orders-x", target.SecretARN) + s.Assert().False(target.IAMAuth) +} + +func (s *AWSResolveSuite) Test_cluster_with_proxy_prefers_proxy_host() { + inst := instance( + resource(typeDBCluster, "ordersDb", obj(map[string]*core.MappingNode{ + "endpoint": obj(map[string]*core.MappingNode{"address": scalar("cluster.internal"), "port": scalar("5432")}), + "databaseName": scalar("orders"), + })), + resource(typeDBProxy, "ordersDb", obj(map[string]*core.MappingNode{ + "endpoint": scalar("proxy.internal"), // flat string + })), + resource(typeSecret, "ordersDb", obj(map[string]*core.MappingNode{"id": scalar("arn:secret")})), + ) + + target, err := resolveAWSTarget(inst, "ordersDb", "") + s.Require().NoError(err) + s.Assert().Equal("proxy.internal", target.Host, "proxy endpoint is preferred") + s.Assert().Equal("5432", target.Port, "port comes from the cluster") + s.Assert().Equal("orders", target.Database) + s.Assert().Equal("arn:secret", target.SecretARN) +} + +func (s *AWSResolveSuite) Test_iam_auth_detected() { + inst := instance(resource(typeDBInstance, "ordersDb", obj(map[string]*core.MappingNode{ + "endpoint": obj(map[string]*core.MappingNode{"address": scalar("h"), "port": scalar("5432")}), + "enableIAMDatabaseAuthentication": scalar("true"), + }))) + + target, err := resolveAWSTarget(inst, "ordersDb", "orders") + s.Require().NoError(err) + s.Assert().True(target.IAMAuth) + s.Assert().Empty(target.SecretARN) + s.Assert().Equal("orders", target.Database, "falls back to provided database name") +} + +func (s *AWSResolveSuite) Test_iam_auth_extracts_user_and_region() { + inst := instance(resource(typeDBInstance, "ordersDb", obj(map[string]*core.MappingNode{ + "endpoint": obj(map[string]*core.MappingNode{"address": scalar("h"), "port": scalar("5432")}), + "enableIAMDatabaseAuthentication": scalar("true"), + "masterUsername": scalar("app_user"), + "arn": scalar("arn:aws:rds:eu-west-2:123:db:orders"), + }))) + + target, err := resolveAWSTarget(inst, "ordersDb", "orders") + s.Require().NoError(err) + s.Assert().True(target.IAMAuth) + s.Assert().Equal("app_user", target.DBUser, "IAM auth needs the database user") + s.Assert().Equal("eu-west-2", target.Region, "region derived from the RDS ARN") +} + +func (s *AWSResolveSuite) Test_rds_managed_secret_fallback() { + inst := instance(resource(typeDBInstance, "ordersDb", obj(map[string]*core.MappingNode{ + "endpoint": obj(map[string]*core.MappingNode{"address": scalar("h"), "port": scalar("5432")}), + "dbName": scalar("orders"), + "masterUserSecret": obj(map[string]*core.MappingNode{"secretArn": scalar("arn:managed")}), + }))) + + target, err := resolveAWSTarget(inst, "ordersDb", "") + s.Require().NoError(err) + s.Assert().Equal("arn:managed", target.SecretARN) +} + +func (s *AWSResolveSuite) Test_no_matching_resources_errors() { + inst := instance(resource(typeDBInstance, "otherDb", obj(map[string]*core.MappingNode{ + "endpoint": obj(map[string]*core.MappingNode{"address": scalar("h")}), + }))) + _, err := resolveAWSTarget(inst, "ordersDb", "") + s.Assert().ErrorContains(err, "no deployed RDS database") +} + +func (s *AWSResolveSuite) Test_defaults_port_and_database() { + inst := instance(resource(typeDBInstance, "ordersDb", obj(map[string]*core.MappingNode{ + "endpoint": obj(map[string]*core.MappingNode{"address": scalar("h")}), + }))) + target, err := resolveAWSTarget(inst, "ordersDb", "") + s.Require().NoError(err) + s.Assert().Equal("5432", target.Port) + s.Assert().Equal("postgres", target.Database) +} + +// roleResource is a concrete resource carrying the secret-role annotation as +// well as the abstract name. +func roleResource(typ, abstractName, role string, spec *core.MappingNode) *state.ResourceState { + r := resource(typ, abstractName, spec) + r.Metadata.Annotations[secretRoleAnnotation] = scalar(role) + return r +} + +// A database now emits two secrets under the same abstract name, and migrations +// run as the owner. The application user cannot create or alter anything, and +// until provisioning has run it does not exist in the database at all, so +// picking it here fails with a permissions error that points nowhere near the +// cause. +func (s *AWSResolveSuite) Test_app_user_secret_is_never_the_migration_credential() { + inst := instance( + resource(typeDBInstance, "ordersDb", obj(map[string]*core.MappingNode{ + "endpoint": obj(map[string]*core.MappingNode{"address": scalar("h"), "port": scalar("5432")}), + "dbName": scalar("orders"), + "masterUserSecret": obj(map[string]*core.MappingNode{"secretArn": scalar("arn:master")}), + })), + roleResource(typeSecret, "ordersDb", secretRoleAppUser, obj(map[string]*core.MappingNode{ + "id": scalar("arn:app-user"), + })), + ) + + target, err := resolveAWSTarget(inst, "ordersDb", "") + s.Require().NoError(err) + s.Assert().Equal("arn:master", target.SecretARN) +} + +// A secret from a deploy that predates the application user carries no role +// annotation, and every one of those is a master credential. +func (s *AWSResolveSuite) Test_an_unmarked_secret_is_still_the_migration_credential() { + inst := instance( + resource(typeDBInstance, "ordersDb", obj(map[string]*core.MappingNode{ + "endpoint": obj(map[string]*core.MappingNode{"address": scalar("h"), "port": scalar("5432")}), + })), + resource(typeSecret, "ordersDb", obj(map[string]*core.MappingNode{"id": scalar("arn:legacy")})), + ) + + target, err := resolveAWSTarget(inst, "ordersDb", "") + s.Require().NoError(err) + s.Assert().Equal("arn:legacy", target.SecretARN) +} diff --git a/apps/cli/internal/deploydb/resolve.go b/apps/cli/internal/deploydb/resolve.go new file mode 100644 index 00000000..7991ee69 --- /dev/null +++ b/apps/cli/internal/deploydb/resolve.go @@ -0,0 +1,128 @@ +// Package deploydb resolves a database connection from a deployed blueprint +// instance's state so the CLI can run schema migrations against a deployed +// environment. +// +// Resolution is provider-specific: how the concrete database and credential +// resources appear in state, and where credentials are fetched from, differ per +// cloud. Celerity is not AWS-only, so resolution is modular. A Resolver is +// selected by the deploy target (see ResolverFor), with one implementation per +// provider (aws.go today, with gcloud and azure to follow). +package deploydb + +import ( + "context" + "fmt" + + "github.com/newstack-cloud/bluelink/libs/blueprint/core" + "github.com/newstack-cloud/bluelink/libs/blueprint/state" +) + +// ResolvedConnection is a ready-to-use database connection derived from +// deployed state, with credentials already resolved from the provider's secret +// store. +type ResolvedConnection struct { + // ConnectionString is the full connection URL (contains credentials). + ConnectionString string + // Target is a human-readable host/db summary, safe to print (no credentials). + Target string +} + +// ResolveInput names the database to resolve a connection for. +type ResolveInput struct { + // SQLDatabaseName is the celerity/sqlDatabase resource's name in the + // blueprint. + SQLDatabaseName string + + // Engine is the database engine ("postgres", "mysql"), which determines the + // shape of the connection string as well as the driver. + Engine string + + // FallbackDatabase is the database name to use when deployed state does not + // carry one. + FallbackDatabase string +} + +// Resolver derives a database connection from deployed instance state for a +// particular deploy target's provider. +type Resolver interface { + Resolve( + ctx context.Context, + instance *state.InstanceState, + input ResolveInput, + ) (*ResolvedConnection, error) +} + +// ResolverFor returns the connection resolver for a deploy target, or an error +// if that target's resolution is not supported yet. +func ResolverFor(deployTarget string) (Resolver, error) { + switch deployTarget { + case "aws", "aws-serverless": + return &awsResolver{}, nil + case "gcloud", "gcloud-serverless": + return nil, fmt.Errorf("resolving a deployed database connection for %q is not yet supported (GCP planned for v1); use --url", deployTarget) + case "azure", "azure-serverless": + return nil, fmt.Errorf("resolving a deployed database connection for %q is not yet supported (Azure planned for v1); use --url", deployTarget) + default: + return nil, fmt.Errorf("cannot resolve a deployed database connection for deploy target %q; use --url", deployTarget) + } +} + +// --- shared state-navigation helpers (provider-agnostic) --- + +func abstractName(resource *state.ResourceState) string { + if resource == nil || resource.Metadata == nil { + return "" + } + return nodeString(resource.Metadata.Annotations[abstractNameAnnotation]) +} + +// nodeString walks a dotted field path from a mapping node and returns the +// scalar string at the end, or "" if any segment is missing. +func nodeString(node *core.MappingNode, path ...string) string { + for _, field := range path { + if node == nil || node.Fields == nil { + return "" + } + node = node.Fields[field] + } + if node == nil || node.Scalar == nil { + return "" + } + return node.Scalar.ToString() +} + +func firstNonEmpty(values ...string) string { + for _, v := range values { + if v != "" { + return v + } + } + return "" +} + +// Stamped by the Celerity transformer on every concrete resource, holding the +// logical name of the abstract resource it was generated from. +const abstractNameAnnotation = "bluelink.transform.source.abstractName" + +// secretRoleAnnotation records which credential a secret generated for a +// database holds, and secretRoleAppUser marks the application user's. +// +// A celerity/sqlDatabase produces more than one secret, all carrying the same +// abstract name, and migrations must run as the owner. The application user has +// no rights to create or alter anything, and is not even guaranteed to exist +// yet. Both constants mirror the transformer's +// resources/sqldatabase.AnnotationKeySecretRole. +const ( + secretRoleAnnotation = "celerity.sqlDatabase.secret.role" + secretRoleAppUser = "app-user" +) + +// Returns the role a secret resource holds, or "" when it is unmarked. Every +// secret from a deploy predating the application user is unmarked, and those are +// all master credentials. +func secretRole(resource *state.ResourceState) string { + if resource == nil || resource.Metadata == nil { + return "" + } + return nodeString(resource.Metadata.Annotations[secretRoleAnnotation]) +} diff --git a/apps/cli/internal/maintenancerunner/awsrunner/awsrunner.go b/apps/cli/internal/maintenancerunner/awsrunner/awsrunner.go new file mode 100644 index 00000000..ad03624e --- /dev/null +++ b/apps/cli/internal/maintenancerunner/awsrunner/awsrunner.go @@ -0,0 +1,190 @@ +// Package awsrunner hosts and invokes the Celerity maintenance runner on AWS. +// +// The runner is a Lambda function in the database's private subnets. Both +// halves of the AWS-specific story live here, and both register themselves on +// import: a Host, which delivers Lambda invocations to the cloud-neutral +// executor, and an Invoker, which the CLI calls it through. Importing this +// package is the only thing that ties either binary to AWS. +// +// lambda:Invoke is what makes this work. It is a control-plane call, so it +// reaches a function in a private subnet from an operator's machine with no +// network path to the VPC at all, and the same credentials that just ran the +// deploy are enough. +package awsrunner + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + awsconfig "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/lambda" + lambdatypes "github.com/aws/aws-sdk-go-v2/service/lambda/types" + "github.com/newstack-cloud/bluelink/libs/blueprint/state" + "github.com/newstack-cloud/celerity/apps/cli/internal/maintenancerunner" +) + +func init() { + maintenancerunner.RegisterInvoker("aws", func() maintenancerunner.Invoker { return &Invoker{} }) + maintenancerunner.RegisterInvoker("aws-serverless", func() maintenancerunner.Invoker { return &Invoker{} }) +} + +// lambdaFunctionType is the concrete resource type the runner is deployed as. +const lambdaFunctionType = "aws/lambda/function" + +// Invoker calls the runner Lambda. +type Invoker struct{} + +// Deployed reports whether the instance has a maintenance runner. +func (i *Invoker) Deployed(instance *state.InstanceState) bool { + _, err := runnerFunctionName(instance) + return err == nil +} + +// Invoke calls the runner and decodes its response. +func (i *Invoker) Invoke( + ctx context.Context, + instance *state.InstanceState, + req maintenancerunner.Request, +) (*maintenancerunner.Response, error) { + functionName, err := runnerFunctionName(instance) + if err != nil { + return nil, err + } + + payload, err := json.Marshal(req) + if err != nil { + return nil, fmt.Errorf("encoding the maintenance request: %w", err) + } + + awsCfg, err := awsconfig.LoadDefaultConfig(ctx, runnerRegionOption(instance)...) + if err != nil { + return nil, fmt.Errorf("loading AWS config: %w", err) + } + + out, err := lambda.NewFromConfig(awsCfg).Invoke(ctx, &lambda.InvokeInput{ + FunctionName: &functionName, + // Synchronous: the CLI has nothing useful to do until the operation has + // either happened or failed, and an operator watching a command wants + // the outcome rather than an acknowledgement. + InvocationType: lambdatypes.InvocationTypeRequestResponse, + Payload: payload, + }) + if err != nil { + return nil, fmt.Errorf( + "invoking the maintenance runner %s: %w "+ + "(the deploying principal needs lambda:InvokeFunction on it)", + functionName, err) + } + + // A function error is the runner crashing rather than an operation failing, + // which the executor reports in the response body. The payload here is + // Lambda's error envelope, which is the most useful thing to show. + if out.FunctionError != nil { + return nil, fmt.Errorf( + "the maintenance runner failed to run: %s: %s", + *out.FunctionError, string(out.Payload)) + } + + var resp maintenancerunner.Response + if err := json.Unmarshal(out.Payload, &resp); err != nil { + return nil, fmt.Errorf("decoding the maintenance runner's response: %w", err) + } + return &resp, nil +} + +// The region the runner is deployed in, taken from its own ARN in instance state. +// +// A Lambda can only be invoked in the region that holds it, so the deployed resource is +// the authoritative source and needs no configuration to agree with. Without this the +// default chain has only the environment to go on, and an operator whose deploy config +// names a region but whose shell does not gets "Missing Region" from a command that had +// the answer in front of it. An empty result leaves the default chain untouched. +func runnerRegionOption(instance *state.InstanceState) []func(*awsconfig.LoadOptions) error { + region := runnerRegion(instance) + if region == "" { + return nil + } + + return []func(*awsconfig.LoadOptions) error{awsconfig.WithRegion(region)} +} + +func runnerRegion(instance *state.InstanceState) string { + if instance == nil { + return "" + } + + for _, resource := range instance.Resources { + if resource == nil || resource.Type != lambdaFunctionType { + continue + } + if annotation(resource, maintenancerunner.RunnerAnnotation) != + maintenancerunner.RunnerAnnotationValue { + continue + } + + return regionFromARN(specString(resource, "arn")) + } + + return "" +} + +// Pulls the region out of an ARN of the form arn:aws:lambda:::function:. +func regionFromARN(arn string) string { + parts := strings.Split(arn, ":") + if len(parts) < 4 || parts[0] != "arn" { + return "" + } + + return parts[3] +} + +// Finds the deployed runner in instance state by the annotation the transformer +// stamps on it, rather than by a name convention the CLI would have to keep in +// step with the transformer. +func runnerFunctionName(instance *state.InstanceState) (string, error) { + if instance == nil { + return "", fmt.Errorf("no instance state available") + } + for _, resource := range instance.Resources { + if resource == nil || resource.Type != lambdaFunctionType { + continue + } + if annotation(resource, maintenancerunner.RunnerAnnotation) != + maintenancerunner.RunnerAnnotationValue { + continue + } + if name := specString(resource, "functionName"); name != "" { + return name, nil + } + if arn := specString(resource, "arn"); arn != "" { + return arn, nil + } + return "", fmt.Errorf("the deployed maintenance runner has no function name in state") + } + return "", fmt.Errorf("this instance has no deployed maintenance runner") +} + +func annotation(resource *state.ResourceState, key string) string { + if resource.Metadata == nil { + return "" + } + node := resource.Metadata.Annotations[key] + if node == nil || node.Scalar == nil { + return "" + } + return node.Scalar.ToString() +} + +func specString(resource *state.ResourceState, field string) string { + spec := resource.SpecData + if spec == nil || spec.Fields == nil { + return "" + } + node := spec.Fields[field] + if node == nil || node.Scalar == nil { + return "" + } + return node.Scalar.ToString() +} diff --git a/apps/cli/internal/maintenancerunner/awsrunner/awsrunner_region_test.go b/apps/cli/internal/maintenancerunner/awsrunner/awsrunner_region_test.go new file mode 100644 index 00000000..e6d5a2d3 --- /dev/null +++ b/apps/cli/internal/maintenancerunner/awsrunner/awsrunner_region_test.go @@ -0,0 +1,66 @@ +package awsrunner + +import ( + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/core" + "github.com/newstack-cloud/bluelink/libs/blueprint/state" + "github.com/newstack-cloud/celerity/apps/cli/internal/maintenancerunner" +) + +func runnerResourceWithARN(arn string) *state.ResourceState { + return &state.ResourceState{ + Type: lambdaFunctionType, + Metadata: &state.ResourceMetadataState{ + Annotations: map[string]*core.MappingNode{ + maintenancerunner.RunnerAnnotation: core.MappingNodeFromString( + maintenancerunner.RunnerAnnotationValue, + ), + }, + }, + SpecData: core.MappingNodeFields("arn", core.MappingNodeFromString(arn)), + } +} + +// A deploy config naming a region used to be ignored, so `celerity schema apply` failed +// with "Missing Region" unless AWS_REGION happened to be exported. The runner's own ARN +// records where it is deployed. +func Test_region_comes_from_the_runners_arn(t *testing.T) { + instance := &state.InstanceState{ + Resources: map[string]*state.ResourceState{ + "runner": runnerResourceWithARN( + "arn:aws:lambda:eu-west-2:027653366630:function:audit-maintenance", + ), + }, + } + + if got := runnerRegion(instance); got != "eu-west-2" { + t.Errorf("got %q, want eu-west-2", got) + } + if opts := runnerRegionOption(instance); len(opts) != 1 { + t.Errorf("expected one load option, got %d", len(opts)) + } +} + +// Without a usable ARN the default chain must be left alone rather than pinned to "". +func Test_no_region_leaves_the_default_chain_untouched(t *testing.T) { + cases := map[string]*state.InstanceState{ + "nil instance": nil, + "no runner": {Resources: map[string]*state.ResourceState{}}, + "empty arn": {Resources: map[string]*state.ResourceState{ + "runner": runnerResourceWithARN(""), + }}, + "malformed arn": {Resources: map[string]*state.ResourceState{ + "runner": runnerResourceWithARN("audit-maintenance"), + }}, + } + + for name, instance := range cases { + if got := runnerRegion(instance); got != "" { + t.Errorf("%s: got %q, want empty", name, got) + } + if opts := runnerRegionOption(instance); opts != nil { + t.Errorf("%s: expected no load options", name) + } + } +} diff --git a/apps/cli/internal/maintenancerunner/awsrunner/awsrunner_test.go b/apps/cli/internal/maintenancerunner/awsrunner/awsrunner_test.go new file mode 100644 index 00000000..86c5bbb0 --- /dev/null +++ b/apps/cli/internal/maintenancerunner/awsrunner/awsrunner_test.go @@ -0,0 +1,116 @@ +package awsrunner + +import ( + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/core" + "github.com/newstack-cloud/bluelink/libs/blueprint/state" + "github.com/newstack-cloud/celerity/apps/cli/internal/maintenancerunner" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func scalar(s string) *core.MappingNode { + return &core.MappingNode{Scalar: core.ScalarFromString(s)} +} + +func lambdaResource(annotations map[string]string, spec map[string]*core.MappingNode) *state.ResourceState { + nodes := map[string]*core.MappingNode{} + for key, value := range annotations { + nodes[key] = scalar(value) + } + return &state.ResourceState{ + Type: lambdaFunctionType, + SpecData: &core.MappingNode{Fields: spec}, + Metadata: &state.ResourceMetadataState{Annotations: nodes}, + } +} + +func instance(resources ...*state.ResourceState) *state.InstanceState { + m := map[string]*state.ResourceState{} + for i, r := range resources { + m[string(rune('a'+i))] = r + } + return &state.InstanceState{Resources: m} +} + +func runnerResource() *state.ResourceState { + return lambdaResource( + map[string]string{ + maintenancerunner.RunnerAnnotation: maintenancerunner.RunnerAnnotationValue, + }, + map[string]*core.MappingNode{"functionName": scalar("orders-maintenance-runner")}, + ) +} + +// An application's functions are all aws/lambda/function, so the runner is +// found by the annotation the transformer stamps on it rather than by type or +// by a name convention the CLI would have to keep in step with. +func TestFindsTheRunnerAmongTheApplicationsFunctions(t *testing.T) { + inst := instance( + lambdaResource(nil, map[string]*core.MappingNode{"functionName": scalar("saveOrder")}), + runnerResource(), + lambdaResource(nil, map[string]*core.MappingNode{"functionName": scalar("health")}), + ) + + name, err := runnerFunctionName(inst) + + require.NoError(t, err) + assert.Equal(t, "orders-maintenance-runner", name) +} + +// An instance deployed before runners existed, or one whose database is +// reachable without one, has none, and that is not an error on the auto path. +func TestAnInstanceWithNoRunnerIsReported(t *testing.T) { + inst := instance(lambdaResource(nil, map[string]*core.MappingNode{"functionName": scalar("saveOrder")})) + + _, err := runnerFunctionName(inst) + + require.Error(t, err) + assert.Contains(t, err.Error(), "no deployed maintenance runner") + assert.False(t, (&Invoker{}).Deployed(inst)) + assert.True(t, (&Invoker{}).Deployed(instance(runnerResource()))) +} + +// Lambda accepts an ARN wherever it accepts a function name, so state that +// carries only the ARN is still usable. +func TestFallsBackToTheARN(t *testing.T) { + inst := instance(lambdaResource( + map[string]string{ + maintenancerunner.RunnerAnnotation: maintenancerunner.RunnerAnnotationValue, + }, + map[string]*core.MappingNode{ + "arn": scalar("arn:aws:lambda:eu-west-2:1:function:orders-maintenance-runner"), + }, + )) + + name, err := runnerFunctionName(inst) + + require.NoError(t, err) + assert.Equal(t, "arn:aws:lambda:eu-west-2:1:function:orders-maintenance-runner", name) +} + +// Detection keys on a variable the execution environment sets for every +// runtime, rather than a function name or region a user could set anywhere. +func TestDetectsALambdaExecutionEnvironment(t *testing.T) { + h := &host{} + assert.Equal(t, "aws", h.Name()) + assert.False(t, h.Detect(), "not running on Lambda") + + t.Setenv("AWS_LAMBDA_RUNTIME_API", "127.0.0.1:9001") + + assert.True(t, h.Detect()) +} + +// Both registries are populated from init, and a runner or CLI that silently +// registered nothing would fail much later with a confusing message. +func TestRegistersItselfAsAHostAndAnInvoker(t *testing.T) { + for _, target := range []string{"aws", "aws-serverless"} { + invoker, err := maintenancerunner.InvokerFor(target) + require.NoError(t, err, target) + assert.NotNil(t, invoker) + } + + assert.Contains(t, maintenancerunner.HostNames(), "aws", + "importing this package must be all it takes for the runner to serve on Lambda") +} diff --git a/apps/cli/internal/maintenancerunner/awsrunner/serve.go b/apps/cli/internal/maintenancerunner/awsrunner/serve.go new file mode 100644 index 00000000..c331b041 --- /dev/null +++ b/apps/cli/internal/maintenancerunner/awsrunner/serve.go @@ -0,0 +1,47 @@ +package awsrunner + +import ( + "context" + "os" + + "github.com/aws/aws-lambda-go/lambda" + "github.com/newstack-cloud/celerity/apps/cli/internal/dbconn" + "github.com/newstack-cloud/celerity/apps/cli/internal/dbconn/awscreds" + "github.com/newstack-cloud/celerity/apps/cli/internal/maintenancerunner" + "go.uber.org/zap" +) + +func init() { + maintenancerunner.RegisterHost(&host{}) +} + +// host runs the maintenance runner on AWS Lambda. +type host struct{} + +func (h *host) Name() string { return "aws" } + +// Detect reports whether the process is a Lambda invocation. +// +// AWS_LAMBDA_RUNTIME_API is set by the execution environment itself, for every +// runtime, and is what the Lambda SDK talks to, so it is present exactly when +// this host can serve. A function name or region, by contrast, a user could set +// anywhere. +func (h *host) Detect() bool { + return os.Getenv("AWS_LAMBDA_RUNTIME_API") != "" +} + +func (h *host) Credentials() dbconn.CredentialSource { return awscreds.New() } + +// Serve hands Lambda invocations to the runner. It does not return. +func (h *host) Serve(handle maintenancerunner.Handler, _ *zap.Logger) error { + lambda.Start(func( + ctx context.Context, + req maintenancerunner.Request, + ) (*maintenancerunner.Response, error) { + // Always a response, never an error. An operation that fails is a + // successful invocation carrying a report the CLI can print, where an + // error here would reach the operator as a Lambda stack trace instead. + return handle(ctx, req), nil + }) + return nil +} diff --git a/apps/cli/internal/maintenancerunner/execute.go b/apps/cli/internal/maintenancerunner/execute.go new file mode 100644 index 00000000..f3265f9a --- /dev/null +++ b/apps/cli/internal/maintenancerunner/execute.go @@ -0,0 +1,304 @@ +package maintenancerunner + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "github.com/newstack-cloud/celerity/apps/cli/internal/dbconn" + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "go.uber.org/zap" +) + +// Executor performs operations against the databases it was deployed to serve. +// +// Nothing in here is cloud-specific. It reads its targets, resolves credentials +// through a dbconn.CredentialSource and runs the same internal/sqlschema code +// the CLI runs locally. What differs per provider is how the executor is hosted +// (a Lambda on AWS) and where credentials come from, and both of those are +// supplied from outside. +// +// It holds no state between invocations beyond its targets, because a +// maintenance operation is rare enough that pooling a connection would only mean +// holding an idle one open against the database's connection limit. +type Executor struct { + targets Targets + credentials dbconn.CredentialSource + logger *zap.Logger + + // connect is the seam the tests replace. Everything else here is dispatch, + // validation and error reporting, none of which needs a real database. + connect func(ctx context.Context, engine string, connStr string) (applier, error) +} + +// applier is the part of sqlschema.Applier the executor uses. +type applier interface { + ProvisionAppUser(ctx context.Context, user sqlschema.AppUser) (*sqlschema.ProvisionReport, error) + PendingMigrations(ctx context.Context, migrationsPath string) ([]sqlschema.PendingMigration, error) + ApplyMigrationDir(ctx context.Context, migrationsPath string, maxRisk sqlschema.RiskLevel) error + Close() error +} + +// NewExecutor builds an executor over a set of database targets, resolving +// credentials through the given provider's source. +func NewExecutor(targets Targets, credentials dbconn.CredentialSource, logger *zap.Logger) *Executor { + return &Executor{ + targets: targets, + credentials: credentials, + logger: logger, + connect: connectToDatabase, + } +} + +// Handle runs one request and always returns a response. An operation that fails +// is reported in the response rather than as a host-level error, so the CLI has +// something to print beyond a stack trace. +func (e *Executor) Handle(ctx context.Context, req Request) *Response { + e.logger.Info("maintenance request", + zap.String("operation", req.Operation), + zap.String("database", req.Database), + ) + + target, err := e.targets.Lookup(req.Database) + if err != nil { + return req.Failed(err) + } + + switch req.Operation { + case OpProvisionUser: + return e.provisionUser(ctx, req, target) + case OpPing: + return e.ping(ctx, req, target) + case OpApply: + return e.applyMigrations(ctx, req, target) + default: + return req.Failed(fmt.Errorf( + "unknown operation %q (this runner supports: %s, %s, %s)", + req.Operation, OpProvisionUser, OpPing, OpApply)) + } +} + +func (e *Executor) provisionUser(ctx context.Context, req Request, target *Target) *Response { + appUser, err := e.appUser(ctx, target) + if err != nil { + return req.Failed(err) + } + + db, err := e.connectAsOwner(ctx, target) + if err != nil { + return req.Failed(err) + } + defer db.Close() + + report, err := db.ProvisionAppUser(ctx, appUser) + if err != nil { + return req.Failed(err) + } + + e.logger.Info("provisioned application user", + zap.String("database", req.Database), + zap.String("user", report.User), + zap.Bool("roleCreated", report.RoleCreated), + ) + return &Response{Operation: req.Operation, Database: req.Database, OK: true, Provision: report} +} + +// Runs the migration set the request carried, as the database owner. +// +// The files are materialised into a directory of the runner's own rather than +// executed as statements, because everything downstream is defined over a +// migration directory: the checksum check, revision tracking and risk +// classification. Running the same sqlschema code over the same shape of input +// is what keeps the runner's behaviour identical to the local path rather than +// merely similar. +func (e *Executor) applyMigrations(ctx context.Context, req Request, target *Target) *Response { + if len(req.Migrations) == 0 { + return req.Failed(fmt.Errorf("no migration files were sent to apply")) + } + + dir, cleanup, err := materialiseMigrations(req.Migrations) + if err != nil { + return req.Failed(err) + } + defer cleanup() + + db, err := e.connectAsOwner(ctx, target) + if err != nil { + return req.Failed(err) + } + defer db.Close() + + // Read what is pending before applying, so the report can name what ran. + // Afterwards there is nothing left to enumerate. + pending, err := db.PendingMigrations(ctx, dir) + if err != nil { + return req.Failed(fmt.Errorf("reading pending migrations: %w", err)) + } + + maxRisk := sqlschema.RiskLevel(req.MaxRisk) + if maxRisk == "" { + maxRisk = sqlschema.RiskSafe + } + + report := &ApplyReport{} + for _, migration := range pending { + if riskExceeds(migration.Risk, maxRisk) { + report.Blocked = append(report.Blocked, BlockedMigration{ + Name: migration.Name, + Risk: string(migration.Risk), + }) + continue + } + report.Applied = append(report.Applied, migration.Name) + } + + if err := db.ApplyMigrationDir(ctx, dir, maxRisk); err != nil { + return req.Failed(err) + } + + e.logger.Info("applied migrations", + zap.String("database", req.Database), + zap.Int("applied", len(report.Applied)), + zap.Int("blocked", len(report.Blocked)), + ) + return &Response{Operation: req.Operation, Database: req.Database, OK: true, Apply: report} +} + +func riskExceeds(risk sqlschema.RiskLevel, maxRisk sqlschema.RiskLevel) bool { + return riskRank(risk) > riskRank(maxRisk) +} + +func riskRank(risk sqlschema.RiskLevel) int { + switch risk { + case sqlschema.RiskBreaking: + return 2 + case sqlschema.RiskRisky: + return 1 + default: + return 0 + } +} + +// Writes the request's files into a fresh directory. +// +// A name that is anything but a bare file name is rejected rather than +// sanitised. A payload that can choose a path can write outside the directory, +// and a request that tries is worth refusing rather than quietly correcting. +func materialiseMigrations(files []MigrationFile) (string, func(), error) { + dir, err := os.MkdirTemp("", "celerity-migrations-*") + if err != nil { + return "", func() {}, fmt.Errorf("creating a migration directory: %w", err) + } + cleanup := func() { os.RemoveAll(dir) } + + for _, file := range files { + if file.Name == "" || file.Name != filepath.Base(file.Name) { + cleanup() + return "", func() {}, fmt.Errorf( + "migration file name %q must be a bare file name", file.Name) + } + path := filepath.Join(dir, file.Name) + if err := os.WriteFile(path, []byte(file.Content), 0600); err != nil { + cleanup() + return "", func() {}, fmt.Errorf("writing migration %s: %w", file.Name, err) + } + } + return dir, cleanup, nil +} + +func (e *Executor) ping(ctx context.Context, req Request, target *Target) *Response { + db, err := e.connectAsOwner(ctx, target) + if err != nil { + return req.Failed(err) + } + defer db.Close() + return &Response{Operation: req.Operation, Database: req.Database, OK: true} +} + +// Reads the application user's credential in whichever mode the database is +// configured for. +func (e *Executor) appUser(ctx context.Context, target *Target) (sqlschema.AppUser, error) { + user := sqlschema.AppUser{ + Name: target.AppUser, + IAMAuth: target.AppUserTokenAuth, + Database: target.Database, + } + if user.Name == "" { + return user, fmt.Errorf("no application user is configured for this database") + } + // Token authentication distributes no credential at all, so there is nothing + // to read. The role still has to exist and hold the provider's grant, which + // is why provisioning runs in both modes. + if user.IAMAuth { + return user, nil + } + + if target.AppUserCredentialRef == "" { + return user, fmt.Errorf( + "database %q uses password authentication but no application user credential was configured", + target.Database) + } + creds, err := e.credentials.Resolve(ctx, target.AppUserCredentialRef) + if err != nil { + return user, fmt.Errorf("reading the application user's credentials: %w", err) + } + user.Password = creds.Password + return user, nil +} + +// The owner/master role is the one migrations run as, and the only one that can +// grant over its own objects. +func (e *Executor) connectAsOwner(ctx context.Context, target *Target) (applier, error) { + endpoint := dbconn.Endpoint{ + Engine: target.Engine, + Host: target.Host, + Port: target.Port, + Database: target.Database, + // A managed database always speaks TLS, and the runner only ever talks + // to one. + TLS: true, + } + + creds, err := e.ownerCredentials(ctx, endpoint, target) + if err != nil { + return nil, err + } + + connStr, err := dbconn.URL(endpoint, creds) + if err != nil { + return nil, err + } + + db, err := e.connect(ctx, target.Engine, connStr) + if err != nil { + // A connection failure here is nearly always a network rule, and the raw + // driver error reports only that a dial timed out. + return nil, fmt.Errorf( + "connecting to %s:%s as the database owner: %w "+ + "(the runner must have a network path to the database)", + target.Host, target.Port, err) + } + return db, nil +} + +// The owner credential comes from the stored master credential, or from a +// platform-issued token where the database authenticates its master that way. +func (e *Executor) ownerCredentials( + ctx context.Context, + endpoint dbconn.Endpoint, + target *Target, +) (dbconn.Credentials, error) { + if target.OwnerCredentialRef == "" { + return e.credentials.Token(ctx, endpoint, target.OwnerUser, target.Region) + } + creds, err := e.credentials.Resolve(ctx, target.OwnerCredentialRef) + if err != nil { + return dbconn.Credentials{}, fmt.Errorf("reading the database owner's credentials: %w", err) + } + return creds, nil +} + +func connectToDatabase(_ context.Context, engine string, connStr string) (applier, error) { + return sqlschema.NewApplier(engine, connStr, zap.NewNop()) +} diff --git a/apps/cli/internal/maintenancerunner/execute_test.go b/apps/cli/internal/maintenancerunner/execute_test.go new file mode 100644 index 00000000..e2f95fd2 --- /dev/null +++ b/apps/cli/internal/maintenancerunner/execute_test.go @@ -0,0 +1,413 @@ +package maintenancerunner + +import ( + "context" + "errors" + "os" + "sort" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/dbconn" + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +type fakeApplier struct { + provisioned sqlschema.AppUser + report *sqlschema.ProvisionReport + err error + closed bool + + // Migration state: what the runner was asked to apply, and what the + // database claims is pending. + pending []sqlschema.PendingMigration + pendingErr error + appliedDir string + appliedRisk sqlschema.RiskLevel + applyErr error + appliedFiles []string +} + +func (f *fakeApplier) ProvisionAppUser(_ context.Context, user sqlschema.AppUser) (*sqlschema.ProvisionReport, error) { + f.provisioned = user + if f.err != nil { + return nil, f.err + } + if f.report != nil { + return f.report, nil + } + return &sqlschema.ProvisionReport{User: user.Name, RoleCreated: true, AuthConfigured: true}, nil +} + +func (f *fakeApplier) PendingMigrations( + _ context.Context, + migrationsPath string, +) ([]sqlschema.PendingMigration, error) { + if f.pendingErr != nil { + return nil, f.pendingErr + } + // Record what the runner actually materialised, so a test can assert the + // files arrived rather than only that a directory was passed. + entries, err := os.ReadDir(migrationsPath) + if err != nil { + return nil, err + } + for _, entry := range entries { + f.appliedFiles = append(f.appliedFiles, entry.Name()) + } + sort.Strings(f.appliedFiles) + return f.pending, nil +} + +func (f *fakeApplier) ApplyMigrationDir( + _ context.Context, + migrationsPath string, + maxRisk sqlschema.RiskLevel, +) error { + f.appliedDir = migrationsPath + f.appliedRisk = maxRisk + return f.applyErr +} + +func (f *fakeApplier) Close() error { + f.closed = true + return nil +} + +// fakeCredentials stands in for a provider's secret store. Everything the +// executor does with a credential is visible through it: which one it uses to +// connect, and which it only writes into the database. +type fakeCredentials struct { + stored map[string]dbconn.Credentials +} + +func (f *fakeCredentials) Resolve(_ context.Context, reference string) (dbconn.Credentials, error) { + creds, ok := f.stored[reference] + if !ok { + return dbconn.Credentials{}, errors.New("AccessDeniedException") + } + return creds, nil +} + +func (f *fakeCredentials) Token( + _ context.Context, _ dbconn.Endpoint, user string, _ string, +) (dbconn.Credentials, error) { + return dbconn.Credentials{Username: user, Password: "issued-token"}, nil +} + +type harness struct { + executor *Executor + applier *fakeApplier + // connStr is what the executor would have connected with, which is where + // the credential and the TLS mode end up. + connStr string + secrets *fakeCredentials +} + +func newHarness(targets Targets) *harness { + h := &harness{ + applier: &fakeApplier{}, + secrets: &fakeCredentials{stored: map[string]dbconn.Credentials{}}, + } + h.executor = NewExecutor(targets, h.secrets, zap.NewNop()) + h.executor.connect = func(_ context.Context, _ string, connStr string) (applier, error) { + h.connStr = connStr + return h.applier, nil + } + return h +} + +// store records a credential the provider's secret store holds. +func (h *harness) store(reference, username, password string) { + h.secrets.stored[reference] = dbconn.Credentials{Username: username, Password: password} +} + +func passwordTarget() Targets { + return Targets{"ordersDb": { + Engine: "postgres", + Host: "orders.proxy-abc.eu-west-2.rds.amazonaws.com", + Port: "5432", + Database: "orders", + OwnerCredentialRef: "arn:aws:secretsmanager:eu-west-2:1:secret:orders-master", + AppUser: "celerity_app", + AppUserCredentialRef: "arn:aws:secretsmanager:eu-west-2:1:secret:orders-app-user", + }} +} + +func TestProvisionsTheApplicationUserFromItsOwnSecret(t *testing.T) { + h := newHarness(passwordTarget()) + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-master", "celerity_master", "master-password") + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-app-user", "celerity_app", "app-password") + + resp := h.executor.Handle(context.Background(), Request{ + Operation: OpProvisionUser, Database: "ordersDb", + }) + + require.True(t, resp.OK, resp.Error) + assert.Equal(t, "celerity_app", h.applier.provisioned.Name) + assert.Equal(t, "app-password", h.applier.provisioned.Password) + assert.True(t, resp.Provision.RoleCreated) + assert.True(t, h.applier.closed, "the connection must not be left open") +} + +// The whole point of the design: the runner connects as the owner, and the +// application's credential is only ever written into the database, never used +// to connect with. +func TestConnectsAsTheOwnerNotTheApplicationUser(t *testing.T) { + h := newHarness(passwordTarget()) + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-master", "celerity_master", "master-password") + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-app-user", "celerity_app", "app-password") + + h.executor.Handle(context.Background(), Request{Operation: OpProvisionUser, Database: "ordersDb"}) + + assert.Contains(t, h.connStr, "celerity_master") + assert.NotContains(t, h.connStr, "app-password") + // A managed database is always reached over TLS. + assert.Contains(t, h.connStr, "sslmode=require") +} + +// IAM mode distributes no credential at all, so there is no application secret +// to read. The role still has to exist, which is why provisioning runs in both +// modes. +func TestIAMModeNeedsNoApplicationSecret(t *testing.T) { + targets := passwordTarget() + targets["ordersDb"].AppUserCredentialRef = "" + targets["ordersDb"].AppUserTokenAuth = true + h := newHarness(targets) + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-master", "celerity_master", "master-password") + + resp := h.executor.Handle(context.Background(), Request{ + Operation: OpProvisionUser, Database: "ordersDb", + }) + + require.True(t, resp.OK, resp.Error) + assert.True(t, h.applier.provisioned.IAMAuth) + assert.Empty(t, h.applier.provisioned.Password) +} + +// A database whose master is itself IAM-authenticated has no master secret to +// read; the runner exchanges its execution role instead. +func TestOwnerCanAuthenticateByIAM(t *testing.T) { + targets := passwordTarget() + targets["ordersDb"].OwnerCredentialRef = "" + targets["ordersDb"].OwnerUser = "celerity_master" + targets["ordersDb"].Region = "eu-west-2" + h := newHarness(targets) + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-app-user", "celerity_app", "app-password") + + resp := h.executor.Handle(context.Background(), Request{ + Operation: OpProvisionUser, Database: "ordersDb", + }) + + require.True(t, resp.OK, resp.Error) + assert.Contains(t, h.connStr, "issued-token") +} + +// An operation that fails is a successful invocation carrying the reason. A +// Lambda error would reach the operator as a stack trace with the actual cause +// buried in CloudWatch. +func TestAFailedOperationIsReportedNotThrown(t *testing.T) { + h := newHarness(passwordTarget()) + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-master", "celerity_master", "master-password") + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-app-user", "celerity_app", "app-password") + h.applier.err = errors.New("permission denied for schema public") + + resp := h.executor.Handle(context.Background(), Request{ + Operation: OpProvisionUser, Database: "ordersDb", + }) + + assert.False(t, resp.OK) + assert.Contains(t, resp.Error, "permission denied for schema public") + assert.Equal(t, "ordersDb", resp.Database) +} + +// The most likely real failure is the runner's role not being granted the +// secret, where the raw error reports only AccessDenied. +func TestAnUnreadableOwnerSecretSaysWhichCredentialFailed(t *testing.T) { + h := newHarness(passwordTarget()) + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-app-user", "celerity_app", "app-password") + + resp := h.executor.Handle(context.Background(), Request{ + Operation: OpProvisionUser, Database: "ordersDb", + }) + + assert.False(t, resp.OK) + assert.Contains(t, resp.Error, "database owner's credentials") + assert.Contains(t, resp.Error, "AccessDeniedException") +} + +// A name the runner does not serve is far more often a stale deploy than a +// typo, so the error lists the databases this runner is configured for. +func TestAnUnknownDatabaseListsWhatTheRunnerServes(t *testing.T) { + h := newHarness(passwordTarget()) + + resp := h.executor.Handle(context.Background(), Request{ + Operation: OpProvisionUser, Database: "auditDb", + }) + + assert.False(t, resp.OK) + assert.Contains(t, resp.Error, `no database named "auditDb"`) + assert.Contains(t, resp.Error, "ordersDb") +} + +func TestAnUnknownOperationIsRefused(t *testing.T) { + h := newHarness(passwordTarget()) + + resp := h.executor.Handle(context.Background(), Request{ + Operation: "execute-sql", Database: "ordersDb", + }) + + assert.False(t, resp.OK) + assert.Contains(t, resp.Error, `unknown operation "execute-sql"`) +} + +// Ping exists so a deploy can prove the network path works without changing +// anything in the database. +func TestPingConnectsAndChangesNothing(t *testing.T) { + h := newHarness(passwordTarget()) + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-master", "celerity_master", "master-password") + + resp := h.executor.Handle(context.Background(), Request{Operation: OpPing, Database: "ordersDb"}) + + require.True(t, resp.OK, resp.Error) + assert.Empty(t, h.applier.provisioned.Name, "ping must not provision anything") + assert.True(t, h.applier.closed) +} + +func TestTargetsRoundTripThroughTheEnvironmentFormat(t *testing.T) { + targets, err := ParseTargets(`{"ordersDb":{"engine":"postgres","host":"h","port":"5432",` + + `"database":"orders","ownerCredentialRef":"a","appUser":"celerity_app",` + + `"appUserCredentialRef":"b"}}`) + require.NoError(t, err) + + target, err := targets.Lookup("ordersDb") + require.NoError(t, err) + assert.Equal(t, "celerity_app", target.AppUser) + assert.Equal(t, "a", target.OwnerCredentialRef) + assert.Equal(t, "b", target.AppUserCredentialRef) +} + +func TestARunnerWithNoTargetsSaysSo(t *testing.T) { + _, err := Targets{}.Lookup("ordersDb") + + require.Error(t, err) + assert.Contains(t, err.Error(), "no database targets configured") +} + +// The whole point of the operation: migration files live on the operator's +// machine and the database is unreachable from it, so the files travel and the +// runner applies them locally. +func TestApplyWritesTheSentMigrationsAndRunsThemAsTheOwner(t *testing.T) { + h := newHarness(passwordTarget()) + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-master", "postgres", "master-pw") + h.applier.pending = []sqlschema.PendingMigration{ + {Name: "20260101000000_initial.sql", Risk: sqlschema.RiskSafe}, + } + + resp := h.executor.Handle(context.Background(), Request{ + Operation: OpApply, + Database: "ordersDb", + Migrations: []MigrationFile{ + {Name: "20260101000000_initial.sql", Content: "CREATE TABLE orders (id int);"}, + {Name: "atlas.sum", Content: "h1:abc\n"}, + }, + }) + + require.True(t, resp.OK, "expected apply to succeed, got: %s", resp.Error) + assert.Equal(t, []string{"20260101000000_initial.sql"}, resp.Apply.Applied) + assert.Equal(t, []string{"20260101000000_initial.sql", "atlas.sum"}, h.applier.appliedFiles, + "the runner must materialise every file it was sent, including the checksum") + assert.Contains(t, h.connStr, "master-pw", "migrations run as the database owner") + assert.True(t, h.applier.closed) +} + +// The risk gate is the operator's authorisation, so it has to survive the trip +// rather than being re-decided by the side that cannot see the flags. +func TestApplyHoldsBackMigrationsAboveTheAuthorisedRisk(t *testing.T) { + h := newHarness(passwordTarget()) + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-master", "postgres", "master-pw") + h.applier.pending = []sqlschema.PendingMigration{ + {Name: "001_safe.sql", Risk: sqlschema.RiskSafe}, + {Name: "002_risky.sql", Risk: sqlschema.RiskRisky}, + {Name: "003_breaking.sql", Risk: sqlschema.RiskBreaking}, + } + + resp := h.executor.Handle(context.Background(), Request{ + Operation: OpApply, + Database: "ordersDb", + MaxRisk: string(sqlschema.RiskRisky), + Migrations: []MigrationFile{{Name: "001_safe.sql", Content: "SELECT 1;"}}, + }) + + require.True(t, resp.OK, resp.Error) + assert.Equal(t, []string{"001_safe.sql", "002_risky.sql"}, resp.Apply.Applied) + require.Len(t, resp.Apply.Blocked, 1) + assert.Equal(t, "003_breaking.sql", resp.Apply.Blocked[0].Name) + assert.Equal(t, sqlschema.RiskRisky, h.applier.appliedRisk) +} + +// An absent MaxRisk must mean "safe only" rather than "no limit". A request that +// lost the field in transit should refuse to run a destructive migration rather +// than authorise every one of them. +func TestApplyWithoutAnAuthorisedRiskAppliesOnlySafeMigrations(t *testing.T) { + h := newHarness(passwordTarget()) + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-master", "postgres", "master-pw") + h.applier.pending = []sqlschema.PendingMigration{ + {Name: "001_breaking.sql", Risk: sqlschema.RiskBreaking}, + } + + resp := h.executor.Handle(context.Background(), Request{ + Operation: OpApply, + Database: "ordersDb", + Migrations: []MigrationFile{{Name: "001_breaking.sql", Content: "DROP TABLE orders;"}}, + }) + + require.True(t, resp.OK, resp.Error) + assert.Empty(t, resp.Apply.Applied) + require.Len(t, resp.Apply.Blocked, 1) + assert.Equal(t, sqlschema.RiskSafe, h.applier.appliedRisk) +} + +// A file name that is a path could write outside the directory the runner +// created for it, so it is refused rather than cleaned up. +func TestApplyRefusesAMigrationNameThatIsAPath(t *testing.T) { + h := newHarness(passwordTarget()) + h.store("arn:aws:secretsmanager:eu-west-2:1:secret:orders-master", "postgres", "master-pw") + + resp := h.executor.Handle(context.Background(), Request{ + Operation: OpApply, + Database: "ordersDb", + Migrations: []MigrationFile{{Name: "../../etc/passwd", Content: "nope"}}, + }) + + assert.False(t, resp.OK) + assert.Contains(t, resp.Error, "bare file name") +} + +func TestApplyWithNoMigrationsSaysSoRatherThanConnecting(t *testing.T) { + h := newHarness(passwordTarget()) + + resp := h.executor.Handle(context.Background(), Request{ + Operation: OpApply, + Database: "ordersDb", + }) + + assert.False(t, resp.OK) + assert.Contains(t, resp.Error, "no migration files") + assert.Empty(t, h.connStr, "there is nothing to do, so nothing should have been connected to") +} + +func TestAnUnknownOperationNamesTheOnesItSupports(t *testing.T) { + h := newHarness(passwordTarget()) + + resp := h.executor.Handle(context.Background(), Request{ + Operation: "drop-everything", + Database: "ordersDb", + }) + + assert.False(t, resp.OK) + assert.Contains(t, resp.Error, OpApply) + assert.Contains(t, resp.Error, OpProvisionUser) +} diff --git a/apps/cli/internal/maintenancerunner/host.go b/apps/cli/internal/maintenancerunner/host.go new file mode 100644 index 00000000..6c5cacb8 --- /dev/null +++ b/apps/cli/internal/maintenancerunner/host.go @@ -0,0 +1,108 @@ +package maintenancerunner + +import ( + "context" + "fmt" + "os" + "sort" + + "github.com/newstack-cloud/celerity/apps/cli/internal/dbconn" + "go.uber.org/zap" +) + +// Handler receives one maintenance request and always returns a response. +type Handler func(ctx context.Context, req Request) *Response + +// Host is the platform the runner runs on. It covers what delivers invocations +// to the runner and where credentials come from there. +// +// The runner binary itself names no provider. It registers whichever hosts were +// compiled into it, picks the one it is running on, and serves. +type Host interface { + // Name identifies the host platform ("aws"). + Name() string + + // Detect reports whether this process is running on it. Implementations + // should key on something the platform itself sets, not on configuration a + // user could get wrong. + Detect() bool + + // Credentials resolves database credentials from the platform's secret + // store. + Credentials() dbconn.CredentialSource + + // Serve delivers invocations to handle. It does not return in normal + // operation. + Serve(handle Handler, logger *zap.Logger) error +} + +// HostEnvVar overrides host detection. It exists for the case detection cannot +// cover, running the runner somewhere that looks like nothing in particular, +// such as a container during a test. +const HostEnvVar = "CELERITY_MAINTENANCE_HOST" + +var hosts = map[string]Host{} + +// RegisterHost adds a host platform. Called from a provider package's init. +func RegisterHost(host Host) { + hosts[host.Name()] = host +} + +// The host to run on is the one named by HostEnvVar, or failing that the first +// one that detects itself. +func resolveHost() (Host, error) { + if name := os.Getenv(HostEnvVar); name != "" { + host, ok := hosts[name] + if !ok { + return nil, fmt.Errorf("%s is set to %q, which this runner was not built with (it has: %v)", + HostEnvVar, name, registeredHostNames()) + } + return host, nil + } + + for _, host := range hosts { + if host.Detect() { + return host, nil + } + } + return nil, fmt.Errorf( + "could not tell which platform this runner is on (it was built with: %v); set %s", + registeredHostNames(), HostEnvVar) +} + +// HostNames returns the host platforms this binary was built with, sorted. +func HostNames() []string { return registeredHostNames() } + +func registeredHostNames() []string { + names := make([]string, 0, len(hosts)) + for name := range hosts { + names = append(names, name) + } + sort.Strings(names) + return names +} + +// Run starts the maintenance runner. It does not return in normal operation. +// +// Targets are read once at startup rather than per invocation. They are +// deploy-time configuration, and a bad one should fail here rather than on +// whichever invocation happens to land on a fresh execution environment. +func Run(logger *zap.Logger) error { + host, err := resolveHost() + if err != nil { + return err + } + + targets, err := LoadTargets() + if err != nil { + return fmt.Errorf("the maintenance runner is misconfigured: %w", err) + } + + logger.Info("maintenance runner starting", + zap.String("host", host.Name()), + zap.Strings("databases", targets.Names()), + ) + + executor := NewExecutor(targets, host.Credentials(), logger) + return host.Serve(executor.Handle, logger) +} diff --git a/apps/cli/internal/maintenancerunner/host_test.go b/apps/cli/internal/maintenancerunner/host_test.go new file mode 100644 index 00000000..6d82beb3 --- /dev/null +++ b/apps/cli/internal/maintenancerunner/host_test.go @@ -0,0 +1,145 @@ +package maintenancerunner + +import ( + "context" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/dbconn" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +type fakeHost struct { + name string + detected bool + served bool +} + +func (f *fakeHost) Name() string { return f.name } +func (f *fakeHost) Detect() bool { return f.detected } + +func (f *fakeHost) Credentials() dbconn.CredentialSource { + return &fakeCredentials{stored: map[string]dbconn.Credentials{}} +} + +func (f *fakeHost) Serve(_ Handler, _ *zap.Logger) error { + f.served = true + return nil +} + +// withHosts replaces the registry for one test. The registry is package-level +// because hosts register themselves from init, which is the point, but it does +// mean a test has to put it back. +func withHosts(t *testing.T, registered ...Host) { + t.Helper() + previous := hosts + hosts = map[string]Host{} + for _, host := range registered { + RegisterHost(host) + } + t.Cleanup(func() { hosts = previous }) +} + +func TestRunsOnTheHostItDetects(t *testing.T) { + aws := &fakeHost{name: "aws", detected: true} + other := &fakeHost{name: "elsewhere"} + withHosts(t, aws, other) + t.Setenv(TargetsEnvVar, `{"ordersDb":{"engine":"postgres","host":"h","port":"5432"}}`) + + require.NoError(t, Run(zap.NewNop())) + + assert.True(t, aws.served) + assert.False(t, other.served, "only the detected host serves") +} + +// The override exists for the case detection cannot cover, somewhere that looks +// like nothing in particular, such as a container during a test. +func TestTheHostCanBeNamedExplicitly(t *testing.T) { + aws := &fakeHost{name: "aws", detected: true} + other := &fakeHost{name: "elsewhere"} + withHosts(t, aws, other) + t.Setenv(TargetsEnvVar, `{"ordersDb":{"engine":"postgres","host":"h","port":"5432"}}`) + t.Setenv(HostEnvVar, "elsewhere") + + require.NoError(t, Run(zap.NewNop())) + + assert.True(t, other.served) + assert.False(t, aws.served, "the override wins over detection") +} + +// Both startup failures name what the binary was actually built with, because +// the alternative is an operator guessing at a runner that exits immediately. +func TestAnUnknownHostNameListsWhatWasBuiltIn(t *testing.T) { + withHosts(t, &fakeHost{name: "aws", detected: true}) + t.Setenv(HostEnvVar, "gcloud") + + err := Run(zap.NewNop()) + + require.Error(t, err) + assert.Contains(t, err.Error(), "gcloud") + assert.Contains(t, err.Error(), "[aws]") +} + +func TestNoDetectedHostIsAStartupFailure(t *testing.T) { + withHosts(t, &fakeHost{name: "aws"}) + + err := Run(zap.NewNop()) + + require.Error(t, err) + assert.Contains(t, err.Error(), "could not tell which platform") + assert.Contains(t, err.Error(), HostEnvVar) +} + +// Targets are deploy-time configuration: a bad one should stop the runner at +// startup, not on whichever invocation lands on a fresh execution environment. +func TestMisconfiguredTargetsFailAtStartup(t *testing.T) { + host := &fakeHost{name: "aws", detected: true} + withHosts(t, host) + t.Setenv(TargetsEnvVar, "not json") + + err := Run(zap.NewNop()) + + require.Error(t, err) + assert.Contains(t, err.Error(), "misconfigured") + assert.False(t, host.served) +} + +func TestTargetNamesAreSorted(t *testing.T) { + targets := Targets{"ordersDb": {}, "auditDb": {}} + + assert.Equal(t, []string{"auditDb", "ordersDb"}, targets.Names()) +} + +// The handler the host is given is the executor's, so what a host serves is +// exactly what the CLI's requests reach. +func TestTheHostIsGivenTheExecutorsHandler(t *testing.T) { + var handled *Response + host := &handlerCapturingHost{ + fakeHost: fakeHost{name: "aws", detected: true}, + call: func(handle Handler) { + handled = handle(context.Background(), Request{ + Operation: "execute-sql", Database: "ordersDb", + }) + }, + } + withHosts(t, host) + t.Setenv(TargetsEnvVar, `{"ordersDb":{"engine":"postgres","host":"h","port":"5432"}}`) + + require.NoError(t, Run(zap.NewNop())) + + require.NotNil(t, handled) + assert.False(t, handled.OK) + assert.Contains(t, handled.Error, "unknown operation") +} + +type handlerCapturingHost struct { + fakeHost + call func(handle Handler) +} + +func (h *handlerCapturingHost) Serve(handle Handler, _ *zap.Logger) error { + h.served = true + h.call(handle) + return nil +} diff --git a/apps/cli/internal/maintenancerunner/invoke.go b/apps/cli/internal/maintenancerunner/invoke.go new file mode 100644 index 00000000..c0d09139 --- /dev/null +++ b/apps/cli/internal/maintenancerunner/invoke.go @@ -0,0 +1,56 @@ +package maintenancerunner + +import ( + "context" + "fmt" + + "github.com/newstack-cloud/bluelink/libs/blueprint/state" +) + +// Invoker calls a deployed maintenance runner and returns its response. +// +// One implementation per deploy target, selected by InvokerFor, for the same +// reason deploydb has one resolver per target: how a runner is addressed and +// invoked is entirely the provider's business, while what is asked of it is +// not. +type Invoker interface { + // Invoke runs one operation against a deployed runner. It returns an error + // only when the runner could not be reached; an operation that ran and + // failed comes back as a Response with OK false. + Invoke(ctx context.Context, instance *state.InstanceState, req Request) (*Response, error) + + // Deployed reports whether the instance has a runner at all. An instance + // deployed before runners existed, or one whose database is publicly + // reachable, does not. + Deployed(instance *state.InstanceState) bool +} + +// newInvoker is the per-target registry. Providers register into it from their +// own package so this file has no dependency on any of them. +var newInvoker = map[string]func() Invoker{} + +// RegisterInvoker adds a deploy target's invoker. Called from a provider +// package's init. +func RegisterInvoker(deployTarget string, build func() Invoker) { + newInvoker[deployTarget] = build +} + +// InvokerFor returns the maintenance runner invoker for a deploy target. +func InvokerFor(deployTarget string) (Invoker, error) { + if build, ok := newInvoker[deployTarget]; ok { + return build(), nil + } + return nil, fmt.Errorf( + "running database maintenance operations is not yet supported for deploy target %q", + deployTarget) +} + +// Annotations the transformer stamps on a deployed runner so the CLI can find +// it in instance state without knowing what the provider named it. +const ( + // RunnerAnnotation marks the concrete resource that is the runner. + RunnerAnnotation = "celerity.maintenance.runner" + + // RunnerAnnotationValue is the value RunnerAnnotation carries. + RunnerAnnotationValue = "true" +) diff --git a/apps/cli/internal/maintenancerunner/protocol.go b/apps/cli/internal/maintenancerunner/protocol.go new file mode 100644 index 00000000..83191b9e --- /dev/null +++ b/apps/cli/internal/maintenancerunner/protocol.go @@ -0,0 +1,262 @@ +// Package maintenancerunner defines the contract between the Celerity CLI and +// the maintenance runner, and implements the runner side of it. +// +// A Celerity SQL database sits on a private network, so nothing outside it can +// open a connection, including the machine the operator runs `celerity schema` +// from. The runner closes that gap without asking anyone to build network +// access. It is deployed inside the network, where it has a data-plane path to +// the database, and invoked over the provider's control plane, which is +// reachable with the same credentials that just ran the deploy. +// +// What crosses the boundary is the *operation*, not the connection. The CLI +// requests "provision the application user on ordersDb"; the runner performs it +// against a local connection and returns a report. Provisioning and migration +// run through the same internal/sqlschema package in both places, so there is +// no second implementation to keep in step. +// +// # Provider boundaries +// +// Everything in this package is cloud-neutral: the request and response format, +// the target configuration, dispatch and the operations themselves. Two things +// are not, and both live outside it. How the runner is hosted and invoked is the +// awsrunner sub-package's business, and where credentials come from is a +// dbconn.CredentialSource's. Adding a provider means adding those two, not +// changing this. +// +// # Why the request does not describe the database +// +// A request names a database; it does not carry a host, a port or a credential. +// Everything needed to connect is stamped into the runner's own configuration +// at deploy time (see TargetsEnvVar). A caller therefore cannot point the +// runner at a database of their choosing, and the set of things it will ever +// connect to is fixed by the blueprint rather than by whoever holds permission +// to invoke it. +package maintenancerunner + +import ( + "encoding/json" + "fmt" + "os" + "sort" + + "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" +) + +// Operations the runner accepts. +// +// Provisioning and ping are named routines that execute no SQL they are handed. +// Apply is different and deliberately so, because migrations *are* SQL written +// by the author of the blueprint and there is no way to run them inside the +// network without carrying them in. What bounds it is the invoking identity +// rather than the payload. The runner's own permissions reach exactly the +// databases the blueprint gave it, and a caller must already hold invoke +// permission on it, which is the same permission that could otherwise redeploy +// the function outright. The migration set is also checksum-verified against +// atlas.sum +// before anything runs, so a payload that disagrees with the directory it +// claims to be is rejected rather than applied. +const ( + // OpProvisionUser creates or repairs the application database user. + OpProvisionUser = "provision-user" + + // OpPing checks the runner can reach and authenticate to a database. It + // exists so a deploy can verify the path works without changing anything. + OpPing = "ping" + + // OpApply applies pending migrations, as the database owner. + OpApply = "apply" +) + +// TargetsEnvVar is the environment variable the transformer stamps the runner's +// database targets into, as a JSON object keyed by the abstract database name. +// +// An environment variable rather than a config store because it is the one +// piece of configuration every host platform supplies the same way. AWS Lambda +// caps environment variables at 4KB in total, which holds on the order of ten +// databases; beyond that the targets need to move to a parameter, which is a +// change to this constant's contract and nothing else. +const TargetsEnvVar = "CELERITY_MAINTENANCE_TARGETS" + +// Request is the Lambda invocation payload. +type Request struct { + // Operation is one of the Op constants. + Operation string `json:"operation"` + + // Database is the abstract name of the celerity/sqlDatabase to act on, as + // written in the blueprint. + Database string `json:"database"` + + // Migrations carries the migration directory for OpApply, because the files + // live on the operator's machine and the runner has no access to it. + // + // A synchronous Lambda invocation caps its payload at 6MB, which is far more + // than a migration directory of text files, but ApplyLimits is checked + // before invoking so an oversized set is reported as such rather than as a + // truncated request. + Migrations []MigrationFile `json:"migrations,omitempty"` + + // MaxRisk is the highest migration risk level the operator authorised, from + // the same --allow-risky and --allow-breaking flags the local path uses. An + // empty value permits only safe migrations. + MaxRisk string `json:"maxRisk,omitempty"` +} + +// MigrationFile is one file from the migration directory, including atlas.sum. +type MigrationFile struct { + // Name is the base file name, never a path. The runner writes these into a + // directory of its own, and a separator here would let a payload write + // outside it. + Name string `json:"name"` + + // Content is the file's bytes as text. Migration files are SQL and the sum + // file is text, so nothing here needs encoding. + Content string `json:"content"` +} + +// Response is the Lambda invocation result. +// +// A failed operation is a successful invocation with OK false rather than a +// Lambda error. The distinction matters because a Lambda error gives the CLI a +// stack trace and no report, while this gives it something to print. +type Response struct { + Operation string `json:"operation"` + Database string `json:"database"` + OK bool `json:"ok"` + + // Error describes why the operation failed, in terms an operator can act on. + Error string `json:"error,omitempty"` + + // Provision is the report from OpProvisionUser. + Provision *sqlschema.ProvisionReport `json:"provision,omitempty"` + + // Apply is the report from OpApply. + Apply *ApplyReport `json:"apply,omitempty"` +} + +// ApplyReport describes what a migration run did, in the same terms the local +// path prints so an operator cannot tell from the output which route was taken. +type ApplyReport struct { + // Applied names the migrations that ran, in order. Empty when the database + // was already up to date. + Applied []string `json:"applied,omitempty"` + + // Blocked names migrations that were left unapplied because their risk + // exceeds what the operator authorised, with the risk that stopped them. + Blocked []BlockedMigration `json:"blocked,omitempty"` +} + +// BlockedMigration is a pending migration held back by the risk gate. +type BlockedMigration struct { + Name string `json:"name"` + Risk string `json:"risk"` +} + +// Changed reports whether the run altered the database. +func (r *ApplyReport) Changed() bool { + return r != nil && len(r.Applied) > 0 +} + +// Failed builds an unsuccessful response for a request. +func (r Request) Failed(err error) *Response { + return &Response{ + Operation: r.Operation, + Database: r.Database, + OK: false, + Error: err.Error(), + } +} + +// Target is everything the runner needs to reach one database as its +// owner/master, and to determine what to provision on it. +// +// Only references travel here, never a credential. What a reference looks like +// is the provider's business (an ARN on AWS today), and the runner resolves it +// through a dbconn.CredentialSource. Its deployed identity is granted exactly +// the references listed here for each database, so what it can read is visible +// in the deployed policy rather than in a payload. +type Target struct { + // Engine is "postgres" or "mysql". + Engine string `json:"engine"` + + // Host and Port are the connection-pool endpoint where there is one, + // otherwise the database's own endpoint. + Host string `json:"host"` + Port string `json:"port"` + + // Database is the database name to connect to. + Database string `json:"database"` + + // OwnerCredentialRef points at the master/owner credential, the role + // migrations run as. Empty when the database authenticates its owner with a + // platform-issued token instead. + OwnerCredentialRef string `json:"ownerCredentialRef,omitempty"` + + // OwnerUser and Region are what a token is issued for, when + // OwnerCredentialRef is empty. + OwnerUser string `json:"ownerUser,omitempty"` + Region string `json:"region,omitempty"` + + // AppUser is the role the application connects as. + AppUser string `json:"appUser"` + + // AppUserCredentialRef points at the application user's generated password. + // Empty when the application authenticates with a token, which needs no + // stored credential. + AppUserCredentialRef string `json:"appUserCredentialRef,omitempty"` + + // AppUserTokenAuth selects platform-issued token authentication (AWS IAM + // database authentication, and its equivalents) for the application user. + AppUserTokenAuth bool `json:"appUserTokenAuth,omitempty"` +} + +// Targets is the runner's deploy-time configuration, keyed by abstract database +// name. +type Targets map[string]*Target + +// LoadTargets reads the runner's targets from its environment. +func LoadTargets() (Targets, error) { + raw := os.Getenv(TargetsEnvVar) + if raw == "" { + return nil, fmt.Errorf( + "%s is not set; the runner was deployed without any database targets", TargetsEnvVar) + } + return ParseTargets(raw) +} + +// ParseTargets parses the targets JSON. +func ParseTargets(raw string) (Targets, error) { + var targets Targets + if err := json.Unmarshal([]byte(raw), &targets); err != nil { + return nil, fmt.Errorf("parsing %s: %w", TargetsEnvVar, err) + } + return targets, nil +} + +// Names returns the databases this runner serves, sorted. +func (t Targets) Names() []string { + names := make([]string, 0, len(t)) + for name := range t { + names = append(names, name) + } + sort.Strings(names) + return names +} + +// Lookup returns the target for a database. A name that does not match is far +// more often a stale deploy than a typo, so the error lists the databases this +// runner is configured for. +func (t Targets) Lookup(database string) (*Target, error) { + if target, ok := t[database]; ok { + return target, nil + } + known := make([]string, 0, len(t)) + for name := range t { + known = append(known, name) + } + if len(known) == 0 { + return nil, fmt.Errorf("this runner has no database targets configured") + } + return nil, fmt.Errorf( + "no database named %q on this runner (it serves: %v); the deployed instance may predate the database", + database, known) +} diff --git a/apps/cli/internal/seed/config_keys_contract_test.go b/apps/cli/internal/seed/config_keys_contract_test.go new file mode 100644 index 00000000..233745dc --- /dev/null +++ b/apps/cli/internal/seed/config_keys_contract_test.go @@ -0,0 +1,126 @@ +package seed + +import ( + "sort" + "strings" + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/stretchr/testify/suite" +) + +// The keys each resource type contributes to the "resources" config namespace, +// pinned so this seeder and the AWS transformer cannot drift apart unnoticed. +// +// Both write the same namespace, read by the same SDK layers, but they are in +// separate repositories with no dependency between them, so nothing but a test +// on each side keeps them honest. The transformer's half lives in +// bluelink-transformer-celerity/transformer/resources_store_cache_test.go. +// +// This has already gone wrong once and cost a day. The transformer implemented +// the namespace for queue, topic, datastore and bucket only, while this seeder +// covered all six, so local development worked perfectly and every deployed +// handler touching a cache or a database failed at cold start on `Config +// namespace "resources" not registered`, after deploying entirely cleanly. +// +// Deployed values differ from these, and should. A real cache has a generated +// AUTH token in a secret store and the namespace carries a reference to it +// (`_authTokenSecretId`), where local development has no password at all. +// What must not differ is the set of keys the SDK can rely on finding. +type ConfigKeysContractTestSuite struct { + suite.Suite +} + +func TestConfigKeysContractTestSuite(t *testing.T) { + suite.Run(t, new(ConfigKeysContractTestSuite)) +} + +func (s *ConfigKeysContractTestSuite) suffixesFor(values map[string]string, name string) []string { + suffixes := []string{} + for key := range values { + if suffix, found := strings.CutPrefix(key, name); found { + suffixes = append(suffixes, suffix) + } + } + sort.Strings(suffixes) + return suffixes +} + +func (s *ConfigKeysContractTestSuite) Test_cache_keys() { + bp := loadBlueprintFor(s, ` +version: 2025-11-02 +resources: + sessions: + type: "celerity/cache" + spec: + name: sessions +`) + + // There is no _authTokenSecretId because there is no secret store locally, + // and no password on the local Valkey. The deployed side adds it. + s.Equal( + []string{"_authMode", "_clusterMode", "_host", "_port", "_tls"}, + s.suffixesFor(ResourceConfigValues(bp), "sessions"), + ) +} + +func (s *ConfigKeysContractTestSuite) Test_sql_database_keys() { + bp := loadBlueprintFor(s, ` +version: 2025-11-02 +resources: + auditDb: + type: "celerity/sqlDatabase" + spec: + engine: postgres + name: audit + schemaPath: "./schemas/audit-db.yaml" +`) + + // The deployed side does not write these yet, because a deployed database + // has no application user to hand out credentials for. See the in-VPC + // maintenance runner design in docs/schema-commands/. + s.Equal( + []string{ + "_authMode", + "_database", + "_engine", + "_host", + "_password", + "_port", + "_ssl", + "_user", + }, + s.suffixesFor(ResourceConfigValues(bp), "audit"), + ) +} + +// The four simple types are a single identifier each: a queue URL, a topic ARN, +// a table name, a bucket name. Nothing to authenticate with, which is why they +// were the four the deploy path managed to implement. +func (s *ConfigKeysContractTestSuite) Test_simple_types_are_a_single_key() { + bp := loadBlueprintFor(s, ` +version: 2025-11-02 +resources: + usersTable: + type: "celerity/datastore" + spec: + name: users + tasks: + type: "celerity/queue" + spec: + name: taskQueue +`) + + values := ResourceConfigValues(bp) + + s.Equal([]string{""}, s.suffixesFor(values, "users")) + s.Equal([]string{""}, s.suffixesFor(values, "taskQueue")) +} + +// Separate from the sibling suite's parsing helper so neither suite depends on +// the other's fixtures. +func loadBlueprintFor(s *ConfigKeysContractTestSuite, yamlContent string) *schema.Blueprint { + bp, err := schema.LoadString(yamlContent, schema.YAMLSpecFormat) + s.Require().NoError(err, "failed to load test blueprint") + return bp +} diff --git a/apps/cli/internal/seed/config_seeder.go b/apps/cli/internal/seed/config_seeder.go index 49dbd7af..668bf5d3 100644 --- a/apps/cli/internal/seed/config_seeder.go +++ b/apps/cli/internal/seed/config_seeder.go @@ -63,7 +63,6 @@ func NewValkeyConfigSeeder(endpoint string, logger *zap.Logger) (*ValkeyConfigSe func (s *ValkeyConfigSeeder) SeedConfig(ctx context.Context, storeID string, values map[string]string) error { merged := make(map[string]string) - // Read existing data if present. existing, err := s.client.Get(ctx, storeID).Result() if err == nil && existing != "" { if jsonErr := json.Unmarshal([]byte(existing), &merged); jsonErr != nil { @@ -191,11 +190,11 @@ func ConfigStoreIDEnvVars(bp *schema.Blueprint) map[string]string { // Set the NAMESPACE so the SDK's config layer registers the namespace // under the original camelCase name (e.g. "appConfig") rather than the // lowercased env-var-derived name (e.g. "appconfig"). - // STORE_PREFIX is intentionally not set for local dev — each config - // namespace has its own dedicated Valkey key so there is no shared - // key space requiring prefix-based filtering. STORE_PREFIX is used - // in deployed environments (e.g. AWS SSM Parameter Store) where keys - // share a path prefix. + // STORE_PREFIX is intentionally not set for local dev, where each + // config namespace has its own dedicated Valkey key and there is no + // shared key space to filter by prefix. It is used in deployed + // environments such as AWS SSM Parameter Store, where keys share a + // path prefix. configNamespaceKey := fmt.Sprintf("CELERITY_CONFIG_%s_NAMESPACE", upper) envVars[configNamespaceKey] = cfg.StoreName } @@ -238,9 +237,8 @@ func ResourceConfigValues(bp *schema.Blueprint) map[string]string { return values } -// cacheConfigValues generates credential config keys for celerity/cache resources. -// The SDK's CacheLayer reads {configKey}_host, _port, _authMode, _tls from the -// resources namespace. +// The SDK's CacheLayer reads {configKey}_host, _port, _authMode and _tls from +// the resources namespace. func cacheConfigValues(bp *schema.Blueprint) map[string]string { values := map[string]string{} for _, resource := range bp.Resources.Values { @@ -260,9 +258,9 @@ func cacheConfigValues(bp *schema.Blueprint) map[string]string { return values } -// simpleResourceConfigValues generates config keys for resources of the given type -// where the config key and value are both the resource's spec.name (or the resource -// name as fallback). Used for datastore, bucket, queue, and topic resources. +// Covers datastore, bucket, queue and topic resources, where the config key and +// the value are both the resource's spec.name, falling back to the resource +// name. func simpleResourceConfigValues(bp *schema.Blueprint, resourceType string) map[string]string { values := map[string]string{} for resourceName, resource := range bp.Resources.Values { @@ -278,10 +276,7 @@ func simpleResourceConfigValues(bp *schema.Blueprint, resourceType string) map[s return values } -// sqlDatabaseConfigValues generates the credential config keys for all -// celerity/sqlDatabase resources in the blueprint. -// -// For each database resource with spec.name "audit", generates: +// A database resource with spec.name "audit" yields the keys // // audit_host, audit_port, audit_database, audit_user, // audit_password, audit_engine, audit_authMode, audit_ssl diff --git a/apps/cli/internal/seed/dynamodb.go b/apps/cli/internal/seed/dynamodb.go index a2812341..5bc309c6 100644 --- a/apps/cli/internal/seed/dynamodb.go +++ b/apps/cli/internal/seed/dynamodb.go @@ -91,7 +91,6 @@ func (s *DynamoDBSeeder) PutItem(ctx context.Context, tableName string, itemJSON return nil } -// toTableInput converts a seed.TableDefinition to a dynamoconv.TableInput. func toTableInput(td TableDefinition) dynamoconv.TableInput { ti := dynamoconv.TableInput{ Name: td.Name, diff --git a/apps/cli/internal/seed/handler_scope.go b/apps/cli/internal/seed/handler_scope.go new file mode 100644 index 00000000..8d9d86e0 --- /dev/null +++ b/apps/cli/internal/seed/handler_scope.go @@ -0,0 +1,103 @@ +package seed + +import ( + "encoding/json" + "sort" + "strings" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/newstack-cloud/bluelink/libs/blueprint/substitutions" +) + +// HandlerScopeFilename is the file the CLI writes so a handler can resolve +// which of the application's resources it actually uses. +// +// The resource links file describes what each resource is, which is a property +// of the application and identical for every handler. This file records which +// of those a given handler touches, which is a property of the handler. +// +// One bundle serves every function, so the resource links file necessarily +// describes the whole application. With nothing else to go on, the SDK's +// resource layers took it as their scope and every handler initialised every +// resource type present anywhere in the app. A handler using nothing but its own +// config still resolved the internal resources namespace, and failed at cold +// start on `Config namespace "resources" not registered`. +const HandlerScopeFilename = "handler-scope.json" + +// The per-handler resource list the metadata extractor derives by walking the +// dependency injection graph, including through services a handler only reaches +// indirectly. +const resourceRefAnnotationKey = "celerity.handler.resource.ref" + +// HandlerScopeJSON maps each handler's id to the resources it uses. +// +// Keyed by handler id, the value of spec.handler such as +// "app-module.StatsController.check", because that is what reaches the running +// function as CELERITY_HANDLER_ID and so the only thing a handler can identify +// itself by at cold start. +// +// An entry with an empty list is meaningful and is written, recording that the +// handler reaches nothing and so must not initialise anything. That differs from +// having no entry at all, which happens for an older bundle or a handler whose +// id could not be determined. The SDK treats a missing entry as the whole +// application being in scope, degrading to the behaviour that existed before +// this file rather than to a handler that silently reaches nothing. +func HandlerScopeJSON(bp *schema.Blueprint) (string, error) { + if bp == nil || bp.Resources == nil { + return "", nil + } + + scope := map[string][]string{} + for _, resource := range bp.Resources.Values { + if resource.Type == nil || resource.Type.Value != "celerity/handler" { + continue + } + + handlerID := extractSpecStringField(resource, "handler") + if handlerID == "" { + continue + } + + refs := annotationStringList(resource, resourceRefAnnotationKey) + sort.Strings(refs) + scope[handlerID] = refs + } + + if len(scope) == 0 { + return "", nil + } + + data, err := json.Marshal(scope) + if err != nil { + return "", err + } + return string(data), nil +} + +// Annotations are string scalars, so the merger joins a list with commas when it +// writes one (see formatAnnotationValue) and this reverses that. An empty slice +// rather than nil is returned so an absent annotation serialises as [] and keeps +// the "reaches nothing" case distinguishable from an absent handler. +func annotationStringList(resource *schema.Resource, key string) []string { + if resource.Metadata == nil || resource.Metadata.Annotations == nil { + return []string{} + } + + node, ok := resource.Metadata.Annotations.Values[key] + if !ok || node == nil { + return []string{} + } + + joined, err := substitutions.SubstitutionsToString("", node) + if err != nil || joined == "" { + return []string{} + } + + refs := []string{} + for _, part := range strings.Split(joined, ",") { + if trimmed := strings.TrimSpace(part); trimmed != "" { + refs = append(refs, trimmed) + } + } + return refs +} diff --git a/apps/cli/internal/seed/handler_scope_test.go b/apps/cli/internal/seed/handler_scope_test.go new file mode 100644 index 00000000..c8da4da2 --- /dev/null +++ b/apps/cli/internal/seed/handler_scope_test.go @@ -0,0 +1,117 @@ +package seed + +import ( + "encoding/json" + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/stretchr/testify/suite" +) + +type HandlerScopeTestSuite struct { + suite.Suite +} + +func TestHandlerScopeTestSuite(t *testing.T) { + suite.Run(t, new(HandlerScopeTestSuite)) +} + +func (s *HandlerScopeTestSuite) scopeOf(yamlContent string) map[string][]string { + bp, err := schema.LoadString(yamlContent, schema.YAMLSpecFormat) + s.Require().NoError(err) + + payload, err := HandlerScopeJSON(bp) + s.Require().NoError(err) + + scope := map[string][]string{} + if payload != "" { + s.Require().NoError(json.Unmarshal([]byte(payload), &scope)) + } + return scope +} + +// Keyed by handler id, because that is what reaches the function as +// CELERITY_HANDLER_ID and so the only thing it can identify itself by. +func (s *HandlerScopeTestSuite) Test_scope_is_keyed_by_handler_id() { + scope := s.scopeOf(` +version: 2025-11-02 +resources: + statsAggregate: + type: "celerity/handler" + metadata: + annotations: + celerity.handler.resource.ref: "appCache" + spec: + handlerName: scheduledAggregate + handler: app-module.StatsController.scheduledAggregate + runtime: nodejs24.x +`) + + s.Equal( + map[string][]string{ + "app-module.StatsController.scheduledAggregate": {"appCache"}, + }, + scope, + ) +} + +// The extractor derives refs by walking the injection graph, so a handler that +// reaches a database only through a service still declares it. Several refs +// arrive comma-joined, because annotations are string scalars. +func (s *HandlerScopeTestSuite) Test_multiple_refs_are_split() { + scope := s.scopeOf(` +version: 2025-11-02 +resources: + auditCreate: + type: "celerity/handler" + metadata: + annotations: + celerity.handler.resource.ref: "auditDatabase,appConfig" + spec: + handlerName: createEntry + handler: app-module.AuditController.createEntry + runtime: nodejs24.x +`) + + s.Equal( + []string{"appConfig", "auditDatabase"}, + scope["app-module.AuditController.createEntry"], + ) +} + +// The case the whole file exists for. A handler that reaches nothing gets an +// entry with an empty list, which is what stops it initialising every resource +// the application happens to declare. An empty list and a missing entry mean +// different things, since a missing entry falls back to the whole +// application. +func (s *HandlerScopeTestSuite) Test_handler_reaching_nothing_gets_an_empty_list() { + scope := s.scopeOf(` +version: 2025-11-02 +resources: + health: + type: "celerity/handler" + spec: + handlerName: check + handler: app-module.HealthController.check + runtime: nodejs24.x +`) + + refs, present := scope["app-module.HealthController.check"] + s.True(present, "a handler with no refs must still appear, or it falls back to everything") + s.Empty(refs) +} + +// Only handlers carry scope; the resources they point at are described by the +// resource links file instead. +func (s *HandlerScopeTestSuite) Test_non_handler_resources_are_ignored() { + scope := s.scopeOf(` +version: 2025-11-02 +resources: + appCache: + type: "celerity/cache" + spec: + name: sessions +`) + + s.Empty(scope) +} diff --git a/apps/cli/internal/seed/hooks.go b/apps/cli/internal/seed/hooks.go index 3613cb95..4571f194 100644 --- a/apps/cli/internal/seed/hooks.go +++ b/apps/cli/internal/seed/hooks.go @@ -80,7 +80,6 @@ func runHook( return fmt.Errorf("starting hook %s: %w", scriptName, err) } - // Stream both stdout and stderr concurrently. done := make(chan struct{}, 2) go streamLines(stdoutPipe, scriptName, false, onOutput, done) go streamLines(stderrPipe, scriptName, true, onOutput, done) @@ -133,7 +132,7 @@ func checkExecutable(path string) error { if runtime.GOOS != "windows" && info.Mode()&0o111 == 0 { return fmt.Errorf( - "hook script %s is not executable — run: chmod +x %s", + "hook script %s is not executable. Run chmod +x %s to fix it", filepath.Base(path), path, ) } diff --git a/apps/cli/internal/seed/loader.go b/apps/cli/internal/seed/loader.go index 3ef2c00c..6e5f5e36 100644 --- a/apps/cli/internal/seed/loader.go +++ b/apps/cli/internal/seed/loader.go @@ -113,8 +113,8 @@ func ResolveSecretsDir(appDir string, mode string) string { return filepath.Join(appDir, "secrets", "local") } -// loadNoSQLSeed reads subdirectories of nosql/, each representing a table. -// Each .json file in a subdirectory is a single record. +// Each subdirectory of nosql/ is a table and each .json file within it a single +// record. func loadNoSQLSeed(nosqlDir string) ([]NoSQLTableSeed, error) { if _, err := os.Stat(nosqlDir); os.IsNotExist(err) { return nil, nil @@ -150,8 +150,8 @@ func loadNoSQLSeed(nosqlDir string) ([]NoSQLTableSeed, error) { return tables, nil } -// loadSQLSeed reads subdirectories of sql/, each representing a database. -// Each .sql file in a subdirectory is a seed script executed in filename-sorted order. +// Each subdirectory of sql/ is a database and each .sql file within it a seed +// script, executed in filename-sorted order. func loadSQLSeed(sqlDir string) ([]SQLDatabaseSeed, error) { if _, err := os.Stat(sqlDir); os.IsNotExist(err) { return nil, nil @@ -229,7 +229,6 @@ func loadHooks(hooksDir string) ([]string, error) { return collectFiles(hooksDir, ".sh") } -// collectFiles returns sorted absolute paths of files with the given extension. func collectFiles(dir string, ext string) ([]string, error) { entries, err := os.ReadDir(dir) if err != nil { @@ -251,7 +250,7 @@ func collectFiles(dir string, ext string) ([]string, error) { return files, nil } -// collectAllFiles returns sorted absolute paths of all files in a directory (non-recursive). +// Not recursive. func collectAllFiles(dir string) ([]string, error) { entries, err := os.ReadDir(dir) if err != nil { diff --git a/apps/cli/internal/seed/minio.go b/apps/cli/internal/seed/minio.go index 39ab8dc0..c1bb58fc 100644 --- a/apps/cli/internal/seed/minio.go +++ b/apps/cli/internal/seed/minio.go @@ -101,7 +101,6 @@ func (u *MinIOUploader) Upload( // DetectContentType determines the MIME type for an object by extension, // falling back to http.DetectContentType for unrecognised extensions. func DetectContentType(objectKey string, data []byte) string { - // Try extension-based detection first for common types. ext := filepath.Ext(objectKey) switch ext { case ".json": @@ -126,6 +125,5 @@ func DetectContentType(objectKey string, data []byte) string { return "text/plain" } - // Fall back to content sniffing. return http.DetectContentType(data) } diff --git a/apps/cli/internal/seed/resource_links.go b/apps/cli/internal/seed/resource_links.go index 8b592dea..ec7b701e 100644 --- a/apps/cli/internal/seed/resource_links.go +++ b/apps/cli/internal/seed/resource_links.go @@ -6,14 +6,14 @@ import ( "github.com/newstack-cloud/bluelink/libs/blueprint/schema" ) -// resourceLink describes a single resource in the CELERITY_RESOURCE_LINKS topology. +// One resource in the CELERITY_RESOURCE_LINKS topology. type resourceLink struct { Type string `json:"type"` ConfigKey string `json:"configKey"` } -// blueprintTypeToLinkType maps blueprint resource type strings to the link type -// names expected by the SDK's resource layers. +// Blueprint resource types mapped onto the link type names the SDK's resource +// layers expect. var blueprintTypeToLinkType = map[string]string{ "celerity/datastore": "datastore", "celerity/sqlDatabase": "sqlDatabase", @@ -35,7 +35,10 @@ var blueprintTypeToLinkType = map[string]string{ // // The configKey is derived from spec.name (falling back to the resource name). func ResourceLinksJSON(bp *schema.Blueprint) (string, error) { - if bp.Resources == nil { + // A nil blueprint is not an error. The Lambda build bundles an empty links + // file when it has no blueprint to derive one from, so the SDK finds the + // file absent of links rather than missing altogether. + if bp == nil || bp.Resources == nil { return "", nil } diff --git a/apps/cli/internal/sqlschema/applier.go b/apps/cli/internal/sqlschema/applier.go index f8a2eba2..0944f8f9 100644 --- a/apps/cli/internal/sqlschema/applier.go +++ b/apps/cli/internal/sqlschema/applier.go @@ -3,19 +3,23 @@ package sqlschema import ( "context" "database/sql" + "errors" "fmt" "os" - "time" + "path/filepath" + "strings" - _ "github.com/jackc/pgx/v5/stdlib" + "ariga.io/atlas/sql/migrate" + atlasschema "ariga.io/atlas/sql/schema" "go.uber.org/zap" ) -const migrationsTable = "celerity_schema_migrations" +const sumFileName = "atlas.sum" -// Applier applies SQL schemas and migration scripts to a database. -// It tracks applied migrations in a celerity_schema_migrations table. -// Engine-specific SQL is delegated to a dialect implementation. +// Applier connects to a SQL database and applies schemas and migrations to it, +// backed by the embedded Atlas engine. Migration history is tracked in the +// atlas_schema_revisions table (see pgRevisions). Engine-specific connection +// concerns are delegated to a dialect implementation. type Applier struct { db *sql.DB dialect dialect @@ -30,7 +34,12 @@ func NewApplier(engine string, connStr string, logger *zap.Logger) (*Applier, er return nil, err } - db, err := sql.Open(d.DriverName(), connStr) + normConnStr, err := d.NormalizeConnString(connStr) + if err != nil { + return nil, err + } + + db, err := sql.Open(d.DriverName(), normConnStr) if err != nil { return nil, fmt.Errorf("connecting to %s: %w", engine, err) } @@ -40,7 +49,7 @@ func NewApplier(engine string, connStr string, logger *zap.Logger) (*Applier, er return nil, fmt.Errorf("pinging %s: %w", engine, err) } - return &Applier{db: db, dialect: d, connStr: connStr, logger: logger}, nil + return &Applier{db: db, dialect: d, connStr: normConnStr, logger: logger}, nil } // Close releases the database connection. @@ -51,12 +60,12 @@ func (a *Applier) Close() error { // EnsureDatabase creates a database if it does not already exist. // Must be called on an Applier connected to the admin database. func (a *Applier) EnsureDatabase(ctx context.Context, dbName string) error { - var exists bool - err := a.db.QueryRowContext(ctx, a.dialect.DatabaseExistsQuery(), dbName).Scan(&exists) + var count int + err := a.db.QueryRowContext(ctx, a.dialect.DatabaseExistsQuery(), dbName).Scan(&count) if err != nil { return fmt.Errorf("checking if database %q exists: %w", dbName, err) } - if exists { + if count > 0 { a.logger.Debug("database already exists", zap.String("database", dbName)) return nil } @@ -70,6 +79,57 @@ func (a *Applier) EnsureDatabase(ctx context.Context, dbName string) error { return nil } +// DropDatabase removes a database if it exists. Must be called on an Applier +// connected to the admin database, with nothing else connected to the target. +func (a *Applier) DropDatabase(ctx context.Context, dbName string) error { + _, err := a.db.ExecContext(ctx, a.dialect.DropDatabaseSQL(a.dialect.QuoteIdentifier(dbName))) + if err != nil { + return fmt.Errorf("dropping database %q: %w", dbName, err) + } + return nil +} + +// HasUncommittedSchemaChanges reports whether the schema YAML describes changes +// that no committed migration covers. It answers the same question as +// `schema diff --check`, but against a scratch database on the connection this +// Applier already holds rather than a throwaway container. +// +// Must be called on an Applier connected to the admin database. The scratch +// database is created empty, replayed into, and dropped again. +func (a *Applier) HasUncommittedSchemaChanges( + ctx context.Context, + schemaPath, migrationsPath, engine, scratchDBName string, +) (bool, error) { + if schemaPath == "" { + return false, nil + } + hasFiles, err := hasMigrationFiles(migrationsPath) + if err != nil || !hasFiles { + return false, err + } + + // Drop first: a scratch database left behind by an interrupted run would + // otherwise fail the replay, which needs an empty database. + if err := a.DropDatabase(ctx, scratchDBName); err != nil { + return false, err + } + if err := a.EnsureDatabase(ctx, scratchDBName); err != nil { + return false, err + } + defer func() { + if err := a.DropDatabase(ctx, scratchDBName); err != nil { + a.logger.Debug("could not drop scratch database", + zap.String("database", scratchDBName), zap.Error(err)) + } + }() + + scratchConnStr, err := a.dialect.ReplaceDatabase(a.connStr, scratchDBName) + if err != nil { + return false, err + } + return CheckPendingMigration(ctx, scratchConnStr, schemaPath, migrationsPath, engine) +} + // ForDatabase returns a new Applier connected to a specific database, // derived from the original connection string by replacing the database path. func (a *Applier) ForDatabase(dbName string) (*Applier, error) { @@ -77,6 +137,10 @@ func (a *Applier) ForDatabase(dbName string) (*Applier, error) { if err != nil { return nil, err } + newConnStr, err = a.dialect.NormalizeConnString(newConnStr) + if err != nil { + return nil, err + } db, err := sql.Open(a.dialect.DriverName(), newConnStr) if err != nil { @@ -90,232 +154,244 @@ func (a *Applier) ForDatabase(dbName string) (*Applier, error) { return &Applier{db: db, dialect: a.dialect, connStr: newConnStr, logger: a.logger}, nil } -func (a *Applier) ensureMigrationsTable(ctx context.Context) error { - _, err := a.db.ExecContext(ctx, a.dialect.CreateMigrationsTableSQL(migrationsTable)) - return err +func (a *Applier) atlasDriver() (migrate.Driver, error) { + return a.dialect.OpenAtlas(a.db) } -func (a *Applier) appliedVersions(ctx context.Context) (map[int]bool, error) { - rows, err := a.db.QueryContext(ctx, a.dialect.SelectVersionsSQL(migrationsTable)) +// Apply brings the connected database up to date for local development. +// +// Once a migration directory exists it is the only source of schema changes, so +// a local database comes up from exactly the migration history every other +// environment runs. Uncommitted schema YAML edits are reported separately (see +// HasUncommittedSchemaChanges) rather than being silently applied on top. +// Reconciling the YAML declaratively over a migrated database would drop +// anything the YAML cannot model, including hand-written indexes, triggers and +// the migration-history table itself. +// +// The schema YAML is applied declaratively only before the first migration +// exists, so a new project gets a working local database without having to run +// `celerity schema diff` first. +// +// The risk gate is fully open here (local dev applies everything); the gate is +// for deployed/live databases (see `schema apply`). +func (a *Applier) Apply(ctx context.Context, schemaPath, migrationsPath, engine string) error { + hasFiles, err := hasMigrationFiles(migrationsPath) if err != nil { - return nil, err + return err } - defer rows.Close() - - versions := map[int]bool{} - for rows.Next() { - var v int - if err := rows.Scan(&v); err != nil { - return nil, err - } - versions[v] = true + if hasFiles { + return a.ApplyMigrationDir(ctx, migrationsPath, RiskBreaking) } - return versions, rows.Err() -} - -func (a *Applier) recordVersion(ctx context.Context, version int, description string) error { - _, err := a.db.ExecContext(ctx, a.dialect.InsertVersionSQL(migrationsTable), - version, description, time.Now(), - ) - return err -} - -func (a *Applier) removeVersion(ctx context.Context, version int) error { - _, err := a.db.ExecContext(ctx, a.dialect.DeleteVersionSQL(migrationsTable), version) - return err + return a.ApplyDeclarative(ctx, schemaPath, engine) } -// ApplySchema parses a schema YAML file and executes the up DDL statements. -func (a *Applier) ApplySchema(ctx context.Context, schemaPath string, engine string) error { +// ApplyDeclarative brings the connected database into line with the desired +// state described by a schema YAML file, applying the diff directly without +// writing migration files. This is the local-development path: it keeps the +// schema YAML as the source of truth for ephemeral databases. Committed +// migrations (via `celerity schema diff`) are applied by ApplyMigrationDir. +func (a *Applier) ApplyDeclarative(ctx context.Context, schemaPath, engine string) error { if schemaPath == "" { return nil } - s, err := ParseSchemaFile(schemaPath) + parsed, err := ParseSchemaFile(schemaPath) if err != nil { return fmt.Errorf("parsing schema: %w", err) } + desired, err := desiredSchema(parsed, engine) + if err != nil { + return fmt.Errorf("building desired schema: %w", err) + } - ddl, err := GenerateDDL(s, engine) + schemaName, err := a.dialect.SchemaName(ctx, a.db) if err != nil { - return fmt.Errorf("generating DDL: %w", err) + return err } + desired.Name = schemaName - for _, stmt := range ddl.Up { - a.logger.Debug("executing DDL", zap.String("statement", truncate(stmt, 200))) - if _, err := a.db.ExecContext(ctx, stmt); err != nil { - return fmt.Errorf("executing DDL: %w\nstatement: %s", err, stmt) + // Extensions are created directly so they exist before any column that + // depends on them (e.g. a default calling an extension function). + if a.dialect.SupportsExtensions() { + for _, ext := range parsed.Extensions { + if _, err := a.db.ExecContext(ctx, fmt.Sprintf("CREATE EXTENSION IF NOT EXISTS %q", ext)); err != nil { + return fmt.Errorf("creating extension %q: %w", ext, err) + } } } - a.logger.Info("schema applied", - zap.String("schemaPath", schemaPath), - zap.Int("statements", len(ddl.Up)), - ) - return nil -} - -// RollbackSchema parses a schema YAML file and executes the down DDL statements. -func (a *Applier) RollbackSchema(ctx context.Context, schemaPath string, engine string) error { - if schemaPath == "" { - return nil + drv, err := a.atlasDriver() + if err != nil { + return err } - s, err := ParseSchemaFile(schemaPath) + // Excluded objects are filtered out of the inspected state, so objects the + // YAML deliberately does not model (hand-written expression indexes, + // triggers, the migration-history table) are neither dropped nor altered. + current, err := drv.InspectSchema(ctx, schemaName, &atlasschema.InspectOptions{ + Exclude: excludePatterns(parsed), + }) if err != nil { - return fmt.Errorf("parsing schema: %w", err) + return fmt.Errorf("inspecting current schema: %w", err) } - ddl, err := GenerateDDL(s, engine) + changes, err := drv.SchemaDiff(current, desired) if err != nil { - return fmt.Errorf("generating DDL: %w", err) + return fmt.Errorf("diffing schema: %w", err) } - - for _, stmt := range ddl.Down { - a.logger.Debug("executing rollback DDL", zap.String("statement", truncate(stmt, 200))) - if _, err := a.db.ExecContext(ctx, stmt); err != nil { - return fmt.Errorf("executing rollback DDL: %w\nstatement: %s", err, stmt) - } + if len(changes) == 0 { + a.logger.Debug("schema already up to date", zap.String("schemaPath", schemaPath)) + return nil } - a.logger.Info("schema rolled back", + if err := drv.ApplyChanges(ctx, changes); err != nil { + return fmt.Errorf("applying schema changes: %w", err) + } + a.logger.Info("schema applied", zap.String("schemaPath", schemaPath), - zap.Int("statements", len(ddl.Down)), + zap.Int("changes", len(changes)), ) return nil } -// ApplyMigrations discovers and executes pending up migration scripts in version order. -func (a *Applier) ApplyMigrations(ctx context.Context, migrationsPath string) error { - scripts, err := DiscoverMigrationScripts(migrationsPath) +// ApplyMigrationDir applies pending migration files from an Atlas migration +// directory in timestamp order, tracking each in the atlas_schema_revisions +// table so already-applied migrations are skipped. Returns nil if the directory +// is empty or absent. +// +// maxRisk is the highest risk level (see the migration risk header) that may be +// auto-applied. Pending migrations are applied in order until one exceeds +// maxRisk, at which point the apply stops with an error naming that migration, +// so a live system is never broken by an auto-applied contract change. +// Migrations already applied before the blocked one remain committed. +func (a *Applier) ApplyMigrationDir(ctx context.Context, migrationsPath string, maxRisk RiskLevel) error { + hasFiles, err := hasMigrationFiles(migrationsPath) if err != nil { return err } - if len(scripts) == 0 { + if !hasFiles { return nil } - - if err := a.ensureMigrationsTable(ctx); err != nil { - return fmt.Errorf("creating migrations table: %w", err) + if err := ValidateMigrationFileNames(migrationsPath); err != nil { + return err } - applied, err := a.appliedVersions(ctx) + dir, err := migrate.NewLocalDir(migrationsPath) if err != nil { - return fmt.Errorf("reading applied versions: %w", err) - } - - appliedCount := 0 - for _, script := range scripts { - if applied[script.Version] { - a.logger.Debug("migration already applied, skipping", - zap.Int("version", script.Version), - ) - continue - } - if script.UpPath == "" { - continue - } - - content, err := os.ReadFile(script.UpPath) - if err != nil { - return fmt.Errorf("reading migration %s: %w", script.UpPath, err) - } - - a.logger.Debug("applying migration", - zap.Int("version", script.Version), - zap.String("description", script.Description), - ) - if _, err := a.db.ExecContext(ctx, string(content)); err != nil { - return fmt.Errorf("applying migration V%d__%s: %w", script.Version, script.Description, err) - } - - if err := a.recordVersion(ctx, script.Version, script.Description); err != nil { - return fmt.Errorf("recording migration V%d: %w", script.Version, err) - } - appliedCount++ + return fmt.Errorf("opening migration directory: %w", err) } - - if appliedCount > 0 { - a.logger.Info("migrations applied", - zap.String("migrationsPath", migrationsPath), - zap.Int("applied", appliedCount), - zap.Int("skipped", len(scripts)-appliedCount), - ) + if err := ensureSumFile(migrationsPath, dir); err != nil { + return fmt.Errorf("ensuring %s: %w", sumFileName, err) } - return nil -} -// RollbackMigrations discovers and executes down migration scripts in reverse version order. -func (a *Applier) RollbackMigrations(ctx context.Context, migrationsPath string) error { - scripts, err := DiscoverMigrationScripts(migrationsPath) + drv, err := a.atlasDriver() if err != nil { return err } - if len(scripts) == 0 { - return nil - } - - if err := a.ensureMigrationsTable(ctx); err != nil { - return fmt.Errorf("creating migrations table: %w", err) + rrw, err := a.dialect.NewRevisions(ctx, a.db) + if err != nil { + return err } - applied, err := a.appliedVersions(ctx) + // A pre-existing database (with the default "public" schema) is not "clean" + // by Atlas's definition; Celerity manages existing databases, so allow it. + ex, err := migrate.NewExecutor(drv, dir, rrw, migrate.WithAllowDirty(true)) if err != nil { - return fmt.Errorf("reading applied versions: %w", err) + return fmt.Errorf("creating migration executor: %w", err) } - for i := len(scripts) - 1; i >= 0; i-- { - script := scripts[i] - if !applied[script.Version] { - continue - } - if script.DownPath == "" { - a.logger.Warn("no down migration found, skipping", - zap.Int("version", script.Version), - zap.String("description", script.Description), + pending, err := ex.Pending(ctx) + if errors.Is(err, migrate.ErrNoPendingFiles) { + a.logger.Debug("no pending migrations", zap.String("migrationsPath", migrationsPath)) + return nil + } + if err != nil { + return fmt.Errorf("computing pending migrations: %w", err) + } + + applied := 0 + for _, file := range pending { + stmts, _ := file.Stmts() + risk, detail := effectiveRisk(file.Bytes(), stmts) + if riskRank(risk) > riskRank(maxRisk) { + a.logger.Info("stopping before a migration that exceeds the risk threshold", + zap.String("migration", file.Name()), + zap.String("risk", string(risk)), + zap.Int("applied", applied), ) - continue - } - - content, err := os.ReadFile(script.DownPath) - if err != nil { - return fmt.Errorf("reading migration %s: %w", script.DownPath, err) + return fmt.Errorf( + "migration %q is classified %q%s and was not applied; run any backfill/data steps then re-run with %s, or split it into expand/contract", + file.Name(), risk, detail, allowFlagHint(risk)) } - - a.logger.Debug("rolling back migration", - zap.Int("version", script.Version), - zap.String("description", script.Description), - ) - if _, err := a.db.ExecContext(ctx, string(content)); err != nil { - return fmt.Errorf("rolling back migration V%d__%s: %w", script.Version, script.Description, err) - } - - if err := a.removeVersion(ctx, script.Version); err != nil { - return fmt.Errorf("removing migration record V%d: %w", script.Version, err) + if err := ex.Execute(ctx, file); err != nil { + return fmt.Errorf("applying migration %s: %w", file.Name(), err) } + applied++ } - a.logger.Info("migrations rolled back", + a.logger.Info("migrations applied", zap.String("migrationsPath", migrationsPath), - zap.Int("scripts", len(scripts)), + zap.Int("applied", applied), ) return nil } -// ApplyAll applies schema DDL (up) followed by pending migration up scripts. -func (a *Applier) ApplyAll(ctx context.Context, schemaPath, migrationsPath, engine string) error { - if err := a.ApplySchema(ctx, schemaPath, engine); err != nil { - return err +// PendingMigration describes a committed migration that has not yet been applied +// to the connected database. +type PendingMigration struct { + Name string + Risk RiskLevel +} + +// PendingMigrations returns the migrations that are committed but not yet applied +// to the connected database, in apply order, each with its effective risk. +func (a *Applier) PendingMigrations(ctx context.Context, migrationsPath string) ([]PendingMigration, error) { + hasFiles, err := hasMigrationFiles(migrationsPath) + if err != nil || !hasFiles { + return nil, err + } + + dir, err := migrate.NewLocalDir(migrationsPath) + if err != nil { + return nil, fmt.Errorf("opening migration directory: %w", err) + } + if err := ensureSumFile(migrationsPath, dir); err != nil { + return nil, fmt.Errorf("ensuring %s: %w", sumFileName, err) + } + drv, err := a.atlasDriver() + if err != nil { + return nil, err + } + rrw, err := a.dialect.NewRevisions(ctx, a.db) + if err != nil { + return nil, err + } + ex, err := migrate.NewExecutor(drv, dir, rrw, migrate.WithAllowDirty(true)) + if err != nil { + return nil, fmt.Errorf("creating migration executor: %w", err) + } + pending, err := ex.Pending(ctx) + if errors.Is(err, migrate.ErrNoPendingFiles) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("computing pending migrations: %w", err) + } + + result := make([]PendingMigration, 0, len(pending)) + for _, file := range pending { + stmts, _ := file.Stmts() + risk, _ := effectiveRisk(file.Bytes(), stmts) + result = append(result, PendingMigration{Name: file.Name(), Risk: risk}) } - return a.ApplyMigrations(ctx, migrationsPath) + return result, nil } -// RollbackAll rolls back applied migrations (down, reverse order) then schema DDL (down). -func (a *Applier) RollbackAll(ctx context.Context, schemaPath, migrationsPath, engine string) error { - if err := a.RollbackMigrations(ctx, migrationsPath); err != nil { - return err +func allowFlagHint(risk RiskLevel) string { + if risk == RiskBreaking { + return "--allow-breaking" } - return a.RollbackSchema(ctx, schemaPath, engine) + return "--allow-risky" } // ExecSQL executes a raw SQL string against the database. @@ -324,9 +400,37 @@ func (a *Applier) ExecSQL(ctx context.Context, sqlContent string) error { return err } -func truncate(s string, max int) string { - if len(s) <= max { - return s +func hasMigrationFiles(migrationsPath string) (bool, error) { + if migrationsPath == "" { + return false, nil + } + entries, err := os.ReadDir(migrationsPath) + if err != nil { + if os.IsNotExist(err) { + return false, nil + } + return false, fmt.Errorf("reading migration directory %s: %w", migrationsPath, err) + } + for _, e := range entries { + if !e.IsDir() && strings.HasSuffix(e.Name(), ".sql") { + return true, nil + } + } + return false, nil +} + +// Written only when absent, so a hand-placed migration directory applies +// without a manual step. An existing atlas.sum is left untouched and is +// validated by the executor instead. +func ensureSumFile(migrationsPath string, dir *migrate.LocalDir) error { + if _, err := os.Stat(filepath.Join(migrationsPath, sumFileName)); err == nil { + return nil + } else if !os.IsNotExist(err) { + return err + } + sum, err := dir.Checksum() + if err != nil { + return err } - return s[:max] + "..." + return migrate.WriteSumFile(dir, sum) } diff --git a/apps/cli/internal/sqlschema/applier_integration_test.go b/apps/cli/internal/sqlschema/applier_integration_test.go index 7d740e7e..a3ad940d 100644 --- a/apps/cli/internal/sqlschema/applier_integration_test.go +++ b/apps/cli/internal/sqlschema/applier_integration_test.go @@ -47,7 +47,35 @@ func (s *ApplierIntegrationSuite) cleanupTestTables() { defer db.Close() _, _ = db.Exec("DROP TABLE IF EXISTS integration_test_users CASCADE") _, _ = db.Exec("DROP TABLE IF EXISTS integration_test_orders CASCADE") - _, _ = db.Exec(fmt.Sprintf("DROP TABLE IF EXISTS %s CASCADE", migrationsTable)) + // The history lives in its own schema; the table in the managed schema is + // the pre-move location, which the adoption path recreates. + _, _ = db.Exec(fmt.Sprintf("DROP SCHEMA IF EXISTS %q CASCADE", pgRevisionsSchema)) + _, _ = db.Exec(fmt.Sprintf("DROP TABLE IF EXISTS %s CASCADE", pgLegacyRevisionsQualified)) +} + +func (s *ApplierIntegrationSuite) tableExists(name string) bool { + db, err := sql.Open("pgx", s.connStr) + s.Require().NoError(err) + defer db.Close() + var exists bool + err = db.QueryRow( + `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = $1)`, name, + ).Scan(&exists) + s.Require().NoError(err) + return exists +} + +func (s *ApplierIntegrationSuite) columnExists(table, column string) bool { + db, err := sql.Open("pgx", s.connStr) + s.Require().NoError(err) + defer db.Close() + var exists bool + err = db.QueryRow( + `SELECT EXISTS(SELECT 1 FROM information_schema.columns WHERE table_name = $1 AND column_name = $2)`, + table, column, + ).Scan(&exists) + s.Require().NoError(err) + return exists } // --- NewApplier --- @@ -95,70 +123,92 @@ func (s *ApplierIntegrationSuite) Test_exec_sql_invalid_returns_error() { s.Assert().Error(err) } -// --- ApplySchema --- +// --- ApplyDeclarative --- -func (s *ApplierIntegrationSuite) Test_apply_schema_creates_tables() { +func (s *ApplierIntegrationSuite) Test_apply_declarative_creates_tables() { dir := s.T().TempDir() schemaPath := filepath.Join(dir, "schema.yaml") - schemaContent := ` + s.Require().NoError(os.WriteFile(schemaPath, []byte(` tables: integration_test_users: columns: id: - type: serial + type: bigint primaryKey: true name: type: varchar(100) email: type: varchar(255) unique: true -` - s.Require().NoError(os.WriteFile(schemaPath, []byte(schemaContent), 0o644)) +`), 0o644)) applier, err := NewApplier("postgres", s.connStr, s.logger) s.Require().NoError(err) defer applier.Close() - err = applier.ApplySchema(context.Background(), schemaPath, "postgres") - s.Require().NoError(err) + s.Require().NoError(applier.ApplyDeclarative(context.Background(), schemaPath, "postgres")) + s.Assert().True(s.tableExists("integration_test_users")) +} - // Verify table was created. - db, err := sql.Open("pgx", s.connStr) +func (s *ApplierIntegrationSuite) Test_apply_declarative_empty_path_is_noop() { + applier, err := NewApplier("postgres", s.connStr, s.logger) s.Require().NoError(err) - defer db.Close() + defer applier.Close() - var exists bool - err = db.QueryRow(` - SELECT EXISTS( - SELECT 1 FROM information_schema.tables - WHERE table_name = 'integration_test_users' - ) - `).Scan(&exists) - s.Require().NoError(err) - s.Assert().True(exists) + s.Assert().NoError(applier.ApplyDeclarative(context.Background(), "", "postgres")) } -func (s *ApplierIntegrationSuite) Test_apply_schema_empty_path_is_noop() { +func (s *ApplierIntegrationSuite) Test_apply_declarative_evolves_existing_schema() { + dir := s.T().TempDir() + v1 := filepath.Join(dir, "v1.yaml") + v2 := filepath.Join(dir, "v2.yaml") + s.Require().NoError(os.WriteFile(v1, []byte(` +tables: + integration_test_users: + columns: + id: + type: bigint + primaryKey: true + name: + type: varchar(100) +`), 0o644)) + s.Require().NoError(os.WriteFile(v2, []byte(` +tables: + integration_test_users: + columns: + id: + type: bigint + primaryKey: true + name: + type: varchar(100) + tier: + type: varchar(20) + nullable: false + default: "'free'" +`), 0o644)) + applier, err := NewApplier("postgres", s.connStr, s.logger) s.Require().NoError(err) defer applier.Close() - err = applier.ApplySchema(context.Background(), "", "postgres") - s.Assert().NoError(err) + s.Require().NoError(applier.ApplyDeclarative(context.Background(), v1, "postgres")) + s.Require().False(s.columnExists("integration_test_users", "tier")) + + // Re-applying the same desired state is a no-op (idempotent diff). + s.Require().NoError(applier.ApplyDeclarative(context.Background(), v1, "postgres")) + + // Evolving the schema generates and applies the ALTER. + s.Require().NoError(applier.ApplyDeclarative(context.Background(), v2, "postgres")) + s.Assert().True(s.columnExists("integration_test_users", "tier")) } -// --- ApplyMigrations --- +// --- ApplyMigrationDir --- -func (s *ApplierIntegrationSuite) Test_apply_migrations_runs_up_scripts() { +func (s *ApplierIntegrationSuite) Test_apply_migration_dir_applies_pending() { dir := s.T().TempDir() s.Require().NoError(os.WriteFile( - filepath.Join(dir, "V001__create_orders.up.sql"), - []byte("CREATE TABLE integration_test_orders (id serial PRIMARY KEY, total numeric);"), - 0o644, - )) - s.Require().NoError(os.WriteFile( - filepath.Join(dir, "V001__create_orders.down.sql"), - []byte("DROP TABLE IF EXISTS integration_test_orders;"), + filepath.Join(dir, "20260101000000_create_orders.sql"), + []byte("CREATE TABLE integration_test_orders (id bigint PRIMARY KEY, total numeric);"), 0o644, )) @@ -166,30 +216,19 @@ func (s *ApplierIntegrationSuite) Test_apply_migrations_runs_up_scripts() { s.Require().NoError(err) defer applier.Close() - err = applier.ApplyMigrations(context.Background(), dir) - s.Require().NoError(err) - - // Verify table was created. - db, err := sql.Open("pgx", s.connStr) - s.Require().NoError(err) - defer db.Close() + s.Require().NoError(applier.ApplyMigrationDir(context.Background(), dir, RiskBreaking)) + s.Assert().True(s.tableExists("integration_test_orders")) - var exists bool - err = db.QueryRow(` - SELECT EXISTS( - SELECT 1 FROM information_schema.tables - WHERE table_name = 'integration_test_orders' - ) - `).Scan(&exists) - s.Require().NoError(err) - s.Assert().True(exists) + // atlas.sum is generated for a hand-placed directory. + _, err = os.Stat(filepath.Join(dir, sumFileName)) + s.Assert().NoError(err) } -func (s *ApplierIntegrationSuite) Test_apply_migrations_skips_already_applied() { +func (s *ApplierIntegrationSuite) Test_apply_migration_dir_skips_already_applied() { dir := s.T().TempDir() s.Require().NoError(os.WriteFile( - filepath.Join(dir, "V001__initial.up.sql"), - []byte("CREATE TABLE IF NOT EXISTS integration_test_orders (id serial PRIMARY KEY);"), + filepath.Join(dir, "20260101000000_init.sql"), + []byte("CREATE TABLE integration_test_orders (id bigint PRIMARY KEY);"), 0o644, )) @@ -197,34 +236,79 @@ func (s *ApplierIntegrationSuite) Test_apply_migrations_skips_already_applied() s.Require().NoError(err) defer applier.Close() - // Apply twice. - s.Require().NoError(applier.ApplyMigrations(context.Background(), dir)) - s.Require().NoError(applier.ApplyMigrations(context.Background(), dir)) + // Applying twice must not error (second run finds no pending migrations). + s.Require().NoError(applier.ApplyMigrationDir(context.Background(), dir, RiskBreaking)) + s.Require().NoError(applier.ApplyMigrationDir(context.Background(), dir, RiskBreaking)) + s.Assert().True(s.tableExists("integration_test_orders")) } -func (s *ApplierIntegrationSuite) Test_apply_migrations_empty_dir_is_noop() { +func (s *ApplierIntegrationSuite) Test_apply_migration_dir_empty_is_noop() { dir := s.T().TempDir() applier, err := NewApplier("postgres", s.connStr, s.logger) s.Require().NoError(err) defer applier.Close() - err = applier.ApplyMigrations(context.Background(), dir) - s.Assert().NoError(err) + s.Assert().NoError(applier.ApplyMigrationDir(context.Background(), dir, RiskBreaking)) } -// --- RollbackMigrations --- +// --- Non-transactional migrations --- -func (s *ApplierIntegrationSuite) Test_rollback_migrations_runs_down_scripts() { - dir := s.T().TempDir() +// Test_apply_non_transactional_migration proves the `-- atlas:txmode none` +// directive is honoured: CREATE INDEX CONCURRENTLY cannot run inside a +// transaction block, so it only succeeds when the migration runs +// non-transactionally. Statement-level resume after a partial failure is backed +// by the Applied/Total/PartialHashes fields the revision store persists. +func (s *ApplierIntegrationSuite) Test_apply_non_transactional_migration() { + migrationsPath := s.T().TempDir() s.Require().NoError(os.WriteFile( - filepath.Join(dir, "V001__create_orders.up.sql"), - []byte("CREATE TABLE integration_test_orders (id serial PRIMARY KEY);"), + filepath.Join(migrationsPath, "20260101000000_concurrent_index.sql"), + []byte("-- celerity:risk safe\n-- atlas:txmode none\n"+ + "CREATE TABLE integration_test_nt (id bigint PRIMARY KEY, sku text);\n"+ + "CREATE INDEX CONCURRENTLY integration_test_nt_sku ON integration_test_nt (sku);\n"), 0o644, )) + + applier, err := NewApplier("postgres", s.connStr, s.logger) + s.Require().NoError(err) + defer applier.Close() + + s.Require().NoError(applier.ApplyMigrationDir(context.Background(), migrationsPath, RiskBreaking)) + s.Assert().True(s.tableExists("integration_test_nt")) +} + +// --- Apply (migrations + declarative dev sync) --- + +func (s *ApplierIntegrationSuite) Test_apply_uses_migrations_alone_once_any_exist() { + dir := s.T().TempDir() + schemaPath := filepath.Join(dir, "schema.yaml") + migrationsPath := filepath.Join(dir, "migrations") + s.Require().NoError(os.MkdirAll(migrationsPath, 0o755)) + + // The migration creates orders and the schema YAML additionally describes + // users, a change no migration has captured yet. Once a migration directory + // exists it is the only source of schema changes locally, so the local + // database comes up from exactly the history every other environment runs + // and the uncaptured edit is not applied. A dev session warns about it and + // points at `celerity schema diff` rather than quietly applying it, because + // a local database that has had schema YAML applied on top of the history + // no longer matches what a deploy would produce. + s.Require().NoError(os.WriteFile(schemaPath, []byte(` +tables: + integration_test_orders: + columns: + id: + type: bigint + primaryKey: true + integration_test_users: + columns: + id: + type: bigint + primaryKey: true +`), 0o644)) s.Require().NoError(os.WriteFile( - filepath.Join(dir, "V001__create_orders.down.sql"), - []byte("DROP TABLE IF EXISTS integration_test_orders;"), + filepath.Join(migrationsPath, "20260101000000_create_orders.sql"), + []byte("CREATE TABLE integration_test_orders (id bigint PRIMARY KEY);"), 0o644, )) @@ -232,27 +316,33 @@ func (s *ApplierIntegrationSuite) Test_rollback_migrations_runs_down_scripts() { s.Require().NoError(err) defer applier.Close() - // Apply first. - s.Require().NoError(applier.ApplyMigrations(context.Background(), dir)) + s.Require().NoError(applier.Apply(context.Background(), schemaPath, migrationsPath, "postgres")) + s.Assert().True(s.tableExists("integration_test_orders"), "created by the migration") + s.Assert().False( + s.tableExists("integration_test_users"), + "schema YAML not yet captured in a migration must not be applied once migrations exist", + ) +} - // Then rollback. - err = applier.RollbackMigrations(context.Background(), dir) - s.Require().NoError(err) +func (s *ApplierIntegrationSuite) Test_apply_falls_back_to_declarative_without_migrations() { + dir := s.T().TempDir() + schemaPath := filepath.Join(dir, "schema.yaml") + s.Require().NoError(os.WriteFile(schemaPath, []byte(` +tables: + integration_test_users: + columns: + id: + type: bigint + primaryKey: true +`), 0o644)) - // Verify table was dropped. - db, err := sql.Open("pgx", s.connStr) + applier, err := NewApplier("postgres", s.connStr, s.logger) s.Require().NoError(err) - defer db.Close() + defer applier.Close() - var exists bool - err = db.QueryRow(` - SELECT EXISTS( - SELECT 1 FROM information_schema.tables - WHERE table_name = 'integration_test_orders' - ) - `).Scan(&exists) - s.Require().NoError(err) - s.Assert().False(exists) + // No migrations directory → declarative apply from the schema YAML. + s.Require().NoError(applier.Apply(context.Background(), schemaPath, filepath.Join(dir, "migrations"), "postgres")) + s.Assert().True(s.tableExists("integration_test_users")) } // --- ForDatabase --- @@ -271,35 +361,18 @@ func (s *ApplierIntegrationSuite) Test_for_database_connects_to_different_db() { s.Assert().NoError(err) } -// --- ApplyAll / RollbackAll --- +// --- risk gate --- -func (s *ApplierIntegrationSuite) Test_apply_all_and_rollback_all() { +func (s *ApplierIntegrationSuite) Test_apply_migration_dir_gates_breaking() { dir := s.T().TempDir() - schemaDir := filepath.Join(dir, "schema") - migrationsDir := filepath.Join(dir, "migrations") - s.Require().NoError(os.MkdirAll(schemaDir, 0o755)) - s.Require().NoError(os.MkdirAll(migrationsDir, 0o755)) - - schemaPath := filepath.Join(schemaDir, "schema.yaml") - s.Require().NoError(os.WriteFile(schemaPath, []byte(` -tables: - integration_test_users: - columns: - id: - type: serial - primaryKey: true - name: - type: varchar(100) -`), 0o644)) - s.Require().NoError(os.WriteFile( - filepath.Join(migrationsDir, "V001__add_email.up.sql"), - []byte("ALTER TABLE integration_test_users ADD COLUMN email varchar(255);"), + filepath.Join(dir, "20260101000000_create.sql"), + []byte("-- celerity:risk safe\nCREATE TABLE integration_test_orders (id bigint PRIMARY KEY, legacy varchar(10));"), 0o644, )) s.Require().NoError(os.WriteFile( - filepath.Join(migrationsDir, "V001__add_email.down.sql"), - []byte("ALTER TABLE integration_test_users DROP COLUMN IF EXISTS email;"), + filepath.Join(dir, "20260101000001_drop.sql"), + []byte("-- celerity:risk breaking\nALTER TABLE integration_test_orders DROP COLUMN legacy;"), 0o644, )) @@ -307,26 +380,48 @@ tables: s.Require().NoError(err) defer applier.Close() - // Apply schema + migrations. - err = applier.ApplyAll(context.Background(), schemaPath, migrationsDir, "postgres") - s.Require().NoError(err) + // Default (safe) applies the safe migration but stops at the breaking one. + err = applier.ApplyMigrationDir(context.Background(), dir, RiskSafe) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "breaking") + s.Assert().True(s.tableExists("integration_test_orders"), "safe migration applied") + s.Assert().True(s.columnExists("integration_test_orders", "legacy"), "breaking migration NOT applied") - // Verify email column exists. - db, err := sql.Open("pgx", s.connStr) - s.Require().NoError(err) - defer db.Close() + // --allow-breaking applies it. + s.Require().NoError(applier.ApplyMigrationDir(context.Background(), dir, RiskBreaking)) + s.Assert().False(s.columnExists("integration_test_orders", "legacy")) +} - var exists bool - err = db.QueryRow(` - SELECT EXISTS( - SELECT 1 FROM information_schema.columns - WHERE table_name = 'integration_test_users' AND column_name = 'email' - ) - `).Scan(&exists) - s.Require().NoError(err) - s.Assert().True(exists) +func (s *ApplierIntegrationSuite) Test_apply_migration_dir_backstops_spoofed_header() { + dir := s.T().TempDir() + s.Require().NoError(os.WriteFile( + filepath.Join(dir, "20260101000000_create.sql"), + []byte("-- celerity:risk safe\nCREATE TABLE integration_test_orders (id bigint PRIMARY KEY, legacy varchar(10));"), + 0o644, + )) + // The header lies (safe) but the SQL drops a column, so the statement + // backstop must still block it under the default gate. + s.Require().NoError(os.WriteFile( + filepath.Join(dir, "20260101000001_drop.sql"), + []byte("-- celerity:risk safe\nALTER TABLE integration_test_orders DROP COLUMN legacy;"), + 0o644, + )) - // Rollback. - err = applier.RollbackAll(context.Background(), schemaPath, migrationsDir, "postgres") + applier, err := NewApplier("postgres", s.connStr, s.logger) s.Require().NoError(err) + defer applier.Close() + + err = applier.ApplyMigrationDir(context.Background(), dir, RiskSafe) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "breaking") + s.Assert().True(s.columnExists("integration_test_orders", "legacy"), "spoofed-safe drop must NOT be applied") + + // Even --allow-risky is not enough, since a data-destructive statement needs + // --allow-breaking. + err = applier.ApplyMigrationDir(context.Background(), dir, RiskRisky) + s.Require().Error(err) + s.Assert().True(s.columnExists("integration_test_orders", "legacy")) + + s.Require().NoError(applier.ApplyMigrationDir(context.Background(), dir, RiskBreaking)) + s.Assert().False(s.columnExists("integration_test_orders", "legacy")) } diff --git a/apps/cli/internal/sqlschema/blueprint.go b/apps/cli/internal/sqlschema/blueprint.go index 00ee2eeb..b0acac54 100644 --- a/apps/cli/internal/sqlschema/blueprint.go +++ b/apps/cli/internal/sqlschema/blueprint.go @@ -24,12 +24,12 @@ func CollectDatabaseResources(bp *schema.Blueprint, projectRoot string) []Databa } dr := DatabaseResource{ - ResourceName: name, - Name: specString(resource.Spec, "name"), - Engine: specString(resource.Spec, "engine"), - SchemaPath: specString(resource.Spec, "schemaPath"), + ResourceName: name, + Name: specString(resource.Spec, "name"), + Engine: specString(resource.Spec, "engine"), + SchemaPath: specString(resource.Spec, "schemaPath"), MigrationsPath: specString(resource.Spec, "migrationsPath"), - AuthMode: specString(resource.Spec, "authMode"), + AuthMode: specString(resource.Spec, "authMode"), } if dr.Name == "" { @@ -94,8 +94,8 @@ func resolvePath(projectRoot, p string) string { return abs } -// ResourceTypeSqlDatabase is the blueprint resource type for SQL databases. -// Exported for use by the compose generator. +// ResourceType returns the blueprint resource type for SQL databases, for use by +// the compose generator. func ResourceType() string { return resourceTypeSqlDatabase } diff --git a/apps/cli/internal/sqlschema/classify.go b/apps/cli/internal/sqlschema/classify.go new file mode 100644 index 00000000..b8805d69 --- /dev/null +++ b/apps/cli/internal/sqlschema/classify.go @@ -0,0 +1,255 @@ +package sqlschema + +import ( + "fmt" + "slices" + "strings" + + "ariga.io/atlas/sql/schema" +) + +// RiskLevel classifies how safe it is to auto-apply a migration against a live +// database. +type RiskLevel string + +const ( + // RiskSafe changes are additive and backward-compatible with running code + // (add table/column-with-default, add non-unique index, drop index/constraint). + RiskSafe RiskLevel = "safe" + // RiskRisky changes are data-dependent and can fail or lock depending on + // existing data (set NOT NULL, add unique index, add foreign key/check, + // change column type, add NOT NULL column without a default). + RiskRisky RiskLevel = "risky" + // RiskBreaking changes are destructive/backward-incompatible with running + // code (drop table/column/schema). + RiskBreaking RiskLevel = "breaking" +) + +// The token a migration file header records its risk under, as in +// "-- celerity:risk breaking (drops column customers.legacy_tier)". +const riskMarker = "celerity:risk" + +func riskRank(level RiskLevel) int { + switch level { + case RiskSafe: + return 0 + case RiskRisky: + return 1 + case RiskBreaking: + return 2 + default: + return 1 // unknown → treat as risky + } +} + +// Returns the highest risk across the changes, with a short reason naming the +// change that set it. +func classifyChanges(changes []schema.Change) (RiskLevel, string) { + level, reason := RiskSafe, "" + for _, c := range changes { + if l, r := classifyChange(c); riskRank(l) > riskRank(level) { + level, reason = l, r + } + } + return level, reason +} + +func classifyChange(change schema.Change) (RiskLevel, string) { + switch c := change.(type) { + case *schema.DropTable: + return RiskBreaking, fmt.Sprintf("drops table %s", tableName(c.T)) + case *schema.DropSchema: + return RiskBreaking, "drops a schema" + case *schema.ModifyTable: + level, reason := classifyChanges(c.Changes) + if reason != "" { + reason = fmt.Sprintf("table %s: %s", tableName(c.T), reason) + } + return level, reason + case *schema.DropColumn: + return RiskBreaking, fmt.Sprintf("drops column %s", columnName(c.C)) + case *schema.AddColumn: + if c.C != nil && !columnNullable(c.C) && c.C.Default == nil { + return RiskRisky, fmt.Sprintf("adds NOT NULL column %s without a default", columnName(c.C)) + } + return RiskSafe, "" + case *schema.ModifyColumn: + if c.Change.Is(schema.ChangeNull) && columnNullable(c.From) && !columnNullable(c.To) { + return RiskRisky, fmt.Sprintf("makes column %s NOT NULL", columnName(c.To)) + } + if c.Change.Is(schema.ChangeType) { + return RiskRisky, fmt.Sprintf("changes the type of column %s", columnName(c.To)) + } + return RiskSafe, "" + case *schema.AddIndex: + if c.I != nil && c.I.Unique { + return RiskRisky, "adds a unique index (may fail on duplicate data)" + } + return RiskSafe, "" + case *schema.AddForeignKey: + return RiskRisky, "adds a foreign key (existing rows may violate it)" + case *schema.AddCheck: + return RiskRisky, "adds a check constraint (existing rows may violate it)" + default: + // Add table/schema/index-drop/constraint-drop and anything else are + // treated as backward-compatible. + return RiskSafe, "" + } +} + +// A migration without a recognised header is treated as risky, so hand-written +// or legacy migrations are never auto-applied silently. +func migrationRisk(content []byte) RiskLevel { + for raw := range strings.SplitSeq(string(content), "\n") { + line := strings.TrimSpace(raw) + _, after, ok := strings.Cut(line, riskMarker) + if !ok { + continue + } + fields := strings.Fields(after) + if len(fields) == 0 { + continue + } + switch level := RiskLevel(fields[0]); level { + case RiskSafe, RiskRisky, RiskBreaking: + return level + } + } + return RiskRisky +} + +// Combines a migration's declared header risk with the un-spoofable floor +// derived from its actual SQL statements. Data-destructive SQL wins over the +// header, so a "safe" header on a file that drops data is treated as breaking. +// detail is a non-empty parenthetical when the SQL floor raised the risk above +// the declared header. +func effectiveRisk(content []byte, statements []string) (RiskLevel, string) { + risk := migrationRisk(content) + if floor, reason := sqlRiskFloor(statements); riskRank(floor) > riskRank(risk) { + return floor, fmt.Sprintf(" (its SQL %s, overriding the header)", reason) + } + return risk, "" +} + +// Scans a migration's actual SQL statements for data-destructive operations and +// returns the minimum risk they imply, independent of any declared header. This +// is the un-spoofable safety floor, so a migration that drops data is treated as +// breaking even if its header claims otherwise, as a generated "safe" file +// hand-edited to add a DROP would. Only drops of tables, schemas, databases and +// columns count, since those are the operations that destroy row data; DROP +// INDEX, CONSTRAINT, DEFAULT and NOT NULL do not. +func sqlRiskFloor(statements []string) (RiskLevel, string) { + for _, stmt := range statements { + if reason := destructiveReason(stripSQLComments(stmt)); reason != "" { + return RiskBreaking, reason + } + } + return RiskSafe, "" +} + +// Keywords following DROP that do not destroy row data. +var nonDestructiveDropTargets = map[string]bool{ + "CONSTRAINT": true, "DEFAULT": true, "NOT": true, "INDEX": true, + "EXPRESSION": true, "IDENTITY": true, "PRIMARY": true, "UNIQUE": true, + "CHECK": true, "FOREIGN": true, "KEY": true, "VIEW": true, + "FUNCTION": true, "TRIGGER": true, "TYPE": true, "SEQUENCE": true, +} + +func destructiveReason(stmt string) string { + tokens := tokenizeSQL(stmt) + for i, tok := range tokens { + if tok != "DROP" { + continue + } + switch target := dropTarget(tokens, i+1); target { + case "TABLE", "SCHEMA", "DATABASE", "COLUMN": + return "drops a " + strings.ToLower(target) + default: + if nonDestructiveDropTargets[target] { + continue + } + // A bare `ALTER TABLE ... DROP ` (COLUMN keyword omitted) is a + // column drop. + if hasToken(tokens[:i], "ALTER") && hasToken(tokens[:i], "TABLE") { + return "drops a column" + } + } + } + return "" +} + +func dropTarget(tokens []string, from int) string { + for j := from; j < len(tokens); j++ { + if tokens[j] == "IF" || tokens[j] == "EXISTS" { + continue + } + return tokens[j] + } + return "" +} + +func hasToken(tokens []string, want string) bool { + return slices.Contains(tokens, want) +} + +func tokenizeSQL(stmt string) []string { + fields := strings.Fields(stmt) + tokens := make([]string, 0, len(fields)) + for _, f := range fields { + if f = strings.Trim(f, "();,\"'`"); f != "" { + tokens = append(tokens, strings.ToUpper(f)) + } + } + return tokens +} + +// Removes -- line comments and /* */ block comments so keyword scanning does not +// match text inside a comment. +func stripSQLComments(stmt string) string { + for { + before, afterOpen, found := strings.Cut(stmt, "/*") + if !found { + break + } + _, afterClose, closed := strings.Cut(afterOpen, "*/") + if !closed { + stmt = before + break + } + stmt = before + " " + afterClose + } + var b strings.Builder + for line := range strings.SplitSeq(stmt, "\n") { + if before, _, found := strings.Cut(line, "--"); found { + line = before + } + b.WriteString(line) + b.WriteByte(' ') + } + return b.String() +} + +func riskHeader(level RiskLevel, reason string) string { + if reason != "" { + return fmt.Sprintf("-- %s %s (%s)\n", riskMarker, level, reason) + } + return fmt.Sprintf("-- %s %s\n", riskMarker, level) +} + +func columnNullable(c *schema.Column) bool { + return c != nil && c.Type != nil && c.Type.Null +} + +func columnName(c *schema.Column) string { + if c == nil { + return "?" + } + return c.Name +} + +func tableName(t *schema.Table) string { + if t == nil { + return "?" + } + return t.Name +} diff --git a/apps/cli/internal/sqlschema/classify_test.go b/apps/cli/internal/sqlschema/classify_test.go new file mode 100644 index 00000000..8f7ffd97 --- /dev/null +++ b/apps/cli/internal/sqlschema/classify_test.go @@ -0,0 +1,126 @@ +package sqlschema + +import ( + "testing" + + "ariga.io/atlas/sql/schema" + "github.com/stretchr/testify/suite" +) + +type ClassifySuite struct { + suite.Suite +} + +func TestClassifySuite(t *testing.T) { + suite.Run(t, new(ClassifySuite)) +} + +func col(name string, nullable bool) *schema.Column { + return schema.NewColumn(name).SetType(&schema.StringType{T: "varchar"}).SetNull(nullable) +} + +func (s *ClassifySuite) classify(changes ...schema.Change) RiskLevel { + level, _ := classifyChanges(changes) + return level +} + +func (s *ClassifySuite) Test_additive_changes_are_safe() { + s.Assert().Equal(RiskSafe, s.classify(&schema.AddTable{T: schema.NewTable("t")})) + s.Assert().Equal(RiskSafe, s.classify(&schema.AddColumn{C: col("x", true)})) + s.Assert().Equal(RiskSafe, s.classify(&schema.AddIndex{I: schema.NewIndex("i")})) + s.Assert().Equal(RiskSafe, s.classify(&schema.DropIndex{I: schema.NewIndex("i")})) +} + +func (s *ClassifySuite) Test_data_dependent_changes_are_risky() { + // NOT NULL column without a default. + s.Assert().Equal(RiskRisky, s.classify(&schema.AddColumn{C: col("x", false)})) + // Making an existing column NOT NULL. + s.Assert().Equal(RiskRisky, s.classify(&schema.ModifyColumn{ + From: col("x", true), To: col("x", false), Change: schema.ChangeNull, + })) + // Changing a column's type. + s.Assert().Equal(RiskRisky, s.classify(&schema.ModifyColumn{ + From: col("x", true), To: col("x", true), Change: schema.ChangeType, + })) + // Unique index / foreign key / check. + s.Assert().Equal(RiskRisky, s.classify(&schema.AddIndex{I: schema.NewUniqueIndex("i")})) + s.Assert().Equal(RiskRisky, s.classify(&schema.AddForeignKey{F: schema.NewForeignKey("fk")})) + s.Assert().Equal(RiskRisky, s.classify(&schema.AddCheck{C: &schema.Check{Name: "c"}})) +} + +func (s *ClassifySuite) Test_destructive_changes_are_breaking() { + s.Assert().Equal(RiskBreaking, s.classify(&schema.DropTable{T: schema.NewTable("t")})) + s.Assert().Equal(RiskBreaking, s.classify(&schema.DropColumn{C: col("x", false)})) +} + +func (s *ClassifySuite) Test_highest_risk_wins() { + level := s.classify( + &schema.AddColumn{C: col("safe", true)}, + &schema.DropColumn{C: col("gone", false)}, + ) + s.Assert().Equal(RiskBreaking, level) +} + +func (s *ClassifySuite) Test_modify_table_recurses() { + mt := &schema.ModifyTable{ + T: schema.NewTable("t"), + Changes: []schema.Change{&schema.DropColumn{C: col("x", false)}}, + } + s.Assert().Equal(RiskBreaking, s.classify(mt)) +} + +func (s *ClassifySuite) Test_sql_floor_flags_data_destructive_statements() { + breaking := []string{ + "DROP TABLE users", + "DROP TABLE IF EXISTS users", + "DROP SCHEMA public CASCADE", + "ALTER TABLE users DROP COLUMN email", + "ALTER TABLE users DROP COLUMN IF EXISTS email", + "ALTER TABLE users DROP email", // bare column drop (COLUMN keyword omitted) + } + for _, stmt := range breaking { + level, reason := sqlRiskFloor([]string{stmt}) + s.Assert().Equal(RiskBreaking, level, stmt) + s.Assert().NotEmpty(reason, stmt) + } + + safe := []string{ + "CREATE TABLE t (id bigint)", + "ALTER TABLE users ADD COLUMN nickname varchar(50)", + "ALTER TABLE users DROP CONSTRAINT chk_total", + "ALTER TABLE users ALTER COLUMN x DROP NOT NULL", + "ALTER TABLE users ALTER COLUMN x DROP DEFAULT", + "DROP INDEX idx_users_email", + "-- DROP TABLE users\nCREATE TABLE t (id bigint)", // drop only in a comment + } + for _, stmt := range safe { + level, _ := sqlRiskFloor([]string{stmt}) + s.Assert().Equal(RiskSafe, level, stmt) + } +} + +func (s *ClassifySuite) Test_effective_risk_backstops_spoofed_header() { + // A "safe" header on SQL that drops data is treated as breaking. + level, detail := effectiveRisk([]byte("-- celerity:risk safe\n"), []string{"ALTER TABLE users DROP COLUMN email"}) + s.Assert().Equal(RiskBreaking, level) + s.Assert().NotEmpty(detail) + + // Header honoured when the SQL is not more destructive than it claims. + level, detail = effectiveRisk([]byte("-- celerity:risk safe\n"), []string{"CREATE TABLE t (id bigint)"}) + s.Assert().Equal(RiskSafe, level) + s.Assert().Empty(detail) + + // A header stricter than the SQL floor is kept (risky header, additive SQL). + level, _ = effectiveRisk([]byte("-- celerity:risk risky\n"), []string{"CREATE TABLE t (id bigint)"}) + s.Assert().Equal(RiskRisky, level) +} + +func (s *ClassifySuite) Test_migration_risk_header_parsing() { + s.Assert().Equal(RiskSafe, migrationRisk([]byte("-- celerity:risk safe\nCREATE TABLE t (id bigint);"))) + s.Assert().Equal(RiskBreaking, migrationRisk([]byte("-- celerity:risk breaking (drops column t.x)\nALTER TABLE t DROP COLUMN x;"))) + s.Assert().Equal(RiskRisky, migrationRisk([]byte("-- celerity:risk risky\n"))) + // Missing header → risky (fail-safe). + s.Assert().Equal(RiskRisky, migrationRisk([]byte("CREATE TABLE t (id bigint);"))) + // Unrecognised level → risky. + s.Assert().Equal(RiskRisky, migrationRisk([]byte("-- celerity:risk bogus\n"))) +} diff --git a/apps/cli/internal/sqlschema/codegen.go b/apps/cli/internal/sqlschema/codegen.go new file mode 100644 index 00000000..c4aa04e0 --- /dev/null +++ b/apps/cli/internal/sqlschema/codegen.go @@ -0,0 +1,340 @@ +package sqlschema + +import ( + "fmt" + "strings" +) + +// CodegenLanguage is a target language for `schema codegen`. +type CodegenLanguage string + +const ( + LangTypeScript CodegenLanguage = "typescript" + LangPython CodegenLanguage = "python" +) + +// GeneratedFile is a single codegen output: the file name (relative to the +// output directory) and its contents. +type GeneratedFile struct { + Name string + Content string +} + +// GenerateCode renders type-safe code for a parsed schema in the given language. +// resourceName names the output file and is used only for the header. v0 supports +// TypeScript (row interfaces + column/table constants) and Python (Pydantic +// models). There is no ORM coupling. +func GenerateCode(s *Schema, lang CodegenLanguage, resourceName string) (*GeneratedFile, error) { + switch lang { + case LangTypeScript: + return &GeneratedFile{ + Name: kebabCase(resourceName) + ".ts", + Content: generateTypeScript(s, resourceName), + }, nil + case LangPython: + return &GeneratedFile{ + Name: snakeCase(resourceName) + ".py", + Content: generatePython(s, resourceName), + }, nil + default: + return nil, fmt.Errorf("unsupported codegen language %q (supported: typescript, python)", lang) + } +} + +func generateTypeScript(s *Schema, resourceName string) string { + var b strings.Builder + fmt.Fprintf(&b, "// %s.ts is auto-generated by `celerity schema codegen`, so do not edit it.\n", kebabCase(resourceName)) + b.WriteString("// Field names mirror the database columns exactly (what your driver returns for a\n") + b.WriteString("// plain query); only type names are stylised. Map to camelCase in your own layer\n") + b.WriteString("// if you want it, because codegen keeps the shape faithful to the database.\n\n") + + tables := sortedKeys(s.Tables) + for _, name := range tables { + table := s.Tables[name] + fmt.Fprintf(&b, "/** %s */\n", tableComment(name, table)) + fmt.Fprintf(&b, "export type %s = {\n", entityTypeName(name, table)) + for _, colName := range orderedColumns(table) { + col := table.Columns[colName] + tsType := tsType(col.Type) + if col.Nullable && !col.PrimaryKey { + tsType += " | null" + } + if col.Description != "" { + fmt.Fprintf(&b, " /** %s */\n", col.Description) + } + fmt.Fprintf(&b, " %s: %s;\n", colName, tsType) + } + b.WriteString("}\n\n") + } + + b.WriteString("export const Tables = {\n") + for _, name := range tables { + fmt.Fprintf(&b, " %s: %q,\n", name, name) + } + b.WriteString("} as const;\n") + + for _, name := range tables { + fmt.Fprintf(&b, "\nexport const %sColumns = {\n", entityTypeName(name, s.Tables[name])) + for _, colName := range orderedColumns(s.Tables[name]) { + fmt.Fprintf(&b, " %s: %q,\n", colName, colName) + } + b.WriteString("} as const;\n") + } + + return b.String() +} + +func generatePython(s *Schema, resourceName string) string { + tables := sortedKeys(s.Tables) + + // Determine which imports the generated models need. + needDatetime, needAny, needOptional := false, false, false + for _, name := range tables { + for _, col := range s.Tables[name].Columns { + switch pyType(col.Type) { + case "datetime": + needDatetime = true + case "Any": + needAny = true + } + if col.Nullable && !col.PrimaryKey { + needOptional = true + } + } + } + + var b strings.Builder + fmt.Fprintf(&b, "# %s.py is auto-generated by `celerity schema codegen`, so do not edit it.\n", snakeCase(resourceName)) + b.WriteString("# Field names mirror the database columns exactly (what your driver returns for a\n") + b.WriteString("# plain query); only class names are stylised.\n") + b.WriteString("from pydantic import BaseModel\n") + if needDatetime { + b.WriteString("from datetime import datetime\n") + } + typingImports := []string{} + if needAny { + typingImports = append(typingImports, "Any") + } + if needOptional { + typingImports = append(typingImports, "Optional") + } + if len(typingImports) > 0 { + fmt.Fprintf(&b, "from typing import %s\n", strings.Join(typingImports, ", ")) + } + + for _, name := range tables { + table := s.Tables[name] + fmt.Fprintf(&b, "\n\nclass %s(BaseModel):\n", entityTypeName(name, table)) + cols := orderedColumns(table) + if len(cols) == 0 { + b.WriteString(" pass\n") + continue + } + for _, colName := range cols { + col := table.Columns[colName] + pt := pyType(col.Type) + if col.Nullable && !col.PrimaryKey { + pt = fmt.Sprintf("Optional[%s]", pt) + } + fmt.Fprintf(&b, " %s: %s\n", colName, pt) + } + } + + return b.String() +} + +func tableComment(name string, t Table) string { + if t.Description != "" { + return t.Description + } + return fmt.Sprintf("A row from the %q table", name) +} + +// Primary keys come first, then the rest, each group sorted alphabetically. The +// order has to be deterministic for codegen output to be stable, which the +// freshness check depends on. +func orderedColumns(t Table) []string { + var pk, rest []string + for _, name := range sortedKeys(t.Columns) { + if t.Columns[name].PrimaryKey { + pk = append(pk, name) + } else { + rest = append(rest, name) + } + } + return append(pk, rest...) +} + +// bigint and the exact numerics map to string to avoid JavaScript number +// precision loss. +func tsType(sqlType string) string { + switch baseSQLType(sqlType) { + case "bigint", "int8", "bigserial", "serial8", "numeric", "decimal", "money": + return "string" + case "smallint", "int2", "integer", "int", "int4", "serial", "serial4", + "real", "float4", "double precision", "float8": + return "number" + case "boolean", "bool": + return "boolean" + case "timestamp", "timestamptz", "timestamp with time zone", + "timestamp without time zone", "date", "time", "timetz": + return "Date" + case "json", "jsonb": + return "unknown" + case "bytea": + return "string" + case "uuid", "text", "varchar", "character varying", "char", "character", + "citext", "inet", "cidr", "macaddr": + return "string" + default: + return "unknown" + } +} + +func pyType(sqlType string) string { + switch baseSQLType(sqlType) { + case "bigint", "int8", "bigserial", "serial8", "numeric", "decimal", "money": + return "str" + case "smallint", "int2", "integer", "int", "int4", "serial", "serial4": + return "int" + case "real", "float4", "double precision", "float8": + return "float" + case "boolean", "bool": + return "bool" + case "timestamp", "timestamptz", "timestamp with time zone", + "timestamp without time zone", "date", "time", "timetz": + return "datetime" + case "json", "jsonb": + return "Any" + case "bytea": + return "bytes" + case "uuid", "text", "varchar", "character varying", "char", "character", + "citext", "inet", "cidr", "macaddr": + return "str" + default: + return "Any" + } +} + +// Lowercases a type and strips any length or precision modifier, so +// "VARCHAR(255)" and "numeric(10,2)" reduce to "varchar" and "numeric". +func baseSQLType(sqlType string) string { + t := strings.ToLower(strings.TrimSpace(sqlType)) + if i := strings.IndexByte(t, '('); i >= 0 { + t = strings.TrimSpace(t[:i]) + } + // Arrays and other suffixes are treated by their base name. + t = strings.TrimSuffix(t, "[]") + return strings.TrimSpace(t) +} + +// The generated type name is the author's typeName override verbatim, or failing +// that the table name singularised and PascalCased, so that "customers" becomes +// "Customer" and "order_events" becomes "OrderEvent". +func entityTypeName(tableName string, table Table) string { + if table.TypeName != "" { + return table.TypeName + } + words := splitIdentifier(tableName) + if len(words) > 0 { + words[len(words)-1] = singularise(words[len(words)-1]) + } + return pascalCaseWords(words) +} + +// Irregular English plurals, and a few uncountables the rules below would mangle, +// mapped to their singular form. +var irregularSingulars = map[string]string{ + "people": "person", "men": "man", "women": "woman", "children": "child", + "teeth": "tooth", "feet": "foot", "mice": "mouse", "geese": "goose", + // Uncountable / already-singular words ending in -s or -ies. + "series": "series", "species": "species", "status": "status", +} + +// Converts a lowercase plural word to its singular form using common English +// rules. It is deliberately simple, since irregular cases are covered by the +// per-table `typeName` override. +func singularise(word string) string { + if s, ok := irregularSingulars[word]; ok { + return s + } + switch { + case len(word) > 3 && strings.HasSuffix(word, "ies"): + return word[:len(word)-3] + "y" + case strings.HasSuffix(word, "ses"), strings.HasSuffix(word, "xes"), + strings.HasSuffix(word, "zes"), strings.HasSuffix(word, "ches"), + strings.HasSuffix(word, "shes"): + return word[:len(word)-2] + case strings.HasSuffix(word, "s") && + !strings.HasSuffix(word, "ss") && + !strings.HasSuffix(word, "us") && + !strings.HasSuffix(word, "is"): + return word[:len(word)-1] + default: + return word + } +} + +// pascalCase converts an identifier (snake_case, kebab-case or camelCase) to +// PascalCase: "order_events" → "OrderEvents", "ordersDb" → "OrdersDb". +func pascalCase(s string) string { + return pascalCaseWords(splitIdentifier(s)) +} + +func pascalCaseWords(words []string) string { + var b strings.Builder + for _, word := range words { + if word == "" { + continue + } + b.WriteString(strings.ToUpper(word[:1])) + b.WriteString(strings.ToLower(word[1:])) + } + return b.String() +} + +func kebabCase(s string) string { + return strings.Join(splitIdentifier(s), "-") +} + +func snakeCase(s string) string { + return strings.Join(splitIdentifier(s), "_") +} + +// Breaks an identifier into lowercase words on camelCase boundaries and +// non-alphanumeric separators. +func splitIdentifier(s string) []string { + var words []string + var cur strings.Builder + var prev rune + for i, r := range s { + isSep := !isAlphaNum(r) + if isSep { + if cur.Len() > 0 { + words = append(words, strings.ToLower(cur.String())) + cur.Reset() + } + prev = r + continue + } + // Split on a lower→upper or letter→digit-group boundary. + if i > 0 && cur.Len() > 0 && isUpper(r) && !isUpper(prev) { + words = append(words, strings.ToLower(cur.String())) + cur.Reset() + } + cur.WriteRune(r) + prev = r + } + if cur.Len() > 0 { + words = append(words, strings.ToLower(cur.String())) + } + return words +} + +func isAlphaNum(r rune) bool { + return isUpper(r) || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') +} + +func isUpper(r rune) bool { + return r >= 'A' && r <= 'Z' +} diff --git a/apps/cli/internal/sqlschema/codegen_test.go b/apps/cli/internal/sqlschema/codegen_test.go new file mode 100644 index 00000000..cc412b6e --- /dev/null +++ b/apps/cli/internal/sqlschema/codegen_test.go @@ -0,0 +1,169 @@ +package sqlschema + +import ( + "testing" + + "github.com/stretchr/testify/suite" +) + +type CodegenSuite struct { + suite.Suite +} + +func TestCodegenSuite(t *testing.T) { + suite.Run(t, new(CodegenSuite)) +} + +func sampleSchema() *Schema { + return &Schema{ + Tables: map[string]Table{ + "customers": { + Description: "customers table row", + Columns: map[string]Column{ + "id": {Type: "bigint", PrimaryKey: true}, + "email": {Type: "varchar(255)", Unique: true}, + "tier": {Type: "integer"}, + "created_at": {Type: "timestamptz"}, + "meta": {Type: "jsonb", Nullable: true}, + }, + }, + "order_events": { + Columns: map[string]Column{ + "id": {Type: "bigint", PrimaryKey: true}, + "customer_id": { + Type: "bigint", + References: &ForeignKey{Table: "customers", Column: "id", OnDelete: "cascade"}, + }, + }, + }, + }, + } +} + +func (s *CodegenSuite) Test_typescript_row_interface_and_types() { + file, err := GenerateCode(sampleSchema(), LangTypeScript, "ordersDb") + s.Require().NoError(err) + s.Assert().Equal("orders-db.ts", file.Name) + + c := file.Content + // Singular entity name, no Row suffix. + s.Assert().Contains(c, "export type Customer = {") + // bigint → string (JS precision), integer → number, timestamptz → Date, jsonb → unknown. + s.Assert().Contains(c, "id: string;") + s.Assert().Contains(c, "tier: number;") + s.Assert().Contains(c, "created_at: Date;") + // Nullable non-PK column gets a `| null`. + s.Assert().Contains(c, "meta: unknown | null;") + // Singularised + PascalCase for snake_case table names. + s.Assert().Contains(c, "export type OrderEvent = {") + // In the constants, Tables keys stay the actual (plural) table names. + s.Assert().Contains(c, "export const Tables = {") + s.Assert().Contains(c, `customers: "customers",`) + s.Assert().Contains(c, "export const CustomerColumns = {") + s.Assert().Contains(c, `email: "email",`) + s.Assert().Contains(c, "do not edit") +} + +func (s *CodegenSuite) Test_typescript_primary_key_column_first() { + file, err := GenerateCode(sampleSchema(), LangTypeScript, "ordersDb") + s.Require().NoError(err) + // id (PK) must appear before the alphabetically-earlier created_at. + s.Assert().Less(index(file.Content, "id: string;"), index(file.Content, "created_at: Date;")) +} + +func (s *CodegenSuite) Test_python_pydantic_models_and_imports() { + file, err := GenerateCode(sampleSchema(), LangPython, "ordersDb") + s.Require().NoError(err) + s.Assert().Equal("orders_db.py", file.Name) + + c := file.Content + s.Assert().Contains(c, "from pydantic import BaseModel") + s.Assert().Contains(c, "from datetime import datetime") + s.Assert().Contains(c, "from typing import Any, Optional") + s.Assert().Contains(c, "class Customer(BaseModel):") + s.Assert().Contains(c, "class OrderEvent(BaseModel):") + s.Assert().Contains(c, "id: str") + s.Assert().Contains(c, "tier: int") + s.Assert().Contains(c, "created_at: datetime") + s.Assert().Contains(c, "meta: Optional[Any]") +} + +func (s *CodegenSuite) Test_deterministic_output() { + a, err := GenerateCode(sampleSchema(), LangTypeScript, "ordersDb") + s.Require().NoError(err) + b, err := GenerateCode(sampleSchema(), LangTypeScript, "ordersDb") + s.Require().NoError(err) + s.Assert().Equal(a.Content, b.Content, "codegen must be deterministic for the freshness check") +} + +func (s *CodegenSuite) Test_unsupported_language() { + _, err := GenerateCode(sampleSchema(), CodegenLanguage("ruby"), "ordersDb") + s.Require().Error(err) + s.Assert().Contains(err.Error(), "unsupported codegen language") +} + +func (s *CodegenSuite) Test_singularise_rules() { + cases := map[string]string{ + "customers": "customer", + "orders": "order", + "events": "event", + "companies": "company", + "categories": "category", + "addresses": "address", + "boxes": "box", + "status": "status", // -us: unchanged + "series": "series", // -is: unchanged (heuristic keeps it) + "people": "person", // irregular + "class": "class", // -ss: unchanged + "order_events": "order_event", + } + for plural, want := range cases { + // order_events is a phrase; singularise operates on the last word, so + // exercise the whole pipeline for it. + if plural == "order_events" { + s.Assert().Equal("OrderEvent", entityTypeName(plural, Table{})) + continue + } + s.Assert().Equalf(want, singularise(plural), "singularise(%q)", plural) + } +} + +func (s *CodegenSuite) Test_type_name_override() { + schema := &Schema{ + Tables: map[string]Table{ + "people": { + TypeName: "Person", + Columns: map[string]Column{"id": {Type: "bigint", PrimaryKey: true}}, + }, + }, + } + file, err := GenerateCode(schema, LangTypeScript, "hrDb") + s.Require().NoError(err) + s.Assert().Contains(file.Content, "export type Person = {") + s.Assert().Contains(file.Content, "export const PersonColumns = {") +} + +func (s *CodegenSuite) Test_identifier_case_helpers() { + s.Assert().Equal("OrderEvents", pascalCase("order_events")) + s.Assert().Equal("OrdersDb", pascalCase("ordersDb")) + s.Assert().Equal("orders-db", kebabCase("ordersDb")) + s.Assert().Equal("orders_db", snakeCase("ordersDb")) + s.Assert().Equal("orders-db", kebabCase("orders_db")) +} + +func (s *CodegenSuite) Test_type_mapping_edges() { + s.Assert().Equal("string", tsType("VARCHAR(255)")) + s.Assert().Equal("string", tsType("numeric(10,2)")) + s.Assert().Equal("boolean", tsType("bool")) + s.Assert().Equal("str", pyType("uuid")) + s.Assert().Equal("float", pyType("double precision")) +} + +func index(haystack, needle string) int { + for i := 0; i+len(needle) <= len(haystack); i++ { + if haystack[i:i+len(needle)] == needle { + return i + } + } + return -1 +} diff --git a/apps/cli/internal/sqlschema/contracts.go b/apps/cli/internal/sqlschema/contracts.go new file mode 100644 index 00000000..ac8404e6 --- /dev/null +++ b/apps/cli/internal/sqlschema/contracts.go @@ -0,0 +1,241 @@ +package sqlschema + +import ( + "fmt" + "io" + "os" + "path/filepath" + "slices" + "sort" + "strings" + + "ariga.io/atlas/sql/schema" + "gopkg.in/yaml.v3" +) + +// ContractsFileName is the name of the file data teams maintain alongside the +// blueprint to declare their schema dependencies. +const ContractsFileName = "schema-contracts.yaml" + +// ContractPolicy is how a contract reacts when a watched table changes. +type ContractPolicy string + +const ( + // PolicyBlocking fails CI (non-zero exit) when a watched table changes. + PolicyBlocking ContractPolicy = "blocking" + // PolicyNotify warns but does not affect the exit code. + PolicyNotify ContractPolicy = "notify" +) + +// ContractsFile is a parsed schema-contracts.yaml. +type ContractsFile struct { + Contracts []Contract `yaml:"contracts"` +} + +// Contract declares a downstream consumer and the schema objects it depends on. +type Contract struct { + Name string `yaml:"name"` + Owner string `yaml:"owner"` + Dependencies []Dependency `yaml:"dependencies"` +} + +// Dependency is a single database (or datastore) dependency within a contract. +type Dependency struct { + Database string `yaml:"database"` + Tables []string `yaml:"tables"` + // Datastore/Entities cover NoSQL datastores; SQL schema management ignores + // them, but they are parsed so a combined contracts file stays valid. + Datastore string `yaml:"datastore"` + Entities []string `yaml:"entities"` + Policy ContractPolicy `yaml:"policy"` +} + +// ContractImpact records that a change to a database's tables touched a contract. +type ContractImpact struct { + Contract string + Owner string + Policy ContractPolicy + Database string + Tables []string +} + +// FindContractsFile returns the path to a schema-contracts.yaml in dir, and +// whether it exists. +func FindContractsFile(dir string) (string, bool) { + path := filepath.Join(dir, ContractsFileName) + if _, err := os.Stat(path); err == nil { + return path, true + } + return "", false +} + +// LoadContractsFile reads and parses a schema-contracts.yaml. +func LoadContractsFile(path string) (*ContractsFile, error) { + f, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("opening contracts file %s: %w", path, err) + } + defer f.Close() + + var cf ContractsFile + dec := yaml.NewDecoder(f) + dec.KnownFields(true) + if err := dec.Decode(&cf); err != nil { + return nil, fmt.Errorf("parsing %s: %w", ContractsFileName, err) + } + return &cf, nil +} + +// ValidateContracts checks a contracts file against the blueprint's SQL database +// resources and their schemas: every SQL dependency must name a known database +// and only tables that exist in it, and every dependency must declare a valid +// policy. It returns a list of human-readable problems (empty when valid). +// Datastore (NoSQL) dependencies are only checked for a valid policy, since NoSQL +// schema management is not yet implemented. +func ValidateContracts(cf *ContractsFile, schemas map[string]*Schema) []string { + var problems []string + for _, c := range cf.Contracts { + if c.Name == "" { + problems = append(problems, "a contract is missing a name") + } + for _, dep := range c.Dependencies { + problems = append(problems, validateDependency(c.Name, dep, schemas)...) + } + } + return problems +} + +func validateDependency(contractName string, dep Dependency, schemas map[string]*Schema) []string { + label := fmt.Sprintf("contract %q", contractName) + + switch dep.Policy { + case PolicyBlocking, PolicyNotify: + case "": + return []string{fmt.Sprintf("%s: a dependency is missing a policy (blocking or notify)", label)} + default: + return []string{fmt.Sprintf("%s: invalid policy %q (must be blocking or notify)", label, dep.Policy)} + } + + // A NoSQL datastore dependency has nothing further to check here. + if dep.Database == "" && dep.Datastore != "" { + return nil + } + if dep.Database == "" { + return []string{fmt.Sprintf("%s: a dependency has neither a database nor a datastore", label)} + } + + sch, ok := schemas[dep.Database] + if !ok { + return []string{fmt.Sprintf( + "%s: depends on database %q, which is not a celerity/sqlDatabase resource in the blueprint", + label, dep.Database)} + } + var problems []string + for _, table := range dep.Tables { + if _, ok := sch.Tables[table]; !ok { + problems = append(problems, fmt.Sprintf( + "%s: depends on table %q in database %q, which does not exist in its schema", + label, table, dep.Database)) + } + } + return problems +} + +// EvaluateContracts returns the contracts affected by a set of changed tables, +// keyed by database resource name. A contract is affected when any table it +// watches on a database appears in that database's changed set. +func EvaluateContracts(cf *ContractsFile, changed map[string][]string) []ContractImpact { + if cf == nil { + return nil + } + var impacts []ContractImpact + for _, c := range cf.Contracts { + for _, dep := range c.Dependencies { + if dep.Database == "" { + continue + } + changedSet := changed[dep.Database] + if len(changedSet) == 0 { + continue + } + var matched []string + for _, table := range dep.Tables { + if slices.Contains(changedSet, table) { + matched = append(matched, table) + } + } + if len(matched) == 0 { + continue + } + sort.Strings(matched) + impacts = append(impacts, ContractImpact{ + Contract: c.Name, + Owner: c.Owner, + Policy: dep.Policy, + Database: dep.Database, + Tables: matched, + }) + } + } + return impacts +} + +// RenderContractImpacts writes a "Contracts affected" section for the given +// impacts. Blocking impacts are marked ⛔, notify impacts ⚠. It writes nothing +// when there are no impacts. +func RenderContractImpacts(w io.Writer, impacts []ContractImpact) { + if len(impacts) == 0 { + return + } + fmt.Fprintln(w, "\n Contracts affected:") + for _, i := range impacts { + marker := "⚠" + if i.Policy == PolicyBlocking { + marker = "⛔" + } + owner := "" + if i.Owner != "" { + owner = fmt.Sprintf(" (%s)", i.Owner) + } + fmt.Fprintf(w, " %s %s%s is affected by a change to %s.%s [%s]\n", + marker, i.Contract, owner, i.Database, strings.Join(i.Tables, ", "), i.Policy) + } +} + +// AnyBlocking reports whether any impact has a blocking policy. +func AnyBlocking(impacts []ContractImpact) bool { + for _, i := range impacts { + if i.Policy == PolicyBlocking { + return true + } + } + return false +} + +// Returns the distinct tables added, dropped or modified by a set of Atlas schema +// changes, less the migration-history table, which no contract can watch. +func changedTables(changes []schema.Change) []string { + seen := map[string]bool{} + for _, c := range changes { + var name string + switch ch := c.(type) { + case *schema.AddTable: + name = tableName(ch.T) + case *schema.DropTable: + name = tableName(ch.T) + case *schema.ModifyTable: + name = tableName(ch.T) + default: + continue + } + if name != "" && name != revisionsTable { + seen[name] = true + } + } + tables := make([]string, 0, len(seen)) + for name := range seen { + tables = append(tables, name) + } + sort.Strings(tables) + return tables +} diff --git a/apps/cli/internal/sqlschema/contracts_test.go b/apps/cli/internal/sqlschema/contracts_test.go new file mode 100644 index 00000000..04e70a00 --- /dev/null +++ b/apps/cli/internal/sqlschema/contracts_test.go @@ -0,0 +1,146 @@ +package sqlschema + +import ( + "os" + "path/filepath" + "strings" + "testing" + + atlasschema "ariga.io/atlas/sql/schema" + "github.com/stretchr/testify/suite" +) + +type ContractsSuite struct { + suite.Suite +} + +func TestContractsSuite(t *testing.T) { + suite.Run(t, new(ContractsSuite)) +} + +func (s *ContractsSuite) writeContracts(content string) string { + dir := s.T().TempDir() + path := filepath.Join(dir, ContractsFileName) + s.Require().NoError(os.WriteFile(path, []byte(content), 0o644)) + return path +} + +func contractSchemas() map[string]*Schema { + return map[string]*Schema{ + "ordersDb": { + Tables: map[string]Table{ + "orders": {Columns: map[string]Column{"id": {Type: "bigint", PrimaryKey: true}}}, + "customers": {Columns: map[string]Column{"id": {Type: "bigint", PrimaryKey: true}}}, + }, + }, + } +} + +func (s *ContractsSuite) Test_load_and_find() { + path := s.writeContracts(` +contracts: + - name: revenue-pipeline + owner: data-team + dependencies: + - database: ordersDb + tables: ["orders"] + policy: blocking +`) + found, ok := FindContractsFile(filepath.Dir(path)) + s.Require().True(ok) + s.Assert().Equal(path, found) + + cf, err := LoadContractsFile(path) + s.Require().NoError(err) + s.Require().Len(cf.Contracts, 1) + s.Assert().Equal("revenue-pipeline", cf.Contracts[0].Name) + s.Assert().Equal(PolicyBlocking, cf.Contracts[0].Dependencies[0].Policy) +} + +func (s *ContractsSuite) Test_validate_ok() { + cf := &ContractsFile{Contracts: []Contract{{ + Name: "revenue-pipeline", + Dependencies: []Dependency{ + {Database: "ordersDb", Tables: []string{"orders", "customers"}, Policy: PolicyBlocking}, + }, + }}} + s.Assert().Empty(ValidateContracts(cf, contractSchemas())) +} + +func (s *ContractsSuite) Test_validate_unknown_database_and_table_and_policy() { + cf := &ContractsFile{Contracts: []Contract{ + {Name: "a", Dependencies: []Dependency{{Database: "ghostDb", Tables: []string{"orders"}, Policy: PolicyNotify}}}, + {Name: "b", Dependencies: []Dependency{{Database: "ordersDb", Tables: []string{"ghost_table"}, Policy: PolicyBlocking}}}, + {Name: "c", Dependencies: []Dependency{{Database: "ordersDb", Tables: []string{"orders"}, Policy: "meh"}}}, + {Name: "d", Dependencies: []Dependency{{Database: "ordersDb", Tables: []string{"orders"}}}}, + }} + problems := ValidateContracts(cf, contractSchemas()) + joined := strings.Join(problems, "\n") + s.Assert().Contains(joined, "not a celerity/sqlDatabase resource") + s.Assert().Contains(joined, "does not exist in its schema") + s.Assert().Contains(joined, `invalid policy "meh"`) + s.Assert().Contains(joined, "missing a policy") +} + +func (s *ContractsSuite) Test_validate_datastore_dependency_only_checks_policy() { + cf := &ContractsFile{Contracts: []Contract{{ + Name: "user-analytics", + Dependencies: []Dependency{{Datastore: "userStore", Policy: PolicyBlocking}}, + }}} + // NoSQL datastore dependency is accepted (policy valid) without a schema. + s.Assert().Empty(ValidateContracts(cf, contractSchemas())) +} + +func (s *ContractsSuite) Test_evaluate_matches_blocking_and_notify() { + cf := &ContractsFile{Contracts: []Contract{ + {Name: "revenue-pipeline", Owner: "data-team", Dependencies: []Dependency{ + {Database: "ordersDb", Tables: []string{"orders"}, Policy: PolicyBlocking}, + }}, + {Name: "customer-analytics", Owner: "data-team", Dependencies: []Dependency{ + {Database: "ordersDb", Tables: []string{"customers", "orders"}, Policy: PolicyNotify}, + }}, + {Name: "unrelated", Dependencies: []Dependency{ + {Database: "ordersDb", Tables: []string{"invoices"}, Policy: PolicyBlocking}, + }}, + }} + + impacts := EvaluateContracts(cf, map[string][]string{"ordersDb": {"orders"}}) + s.Require().Len(impacts, 2) + s.Assert().True(AnyBlocking(impacts)) + + // "unrelated" watches invoices, which did not change, so it is not impacted. + names := []string{impacts[0].Contract, impacts[1].Contract} + s.Assert().Contains(names, "revenue-pipeline") + s.Assert().Contains(names, "customer-analytics") + s.Assert().NotContains(names, "unrelated") +} + +func (s *ContractsSuite) Test_evaluate_no_change_no_impact() { + cf := &ContractsFile{Contracts: []Contract{{ + Name: "revenue-pipeline", + Dependencies: []Dependency{{Database: "ordersDb", Tables: []string{"orders"}, Policy: PolicyBlocking}}, + }}} + s.Assert().Empty(EvaluateContracts(cf, map[string][]string{"ordersDb": {"customers"}})) + s.Assert().Empty(EvaluateContracts(nil, map[string][]string{"ordersDb": {"orders"}})) +} + +func (s *ContractsSuite) Test_changed_tables_extraction() { + changes := []atlasschema.Change{ + &atlasschema.AddTable{T: atlasschema.NewTable("orders")}, + &atlasschema.ModifyTable{T: atlasschema.NewTable("customers")}, + &atlasschema.AddTable{T: atlasschema.NewTable(revisionsTable)}, // ignored + } + s.Assert().Equal([]string{"customers", "orders"}, changedTables(changes)) +} + +func (s *ContractsSuite) Test_render_contract_impacts() { + var b strings.Builder + RenderContractImpacts(&b, []ContractImpact{ + {Contract: "revenue-pipeline", Owner: "data-team", Policy: PolicyBlocking, Database: "ordersDb", Tables: []string{"orders"}}, + {Contract: "customer-analytics", Owner: "data-team", Policy: PolicyNotify, Database: "ordersDb", Tables: []string{"customers"}}, + }) + out := b.String() + s.Assert().Contains(out, "Contracts affected:") + s.Assert().Contains(out, "⛔ revenue-pipeline (data-team) is affected by a change to ordersDb.orders [blocking]") + s.Assert().Contains(out, "⚠ customer-analytics (data-team) is affected by a change to ordersDb.customers [notify]") +} diff --git a/apps/cli/internal/sqlschema/ddl.go b/apps/cli/internal/sqlschema/ddl.go deleted file mode 100644 index be8a0296..00000000 --- a/apps/cli/internal/sqlschema/ddl.go +++ /dev/null @@ -1,279 +0,0 @@ -package sqlschema - -import ( - "fmt" - "sort" - "strings" -) - -// DDLResult holds both up (create) and down (drop) DDL statements. -type DDLResult struct { - Up []string - Down []string -} - -// GenerateDDL produces ordered up and down DDL statements from a parsed schema. -// The engine parameter is validated (v0: "postgres" only). -// -// Up statements are in dependency order: -// 1. Extensions -// 2. Tables (CREATE TABLE) -// 3. Foreign keys (ALTER TABLE ADD CONSTRAINT) -// 4. Indexes (CREATE INDEX) -// 5. Check constraints -// -// Down statements are in reverse dependency order: -// 1. Check constraints (DROP) -// 2. Indexes (DROP) -// 3. Foreign keys (DROP) -// 4. Tables (DROP) — reverse alphabetical -// 5. Extensions (DROP) -func GenerateDDL(s *Schema, engine string) (*DDLResult, error) { - if engine != "postgres" { - return nil, fmt.Errorf("unsupported SQL engine %q (supported: postgres)", engine) - } - - tableNames := sortedKeys(s.Tables) - - // --- Up statements --- - var up []string - up = append(up, generateCreateExtensions(s.Extensions)...) - - for _, tableName := range tableNames { - table := s.Tables[tableName] - stmt, err := generateCreateTable(tableName, table) - if err != nil { - return nil, fmt.Errorf("table %s: %w", tableName, err) - } - up = append(up, stmt) - } - - up = append(up, generateAddForeignKeys(s.Tables, tableNames)...) - up = append(up, generateCreateIndexes(s.Tables, tableNames)...) - up = append(up, generateAddCheckConstraints(s.Tables, tableNames)...) - - // --- Down statements (reverse dependency order) --- - var down []string - down = append(down, generateDropCheckConstraints(s.Tables, tableNames)...) - down = append(down, generateDropIndexes(s.Tables, tableNames)...) - down = append(down, generateDropForeignKeys(s.Tables, tableNames)...) - - // Drop tables in reverse order. - for i := len(tableNames) - 1; i >= 0; i-- { - down = append(down, fmt.Sprintf("DROP TABLE IF EXISTS %s CASCADE", quoteIdent(tableNames[i]))) - } - - down = append(down, generateDropExtensions(s.Extensions)...) - - return &DDLResult{Up: up, Down: down}, nil -} - -// --- Up generators --- - -func generateCreateExtensions(extensions []string) []string { - stmts := make([]string, len(extensions)) - for i, ext := range extensions { - stmts[i] = fmt.Sprintf("CREATE EXTENSION IF NOT EXISTS %q", ext) - } - return stmts -} - -func generateCreateTable(name string, table Table) (string, error) { - if len(table.Columns) == 0 { - return "", fmt.Errorf("table has no columns") - } - - colNames := sortedKeys(table.Columns) - - var colDefs []string - var primaryKeys []string - - for _, colName := range colNames { - col := table.Columns[colName] - def := fmt.Sprintf(" %s %s", quoteIdent(colName), col.Type) - - if col.PrimaryKey { - primaryKeys = append(primaryKeys, quoteIdent(colName)) - } - - if !col.Nullable && !col.PrimaryKey { - def += " NOT NULL" - } - - if col.Unique { - def += " UNIQUE" - } - - if col.Default != "" { - def += " DEFAULT " + col.Default - } - - colDefs = append(colDefs, def) - } - - if len(primaryKeys) > 0 { - colDefs = append(colDefs, fmt.Sprintf(" PRIMARY KEY (%s)", strings.Join(primaryKeys, ", "))) - } - - return fmt.Sprintf( - "CREATE TABLE IF NOT EXISTS %s (\n%s\n)", - quoteIdent(name), - strings.Join(colDefs, ",\n"), - ), nil -} - -func generateAddForeignKeys(tables map[string]Table, tableNames []string) []string { - var stmts []string - for _, tableName := range tableNames { - table := tables[tableName] - colNames := sortedKeys(table.Columns) - for _, colName := range colNames { - col := table.Columns[colName] - if col.References == nil { - continue - } - fkName := fkConstraintName(tableName, colName) - stmt := fmt.Sprintf( - "ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s(%s)", - quoteIdent(tableName), - quoteIdent(fkName), - quoteIdent(colName), - quoteIdent(col.References.Table), - quoteIdent(col.References.Column), - ) - if col.References.OnDelete != "" { - stmt += " ON DELETE " + strings.ToUpper(col.References.OnDelete) - } - stmts = append(stmts, stmt) - } - } - return stmts -} - -func generateCreateIndexes(tables map[string]Table, tableNames []string) []string { - var stmts []string - for _, tableName := range tableNames { - table := tables[tableName] - for _, idx := range table.Indexes { - uniqueStr := "" - if idx.Unique { - uniqueStr = "UNIQUE " - } - quotedCols := make([]string, len(idx.Columns)) - for i, c := range idx.Columns { - quotedCols[i] = quoteIdent(c) - } - stmts = append(stmts, fmt.Sprintf( - "CREATE %sINDEX IF NOT EXISTS %s ON %s (%s)", - uniqueStr, - quoteIdent(idx.Name), - quoteIdent(tableName), - strings.Join(quotedCols, ", "), - )) - } - } - return stmts -} - -func generateAddCheckConstraints(tables map[string]Table, tableNames []string) []string { - var stmts []string - for _, tableName := range tableNames { - table := tables[tableName] - for _, c := range table.Constraints { - if c.Type != "check" || c.Expression == "" { - continue - } - stmts = append(stmts, fmt.Sprintf( - "ALTER TABLE %s ADD CONSTRAINT %s CHECK (%s)", - quoteIdent(tableName), - quoteIdent(c.Name), - c.Expression, - )) - } - } - return stmts -} - -// --- Down generators --- - -func generateDropExtensions(extensions []string) []string { - stmts := make([]string, len(extensions)) - // Drop in reverse order. - for i, ext := range extensions { - stmts[len(extensions)-1-i] = fmt.Sprintf("DROP EXTENSION IF EXISTS %q CASCADE", ext) - } - return stmts -} - -func generateDropForeignKeys(tables map[string]Table, tableNames []string) []string { - var stmts []string - // Reverse table order for dropping. - for i := len(tableNames) - 1; i >= 0; i-- { - tableName := tableNames[i] - table := tables[tableName] - colNames := sortedKeys(table.Columns) - for _, colName := range colNames { - col := table.Columns[colName] - if col.References == nil { - continue - } - fkName := fkConstraintName(tableName, colName) - stmts = append(stmts, fmt.Sprintf( - "ALTER TABLE %s DROP CONSTRAINT IF EXISTS %s", - quoteIdent(tableName), - quoteIdent(fkName), - )) - } - } - return stmts -} - -func generateDropIndexes(tables map[string]Table, tableNames []string) []string { - var stmts []string - for i := len(tableNames) - 1; i >= 0; i-- { - table := tables[tableNames[i]] - for _, idx := range table.Indexes { - stmts = append(stmts, fmt.Sprintf("DROP INDEX IF EXISTS %s", quoteIdent(idx.Name))) - } - } - return stmts -} - -func generateDropCheckConstraints(tables map[string]Table, tableNames []string) []string { - var stmts []string - for i := len(tableNames) - 1; i >= 0; i-- { - tableName := tableNames[i] - table := tables[tableName] - for _, c := range table.Constraints { - if c.Type != "check" || c.Name == "" { - continue - } - stmts = append(stmts, fmt.Sprintf( - "ALTER TABLE %s DROP CONSTRAINT IF EXISTS %s", - quoteIdent(tableName), - quoteIdent(c.Name), - )) - } - } - return stmts -} - -// --- Helpers --- - -func fkConstraintName(tableName, colName string) string { - return fmt.Sprintf("fk_%s_%s", tableName, colName) -} - -// quoteIdent quotes a SQL identifier with double quotes. -func quoteIdent(name string) string { - return `"` + strings.ReplaceAll(name, `"`, `""`) + `"` -} - -func sortedKeys[V any](m map[string]V) []string { - keys := make([]string, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - sort.Strings(keys) - return keys -} diff --git a/apps/cli/internal/sqlschema/ddl_test.go b/apps/cli/internal/sqlschema/ddl_test.go deleted file mode 100644 index ce06d5dd..00000000 --- a/apps/cli/internal/sqlschema/ddl_test.go +++ /dev/null @@ -1,238 +0,0 @@ -package sqlschema - -import ( - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func Test_GenerateDDL_unsupported_engine(t *testing.T) { - s := &Schema{Tables: map[string]Table{"t": {Columns: map[string]Column{"id": {Type: "int"}}}}} - _, err := GenerateDDL(s, "mysql") - assert.ErrorContains(t, err, "unsupported SQL engine") -} - -func Test_GenerateDDL_extensions(t *testing.T) { - s := &Schema{ - Extensions: []string{"uuid-ossp", "pg_trgm"}, - Tables: map[string]Table{ - "t": {Columns: map[string]Column{"id": {Type: "serial", PrimaryKey: true}}}, - }, - } - ddl, err := GenerateDDL(s, "postgres") - require.NoError(t, err) - assert.Contains(t, ddl.Up[0], `"uuid-ossp"`) - assert.Contains(t, ddl.Up[1], `"pg_trgm"`) - - // Down should drop extensions in reverse order. - lastDown := ddl.Down[len(ddl.Down)-1] - secondLastDown := ddl.Down[len(ddl.Down)-2] - assert.Contains(t, lastDown, `"uuid-ossp"`) - assert.Contains(t, secondLastDown, `"pg_trgm"`) -} - -func Test_GenerateDDL_basic_table(t *testing.T) { - s := &Schema{ - Tables: map[string]Table{ - "users": { - Columns: map[string]Column{ - "id": {Type: "serial", PrimaryKey: true}, - "name": {Type: "varchar(100)", Nullable: false}, - "email": {Type: "varchar(255)", Nullable: true, Unique: true}, - }, - }, - }, - } - - ddl, err := GenerateDDL(s, "postgres") - require.NoError(t, err) - require.Len(t, ddl.Up, 1) - - stmt := ddl.Up[0] - assert.Contains(t, stmt, `CREATE TABLE IF NOT EXISTS "users"`) - assert.Contains(t, stmt, `"id" serial`) - assert.Contains(t, stmt, `"name" varchar(100) NOT NULL`) - assert.Contains(t, stmt, `"email" varchar(255) UNIQUE`) - assert.Contains(t, stmt, `PRIMARY KEY ("id")`) - - // Down should drop the table. - require.Len(t, ddl.Down, 1) - assert.Contains(t, ddl.Down[0], `DROP TABLE IF EXISTS "users" CASCADE`) -} - -func Test_GenerateDDL_with_defaults(t *testing.T) { - s := &Schema{ - Tables: map[string]Table{ - "events": { - Columns: map[string]Column{ - "id": {Type: "serial", PrimaryKey: true}, - "created_at": {Type: "timestamptz", Default: "NOW()"}, - }, - }, - }, - } - - ddl, err := GenerateDDL(s, "postgres") - require.NoError(t, err) - assert.Contains(t, ddl.Up[0], `DEFAULT NOW()`) -} - -func Test_GenerateDDL_foreign_keys(t *testing.T) { - s := &Schema{ - Tables: map[string]Table{ - "orders": { - Columns: map[string]Column{ - "id": {Type: "serial", PrimaryKey: true}, - "user_id": {Type: "integer", References: &ForeignKey{Table: "users", Column: "id", OnDelete: "CASCADE"}}, - }, - }, - "users": { - Columns: map[string]Column{ - "id": {Type: "serial", PrimaryKey: true}, - }, - }, - }, - } - - ddl, err := GenerateDDL(s, "postgres") - require.NoError(t, err) - - // Find the FK up statement. - var fkUp string - for _, stmt := range ddl.Up { - if strings.Contains(stmt, "FOREIGN KEY") { - fkUp = stmt - break - } - } - require.NotEmpty(t, fkUp, "expected a foreign key statement") - assert.Contains(t, fkUp, `REFERENCES "users"("id")`) - assert.Contains(t, fkUp, "ON DELETE CASCADE") - - // Find the FK down statement. - var fkDown string - for _, stmt := range ddl.Down { - if strings.Contains(stmt, "DROP CONSTRAINT") { - fkDown = stmt - break - } - } - require.NotEmpty(t, fkDown, "expected a drop constraint statement") - assert.Contains(t, fkDown, `"fk_orders_user_id"`) -} - -func Test_GenerateDDL_indexes(t *testing.T) { - s := &Schema{ - Tables: map[string]Table{ - "audit_log": { - Columns: map[string]Column{ - "id": {Type: "serial", PrimaryKey: true}, - "entity_type": {Type: "varchar(50)"}, - "entity_id": {Type: "varchar(100)"}, - }, - Indexes: []Index{ - {Name: "idx_entity", Columns: []string{"entity_type", "entity_id"}}, - {Name: "idx_unique_entity", Columns: []string{"entity_type", "entity_id"}, Unique: true}, - }, - }, - }, - } - - ddl, err := GenerateDDL(s, "postgres") - require.NoError(t, err) - - var upIndexStmts []string - for _, stmt := range ddl.Up { - if strings.Contains(stmt, "INDEX") { - upIndexStmts = append(upIndexStmts, stmt) - } - } - require.Len(t, upIndexStmts, 2) - assert.Contains(t, upIndexStmts[0], `CREATE INDEX IF NOT EXISTS "idx_entity"`) - assert.Contains(t, upIndexStmts[1], `CREATE UNIQUE INDEX IF NOT EXISTS "idx_unique_entity"`) - - var downIndexStmts []string - for _, stmt := range ddl.Down { - if strings.Contains(stmt, "DROP INDEX") { - downIndexStmts = append(downIndexStmts, stmt) - } - } - require.Len(t, downIndexStmts, 2) -} - -func Test_GenerateDDL_check_constraints(t *testing.T) { - s := &Schema{ - Tables: map[string]Table{ - "products": { - Columns: map[string]Column{ - "id": {Type: "serial", PrimaryKey: true}, - "price": {Type: "numeric(10,2)"}, - }, - Constraints: []Constraint{ - {Name: "chk_price_positive", Type: "check", Expression: "price > 0"}, - }, - }, - }, - } - - ddl, err := GenerateDDL(s, "postgres") - require.NoError(t, err) - - var checkUp string - for _, stmt := range ddl.Up { - if strings.Contains(stmt, "CHECK") { - checkUp = stmt - break - } - } - require.NotEmpty(t, checkUp) - assert.Contains(t, checkUp, `CHECK (price > 0)`) - - var checkDown string - for _, stmt := range ddl.Down { - if strings.Contains(stmt, "chk_price_positive") { - checkDown = stmt - break - } - } - require.NotEmpty(t, checkDown) - assert.Contains(t, checkDown, `DROP CONSTRAINT IF EXISTS "chk_price_positive"`) -} - -func Test_GenerateDDL_deterministic_order(t *testing.T) { - s := &Schema{ - Tables: map[string]Table{ - "zebra": {Columns: map[string]Column{"id": {Type: "serial", PrimaryKey: true}}}, - "alpha": {Columns: map[string]Column{"id": {Type: "serial", PrimaryKey: true}}}, - "middle": {Columns: map[string]Column{"id": {Type: "serial", PrimaryKey: true}}}, - }, - } - - ddl1, err := GenerateDDL(s, "postgres") - require.NoError(t, err) - ddl2, err := GenerateDDL(s, "postgres") - require.NoError(t, err) - assert.Equal(t, ddl1, ddl2) - - // Up: alphabetical order. - assert.Contains(t, ddl1.Up[0], `"alpha"`) - assert.Contains(t, ddl1.Up[1], `"middle"`) - assert.Contains(t, ddl1.Up[2], `"zebra"`) - - // Down: reverse alphabetical order. - assert.Contains(t, ddl1.Down[0], `"zebra"`) - assert.Contains(t, ddl1.Down[1], `"middle"`) - assert.Contains(t, ddl1.Down[2], `"alpha"`) -} - -func Test_GenerateDDL_empty_table_error(t *testing.T) { - s := &Schema{ - Tables: map[string]Table{ - "empty": {Columns: map[string]Column{}}, - }, - } - _, err := GenerateDDL(s, "postgres") - assert.ErrorContains(t, err, "no columns") -} diff --git a/apps/cli/internal/sqlschema/dialect.go b/apps/cli/internal/sqlschema/dialect.go index abe3bfc9..18e420e1 100644 --- a/apps/cli/internal/sqlschema/dialect.go +++ b/apps/cli/internal/sqlschema/dialect.go @@ -1,9 +1,17 @@ package sqlschema -import "fmt" +import ( + "context" + "database/sql" + "fmt" -// dialect encapsulates engine-specific SQL syntax and driver details. -// Each supported database engine provides its own implementation. + "ariga.io/atlas/sql/migrate" + atlasschema "ariga.io/atlas/sql/schema" +) + +// dialect encapsulates engine-specific SQL syntax, driver details and the Atlas +// integration for a database engine. Each supported engine provides its own +// implementation. type dialect interface { // DriverName returns the database/sql driver name (e.g. "pgx", "mysql"). DriverName() string @@ -16,18 +24,9 @@ type dialect interface { // The name is already quoted with QuoteIdentifier. CreateDatabaseSQL(quotedName string) string - // CreateMigrationsTableSQL returns the DDL to create the migrations tracking table. - CreateMigrationsTableSQL(tableName string) string - - // InsertVersionSQL returns the SQL to insert a migration version record, - // ignoring duplicates. Uses engine-appropriate parameter placeholders. - InsertVersionSQL(tableName string) string - - // DeleteVersionSQL returns the SQL to delete a migration version record. - DeleteVersionSQL(tableName string) string - - // SelectVersionsSQL returns the SQL to select all applied migration versions. - SelectVersionsSQL(tableName string) string + // DropDatabaseSQL returns the DDL to drop a database if it exists. The name + // is already quoted with QuoteIdentifier. + DropDatabaseSQL(quotedName string) string // QuoteIdentifier quotes a database identifier (table name, database name) // using the engine's quoting convention. @@ -35,15 +34,65 @@ type dialect interface { // ReplaceDatabase returns a new connection string with the database name replaced. ReplaceDatabase(connStr string, dbName string) (string, error) + + // NormalizeConnString adjusts a connection string with parameters the engine + // needs (e.g. MySQL's parseTime), returning it unchanged when none are needed. + NormalizeConnString(connStr string) (string, error) + + // OpenAtlas wraps a live connection in the engine's Atlas driver, which + // provides schema inspection, diffing and change application. + OpenAtlas(db *sql.DB) (migrate.Driver, error) + + // ParseType parses an engine-native column type (e.g. "varchar(255)") into an + // Atlas type. + ParseType(columnType string) (atlasschema.Type, error) + + // SchemaName returns the name of the schema Celerity manages within the + // connected database. Postgres uses a fixed "public"; MySQL uses the connected + // database name. + SchemaName(ctx context.Context, db *sql.DB) (string, error) + + // IndexTypeAttr maps an index method from the schema YAML (e.g. "gin") to the + // engine's Atlas attribute. It returns a nil attribute for the empty string + // and for the engine default (btree), so a schema that omits the method + // diffs identically to one that spells out the default. Unsupported methods + // are an error naming what the engine accepts. + IndexTypeAttr(indexType string) (atlasschema.Attr, error) + + // NewRevisions returns the engine-specific migration-history store backing the + // atlas_schema_revisions table. + NewRevisions(ctx context.Context, db *sql.DB) (migrate.RevisionReadWriter, error) + + // ProvisionAppUser creates or repairs the application database role. Every + // identifier in the request has already been validated, which is what lets + // the implementations interpolate them into DDL that cannot take + // placeholders. It must be idempotent: it runs after every deploy. + ProvisionAppUser(ctx context.Context, db *sql.DB, req provisionRequest) (*ProvisionReport, error) + + // SupportsExtensions reports whether the engine has CREATE EXTENSION (Postgres). + SupportsExtensions() bool + + // FingerprintAdvancedObjects fingerprints the objects the structural diff does + // not cover (views, triggers, functions, policies) for drift detection. It + // returns an empty map on engines where this is not yet implemented. + FingerprintAdvancedObjects(ctx context.Context, db *sql.DB, schemaName string) (map[string]string, error) } +// mysqlEnabled gates the MySQL dialect. MySQL support is fully implemented but is +// not part of the v0 release, so it is disabled by default; the MySQL tests flip +// it on. Flip this default (or remove the gate) to ship MySQL support. +var mysqlEnabled = false + func dialectForEngine(engine string) (dialect, error) { switch engine { case "postgres", "": return postgresDialect{}, nil case "mysql": - return nil, fmt.Errorf("SQL engine %q is not yet supported (planned for v1)", engine) + if !mysqlEnabled { + return nil, fmt.Errorf("SQL engine %q is not yet supported (postgres is supported in v0; MySQL is planned for a future release)", engine) + } + return mysqlDialect{}, nil default: - return nil, fmt.Errorf("unsupported SQL engine %q", engine) + return nil, fmt.Errorf("unsupported SQL engine %q (supported: postgres)", engine) } } diff --git a/apps/cli/internal/sqlschema/dialect_mysql.go b/apps/cli/internal/sqlschema/dialect_mysql.go new file mode 100644 index 00000000..56f84457 --- /dev/null +++ b/apps/cli/internal/sqlschema/dialect_mysql.go @@ -0,0 +1,116 @@ +package sqlschema + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "ariga.io/atlas/sql/migrate" + "ariga.io/atlas/sql/mysql" + atlasschema "ariga.io/atlas/sql/schema" + gomysql "github.com/go-sql-driver/mysql" +) + +type mysqlDialect struct{} + +func (mysqlDialect) DriverName() string { return "mysql" } + +func (mysqlDialect) DatabaseExistsQuery() string { + return "SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = ?" +} + +func (mysqlDialect) CreateDatabaseSQL(quotedName string) string { + return fmt.Sprintf("CREATE DATABASE %s", quotedName) +} + +func (mysqlDialect) DropDatabaseSQL(quotedName string) string { + return fmt.Sprintf("DROP DATABASE IF EXISTS %s", quotedName) +} + +func (mysqlDialect) QuoteIdentifier(name string) string { + return "`" + strings.ReplaceAll(name, "`", "``") + "`" +} + +func (mysqlDialect) ReplaceDatabase(connStr string, dbName string) (string, error) { + cfg, err := gomysql.ParseDSN(connStr) + if err != nil { + return "", fmt.Errorf("parsing MySQL DSN: %w", err) + } + cfg.DBName = dbName + return cfg.FormatDSN(), nil +} + +// NormalizeConnString ensures the DSN scans DATETIME columns into time.Time, +// which the migration-history reader relies on. +func (mysqlDialect) NormalizeConnString(connStr string) (string, error) { + cfg, err := gomysql.ParseDSN(connStr) + if err != nil { + return "", fmt.Errorf("parsing MySQL DSN: %w", err) + } + cfg.ParseTime = true + return cfg.FormatDSN(), nil +} + +func (mysqlDialect) OpenAtlas(db *sql.DB) (migrate.Driver, error) { + drv, err := mysql.Open(db) + if err != nil { + return nil, fmt.Errorf("opening atlas mysql driver: %w", err) + } + return drv, nil +} + +func (mysqlDialect) ParseType(columnType string) (atlasschema.Type, error) { + return mysql.ParseType(columnType) +} + +// SchemaName returns the connected database, which is the schema Atlas manages +// for MySQL (MySQL has no separate schema namespace within a database). +func (mysqlDialect) SchemaName(ctx context.Context, db *sql.DB) (string, error) { + var name sql.NullString + if err := db.QueryRowContext(ctx, "SELECT DATABASE()").Scan(&name); err != nil { + return "", fmt.Errorf("reading current database name: %w", err) + } + if !name.Valid || name.String == "" { + return "", fmt.Errorf("no database selected in the MySQL connection") + } + return name.String, nil +} + +// The index methods that can be declared in the schema YAML. +var mysqlIndexTypes = map[string]string{ + "btree": mysql.IndexTypeBTree, + "hash": mysql.IndexTypeHash, + "fulltext": mysql.IndexTypeFullText, + "spatial": mysql.IndexTypeSpatial, +} + +func (mysqlDialect) IndexTypeAttr(indexType string) (atlasschema.Attr, error) { + if indexType == "" { + return nil, nil + } + t, ok := mysqlIndexTypes[strings.ToLower(indexType)] + if !ok { + return nil, fmt.Errorf( + "unsupported index type %q for mysql (supported: %s)", + indexType, strings.Join(sortedKeys(mysqlIndexTypes), ", "), + ) + } + if t == mysql.IndexTypeBTree { + return nil, nil + } + return &mysql.IndexType{T: t}, nil +} + +func (mysqlDialect) NewRevisions(ctx context.Context, db *sql.DB) (migrate.RevisionReadWriter, error) { + return newMySQLRevisions(ctx, db) +} + +func (mysqlDialect) SupportsExtensions() bool { return false } + +// FingerprintAdvancedObjects returns no fingerprints. Advanced-object drift +// (triggers, functions, views) is not yet implemented for MySQL, so those +// objects are not tracked by drift detection there. +func (mysqlDialect) FingerprintAdvancedObjects(context.Context, *sql.DB, string) (map[string]string, error) { + return map[string]string{}, nil +} diff --git a/apps/cli/internal/sqlschema/dialect_postgres.go b/apps/cli/internal/sqlschema/dialect_postgres.go index 65c2d257..c5062d56 100644 --- a/apps/cli/internal/sqlschema/dialect_postgres.go +++ b/apps/cli/internal/sqlschema/dialect_postgres.go @@ -1,46 +1,37 @@ package sqlschema import ( + "context" + "database/sql" "fmt" "net/url" + "strings" + + "ariga.io/atlas/sql/migrate" + "ariga.io/atlas/sql/postgres" + atlasschema "ariga.io/atlas/sql/schema" + _ "github.com/jackc/pgx/v5/stdlib" ) +// The schema Celerity manages within a Postgres database. Postgres databases +// always have a "public" schema, and scoping diffs to it keeps other schemas +// untouched. +const postgresSchemaName = "public" + type postgresDialect struct{} func (postgresDialect) DriverName() string { return "pgx" } func (postgresDialect) DatabaseExistsQuery() string { - return "SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)" + return "SELECT COUNT(*) FROM pg_database WHERE datname = $1" } func (postgresDialect) CreateDatabaseSQL(quotedName string) string { return fmt.Sprintf("CREATE DATABASE %s", quotedName) } -func (postgresDialect) CreateMigrationsTableSQL(tableName string) string { - return fmt.Sprintf(` - CREATE TABLE IF NOT EXISTS %s ( - version integer NOT NULL, - description text NOT NULL, - applied_at timestamptz NOT NULL DEFAULT NOW(), - PRIMARY KEY (version) - ) - `, tableName) -} - -func (postgresDialect) InsertVersionSQL(tableName string) string { - return fmt.Sprintf( - "INSERT INTO %s (version, description, applied_at) VALUES ($1, $2, $3) ON CONFLICT (version) DO NOTHING", - tableName, - ) -} - -func (postgresDialect) DeleteVersionSQL(tableName string) string { - return fmt.Sprintf("DELETE FROM %s WHERE version = $1", tableName) -} - -func (postgresDialect) SelectVersionsSQL(tableName string) string { - return fmt.Sprintf("SELECT version FROM %s ORDER BY version", tableName) +func (postgresDialect) DropDatabaseSQL(quotedName string) string { + return fmt.Sprintf("DROP DATABASE IF EXISTS %s", quotedName) } func (postgresDialect) QuoteIdentifier(name string) string { @@ -55,3 +46,64 @@ func (postgresDialect) ReplaceDatabase(connStr string, dbName string) (string, e u.Path = "/" + dbName return u.String(), nil } + +func (postgresDialect) OpenAtlas(db *sql.DB) (migrate.Driver, error) { + drv, err := postgres.Open(db) + if err != nil { + return nil, fmt.Errorf("opening atlas postgres driver: %w", err) + } + return drv, nil +} + +func (postgresDialect) ParseType(columnType string) (atlasschema.Type, error) { + return postgres.ParseType(columnType) +} + +func (postgresDialect) SchemaName(context.Context, *sql.DB) (string, error) { + return postgresSchemaName, nil +} + +// The index methods that can be declared in the schema YAML. Methods beyond +// these, and indexes needing operator classes, expressions or predicates, belong +// in a hand-written migration. +var postgresIndexTypes = map[string]string{ + "btree": postgres.IndexTypeBTree, + "gin": postgres.IndexTypeGIN, + "gist": postgres.IndexTypeGiST, + "spgist": postgres.IndexTypeSPGiST, + "brin": postgres.IndexTypeBRIN, + "hash": postgres.IndexTypeHash, +} + +func (postgresDialect) IndexTypeAttr(indexType string) (atlasschema.Attr, error) { + if indexType == "" { + return nil, nil + } + t, ok := postgresIndexTypes[strings.ToLower(indexType)] + if !ok { + return nil, fmt.Errorf( + "unsupported index type %q for postgres (supported: %s)", + indexType, strings.Join(sortedKeys(postgresIndexTypes), ", "), + ) + } + // Atlas defaults an absent attribute to btree; leaving it unset keeps a + // schema that spells out the default diff-identical to one that omits it. + if t == postgres.IndexTypeBTree { + return nil, nil + } + return &postgres.IndexType{T: t}, nil +} + +func (postgresDialect) NewRevisions(ctx context.Context, db *sql.DB) (migrate.RevisionReadWriter, error) { + return newPGRevisions(ctx, db) +} + +func (postgresDialect) SupportsExtensions() bool { return true } + +func (postgresDialect) NormalizeConnString(connStr string) (string, error) { + return connStr, nil +} + +func (postgresDialect) FingerprintAdvancedObjects(ctx context.Context, db *sql.DB, _ string) (map[string]string, error) { + return fingerprintPostgresAdvancedObjects(ctx, db) +} diff --git a/apps/cli/internal/sqlschema/dialect_test.go b/apps/cli/internal/sqlschema/dialect_test.go new file mode 100644 index 00000000..32bd76ab --- /dev/null +++ b/apps/cli/internal/sqlschema/dialect_test.go @@ -0,0 +1,48 @@ +package sqlschema + +import ( + "testing" + + "github.com/stretchr/testify/suite" +) + +// enableMySQLForTest turns the gated MySQL dialect on for the duration of a test, +// restoring the previous state afterwards. +func enableMySQLForTest(t *testing.T) { + prev := mysqlEnabled + mysqlEnabled = true + t.Cleanup(func() { mysqlEnabled = prev }) +} + +type DialectGateSuite struct { + suite.Suite +} + +func TestDialectGateSuite(t *testing.T) { + suite.Run(t, new(DialectGateSuite)) +} + +func (s *DialectGateSuite) Test_mysql_gated_off_by_default() { + _, err := dialectForEngine("mysql") + s.Require().Error(err) + s.Assert().Contains(err.Error(), "not yet supported") +} + +func (s *DialectGateSuite) Test_mysql_available_when_enabled() { + enableMySQLForTest(s.T()) + d, err := dialectForEngine("mysql") + s.Require().NoError(err) + s.Assert().Equal("mysql", d.DriverName()) +} + +func (s *DialectGateSuite) Test_postgres_always_available() { + d, err := dialectForEngine("postgres") + s.Require().NoError(err) + s.Assert().Equal("pgx", d.DriverName()) +} + +func (s *DialectGateSuite) Test_unknown_engine_errors() { + _, err := dialectForEngine("oracle") + s.Require().Error(err) + s.Assert().Contains(err.Error(), "unsupported SQL engine") +} diff --git a/apps/cli/internal/sqlschema/drift.go b/apps/cli/internal/sqlschema/drift.go new file mode 100644 index 00000000..764b15ef --- /dev/null +++ b/apps/cli/internal/sqlschema/drift.go @@ -0,0 +1,432 @@ +package sqlschema + +import ( + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "fmt" + "io" + "os" + "path/filepath" + "sort" + + "ariga.io/atlas/sql/migrate" + atlasschema "ariga.io/atlas/sql/schema" +) + +// DriftReport describes how a live database has diverged from the state its +// committed migrations should have produced. It is reported at three layers, +// matching the schema-management spec: +// +// - History: the revision table vs the migration directory (migrations applied +// out-of-band, missing from the directory, or applied out of order). +// - Structural: the live tables/columns/indexes/keys/constraints vs the +// expected state (everything the schema YAML models). +// - Advanced: triggers/functions/views/RLS policies fingerprinted from the +// catalog (objects created by hand-written migrations), reported coarsely as +// changed / missing / unexpected. +// +// Each layer is a list of human-readable lines; empty means no drift at that +// layer. +type DriftReport struct { + Resource string + Target string + History []string + Structural []string + Advanced []string + // StructuralTables lists the tables that drifted structurally, for schema + // contract evaluation. Contracts, when populated by the caller, are rendered + // in the report. + StructuralTables []string + Contracts []ContractImpact +} + +// HasDrift reports whether any layer found drift. +func (r *DriftReport) HasDrift() bool { + return len(r.History)+len(r.Structural)+len(r.Advanced) > 0 +} + +// Render writes a human-readable report to w. +func (r *DriftReport) Render(w io.Writer) { + if !r.HasDrift() { + fmt.Fprintf(w, "No drift detected for %s (%s).\n", r.Resource, r.Target) + return + } + + fmt.Fprintf(w, "Drift detected for %s (%s)\n", r.Resource, r.Target) + renderDriftSection(w, "History drift", r.History) + renderDriftSection(w, "Structural drift", r.Structural) + renderDriftSection(w, "Advanced-object drift", r.Advanced) + + RenderContractImpacts(w, r.Contracts) + + fmt.Fprintln(w, "\n Resolution:") + fmt.Fprintln(w, " - To adopt a change: add it to the schema YAML, run `celerity schema diff`") + fmt.Fprintln(w, " (generated statements are guarded so they no-op where the object already") + fmt.Fprintln(w, " exists), then apply with --allow-drift.") + fmt.Fprintln(w, " - To remove a change: create a hand-written migration reverting it") + fmt.Fprintln(w, " (`celerity schema new`), then apply with --allow-drift.") +} + +func renderDriftSection(w io.Writer, title string, lines []string) { + if len(lines) == 0 { + return + } + fmt.Fprintf(w, "\n %s:\n", title) + for _, line := range lines { + fmt.Fprintf(w, " ~ %s\n", line) + } +} + +// DetectDrift compares the live database behind `live` against the state its +// committed migrations should have produced. +// +// History drift is always computed (it needs only the revision table and the +// migration directory). Structural and advanced-object drift require a clean dev +// database at devConnStr: the migrations recorded as applied are replayed into it +// to reconstruct the expected state, which is then diffed against the live +// database. Pass devConnStr == "" to run history drift only. +func DetectDrift(ctx context.Context, live *Applier, devConnStr, migrationsPath, engine string) (*DriftReport, error) { + report := &DriftReport{} + + rrw, err := live.dialect.NewRevisions(ctx, live.db) + if err != nil { + return nil, err + } + revisions, err := rrw.ReadRevisions(ctx) + if err != nil { + return nil, fmt.Errorf("reading migration history: %w", err) + } + dirVersions, err := migrationVersionSet(migrationsPath) + if err != nil { + return nil, err + } + report.History = historyDrift(revisions, dirVersions) + + if devConnStr == "" { + return report, nil + } + + applied := make(map[string]bool, len(revisions)) + for _, r := range revisions { + applied[r.Version] = true + } + stagedDir, cleanup, err := stageAppliedDir(migrationsPath, applied) + if err != nil { + return nil, err + } + defer cleanup() + + devApplier, err := NewApplier(engine, devConnStr, live.logger) + if err != nil { + return nil, fmt.Errorf("connecting to dev database: %w", err) + } + defer devApplier.Close() + + // Replay the applied migrations to reconstruct the expected schema. The + // dev database is throwaway, so every migration is allowed regardless of risk. + if err := devApplier.ApplyMigrationDir(ctx, stagedDir, RiskBreaking); err != nil { + return nil, fmt.Errorf("reconstructing expected schema on the dev database: %w", err) + } + + expectedSchema, expectedName, err := inspectManagedSchema(ctx, devApplier) + if err != nil { + return nil, fmt.Errorf("inspecting expected schema: %w", err) + } + actualSchema, _, err := inspectManagedSchema(ctx, live) + if err != nil { + return nil, fmt.Errorf("inspecting live database: %w", err) + } + + drv, err := live.atlasDriver() + if err != nil { + return nil, err + } + // The expected schema was reconstructed on a differently-named dev database + // (MySQL scopes a schema to the database name); align the names so the diff + // reflects only structural differences, not a schema rename. + expectedSchema.Name = actualSchema.Name + // The changes that would turn `expected` into `actual` are the drift: they + // describe how the live database has diverged from what the migrations + // produced. + changes, err := drv.SchemaDiff(expectedSchema, actualSchema) + if err != nil { + return nil, fmt.Errorf("diffing live database against expected state: %w", err) + } + report.Structural = renderStructuralChanges(changes) + report.StructuralTables = changedTables(changes) + + expectedFP, err := devApplier.dialect.FingerprintAdvancedObjects(ctx, devApplier.db, expectedName) + if err != nil { + return nil, fmt.Errorf("fingerprinting expected advanced objects: %w", err) + } + liveName, err := live.dialect.SchemaName(ctx, live.db) + if err != nil { + return nil, err + } + liveFP, err := live.dialect.FingerprintAdvancedObjects(ctx, live.db, liveName) + if err != nil { + return nil, fmt.Errorf("fingerprinting live advanced objects: %w", err) + } + report.Advanced = diffFingerprints(expectedFP, liveFP) + + return report, nil +} + +func inspectManagedSchema(ctx context.Context, a *Applier) (*atlasschema.Schema, string, error) { + drv, err := a.atlasDriver() + if err != nil { + return nil, "", err + } + name, err := a.dialect.SchemaName(ctx, a.db) + if err != nil { + return nil, "", err + } + sch, err := drv.InspectSchema(ctx, name, nil) + return sch, name, err +} + +// Flags revisions applied but no longer present in the directory, and revisions +// applied out of version order. Migration files that are present but not yet +// applied are simply pending rather than drift, so they are not reported. +func historyDrift(revisions []*migrate.Revision, dirVersions map[string]bool) []string { + var lines []string + for _, r := range revisions { + if !dirVersions[r.Version] { + lines = append(lines, fmt.Sprintf( + "migration %s (%s) is recorded as applied but is missing from the migration directory", + r.Version, r.Description)) + } + } + + byExecuted := append([]*migrate.Revision(nil), revisions...) + sort.Slice(byExecuted, func(i, j int) bool { + return byExecuted[i].ExecutedAt.Before(byExecuted[j].ExecutedAt) + }) + maxVersion := "" + for _, r := range byExecuted { + if maxVersion != "" && r.Version < maxVersion { + lines = append(lines, fmt.Sprintf( + "migration %s was applied after a later version (out of order)", r.Version)) + } + if r.Version > maxVersion { + maxVersion = r.Version + } + } + return lines +} + +// The changes are diffed expected → live, so Add* means the object exists in the +// database but not in the migrations, Drop* means it is defined by the +// migrations but missing from the database, and Modify* means it differs. +func renderStructuralChanges(changes []atlasschema.Change) []string { + var lines []string + for _, c := range changes { + lines = append(lines, renderStructuralChange(c)...) + } + return lines +} + +func renderStructuralChange(change atlasschema.Change) []string { + switch c := change.(type) { + case *atlasschema.AddTable: + if isInternalTable(c.T) { + return nil + } + return []string{fmt.Sprintf("table %s exists in the database but not in the migrations", tableName(c.T))} + case *atlasschema.DropTable: + if isInternalTable(c.T) { + return nil + } + return []string{fmt.Sprintf("table %s is defined by the migrations but missing from the database", tableName(c.T))} + case *atlasschema.ModifyTable: + if isInternalTable(c.T) { + return nil + } + var lines []string + for _, sub := range c.Changes { + lines = append(lines, renderTableChange(tableName(c.T), sub)...) + } + return lines + default: + return nil + } +} + +func renderTableChange(table string, change atlasschema.Change) []string { + switch c := change.(type) { + case *atlasschema.AddColumn: + return []string{fmt.Sprintf("table %s: column %s exists in the database but not in the migrations", table, columnName(c.C))} + case *atlasschema.DropColumn: + return []string{fmt.Sprintf("table %s: column %s is defined by the migrations but missing from the database", table, columnName(c.C))} + case *atlasschema.ModifyColumn: + return []string{fmt.Sprintf("table %s: column %s differs from the migrations", table, columnName(c.To))} + case *atlasschema.AddIndex: + return []string{fmt.Sprintf("table %s: index %s exists in the database but not in the migrations", table, indexName(c.I))} + case *atlasschema.DropIndex: + return []string{fmt.Sprintf("table %s: index %s is defined by the migrations but missing from the database", table, indexName(c.I))} + case *atlasschema.AddForeignKey: + return []string{fmt.Sprintf("table %s: a foreign key exists in the database but not in the migrations", table)} + case *atlasschema.DropForeignKey: + return []string{fmt.Sprintf("table %s: a foreign key is defined by the migrations but missing from the database", table)} + case *atlasschema.AddCheck: + return []string{fmt.Sprintf("table %s: a check constraint exists in the database but not in the migrations", table)} + case *atlasschema.DropCheck: + return []string{fmt.Sprintf("table %s: a check constraint is defined by the migrations but missing from the database", table)} + default: + return []string{fmt.Sprintf("table %s: definition differs from the migrations", table)} + } +} + +func isInternalTable(t *atlasschema.Table) bool { + return t != nil && t.Name == revisionsTable +} + +func indexName(i *atlasschema.Index) string { + if i == nil { + return "?" + } + return i.Name +} + +func diffFingerprints(expected, live map[string]string) []string { + var lines []string + for _, key := range sortedKeys(live) { + want, ok := expected[key] + if !ok { + lines = append(lines, fmt.Sprintf("unexpected %s (created out-of-band)", key)) + } else if want != live[key] { + lines = append(lines, fmt.Sprintf("%s has been changed out-of-band", key)) + } + } + for _, key := range sortedKeys(expected) { + if _, ok := live[key]; !ok { + lines = append(lines, fmt.Sprintf("%s is defined by the migrations but missing from the database", key)) + } + } + return lines +} + +// Reads the objects the structural diff does not cover (views, triggers, +// functions and row-level-security policies) from the catalog and returns a map +// of `kind "name"` to a hash of the object's definition. Objects owned by an +// extension are excluded so they do not appear as drift when the extension is +// present on both sides. +func fingerprintPostgresAdvancedObjects(ctx context.Context, db *sql.DB) (map[string]string, error) { + fp := map[string]string{} + + if err := scanFingerprints(ctx, db, fp, "view", + `SELECT table_name, view_definition + FROM information_schema.views + WHERE table_schema = 'public'`); err != nil { + return nil, err + } + + if err := scanFingerprints(ctx, db, fp, "trigger", + `SELECT event_object_table || '.' || trigger_name AS name, + action_timing || ' ' || + string_agg(event_manipulation, ',' ORDER BY event_manipulation) || ' ' || + action_statement AS def + FROM information_schema.triggers + WHERE trigger_schema = 'public' + GROUP BY event_object_table, trigger_name, action_timing, action_statement`); err != nil { + return nil, err + } + + if err := scanFingerprints(ctx, db, fp, "function", + `SELECT p.proname, pg_get_functiondef(p.oid) + FROM pg_proc p + JOIN pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = 'public' + AND NOT EXISTS ( + SELECT 1 FROM pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e' + )`); err != nil { + return nil, err + } + + if err := scanFingerprints(ctx, db, fp, "policy", + `SELECT tablename || '.' || policyname AS name, + cmd || ' ' || COALESCE(qual, '') || ' ' || COALESCE(with_check, '') AS def + FROM pg_policies + WHERE schemaname = 'public'`); err != nil { + return nil, err + } + + return fp, nil +} + +func scanFingerprints(ctx context.Context, db *sql.DB, fp map[string]string, kind, query string) error { + rows, err := db.QueryContext(ctx, query) + if err != nil { + return fmt.Errorf("reading %s definitions: %w", kind, err) + } + defer rows.Close() + + for rows.Next() { + var name, def string + if err := rows.Scan(&name, &def); err != nil { + return fmt.Errorf("scanning %s definition: %w", kind, err) + } + sum := sha256.Sum256([]byte(def)) + fp[fmt.Sprintf("%s %q", kind, name)] = hex.EncodeToString(sum[:]) + } + return rows.Err() +} + +func migrationVersionSet(migrationsPath string) (map[string]bool, error) { + files, err := migrationFileSet(migrationsPath) + if err != nil { + return nil, err + } + versions := map[string]bool{} + for name := range files { + if v := parseVersion(name); v != "" { + versions[v] = true + } + } + return versions, nil +} + +// Copies the migration files whose versions are recorded as applied into a +// temporary Atlas directory, with a fresh atlas.sum, so the planner and executor +// can replay exactly the applied history to reconstruct the expected state. +func stageAppliedDir(migrationsPath string, applied map[string]bool) (string, func(), error) { + tmp, err := os.MkdirTemp("", "celerity-drift-applied-*") + if err != nil { + return "", nil, fmt.Errorf("creating temporary replay directory: %w", err) + } + cleanup := func() { _ = os.RemoveAll(tmp) } + + dir, err := migrate.NewLocalDir(tmp) + if err != nil { + cleanup() + return "", nil, fmt.Errorf("opening temporary replay directory: %w", err) + } + + files, err := migrationFileSet(migrationsPath) + if err != nil { + cleanup() + return "", nil, err + } + for name := range files { + version := parseVersion(name) + if version == "" || !applied[version] { + continue + } + content, err := os.ReadFile(filepath.Join(migrationsPath, name)) + if err != nil { + cleanup() + return "", nil, fmt.Errorf("reading migration %s: %w", name, err) + } + if err := dir.WriteFile(name, content); err != nil { + cleanup() + return "", nil, fmt.Errorf("staging migration %s: %w", name, err) + } + } + if err := writeSumFile(dir); err != nil { + cleanup() + return "", nil, err + } + return tmp, cleanup, nil +} diff --git a/apps/cli/internal/sqlschema/drift_integration_test.go b/apps/cli/internal/sqlschema/drift_integration_test.go new file mode 100644 index 00000000..4fc97b3c --- /dev/null +++ b/apps/cli/internal/sqlschema/drift_integration_test.go @@ -0,0 +1,194 @@ +package sqlschema + +import ( + "context" + "fmt" + "os" + "path/filepath" + "sync/atomic" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/testutils" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +// DriftIntegrationSuite exercises DetectDrift end-to-end against a real Postgres +// server. The primary test database plays the "live" database; each test also +// provisions a throwaway dev database on the same server to reconstruct the +// expected state from the applied migrations. +type DriftIntegrationSuite struct { + suite.Suite + host, port, user, password, database string + primaryConn string + devDatabases []string +} + +var driftDevCounter int64 + +func TestDriftIntegrationSuite(t *testing.T) { + suite.Run(t, new(DriftIntegrationSuite)) +} + +func (s *DriftIntegrationSuite) SetupTest() { + s.host = testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_HOST") + s.port = testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_PORT") + s.user = testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_USER") + s.password = testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_PASSWORD") + s.database = testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_DATABASE") + s.primaryConn = FormatConnectionString(s.host, s.port, s.user, s.password, s.database) + s.reset(s.primaryConn) +} + +func (s *DriftIntegrationSuite) TearDownTest() { + admin, err := NewApplier("postgres", s.primaryConn, zap.NewNop()) + if err != nil { + return + } + defer admin.Close() + for _, name := range s.devDatabases { + _ = admin.ExecSQL(context.Background(), fmt.Sprintf("DROP DATABASE IF EXISTS %s WITH (FORCE)", name)) + } + s.devDatabases = nil +} + +// reset returns the public schema of a database to empty. +func (s *DriftIntegrationSuite) reset(connStr string) { + appl, err := NewApplier("postgres", connStr, zap.NewNop()) + s.Require().NoError(err) + defer appl.Close() + s.Require().NoError(appl.ExecSQL(context.Background(), "DROP SCHEMA public CASCADE")) + s.Require().NoError(appl.ExecSQL(context.Background(), "CREATE SCHEMA public")) + // The migration history lives in its own schema, outside the one the reset + // above clears. + s.Require().NoError(appl.ExecSQL(context.Background(), + fmt.Sprintf("DROP SCHEMA IF EXISTS %q CASCADE", pgRevisionsSchema))) +} + +// freshDevDB creates a clean, uniquely-named database on the same server and +// returns its connection string. +func (s *DriftIntegrationSuite) freshDevDB() string { + name := fmt.Sprintf("celerity_drift_dev_%d", atomic.AddInt64(&driftDevCounter, 1)) + admin, err := NewApplier("postgres", s.primaryConn, zap.NewNop()) + s.Require().NoError(err) + defer admin.Close() + _ = admin.ExecSQL(context.Background(), fmt.Sprintf("DROP DATABASE IF EXISTS %s WITH (FORCE)", name)) + s.Require().NoError(admin.EnsureDatabase(context.Background(), name)) + s.devDatabases = append(s.devDatabases, name) + return FormatConnectionString(s.host, s.port, s.user, s.password, name) +} + +func (s *DriftIntegrationSuite) writeSchemaFile(content string) string { + path := filepath.Join(s.T().TempDir(), "schema.yaml") + s.Require().NoError(os.WriteFile(path, []byte(content), 0o644)) + return path +} + +const driftBaseSchema = ` +tables: + orders: + columns: + id: + type: bigint + primaryKey: true + total_cents: + type: integer + nullable: false +` + +// migrateLive generates a migration for the given schema and applies it to the +// primary (live) database, returning the migrations directory. +func (s *DriftIntegrationSuite) migrateLive(schemaContent string) string { + ctx := context.Background() + migrationsDir := s.T().TempDir() + schemaPath := s.writeSchemaFile(schemaContent) + + // Generate the migration on its own clean dev database. + genDev := s.freshDevDB() + _, err := GenerateMigration(ctx, genDev, schemaPath, migrationsDir, "postgres", "init") + s.Require().NoError(err) + + // Apply it to the live database. + live, err := NewApplier("postgres", s.primaryConn, zap.NewNop()) + s.Require().NoError(err) + defer live.Close() + s.Require().NoError(live.ApplyMigrationDir(ctx, migrationsDir, RiskBreaking)) + return migrationsDir +} + +func (s *DriftIntegrationSuite) detect(migrationsDir, devConn string) *DriftReport { + live, err := NewApplier("postgres", s.primaryConn, zap.NewNop()) + s.Require().NoError(err) + defer live.Close() + report, err := DetectDrift(context.Background(), live, devConn, migrationsDir, "postgres") + s.Require().NoError(err) + return report +} + +func (s *DriftIntegrationSuite) execLive(sqlStmt string) { + live, err := NewApplier("postgres", s.primaryConn, zap.NewNop()) + s.Require().NoError(err) + defer live.Close() + s.Require().NoError(live.ExecSQL(context.Background(), sqlStmt)) +} + +func (s *DriftIntegrationSuite) Test_no_drift_when_live_matches_migrations() { + migrationsDir := s.migrateLive(driftBaseSchema) + + report := s.detect(migrationsDir, s.freshDevDB()) + s.Assert().False(report.HasDrift(), "expected no drift, got: %+v", report) +} + +func (s *DriftIntegrationSuite) Test_structural_drift_out_of_band_column() { + migrationsDir := s.migrateLive(driftBaseSchema) + + // An out-of-band hotfix adds a column no migration defines. + s.execLive("ALTER TABLE orders ADD COLUMN discount_cents integer") + + report := s.detect(migrationsDir, s.freshDevDB()) + s.Require().True(report.HasDrift()) + s.Require().NotEmpty(report.Structural) + joined := "" + for _, l := range report.Structural { + joined += l + "\n" + } + s.Assert().Contains(joined, "discount_cents") + s.Assert().Contains(joined, "exists in the database but not in the migrations") +} + +func (s *DriftIntegrationSuite) Test_advanced_drift_out_of_band_view() { + migrationsDir := s.migrateLive(driftBaseSchema) + + // An out-of-band view is an advanced object the structural diff does not cover. + s.execLive("CREATE VIEW big_orders AS SELECT id FROM orders WHERE total_cents > 10000") + + report := s.detect(migrationsDir, s.freshDevDB()) + s.Require().True(report.HasDrift()) + s.Require().NotEmpty(report.Advanced) + joined := "" + for _, l := range report.Advanced { + joined += l + "\n" + } + s.Assert().Contains(joined, "big_orders") + s.Assert().Contains(joined, "created out-of-band") +} + +func (s *DriftIntegrationSuite) Test_history_drift_when_applied_file_removed() { + migrationsDir := s.migrateLive(driftBaseSchema) + + // Remove the applied migration file from the directory to simulate a history + // that no longer matches the recorded revisions. + entries, err := os.ReadDir(migrationsDir) + s.Require().NoError(err) + for _, e := range entries { + if filepath.Ext(e.Name()) == ".sql" { + s.Require().NoError(os.Remove(filepath.Join(migrationsDir, e.Name()))) + } + } + + // History drift needs no dev database. + report := s.detect(migrationsDir, "") + s.Require().True(report.HasDrift()) + s.Require().NotEmpty(report.History) + s.Assert().Contains(report.History[0], "missing from the migration directory") +} diff --git a/apps/cli/internal/sqlschema/drift_test.go b/apps/cli/internal/sqlschema/drift_test.go new file mode 100644 index 00000000..01651a09 --- /dev/null +++ b/apps/cli/internal/sqlschema/drift_test.go @@ -0,0 +1,132 @@ +package sqlschema + +import ( + "testing" + "time" + + "ariga.io/atlas/sql/migrate" + atlasschema "ariga.io/atlas/sql/schema" + "github.com/stretchr/testify/suite" +) + +type DriftUnitSuite struct { + suite.Suite +} + +func TestDriftUnitSuite(t *testing.T) { + suite.Run(t, new(DriftUnitSuite)) +} + +func rev(version, desc string, executedAt time.Time) *migrate.Revision { + return &migrate.Revision{Version: version, Description: desc, ExecutedAt: executedAt} +} + +func (s *DriftUnitSuite) Test_history_drift_clean() { + base := time.Date(2026, 7, 21, 10, 0, 0, 0, time.UTC) + revisions := []*migrate.Revision{ + rev("20260721100000", "init", base), + rev("20260721100100", "add_tier", base.Add(time.Minute)), + } + dir := map[string]bool{"20260721100000": true, "20260721100100": true} + + s.Assert().Empty(historyDrift(revisions, dir)) +} + +func (s *DriftUnitSuite) Test_history_drift_applied_but_missing_from_dir() { + base := time.Date(2026, 7, 21, 10, 0, 0, 0, time.UTC) + revisions := []*migrate.Revision{ + rev("20260721100000", "init", base), + rev("20260721100100", "hotfix", base.Add(time.Minute)), + } + // The hotfix migration is recorded as applied but absent from the directory. + dir := map[string]bool{"20260721100000": true} + + lines := historyDrift(revisions, dir) + s.Require().Len(lines, 1) + s.Assert().Contains(lines[0], "20260721100100") + s.Assert().Contains(lines[0], "missing from the migration directory") +} + +func (s *DriftUnitSuite) Test_history_drift_out_of_order() { + base := time.Date(2026, 7, 21, 10, 0, 0, 0, time.UTC) + // The later version was applied before the earlier version. + revisions := []*migrate.Revision{ + rev("20260721100000", "init", base.Add(time.Minute)), + rev("20260721100100", "add_tier", base), + } + dir := map[string]bool{"20260721100000": true, "20260721100100": true} + + lines := historyDrift(revisions, dir) + s.Require().Len(lines, 1) + s.Assert().Contains(lines[0], "out of order") +} + +func (s *DriftUnitSuite) Test_pending_migration_is_not_history_drift() { + base := time.Date(2026, 7, 21, 10, 0, 0, 0, time.UTC) + revisions := []*migrate.Revision{rev("20260721100000", "init", base)} + // A second migration exists in the directory but has not been applied yet. + dir := map[string]bool{"20260721100000": true, "20260721100100": true} + + s.Assert().Empty(historyDrift(revisions, dir)) +} + +func (s *DriftUnitSuite) Test_render_structural_added_column() { + change := &atlasschema.ModifyTable{ + T: atlasschema.NewTable("orders"), + Changes: []atlasschema.Change{ + &atlasschema.AddColumn{C: atlasschema.NewColumn("discount_cents")}, + }, + } + lines := renderStructuralChanges([]atlasschema.Change{change}) + s.Require().Len(lines, 1) + s.Assert().Contains(lines[0], "orders") + s.Assert().Contains(lines[0], "discount_cents") + s.Assert().Contains(lines[0], "exists in the database but not in the migrations") +} + +func (s *DriftUnitSuite) Test_render_structural_added_table() { + change := &atlasschema.AddTable{T: atlasschema.NewTable("audit_log")} + lines := renderStructuralChanges([]atlasschema.Change{change}) + s.Require().Len(lines, 1) + s.Assert().Contains(lines[0], "audit_log") +} + +func (s *DriftUnitSuite) Test_render_structural_ignores_revision_table() { + change := &atlasschema.AddTable{T: atlasschema.NewTable(revisionsTable)} + s.Assert().Empty(renderStructuralChanges([]atlasschema.Change{change})) +} + +func (s *DriftUnitSuite) Test_diff_fingerprints() { + expected := map[string]string{ + `view "orders_summary"`: "aaa", + `trigger "orders.audit"`: "bbb", + } + live := map[string]string{ + `view "orders_summary"`: "ccc", // changed + `function "compute_total"`: "ddd", // unexpected + // trigger orders.audit missing + } + + lines := diffFingerprints(expected, live) + s.Require().Len(lines, 3) + joined := "" + for _, l := range lines { + joined += l + "\n" + } + s.Assert().Contains(joined, `function "compute_total"`) + s.Assert().Contains(joined, "created out-of-band") + s.Assert().Contains(joined, "has been changed out-of-band") + s.Assert().Contains(joined, "missing from the database") +} + +func (s *DriftUnitSuite) Test_report_has_drift_and_render() { + report := &DriftReport{ + Resource: "ordersDb", + Target: "postgres: orders", + Structural: []string{"table orders: column discount_cents exists in the database but not in the migrations"}, + } + s.Assert().True(report.HasDrift()) + + empty := &DriftReport{Resource: "ordersDb", Target: "postgres: orders"} + s.Assert().False(empty.HasDrift()) +} diff --git a/apps/cli/internal/sqlschema/exclude.go b/apps/cli/internal/sqlschema/exclude.go new file mode 100644 index 00000000..1448b036 --- /dev/null +++ b/apps/cli/internal/sqlschema/exclude.go @@ -0,0 +1,38 @@ +package sqlschema + +import ( + "fmt" + + atlasschema "ariga.io/atlas/sql/schema" +) + +// excludePatterns returns the patterns that YAML-driven diffs must ignore: the +// schema's own `exclude` list plus the migration-history table, which Celerity +// owns and no schema YAML models. +// +// Patterns are Atlas globs relative to the managed schema, such as "legacy_*" +// for a table or "audit_log.idx_*" for objects within one. An optional type +// selector narrows which kind of object matches, as in +// "audit_log.idx_audit_fts[type=index]". See +// ariga.io/atlas/sql/schema.ExcludeSchema for the full syntax. +func excludePatterns(s *Schema) []string { + patterns := make([]string, 0, len(s.Exclude)+1) + patterns = append(patterns, s.Exclude...) + // Databases migrated before the history table moved to its own schema still + // carry it in the managed schema; without this the declarative diff would + // drop it and wipe the migration history. + return append(patterns, revisionsTable) +} + +// A typo in a pattern silently matches nothing, so every pattern is parsed here +// to make it surface from `schema validate` instead. +func validateExcludePatterns(patterns []string) error { + for _, p := range patterns { + probe := atlasschema.New(defaultSchemaName) + atlasschema.NewRealm(probe) + if _, err := atlasschema.ExcludeSchema(probe, []string{p}); err != nil { + return fmt.Errorf("invalid exclude pattern %q: %w", p, err) + } + } + return nil +} diff --git a/apps/cli/internal/sqlschema/exclude_test.go b/apps/cli/internal/sqlschema/exclude_test.go new file mode 100644 index 00000000..1bd93eb1 --- /dev/null +++ b/apps/cli/internal/sqlschema/exclude_test.go @@ -0,0 +1,45 @@ +package sqlschema + +import ( + "testing" + + "github.com/stretchr/testify/suite" +) + +type ExcludeTestSuite struct { + suite.Suite +} + +func TestExcludeTestSuite(t *testing.T) { + suite.Run(t, new(ExcludeTestSuite)) +} + +func (s *ExcludeTestSuite) Test_history_table_is_always_excluded() { + patterns := excludePatterns(&Schema{}) + s.Assert().Contains(patterns, revisionsTable, + "the migration-history table must never be visible to a YAML-driven diff") +} + +func (s *ExcludeTestSuite) Test_declared_patterns_are_kept() { + patterns := excludePatterns(&Schema{ + Exclude: []string{"audit_log.idx_audit_fts[type=index]", "legacy_*"}, + }) + s.Assert().Contains(patterns, "audit_log.idx_audit_fts[type=index]") + s.Assert().Contains(patterns, "legacy_*") +} + +func (s *ExcludeTestSuite) Test_valid_patterns_accepted() { + err := validateExcludePatterns([]string{ + "legacy_events", + "legacy_*", + "audit_log.idx_audit_fts[type=index]", + "audit_log.tmp_*[type=column]", + }) + s.Assert().NoError(err) +} + +func (s *ExcludeTestSuite) Test_unparsable_pattern_rejected() { + err := validateExcludePatterns([]string{"audit_log.a.b.c.d"}) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "invalid exclude pattern") +} diff --git a/apps/cli/internal/sqlschema/export.go b/apps/cli/internal/sqlschema/export.go new file mode 100644 index 00000000..af736c34 --- /dev/null +++ b/apps/cli/internal/sqlschema/export.go @@ -0,0 +1,282 @@ +package sqlschema + +import ( + "encoding/json" + "fmt" + "strings" +) + +// ExportFormat is an output format for `schema export`. +type ExportFormat string + +const ( + ExportSQL ExportFormat = "sql" + ExportMarkdown ExportFormat = "markdown" + ExportJSONSchema ExportFormat = "json-schema" + ExportMermaid ExportFormat = "mermaid" +) + +// ExportSchema renders a parsed schema in the given format for data-team +// consumption. resourceName is used in headers/titles. The export is derived +// purely from the schema YAML, so it needs no database connection. +func ExportSchema(s *Schema, format ExportFormat, resourceName string) (string, error) { + switch format { + case ExportSQL: + return exportSQL(s), nil + case ExportMarkdown: + return exportMarkdown(s, resourceName), nil + case ExportJSONSchema: + return exportJSONSchema(s, resourceName) + case ExportMermaid: + return exportMermaid(s), nil + default: + return "", fmt.Errorf("unsupported export format %q (supported: sql, markdown, json-schema, mermaid)", format) + } +} + +func exportSQL(s *Schema) string { + var b strings.Builder + b.WriteString("-- Exported by `celerity schema export --format sql`\n") + + for _, ext := range s.Extensions { + fmt.Fprintf(&b, "CREATE EXTENSION IF NOT EXISTS %q;\n", ext) + } + if len(s.Extensions) > 0 { + b.WriteString("\n") + } + + for _, name := range sortedKeys(s.Tables) { + table := s.Tables[name] + fmt.Fprintf(&b, "CREATE TABLE %s (\n", name) + + var lines []string + for _, colName := range orderedColumns(table) { + lines = append(lines, " "+columnDDL(colName, table.Columns[colName])) + } + if pk := primaryKeyColumns(table); len(pk) > 0 { + lines = append(lines, fmt.Sprintf(" PRIMARY KEY (%s)", strings.Join(pk, ", "))) + } + for _, colName := range orderedColumns(table) { + col := table.Columns[colName] + if col.References != nil { + lines = append(lines, fmt.Sprintf( + " FOREIGN KEY (%s) REFERENCES %s (%s)%s", + colName, col.References.Table, col.References.Column, onDeleteClause(col.References.OnDelete))) + } + } + for _, c := range table.Constraints { + if c.Type == "check" && c.Expression != "" { + lines = append(lines, fmt.Sprintf(" CONSTRAINT %s CHECK (%s)", c.Name, c.Expression)) + } + } + b.WriteString(strings.Join(lines, ",\n")) + b.WriteString("\n);\n") + + for _, idx := range table.Indexes { + unique := "" + if idx.Unique { + unique = "UNIQUE " + } + fmt.Fprintf(&b, "CREATE %sINDEX %s ON %s (%s);\n", + unique, idx.Name, name, strings.Join(idx.Columns, ", ")) + } + b.WriteString("\n") + } + + return strings.TrimRight(b.String(), "\n") + "\n" +} + +func columnDDL(name string, col Column) string { + parts := []string{name, col.Type} + if !col.Nullable || col.PrimaryKey { + parts = append(parts, "NOT NULL") + } + if col.Unique { + parts = append(parts, "UNIQUE") + } + if col.Default != "" { + parts = append(parts, "DEFAULT "+col.Default) + } + return strings.Join(parts, " ") +} + +func onDeleteClause(onDelete string) string { + if onDelete == "" { + return "" + } + return " ON DELETE " + strings.ToUpper(onDelete) +} + +func primaryKeyColumns(t Table) []string { + var pk []string + for _, name := range orderedColumns(t) { + if t.Columns[name].PrimaryKey { + pk = append(pk, name) + } + } + return pk +} + +func exportMarkdown(s *Schema, resourceName string) string { + var b strings.Builder + fmt.Fprintf(&b, "# %s schema\n", resourceName) + + for _, name := range sortedKeys(s.Tables) { + table := s.Tables[name] + fmt.Fprintf(&b, "\n## %s\n", name) + if table.Description != "" { + fmt.Fprintf(&b, "\n%s\n", table.Description) + } + if len(table.Tags) > 0 { + fmt.Fprintf(&b, "\nTags: %s\n", strings.Join(table.Tags, ", ")) + } + b.WriteString("\n| Column | Type | Nullable | Key | Classification | Tags | Description |\n") + b.WriteString("|---|---|---|---|---|---|---|\n") + for _, colName := range orderedColumns(table) { + col := table.Columns[colName] + nullable := "no" + if col.Nullable && !col.PrimaryKey { + nullable = "yes" + } + key := "" + switch { + case col.PrimaryKey: + key = "PK" + case col.References != nil: + key = fmt.Sprintf("FK → %s.%s", col.References.Table, col.References.Column) + case col.Unique: + key = "unique" + } + fmt.Fprintf(&b, "| %s | %s | %s | %s | %s | %s | %s |\n", + colName, col.Type, nullable, key, col.Classification, strings.Join(col.Tags, ", "), col.Description) + } + + if len(table.Indexes) > 0 { + b.WriteString("\nIndexes:\n") + for _, idx := range table.Indexes { + unique := "" + if idx.Unique { + unique = " (unique)" + } + fmt.Fprintf(&b, "- `%s`%s on (%s)\n", idx.Name, unique, strings.Join(idx.Columns, ", ")) + } + } + } + + return b.String() +} + +// A minimal JSON Schema document with one object definition per table. +type jsonSchemaDoc struct { + Schema string `json:"$schema"` + Title string `json:"title"` + Definitions map[string]jsonSchemaType `json:"definitions"` +} + +type jsonSchemaType struct { + Type string `json:"type"` + Description string `json:"description,omitempty"` + Properties map[string]jsonSchemaProp `json:"properties"` + Required []string `json:"required,omitempty"` + AdditionalProperties bool `json:"additionalProperties"` +} + +type jsonSchemaProp struct { + Type []string `json:"type"` + Description string `json:"description,omitempty"` +} + +func exportJSONSchema(s *Schema, resourceName string) (string, error) { + doc := jsonSchemaDoc{ + Schema: "http://json-schema.org/draft-07/schema#", + Title: resourceName, + Definitions: map[string]jsonSchemaType{}, + } + + for _, name := range sortedKeys(s.Tables) { + table := s.Tables[name] + def := jsonSchemaType{ + Type: "object", + Description: table.Description, + Properties: map[string]jsonSchemaProp{}, + AdditionalProperties: false, + } + for _, colName := range orderedColumns(table) { + col := table.Columns[colName] + jsonType := jsonSchemaColumnType(col.Type) + types := []string{jsonType} + if col.Nullable && !col.PrimaryKey { + types = append(types, "null") + } else { + def.Required = append(def.Required, colName) + } + def.Properties[colName] = jsonSchemaProp{Type: types, Description: col.Description} + } + doc.Definitions[name] = def + } + + out, err := json.MarshalIndent(doc, "", " ") + if err != nil { + return "", fmt.Errorf("encoding json schema: %w", err) + } + return string(out) + "\n", nil +} + +func jsonSchemaColumnType(sqlType string) string { + switch baseSQLType(sqlType) { + case "smallint", "int2", "integer", "int", "int4", "serial", "serial4", + "bigint", "int8", "bigserial", "serial8": + return "integer" + case "numeric", "decimal", "real", "float4", "double precision", "float8", "money": + return "number" + case "boolean", "bool": + return "boolean" + case "json", "jsonb": + return "object" + default: + return "string" + } +} + +func exportMermaid(s *Schema) string { + var b strings.Builder + b.WriteString("erDiagram\n") + + for _, name := range sortedKeys(s.Tables) { + table := s.Tables[name] + fmt.Fprintf(&b, " %s {\n", name) + for _, colName := range orderedColumns(table) { + col := table.Columns[colName] + key := "" + switch { + case col.PrimaryKey: + key = "PK" + case col.References != nil: + key = "FK" + } + // Mermaid identifiers cannot contain parentheses; use the base type. + line := fmt.Sprintf(" %s %s", mermaidType(col.Type), colName) + if key != "" { + line += " " + key + } + b.WriteString(line + "\n") + } + b.WriteString(" }\n") + } + + for _, name := range sortedKeys(s.Tables) { + for _, colName := range orderedColumns(s.Tables[name]) { + col := s.Tables[name].Columns[colName] + if col.References != nil { + fmt.Fprintf(&b, " %s ||--o{ %s : %q\n", col.References.Table, name, colName) + } + } + } + + return b.String() +} + +func mermaidType(sqlType string) string { + base := baseSQLType(sqlType) + return strings.ReplaceAll(base, " ", "_") +} diff --git a/apps/cli/internal/sqlschema/export_test.go b/apps/cli/internal/sqlschema/export_test.go new file mode 100644 index 00000000..50f6cb69 --- /dev/null +++ b/apps/cli/internal/sqlschema/export_test.go @@ -0,0 +1,115 @@ +package sqlschema + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/suite" +) + +type ExportSuite struct { + suite.Suite +} + +func TestExportSuite(t *testing.T) { + suite.Run(t, new(ExportSuite)) +} + +func exportSample() *Schema { + return &Schema{ + Extensions: []string{"uuid-ossp"}, + Tables: map[string]Table{ + "customers": { + Tags: []string{"core-entity"}, + Columns: map[string]Column{ + "id": {Type: "bigint", PrimaryKey: true}, + "email": {Type: "varchar(255)", Unique: true}, + "note": {Type: "text", Nullable: true, Description: "free text", Classification: "internal", Tags: []string{"freeform"}}, + }, + }, + "orders": { + Description: "customer orders", + Columns: map[string]Column{ + "id": {Type: "bigint", PrimaryKey: true}, + "customer_id": { + Type: "bigint", + References: &ForeignKey{Table: "customers", Column: "id", OnDelete: "cascade"}, + }, + }, + Indexes: []Index{{Name: "idx_orders_customer", Columns: []string{"customer_id"}}}, + }, + }, + } +} + +func (s *ExportSuite) Test_sql_ddl() { + out, err := ExportSchema(exportSample(), ExportSQL, "ordersDb") + s.Require().NoError(err) + s.Assert().Contains(out, `CREATE EXTENSION IF NOT EXISTS "uuid-ossp";`) + s.Assert().Contains(out, "CREATE TABLE customers (") + s.Assert().Contains(out, "email varchar(255) NOT NULL UNIQUE") + s.Assert().Contains(out, "note text") + s.Assert().Contains(out, "PRIMARY KEY (id)") + s.Assert().Contains(out, "FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE CASCADE") + s.Assert().Contains(out, "CREATE INDEX idx_orders_customer ON orders (customer_id);") +} + +func (s *ExportSuite) Test_markdown() { + out, err := ExportSchema(exportSample(), ExportMarkdown, "ordersDb") + s.Require().NoError(err) + s.Assert().Contains(out, "# ordersDb schema") + s.Assert().Contains(out, "## customers") + s.Assert().Contains(out, "| Column | Type | Nullable | Key | Classification | Tags | Description |") + s.Assert().Contains(out, "| id | bigint | no | PK |") + s.Assert().Contains(out, "internal") + s.Assert().Contains(out, "FK → customers.id") + s.Assert().Contains(out, "customer orders") + // Table-level and column-level tags are surfaced. + s.Assert().Contains(out, "Tags: core-entity") + s.Assert().Contains(out, "freeform") +} + +func (s *ExportSuite) Test_json_schema_is_valid_and_structured() { + out, err := ExportSchema(exportSample(), ExportJSONSchema, "ordersDb") + s.Require().NoError(err) + + var doc map[string]any + s.Require().NoError(json.Unmarshal([]byte(out), &doc)) + s.Assert().Equal("ordersDb", doc["title"]) + + defs, ok := doc["definitions"].(map[string]any) + s.Require().True(ok) + customers, ok := defs["customers"].(map[string]any) + s.Require().True(ok) + s.Assert().Equal("object", customers["type"]) + + props := customers["properties"].(map[string]any) + // Nullable column carries a ["string","null"] type union. + note := props["note"].(map[string]any) + noteTypes := note["type"].([]any) + s.Assert().Contains(noteTypes, "null") + + // Non-nullable PK is required. + required := customers["required"].([]any) + s.Assert().Contains(required, "id") + s.Assert().NotContains(required, "note") +} + +func (s *ExportSuite) Test_mermaid_erd() { + out, err := ExportSchema(exportSample(), ExportMermaid, "ordersDb") + s.Require().NoError(err) + s.Assert().Contains(out, "erDiagram") + s.Assert().Contains(out, "customers {") + s.Assert().Contains(out, "bigint id PK") + // varchar(255) must not leak parentheses into a Mermaid identifier. + s.Assert().Contains(out, "varchar email") + s.Assert().NotContains(out, "varchar(255)") + // Relationship from the foreign key. + s.Assert().Contains(out, `customers ||--o{ orders : "customer_id"`) +} + +func (s *ExportSuite) Test_unsupported_format() { + _, err := ExportSchema(exportSample(), ExportFormat("xml"), "ordersDb") + s.Require().Error(err) + s.Assert().Contains(err.Error(), "unsupported export format") +} diff --git a/apps/cli/internal/sqlschema/inspect.go b/apps/cli/internal/sqlschema/inspect.go new file mode 100644 index 00000000..dc9fbc54 --- /dev/null +++ b/apps/cli/internal/sqlschema/inspect.go @@ -0,0 +1,156 @@ +package sqlschema + +import ( + "context" + "fmt" + "io" + "strings" + "time" + + atlasschema "ariga.io/atlas/sql/schema" +) + +// MigrationRecord is a single applied migration read from the revision history. +type MigrationRecord struct { + Version string + Description string + AppliedAt time.Time + ExecutionTime time.Duration + Failed bool + Error string +} + +// ReadMigrationHistory returns the applied-migration history recorded in the +// database's atlas_schema_revisions table, ordered by version. +func ReadMigrationHistory(ctx context.Context, a *Applier) ([]MigrationRecord, error) { + rrw, err := a.dialect.NewRevisions(ctx, a.db) + if err != nil { + return nil, err + } + revisions, err := rrw.ReadRevisions(ctx) + if err != nil { + return nil, fmt.Errorf("reading migration history: %w", err) + } + + records := make([]MigrationRecord, 0, len(revisions)) + for _, r := range revisions { + records = append(records, MigrationRecord{ + Version: r.Version, + Description: r.Description, + AppliedAt: r.ExecutedAt, + ExecutionTime: r.ExecutionTime, + Failed: r.Error != "", + Error: r.Error, + }) + } + return records, nil +} + +// RenderMigrationHistory writes a human-readable migration history table. +func RenderMigrationHistory(w io.Writer, records []MigrationRecord) { + if len(records) == 0 { + fmt.Fprintln(w, "No migrations have been applied.") + return + } + for _, r := range records { + status := "ok" + if r.Failed { + status = "FAILED" + } + fmt.Fprintf(w, "%s %-40s applied %s (%s) [%s]\n", + r.Version, truncate(r.Description, 40), r.AppliedAt.UTC().Format(time.RFC3339), + r.ExecutionTime.Round(time.Millisecond), status) + if r.Failed { + fmt.Fprintf(w, " error: %s\n", r.Error) + } + } +} + +// InspectCurrentSchema reads the live database's public schema and renders it as +// a readable summary of the current deployed state. +func InspectCurrentSchema(ctx context.Context, a *Applier) (string, error) { + drv, err := a.atlasDriver() + if err != nil { + return "", err + } + name, err := a.dialect.SchemaName(ctx, a.db) + if err != nil { + return "", err + } + sch, err := drv.InspectSchema(ctx, name, nil) + if err != nil { + return "", fmt.Errorf("inspecting current schema: %w", err) + } + return renderInspectedSchema(sch), nil +} + +func renderInspectedSchema(sch *atlasschema.Schema) string { + var b strings.Builder + fmt.Fprintf(&b, "schema %q (current deployed state):\n", sch.Name) + + for _, table := range sch.Tables { + // Celerity's own revision-history table is not part of the schema the + // author describes, so it is left out of the summary. + if table.Name == revisionsTable { + continue + } + fmt.Fprintf(&b, "\n %s\n", table.Name) + pk := primaryKeySet(table) + for _, col := range table.Columns { + null := "NOT NULL" + if col.Type != nil && col.Type.Null { + null = "NULL" + } + marker := "" + if pk[col.Name] { + marker = " PK" + } + fmt.Fprintf(&b, " %-24s %-20s %s%s\n", col.Name, columnRawType(col), null, marker) + } + for _, fk := range table.ForeignKeys { + fmt.Fprintf(&b, " → FK %s references %s\n", fkColumnNames(fk), fkRefTableName(fk)) + } + } + return b.String() +} + +func primaryKeySet(t *atlasschema.Table) map[string]bool { + set := map[string]bool{} + if t.PrimaryKey != nil { + for _, part := range t.PrimaryKey.Parts { + if part.C != nil { + set[part.C.Name] = true + } + } + } + return set +} + +func columnRawType(c *atlasschema.Column) string { + if c.Type == nil || c.Type.Raw == "" { + return "?" + } + return c.Type.Raw +} + +func fkColumnNames(fk *atlasschema.ForeignKey) string { + names := make([]string, 0, len(fk.Columns)) + for _, c := range fk.Columns { + names = append(names, c.Name) + } + return strings.Join(names, ", ") +} + +func fkRefTableName(fk *atlasschema.ForeignKey) string { + if fk.RefTable == nil { + return "?" + } + return fk.RefTable.Name +} + +func truncate(s string, max int) string { + if len(s) <= max { + return s + } + return s[:max-1] + "…" +} diff --git a/apps/cli/internal/sqlschema/migrationdir.go b/apps/cli/internal/sqlschema/migrationdir.go new file mode 100644 index 00000000..3adc3d02 --- /dev/null +++ b/apps/cli/internal/sqlschema/migrationdir.go @@ -0,0 +1,506 @@ +package sqlschema + +import ( + "context" + "database/sql" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + "ariga.io/atlas/sql/migrate" + atlasschema "ariga.io/atlas/sql/schema" +) + +var nonSlugChars = regexp.MustCompile(`[^a-z0-9]+`) + +// ScaffoldMigration creates an empty, timestamped migration file for +// hand-written SQL and updates the atlas.sum integrity file. It returns the path +// of the created file. +func ScaffoldMigration(migrationsPath, description string) (string, error) { + dir, err := openOrCreateDir(migrationsPath) + if err != nil { + return "", err + } + + version, err := nextAvailableVersion(migrationsPath, time.Now()) + if err != nil { + return "", err + } + name := migrationFileName(version, description) + body := fmt.Sprintf( + "%s-- %s\n-- Hand-written migration. Add your SQL statements below.\n"+ + "-- Downgrade the risk above to `safe` only if this migration is additive/backward-compatible.\n", + riskHeader(RiskRisky, "hand-written"), description) + if err := dir.WriteFile(name, []byte(body)); err != nil { + return "", fmt.Errorf("writing migration file: %w", err) + } + if err := writeSumFile(dir); err != nil { + return "", err + } + return filepath.Join(migrationsPath, name), nil +} + +// GenerateMigration computes the difference between the schema YAML (desired +// state) and the current state, which it obtains by replaying the existing +// migration directory on the dev database at devConnStr. The difference is +// written as a new timestamped migration file and atlas.sum is updated. It +// returns the path of the created file, or "" if there is no difference. +// +// The dev database must be empty; the planner replays the migration directory +// into it to compute the current state. +func GenerateMigration(ctx context.Context, devConnStr, schemaPath, migrationsPath, engine, name string) (string, error) { + parsed, err := ParseSchemaFile(schemaPath) + if err != nil { + return "", fmt.Errorf("parsing schema: %w", err) + } + desired, err := desiredSchema(parsed, engine) + if err != nil { + return "", fmt.Errorf("building desired schema: %w", err) + } + + firstMigration, err := isEmptyMigrationDir(migrationsPath) + if err != nil { + return "", err + } + + dir, err := openOrCreateDir(migrationsPath) + if err != nil { + return "", err + } + + drv, devSchema, closeDev, err := openDevDriver(ctx, engine, devConnStr) + if err != nil { + return "", err + } + defer closeDev() + desired.Name = devSchema + + planName := slugify(name) + if planName == "" { + planName = "changes" + } + + before, err := migrationFileSet(migrationsPath) + if err != nil { + return "", err + } + + planner := migrate.NewPlanner(drv, dir, + migrate.PlanWithSchemaQualifier(""), + // Objects the YAML does not model are filtered out of the replayed + // state, so a hand-written index or trigger is never planned for + // removal just because the schema YAML has no way to describe it. + migrate.PlanWithExclude(excludePatterns(parsed)...), + ) + plan, err := planner.PlanSchema(ctx, planName, migrate.Schema(desired)) + if errors.Is(err, migrate.ErrNoPlan) { + return "", nil + } + if err != nil { + return "", fmt.Errorf("planning migration: %w", err) + } + + // Emit CREATE EXTENSION for declared extensions on the initial migration. + // Guarded with IF NOT EXISTS so a hand-edited history stays safe. + if firstMigration { + var extChanges []*migrate.Change + for _, ext := range parsed.Extensions { + extChanges = append(extChanges, &migrate.Change{ + Cmd: fmt.Sprintf("CREATE EXTENSION IF NOT EXISTS %q", ext), + Comment: fmt.Sprintf("enable extension %q", ext), + }) + } + plan.Changes = append(extChanges, plan.Changes...) + } + + // Classify the change set so the migration carries a risk header for the + // apply-time safety gate. Prepended extension changes have a nil Source. + var sources []atlasschema.Change + for _, change := range plan.Changes { + if change.Source != nil { + sources = append(sources, change.Source) + } + } + riskLevel, riskReason := classifyChanges(sources) + + if err := planner.WritePlan(plan); err != nil { + return "", fmt.Errorf("writing migration: %w", err) + } + + // WritePlan names the file itself (version generated at write time), so + // locate the newly written migration by diffing the directory listing. + newFile := "" + after, err := migrationFileSet(migrationsPath) + if err != nil { + return "", err + } + for name := range after { + if !before[name] { + newFile = name + break + } + } + if newFile == "" { + return "", fmt.Errorf("migration planned but no new file was written") + } + + // Atlas versions to the second; if the new migration collides with an + // existing one (e.g. `schema new` then `schema diff` in the same second), + // rename it to a later version so the history stays ordered and unique. + newFile, err = ensureUniqueVersion(migrationsPath, newFile, before) + if err != nil { + return "", err + } + + newPath := filepath.Join(migrationsPath, newFile) + if err := prependLine(newPath, riskHeader(riskLevel, riskReason)); err != nil { + return "", err + } + if err := writeSumFile(dir); err != nil { + return "", err + } + return newPath, nil +} + +func prependLine(path, line string) error { + content, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("reading migration file: %w", err) + } + if err := os.WriteFile(path, append([]byte(line), content...), 0o644); err != nil { + return fmt.Errorf("writing migration file: %w", err) + } + return nil +} + +// ReadMigrationRisk returns the risk classification recorded in a migration +// file's header (falling back to risky when absent). +func ReadMigrationRisk(path string) (RiskLevel, error) { + content, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("reading migration file: %w", err) + } + return migrationRisk(content), nil +} + +func ensureUniqueVersion(migrationsPath, fileName string, existing map[string]bool) (string, error) { + version := parseVersion(fileName) + prevMax := maxVersion(existing) + if version == "" || version > prevMax { + return fileName, nil + } + + newName := bumpVersion(prevMax) + fileName[len(version):] + if err := os.Rename( + filepath.Join(migrationsPath, fileName), + filepath.Join(migrationsPath, newName), + ); err != nil { + return "", fmt.Errorf("renaming migration to a unique version: %w", err) + } + return newName, nil +} + +func migrationFileSet(migrationsPath string) (map[string]bool, error) { + set := map[string]bool{} + entries, err := os.ReadDir(migrationsPath) + if err != nil { + if os.IsNotExist(err) { + return set, nil + } + return nil, fmt.Errorf("reading migrations directory %s: %w", migrationsPath, err) + } + for _, e := range entries { + if !e.IsDir() && strings.HasSuffix(e.Name(), ".sql") { + set[e.Name()] = true + } + } + return set, nil +} + +// CheckPendingMigration reports whether the schema YAML has changes that are not +// yet captured by a committed migration, which is to say whether +// `celerity schema diff` would generate a new migration. It computes the diff +// against the dev database +// (replaying the existing migration directory) but writes nothing. Used by +// `schema diff --check` as a CI completeness gate. +func CheckPendingMigration(ctx context.Context, devConnStr, schemaPath, migrationsPath, engine string) (bool, error) { + parsed, err := ParseSchemaFile(schemaPath) + if err != nil { + return false, fmt.Errorf("parsing schema: %w", err) + } + desired, err := desiredSchema(parsed, engine) + if err != nil { + return false, fmt.Errorf("building desired schema: %w", err) + } + + path, cleanup, err := replayDir(migrationsPath) + if err != nil { + return false, err + } + defer cleanup() + dir, err := migrate.NewLocalDir(path) + if err != nil { + return false, fmt.Errorf("opening migrations directory: %w", err) + } + + drv, devSchema, closeDev, err := openDevDriver(ctx, engine, devConnStr) + if err != nil { + return false, err + } + defer closeDev() + desired.Name = devSchema + + plan, err := migrate.NewPlanner(drv, dir, + migrate.PlanWithSchemaQualifier(""), + migrate.PlanWithExclude(excludePatterns(parsed)...), + ).PlanSchema(ctx, "check", migrate.Schema(desired)) + if errors.Is(err, migrate.ErrNoPlan) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("checking for pending schema changes: %w", err) + } + return len(plan.Changes) > 0, nil +} + +// ChangedTables returns the tables the pending schema change would touch, those +// added, dropped or modified by the migration `schema diff` would generate. It +// computes the diff against the dev database (replaying the existing migration +// directory) but writes nothing. Used to evaluate schema contracts. +func ChangedTables(ctx context.Context, devConnStr, schemaPath, migrationsPath, engine string) ([]string, error) { + parsed, err := ParseSchemaFile(schemaPath) + if err != nil { + return nil, fmt.Errorf("parsing schema: %w", err) + } + desired, err := desiredSchema(parsed, engine) + if err != nil { + return nil, fmt.Errorf("building desired schema: %w", err) + } + + path, cleanup, err := replayDir(migrationsPath) + if err != nil { + return nil, err + } + defer cleanup() + dir, err := migrate.NewLocalDir(path) + if err != nil { + return nil, fmt.Errorf("opening migrations directory: %w", err) + } + + drv, devSchema, closeDev, err := openDevDriver(ctx, engine, devConnStr) + if err != nil { + return nil, err + } + defer closeDev() + desired.Name = devSchema + + plan, err := migrate.NewPlanner(drv, dir, migrate.PlanWithSchemaQualifier("")).PlanSchema(ctx, "contracts", migrate.Schema(desired)) + if errors.Is(err, migrate.ErrNoPlan) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("computing schema changes: %w", err) + } + + var sources []atlasschema.Change + for _, change := range plan.Changes { + if change.Source != nil { + sources = append(sources, change.Source) + } + } + return changedTables(sources), nil +} + +// Returns the name of the schema Celerity manages within the dev database +// alongside the driver, since the caller has to align the desired schema with it. +func openDevDriver(ctx context.Context, engine, devConnStr string) (migrate.Driver, string, func(), error) { + d, err := dialectForEngine(engine) + if err != nil { + return nil, "", nil, err + } + connStr, err := d.NormalizeConnString(devConnStr) + if err != nil { + return nil, "", nil, err + } + db, err := sql.Open(d.DriverName(), connStr) + if err != nil { + return nil, "", nil, fmt.Errorf("connecting to dev database: %w", err) + } + if err := db.PingContext(ctx); err != nil { + db.Close() + return nil, "", nil, fmt.Errorf("pinging dev database: %w", err) + } + drv, err := d.OpenAtlas(db) + if err != nil { + db.Close() + return nil, "", nil, err + } + schemaName, err := d.SchemaName(ctx, db) + if err != nil { + db.Close() + return nil, "", nil, err + } + return drv, schemaName, func() { db.Close() }, nil +} + +// Returns the real migrations directory when it exists, and a temporary empty +// one with a cleanup when it does not, so a check can run before any migration +// exists. +func replayDir(migrationsPath string) (string, func(), error) { + if _, err := os.Stat(migrationsPath); err == nil { + return migrationsPath, func() {}, nil + } else if !os.IsNotExist(err) { + return "", nil, err + } + tmp, err := os.MkdirTemp("", "celerity-schema-check-*") + if err != nil { + return "", nil, fmt.Errorf("creating temporary replay directory: %w", err) + } + return tmp, func() { _ = os.RemoveAll(tmp) }, nil +} + +// RehashMigrationDir recomputes atlas.sum from the files currently in the +// migration directory. It is the deliberate "I edited a migration on purpose" +// step. Everything else in the CLI treats a checksum mismatch as a hard error, +// because on an already-applied migration it means the history no longer matches +// what ran. +func RehashMigrationDir(migrationsPath string) error { + if err := ValidateMigrationFileNames(migrationsPath); err != nil { + return err + } + dir, err := migrate.NewLocalDir(migrationsPath) + if err != nil { + return fmt.Errorf("opening migrations directory: %w", err) + } + return writeSumFile(dir) +} + +// ValidateMigrationFileNames checks that every .sql file in the directory +// follows the _.sql convention and that no two files +// share a version. +// +// Atlas derives a migration's identity from the leading segment of its file +// name. Files that do not follow the convention, such as a Flyway-style +// "V001__name.up.sql" pair, collide on version, and the collision surfaces deep +// inside the executor as a panic rather than an error, so this runs before +// anything is executed. +func ValidateMigrationFileNames(migrationsPath string) error { + files, err := migrationFileSet(migrationsPath) + if err != nil { + return err + } + + versions := map[string]string{} + for _, name := range sortedKeys(files) { + version := parseVersion(name) + if version == "" { + return fmt.Errorf( + "migration file %q does not follow the _.sql naming convention "+ + "(e.g. 20260713102400_add_customer_tier.sql); create migrations with "+ + "`celerity schema diff` or `celerity schema new` so they are named and ordered correctly", + name, + ) + } + if other, ok := versions[version]; ok { + return fmt.Errorf( + "migration files %q and %q share the version %q; each migration needs its own version "+ + "(migrations are forward-only, so there are no paired up/down files)", + other, name, version, + ) + } + versions[version] = name + } + return nil +} + +func openOrCreateDir(migrationsPath string) (*migrate.LocalDir, error) { + if err := os.MkdirAll(migrationsPath, 0o755); err != nil { + return nil, fmt.Errorf("creating migrations directory: %w", err) + } + dir, err := migrate.NewLocalDir(migrationsPath) + if err != nil { + return nil, fmt.Errorf("opening migrations directory: %w", err) + } + return dir, nil +} + +func isEmptyMigrationDir(migrationsPath string) (bool, error) { + has, err := hasMigrationFiles(migrationsPath) + return !has, err +} + +func writeSumFile(dir *migrate.LocalDir) error { + sum, err := dir.Checksum() + if err != nil { + return fmt.Errorf("computing directory checksum: %w", err) + } + if err := migrate.WriteSumFile(dir, sum); err != nil { + return fmt.Errorf("writing %s: %w", sumFileName, err) + } + return nil +} + +func migrationFileName(version, description string) string { + slug := slugify(description) + if slug == "" { + slug = "migration" + } + return fmt.Sprintf("%s_%s.sql", version, slug) +} + +const versionLayout = "20060102150405" + +// Returns a timestamp version (to the second) strictly greater than every +// existing migration version in the directory, so migrations created within the +// same second do not collide. Atlas keys migrations by version, so uniqueness is +// required for correctness. +func nextAvailableVersion(migrationsPath string, base time.Time) (string, error) { + files, err := migrationFileSet(migrationsPath) + if err != nil { + return "", err + } + baseVersion := base.UTC().Format(versionLayout) + max := maxVersion(files) + if max == "" || baseVersion > max { + return baseVersion, nil + } + return bumpVersion(max), nil +} + +func maxVersion(files map[string]bool) string { + max := "" + for name := range files { + // Versions are fixed-width timestamps, so lexical comparison is ordinal. + if v := parseVersion(name); v > max { + max = v + } + } + return max +} + +func parseVersion(fileName string) string { + version, _, found := strings.Cut(fileName, "_") + if !found || len(version) != len(versionLayout) { + return "" + } + if _, err := time.Parse(versionLayout, version); err != nil { + return "" + } + return version +} + +func bumpVersion(version string) string { + t, err := time.Parse(versionLayout, version) + if err != nil { + return version + } + return t.Add(time.Second).Format(versionLayout) +} + +func slugify(s string) string { + return strings.Trim(nonSlugChars.ReplaceAllString(strings.ToLower(s), "_"), "_") +} diff --git a/apps/cli/internal/sqlschema/migrationdir_integration_test.go b/apps/cli/internal/sqlschema/migrationdir_integration_test.go new file mode 100644 index 00000000..45596180 --- /dev/null +++ b/apps/cli/internal/sqlschema/migrationdir_integration_test.go @@ -0,0 +1,269 @@ +package sqlschema + +import ( + "context" + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/testutils" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +// MigrationDirIntegrationSuite covers the schema diff/new engine. It uses the +// dev database purely as Atlas's replay target, so each test drops any objects +// it may have created and starts from an empty database. +type MigrationDirIntegrationSuite struct { + suite.Suite + devConnStr string +} + +func TestMigrationDirIntegrationSuite(t *testing.T) { + suite.Run(t, new(MigrationDirIntegrationSuite)) +} + +func (s *MigrationDirIntegrationSuite) SetupTest() { + host := testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_HOST") + port := testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_PORT") + user := testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_USER") + password := testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_PASSWORD") + database := testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_DATABASE") + s.devConnStr = FormatConnectionString(host, port, user, password, database) + + // Atlas requires a clean dev database to replay into. + s.dropAll() +} + +func (s *MigrationDirIntegrationSuite) dropAll() { + // Reset the public schema so the dev database is completely clean, which is + // what the Atlas planner requires to replay a migration directory into. A + // real `schema diff` uses a fresh ephemeral container for the same reason. + appl, err := NewApplier("postgres", s.devConnStr, zap.NewNop()) + s.Require().NoError(err) + defer appl.Close() + for _, stmt := range []string{ + "DROP SCHEMA public CASCADE", + "CREATE SCHEMA public", + // Atlas counts every schema in the database when deciding whether it is + // clean, so the migration-history schema has to go too. + fmt.Sprintf("DROP SCHEMA IF EXISTS %q CASCADE", pgRevisionsSchema), + } { + s.Require().NoError(appl.ExecSQL(context.Background(), stmt)) + } +} + +func (s *MigrationDirIntegrationSuite) writeSchema(dir, name, content string) string { + path := filepath.Join(dir, name) + s.Require().NoError(os.WriteFile(path, []byte(content), 0o644)) + return path +} + +func (s *MigrationDirIntegrationSuite) Test_scaffold_migration_creates_file_and_sum() { + dir := s.T().TempDir() + path, err := ScaffoldMigration(dir, "add audit trigger") + s.Require().NoError(err) + + s.Assert().FileExists(path) + s.Assert().Contains(filepath.Base(path), "_add_audit_trigger.sql") + s.Assert().FileExists(filepath.Join(dir, sumFileName)) +} + +func (s *MigrationDirIntegrationSuite) Test_generate_migration_initial_creates_file() { + migrationsDir := s.T().TempDir() + schemaPath := s.writeSchema(s.T().TempDir(), "schema.yaml", ` +tables: + customers: + columns: + id: + type: bigint + primaryKey: true + email: + type: varchar(255) +`) + + path, err := GenerateMigration(context.Background(), s.devConnStr, schemaPath, migrationsDir, "postgres", "init") + s.Require().NoError(err) + s.Require().NotEmpty(path) + s.Assert().FileExists(path) + s.Assert().Contains(filepath.Base(path), "_init.sql") + + content, err := os.ReadFile(path) + s.Require().NoError(err) + s.Assert().Contains(string(content), "CREATE TABLE") + s.Assert().FileExists(filepath.Join(migrationsDir, sumFileName)) +} + +func (s *MigrationDirIntegrationSuite) Test_generate_migration_no_change_returns_empty() { + migrationsDir := s.T().TempDir() + schemaDir := s.T().TempDir() + schemaPath := s.writeSchema(schemaDir, "schema.yaml", ` +tables: + customers: + columns: + id: + type: bigint + primaryKey: true +`) + + first, err := GenerateMigration(context.Background(), s.devConnStr, schemaPath, migrationsDir, "postgres", "init") + s.Require().NoError(err) + s.Require().NotEmpty(first) + + // Re-running against the same schema produces no new migration. + s.dropAll() + second, err := GenerateMigration(context.Background(), s.devConnStr, schemaPath, migrationsDir, "postgres", "noop") + s.Require().NoError(err) + s.Assert().Empty(second, "no schema change should yield no migration file") +} + +func (s *MigrationDirIntegrationSuite) Test_generate_migration_evolution_creates_alter() { + migrationsDir := s.T().TempDir() + schemaDir := s.T().TempDir() + v1 := s.writeSchema(schemaDir, "v1.yaml", ` +tables: + customers: + columns: + id: + type: bigint + primaryKey: true +`) + v2 := s.writeSchema(schemaDir, "v2.yaml", ` +tables: + customers: + columns: + id: + type: bigint + primaryKey: true + tier: + type: varchar(20) + nullable: false + default: "'free'" +`) + + _, err := GenerateMigration(context.Background(), s.devConnStr, v1, migrationsDir, "postgres", "init") + s.Require().NoError(err) + + s.dropAll() + altPath, err := GenerateMigration(context.Background(), s.devConnStr, v2, migrationsDir, "postgres", "add_tier") + s.Require().NoError(err) + s.Require().NotEmpty(altPath) + + content, err := os.ReadFile(altPath) + s.Require().NoError(err) + s.Assert().Contains(string(content), "ADD COLUMN") + s.Assert().Contains(string(content), "tier") +} + +func (s *MigrationDirIntegrationSuite) Test_generated_migrations_apply_cleanly() { + migrationsDir := s.T().TempDir() + schemaDir := s.T().TempDir() + schemaPath := s.writeSchema(schemaDir, "schema.yaml", ` +tables: + customers: + columns: + id: + type: bigint + primaryKey: true + email: + type: varchar(255) + unique: true +`) + + _, err := GenerateMigration(context.Background(), s.devConnStr, schemaPath, migrationsDir, "postgres", "init") + s.Require().NoError(err) + + // A generated migration must apply against a clean database. + s.dropAll() + applier, err := NewApplier("postgres", s.devConnStr, zap.NewNop()) + s.Require().NoError(err) + defer applier.Close() + s.Require().NoError(applier.ApplyMigrationDir(context.Background(), migrationsDir, RiskBreaking)) +} + +func (s *MigrationDirIntegrationSuite) Test_check_pending_migration() { + migrationsDir := s.T().TempDir() + schemaDir := s.T().TempDir() + v1 := s.writeSchema(schemaDir, "v1.yaml", ` +tables: + customers: + columns: + id: + type: bigint + primaryKey: true + email: + type: varchar(255) +`) + + // No migrations yet, but the schema defines tables → pending. + s.dropAll() + pending, err := CheckPendingMigration(context.Background(), s.devConnStr, v1, migrationsDir, "postgres") + s.Require().NoError(err) + s.Assert().True(pending, "an initial migration is needed") + + // Generate the migration → now up to date. + s.dropAll() + _, err = GenerateMigration(context.Background(), s.devConnStr, v1, migrationsDir, "postgres", "init") + s.Require().NoError(err) + s.dropAll() + pending, err = CheckPendingMigration(context.Background(), s.devConnStr, v1, migrationsDir, "postgres") + s.Require().NoError(err) + s.Assert().False(pending, "committed migration covers the schema") + + // Change the schema without generating a migration → pending again. + v2 := s.writeSchema(schemaDir, "v2.yaml", ` +tables: + customers: + columns: + id: + type: bigint + primaryKey: true + email: + type: varchar(255) + tier: + type: varchar(20) +`) + s.dropAll() + pending, err = CheckPendingMigration(context.Background(), s.devConnStr, v2, migrationsDir, "postgres") + s.Require().NoError(err) + s.Assert().True(pending, "the schema change is not yet captured by a migration") +} + +func (s *MigrationDirIntegrationSuite) Test_generated_migration_stamps_risk_header() { + migrationsDir := s.T().TempDir() + schemaDir := s.T().TempDir() + v1 := s.writeSchema(schemaDir, "v1.yaml", ` +tables: + customers: + columns: + id: + type: bigint + primaryKey: true + legacy: + type: varchar(10) +`) + v2 := s.writeSchema(schemaDir, "v2.yaml", ` +tables: + customers: + columns: + id: + type: bigint + primaryKey: true +`) + + // Creating a table is additive → safe. + p1, err := GenerateMigration(context.Background(), s.devConnStr, v1, migrationsDir, "postgres", "init") + s.Require().NoError(err) + risk1, err := ReadMigrationRisk(p1) + s.Require().NoError(err) + s.Assert().Equal(RiskSafe, risk1) + + // Dropping a column is destructive → breaking. + s.dropAll() + p2, err := GenerateMigration(context.Background(), s.devConnStr, v2, migrationsDir, "postgres", "drop_legacy") + s.Require().NoError(err) + risk2, err := ReadMigrationRisk(p2) + s.Require().NoError(err) + s.Assert().Equal(RiskBreaking, risk2) +} diff --git a/apps/cli/internal/sqlschema/migrationdir_test.go b/apps/cli/internal/sqlschema/migrationdir_test.go new file mode 100644 index 00000000..f7e6cf95 --- /dev/null +++ b/apps/cli/internal/sqlschema/migrationdir_test.go @@ -0,0 +1,124 @@ +package sqlschema + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/suite" +) + +type MigrationVersionSuite struct { + suite.Suite +} + +func TestMigrationVersionSuite(t *testing.T) { + suite.Run(t, new(MigrationVersionSuite)) +} + +func (s *MigrationVersionSuite) Test_parse_version() { + s.Assert().Equal("20260721091215", parseVersion("20260721091215_init.sql")) + s.Assert().Equal("", parseVersion("atlas.sum")) + s.Assert().Equal("", parseVersion("not_a_version.sql")) +} + +func (s *MigrationVersionSuite) Test_next_available_version_uses_base_when_empty_dir() { + dir := s.T().TempDir() + base := time.Date(2026, 7, 21, 9, 12, 15, 0, time.UTC) + v, err := nextAvailableVersion(dir, base) + s.Require().NoError(err) + s.Assert().Equal("20260721091215", v) +} + +func (s *MigrationVersionSuite) Test_next_available_version_bumps_on_collision() { + dir := s.T().TempDir() + // Existing migration at the same second the base falls on. + s.Require().NoError(os.WriteFile(filepath.Join(dir, "20260721091215_init.sql"), []byte("-- x"), 0o644)) + + base := time.Date(2026, 7, 21, 9, 12, 15, 0, time.UTC) + v, err := nextAvailableVersion(dir, base) + s.Require().NoError(err) + s.Assert().Equal("20260721091216", v, "must be strictly greater than the existing version") +} + +func (s *MigrationVersionSuite) Test_scaffold_two_in_same_second_do_not_collide() { + dir := s.T().TempDir() + first, err := ScaffoldMigration(dir, "one") + s.Require().NoError(err) + second, err := ScaffoldMigration(dir, "two") + s.Require().NoError(err) + s.Assert().NotEqual( + parseVersion(filepath.Base(first)), + parseVersion(filepath.Base(second)), + "back-to-back scaffolds must get distinct versions", + ) +} + +type MigrationFileNameSuite struct { + suite.Suite +} + +func TestMigrationFileNameSuite(t *testing.T) { + suite.Run(t, new(MigrationFileNameSuite)) +} + +func (s *MigrationFileNameSuite) Test_generated_names_are_accepted() { + dir := s.T().TempDir() + _, err := ScaffoldMigration(dir, "add audit trigger") + s.Require().NoError(err) + _, err = ScaffoldMigration(dir, "add search index") + s.Require().NoError(err) + + s.Assert().NoError(ValidateMigrationFileNames(dir)) +} + +func (s *MigrationFileNameSuite) Test_flyway_style_names_are_rejected() { + // A Flyway-style pair shares one version, which Atlas resolves deep inside + // the executor as an out-of-range panic rather than an error. + dir := s.T().TempDir() + s.Require().NoError(os.WriteFile( + filepath.Join(dir, "V001__add_search_index.up.sql"), []byte("CREATE INDEX i ON t (c);"), 0o644)) + s.Require().NoError(os.WriteFile( + filepath.Join(dir, "V001__add_search_index.down.sql"), []byte("DROP INDEX i;"), 0o644)) + + err := ValidateMigrationFileNames(dir) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "naming convention") +} + +func (s *MigrationFileNameSuite) Test_duplicate_versions_are_rejected() { + dir := s.T().TempDir() + s.Require().NoError(os.WriteFile( + filepath.Join(dir, "20260721091215_init.sql"), []byte("SELECT 1;"), 0o644)) + s.Require().NoError(os.WriteFile( + filepath.Join(dir, "20260721091215_other.sql"), []byte("SELECT 1;"), 0o644)) + + err := ValidateMigrationFileNames(dir) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "share the version") +} + +func (s *MigrationFileNameSuite) Test_rehash_after_hand_editing() { + dir := s.T().TempDir() + path, err := ScaffoldMigration(dir, "add search index") + s.Require().NoError(err) + + // Editing the scaffolded file invalidates the sum written when it was created. + s.Require().NoError(os.WriteFile(path, []byte( + "-- celerity:risk safe\nCREATE INDEX idx ON audit_log USING gin (details);\n"), 0o644)) + s.Require().Error(ValidateMigrationDir(dir)) + + s.Require().NoError(RehashMigrationDir(dir)) + s.Assert().NoError(ValidateMigrationDir(dir)) +} + +func (s *MigrationFileNameSuite) Test_rehash_rejects_a_misnamed_directory() { + dir := s.T().TempDir() + s.Require().NoError(os.WriteFile( + filepath.Join(dir, "V001__init.up.sql"), []byte("SELECT 1;"), 0o644)) + + err := RehashMigrationDir(dir) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "naming convention") +} diff --git a/apps/cli/internal/sqlschema/migrations.go b/apps/cli/internal/sqlschema/migrations.go deleted file mode 100644 index 39467623..00000000 --- a/apps/cli/internal/sqlschema/migrations.go +++ /dev/null @@ -1,107 +0,0 @@ -package sqlschema - -import ( - "fmt" - "os" - "path/filepath" - "sort" - "strconv" - "strings" -) - -// DiscoverMigrationScripts finds versioned SQL migration pairs -// (V__.up.sql / V__.down.sql) -// in the given directory, sorted by version number. -func DiscoverMigrationScripts(migrationsPath string) ([]MigrationScript, error) { - if migrationsPath == "" { - return nil, nil - } - - if _, err := os.Stat(migrationsPath); os.IsNotExist(err) { - return nil, nil - } - - entries, err := os.ReadDir(migrationsPath) - if err != nil { - return nil, fmt.Errorf("reading migrations directory %s: %w", migrationsPath, err) - } - - // Group files by version+description key. - type migrationKey struct { - version int - description string - } - scripts := map[migrationKey]*MigrationScript{} - - for _, entry := range entries { - if entry.IsDir() || filepath.Ext(entry.Name()) != ".sql" { - continue - } - - version, description, direction, err := parseMigrationFilename(entry.Name()) - if err != nil { - continue // Skip files that don't match the naming convention. - } - - key := migrationKey{version: version, description: description} - ms, ok := scripts[key] - if !ok { - ms = &MigrationScript{Version: version, Description: description} - scripts[key] = ms - } - - fullPath := filepath.Join(migrationsPath, entry.Name()) - switch direction { - case "up": - ms.UpPath = fullPath - case "down": - ms.DownPath = fullPath - } - } - - // Flatten to sorted slice. - result := make([]MigrationScript, 0, len(scripts)) - for _, ms := range scripts { - result = append(result, *ms) - } - - sort.Slice(result, func(i, j int) bool { - return result[i].Version < result[j].Version - }) - - return result, nil -} - -// parseMigrationFilename parses a filename like "V001__add_search_index.up.sql" -// into version number, description, and direction (up/down). -func parseMigrationFilename(name string) (version int, description string, direction string, err error) { - // Strip .sql extension. - base := strings.TrimSuffix(name, ".sql") - - // Extract direction suffix (.up or .down). - if strings.HasSuffix(base, ".up") { - direction = "up" - base = strings.TrimSuffix(base, ".up") - } else if strings.HasSuffix(base, ".down") { - direction = "down" - base = strings.TrimSuffix(base, ".down") - } else { - return 0, "", "", fmt.Errorf("filename %q missing .up or .down suffix", name) - } - - if !strings.HasPrefix(base, "V") { - return 0, "", "", fmt.Errorf("filename %q does not start with V", name) - } - - parts := strings.SplitN(base[1:], "__", 2) - if len(parts) != 2 { - return 0, "", "", fmt.Errorf("filename %q does not match V__..sql", name) - } - - version, err = strconv.Atoi(parts[0]) - if err != nil { - return 0, "", "", fmt.Errorf("invalid version number in %q: %w", name, err) - } - - return version, parts[1], direction, nil -} diff --git a/apps/cli/internal/sqlschema/migrations_test.go b/apps/cli/internal/sqlschema/migrations_test.go deleted file mode 100644 index 6d14c01e..00000000 --- a/apps/cli/internal/sqlschema/migrations_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package sqlschema - -import ( - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func Test_DiscoverMigrationScripts_empty_path(t *testing.T) { - scripts, err := DiscoverMigrationScripts("") - require.NoError(t, err) - assert.Nil(t, scripts) -} - -func Test_DiscoverMigrationScripts_missing_dir(t *testing.T) { - scripts, err := DiscoverMigrationScripts("/nonexistent/path") - require.NoError(t, err) - assert.Nil(t, scripts) -} - -func Test_DiscoverMigrationScripts_sorted_with_pairs(t *testing.T) { - dir := t.TempDir() - files := []string{ - "V003__add_trigger.up.sql", - "V003__add_trigger.down.sql", - "V001__add_index.up.sql", - "V001__add_index.down.sql", - "V002__add_column.up.sql", - "V002__add_column.down.sql", - } - for _, f := range files { - require.NoError(t, os.WriteFile(filepath.Join(dir, f), []byte("-- sql"), 0o644)) - } - - scripts, err := DiscoverMigrationScripts(dir) - require.NoError(t, err) - require.Len(t, scripts, 3) - - assert.Equal(t, 1, scripts[0].Version) - assert.Equal(t, "add_index", scripts[0].Description) - assert.Contains(t, scripts[0].UpPath, "V001__add_index.up.sql") - assert.Contains(t, scripts[0].DownPath, "V001__add_index.down.sql") - - assert.Equal(t, 2, scripts[1].Version) - assert.Equal(t, 3, scripts[2].Version) -} - -func Test_DiscoverMigrationScripts_up_only(t *testing.T) { - dir := t.TempDir() - require.NoError(t, os.WriteFile(filepath.Join(dir, "V001__init.up.sql"), []byte("-- up"), 0o644)) - - scripts, err := DiscoverMigrationScripts(dir) - require.NoError(t, err) - require.Len(t, scripts, 1) - assert.NotEmpty(t, scripts[0].UpPath) - assert.Empty(t, scripts[0].DownPath) -} - -func Test_DiscoverMigrationScripts_skips_non_matching(t *testing.T) { - dir := t.TempDir() - files := []string{ - "V001__valid.up.sql", - "V001__valid.down.sql", - "README.md", - "notes.sql", // No V prefix or direction. - "V002__nodir.sql", // Missing .up/.down suffix. - "Vxyz__bad.up.sql", // Non-numeric version. - } - for _, f := range files { - require.NoError(t, os.WriteFile(filepath.Join(dir, f), []byte("content"), 0o644)) - } - - scripts, err := DiscoverMigrationScripts(dir) - require.NoError(t, err) - require.Len(t, scripts, 1) - assert.Equal(t, 1, scripts[0].Version) -} - -func Test_DiscoverMigrationScripts_skips_directories(t *testing.T) { - dir := t.TempDir() - require.NoError(t, os.Mkdir(filepath.Join(dir, "V001__subdir.up.sql"), 0o755)) - require.NoError(t, os.WriteFile(filepath.Join(dir, "V002__real.up.sql"), []byte("-- sql"), 0o644)) - - scripts, err := DiscoverMigrationScripts(dir) - require.NoError(t, err) - require.Len(t, scripts, 1) - assert.Equal(t, 2, scripts[0].Version) -} - -func Test_parseMigrationFilename_valid(t *testing.T) { - tests := []struct { - name string - wantVersion int - wantDesc string - wantDir string - }{ - {"V001__add_index.up.sql", 1, "add_index", "up"}, - {"V001__add_index.down.sql", 1, "add_index", "down"}, - {"V123__complex_migration_name.up.sql", 123, "complex_migration_name", "up"}, - {"V0__init.down.sql", 0, "init", "down"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - v, d, dir, err := parseMigrationFilename(tt.name) - require.NoError(t, err) - assert.Equal(t, tt.wantVersion, v) - assert.Equal(t, tt.wantDesc, d) - assert.Equal(t, tt.wantDir, dir) - }) - } -} - -func Test_parseMigrationFilename_invalid(t *testing.T) { - invalid := []string{ - "001__no_prefix.up.sql", - "V001_single_underscore.up.sql", - "V001__no_direction.sql", - "Vabc__not_numeric.up.sql", - "random.sql", - } - - for _, name := range invalid { - t.Run(name, func(t *testing.T) { - _, _, _, err := parseMigrationFilename(name) - assert.Error(t, err) - }) - } -} diff --git a/apps/cli/internal/sqlschema/mysql_integration_test.go b/apps/cli/internal/sqlschema/mysql_integration_test.go new file mode 100644 index 00000000..01843aff --- /dev/null +++ b/apps/cli/internal/sqlschema/mysql_integration_test.go @@ -0,0 +1,186 @@ +package sqlschema + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/testutils" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +// MySQLIntegrationSuite exercises the MySQL dialect end-to-end against a real +// MySQL server: schema diff, apply, history, inspect and drift. +type MySQLIntegrationSuite struct { + suite.Suite + host, port, user, password, database string + devDatabases []string +} + +var mysqlDevCounter int64 + +func TestMySQLIntegrationSuite(t *testing.T) { + suite.Run(t, new(MySQLIntegrationSuite)) +} + +func (s *MySQLIntegrationSuite) SetupTest() { + // MySQL is gated off for v0; enable it for the duration of these tests. + enableMySQLForTest(s.T()) + s.host = testutils.RequireEnv(s.T(), "CELERITY_TEST_MYSQL_HOST") + s.port = testutils.RequireEnv(s.T(), "CELERITY_TEST_MYSQL_PORT") + s.user = testutils.RequireEnv(s.T(), "CELERITY_TEST_MYSQL_USER") + s.password = testutils.RequireEnv(s.T(), "CELERITY_TEST_MYSQL_PASSWORD") + s.database = testutils.RequireEnv(s.T(), "CELERITY_TEST_MYSQL_DATABASE") + s.resetTables(s.dsn(s.database)) +} + +func (s *MySQLIntegrationSuite) TearDownTest() { + admin, err := NewApplier("mysql", s.dsn(s.database), zap.NewNop()) + if err != nil { + return + } + defer admin.Close() + for _, name := range s.devDatabases { + _ = admin.ExecSQL(context.Background(), fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", name)) + } + s.devDatabases = nil +} + +func (s *MySQLIntegrationSuite) dsn(db string) string { + return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", s.user, s.password, s.host, s.port, db) +} + +// resetTables drops every table in the connected database, leaving it empty. +func (s *MySQLIntegrationSuite) resetTables(dsn string) { + appl, err := NewApplier("mysql", dsn, zap.NewNop()) + s.Require().NoError(err) + defer appl.Close() + ctx := context.Background() + + rows, err := appl.db.QueryContext(ctx, + "SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE()") + s.Require().NoError(err) + var tables []string + for rows.Next() { + var name string + s.Require().NoError(rows.Scan(&name)) + tables = append(tables, name) + } + s.Require().NoError(rows.Err()) + rows.Close() + + if len(tables) == 0 { + return + } + s.Require().NoError(appl.ExecSQL(ctx, "SET FOREIGN_KEY_CHECKS=0")) + for _, t := range tables { + s.Require().NoError(appl.ExecSQL(ctx, fmt.Sprintf("DROP TABLE IF EXISTS `%s`", t))) + } + s.Require().NoError(appl.ExecSQL(ctx, "SET FOREIGN_KEY_CHECKS=1")) +} + +func (s *MySQLIntegrationSuite) freshDevDB() string { + name := fmt.Sprintf("celerity_mysql_dev_%d", atomic.AddInt64(&mysqlDevCounter, 1)) + admin, err := NewApplier("mysql", s.dsn(s.database), zap.NewNop()) + s.Require().NoError(err) + defer admin.Close() + ctx := context.Background() + s.Require().NoError(admin.ExecSQL(ctx, fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", name))) + s.Require().NoError(admin.ExecSQL(ctx, fmt.Sprintf("CREATE DATABASE `%s`", name))) + s.devDatabases = append(s.devDatabases, name) + return s.dsn(name) +} + +func (s *MySQLIntegrationSuite) writeSchema(content string) (string, string) { + dir := s.T().TempDir() + path := filepath.Join(dir, "schema.yaml") + s.Require().NoError(os.WriteFile(path, []byte(content), 0o644)) + return path, s.T().TempDir() +} + +const mysqlSchema = ` +tables: + customers: + columns: + id: + type: bigint + primaryKey: true + email: + type: varchar(255) + orders: + columns: + id: + type: bigint + primaryKey: true + total_cents: + type: int + nullable: false +` + +func (s *MySQLIntegrationSuite) Test_full_flow_diff_apply_history_show() { + ctx := context.Background() + schemaPath, migrationsDir := s.writeSchema(mysqlSchema) + + // Generate a migration on a throwaway dev database. + path, err := GenerateMigration(ctx, s.freshDevDB(), schemaPath, migrationsDir, "mysql", "init") + s.Require().NoError(err) + s.Require().NotEmpty(path) + content, err := os.ReadFile(path) + s.Require().NoError(err) + s.Assert().Contains(string(content), "CREATE TABLE") + + // Apply it to the live database. + live, err := NewApplier("mysql", s.dsn(s.database), zap.NewNop()) + s.Require().NoError(err) + defer live.Close() + s.Require().NoError(live.ApplyMigrationDir(ctx, migrationsDir, RiskBreaking)) + + // History records the applied migration. + records, err := ReadMigrationHistory(ctx, live) + s.Require().NoError(err) + s.Require().Len(records, 1) + s.Assert().Equal("init", records[0].Description) + s.Assert().False(records[0].Failed) + + // Show reflects the applied tables. + shown, err := InspectCurrentSchema(ctx, live) + s.Require().NoError(err) + s.Assert().Contains(shown, "customers") + s.Assert().Contains(shown, "orders") + + // Re-applying is a no-op (idempotent). + s.Require().NoError(live.ApplyMigrationDir(ctx, migrationsDir, RiskBreaking)) + records, err = ReadMigrationHistory(ctx, live) + s.Require().NoError(err) + s.Assert().Len(records, 1) +} + +func (s *MySQLIntegrationSuite) Test_structural_drift() { + ctx := context.Background() + schemaPath, migrationsDir := s.writeSchema(mysqlSchema) + + _, err := GenerateMigration(ctx, s.freshDevDB(), schemaPath, migrationsDir, "mysql", "init") + s.Require().NoError(err) + + live, err := NewApplier("mysql", s.dsn(s.database), zap.NewNop()) + s.Require().NoError(err) + defer live.Close() + s.Require().NoError(live.ApplyMigrationDir(ctx, migrationsDir, RiskBreaking)) + + // No drift when the live database matches the migrations. + report, err := DetectDrift(ctx, live, s.freshDevDB(), migrationsDir, "mysql") + s.Require().NoError(err) + s.Assert().False(report.HasDrift(), "unexpected drift: %+v", report) + + // An out-of-band column is structural drift. + s.Require().NoError(live.ExecSQL(ctx, "ALTER TABLE orders ADD COLUMN discount_cents int")) + report, err = DetectDrift(ctx, live, s.freshDevDB(), migrationsDir, "mysql") + s.Require().NoError(err) + s.Require().True(report.HasDrift()) + s.Assert().Contains(strings.Join(report.Structural, "\n"), "discount_cents") +} diff --git a/apps/cli/internal/sqlschema/provision.go b/apps/cli/internal/sqlschema/provision.go new file mode 100644 index 00000000..908abbb7 --- /dev/null +++ b/apps/cli/internal/sqlschema/provision.go @@ -0,0 +1,171 @@ +package sqlschema + +import ( + "context" + "fmt" + "regexp" + + "go.uber.org/zap" +) + +// AppUser describes the database role the application connects as. +// +// This is deliberately not the master user. The master can drop any table and +// read every database on the instance, and the RDS Proxy already holds it to +// authenticate on the application's behalf; handing it to every handler would +// undo the per-handler role work. Migrations keep running as the master, the +// application runs as this role, and provisioning is what connects the two. +type AppUser struct { + // Name is the role to create. It is validated as an identifier, since + // provisioning takes no free-form SQL. + Name string + + // Password backs password authentication. Ignored in IAM mode. + Password string + + // IAMAuth grants the engine's IAM authentication role instead of setting a + // password, so the handler exchanges its execution role for a short-lived + // token. + IAMAuth bool + + // Database is the database the role is granted CONNECT on. Defaults to the + // connected database when empty. + Database string +} + +// ProvisionReport records what provisioning actually changed, so a repeat run +// can honestly report that it did nothing. +type ProvisionReport struct { + // User is the role that was provisioned. + User string + + // Schema is the schema its object privileges were granted in. + Schema string + + // RoleCreated is true when the role did not exist and was created. + RoleCreated bool + + // AuthConfigured is true when a password was set or the IAM role granted. + AuthConfigured bool + + // IAMAuth records which authentication mode was configured. + IAMAuth bool + + // Grants lists the privileges applied, in the order they were applied. Safe + // to print: identifiers only, never the password. + Grants []string +} + +// Changed reports whether provisioning altered anything beyond re-applying +// grants that were already in place. Grants are idempotent and cheap, so they +// are re-applied every run and do not count as a change. +func (r *ProvisionReport) Changed() bool { + return r != nil && (r.RoleCreated || r.AuthConfigured) +} + +// Render writes a human-readable summary of a provisioning run. +func (r *ProvisionReport) Render(w interface{ Write([]byte) (int, error) }) { + if r == nil { + return + } + verb := "already present" + if r.RoleCreated { + verb = "created" + } + mode := "password authentication" + if r.IAMAuth { + mode = "IAM authentication" + } + fmt.Fprintf(w, " Application user %q %s, %s configured.\n", r.User, verb, mode) + for _, grant := range r.Grants { + fmt.Fprintf(w, " granted %s\n", grant) + } +} + +// identifierPattern is what provisioning will accept as a role, schema or +// database name. +// +// Every engine allows far more than this once quoting is involved, and none of +// it is needed here, because these names come from a blueprint rather than from +// user input at the point of use. Refusing anything unusual is what keeps +// provisioning a fixed routine parameterised by identifiers rather than +// something that executes SQL it was handed. +var identifierPattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_$]*$`) + +// Postgres's limit is 63 bytes and MySQL allows 64, so the stricter of the two +// applies everywhere and a name stays portable between engines. +const maxIdentifierLength = 63 + +// A name that passes this is safe to interpolate into DDL. +func validateIdentifier(kind string, name string) error { + if name == "" { + return fmt.Errorf("%s name is required", kind) + } + if len(name) > maxIdentifierLength { + return fmt.Errorf("%s name %q is longer than %d characters", kind, name, maxIdentifierLength) + } + if !identifierPattern.MatchString(name) { + return fmt.Errorf( + "%s name %q is not a plain identifier (letters, digits and underscores, not starting with a digit)", + kind, name) + } + return nil +} + +// ProvisionAppUser creates or repairs the application database role. It is +// idempotent, so it can run after every deploy, and after a database is restored +// or replaced, without a caller having to determine whether it is needed. +// +// It must be called on an Applier connected as the owner/master, the role that +// runs migrations, since it grants privileges over that role's objects. The +// default privileges it sets are attached to that same role, so tables created +// by later migrations are usable by the application without provisioning running +// again. +func (a *Applier) ProvisionAppUser(ctx context.Context, user AppUser) (*ProvisionReport, error) { + if err := validateIdentifier("application user", user.Name); err != nil { + return nil, err + } + if user.Database != "" { + if err := validateIdentifier("database", user.Database); err != nil { + return nil, err + } + } + if !user.IAMAuth && user.Password == "" { + return nil, fmt.Errorf( + "application user %q uses password authentication but no password was supplied", + user.Name) + } + + schemaName, err := a.dialect.SchemaName(ctx, a.db) + if err != nil { + return nil, fmt.Errorf("resolving the managed schema: %w", err) + } + if err := validateIdentifier("schema", schemaName); err != nil { + return nil, err + } + + report, err := a.dialect.ProvisionAppUser(ctx, a.db, provisionRequest{ + User: user, + Schema: schemaName, + Database: user.Database, + }) + if err != nil { + return nil, err + } + + a.logger.Info("provisioned application database user", + zap.String("user", report.User), + zap.Bool("roleCreated", report.RoleCreated), + zap.Bool("iamAuth", report.IAMAuth), + ) + return report, nil +} + +// The validated input a dialect's provisioning routine works from. Every +// identifier in it has passed validateIdentifier, which is what allows the +// dialects to interpolate them into DDL. +type provisionRequest struct { + User AppUser + Schema string + Database string +} diff --git a/apps/cli/internal/sqlschema/provision_integration_test.go b/apps/cli/internal/sqlschema/provision_integration_test.go new file mode 100644 index 00000000..87323f1e --- /dev/null +++ b/apps/cli/internal/sqlschema/provision_integration_test.go @@ -0,0 +1,201 @@ +package sqlschema + +import ( + "context" + "database/sql" + "fmt" + "net" + "net/url" + "testing" + + _ "github.com/jackc/pgx/v5/stdlib" + "github.com/newstack-cloud/celerity/apps/cli/internal/testutils" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +// The application role is the one piece of this that cannot be verified by +// asserting on generated SQL: whether a grant actually lets a connection read a +// table is a question only a database answers. +type ProvisionIntegrationSuite struct { + suite.Suite + connStr string + logger *zap.Logger +} + +func TestProvisionIntegrationSuite(t *testing.T) { + suite.Run(t, new(ProvisionIntegrationSuite)) +} + +const testAppUser = "celerity_app_provision_test" + +func (s *ProvisionIntegrationSuite) SetupTest() { + host := testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_HOST") + port := testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_PORT") + user := testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_USER") + password := testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_PASSWORD") + database := testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_DATABASE") + + s.connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable", + user, password, host, port, database) + s.logger = zap.NewNop() + s.cleanup() +} + +func (s *ProvisionIntegrationSuite) TearDownTest() { + s.cleanup() +} + +// Dropping a role means undoing everything granted to it first, including the +// default privileges, which are not owned by the role and so do not go with it. +func (s *ProvisionIntegrationSuite) cleanup() { + db, err := sql.Open("pgx", s.connStr) + if err != nil { + return + } + defer db.Close() + + _, _ = db.Exec("DROP TABLE IF EXISTS provision_test_orders CASCADE") + _, _ = db.Exec(fmt.Sprintf( + `ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE ALL ON TABLES FROM %q`, testAppUser)) + _, _ = db.Exec(fmt.Sprintf( + `ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE ALL ON SEQUENCES FROM %q`, testAppUser)) + _, _ = db.Exec(fmt.Sprintf(`DROP OWNED BY %q CASCADE`, testAppUser)) + _, _ = db.Exec(fmt.Sprintf(`DROP ROLE IF EXISTS %q`, testAppUser)) +} + +func (s *ProvisionIntegrationSuite) provision(password string) *ProvisionReport { + applier, err := NewApplier("postgres", s.connStr, s.logger) + s.Require().NoError(err) + defer applier.Close() + + report, err := applier.ProvisionAppUser(context.Background(), AppUser{ + Name: testAppUser, + Password: password, + }) + s.Require().NoError(err) + return report +} + +// appConn opens a connection as the provisioned application user, which is the +// only way to be sure the grants mean what they are supposed to. +func (s *ProvisionIntegrationSuite) appConn(password string) *sql.DB { + host := testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_HOST") + port := testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_PORT") + database := testutils.RequireEnv(s.T(), "CELERITY_TEST_POSTGRES_DATABASE") + + // url.URL rather than a formatted string: a password is arbitrary text and + // has to be percent-encoded to survive a connection URL. + u := url.URL{ + Scheme: "postgres", + User: url.UserPassword(testAppUser, password), + Host: net.JoinHostPort(host, port), + Path: "/" + database, + RawQuery: "sslmode=disable", + } + db, err := sql.Open("pgx", u.String()) + s.Require().NoError(err) + s.Require().NoError(db.Ping(), "the provisioned user could not authenticate") + return db +} + +func (s *ProvisionIntegrationSuite) ownerExec(statements ...string) { + db, err := sql.Open("pgx", s.connStr) + s.Require().NoError(err) + defer db.Close() + for _, stmt := range statements { + _, err := db.Exec(stmt) + s.Require().NoError(err, stmt) + } +} + +func (s *ProvisionIntegrationSuite) Test_provisioned_user_can_authenticate_and_read_and_write() { + const password = "provision-test-password" + s.ownerExec(`CREATE TABLE provision_test_orders (id serial PRIMARY KEY, label text)`) + + report := s.provision(password) + s.True(report.RoleCreated) + s.True(report.AuthConfigured) + + app := s.appConn(password) + defer app.Close() + + // The sequence grant matters as much as the table grant: without it an + // insert into a serial column fails on permission for the sequence, which + // reads as a mystifying error at runtime. + _, err := app.Exec(`INSERT INTO provision_test_orders (label) VALUES ('first')`) + s.Require().NoError(err) + + var label string + s.Require().NoError( + app.QueryRow(`SELECT label FROM provision_test_orders`).Scan(&label)) + s.Equal("first", label) +} + +// The reason default privileges are part of provisioning: without them the +// application cannot see anything a later migration creates, and provisioning +// would have to run again after every migration. +func (s *ProvisionIntegrationSuite) Test_tables_created_after_provisioning_are_usable() { + const password = "provision-test-password" + s.provision(password) + + s.ownerExec(`CREATE TABLE provision_test_orders (id serial PRIMARY KEY, label text)`) + + app := s.appConn(password) + defer app.Close() + + _, err := app.Exec(`INSERT INTO provision_test_orders (label) VALUES ('later')`) + s.Require().NoError(err, "a table created after provisioning must be writable without re-provisioning") +} + +// The application gets DML and nothing structural. Migrations are the only +// thing that changes shape, and they run as the owner. +func (s *ProvisionIntegrationSuite) Test_application_user_cannot_change_the_schema() { + const password = "provision-test-password" + s.provision(password) + + app := s.appConn(password) + defer app.Close() + + _, err := app.Exec(`CREATE TABLE provision_test_forbidden (id int)`) + s.Require().Error(err, "the application user must not be able to create tables") + s.Contains(err.Error(), "permission denied") +} + +// Provisioning runs after every deploy, so a second run against a database that +// already has the role must be a no-op that reports as much. +func (s *ProvisionIntegrationSuite) Test_provisioning_twice_reports_no_change() { + const password = "provision-test-password" + s.provision(password) + + report := s.provision(password) + + s.False(report.RoleCreated, "the role already existed") + s.NotEmpty(report.Grants, "grants are re-applied regardless") +} + +// Rotating the secret has to reach the database, and the only thing that +// carries it there is a repeat provisioning run. +func (s *ProvisionIntegrationSuite) Test_a_changed_password_is_applied() { + s.provision("first-password") + + s.provision("second-password") + + app := s.appConn("second-password") + defer app.Close() +} + +// Generated passwords exclude quotes, but a database restored from elsewhere or +// a hand-set secret need not, and a password mangled by quoting produces a +// login failure with no clue as to why. +func (s *ProvisionIntegrationSuite) Test_a_password_with_quotes_and_backslashes_round_trips() { + const awkward = `p'a"s\s w%o$rd` + + s.provision(awkward) + + app := s.appConn(awkward) + defer app.Close() + + var one int + s.Require().NoError(app.QueryRow("SELECT 1").Scan(&one)) +} diff --git a/apps/cli/internal/sqlschema/provision_mysql.go b/apps/cli/internal/sqlschema/provision_mysql.go new file mode 100644 index 00000000..5c4a7bb9 --- /dev/null +++ b/apps/cli/internal/sqlschema/provision_mysql.go @@ -0,0 +1,134 @@ +package sqlschema + +import ( + "context" + "database/sql" + "fmt" + "strings" +) + +// The host part of the application account. Handlers reach the database through +// the proxy from addresses that are not fixed, so the account is not +// host-restricted and security groups control the network path instead. +const mysqlAppUserHost = "%" + +// The authentication plugin RDS uses for IAM database authentication. +const mysqlIAMPlugin = "AWSAuthenticationPlugin" + +// ProvisionAppUser creates or repairs the application account on MySQL. +// +// MySQL grants privileges on a database with a wildcard, so unlike Postgres +// there is no separate default-privileges step. Tables created by later +// migrations are covered by the same grant. +func (d mysqlDialect) ProvisionAppUser( + ctx context.Context, + db *sql.DB, + req provisionRequest, +) (*ProvisionReport, error) { + name := req.User.Name + account := fmt.Sprintf("'%s'@'%s'", name, mysqlAppUserHost) + + database := req.Database + if database == "" { + database = req.Schema + } + + report := &ProvisionReport{User: name, Schema: req.Schema, IAMAuth: req.User.IAMAuth} + + exists, err := mysqlUserExists(ctx, db, name) + if err != nil { + return nil, err + } + if !exists { + if _, err := db.ExecContext(ctx, "CREATE USER "+account); err != nil { + return nil, fmt.Errorf("creating user %s: %w", account, err) + } + report.RoleCreated = true + } + + if err := mysqlConfigureAuth(ctx, db, req, account, report); err != nil { + return nil, err + } + + grant := fmt.Sprintf("%s ON %s.* TO %s", + appUserPrivileges, d.QuoteIdentifier(database), account) + if _, err := db.ExecContext(ctx, "GRANT "+grant); err != nil { + return nil, fmt.Errorf("granting %s: %w", grant, err) + } + report.Grants = append(report.Grants, grant) + + return report, nil +} + +func mysqlConfigureAuth( + ctx context.Context, + db *sql.DB, + req provisionRequest, + account string, + report *ProvisionReport, +) error { + if req.User.IAMAuth { + stmt := fmt.Sprintf("ALTER USER %s IDENTIFIED WITH %s AS 'RDS'", account, mysqlIAMPlugin) + if _, err := db.ExecContext(ctx, stmt); err != nil { + return fmt.Errorf( + "configuring IAM authentication for %s (the %s plugin exists only on RDS and Aurora MySQL): %w", + account, mysqlIAMPlugin, err) + } + report.AuthConfigured = true + return nil + } + + literal, err := mysqlQuoteLiteral(ctx, db, req.User.Password) + if err != nil { + return err + } + // The statement carries the password, so nothing built here may appear in an + // error message. + if _, err := db.ExecContext(ctx, + fmt.Sprintf("ALTER USER %s IDENTIFIED BY %s", account, literal)); err != nil { + return fmt.Errorf("setting the password for %s: %w", account, err) + } + report.AuthConfigured = true + return nil +} + +func mysqlUserExists(ctx context.Context, db *sql.DB, name string) (bool, error) { + var count int + err := db.QueryRowContext(ctx, + "SELECT COUNT(*) FROM mysql.user WHERE user = ? AND host = ?", + name, mysqlAppUserHost, + ).Scan(&count) + if err != nil { + return false, fmt.Errorf("checking whether user %q exists: %w", name, err) + } + return count > 0, nil +} + +// Quotes a string for interpolation into DDL that cannot take a placeholder. +// +// MySQL has no server-side quoting function to delegate to the way Postgres's +// format does, so the escaping is done here, and it depends on the session's +// sql_mode. Under NO_BACKSLASH_ESCAPES a backslash is an ordinary character and +// escaping with one would change the value being stored. Rather than guess, that +// mode is refused. +func mysqlQuoteLiteral(ctx context.Context, db *sql.DB, value string) (string, error) { + var mode string + if err := db.QueryRowContext(ctx, "SELECT @@session.sql_mode").Scan(&mode); err != nil { + return "", fmt.Errorf("reading sql_mode: %w", err) + } + if strings.Contains(strings.ToUpper(mode), "NO_BACKSLASH_ESCAPES") { + return "", fmt.Errorf( + "cannot set a password while the session runs with NO_BACKSLASH_ESCAPES; " + + "remove it from sql_mode on the database's parameter group, or use IAM authentication") + } + + replacer := strings.NewReplacer( + `\`, `\\`, + `'`, `\'`, + "\x00", `\0`, + "\n", `\n`, + "\r", `\r`, + "\x1a", `\Z`, + ) + return "'" + replacer.Replace(value) + "'", nil +} diff --git a/apps/cli/internal/sqlschema/provision_postgres.go b/apps/cli/internal/sqlschema/provision_postgres.go new file mode 100644 index 00000000..2f11d6f9 --- /dev/null +++ b/apps/cli/internal/sqlschema/provision_postgres.go @@ -0,0 +1,157 @@ +package sqlschema + +import ( + "context" + "database/sql" + "errors" + "fmt" +) + +// The role RDS grants IAM database authentication through. It exists only on +// RDS and Aurora Postgres, which is how provisioning tells a managed database +// from a plain one. +const pgIAMRole = "rds_iam" + +// What the application is granted on the managed schema, which is to read and +// write rows and nothing structural. Migrations create and alter objects, and +// they run as the owner. +const appUserPrivileges = "SELECT, INSERT, UPDATE, DELETE" + +// Identity and serial columns need the sequence granted as well as the table. +const appUserSequencePrivileges = "USAGE, SELECT" + +// ProvisionAppUser creates or repairs the application role on Postgres. +// +// Every statement is written to be safe to repeat. The role is created only when +// absent, authentication is re-applied unconditionally (which is also how a +// rotated password reaches the database), and grants are idempotent by +// definition. +func (d postgresDialect) ProvisionAppUser( + ctx context.Context, + db *sql.DB, + req provisionRequest, +) (*ProvisionReport, error) { + name := req.User.Name + quotedUser := d.QuoteIdentifier(name) + + database := req.Database + if database == "" { + if err := db.QueryRowContext(ctx, "SELECT current_database()").Scan(&database); err != nil { + return nil, fmt.Errorf("reading the connected database name: %w", err) + } + if err := validateIdentifier("database", database); err != nil { + return nil, err + } + } + + report := &ProvisionReport{User: name, Schema: req.Schema, IAMAuth: req.User.IAMAuth} + + exists, err := pgRoleExists(ctx, db, name) + if err != nil { + return nil, err + } + if !exists { + if _, err := db.ExecContext(ctx, fmt.Sprintf("CREATE ROLE %s WITH LOGIN", quotedUser)); err != nil { + return nil, fmt.Errorf("creating role %q: %w", name, err) + } + report.RoleCreated = true + } + + if err := d.configurePostgresAuth(ctx, db, req, quotedUser, report); err != nil { + return nil, err + } + + grants := []string{ + fmt.Sprintf("CONNECT ON DATABASE %s TO %s", d.QuoteIdentifier(database), quotedUser), + fmt.Sprintf("USAGE ON SCHEMA %s TO %s", d.QuoteIdentifier(req.Schema), quotedUser), + fmt.Sprintf("%s ON ALL TABLES IN SCHEMA %s TO %s", + appUserPrivileges, d.QuoteIdentifier(req.Schema), quotedUser), + fmt.Sprintf("%s ON ALL SEQUENCES IN SCHEMA %s TO %s", + appUserSequencePrivileges, d.QuoteIdentifier(req.Schema), quotedUser), + } + for _, grant := range grants { + if _, err := db.ExecContext(ctx, "GRANT "+grant); err != nil { + return nil, fmt.Errorf("granting %s: %w", grant, err) + } + report.Grants = append(report.Grants, grant) + } + + // Without this, every migration that creates a table would leave the + // application unable to read it until provisioning ran again. The defaults + // attach to the role executing this statement, which is the same role + // migrations run as, so they apply to exactly the objects Celerity creates + // and not to anything another role makes in the same schema. + defaults := []string{ + fmt.Sprintf("%s ON TABLES TO %s", appUserPrivileges, quotedUser), + fmt.Sprintf("%s ON SEQUENCES TO %s", appUserSequencePrivileges, quotedUser), + } + for _, def := range defaults { + stmt := fmt.Sprintf("ALTER DEFAULT PRIVILEGES IN SCHEMA %s GRANT %s", + d.QuoteIdentifier(req.Schema), def) + if _, err := db.ExecContext(ctx, stmt); err != nil { + return nil, fmt.Errorf("setting default privileges (%s): %w", def, err) + } + report.Grants = append(report.Grants, "default privileges: "+def) + } + + return report, nil +} + +func (d postgresDialect) configurePostgresAuth( + ctx context.Context, + db *sql.DB, + req provisionRequest, + quotedUser string, + report *ProvisionReport, +) error { + if req.User.IAMAuth { + iamAvailable, err := pgRoleExists(ctx, db, pgIAMRole) + if err != nil { + return err + } + if !iamAvailable { + return fmt.Errorf( + "database %q is configured for IAM authentication but has no %s role, "+ + "which only exists on RDS and Aurora Postgres with IAM database authentication enabled", + req.Database, pgIAMRole) + } + if _, err := db.ExecContext(ctx, + fmt.Sprintf("GRANT %s TO %s", pgIAMRole, quotedUser)); err != nil { + return fmt.Errorf("granting %s to %q: %w", pgIAMRole, req.User.Name, err) + } + report.AuthConfigured = true + return nil + } + + // The password is the one value here that is not an identifier, so the + // server quotes it rather than string-building doing so. format's %L applies + // Postgres's own literal-quoting rules, including the escape-string prefix + // when the value needs one. + var stmt string + err := db.QueryRowContext(ctx, + "SELECT format('ALTER ROLE %I WITH LOGIN PASSWORD %L', $1::text, $2::text)", + req.User.Name, req.User.Password, + ).Scan(&stmt) + if err != nil { + return fmt.Errorf("preparing the password statement for %q: %w", req.User.Name, err) + } + if _, err := db.ExecContext(ctx, stmt); err != nil { + // The statement carries the password, so it must never reach an error + // message, a log line or a CI transcript. + return fmt.Errorf("setting the password for %q: %w", req.User.Name, err) + } + report.AuthConfigured = true + return nil +} + +func pgRoleExists(ctx context.Context, db *sql.DB, name string) (bool, error) { + var one int + err := db.QueryRowContext(ctx, "SELECT 1 FROM pg_roles WHERE rolname = $1", name).Scan(&one) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("checking whether role %q exists: %w", name, err) + } + return true, nil +} diff --git a/apps/cli/internal/sqlschema/provision_test.go b/apps/cli/internal/sqlschema/provision_test.go new file mode 100644 index 00000000..cd3a0b31 --- /dev/null +++ b/apps/cli/internal/sqlschema/provision_test.go @@ -0,0 +1,80 @@ +package sqlschema + +import ( + "context" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Provisioning interpolates names into DDL that cannot take placeholders, so +// what it accepts as a name is the boundary that keeps it a fixed routine +// rather than something that runs SQL it was handed. +func TestValidateIdentifier(t *testing.T) { + valid := []string{"celerity_app", "app$1", "_leading", "A", strings.Repeat("a", 63)} + for _, name := range valid { + assert.NoError(t, validateIdentifier("application user", name), name) + } + + rejected := map[string]string{ + "": "is required", + "1app": "not a plain identifier", + "app-user": "not a plain identifier", + "app user": "not a plain identifier", + `app"; DROP DATABASE x; --`: "not a plain identifier", + "app\x00": "not a plain identifier", + strings.Repeat("a", 64): "longer than 63", + } + for name, want := range rejected { + err := validateIdentifier("application user", name) + require.Error(t, err, "%q should be rejected", name) + assert.Contains(t, err.Error(), want) + } +} + +// A database in password mode with no password would produce a role nothing can +// authenticate as, which fails later and somewhere less obvious. +func TestProvisionAppUserRequiresACredential(t *testing.T) { + applier := &Applier{} + + _, err := applier.ProvisionAppUser(context.Background(), AppUser{Name: "celerity_app"}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "no password was supplied") +} + +func TestProvisionAppUserValidatesNames(t *testing.T) { + applier := &Applier{} + + _, err := applier.ProvisionAppUser(context.Background(), AppUser{ + Name: "celerity app", Password: "x", + }) + + require.Error(t, err) + assert.Contains(t, err.Error(), "application user") +} + +// Grants are re-applied on every run because they are idempotent and cheap, so +// applying them is not itself a change worth reporting. +func TestProvisionReportChanged(t *testing.T) { + assert.False(t, (&ProvisionReport{Grants: []string{"USAGE ON SCHEMA"}}).Changed()) + assert.True(t, (&ProvisionReport{RoleCreated: true}).Changed()) + assert.True(t, (&ProvisionReport{AuthConfigured: true}).Changed()) + assert.False(t, (*ProvisionReport)(nil).Changed()) +} + +func TestProvisionReportRenderOmitsTheCredential(t *testing.T) { + var out strings.Builder + report := &ProvisionReport{ + User: "celerity_app", + AuthConfigured: true, + Grants: []string{`USAGE ON SCHEMA "public" TO "celerity_app"`}, + } + + report.Render(&out) + + assert.Contains(t, out.String(), `"celerity_app" already present, password authentication configured`) + assert.Contains(t, out.String(), "granted USAGE ON SCHEMA") +} diff --git a/apps/cli/internal/sqlschema/realm.go b/apps/cli/internal/sqlschema/realm.go new file mode 100644 index 00000000..ce0fb44e --- /dev/null +++ b/apps/cli/internal/sqlschema/realm.go @@ -0,0 +1,165 @@ +package sqlschema + +import ( + "fmt" + "sort" + "strings" + + atlasschema "ariga.io/atlas/sql/schema" +) + +// The name the desired schema is built with, matching Postgres's "public". For +// engines whose managed schema is the database itself (MySQL), DB-backed callers +// override the built schema's name with the real one before diffing. +const defaultSchemaName = "public" + +// desiredSchema maps a parsed Celerity schema YAML to an Atlas schema object +// (the desired end state) for the given engine. +// +// A column is NOT NULL unless it declares `nullable: true`, and primary-key +// columns are always NOT NULL. +func desiredSchema(s *Schema, engine string) (*atlasschema.Schema, error) { + d, err := dialectForEngine(engine) + if err != nil { + return nil, err + } + + sch := atlasschema.New(defaultSchemaName) + tables := map[string]*atlasschema.Table{} + columns := map[string]map[string]*atlasschema.Column{} + + // Step 1: tables, columns, primary keys, unique columns, indexes, checks. + for _, tableName := range sortedKeys(s.Tables) { + at, cols, err := buildTable(d, tableName, s.Tables[tableName]) + if err != nil { + return nil, fmt.Errorf("table %s: %w", tableName, err) + } + sch.AddTables(at) + tables[tableName] = at + columns[tableName] = cols + } + + // Step 2: foreign keys (need the referenced tables/columns to exist first). + for _, tableName := range sortedKeys(s.Tables) { + if err := addForeignKeys(tableName, s.Tables[tableName], tables, columns); err != nil { + return nil, fmt.Errorf("table %s: %w", tableName, err) + } + } + + return sch, nil +} + +func buildTable(d dialect, name string, tbl Table) (*atlasschema.Table, map[string]*atlasschema.Column, error) { + at := atlasschema.NewTable(name) + cols := map[string]*atlasschema.Column{} + var pk []*atlasschema.Column + + for _, colName := range sortedKeys(tbl.Columns) { + col := tbl.Columns[colName] + colType, err := d.ParseType(col.Type) + if err != nil { + return nil, nil, fmt.Errorf("column %s: parsing type %q: %w", colName, col.Type, err) + } + + ac := atlasschema.NewColumn(colName).SetType(colType) + ac.SetNull(col.Nullable && !col.PrimaryKey) + if col.Default != "" { + ac.SetDefault(&atlasschema.RawExpr{X: col.Default}) + } + at.AddColumns(ac) + cols[colName] = ac + if col.PrimaryKey { + pk = append(pk, ac) + } + } + + if len(pk) > 0 { + at.SetPrimaryKey(atlasschema.NewPrimaryKey(pk...)) + } + + // Column-level UNIQUE becomes a unique index using Postgres's default + // naming convention, so it round-trips against an inspected database. + for _, colName := range sortedKeys(tbl.Columns) { + if tbl.Columns[colName].Unique { + idxName := fmt.Sprintf("%s_%s_key", name, colName) + at.AddIndexes(atlasschema.NewUniqueIndex(idxName).AddColumns(cols[colName])) + } + } + + for _, idx := range tbl.Indexes { + ix := atlasschema.NewIndex(idx.Name) + if idx.Unique { + ix = atlasschema.NewUniqueIndex(idx.Name) + } + for _, c := range idx.Columns { + col, ok := cols[c] + if !ok { + return nil, nil, fmt.Errorf("index %s references unknown column %q", idx.Name, c) + } + ix.AddColumns(col) + } + typeAttr, err := d.IndexTypeAttr(idx.Type) + if err != nil { + return nil, nil, fmt.Errorf("index %s: %w", idx.Name, err) + } + if typeAttr != nil { + ix.AddAttrs(typeAttr) + } + at.AddIndexes(ix) + } + + for _, c := range tbl.Constraints { + if c.Type != "check" || c.Expression == "" { + continue + } + at.AddChecks(atlasschema.NewCheck().SetName(c.Name).SetExpr(c.Expression)) + } + + return at, cols, nil +} + +func addForeignKeys( + tableName string, + tbl Table, + tables map[string]*atlasschema.Table, + columns map[string]map[string]*atlasschema.Column, +) error { + for _, colName := range sortedKeys(tbl.Columns) { + col := tbl.Columns[colName] + if col.References == nil { + continue + } + + refTable, ok := tables[col.References.Table] + if !ok { + return fmt.Errorf("column %s references unknown table %q", colName, col.References.Table) + } + refCol, ok := columns[col.References.Table][col.References.Column] + if !ok { + return fmt.Errorf("column %s references unknown column %s.%s", colName, col.References.Table, col.References.Column) + } + + fk := atlasschema.NewForeignKey(fkConstraintName(tableName, colName)). + AddColumns(columns[tableName][colName]). + SetRefTable(refTable). + AddRefColumns(refCol) + if col.References.OnDelete != "" { + fk.SetOnDelete(atlasschema.ReferenceOption(strings.ToUpper(col.References.OnDelete))) + } + tables[tableName].AddForeignKeys(fk) + } + return nil +} + +func fkConstraintName(tableName, colName string) string { + return fmt.Sprintf("fk_%s_%s", tableName, colName) +} + +func sortedKeys[V any](m map[string]V) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} diff --git a/apps/cli/internal/sqlschema/realm_test.go b/apps/cli/internal/sqlschema/realm_test.go new file mode 100644 index 00000000..fbddd8bc --- /dev/null +++ b/apps/cli/internal/sqlschema/realm_test.go @@ -0,0 +1,196 @@ +package sqlschema + +import ( + "testing" + + "ariga.io/atlas/sql/postgres" + atlasschema "ariga.io/atlas/sql/schema" + "github.com/stretchr/testify/suite" +) + +type RealmTestSuite struct { + suite.Suite +} + +func TestRealmTestSuite(t *testing.T) { + suite.Run(t, new(RealmTestSuite)) +} + +func (s *RealmTestSuite) Test_maps_columns_and_nullability() { + schema := &Schema{ + Tables: map[string]Table{ + "users": { + Columns: map[string]Column{ + // Primary key: always NOT NULL even though nullable defaults false. + "id": {Type: "bigint", PrimaryKey: true}, + // Default (nullable false) → NOT NULL. + "email": {Type: "varchar(255)"}, + // Explicitly nullable. + "nickname": {Type: "varchar(100)", Nullable: true}, + }, + }, + }, + } + + sch, err := desiredSchema(schema, "postgres") + s.Require().NoError(err) + + tbl, ok := sch.Table("users") + s.Require().True(ok) + + id, ok := tbl.Column("id") + s.Require().True(ok) + s.Assert().False(id.Type.Null, "primary key must be NOT NULL") + + email, ok := tbl.Column("email") + s.Require().True(ok) + s.Assert().False(email.Type.Null, "non-nullable column must be NOT NULL") + + nickname, ok := tbl.Column("nickname") + s.Require().True(ok) + s.Assert().True(nickname.Type.Null, "nullable:true column must allow NULL") + + s.Require().NotNil(tbl.PrimaryKey) +} + +func (s *RealmTestSuite) Test_resolves_foreign_keys() { + schema := &Schema{ + Tables: map[string]Table{ + "customers": {Columns: map[string]Column{"id": {Type: "bigint", PrimaryKey: true}}}, + "orders": { + Columns: map[string]Column{ + "id": {Type: "bigint", PrimaryKey: true}, + "customer_id": {Type: "bigint", References: &ForeignKey{Table: "customers", Column: "id", OnDelete: "cascade"}}, + }, + }, + }, + } + + sch, err := desiredSchema(schema, "postgres") + s.Require().NoError(err) + + orders, ok := sch.Table("orders") + s.Require().True(ok) + s.Require().Len(orders.ForeignKeys, 1) + s.Assert().Equal("customers", orders.ForeignKeys[0].RefTable.Name) +} + +func (s *RealmTestSuite) Test_unknown_fk_target_errors() { + schema := &Schema{ + Tables: map[string]Table{ + "orders": { + Columns: map[string]Column{ + "customer_id": {Type: "bigint", References: &ForeignKey{Table: "missing", Column: "id"}}, + }, + }, + }, + } + _, err := desiredSchema(schema, "postgres") + s.Assert().ErrorContains(err, "unknown table") +} + +func (s *RealmTestSuite) Test_unsupported_engine_errors() { + schema := &Schema{Tables: map[string]Table{"users": {Columns: map[string]Column{"id": {Type: "bigint"}}}}} + _, err := desiredSchema(schema, "oracle") + s.Assert().ErrorContains(err, "unsupported SQL engine") +} + +func (s *RealmTestSuite) Test_mysql_engine_builds_schema() { + enableMySQLForTest(s.T()) + schema := &Schema{Tables: map[string]Table{ + "users": {Columns: map[string]Column{ + "id": {Type: "bigint", PrimaryKey: true}, + "name": {Type: "varchar(100)"}, + }}, + }} + sch, err := desiredSchema(schema, "mysql") + s.Require().NoError(err) + s.Require().Len(sch.Tables, 1) + s.Assert().Equal("users", sch.Tables[0].Name) +} + +func (s *RealmTestSuite) Test_index_type_maps_to_the_engine_attribute() { + schema := &Schema{ + Tables: map[string]Table{ + "audit_log": { + Columns: map[string]Column{ + "id": {Type: "bigint", PrimaryKey: true}, + "details": {Type: "jsonb"}, + }, + Indexes: []Index{ + {Name: "idx_audit_details", Columns: []string{"details"}, Type: "gin"}, + }, + }, + }, + } + + sch, err := desiredSchema(schema, "postgres") + s.Require().NoError(err) + + tbl, ok := sch.Table("audit_log") + s.Require().True(ok) + idx, ok := tbl.Index("idx_audit_details") + s.Require().True(ok) + + typ := indexTypeAttr(idx.Attrs) + s.Require().NotNil(typ, "index must carry an index-type attribute") + s.Assert().Equal(postgres.IndexTypeGIN, typ.T) +} + +func (s *RealmTestSuite) Test_btree_is_left_implicit() { + // Atlas defaults an absent attribute to btree. Spelling out the default must + // produce the same desired state as omitting it, or every diff would churn. + explicit := &Schema{ + Tables: map[string]Table{ + "users": { + Columns: map[string]Column{"email": {Type: "varchar(255)"}}, + Indexes: []Index{{Name: "idx_users_email", Columns: []string{"email"}, Type: "btree"}}, + }, + }, + } + implicit := &Schema{ + Tables: map[string]Table{ + "users": { + Columns: map[string]Column{"email": {Type: "varchar(255)"}}, + Indexes: []Index{{Name: "idx_users_email", Columns: []string{"email"}}}, + }, + }, + } + + for _, schema := range []*Schema{explicit, implicit} { + sch, err := desiredSchema(schema, "postgres") + s.Require().NoError(err) + tbl, ok := sch.Table("users") + s.Require().True(ok) + idx, ok := tbl.Index("idx_users_email") + s.Require().True(ok) + s.Assert().Nil(indexTypeAttr(idx.Attrs), "btree must be left as the engine default") + } +} + +func (s *RealmTestSuite) Test_unsupported_index_type_is_rejected() { + schema := &Schema{ + Tables: map[string]Table{ + "users": { + Columns: map[string]Column{"email": {Type: "varchar(255)"}}, + Indexes: []Index{{Name: "idx_users_email", Columns: []string{"email"}, Type: "bloom"}}, + }, + }, + } + + _, err := desiredSchema(schema, "postgres") + s.Require().Error(err) + s.Assert().Contains(err.Error(), "unsupported index type") + s.Assert().Contains(err.Error(), "gin", "the error must name what the engine accepts") +} + +// indexTypeAttr returns the Postgres index-type attribute on an index, or nil +// when the index carries none (meaning the engine default, btree). +func indexTypeAttr(attrs []atlasschema.Attr) *postgres.IndexType { + for _, a := range attrs { + if t, ok := a.(*postgres.IndexType); ok { + return t + } + } + return nil +} diff --git a/apps/cli/internal/sqlschema/revisions.go b/apps/cli/internal/sqlschema/revisions.go new file mode 100644 index 00000000..0488b76d --- /dev/null +++ b/apps/cli/internal/sqlschema/revisions.go @@ -0,0 +1,201 @@ +package sqlschema + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "time" + + "ariga.io/atlas/sql/migrate" +) + +// The migration-history table Celerity owns. It matches the +// Atlas default name so teams that separately use Atlas tooling against the same +// migration directory see a consistent history table. +const revisionsTable = "atlas_schema_revisions" + +// On Postgres the history table lives in its own schema, as Atlas does by +// default, so that it sits outside the schema the YAML models. Nothing scoped to +// the managed schema (declarative diffs, `schema show`, exports) can reach it, +// let alone drop it. +const ( + pgRevisionsSchema = "atlas_schema_revisions" + pgRevisionsQualified = `"` + pgRevisionsSchema + `"."` + revisionsTable + `"` + // Where the table lived before it was moved into its own schema. Databases + // migrated by an earlier CLI still have it here; ensureTable adopts those + // rows on first use. + pgLegacyRevisionsQualified = `"` + postgresSchemaName + `"."` + revisionsTable + `"` +) + +// Implements migrate.RevisionReadWriter over a Postgres connection. +// Atlas has no public concrete revision store, so we own this table, which keeps +// the table name (atlas_schema_revisions) under our control as the Gen 3 spec +// requires. The Revision struct's Applied/Total/PartialHashes fields carry +// statement-level progress so a non-transactional migration can resume safely. +type pgRevisions struct { + db *sql.DB +} + +func newPGRevisions(ctx context.Context, db *sql.DB) (*pgRevisions, error) { + p := &pgRevisions{db: db} + if err := p.ensureTable(ctx); err != nil { + return nil, err + } + return p, nil +} + +func (p *pgRevisions) ensureTable(ctx context.Context) error { + if _, err := p.db.ExecContext(ctx, + fmt.Sprintf("CREATE SCHEMA IF NOT EXISTS %q", pgRevisionsSchema), + ); err != nil { + return fmt.Errorf("creating %s schema: %w", pgRevisionsSchema, err) + } + + _, err := p.db.ExecContext(ctx, fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s ( + version varchar NOT NULL PRIMARY KEY, + description text NOT NULL, + type bigint NOT NULL DEFAULT 0, + applied bigint NOT NULL DEFAULT 0, + total bigint NOT NULL DEFAULT 0, + executed_at timestamptz NOT NULL, + execution_time bigint NOT NULL DEFAULT 0, + error text NOT NULL DEFAULT '', + error_stmt text NOT NULL DEFAULT '', + hash text NOT NULL DEFAULT '', + partial_hashes jsonb, + operator_version text NOT NULL DEFAULT '' + )`, pgRevisionsQualified)) + if err != nil { + return fmt.Errorf("creating %s table: %w", pgRevisionsQualified, err) + } + + return p.adoptLegacyRevisions(ctx) +} + +// Moves history written by an earlier CLI, which kept the table in the managed +// schema, into the dedicated schema. It runs in one transaction and copies before +// dropping, so an interrupted move leaves the history readable in the old +// location rather than lost. +// +// Rows already in the new table win, because a database that has been migrated +// since the move is authoritative and the legacy table is stale. +func (p *pgRevisions) adoptLegacyRevisions(ctx context.Context) error { + var exists bool + err := p.db.QueryRowContext(ctx, `SELECT EXISTS ( + SELECT 1 FROM information_schema.tables + WHERE table_schema = $1 AND table_name = $2 + )`, postgresSchemaName, revisionsTable).Scan(&exists) + if err != nil { + return fmt.Errorf("checking for a legacy %s table: %w", revisionsTable, err) + } + if !exists { + return nil + } + + tx, err := p.db.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("starting the migration-history move: %w", err) + } + defer tx.Rollback() + + if _, err := tx.ExecContext(ctx, fmt.Sprintf( + "INSERT INTO %s (%s) SELECT %s FROM %s ON CONFLICT (version) DO NOTHING", + pgRevisionsQualified, revisionColumns, revisionColumns, pgLegacyRevisionsQualified, + )); err != nil { + return fmt.Errorf("copying migration history out of %s: %w", postgresSchemaName, err) + } + if _, err := tx.ExecContext(ctx, fmt.Sprintf("DROP TABLE %s", pgLegacyRevisionsQualified)); err != nil { + return fmt.Errorf("dropping the legacy %s table: %w", revisionsTable, err) + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("committing the migration-history move: %w", err) + } + return nil +} + +func (p *pgRevisions) Ident() *migrate.TableIdent { + return &migrate.TableIdent{Name: revisionsTable, Schema: pgRevisionsSchema} +} + +func (p *pgRevisions) ReadRevisions(ctx context.Context) ([]*migrate.Revision, error) { + rows, err := p.db.QueryContext(ctx, fmt.Sprintf("SELECT %s FROM %s ORDER BY version", revisionColumns, pgRevisionsQualified)) + if err != nil { + return nil, err + } + defer rows.Close() + + var revisions []*migrate.Revision + for rows.Next() { + r, err := scanRevision(rows) + if err != nil { + return nil, err + } + revisions = append(revisions, r) + } + return revisions, rows.Err() +} + +func (p *pgRevisions) ReadRevision(ctx context.Context, version string) (*migrate.Revision, error) { + row := p.db.QueryRowContext(ctx, + fmt.Sprintf("SELECT %s FROM %s WHERE version = $1", revisionColumns, pgRevisionsQualified), version) + r, err := scanRevision(row) + if errors.Is(err, sql.ErrNoRows) { + return nil, migrate.ErrRevisionNotExist + } + return r, err +} + +func (p *pgRevisions) WriteRevision(ctx context.Context, r *migrate.Revision) error { + partialHashes, err := json.Marshal(r.PartialHashes) + if err != nil { + return fmt.Errorf("marshalling partial hashes: %w", err) + } + _, err = p.db.ExecContext(ctx, fmt.Sprintf(`INSERT INTO %s + (version, description, type, applied, total, executed_at, execution_time, error, error_stmt, hash, partial_hashes, operator_version) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) + ON CONFLICT (version) DO UPDATE SET + description=$2, type=$3, applied=$4, total=$5, executed_at=$6, execution_time=$7, + error=$8, error_stmt=$9, hash=$10, partial_hashes=$11, operator_version=$12`, pgRevisionsQualified), + r.Version, r.Description, int64(r.Type), r.Applied, r.Total, r.ExecutedAt, + int64(r.ExecutionTime), r.Error, r.ErrorStmt, r.Hash, partialHashes, r.OperatorVersion) + if err != nil { + return fmt.Errorf("writing revision %s: %w", r.Version, err) + } + return nil +} + +func (p *pgRevisions) DeleteRevision(ctx context.Context, version string) error { + _, err := p.db.ExecContext(ctx, fmt.Sprintf("DELETE FROM %s WHERE version = $1", pgRevisionsQualified), version) + return err +} + +const revisionColumns = "version, description, type, applied, total, executed_at, execution_time, error, error_stmt, hash, partial_hashes, operator_version" + +type rowScanner interface { + Scan(dest ...any) error +} + +func scanRevision(s rowScanner) (*migrate.Revision, error) { + var ( + r migrate.Revision + revType int64 + executionTime int64 + partialHashes []byte + ) + if err := s.Scan( + &r.Version, &r.Description, &revType, &r.Applied, &r.Total, &r.ExecutedAt, + &executionTime, &r.Error, &r.ErrorStmt, &r.Hash, &partialHashes, &r.OperatorVersion, + ); err != nil { + return nil, err + } + r.Type = migrate.RevisionType(revType) + r.ExecutionTime = time.Duration(executionTime) + if len(partialHashes) > 0 { + if err := json.Unmarshal(partialHashes, &r.PartialHashes); err != nil { + return nil, fmt.Errorf("unmarshalling partial hashes for %s: %w", r.Version, err) + } + } + return &r, nil +} diff --git a/apps/cli/internal/sqlschema/revisions_mysql.go b/apps/cli/internal/sqlschema/revisions_mysql.go new file mode 100644 index 00000000..3b68e66a --- /dev/null +++ b/apps/cli/internal/sqlschema/revisions_mysql.go @@ -0,0 +1,138 @@ +package sqlschema + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "time" + + "ariga.io/atlas/sql/migrate" +) + +// mysqlRevisions implements migrate.RevisionReadWriter over a MySQL connection, +// backing the same atlas_schema_revisions table as the Postgres store but with +// MySQL-compatible DDL and an upsert. +type mysqlRevisions struct { + db *sql.DB + schema string +} + +func newMySQLRevisions(ctx context.Context, db *sql.DB) (*mysqlRevisions, error) { + schema, err := mysqlDialect{}.SchemaName(ctx, db) + if err != nil { + return nil, err + } + p := &mysqlRevisions{db: db, schema: schema} + if err := p.ensureTable(ctx); err != nil { + return nil, err + } + return p, nil +} + +func (p *mysqlRevisions) ensureTable(ctx context.Context) error { + _, err := p.db.ExecContext(ctx, fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s ( + version varchar(255) NOT NULL PRIMARY KEY, + description text NOT NULL, + type bigint NOT NULL DEFAULT 0, + applied bigint NOT NULL DEFAULT 0, + total bigint NOT NULL DEFAULT 0, + executed_at datetime(6) NOT NULL, + execution_time bigint NOT NULL DEFAULT 0, + error text, + error_stmt text, + hash varchar(255) NOT NULL DEFAULT '', + partial_hashes json, + operator_version varchar(255) NOT NULL DEFAULT '' + )`, revisionsTable)) + if err != nil { + return fmt.Errorf("creating %s table: %w", revisionsTable, err) + } + return nil +} + +// For MySQL the revision table's schema is the connected database. +func (p *mysqlRevisions) Ident() *migrate.TableIdent { + return &migrate.TableIdent{Name: revisionsTable, Schema: p.schema} +} + +func (p *mysqlRevisions) ReadRevisions(ctx context.Context) ([]*migrate.Revision, error) { + rows, err := p.db.QueryContext(ctx, fmt.Sprintf("SELECT %s FROM %s ORDER BY version", revisionColumns, revisionsTable)) + if err != nil { + return nil, err + } + defer rows.Close() + + var revisions []*migrate.Revision + for rows.Next() { + r, err := scanMySQLRevision(rows) + if err != nil { + return nil, err + } + revisions = append(revisions, r) + } + return revisions, rows.Err() +} + +func (p *mysqlRevisions) ReadRevision(ctx context.Context, version string) (*migrate.Revision, error) { + row := p.db.QueryRowContext(ctx, + fmt.Sprintf("SELECT %s FROM %s WHERE version = ?", revisionColumns, revisionsTable), version) + r, err := scanMySQLRevision(row) + if errors.Is(err, sql.ErrNoRows) { + return nil, migrate.ErrRevisionNotExist + } + return r, err +} + +func (p *mysqlRevisions) WriteRevision(ctx context.Context, r *migrate.Revision) error { + partialHashes, err := json.Marshal(r.PartialHashes) + if err != nil { + return fmt.Errorf("marshalling partial hashes: %w", err) + } + _, err = p.db.ExecContext(ctx, fmt.Sprintf(`INSERT INTO %s + (version, description, type, applied, total, executed_at, execution_time, error, error_stmt, hash, partial_hashes, operator_version) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?) + ON DUPLICATE KEY UPDATE + description=VALUES(description), type=VALUES(type), applied=VALUES(applied), total=VALUES(total), + executed_at=VALUES(executed_at), execution_time=VALUES(execution_time), error=VALUES(error), + error_stmt=VALUES(error_stmt), hash=VALUES(hash), partial_hashes=VALUES(partial_hashes), + operator_version=VALUES(operator_version)`, revisionsTable), + r.Version, r.Description, int64(r.Type), r.Applied, r.Total, r.ExecutedAt, + int64(r.ExecutionTime), r.Error, r.ErrorStmt, r.Hash, partialHashes, r.OperatorVersion) + if err != nil { + return fmt.Errorf("writing revision %s: %w", r.Version, err) + } + return nil +} + +func (p *mysqlRevisions) DeleteRevision(ctx context.Context, version string) error { + _, err := p.db.ExecContext(ctx, fmt.Sprintf("DELETE FROM %s WHERE version = ?", revisionsTable), version) + return err +} + +func scanMySQLRevision(s rowScanner) (*migrate.Revision, error) { + var ( + r migrate.Revision + revType int64 + executionTime int64 + errText, errStmt sql.NullString + partialHashes []byte + ) + if err := s.Scan( + &r.Version, &r.Description, &revType, &r.Applied, &r.Total, &r.ExecutedAt, + &executionTime, &errText, &errStmt, &r.Hash, &partialHashes, &r.OperatorVersion, + ); err != nil { + return nil, err + } + r.Type = migrate.RevisionType(revType) + r.ExecutionTime = time.Duration(executionTime) + r.Error = errText.String + r.ErrorStmt = errStmt.String + if len(partialHashes) > 0 { + if err := json.Unmarshal(partialHashes, &r.PartialHashes); err != nil { + return nil, fmt.Errorf("unmarshalling partial hashes for %s: %w", r.Version, err) + } + } + return &r, nil +} diff --git a/apps/cli/internal/sqlschema/types.go b/apps/cli/internal/sqlschema/types.go index 0795635a..aca269cc 100644 --- a/apps/cli/internal/sqlschema/types.go +++ b/apps/cli/internal/sqlschema/types.go @@ -5,6 +5,13 @@ package sqlschema type Schema struct { Tables map[string]Table `yaml:"tables"` Extensions []string `yaml:"extensions"` + // Exclude lists objects that exist in the database but are deliberately not + // modelled here, typically because a hand-written migration creates them + // (expression or partial indexes, triggers, functions, policies). Patterns + // use Atlas's glob syntax relative to the managed schema, e.g. + // "audit_log.index[idx_*]" or "legacy_*". Excluded objects are never + // created, altered or dropped by schema-YAML-driven diffs. + Exclude []string `yaml:"exclude"` } // Table describes a single database table. @@ -13,18 +20,29 @@ type Table struct { Columns map[string]Column `yaml:"columns"` Indexes []Index `yaml:"indexes"` Constraints []Constraint `yaml:"constraints"` + // Tags are free-form categorisation labels (e.g. "financial", "core-entity") + // surfaced in exports. They have no effect on DDL. + Tags []string `yaml:"tags"` + // TypeName overrides the generated entity type name for this table (used by + // `schema codegen`). When empty, the name is derived by singularising the + // table name (e.g. customers → Customer). Set this for irregular plurals the + // singulariser gets wrong. + TypeName string `yaml:"typeName"` } // Column describes a single table column with engine-native type. type Column struct { - Type string `yaml:"type"` - PrimaryKey bool `yaml:"primaryKey"` - Nullable bool `yaml:"nullable"` - Unique bool `yaml:"unique"` - Default string `yaml:"default"` - Description string `yaml:"description"` - Classification string `yaml:"classification"` - References *ForeignKey `yaml:"references"` + Type string `yaml:"type"` + PrimaryKey bool `yaml:"primaryKey"` + Nullable bool `yaml:"nullable"` + Unique bool `yaml:"unique"` + Default string `yaml:"default"` + Description string `yaml:"description"` + Classification string `yaml:"classification"` + // Tags are free-form categorisation labels for the column, surfaced in + // exports. They have no effect on DDL. + Tags []string `yaml:"tags"` + References *ForeignKey `yaml:"references"` } // ForeignKey describes a foreign key reference from a column. @@ -39,6 +57,12 @@ type Index struct { Name string `yaml:"name"` Columns []string `yaml:"columns"` Unique bool `yaml:"unique"` + // Type is the index method (Postgres: btree, gin, gist, spgist, brin, hash; + // MySQL: btree, hash, fulltext, spatial). Empty means the engine default + // (btree). Only the index method is covered. Expression parts, operator + // classes and partial-index predicates are not modelled here, and those + // indexes belong in a hand-written migration listed under Schema.Exclude. + Type string `yaml:"type"` } // Constraint describes a table constraint (check, unique, composite foreign key). @@ -49,15 +73,6 @@ type Constraint struct { Columns []string `yaml:"columns"` } -// MigrationScript represents a versioned SQL migration with up/down files -// (V__.up.sql / V__.down.sql). -type MigrationScript struct { - Version int - Description string - UpPath string - DownPath string -} - // DatabaseResource holds the resolved configuration for a celerity/sqlDatabase // blueprint resource. Paths are resolved to absolute paths. type DatabaseResource struct { diff --git a/apps/cli/internal/sqlschema/validate.go b/apps/cli/internal/sqlschema/validate.go new file mode 100644 index 00000000..4f789340 --- /dev/null +++ b/apps/cli/internal/sqlschema/validate.go @@ -0,0 +1,52 @@ +package sqlschema + +import ( + "fmt" + + "ariga.io/atlas/sql/migrate" +) + +// ValidateSchema parses a schema YAML file and checks that it maps cleanly to +// the target engine: the file must parse, foreign keys must reference existing +// tables and columns, and column types must be understood. It does not require +// a database connection. +func ValidateSchema(schemaPath, engine string) error { + parsed, err := ParseSchemaFile(schemaPath) + if err != nil { + return err + } + if _, err := desiredSchema(parsed, engine); err != nil { + return err + } + return validateExcludePatterns(parsed.Exclude) +} + +// ValidateMigrationDir checks that the atlas.sum integrity file is present and +// matches the migration directory contents. Returns nil when the directory +// holds no migrations yet. +func ValidateMigrationDir(migrationsPath string) error { + has, err := hasMigrationFiles(migrationsPath) + if err != nil { + return err + } + if !has { + return nil + } + if err := ValidateMigrationFileNames(migrationsPath); err != nil { + return err + } + + dir, err := migrate.NewLocalDir(migrationsPath) + if err != nil { + return fmt.Errorf("opening migrations directory: %w", err) + } + if err := migrate.Validate(dir); err != nil { + return fmt.Errorf( + "migration directory integrity check failed (%w). If you edited a migration on purpose "+ + "(a hand-written file from `celerity schema new`), run `celerity schema hash` to "+ + "re-sum the directory. Otherwise the files no longer match the history that ran", + err, + ) + } + return nil +} diff --git a/apps/cli/internal/sqlschema/validate_test.go b/apps/cli/internal/sqlschema/validate_test.go new file mode 100644 index 00000000..23fd77dc --- /dev/null +++ b/apps/cli/internal/sqlschema/validate_test.go @@ -0,0 +1,92 @@ +package sqlschema + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" +) + +type ValidateSuite struct { + suite.Suite +} + +func TestValidateSuite(t *testing.T) { + suite.Run(t, new(ValidateSuite)) +} + +func (s *ValidateSuite) writeFile(dir, name, content string) string { + path := filepath.Join(dir, name) + s.Require().NoError(os.WriteFile(path, []byte(content), 0o644)) + return path +} + +func (s *ValidateSuite) Test_validate_schema_valid() { + path := s.writeFile(s.T().TempDir(), "schema.yaml", ` +tables: + customers: + columns: + id: + type: bigint + primaryKey: true + orders: + columns: + id: + type: bigint + primaryKey: true + customer_id: + type: bigint + references: + table: customers + column: id +`) + s.Assert().NoError(ValidateSchema(path, "postgres")) +} + +func (s *ValidateSuite) Test_validate_schema_bad_foreign_key() { + path := s.writeFile(s.T().TempDir(), "schema.yaml", ` +tables: + orders: + columns: + customer_id: + type: bigint + references: + table: missing + column: id +`) + err := ValidateSchema(path, "postgres") + s.Assert().ErrorContains(err, "unknown table") +} + +func (s *ValidateSuite) Test_validate_schema_unparseable() { + path := s.writeFile(s.T().TempDir(), "schema.yaml", "this: [is: not: valid") + s.Assert().Error(ValidateSchema(path, "postgres")) +} + +func (s *ValidateSuite) Test_validate_migration_dir_empty_is_ok() { + s.Assert().NoError(ValidateMigrationDir(s.T().TempDir())) +} + +func (s *ValidateSuite) Test_validate_migration_dir_valid_sum() { + dir := s.T().TempDir() + _, err := ScaffoldMigration(dir, "init") + s.Require().NoError(err) + s.Assert().NoError(ValidateMigrationDir(dir)) +} + +func (s *ValidateSuite) Test_validate_migration_dir_missing_sum() { + dir := s.T().TempDir() + s.writeFile(dir, "20260101000000_init.sql", "CREATE TABLE t (id bigint);") + // No atlas.sum written. + s.Assert().Error(ValidateMigrationDir(dir)) +} + +func (s *ValidateSuite) Test_validate_migration_dir_tampered_file() { + dir := s.T().TempDir() + created, err := ScaffoldMigration(dir, "init") + s.Require().NoError(err) + // Modify the file after the sum was written. + s.Require().NoError(os.WriteFile(created, []byte("CREATE TABLE tampered (id bigint);"), 0o644)) + s.Assert().Error(ValidateMigrationDir(dir)) +} From 7228ce448d997386af76b7d01778e9228544876e Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 14 Oct 2026 16:19:11 +0100 Subject: [PATCH 10/12] feat(cli): support Go and community SDKs on the os-only runtime An os-only runtime identifier names a base operating system rather than a language. The core runtime starts a pre-compiled handlers executable and streams events to it over the IPC protocol, and nothing in that contract says what compiled it, so the language cannot be read off the runtime string the way nodejs24.x gives it away. It is resolved from the project instead. Two toolchains ship. Go drives the celerity-go tool from the Celerity Go SDK, which writes the platform imports for a deploy target and reports the handlers the binary serves by building it and running it, so the handler list comes from the same registry the dispatcher routes against. The second is driven entirely by a handlerBuild block in the deploy config, which is how a community SDK for any other compiled language is supported without CLI code of its own. The toolchain package is a leaf because deployconfig already imports build and handlerresolve, so a toolchain importing deploy config back would close a cycle. The handlerBuild schema therefore lives with the toolchain and deploy config embeds it. A Lambda build takes a compiled path that skips dependency layers, source copying and entry point generation, none of which apply to a binary. The architecture is recorded on the manifest and checked against the built file, because a mismatch is a valid archive the kernel refuses to exec and surfaces only as exit status 126. A dev session cross-compiles for the architecture the Docker daemon runs containers at rather than the one the CLI was built for, since a remote context or a Linux VM differs. The watcher takes its roots from the toolchain, because a Go module keeps handlers at the module root where watching src would find nothing, and it rebuilds before extracting, leaving the last working build serving when a rebuild fails. A manifest from a community extractor is validated before it is merged. The merge skips what it does not recognise by design, so an unvalidated manifest with the wrong annotation keys would merge cleanly and produce an application with no handlers, surfacing much later as a runtime handshake failure. --- apps/cli/internal/blueprint/helpers.go | 16 +- apps/cli/internal/blueprint/sdk_version.go | 22 ++ .../internal/blueprint/toolchain_inputs.go | 83 +++++ .../blueprint/toolchain_inputs_test.go | 77 +++++ apps/cli/internal/consts/consts.go | 18 + .../internal/consts/runtime_conventions.go | 68 +++- .../consts/runtime_conventions_test.go | 47 ++- apps/cli/internal/devconfig/deploy_config.go | 31 ++ apps/cli/internal/devconfig/resolver.go | 93 ++++- apps/cli/internal/devconfig/toolchain.go | 177 ++++++++++ apps/cli/internal/devconfig/toolchain_test.go | 151 ++++++++ apps/cli/internal/devrun/orchestrator.go | 160 ++++++++- apps/cli/internal/devrun/stubs.go | 85 ++++- apps/cli/internal/devrun/stubs_test.go | 65 ++++ apps/cli/internal/devrun/watcher.go | 125 +++++-- .../internal/devrun/watcher_compiled_test.go | 123 +++++++ .../cli/internal/devrun/watcher_paths_test.go | 104 ++++++ apps/cli/internal/devtest/node_runner.go | 2 +- apps/cli/internal/devtest/oshandler_runner.go | 111 ++++++ .../internal/devtest/oshandler_runner_test.go | 120 +++++++ apps/cli/internal/devtest/python_runner.go | 2 +- apps/cli/internal/devtest/registry.go | 49 ++- apps/cli/internal/devtest/registry_test.go | 15 +- apps/cli/internal/docker/architecture.go | 41 +++ apps/cli/internal/docker/architecture_test.go | 26 ++ apps/cli/internal/docker/client.go | 4 +- apps/cli/internal/handlerresolve/resolver.go | 225 ++++++++++++ .../internal/handlerresolve/resolver_test.go | 200 +++++++++++ .../cli/internal/handlerresolve/sdk_detect.go | 154 +++++++++ .../handlerresolve/sdk_detect_test.go | 138 ++++++++ .../internal/handlerresolve/toolchain_test.go | 186 ++++++++++ apps/cli/internal/handlertoolchain/config.go | 156 +++++++++ apps/cli/internal/handlertoolchain/custom.go | 167 +++++++++ .../internal/handlertoolchain/custom_test.go | 241 +++++++++++++ apps/cli/internal/handlertoolchain/exec.go | 79 +++++ apps/cli/internal/handlertoolchain/files.go | 107 ++++++ .../internal/handlertoolchain/files_test.go | 77 +++++ apps/cli/internal/handlertoolchain/golang.go | 270 +++++++++++++++ .../internal/handlertoolchain/golang_test.go | 322 ++++++++++++++++++ apps/cli/internal/handlertoolchain/gomod.go | 99 ++++++ apps/cli/internal/handlertoolchain/resolve.go | 80 +++++ .../internal/handlertoolchain/resolve_test.go | 112 ++++++ .../handlertoolchain/stub_runner_test.go | 76 +++++ .../internal/handlertoolchain/toolchain.go | 138 ++++++++ .../internal/preprocess/consumer_collapse.go | 300 ++++++++++++++++ .../preprocess/consumer_collapse_test.go | 215 ++++++++++++ apps/cli/internal/preprocess/extractor.go | 25 +- .../cli/internal/preprocess/extractor_test.go | 92 +++++ apps/cli/internal/preprocess/merger.go | 73 ++-- .../preprocess/merger_resource_links.go | 174 ++++++++++ .../preprocess/merger_resource_links_test.go | 255 ++++++++++++++ apps/cli/internal/preprocess/validate.go | 80 +++++ 52 files changed, 5716 insertions(+), 140 deletions(-) create mode 100644 apps/cli/internal/blueprint/toolchain_inputs.go create mode 100644 apps/cli/internal/blueprint/toolchain_inputs_test.go create mode 100644 apps/cli/internal/devconfig/toolchain.go create mode 100644 apps/cli/internal/devconfig/toolchain_test.go create mode 100644 apps/cli/internal/devrun/stubs_test.go create mode 100644 apps/cli/internal/devrun/watcher_compiled_test.go create mode 100644 apps/cli/internal/devrun/watcher_paths_test.go create mode 100644 apps/cli/internal/devtest/oshandler_runner.go create mode 100644 apps/cli/internal/devtest/oshandler_runner_test.go create mode 100644 apps/cli/internal/docker/architecture.go create mode 100644 apps/cli/internal/docker/architecture_test.go create mode 100644 apps/cli/internal/handlerresolve/resolver.go create mode 100644 apps/cli/internal/handlerresolve/resolver_test.go create mode 100644 apps/cli/internal/handlerresolve/sdk_detect.go create mode 100644 apps/cli/internal/handlerresolve/sdk_detect_test.go create mode 100644 apps/cli/internal/handlerresolve/toolchain_test.go create mode 100644 apps/cli/internal/handlertoolchain/config.go create mode 100644 apps/cli/internal/handlertoolchain/custom.go create mode 100644 apps/cli/internal/handlertoolchain/custom_test.go create mode 100644 apps/cli/internal/handlertoolchain/exec.go create mode 100644 apps/cli/internal/handlertoolchain/files.go create mode 100644 apps/cli/internal/handlertoolchain/files_test.go create mode 100644 apps/cli/internal/handlertoolchain/golang.go create mode 100644 apps/cli/internal/handlertoolchain/golang_test.go create mode 100644 apps/cli/internal/handlertoolchain/gomod.go create mode 100644 apps/cli/internal/handlertoolchain/resolve.go create mode 100644 apps/cli/internal/handlertoolchain/resolve_test.go create mode 100644 apps/cli/internal/handlertoolchain/stub_runner_test.go create mode 100644 apps/cli/internal/handlertoolchain/toolchain.go create mode 100644 apps/cli/internal/preprocess/consumer_collapse.go create mode 100644 apps/cli/internal/preprocess/consumer_collapse_test.go create mode 100644 apps/cli/internal/preprocess/extractor_test.go create mode 100644 apps/cli/internal/preprocess/merger_resource_links.go create mode 100644 apps/cli/internal/preprocess/merger_resource_links_test.go create mode 100644 apps/cli/internal/preprocess/validate.go diff --git a/apps/cli/internal/blueprint/helpers.go b/apps/cli/internal/blueprint/helpers.go index 756da6f1..ede8d260 100644 --- a/apps/cli/internal/blueprint/helpers.go +++ b/apps/cli/internal/blueprint/helpers.go @@ -9,6 +9,7 @@ import ( "github.com/newstack-cloud/bluelink/libs/blueprint/core" "github.com/newstack-cloud/bluelink/libs/blueprint/schema" "github.com/newstack-cloud/bluelink/libs/blueprint/substitutions" + "github.com/newstack-cloud/celerity/apps/cli/internal/consts" ) const ( @@ -17,9 +18,15 @@ const ( ) // Supported runtime-to-image-repo mappings. +// +// Every OS-only runtime resolves to the core runtime image. There is no image +// per compiled language and there should not be: the image carries the +// runtime and no handlers, and the language-specific part is linked into the +// handlers executable that the CLI builds and the runtime starts. var runtimeImageRepos = map[string]string{ - "nodejs24.x": "ghcr.io/newstack-cloud/celerity-runtime-nodejs-24", - "python3.13": "ghcr.io/newstack-cloud/celerity-runtime-python-3-13", + "nodejs24.x": "ghcr.io/newstack-cloud/celerity-runtime-nodejs-24", + "python3.13": "ghcr.io/newstack-cloud/celerity-runtime-python-3-13", + consts.RuntimeOSOnlyDebian13: "ghcr.io/newstack-cloud/celerity-runtime-core", } // HandlerInfo holds extracted metadata about a handler resource. @@ -96,12 +103,17 @@ func DetectRuntime(bp *schema.Blueprint) (string, error) { // projectFileRuntimes maps project files to their default runtime identifiers. // Used as a fallback when no handler resources exist in the blueprint // (decorator-driven projects where handlers are extracted from source code). +// go.mod is last. A Go Celerity application is the only one of the three whose +// project file routinely appears alongside another: a Node or Python project +// with a Go tool of its own in the same directory is ordinary, and matching +// go.mod first would read it as a Go application. var projectFileRuntimes = []struct { File string Runtime string }{ {"package.json", "nodejs24.x"}, {"pyproject.toml", "python3.13"}, + {"go.mod", consts.RuntimeOSOnlyDebian13}, } // DetectRuntimeFromProject infers the runtime from project files in appDir. diff --git a/apps/cli/internal/blueprint/sdk_version.go b/apps/cli/internal/blueprint/sdk_version.go index 4c649c92..2bfdadd4 100644 --- a/apps/cli/internal/blueprint/sdk_version.go +++ b/apps/cli/internal/blueprint/sdk_version.go @@ -15,6 +15,17 @@ import ( const nodeSDKPackage = "@celerity-sdk/core" const pythonSDKPackage = "celerity-sdk" +// CoreRuntimeImageVersion is the core runtime image version an OS-only +// runtime resolves to. +// +// Pinned in the CLI rather than detected from the project, because there is +// nothing in the project to detect. The core runtime carries no language SDK +// and versions independently of every SDK: the contract it has to stay +// compatible with is the IPC protocol, which is versioned in the proto +// package path. The SDK the handlers executable was built against travels +// inside the executable. +const CoreRuntimeImageVersion = "0.3.0" + // DetectSDKVersion reads the project's dependency file and returns the // Celerity SDK version declared for the given runtime. // The returned version is stripped of range prefixes (^, ~, >=, etc.) @@ -31,6 +42,17 @@ func DetectSDKVersion(appDir string, runtime string) (string, error) { var sdkDetectors = map[string]func(string) (string, error){ consts.LanguageNodeJS: detectNodeSDKVersion, consts.LanguagePython: detectPythonSDKVersion, + consts.RuntimeOSOnly: detectCoreRuntimeVersion, +} + +// detectCoreRuntimeVersion answers with the pinned core runtime version. +// +// Registered as a detector rather than special-cased by the caller so that an +// OS-only runtime does not fall through to the "no SDK version detection" +// error and silently take the default image version, which tracks the +// language SDKs and would be the wrong number. +func detectCoreRuntimeVersion(string) (string, error) { + return CoreRuntimeImageVersion, nil } // nodePackageJSON is the minimal structure needed to extract dependency versions. diff --git a/apps/cli/internal/blueprint/toolchain_inputs.go b/apps/cli/internal/blueprint/toolchain_inputs.go new file mode 100644 index 00000000..19beca62 --- /dev/null +++ b/apps/cli/internal/blueprint/toolchain_inputs.go @@ -0,0 +1,83 @@ +package blueprint + +import ( + "slices" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" +) + +// toolchainResourceKinds maps a blueprint resource type to the resource kind +// name a Celerity SDK links an implementation for. +// +// Only the kinds an SDK provides a client for. celerity/config is absent +// because configuration reaches a handler through the config store rather +// than through a resource layer, and the API, handler and VPC types describe +// the application rather than something it reaches. +var toolchainResourceKinds = map[string]string{ + "celerity/bucket": "bucket", + "celerity/cache": "cache", + "celerity/datastore": "datastore", + "celerity/queue": "queue", + "celerity/sqlDatabase": "sqlDatabase", + "celerity/topic": "topic", +} + +// ResourceKinds returns the sorted, deduplicated resource kinds a blueprint +// declares. +// +// A compiled language cannot discover these at startup the way an interpreted +// one can, so the build has to link an implementation for each kind ahead of +// time. Deriving them from the blueprint is what keeps that out of the +// application's own source. +func ResourceKinds(bp *schema.Blueprint) []string { + if bp == nil || bp.Resources == nil { + return nil + } + + seen := map[string]bool{} + for _, resource := range bp.Resources.Values { + if resource == nil || resource.Type == nil { + continue + } + if kind, ok := toolchainResourceKinds[resource.Type.Value]; ok { + seen[kind] = true + } + } + return sortedKeysOf(seen) +} + +// SQLEngines returns the sorted, deduplicated engines of a blueprint's SQL +// databases, so a driver is linked for each. +func SQLEngines(bp *schema.Blueprint) []string { + if bp == nil || bp.Resources == nil { + return nil + } + + seen := map[string]bool{} + for _, resource := range bp.Resources.Values { + if resource == nil || resource.Type == nil { + continue + } + if resource.Type.Value != "celerity/sqlDatabase" { + continue + } + if engine := specStringField(resource, "engine"); engine != "" { + seen[engine] = true + } + } + return sortedKeysOf(seen) +} + +// sortedKeysOf returns the set's keys in order, so a generated file and the +// command line that produced it reproduce between runs. +func sortedKeysOf(set map[string]bool) []string { + if len(set) == 0 { + return nil + } + keys := make([]string, 0, len(set)) + for key := range set { + keys = append(keys, key) + } + slices.Sort(keys) + return keys +} diff --git a/apps/cli/internal/blueprint/toolchain_inputs_test.go b/apps/cli/internal/blueprint/toolchain_inputs_test.go new file mode 100644 index 00000000..8b46a01d --- /dev/null +++ b/apps/cli/internal/blueprint/toolchain_inputs_test.go @@ -0,0 +1,77 @@ +package blueprint + +import ( + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/core" + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/stretchr/testify/assert" +) + +func resourceOfType(resourceType string, spec map[string]*core.MappingNode) *schema.Resource { + r := &schema.Resource{Type: &schema.ResourceTypeWrapper{Value: resourceType}} + if spec != nil { + r.Spec = &core.MappingNode{Fields: spec} + } + return r +} + +func blueprintWith(resources map[string]*schema.Resource) *schema.Blueprint { + return &schema.Blueprint{Resources: &schema.ResourceMap{Values: resources}} +} + +func stringNode(value string) *core.MappingNode { + return &core.MappingNode{Scalar: &core.ScalarValue{StringValue: &value}} +} + +func TestResourceKinds_sortedAndDeduplicated(t *testing.T) { + bp := blueprintWith(map[string]*schema.Resource{ + "filesBucket": resourceOfType("celerity/bucket", nil), + "imagesBucket": resourceOfType("celerity/bucket", nil), + "usersStore": resourceOfType("celerity/datastore", nil), + "workQueue": resourceOfType("celerity/queue", nil), + }) + + assert.Equal(t, []string{"bucket", "datastore", "queue"}, ResourceKinds(bp)) +} + +// Configuration reaches a handler through the config store, and the API and +// handler types describe the application rather than something it reaches. +func TestResourceKinds_ignoresTypesWithNoResourceLayer(t *testing.T) { + bp := blueprintWith(map[string]*schema.Resource{ + "appConfig": resourceOfType("celerity/config", nil), + "api": resourceOfType("celerity/api", nil), + "getUsers": resourceOfType("celerity/handler", nil), + }) + + assert.Empty(t, ResourceKinds(bp)) +} + +func TestResourceKinds_nilBlueprint(t *testing.T) { + assert.Nil(t, ResourceKinds(nil)) + assert.Nil(t, ResourceKinds(&schema.Blueprint{})) +} + +func TestSQLEngines_sortedAndDeduplicated(t *testing.T) { + bp := blueprintWith(map[string]*schema.Resource{ + "primary": resourceOfType("celerity/sqlDatabase", map[string]*core.MappingNode{ + "engine": stringNode("postgres"), + }), + "replica": resourceOfType("celerity/sqlDatabase", map[string]*core.MappingNode{ + "engine": stringNode("postgres"), + }), + "legacy": resourceOfType("celerity/sqlDatabase", map[string]*core.MappingNode{ + "engine": stringNode("mysql"), + }), + "notADatabase": resourceOfType("celerity/datastore", nil), + }) + + assert.Equal(t, []string{"mysql", "postgres"}, SQLEngines(bp)) +} + +func TestSQLEngines_databaseWithNoDeclaredEngine(t *testing.T) { + bp := blueprintWith(map[string]*schema.Resource{ + "primary": resourceOfType("celerity/sqlDatabase", nil), + }) + assert.Empty(t, SQLEngines(bp)) +} diff --git a/apps/cli/internal/consts/consts.go b/apps/cli/internal/consts/consts.go index 019d64c5..9cbb0648 100644 --- a/apps/cli/internal/consts/consts.go +++ b/apps/cli/internal/consts/consts.go @@ -19,6 +19,10 @@ const ( // LanguageGo is the Go language constant // to be used for initialising and managing go projects. + // + // This is a scaffolding language rather than a runtime prefix. Go handlers + // run on an OS-only runtime, so no runtime identifier starts with "go" and + // this must never be registered as a key in a runtime-prefix map. LanguageGo = "go" // LanguageRust is the Rust language constant @@ -39,6 +43,20 @@ var ( } ) +const ( + // RuntimeOSOnly is the prefix shared by every OS-only runtime identifier. + // + // An OS-only runtime carries no language interpreter. The handlers + // executable is compiled ahead of time and the core runtime starts it as a + // separate process, so the identifier names the base OS rather than a + // language. Which language built the executable is resolved from the + // project, not from this string. + RuntimeOSOnly = "os-only" + + // RuntimeOSOnlyDebian13 is the OS-only runtime built on Debian 13 (trixie). + RuntimeOSOnlyDebian13 = "os-only.debian13" +) + const ( BlueprintSourceFile = "file" BlueprintSourceS3 = "s3" diff --git a/apps/cli/internal/consts/runtime_conventions.go b/apps/cli/internal/consts/runtime_conventions.go index fdbfc11a..148d4d03 100644 --- a/apps/cli/internal/consts/runtime_conventions.go +++ b/apps/cli/internal/consts/runtime_conventions.go @@ -9,7 +9,15 @@ type RuntimeConventions struct { // First match on disk wins. If none exist, the first path is used as the default. DefaultModulePaths []string + // WatchRoots are the directories, relative to the application directory, + // that the watcher walks. Node.js and Python projects keep their handlers + // under src/; a Go module has them at the module root, so this is not a + // constant the watcher can assume. + WatchRoots []string + // WatchExtensions are the file extensions the watcher considers relevant. + // Empty for an OS-only runtime, where the extensions belong to whichever + // language built the handlers executable and come from the toolchain. WatchExtensions []string // WatchSkipDirs are directory names the watcher should skip. @@ -24,34 +32,59 @@ type RuntimeConventions struct { var runtimeConventions = map[string]RuntimeConventions{ LanguageNodeJS: { DefaultModulePaths: []string{"src/app-module.ts", "src/app.module.ts"}, + WatchRoots: []string{"src"}, WatchExtensions: []string{".ts", ".js", ".mjs"}, WatchSkipDirs: []string{"node_modules"}, SupportsExtraction: true, }, LanguagePython: { DefaultModulePaths: []string{"src/app_module.py"}, + WatchRoots: []string{"src"}, WatchExtensions: []string{".py"}, WatchSkipDirs: []string{"__pycache__", ".venv", "venv", ".mypy_cache"}, SupportsExtraction: true, }, - LanguageGo: { - DefaultModulePaths: []string{"main.go"}, - WatchExtensions: []string{".go"}, - WatchSkipDirs: []string{"vendor"}, - SupportsExtraction: false, + // Keyed by the OS-only prefix rather than by a language, because Go + // handlers declare os-only.debian13 and no runtime identifier starts with + // "go". + // + // WatchExtensions is empty and DefaultModulePaths unset because both are + // properties of the language that built the handlers executable, which the + // runtime identifier does not name. The resolved toolchain supplies them. + RuntimeOSOnly: { + WatchRoots: []string{"."}, + WatchSkipDirs: []string{".celerity", "vendor", "target", "node_modules"}, + SupportsExtraction: true, }, } // ConventionsForRuntime returns the RuntimeConventions for the given runtime string. -// The runtime string (e.g. "nodejs24.x", "python3.13") is matched by prefix -// against known language keys. +// The runtime string (e.g. "nodejs24.x", "python3.13", "os-only.debian13") is +// matched by prefix against the known runtime keys. func ConventionsForRuntime(runtime string) (RuntimeConventions, bool) { - for prefix, conv := range runtimeConventions { - if strings.HasPrefix(runtime, prefix) { - return conv, true + return longestPrefixMatch(runtimeConventions, runtime) +} + +// The longest prefix wins rather than the first match, because Go map +// iteration is unordered and a first-match loop over two keys that both prefix +// a runtime identifier picks a different one from run to run. Nothing +// registered today overlaps, which is exactly why the bug would be found long +// after the key that introduced it was added. +func longestPrefixMatch[T any](m map[string]T, runtime string) (T, bool) { + var ( + best T + found bool + longest int + ) + for prefix, value := range m { + if !strings.HasPrefix(runtime, prefix) { + continue + } + if !found || len(prefix) > longest { + best, found, longest = value, true, len(prefix) } } - return RuntimeConventions{}, false + return best, found } // TestConventions defines language-specific defaults for test execution. @@ -85,12 +118,11 @@ var testConventions = map[string]TestConventions{ } // TestConventionsForRuntime returns the TestConventions for the given runtime string. -// Matching works the same as ConventionsForRuntime — by prefix. +// Matching works by longest prefix, the same as ConventionsForRuntime. +// +// There is deliberately no OS-only entry, because one OS-only runtime serves +// Go, Rust, Zig and C++, whose test layouts have nothing in common. The +// directories belong to the resolved toolchain rather than to the runtime. func TestConventionsForRuntime(runtime string) (TestConventions, bool) { - for prefix, conv := range testConventions { - if strings.HasPrefix(runtime, prefix) { - return conv, true - } - } - return TestConventions{}, false + return longestPrefixMatch(testConventions, runtime) } diff --git a/apps/cli/internal/consts/runtime_conventions_test.go b/apps/cli/internal/consts/runtime_conventions_test.go index a456aa75..8bca0af1 100644 --- a/apps/cli/internal/consts/runtime_conventions_test.go +++ b/apps/cli/internal/consts/runtime_conventions_test.go @@ -26,13 +26,44 @@ func TestConventionsForRuntime_python(t *testing.T) { assert.True(t, conv.SupportsExtraction) } -func TestConventionsForRuntime_go(t *testing.T) { - conv, ok := ConventionsForRuntime("go1.22") +func TestConventionsForRuntime_osOnly(t *testing.T) { + conv, ok := ConventionsForRuntime(RuntimeOSOnlyDebian13) assert.True(t, ok) - assert.Equal(t, []string{"main.go"}, conv.DefaultModulePaths) - assert.Contains(t, conv.WatchExtensions, ".go") + assert.Equal(t, []string{"."}, conv.WatchRoots) + assert.Contains(t, conv.WatchSkipDirs, ".celerity") assert.Contains(t, conv.WatchSkipDirs, "vendor") - assert.False(t, conv.SupportsExtraction) + assert.True(t, conv.SupportsExtraction) + // The language that built the handlers executable is not named by the + // runtime identifier, so these come from the toolchain instead. + assert.Empty(t, conv.WatchExtensions) + assert.Empty(t, conv.DefaultModulePaths) +} + +// Go handlers declare an OS-only runtime, so there is no Go runtime identifier +// for a "go"-keyed entry to match against. +func TestConventionsForRuntime_goIsNotARuntime(t *testing.T) { + _, ok := ConventionsForRuntime("go1.22") + assert.False(t, ok) +} + +func TestConventionsForRuntime_nodeAndPythonWatchSrc(t *testing.T) { + for _, runtime := range []string{"nodejs24.x", "python3.13"} { + conv, ok := ConventionsForRuntime(runtime) + assert.True(t, ok, runtime) + assert.Equal(t, []string{"src"}, conv.WatchRoots, runtime) + } +} + +// Map iteration is unordered, so which of two overlapping keys wins must not +// come down to luck. Run it enough times that a first-match implementation +// would be overwhelmingly likely to return the shorter key at least once. +func TestConventionsForRuntime_longestPrefixWins(t *testing.T) { + m := map[string]int{"os": 1, "os-only": 2, "os-only.debian13": 3} + for range 100 { + got, ok := longestPrefixMatch(m, "os-only.debian13") + assert.True(t, ok) + assert.Equal(t, 3, got) + } } func TestConventionsForRuntime_unknown(t *testing.T) { @@ -63,7 +94,9 @@ func TestTestConventionsForRuntime_unknown(t *testing.T) { assert.False(t, ok) } -func TestTestConventionsForRuntime_go_not_supported(t *testing.T) { - _, ok := TestConventionsForRuntime("go1.22") +// Test directories belong to the toolchain for an OS-only runtime, not to the +// runtime, which serves several languages at once. +func TestTestConventionsForRuntime_osOnly_notSupported(t *testing.T) { + _, ok := TestConventionsForRuntime(RuntimeOSOnlyDebian13) assert.False(t, ok) } diff --git a/apps/cli/internal/devconfig/deploy_config.go b/apps/cli/internal/devconfig/deploy_config.go index 49f47753..6eb4ce58 100644 --- a/apps/cli/internal/devconfig/deploy_config.go +++ b/apps/cli/internal/devconfig/deploy_config.go @@ -6,13 +6,20 @@ import ( "os" "regexp" "strings" + + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" ) // deployConfig represents the minimal structure of app.deploy.jsonc. +// +// Read here rather than through internal/deployconfig so that a dev session +// does not depend on the deploy engine's configuration conversion, which +// needs far more of the file than a dev run does. type deployConfig struct { DeployTarget struct { Name string `json:"name"` } `json:"deployTarget"` + HandlerBuild *handlertoolchain.Config `json:"handlerBuild,omitempty"` } // ReadDeployTarget reads the deploy target name from a deploy config file. @@ -64,3 +71,27 @@ func stripJSONCComments(s string) string { s = strings.ReplaceAll(s, ",\n]", "\n]") return s } + +// ReadHandlerBuild reads the handlerBuild block from a deploy config file, +// returning nil where the file declares none. +// +// How a community SDK's handlers executable is built, which for an OS-only +// runtime is the only thing that says what language the application is in. +func ReadHandlerBuild(path string) (*handlertoolchain.Config, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("reading deploy config %s: %w", path, err) + } + + var cfg deployConfig + if err := json.Unmarshal([]byte(stripJSONCComments(string(data))), &cfg); err != nil { + return nil, fmt.Errorf("parsing deploy config %s: %w", path, err) + } + if cfg.HandlerBuild == nil { + return nil, nil + } + if err := cfg.HandlerBuild.Validate(); err != nil { + return nil, fmt.Errorf("deploy config %s: %w", path, err) + } + return cfg.HandlerBuild, nil +} diff --git a/apps/cli/internal/devconfig/resolver.go b/apps/cli/internal/devconfig/resolver.go index 8707f0fa..7d526a5c 100644 --- a/apps/cli/internal/devconfig/resolver.go +++ b/apps/cli/internal/devconfig/resolver.go @@ -12,6 +12,7 @@ import ( "github.com/newstack-cloud/celerity/apps/cli/internal/consts" "github.com/newstack-cloud/celerity/apps/cli/internal/devconfig/resolve" "github.com/newstack-cloud/celerity/apps/cli/internal/docker" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" "github.com/newstack-cloud/celerity/apps/cli/internal/seed" "go.uber.org/zap" @@ -33,6 +34,10 @@ type ResolveOpts struct { Mode string // "run" or "test" Verbose bool LocalAuth bool // true (default) = patch issuer to dev auth sidecar; false = --no-local-auth + // Tracing runs a collector in the session and exports the application's + // spans to it, so a dispatch can be read as a timeline rather than + // reconstructed from log lines. + Tracing bool } // ResolvedConfig is the fully resolved configuration for a dev run. @@ -55,6 +60,14 @@ type ResolvedConfig struct { ModulePath string Port string ServiceName string + // Toolchain builds the handlers executable, and is nil for a runtime that + // hosts the language itself. + Toolchain handlertoolchain.Toolchain + // HandlersExecutable is where the built executable must be written on the + // host for the container to find it. Empty when there is no Toolchain. + HandlersExecutable string + // Telemetry names what traces are exported with, or is empty for none. + Telemetry string } // Resolve assembles the complete configuration by loading the blueprint, @@ -75,6 +88,11 @@ func Resolve(ctx context.Context, opts ResolveOpts, logger *zap.Logger) (*Resolv return nil, err } + deployConfigPath := opts.DeployConfig + if deployConfigPath == "" { + deployConfigPath = FindDeployConfig(appDir) + } + deployTarget, err := resolveDeployTarget(appDir, opts.DeployConfig) if err != nil { return nil, err @@ -95,9 +113,25 @@ func Resolve(ctx context.Context, opts ResolveOpts, logger *zap.Logger) (*Resolv modulePath := resolveModulePath(appDir, opts.ModulePath, runtime) + toolchain, err := resolveToolchain(runtime, appDir, deployConfigPath) + if err != nil { + return nil, err + } + conv, _ := consts.ConventionsForRuntime(runtime) var manifest *preprocess.HandlerManifest - if conv.SupportsExtraction { + switch { + case toolchain != nil: + manifest, err = extractViaToolchain(ctx, toolchain, extractRequest{ + AppDir: appDir, + Blueprint: bp, + DeployTarget: deployTarget, + Telemetry: telemetryFor(opts), + }, logger) + if err != nil { + return nil, err + } + case conv.SupportsExtraction: extractor := preprocess.NewExtractor(preprocess.ExtractorConfig{ Runtime: runtime, ModulePath: modulePath, @@ -107,7 +141,7 @@ func Resolve(ctx context.Context, opts ResolveOpts, logger *zap.Logger) (*Resolv if err != nil { return nil, fmt.Errorf("handler extraction: %w", err) } - } else { + default: logger.Info("handler extraction not available for runtime, using raw blueprint", zap.String("runtime", runtime), ) @@ -178,7 +212,8 @@ func Resolve(ctx context.Context, opts ResolveOpts, logger *zap.Logger) (*Resolv } composeCfg, err := compose.GenerateComposeConfig( - merged, deployTarget, composeProjectPrefix+serviceName, appDir, portOffset, opts.LocalAuth, logger, + merged, deployTarget, composeProjectPrefix+serviceName, appDir, portOffset, + opts.LocalAuth, opts.Tracing, logger, ) if err != nil { return nil, fmt.Errorf("generating compose config: %w", err) @@ -187,8 +222,14 @@ func Resolve(ctx context.Context, opts ResolveOpts, logger *zap.Logger) (*Resolv containerCfg := buildContainerConfig( runtimeImage, serviceName, port, appDir, mergedPath, modulePath, composeCfg, merged, deployTarget, opts.Verbose, + toolchain != nil, ) + handlersExecutable := "" + if toolchain != nil { + handlersExecutable = filepath.Join(appDir, DevHandlersPath) + } + return &ResolvedConfig{ Blueprint: merged, SpecFormat: specFormat, @@ -208,6 +249,9 @@ func Resolve(ctx context.Context, opts ResolveOpts, logger *zap.Logger) (*Resolv ModulePath: modulePath, Port: port, ServiceName: serviceName, + Toolchain: toolchain, + Telemetry: telemetryFor(opts), + HandlersExecutable: handlersExecutable, }, nil } @@ -257,6 +301,17 @@ func resolveSecretsDir(appDir string, mode string) string { return resolve.DirWithTestFallback(appDir, "secrets", mode) } +// telemetryFor reports what the session exports traces with. +// +// Only OpenTelemetry, because that is what every Celerity SDK implements and +// what the collector in the session speaks. +func telemetryFor(opts ResolveOpts) string { + if !opts.Tracing { + return "" + } + return handlertoolchain.TelemetryOTel +} + func deployTargetToProvider(deployTarget string) string { return resolve.DeployTargetToProvider(deployTarget) } @@ -272,6 +327,7 @@ func buildContainerConfig( bp *schema.Blueprint, deployTarget string, verbose bool, + osOnly bool, ) *docker.ContainerConfig { envVars := map[string]string{ "CELERITY_BLUEPRINT": "/opt/celerity/merged.blueprint.yaml", @@ -283,6 +339,10 @@ func buildContainerConfig( "CELERITY_RUNTIME": "true", "CELERITY_LOG_FORMAT": "json", "CELERITY_CONFIG_VALKEY_HOST": "valkey", + // Set whether or not traces are exported. An SDK reads it only once + // exporting is enabled, which keeps the one gate in the compose + // generator beside the collector it needs. + "OTEL_SERVICE_NAME": serviceName, } if verbose { @@ -310,6 +370,17 @@ func buildContainerConfig( envVars["CELERITY_RESOURCE_LINKS"] = linksJSON } + if osOnly { + // The core runtime hosts no language: it starts a pre-compiled + // handlers executable and streams events to it, so it has to be told + // where that executable is. The image defaults to + // /opt/celerity/app/handlers, which is where a derivative image puts + // one; a dev session builds its own under .celerity instead. + envVars["CELERITY_HANDLERS_EXECUTABLE"] = ContainerHandlersExecutable() + // Meaningless without a module to load. The executable is the module. + delete(envVars, "CELERITY_MODULE_PATH") + } + binds := []string{ appDir + ":/opt/celerity/app", mergedBlueprintPath + ":/opt/celerity/merged.blueprint.yaml:ro", @@ -323,7 +394,7 @@ func buildContainerConfig( return &docker.ContainerConfig{ Image: image, ContainerName: "celerity-dev-" + serviceName, - Cmd: []string{"dev"}, + Cmd: containerCmd(osOnly), HostPort: port, ContainerPort: "8080", AppDir: appDir, @@ -332,3 +403,17 @@ func buildContainerConfig( NetworkName: networkName, } } + +// containerCmd is the argument list the runtime image is started with. +// +// The language runtime images have an entrypoint script that takes "dev" and +// installs the application's dependencies before handing over. The core +// runtime has no script and reads no arguments at all, so "dev" there is an +// argument nothing consumes, which is a trap for whoever gives it meaning +// later. +func containerCmd(osOnly bool) []string { + if osOnly { + return nil + } + return []string{"dev"} +} diff --git a/apps/cli/internal/devconfig/toolchain.go b/apps/cli/internal/devconfig/toolchain.go new file mode 100644 index 00000000..9d965286 --- /dev/null +++ b/apps/cli/internal/devconfig/toolchain.go @@ -0,0 +1,177 @@ +package devconfig + +import ( + "context" + "fmt" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/newstack-cloud/celerity/apps/cli/internal/blueprint" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" + "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" + "go.uber.org/zap" +) + +const ( + // DevHandlersPath is where a dev session's handlers executable is built, + // relative to the application directory. + // + // Under .celerity because the application directory is already bind + // mounted into the container, so an executable written there needs no + // mount of its own, and .celerity is the directory the CLI already owns + // and projects already ignore. + DevHandlersPath = ".celerity/dev/handlers" + + // containerAppDir is where the application directory is mounted. + containerAppDir = "/opt/celerity/app" +) + +// ContainerHandlersExecutable is the path the core runtime starts, as seen +// from inside the container. +func ContainerHandlersExecutable() string { + return containerAppDir + "/" + DevHandlersPath +} + +// resolveToolchain resolves the build tooling for an OS-only runtime, reading +// the handlerBuild block from the deploy config where there is one. +func resolveToolchain(runtime, appDir, deployConfigPath string) (handlertoolchain.Toolchain, error) { + if !handlertoolchain.IsOSOnly(runtime) { + return nil, nil + } + + var handlerBuild *handlertoolchain.Config + if deployConfigPath != "" { + var err error + handlerBuild, err = ReadHandlerBuild(deployConfigPath) + if err != nil { + return nil, err + } + } + + return handlertoolchain.Resolve(handlertoolchain.Options{ + Runtime: runtime, + AppDir: appDir, + Config: handlerBuild, + }) +} + +// extractRequest is what a toolchain needs to report an application's +// handlers. +type extractRequest struct { + AppDir string + Blueprint *schema.Blueprint + DeployTarget string + // Telemetry names what traces are exported with, or is empty for none. + // + // Carried here rather than read where Prepare is called, because the + // watcher re-prepares on every change through an extractor built from the + // resolved config. Left out of it, a session that started with tracing + // would regenerate without it on the first file saved and stop exporting + // with nothing said. + Telemetry string +} + +// extractViaToolchain prepares the project for a dev session and reports what +// its handlers executable serves. +func extractViaToolchain( + ctx context.Context, + toolchain handlertoolchain.Toolchain, + req extractRequest, + logger *zap.Logger, +) (*preprocess.HandlerManifest, error) { + // ModeDev, so the executable links what a local session reads: its own + // config store and the emulator clients a deployed artefact must not + // carry. + err := toolchain.Prepare(ctx, handlertoolchain.PrepareParams{ + AppDir: req.AppDir, + DeployTarget: req.DeployTarget, + Mode: handlertoolchain.ModeDev, + ResourceKinds: blueprint.ResourceKinds(req.Blueprint), + SQLEngines: blueprint.SQLEngines(req.Blueprint), + Telemetry: req.Telemetry, + // The session this prepares for is the one `celerity dev test` runs + // its integration suites against, and those suites reach the session's + // own resources through the same provider the application does. + TestPackages: true, + }) + if err != nil { + return nil, fmt.Errorf("preparing the %s toolchain: %w", toolchain.Name(), err) + } + + manifest, err := toolchain.Extract(ctx, handlertoolchain.ExtractParams{AppDir: req.AppDir}) + if err != nil { + return nil, fmt.Errorf("handler extraction: %w", err) + } + if manifest == nil { + logger.Info("the toolchain does not extract handlers, using raw blueprint", + zap.String("toolchain", toolchain.Name()), + ) + return &preprocess.HandlerManifest{Version: preprocess.ManifestVersion}, nil + } + return manifest, nil +} + +// BuildDevHandlers builds the handlers executable a dev session runs. +// +// arch is the architecture the container runs at, which is the Docker daemon's +// rather than the CLI's: the two differ on a remote context or a Linux VM, and +// an executable built for the wrong one is refused by the kernel with nothing +// to say why. +func BuildDevHandlers( + ctx context.Context, + cfg *ResolvedConfig, + arch string, +) error { + if cfg.Toolchain == nil { + return nil + } + + err := cfg.Toolchain.BuildBinary(ctx, handlertoolchain.BinaryParams{ + AppDir: cfg.AppDir, + OS: "linux", + Arch: arch, + OutputPath: cfg.HandlersExecutable, + DeployTarget: cfg.DeployTarget, + Mode: handlertoolchain.ModeDev, + }) + if err != nil { + return fmt.Errorf("building the handlers executable: %w", err) + } + + return handlertoolchain.CheckArchitecture(cfg.HandlersExecutable, arch) +} + +// ToolchainExtractor reports an application's handlers through its toolchain. +// +// A thin adapter so a dev session's watcher can re-extract the same way it +// first did, without holding the resolved config or knowing which toolchain +// answered. +type ToolchainExtractor struct { + toolchain handlertoolchain.Toolchain + req extractRequest + logger *zap.Logger +} + +// NewToolchainExtractor returns an extractor for a resolved dev session. +func NewToolchainExtractor(cfg *ResolvedConfig) *ToolchainExtractor { + return &ToolchainExtractor{ + toolchain: cfg.Toolchain, + req: extractRequest{ + AppDir: cfg.AppDir, + Blueprint: cfg.Blueprint, + DeployTarget: cfg.DeployTarget, + Telemetry: cfg.Telemetry, + }, + logger: zap.NewNop(), + } +} + +// WithLogger returns the extractor reporting through the given logger. +func (e *ToolchainExtractor) WithLogger(logger *zap.Logger) *ToolchainExtractor { + e.logger = logger + return e +} + +// Extract reports the handlers the application serves. +func (e *ToolchainExtractor) Extract(ctx context.Context) (*preprocess.HandlerManifest, error) { + return extractViaToolchain(ctx, e.toolchain, e.req, e.logger) +} diff --git a/apps/cli/internal/devconfig/toolchain_test.go b/apps/cli/internal/devconfig/toolchain_test.go new file mode 100644 index 00000000..5d71258b --- /dev/null +++ b/apps/cli/internal/devconfig/toolchain_test.go @@ -0,0 +1,151 @@ +package devconfig + +import ( + "os" + "path/filepath" + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/newstack-cloud/celerity/apps/cli/internal/consts" + "github.com/newstack-cloud/celerity/apps/cli/internal/docker" + "github.com/stretchr/testify/suite" +) + +type DevToolchainSuite struct { + suite.Suite + appDir string +} + +func (s *DevToolchainSuite) SetupTest() { s.appDir = s.T().TempDir() } + +func (s *DevToolchainSuite) writeDeployConfig(contents string) string { + path := filepath.Join(s.appDir, "app.deploy.jsonc") + s.Require().NoError(os.WriteFile(path, []byte(contents), 0o644)) + return path +} + +func (s *DevToolchainSuite) Test_ReadHandlerBuild_absent_block_is_not_an_error() { + path := s.writeDeployConfig(`{"appName":"app","deployTarget":{"name":"aws"}}`) + + cfg, err := ReadHandlerBuild(path) + s.Require().NoError(err) + s.Assert().Nil(cfg) +} + +func (s *DevToolchainSuite) Test_ReadHandlerBuild_reads_the_block_through_comments() { + path := s.writeDeployConfig(`{ + // The deploy target this app goes to. + "appName": "app", + "deployTarget": { "name": "aws" }, + "handlerBuild": { + "command": "cargo build --release", + "binary": "target/release/handlers", + "watchExtensions": [".rs"], + "test": { "unit": "cargo test" } + } + }`) + + cfg, err := ReadHandlerBuild(path) + s.Require().NoError(err) + s.Require().NotNil(cfg) + s.Assert().Equal("cargo build --release", cfg.Command) + s.Assert().Equal("target/release/handlers", cfg.Binary) + s.Assert().Equal([]string{".rs"}, cfg.WatchExtensions) + s.Assert().Equal("cargo test", cfg.Test["unit"]) +} + +func (s *DevToolchainSuite) Test_ReadHandlerBuild_reports_an_incomplete_block() { + path := s.writeDeployConfig(`{"deployTarget":{"name":"aws"},"handlerBuild":{"command":"make"}}`) + + _, err := ReadHandlerBuild(path) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "handlerBuild.binary") +} + +func (s *DevToolchainSuite) Test_resolveToolchain_is_nothing_for_a_hosted_language() { + tc, err := resolveToolchain("nodejs24.x", s.appDir, "") + s.Require().NoError(err) + s.Assert().Nil(tc) +} + +func (s *DevToolchainSuite) Test_resolveToolchain_uses_the_handler_build_block() { + path := s.writeDeployConfig(`{ + "deployTarget": {"name":"aws"}, + "handlerBuild": {"command":"make","binary":"out/handlers"} + }`) + + tc, err := resolveToolchain(consts.RuntimeOSOnlyDebian13, s.appDir, path) + s.Require().NoError(err) + s.Require().NotNil(tc) + s.Assert().Equal("custom", tc.Name()) +} + +func (s *DevToolchainSuite) Test_resolveToolchain_infers_a_go_project() { + s.Require().NoError(os.WriteFile( + filepath.Join(s.appDir, "go.mod"), + []byte("module example.com/app\n\nrequire github.com/newstack-cloud/celerity-go-sdk v0.1.0\n"), + 0o644)) + + tc, err := resolveToolchain(consts.RuntimeOSOnlyDebian13, s.appDir, "") + s.Require().NoError(err) + s.Require().NotNil(tc) + s.Assert().Equal("go", tc.Name()) +} + +// The application directory is already mounted, so the executable needs no +// mount of its own. +func (s *DevToolchainSuite) Test_the_container_path_sits_under_the_mounted_app_dir() { + s.Assert().Equal("/opt/celerity/app/.celerity/dev/handlers", ContainerHandlersExecutable()) +} + +type OSOnlyContainerSuite struct { + suite.Suite +} + +// emptyBlueprint is a blueprint with no resources, which is enough for the +// container config: what it reads from one is per-resource config store ids. +func emptyBlueprint() *schema.Blueprint { + return &schema.Blueprint{Resources: &schema.ResourceMap{Values: map[string]*schema.Resource{}}} +} + +func (s *OSOnlyContainerSuite) containerConfig(osOnly bool, modulePath string) *docker.ContainerConfig { + return buildContainerConfig( + "ghcr.io/newstack-cloud/celerity-runtime-core:dev-0.3.0", + "orders", "8080", "/app", "/opt/celerity/merged.blueprint.yaml", + modulePath, nil, emptyBlueprint(), "aws", false, osOnly, + ) +} + +func (s *OSOnlyContainerSuite) config(osOnly bool) map[string]string { + return s.containerConfig(osOnly, "main.go").EnvVars +} + +// The core runtime has to be told where the executable it starts lives: the +// image default is where a derivative image puts one, not where a dev session +// builds one. +func (s *OSOnlyContainerSuite) Test_os_only_is_told_where_the_executable_is() { + env := s.config(true) + s.Assert().Equal(ContainerHandlersExecutable(), env["CELERITY_HANDLERS_EXECUTABLE"]) +} + +// There is no module to load; the executable is the module. +func (s *OSOnlyContainerSuite) Test_os_only_has_no_module_path() { + s.Assert().NotContains(s.config(true), "CELERITY_MODULE_PATH") + s.Assert().Contains(s.config(false), "CELERITY_MODULE_PATH") +} + +// The core runtime reads no arguments, so "dev" is an argument nothing +// consumes. +func (s *OSOnlyContainerSuite) Test_os_only_is_started_with_no_arguments() { + s.Assert().Nil(s.containerConfig(true, "main.go").Cmd) + s.Assert().Equal([]string{"dev"}, s.containerConfig(false, "src/app.module.ts").Cmd) +} + +// The blueprint is mounted outside the app directory, so the image default +// does not point at it. +func (s *OSOnlyContainerSuite) Test_the_blueprint_path_is_where_the_cli_mounts_it() { + s.Assert().Equal("/opt/celerity/merged.blueprint.yaml", s.config(true)["CELERITY_BLUEPRINT"]) +} + +func TestDevToolchainSuite(t *testing.T) { suite.Run(t, new(DevToolchainSuite)) } +func TestOSOnlyContainerSuite(t *testing.T) { suite.Run(t, new(OSOnlyContainerSuite)) } diff --git a/apps/cli/internal/devrun/orchestrator.go b/apps/cli/internal/devrun/orchestrator.go index 01d8c075..b75978f8 100644 --- a/apps/cli/internal/devrun/orchestrator.go +++ b/apps/cli/internal/devrun/orchestrator.go @@ -12,10 +12,13 @@ import ( "github.com/newstack-cloud/bluelink/libs/blueprint/schema" "github.com/newstack-cloud/celerity/apps/cli/internal/blueprint" + "runtime" + "github.com/newstack-cloud/celerity/apps/cli/internal/compose" "github.com/newstack-cloud/celerity/apps/cli/internal/devlogs" "github.com/newstack-cloud/celerity/apps/cli/internal/devstate" "github.com/newstack-cloud/celerity/apps/cli/internal/docker" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" "github.com/newstack-cloud/celerity/apps/cli/internal/seed" "github.com/newstack-cloud/celerity/apps/cli/internal/sqlschema" @@ -44,6 +47,12 @@ type OrchestratorConfig struct { Manifest *preprocess.HandlerManifest ContainerCfg *docker.ContainerConfig ComposeCfg *compose.ComposeConfig + + // Toolchain builds the handlers executable, and is nil for a runtime that + // hosts the language itself. + Toolchain handlertoolchain.Toolchain + // HandlersExecutable is where that executable is written on the host. + HandlersExecutable string } // Orchestrator manages the full dev run lifecycle. @@ -51,7 +60,7 @@ type Orchestrator struct { config OrchestratorConfig docker docker.RuntimeContainerManager compose *compose.ComposeManager - extractor *preprocess.Extractor + extractor Extractor output *Output logger *zap.Logger @@ -64,7 +73,7 @@ func NewOrchestrator( config OrchestratorConfig, dockerMgr docker.RuntimeContainerManager, composeMgr *compose.ComposeManager, - extractor *preprocess.Extractor, + extractor Extractor, output *Output, logger *zap.Logger, ) *Orchestrator { @@ -96,16 +105,13 @@ func (o *Orchestrator) RunForeground(ctx context.Context) error { ctx, cancel := context.WithCancel(ctx) defer cancel() - // Start file watcher in background. go o.startWatcher(ctx) - // Stream logs in background. logDone := make(chan error, 1) go func() { logDone <- o.streamLogs(ctx) }() - // Wait for shutdown signal or log stream end. sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) @@ -166,12 +172,12 @@ func (o *Orchestrator) Shutdown(ctx context.Context) error { } // DumpLogs syncs all container logs to files in .celerity/logs/ before teardown. -// This is called by `dev test` so logs are preserved after the environment is torn down. -// Returns the log directory path, or empty string if no logs were written. +// This is called by `dev test` so logs are preserved after the environment is +// torn down. It returns the log directory path, whether or not anything was +// written to it. func (o *Orchestrator) DumpLogs(ctx context.Context) string { logDir := filepath.Join(celerityDir(o.config.AppDir), "logs") - // Dump compose service logs (datastore, stubs, valkey, etc.) o.dumpComposeLogs(ctx, logDir) if o.containerID == "" { @@ -205,8 +211,6 @@ func (o *Orchestrator) DumpLogs(ctx context.Context) string { return result.LogDir } -// dumpComposeLogs writes each compose service's logs to a separate file -// in the log directory (e.g. stubs.log, datastore.log, valkey.log). func (o *Orchestrator) dumpComposeLogs(ctx context.Context, logDir string) { if o.compose == nil { return @@ -586,21 +590,21 @@ func (o *Orchestrator) applySqlSchemas( zap.String("migrationsPath", db.MigrationsPath), ) - // Create the database if it doesn't exist (using admin connection). if err := applier.EnsureDatabase(ctx, db.Name); err != nil { return fmt.Errorf("ensuring database %s: %w", db.Name, err) } - // Connect to the target database for schema + migration application. dbApplier, err := applier.ForDatabase(db.Name) if err != nil { return fmt.Errorf("connecting to database %s: %w", db.Name, err) } - if err := dbApplier.ApplyAll(ctx, db.SchemaPath, db.MigrationsPath, db.Engine); err != nil { + if err := dbApplier.Apply(ctx, db.SchemaPath, db.MigrationsPath, db.Engine); err != nil { dbApplier.Close() return fmt.Errorf("applying schema for database %s: %w", db.Name, err) } dbApplier.Close() + + o.warnOnUncommittedSchemaChanges(ctx, applier, db) } o.output.PrintStep(fmt.Sprintf("SQL schemas applied (%d databases)", len(dbResources))) @@ -703,9 +707,8 @@ func (o *Orchestrator) createSQLSeeder( }, nil } -// sqlSeederAdapter adapts sqlschema.Applier to the seed.SQLSeeder interface. -// It uses the admin Applier to derive per-database connections on demand, -// caching them for the lifetime of the seed run. +// Per-database connections are derived from the admin Applier on demand and +// cached for the lifetime of the seed run. type sqlSeederAdapter struct { admin *sqlschema.Applier conns map[string]*sqlschema.Applier @@ -797,6 +800,19 @@ func (o *Orchestrator) printSeedSummary(result *seed.SeedResult) { } func (o *Orchestrator) startContainer(ctx context.Context) error { + // Built before the container is created rather than after. The core + // runtime starts the executable itself as soon as it is serving, and + // exits non-zero when it is not there, so a container started first would + // race the build and usually lose. + if o.config.Toolchain != nil { + o.output.PrintProgress("Building handlers executable...") + if err := o.buildHandlersExecutable(ctx); err != nil { + o.output.PrintError("Failed to build the handlers executable", err) + return err + } + o.output.PrintStep("Handlers executable built") + } + o.output.PrintProgress("Starting container...") if err := o.docker.CleanupStale(ctx, o.config.ContainerCfg.ContainerName); err != nil { o.logger.Warn("stale container cleanup failed", zap.Error(err)) @@ -810,6 +826,9 @@ func (o *Orchestrator) startContainer(ctx context.Context) error { o.containerID = containerID o.output.PrintStep(fmt.Sprintf("Container started (%s)", o.config.ContainerCfg.ContainerName)) + if o.config.ComposeCfg != nil && o.config.ComposeCfg.TracingUIURL != "" { + o.output.PrintInfo(fmt.Sprintf("Traces: %s", o.config.ComposeCfg.TracingUIURL)) + } return nil } @@ -836,6 +855,12 @@ func (o *Orchestrator) startWatcher(ctx context.Context) { return } + var watchPaths *handlertoolchain.WatchPaths + if o.config.Toolchain != nil { + paths := o.config.Toolchain.WatchPaths() + watchPaths = &paths + } + watcher := NewHandlerWatcher(WatcherConfig{ AppDir: o.config.AppDir, Runtime: o.config.Runtime, @@ -846,6 +871,8 @@ func (o *Orchestrator) startWatcher(ctx context.Context) { ContainerID: o.containerID, Output: o.output, Logger: o.logger, + Rebuild: o.rebuildHandlers(), + WatchPaths: watchPaths, }, o.manifest) if err := watcher.Watch(ctx); err != nil { @@ -926,7 +953,6 @@ func HandleStaleState( ) } - // For detached mode, check if container is still running. if state.Detached && state.ContainerID != "" { running, _ := dockerMgr.IsRunning(ctx, state.ContainerID) if running { @@ -1006,7 +1032,105 @@ func LoadStateForCommand(appDir string) (*devstate.DevState, error) { return state, nil } -// celerityDir returns the .celerity directory path. func celerityDir(appDir string) string { return filepath.Join(appDir, ".celerity") } + +// Nil where the runtime hosts the language itself and there is nothing to +// build. +func (o *Orchestrator) rebuildHandlers() func(context.Context) error { + if o.config.Toolchain == nil { + return nil + } + return func(ctx context.Context) error { + return o.buildHandlersExecutable(ctx) + } +} + +// Compiles the application for the architecture the container runs at, which is +// the Docker daemon's rather than this machine's for the reasons set out on +// docker.DaemonArchitecture. +func (o *Orchestrator) buildHandlersExecutable(ctx context.Context) error { + arch, err := o.containerArchitecture(ctx) + if err != nil { + return err + } + + o.logger.Info("building the handlers executable", + zap.String("toolchain", o.config.Toolchain.Name()), + zap.String("arch", arch), + ) + + err = o.config.Toolchain.BuildBinary(ctx, handlertoolchain.BinaryParams{ + AppDir: o.config.AppDir, + OS: "linux", + Arch: arch, + OutputPath: o.config.HandlersExecutable, + DeployTarget: o.config.DeployTarget, + Mode: handlertoolchain.ModeDev, + }) + if err != nil { + return fmt.Errorf("building the handlers executable: %w", err) + } + + return handlertoolchain.CheckArchitecture(o.config.HandlersExecutable, arch) +} + +// Falls back to this machine's architecture where the daemon does not report +// one, which also covers a manager that does not implement the interface. +func (o *Orchestrator) containerArchitecture(ctx context.Context) (string, error) { + type architectureReporter interface { + DaemonArchitecture(ctx context.Context) (string, error) + } + + reporter, ok := o.docker.(architectureReporter) + if !ok { + return runtime.GOARCH, nil + } + + arch, err := reporter.DaemonArchitecture(ctx) + if err != nil { + o.logger.Warn("could not read the Docker daemon architecture, using this machine's", + zap.String("arch", runtime.GOARCH), + zap.Error(err), + ) + return runtime.GOARCH, nil + } + return arch, nil +} + +// Warns when the schema YAML has moved ahead of the committed migrations. The +// local database is built from the migration history alone, so those edits are +// not present in it until `celerity schema diff` captures them. +// +// The check is advisory, so a failure to run it, for want of room for a scratch +// database say, must not stop the dev environment coming up. +func (o *Orchestrator) warnOnUncommittedSchemaChanges( + ctx context.Context, + applier *sqlschema.Applier, + db sqlschema.DatabaseResource, +) { + pending, err := applier.HasUncommittedSchemaChanges( + ctx, db.SchemaPath, db.MigrationsPath, db.Engine, scratchDBName(db.Name), + ) + if err != nil { + o.logger.Debug("could not check for uncommitted schema changes", + zap.String("database", db.Name), zap.Error(err)) + return + } + if !pending { + return + } + + o.output.PrintWarning(fmt.Sprintf( + "Schema YAML for %q has changes with no committed migration. The local database "+ + "was built from the migration history, so they are not applied. "+ + "Run `celerity schema diff` to capture them.", db.Name, + ), nil) +} + +// Names the throwaway database the uncommitted-changes check replays +// migrations into, created and dropped within a single check. +func scratchDBName(dbName string) string { + return dbName + "_celerity_dev_check" +} diff --git a/apps/cli/internal/devrun/stubs.go b/apps/cli/internal/devrun/stubs.go index 760a01d6..844e07f0 100644 --- a/apps/cli/internal/devrun/stubs.go +++ b/apps/cli/internal/devrun/stubs.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "net/http" + "strings" "time" "github.com/newstack-cloud/celerity/apps/cli/internal/compose" @@ -12,15 +13,18 @@ import ( "go.uber.org/zap" ) -// loadStubs loads mountebank imposters and seeds stub service URLs into -// the config namespace. This runs after startDependencies (mountebank is -// healthy) and before seedData. +// Runs after startDependencies, so mountebank is already healthy, and before +// seedData. // -// When hostMode is true (integration tests), stub URLs are seeded as -// localhost addresses since the test process runs on the host. -// When false (full/API mode), URLs use Docker network addresses since -// the app container runs on the compose network. +// With hostMode set, for integration tests, stub URLs are seeded as localhost +// addresses because the test process runs on the host. Without it, for full and +// API mode, they use Docker network addresses reachable from the app container +// on the compose network. func (o *Orchestrator) loadStubs(ctx context.Context, hostMode bool) error { + if o.config.ComposeCfg == nil { + return nil + } + stubServices := o.config.ComposeCfg.StubServices if len(stubServices) == 0 { return nil @@ -32,13 +36,11 @@ func (o *Orchestrator) loadStubs(ctx context.Context, hostMode bool) error { return nil } - // Wait for mountebank to be ready. if err := waitForMountebank(ctx, mbAPIURL); err != nil { o.output.PrintWarning("Mountebank not ready", err) return nil } - // Load imposters from stub files. loaded, err := devstubs.LoadStubs(o.config.AppDir) if err != nil { o.output.PrintWarning("Failed to load stubs for imposters", err) @@ -75,14 +77,12 @@ func (o *Orchestrator) seedStubConfigValues(ctx context.Context, stubServices [] } defer seeder.Close() + configs := seed.CollectConfigResources(o.config.Blueprint) + for _, svc := range stubServices { - namespace := svc.ConfigNamespace - if namespace == "" { - // Default to the first config resource's store name. - configs := seed.CollectConfigResources(o.config.Blueprint) - if len(configs) > 0 { - namespace = configs[0].StoreName - } + namespace, err := resolveStubConfigNamespace(svc, configs) + if err != nil { + return err } if namespace == "" { o.logger.Warn("no config namespace for stub service, skipping config seed", @@ -93,10 +93,10 @@ func (o *Orchestrator) seedStubConfigValues(ctx context.Context, stubServices [] var url string if hostMode { - // Host URL — integration tests run on the host. + // Integration tests run on the host. url = fmt.Sprintf("http://localhost:%d", svc.HostPort) } else { - // Docker network URL — the app container resolves "stubs" via compose DNS. + // The app container resolves "stubs" through compose DNS. url = fmt.Sprintf("http://%s:%d", compose.ServiceNameStubs, svc.Port) } values := map[string]string{svc.ConfigKey: url} @@ -141,3 +141,52 @@ func waitForMountebank(ctx context.Context, baseURL string) error { return fmt.Errorf("mountebank not ready at %s after 15s", baseURL) } + +// A declared namespace wins, matched against the application's config resources +// by either the blueprint resource name or the store name, so an author can name +// whichever they think of it by. +// +// With nothing declared and exactly one config resource there is no choice to +// make, so that one is used. With several this is an error rather than a guess, +// because picking one seeds the URL into a store the application never reads and +// the only symptom is requests going to the real endpoint instead of the stub, a +// long way from the blueprint that caused it. +func resolveStubConfigNamespace( + svc compose.StubServiceInfo, + configs []seed.ConfigResourceInfo, +) (string, error) { + if declared := svc.ConfigNamespace; declared != "" { + for _, cfg := range configs { + if cfg.ResourceName == declared || cfg.StoreName == declared { + return cfg.StoreName, nil + } + } + // Named a store this application does not declare. Passed through + // rather than refused, since a store can exist without the blueprint + // describing it. + return declared, nil + } + + switch len(configs) { + case 0: + // Nothing to seed into. The caller skips the service. + return "", nil + case 1: + return configs[0].StoreName, nil + default: + return "", fmt.Errorf( + "stub service %q does not say which config store its URL belongs in, and this "+ + "application has %d: %s.\n"+ + "Set configNamespace on the stub service to one of them", + svc.Name, len(configs), strings.Join(configStoreNames(configs), ", "), + ) + } +} + +func configStoreNames(configs []seed.ConfigResourceInfo) []string { + names := make([]string, 0, len(configs)) + for _, cfg := range configs { + names = append(names, cfg.StoreName) + } + return names +} diff --git a/apps/cli/internal/devrun/stubs_test.go b/apps/cli/internal/devrun/stubs_test.go new file mode 100644 index 00000000..09f95eff --- /dev/null +++ b/apps/cli/internal/devrun/stubs_test.go @@ -0,0 +1,65 @@ +package devrun + +import ( + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/compose" + "github.com/newstack-cloud/celerity/apps/cli/internal/seed" + "github.com/stretchr/testify/suite" +) + +type StubsTestSuite struct { + suite.Suite +} + +func TestStubsTestSuite(t *testing.T) { + suite.Run(t, new(StubsTestSuite)) +} + +func (s *StubsTestSuite) Test_declared_namespace_wins() { + svc := compose.StubServiceInfo{ + Name: "enrichment-service", + ConfigKey: "ENRICHMENT_SERVICE_BASE_URL", + ConfigNamespace: "appConfig", + } + configs := []seed.ConfigResourceInfo{ + {ResourceName: "appConfig", StoreName: "appConfig"}, + {ResourceName: "appConfig2", StoreName: "appConfig2"}, + } + + namespace, err := resolveStubConfigNamespace(svc, configs) + s.Require().NoError(err) + s.Assert().Equal("appConfig", namespace) +} + +func (s *StubsTestSuite) Test_single_config_resource_is_used_by_default() { + svc := compose.StubServiceInfo{Name: "enrichment-service", ConfigKey: "BASE_URL"} + configs := []seed.ConfigResourceInfo{{ResourceName: "appConfig", StoreName: "app-config"}} + + namespace, err := resolveStubConfigNamespace(svc, configs) + s.Require().NoError(err) + s.Assert().Equal("app-config", namespace) +} + +func (s *StubsTestSuite) Test_several_config_resources_without_a_declared_namespace_is_an_error() { + // Guessing here silently seeds the URL into a store the application never + // reads, which only shows up later as requests going to the real endpoint. + svc := compose.StubServiceInfo{Name: "enrichment-service", ConfigKey: "ENRICHMENT_SERVICE_BASE_URL"} + configs := []seed.ConfigResourceInfo{ + {ResourceName: "appConfig", StoreName: "appConfig"}, + {ResourceName: "appConfig2", StoreName: "appConfig2"}, + } + + _, err := resolveStubConfigNamespace(svc, configs) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "configNamespace") + s.Assert().Contains(err.Error(), "appConfig2", "the error must name the candidate stores") +} + +func (s *StubsTestSuite) Test_no_config_resources_skips_seeding() { + svc := compose.StubServiceInfo{Name: "enrichment-service", ConfigKey: "BASE_URL"} + + namespace, err := resolveStubConfigNamespace(svc, nil) + s.Require().NoError(err) + s.Assert().Empty(namespace) +} diff --git a/apps/cli/internal/devrun/watcher.go b/apps/cli/internal/devrun/watcher.go index e92b5fa1..b3c9a2e5 100644 --- a/apps/cli/internal/devrun/watcher.go +++ b/apps/cli/internal/devrun/watcher.go @@ -12,6 +12,7 @@ import ( "github.com/newstack-cloud/bluelink/libs/blueprint/schema" "github.com/newstack-cloud/celerity/apps/cli/internal/consts" "github.com/newstack-cloud/celerity/apps/cli/internal/docker" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" "go.uber.org/zap" ) @@ -24,13 +25,33 @@ const ( type WatcherConfig struct { AppDir string Runtime string - Extractor *preprocess.Extractor + Extractor Extractor Blueprint *schema.Blueprint SpecFormat schema.SpecFormat Docker docker.RuntimeContainerManager ContainerID string Output *Output Logger *zap.Logger + // Rebuild rebuilds the handlers executable, and is nil for a runtime that + // hosts the language itself. Its presence is also what makes any source + // change worth a restart, rather than only a changed handler set. + Rebuild func(ctx context.Context) error + + // WatchPaths is what the resolved toolchain reports as worth watching, and + // is nil for a runtime that hosts the language itself. It has to come from + // the toolchain for an OS-only runtime, whose identifier names no + // extensions and whose conventions carry none, leaving every change + // irrelevant if they were used instead. + WatchPaths *handlertoolchain.WatchPaths +} + +// Extractor reports the handlers an application serves. +// +// An interface rather than *preprocess.Extractor because for an OS-only +// runtime extraction belongs to whichever toolchain built the executable, and +// the dev session has one of those instead. +type Extractor interface { + Extract(ctx context.Context) (*preprocess.HandlerManifest, error) } // HandlerWatcher watches the source directory for handler changes @@ -51,9 +72,9 @@ func NewHandlerWatcher(config WatcherConfig, initialManifest *preprocess.Handler // Watch starts watching the source directory for file changes. // Blocks until the context is cancelled. func (w *HandlerWatcher) Watch(ctx context.Context) error { - conv, ok := consts.ConventionsForRuntime(w.config.Runtime) + paths, ok := w.watchPaths() if !ok { - w.config.Logger.Debug("no conventions for runtime, skipping watcher", + w.config.Logger.Debug("nothing says what to watch, skipping watcher", zap.String("runtime", w.config.Runtime), ) return nil @@ -65,9 +86,19 @@ func (w *HandlerWatcher) Watch(ctx context.Context) error { } defer watcher.Close() - srcDir := filepath.Join(w.config.AppDir, "src") - if err := addWatchRecursive(watcher, srcDir, conv.WatchSkipDirs); err != nil { - w.config.Logger.Debug("cannot watch src directory", zap.Error(err)) + watched := 0 + for _, root := range paths.Roots { + dir := filepath.Join(w.config.AppDir, root) + if err := addWatchRecursive(watcher, dir, paths.SkipDirs); err != nil { + w.config.Logger.Debug("cannot watch directory", + zap.String("dir", dir), + zap.Error(err), + ) + continue + } + watched++ + } + if watched == 0 { return nil } @@ -82,7 +113,7 @@ func (w *HandlerWatcher) Watch(ctx context.Context) error { if !ok { return nil } - if !isRelevantChange(event, conv.WatchExtensions) { + if !isRelevantChange(event, paths) { continue } if debounceTimer != nil { @@ -102,28 +133,45 @@ func (w *HandlerWatcher) Watch(ctx context.Context) error { } func (w *HandlerWatcher) handleChange(ctx context.Context) { + // Rebuilt before anything else, and the container left alone when it + // fails. A compiled application that no longer compiles should leave the + // last working build serving rather than take the session down. + if w.config.Rebuild != nil { + w.config.Output.PrintInfo("[watcher] Change detected, rebuilding...") + if err := w.config.Rebuild(ctx); err != nil { + w.config.Output.PrintWarning("Rebuild failed, leaving the running build in place", err) + return + } + } + manifest, err := w.config.Extractor.Extract(ctx) if err != nil { w.config.Logger.Warn("re-extraction failed", zap.Error(err)) return } - if w.lastManifest.Equal(manifest) { - return - } - - w.config.Output.PrintInfo("[watcher] Handler change detected, restarting container...") + handlersChanged := !w.lastManifest.Equal(manifest) - merged, err := preprocess.Merge(w.config.Blueprint, manifest, w.config.Logger) - if err != nil { - w.config.Logger.Warn("re-merge failed", zap.Error(err)) + // An interpreted runtime picks up changed source on its own, so only a + // changed handler set is worth a restart. A rebuilt executable is a new + // file the running container is not executing, so it always is. + if !handlersChanged && w.config.Rebuild == nil { return } - outputDir := filepath.Join(w.config.AppDir, ".celerity") - if _, err := preprocess.WriteMerged(merged, w.config.SpecFormat, outputDir); err != nil { - w.config.Logger.Warn("writing merged blueprint failed", zap.Error(err)) - return + if handlersChanged { + merged, err := preprocess.Merge(w.config.Blueprint, manifest, w.config.Logger) + if err != nil { + w.config.Logger.Warn("re-merge failed", zap.Error(err)) + return + } + + outputDir := filepath.Join(w.config.AppDir, ".celerity") + if _, err := preprocess.WriteMerged(merged, w.config.SpecFormat, outputDir); err != nil { + w.config.Logger.Warn("writing merged blueprint failed", zap.Error(err)) + return + } + w.config.Blueprint = merged } if err := w.config.Docker.RestartContainer(ctx, w.config.ContainerID); err != nil { @@ -132,16 +180,49 @@ func (w *HandlerWatcher) handleChange(ctx context.Context) { } w.lastManifest = manifest - w.config.Blueprint = merged w.config.Output.PrintStep("Container restarted") } -func isRelevantChange(event fsnotify.Event, watchExtensions []string) bool { +// The toolchain paths are preferred over the runtime conventions. An OS-only +// runtime identifier names a base operating system and nothing about what +// compiled the executable, so its conventions carry no extensions and a +// session resolved from them treats every change as irrelevant. +func (w *HandlerWatcher) watchPaths() (handlertoolchain.WatchPaths, bool) { + if w.config.WatchPaths != nil { + paths := *w.config.WatchPaths + if len(paths.Roots) > 0 && len(paths.Extensions) > 0 { + return paths, true + } + } + + conv, ok := consts.ConventionsForRuntime(w.config.Runtime) + if !ok || len(conv.WatchExtensions) == 0 { + return handlertoolchain.WatchPaths{}, false + } + + roots := conv.WatchRoots + if len(roots) == 0 { + roots = []string{"src"} + } + // SkipFiles is left empty deliberately. It exists so a toolchain can skip + // the file its own Prepare rewrites, and a runtime that hosts the language + // itself has no such file, so there is nothing for a convention to name. + return handlertoolchain.WatchPaths{ + Roots: roots, + Extensions: conv.WatchExtensions, + SkipDirs: conv.WatchSkipDirs, + }, true +} + +func isRelevantChange(event fsnotify.Event, paths handlertoolchain.WatchPaths) bool { if event.Op&(fsnotify.Write|fsnotify.Create|fsnotify.Remove|fsnotify.Rename) == 0 { return false } + if slices.Contains(paths.SkipFiles, filepath.Base(event.Name)) { + return false + } ext := strings.ToLower(filepath.Ext(event.Name)) - return slices.Contains(watchExtensions, ext) + return slices.Contains(paths.Extensions, ext) } func addWatchRecursive(watcher *fsnotify.Watcher, dir string, skipDirs []string) error { diff --git a/apps/cli/internal/devrun/watcher_compiled_test.go b/apps/cli/internal/devrun/watcher_compiled_test.go new file mode 100644 index 00000000..955e9b56 --- /dev/null +++ b/apps/cli/internal/devrun/watcher_compiled_test.go @@ -0,0 +1,123 @@ +package devrun + +import ( + "context" + "errors" + "io" + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/newstack-cloud/celerity/apps/cli/internal/docker" + "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +// Returns a fixed manifest. +type stubExtractor struct { + manifest *preprocess.HandlerManifest + err error +} + +func (e *stubExtractor) Extract(context.Context) (*preprocess.HandlerManifest, error) { + return e.manifest, e.err +} + +// Counts container restarts and ignores everything else. +type restartRecorder struct { + docker.RuntimeContainerManager + restarts int +} + +func (r *restartRecorder) RestartContainer(context.Context, string) error { + r.restarts++ + return nil +} + +type WatcherCompiledSuite struct { + suite.Suite + docker *restartRecorder + manifest *preprocess.HandlerManifest +} + +func (s *WatcherCompiledSuite) SetupTest() { + s.docker = &restartRecorder{} + s.manifest = &preprocess.HandlerManifest{ + Version: "1", + FunctionHandlers: []preprocess.FunctionHandler{ + {ResourceName: "getOrder"}, + }, + } +} + +// Builds a watcher whose re-extraction returns the same handler set it started +// with, so only the rebuild distinguishes the two runtimes. +func (s *WatcherCompiledSuite) watcher(rebuild func(context.Context) error) *HandlerWatcher { + return NewHandlerWatcher(WatcherConfig{ + AppDir: s.T().TempDir(), + Runtime: "os-only.debian13", + Extractor: &stubExtractor{manifest: s.manifest}, + Blueprint: &schema.Blueprint{}, + SpecFormat: schema.YAMLSpecFormat, + Docker: s.docker, + ContainerID: "container", + Output: NewOutput(io.Discard, false), + Logger: zap.NewNop(), + Rebuild: rebuild, + }, s.manifest) +} + +// A compiled application is running a binary, so an unchanged handler set +// still leaves the container executing the old build. +func (s *WatcherCompiledSuite) Test_rebuilds_and_restarts_even_when_the_handlers_are_unchanged() { + rebuilt := 0 + w := s.watcher(func(context.Context) error { + rebuilt++ + return nil + }) + + w.handleChange(context.Background()) + + s.Assert().Equal(1, rebuilt) + s.Assert().Equal(1, s.docker.restarts) +} + +// An interpreted runtime picks changed source up itself, so an unchanged +// handler set is not worth a restart. +func (s *WatcherCompiledSuite) Test_without_a_rebuild_an_unchanged_handler_set_does_not_restart() { + w := s.watcher(nil) + + w.handleChange(context.Background()) + + s.Assert().Zero(s.docker.restarts) +} + +// A build that no longer compiles should leave the last working one serving +// rather than take the session down with it. +func (s *WatcherCompiledSuite) Test_a_failed_rebuild_leaves_the_container_alone() { + w := s.watcher(func(context.Context) error { + return errors.New("go build failed") + }) + + w.handleChange(context.Background()) + + s.Assert().Zero(s.docker.restarts) +} + +// Nothing should be rebuilt from source that the extractor has not seen yet, +// so the rebuild has to come first. +func (s *WatcherCompiledSuite) Test_the_rebuild_runs_before_extraction() { + var order []string + w := s.watcher(func(context.Context) error { + order = append(order, "rebuild") + return nil + }) + w.config.Extractor = &stubExtractor{manifest: s.manifest, err: errors.New("extract failed")} + + w.handleChange(context.Background()) + + s.Assert().Equal([]string{"rebuild"}, order) + s.Assert().Zero(s.docker.restarts, "a failed extraction should not restart") +} + +func TestWatcherCompiledSuite(t *testing.T) { suite.Run(t, new(WatcherCompiledSuite)) } diff --git a/apps/cli/internal/devrun/watcher_paths_test.go b/apps/cli/internal/devrun/watcher_paths_test.go new file mode 100644 index 00000000..08760661 --- /dev/null +++ b/apps/cli/internal/devrun/watcher_paths_test.go @@ -0,0 +1,104 @@ +package devrun + +import ( + "testing" + + "github.com/fsnotify/fsnotify" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +// What to watch is a property of the language rather than of the runtime, and +// an OS-only runtime identifier names only a base operating system. So the +// conventions for one carry no extensions at all, and a watcher resolving +// from them finds every change irrelevant and never reloads. +type WatcherPathsSuite struct { + suite.Suite +} + +func TestWatcherPathsSuite(t *testing.T) { suite.Run(t, new(WatcherPathsSuite)) } + +func (s *WatcherPathsSuite) watcher(runtime string, paths *handlertoolchain.WatchPaths) *HandlerWatcher { + return NewHandlerWatcher(WatcherConfig{ + AppDir: s.T().TempDir(), + Runtime: runtime, + Logger: zap.NewNop(), + WatchPaths: paths, + }, nil) +} + +// A change of the kind a saved file produces. +func write(name string) fsnotify.Event { + return fsnotify.Event{Name: name, Op: fsnotify.Write} +} + +func (s *WatcherPathsSuite) Test_an_os_only_runtime_watches_what_its_toolchain_names() { + w := s.watcher("os-only.debian13", &handlertoolchain.WatchPaths{ + Roots: []string{"."}, + Extensions: []string{".go"}, + }) + + paths, ok := w.watchPaths() + + s.Require().True(ok) + s.Assert().Equal([]string{"."}, paths.Roots) + s.Assert().True(isRelevantChange(write("cmd/app/orders.go"), paths)) +} + +// The file Prepare writes is a source file in a watched root, so reacting to +// it would have each rebuild trigger the next for as long as the session ran. +func (s *WatcherPathsSuite) Test_a_change_to_the_generated_platform_file_is_not_relevant() { + w := s.watcher("os-only.debian13", &handlertoolchain.WatchPaths{ + Roots: []string{"."}, + Extensions: []string{".go"}, + SkipFiles: []string{"celerity_platform_gen.go"}, + }) + + paths, ok := w.watchPaths() + + s.Require().True(ok) + s.Assert().False(isRelevantChange(write("celerity_platform_gen.go"), paths)) + s.Assert().True(isRelevantChange(write("handlers.go"), paths), + "only that one file, not every generated-looking name") +} + +// Reported rather than watched with nothing, because a watcher registered on +// the module root that treats no extension as relevant is running and reloading +// nothing. +func (s *WatcherPathsSuite) Test_an_os_only_runtime_with_no_toolchain_has_nothing_to_watch() { + w := s.watcher("os-only.debian13", nil) + + _, ok := w.watchPaths() + + s.Assert().False(ok) +} + +func (s *WatcherPathsSuite) Test_a_runtime_that_hosts_the_language_still_uses_its_conventions() { + w := s.watcher("nodejs24.x", nil) + + paths, ok := w.watchPaths() + + s.Require().True(ok) + s.Assert().Equal([]string{"src"}, paths.Roots) + s.Assert().True(isRelevantChange(write("src/handlers.ts"), paths)) + s.Assert().False(isRelevantChange(write("src/notes.md"), paths)) +} + +// A toolchain that names roots but no extensions would otherwise watch and +// react to nothing, which is the failure this guards against rather than a +// shape any toolchain is expected to return. +func (s *WatcherPathsSuite) Test_toolchain_paths_missing_extensions_fall_back_to_the_conventions() { + w := s.watcher("nodejs24.x", &handlertoolchain.WatchPaths{Roots: []string{"."}}) + + paths, ok := w.watchPaths() + + s.Require().True(ok) + s.Assert().Equal([]string{"src"}, paths.Roots) +} + +func (s *WatcherPathsSuite) Test_a_change_that_is_not_a_write_is_not_relevant() { + paths := handlertoolchain.WatchPaths{Extensions: []string{".go"}} + + s.Assert().False(isRelevantChange(fsnotify.Event{Name: "orders.go", Op: fsnotify.Chmod}, paths)) +} diff --git a/apps/cli/internal/devtest/node_runner.go b/apps/cli/internal/devtest/node_runner.go index 27ff625e..ebac70ef 100644 --- a/apps/cli/internal/devtest/node_runner.go +++ b/apps/cli/internal/devtest/node_runner.go @@ -38,7 +38,7 @@ func (r *NodeRunner) Run(ctx context.Context, config RunConfig) (*RunResult, err if len(commands) == 0 { return nil, fmt.Errorf( - "no test scripts found in package.json and no test framework detected; "+ + "no test scripts found in package.json and no test framework detected; " + "add a \"test\" script to package.json or use --test-command", ) } diff --git a/apps/cli/internal/devtest/oshandler_runner.go b/apps/cli/internal/devtest/oshandler_runner.go new file mode 100644 index 00000000..312fa658 --- /dev/null +++ b/apps/cli/internal/devtest/oshandler_runner.go @@ -0,0 +1,111 @@ +package devtest + +import ( + "context" + "fmt" + "os" + "os/exec" + "strings" + + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" + "go.uber.org/zap" +) + +// OSHandlerRunner executes tests for an application on an OS-only runtime. +// +// Which command that is belongs to the toolchain rather than to this package. +// One OS-only runtime serves Go, Rust, Zig and C++, whose test layouts and +// runners have nothing in common, so there is no per-runtime convention to +// detect the way there is for Node.js and Python. +type OSHandlerRunner struct { + toolchain handlertoolchain.Toolchain + logger *zap.Logger +} + +// NewOSHandlerRunner creates a runner that defers to the given toolchain. +func NewOSHandlerRunner(toolchain handlertoolchain.Toolchain, logger *zap.Logger) *OSHandlerRunner { + return &OSHandlerRunner{toolchain: toolchain, logger: logger} +} + +// Run executes the configured test suites. +func (r *OSHandlerRunner) Run(ctx context.Context, config RunConfig) (*RunResult, error) { + if config.TestCommand != "" { + return r.run(ctx, config, []string{"sh", "-c", config.TestCommand}) + } + + if r.toolchain == nil { + return nil, fmt.Errorf( + "no toolchain resolved for runtime %q, so there is no test command to run.\n"+ + "Pass --test-command, or declare handlerBuild.test in your deploy config", + config.Runtime, + ) + } + + suites := expandSuites(config.Suites) + var commands [][]string + var unconfigured []string + for _, suite := range suites { + command, ok := r.toolchain.TestCommand(string(suite)) + if !ok { + unconfigured = append(unconfigured, string(suite)) + continue + } + commands = append(commands, command) + } + + if len(commands) == 0 { + return nil, fmt.Errorf( + "the %s toolchain has no test command for %s.\n"+ + "Declare handlerBuild.test for those suites, or pass --test-command", + r.toolchain.Name(), strings.Join(unconfigured, ", "), + ) + } + for _, suite := range unconfigured { + r.logger.Warn("no test command for suite, skipping", + zap.String("suite", suite), + zap.String("toolchain", r.toolchain.Name()), + ) + } + + // The worst exit code wins, so one failing suite fails the run even where + // a later one passes. + result := &RunResult{} + for _, command := range commands { + suiteResult, err := r.run(ctx, config, command) + if err != nil { + return nil, err + } + if suiteResult.ExitCode != 0 && result.ExitCode == 0 { + result.ExitCode = suiteResult.ExitCode + } + } + return result, nil +} + +func (r *OSHandlerRunner) run(ctx context.Context, config RunConfig, command []string) (*RunResult, error) { + bin, err := exec.LookPath(command[0]) + if err != nil { + return nil, fmt.Errorf("%s not found on PATH: %w", command[0], err) + } + + cmd := exec.CommandContext(ctx, bin, command[1:]...) + cmd.Dir = config.AppDir + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.Env = r.buildEnv(config) + + r.logger.Debug("running tests", zap.Strings("command", command)) + err = cmd.Run() + return &RunResult{ExitCode: exitCodeFromError(err)}, nil +} + +func (r *OSHandlerRunner) buildEnv(config RunConfig) []string { + env := os.Environ() + for k, v := range config.Env { + env = append(env, k+"="+v) + } + if config.HostPort != "" { + env = append(env, "CELERITY_TEST_BASE_URL=http://localhost:"+config.HostPort) + } + return env +} diff --git a/apps/cli/internal/devtest/oshandler_runner_test.go b/apps/cli/internal/devtest/oshandler_runner_test.go new file mode 100644 index 00000000..478506c8 --- /dev/null +++ b/apps/cli/internal/devtest/oshandler_runner_test.go @@ -0,0 +1,120 @@ +package devtest + +import ( + "context" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" + "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +// fakeToolchain answers with the test commands it was given. +type fakeToolchain struct { + commands map[string][]string +} + +func (t *fakeToolchain) Name() string { return "fake" } +func (t *fakeToolchain) Validate(string) error { return nil } + +func (t *fakeToolchain) Prepare(context.Context, handlertoolchain.PrepareParams) error { return nil } + +func (t *fakeToolchain) Extract( + context.Context, handlertoolchain.ExtractParams, +) (*preprocess.HandlerManifest, error) { + return nil, nil +} + +func (t *fakeToolchain) BuildBinary(context.Context, handlertoolchain.BinaryParams) error { + return nil +} + +func (t *fakeToolchain) WatchPaths() handlertoolchain.WatchPaths { + return handlertoolchain.WatchPaths{} +} + +func (t *fakeToolchain) TestCommand(suite string) ([]string, bool) { + command, ok := t.commands[suite] + return command, ok +} + +type OSHandlerRunnerSuite struct { + suite.Suite + logger *zap.Logger +} + +func (s *OSHandlerRunnerSuite) SetupTest() { s.logger = zap.NewNop() } + +func (s *OSHandlerRunnerSuite) config(suites ...TestSuite) RunConfig { + return RunConfig{ + AppDir: s.T().TempDir(), + Runtime: "os-only.debian13", + Suites: suites, + } +} + +func (s *OSHandlerRunnerSuite) Test_runs_the_toolchains_command_for_the_suite() { + tc := &fakeToolchain{commands: map[string][]string{"unit": {"true"}}} + runner := NewOSHandlerRunner(tc, s.logger) + + result, err := runner.Run(context.Background(), s.config(SuiteUnit)) + s.Require().NoError(err) + s.Assert().Zero(result.ExitCode) +} + +// A failing suite has to fail the run, or a red test suite reads as green. +func (s *OSHandlerRunnerSuite) Test_a_failing_suite_fails_the_run() { + tc := &fakeToolchain{commands: map[string][]string{"unit": {"false"}}} + runner := NewOSHandlerRunner(tc, s.logger) + + result, err := runner.Run(context.Background(), s.config(SuiteUnit)) + s.Require().NoError(err) + s.Assert().NotZero(result.ExitCode) +} + +// The worst outcome wins: a later passing suite must not mask an earlier +// failure. +func (s *OSHandlerRunnerSuite) Test_one_failing_suite_among_several_fails_the_run() { + tc := &fakeToolchain{commands: map[string][]string{ + "unit": {"false"}, + "integration": {"true"}, + }} + runner := NewOSHandlerRunner(tc, s.logger) + + result, err := runner.Run(context.Background(), s.config(SuiteUnit, SuiteIntegration)) + s.Require().NoError(err) + s.Assert().NotZero(result.ExitCode) +} + +func (s *OSHandlerRunnerSuite) Test_an_explicit_test_command_wins() { + tc := &fakeToolchain{commands: map[string][]string{"unit": {"false"}}} + runner := NewOSHandlerRunner(tc, s.logger) + + config := s.config(SuiteUnit) + config.TestCommand = "true" + + result, err := runner.Run(context.Background(), config) + s.Require().NoError(err) + s.Assert().Zero(result.ExitCode) +} + +func (s *OSHandlerRunnerSuite) Test_no_command_for_any_suite_says_how_to_declare_one() { + runner := NewOSHandlerRunner(&fakeToolchain{}, s.logger) + + _, err := runner.Run(context.Background(), s.config(SuiteUnit)) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "handlerBuild.test") +} + +// Without a toolchain there is nothing to ask, and guessing a command for a +// language the CLI cannot identify would run the wrong thing. +func (s *OSHandlerRunnerSuite) Test_no_toolchain_and_no_command_is_an_error() { + runner := NewOSHandlerRunner(nil, s.logger) + + _, err := runner.Run(context.Background(), s.config(SuiteUnit)) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "--test-command") +} + +func TestOSHandlerRunnerSuite(t *testing.T) { suite.Run(t, new(OSHandlerRunnerSuite)) } diff --git a/apps/cli/internal/devtest/python_runner.go b/apps/cli/internal/devtest/python_runner.go index c1ae6238..bc7eb932 100644 --- a/apps/cli/internal/devtest/python_runner.go +++ b/apps/cli/internal/devtest/python_runner.go @@ -37,7 +37,7 @@ func (r *PythonRunner) Run(ctx context.Context, config RunConfig) (*RunResult, e } if pytestBin == "" { return nil, fmt.Errorf( - "pytest not found; install it in a virtualenv (.venv or venv) "+ + "pytest not found; install it in a virtualenv (.venv or venv) " + "or system-wide, or use --test-command", ) } diff --git a/apps/cli/internal/devtest/registry.go b/apps/cli/internal/devtest/registry.go index 802a266d..0a4e9719 100644 --- a/apps/cli/internal/devtest/registry.go +++ b/apps/cli/internal/devtest/registry.go @@ -5,27 +5,54 @@ import ( "strings" "github.com/newstack-cloud/celerity/apps/cli/internal/consts" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" "go.uber.org/zap" ) // RunnerFactory creates a TestRunner for a given runtime. -type RunnerFactory func(logger *zap.Logger) TestRunner +// +// The toolchain is nil for a runtime that hosts the language itself, where the +// test command is a convention of that language rather than something the +// project declares. +type RunnerFactory func(toolchain handlertoolchain.Toolchain, logger *zap.Logger) TestRunner var runners = map[string]RunnerFactory{ - consts.LanguageNodeJS: func(l *zap.Logger) TestRunner { return NewNodeRunner(l) }, - consts.LanguagePython: func(l *zap.Logger) TestRunner { return NewPythonRunner(l) }, + consts.LanguageNodeJS: func(_ handlertoolchain.Toolchain, l *zap.Logger) TestRunner { + return NewNodeRunner(l) + }, + consts.LanguagePython: func(_ handlertoolchain.Toolchain, l *zap.Logger) TestRunner { + return NewPythonRunner(l) + }, + consts.RuntimeOSOnly: func(t handlertoolchain.Toolchain, l *zap.Logger) TestRunner { + return NewOSHandlerRunner(t, l) + }, } // RunnerForRuntime returns a TestRunner for the given runtime string, -// matching by prefix (e.g. "nodejs24.x" matches "nodejs"). -func RunnerForRuntime(runtime string, logger *zap.Logger) (TestRunner, error) { +// matching by longest prefix (e.g. "nodejs24.x" matches "nodejs"). +func RunnerForRuntime( + runtime string, + toolchain handlertoolchain.Toolchain, + logger *zap.Logger, +) (TestRunner, error) { + var ( + best RunnerFactory + longest int + found bool + ) for prefix, factory := range runners { - if strings.HasPrefix(runtime, prefix) { - return factory(logger), nil + if !strings.HasPrefix(runtime, prefix) { + continue + } + if !found || len(prefix) > longest { + best, longest, found = factory, len(prefix), true } } - return nil, fmt.Errorf( - "no test runner for runtime %q; supported runtimes: nodejs, python", - runtime, - ) + if !found { + return nil, fmt.Errorf( + "no test runner for runtime %q; supported runtimes: nodejs, python, os-only", + runtime, + ) + } + return best(toolchain, logger), nil } diff --git a/apps/cli/internal/devtest/registry_test.go b/apps/cli/internal/devtest/registry_test.go index 80146a44..5ad5f224 100644 --- a/apps/cli/internal/devtest/registry_test.go +++ b/apps/cli/internal/devtest/registry_test.go @@ -3,6 +3,7 @@ package devtest import ( "testing" + "github.com/newstack-cloud/celerity/apps/cli/internal/consts" "github.com/stretchr/testify/suite" "go.uber.org/zap" ) @@ -22,19 +23,27 @@ func (s *RegistryTestSuite) SetupTest() { } func (s *RegistryTestSuite) Test_nodejs_runtime_returns_node_runner() { - runner, err := RunnerForRuntime("nodejs22.x", s.logger) + runner, err := RunnerForRuntime("nodejs22.x", nil, s.logger) s.Require().NoError(err) s.Assert().IsType(&NodeRunner{}, runner) } func (s *RegistryTestSuite) Test_python_runtime_returns_python_runner() { - runner, err := RunnerForRuntime("python3.12.x", s.logger) + runner, err := RunnerForRuntime("python3.12.x", nil, s.logger) s.Require().NoError(err) s.Assert().IsType(&PythonRunner{}, runner) } func (s *RegistryTestSuite) Test_unknown_runtime_returns_error() { - _, err := RunnerForRuntime("rust1.75", s.logger) + _, err := RunnerForRuntime("rust1.75", nil, s.logger) s.Assert().Error(err) s.Assert().Contains(err.Error(), "no test runner for runtime") } + +// An OS-only runtime serves several languages, so the runner defers to the +// toolchain for the command rather than detecting one from the runtime. +func (s *RegistryTestSuite) Test_os_only_runtime_returns_the_toolchain_runner() { + runner, err := RunnerForRuntime(consts.RuntimeOSOnlyDebian13, nil, s.logger) + s.Require().NoError(err) + s.Assert().IsType(&OSHandlerRunner{}, runner) +} diff --git a/apps/cli/internal/docker/architecture.go b/apps/cli/internal/docker/architecture.go new file mode 100644 index 00000000..45f313be --- /dev/null +++ b/apps/cli/internal/docker/architecture.go @@ -0,0 +1,41 @@ +package docker + +import ( + "context" + "fmt" +) + +// DaemonArchitecture reports the architecture the Docker daemon runs +// containers at, as a GOARCH name. +// +// Read from the daemon rather than taken from the CLI's own GOARCH, because the +// two are often different. A remote context, or a Linux VM on an arm64 Mac, runs +// containers at an architecture the client is not built for, and a handlers +// executable cross-compiled for the wrong one is a valid file the kernel refuses +// to exec, which the supervisor reports as a bare ENOEXEC. +func (r *RuntimeContainer) DaemonArchitecture(ctx context.Context) (string, error) { + info, err := r.client.Info(ctx) + if err != nil { + return "", fmt.Errorf("asking the Docker daemon for its architecture: %w", err) + } + return NormaliseArchitecture(info.Architecture), nil +} + +// NormaliseArchitecture maps the architecture names Docker reports onto GOARCH +// names. +// +// Docker reports the kernel's own spelling (uname -m), which is not what Go +// calls the same architectures. +func NormaliseArchitecture(arch string) string { + switch arch { + case "aarch64", "arm64", "arm64/v8": + return "arm64" + case "x86_64", "amd64": + return "amd64" + default: + // Passed through rather than rejected, because an architecture neither + // side has a translation for is still the right answer to hand a + // compiler, and the build fails plainly enough if it is not. + return arch + } +} diff --git a/apps/cli/internal/docker/architecture_test.go b/apps/cli/internal/docker/architecture_test.go new file mode 100644 index 00000000..3095f6bf --- /dev/null +++ b/apps/cli/internal/docker/architecture_test.go @@ -0,0 +1,26 @@ +package docker + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// Docker reports the kernel's spelling, which is not Go's. +func TestNormaliseArchitecture(t *testing.T) { + for reported, want := range map[string]string{ + "aarch64": "arm64", + "arm64": "arm64", + "arm64/v8": "arm64", + "x86_64": "amd64", + "amd64": "amd64", + } { + assert.Equal(t, want, NormaliseArchitecture(reported), reported) + } +} + +// An architecture with no translation is still the right answer to hand a +// compiler. +func TestNormaliseArchitecture_passesThroughTheUnknown(t *testing.T) { + assert.Equal(t, "riscv64", NormaliseArchitecture("riscv64")) +} diff --git a/apps/cli/internal/docker/client.go b/apps/cli/internal/docker/client.go index 7c899292..96844db8 100644 --- a/apps/cli/internal/docker/client.go +++ b/apps/cli/internal/docker/client.go @@ -205,7 +205,7 @@ func (rc *RuntimeContainer) CleanupStale( ) error { info, err := rc.client.ContainerInspect(ctx, containerName) if err != nil { - // Container doesn't exist — nothing to clean up. + // The container does not exist, so there is nothing to clean up. return nil } @@ -250,7 +250,7 @@ func buildHostConfig(cfg *ContainerConfig) *container.HostConfig { return hostCfg } -// pullProgressEvent matches the JSON structure from Docker's image pull stream. +// Matches the JSON structure from Docker's image pull stream. type pullProgressEvent struct { ID string `json:"id"` Status string `json:"status"` diff --git a/apps/cli/internal/handlerresolve/resolver.go b/apps/cli/internal/handlerresolve/resolver.go new file mode 100644 index 00000000..ea127efd --- /dev/null +++ b/apps/cli/internal/handlerresolve/resolver.go @@ -0,0 +1,225 @@ +// Package handlerresolve is the shared extract + merge + collect pipeline +// used by both the dev and build commands so handler discovery behaves +// identically across them. +package handlerresolve + +import ( + "context" + "fmt" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/newstack-cloud/celerity/apps/cli/internal/blueprint" + "github.com/newstack-cloud/celerity/apps/cli/internal/consts" + "github.com/newstack-cloud/celerity/apps/cli/internal/devconfig/resolve" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" + "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" + "go.uber.org/zap" +) + +// ResolvedHandlers is the output of Resolve. +type ResolvedHandlers struct { + Runtime string + ModulePath string + Handlers []blueprint.HandlerInfo + Blueprint *schema.Blueprint + MergedBlueprint *schema.Blueprint + SpecFormat schema.SpecFormat + Manifest *preprocess.HandlerManifest + // Toolchain builds the handlers executable, and is nil for a runtime that + // hosts the language itself. Carried here so callers thread the one that + // was resolved rather than resolving their own. + Toolchain handlertoolchain.Toolchain +} + +// Options configures Resolve. +type Options struct { + AppDir string + BlueprintFile string + ModulePathOverride string + // Toolchain builds the handlers executable for an OS-only runtime. + // Resolved by the caller, which is the only place that has both the app + // directory and the deploy config; nil for every other runtime. + Toolchain handlertoolchain.Toolchain + // DeployTarget and Mode tell the toolchain what it is generating for. + DeployTarget string + Mode string + // Telemetry names what traces are exported with, or is empty for none. + Telemetry string +} + +// Extractor is an interface (rather than the concrete preprocess.Extractor) +// so tests can inject a stub without depending on the celerity-extract +// binary being installed on the host system. +type Extractor interface { + Extract(ctx context.Context) (*preprocess.HandlerManifest, error) +} + +// ExtractorFactory allows tests to substitute a stub extractor. +type ExtractorFactory func(cfg preprocess.ExtractorConfig, logger *zap.Logger) Extractor + +func defaultExtractorFactory(cfg preprocess.ExtractorConfig, logger *zap.Logger) Extractor { + return preprocess.NewExtractor(cfg, logger) +} + +// Resolve extracts an application's handlers and merges them into its +// blueprint. The merged blueprint is not persisted to disk, which is a +// dev-specific concern, so callers decide whether to write it out. +func Resolve( + ctx context.Context, + opts Options, + logger *zap.Logger, +) (*ResolvedHandlers, error) { + return resolveWith(ctx, opts, defaultExtractorFactory, logger) +} + +func resolveWith( + ctx context.Context, + opts Options, + factory ExtractorFactory, + logger *zap.Logger, +) (*ResolvedHandlers, error) { + bp, specFormat, err := loadBlueprint(opts.BlueprintFile) + if err != nil { + return nil, err + } + + runtime, err := detectRuntime(bp, opts.AppDir, logger) + if err != nil { + return nil, err + } + + modulePath := resolveModulePath(opts.AppDir, opts.ModulePathOverride, runtime) + + // Prepared before extraction rather than before the build, because + // extraction compiles the application and so fails on a project whose + // generated platform imports are absent or belong to another deploy + // target. + if opts.Toolchain != nil { + if err := prepareToolchain(ctx, opts, bp); err != nil { + return nil, err + } + } + + manifest, err := runExtraction(ctx, runtime, modulePath, opts, factory, logger) + if err != nil { + return nil, err + } + + // Collapsed here as well as inside Merge so the manifest returned to + // callers describes the same handler resources the merged blueprint does. + // A caller reading the uncollapsed one would build artefacts for resources + // that no longer exist. The operation is idempotent, so the second call is + // a no-op. + manifest = preprocess.CollapseRoutedConsumers(manifest, logger) + + merged, err := preprocess.Merge(bp, manifest, logger) + if err != nil { + return nil, fmt.Errorf("blueprint merge: %w", err) + } + + return &ResolvedHandlers{ + Runtime: runtime, + ModulePath: modulePath, + Handlers: blueprint.CollectHandlerInfo(merged), + Blueprint: bp, + MergedBlueprint: merged, + SpecFormat: specFormat, + Manifest: manifest, + Toolchain: opts.Toolchain, + }, nil +} + +func loadBlueprint(blueprintFile string) (*schema.Blueprint, schema.SpecFormat, error) { + if blueprintFile == "" { + return nil, "", fmt.Errorf("blueprint file path is required") + } + bp, specFormat, err := blueprint.LoadForDev(blueprintFile) + if err != nil { + return nil, "", fmt.Errorf("loading blueprint %s: %w", blueprintFile, err) + } + return bp, specFormat, nil +} + +func detectRuntime(bp *schema.Blueprint, appDir string, logger *zap.Logger) (string, error) { + runtime, err := blueprint.DetectRuntime(bp) + if err == nil { + return runtime, nil + } + + // Decorator-driven projects have no handler resources in the blueprint + // until after extraction, so fall back to project files for runtime detection. + runtime, projectErr := blueprint.DetectRuntimeFromProject(appDir) + if projectErr != nil { + return "", fmt.Errorf("detecting runtime: %w", projectErr) + } + logger.Info("runtime auto-detected from project files", + zap.String("runtime", runtime), + ) + return runtime, nil +} + +func resolveModulePath(appDir, override, runtime string) string { + conv, ok := consts.ConventionsForRuntime(runtime) + if !ok { + return override + } + return resolve.ModulePath(appDir, override, conv.DefaultModulePaths) +} + +func prepareToolchain(ctx context.Context, opts Options, bp *schema.Blueprint) error { + err := opts.Toolchain.Prepare(ctx, handlertoolchain.PrepareParams{ + AppDir: opts.AppDir, + DeployTarget: opts.DeployTarget, + Mode: opts.Mode, + ResourceKinds: blueprint.ResourceKinds(bp), + SQLEngines: blueprint.SQLEngines(bp), + Telemetry: opts.Telemetry, + }) + if err != nil { + return fmt.Errorf("preparing the %s toolchain: %w", opts.Toolchain.Name(), err) + } + return nil +} + +func runExtraction( + ctx context.Context, + runtime, modulePath string, + opts Options, + factory ExtractorFactory, + logger *zap.Logger, +) (*preprocess.HandlerManifest, error) { + // An OS-only runtime hosts no language, so the extractor belongs to + // whichever toolchain built the executable rather than to the runtime. + if opts.Toolchain != nil { + manifest, err := opts.Toolchain.Extract(ctx, handlertoolchain.ExtractParams{AppDir: opts.AppDir}) + if err != nil { + return nil, fmt.Errorf("handler extraction: %w", err) + } + if manifest == nil { + logger.Info("the toolchain does not extract handlers, using raw blueprint", + zap.String("toolchain", opts.Toolchain.Name()), + ) + return &preprocess.HandlerManifest{Version: preprocess.ManifestVersion}, nil + } + return manifest, nil + } + + conv, _ := consts.ConventionsForRuntime(runtime) + if !conv.SupportsExtraction { + logger.Info("handler extraction not available for runtime, using raw blueprint", + zap.String("runtime", runtime), + ) + return &preprocess.HandlerManifest{Version: preprocess.ManifestVersion}, nil + } + + extractor := factory(preprocess.ExtractorConfig{ + Runtime: runtime, + ModulePath: modulePath, + ProjectRoot: opts.AppDir, + }, logger) + manifest, err := extractor.Extract(ctx) + if err != nil { + return nil, fmt.Errorf("handler extraction: %w", err) + } + return manifest, nil +} diff --git a/apps/cli/internal/handlerresolve/resolver_test.go b/apps/cli/internal/handlerresolve/resolver_test.go new file mode 100644 index 00000000..7eb493e3 --- /dev/null +++ b/apps/cli/internal/handlerresolve/resolver_test.go @@ -0,0 +1,200 @@ +package handlerresolve + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +type ResolverTestSuite struct { + suite.Suite + logger *zap.Logger +} + +func TestResolverTestSuite(t *testing.T) { + suite.Run(t, new(ResolverTestSuite)) +} + +func (s *ResolverTestSuite) SetupTest() { + s.logger = zap.NewNop() +} + +// stubExtractor lets us inject a fake extraction result without depending +// on the celerity-extract binary being installed. +type stubExtractor struct { + manifest *preprocess.HandlerManifest + err error +} + +func (e *stubExtractor) Extract(_ context.Context) (*preprocess.HandlerManifest, error) { + if e.err != nil { + return nil, e.err + } + return e.manifest, nil +} + +func (s *ResolverTestSuite) stubFactory(extractor Extractor) ExtractorFactory { + return func(_ preprocess.ExtractorConfig, _ *zap.Logger) Extractor { + return extractor + } +} + +func (s *ResolverTestSuite) Test_Resolve_decorator_driven_node_project_returns_handlers_from_extractor() { + appDir := s.T().TempDir() + s.writeFile(filepath.Join(appDir, "package.json"), `{"name":"test","type":"module","dependencies":{"@celerity-sdk/core":"^0.6.0"}}`) + s.writeFile(filepath.Join(appDir, "src", "app-module.ts"), "export default class AppModule {}") + + blueprintPath := filepath.Join(appDir, "app.blueprint.yaml") + s.writeFile(blueprintPath, decoratorDrivenBlueprint) + + extractor := &stubExtractor{ + manifest: &preprocess.HandlerManifest{ + Version: "1", + Handlers: []preprocess.ClassHandler{ + { + ResourceName: "getUser", + ClassName: "UsersController", + MethodName: "getUser", + SourceFile: "src/users/users-controller.ts", + HandlerType: "http", + Annotations: map[string]any{ + "celerity.handler.http.method": "GET", + "celerity.handler.http.path": "/users/{id}", + }, + Spec: preprocess.HandlerSpec{ + HandlerName: "users-controller.getUser", + CodeLocation: "src/users/users-controller.ts", + Handler: "getUser", + }, + }, + }, + }, + } + + resolved, err := resolveWith( + context.Background(), + Options{AppDir: appDir, BlueprintFile: blueprintPath}, + s.stubFactory(extractor), + s.logger, + ) + s.Require().NoError(err) + s.Require().NotNil(resolved) + s.Equal("nodejs24.x", resolved.Runtime) + s.Require().Len(resolved.Handlers, 1) + s.Equal("getUser", resolved.Handlers[0].ResourceName) +} + +func (s *ResolverTestSuite) Test_Resolve_blueprint_driven_project_returns_handlers_from_blueprint() { + appDir := s.T().TempDir() + s.writeFile(filepath.Join(appDir, "package.json"), `{"name":"test","dependencies":{"@celerity-sdk/core":"^0.6.0"}}`) + + blueprintPath := filepath.Join(appDir, "app.blueprint.yaml") + s.writeFile(blueprintPath, blueprintWithExplicitHandler) + + extractor := &stubExtractor{ + manifest: &preprocess.HandlerManifest{Version: "1"}, + } + + resolved, err := resolveWith( + context.Background(), + Options{AppDir: appDir, BlueprintFile: blueprintPath}, + s.stubFactory(extractor), + s.logger, + ) + s.Require().NoError(err) + s.Require().Len(resolved.Handlers, 1) + s.Equal("getUser", resolved.Handlers[0].ResourceName) + s.Equal("users.getUser", resolved.Handlers[0].HandlerName) +} + +func (s *ResolverTestSuite) Test_Resolve_fails_when_blueprint_missing() { + resolved, err := resolveWith( + context.Background(), + Options{AppDir: s.T().TempDir(), BlueprintFile: "does-not-exist.yaml"}, + s.stubFactory(&stubExtractor{}), + s.logger, + ) + s.Nil(resolved) + s.Require().Error(err) + s.Contains(err.Error(), "loading blueprint") +} + +func (s *ResolverTestSuite) Test_Resolve_fails_when_runtime_cannot_be_detected() { + appDir := s.T().TempDir() + // No package.json, no pyproject.toml → runtime detection fails + blueprintPath := filepath.Join(appDir, "app.blueprint.yaml") + s.writeFile(blueprintPath, minimalBlueprint) + + resolved, err := resolveWith( + context.Background(), + Options{AppDir: appDir, BlueprintFile: blueprintPath}, + s.stubFactory(&stubExtractor{}), + s.logger, + ) + s.Nil(resolved) + s.Require().Error(err) + s.Contains(err.Error(), "detecting runtime") +} + +func (s *ResolverTestSuite) Test_Resolve_propagates_extractor_errors() { + appDir := s.T().TempDir() + s.writeFile(filepath.Join(appDir, "package.json"), `{"name":"test","type":"module"}`) + blueprintPath := filepath.Join(appDir, "app.blueprint.yaml") + s.writeFile(blueprintPath, decoratorDrivenBlueprint) + + extractor := &stubExtractor{err: errFromExtractor} + + resolved, err := resolveWith( + context.Background(), + Options{AppDir: appDir, BlueprintFile: blueprintPath}, + s.stubFactory(extractor), + s.logger, + ) + s.Nil(resolved) + s.Require().Error(err) + s.Contains(err.Error(), "handler extraction") +} + +func (s *ResolverTestSuite) writeFile(path, content string) { + s.Require().NoError(os.MkdirAll(filepath.Dir(path), 0755)) + s.Require().NoError(os.WriteFile(path, []byte(content), 0644)) +} + +var errFromExtractor = extractorErr("boom") + +type extractorErr string + +func (e extractorErr) Error() string { return string(e) } + +const decoratorDrivenBlueprint = `version: 2025-11-02 +resources: + myApi: + type: "celerity/api" + spec: + protocols: + - http +` + +const blueprintWithExplicitHandler = `version: 2025-11-02 +resources: + getUser: + type: "celerity/handler" + spec: + runtime: "nodejs24.x" + handlerName: "users.getUser" + codeLocation: "src/users.ts" +` + +const minimalBlueprint = `version: 2025-11-02 +resources: + something: + type: "celerity/api" + spec: + protocols: + - http +` diff --git a/apps/cli/internal/handlerresolve/sdk_detect.go b/apps/cli/internal/handlerresolve/sdk_detect.go new file mode 100644 index 00000000..cf759fab --- /dev/null +++ b/apps/cli/internal/handlerresolve/sdk_detect.go @@ -0,0 +1,154 @@ +package handlerresolve + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" +) + +// RequireCelerityRuntimeSDK fails fast at build time with a clear message +// instead of letting the generated bootstrap fail at Lambda runtime when +// the Celerity SDK isn't installed. +func RequireCelerityRuntimeSDK(appDir, runtime string) error { + switch { + case isNodeRuntime(runtime): + return requireNodeSDK(appDir) + case isPythonRuntime(runtime): + return requirePythonSDK(appDir) + } + return nil +} + +func requireNodeSDK(appDir string) error { + if nodeHasCelerityDep(appDir) { + return nil + } + return fmt.Errorf( + "celerity/handler resources declared but no @celerity-sdk/* package is a dependency " + + "in package.json; add @celerity-sdk/core (and @celerity-sdk/serverless-aws for " + + "Lambda deploys) to your dependencies", + ) +} + +func requirePythonSDK(appDir string) error { + if pythonHasCelerityDep(appDir) { + return nil + } + return fmt.Errorf( + "celerity/handler resources declared but celerity-sdk is not a dependency in " + + "pyproject.toml; add celerity-sdk to your project dependencies", + ) +} + +func isNodeRuntime(runtime string) bool { + return strings.HasPrefix(runtime, "nodejs") +} + +func isPythonRuntime(runtime string) bool { + return strings.HasPrefix(runtime, "python") +} + +func nodeHasCelerityDep(appDir string) bool { + data, err := os.ReadFile(filepath.Join(appDir, "package.json")) + if err != nil { + return false + } + var pkg struct { + Dependencies map[string]string `json:"dependencies"` + DevDependencies map[string]string `json:"devDependencies"` + PeerDependencies map[string]string `json:"peerDependencies"` + } + if err := json.Unmarshal(data, &pkg); err != nil { + return false + } + return hasCelerityScopedPackage(pkg.Dependencies) || + hasCelerityScopedPackage(pkg.DevDependencies) || + hasCelerityScopedPackage(pkg.PeerDependencies) +} + +func hasCelerityScopedPackage(deps map[string]string) bool { + for name := range deps { + if strings.HasPrefix(name, "@celerity-sdk/") { + return true + } + } + return false +} + +// A line-based scan instead of full TOML parsing, to avoid pulling in a parser +// dependency for a simple substring check. +func pythonHasCelerityDep(appDir string) bool { + data, err := os.ReadFile(filepath.Join(appDir, "pyproject.toml")) + if err != nil { + return false + } + return bytesContainCelerityDep(data) +} + +func bytesContainCelerityDep(data []byte) bool { + text := string(data) + for line := range strings.SplitSeq(text, "\n") { + stripped := strings.TrimSpace(line) + if lineDeclaresCelerityDep(stripped) { + return true + } + } + return false +} + +// Recognises the common pyproject.toml formats: +// - `celerity-sdk = "^1.0"` (poetry) +// - `"celerity-sdk>=1.0",` (PEP 621 list entry) +// - `celerity-sdk` (bare name) +func lineDeclaresCelerityDep(line string) bool { + if line == "" || strings.HasPrefix(line, "#") { + return false + } + lowered := strings.ToLower(line) + idx := strings.Index(lowered, "celerity-sdk") + if idx == -1 { + return false + } + if !hasPackageNameBoundaryBefore(lowered, idx) { + return false + } + return hasPackageNameBoundaryAfter(lowered, idx+len("celerity-sdk")) +} + +func hasPackageNameBoundaryBefore(s string, idx int) bool { + if idx == 0 { + return true + } + ch := s[idx-1] + return ch == '"' || ch == '\'' || ch == '[' || ch == ' ' || ch == '\t' || ch == ',' +} + +func hasPackageNameBoundaryAfter(s string, idx int) bool { + if idx >= len(s) { + return true + } + ch := s[idx] + return ch == '"' || ch == '\'' || ch == ' ' || ch == '\t' || + ch == '=' || ch == '>' || ch == '<' || ch == '~' || + ch == ',' || ch == ']' +} + +// RequireRuntimeSDK checks that the project declares whatever it needs to +// build and run its handlers. +// +// Prefer this over RequireCelerityRuntimeSDK. For an OS-only runtime the +// question is not whether a language SDK is installed but whether the resolved +// toolchain can build an executable at all, which only that toolchain can +// report. RequireCelerityRuntimeSDK returns nil for a runtime it does not +// recognise, so calling it directly for an OS-only project checks nothing. +func RequireRuntimeSDK(appDir string, resolved *ResolvedHandlers) error { + if resolved == nil { + return nil + } + if resolved.Toolchain != nil { + return resolved.Toolchain.Validate(appDir) + } + return RequireCelerityRuntimeSDK(appDir, resolved.Runtime) +} diff --git a/apps/cli/internal/handlerresolve/sdk_detect_test.go b/apps/cli/internal/handlerresolve/sdk_detect_test.go new file mode 100644 index 00000000..96073510 --- /dev/null +++ b/apps/cli/internal/handlerresolve/sdk_detect_test.go @@ -0,0 +1,138 @@ +package handlerresolve + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" +) + +type SDKDetectTestSuite struct { + suite.Suite +} + +func TestSDKDetectTestSuite(t *testing.T) { + suite.Run(t, new(SDKDetectTestSuite)) +} + +// --- Node.js --- + +func (s *SDKDetectTestSuite) Test_node_celerity_core_in_dependencies_passes() { + appDir := s.newProject(`{"name":"x","dependencies":{"@celerity-sdk/core":"^0.6.0"}}`, "") + s.NoError(RequireCelerityRuntimeSDK(appDir, "nodejs24.x")) +} + +func (s *SDKDetectTestSuite) Test_node_celerity_scoped_package_in_dev_dependencies_passes() { + appDir := s.newProject(`{"name":"x","devDependencies":{"@celerity-sdk/testing":"^0.6.0"}}`, "") + s.NoError(RequireCelerityRuntimeSDK(appDir, "nodejs22.x")) +} + +func (s *SDKDetectTestSuite) Test_node_celerity_in_peer_dependencies_passes() { + appDir := s.newProject(`{"name":"x","peerDependencies":{"@celerity-sdk/core":"^0.6.0"}}`, "") + s.NoError(RequireCelerityRuntimeSDK(appDir, "nodejs24.x")) +} + +func (s *SDKDetectTestSuite) Test_node_no_celerity_package_fails() { + appDir := s.newProject(`{"name":"x","dependencies":{"express":"^4.0.0"}}`, "") + err := RequireCelerityRuntimeSDK(appDir, "nodejs24.x") + s.Require().Error(err) + s.Contains(err.Error(), "@celerity-sdk") +} + +func (s *SDKDetectTestSuite) Test_node_missing_package_json_fails() { + appDir := s.T().TempDir() + err := RequireCelerityRuntimeSDK(appDir, "nodejs24.x") + s.Require().Error(err) + s.Contains(err.Error(), "@celerity-sdk") +} + +func (s *SDKDetectTestSuite) Test_node_malformed_package_json_fails() { + appDir := s.newProject(`{not json`, "") + err := RequireCelerityRuntimeSDK(appDir, "nodejs24.x") + s.Require().Error(err) +} + +// --- Python --- + +func (s *SDKDetectTestSuite) Test_python_celerity_sdk_in_pep621_dependencies_passes() { + appDir := s.newProject("", ` +[project] +name = "myapp" +dependencies = [ + "celerity-sdk>=0.6.0", + "boto3", +] +`) + s.NoError(RequireCelerityRuntimeSDK(appDir, "python3.13")) +} + +func (s *SDKDetectTestSuite) Test_python_celerity_sdk_in_poetry_dependencies_passes() { + appDir := s.newProject("", ` +[tool.poetry.dependencies] +python = "^3.13" +celerity-sdk = "^0.6.0" +`) + s.NoError(RequireCelerityRuntimeSDK(appDir, "python3.13")) +} + +func (s *SDKDetectTestSuite) Test_python_no_celerity_package_fails() { + appDir := s.newProject("", ` +[project] +name = "myapp" +dependencies = ["boto3"] +`) + err := RequireCelerityRuntimeSDK(appDir, "python3.13") + s.Require().Error(err) + s.Contains(err.Error(), "celerity-sdk") +} + +func (s *SDKDetectTestSuite) Test_python_missing_pyproject_fails() { + appDir := s.T().TempDir() + err := RequireCelerityRuntimeSDK(appDir, "python3.13") + s.Require().Error(err) + s.Contains(err.Error(), "celerity-sdk") +} + +func (s *SDKDetectTestSuite) Test_python_celerity_sdk_boundary_avoids_false_positive_substring() { + appDir := s.newProject("", ` +[project] +dependencies = ["celerity-sdk-unrelated-tooling"] +`) + err := RequireCelerityRuntimeSDK(appDir, "python3.13") + s.Require().Error(err) +} + +func (s *SDKDetectTestSuite) Test_python_commented_celerity_sdk_is_ignored() { + appDir := s.newProject("", ` +[project] +# dependencies = ["celerity-sdk>=0.6.0"] +dependencies = ["boto3"] +`) + err := RequireCelerityRuntimeSDK(appDir, "python3.13") + s.Require().Error(err) +} + +// --- Other runtimes --- + +func (s *SDKDetectTestSuite) Test_non_node_non_python_runtime_is_nil() { + appDir := s.T().TempDir() + s.NoError(RequireCelerityRuntimeSDK(appDir, "rust1.x")) +} + +// --- helpers --- + +func (s *SDKDetectTestSuite) newProject(packageJSON, pyprojectTOML string) string { + appDir := s.T().TempDir() + if packageJSON != "" { + s.Require().NoError(os.WriteFile( + filepath.Join(appDir, "package.json"), []byte(packageJSON), 0644, + )) + } + if pyprojectTOML != "" { + s.Require().NoError(os.WriteFile( + filepath.Join(appDir, "pyproject.toml"), []byte(pyprojectTOML), 0644, + )) + } + return appDir +} diff --git a/apps/cli/internal/handlerresolve/toolchain_test.go b/apps/cli/internal/handlerresolve/toolchain_test.go new file mode 100644 index 00000000..6948d609 --- /dev/null +++ b/apps/cli/internal/handlerresolve/toolchain_test.go @@ -0,0 +1,186 @@ +package handlerresolve + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/consts" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" + "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +// stubToolchain records what it was asked for and answers with what the test +// set up. +type stubToolchain struct { + prepared []handlertoolchain.PrepareParams + extractCalls int + manifest *preprocess.HandlerManifest + prepareErr error + extractErr error + validateErr error +} + +func (t *stubToolchain) Name() string { return "stub" } + +func (t *stubToolchain) Validate(string) error { return t.validateErr } + +func (t *stubToolchain) Prepare(_ context.Context, p handlertoolchain.PrepareParams) error { + t.prepared = append(t.prepared, p) + return t.prepareErr +} + +func (t *stubToolchain) Extract( + context.Context, handlertoolchain.ExtractParams, +) (*preprocess.HandlerManifest, error) { + t.extractCalls++ + return t.manifest, t.extractErr +} + +func (t *stubToolchain) BuildBinary(context.Context, handlertoolchain.BinaryParams) error { + return nil +} + +func (t *stubToolchain) WatchPaths() handlertoolchain.WatchPaths { + return handlertoolchain.WatchPaths{} +} + +func (t *stubToolchain) TestCommand(string) ([]string, bool) { return nil, false } + +type ToolchainResolveSuite struct { + suite.Suite + appDir string + blueprintFile string + logger *zap.Logger +} + +func (s *ToolchainResolveSuite) SetupTest() { + s.appDir = s.T().TempDir() + s.logger = zap.NewNop() + s.blueprintFile = filepath.Join(s.appDir, "app.blueprint.yaml") + s.Require().NoError(os.WriteFile(s.blueprintFile, []byte(` +version: 2025-11-02 +transform: celerity-2026-02-28 +resources: + ordersTable: + type: "celerity/datastore" + spec: + name: orders + primaryDb: + type: "celerity/sqlDatabase" + spec: + engine: postgres + getOrder: + type: "celerity/handler" + metadata: + annotations: + celerity.handler.http: true + celerity.handler.http.method: "GET" + celerity.handler.http.path: "/orders/{orderId}" + spec: + handlerName: Orders-GetOrder-v1 + handler: getOrder + runtime: "os-only.debian13" +`), 0o644)) +} + +func (s *ToolchainResolveSuite) options(tc handlertoolchain.Toolchain) Options { + return Options{ + AppDir: s.appDir, + BlueprintFile: s.blueprintFile, + Toolchain: tc, + DeployTarget: "aws-serverless", + Mode: handlertoolchain.ModeDeploy, + } +} + +// A compiled language cannot discover its resources at startup, so the kinds +// the blueprint declares have to reach the toolchain that links them. +func (s *ToolchainResolveSuite) Test_prepare_receives_the_blueprints_resources_and_engines() { + tc := &stubToolchain{manifest: &preprocess.HandlerManifest{Version: "v1"}} + + _, err := Resolve(context.Background(), s.options(tc), s.logger) + s.Require().NoError(err) + + s.Require().Len(tc.prepared, 1) + s.Assert().Equal([]string{"datastore", "sqlDatabase"}, tc.prepared[0].ResourceKinds) + s.Assert().Equal([]string{"postgres"}, tc.prepared[0].SQLEngines) + s.Assert().Equal("aws-serverless", tc.prepared[0].DeployTarget) + s.Assert().Equal(handlertoolchain.ModeDeploy, tc.prepared[0].Mode) +} + +// Extraction compiles the application, so generation has to come first or it +// compiles against the wrong platform imports, or none. +func (s *ToolchainResolveSuite) Test_prepare_runs_before_extraction() { + tc := &stubToolchain{prepareErr: errors.New("generate failed")} + + _, err := Resolve(context.Background(), s.options(tc), s.logger) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "preparing the stub toolchain") + s.Assert().Zero(tc.extractCalls, "extraction should not run after generation failed") +} + +func (s *ToolchainResolveSuite) Test_the_toolchains_manifest_is_the_one_merged() { + tc := &stubToolchain{manifest: &preprocess.HandlerManifest{ + Version: "v1", + FunctionHandlers: []preprocess.FunctionHandler{{ + ResourceName: "listOrders", + Annotations: map[string]any{ + "celerity.handler.http": true, + "celerity.handler.http.method": "GET", + "celerity.handler.http.path": "/orders", + }, + Spec: preprocess.HandlerSpec{HandlerName: "Orders-ListOrders-v1", Handler: "listOrders"}, + }}, + }} + + resolved, err := Resolve(context.Background(), s.options(tc), s.logger) + s.Require().NoError(err) + s.Assert().Equal(1, tc.extractCalls) + s.Assert().Len(resolved.Manifest.FunctionHandlers, 1) + s.Assert().Contains(resolved.MergedBlueprint.Resources.Values, "listOrders") +} + +// A toolchain that cannot extract is not an error: the blueprint's +// hand-authored handler resources stand on their own. +func (s *ToolchainResolveSuite) Test_a_toolchain_that_does_not_extract_falls_back_to_the_blueprint() { + tc := &stubToolchain{manifest: nil} + + resolved, err := Resolve(context.Background(), s.options(tc), s.logger) + s.Require().NoError(err) + s.Assert().Empty(resolved.Manifest.AllHandlers()) + // The blueprint's own handler survives the merge. + s.Assert().Contains(resolved.MergedBlueprint.Resources.Values, "getOrder") +} + +func (s *ToolchainResolveSuite) Test_the_resolved_toolchain_is_handed_back_to_the_caller() { + tc := &stubToolchain{manifest: &preprocess.HandlerManifest{Version: "v1"}} + + resolved, err := Resolve(context.Background(), s.options(tc), s.logger) + s.Require().NoError(err) + s.Assert().Same(tc, resolved.Toolchain) +} + +func (s *ToolchainResolveSuite) Test_RequireRuntimeSDK_defers_to_the_toolchain() { + tc := &stubToolchain{validateErr: errors.New("go.mod does not require the SDK")} + + err := RequireRuntimeSDK(s.appDir, &ResolvedHandlers{ + Runtime: consts.RuntimeOSOnlyDebian13, + Toolchain: tc, + }) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "go.mod") +} + +// Without a toolchain it is the language SDK check as before. +func (s *ToolchainResolveSuite) Test_RequireRuntimeSDK_without_a_toolchain_checks_the_language_sdk() { + err := RequireRuntimeSDK(s.appDir, &ResolvedHandlers{Runtime: "nodejs24.x"}) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "package.json") +} + +func TestToolchainResolveSuite(t *testing.T) { suite.Run(t, new(ToolchainResolveSuite)) } diff --git a/apps/cli/internal/handlertoolchain/config.go b/apps/cli/internal/handlertoolchain/config.go new file mode 100644 index 00000000..8bff6d26 --- /dev/null +++ b/apps/cli/internal/handlertoolchain/config.go @@ -0,0 +1,156 @@ +package handlertoolchain + +import ( + "fmt" + "maps" + "slices" +) + +// Config is the handlerBuild block of an application's deploy config. +// +// It is what makes a community SDK for a compiled language usable without any +// CLI code. The author states how to produce a handlers executable and, where +// their SDK can, how to report what it serves, and everything the CLI does +// with the result is language-neutral. +// +// It lives on the deploy config rather than in celerity.config.toml because +// that provider carries only scalars, and because a build command legitimately +// differs per deploy target. +type Config struct { + // Command builds the handlers executable. Run through the shell, from the + // application directory. + Command string `json:"command"` + // Binary is where Command leaves the executable, relative to the + // application directory. The CLI copies it to wherever it is needed. + Binary string `json:"binary"` + // Env is added to Command's environment, on top of the CELERITY_BUILD_* + // variables the CLI injects. + Env map[string]string `json:"env,omitempty"` + // Tidy, where set, is run after Command to reconcile the project's + // dependency manifest. + Tidy string `json:"tidy,omitempty"` + // Extract reports the handlers the executable serves. Optional, and + // without it the blueprint's hand-authored handler resources are used as + // they are. + Extract *ExtractConfig `json:"extract,omitempty"` + // Test maps a suite name (unit, integration, api) to its command. + Test map[string]string `json:"test,omitempty"` + // WatchRoots are the directories a dev session watches, relative to the + // application directory. Defaults to the application directory itself. + WatchRoots []string `json:"watchRoots,omitempty"` + // WatchExtensions are the file extensions a dev session rebuilds for. + WatchExtensions []string `json:"watchExtensions,omitempty"` + // WatchSkipDirs are directory names the watcher does not descend into. + WatchSkipDirs []string `json:"watchSkipDirs,omitempty"` + // Targets overrides any of the above per deploy target. A cross-compiled + // binary usually lands somewhere different for each. + Targets map[string]*Config `json:"targets,omitempty"` +} + +// ExtractConfig describes a command that reports an application's handlers. +type ExtractConfig struct { + // Command produces a handler manifest. Run through the shell, from the + // application directory. + Command string `json:"command"` + // ManifestFile is where Command writes the manifest, relative to the + // application directory. When empty the manifest is read from the + // command's standard output. + ManifestFile string `json:"manifestFile,omitempty"` +} + +// Validate reports whether the block is usable. +func (c *Config) Validate() error { + if c == nil { + return nil + } + if c.Command == "" { + return fmt.Errorf("handlerBuild.command is required: it is the command that builds the handlers executable") + } + if c.Binary == "" { + return fmt.Errorf("handlerBuild.binary is required: it is where handlerBuild.command leaves the executable") + } + if c.Extract != nil && c.Extract.Command == "" { + return fmt.Errorf("handlerBuild.extract.command is required when handlerBuild.extract is set") + } + for target, override := range c.Targets { + if override == nil { + continue + } + if len(override.Targets) > 0 { + return fmt.Errorf("handlerBuild.targets.%s.targets is not allowed: overrides do not nest", target) + } + } + return nil +} + +// Overrides are applied field by field rather than wholesale, so an override +// naming only the binary path keeps the base command rather than silently +// blanking it. +func (c *Config) forTarget(deployTarget string) *Config { + if c == nil { + return nil + } + override, ok := c.Targets[deployTarget] + if !ok || override == nil { + return c + } + + merged := *c + merged.Targets = nil + + if override.Command != "" { + merged.Command = override.Command + } + if override.Binary != "" { + merged.Binary = override.Binary + } + if override.Tidy != "" { + merged.Tidy = override.Tidy + } + if override.Extract != nil { + merged.Extract = override.Extract + } + if len(override.Test) > 0 { + merged.Test = override.Test + } + if len(override.WatchRoots) > 0 { + merged.WatchRoots = override.WatchRoots + } + if len(override.WatchExtensions) > 0 { + merged.WatchExtensions = override.WatchExtensions + } + if len(override.WatchSkipDirs) > 0 { + merged.WatchSkipDirs = override.WatchSkipDirs + } + // Merged rather than replaced: env vars are independent settings, and an + // override adding one should not drop the rest. + if len(override.Env) > 0 { + merged.Env = make(map[string]string, len(c.Env)+len(override.Env)) + maps.Copy(merged.Env, c.Env) + maps.Copy(merged.Env, override.Env) + } else { + merged.Env = maps.Clone(c.Env) + } + + return &merged +} + +func (c *Config) watchPaths() WatchPaths { + roots := c.WatchRoots + if len(roots) == 0 { + roots = []string{"."} + } + skip := c.WatchSkipDirs + if len(skip) == 0 { + skip = []string{".celerity"} + } else if !slices.Contains(skip, ".celerity") { + // Always skipped, since it holds the CLI's own build output and + // watching it makes every rebuild trigger the next one. + skip = append(slices.Clone(skip), ".celerity") + } + return WatchPaths{ + Roots: roots, + Extensions: c.WatchExtensions, + SkipDirs: skip, + } +} diff --git a/apps/cli/internal/handlertoolchain/custom.go b/apps/cli/internal/handlertoolchain/custom.go new file mode 100644 index 00000000..e53975c6 --- /dev/null +++ b/apps/cli/internal/handlertoolchain/custom.go @@ -0,0 +1,167 @@ +package handlertoolchain + +import ( + "context" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" +) + +// Environment variables the CLI injects into every handlerBuild command, so a +// build script can key off what it is being asked for rather than hard-coding +// one platform and one deploy target. +const ( + EnvBuildOS = "CELERITY_BUILD_OS" + EnvBuildArch = "CELERITY_BUILD_ARCH" + EnvBuildOutput = "CELERITY_BUILD_OUTPUT" + EnvBuildDeployTarget = "CELERITY_BUILD_DEPLOY_TARGET" + EnvBuildMode = "CELERITY_BUILD_MODE" +) + +// customToolchain drives a handlerBuild block. +type customToolchain struct { + config *Config + runner Runner +} + +func newCustomToolchain(config *Config, runner Runner) *customToolchain { + return &customToolchain{config: config, runner: runner} +} + +func (t *customToolchain) Name() string { return "custom" } + +func (t *customToolchain) Validate(string) error { + // Resolve only selects this toolchain from a handlerBuild block it has + // already validated, so there is nothing left to check here. A missing + // compiler surfaces when the build command runs, which is where the error + // means something. + return nil +} + +// Prepare does nothing, since code generation for a community SDK is the +// build command's own business. +func (t *customToolchain) Prepare(context.Context, PrepareParams) error { return nil } + +func (t *customToolchain) BuildBinary(ctx context.Context, p BinaryParams) error { + cfg := t.config.forTarget(p.DeployTarget) + + output, err := filepath.Abs(p.OutputPath) + if err != nil { + return fmt.Errorf("resolving the handlers executable output path: %w", err) + } + if err := os.MkdirAll(filepath.Dir(output), 0o755); err != nil { + return fmt.Errorf("creating the output directory: %w", err) + } + + env := buildEnv(cfg.Env, p, output) + if err := t.runner.Run(ctx, p.AppDir, env, toolOutput(ctx), "sh", "-c", cfg.Command); err != nil { + return fmt.Errorf("handlerBuild.command failed: %w", err) + } + if cfg.Tidy != "" { + if err := t.runner.Run(ctx, p.AppDir, env, toolOutput(ctx), "sh", "-c", cfg.Tidy); err != nil { + return fmt.Errorf("handlerBuild.tidy failed: %w", err) + } + } + + // The command may have written straight to CELERITY_BUILD_OUTPUT, in + // which case the declared binary path is the same file and there is + // nothing to copy. + built := cfg.Binary + if !filepath.IsAbs(built) { + built = filepath.Join(p.AppDir, built) + } + if sameFile(built, output) { + return ensureExecutable(output) + } + + if err := copyExecutable(built, output); err != nil { + return fmt.Errorf( + "handlerBuild.command ran but %s is not there: %w.\n"+ + "handlerBuild.binary must name where the command leaves the executable", + cfg.Binary, err, + ) + } + return nil +} + +func (t *customToolchain) Extract(ctx context.Context, p ExtractParams) (*preprocess.HandlerManifest, error) { + cfg := t.config + if cfg.Extract == nil { + // With no extractor the blueprint's hand-authored handler resources + // stand on their own. + return nil, nil + } + + out, err := t.runner.Output(ctx, p.AppDir, cfg.Env, toolOutput(ctx), "sh", "-c", cfg.Extract.Command) + if err != nil { + return nil, fmt.Errorf("handlerBuild.extract.command failed: %w", err) + } + + data := out + if cfg.Extract.ManifestFile != "" { + path := cfg.Extract.ManifestFile + if !filepath.IsAbs(path) { + path = filepath.Join(p.AppDir, path) + } + data, err = os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("reading the manifest at handlerBuild.extract.manifestFile: %w", err) + } + } + + var manifest preprocess.HandlerManifest + if err := json.Unmarshal(data, &manifest); err != nil { + return nil, fmt.Errorf("parsing the handler manifest: %w", err) + } + if err := preprocess.ValidateManifest(&manifest); err != nil { + return nil, fmt.Errorf("handlerBuild.extract.command produced an unusable manifest: %w", err) + } + return &manifest, nil +} + +func (t *customToolchain) WatchPaths() WatchPaths { return t.config.watchPaths() } + +func (t *customToolchain) TestCommand(suite string) ([]string, bool) { + cmd, ok := t.config.Test[suite] + if !ok || cmd == "" { + return nil, false + } + return []string{"sh", "-c", cmd}, true +} + +func buildEnv(base map[string]string, p BinaryParams, output string) map[string]string { + env := make(map[string]string, len(base)+5) + for key, value := range base { + env[key] = value + } + env[EnvBuildOS] = p.OS + env[EnvBuildArch] = p.Arch + env[EnvBuildOutput] = output + env[EnvBuildDeployTarget] = p.DeployTarget + env[EnvBuildMode] = p.Mode + return env +} + +type toolOutputKey struct{} + +// WithToolOutput returns a context carrying where a toolchain's command output +// should be streamed. +// +// On the context because the sink is a property of how the CLI is being run, +// a log file when a TUI owns the terminal and stdout when it does not, rather +// than of the build being asked for. Threading it through every params struct +// would put it in the signature of calls that never produce any output. +func WithToolOutput(ctx context.Context, w io.Writer) context.Context { + return context.WithValue(ctx, toolOutputKey{}, w) +} + +func toolOutput(ctx context.Context) io.Writer { + if w, ok := ctx.Value(toolOutputKey{}).(io.Writer); ok && w != nil { + return w + } + return io.Discard +} diff --git a/apps/cli/internal/handlertoolchain/custom_test.go b/apps/cli/internal/handlertoolchain/custom_test.go new file mode 100644 index 00000000..07b65793 --- /dev/null +++ b/apps/cli/internal/handlertoolchain/custom_test.go @@ -0,0 +1,241 @@ +package handlertoolchain + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" +) + +type CustomToolchainSuite struct { + suite.Suite + appDir string + runner *stubRunner +} + +func (s *CustomToolchainSuite) SetupTest() { + s.appDir = s.T().TempDir() + s.runner = &stubRunner{} +} + +func (s *CustomToolchainSuite) toolchain(c *Config) *customToolchain { + return newCustomToolchain(c, s.runner) +} + +// writesBinaryAt makes the stub stand in for a build command that produced +// the executable the config names. +func (s *CustomToolchainSuite) writesBinaryAt(rel string) { + s.runner.onRun = func(recordedCommand) error { + path := filepath.Join(s.appDir, rel) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + return os.WriteFile(path, []byte("binary"), 0o644) + } +} + +func (s *CustomToolchainSuite) Test_BuildBinary_runs_the_command_and_collects_the_binary() { + s.writesBinaryAt("target/release/handlers") + tc := s.toolchain(&Config{Command: "cargo build --release", Binary: "target/release/handlers"}) + + out := filepath.Join(s.T().TempDir(), "handlers") + s.Require().NoError(tc.BuildBinary(context.Background(), BinaryParams{ + AppDir: s.appDir, OS: "linux", Arch: "arm64", OutputPath: out, + DeployTarget: "aws-serverless", Mode: ModeDeploy, + })) + + s.Require().Len(s.runner.commands, 1) + s.Assert().Equal("sh -c cargo build --release", s.runner.lines()[0]) + s.Assert().FileExists(out) + + info, err := os.Stat(out) + s.Require().NoError(err) + s.Assert().NotZero(info.Mode()&0o111, "expected the collected binary to be executable") +} + +// A build script keys off these rather than hard-coding one platform. +func (s *CustomToolchainSuite) Test_BuildBinary_injects_the_build_environment() { + s.writesBinaryAt("out/handlers") + tc := s.toolchain(&Config{ + Command: "make", Binary: "out/handlers", + Env: map[string]string{"RUSTFLAGS": "-C target-feature=+crt-static"}, + }) + + out := filepath.Join(s.T().TempDir(), "handlers") + s.Require().NoError(tc.BuildBinary(context.Background(), BinaryParams{ + AppDir: s.appDir, OS: "linux", Arch: "amd64", OutputPath: out, + DeployTarget: "aws-serverless", Mode: ModeDev, + })) + + env := s.runner.commands[0].Env + s.Assert().Equal("linux", env[EnvBuildOS]) + s.Assert().Equal("amd64", env[EnvBuildArch]) + s.Assert().Equal(out, env[EnvBuildOutput]) + s.Assert().Equal("aws-serverless", env[EnvBuildDeployTarget]) + s.Assert().Equal(ModeDev, env[EnvBuildMode]) + s.Assert().Equal("-C target-feature=+crt-static", env["RUSTFLAGS"]) +} + +// A cross-compiled binary lands somewhere different per target. +func (s *CustomToolchainSuite) Test_BuildBinary_applies_the_per_target_override() { + s.writesBinaryAt("target/aarch64/release/handlers") + tc := s.toolchain(&Config{ + Command: "cargo build --release", + Binary: "target/release/handlers", + Targets: map[string]*Config{ + "aws-serverless": {Binary: "target/aarch64/release/handlers"}, + }, + }) + + out := filepath.Join(s.T().TempDir(), "handlers") + s.Require().NoError(tc.BuildBinary(context.Background(), BinaryParams{ + AppDir: s.appDir, OS: "linux", Arch: "arm64", OutputPath: out, + DeployTarget: "aws-serverless", + })) + s.Assert().FileExists(out) + // The override named only the binary, so the base command still stands. + s.Assert().Equal("sh -c cargo build --release", s.runner.lines()[0]) +} + +func (s *CustomToolchainSuite) Test_BuildBinary_says_which_setting_is_wrong_when_the_binary_is_absent() { + tc := s.toolchain(&Config{Command: "true", Binary: "target/release/handlers"}) + + err := tc.BuildBinary(context.Background(), BinaryParams{ + AppDir: s.appDir, OutputPath: filepath.Join(s.T().TempDir(), "handlers"), + }) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "handlerBuild.binary") +} + +// A command that writes straight to CELERITY_BUILD_OUTPUT has already put the +// executable where it belongs. +func (s *CustomToolchainSuite) Test_BuildBinary_accepts_a_command_that_writes_to_the_output_path() { + out := filepath.Join(s.appDir, "build", "handlers") + s.runner.onRun = func(c recordedCommand) error { + path := c.Env[EnvBuildOutput] + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + return os.WriteFile(path, []byte("binary"), 0o644) + } + tc := s.toolchain(&Config{Command: "build.sh", Binary: "build/handlers"}) + + s.Require().NoError(tc.BuildBinary(context.Background(), BinaryParams{ + AppDir: s.appDir, OutputPath: out, + })) + info, err := os.Stat(out) + s.Require().NoError(err) + s.Assert().NotZero(info.Mode() & 0o111) +} + +// Without an extractor the blueprint's hand-authored handlers stand alone, +// which is not an error. +func (s *CustomToolchainSuite) Test_Extract_without_an_extractor_reports_nothing() { + tc := s.toolchain(&Config{Command: "make", Binary: "out/handlers"}) + + manifest, err := tc.Extract(context.Background(), ExtractParams{AppDir: s.appDir}) + s.Require().NoError(err) + s.Assert().Nil(manifest) + s.Assert().Empty(s.runner.commands) +} + +func (s *CustomToolchainSuite) Test_Extract_reads_the_manifest_from_stdout() { + s.runner.output = []byte(`{"version":"1","functionHandlers":[{"resourceName":"getOrder"}]}`) + tc := s.toolchain(&Config{ + Command: "make", Binary: "out/handlers", + Extract: &ExtractConfig{Command: "./scripts/extract"}, + }) + + manifest, err := tc.Extract(context.Background(), ExtractParams{AppDir: s.appDir}) + s.Require().NoError(err) + s.Require().NotNil(manifest) + s.Assert().Len(manifest.FunctionHandlers, 1) +} + +func (s *CustomToolchainSuite) Test_Extract_reads_the_manifest_from_a_declared_file() { + s.runner.onRun = func(recordedCommand) error { + return os.WriteFile( + filepath.Join(s.appDir, "manifest.json"), + []byte(`{"version":"1","functionHandlers":[{"resourceName":"getOrder"}]}`), 0o644) + } + tc := s.toolchain(&Config{ + Command: "make", Binary: "out/handlers", + Extract: &ExtractConfig{Command: "./scripts/extract", ManifestFile: "manifest.json"}, + }) + + manifest, err := tc.Extract(context.Background(), ExtractParams{AppDir: s.appDir}) + s.Require().NoError(err) + s.Require().NotNil(manifest) + s.Assert().Len(manifest.FunctionHandlers, 1) +} + +// The merge skips what it does not recognise, so an unusable manifest would +// otherwise produce an application with no handlers and no complaint. +func (s *CustomToolchainSuite) Test_Extract_refuses_a_manifest_the_merge_would_silently_skip() { + s.runner.output = []byte(`{"version":"1","functionHandlers":[{"exportName":"getOrder"}]}`) + tc := s.toolchain(&Config{ + Command: "make", Binary: "out/handlers", + Extract: &ExtractConfig{Command: "./scripts/extract"}, + }) + + _, err := tc.Extract(context.Background(), ExtractParams{AppDir: s.appDir}) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "resourceName") +} + +func (s *CustomToolchainSuite) Test_TestCommand_reports_only_configured_suites() { + tc := s.toolchain(&Config{ + Command: "make", Binary: "out/handlers", + Test: map[string]string{"unit": "cargo test"}, + }) + + cmd, ok := tc.TestCommand("unit") + s.Require().True(ok) + s.Assert().Equal([]string{"sh", "-c", "cargo test"}, cmd) + + _, ok = tc.TestCommand("integration") + s.Assert().False(ok) +} + +// Watching the CLI's own build output would make each rebuild trigger the next. +func (s *CustomToolchainSuite) Test_WatchPaths_always_skips_the_celerity_directory() { + tc := s.toolchain(&Config{ + Command: "make", Binary: "out/handlers", + WatchExtensions: []string{".rs"}, + WatchSkipDirs: []string{"target"}, + }) + + paths := tc.WatchPaths() + s.Assert().Equal([]string{"."}, paths.Roots) + s.Assert().Equal([]string{".rs"}, paths.Extensions) + s.Assert().Contains(paths.SkipDirs, "target") + s.Assert().Contains(paths.SkipDirs, ".celerity") +} + +func (s *CustomToolchainSuite) Test_forTarget_merges_env_rather_than_replacing_it() { + cfg := &Config{ + Command: "make", Binary: "out/handlers", + Env: map[string]string{"A": "1", "B": "2"}, + Targets: map[string]*Config{ + "aws-serverless": {Env: map[string]string{"B": "override", "C": "3"}}, + }, + } + + merged := cfg.forTarget("aws-serverless") + s.Assert().Equal(map[string]string{"A": "1", "B": "override", "C": "3"}, merged.Env) + s.Assert().Equal("make", merged.Command) +} + +func (s *CustomToolchainSuite) Test_Validate_rejects_nested_target_overrides() { + cfg := &Config{ + Command: "make", Binary: "out/handlers", + Targets: map[string]*Config{ + "aws-serverless": {Targets: map[string]*Config{"aws": {}}}, + }, + } + s.Assert().Error(cfg.Validate()) +} + +func TestCustomToolchainSuite(t *testing.T) { suite.Run(t, new(CustomToolchainSuite)) } diff --git a/apps/cli/internal/handlertoolchain/exec.go b/apps/cli/internal/handlertoolchain/exec.go new file mode 100644 index 00000000..6f341ee3 --- /dev/null +++ b/apps/cli/internal/handlertoolchain/exec.go @@ -0,0 +1,79 @@ +package handlertoolchain + +import ( + "context" + "fmt" + "io" + "os" + "os/exec" + "sort" +) + +// Runner runs the external commands a toolchain drives. +// +// Declared here rather than reused from internal/build so this package stays a +// leaf. The two are the same shape by coincidence of both shelling out rather +// than because they share a contract. +type Runner interface { + // Run executes name with args in dir, with env added to the process + // environment, streaming output to toolOutput. + Run(ctx context.Context, dir string, env map[string]string, toolOutput io.Writer, name string, args ...string) error + // Output executes the command and returns its standard output, streaming + // only standard error to toolOutput. + Output(ctx context.Context, dir string, env map[string]string, toolOutput io.Writer, name string, args ...string) ([]byte, error) +} + +// ExecRunner is the Runner backed by os/exec. +type ExecRunner struct{} + +func (ExecRunner) Run( + ctx context.Context, + dir string, + env map[string]string, + toolOutput io.Writer, + name string, + args ...string, +) error { + cmd := command(ctx, dir, env, name, args...) + cmd.Stdout = toolOutput + cmd.Stderr = toolOutput + if err := cmd.Run(); err != nil { + return fmt.Errorf("running %s: %w", name, err) + } + return nil +} + +func (ExecRunner) Output( + ctx context.Context, + dir string, + env map[string]string, + toolOutput io.Writer, + name string, + args ...string, +) ([]byte, error) { + cmd := command(ctx, dir, env, name, args...) + cmd.Stderr = toolOutput + out, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("running %s: %w", name, err) + } + return out, nil +} + +func command(ctx context.Context, dir string, env map[string]string, name string, args ...string) *exec.Cmd { + cmd := exec.CommandContext(ctx, name, args...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), envPairs(env)...) + return cmd +} + +// Sorted so a command line reproduces between runs and a test can assert on +// it. +func envPairs(env map[string]string) []string { + pairs := make([]string, 0, len(env)) + for key, value := range env { + pairs = append(pairs, key+"="+value) + } + sort.Strings(pairs) + return pairs +} diff --git a/apps/cli/internal/handlertoolchain/files.go b/apps/cli/internal/handlertoolchain/files.go new file mode 100644 index 00000000..ed7757d2 --- /dev/null +++ b/apps/cli/internal/handlertoolchain/files.go @@ -0,0 +1,107 @@ +package handlertoolchain + +import ( + "debug/elf" + "fmt" + "io" + "os" + "path/filepath" +) + +// The core runtime starts the handlers executable as a child process, so it +// has to carry the execute bit through every copy and archive on the way. +const executableMode os.FileMode = 0o755 + +func sameFile(a, b string) bool { + infoA, err := os.Stat(a) + if err != nil { + return false + } + infoB, err := os.Stat(b) + if err != nil { + return false + } + return os.SameFile(infoA, infoB) +} + +func ensureExecutable(path string) error { + if err := os.Chmod(path, executableMode); err != nil { + return fmt.Errorf("making %s executable: %w", filepath.Base(path), err) + } + return nil +} + +// The execute bit is set explicitly rather than carried over, because the mode +// a copy inherits depends on the umask and an executable that arrives without +// it fails as a bare "permission denied" from the supervisor. +func copyExecutable(src, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + + if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { + return err + } + + out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, executableMode) + if err != nil { + return err + } + defer out.Close() + + if _, err := io.Copy(out, in); err != nil { + return err + } + if err := out.Close(); err != nil { + return err + } + return ensureExecutable(dst) +} + +// CheckArchitecture reports whether the executable at path is built for the +// given GOARCH. +// +// Worth a check of its own because the failure it catches is otherwise +// invisible. An executable of the wrong architecture is a valid file the +// kernel refuses to exec, which surfaces as "exit status 126" with no +// indication of why, long after the build that caused it. +// +// A non-ELF file is not an error. A Lambda or container target is always +// Linux, so anything else is a build for somewhere the check does not apply +// rather than a mistake. +func CheckArchitecture(path, goarch string) error { + file, err := elf.Open(path) + if err != nil { + return nil + } + defer file.Close() + + want, ok := elfMachines[goarch] + if !ok { + return nil + } + if file.Machine != want { + return fmt.Errorf( + "the handlers executable at %s is built for %s, and this target needs %s.\n"+ + "The kernel refuses to run it, which shows up as exit status 126 with nothing else to go on", + path, machineGOARCH(file.Machine), goarch, + ) + } + return nil +} + +var elfMachines = map[string]elf.Machine{ + "arm64": elf.EM_AARCH64, + "amd64": elf.EM_X86_64, +} + +func machineGOARCH(machine elf.Machine) string { + for goarch, m := range elfMachines { + if m == machine { + return goarch + } + } + return machine.String() +} diff --git a/apps/cli/internal/handlertoolchain/files_test.go b/apps/cli/internal/handlertoolchain/files_test.go new file mode 100644 index 00000000..64865d32 --- /dev/null +++ b/apps/cli/internal/handlertoolchain/files_test.go @@ -0,0 +1,77 @@ +package handlertoolchain + +import ( + "debug/elf" + "encoding/binary" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" +) + +type ArchitectureSuite struct { + suite.Suite + dir string +} + +func (s *ArchitectureSuite) SetupTest() { s.dir = s.T().TempDir() } + +// writeELF writes a 64-byte ELF64 header declaring the given machine. Enough +// for debug/elf to read the architecture, which is all the check looks at. +func (s *ArchitectureSuite) writeELF(name string, machine elf.Machine) string { + header := make([]byte, 64) + copy(header, []byte{0x7f, 'E', 'L', 'F'}) + header[4] = 2 // ELFCLASS64 + header[5] = 1 // little endian + header[6] = 1 // version + binary.LittleEndian.PutUint16(header[16:], uint16(elf.ET_EXEC)) + binary.LittleEndian.PutUint16(header[18:], uint16(machine)) + binary.LittleEndian.PutUint32(header[20:], 1) + binary.LittleEndian.PutUint16(header[52:], 64) // e_ehsize + + path := filepath.Join(s.dir, name) + s.Require().NoError(os.WriteFile(path, header, executableMode)) + return path +} + +func (s *ArchitectureSuite) Test_matching_architecture_passes() { + s.Assert().NoError(CheckArchitecture(s.writeELF("arm", elf.EM_AARCH64), "arm64")) + s.Assert().NoError(CheckArchitecture(s.writeELF("x86", elf.EM_X86_64), "amd64")) +} + +// The kernel's refusal to exec a foreign binary surfaces as exit status 126 +// with nothing to say why, so the error has to supply the why itself. +func (s *ArchitectureSuite) Test_mismatched_architecture_names_both_sides() { + err := CheckArchitecture(s.writeELF("arm", elf.EM_AARCH64), "amd64") + s.Require().Error(err) + s.Assert().Contains(err.Error(), "arm64") + s.Assert().Contains(err.Error(), "amd64") + s.Assert().Contains(err.Error(), "126") +} + +// A non-ELF file means a build for somewhere the check does not apply, not a +// mistake. +func (s *ArchitectureSuite) Test_non_elf_file_is_not_an_error() { + path := filepath.Join(s.dir, "mach-o") + s.Require().NoError(os.WriteFile(path, []byte("not an elf file"), executableMode)) + s.Assert().NoError(CheckArchitecture(path, "arm64")) +} + +func (s *ArchitectureSuite) Test_unknown_goarch_is_not_checked() { + s.Assert().NoError(CheckArchitecture(s.writeELF("arm", elf.EM_AARCH64), "riscv64")) +} + +func (s *ArchitectureSuite) Test_copyExecutable_sets_the_execute_bit_regardless_of_the_source() { + src := filepath.Join(s.dir, "src") + s.Require().NoError(os.WriteFile(src, []byte("binary"), 0o600)) + + dst := filepath.Join(s.dir, "nested", "dst") + s.Require().NoError(copyExecutable(src, dst)) + + info, err := os.Stat(dst) + s.Require().NoError(err) + s.Assert().Equal(executableMode, info.Mode().Perm()) +} + +func TestArchitectureSuite(t *testing.T) { suite.Run(t, new(ArchitectureSuite)) } diff --git a/apps/cli/internal/handlertoolchain/golang.go b/apps/cli/internal/handlertoolchain/golang.go new file mode 100644 index 00000000..4ae84218 --- /dev/null +++ b/apps/cli/internal/handlertoolchain/golang.go @@ -0,0 +1,270 @@ +package handlertoolchain + +import ( + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + + "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" +) + +const ( + // GoToolBinary is the Celerity Go SDK's build-time tool. + GoToolBinary = "celerity-go" + + // GoToolModule is the module that tool is in. Its own module rather than + // the SDK's, so an application links no part of the build tooling. + GoToolModule = GoSDKModule + "/cmd/" + GoToolBinary + + // GoToolEnvVar overrides where that tool is found, for a checkout that + // has not installed it on PATH. + GoToolEnvVar = "CELERITY_GO_TOOL" + + // goGeneratedFile is what celerity-go generate writes. Target-specific, + // and expected to be gitignored. + goGeneratedFile = "celerity_platform_gen.go" +) + +// goToolchain drives the Celerity Go SDK's celerity-go tool. +type goToolchain struct { + runner Runner +} + +func newGoToolchain(runner Runner) *goToolchain { return &goToolchain{runner: runner} } + +func (t *goToolchain) Name() string { return "go" } + +func (t *goToolchain) Validate(appDir string) error { + declared, err := declaresGoSDK(appDir) + if err != nil { + return err + } + if !declared { + return fmt.Errorf( + "this is a Go application on an OS-only runtime, but go.mod does not require %s.\n"+ + "Run: go get %s", + GoSDKModule, GoSDKModule, + ) + } + return nil +} + +// Prepare writes the platform imports for the deploy target and reconciles +// go.mod. +// +// Regenerated every time rather than reused, because what generate writes is +// chosen for one deploy target and one mode. The file a dev session leaves +// behind links the local config store and emulator clients that a deployed +// artefact must not carry. +func (t *goToolchain) Prepare(ctx context.Context, p PrepareParams) error { + tool, err := goToolCommand(p.AppDir) + if err != nil { + return err + } + + args := []string{"generate", "--target", p.DeployTarget, "--package", "."} + if p.Mode == ModeDev { + args = append(args, "--local") + } + if len(p.ResourceKinds) > 0 { + args = append(args, "--resource", strings.Join(p.ResourceKinds, ",")) + } + if len(p.SQLEngines) > 0 { + args = append(args, "--sql-engine", strings.Join(p.SQLEngines, ",")) + } + if p.Telemetry != "" { + args = append(args, "--telemetry", p.Telemetry) + } + if p.TestPackages { + // No --test-tags alongside it. The tool defaults to the integration + // tag, which is the one TestCommand runs the integration suite under, + // so naming it here would be a second place for the two to disagree. + args = append(args, "--test-packages") + } + + name, args := invocation(tool, args...) + if err := t.runner.Run(ctx, p.AppDir, nil, toolOutput(ctx), name, args...); err != nil { + return fmt.Errorf("%s generate failed: %w", GoToolBinary, err) + } + + // generate writes imports go.mod does not declare, so the module has to be + // reconciled before anything will compile. + // + // tidy rather than `go mod download`, which resolves nothing that is not + // required yet, or `go get` of each platform module, which would need a + // second list of what generate writes kept in step here. The cost is + // tidy's breadth, being a whole-module reconciliation that also drops a + // requirement nothing imports any more. + if err := t.runner.Run(ctx, p.AppDir, nil, toolOutput(ctx), "go", "mod", "tidy"); err != nil { + return fmt.Errorf( + "go mod tidy failed after %s generate: %w.\n"+ + "generate writes platform imports that go.mod does not yet declare, so the module "+ + "has to be reconciled before the application will build", + GoToolBinary, err, + ) + } + return nil +} + +func (t *goToolchain) Extract(ctx context.Context, p ExtractParams) (*preprocess.HandlerManifest, error) { + tool, err := goToolCommand(p.AppDir) + if err != nil { + return nil, err + } + + // celerity-go writes the manifest to a file and prints a human summary to + // standard output, so unlike the Node and Python extractors there is + // nothing to read off the pipe. + out, err := os.CreateTemp("", "celerity-handler-manifest-*.json") + if err != nil { + return nil, fmt.Errorf("making somewhere for the handler manifest: %w", err) + } + manifestPath := out.Name() + _ = out.Close() + defer os.Remove(manifestPath) + + name, args := invocation(tool, "extract", "--package", ".", "--out", manifestPath) + err = t.runner.Run(ctx, p.AppDir, nil, toolOutput(ctx), name, args...) + if err != nil { + return nil, fmt.Errorf("%s extract failed: %w", GoToolBinary, err) + } + + data, err := os.ReadFile(manifestPath) + if err != nil { + return nil, fmt.Errorf("reading the handler manifest %s wrote: %w", GoToolBinary, err) + } + + var manifest preprocess.HandlerManifest + if err := json.Unmarshal(data, &manifest); err != nil { + return nil, fmt.Errorf("parsing the handler manifest: %w", err) + } + if err := preprocess.ValidateManifest(&manifest); err != nil { + return nil, fmt.Errorf("%s produced an unusable manifest: %w", GoToolBinary, err) + } + return &manifest, nil +} + +func (t *goToolchain) BuildBinary(ctx context.Context, p BinaryParams) error { + output, err := filepath.Abs(p.OutputPath) + if err != nil { + return fmt.Errorf("resolving the handlers executable output path: %w", err) + } + if err := os.MkdirAll(filepath.Dir(output), 0o755); err != nil { + return fmt.Errorf("creating the output directory: %w", err) + } + + // Statically linked, because the image the executable is built against is + // not the one it ends up on. An OS-only runtime identifier maps to a + // different base OS on each deploy target, and a dynamically linked binary + // built on the newest of them will not start on the oldest. + env := map[string]string{ + "CGO_ENABLED": "0", + "GOOS": p.OS, + "GOARCH": p.Arch, + } + args := []string{"build", "-trimpath", "-ldflags", "-s -w", "-o", output, "."} + if err := t.runner.Run(ctx, p.AppDir, env, toolOutput(ctx), "go", args...); err != nil { + return fmt.Errorf("go build failed: %w", err) + } + + if err := ensureExecutable(output); err != nil { + return err + } + return CheckArchitecture(output, p.Arch) +} + +func (t *goToolchain) WatchPaths() WatchPaths { + return WatchPaths{ + // The module root rather than src/, since a Go module keeps its + // handlers wherever its packages are and the main package is commonly + // under cmd/. + Roots: []string{"."}, + // Source only. go.mod is rewritten by the `go mod tidy` that Prepare + // runs, so watching it would put the same rebuild loop back by + // another route. + Extensions: []string{".go"}, + SkipDirs: []string{".celerity", "vendor"}, + // Rewritten by every Prepare, which a rebuild runs, so reacting to it + // would make each rebuild trigger the next. + SkipFiles: []string{goGeneratedFile}, + } +} + +func (t *goToolchain) TestCommand(suite string) ([]string, bool) { + switch suite { + case "unit": + return []string{"go", "test", "./..."}, true + case "integration": + return []string{"go", "test", "-tags", "integration", "./..."}, true + case "api": + return []string{"go", "test", "-tags", "api", "./..."}, true + default: + return nil, false + } +} + +// The prefix is more than one word where celerity-go is reached through the Go +// toolchain rather than as a binary of its own, so the subcommand cannot +// simply be the first argument. +func invocation(prefix []string, args ...string) (string, []string) { + full := make([]string, 0, len(prefix)-1+len(args)) + full = append(full, prefix[1:]...) + full = append(full, args...) + return prefix[0], full +} + +// Returns the command that runs celerity-go, as a prefix the subcommand is +// appended to. +// +// The tool dependency is preferred over PATH, and that order is the point. +// celerity-go generate writes imports of SDK packages and extract emits the +// SDK's manifest format, so the tool and the SDK the application compiles +// against have to be the same version. A tool dependency is resolved by the +// same minimal version selection as the SDK requirement beside it, making +// agreement structural, while one on PATH is whatever was installed globally +// and last. +// +// Nothing is downloaded, and `go run @` is not used either. +// The tool shells out to go build, go mod tidy and go list, so it cannot run +// without a Go toolchain and a fetched binary would save nothing, and a +// version guessed here would be the very mismatch the ordering above prevents. +func goToolCommand(appDir string) ([]string, error) { + if override := os.Getenv(GoToolEnvVar); override != "" { + return []string{override}, nil + } + + goMod, err := readGoMod(appDir) + if err != nil { + return nil, err + } + if declaresTool(goMod, GoToolModule) { + return []string{"go", "tool", GoToolBinary}, nil + } + + if path, err := exec.LookPath(GoToolBinary); err == nil { + return []string{path}, nil + } + + return nil, fmt.Errorf("%s", missingGoTool(goMod)) +} + +// The fix is named at the version the application already requires rather +// than at whatever is newest, since the two have to match. +func missingGoTool(goMod string) string { + at := "" + if version, found := requires(goMod, GoSDKModule); found && version != "" { + at = "@" + version + } + + return fmt.Sprintf( + "%s is not available, and it is what builds a Go application for a deploy target.\n"+ + "Declare it alongside the SDK so the two stay at one version:\n"+ + " go get -tool %s%s\n"+ + "Alternatively put it on PATH, or point %s at it.", + GoToolBinary, GoToolModule, at, GoToolEnvVar, + ) +} diff --git a/apps/cli/internal/handlertoolchain/golang_test.go b/apps/cli/internal/handlertoolchain/golang_test.go new file mode 100644 index 00000000..00a253fe --- /dev/null +++ b/apps/cli/internal/handlertoolchain/golang_test.go @@ -0,0 +1,322 @@ +package handlertoolchain + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" + "github.com/stretchr/testify/suite" +) + +type GoToolchainSuite struct { + suite.Suite + appDir string + runner *stubRunner + tc *goToolchain +} + +func (s *GoToolchainSuite) SetupTest() { + s.appDir = s.T().TempDir() + s.runner = &stubRunner{} + s.tc = newGoToolchain(s.runner) + // Resolved from the env var so the suite does not need celerity-go + // installed on the host. + s.T().Setenv(GoToolEnvVar, "/usr/local/bin/celerity-go") +} + +func (s *GoToolchainSuite) prepare(p PrepareParams) error { + p.AppDir = s.appDir + return s.tc.Prepare(context.Background(), p) +} + +func (s *GoToolchainSuite) Test_Prepare_generates_for_the_deploy_target_then_reconciles_the_module() { + s.Require().NoError(s.prepare(PrepareParams{DeployTarget: "aws-serverless", Mode: ModeDeploy})) + + s.Require().Len(s.runner.commands, 2) + s.Assert().Contains(s.runner.lines()[0], "generate --target aws-serverless --package .") + s.Assert().Equal("go mod tidy", s.runner.lines()[1]) +} + +// A dev session reads its own config store and talks to local emulators, so +// it links packages a deployed artefact must not carry. +func (s *GoToolchainSuite) Test_Prepare_passes_local_only_in_dev_mode() { + s.Require().NoError(s.prepare(PrepareParams{DeployTarget: "aws-serverless", Mode: ModeDev})) + s.Assert().Contains(s.runner.lines()[0], "--local") + + s.runner.commands = nil + s.Require().NoError(s.prepare(PrepareParams{DeployTarget: "aws-serverless", Mode: ModeDeploy})) + s.Assert().NotContains(s.runner.lines()[0], "--local") +} + +func (s *GoToolchainSuite) Test_Prepare_passes_blueprint_resources_and_engines() { + s.Require().NoError(s.prepare(PrepareParams{ + DeployTarget: "aws-serverless", + Mode: ModeDeploy, + ResourceKinds: []string{"bucket", "datastore"}, + SQLEngines: []string{"postgres"}, + Telemetry: "otel", + })) + + line := s.runner.lines()[0] + s.Assert().Contains(line, "--resource bucket,datastore") + s.Assert().Contains(line, "--sql-engine postgres") + s.Assert().Contains(line, "--telemetry otel") +} + +// A test that reaches a real resource has to reach it through the same +// provider the application does, and in Go that means the provider package is +// linked into the test binary too. +func (s *GoToolchainSuite) Test_Prepare_generates_for_the_integration_suites_when_asked() { + s.Require().NoError(s.prepare(PrepareParams{ + DeployTarget: "aws-serverless", + Mode: ModeDev, + TestPackages: true, + })) + + s.Assert().Contains(s.runner.lines()[0], "--test-packages") +} + +// Nothing in a deployed artefact reads them, so generating them would write +// files into source for no reader. +func (s *GoToolchainSuite) Test_Prepare_leaves_the_test_suites_alone_by_default() { + s.Require().NoError(s.prepare(PrepareParams{DeployTarget: "aws-serverless", Mode: ModeDeploy})) + + s.Assert().NotContains(s.runner.lines()[0], "--test-packages") +} + +func (s *GoToolchainSuite) Test_Prepare_explains_why_the_module_had_to_be_reconciled() { + s.runner.failOn = "go mod tidy" + + err := s.prepare(PrepareParams{DeployTarget: "aws-serverless", Mode: ModeDeploy}) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "platform imports") +} + +// Statically linked, because the base OS differs between the image the +// executable is built against and the ones it is deployed to. +func (s *GoToolchainSuite) Test_BuildBinary_builds_a_static_stripped_binary_for_the_target() { + out := filepath.Join(s.appDir, ".celerity", "dev", "handlers") + s.runner.onRun = func(recordedCommand) error { + return os.WriteFile(out, []byte("binary"), 0o644) + } + + err := s.tc.BuildBinary(context.Background(), BinaryParams{ + AppDir: s.appDir, OS: "linux", Arch: "arm64", OutputPath: out, + }) + s.Require().NoError(err) + + s.Require().Len(s.runner.commands, 1) + cmd := s.runner.commands[0] + s.Assert().Equal("go", cmd.Name) + s.Assert().Contains(cmd.line(), "-trimpath") + s.Assert().Equal("0", cmd.Env["CGO_ENABLED"]) + s.Assert().Equal("linux", cmd.Env["GOOS"]) + s.Assert().Equal("arm64", cmd.Env["GOARCH"]) +} + +// The runtime starts the executable as a child process, so a build that left +// it unreadable as a program fails as a bare permission error. +func (s *GoToolchainSuite) Test_BuildBinary_leaves_the_executable_bit_set() { + out := filepath.Join(s.appDir, "handlers") + s.runner.onRun = func(recordedCommand) error { + return os.WriteFile(out, []byte("binary"), 0o600) + } + + s.Require().NoError(s.tc.BuildBinary(context.Background(), BinaryParams{ + AppDir: s.appDir, OS: "linux", Arch: "arm64", OutputPath: out, + })) + + info, err := os.Stat(out) + s.Require().NoError(err) + s.Assert().NotZero(info.Mode()&0o111, "expected the executable bit to be set") +} + +func (s *GoToolchainSuite) Test_Extract_reads_the_manifest_from_the_file_the_tool_writes() { + s.runner.onRun = func(c recordedCommand) error { + // celerity-go prints a human summary and writes the manifest to the + // path given by --out, so there is nothing to read off stdout. + return os.WriteFile(outFlag(c.Args), []byte(`{ + "version": "v1", + "handlers": [], + "functionHandlers": [{"resourceName": "getOrder", "exportName": "getOrder"}], + "guardHandlers": [] + }`), 0o644) + } + + manifest, err := s.tc.Extract(context.Background(), ExtractParams{AppDir: s.appDir}) + s.Require().NoError(err) + s.Require().NotNil(manifest) + s.Assert().Len(manifest.FunctionHandlers, 1) + s.Assert().Equal("getOrder", manifest.FunctionHandlers[0].ResourceName) +} + +func (s *GoToolchainSuite) Test_Extract_rejects_an_unusable_manifest() { + s.runner.onRun = func(c recordedCommand) error { + return os.WriteFile(outFlag(c.Args), []byte(`{"version":"v1","functionHandlers":[{"exportName":"x"}]}`), 0o644) + } + + _, err := s.tc.Extract(context.Background(), ExtractParams{AppDir: s.appDir}) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "resourceName") +} + +func (s *GoToolchainSuite) Test_Validate_requires_the_sdk_in_go_mod() { + err := s.tc.Validate(s.appDir) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "go get "+GoSDKModule) + + s.Require().NoError(os.WriteFile( + filepath.Join(s.appDir, "go.mod"), + []byte("module example.com/app\n\nrequire "+GoSDKModule+" v0.1.0\n"), 0o644)) + s.Assert().NoError(s.tc.Validate(s.appDir)) +} + +func (s *GoToolchainSuite) Test_the_tool_is_taken_from_the_env_override_first() { + s.T().Setenv(GoToolEnvVar, "/opt/celerity/celerity-go") + + prefix, err := goToolCommand(s.appDir) + + s.Require().NoError(err) + s.Assert().Equal([]string{"/opt/celerity/celerity-go"}, prefix) +} + +// Preferred over PATH, because a tool dependency is resolved by the same +// version selection as the SDK requirement beside it while one on PATH is +// whatever was installed last. +func (s *GoToolchainSuite) Test_a_tool_dependency_is_preferred_over_one_on_the_path() { + s.T().Setenv(GoToolEnvVar, "") + s.onPath(GoToolBinary) + s.writeGoMod("module example.com/app\n\nrequire " + GoSDKModule + " v0.2.1\n" + + "\ntool " + GoToolModule + "\n") + + prefix, err := goToolCommand(s.appDir) + + s.Require().NoError(err) + s.Assert().Equal([]string{"go", "tool", GoToolBinary}, prefix) +} + +func (s *GoToolchainSuite) Test_a_tool_dependency_inside_a_block_counts_too() { + s.T().Setenv(GoToolEnvVar, "") + s.T().Setenv("PATH", s.T().TempDir()) + s.writeGoMod("module example.com/app\n\ntool (\n\t" + GoToolModule + "\n)\n") + + prefix, err := goToolCommand(s.appDir) + + s.Require().NoError(err) + s.Assert().Equal([]string{"go", "tool", GoToolBinary}, prefix) +} + +func (s *GoToolchainSuite) Test_the_path_is_used_where_nothing_declares_the_tool() { + s.T().Setenv(GoToolEnvVar, "") + binary := s.onPath(GoToolBinary) + s.writeGoMod("module example.com/app\n\nrequire " + GoSDKModule + " v0.2.1\n") + + prefix, err := goToolCommand(s.appDir) + + s.Require().NoError(err) + s.Assert().Equal([]string{binary}, prefix) +} + +// At the version the application already requires rather than at whatever is +// newest, since generate writes imports of that version's packages. +func (s *GoToolchainSuite) Test_an_absent_tool_names_the_command_that_adds_it() { + s.T().Setenv(GoToolEnvVar, "") + s.T().Setenv("PATH", s.T().TempDir()) + s.writeGoMod("module example.com/app\n\nrequire " + GoSDKModule + " v0.2.1\n") + + _, err := goToolCommand(s.appDir) + + s.Require().Error(err) + s.Assert().Contains(err.Error(), "go get -tool "+GoToolModule+"@v0.2.1") + s.Assert().Contains(err.Error(), GoToolEnvVar) +} + +func (s *GoToolchainSuite) Test_an_absent_tool_omits_a_version_it_cannot_read() { + s.T().Setenv(GoToolEnvVar, "") + s.T().Setenv("PATH", s.T().TempDir()) + + _, err := goToolCommand(s.appDir) + + s.Require().Error(err) + s.Assert().Contains(err.Error(), "go get -tool "+GoToolModule+"\n") +} + +// A path that merely begins with the SDK's is a different module. +func (s *GoToolchainSuite) Test_a_lookalike_module_is_not_the_tool() { + s.T().Setenv(GoToolEnvVar, "") + s.T().Setenv("PATH", s.T().TempDir()) + s.writeGoMod("module example.com/app\n\ntool " + GoToolModule + "-contrib\n") + + _, err := goToolCommand(s.appDir) + + s.Require().Error(err) +} + +func (s *GoToolchainSuite) writeGoMod(contents string) { + s.T().Helper() + s.Require().NoError(os.WriteFile(filepath.Join(s.appDir, "go.mod"), []byte(contents), 0o755)) +} + +// onPath puts an executable of that name on PATH and answers with its path. +func (s *GoToolchainSuite) onPath(name string) string { + s.T().Helper() + dir := s.T().TempDir() + path := filepath.Join(dir, name) + s.Require().NoError(os.WriteFile(path, []byte("#!/bin/sh\n"), 0o755)) + s.T().Setenv("PATH", dir) + return path +} + +func (s *GoToolchainSuite) Test_WatchPaths_covers_the_module_root_and_skips_build_output() { + paths := s.tc.WatchPaths() + s.Assert().Equal([]string{"."}, paths.Roots) + s.Assert().Equal([]string{".go"}, paths.Extensions) + s.Assert().Contains(paths.SkipDirs, ".celerity") + s.Assert().Contains(paths.SkipFiles, goGeneratedFile, + "Prepare rewrites it, so reacting to it would make each rebuild trigger the next") +} + +// outFlag reports the value of --out in a recorded command. +func outFlag(args []string) string { + for i, arg := range args { + if arg == "--out" && i+1 < len(args) { + return args[i+1] + } + } + return "" +} + +func TestGoToolchainSuite(t *testing.T) { suite.Run(t, new(GoToolchainSuite)) } + +// The manifest the Go SDK emits declares "v1" while the CLI's own fallback +// constructs "1". Both have been in the wild unvalidated, so both are read. +func TestValidateManifest_acceptsBothVersionSpellings(t *testing.T) { + for _, version := range []string{"1", "v1"} { + var m preprocess.HandlerManifest + err := json.Unmarshal([]byte(`{"version":"`+version+`"}`), &m) + if err != nil { + t.Fatal(err) + } + if err := preprocess.ValidateManifest(&m); err != nil { + t.Fatalf("version %q: %v", version, err) + } + } +} + +func TestValidateManifest_namesTheOffendingAnnotation(t *testing.T) { + m := &preprocess.HandlerManifest{ + Version: "v1", + FunctionHandlers: []preprocess.FunctionHandler{{ + ResourceName: "getOrder", + Annotations: map[string]any{"handler.http": true}, + }}, + } + err := preprocess.ValidateManifest(m) + if err == nil || !strings.Contains(err.Error(), "handler.http") { + t.Fatalf("expected the bad annotation key to be named, got %v", err) + } +} diff --git a/apps/cli/internal/handlertoolchain/gomod.go b/apps/cli/internal/handlertoolchain/gomod.go new file mode 100644 index 00000000..7765a54a --- /dev/null +++ b/apps/cli/internal/handlertoolchain/gomod.go @@ -0,0 +1,99 @@ +package handlertoolchain + +import ( + "fmt" + "os" + "path/filepath" + "strings" +) + +// A text scan rather than a go.mod parse. All that is asked of the file is +// whether a module path appears as a requirement, whether it appears as a +// tool, and what version a requirement names, none of which need the file +// understood, and reaching for golang.org/x/mod would pull a dependency into +// a package that otherwise needs none. + +func readGoMod(appDir string) (string, error) { + data, err := os.ReadFile(filepath.Join(appDir, "go.mod")) + if err != nil { + if os.IsNotExist(err) { + return "", nil + } + return "", fmt.Errorf("reading go.mod: %w", err) + } + return string(data), nil +} + +// A path that merely starts with the one asked for does not count, so a +// hypothetical celerity-go-sdk-contrib is not mistaken for the SDK. +func requires(goMod, modulePath string) (version string, found bool) { + for line := range strings.Lines(goMod) { + rest, ok := directiveArgument(line, modulePath) + if !ok { + continue + } + fields := strings.Fields(rest) + if len(fields) == 0 { + return "", true + } + return fields[0], true + } + return "", false +} + +// A tool dependency is what makes `go tool ` resolve a module. Both +// spellings count, a lone `tool ` and a path inside a `tool (...)` +// block. +func declaresTool(goMod, modulePath string) bool { + inBlock := false + for line := range strings.Lines(goMod) { + trimmed := strings.TrimSpace(line) + if strings.HasPrefix(trimmed, "//") { + continue + } + + switch { + case trimmed == "tool (": + inBlock = true + continue + case inBlock && trimmed == ")": + inBlock = false + continue + } + + candidate := trimmed + if !inBlock { + after, isTool := strings.CutPrefix(trimmed, "tool ") + if !isTool { + continue + } + candidate = strings.TrimSpace(after) + } + if candidate == modulePath { + return true + } + } + return false +} + +// Returns the remainder of a line that names a module path, having rejected +// comments and longer paths that merely begin with it. +func directiveArgument(line, modulePath string) (rest string, found bool) { + trimmed := strings.TrimSpace(line) + if strings.HasPrefix(trimmed, "//") { + return "", false + } + _, after, ok := strings.Cut(trimmed, modulePath) + if !ok { + return "", false + } + if after != "" && isModulePathChar(after[0]) { + return "", false + } + return strings.TrimSpace(after), true +} + +func isModulePathChar(c byte) bool { + return c == '-' || c == '.' || c == '_' || c == '/' || + (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') +} diff --git a/apps/cli/internal/handlertoolchain/resolve.go b/apps/cli/internal/handlertoolchain/resolve.go new file mode 100644 index 00000000..75df0da1 --- /dev/null +++ b/apps/cli/internal/handlertoolchain/resolve.go @@ -0,0 +1,80 @@ +package handlertoolchain + +import ( + "fmt" + "strings" + + "github.com/newstack-cloud/celerity/apps/cli/internal/consts" +) + +// GoSDKModule is the Celerity Go SDK's module path. A go.mod requiring it is +// what identifies a Go Celerity application. +const GoSDKModule = "github.com/newstack-cloud/celerity-go-sdk" + +// Options configures toolchain resolution. +type Options struct { + // Runtime is the blueprint's runtime identifier. + Runtime string + // AppDir is the application directory. + AppDir string + // Config is the handlerBuild block, or nil when the app declares none. + Config *Config + // Runner runs external commands. Defaults to ExecRunner. + Runner Runner +} + +// Resolve returns the toolchain for an application, or (nil, nil) where the +// runtime is not an OS-only one. +// +// Returning nil rather than an error for Node.js and Python keeps every call +// site uniform. A caller threads whatever comes back, and the nil case means +// the runtime hosts the language itself and there is nothing to build. +// +// An explicit handlerBuild block wins over an inferred Go project, because a +// Go application that declares one has asked to drive its own build. +func Resolve(opts Options) (Toolchain, error) { + if !IsOSOnly(opts.Runtime) { + return nil, nil + } + + runner := opts.Runner + if runner == nil { + runner = ExecRunner{} + } + + if opts.Config != nil { + if err := opts.Config.Validate(); err != nil { + return nil, err + } + return newCustomToolchain(opts.Config, runner), nil + } + + isGo, err := declaresGoSDK(opts.AppDir) + if err != nil { + return nil, err + } + if isGo { + return newGoToolchain(runner), nil + } + + return nil, fmt.Errorf( + "runtime %q needs a handlers executable, and this project does not say how to build one.\n"+ + "For Go, require %s in go.mod. For another compiled language, add a handlerBuild "+ + "block to your deploy config naming the command that builds the executable", + opts.Runtime, GoSDKModule, + ) +} + +// IsOSOnly reports whether a runtime identifier names an OS-only runtime. +func IsOSOnly(runtime string) bool { + return strings.HasPrefix(runtime, consts.RuntimeOSOnly) +} + +func declaresGoSDK(appDir string) (bool, error) { + goMod, err := readGoMod(appDir) + if err != nil { + return false, err + } + _, found := requires(goMod, GoSDKModule) + return found, nil +} diff --git a/apps/cli/internal/handlertoolchain/resolve_test.go b/apps/cli/internal/handlertoolchain/resolve_test.go new file mode 100644 index 00000000..adece7fa --- /dev/null +++ b/apps/cli/internal/handlertoolchain/resolve_test.go @@ -0,0 +1,112 @@ +package handlertoolchain + +import ( + "os" + "path/filepath" + "testing" + + "github.com/newstack-cloud/celerity/apps/cli/internal/consts" + "github.com/stretchr/testify/suite" +) + +type ResolveSuite struct { + suite.Suite + appDir string +} + +func (s *ResolveSuite) SetupTest() { s.appDir = s.T().TempDir() } + +func (s *ResolveSuite) writeGoMod(contents string) { + s.Require().NoError(os.WriteFile(filepath.Join(s.appDir, "go.mod"), []byte(contents), 0o644)) +} + +func (s *ResolveSuite) validConfig() *Config { + return &Config{Command: "cargo build --release", Binary: "target/release/handlers"} +} + +// A runtime that hosts the language itself has no executable to build, so +// there is nothing to resolve and nothing to report. +func (s *ResolveSuite) Test_non_os_only_runtime_resolves_to_nothing() { + for _, runtime := range []string{"nodejs24.x", "python3.13"} { + toolchain, err := Resolve(Options{Runtime: runtime, AppDir: s.appDir}) + s.Require().NoError(err, runtime) + s.Assert().Nil(toolchain, runtime) + } +} + +func (s *ResolveSuite) Test_go_module_requiring_the_sdk_resolves_to_the_go_toolchain() { + s.writeGoMod("module example.com/app\n\ngo 1.26.0\n\nrequire " + GoSDKModule + " v0.1.0\n") + + toolchain, err := Resolve(Options{Runtime: consts.RuntimeOSOnlyDebian13, AppDir: s.appDir}) + s.Require().NoError(err) + s.Require().NotNil(toolchain) + s.Assert().Equal("go", toolchain.Name()) +} + +func (s *ResolveSuite) Test_handler_build_block_resolves_to_the_custom_toolchain() { + toolchain, err := Resolve(Options{ + Runtime: consts.RuntimeOSOnlyDebian13, + AppDir: s.appDir, + Config: s.validConfig(), + }) + s.Require().NoError(err) + s.Require().NotNil(toolchain) + s.Assert().Equal("custom", toolchain.Name()) +} + +// An author who wrote a handlerBuild block has said they want to drive their +// own build, so it wins over the Go project the directory also looks like. +func (s *ResolveSuite) Test_handler_build_block_beats_an_inferred_go_project() { + s.writeGoMod("module example.com/app\n\nrequire " + GoSDKModule + " v0.1.0\n") + + toolchain, err := Resolve(Options{ + Runtime: consts.RuntimeOSOnlyDebian13, + AppDir: s.appDir, + Config: s.validConfig(), + }) + s.Require().NoError(err) + s.Assert().Equal("custom", toolchain.Name()) +} + +func (s *ResolveSuite) Test_os_only_with_no_signal_says_both_ways_to_fix_it() { + _, err := Resolve(Options{Runtime: consts.RuntimeOSOnlyDebian13, AppDir: s.appDir}) + s.Require().Error(err) + s.Assert().Contains(err.Error(), GoSDKModule) + s.Assert().Contains(err.Error(), "handlerBuild") +} + +// A go.mod that does not require the SDK is a Go project that is not a +// Celerity application, which is not the same as a Go Celerity application. +func (s *ResolveSuite) Test_go_module_without_the_sdk_is_not_a_go_project() { + s.writeGoMod("module example.com/app\n\ngo 1.26.0\n") + + _, err := Resolve(Options{Runtime: consts.RuntimeOSOnlyDebian13, AppDir: s.appDir}) + s.Require().Error(err) +} + +func (s *ResolveSuite) Test_commented_out_requirement_is_not_a_requirement() { + s.writeGoMod("module example.com/app\n\n// require " + GoSDKModule + " v0.1.0\n") + + _, err := Resolve(Options{Runtime: consts.RuntimeOSOnlyDebian13, AppDir: s.appDir}) + s.Require().Error(err) +} + +// A module whose path merely starts with the SDK's is a different module. +func (s *ResolveSuite) Test_longer_module_path_is_not_the_sdk() { + s.writeGoMod("module example.com/app\n\nrequire " + GoSDKModule + "-contrib v0.1.0\n") + + _, err := Resolve(Options{Runtime: consts.RuntimeOSOnlyDebian13, AppDir: s.appDir}) + s.Require().Error(err) +} + +func (s *ResolveSuite) Test_invalid_handler_build_block_is_refused() { + _, err := Resolve(Options{ + Runtime: consts.RuntimeOSOnlyDebian13, + AppDir: s.appDir, + Config: &Config{Binary: "target/release/handlers"}, + }) + s.Require().Error(err) + s.Assert().Contains(err.Error(), "handlerBuild.command") +} + +func TestResolveSuite(t *testing.T) { suite.Run(t, new(ResolveSuite)) } diff --git a/apps/cli/internal/handlertoolchain/stub_runner_test.go b/apps/cli/internal/handlertoolchain/stub_runner_test.go new file mode 100644 index 00000000..af3a79f5 --- /dev/null +++ b/apps/cli/internal/handlertoolchain/stub_runner_test.go @@ -0,0 +1,76 @@ +package handlertoolchain + +import ( + "context" + "io" + "strings" +) + +// recordedCommand is one invocation a stubRunner saw. +type recordedCommand struct { + Dir string + Env map[string]string + Name string + Args []string +} + +func (c recordedCommand) line() string { + return strings.Join(append([]string{c.Name}, c.Args...), " ") +} + +// stubRunner records commands instead of running them, and can be told to +// fail one or to write a file as a side effect of another. +type stubRunner struct { + commands []recordedCommand + // failOn fails any command whose rendered line contains this substring. + failOn string + err error + // output is what Output returns. + output []byte + // onRun runs after a command is recorded, to stand in for whatever the + // real command would have written to disk. + onRun func(c recordedCommand) error +} + +func (r *stubRunner) record(dir string, env map[string]string, name string, args []string) recordedCommand { + c := recordedCommand{Dir: dir, Env: env, Name: name, Args: args} + r.commands = append(r.commands, c) + return c +} + +func (r *stubRunner) check(c recordedCommand) error { + if r.failOn != "" && strings.Contains(c.line(), r.failOn) { + if r.err != nil { + return r.err + } + return io.ErrUnexpectedEOF + } + if r.onRun != nil { + return r.onRun(c) + } + return nil +} + +func (r *stubRunner) Run( + _ context.Context, dir string, env map[string]string, _ io.Writer, name string, args ...string, +) error { + return r.check(r.record(dir, env, name, args)) +} + +func (r *stubRunner) Output( + _ context.Context, dir string, env map[string]string, _ io.Writer, name string, args ...string, +) ([]byte, error) { + if err := r.check(r.record(dir, env, name, args)); err != nil { + return nil, err + } + return r.output, nil +} + +// lines renders every recorded command for assertions. +func (r *stubRunner) lines() []string { + out := make([]string, 0, len(r.commands)) + for _, c := range r.commands { + out = append(out, c.line()) + } + return out +} diff --git a/apps/cli/internal/handlertoolchain/toolchain.go b/apps/cli/internal/handlertoolchain/toolchain.go new file mode 100644 index 00000000..abefdf6d --- /dev/null +++ b/apps/cli/internal/handlertoolchain/toolchain.go @@ -0,0 +1,138 @@ +// Package handlertoolchain resolves and drives the build tooling for an +// OS-only runtime. +// +// An OS-only runtime identifier (os-only.debian13) names a base operating +// system rather than a language, so unlike "nodejs24.x" it does not give the +// language away and the toolchain has to be resolved from the project instead. +// Two implementations ship, one driving the Celerity Go SDK's celerity-go tool +// and a declarative one driven by a handlerBuild block in the application's +// deploy config, which is how a community SDK for another compiled language is +// supported without CLI code of its own. +// +// This package is deliberately a leaf. internal/deployconfig already imports +// internal/build and internal/handlerresolve, so a toolchain importing +// deployconfig back would close a cycle. The handlerBuild schema therefore +// lives here and deploy config embeds it. +package handlertoolchain + +import ( + "context" + + "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" +) + +// Build modes. A dev session reads its own local config store and talks to +// local emulators, so it links different packages from a deployed artefact. +const ( + ModeDev = "dev" + ModeDeploy = "deploy" +) + +// TelemetryOTel is what PrepareParams.Telemetry carries to link an +// OpenTelemetry exporter. Its own setting rather than one derived from the +// deploy target, since an application deployed anywhere may export anywhere. +const TelemetryOTel = "otel" + +// PrepareParams describes the code generation a toolchain does before either +// building or extracting. +type PrepareParams struct { + AppDir string + // DeployTarget is the app's deploy target (e.g. "aws-serverless"), which + // decides the platform packages linked into the executable. + DeployTarget string + // Mode is ModeDev or ModeDeploy. + Mode string + // ResourceKinds are the Celerity resource kinds the blueprint declares + // (bucket, queue, topic, cache, datastore, sqlDatabase), so the toolchain + // links an implementation for each. + ResourceKinds []string + // SQLEngines are the engines of the blueprint's SQL databases + // (e.g. "postgres"), so a driver is linked for each. + SQLEngines []string + // Telemetry names what traces are exported with, or is empty for none. + Telemetry string + // TestPackages links the platform packages into the project's integration + // suites as well as into the application, so a test that reaches a real + // resource reaches it through the same provider the deployed binary would. + // Set for a dev session and not for a deploy, where there are no tests to + // generate for. + TestPackages bool +} + +// ExtractParams describes a handler extraction run. +type ExtractParams struct { + AppDir string +} + +// BinaryParams describes one handlers executable to produce. +type BinaryParams struct { + AppDir string + // OS and Arch are the platform the executable has to run on rather than + // the one building it. A dev session targets the Docker daemon's + // architecture, and a Lambda build targets the architecture the function + // is declared with. + OS string + Arch string + // OutputPath is where the executable must end up. + OutputPath string + // DeployTarget and Mode mirror PrepareParams. + DeployTarget string + Mode string +} + +// WatchPaths describes what a dev session's file watcher should follow. +// +// Returned by the toolchain rather than read from the runtime conventions +// because all three are properties of the language. A Go module keeps its +// handlers at the module root while a Node project keeps them under src/, and +// a Rust project needs the .toml files no other language does. +type WatchPaths struct { + // Roots are directories relative to the application directory. + Roots []string + // Extensions are the file extensions a change is relevant for. + Extensions []string + // SkipDirs are directory names not to descend into. + SkipDirs []string + // SkipFiles are base names a change is never relevant for, whatever their + // extension. + // + // A toolchain's own generated file has to be listed here or a session + // cannot settle, because Prepare rewrites that file and reacting to the + // rewrite runs Prepare again. + SkipFiles []string +} + +// Toolchain turns an application's source into a handlers executable for an +// OS-only runtime, and reports what that executable serves. +type Toolchain interface { + // Name identifies the toolchain in output and errors (e.g. "go"). + Name() string + + // Validate reports whether the project is actually set up for this + // toolchain, so a missing SDK dependency fails before a build does. + Validate(appDir string) error + + // Prepare runs whatever code generation has to happen before the + // application will compile for this target. It is safe to call more than + // once and regenerates rather than reusing what is on disk, because a dev + // session's generated file is the wrong one for a deploy and vice versa. + Prepare(ctx context.Context, p PrepareParams) error + + // Extract reports the handlers the executable serves. Returning a nil + // manifest means this toolchain cannot extract, and the blueprint's + // hand-authored handler resources are used as they are. + // + // Callers run Prepare first: extraction compiles the application, so it + // fails on a project whose generated platform imports are absent or stale. + Extract(ctx context.Context, p ExtractParams) (*preprocess.HandlerManifest, error) + + // BuildBinary compiles the handlers executable to p.OutputPath. + BuildBinary(ctx context.Context, p BinaryParams) error + + // WatchPaths describes what a dev session should watch. + WatchPaths() WatchPaths + + // TestCommand returns the command for a named test suite, and whether one + // is configured. + TestCommand(suite string) ([]string, bool) +} diff --git a/apps/cli/internal/preprocess/consumer_collapse.go b/apps/cli/internal/preprocess/consumer_collapse.go new file mode 100644 index 00000000..5e9d54c3 --- /dev/null +++ b/apps/cli/internal/preprocess/consumer_collapse.go @@ -0,0 +1,300 @@ +package preprocess + +import ( + "sort" + + "go.uber.org/zap" +) + +const ( + // consumerRouteAnnotation carries the value of the consumer's routing field + // that selects one handler, set by the extraction CLI from + // @MessageHandler(""). + consumerRouteAnnotation = "celerity.handler.consumer.route" + // handlerTagAnnotation is what the deploy target stamps on the function as + // CELERITY_HANDLER_TAG, and what the runtime addresses a handler by. + handlerTagAnnotation = "celerity.handler.tag" + // resourceRefAnnotation names the application resources a handler reaches, + // which is what a deploy target turns into the handler's resource layers + // and its IAM grants. + // + // Collapsing a routed consumer takes the union across the handlers it + // replaces, since the single remaining function runs all of their code and + // so needs every resource any of them reached. + resourceRefAnnotation = "celerity.handler.resource.ref" +) + +// CollapseRoutedConsumers replaces the per-method handler resources of a routed +// consumer with a single resource for the consumer as a whole. +// +// Extraction produces one handler resource per @MessageHandler, which a deploy +// target turns into one function each, and for a consumer that is wrong. Every +// one of those functions consumes the same queue and the source hands each +// message to whichever function polls first, so the declared routing key never +// applies and messages are processed by an arbitrary handler. Nothing reports +// it, because a handler that receives a message it was not routed cannot tell +// the difference. +// +// Collapsing here rather than in the deploy target keeps one handler resource to +// one function everywhere downstream. The runtime routes the batch in-process, +// which it can do because every handler is in the same bundle. +// +// The operation is idempotent, since a manifest that has already been collapsed +// has one handler per consumer and is returned unchanged. +func CollapseRoutedConsumers(manifest *HandlerManifest, logger *zap.Logger) *HandlerManifest { + if manifest == nil { + return nil + } + + groups, order := groupConsumerHandlers(manifest.Handlers) + if len(order) == 0 { + return manifest + } + + collapsed := make([]ClassHandler, 0, len(manifest.Handlers)) + done := map[string]bool{} + + for _, handler := range manifest.Handlers { + source := consumerSourceOf(handler) + group := groups[source] + + // A consumer with a single handler has nothing to route between, so it + // keeps the resource it already had and the target keeps emitting exactly + // what it emitted before. + if source == "" || len(group) < 2 { + collapsed = append(collapsed, handler) + continue + } + + if done[source] { + continue + } + done[source] = true + + merged := collapseConsumerGroup(source, group) + collapsed = append(collapsed, merged) + + if logger != nil { + logger.Debug("collapsed routed consumer handlers", + zap.String("consumer", source), + zap.String("resource", merged.ResourceName), + zap.Int("handlers", len(group)), + ) + } + } + + out := *manifest + out.Handlers = collapsed + return &out +} + +// First-seen order is kept so the collapsed manifest is stable between runs. +func groupConsumerHandlers(handlers []ClassHandler) (map[string][]ClassHandler, []string) { + groups := map[string][]ClassHandler{} + order := []string{} + + for _, handler := range handlers { + source := consumerSourceOf(handler) + if source == "" { + continue + } + if _, seen := groups[source]; !seen { + order = append(order, source) + } + groups[source] = append(groups[source], handler) + } + return groups, order +} + +// The handler tag stays the bare consumer name, which is what the runtime +// matches handlers against, so this only has to be a distinct resource name. +func collapsedResourceName(source string) string { + return source + "_handler" +} + +func consumerSourceOf(handler ClassHandler) string { + if handler.HandlerType != "consumer" { + return "" + } + source, _ := handler.Annotations[consumerSourceAnnotation].(string) + return source +} + +// Builds the single handler resource that stands for a whole consumer. +func collapseConsumerGroup(source string, group []ClassHandler) ClassHandler { + first := group[0] + + merged := ClassHandler{ + // Suffixed rather than named after the consumer, because the blueprint + // already has a celerity/consumer resource under that name and merging a + // handler onto it would turn the consumer itself into the handler, taking + // its resource links with it. + ResourceName: collapsedResourceName(source), + ClassName: first.ClassName, + // No single method, since this resource stands for every @MessageHandler + // on the class and naming one of them would misreport what the function + // runs. + MethodName: "", + SourceFile: first.SourceFile, + HandlerType: "consumer", + Annotations: collapsedAnnotations(source, group), + Spec: HandlerSpec{ + HandlerName: first.ClassName, + CodeLocation: first.Spec.CodeLocation, + // Addresses the consumer rather than a method. The runtime resolves a + // handler id ahead of routing, so an id naming one method would + // dispatch the whole batch to it and skip routing entirely. + Handler: consumerHandlerRef(first), + Timeout: maxTimeout(group), + }, + } + return merged +} + +// Merges the group's annotations onto the consumer. +// +// The route is dropped, because it distinguished the resources that no longer +// exist and leaving it would declare that this function serves one route. The +// tag becomes the consumer's own name, which is how a function is marked as +// serving the whole consumer rather than one handler. +func collapsedAnnotations(source string, group []ClassHandler) map[string]any { + annotations := map[string]any{} + + // Carry anything the whole group agrees on, so a per-consumer setting applied + // to every handler survives. Anything the handlers disagree on describes one + // handler rather than the consumer, and cannot be represented once collapsed. + for key, value := range group[0].Annotations { + if key == consumerRouteAnnotation || key == handlerTagAnnotation || + key == resourceRefAnnotation { + continue + } + if agreesAcrossGroup(group, key, value) { + annotations[key] = value + } + } + + annotations[consumerSourceAnnotation] = source + annotations[handlerTagAnnotation] = source + + if refs := unionResourceRefs(group); len(refs) > 0 { + annotations[resourceRefAnnotation] = refs + } + return annotations +} + +func agreesAcrossGroup(group []ClassHandler, key string, value any) bool { + first, ok := value.(string) + if !ok { + // Only scalars are compared; a structured annotation is left to the + // explicit handling above rather than guessed at. + if _, isBool := value.(bool); !isBool { + return false + } + } + + for _, handler := range group[1:] { + other, exists := handler.Annotations[key] + if !exists { + return false + } + if boolValue, isBool := value.(bool); isBool { + if otherBool, ok := other.(bool); !ok || otherBool != boolValue { + return false + } + continue + } + if otherString, ok := other.(string); !ok || otherString != first { + return false + } + } + return true +} + +// Collects every resource any handler in the group uses. The function runs all +// of them, so granting only what one handler declared would leave the others +// unable to reach what they use. +func unionResourceRefs(group []ClassHandler) []any { + seen := map[string]bool{} + for _, handler := range group { + for _, ref := range refsOf(handler) { + seen[ref] = true + } + } + if len(seen) == 0 { + return nil + } + + names := make([]string, 0, len(seen)) + for name := range seen { + names = append(names, name) + } + sort.Strings(names) + + refs := make([]any, 0, len(names)) + for _, name := range names { + refs = append(refs, name) + } + return refs +} + +func refsOf(handler ClassHandler) []string { + raw, ok := handler.Annotations[resourceRefAnnotation] + if !ok { + return nil + } + switch value := raw.(type) { + case []any: + refs := make([]string, 0, len(value)) + for _, entry := range value { + if name, ok := entry.(string); ok && name != "" { + refs = append(refs, name) + } + } + return refs + case []string: + return value + case string: + if value == "" { + return nil + } + return []string{value} + } + return nil +} + +// Reduces a handler reference to the class that owns it, so +// `app-module.UserEventsConsumer.onUserCreated` becomes +// `app-module.UserEventsConsumer`. The module segment is what the target reads +// to find the bundle entry point, and dropping the method keeps the reference +// from resolving to a single handler at runtime. +func consumerHandlerRef(handler ClassHandler) string { + ref := handler.Spec.Handler + if ref == "" { + return "" + } + if handler.MethodName == "" { + return ref + } + suffix := "." + handler.MethodName + if len(ref) > len(suffix) && ref[len(ref)-len(suffix):] == suffix { + return ref[:len(ref)-len(suffix)] + } + return ref +} + +// The longest timeout any handler in the group asked for. One function serves +// all of them, so a shorter value would cut short a handler whose author had +// asked for longer. +func maxTimeout(group []ClassHandler) *int { + var longest *int + for _, handler := range group { + if handler.Spec.Timeout == nil { + continue + } + if longest == nil || *handler.Spec.Timeout > *longest { + value := *handler.Spec.Timeout + longest = &value + } + } + return longest +} diff --git a/apps/cli/internal/preprocess/consumer_collapse_test.go b/apps/cli/internal/preprocess/consumer_collapse_test.go new file mode 100644 index 00000000..eb79f02c --- /dev/null +++ b/apps/cli/internal/preprocess/consumer_collapse_test.go @@ -0,0 +1,215 @@ +package preprocess + +import ( + "testing" + + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +type ConsumerCollapseSuite struct { + suite.Suite +} + +func consumerHandler(consumer, method, route string, refs ...string) ClassHandler { + annotations := map[string]any{ + "celerity.handler.consumer": true, + consumerSourceAnnotation: consumer, + handlerTagAnnotation: consumer + "::" + method, + } + if route != "" { + annotations[consumerRouteAnnotation] = route + } + if len(refs) > 0 { + entries := make([]any, 0, len(refs)) + for _, ref := range refs { + entries = append(entries, ref) + } + annotations[resourceRefAnnotation] = entries + } + + return ClassHandler{ + ResourceName: consumer + "_" + method, + ClassName: "UserEventsConsumer", + MethodName: method, + SourceFile: "/app/src/app-module.ts", + HandlerType: "consumer", + Annotations: annotations, + Spec: HandlerSpec{ + HandlerName: "UserEventsConsumer-" + method, + CodeLocation: "./src", + Handler: "app-module.UserEventsConsumer." + method, + }, + } +} + +func (s *ConsumerCollapseSuite) routedManifest() *HandlerManifest { + return &HandlerManifest{ + Handlers: []ClassHandler{ + consumerHandler("userEventsConsumer", "onUserCreated", "user.created", "auditDatabase"), + consumerHandler("userEventsConsumer", "onUserUpdated", "user.updated", "auditDatabase"), + consumerHandler("userEventsConsumer", "onUserDeleted", "user.deleted", "usersDatastore"), + consumerHandler("userEventsConsumer", "onUnknownEvent", ""), + }, + } +} + +func (s *ConsumerCollapseSuite) Test_collapses_a_routed_consumer_to_one_resource() { + // The defect: four resources became four functions on one queue, so the source + // handed each message to whichever polled first and the route never applied. + out := CollapseRoutedConsumers(s.routedManifest(), zap.NewNop()) + + s.Require().Len(out.Handlers, 1) + s.Assert().Equal("userEventsConsumer_handler", out.Handlers[0].ResourceName) + s.Assert().Equal("consumer", out.Handlers[0].HandlerType) +} + +func (s *ConsumerCollapseSuite) Test_does_not_collide_with_the_consumer_resource() { + // The blueprint already declares celerity/consumer "userEventsConsumer". + // Merging the handler onto that name turned the consumer into the handler and + // gave it the handler's resource links, which failed the blueprint load with + // "No abstract link definition found for link type: celerity/consumer -> + // celerity/sqlDatabase". + out := CollapseRoutedConsumers(s.routedManifest(), zap.NewNop()) + + s.Assert().NotEqual("userEventsConsumer", out.Handlers[0].ResourceName) + s.Assert().Equal("userEventsConsumer", out.Handlers[0].Annotations[consumerSourceAnnotation]) +} + +func (s *ConsumerCollapseSuite) Test_tags_the_collapsed_resource_with_the_consumer() { + out := CollapseRoutedConsumers(s.routedManifest(), zap.NewNop()) + annotations := out.Handlers[0].Annotations + + // The tag stays the one way a function says what it serves; naming the + // consumer is how it says it serves all of it. + s.Assert().Equal("userEventsConsumer", annotations[handlerTagAnnotation]) + s.Assert().Equal("userEventsConsumer", annotations[consumerSourceAnnotation]) + s.Assert().NotContains(annotations, consumerRouteAnnotation) +} + +func (s *ConsumerCollapseSuite) Test_handler_ref_addresses_the_class_not_a_method() { + // The runtime resolves a handler id ahead of routing, so an id naming one + // method would send the whole batch there and skip routing entirely. + out := CollapseRoutedConsumers(s.routedManifest(), zap.NewNop()) + + s.Assert().Equal("app-module.UserEventsConsumer", out.Handlers[0].Spec.Handler) + s.Assert().Empty(out.Handlers[0].MethodName) +} + +func (s *ConsumerCollapseSuite) Test_takes_the_union_of_resource_refs() { + // One function runs every handler, so it needs what all of them reach. + out := CollapseRoutedConsumers(s.routedManifest(), zap.NewNop()) + + s.Assert().ElementsMatch( + []any{"auditDatabase", "usersDatastore"}, + out.Handlers[0].Annotations[resourceRefAnnotation], + ) +} + +func (s *ConsumerCollapseSuite) Test_leaves_a_single_handler_consumer_alone() { + // Nothing to route between, so it keeps the resource it had and the target + // emits exactly what it emitted before. + manifest := &HandlerManifest{ + Handlers: []ClassHandler{ + consumerHandler("taskConsumer", "handle", ""), + }, + } + + out := CollapseRoutedConsumers(manifest, zap.NewNop()) + + s.Require().Len(out.Handlers, 1) + s.Assert().Equal("taskConsumer_handle", out.Handlers[0].ResourceName) + s.Assert().Equal("taskConsumer::handle", out.Handlers[0].Annotations[handlerTagAnnotation]) +} + +func (s *ConsumerCollapseSuite) Test_leaves_non_consumer_handlers_untouched() { + manifest := &HandlerManifest{ + Handlers: []ClassHandler{ + { + ResourceName: "usersController_listUsers", + ClassName: "UsersController", + MethodName: "listUsers", + HandlerType: "http", + Annotations: map[string]any{"celerity.handler.http": true}, + Spec: HandlerSpec{Handler: "app-module.UsersController.listUsers"}, + }, + consumerHandler("userEventsConsumer", "onUserCreated", "user.created"), + consumerHandler("userEventsConsumer", "onUserUpdated", "user.updated"), + }, + } + + out := CollapseRoutedConsumers(manifest, zap.NewNop()) + + s.Require().Len(out.Handlers, 2) + s.Assert().Equal("usersController_listUsers", out.Handlers[0].ResourceName) + s.Assert().Equal("userEventsConsumer_handler", out.Handlers[1].ResourceName) +} + +func (s *ConsumerCollapseSuite) Test_keeps_separate_consumers_separate() { + manifest := &HandlerManifest{ + Handlers: []ClassHandler{ + consumerHandler("userEventsConsumer", "onUserCreated", "user.created"), + consumerHandler("userEventsConsumer", "onUserUpdated", "user.updated"), + consumerHandler("orderEventsConsumer", "onPlaced", "order.placed"), + consumerHandler("orderEventsConsumer", "onShipped", "order.shipped"), + }, + } + + out := CollapseRoutedConsumers(manifest, zap.NewNop()) + + s.Require().Len(out.Handlers, 2) + s.Assert().Equal("userEventsConsumer_handler", out.Handlers[0].ResourceName) + s.Assert().Equal("orderEventsConsumer_handler", out.Handlers[1].ResourceName) +} + +func (s *ConsumerCollapseSuite) Test_is_idempotent() { + // Called both in Merge and by the resolver, so collapsing twice must not + // differ from collapsing once. + once := CollapseRoutedConsumers(s.routedManifest(), zap.NewNop()) + twice := CollapseRoutedConsumers(once, zap.NewNop()) + + s.Assert().Equal(once.Handlers, twice.Handlers) +} + +func (s *ConsumerCollapseSuite) Test_takes_the_longest_timeout_in_the_group() { + // A shorter value would cut short a handler whose author asked for longer. + short, long := 10, 45 + manifest := s.routedManifest() + manifest.Handlers[0].Spec.Timeout = &short + manifest.Handlers[1].Spec.Timeout = &long + + out := CollapseRoutedConsumers(manifest, zap.NewNop()) + + s.Require().NotNil(out.Handlers[0].Spec.Timeout) + s.Assert().Equal(45, *out.Handlers[0].Spec.Timeout) +} + +func (s *ConsumerCollapseSuite) Test_keeps_an_annotation_the_whole_group_agrees_on() { + manifest := s.routedManifest() + for i := range manifest.Handlers { + manifest.Handlers[i].Annotations["celerity.handler.vpc"] = "private" + } + + out := CollapseRoutedConsumers(manifest, zap.NewNop()) + + s.Assert().Equal("private", out.Handlers[0].Annotations["celerity.handler.vpc"]) +} + +func (s *ConsumerCollapseSuite) Test_drops_an_annotation_the_group_disagrees_on() { + // It described one handler, and one function cannot honour two values. + manifest := s.routedManifest() + manifest.Handlers[0].Annotations["celerity.handler.memory"] = "512" + manifest.Handlers[1].Annotations["celerity.handler.memory"] = "1024" + + out := CollapseRoutedConsumers(manifest, zap.NewNop()) + + s.Assert().NotContains(out.Handlers[0].Annotations, "celerity.handler.memory") +} + +func (s *ConsumerCollapseSuite) Test_handles_a_nil_manifest() { + s.Assert().Nil(CollapseRoutedConsumers(nil, zap.NewNop())) +} + +func TestConsumerCollapseSuite(t *testing.T) { + suite.Run(t, new(ConsumerCollapseSuite)) +} diff --git a/apps/cli/internal/preprocess/extractor.go b/apps/cli/internal/preprocess/extractor.go index 8c37997e..327a6e0f 100644 --- a/apps/cli/internal/preprocess/extractor.go +++ b/apps/cli/internal/preprocess/extractor.go @@ -77,6 +77,19 @@ func (e *Extractor) buildArgs() ([]string, error) { } } +// The module loader extraction runs the application under. It has to be an SWC +// one, because esbuild (which tsx uses) does not implement +// emitDecoratorMetadata, and without design:paramtypes a handler that injects a +// service by type alone contributes no edge to the injection graph. Extraction +// then succeeds with that handler reported as reaching nothing, so its resource +// links are lost and the deployed handler fails on its first real event for +// want of a permission. +const nodeLoader = "@swc-node/register/esm-register" + +// The directory the loader is installed at, which is how its presence is +// checked. +var nodeLoaderPackage = filepath.Join("node_modules", "@swc-node", "register") + func (e *Extractor) buildNodeArgs() ([]string, error) { extractBin := filepath.Join(e.config.ProjectRoot, "node_modules", ".bin", "celerity-extract") if _, err := os.Stat(extractBin); err != nil { @@ -86,9 +99,19 @@ func (e *Extractor) buildNodeArgs() ([]string, error) { ) } + loaderDir := filepath.Join(e.config.ProjectRoot, nodeLoaderPackage) + if _, err := os.Stat(loaderDir); err != nil { + return nil, fmt.Errorf( + "handler extraction needs @swc-node/register, which is not installed at %s.\n"+ + "It is what emits the decorator metadata a handler's resource links are read "+ + "from; without it they are silently lost", + loaderDir, + ) + } + return []string{ "node", - "--import", "tsx", + "--import", nodeLoader, extractBin, "--module", e.config.ModulePath, "--project-root", e.config.ProjectRoot, diff --git a/apps/cli/internal/preprocess/extractor_test.go b/apps/cli/internal/preprocess/extractor_test.go new file mode 100644 index 00000000..b40c1aff --- /dev/null +++ b/apps/cli/internal/preprocess/extractor_test.go @@ -0,0 +1,92 @@ +package preprocess + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +type ExtractorTestSuite struct { + suite.Suite + logger *zap.Logger +} + +func (s *ExtractorTestSuite) SetupTest() { + logger, _ := zap.NewDevelopment() + s.logger = logger +} + +// Lays out the parts of node_modules that buildNodeArgs checks for, so a test +// can omit one and assert on the resulting error. +func (s *ExtractorTestSuite) projectRoot(withExtractBin, withLoader bool) string { + root := s.T().TempDir() + + if withExtractBin { + binDir := filepath.Join(root, "node_modules", ".bin") + s.Require().NoError(os.MkdirAll(binDir, 0755)) + s.Require().NoError( + os.WriteFile(filepath.Join(binDir, "celerity-extract"), []byte("#!/bin/sh\n"), 0755), + ) + } + + if withLoader { + s.Require().NoError( + os.MkdirAll(filepath.Join(root, "node_modules", "@swc-node", "register"), 0755), + ) + } + + return root +} + +func (s *ExtractorTestSuite) newExtractor(root string) *Extractor { + return NewExtractor(ExtractorConfig{ + Runtime: "nodejs22.x", + ModulePath: "src/app-module.ts", + ProjectRoot: root, + }, s.logger) +} + +// The loader has to be an SWC one: esbuild does not implement +// emitDecoratorMetadata, and without design:paramtypes a handler that injects a +// service by type alone contributes no edge to the injection graph, so its +// resource links are silently lost. +func (s *ExtractorTestSuite) Test_buildNodeArgs_uses_the_swc_loader() { + root := s.projectRoot(true, true) + + args, err := s.newExtractor(root).buildNodeArgs() + + s.Require().NoError(err) + s.Require().Equal([]string{ + "node", + "--import", "@swc-node/register/esm-register", + filepath.Join(root, "node_modules", ".bin", "celerity-extract"), + "--module", "src/app-module.ts", + "--project-root", root, + }, args) + s.Assert().NotContains(args, "tsx") +} + +func (s *ExtractorTestSuite) Test_buildNodeArgs_reports_a_missing_loader() { + root := s.projectRoot(true, false) + + _, err := s.newExtractor(root).buildNodeArgs() + + s.Require().Error(err) + s.Assert().Contains(err.Error(), "@swc-node/register") +} + +func (s *ExtractorTestSuite) Test_buildNodeArgs_reports_a_missing_extraction_cli() { + root := s.projectRoot(false, true) + + _, err := s.newExtractor(root).buildNodeArgs() + + s.Require().Error(err) + s.Assert().Contains(err.Error(), "@celerity-sdk/cli") +} + +func TestExtractorTestSuite(t *testing.T) { + suite.Run(t, new(ExtractorTestSuite)) +} diff --git a/apps/cli/internal/preprocess/merger.go b/apps/cli/internal/preprocess/merger.go index 334934c2..4618b2a7 100644 --- a/apps/cli/internal/preprocess/merger.go +++ b/apps/cli/internal/preprocess/merger.go @@ -65,12 +65,13 @@ func Merge( ) } - // Link extracted handlers to the API resource so the runtime - // can discover them via linkSelector.byLabel matching. + // Wire each handler into the resources it belongs to, through the labels + // a link selector matches on. if manifest.AllHandlers() > 0 { linkHandlersToApi(bp, manifest) linkHandlersToConsumers(bp, manifest, logger) linkHandlersToSchedules(bp, manifest, logger) + linkHandlersToResources(bp, manifest, logger) } return bp, nil @@ -82,6 +83,22 @@ func WriteMerged( bp *schema.Blueprint, format schema.SpecFormat, outputDir string, +) (string, error) { + return WriteMergedWithMode(bp, format, outputDir, 0o644) +} + +// WriteMergedWithMode is WriteMerged with the file permissions stated. +// +// A separate entry point because the two callers need different modes. A dev +// session's merged blueprint is ordinary generated output, while a deploy's +// carries the environment's configuration values, secrets among them, seeded +// so a first deploy can stand its store up, and that one must not be world +// readable. +func WriteMergedWithMode( + bp *schema.Blueprint, + format schema.SpecFormat, + outputDir string, + mode os.FileMode, ) (string, error) { if err := os.MkdirAll(outputDir, 0o755); err != nil { return "", fmt.Errorf("creating output directory: %w", err) @@ -109,10 +126,16 @@ func WriteMerged( outPath := filepath.Join(outputDir, filename) tmpPath := outPath + ".tmp" - if err := os.WriteFile(tmpPath, data, 0o644); err != nil { + if err := os.WriteFile(tmpPath, data, mode); err != nil { return "", fmt.Errorf("writing merged blueprint: %w", err) } + // Set explicitly as well as passed to WriteFile, which applies the + // process umask and so cannot be relied on to produce the mode asked for. + if err := os.Chmod(tmpPath, mode); err != nil { + return "", fmt.Errorf("setting merged blueprint permissions: %w", err) + } + if err := os.Rename(tmpPath, outPath); err != nil { return "", fmt.Errorf("renaming merged blueprint: %w", err) } @@ -135,9 +158,8 @@ func mergeHandler( bp.Resources.Values[resourceName] = buildNewResource(resourceName, annotations, spec) } -// fillExistingResource fills in missing annotations and spec fields from extracted metadata. -// Blueprint-defined values take precedence for infrastructure config (e.g. timeout). -// Extracted values take precedence for routing info (annotations). +// Blueprint-defined values take precedence for infrastructure config +// (e.g. timeout); extracted values take precedence for routing annotations. func fillExistingResource( resource *schema.Resource, resourceName string, @@ -236,11 +258,9 @@ func setSpecField(spec *core.MappingNode, key string, value string) { } } -// linkHandlersToApi finds the first celerity/api resource in the blueprint, -// adds a linkSelector to it (if not already set), and labels all extracted -// handler resources so the runtime can discover them via label matching. +// Labels every extracted handler resource for the blueprint's celerity/api +// resource, so the runtime resolves them by label matching. func linkHandlersToApi(bp *schema.Blueprint, manifest *HandlerManifest) { - // Find the first celerity/api resource. apiName := "" for name, resource := range bp.Resources.Values { if resource.Type != nil && resource.Type.Value == resourceTypeApi { @@ -275,7 +295,6 @@ func linkHandlersToApi(bp *schema.Blueprint, manifest *HandlerManifest) { handlerNames[h.ResourceName] = true } - // Add matching labels to extracted handler resources. apiResource := bp.Resources.Values[apiName] for name, resource := range bp.Resources.Values { if handlerNames[name] { @@ -284,12 +303,11 @@ func linkHandlersToApi(bp *schema.Blueprint, manifest *HandlerManifest) { } } - // Register custom guards (from @Guard decorators) in the API auth config. mergeCustomGuards(apiResource, bp) } -// mergeCustomGuards scans handler resources for the customGuardAnnotation -// and adds a corresponding { type: custom } entry in the API's spec.auth.guards. +// Each handler carrying customGuardAnnotation gets a { type: custom } entry in +// the API's spec.auth.guards. func mergeCustomGuards(apiResource *schema.Resource, bp *schema.Blueprint) { ensureSpec(apiResource) @@ -314,7 +332,6 @@ func mergeCustomGuards(apiResource *schema.Resource, bp *schema.Blueprint) { } } -// annotationStringValue reads a string annotation from a resource's metadata. func annotationStringValue(resource *schema.Resource, key string) string { if resource.Metadata == nil || resource.Metadata.Annotations == nil { return "" @@ -330,7 +347,7 @@ func annotationStringValue(resource *schema.Resource, key string) string { return s } -// ensureSpecPath navigates (and creates if needed) nested MappingNode fields. +// Navigates nested MappingNode fields, creating any that are absent. func ensureSpecPath(spec *core.MappingNode, keys ...string) *core.MappingNode { current := spec for _, key := range keys { @@ -363,24 +380,21 @@ const consumerSourceAnnotation = "celerity.handler.consumer.source" // on handler methods decorated with @ScheduleHandler("scheduleName"). const scheduleSourceAnnotation = "celerity.handler.schedule.source" -// linkHandlersToConsumers links consumer-type handler resources to their -// corresponding celerity/consumer resource so the Rust runtime can discover -// them via linkSelector.byLabel matching. +// Links consumer-type handler resources to their celerity/consumer resource, +// so the runtime resolves them by label matching. func linkHandlersToConsumers(bp *schema.Blueprint, manifest *HandlerManifest, logger *zap.Logger) { linkHandlersToSourceResources(bp, manifest, resourceTypeConsumer, consumerSourceAnnotation, logger) } -// linkHandlersToSchedules links schedule-type handler resources to their -// corresponding celerity/schedule resource. +// Links schedule-type handler resources to their celerity/schedule resource. func linkHandlersToSchedules(bp *schema.Blueprint, manifest *HandlerManifest, logger *zap.Logger) { linkHandlersToSourceResources(bp, manifest, resourceTypeSchedule, scheduleSourceAnnotation, logger) } -// linkHandlersToSourceResources is the shared implementation for linking -// handler resources to consumer or schedule source resources. -// It groups handlers by their source annotation value (which is the resource -// name of the consumer/schedule), adds a linkSelector to the source resource, -// and labels the handler resources to match. +// Shared by consumer and schedule linking. Handlers are grouped by their +// source annotation value, which is the resource name of the consumer or +// schedule, and each source gets a linkSelector its handlers are labelled to +// match. func linkHandlersToSourceResources( bp *schema.Blueprint, manifest *HandlerManifest, @@ -388,7 +402,6 @@ func linkHandlersToSourceResources( sourceAnnotationKey string, logger *zap.Logger, ) { - // Build a map: source resource name → list of handler resource names. sourceToHandlers := map[string][]string{} for _, h := range manifest.Handlers { source, ok := h.Annotations[sourceAnnotationKey] @@ -414,7 +427,6 @@ func linkHandlersToSourceResources( return } - // For each source resource, add linkSelector and label matching handlers. for sourceName, handlerNames := range sourceToHandlers { sourceResource, exists := bp.Resources.Values[sourceName] if !exists { @@ -433,7 +445,6 @@ func linkHandlersToSourceResources( labelKey = "sourceSchedule" } - // Add linkSelector to the source resource if not already set. if sourceResource.LinkSelector == nil { sourceResource.LinkSelector = &schema.LinkSelector{ ByLabel: &schema.StringMap{ @@ -442,7 +453,6 @@ func linkHandlersToSourceResources( } } - // Label handler resources to match the source's linkSelector. labelValue := sourceName if sourceResource.LinkSelector.ByLabel != nil { // Use existing label key/value if linkSelector was already set. @@ -478,8 +488,7 @@ func ensureLabels(resource *schema.Resource) { } } -// formatAnnotationValue converts an annotation value to its string representation. -// JSON arrays (from extraction CLI) are joined with commas to match the +// JSON arrays from the extraction CLI are joined with commas to match the // comma-separated format the runtime expects (e.g. "admin,jwt"). func formatAnnotationValue(value any) string { switch v := value.(type) { diff --git a/apps/cli/internal/preprocess/merger_resource_links.go b/apps/cli/internal/preprocess/merger_resource_links.go new file mode 100644 index 00000000..a5533b7d --- /dev/null +++ b/apps/cli/internal/preprocess/merger_resource_links.go @@ -0,0 +1,174 @@ +package preprocess + +import ( + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "go.uber.org/zap" +) + +// resourceUseLabelPrefix prefixes the label that wires a handler to a resource +// it reaches. +// +// One key per resource rather than one shared key, because a link selector +// matches on any single label pair. A shared key with different values would +// match nothing, and a shared key with a shared value would reach every +// resource in the application rather than the ones the handler uses. +const resourceUseLabelPrefix = "celerity.resource.use." + +// linkableResourceTypes are the resource types a handler can hold an outbound +// link to. +// +// A handler reaching an API or another handler is not a data-access link and +// has no transformer case, so a reference to one is a mistake in the +// application rather than something to wire. +var linkableResourceTypes = map[string]bool{ + "celerity/bucket": true, + "celerity/cache": true, + "celerity/datastore": true, + "celerity/queue": true, + "celerity/sqlDatabase": true, + "celerity/topic": true, +} + +// Wires each handler to the resources it reaches. +// +// The direction is the opposite of API and consumer linking. There the API owns +// the selector and the handlers carry the label, while here the handler owns +// the selector and the resource carries the label, because the handler is the +// linked-from side of a data-access link and nothing on the resource records +// which handlers use it. +// +// The labels are what a transformer turns into the handler's resource layers +// and its IAM grants, so a resource left unlabelled is one the handler has no +// permission to reach. +func linkHandlersToResources(bp *schema.Blueprint, manifest *HandlerManifest, logger *zap.Logger) { + if bp.Resources == nil { + return + } + + for _, refs := range handlerResourceRefs(manifest) { + handler, ok := bp.Resources.Values[refs.handlerName] + if !ok { + continue + } + for _, resourceName := range refs.resourceNames { + linkHandlerToResource(bp, handler, refs.handlerName, resourceName, logger) + } + } +} + +func linkHandlerToResource( + bp *schema.Blueprint, + handler *schema.Resource, + handlerName string, + resourceName string, + logger *zap.Logger, +) { + target, ok := bp.Resources.Values[resourceName] + if !ok { + // A reference to something the blueprint does not declare. Skipped + // rather than refused, because extraction reads names out of source and + // a renamed resource should not stop a dev session starting. + logger.Warn("handler references a resource the blueprint does not declare", + zap.String("handler", handlerName), + zap.String("resource", resourceName), + ) + return + } + if target.Type == nil || !linkableResourceTypes[target.Type.Value] { + logger.Warn("handler references a resource it cannot link to", + zap.String("handler", handlerName), + zap.String("resource", resourceName), + ) + return + } + + key := resourceUseLabelPrefix + resourceName + addLinkSelectorLabel(handler, key, resourceName) + addResourceLabel(target, key, resourceName) +} + +type handlerResourceRef struct { + handlerName string + resourceNames []string +} + +// Reads the resource references off every handler in the manifest, guards +// included, since a guard runs before the handler it protects and reaches +// resources of its own. +func handlerResourceRefs(manifest *HandlerManifest) []handlerResourceRef { + var refs []handlerResourceRef + + add := func(resourceName string, annotations map[string]any) { + names := resourceRefsFrom(annotations) + if len(names) > 0 { + refs = append(refs, handlerResourceRef{handlerName: resourceName, resourceNames: names}) + } + } + + for _, h := range manifest.Handlers { + add(h.ResourceName, h.Annotations) + } + for _, h := range manifest.FunctionHandlers { + add(h.ResourceName, h.Annotations) + } + for _, h := range manifest.GuardHandlers { + add(h.ResourceName, h.Annotations) + } + + return refs +} + +// Both []string and []any are accepted because the manifest is decoded into +// map[string]any, so a JSON array of strings arrives as []any whatever the +// extraction CLI wrote. +func resourceRefsFrom(annotations map[string]any) []string { + raw, ok := annotations[resourceRefAnnotation] + if !ok { + return nil + } + + switch refs := raw.(type) { + case []string: + return refs + case []any: + names := make([]string, 0, len(refs)) + for _, ref := range refs { + if name, ok := ref.(string); ok && name != "" { + names = append(names, name) + } + } + return names + case string: + // A single reference written unwrapped. + if refs != "" { + return []string{refs} + } + } + return nil +} + +func addLinkSelectorLabel(resource *schema.Resource, key, value string) { + if resource.LinkSelector == nil { + resource.LinkSelector = &schema.LinkSelector{} + } + if resource.LinkSelector.ByLabel == nil { + resource.LinkSelector.ByLabel = &schema.StringMap{} + } + if resource.LinkSelector.ByLabel.Values == nil { + resource.LinkSelector.ByLabel.Values = map[string]string{} + } + resource.LinkSelector.ByLabel.Values[key] = value +} + +func addResourceLabel(resource *schema.Resource, key, value string) { + if resource.Metadata == nil { + resource.Metadata = &schema.Metadata{} + } + if resource.Metadata.Labels == nil { + resource.Metadata.Labels = &schema.StringMap{} + } + if resource.Metadata.Labels.Values == nil { + resource.Metadata.Labels.Values = map[string]string{} + } + resource.Metadata.Labels.Values[key] = value +} diff --git a/apps/cli/internal/preprocess/merger_resource_links_test.go b/apps/cli/internal/preprocess/merger_resource_links_test.go new file mode 100644 index 00000000..faf7d486 --- /dev/null +++ b/apps/cli/internal/preprocess/merger_resource_links_test.go @@ -0,0 +1,255 @@ +package preprocess + +import ( + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +type MergerResourceLinksTestSuite struct { + suite.Suite + logger *zap.Logger +} + +func (s *MergerResourceLinksTestSuite) SetupTest() { + logger, _ := zap.NewDevelopment() + s.logger = logger +} + +func (s *MergerResourceLinksTestSuite) loadBlueprint(yamlContent string) *schema.Blueprint { + bp, err := schema.LoadString(yamlContent, schema.YAMLSpecFormat) + s.Require().NoError(err, "failed to load test blueprint") + return bp +} + +const dataResourcesBlueprint = ` +version: 2025-11-02 +resources: + api: + type: "celerity/api" + spec: + name: my-api + usersDatastore: + type: "celerity/datastore" + spec: + name: users + auditDatabase: + type: "celerity/sqlDatabase" + spec: + engine: postgres + filesBucket: + type: "celerity/bucket" + spec: + name: files +` + +func (s *MergerResourceLinksTestSuite) manifestWithRefs(refs ...any) *HandlerManifest { + annotations := map[string]any{ + "celerity.handler.http.method": "GET", + "celerity.handler.http.path": "/users", + } + if refs != nil { + annotations[resourceRefAnnotation] = refs + } + + return &HandlerManifest{ + Version: "1", + Handlers: []ClassHandler{ + { + ResourceName: "usersHandler", + ClassName: "UsersController", + MethodName: "list", + SourceFile: "users.ts", + HandlerType: "http", + Annotations: annotations, + Spec: HandlerSpec{ + HandlerName: "Users-list", + CodeLocation: "users.ts", + Handler: "UsersController.list", + }, + }, + }, + } +} + +func (s *MergerResourceLinksTestSuite) selectorLabels( + result *schema.Blueprint, + name string, +) map[string]string { + resource, ok := result.Resources.Values[name] + s.Require().True(ok, "expected resource %s", name) + if resource.LinkSelector == nil || resource.LinkSelector.ByLabel == nil { + return map[string]string{} + } + return resource.LinkSelector.ByLabel.Values +} + +func (s *MergerResourceLinksTestSuite) labels( + result *schema.Blueprint, + name string, +) map[string]string { + resource, ok := result.Resources.Values[name] + s.Require().True(ok, "expected resource %s", name) + if resource.Metadata == nil || resource.Metadata.Labels == nil { + return map[string]string{} + } + return resource.Metadata.Labels.Values +} + +// The handler is the linked-from resource for data access, so the selector +// belongs on the handler and the matching label on the resource. This is the +// opposite direction to API and consumer linking. +func (s *MergerResourceLinksTestSuite) Test_selector_goes_on_the_handler_and_label_on_the_resource() { + bp := s.loadBlueprint(dataResourcesBlueprint) + + result, err := Merge(bp, s.manifestWithRefs("usersDatastore"), s.logger) + s.Require().NoError(err) + + labelKey := resourceUseLabelPrefix + "usersDatastore" + s.Assert().Equal("usersDatastore", s.selectorLabels(result, "usersHandler")[labelKey]) + s.Assert().Equal("usersDatastore", s.labels(result, "usersDatastore")[labelKey]) +} + +// byLabel matches on any single pair, so a distinct key per resource is what +// lets one handler reach several resources without reaching all of them. +func (s *MergerResourceLinksTestSuite) Test_several_refs_produce_a_key_per_resource() { + bp := s.loadBlueprint(dataResourcesBlueprint) + + result, err := Merge( + bp, + s.manifestWithRefs("usersDatastore", "auditDatabase"), + s.logger, + ) + s.Require().NoError(err) + + selector := s.selectorLabels(result, "usersHandler") + s.Assert().Equal("usersDatastore", selector[resourceUseLabelPrefix+"usersDatastore"]) + s.Assert().Equal("auditDatabase", selector[resourceUseLabelPrefix+"auditDatabase"]) + + // The unreferenced resource stays unlabelled, so the handler cannot reach it. + s.Assert().NotContains( + s.labels(result, "filesBucket"), + resourceUseLabelPrefix+"filesBucket", + ) +} + +func (s *MergerResourceLinksTestSuite) Test_no_refs_leaves_the_handler_selector_untouched() { + bp := s.loadBlueprint(dataResourcesBlueprint) + + result, err := Merge(bp, s.manifestWithRefs(), s.logger) + s.Require().NoError(err) + + for key := range s.selectorLabels(result, "usersHandler") { + s.Assert().NotContains(key, resourceUseLabelPrefix) + } +} + +func (s *MergerResourceLinksTestSuite) Test_unknown_resource_ref_is_skipped() { + bp := s.loadBlueprint(dataResourcesBlueprint) + + result, err := Merge( + bp, + s.manifestWithRefs("usersDatastore", "notARealResource"), + s.logger, + ) + s.Require().NoError(err) + + selector := s.selectorLabels(result, "usersHandler") + s.Assert().Equal("usersDatastore", selector[resourceUseLabelPrefix+"usersDatastore"]) + s.Assert().NotContains(selector, resourceUseLabelPrefix+"notARealResource") +} + +// A ref to something a handler cannot hold an outbound link to is a mistake, and +// wiring it would produce a link the transformer has no case for. +func (s *MergerResourceLinksTestSuite) Test_ref_to_an_unlinkable_type_is_skipped() { + bp := s.loadBlueprint(dataResourcesBlueprint) + + result, err := Merge(bp, s.manifestWithRefs("api"), s.logger) + s.Require().NoError(err) + + s.Assert().NotContains( + s.selectorLabels(result, "usersHandler"), + resourceUseLabelPrefix+"api", + ) + s.Assert().NotContains(s.labels(result, "api"), resourceUseLabelPrefix+"api") +} + +// JSON decoding into map[string]any yields []any, which is what the annotation +// actually arrives as from the extraction CLI. +func (s *MergerResourceLinksTestSuite) Test_refs_arriving_as_any_slice() { + bp := s.loadBlueprint(dataResourcesBlueprint) + manifest := s.manifestWithRefs() + manifest.Handlers[0].Annotations[resourceRefAnnotation] = []any{"usersDatastore"} + + result, err := Merge(bp, manifest, s.logger) + s.Require().NoError(err) + + s.Assert().Equal( + "usersDatastore", + s.selectorLabels(result, "usersHandler")[resourceUseLabelPrefix+"usersDatastore"], + ) +} + +func (s *MergerResourceLinksTestSuite) Test_preserves_an_existing_link_selector() { + bp := s.loadBlueprint(` +version: 2025-11-02 +resources: + usersHandler: + type: "celerity/handler" + linkSelector: + byLabel: + application: orders + spec: + handlerName: Users-list + usersDatastore: + type: "celerity/datastore" + spec: + name: users +`) + + result, err := Merge(bp, s.manifestWithRefs("usersDatastore"), s.logger) + s.Require().NoError(err) + + selector := s.selectorLabels(result, "usersHandler") + s.Assert().Equal("orders", selector["application"]) + s.Assert().Equal("usersDatastore", selector[resourceUseLabelPrefix+"usersDatastore"]) +} + +func (s *MergerResourceLinksTestSuite) Test_guard_handlers_are_wired_too() { + bp := s.loadBlueprint(dataResourcesBlueprint) + manifest := &HandlerManifest{ + Version: "1", + GuardHandlers: []GuardHandler{ + { + ResourceName: "adminGuard_check", + GuardName: "admin", + SourceFile: "admin-guard.ts", + GuardType: "class", + ClassName: "AdminGuard", + Annotations: map[string]any{ + "celerity.handler.guard.custom": "admin", + resourceRefAnnotation: []any{"usersDatastore"}, + }, + Spec: HandlerSpec{ + HandlerName: "AdminGuard-check", + CodeLocation: "admin-guard.ts", + Handler: "AdminGuard.check", + }, + }, + }, + } + + result, err := Merge(bp, manifest, s.logger) + s.Require().NoError(err) + + s.Assert().Equal( + "usersDatastore", + s.selectorLabels(result, "adminGuard_check")[resourceUseLabelPrefix+"usersDatastore"], + ) +} + +func TestMergerResourceLinksTestSuite(t *testing.T) { + suite.Run(t, new(MergerResourceLinksTestSuite)) +} diff --git a/apps/cli/internal/preprocess/validate.go b/apps/cli/internal/preprocess/validate.go new file mode 100644 index 00000000..02114456 --- /dev/null +++ b/apps/cli/internal/preprocess/validate.go @@ -0,0 +1,80 @@ +package preprocess + +import ( + "fmt" + "strings" +) + +// ManifestVersion is the handler manifest format this package reads. +// +// Accepted in two spellings. The Celerity Go SDK emits "v1" while the CLI's +// own no-extraction fallback constructs "1", and both have been in the wild +// unvalidated. Rejecting either now would break working projects to enforce a +// distinction that never meant anything. +const ( + ManifestVersion = "1" + ManifestVersionGoSDK = "v1" +) + +// ValidateManifest reports whether a handler manifest can be merged into a +// blueprint. +// +// Worth checking for an extractor the CLI does not ship. A community SDK +// hand-produces this document and the merge is forgiving by design, skipping +// what it does not recognise. A manifest with the wrong annotation keys, or +// handlers with no resource name, therefore merges cleanly and produces an +// application with no handlers at all, surfacing as a runtime handshake +// failure a long way from the mistake. +func ValidateManifest(m *HandlerManifest) error { + if m == nil { + return fmt.Errorf("no manifest") + } + + switch m.Version { + case ManifestVersion, ManifestVersionGoSDK: + case "": + return fmt.Errorf( + "the manifest declares no version; this CLI reads %q", + ManifestVersion, + ) + default: + return fmt.Errorf( + "the manifest declares version %q and this CLI reads %q", + m.Version, ManifestVersion, + ) + } + + var problems []string + for i, h := range m.Handlers { + problems = append(problems, handlerProblems(fmt.Sprintf("handlers[%d]", i), h.ResourceName, h.Annotations)...) + } + for i, h := range m.FunctionHandlers { + problems = append(problems, handlerProblems(fmt.Sprintf("functionHandlers[%d]", i), h.ResourceName, h.Annotations)...) + } + for i, h := range m.GuardHandlers { + problems = append(problems, handlerProblems(fmt.Sprintf("guardHandlers[%d]", i), h.ResourceName, h.Annotations)...) + } + + if len(problems) > 0 { + return fmt.Errorf("%s", strings.Join(problems, "\n")) + } + return nil +} + +func handlerProblems(where, resourceName string, annotations map[string]any) []string { + var problems []string + if resourceName == "" { + problems = append(problems, fmt.Sprintf( + "%s has no resourceName, which is what names it in the blueprint", where)) + } + for key := range annotations { + if !strings.HasPrefix(key, annotationPrefix) { + problems = append(problems, fmt.Sprintf( + "%s has annotation %q, which is not a Celerity annotation: every key starts with %q", + where, key, annotationPrefix)) + } + } + return problems +} + +const annotationPrefix = "celerity." From e168372a911c0b04b2a554daff453aa53f905415 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 14 Oct 2026 16:19:27 +0100 Subject: [PATCH 11/12] feat(cli): refine the dev commands Compose generation, log parsing and the stub service wiring behind celerity dev run and celerity dev test. A stub service now says which config store its URL belongs in, and an application with several stores is an error rather than a guess, because picking one seeds the URL into a store the application never reads and the only symptom is requests reaching the real endpoint. --- apps/cli/cmd/commands/dev.go | 2 +- apps/cli/cmd/commands/dev_logs.go | 2 +- apps/cli/cmd/commands/dev_run.go | 21 +++- apps/cli/cmd/commands/dev_status.go | 2 +- apps/cli/cmd/commands/dev_stop.go | 2 +- apps/cli/cmd/commands/dev_stubs.go | 6 +- apps/cli/cmd/commands/dev_test_cmd.go | 80 +++++++++++---- apps/cli/internal/compose/consts.go | 24 +++++ apps/cli/internal/compose/generator.go | 55 ++++++++++- apps/cli/internal/compose/generator_test.go | 62 ++++++------ apps/cli/internal/compose/tracing_test.go | 102 ++++++++++++++++++++ apps/cli/internal/compose/types.go | 8 +- apps/cli/internal/devlogs/parser.go | 13 ++- apps/cli/internal/devlogs/parser_test.go | 5 +- apps/cli/internal/devlogs/slog.go | 66 +++++++++++++ apps/cli/internal/devlogs/slog_test.go | 91 +++++++++++++++++ apps/cli/internal/devlogs/streamer_test.go | 5 +- apps/cli/internal/devstubs/types.go | 8 +- 18 files changed, 480 insertions(+), 74 deletions(-) create mode 100644 apps/cli/internal/compose/tracing_test.go create mode 100644 apps/cli/internal/devlogs/slog.go create mode 100644 apps/cli/internal/devlogs/slog_test.go diff --git a/apps/cli/cmd/commands/dev.go b/apps/cli/cmd/commands/dev.go index be92d8b5..7d1b5903 100644 --- a/apps/cli/cmd/commands/dev.go +++ b/apps/cli/cmd/commands/dev.go @@ -1,7 +1,7 @@ package commands import ( - "github.com/newstack-cloud/celerity/apps/cli/internal/config" + "github.com/newstack-cloud/deploy-cli-sdk/config" "github.com/spf13/cobra" ) diff --git a/apps/cli/cmd/commands/dev_logs.go b/apps/cli/cmd/commands/dev_logs.go index e05a291b..1076fbb7 100644 --- a/apps/cli/cmd/commands/dev_logs.go +++ b/apps/cli/cmd/commands/dev_logs.go @@ -6,10 +6,10 @@ import ( "path/filepath" "strings" - "github.com/newstack-cloud/celerity/apps/cli/internal/config" "github.com/newstack-cloud/celerity/apps/cli/internal/devlogs" "github.com/newstack-cloud/celerity/apps/cli/internal/devrun" "github.com/newstack-cloud/celerity/apps/cli/internal/docker" + "github.com/newstack-cloud/deploy-cli-sdk/config" "github.com/spf13/cobra" "golang.org/x/term" ) diff --git a/apps/cli/cmd/commands/dev_run.go b/apps/cli/cmd/commands/dev_run.go index c720976e..5f196e9d 100644 --- a/apps/cli/cmd/commands/dev_run.go +++ b/apps/cli/cmd/commands/dev_run.go @@ -6,12 +6,12 @@ import ( "path/filepath" "github.com/newstack-cloud/celerity/apps/cli/internal/compose" - "github.com/newstack-cloud/celerity/apps/cli/internal/config" "github.com/newstack-cloud/celerity/apps/cli/internal/consts" "github.com/newstack-cloud/celerity/apps/cli/internal/devconfig" "github.com/newstack-cloud/celerity/apps/cli/internal/devrun" "github.com/newstack-cloud/celerity/apps/cli/internal/docker" "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" + "github.com/newstack-cloud/deploy-cli-sdk/config" "github.com/spf13/cobra" "go.uber.org/zap" "golang.org/x/term" @@ -74,6 +74,10 @@ Use --detached to run in the background.`, confProvider.BindPFlag("devRunNoLocalAuth", runCmd.Flags().Lookup("no-local-auth")) confProvider.BindEnvVar("devRunNoLocalAuth", "CELERITY_CLI_DEV_RUN_NO_LOCAL_AUTH") + runCmd.Flags().Bool("tracing", false, "Run a trace collector in the session and export the application's spans to it") + confProvider.BindPFlag("devRunTracing", runCmd.Flags().Lookup("tracing")) + confProvider.BindEnvVar("devRunTracing", "CELERITY_CLI_DEV_RUN_TRACING") + devCmd.AddCommand(runCmd) } @@ -110,15 +114,20 @@ func runDevRun(ctx context.Context, confProvider *config.Provider) error { return err } - var extractor *preprocess.Extractor + var extractor devrun.Extractor conv, _ := consts.ConventionsForRuntime(resolved.Runtime) - if conv.SupportsExtraction { + switch { + case resolved.Toolchain != nil: + // An OS-only runtime hosts no language, so the extractor belongs to + // whichever toolchain built the executable. + extractor = devconfig.NewToolchainExtractor(resolved) + case conv.SupportsExtraction: extractor = preprocess.NewExtractor(preprocess.ExtractorConfig{ Runtime: resolved.Runtime, ModulePath: resolved.ModulePath, ProjectRoot: resolved.AppDir, }, logger) - } else { + default: logger.Info("handler extraction not supported, watcher will only restart on file changes", zap.String("runtime", resolved.Runtime), ) @@ -143,6 +152,8 @@ func runDevRun(ctx context.Context, confProvider *config.Provider) error { Manifest: resolved.Manifest, ContainerCfg: resolved.ContainerConfig, ComposeCfg: resolved.ComposeConfig, + Toolchain: resolved.Toolchain, + HandlersExecutable: resolved.HandlersExecutable, }, dockerMgr, composeMgr, @@ -170,6 +181,7 @@ func resolveOptsFromFlags(confProvider *config.Provider) devconfig.ResolveOpts { verbose, _ := confProvider.GetBool("devRunVerbose") noLocalAuth, _ := confProvider.GetBool("devRunNoLocalAuth") + tracing, _ := confProvider.GetBool("devRunTracing") return devconfig.ResolveOpts{ BlueprintFile: blueprintFile, @@ -182,6 +194,7 @@ func resolveOptsFromFlags(confProvider *config.Provider) devconfig.ResolveOpts { Mode: "run", Verbose: verbose, LocalAuth: !noLocalAuth, + Tracing: tracing, } } diff --git a/apps/cli/cmd/commands/dev_status.go b/apps/cli/cmd/commands/dev_status.go index 65a8d374..11058610 100644 --- a/apps/cli/cmd/commands/dev_status.go +++ b/apps/cli/cmd/commands/dev_status.go @@ -3,10 +3,10 @@ package commands import ( "os" - "github.com/newstack-cloud/celerity/apps/cli/internal/config" "github.com/newstack-cloud/celerity/apps/cli/internal/devrun" "github.com/newstack-cloud/celerity/apps/cli/internal/devstate" "github.com/newstack-cloud/celerity/apps/cli/internal/docker" + "github.com/newstack-cloud/deploy-cli-sdk/config" "github.com/spf13/cobra" "golang.org/x/term" ) diff --git a/apps/cli/cmd/commands/dev_stop.go b/apps/cli/cmd/commands/dev_stop.go index fa5bad96..10e99f0d 100644 --- a/apps/cli/cmd/commands/dev_stop.go +++ b/apps/cli/cmd/commands/dev_stop.go @@ -4,10 +4,10 @@ import ( "os" "github.com/newstack-cloud/celerity/apps/cli/internal/compose" - "github.com/newstack-cloud/celerity/apps/cli/internal/config" "github.com/newstack-cloud/celerity/apps/cli/internal/devrun" "github.com/newstack-cloud/celerity/apps/cli/internal/devstate" "github.com/newstack-cloud/celerity/apps/cli/internal/docker" + "github.com/newstack-cloud/deploy-cli-sdk/config" "github.com/spf13/cobra" "golang.org/x/term" ) diff --git a/apps/cli/cmd/commands/dev_stubs.go b/apps/cli/cmd/commands/dev_stubs.go index 5139faf0..978d5e50 100644 --- a/apps/cli/cmd/commands/dev_stubs.go +++ b/apps/cli/cmd/commands/dev_stubs.go @@ -5,8 +5,8 @@ import ( "os" "path/filepath" - "github.com/newstack-cloud/celerity/apps/cli/internal/config" "github.com/newstack-cloud/celerity/apps/cli/internal/devstubs" + "github.com/newstack-cloud/deploy-cli-sdk/config" "github.com/spf13/cobra" ) @@ -47,7 +47,7 @@ func runStubsValidate(confProvider *config.Provider) error { stubsDir := filepath.Join(appDir, "stubs") if _, err := os.Stat(stubsDir); os.IsNotExist(err) { - fmt.Println("No stubs/ directory found — nothing to validate.") + fmt.Println("No stubs/ directory found, so there is nothing to validate.") return nil } @@ -79,7 +79,7 @@ func runStubsValidate(confProvider *config.Provider) error { } } - fmt.Printf("Validated %d service(s), %d endpoint(s), %d stub(s) — all OK.\n", + fmt.Printf("Validated %d service(s), %d endpoint(s), %d stub(s). All OK.\n", len(services), totalEndpoints, totalStubs) return nil } diff --git a/apps/cli/cmd/commands/dev_test_cmd.go b/apps/cli/cmd/commands/dev_test_cmd.go index 2ec60cb8..01df678b 100644 --- a/apps/cli/cmd/commands/dev_test_cmd.go +++ b/apps/cli/cmd/commands/dev_test_cmd.go @@ -13,14 +13,15 @@ import ( "time" "github.com/newstack-cloud/celerity/apps/cli/internal/compose" - "github.com/newstack-cloud/celerity/apps/cli/internal/config" "github.com/newstack-cloud/celerity/apps/cli/internal/consts" "github.com/newstack-cloud/celerity/apps/cli/internal/devconfig" "github.com/newstack-cloud/celerity/apps/cli/internal/devrun" "github.com/newstack-cloud/celerity/apps/cli/internal/devtest" "github.com/newstack-cloud/celerity/apps/cli/internal/docker" + "github.com/newstack-cloud/celerity/apps/cli/internal/handlertoolchain" "github.com/newstack-cloud/celerity/apps/cli/internal/preprocess" "github.com/newstack-cloud/celerity/apps/cli/internal/seed" + "github.com/newstack-cloud/deploy-cli-sdk/config" "github.com/spf13/cobra" "go.uber.org/zap" "golang.org/x/term" @@ -108,10 +109,13 @@ After tests complete, all infrastructure is torn down unless --no-teardown is se confProvider.BindPFlag("devTestNoLocalAuth", testCmd.Flags().Lookup("no-local-auth")) confProvider.BindEnvVar("devTestNoLocalAuth", "CELERITY_CLI_DEV_TEST_NO_LOCAL_AUTH") + testCmd.Flags().Bool("tracing", false, "Run a trace collector in the session and export the application's spans to it") + confProvider.BindPFlag("devTestTracing", testCmd.Flags().Lookup("tracing")) + confProvider.BindEnvVar("devTestTracing", "CELERITY_CLI_DEV_TEST_TRACING") + devCmd.AddCommand(testCmd) } -// testFlags holds parsed CLI flags for dev test. type testFlags struct { suites []devtest.TestSuite infraLevel devtest.InfraLevel @@ -154,9 +158,9 @@ func parseTestFlags(confProvider *config.Provider) (*testFlags, error) { }, nil } -// setupTestInfra resolves config, starts Docker dependencies and (for API suites) -// the app container, then waits for health. Returns nil orchestrator when no -// infrastructure is needed (unit-only suites). +// Resolves config, starts Docker dependencies and, for API suites, the app +// container, then waits for health. A nil orchestrator is returned when no +// infrastructure is needed, as for unit-only suites. func setupTestInfra( ctx context.Context, opts devconfig.ResolveOpts, @@ -250,8 +254,8 @@ func setupTestInfra( return orch, resolved, nil } -// buildTestEnv assembles the environment variables passed to the test process, -// including host endpoints, config store IDs, and Valkey connection overrides. +// Assembles the environment variables passed to the test process, covering host +// endpoints, config store IDs and Valkey connection overrides. func buildTestEnv(resolved *devconfig.ResolvedConfig) map[string]string { testEnv := map[string]string{} if resolved == nil { @@ -306,7 +310,6 @@ func runDevTest(ctx context.Context, confProvider *config.Provider) error { var orch *devrun.Orchestrator var resolved *devconfig.ResolvedConfig - // Set up signal handling for teardown. ctx, cancel := context.WithCancel(ctx) defer cancel() @@ -319,8 +322,8 @@ func runDevTest(ctx context.Context, confProvider *config.Provider) error { if orch == nil || flags.noTeardown { return } - // Only dump logs when tests failed or errored — on success - // the logs are noise. + // Logs are only dumped when tests failed or errored, since on success + // they are noise. if testsFailed && flags.infraLevel >= devtest.InfraLevelCompose { if logDir := orch.DumpLogs(context.Background()); logDir != "" { output.PrintStep(fmt.Sprintf("Logs saved to %s", logDir)) @@ -332,7 +335,6 @@ func runDevTest(ctx context.Context, confProvider *config.Provider) error { } } - // Start infrastructure if needed. if flags.infraLevel > devtest.InfraLevelNone { orch, resolved, err = setupTestInfra(ctx, opts, flags, output, logger) if err != nil { @@ -341,8 +343,8 @@ func runDevTest(ctx context.Context, confProvider *config.Provider) error { } } - // Resolve runtime for the test runner. - // If we didn't resolve config (unit-only), detect runtime from project files. + // A unit-only run resolves no config, so the runtime for the test runner + // comes from the project files instead. runtime := "" appDir := opts.AppDir if appDir == "" || appDir == "." { @@ -359,7 +361,13 @@ func runDevTest(ctx context.Context, confProvider *config.Provider) error { runtime = detectedRuntime } - runner, err := devtest.RunnerForRuntime(runtime, logger) + toolchain, err := testToolchain(resolved, runtime, appDir) + if err != nil { + teardown() + return err + } + + runner, err := devtest.RunnerForRuntime(runtime, toolchain, logger) if err != nil { teardown() return err @@ -386,7 +394,6 @@ func runDevTest(ctx context.Context, confProvider *config.Provider) error { runConfig.HostPort = resolved.Port } - // Run tests, handling signals. resultChan := make(chan *devtest.RunResult, 1) errChan := make(chan error, 1) go func() { @@ -444,6 +451,7 @@ func testResolveOpts(confProvider *config.Provider) devconfig.ResolveOpts { serviceName, _ := confProvider.GetString("devTestServiceName") verbose, _ := confProvider.GetBool("devTestVerbose") noLocalAuth, _ := confProvider.GetBool("devTestNoLocalAuth") + tracing, _ := confProvider.GetBool("devTestTracing") return devconfig.ResolveOpts{ BlueprintFile: blueprintFile, @@ -456,6 +464,7 @@ func testResolveOpts(confProvider *config.Provider) devconfig.ResolveOpts { Mode: "test", Verbose: verbose, LocalAuth: !noLocalAuth, + Tracing: tracing, } } @@ -481,8 +490,7 @@ func isValidSuite(s devtest.TestSuite) bool { return slices.Contains(devtest.ValidSuites, s) } -// detectRuntimeFromProject detects the runtime from project files when no -// blueprint resolution is performed (unit-only mode). +// Used in unit-only mode, where no blueprint resolution is performed. func detectRuntimeFromProject(appDir string) (string, error) { if _, err := os.Stat(appDir + "/package.json"); err == nil { return "nodejs", nil @@ -491,7 +499,43 @@ func detectRuntimeFromProject(appDir string) (string, error) { return "python", nil } if _, err := os.Stat(appDir + "/go.mod"); err == nil { - return "go", nil + // The OS-only runtime identifier rather than "go", because a Go + // application runs on one and that is what the runner registry and the + // conventions are keyed by. + return consts.RuntimeOSOnlyDebian13, nil } return "", fmt.Errorf("no package.json, pyproject.toml, or go.mod found in %s", appDir) } + +// Finds the build tooling whose test command a run should use. +// +// Taken from the resolved config where there is one, so the test run uses the +// same toolchain the application was resolved with. A unit-only run resolves no +// config at all, so one is worked out from the project directory instead. +func testToolchain( + resolved *devconfig.ResolvedConfig, + runtime string, + appDir string, +) (handlertoolchain.Toolchain, error) { + if resolved != nil { + return resolved.Toolchain, nil + } + if !handlertoolchain.IsOSOnly(runtime) { + return nil, nil + } + + var handlerBuild *handlertoolchain.Config + if path := devconfig.FindDeployConfig(appDir); path != "" { + var err error + handlerBuild, err = devconfig.ReadHandlerBuild(path) + if err != nil { + return nil, err + } + } + + return handlertoolchain.Resolve(handlertoolchain.Options{ + Runtime: runtime, + AppDir: appDir, + Config: handlerBuild, + }) +} diff --git a/apps/cli/internal/compose/consts.go b/apps/cli/internal/compose/consts.go index a24240ff..85c1d509 100644 --- a/apps/cli/internal/compose/consts.go +++ b/apps/cli/internal/compose/consts.go @@ -50,6 +50,18 @@ const ( mountebankImage = "bbyars/mountebank:2.9.3" mountebankAPIPort = "2525" + + // Jaeger v2 is an OpenTelemetry Collector distribution, so one container + // both ingests OTLP and serves the UI that reads it. A separate collector + // in front of it would be a second image and a config file to mount for + // no gain in a session whose traces nothing forwards anywhere. + // + // Storage is in memory, which needs no volume and no cleanup: a session's + // traces describe that session, and keeping them past it would mean + // reading a trace of code that has since been rebuilt. + tracingImage = "jaegertracing/jaeger:2.22.0" + tracingOTLPPort = "4317" + tracingUIPort = "16686" ) // ServiceName constants for compose services. @@ -62,6 +74,11 @@ const ( ServiceNameLocalEvents = "local-events" ServiceNameDevAuth = "dev-auth" ServiceNameStubs = "stubs" + // ServiceNameTracing is otelcollector rather than jaeger because that is + // the host every Celerity SDK defaults its OTLP endpoint to, so an + // application reaches a session's traces whether or not the endpoint was + // set for it. The endpoint is set as well, since every other service's is. + ServiceNameTracing = "otelcollector" ) // Runtime environment variable names set by compose services. @@ -77,6 +94,13 @@ const ( EnvCacheEndpoint = "CELERITY_LOCAL_CACHE_ENDPOINT" EnvDevAuthBaseURL = "CELERITY_DEV_AUTH_BASE_URL" EnvStubsAPIURL = "CELERITY_STUBS_API_URL" + // EnvTelemetryEnabled has to be true before an SDK builds an exporter at + // all, so that an application which traces nothing opens no connection. + EnvTelemetryEnabled = "CELERITY_TELEMETRY_ENABLED" + // EnvTraceEndpoint is the Celerity name for where to export traces. + // OpenTelemetry's own OTEL_EXPORTER_OTLP_ENDPOINT is read ahead of it, so + // a developer who sets that points their session wherever they like. + EnvTraceEndpoint = "CELERITY_TRACE_OTLP_COLLECTOR_ENDPOINT" ) var defaultPostgresCreds = struct { diff --git a/apps/cli/internal/compose/generator.go b/apps/cli/internal/compose/generator.go index 7ad0ca0d..584bb574 100644 --- a/apps/cli/internal/compose/generator.go +++ b/apps/cli/internal/compose/generator.go @@ -32,6 +32,7 @@ func GenerateComposeConfig( appDir string, portOffset int, localAuth bool, + tracing bool, logger *zap.Logger, ) (*ComposeConfig, error) { emptyConfig := &ComposeConfig{ @@ -69,6 +70,7 @@ func GenerateComposeConfig( } } + addTracingServiceIfNeeded(services, runtimeEnvVars, portOffset, tracing) addValkeyServiceIfNeeded(services, runtimeEnvVars, resourceTypes, portOffset) addDevAuthServiceIfNeeded(services, runtimeEnvVars, bp, portOffset, localAuth) stubServices, err := addStubsServiceIfNeeded(services, runtimeEnvVars, appDir, portOffset, logger) @@ -101,9 +103,58 @@ func GenerateComposeConfig( FilePath: composeFilePath, StreamEnabledTables: streamEnabledTables, StubServices: stubServices, + TracingUIURL: tracingUIURL(services, portOffset), }, nil } +// addTracingServiceIfNeeded adds the collector a session's traces are read in. +// +// Asked for rather than inferred from the blueprint's resources, because what +// it serves is the dispatch span every handler opens rather than any one +// resource's calls. +func addTracingServiceIfNeeded( + services map[string]*ComposeService, + runtimeEnvVars map[string]string, + portOffset int, + tracing bool, +) { + if !tracing { + return + } + + services[ServiceNameTracing] = &ComposeService{ + Image: tracingImage, + Ports: []string{ + // The UI, which is the point of running it. + offsetPort(tracingUIPort, portOffset) + ":" + tracingUIPort, + // OTLP as well, although the application container reaches it over + // the compose network: an integration suite runs on the host, and + // a handler it exercises in process exports from there. + offsetPort(tracingOTLPPort, portOffset) + ":" + tracingOTLPPort, + }, + HealthCheck: toComposeHealth(&HealthCheck{ + // wget rather than curl, which the image does not carry. + Test: []string{"CMD", "wget", "--spider", "-q", "http://localhost:" + tracingUIPort + "/"}, + Interval: "5s", + Timeout: "3s", + Retries: 5, + StartPeriod: "5s", + }), + } + + runtimeEnvVars[EnvTelemetryEnabled] = "true" + runtimeEnvVars[EnvTraceEndpoint] = "http://" + ServiceNameTracing + ":" + tracingOTLPPort +} + +// tracingUIURL is where the collector's UI is reachable from the host, or +// empty where no collector was asked for. +func tracingUIURL(services map[string]*ComposeService, portOffset int) string { + if _, running := services[ServiceNameTracing]; !running { + return "" + } + return "http://localhost:" + offsetPort(tracingUIPort, portOffset) +} + func collectResourceTypes(bp *schema.Blueprint) map[string]bool { types := map[string]bool{} for _, resource := range bp.Resources.Values { @@ -539,12 +590,14 @@ var serviceHostReplacements = []struct{ from, to string }{ {"://" + ServiceNameValkey + ":", "://localhost:"}, {"://" + ServiceNameDevAuth + ":", "://localhost:"}, {"://" + ServiceNameStubs + ":", "://localhost:"}, + {"://" + ServiceNameTracing + ":", "://localhost:"}, {"@" + ServiceNameSqlDatabase + ":", "@localhost:"}, } var knownContainerPorts = []string{ dynamoDBLocalPort, minioPort, minioAPIPort, postgresPort, valkeyPort, devAuthPort, mountebankAPIPort, + tracingOTLPPort, tracingUIPort, } // buildHostEnvVars rewrites RuntimeEnvVars (compose service names + container ports) @@ -793,7 +846,7 @@ func collectDatastoreBridgeConfigs( return nil, nil } - // Only AWS targets use DynamoDB Local — other providers are not yet supported. + // Only AWS targets use DynamoDB Local. Other providers are not yet supported. if deployTarget != DeployTargetAWS && deployTarget != DeployTargetAWSServerless { return nil, nil } diff --git a/apps/cli/internal/compose/generator_test.go b/apps/cli/internal/compose/generator_test.go index 94a1854a..4d17a233 100644 --- a/apps/cli/internal/compose/generator_test.go +++ b/apps/cli/internal/compose/generator_test.go @@ -35,7 +35,7 @@ version: 2025-11-02 resources: {} `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().Empty(cfg.Services) s.Assert().Empty(cfg.RuntimeEnvVars) @@ -51,7 +51,7 @@ resources: name: users `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) ds, ok := cfg.Services[ServiceNameDatastore] @@ -74,7 +74,7 @@ resources: name: users `) appDir := s.T().TempDir() - _, err := GenerateComposeConfig(bp, DeployTargetGCloud, "test-project", appDir, 0, true, s.logger) + _, err := GenerateComposeConfig(bp, DeployTargetGCloud, "test-project", appDir, 0, true, false, s.logger) s.Require().Error(err) s.Assert().Contains(err.Error(), "not yet supported") } @@ -89,7 +89,7 @@ resources: name: users `) appDir := s.T().TempDir() - _, err := GenerateComposeConfig(bp, DeployTargetAzure, "test-project", appDir, 0, true, s.logger) + _, err := GenerateComposeConfig(bp, DeployTargetAzure, "test-project", appDir, 0, true, false, s.logger) s.Require().Error(err) s.Assert().Contains(err.Error(), "not yet supported") } @@ -104,7 +104,7 @@ resources: name: users `) appDir := s.T().TempDir() - _, err := GenerateComposeConfig(bp, "custom-platform", "test-project", appDir, 0, true, s.logger) + _, err := GenerateComposeConfig(bp, "custom-platform", "test-project", appDir, 0, true, false, s.logger) s.Require().Error(err) s.Assert().Contains(err.Error(), "unsupported deploy target") } @@ -131,7 +131,7 @@ resources: name: events `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) // URL-type host env vars should use localhost, not Docker service names. @@ -154,7 +154,7 @@ resources: name: users `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWSServerless, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWSServerless, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) _, ok := cfg.Services[ServiceNameDatastore] @@ -171,7 +171,7 @@ resources: name: my-bucket `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) storage, ok := cfg.Services[ServiceNameStorage] @@ -197,7 +197,7 @@ resources: name: sessions `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) // Single Valkey service even though two resource types need it. @@ -225,7 +225,7 @@ resources: authMode: password `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) pg, ok := cfg.Services[ServiceNameSqlDatabase] @@ -285,7 +285,7 @@ resources: name: audit `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) // 4 services: datastore, storage, valkey (shared), sql-database. @@ -306,7 +306,7 @@ resources: name: events `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) expectedPath := filepath.Join(appDir, ".celerity", "compose.generated.yaml") @@ -330,7 +330,7 @@ resources: name: main-vpc `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().Empty(cfg.Services) } @@ -370,7 +370,7 @@ resources: schedule: "rate(1d)" `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) le, ok := cfg.Services[ServiceNameLocalEvents] @@ -414,7 +414,7 @@ resources: sourceId: "celerity::topic::notifications" `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().Contains(cfg.Services, ServiceNameLocalEvents) @@ -460,7 +460,7 @@ resources: batchSize: 25 `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().Contains(cfg.Services, ServiceNameLocalEvents) @@ -513,7 +513,7 @@ resources: batchSize: 10 `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().Contains(cfg.Services, ServiceNameLocalEvents) @@ -565,7 +565,7 @@ resources: batchSize: 5 `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().Contains(cfg.Services, ServiceNameLocalEvents) @@ -647,7 +647,7 @@ resources: batchSize: 10 `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().Contains(cfg.Services, ServiceNameDatastore) @@ -688,7 +688,7 @@ resources: name: events `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().NotContains(cfg.Services, ServiceNameLocalEvents) @@ -734,7 +734,7 @@ resources: batchSize: 25 `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().Len(cfg.StreamEnabledTables, 1) @@ -770,7 +770,7 @@ resources: batchSize: 25 `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWSServerless, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWSServerless, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().Contains(cfg.Services, ServiceNameLocalEvents) @@ -808,7 +808,7 @@ resources: batchSize: 10 `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().NotContains(cfg.Services, ServiceNameLocalEvents) @@ -840,7 +840,7 @@ resources: batchSize: 5 `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().Contains(cfg.Services, ServiceNameLocalEvents) @@ -883,7 +883,7 @@ resources: batchSize: 5 `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().Contains(cfg.Services, ServiceNameLocalEvents) @@ -939,7 +939,7 @@ resources: audience: "my-app" `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) devAuth, ok := cfg.Services[ServiceNameDevAuth] @@ -966,7 +966,7 @@ resources: issuer: "https://auth.example.com" `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) devAuth := cfg.Services[ServiceNameDevAuth] @@ -984,7 +984,7 @@ resources: - http `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().NotContains(cfg.Services, ServiceNameDevAuth) } @@ -999,7 +999,7 @@ resources: name: users `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 100, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 100, true, false, s.logger) s.Require().NoError(err) ds := cfg.Services[ServiceNameDatastore] @@ -1035,7 +1035,7 @@ resources: 0o644, )) - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) stubs, ok := cfg.Services[ServiceNameStubs] @@ -1059,7 +1059,7 @@ resources: name: events `) appDir := s.T().TempDir() - cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, s.logger) + cfg, err := GenerateComposeConfig(bp, DeployTargetAWS, "test-project", appDir, 0, true, false, s.logger) s.Require().NoError(err) s.Assert().NotContains(cfg.Services, ServiceNameStubs) } diff --git a/apps/cli/internal/compose/tracing_test.go b/apps/cli/internal/compose/tracing_test.go new file mode 100644 index 00000000..31d3b13c --- /dev/null +++ b/apps/cli/internal/compose/tracing_test.go @@ -0,0 +1,102 @@ +package compose + +import ( + "testing" + + "github.com/newstack-cloud/bluelink/libs/blueprint/schema" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" +) + +// A session's traces are read in a collector it runs itself, so what has to be +// right is that the application is told where to export and the developer is +// told where to look. +type TracingServiceSuite struct { + suite.Suite + logger *zap.Logger +} + +func TestTracingServiceSuite(t *testing.T) { suite.Run(t, new(TracingServiceSuite)) } + +func (s *TracingServiceSuite) SetupTest() { + s.logger = zap.NewNop() +} + +// An API alone, so nothing in the blueprint could imply a collector: it is +// there because it was asked for. +const tracingBlueprint = ` +version: 2025-11-02 +resources: + ordersApi: + type: "celerity/api" + spec: + name: orders +` + +func (s *TracingServiceSuite) generate(portOffset int, tracing bool) *ComposeConfig { + s.T().Helper() + bp, err := schema.LoadString(tracingBlueprint, schema.YAMLSpecFormat) + s.Require().NoError(err) + + cfg, err := GenerateComposeConfig( + bp, DeployTargetAWS, "test-project", s.T().TempDir(), portOffset, true, tracing, s.logger, + ) + s.Require().NoError(err) + return cfg +} + +func (s *TracingServiceSuite) Test_no_collector_runs_unless_one_is_asked_for() { + cfg := s.generate(0, false) + + s.Assert().NotContains(cfg.Services, ServiceNameTracing) + s.Assert().NotContains(cfg.RuntimeEnvVars, EnvTelemetryEnabled) + s.Assert().Empty(cfg.TracingUIURL) +} + +func (s *TracingServiceSuite) Test_the_collector_serves_its_ui_and_ingests_otlp() { + cfg := s.generate(0, true) + + service, running := cfg.Services[ServiceNameTracing] + s.Require().True(running) + s.Assert().Equal(tracingImage, service.Image) + s.Assert().ElementsMatch([]string{"16686:16686", "4317:4317"}, service.Ports) + s.Require().NotNil(service.HealthCheck) + s.Assert().Contains(service.HealthCheck.Test, "wget", + "the image carries no curl") +} + +// Enabling is not enough on its own: an SDK builds no exporter until it is +// told tracing is on, so an endpoint without the switch exports nothing. +func (s *TracingServiceSuite) Test_the_application_is_told_tracing_is_on_and_where_to_export() { + cfg := s.generate(0, true) + + s.Assert().Equal("true", cfg.RuntimeEnvVars[EnvTelemetryEnabled]) + s.Assert().Equal( + "http://"+ServiceNameTracing+":4317", + cfg.RuntimeEnvVars[EnvTraceEndpoint], + "the compose network name, since the application container is on it", + ) +} + +// A suite run by `celerity dev test` runs on the host, so a handler it +// exercises in process cannot reach a compose service by name. +func (s *TracingServiceSuite) Test_the_host_endpoint_reaches_the_published_port() { + cfg := s.generate(0, true) + + s.Assert().Equal("http://localhost:4317", cfg.HostEnvVars[EnvTraceEndpoint]) +} + +// dev run and dev test both bring a stack up, so the second has to land +// somewhere the first is not already listening. +func (s *TracingServiceSuite) Test_a_second_stack_offsets_both_ports() { + cfg := s.generate(100, true) + + service := cfg.Services[ServiceNameTracing] + s.Assert().ElementsMatch([]string{"16786:16686", "4417:4317"}, service.Ports) + s.Assert().Equal("http://localhost:16786", cfg.TracingUIURL) + s.Assert().Equal("http://localhost:4417", cfg.HostEnvVars[EnvTraceEndpoint]) +} + +func (s *TracingServiceSuite) Test_the_ui_url_is_reported_for_the_session_to_print() { + s.Assert().Equal("http://localhost:16686", s.generate(0, true).TracingUIURL) +} diff --git a/apps/cli/internal/compose/types.go b/apps/cli/internal/compose/types.go index bb20a111..2e62a743 100644 --- a/apps/cli/internal/compose/types.go +++ b/apps/cli/internal/compose/types.go @@ -29,8 +29,8 @@ type HealthCheck struct { // ComposeConfig represents the generated Docker Compose configuration. type ComposeConfig struct { - Services map[string]*ComposeService - RuntimeEnvVars map[string]string + Services map[string]*ComposeService + RuntimeEnvVars map[string]string // HostEnvVars contains the same endpoints as RuntimeEnvVars but rewritten // for host access (localhost with host-mapped ports). Use these when // connecting from the host machine (seeding, test runners) rather than @@ -42,6 +42,10 @@ type ComposeConfig struct { // StubServices holds loaded stub service configs for the orchestrator // to seed config values and load mountebank imposters after compose up. StubServices []StubServiceInfo + // TracingUIURL is where a session's traces are read, and is empty when no + // collector was asked for. Carried rather than derived by the caller, + // because the host port it is on is the generator's port offset applied. + TracingUIURL string } // StubServiceInfo carries the information needed to seed config values diff --git a/apps/cli/internal/devlogs/parser.go b/apps/cli/internal/devlogs/parser.go index 43e49313..7adeb066 100644 --- a/apps/cli/internal/devlogs/parser.go +++ b/apps/cli/internal/devlogs/parser.go @@ -81,6 +81,13 @@ func sdkParserForRuntime(runtime string) SDKLogParseFunc { return parseNodeJSLog case strings.HasPrefix(lower, "python"): return parseStructlogJSON + // An OS-only runtime hosts no language, so the format belongs to whichever + // SDK built the handlers executable rather than to the runtime. slog is + // what the Go SDK writes, and it is tried rather than selected, so a record + // that is not one falls through to the passthrough a community SDK's output + // already gets. + case strings.HasPrefix(lower, "os-only"): + return parseSlogJSON default: return nil } @@ -99,9 +106,9 @@ func parseNodeJSLog(raw string) (LogLine, bool) { return parsePinoJSON(raw) } -// isNodeJSDebugLine reports whether raw looks like output from the Node.js -// debug package, which prefixes every line with an ISO 8601 timestamp -// (YYYY-MM-DDTHH:MM:SS...) followed by the debug namespace and message. +// The Node.js debug package prefixes every line with an ISO 8601 timestamp +// (YYYY-MM-DDTHH:MM:SS...) followed by the debug namespace and the message, so +// the leading separators are enough to recognise one. func isNodeJSDebugLine(raw string) bool { if len(raw) < 20 { return false diff --git a/apps/cli/internal/devlogs/parser_test.go b/apps/cli/internal/devlogs/parser_test.go index 03108bc0..9cab847a 100644 --- a/apps/cli/internal/devlogs/parser_test.go +++ b/apps/cli/internal/devlogs/parser_test.go @@ -74,7 +74,8 @@ func (s *ParserTestSuite) Test_pino_json_not_matched_by_default_parser() { } func (s *ParserTestSuite) Test_pino_json_matched_by_versioned_nodejs_runtime() { - // Runtimes are stored as e.g. "nodejs24.x" — the parser must use prefix matching. + // Runtimes are stored as e.g. "nodejs24.x", so the parser must match by + // prefix. raw := `{"level":30,"time":"2024-01-01T00:00:00Z","msg":"hello","handlerName":"Orders"}` parser := NewLogParser("nodejs24.x") line := parser.Parse(raw) @@ -84,7 +85,7 @@ func (s *ParserTestSuite) Test_pino_json_matched_by_versioned_nodejs_runtime() { } func (s *ParserTestSuite) Test_pino_json_name_field_excluded_from_extra() { - // "name" is pino's logger name — should not appear as an extra field. + // "name" is pino's logger name, which should not appear as an extra field. raw := `{"level":30,"time":"2024-01-01T00:00:00Z","msg":"guard action","name":"guard","handlerName":"Orders"}` line := s.nodeParser().Parse(raw) s.Equal("guard action", line.Message) diff --git a/apps/cli/internal/devlogs/slog.go b/apps/cli/internal/devlogs/slog.go new file mode 100644 index 00000000..1f8c6fcb --- /dev/null +++ b/apps/cli/internal/devlogs/slog.go @@ -0,0 +1,66 @@ +package devlogs + +import ( + "encoding/json" + "strings" +) + +// The Celerity Go SDK writes through log/slog, whose JSON handler names the +// three record fields time, level and msg, and renders a level in upper case. +// Neither matches structlog, which writes timestamp and lower-case names, so +// reusing the Python parser for it would leave every record undated and at +// the default level. + +// A dispatch arrives already carrying these, bound by the SDK before the +// application has added anything of its own. +const ( + slogHandlerKey = "handler" + slogEventIDKey = "eventId" +) + +var slogKnownKeys = map[string]bool{ + "time": true, "level": true, "msg": true, + slogHandlerKey: true, slogEventIDKey: true, +} + +// slog's own set, and only these four, so a line that merely carries a level is +// not taken for an slog record. The Rust core runtime's tracing JSON also spells +// its levels in upper case, and the two are separated by that one carrying a +// fields object, which parseTracingJSON checks for first. +var slogLevels = map[string]bool{ + LevelDebug: true, LevelInfo: true, + LevelWarn: true, LevelError: true, +} + +func parseSlogJSON(raw string) (LogLine, bool) { + if len(raw) == 0 || raw[0] != '{' { + return LogLine{}, false + } + + var all map[string]any + if err := json.Unmarshal([]byte(raw), &all); err != nil { + return LogLine{}, false + } + + level, hasLevel := all["level"].(string) + if !hasLevel || !slogLevels[strings.ToUpper(level)] { + return LogLine{}, false + } + // A record has a message, and demanding one is what keeps an arbitrary + // JSON object that happens to carry a level from being read as a record. + if _, hasMessage := all["msg"].(string); !hasMessage { + return LogLine{}, false + } + + return LogLine{ + Timestamp: stringFromMap(all, "time"), + Level: strings.ToUpper(level), + Message: stringFromMap(all, "msg"), + HandlerName: stringFromMap(all, slogHandlerKey), + // The SDK's own correlation id for one dispatch, which is what the + // other two SDKs call a request id. + RequestID: stringFromMap(all, slogEventIDKey), + RawLine: raw, + Extra: collectExtra(all, slogKnownKeys), + }, true +} diff --git a/apps/cli/internal/devlogs/slog_test.go b/apps/cli/internal/devlogs/slog_test.go new file mode 100644 index 00000000..8a31bc67 --- /dev/null +++ b/apps/cli/internal/devlogs/slog_test.go @@ -0,0 +1,91 @@ +package devlogs + +import ( + "testing" + + "github.com/stretchr/testify/suite" +) + +// The lines asserted here were produced by the Celerity Go SDK rather than +// written to look like it, since what the parser has to agree with is what +// log/slog's JSON handler actually emits: the fields named time, level and +// msg, and a level in upper case. +type SlogSuite struct { + suite.Suite + parser *LogParser +} + +func TestSlogSuite(t *testing.T) { suite.Run(t, new(SlogSuite)) } + +func (s *SlogSuite) SetupTest() { + s.parser = NewLogParser("os-only.debian13") +} + +func (s *SlogSuite) Test_a_record_keeps_its_time_level_and_message() { + line := s.parser.Parse( + `{"time":"2026-10-09T02:43:48.431277+01:00","level":"INFO","msg":"order created",` + + `"orderId":"o-1","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"}`) + + s.Assert().Equal("2026-10-09T02:43:48.431277+01:00", line.Timestamp) + s.Assert().Equal(LevelInfo, line.Level) + s.Assert().Equal("order created", line.Message) +} + +// Without this the whole line is printed as the message and every record +// reads at info, which is what a Go session got before the parser existed. +func (s *SlogSuite) Test_every_level_is_recognised() { + for raw, want := range map[string]string{ + `{"time":"t","level":"DEBUG","msg":"m"}`: LevelDebug, + `{"time":"t","level":"INFO","msg":"m"}`: LevelInfo, + `{"time":"t","level":"WARN","msg":"m"}`: LevelWarn, + `{"time":"t","level":"ERROR","msg":"m"}`: LevelError, + } { + s.Assert().Equal(want, s.parser.Parse(raw).Level, raw) + } +} + +// Bound by the SDK before a handler has added anything, so they are the +// correlation a reader scanning a session is looking for rather than +// attributes among the application's own. +func (s *SlogSuite) Test_the_handler_and_the_event_are_lifted_out_of_the_attributes() { + line := s.parser.Parse( + `{"time":"t","level":"INFO","msg":"dispatched","handler":"createOrder",` + + `"tag":"http","eventId":"ev-1"}`) + + s.Assert().Equal("createOrder", line.HandlerName) + s.Assert().Equal("ev-1", line.RequestID) + s.Assert().Equal("http", line.Extra["tag"], "the rest stay attributes") + s.Assert().NotContains(line.Extra, "handler") + s.Assert().NotContains(line.Extra, "msg") +} + +// The Rust core runtime also spells its levels in upper case, and its records +// are the ones with a fields object. They have to keep going to the tracing +// parser, which names the span a line came from. +func (s *SlogSuite) Test_a_core_runtime_record_is_still_read_as_one() { + line := s.parser.Parse( + `{"timestamp":"t","level":"INFO","fields":{"message":"listening"},"target":"celerity"}`) + + s.Assert().Equal("runtime", line.Source) + s.Assert().Equal("listening", line.Message) +} + +func (s *SlogSuite) Test_json_that_is_not_a_record_falls_through() { + for _, raw := range []string{ + `{"level":"INFO"}`, + `{"msg":"no level"}`, + `{"level":"TRACE","msg":"not one of slog's"}`, + `{"level":42,"msg":"m"}`, + } { + _, ok := parseSlogJSON(raw) + s.Assert().False(ok, raw) + } +} + +// A compiled language the CLI has no parser for still reaches the reader. +func (s *SlogSuite) Test_a_line_that_is_not_json_is_passed_through() { + line := s.parser.Parse("plain text from another sdk") + + s.Assert().Equal("plain text from another sdk", line.Message) + s.Assert().Equal(LevelInfo, line.Level) +} diff --git a/apps/cli/internal/devlogs/streamer_test.go b/apps/cli/internal/devlogs/streamer_test.go index df302b25..e76b660b 100644 --- a/apps/cli/internal/devlogs/streamer_test.go +++ b/apps/cli/internal/devlogs/streamer_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/suite" ) -// mockDockerManager is a minimal mock that returns pre-canned log data. +// A minimal mock that returns pre-canned log data. type mockDockerManager struct { logData string } @@ -54,7 +54,8 @@ func (s *StreamerTestSuite) Test_pino_json_still_formatted() { } func (s *StreamerTestSuite) Test_pino_json_parsed_with_versioned_runtime() { - // Runtimes are stored as "nodejs24.x" — ensure pino JSON is parsed with a versioned runtime. + // Runtimes are stored as "nodejs24.x", so pino JSON has to be parsed for a + // versioned runtime too. input := `{"level":30,"time":"2024-01-01T00:00:00Z","msg":"user created","handlerName":"Users","name":"request"}` + "\n" out := s.streamWithRuntime(input, StreamOptions{}, "nodejs24.x") diff --git a/apps/cli/internal/devstubs/types.go b/apps/cli/internal/devstubs/types.go index 7724bf26..c63f6572 100644 --- a/apps/cli/internal/devstubs/types.go +++ b/apps/cli/internal/devstubs/types.go @@ -3,10 +3,10 @@ package devstubs // ServiceConfig is the service-level configuration parsed from // stubs//service.yaml. type ServiceConfig struct { - Port int `yaml:"port"` - ConfigKey string `yaml:"configKey"` - ConfigNamespace string `yaml:"configNamespace,omitempty"` - DefaultResponse map[string]any `yaml:"defaultResponse,omitempty"` + Port int `yaml:"port"` + ConfigKey string `yaml:"configKey"` + ConfigNamespace string `yaml:"configNamespace,omitempty"` + DefaultResponse map[string]any `yaml:"defaultResponse,omitempty"` } // EndpointStubFile is the structure of a single endpoint stub file From 81548fe54f4c2d5f77b1be55e919466746e3ecfd Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Wed, 14 Oct 2026 16:19:43 +0100 Subject: [PATCH 12/12] chore: ignore build output and unpublished working notes go build with no -o writes the local events binary under the module basename, so it lands next to the source rather than in a build directory and shows up as untracked. Design records, implementation plans and working notes move to a docs/internal directory beside the project they describe, ignored by one rule that covers every sub-project so a new one needs no change. The documentation that ships lives in the Celerity docs site, so none of this belongs in version control, and keeping it under a predictable name stops an add -A pulling it back in. --- .gitignore | 6 ++++++ apps/local-events/.gitignore | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/.gitignore b/.gitignore index 04662f00..47ef8b13 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,9 @@ node_modules **/.claude blueprint-ls.log + +# Design records, implementation plans and working notes. Kept next to the +# project they describe but deliberately unpublished, since the documentation +# that ships lives in the celerity docs site rather than here. One rule covers +# every sub-project, so a new one needs no change to this file. +**/docs/internal/ diff --git a/apps/local-events/.gitignore b/apps/local-events/.gitignore index b8f8256c..a20a2e5a 100644 --- a/apps/local-events/.gitignore +++ b/apps/local-events/.gitignore @@ -8,6 +8,10 @@ gen-*.go *.so *.dylib +# The compiled sidecar. `go build` with no -o writes it here under the module +# basename, so it lands next to the source rather than in a build directory. +/local-events + # Test binary, built with `go test -c` *.test