diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 2e237864..0dc521b2 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,7 +5,7 @@ "plugins": [ { "name": "visualci", - "version": "0.1.45", + "version": "0.1.46", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "author": { "name": "DocSpring", "url": "https://visualci.com" }, "homepage": "https://visualci.com/docs/skills/", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 8a80ecf3..78da2802 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.45", + "version": "0.1.46", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "author": { "name": "DocSpring", "url": "https://visualci.com" }, "homepage": "https://visualci.com/docs/skills/", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 488d8bd6..48895fdc 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "visualci", "displayName": "VisualCI", - "version": "0.1.45", + "version": "0.1.46", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "author": { "name": "DocSpring" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 710ef512..43ae6e88 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,10 +23,25 @@ env: jobs: lint: runs-on: ${{ fromJSON(vars.CI_RUNNER || '"ubuntu-latest"') }} + environment: ${{ github.ref == 'refs/heads/main' && 'kache-write' || '' }} timeout-minutes: 30 steps: - uses: actions/checkout@v4 - - uses: Swatinem/rust-cache@v2 + # Compile cache (kache, as Cargo's rustc wrapper): the R2 bucket every machine shares (KACHE_BUCKET), else the + # GitHub Actions cache. Only main writes it: the read-write key is a secret of the kache-write environment, + # which only main may use, so a pull request (whatever its ci.yml says) gets the read-only key. + - uses: kunobi-ninja/kache-action@061011817fd04b0e460f79d6bb3c115b1fc8f029 # v1 + with: + version: "2.4.0" + cache-key-prefix: kache-${{ github.job }} + save-cache: ${{ github.ref == 'refs/heads/main' }} + pr-comment: false + s3-bucket: ${{ vars.KACHE_BUCKET }} + s3-endpoint: ${{ vars.KACHE_ENDPOINT }} + s3-region: auto + s3-prefix: visualci + s3-access-key-id: ${{ github.ref == 'refs/heads/main' && secrets.KACHE_RW_ACCESS_KEY_ID || secrets.KACHE_RO_ACCESS_KEY_ID }} + s3-secret-access-key: ${{ github.ref == 'refs/heads/main' && secrets.KACHE_RW_SECRET_ACCESS_KEY || secrets.KACHE_RO_SECRET_ACCESS_KEY }} - run: rustup show active-toolchain || rustup toolchain install - run: cargo fmt --all --check - run: cargo clippy --locked --workspace --all-targets -- -D warnings @@ -36,13 +51,14 @@ jobs: # The Laravel Rust app (app/, sc-8900): its own workspace until it replaces server/ at cutover. Not deployed yet. app: runs-on: ${{ fromJSON(vars.CI_RUNNER || '"ubuntu-latest"') }} + environment: ${{ github.ref == 'refs/heads/main' && 'kache-write' || '' }} timeout-minutes: 40 services: postgres: image: postgres:17 env: - POSTGRES_USER: loco - POSTGRES_PASSWORD: loco + POSTGRES_USER: visualci + POSTGRES_PASSWORD: visualci POSTGRES_DB: visualci_app_test ports: ["55433:5432"] options: --health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10 @@ -56,9 +72,21 @@ jobs: docker run -d --name s3 -p 59000:9000 \ -e RUSTFS_ACCESS_KEY=visualci -e RUSTFS_SECRET_KEY=visualci-dev-secret rustfs/rustfs:1.0.6 for _ in $(seq 1 30); do curl -s -o /dev/null http://127.0.0.1:59000/ && break; sleep 1; done - - uses: Swatinem/rust-cache@v2 + # Compile cache (kache, as Cargo's rustc wrapper): the R2 bucket every machine shares (KACHE_BUCKET), else the + # GitHub Actions cache. Only main writes it: the read-write key is a secret of the kache-write environment, + # which only main may use, so a pull request (whatever its ci.yml says) gets the read-only key. + - uses: kunobi-ninja/kache-action@061011817fd04b0e460f79d6bb3c115b1fc8f029 # v1 with: - workspaces: app + version: "2.4.0" + cache-key-prefix: kache-${{ github.job }} + save-cache: ${{ github.ref == 'refs/heads/main' }} + pr-comment: false + s3-bucket: ${{ vars.KACHE_BUCKET }} + s3-endpoint: ${{ vars.KACHE_ENDPOINT }} + s3-region: auto + s3-prefix: visualci + s3-access-key-id: ${{ github.ref == 'refs/heads/main' && secrets.KACHE_RW_ACCESS_KEY_ID || secrets.KACHE_RO_ACCESS_KEY_ID }} + s3-secret-access-key: ${{ github.ref == 'refs/heads/main' && secrets.KACHE_RW_SECRET_ACCESS_KEY || secrets.KACHE_RO_SECRET_ACCESS_KEY }} - run: rustup show active-toolchain || rustup toolchain install - run: cargo fmt --check - run: cargo clippy --locked --all-targets -- -D warnings @@ -87,6 +115,7 @@ jobs: test: runs-on: ${{ fromJSON(vars.CI_RUNNER || '"ubuntu-latest"') }} + environment: ${{ github.ref == 'refs/heads/main' && 'kache-write' || '' }} timeout-minutes: 40 services: postgres: @@ -99,7 +128,21 @@ jobs: options: --health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10 steps: - uses: actions/checkout@v4 - - uses: Swatinem/rust-cache@v2 + # Compile cache (kache, as Cargo's rustc wrapper): the R2 bucket every machine shares (KACHE_BUCKET), else the + # GitHub Actions cache. Only main writes it: the read-write key is a secret of the kache-write environment, + # which only main may use, so a pull request (whatever its ci.yml says) gets the read-only key. + - uses: kunobi-ninja/kache-action@061011817fd04b0e460f79d6bb3c115b1fc8f029 # v1 + with: + version: "2.4.0" + cache-key-prefix: kache-${{ github.job }} + save-cache: ${{ github.ref == 'refs/heads/main' }} + pr-comment: false + s3-bucket: ${{ vars.KACHE_BUCKET }} + s3-endpoint: ${{ vars.KACHE_ENDPOINT }} + s3-region: auto + s3-prefix: visualci + s3-access-key-id: ${{ github.ref == 'refs/heads/main' && secrets.KACHE_RW_ACCESS_KEY_ID || secrets.KACHE_RO_ACCESS_KEY_ID }} + s3-secret-access-key: ${{ github.ref == 'refs/heads/main' && secrets.KACHE_RW_SECRET_ACCESS_KEY || secrets.KACHE_RO_SECRET_ACCESS_KEY }} # The request tests also write the MCP tools' and REST API's answers as JSON snapshots, for the visual job. - run: cargo test --locked --workspace env: @@ -120,6 +163,7 @@ jobs: visual: needs: [test] runs-on: ${{ fromJSON(vars.CI_RUNNER || '"ubuntu-latest"') }} + environment: ${{ github.ref == 'refs/heads/main' && 'kache-write' || '' }} timeout-minutes: 30 services: postgres: @@ -141,7 +185,21 @@ jobs: docker run -d --name s3 -p 59000:9000 \ -e RUSTFS_ACCESS_KEY=visualci -e RUSTFS_SECRET_KEY=visualci-dev-secret rustfs/rustfs:1.0.6 for _ in $(seq 1 30); do curl -s -o /dev/null http://127.0.0.1:59000/ && break; sleep 1; done - - uses: Swatinem/rust-cache@v2 + # Compile cache (kache, as Cargo's rustc wrapper): the R2 bucket every machine shares (KACHE_BUCKET), else the + # GitHub Actions cache. Only main writes it: the read-write key is a secret of the kache-write environment, + # which only main may use, so a pull request (whatever its ci.yml says) gets the read-only key. + - uses: kunobi-ninja/kache-action@061011817fd04b0e460f79d6bb3c115b1fc8f029 # v1 + with: + version: "2.4.0" + cache-key-prefix: kache-${{ github.job }} + save-cache: ${{ github.ref == 'refs/heads/main' }} + pr-comment: false + s3-bucket: ${{ vars.KACHE_BUCKET }} + s3-endpoint: ${{ vars.KACHE_ENDPOINT }} + s3-region: auto + s3-prefix: visualci + s3-access-key-id: ${{ github.ref == 'refs/heads/main' && secrets.KACHE_RW_ACCESS_KEY_ID || secrets.KACHE_RO_ACCESS_KEY_ID }} + s3-secret-access-key: ${{ github.ref == 'refs/heads/main' && secrets.KACHE_RW_SECRET_ACCESS_KEY || secrets.KACHE_RO_SECRET_ACCESS_KEY }} - run: cargo build --locked -p visualci_server -p visualci-cli - uses: pnpm/action-setup@v4 with: @@ -182,6 +240,7 @@ jobs: clients: runs-on: ${{ fromJSON(vars.CI_RUNNER || '"ubuntu-latest"') }} + environment: ${{ github.ref == 'refs/heads/main' && 'kache-write' || '' }} timeout-minutes: 15 steps: - uses: actions/checkout@v4 @@ -198,9 +257,21 @@ jobs: node-version: "24" # The Compare two PDFs page runs crates/visualci-wasm in the browser (scripts/wasm.mjs builds it). - run: rustup target add wasm32-unknown-unknown - - uses: Swatinem/rust-cache@v2 + # Compile cache (kache, as Cargo's rustc wrapper): the R2 bucket every machine shares (KACHE_BUCKET), else the + # GitHub Actions cache. Only main writes it: the read-write key is a secret of the kache-write environment, + # which only main may use, so a pull request (whatever its ci.yml says) gets the read-only key. + - uses: kunobi-ninja/kache-action@061011817fd04b0e460f79d6bb3c115b1fc8f029 # v1 with: - key: wasm + version: "2.4.0" + cache-key-prefix: kache-${{ github.job }} + save-cache: ${{ github.ref == 'refs/heads/main' }} + pr-comment: false + s3-bucket: ${{ vars.KACHE_BUCKET }} + s3-endpoint: ${{ vars.KACHE_ENDPOINT }} + s3-region: auto + s3-prefix: visualci + s3-access-key-id: ${{ github.ref == 'refs/heads/main' && secrets.KACHE_RW_ACCESS_KEY_ID || secrets.KACHE_RO_ACCESS_KEY_ID }} + s3-secret-access-key: ${{ github.ref == 'refs/heads/main' && secrets.KACHE_RW_SECRET_ACCESS_KEY || secrets.KACHE_RO_SECRET_ACCESS_KEY }} # The production site: with the Plausible snippets (analytics.ts) and, required, the WebAssembly. - run: pnpm install --frozen-lockfile && VISUALCI_ANALYTICS=1 VISUALCI_REQUIRE_WASM=1 pnpm build working-directory: server/frontend diff --git a/AGENTS.md b/AGENTS.md index 763d4ba3..0af66aa3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,6 +14,19 @@ design is in `docs/design.md`; read it before changing the architecture, and upd 3. Merge with `gh pr merge --squash --delete-branch` once every check is green. If GitHub refuses because VisualCI is pending, that's the review you skipped. Never bypass the ruleset. (1 Dec 2026, unreviewed builds let a CSS break from three merges reach production.) +- **Hold the merge lock from the final rebase to the merge.** A PR must be up to date with `main` before it merges, + so a merge by one agent sends every other agent's PR back through CI. Take Fleetlayer's lock, one per repository, + around the last rebase, the CI run and the merge, in one script, and only for one PR at a time: + + ```sh + id=$(fleetlayer lease acquire main-merge --payload '{"repo":"DocSpring/visualci"}' --reason "merge PR #N" \ + --pid $$ --wait --json | jq -r .id | tail -1) + trap 'fleetlayer lease release "$id"' EXIT + # rebase onto origin/main, push, wait for the checks (with a timeout), gh pr merge N --squash --delete-branch + ``` + + `--pid $$` ties the lock to the script, so it outlives an idle session and is freed when the script ends. (3 Dec + 2026: two agents' merges kept making each other's green PRs out of date.) - No backwards compatibility before launch. There are no old setups to keep working: rename, change formats and drop old behaviour outright, with no redirects, aliases, fallbacks or shims for the old way (Nathan, 1 Dec 2026). - `skills/` is generated from the docs pages with `skill:` front matter. After editing such a page, run diff --git a/app/Cargo.lock b/app/Cargo.lock index c79c4f17..1a92f968 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -286,6 +286,12 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bcrypt" version = "0.19.3" @@ -455,6 +461,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -615,6 +623,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.3" @@ -797,6 +811,51 @@ dependencies = [ "cmov", ] +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.10", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.9" @@ -816,7 +875,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid 0.9.6", "crypto-common 0.1.6", + "subtle", ] [[package]] @@ -826,7 +887,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid", + "const-oid 0.10.3", "crypto-common 0.2.2", "ctutils", ] @@ -979,6 +1040,16 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.16" @@ -1039,6 +1110,21 @@ dependencies = [ "windows-sys 0.101.0", ] +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.34" @@ -1112,6 +1198,7 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ + "futures-channel", "futures-core", "futures-io", "futures-macro", @@ -1243,7 +1330,16 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" dependencies = [ - "hmac", + "hmac 0.13.0", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", ] [[package]] @@ -1528,6 +1624,12 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -1575,6 +1677,25 @@ dependencies = [ "quick-error", ] +[[package]] +name = "include_dir" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd" +dependencies = [ + "include_dir_macros", +] + +[[package]] +name = "include_dir_macros" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75" +dependencies = [ + "proc-macro2", + "quote", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -1875,6 +1996,16 @@ dependencies = [ "syn 2.0.119", ] +[[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.107" @@ -1886,6 +2017,21 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64 0.22.1", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + [[package]] name = "laravel-rust" version = "0.1.4" @@ -1905,7 +2051,7 @@ dependencies = [ "futures-util", "getrandom 0.4.3", "hex", - "hmac", + "hmac 0.13.0", "http", "http-body", "http-body-util", @@ -2053,7 +2199,7 @@ dependencies = [ "futures-util", "getrandom 0.4.3", "hex", - "hmac", + "hmac 0.13.0", "http", "http-body", "idna", @@ -2137,7 +2283,7 @@ dependencies = [ "anyhow", "futures-util", "hex", - "hmac", + "hmac 0.13.0", "inertia-laravel-rust", "inventory", "laravel-rust-core", @@ -2190,7 +2336,7 @@ dependencies = [ "futures-util", "getrandom 0.4.3", "hex", - "hmac", + "hmac 0.13.0", "http", "http-body", "http-body-util", @@ -2293,7 +2439,7 @@ dependencies = [ "base64 0.23.1", "bytes", "futures-util", - "hmac", + "hmac 0.13.0", "inventory", "laravel-rust-core", "laravel-rust-http", @@ -2479,6 +2625,9 @@ name = "lazy_static" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] [[package]] name = "libc" @@ -2761,6 +2910,22 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -2776,6 +2941,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2783,6 +2958,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -2930,6 +3106,31 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -2942,6 +3143,27 @@ version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -3121,13 +3343,23 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + [[package]] name = "rand" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ - "rand_chacha", + "rand_chacha 0.9.0", "rand_core 0.9.5", ] @@ -3142,6 +3374,16 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + [[package]] name = "rand_chacha" version = "0.9.0" @@ -3152,6 +3394,15 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + [[package]] name = "rand_core" version = "0.9.5" @@ -3332,6 +3583,77 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rmcp" +version = "3.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc4fa9a7558c480e1817c0f02e9a73782001ac1f47fb9d26cc073915963282ea" +dependencies = [ + "async-trait", + "base64 0.23.1", + "bytes", + "chrono", + "futures", + "http", + "http-body", + "http-body-util", + "indexmap", + "jiff 1.1.0", + "libc", + "pastey", + "percent-encoding", + "pin-project-lite", + "rand 0.10.4", + "rmcp-macros", + "schemars", + "serde", + "serde_json", + "sha2 0.11.3", + "sse-stream", + "thiserror", + "tokio", + "tokio-stream", + "tokio-util", + "tower-service", + "tracing", + "unicode-general-category", + "unicode-normalization", + "uuid", +] + +[[package]] +name = "rmcp-macros" +version = "3.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43c1bf063ba32333267a8bc282ec33ae0edf56bf74890118cb0c7bf910a7a1c0" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "serde_json", + "syn 3.0.10", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rustc-demangle" version = "0.1.28" @@ -3463,7 +3785,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c091b4ca9c4d51c1a959fa746cc74f5a612a2242070a4ae7b14e22b04c71f8c" dependencies = [ "base64 0.23.1", - "hmac", + "hmac 0.13.0", "instant-xml", "jiff 1.1.0", "md-5", @@ -3505,6 +3827,7 @@ version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" dependencies = [ + "chrono", "dyn-clone", "ref-cast", "schemars_derive", @@ -3706,6 +4029,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -3734,6 +4067,18 @@ version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint 0.4.8", + "num-traits", + "thiserror", + "time", +] + [[package]] name = "slab" version = "0.4.12" @@ -3785,6 +4130,16 @@ dependencies = [ "lock_api", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "sqlx" version = "0.9.1" @@ -3923,7 +4278,7 @@ dependencies = [ "futures-util", "hex", "hkdf", - "hmac", + "hmac 0.13.0", "itoa", "log", "md-5", @@ -3969,6 +4324,19 @@ dependencies = [ "uuid", ] +[[package]] +name = "sse-stream" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4" +dependencies = [ + "bytes", + "futures-util", + "http-body", + "http-body-util", + "pin-project-lite", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -4046,6 +4414,16 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -4213,6 +4591,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "libc", "pin-project-lite", "tokio", ] @@ -4411,6 +4790,12 @@ version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -4534,21 +4919,32 @@ name = "visualci-app" version = "0.0.0" dependencies = [ "axum", + "base64 0.22.1", "globset", "hex", + "hmac 0.12.1", "image", + "include_dir", + "ipnet", + "jsonwebtoken", "laravel-rust", "oauth-provider", "oauth-provider-laravel", "regex", "reqwest 0.12.28", + "rmcp", + "rsa", "rusty-s3", + "schemars", "serde", "serde_json", "sha2 0.10.9", "snapshot-diff", + "sqlx", "tokio", + "tower", "tracing", + "url", "visualci-core", ] @@ -4566,7 +4962,9 @@ dependencies = [ "sha2 0.10.9", "similar", "snapshot-diff", + "tar", "thiserror", + "zstd", ] [[package]] @@ -5073,6 +5471,34 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zstd" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b04655dc7bf4abd8ebe23dac6bef20fceea52a29ad19e37a4101b3951d7e8b45" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df2575690b2a3eccad509fe7898cdde32a5afca06a06449ff4dcfb318c7b7281" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.2.0+zstd.1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160" +dependencies = [ + "cc", + "pkg-config", +] + [[package]] name = "zune-core" version = "0.5.4" diff --git a/app/Cargo.toml b/app/Cargo.toml index 4c410008..c4173843 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -26,27 +26,46 @@ path = "src/main.rs" laravel-rust = { version = "=0.1.4", features = ["database-postgres", "minijinja"] } # The same axum Laravel Rust runs on, for extractors (auth::Principal) axum = "0.8" +base64 = "0.22" hex = "0.4" oauth-provider = "0.1.3" oauth-provider-laravel = { version = "=0.1.1", features = ["postgres"] } +hmac = "0.12" +jsonwebtoken = "9" serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" -tokio = { version = "1", features = ["macros", "rt-multi-thread"] } +tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] } reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } rusty-s3 = "0.12" globset = "0.4" +ipnet = "2" +schemars = "1" +sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "tls-rustls-ring", "postgres"] } tracing = "0.1" +include_dir = "0.7" +rmcp = { version = "3.12", features = ["server", "transport-streamable-http-server", "macros"] } +tower = { version = "0.5", features = ["util"] } +url = "2" +regex = "1" # VisualCI's own crates, shared with the CLI. -visualci-core = { path = "../crates/visualci-core" } +visualci-core = { path = "../crates/visualci-core", features = ["bundle"] } snapshot-diff = { path = "../crates/snapshot-diff" } [dev-dependencies] regex = "1" +# A GitHub App key made at test time, so no private key is committed +rsa = { version = "0.9", features = ["pem"] } [profile.dev] debug = "line-tables-only" [profile.dev.package."*"] debug = false + +# Generating the tests' RSA key is slow unoptimised +[profile.dev.package.num-bigint-dig] +opt-level = 3 +[profile.dev.package.rsa] +opt-level = 3 diff --git a/app/database/migrations/2026_12_03_000200_create_domain_tables.rs b/app/database/migrations/2026_12_03_000200_create_domain_tables.rs index b08c5975..3e176dcf 100644 --- a/app/database/migrations/2026_12_03_000200_create_domain_tables.rs +++ b/app/database/migrations/2026_12_03_000200_create_domain_tables.rs @@ -209,6 +209,10 @@ CREATE TABLE credit_transactions ( updated_at timestamp with time zone DEFAULT now() NOT NULL, project_id bigint, open_source_credits bigint DEFAULT 0 NOT NULL, + -- The build a charge is for (one row per build charge step); NULL for purchases, grants and gallery days. + build_id bigint, + -- A gallery day's roll-up: one row per (organization, project, day), its amount grown as images are served. + day date, CONSTRAINT credit_transactions_kind_check CHECK ((kind = ANY (ARRAY['purchase'::text, 'grant'::text, 'build'::text, 'render'::text, 'diff'::text, 'summary'::text, 'refund'::text, 'adjustment'::text, 'gallery'::text]))) ); @@ -747,6 +751,8 @@ CREATE INDEX credit_transactions_org_created ON credit_transactions USING btree CREATE INDEX credit_transactions_project ON credit_transactions USING btree (project_id, created_at); CREATE UNIQUE INDEX credit_transactions_purchase_once ON credit_transactions USING btree (organization_id, reference) WHERE (kind = 'purchase'::text); +CREATE UNIQUE INDEX credit_transactions_gallery_day ON credit_transactions USING btree (organization_id, project_id, day) WHERE (kind = 'gallery'::text); +CREATE INDEX credit_transactions_build_idx ON credit_transactions USING btree (build_id) WHERE build_id IS NOT NULL; CREATE INDEX feedback_account_created ON feedback USING btree (account, created_at); @@ -915,6 +921,11 @@ CREATE INDEX build_groups_source_idx ON build_groups USING btree (source_build_i CREATE INDEX snapshots_build_group_idx ON snapshots USING btree (build_id, group_key); -- Hot paths and foreign keys (every delete of a parent row checks these columns). +CREATE INDEX baselines_review_idx ON baselines USING btree (review_id) WHERE review_id IS NOT NULL; +CREATE INDEX baselines_approved_by_idx ON baselines USING btree (approved_by) WHERE approved_by IS NOT NULL; +CREATE INDEX builds_created_by_idx ON builds USING btree (created_by_user_id) WHERE created_by_user_id IS NOT NULL; +CREATE INDEX comments_user_idx ON comments USING btree (user_id) WHERE user_id IS NOT NULL; +CREATE INDEX comment_threads_resolved_by_idx ON comment_threads USING btree (resolved_by) WHERE resolved_by IS NOT NULL; CREATE INDEX snapshots_render_idx ON snapshots USING btree (render_id) WHERE render_id IS NOT NULL; CREATE INDEX snapshots_source_blob_idx ON snapshots USING btree (source_blob) WHERE source_blob IS NOT NULL; @@ -1055,6 +1066,9 @@ CREATE TABLE downloads ( CREATE INDEX downloads_build_filter ON downloads USING btree (build_id, filter_key, created_at DESC); CREATE INDEX downloads_created_brin ON downloads USING brin (created_at); +ALTER TABLE ONLY credit_transactions + ADD CONSTRAINT credit_transactions_build_id_fkey FOREIGN KEY (build_id) REFERENCES builds(id) ON DELETE SET NULL; + -- Project tokens (the auth migration) belong to a project. ALTER TABLE ONLY project_tokens ADD CONSTRAINT project_tokens_project_id_fkey FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE; diff --git a/app/database/migrations/2026_12_03_000300_create_emails_table.rs b/app/database/migrations/2026_12_03_000300_create_emails_table.rs new file mode 100644 index 00000000..240e0138 --- /dev/null +++ b/app/database/migrations/2026_12_03_000300_create_emails_table.rs @@ -0,0 +1,37 @@ +use laravel::db::AnyTransaction; + +/// The emails outbox (ported as today's), and each person's email choices and sign-up notice. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "CREATE TABLE emails ( + id BIGSERIAL PRIMARY KEY, + kind TEXT NOT NULL, + dedupe_key TEXT NOT NULL UNIQUE, + organization_id BIGINT REFERENCES organizations(id) ON DELETE CASCADE, + user_id BIGINT REFERENCES users(id) ON DELETE CASCADE, + recipient TEXT NOT NULL, + data JSONB NOT NULL, + subject TEXT, + text_body TEXT, + html_body TEXT, + state TEXT NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'sent', 'failed')), + attempts INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + claimed_at TIMESTAMPTZ, + sent_at TIMESTAMPTZ, + dismissed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() + ); + CREATE INDEX emails_pending ON emails (created_at) WHERE state = 'pending'; + CREATE INDEX emails_organization ON emails (organization_id, created_at); + CREATE INDEX emails_failed ON emails (id) WHERE state = 'failed' AND dismissed_at IS NULL; + ALTER TABLE users + ADD COLUMN email_low_credits BOOLEAN NOT NULL DEFAULT true, + ADD COLUMN email_receipts BOOLEAN NOT NULL DEFAULT true, + ADD COLUMN signup_notified_at TIMESTAMPTZ;", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/database/migrations/2026_12_03_000300_render_uploads_blob_deleting_gallery_urls.rs b/app/database/migrations/2026_12_03_000300_render_uploads_blob_deleting_gallery_urls.rs new file mode 100644 index 00000000..27e7ee3a --- /dev/null +++ b/app/database/migrations/2026_12_03_000300_render_uploads_blob_deleting_gallery_urls.rs @@ -0,0 +1,41 @@ +//! Columns the renderer API, retention and the gallery need (#81's review): +//! +//! - `blobs.deleting`: retention marks a blob before deleting its object, and deletes the row only while it's still +//! marked. Registering the hash again clears the mark (and has the file uploaded again), so a build reusing a file +//! while a prune runs keeps it. +//! - `renders.uploads`: the PNGs a render uploaded through its own uploads, by hash: `"blob"` for one it uploaded to +//! the blob itself, `"proof"` for one already stored, which it uploaded to a proof key instead. Completing the render +//! may name only these as page images, so a renderer can't name another tenant's PNG by its hash. +//! - `renders.used_at`: when a snapshot last reused the render. Retention leaves a recently reused render's images and +//! texts alone, since the build reusing it isn't in the prune's keep sets. +//! - `projects.gallery_urls`: the gallery URLs last purged as published, so a screenshot that drops out of the gallery +//! is purged too. +//! - `gallery_purge_failures`: purges that used up their retries, counted in `/status`. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query(SCHEMA).unprepared().await?; + Ok(()) +} + +const SCHEMA: &str = r" +ALTER TABLE blobs ADD COLUMN deleting boolean DEFAULT false NOT NULL; +CREATE INDEX blobs_deleting ON blobs USING btree (sha256) WHERE deleting; + +ALTER TABLE renders ADD COLUMN uploads jsonb DEFAULT '{}'::jsonb NOT NULL; +ALTER TABLE renders ADD COLUMN used_at timestamp with time zone; +CREATE INDEX renders_used_at ON renders USING btree (used_at) WHERE used_at IS NOT NULL; + +ALTER TABLE projects ADD COLUMN gallery_urls jsonb DEFAULT '[]'::jsonb NOT NULL; + +CREATE TABLE gallery_purge_failures ( + id bigserial PRIMARY KEY, + project_id bigint REFERENCES projects(id) ON DELETE CASCADE, + build_id bigint REFERENCES builds(id) ON DELETE SET NULL, + urls jsonb NOT NULL, + error text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); +CREATE INDEX gallery_purge_failures_created ON gallery_purge_failures USING btree (created_at); +"; diff --git a/app/database/migrations/2026_12_03_000400_create_invitations_table.rs b/app/database/migrations/2026_12_03_000400_create_invitations_table.rs new file mode 100644 index 00000000..3ca537ef --- /dev/null +++ b/app/database/migrations/2026_12_03_000400_create_invitations_table.rs @@ -0,0 +1,33 @@ +use laravel::db::AnyTransaction; + +/// Invitations to an organization, by email or by a login on a forge (ported as today's). `for_user_id` is the +/// account it's for when one existed when it was sent, so it shows on their side; it waits for them to accept. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "CREATE TABLE invitations ( + id BIGSERIAL PRIMARY KEY, + pid UUID NOT NULL UNIQUE, + organization_id BIGINT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE, + email TEXT, + forge TEXT, + login TEXT, + role TEXT NOT NULL CHECK (role IN ('admin', 'member', 'read')), + invited_by BIGINT REFERENCES users(id) ON DELETE SET NULL, + accepted_by BIGINT REFERENCES users(id) ON DELETE SET NULL, + accepted_at TIMESTAMPTZ, + for_user_id BIGINT REFERENCES users(id) ON DELETE CASCADE, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK ((email IS NOT NULL) <> (login IS NOT NULL)), + CHECK ((login IS NULL) = (forge IS NULL)) + ); + CREATE UNIQUE INDEX invitations_pending_email ON invitations (organization_id, lower(email)) + WHERE accepted_at IS NULL AND email IS NOT NULL; + CREATE UNIQUE INDEX invitations_pending_login ON invitations (organization_id, forge, lower(login)) + WHERE accepted_at IS NULL AND login IS NOT NULL; + CREATE INDEX invitations_for_user ON invitations (for_user_id) WHERE accepted_at IS NULL;", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/database/migrations/2026_12_03_000400_diffs_used_at.rs b/app/database/migrations/2026_12_03_000400_diffs_used_at.rs new file mode 100644 index 00000000..be42b880 --- /dev/null +++ b/app/database/migrations/2026_12_03_000400_diffs_used_at.rs @@ -0,0 +1,14 @@ +//! `diffs.used_at`: when a comparison last reused the cached diff. Retention leaves the overlay of a diff reused in the +//! last day alone, since the build reusing it isn't in the prune's keep sets. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query(SCHEMA).unprepared().await?; + Ok(()) +} + +const SCHEMA: &str = r" +ALTER TABLE diffs ADD COLUMN used_at timestamp with time zone; +CREATE INDEX diffs_used_at ON diffs USING btree (used_at) WHERE used_at IS NOT NULL; +"; diff --git a/app/database/migrations/2026_12_03_000500_add_heard_about_to_users.rs b/app/database/migrations/2026_12_03_000500_add_heard_about_to_users.rs new file mode 100644 index 00000000..a46492d1 --- /dev/null +++ b/app/database/migrations/2026_12_03_000500_add_heard_about_to_users.rs @@ -0,0 +1,15 @@ +use laravel::db::AnyTransaction; + +/// "How did you hear about VisualCI?" (asked once after sign-up), ported as today's. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "ALTER TABLE users + ADD COLUMN heard_about_pending BOOLEAN NOT NULL DEFAULT false, + ADD COLUMN heard_about_source TEXT, + ADD COLUMN heard_about_detail TEXT; + CREATE INDEX users_signup_unnotified ON users (id) WHERE signup_notified_at IS NULL;", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/database/migrations/2026_12_03_000500_projects_comment_when_unchanged.rs b/app/database/migrations/2026_12_03_000500_projects_comment_when_unchanged.rs new file mode 100644 index 00000000..c12e663b --- /dev/null +++ b/app/database/migrations/2026_12_03_000500_projects_comment_when_unchanged.rs @@ -0,0 +1,11 @@ +//! `projects.comment_when_unchanged` (c2da705, #90): whether VisualCI comments on a pull request whose builds are all +//! unchanged. Off by default, for every project: such a pull request gets only the passing check. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query("ALTER TABLE projects ADD COLUMN comment_when_unchanged boolean DEFAULT false NOT NULL") + .unprepared() + .await?; + Ok(()) +} diff --git a/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs b/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs new file mode 100644 index 00000000..4bcab92a --- /dev/null +++ b/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs @@ -0,0 +1,30 @@ +use laravel::db::AnyTransaction; + +/// `visualci login`'s device-code sign-in (ported as today's): the device code is stored hashed; a code gives one +/// token, once. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "CREATE TABLE device_logins ( + id BIGSERIAL PRIMARY KEY, + device_code_hash TEXT NOT NULL UNIQUE, + user_code TEXT NOT NULL UNIQUE, + -- What's asking, shown on the approval page: \"visualci CLI on ada-laptop\". + client_name TEXT NOT NULL, + -- Who asked for it (behind the trusted proxies, the address they report), shown on the approval page and + -- counted for the per-address limit. + requester_ip TEXT, + last_polled_at TIMESTAMPTZ, + user_id BIGINT REFERENCES users(id) ON DELETE CASCADE, + approved_at TIMESTAMPTZ, + denied_at TIMESTAMPTZ, + -- When the CLI collected its token. + consumed_at TIMESTAMPTZ, + expires_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() + ); + CREATE INDEX device_logins_requester ON device_logins (requester_ip, created_at);", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/src/auth/device.rs b/app/src/auth/device.rs new file mode 100644 index 00000000..b914b479 --- /dev/null +++ b/app/src/auth/device.rs @@ -0,0 +1,317 @@ +//! `visualci login`'s device-code sign-in (in the style of RFC 8628; sc-8900, the auth side, ported from today's +//! server). The CLI asks for a code pair: a secret device code it polls with, and a short user code the person types +//! or follows on the app's /device page. Once they approve it, the next poll gets a new personal token, once, and the +//! person gets a security notice. Codes last ten minutes. +//! +//! A code pair can be asked for by anyone, so the approval page is built against phishing: it names the request as a +//! VisualCI command-line sign-in, with where and when it was asked for, and says to approve it only right after running +//! `visualci login`; the name the CLI sent is a detail below that. Each address may ask for a few codes in ten minutes, +//! and expired codes are deleted daily. + +use std::net::IpAddr; + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::http::{Next, Request, Response, middleware}; +use laravel::prelude::*; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; +use serde_json::{Value, json}; + +use crate::models::{User, token_hash}; +use crate::notify::outbox::AppUrl; +use crate::notify::{self, Kind, To}; + +/// The CLI's side, on the `api` group: no session, no CSRF. +pub fn api_routes(route: &mut Router) { + route.middleware(limit_codes).group(|route| { + route.post("/v1/device/code", code); + }); + route.post("/v1/device/token", token); +} + +/// The person's side, on the `web` group. +pub fn routes(route: &mut Router) { + route.get("/api/ui/device/{code}", show); + route.post("/api/ui/device/{code}", decide); +} + +/// How long a code pair can be approved and collected. +pub const LIFETIME_SECONDS: i64 = 600; +/// How often the CLI may ask. +pub const INTERVAL_SECONDS: i64 = 3; +/// Code pairs one address may ask for in ten minutes. +pub const CODES_PER_ADDRESS: i64 = 10; + +/// The address that asked for a code pair (behind the trusted proxies, the one they report). +#[derive(Clone, Copy, Debug)] +pub struct Requester(pub IpAddr); + +/// Route middleware for `/api/v1/device/code`: at most [`CODES_PER_ADDRESS`] code pairs per address in ten minutes +/// (429 after that), and the address passed on for the approval page. +#[middleware] +pub async fn limit_codes(request: Request, next: Next) -> Response { + let ip = request.ip(); + let address = ip.to_string(); + let recent: laravel::Result> = db::query!( + "SELECT count(*) FROM device_logins WHERE requester_ip = {address} AND created_at > now() - interval '10 minutes'" + ) + .scalar() + .await; + match recent { + Ok(Some(n)) if n >= CODES_PER_ADDRESS => { + return Response::new(Json( + json!({ "error": "too many sign-in codes from this address; try again in ten minutes" }), + )) + .with_status(429) + .with_header("retry-after", "600"); + } + Err(e) => tracing::warn!(error = %e, "device code limit"), + _ => {} + } + let mut http = request.into_http(); + http.extensions_mut().insert(Requester(ip)); + next.run(Request::from_http(http)).await +} + +/// Letters that can't be mistaken for each other or for digits. +const USER_CODE_ALPHABET: &[u8] = b"BCDFGHJKLMNPQRSTVWXZ"; + +/// A user code such as `KQHT-WMRP`. +fn new_user_code() -> String { + let mut letters = Vec::new(); + while letters.len() < 8 { + letters.extend(laravel::str::random(64).bytes().filter(|b| USER_CODE_ALPHABET.contains(b))); + } + let code: String = letters[..8].iter().map(|&b| char::from(b)).collect(); + format!("{}-{}", &code[..4], &code[4..]) +} + +/// A user code as people type it: upper case, with the dash where it belongs. +#[must_use] +pub fn normalize_user_code(code: &str) -> String { + let letters: String = code.chars().filter(char::is_ascii_alphabetic).map(|c| c.to_ascii_uppercase()).collect(); + if letters.len() == 8 { format!("{}-{}", &letters[..4], &letters[4..]) } else { letters } +} + +#[laravel::input] +#[validate(anyone)] +pub struct CodeInput { + /// What's asking, shown when the person approves: "visualci CLI on ada-laptop". + name: Option, +} + +/// `POST /api/v1/device/code`: a code pair. The person opens `verification_uri_complete` (or `verification_uri` and +/// types `user_code`) and approves; the CLI polls `/api/v1/device/token` with `device_code` every `interval` seconds. +pub async fn code( + app: laravel::config::Section, + requester: Option>, + Valid(p): Valid, +) -> laravel::Result> { + let requester = requester.map(|r| r.0.0.to_string()); + let client: String = p.name.unwrap_or_default().chars().filter(|c| !c.is_control()).take(100).collect(); + let client = if client.trim().is_empty() { "visualci CLI".to_string() } else { client }; + let lifetime = LIFETIME_SECONDS; + for _ in 0..5 { + let device = laravel::str::random(40); + let user = new_user_code(); + let hash = token_hash(&device); + let inserted: Option = db::query!( + "INSERT INTO device_logins (device_code_hash, user_code, client_name, requester_ip, expires_at) \ + VALUES ({hash}, {user}, {client}, {requester}, now() + make_interval(secs => {lifetime}::int)) \ + ON CONFLICT DO NOTHING RETURNING id" + ) + .scalar() + .await?; + if inserted.is_some() { + let uri = format!("{}/device", app.url.trim_end_matches('/')); + return Ok(Json(json!({ + "device_code": device, + "user_code": user, + "verification_uri": uri, + "verification_uri_complete": format!("{uri}?code={user}"), + "expires_in": LIFETIME_SECONDS, + "interval": INTERVAL_SECONDS, + }))); + } + } + Err(laravel::abort_with(503, "couldn't make a code; try again")) +} + +#[laravel::input] +#[validate(anyone)] +pub struct TokenInput { + #[validate(required, max_length(200))] + device_code: String, +} + +/// `POST /api/v1/device/token`, polled: `status` is `pending` (ask again), `slow_down` (asked again within the +/// interval: wait longer), `denied`, `expired`, or `approved` with a new personal token (`token`), given once. +pub async fn token(Valid(p): Valid) -> laravel::Result> { + let hash = token_hash(&p.device_code); + // A second's grace for clocks and networks, as RFC 8628 asks clients to keep the interval. + let pace = INTERVAL_SECONDS - 1; + let paced: Option = db::query!( + "UPDATE device_logins SET last_polled_at = now() WHERE device_code_hash = {hash} \ + AND (last_polled_at IS NULL OR last_polled_at <= now() - make_interval(secs => {pace}::int)) RETURNING id" + ) + .scalar() + .await?; + if paced.is_none() { + let known: Option = + db::query!("SELECT id FROM device_logins WHERE device_code_hash = {hash}").scalar().await?; + if known.is_some() { + return Ok(Json(json!({ "status": "slow_down" }))); + } + } + // Claim an approved, uncollected code and make its token in one transaction: two polls never both get a token, + // and a failure leaves the code to collect again. + let claimed = db::transaction(async |tx| { + let Some(row) = db::query!( + tx, + "UPDATE device_logins SET consumed_at = now() WHERE device_code_hash = {hash} AND approved_at IS NOT NULL \ + AND consumed_at IS NULL AND expires_at > now() RETURNING user_id, client_name" + ) + .select_one() + .await? + else { + return Ok(None); + }; + let user_id: i64 = row.try_get("user_id")?; + let client: String = row.try_get("client_name")?; + let (token, token_hash_, shown) = super::tokens::generate("vcu_"); + db::query!( + tx, + "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({user_id}, {client}, {token_hash_}, {shown}, now(), now())" + ) + .insert() + .await?; + Ok(Some((user_id, client, token))) + }) + .await?; + if let Some((user_id, client, token)) = claimed { + let at = laravel::now().timestamp().strftime("%-d %B %Y, %H:%M UTC").to_string(); + let kind = Kind::DeviceSignIn { client, at }; + let key = format!("device_sign_in:{user_id}:{}", laravel::now().timestamp().as_millisecond()); + notify::queue(&kind, To::User(user_id), None, &key).await?; + let name: Option = db::query!("SELECT name FROM users WHERE id = {user_id}").scalar().await?; + return Ok(Json(json!({ "status": "approved", "token": token, "user": name }))); + } + let row = db::query!( + "SELECT (denied_at IS NOT NULL) AS denied, (expires_at > now() AND consumed_at IS NULL) AS live \ + FROM device_logins WHERE device_code_hash = {hash}" + ) + .select_one() + .await?; + let status = match row { + Some(r) if r.try_get::("denied")? => "denied", + Some(r) if r.try_get::("live")? => "pending", + _ => "expired", + }; + Ok(Json(json!({ "status": status }))) +} + +/// What the approval page says, before anything the request itself sent. +pub const LABEL: &str = "VisualCI command-line sign-in"; +pub const WARNING: &str = "Only approve this if you just ran visualci login yourself. Approving gives whoever asked a \ + token that acts as you."; + +/// `GET /api/ui/device/{code}`: the sign-in a user code asks for, to approve or deny: a fixed label and warning, where +/// and when it was asked for, and the name the CLI sent as a detail (`client`), since anyone can choose that. 404 when +/// there's no such pending code. +pub async fn show( + Authenticated(_user): Authenticated, + Params(code): Params, +) -> laravel::Result> { + let code = normalize_user_code(&code); + let row = db::query!( + "SELECT client_name, requester_ip, \ + to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') AS requested_at \ + FROM device_logins WHERE user_code = {code} AND expires_at > now() \ + AND approved_at IS NULL AND denied_at IS NULL" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + Ok(Json(json!({ + "label": LABEL, + "warning": WARNING, + "requested_from": row.try_get::>("requester_ip")?, + "requested_at": row.try_get::("requested_at")?, + "client": row.try_get::("client_name")?, + }))) +} + +/// Delete codes that expired more than a day ago, daily; pushes `VISUALCI_DEVICE_PRUNE_HEARTBEAT`. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct PruneDeviceLogins; + +#[job] +impl PruneDeviceLogins { + async fn handle(self) -> laravel::Result<()> { + let pruned = prune().await; + let health = pruned.as_ref().map(|_| ()).map_err(ToString::to_string); + crate::heartbeat::push("VISUALCI_DEVICE_PRUNE_HEARTBEAT", health).await; + pruned.map(|_| ()) + } +} + +/// Delete codes that expired more than a day ago. Returns how many. +/// +/// # Errors +/// On a database error. +pub async fn prune() -> laravel::Result { + db::query!("DELETE FROM device_logins WHERE expires_at < now() - interval '1 day'").delete().await +} + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(PruneDeviceLogins).daily().without_overlapping(); +} + +#[laravel::input] +#[validate(authenticated)] +pub struct DecideInput { + approve: bool, +} + +/// `POST /api/ui/device/{code}`: approve or deny. Approving gives the waiting CLI a personal token for this person. +pub async fn decide( + Authenticated(user): Authenticated, + Params(code): Params, + Valid(p): Valid, +) -> laravel::Result> { + let (code, user_id) = (normalize_user_code(&code), user.id); + let decided: Option = if p.approve { + db::query!( + "UPDATE device_logins SET approved_at = now(), user_id = {user_id} WHERE user_code = {code} \ + AND expires_at > now() AND approved_at IS NULL AND denied_at IS NULL RETURNING id" + ) + .scalar() + .await? + } else { + db::query!( + "UPDATE device_logins SET denied_at = now(), user_id = {user_id} WHERE user_code = {code} \ + AND expires_at > now() AND approved_at IS NULL AND denied_at IS NULL RETURNING id" + ) + .scalar() + .await? + }; + decided.ok_or_else(|| laravel::abort(404))?; + Ok(Json(json!({ "ok": true }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn user_codes_read_as_typed() { + assert_eq!(normalize_user_code("kqht wmrp"), "KQHT-WMRP"); + assert_eq!(normalize_user_code("KQHT-WMRP"), "KQHT-WMRP"); + let code = new_user_code(); + assert_eq!(code.len(), 9); + assert!(code.chars().all(|c| c == '-' || USER_CODE_ALPHABET.contains(&(c as u8)))); + } +} diff --git a/app/src/auth/invitations.rs b/app/src/auth/invitations.rs new file mode 100644 index 00000000..3ca34dec --- /dev/null +++ b/app/src/auth/invitations.rs @@ -0,0 +1,561 @@ +//! Invitations and members (sc-8900, the auth side), ported from today's server. An admin invites someone by email +//! or GitHub login; the invitation waits for its invitee to accept or decline it in the app, whether or not they +//! already have an account, so nobody joins an organization, or shows among its members, without saying so. Admins +//! change members' roles or remove them, except where the forge decides the membership, and an organization always +//! keeps an admin. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::Role; +use super::memberships::MembershipChanged; +use crate::forge::ForgeKind; +use crate::models::User; +use crate::notify::{self, Kind, To}; + +pub fn routes(route: &mut Router) { + route.get("/api/ui/invitations", mine); + route.post("/api/ui/invitations/{id}/accept", accept); + route.post("/api/ui/invitations/{id}/decline", decline); + route.get("/api/ui/orgs/{org}/members", members); + route.post("/api/ui/orgs/{org}/invitations", invite); + route.delete("/api/ui/orgs/{org}/invitations/{id}", withdraw); + route.patch("/api/ui/orgs/{org}/members/{id}", update_member); + route.delete("/api/ui/orgs/{org}/members/{id}", remove_member); +} + +/// Invitation emails an organization may send in a day, and one address may receive from all organizations: inviting, +/// withdrawing and inviting again would otherwise send mail without end, from VisualCI's own domain. +pub const DAILY_PER_ORGANIZATION: i64 = 50; +pub const DAILY_PER_RECIPIENT: i64 = 3; + +/// Who an invitation is for: an email address, or a login on a forge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Invitee { + Email(String), + Login(ForgeKind, String), +} + +impl Invitee { + /// `someone@example.com`, `@octocat` or `octocat` (a GitHub login). + /// + /// # Errors + /// A message when it's neither. + pub fn parse(input: &str) -> Result { + let s = input.trim(); + if s.contains('@') && !s.starts_with('@') { + let (local, domain) = s.split_once('@').unwrap_or_default(); + if local.is_empty() || !domain.contains('.') || s.contains(char::is_whitespace) { + return Err(format!("{s:?} isn't an email address")); + } + return Ok(Self::Email(s.to_lowercase())); + } + let login = s.trim_start_matches('@'); + let valid = !login.is_empty() + && login.len() <= 39 + && login.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') + && !login.starts_with('-'); + if valid { + Ok(Self::Login(ForgeKind::Github, login.to_string())) + } else { + Err(format!("{s:?} isn't an email address or GitHub login")) + } + } + + /// The account it's for when one exists already: a verified email, or a login on github.com or gitlab.com (a + /// self-managed instance's logins are its own). + /// + /// # Errors + /// On a database error. + pub async fn account(&self) -> laravel::Result> { + match self { + Self::Email(e) => db::query!( + "SELECT id FROM users WHERE lower(email) = {e} AND email_verified_at IS NOT NULL ORDER BY id LIMIT 1" + ) + .scalar() + .await, + Self::Login(f, l) => { + let (forge, login) = (f.as_str(), l.to_lowercase()); + db::query!( + "SELECT user_id FROM identities WHERE forge = {forge} AND site = '' AND lower(login) = {login} \ + ORDER BY id LIMIT 1" + ) + .scalar() + .await + } + } + } +} + +/// Where an invitation's email goes: the account's address when it's for one, else the address it names (an +/// invitation by login to someone without an account gets no email). +async fn address(invitee: &Invitee, account: Option) -> laravel::Result> { + if let Some(id) = account { + return db::query!("SELECT email FROM users WHERE id = {id}").scalar().await; + } + Ok(match invitee { + Invitee::Email(e) => Some(e.clone()), + Invitee::Login(..) => None, + }) +} + +/// `Err(message)` when an invitation to `address` from organization `org_id` would go over a daily limit. +/// +/// # Errors +/// On a database error. +pub async fn may_send(org_id: i64, address: Option<&str>) -> laravel::Result> { + let sent_by_org: i64 = db::query!( + "SELECT count(*) FROM emails WHERE kind = 'invited' AND organization_id = {org_id} \ + AND created_at > now() - interval '24 hours'" + ) + .scalar() + .await? + .unwrap_or(0); + if sent_by_org >= DAILY_PER_ORGANIZATION { + return Ok(Err(format!( + "this organization has sent {DAILY_PER_ORGANIZATION} invitations in the last 24 hours, the limit; try \ + again tomorrow" + ))); + } + if let Some(address) = address { + let received: i64 = db::query!( + "SELECT count(*) FROM emails WHERE kind = 'invited' AND lower(recipient) = lower({address}) \ + AND created_at > now() - interval '24 hours'" + ) + .scalar() + .await? + .unwrap_or(0); + if received >= DAILY_PER_RECIPIENT { + return Ok(Err("that person has been invited too often in the last 24 hours; try again tomorrow".into())); + } + } + Ok(Ok(())) +} + +/// The organization by slug and the person's role there; a 404 when they aren't a member. Staff are no exception: +/// their tools are the admin MCP's, with its audit log, never the customer pages. +async fn org_role(user: &User, slug: &str) -> laravel::Result<(i64, String, Role)> { + let user_id = user.id; + let row = db::query!( + "SELECT o.id, o.name, m.role FROM organizations o \ + LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} WHERE o.slug = {slug}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let role = row.try_get::>("role")?.as_deref().and_then(Role::parse); + let role = match role { + Some(r) => r, + None => return Err(laravel::abort(404)), + }; + Ok((row.try_get("id")?, row.try_get("name")?, role)) +} + +/// The organization, when the person is an admin there: a member gets a 403, anyone else a 404. +async fn admin_org(user: &User, slug: &str, action: &str) -> laravel::Result<(i64, String)> { + let (id, name, role) = org_role(user, slug).await?; + if role < Role::Admin { + return Err(laravel::abort_with(403, format!("only admins can {action}"))); + } + Ok((id, name)) +} + +fn json_of(text: &str) -> laravel::Result { + serde_json::from_str(text).map_err(|e| laravel::Error::msg(e.to_string())) +} + +fn uuid(s: &str) -> laravel::Result { + laravel::str::Uuid::parse_str(s).map(|u| u.to_string()).map_err(|_| laravel::abort(404)) +} + +/// An organization's pending invitations, newest first. +/// +/// # Errors +/// On a database error. +pub async fn pending(org_id: i64) -> laravel::Result> { + let rows = db::query!( + "SELECT json_build_object('id', i.pid, \ + 'invitee', COALESCE(i.email, '@' || i.login || CASE i.forge WHEN 'github' THEN ' (GitHub)' \ + WHEN 'gitlab' THEN ' (GitLab)' ELSE '' END), \ + 'email', i.email, 'forge', i.forge, 'login', i.login, 'role', i.role, \ + 'created_at', to_char(i.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'))::text AS j \ + FROM invitations i WHERE i.organization_id = {org_id} AND i.accepted_at IS NULL ORDER BY i.id DESC" + ) + .select() + .await?; + rows.iter().map(|r| json_of(&r.try_get::("j")?)).collect() +} + +/// An organization's members, admins first then by name, with their forge logins; emails only for its admins. +/// +/// # Errors +/// On a database error. +pub async fn members_json(org_id: i64, with_emails: bool) -> laravel::Result> { + let rows = db::query!( + "SELECT json_build_object('id', u.pid, 'name', u.name, \ + 'email', CASE WHEN {with_emails} THEN u.email END, 'avatar_url', u.avatar_url, \ + 'login', (SELECT login FROM identities WHERE user_id = u.id ORDER BY id LIMIT 1), \ + 'identities', COALESCE((SELECT json_agg(json_build_object('forge', forge, 'login', login) ORDER BY id) \ + FROM identities WHERE user_id = u.id), '[]'::json), \ + 'role', m.role, 'source', m.source, \ + 'synced_at', to_char(m.synced_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'), \ + 'since', to_char(m.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'))::text AS j \ + FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.organization_id = {org_id} \ + ORDER BY CASE m.role WHEN 'admin' THEN 0 WHEN 'member' THEN 1 ELSE 2 END, u.name" + ) + .select() + .await?; + rows.iter().map(|r| json_of(&r.try_get::("j")?)).collect() +} + +/// `GET /api/ui/orgs/{org}/members`: its members, and its pending invitations for its admins. +pub async fn members( + Authenticated(user): Authenticated, + Params(org): Params, +) -> laravel::Result> { + let (org_id, _, role) = org_role(&user, &org).await?; + let admin = role == Role::Admin; + let invitations = if admin { pending(org_id).await? } else { Vec::new() }; + Ok(Json(json!({ "members": members_json(org_id, admin).await?, "invitations": invitations }))) +} + +/// The pending invitations for a person: recorded for them, or to their verified email, or to one of their logins on +/// github.com or gitlab.com. Newest first, each with its organization and who invited them. +/// +/// # Errors +/// On a database error. +pub async fn pending_for(user: &User) -> laravel::Result> { + let user_id = user.id; + let email = user.email_verified_at.is_some().then(|| user.email.to_lowercase()); + let rows = db::query!( + "SELECT json_build_object('id', i.pid, 'organization', json_build_object('slug', o.slug, 'name', o.name), \ + 'role', i.role, 'invited_by', inviter.name, \ + 'created_at', to_char(i.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'))::text AS j \ + FROM invitations i JOIN organizations o ON o.id = i.organization_id \ + LEFT JOIN users inviter ON inviter.id = i.invited_by \ + WHERE i.accepted_at IS NULL AND (i.for_user_id = {user_id} \ + OR (i.email IS NOT NULL AND lower(i.email) = {email}) \ + OR EXISTS (SELECT 1 FROM identities d WHERE d.user_id = {user_id} AND d.site = '' \ + AND d.forge = i.forge AND lower(d.login) = lower(i.login))) \ + ORDER BY i.id DESC" + ) + .select() + .await?; + rows.iter().map(|r| json_of(&r.try_get::("j")?)).collect() +} + +/// The pending invitation `pid` when it's for this person: its ID, organization and role. A 404 otherwise. +async fn theirs(user: &User, pid: &str) -> laravel::Result<(i64, i64, Role)> { + let pid = uuid(pid)?; + let user_id = user.id; + let email = user.email_verified_at.is_some().then(|| user.email.to_lowercase()); + let row = db::query!( + "SELECT i.id, i.organization_id, i.role FROM invitations i \ + WHERE i.pid = {pid}::uuid AND i.accepted_at IS NULL AND (i.for_user_id = {user_id} \ + OR (i.email IS NOT NULL AND lower(i.email) = {email}) \ + OR EXISTS (SELECT 1 FROM identities d WHERE d.user_id = {user_id} AND d.site = '' \ + AND d.forge = i.forge AND lower(d.login) = lower(i.login)))" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let role: String = row.try_get("role")?; + Ok((row.try_get("id")?, row.try_get("organization_id")?, Role::parse(&role).unwrap_or(Role::Read))) +} + +/// `GET /api/ui/invitations`: the signed-in person's pending invitations. +pub async fn mine(Authenticated(user): Authenticated) -> laravel::Result> { + Ok(Json(json!({ "invitations": pending_for(&user).await? }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct InviteInput { + /// An email address, or a GitHub login (`octocat` or `@octocat`). + #[validate(required, max_length(320))] + invitee: String, + #[validate(required)] + role: String, +} + +/// `POST /api/ui/orgs/{org}/invitations` (admins): invite someone, or change the role of their pending invitation. +/// It waits for them to accept, whether or not they have an account; they get an email either way when there's an +/// address to send it to. +pub async fn invite( + Authenticated(user): Authenticated, + Params(org): Params, + Valid(p): Valid, +) -> laravel::Result> { + let (org_id, _) = admin_org(&user, &org, "invite people").await?; + Ok(Json(invite_to(org_id, &user, &p.invitee, &p.role).await?)) +} + +/// Invite `invitee` (an email address or GitHub login) to organization `org_id` as `role`, sent by `by`, or change +/// the role of their pending invitation; returns the invitation as the members page and the MCP server show it. The +/// caller checks that `by` is an admin there. Errors: 422 for an invitee or role it can't read, 429 over a daily +/// limit (staff aren't limited). +/// +/// # Errors +/// Those, and database errors. +pub async fn invite_to(org_id: i64, by: &User, invitee: &str, role: &str) -> laravel::Result { + let user = by; + let role = Role::parse(role).ok_or_else(|| laravel::abort_with(422, "role is admin, member or read"))?; + let invitee = Invitee::parse(invitee).map_err(|e| laravel::abort_with(422, e))?; + let account = invitee.account().await?; + let to = address(&invitee, account).await?; + if !user.staff + && let Err(e) = may_send(org_id, to.as_deref()).await? + { + return Err(laravel::abort_with(429, e)); + } + let (email, forge, login) = match &invitee { + Invitee::Email(e) => (Some(e.clone()), None, None), + Invitee::Login(f, l) => (None, Some(f.as_str().to_string()), Some(l.clone())), + }; + let (role_name, inviter, pid) = (role.as_str(), user.id, laravel::str::uuid7().to_string()); + let lower_login = login.as_deref().map(str::to_lowercase); + let existing: Option = db::query!( + "SELECT id FROM invitations WHERE organization_id = {org_id} AND accepted_at IS NULL \ + AND ((email IS NOT NULL AND lower(email) = {email}) \ + OR (login IS NOT NULL AND forge = {forge} AND lower(login) = {lower_login}))" + ) + .scalar() + .await?; + let id: i64 = match existing { + Some(id) => { + db::query!( + "UPDATE invitations SET role = {role_name}, for_user_id = COALESCE({account}, for_user_id), \ + updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + id + } + None => db::query!( + "INSERT INTO invitations (pid, organization_id, email, forge, login, role, invited_by, for_user_id) \ + VALUES ({pid}::uuid, {org_id}, {email}, {forge}, {login}, {role_name}, {inviter}, {account}) RETURNING id" + ) + .scalar() + .await? + .ok_or_else(|| laravel::Error::msg("no invitation id"))?, + }; + if let Some(to) = to { + let kind = Kind::Invited { inviter: user.name.clone(), role: role_name.to_string() }; + notify::queue(&kind, To::Address(to), Some(org_id), &format!("invited:{id}")).await?; + } + let row = db::query!("SELECT json_build_object('id', i.pid, \ + 'invitee', COALESCE(i.email, '@' || i.login || CASE i.forge WHEN 'github' THEN ' (GitHub)' \ + WHEN 'gitlab' THEN ' (GitLab)' ELSE '' END), \ + 'email', i.email, 'forge', i.forge, 'login', i.login, 'role', i.role, \ + 'created_at', to_char(i.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"'))::text AS j FROM invitations i WHERE i.id = {id}") + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + json_of(&row.try_get::("j")?) +} + +/// `POST /api/ui/invitations/{id}/accept`: join with its role, or keep a higher one already held (an invitation +/// never lowers a role: otherwise an admin could demote the last admin, or take a forge-derived membership out of the +/// forge's hands by inviting downwards). +pub async fn accept( + Authenticated(user): Authenticated, + Params(id): Params, +) -> laravel::Result> { + let (invitation, org_id, role) = theirs(&user, &id).await?; + let (user_id, role_name) = (user.id, role.as_str()); + let joined = db::transaction(async |tx| { + // Still pending? Withdrawn meanwhile, or accepted by a double click: nothing to do. + let pending: Option = db::query!( + tx, + "SELECT id FROM invitations WHERE id = {invitation} AND accepted_at IS NULL FOR UPDATE" + ) + .scalar() + .await?; + if pending.is_none() { + return Ok(None); + } + let current: Option = db::query!( + tx, + "SELECT role FROM memberships WHERE organization_id = {org_id} AND user_id = {user_id} FOR UPDATE" + ) + .scalar() + .await?; + let joined = match current.as_deref().and_then(Role::parse) { + None => { + db::query!( + tx, + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org_id}, {user_id}, {role_name}, 'invite', now(), now())" + ) + .insert() + .await?; + true + } + Some(r) if r < role => { + db::query!( + tx, + "UPDATE memberships SET role = {role_name}, source = 'invite', synced_at = NULL, updated_at = now() \ + WHERE organization_id = {org_id} AND user_id = {user_id}" + ) + .update() + .await?; + true + } + Some(_) => false, + }; + db::query!( + tx, + "UPDATE invitations SET accepted_by = {user_id}, accepted_at = now(), updated_at = now() \ + WHERE id = {invitation}" + ) + .update() + .await?; + Ok(Some(joined)) + }) + .await?; + let Some(joined) = joined else { return Err(laravel::abort(404)) }; + // They're told, as today's grant does, once the membership is there. + if joined { + MembershipChanged::now(org_id, user_id, Some(role)).dispatch().await?; + } + let slug: Option = db::query!("SELECT slug FROM organizations WHERE id = {org_id}").scalar().await?; + Ok(Json(json!({ "slug": slug }))) +} + +/// `POST /api/ui/invitations/{id}/decline`: it's withdrawn, as if its admin had. +pub async fn decline( + Authenticated(user): Authenticated, + Params(id): Params, +) -> laravel::Result> { + let (invitation, _, _) = theirs(&user, &id).await?; + db::query!("DELETE FROM invitations WHERE id = {invitation}").delete().await?; + Ok(Json(json!({ "ok": true }))) +} + +/// `DELETE /api/ui/orgs/{org}/invitations/{id}` (admins): withdraw a pending invitation. +pub async fn withdraw( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, +) -> laravel::Result> { + let (org_id, _) = admin_org(&user, &org, "withdraw invitations").await?; + let pid = uuid(&id)?; + db::query!( + "DELETE FROM invitations WHERE pid = {pid}::uuid AND organization_id = {org_id} AND accepted_at IS NULL" + ) + .delete() + .await?; + Ok(Json(json!({ "ok": true }))) +} + +/// The membership of user `pid` in an organization the person administers: its organization and user IDs. A +/// membership the forge decides can't be changed here. +async fn managed(user: &User, org: &str, pid: &str) -> laravel::Result<(i64, i64)> { + let (org_id, _) = admin_org(user, org, "manage members").await?; + let pid = uuid(pid)?; + let row = db::query!( + "SELECT m.user_id, m.source FROM memberships m JOIN users u ON u.id = m.user_id \ + WHERE m.organization_id = {org_id} AND u.pid = {pid}::uuid" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let source: String = row.try_get("source")?; + if let Some(forge) = ForgeKind::parse(&source) { + return Err(laravel::abort_with( + 422, + format!("this access comes from {}: change their permission on the repository there", forge.label()), + )); + } + Ok((org_id, row.try_get("user_id")?)) +} + +/// Change (`Some(role)`) or remove (`None`) a membership, unless that would leave the organization without an admin. +/// The admin memberships are locked first, so two admins demoting or removing each other at once can't both succeed. +/// `false` when it would leave no admin. +async fn change_member(org_id: i64, member: i64, role: Option) -> laravel::Result { + db::transaction(async |tx| { + let admins = db::query!( + tx, + "SELECT user_id FROM memberships WHERE organization_id = {org_id} AND role = 'admin' FOR UPDATE" + ) + .select() + .await?; + let others = admins.iter().filter(|r| r.try_get::("user_id").is_ok_and(|id| id != member)).count(); + if role != Some(Role::Admin) && others == 0 { + return Ok(false); + } + match role { + Some(role) => { + let role_name = role.as_str(); + db::query!( + tx, + "UPDATE memberships SET role = {role_name}, updated_at = now() \ + WHERE organization_id = {org_id} AND user_id = {member}" + ) + .update() + .await?; + } + None => { + db::query!(tx, "DELETE FROM memberships WHERE organization_id = {org_id} AND user_id = {member}") + .delete() + .await?; + } + } + Ok(true) + }) + .await +} + +#[laravel::input] +#[validate(authenticated)] +pub struct MemberInput { + #[validate(required)] + role: String, +} + +/// `PATCH /api/ui/orgs/{org}/members/{id}` (admins): change a member's role. The organization keeps an admin. +pub async fn update_member( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, + Valid(p): Valid, +) -> laravel::Result> { + let role = Role::parse(&p.role).ok_or_else(|| laravel::abort_with(422, "role is admin, member or read"))?; + let (org_id, member) = managed(&user, &org, &id).await?; + if !change_member(org_id, member, Some(role)).await? { + return Err(laravel::abort_with(422, "the organization needs another admin first")); + } + Ok(Json(json!({ "members": members_json(org_id, true).await? }))) +} + +/// `DELETE /api/ui/orgs/{org}/members/{id}` (admins): remove a member, who's told unless they removed themselves. +/// The organization keeps an admin. +pub async fn remove_member( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, +) -> laravel::Result> { + let (org_id, member) = managed(&user, &org, &id).await?; + if !change_member(org_id, member, None).await? { + return Err(laravel::abort_with(422, "the organization needs another admin first")); + } + if member != user.id { + MembershipChanged::now(org_id, member, None).dispatch().await?; + } + Ok(Json(json!({ "members": members_json(org_id, true).await? }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_invitees() { + assert_eq!(Invitee::parse(" Ann@Example.com "), Ok(Invitee::Email("ann@example.com".into()))); + assert_eq!(Invitee::parse("@octo-cat"), Ok(Invitee::Login(ForgeKind::Github, "octo-cat".into()))); + assert_eq!(Invitee::parse("octocat"), Ok(Invitee::Login(ForgeKind::Github, "octocat".into()))); + for bad in ["", "@", "a@b", "two words", "-x", "a b@c.com"] { + assert!(Invitee::parse(bad).is_err(), "{bad}"); + } + } +} diff --git a/app/src/auth/me.rs b/app/src/auth/me.rs new file mode 100644 index 00000000..30dd4c56 --- /dev/null +++ b/app/src/auth/me.rs @@ -0,0 +1,459 @@ +//! The signed-in person's own page (sc-8900, the auth side), ported from today's server: `GET /api/ui/me` (who they +//! are, their organizations, their pending invitations, their email choices), turning low-credit and receipt emails +//! on or off, an organization's billing email, and "How did you hear about VisualCI?". Also the team's email about +//! each new sign-up, which waits for that answer. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; +use serde_json::{Value, json}; + +use super::Role; +use super::invitations::{self, Invitee}; +use crate::models::User; +use crate::notify::outbox::AppUrl; +use crate::notify::{self, Kind, To}; + +pub fn routes(route: &mut Router) { + route.get("/api/ui/me", me); + route.patch("/api/ui/me/notifications", update_notifications); + route.post("/api/ui/me/heard-about", heard_about); + route.put("/api/ui/orgs/{org}/billing-email", update_billing_email); +} + +/// An answer to "How did you hear about VisualCI?". The keys are stored, so a label can change but a key can't. +#[derive(Clone, Copy, Debug, serde::Serialize)] +pub struct Choice { + pub key: &'static str, + /// On the card. + pub label: &'static str, + /// On /staff and in the admin tools: "AI assistant: Claude". + pub short_label: &'static str, + /// The text box's label, for the answers that have one. + pub detail_label: Option<&'static str>, +} + +pub const DETAIL_MAX: usize = 255; + +pub const OPTIONS: &[Choice] = &[ + Choice { + key: "search", + label: "Search engine", + short_label: "Search", + detail_label: Some("What did you search for?"), + }, + Choice { + key: "ai_assistant", + label: "AI Assistant (ChatGPT, Claude, etc.)", + short_label: "AI assistant", + detail_label: Some("Which one?"), + }, + Choice { key: "colleague", label: "Colleague or friend", short_label: "Colleague or friend", detail_label: None }, + Choice { + key: "article", + label: "Blog post or article", + short_label: "Blog post or article", + detail_label: Some("Which one?"), + }, + Choice { + key: "social", + label: "Social media (X, LinkedIn, Reddit, etc.)", + short_label: "Social media", + detail_label: Some("Which one?"), + }, + Choice { + key: "directory", + label: "Directory (MCP, software, etc.)", + short_label: "Directory", + detail_label: Some("Which one?"), + }, + Choice { key: "github", label: "GitHub", short_label: "GitHub", detail_label: None }, + Choice { key: "other", label: "Other", short_label: "Other", detail_label: Some("Where did you hear about us?") }, +]; + +/// What's stored: a key we offer (else nothing) and its detail as one clean line of at most 255 characters. An answer +/// we don't offer is dropped, never refused. +#[must_use] +pub fn clean(source: Option<&str>, detail: Option<&str>) -> (Option, Option) { + let Some(option) = source.and_then(|s| OPTIONS.iter().find(|o| o.key == s)) else { return (None, None) }; + let detail = detail + .map(|d| d.chars().map(|c| if c.is_control() { ' ' } else { c }).collect::()) + .map(|d| d.split_whitespace().collect::>().join(" ")) + .map(|d| d.chars().take(DETAIL_MAX).collect::()) + .filter(|d| !d.is_empty() && option.detail_label.is_some()); + (Some(option.key.to_string()), detail) +} + +/// "AI assistant: Claude", or `None` when there's no answer. +#[must_use] +pub fn summary(source: Option<&str>, detail: Option<&str>) -> Option { + let source = source.filter(|s| !s.is_empty())?; + let label = OPTIONS.iter().find(|o| o.key == source).map_or(source, |o| o.short_label); + Some(match detail.filter(|d| !d.is_empty()) { + Some(d) => format!("{label}: {d}"), + None => label.to_string(), + }) +} + +/// `GET /api/ui/me`. +/// The forges a person can sign in with here: those whose OAuth application has its ID and secret. +#[derive(Clone, laravel::config::Section)] +pub struct SignInApps { + #[env("GITHUB_CLIENT_ID")] + pub github_id: Option, + #[env("GITHUB_CLIENT_SECRET")] + pub github_secret: Option, + #[env("GITLAB_CLIENT_ID")] + pub gitlab_id: Option, + #[env("GITLAB_CLIENT_SECRET")] + pub gitlab_secret: Option, +} + +impl SignInApps { + #[must_use] + pub fn forges(&self) -> Vec<&'static str> { + let set = |v: &Option| v.as_deref().is_some_and(|s| !s.trim().is_empty()); + let mut forges = Vec::new(); + if set(&self.github_id) && set(&self.github_secret) { + forges.push("github"); + } + if set(&self.gitlab_id) && set(&self.gitlab_secret) { + forges.push("gitlab"); + } + forges + } +} + +pub async fn me( + Authenticated(user): Authenticated, + apps: laravel::config::Section, +) -> laravel::Result> { + let user_id = user.id; + let row = db::query!( + "SELECT staff, heard_about_pending, email_low_credits, email_receipts, \ + COALESCE((SELECT json_agg(json_build_object('forge', forge, 'login', login) ORDER BY id) \ + FROM identities WHERE user_id = {user_id}), '[]'::json)::text AS identities, \ + COALESCE((SELECT json_agg(json_build_object('id', o.id, 'slug', o.slug, 'name', o.name, 'role', m.role) \ + ORDER BY o.name) FROM memberships m JOIN organizations o ON o.id = m.organization_id \ + WHERE m.user_id = {user_id}), '[]'::json)::text AS organizations \ + FROM users WHERE id = {user_id}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(401))?; + let identities: Value = serde_json::from_str(&row.try_get::("identities")?).unwrap_or_default(); + let mut organizations: Value = serde_json::from_str(&row.try_get::("organizations")?).unwrap_or_default(); + // Each organization's plan and credits this month, as the domain computes them (OrgsPage reads usage.plan.name) + if let Some(list) = organizations.as_array_mut() { + for org in list.iter_mut() { + let Some(id) = org.get("id").and_then(Value::as_i64) else { continue }; + let usage = match crate::models::Organization::find(id).await? { + Some(o) => crate::domain::credits::usage(&o).await?, + None => Value::Null, + }; + if let Some(o) = org.as_object_mut() { + o.remove("id"); + o.insert("usage".into(), usage); + } + } + } + Ok(Json(json!({ + "user": { + "name": user.name, "email": user.email, "avatar_url": user.avatar_url, + "login": identities.get(0).and_then(|i| i.get("login")).cloned(), "identities": identities, + }, + "forges": apps.forges(), + "organizations": organizations, + "invitations": invitations::pending_for(&user).await?, + "staff": row.try_get::("staff")?, + // Ask "How did you hear about VisualCI?" (once, after sign-up), with these choices. + "heard_about_pending": row.try_get::("heard_about_pending")?, + "heard_about_options": OPTIONS, + // Emails people can turn off; security emails, billing problems and running out of credits always go. + "notifications": { + "low_credits": row.try_get::("email_low_credits")?, + "receipts": row.try_get::("email_receipts")?, + }, + }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct NotificationsInput { + low_credits: Option, + receipts: Option, +} + +/// `PATCH /api/ui/me/notifications`: turn low-credit warnings or receipt-style emails on or off for yourself. +pub async fn update_notifications( + Authenticated(user): Authenticated, + Valid(p): Valid, +) -> laravel::Result> { + let (user_id, low_credits, receipts) = (user.id, p.low_credits, p.receipts); + let row = db::query!( + "UPDATE users SET email_low_credits = COALESCE({low_credits}, email_low_credits), \ + email_receipts = COALESCE({receipts}, email_receipts), updated_at = now() \ + WHERE id = {user_id} RETURNING email_low_credits, email_receipts" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(401))?; + Ok(Json(json!({ + "low_credits": row.try_get::("email_low_credits")?, + "receipts": row.try_get::("email_receipts")?, + }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct HeardAboutInput { + skip: Option, + source: Option, + detail: Option, +} + +/// `POST /api/ui/me/heard-about`: an answer, or Skip. Either way it isn't asked again, and the team's email about +/// the sign-up, which waits for it, goes out. +pub async fn heard_about( + Authenticated(user): Authenticated, + Valid(p): Valid, +) -> laravel::Result> { + let (source, detail) = if p.skip.unwrap_or(false) { + (None, None) + } else { + clean(p.source.as_ref().and_then(Value::as_str), p.detail.as_ref().and_then(Value::as_str)) + }; + let user_id = user.id; + db::query!( + "UPDATE users SET heard_about_pending = false, \ + heard_about_source = COALESCE({source}, heard_about_source), \ + heard_about_detail = CASE WHEN {source}::text IS NULL THEN heard_about_detail ELSE {detail} END, \ + updated_at = now() WHERE id = {user_id}" + ) + .update() + .await?; + NotifySignups.dispatch().await?; + Ok(Json(json!({ "ok": true }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct BillingEmailInput { + /// Empty sends billing emails to the admins again. + #[validate(max_length(320))] + billing_email: Option, +} + +/// `PUT /api/ui/orgs/{org}/billing-email` (admins): where billing emails go instead of the admins. +pub async fn update_billing_email( + Authenticated(user): Authenticated, + Params(org): Params, + Valid(p): Valid, +) -> laravel::Result> { + let user_id = user.id; + let row = db::query!( + "SELECT o.id, m.role FROM organizations o \ + LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} WHERE o.slug = {org}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let org_id: i64 = row.try_get("id")?; + match row.try_get::>("role")?.as_deref().and_then(Role::parse) { + Some(Role::Admin) => {} + Some(_) => return Err(laravel::abort_with(403, "only admins can change the billing email")), + None => return Err(laravel::abort(404)), + } + let email = p.billing_email.as_deref().unwrap_or("").trim(); + if !email.is_empty() && !matches!(Invitee::parse(email), Ok(Invitee::Email(_))) { + return Err(laravel::abort_with(422, format!("{email:?} isn't an email address"))); + } + let email = (!email.is_empty()).then(|| email.to_lowercase()); + db::query!("UPDATE organizations SET billing_email = {email}, updated_at = now() WHERE id = {org_id}") + .update() + .await?; + Ok(Json(json!({ "billing_email": email }))) +} + +/// The team's address for sign-up emails. +#[derive(Clone, laravel::config::Section)] +pub struct Team { + #[env("VISUALCI_TEAM_EMAIL", default = "support@visualci.com")] + pub email: String, +} + +/// How long after sign-up the team's email waits for "How did you hear". +pub const WAIT_MINUTES: i64 = 10; + +/// The team's email's text: who, how they signed up and heard about VisualCI, their organizations, and anything they +/// asked for. +#[must_use] +pub fn signup_text( + who: &str, + signup_via: Option<&str>, + heard: &str, + orgs: &[String], + requests: &[String], + app_url: &str, +) -> String { + let mut lines = vec![ + format!("New sign-up: {who}"), + format!("Signed up with: {}", signup_via.unwrap_or("unknown")), + format!("Heard about VisualCI from: {heard}"), + ]; + for org in orgs { + lines.push(format!("Organization: {app_url}/{org}")); + } + if requests.is_empty() { + lines.push("They haven't asked for anything yet.".to_string()); + } else { + lines.push(String::new()); + lines.push("What they need from VisualCI:".to_string()); + for r in requests { + lines.push(String::new()); + lines.push(r.clone()); + } + } + lines.push(String::new()); + lines.push(format!("All sign-ups: {app_url}/staff. Replying to this email reaches them.")); + lines.join("\n") +} + +/// Queue the team's email about every sign-up that's ready (answered or skipped, or past the wait), up to 20 a run. +/// The outbox sends it (with retries, and its own heartbeat); the dedupe key makes a second run's copy a no-op. +/// Returns how many were queued. +/// +/// # Errors +/// On a database error. +pub async fn queue_signups(team: &Team, app_url: &str) -> laravel::Result { + let wait = WAIT_MINUTES; + let ready = db::query!( + "SELECT id, name, email, signup_via, heard_about_pending, heard_about_source, heard_about_detail, \ + (SELECT login FROM identities WHERE user_id = users.id ORDER BY id LIMIT 1) AS login \ + FROM users WHERE signup_notified_at IS NULL \ + AND (NOT heard_about_pending OR created_at < now() - make_interval(mins => {wait}::int)) \ + ORDER BY id LIMIT 20" + ) + .select() + .await?; + let app_url = app_url.trim_end_matches('/'); + let mut queued = 0; + for u in ready { + let id: i64 = u.try_get("id")?; + let (name, email): (String, String) = (u.try_get("name")?, u.try_get("email")?); + let login: Option = u.try_get("login")?; + let source: Option = u.try_get("heard_about_source")?; + let detail: Option = u.try_get("heard_about_detail")?; + let heard = match summary(source.as_deref(), detail.as_deref()) { + Some(s) => s, + None if u.try_get::("heard_about_pending")? => "not answered yet".to_string(), + None => "skipped".to_string(), + }; + let orgs: Vec = db::query!( + "SELECT o.slug FROM memberships m JOIN organizations o ON o.id = m.organization_id \ + WHERE m.user_id = {id} ORDER BY o.id" + ) + .select() + .await? + .iter() + .map(|r| r.try_get("slug")) + .collect::>()?; + let requests: Vec = + db::query!("SELECT description FROM feedback WHERE user_id = {id} AND kind = 'request' ORDER BY id") + .select() + .await? + .iter() + .map(|r| r.try_get("description")) + .collect::>()?; + let who = match &login { + Some(l) => format!("{name} (@{l}) <{email}>"), + None => format!("{name} <{email}>"), + }; + let signup_via: Option = u.try_get("signup_via")?; + let text = signup_text(&who, signup_via.as_deref(), &heard, &orgs, &requests, app_url); + let subject = format!("New VisualCI sign-up: {}", login.as_deref().unwrap_or(&name)); + let kind = Kind::NewSignup { subject, text, reply_to: email }; + notify::queue(&kind, To::Address(team.email.clone()), None, &format!("new_signup:{id}")).await?; + db::query!("UPDATE users SET signup_notified_at = now() WHERE id = {id}").update().await?; + queued += 1; + } + Ok(queued) +} + +/// How long a ready sign-up may wait before the heartbeat fails: the schedule runs every minute. +pub const STALE_MINUTES: i64 = 30; + +/// Queue the team's sign-up emails; pushes `VISUALCI_SIGNUPS_HEARTBEAT`, failing when one ready sign-up has waited +/// more than half an hour (the job stopped running, or keeps failing). +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct NotifySignups; + +#[job] +impl NotifySignups { + async fn handle( + self, + team: laravel::config::Section, + app: laravel::config::Section, + ) -> laravel::Result<()> { + let result = queue_signups(&team, &app.url).await; + let stale = WAIT_MINUTES + STALE_MINUTES; + let waiting = db::query!( + "SELECT count(*) FROM users WHERE signup_notified_at IS NULL \ + AND created_at < now() - make_interval(mins => {stale}::int)" + ) + .scalar::() + .await; + // A database that can't answer fails the heartbeat too. + let health = match (&result, waiting) { + (Err(e), _) => Err(e.to_string()), + (Ok(_), Err(e)) => Err(e.to_string()), + (Ok(_), Ok(Some(n))) if n > 0 => { + Err(format!("{n} sign-ups waited over {stale} minutes for the team's email")) + } + _ => Ok(()), + }; + crate::heartbeat::push("VISUALCI_SIGNUPS_HEARTBEAT", health).await; + result.map(|_| ()) + } +} + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(NotifySignups).every_minute().without_overlapping(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn answers_are_cleaned_and_summarised() { + assert_eq!( + clean(Some("ai_assistant"), Some(" Claude\n ")), + (Some("ai_assistant".into()), Some("Claude".into())) + ); + assert_eq!(clean(Some("colleague"), Some("Bob")), (Some("colleague".into()), None)); + assert_eq!(clean(Some("made-up"), Some("x")), (None, None)); + assert_eq!(summary(Some("ai_assistant"), Some("Claude")).as_deref(), Some("AI assistant: Claude")); + assert_eq!(summary(None, None), None); + } + + #[test] + fn the_team_email_says_who_how_and_what_they_asked_for() { + let text = signup_text( + "Ada (@ada) ", + Some("github, from an MCP client's sign-in"), + "AI assistant: Claude", + &["ada".into()], + &["Buildkite with Cypress".into()], + "https://app.visualci.com", + ); + assert!(text.contains("New sign-up: Ada (@ada) "), "{text}"); + assert!(text.contains("Signed up with: github, from an MCP client's sign-in")); + assert!(text.contains("Heard about VisualCI from: AI assistant: Claude")); + assert!(text.contains("Organization: https://app.visualci.com/ada")); + assert!(text.contains("Buildkite with Cypress")); + } +} diff --git a/app/src/auth/memberships.rs b/app/src/auth/memberships.rs index 38ac485e..4ea95108 100644 --- a/app/src/auth/memberships.rs +++ b/app/src/auth/memberships.rs @@ -21,6 +21,16 @@ pub struct MembershipChanged { pub organization_id: i64, pub user_id: i64, pub role: Option, + /// When the membership changed (milliseconds), fixed at dispatch: the notice's dedupe key, so a retried listener + /// doesn't send it twice. + pub changed_at: i64, +} + +impl MembershipChanged { + #[must_use] + pub fn now(organization_id: i64, user_id: i64, role: Option) -> Self { + Self { organization_id, user_id, role, changed_at: laravel::now().timestamp().as_millisecond() } + } } #[derive(Debug)] @@ -151,7 +161,7 @@ pub async fn apply( }) .await?; for (org, role) in ¬ices { - MembershipChanged { organization_id: *org, user_id, role: *role }.dispatch().await?; + MembershipChanged::now(*org, user_id, *role).dispatch().await?; } Ok(notices.len()) } diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 6e1edfa9..843d2983 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -8,9 +8,16 @@ //! //! Nobody found: `401`. +pub mod device; +pub mod invitations; +pub mod me; pub mod memberships; pub mod oauth; +pub mod orgs; +pub mod setup; pub mod sign_in; +pub mod staff; +pub mod tokens; use axum::extract::FromRequestParts; use axum::http::request::Parts; @@ -259,10 +266,18 @@ pub async fn whoami(principal: Principal) -> laravel::Result laravel::Result> { + let name = name.trim(); + if name.is_empty() || name.chars().count() > MAX_NAME { + return Ok(Err(format!("an organization's name is 1 to {MAX_NAME} characters"))); + } + if user.staff { + return Ok(Ok(())); + } + let user_id = user.id; + let row = db::query!( + "SELECT (SELECT count(*) FROM memberships WHERE user_id = {user_id} AND source = 'created' \ + AND created_at > now() - interval '24 hours') AS today, \ + (created_at > now() - interval '24 hours') AS new_account \ + FROM users WHERE id = {user_id}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(401))?; + let today: i64 = row.try_get("today")?; + // Their own organization, made at sign-up, doesn't count. + let personal = i64::from(today > 0 && row.try_get::("new_account")?); + if today - personal >= DAILY_CREATE_LIMIT { + return Ok(Err(format!( + "you've created {DAILY_CREATE_LIMIT} organizations in the last 24 hours, the limit; try again tomorrow, or \ + ask support@visualci.com for more" + ))); + } + Ok(Ok(())) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct CreateInput { + #[validate(required, max_length(60))] + slug: String, + #[validate(required)] + name: String, +} + +/// `POST /api/ui/orgs`: a new organization with the person as its admin. +pub async fn create( + Authenticated(user): Authenticated, + Valid(p): Valid, +) -> laravel::Result> { + let slug = create_org(&user, &p.slug, &p.name).await?; + Ok(Json(json!({ "slug": slug }))) +} + +/// A new organization with `user` as its admin; returns its slug. Errors: 422 for a slug or name it refuses or over +/// the daily limit, 409 for a slug that's taken. +/// +/// # Errors +/// Those, and database errors. +pub async fn create_org(user: &User, slug: &str, name: &str) -> laravel::Result { + let p = CreateInput { slug: slug.to_string(), name: name.to_string() }; + if !valid_slug(&p.slug) { + return Err(laravel::abort_with( + 422, + "slugs use lowercase letters, digits and dashes, and can't be a reserved word such as account or api", + )); + } + if let Err(e) = may_create(user, &p.name).await? { + return Err(laravel::abort_with(422, e)); + } + let (slug, name, user_id) = (p.slug, p.name.trim().to_string(), user.id); + let created = db::transaction(async |tx| { + let org: Option = db::query!( + tx, + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, {name}, now(), now()) ON CONFLICT (slug) DO NOTHING RETURNING id" + ) + .scalar() + .await?; + if let Some(org) = org { + db::query!( + tx, + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {user_id}, 'admin', 'created', now(), now())" + ) + .insert() + .await?; + } + Ok(org) + }) + .await?; + if created.is_none() { + return Err(laravel::abort_with(409, "that slug is taken")); + } + Ok(slug) +} diff --git a/app/src/auth/setup.rs b/app/src/auth/setup.rs new file mode 100644 index 00000000..f9a9bac3 --- /dev/null +++ b/app/src/auth/setup.rs @@ -0,0 +1,95 @@ +//! The "Set up VisualCI" checklist (sc-8900, ported from today's server): each step ticks itself from what has actually +//! happened, with no "mark done". An organization's admins can close it, or open it again. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::Role; +use crate::models::User; + +pub fn routes(route: &mut Router) { + route.post("/api/ui/orgs/{org}/setup", update); +} + +/// The steps, in order. +pub const STEPS: &[&str] = &["connect_agent", "create_project", "install_github_app", "add_to_ci", "review_changes"]; + +/// The checklist for an organization as `user_pid` sees it (a connected agent is per person: an MCP connection, or a +/// personal token that has been used; with no person, such as a project token, it isn't done): each step and whether +/// it's done, the next one, whether it's complete (a build has been approved) and whether someone closed it. Callers +/// check first that the person may see the organization: this reads it as asked. +/// +/// # Errors +/// On a database error. +pub async fn state(org_id: i64, user_pid: Option) -> laravel::Result { + // An OAuth token's subject is the person's pid as text; the users table is matched on the uuid, by its index + let subject = user_pid.map(|p| p.to_string()); + let row = db::query!( + "SELECT \ + {subject}::text IS NOT NULL AND ( \ + EXISTS (SELECT 1 FROM oauth_tokens t WHERE t.subject = {subject}) \ + OR EXISTS (SELECT 1 FROM user_tokens ut JOIN users u ON u.id = ut.user_id \ + WHERE u.pid = {subject}::uuid AND ut.last_used_at IS NOT NULL)) AS connect_agent, \ + EXISTS (SELECT 1 FROM projects WHERE organization_id = {org_id}) AS create_project, \ + EXISTS (SELECT 1 FROM projects WHERE organization_id = {org_id} AND forge_installation IS NOT NULL) \ + AS install_github_app, \ + EXISTS (SELECT 1 FROM builds b JOIN projects p ON p.id = b.project_id \ + WHERE p.organization_id = {org_id} AND b.mode = 'ci') AS add_to_ci, \ + EXISTS (SELECT 1 FROM reviews r JOIN builds b ON b.id = r.build_id JOIN projects p ON p.id = b.project_id \ + WHERE p.organization_id = {org_id} AND r.action = 'approve') AS review_changes, \ + (SELECT setup_dismissed_at IS NOT NULL FROM organizations WHERE id = {org_id}) AS dismissed" + ) + .select_one() + .await? + .ok_or_else(|| laravel::Error::msg("no setup row"))?; + let mut steps = Vec::new(); + for key in STEPS { + steps.push((*key, row.try_get::(*key)?)); + } + let next = steps.iter().find(|(_, done)| !done).map(|(key, _)| *key); + let complete = steps.last().is_some_and(|(_, done)| *done); + Ok(json!({ + "steps": steps.iter().map(|(key, done)| json!({ "key": key, "done": done })).collect::>(), + "next": next, + "complete": complete, + "dismissed": row.try_get::>("dismissed")?.unwrap_or(false), + })) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct SetupInput { + dismissed: bool, +} + +/// `POST /api/ui/orgs/{org}/setup` (admins): close the checklist, or open it again. +pub async fn update( + Authenticated(user): Authenticated, + Params(org): Params, + Valid(p): Valid, +) -> laravel::Result> { + let user_id = user.id; + let row = db::query!( + "SELECT o.id, m.role FROM organizations o \ + LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} WHERE o.slug = {org}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let org_id: i64 = row.try_get("id")?; + match row.try_get::>("role")?.as_deref().and_then(Role::parse) { + Some(Role::Admin) => {} + Some(_) => return Err(laravel::abort_with(403, "only admins can change the setup checklist")), + None => return Err(laravel::abort(404)), + } + let dismissed = p.dismissed; + db::query!( + "UPDATE organizations SET setup_dismissed_at = CASE WHEN {dismissed} THEN now() END, updated_at = now() \ + WHERE id = {org_id}" + ) + .update() + .await?; + Ok(Json(state(org_id, Some(user.pid)).await?)) +} diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index 44edbfd1..5eed8d59 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -379,7 +379,7 @@ async fn new_user(id: &Identity) -> laravel::Result { .cloned() .unwrap_or_else(|| format!("{}+{}@users.noreply.{}.visualci.com", id.id, id.login, id.forge.as_str())); let verified = (!id.trusted_emails().is_empty()).then(laravel::now); - create!(User { + let user = create!(User { pid: laravel::str::uuid7(), name: id.name.clone().unwrap_or_else(|| id.login.clone()), email: email, @@ -387,7 +387,11 @@ async fn new_user(id: &Identity) -> laravel::Result { avatar_url: id.avatar_url.clone(), staff: false, }) - .await + .await?; + // "How did you hear about VisualCI?" is asked once, after sign-up; the team's email waits for it + let user_id = user.id; + db::query!("UPDATE users SET heard_about_pending = true WHERE id = {user_id}").update().await?; + Ok(user) } async fn record_waitlist(id: &Identity, source: &str) -> laravel::Result<()> { diff --git a/app/src/auth/staff.rs b/app/src/auth/staff.rs new file mode 100644 index 00000000..18b56f6a --- /dev/null +++ b/app/src/auth/staff.rs @@ -0,0 +1,130 @@ +//! Staff pages on the auth and emails side (sc-8900), ported from today's server: the latest sign-ups, every email +//! VisualCI sends rendered with sample data, and failed emails to retry or dismiss. Anyone who isn't staff gets a 404. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::me::summary; +use crate::models::User; +use crate::notify::outbox::AppUrl; +use crate::notify::{About, DeliverEmails, render, render::samples}; + +pub fn routes(route: &mut Router) { + route.get("/api/ui/staff/signups", signups); + route.get("/api/ui/staff/emails", emails); + route.post("/api/ui/staff/emails/{id}/resolve", resolve); +} + +fn staff_only(user: &User) -> laravel::Result<()> { + if user.staff { Ok(()) } else { Err(laravel::abort(404)) } +} + +const TIME: &str = "YYYY-MM-DD\"T\"HH24:MI:SS\"Z\""; + +/// `GET /api/ui/staff/signups`: the latest 100 people, newest first, with how they heard about VisualCI. +pub async fn signups(Authenticated(user): Authenticated) -> laravel::Result> { + staff_only(&user)?; + let rows = db::query!( + "SELECT name, email, heard_about_source, heard_about_detail, \ + to_char(created_at AT TIME ZONE 'UTC', {TIME}) AS created_at, \ + (SELECT login FROM identities WHERE user_id = users.id ORDER BY id LIMIT 1) AS login \ + FROM users ORDER BY id DESC LIMIT 100" + ) + .select() + .await?; + let mut list = Vec::new(); + for r in rows { + let (source, detail): (Option, Option) = + (r.try_get("heard_about_source")?, r.try_get("heard_about_detail")?); + list.push(json!({ + "name": r.try_get::("name")?, "email": r.try_get::("email")?, + "login": r.try_get::>("login")?, "created_at": r.try_get::("created_at")?, + "heard_about": summary(source.as_deref(), detail.as_deref()), + })); + } + Ok(Json(json!({ "signups": list }))) +} + +/// `GET /api/ui/staff/emails`: every email rendered with sample data (for Acme), and the failed ones nobody has +/// retried or dismissed yet, newest first. +pub async fn emails( + Authenticated(user): Authenticated, + app: laravel::config::Section, +) -> laravel::Result> { + staff_only(&user)?; + let about = About { org_name: "Acme", org_slug: "acme", app_url: app.url.trim_end_matches('/') }; + let list: Vec = samples() + .into_iter() + .map(|(label, kind)| { + let r = render(&kind, &about); + json!({ + "label": label, "kind": kind.name(), "subject": r.subject, "text": r.text, "html": r.html, + "can_turn_off": kind.preference().is_some(), + }) + }) + .collect(); + let rows = db::query!( + "SELECT e.id, e.kind, e.recipient, e.attempts, e.last_error, o.slug AS org, \ + to_char(e.created_at AT TIME ZONE 'UTC', {TIME}) AS created_at, \ + to_char(e.updated_at AT TIME ZONE 'UTC', {TIME}) AS failed_at \ + FROM emails e LEFT JOIN organizations o ON o.id = e.organization_id \ + WHERE e.state = 'failed' AND e.dismissed_at IS NULL ORDER BY e.id DESC LIMIT 100" + ) + .select() + .await?; + let mut failed = Vec::new(); + for r in rows { + failed.push(json!({ + "id": r.try_get::("id")?, "kind": r.try_get::("kind")?, + "recipient": r.try_get::("recipient")?, "org": r.try_get::>("org")?, + "attempts": r.try_get::("attempts")?, "last_error": r.try_get::>("last_error")?, + "created_at": r.try_get::("created_at")?, "failed_at": r.try_get::("failed_at")?, + })); + } + Ok(Json(json!({ "emails": list, "failed": failed }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct ResolveInput { + /// `retry` or `dismiss`. + #[validate(required)] + action: String, +} + +/// `POST /api/ui/staff/emails/{id}/resolve`: retry a failed email (sent again from scratch) or dismiss it. Either way +/// it stops counting in `/status`'s `emails_failed_unresolved`. 404 when there's no such failed, undismissed email. +pub async fn resolve( + Authenticated(user): Authenticated, + Params(id): Params, + Valid(p): Valid, +) -> laravel::Result> { + staff_only(&user)?; + let done: Option = match p.action.as_str() { + "retry" => { + db::query!( + "UPDATE emails SET state = 'pending', attempts = 0, claimed_at = NULL, updated_at = now() \ + WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id" + ) + .scalar() + .await? + } + "dismiss" => { + db::query!( + "UPDATE emails SET dismissed_at = now(), updated_at = now() \ + WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id" + ) + .scalar() + .await? + } + _ => return Err(laravel::abort_with(422, "action is retry or dismiss")), + }; + done.ok_or_else(|| laravel::abort(404))?; + tracing::info!(email_id = id, action = %p.action, staff = user.id, "staff resolved a failed email"); + if p.action == "retry" { + DeliverEmails.dispatch().await?; + } + Ok(Json(json!({ "id": id }))) +} diff --git a/app/src/auth/tokens.rs b/app/src/auth/tokens.rs new file mode 100644 index 00000000..9448fa02 --- /dev/null +++ b/app/src/auth/tokens.rs @@ -0,0 +1,186 @@ +//! Personal and project tokens in the web app (sc-8900, the auth side), ported from today's server: a person's own +//! tokens (`vcu_…`, for the MCP server and scripts) and a project's (`vci_…`, CI's, for its admins). A token is shown +//! once, when it's made; only its SHA-256 and its first characters are kept. Making one emails a security notice. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::Role; +use crate::models::{User, token_hash}; +use crate::notify::{self, Kind, To}; + +pub fn routes(route: &mut Router) { + route.get("/api/ui/me/tokens", list_user_tokens); + route.post("/api/ui/me/tokens", create_user_token); + route.delete("/api/ui/me/tokens/{id}", delete_user_token); + route.post("/api/ui/orgs/{org}/projects/{project}/tokens", create_project_token); + route.delete("/api/ui/orgs/{org}/projects/{project}/tokens/{id}", delete_project_token); +} + +/// The security notice for a token just made, once per token. The token exists by now and is about to be shown, its +/// only showing: a notice that can't be queued is logged, never allowed to lose it. +async fn notice(kind: &Kind, user_id: i64, org_id: Option, key: &str) { + if let Err(e) = notify::queue(kind, To::User(user_id), org_id, key).await { + tracing::error!(user_id, key, error = %e, "a token's security notice wasn't queued"); + } +} + +/// A new token: the prefix and 40 letters and digits. Returns it, its hash and what's shown of it. +pub(crate) fn generate(prefix: &str) -> (String, String, String) { + let token = format!("{prefix}{}", laravel::str::random(40)); + let shown = token[..prefix.len() + 6].to_string(); + (token.clone(), token_hash(&token), shown) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct CreateToken { + #[validate(required, max_length(100))] + name: String, +} + +/// The signed-in person's personal tokens. +pub async fn list_user_tokens(Authenticated(user): Authenticated) -> laravel::Result> { + let user_id = user.id; + let rows = db::query!( + "SELECT id, name, token_prefix, to_char(last_used_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') AS last_used_at, \ + to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') AS created_at \ + FROM user_tokens WHERE user_id = {user_id} ORDER BY id" + ) + .select() + .await?; + let tokens: Vec = rows + .iter() + .map(|r| { + Ok(json!({ + "id": r.try_get::("id")?, + "name": r.try_get::("name")?, + "prefix": r.try_get::("token_prefix")?, + "last_used_at": r.try_get::>("last_used_at")?, + "created_at": r.try_get::("created_at")?, + })) + }) + .collect::>()?; + Ok(Json(json!({ "tokens": tokens }))) +} + +/// A new personal token for `user_id`, named `name`, and its id. Only its hash is stored, so this is the one time +/// it's seen. +/// +/// # Errors +/// On a database error. +pub async fn make_user_token(user_id: i64, name: &str) -> laravel::Result<(String, i64)> { + let (token, hash, shown) = generate("vcu_"); + let id: i64 = db::query!( + "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({user_id}, {name}, {hash}, {shown}, now(), now()) RETURNING id" + ) + .scalar() + .await? + .ok_or_else(|| laravel::Error::msg("no token id"))?; + Ok((token, id)) +} + +/// Make a personal token. It's shown once. +pub async fn create_user_token( + Authenticated(user): Authenticated, + Valid(p): Valid, +) -> laravel::Result> { + let name = p.name.trim().to_string(); + if name.is_empty() { + return Err(laravel::abort_with(422, "give the token a name")); + } + let user_id = user.id; + let (token, id) = make_user_token(user_id, &name).await?; + let kind = Kind::TokenCreated { name: name.clone(), project: None }; + notice(&kind, user_id, None, &format!("token_created:user:{id}")).await; + Ok(Json(json!({ "token": token }))) +} + +/// Delete one of the signed-in person's tokens (anyone else's is left alone). +pub async fn delete_user_token( + Authenticated(user): Authenticated, + Params(id): Params, +) -> laravel::Result> { + let user_id = user.id; + db::query!("DELETE FROM user_tokens WHERE id = {id} AND user_id = {user_id}").delete().await?; + Ok(Json(json!({ "ok": true }))) +} + +/// The project, with its organization, when the person is an admin there. A member gets a 403, anyone else a 404. +async fn admin_project(user: &User, org: &str, project: &str, action: &str) -> laravel::Result<(i64, i64, String)> { + let user_id = user.id; + let row = db::query!( + "SELECT p.id, p.organization_id, p.slug, m.role FROM projects p JOIN organizations o ON o.id = p.organization_id \ + LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} \ + WHERE o.slug = {org} AND p.slug = {project}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + match row.try_get::>("role")?.as_deref().and_then(Role::parse) { + Some(Role::Admin) => Ok((row.try_get("id")?, row.try_get("organization_id")?, row.try_get("slug")?)), + Some(_) => Err(laravel::abort_with(403, format!("only admins can {action}"))), + None => Err(laravel::abort(404)), + } +} + +/// Make a project token (admins). It's shown once; the person who made it gets a security notice. +pub async fn create_project_token( + Authenticated(user): Authenticated, + Params((org, project)): Params<(String, String)>, + Valid(p): Valid, +) -> laravel::Result> { + let (project_id, _, _) = admin_project(&user, &org, &project, "create project tokens").await?; + let (token, _) = make_project_token(&user, project_id, p.name.trim()).await?; + Ok(Json(json!({ "token": token }))) +} + +/// A new token for project `project_id`, made by `by`, and its id. It's shown once: only its hash is stored. `by` gets +/// a security notice. The caller checks that `by` is an admin of the project's organization. +/// +/// # Errors +/// On a database error, or when there's no such project. +pub async fn make_project_token(by: &User, project_id: i64, name: &str) -> laravel::Result<(String, i64)> { + let row = db::query!("SELECT organization_id, slug FROM projects WHERE id = {project_id}") + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + let (org_id, project_slug): (i64, String) = (row.try_get("organization_id")?, row.try_get("slug")?); + let name = name.trim().to_string(); + let (token, hash, shown) = generate("vci_"); + let id: i64 = db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, {name}, {hash}, {shown}, now(), now()) RETURNING id" + ) + .scalar() + .await? + .ok_or_else(|| laravel::Error::msg("no token id"))?; + let kind = Kind::TokenCreated { name, project: Some(project_slug) }; + notice(&kind, by.id, Some(org_id), &format!("token_created:project:{id}")).await; + Ok((token, id)) +} + +/// Delete a project token (admins). +pub async fn delete_project_token( + Authenticated(user): Authenticated, + Params((org, project, id)): Params<(String, String, i64)>, +) -> laravel::Result> { + let (project_id, _, _) = admin_project(&user, &org, &project, "delete project tokens").await?; + remove_project_token(project_id, id).await?; + Ok(Json(json!({ "ok": true }))) +} + +/// Delete project `project_id`'s token `id`; `false` when it has no such token. The caller checks the person may. +/// +/// # Errors +/// On a database error. +pub async fn remove_project_token(project_id: i64, id: i64) -> laravel::Result { + let deleted: Option = + db::query!("DELETE FROM project_tokens WHERE id = {id} AND project_id = {project_id} RETURNING id") + .scalar() + .await?; + Ok(deleted.is_some()) +} diff --git a/app/src/billing/mod.rs b/app/src/billing/mod.rs new file mode 100644 index 00000000..497029ed --- /dev/null +++ b/app/src/billing/mod.rs @@ -0,0 +1,127 @@ +//! Billing (sc-8900, the billing side; ported from today's server as it moves over). For now, the credit pack the +//! emails quote. + +/// A pack of credits bought on top of a plan. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CreditPack { + pub credits: i64, + pub price_cents: i64, + /// Automatic packs buy one when the balance falls below this. + pub reload_below: i64, +} + +/// Most automatic reloads an organization can allow in a month. +pub const MAX_AUTO_RELOAD_PACKS: i32 = 50; + +/// One pack: 500,000 credits for $15, as today. +pub const CREDIT_PACK: CreditPack = CreditPack { credits: 500_000, price_cents: 1_500, reload_below: 100_000 }; + +pub mod routes; +pub mod stripe; +pub mod webhook; + +/// A plan an organization can be on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Plan { + pub id: &'static str, + pub name: &'static str, + /// US cents per month. + pub price_cents: i64, + /// Credits included each calendar month (UTC). + pub included_credits: i64, + /// Whether the organization can buy credit packs past the allowance. + pub credit_packs: bool, + /// No allowance or limit at all: builds never stop for credits. + pub unlimited: bool, +} + +pub const FREE: Plan = + Plan { id: "free", name: "Free", price_cents: 0, included_credits: 25_000, credit_packs: false, unlimited: false }; +pub const TEAM: Plan = Plan { + id: "team", + name: "Team", + price_cents: 2_900, + included_credits: 1_000_000, + credit_packs: true, + unlimited: false, +}; +/// DocSpring's own organizations: unlimited, free, and never offered. +pub const STAFF: Plan = + Plan { id: "staff", name: "Staff", price_cents: 0, included_credits: 0, credit_packs: false, unlimited: true }; + +/// The plan with this id (an organization's `plan` column). Anything unknown is Free. +#[must_use] +pub fn plan_by_id(id: &str) -> Plan { + [TEAM, STAFF].into_iter().find(|p| p.id == id).unwrap_or(FREE) +} + +/// Stripe (`STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`). Production's keys come only from the cluster's +/// ExternalSecrets; tests fake Stripe. +#[derive(Clone, laravel::config::Section)] +pub struct Stripe { + #[env("STRIPE_SECRET_KEY")] + pub secret_key: Option, + #[env("STRIPE_WEBHOOK_SECRET")] + pub webhook_secret: Option, +} + +impl Stripe { + /// Whether the secret key is a live one (`sk_live_`, `rk_live_`); `None` without a key. + #[must_use] + pub fn live(&self) -> Option { + let key = self.secret_key.as_deref().map(str::trim).filter(|k| !k.is_empty())?; + Some(key.starts_with("sk_live_") || key.starts_with("rk_live_")) + } +} + +/// At boot: production never runs on a test key (`sk_test_`, `rk_test_`), which would take no real payments while +/// granting real plans and credits. +/// +/// # Errors +/// In production, when the Stripe key isn't a live one. +pub fn check(stripe: &Stripe, production: bool) -> laravel::Result<()> { + if production && stripe.live() == Some(false) { + return Err(laravel::Error::msg( + "STRIPE_SECRET_KEY is a test key; production needs a live one (sk_live_ or rk_live_)", + )); + } + Ok(()) +} + +/// Add purchased credits once per `reference` (a Checkout session or an invoice): `true` when added, `false` when +/// that reference was already credited. Two callers that both get here (an automatic reload and its `invoice.paid` +/// webhook) are kept apart by the `credit_transactions_purchase_once` index. +/// +/// # Errors +/// On a database error. +pub async fn add_purchased_credits(org_id: i64, credits: i64, reference: &str) -> laravel::Result { + let added = laravel::db::transaction(async |tx| { + let balance: Option = laravel::db::query!( + tx, + "UPDATE organizations SET credits_balance = credits_balance + {credits}, updated_at = now() \ + WHERE id = {org_id} RETURNING credits_balance" + ) + .scalar() + .await?; + let Some(balance) = balance else { return Ok(false) }; + let inserted: Option = laravel::db::query!( + tx, + "INSERT INTO credit_transactions (organization_id, amount, balance_after, kind, reference) \ + VALUES ({org_id}, {credits}, {balance}, 'purchase', {reference}) \ + ON CONFLICT (organization_id, reference) WHERE kind = 'purchase' DO NOTHING RETURNING id" + ) + .scalar() + .await?; + if inserted.is_none() { + // Already credited: undo this transaction's balance change + return Err(laravel::Error::msg("already credited")); + } + Ok(true) + }) + .await; + match added { + Ok(added) => Ok(added), + Err(e) if e.to_string().contains("already credited") => Ok(false), + Err(e) => Err(e), + } +} diff --git a/app/src/billing/routes.rs b/app/src/billing/routes.rs new file mode 100644 index 00000000..1120757f --- /dev/null +++ b/app/src/billing/routes.rs @@ -0,0 +1,389 @@ +//! The billing page's routes (`/api/ui/...`, the web app's session), ported from today's server: the plans, Checkout +//! for the Team plan and for credit packs, Stripe's customer portal, automatic reloads, payment methods and invoices. +//! Only an organization's admins choose the plan and pay; anyone else gets a 403 (a member) or a 404. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::stripe::{self, Method, catalog, checkout_tax_fields, ensure_customer}; +use super::{CREDIT_PACK, FREE, MAX_AUTO_RELOAD_PACKS, STAFF, Stripe, TEAM, plan_by_id}; +use crate::models::User; +use crate::notify::outbox::AppUrl; + +/// The routes, on the `web` group. +pub fn routes(route: &mut Router) { + route.get("/api/ui/billing/plans", plans); + route.post("/api/ui/orgs/{org}/billing/checkout", checkout); + route.post("/api/ui/orgs/{org}/billing/portal", portal); + route.post("/api/ui/orgs/{org}/billing/packs", buy_packs); + route.put("/api/ui/orgs/{org}/billing/auto-reload", set_auto_reload); + route.get("/api/ui/orgs/{org}/billing/payment-methods", payment_methods); + route.post("/api/ui/orgs/{org}/billing/payment-methods/setup", add_payment_method); + route.post("/api/ui/orgs/{org}/billing/payment-methods/{id}/default", default_payment_method); + route.delete("/api/ui/orgs/{org}/billing/payment-methods/{id}", remove_payment_method); + route.get("/api/ui/orgs/{org}/billing/invoices", invoices); +} + +/// An organization as billing reads it. +struct BillingOrg { + id: i64, + slug: String, + plan: String, + customer: Option, + subscription: Option, +} + +/// The organization, when the user is one of its admins. +async fn billing_org(user: &User, slug: &str) -> laravel::Result { + let user_id = user.id; + let row = db::query!( + "SELECT o.id, o.slug, o.plan, o.stripe_customer_id, o.stripe_subscription_id, m.role \ + FROM organizations o LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} \ + WHERE o.slug = {slug}" + ) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + match row.try_get::>("role")?.as_deref() { + Some("admin") => Ok(BillingOrg { + id: row.try_get("id")?, + slug: row.try_get("slug")?, + plan: row.try_get("plan")?, + customer: row.try_get("stripe_customer_id")?, + subscription: row.try_get("stripe_subscription_id")?, + }), + Some(_) => Err(laravel::abort_with(403, "only admins can change the plan")), + None => Err(laravel::abort(404)), + } +} + +/// Stripe's secret key, or a 400 when payments aren't set up. +fn key(stripe: &Stripe) -> laravel::Result<&str> { + stripe + .secret_key + .as_deref() + .filter(|k| !k.is_empty()) + .ok_or_else(|| laravel::abort_with(400, "payments aren't set up yet")) +} + +fn app_url(app: &AppUrl) -> String { + app.url.trim_end_matches('/').to_string() +} + +/// `GET /api/ui/billing/plans`: the plans anyone can choose, the pack, and whether payments are on. +pub async fn plans(stripe: laravel::config::Section) -> Json { + let plan = |p: super::Plan| { + json!({ "id": p.id, "name": p.name, "price_cents": p.price_cents, "included_credits": p.included_credits, + "credit_packs": p.credit_packs, "unlimited": p.unlimited }) + }; + Json(json!({ + "plans": [plan(FREE), plan(TEAM)], + "credit_pack": { "credits": CREDIT_PACK.credits, "price_cents": CREDIT_PACK.price_cents, + "reload_below": CREDIT_PACK.reload_below }, + "max_auto_reload_packs": MAX_AUTO_RELOAD_PACKS, + "stripe_enabled": stripe.secret_key.as_deref().is_some_and(|k| !k.is_empty()), + })) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct CheckoutParams { + #[validate(required)] + plan: String, +} + +/// Stripe Checkout for the Team subscription (flexible billing mode, Stripe Tax). +pub async fn checkout( + Authenticated(user): Authenticated, + Params(org): Params, + stripe: laravel::config::Section, + app: laravel::config::Section, + Valid(p): Valid, +) -> laravel::Result> { + let key = key(&stripe)?; + if p.plan != TEAM.id { + return Err(laravel::abort_with(400, "the only plan to subscribe to is team")); + } + let org = billing_org(&user, &org).await?; + if org.plan == TEAM.id || org.subscription.is_some() { + return Err(laravel::abort_with(400, "this organization already has a Team subscription")); + } + if org.plan == STAFF.id { + return Err(laravel::abort_with(400, "this organization is on the Staff plan, which has no limits")); + } + let catalog = catalog(key).await?; + let customer = ensure_customer(key, org.id, &user.email).await?; + let base = format!("{}/{}/billing", app_url(&app), org.slug); + let mut form = vec![ + ("mode", "subscription".to_string()), + ("customer", customer), + ("success_url", format!("{base}?checkout=success")), + ("cancel_url", format!("{base}?checkout=cancelled")), + ("client_reference_id", org.id.to_string()), + ("line_items[0][price]", catalog.team_price.clone()), + ("line_items[0][quantity]", "1".to_string()), + ("metadata[organization_id]", org.id.to_string()), + ("subscription_data[metadata][organization_id]", org.id.to_string()), + ("subscription_data[billing_mode][type]", "flexible".to_string()), + ]; + form.extend(checkout_tax_fields()); + let body = stripe::post(key, "checkout/sessions", &form).await?; + Ok(Json(json!({ "url": body["url"] }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct PackParams { + /// One unless it says otherwise + packs: Option, +} + +/// Stripe Checkout for credit packs (a one-off payment with an invoice and Stripe Tax), on Team. +pub async fn buy_packs( + Authenticated(user): Authenticated, + Params(org): Params, + stripe: laravel::config::Section, + app: laravel::config::Section, + Valid(p): Valid, +) -> laravel::Result> { + let key = key(&stripe)?; + let packs = p.packs.unwrap_or(1); + if !(1..=20).contains(&packs) { + return Err(laravel::abort_with(400, "buy between 1 and 20 packs at a time")); + } + let org = billing_org(&user, &org).await?; + let Some(customer) = org.customer.clone().filter(|_| plan_by_id(&org.plan).credit_packs) else { + return Err(laravel::abort_with(400, "credit packs come with the Team plan")); + }; + let catalog = catalog(key).await?; + let base = format!("{}/{}/billing", app_url(&app), org.slug); + let mut form = vec![ + ("mode", "payment".to_string()), + ("customer", customer), + ("success_url", format!("{base}?packs=success")), + ("cancel_url", format!("{base}?packs=cancelled")), + ("client_reference_id", org.id.to_string()), + ("line_items[0][price]", catalog.pack_price.clone()), + ("line_items[0][quantity]", packs.to_string()), + ("invoice_creation[enabled]", "true".to_string()), + ("metadata[organization_id]", org.id.to_string()), + ("metadata[kind]", "credit_pack".to_string()), + ("metadata[packs]", packs.to_string()), + ]; + form.extend(checkout_tax_fields()); + let body = stripe::post(key, "checkout/sessions", &form).await?; + Ok(Json(json!({ "url": body["url"] }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct AutoReloadParams { + #[validate(required)] + packs: i32, +} + +/// How many packs automatic reloads may buy in a month (0 turns them off). Setting it also resumes reloads a failed +/// payment paused: the owner says the card is fixed. +pub async fn set_auto_reload( + Authenticated(user): Authenticated, + Params(org): Params, + Valid(p): Valid, +) -> laravel::Result> { + if !(0..=MAX_AUTO_RELOAD_PACKS).contains(&p.packs) { + return Err(laravel::abort_with( + 400, + format!("automatic reloads can buy 0 to {MAX_AUTO_RELOAD_PACKS} packs a month"), + )); + } + let org = billing_org(&user, &org).await?; + let (id, packs) = (org.id, p.packs); + db::query!( + "UPDATE organizations SET auto_reload_packs = {packs}, reloads_paused_at = NULL, billing_problem = NULL, \ + updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + Ok(Json(json!({ "auto_reload_packs": packs }))) +} + +/// Stripe's customer portal: change the card, name, address and tax ID, see invoices, cancel at the end of the period. +pub async fn portal( + Authenticated(user): Authenticated, + Params(org): Params, + stripe: laravel::config::Section, + app: laravel::config::Section, +) -> laravel::Result> { + let key = key(&stripe)?; + let org = billing_org(&user, &org).await?; + let Some(customer) = org.customer.clone() else { + return Err(laravel::abort_with(400, "this organization has no subscription")); + }; + let catalog = catalog(key).await?; + let form = [ + ("customer", customer), + ("configuration", catalog.portal_configuration.clone()), + ("return_url", format!("{}/{}/billing", app_url(&app), org.slug)), + ]; + let body = stripe::post(key, "billing_portal/sessions", &form).await?; + Ok(Json(json!({ "url": body["url"] }))) +} + +/// The customer's default payment method (its ID), as invoices use it. +async fn default_method(key: &str, customer: &str) -> laravel::Result> { + let c = stripe::get(key, &format!("customers/{customer}"), &[]).await?; + let d = &c["invoice_settings"]["default_payment_method"]; + Ok(d.as_str().map(str::to_string).or_else(|| d["id"].as_str().map(str::to_string))) +} + +/// A payment method, checked to be this customer's before anything is done with it. +async fn own_method(key: &str, customer: &str, id: &str) -> laravel::Result { + let prefixed = id.starts_with("pm_") || id.starts_with("card_") || id.starts_with("src_"); + // It goes into a Stripe API path: letters, digits and underscores only. + if !prefixed || id.len() > 255 || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { + return Err(laravel::abort(404)); + } + let pm = stripe::get(key, &format!("payment_methods/{id}"), &[]).await.map_err(|_| laravel::abort(404))?; + if pm["customer"].as_str() != Some(customer) { + return Err(laravel::abort(404)); + } + Ok(pm) +} + +/// The organization's saved payment methods: cards (brand, last 4, expiry) and others by type, the default marked. +/// A first card (just added in Checkout's setup mode) becomes the default. +pub async fn payment_methods( + Authenticated(user): Authenticated, + Params(org): Params, + stripe: laravel::config::Section, +) -> laravel::Result> { + let key = key(&stripe)?; + let org = billing_org(&user, &org).await?; + let Some(customer) = org.customer else { return Ok(Json(json!({ "methods": [] }))) }; + let mut default = default_method(key, &customer).await?; + let list = stripe::get(key, &format!("customers/{customer}/payment_methods"), &[("limit", "100".into())]).await?; + if default.is_none() + && let Some(newest) = list["data"][0]["id"].as_str() + { + stripe::post( + key, + &format!("customers/{customer}"), + &[("invoice_settings[default_payment_method]", newest.to_string())], + ) + .await?; + default = Some(newest.to_string()); + } + let methods: Vec = list["data"] + .as_array() + .into_iter() + .flatten() + .map(|m| { + let kind = m["type"].as_str().unwrap_or(""); + let card = &m["card"]; + json!({ + "id": m["id"], "type": kind, "brand": card["brand"], + "last4": card["last4"].as_str().or_else(|| m[kind]["last4"].as_str()), + "exp_month": card["exp_month"], "exp_year": card["exp_year"], + "default": m["id"].as_str() == default.as_deref(), + }) + }) + .collect(); + Ok(Json(json!({ "methods": methods }))) +} + +/// "Add payment method": Stripe Checkout in setup mode, back to the Payment methods tab. +pub async fn add_payment_method( + Authenticated(user): Authenticated, + Params(org): Params, + stripe: laravel::config::Section, + app: laravel::config::Section, +) -> laravel::Result> { + let key = key(&stripe)?; + let org = billing_org(&user, &org).await?; + let customer = ensure_customer(key, org.id, &user.email).await?; + let back = format!("{}/{}/billing/payment-methods", app_url(&app), org.slug); + let form = [ + ("mode", "setup".to_string()), + ("customer", customer), + ("currency", "usd".to_string()), + ("success_url", format!("{back}?added=1")), + ("cancel_url", back), + ("metadata[organization_id]", org.id.to_string()), + ]; + let session = stripe::post(key, "checkout/sessions", &form).await?; + Ok(Json(json!({ "url": session["url"] }))) +} + +/// "Make default": invoices and automatic reloads charge it from now on, and the subscription too. +pub async fn default_payment_method( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, + stripe: laravel::config::Section, +) -> laravel::Result> { + let key = key(&stripe)?; + let org = billing_org(&user, &org).await?; + let customer = org.customer.ok_or_else(|| laravel::abort(404))?; + own_method(key, &customer, &id).await?; + stripe::post(key, &format!("customers/{customer}"), &[("invoice_settings[default_payment_method]", id.clone())]) + .await?; + if let Some(sub) = &org.subscription { + stripe::post(key, &format!("subscriptions/{sub}"), &[("default_payment_method", id)]).await?; + } + Ok(Json(json!({ "ok": true }))) +} + +/// "Remove": detach a payment method. The default can't go while the Team plan needs it. +pub async fn remove_payment_method( + Authenticated(user): Authenticated, + Params((org, id)): Params<(String, String)>, + stripe: laravel::config::Section, +) -> laravel::Result> { + let key = key(&stripe)?; + let org = billing_org(&user, &org).await?; + let customer = org.customer.ok_or_else(|| laravel::abort(404))?; + own_method(key, &customer, &id).await?; + if org.subscription.is_some() && default_method(key, &customer).await?.as_deref() == Some(id.as_str()) { + return Err(laravel::abort_with(400, "make another card the default first: the Team plan charges this one")); + } + stripe::request(key, Method::Post, &format!("payment_methods/{id}/detach"), &[], None).await?; + Ok(Json(json!({ "ok": true }))) +} + +#[laravel::query] +pub struct InvoicesQuery { + /// Stripe's cursor: the last invoice ID of the previous page. + after: Option, +} + +/// The organization's Stripe invoices, newest first, 20 at a time, with their PDFs and hosted pages. +pub async fn invoices( + Authenticated(user): Authenticated, + Params(org): Params, + stripe: laravel::config::Section, + Query(q): Query, +) -> laravel::Result> { + let key = key(&stripe)?; + let org = billing_org(&user, &org).await?; + let Some(customer) = org.customer else { return Ok(Json(json!({ "invoices": [], "has_more": false }))) }; + let mut query = vec![("customer", customer), ("limit", "20".to_string())]; + if let Some(after) = q.after.filter(|a| a.starts_with("in_")) { + query.push(("starting_after", after)); + } + let list = stripe::get(key, "invoices", &query).await?; + let invoices: Vec = list["data"] + .as_array() + .into_iter() + .flatten() + .filter(|i| i["status"].as_str() != Some("draft")) + .map(|i| { + let description = i["lines"]["data"][0]["description"].as_str().or_else(|| i["description"].as_str()); + json!({ + "id": i["id"], "number": i["number"], "created": i["created"], "description": description, + "total": i["total"], "currency": i["currency"], "status": i["status"], + "pdf": i["invoice_pdf"], "url": i["hosted_invoice_url"], + }) + }) + .collect(); + Ok(Json(json!({ "invoices": invoices, "has_more": list["has_more"] }))) +} diff --git a/app/src/billing/stripe.rs b/app/src/billing/stripe.rs new file mode 100644 index 00000000..e18d2e05 --- /dev/null +++ b/app/src/billing/stripe.rs @@ -0,0 +1,224 @@ +//! Stripe's API, and the catalog billing uses, ported from today's server. Everything is a Stripe Product and Price, +//! created on first use: the products have fixed IDs, prices are found by lookup key (a changed amount gets a new +//! price, which takes the key), and the customer portal configuration is the one marked `metadata[visualci]`. Stripe +//! Tax is on everywhere, with billing addresses and tax IDs collected. + +use laravel::db; +use laravel::http::client; +use serde_json::Value; +use tokio::sync::OnceCell; + +use super::{CREDIT_PACK, TEAM}; + +/// Product tax code: Software as a service (SaaS), business use. +const TAX_CODE: &str = "txcd_10103001"; +const TEAM_PRODUCT: &str = "visualci_team"; +const PACK_PRODUCT: &str = "visualci_credit_pack"; +const TEAM_PRICE: &str = "visualci_team_monthly"; +const PACK_PRICE: &str = "visualci_credit_pack"; +/// Marks the customer portal configuration this code manages. +const PORTAL_MARKER: &str = "visualci"; + +/// A Stripe API call: GET with a query, POST with a form, or DELETE. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Method { + Get, + Post, + Delete, +} + +/// Call Stripe's API. `idempotency_key` makes a retried request return the first result instead of acting again. +/// +/// # Errors +/// When Stripe can't be reached or refuses the request. +pub async fn request( + key: &str, + method: Method, + path: &str, + form: &[(&str, String)], + idempotency_key: Option<&str>, +) -> laravel::Result { + let url = format!("https://api.stripe.com/v1/{path}"); + let pending = match method { + Method::Get => client::get(url).query(form), + Method::Post => client::post(url).form(form), + Method::Delete => client::delete(url), + }; + let mut pending = pending.basic_auth(key, "").accept_json(); + if let Some(k) = idempotency_key { + pending = pending.header("Idempotency-Key", k); + } + let response = pending.await?; + let body: Value = response.json().unwrap_or_default(); + if !response.successful() { + return Err(laravel::Error::msg(format!("Stripe: HTTP {}: {}", response.status(), body["error"]["message"]))); + } + Ok(body) +} + +/// # Errors +/// When Stripe can't be reached or refuses the request. +pub async fn post(key: &str, path: &str, form: &[(&str, String)]) -> laravel::Result { + request(key, Method::Post, path, form, None).await +} + +/// # Errors +/// When Stripe can't be reached or refuses the request. +pub async fn get(key: &str, path: &str, query: &[(&str, String)]) -> laravel::Result { + request(key, Method::Get, path, query, None).await +} + +/// The Stripe objects billing uses, by ID. +#[derive(Clone, Debug)] +pub struct Catalog { + pub team_price: String, + pub pack_price: String, + pub portal_configuration: String, +} + +static CATALOG: OnceCell = OnceCell::const_new(); + +/// The catalog, created in Stripe the first time it's needed in this process. +/// +/// # Errors +/// When Stripe can't be reached or refuses a request. +pub async fn catalog(key: &str) -> laravel::Result<&'static Catalog> { + CATALOG.get_or_try_init(|| ensure_catalog(key)).await +} + +/// Creates or updates the products, prices and portal configuration. Safe to run any number of times. +/// +/// # Errors +/// When Stripe can't be reached or refuses a request. +pub async fn ensure_catalog(key: &str) -> laravel::Result { + ensure_product(key, TEAM_PRODUCT, "VisualCI Team").await?; + ensure_product(key, PACK_PRODUCT, &format!("VisualCI credit pack: {} credits", CREDIT_PACK.credits)).await?; + let team_price = ensure_price(key, TEAM_PRICE, TEAM_PRODUCT, TEAM.price_cents, true).await?; + let pack_price = ensure_price(key, PACK_PRICE, PACK_PRODUCT, CREDIT_PACK.price_cents, false).await?; + let portal_configuration = ensure_portal(key, &team_price).await?; + tracing::info!(team_price, pack_price, portal_configuration, "Stripe catalog ready"); + Ok(Catalog { team_price, pack_price, portal_configuration }) +} + +async fn ensure_product(key: &str, id: &str, name: &str) -> laravel::Result<()> { + let form = [("name", name.to_string()), ("tax_code", TAX_CODE.to_string())]; + if get(key, &format!("products/{id}"), &[]).await.is_ok() { + post(key, &format!("products/{id}"), &form).await?; + } else { + let mut create = vec![("id", id.to_string())]; + create.extend(form); + post(key, "products", &create).await?; + } + Ok(()) +} + +async fn ensure_price( + key: &str, + lookup_key: &str, + product: &str, + cents: i64, + monthly: bool, +) -> laravel::Result { + let found = get(key, "prices", &[("lookup_keys[]", lookup_key.to_string()), ("active", "true".into())]).await?; + if let Some(price) = found["data"].as_array().and_then(|d| d.first()) { + let same = price["unit_amount"].as_i64() == Some(cents) + && price["product"].as_str() == Some(product) + && price["recurring"].is_object() == monthly; + if same && let Some(id) = price["id"].as_str() { + return Ok(id.to_string()); + } + } + let mut form = vec![ + ("product", product.to_string()), + ("currency", "usd".to_string()), + ("unit_amount", cents.to_string()), + ("tax_behavior", "exclusive".to_string()), + ("lookup_key", lookup_key.to_string()), + ("transfer_lookup_key", "true".to_string()), + ]; + if monthly { + form.push(("recurring[interval]", "month".to_string())); + } + let price = post(key, "prices", &form).await?; + price["id"].as_str().map(str::to_string).ok_or_else(|| laravel::Error::msg("Stripe: a price without an id")) +} + +/// The customer portal: update the card, name, address and tax ID, see invoices, and cancel at the end of the period. +async fn ensure_portal(key: &str, team_price: &str) -> laravel::Result { + let form = vec![ + ("business_profile[headline]", "VisualCI billing".to_string()), + ("features[customer_update][enabled]", "true".to_string()), + ("features[customer_update][allowed_updates][]", "email".to_string()), + ("features[customer_update][allowed_updates][]", "name".to_string()), + ("features[customer_update][allowed_updates][]", "address".to_string()), + ("features[customer_update][allowed_updates][]", "tax_id".to_string()), + ("features[invoice_history][enabled]", "true".to_string()), + ("features[payment_method_update][enabled]", "true".to_string()), + ("features[subscription_cancel][enabled]", "true".to_string()), + ("features[subscription_cancel][mode]", "at_period_end".to_string()), + ("features[subscription_update][enabled]", "true".to_string()), + ("features[subscription_update][default_allowed_updates][]", "price".to_string()), + ("features[subscription_update][products][0][product]", TEAM_PRODUCT.to_string()), + ("features[subscription_update][products][0][prices][]", team_price.to_string()), + ("features[subscription_update][proration_behavior]", "create_prorations".to_string()), + ("metadata[visualci]", "billing".to_string()), + ]; + let existing = + get(key, "billing_portal/configurations", &[("active", "true".into()), ("limit", "100".into())]).await?; + let ours = existing["data"] + .as_array() + .and_then(|d| d.iter().find(|c| c["metadata"][PORTAL_MARKER].is_string())) + .and_then(|c| c["id"].as_str().map(str::to_string)); + let config = match ours { + Some(id) => post(key, &format!("billing_portal/configurations/{id}"), &form).await?, + None => post(key, "billing_portal/configurations", &form).await?, + }; + config["id"] + .as_str() + .map(str::to_string) + .ok_or_else(|| laravel::Error::msg("Stripe: a portal configuration without an id")) +} + +/// The organization's Stripe customer, created (named after the organization, billed to `email`) the first time it +/// pays for anything. +/// +/// # Errors +/// On a database error, or when Stripe can't be reached. +pub async fn ensure_customer(key: &str, org_id: i64, email: &str) -> laravel::Result { + let row = db::query!("SELECT name, slug, stripe_customer_id FROM organizations WHERE id = {org_id}") + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + if let Some(id) = row.try_get::>("stripe_customer_id")? { + return Ok(id); + } + let (name, slug): (String, String) = (row.try_get("name")?, row.try_get("slug")?); + let form = [ + ("name", name), + ("email", email.to_string()), + ("metadata[organization_id]", org_id.to_string()), + ("metadata[organization]", slug), + ]; + let idempotency = format!("visualci-customer-{org_id}"); + let customer = request(key, Method::Post, "customers", &form, Some(&idempotency)).await?; + let id = customer["id"] + .as_str() + .map(str::to_string) + .ok_or_else(|| laravel::Error::msg("Stripe: a customer without an id"))?; + db::query!("UPDATE organizations SET stripe_customer_id = {id}, updated_at = now() WHERE id = {org_id}") + .update() + .await?; + Ok(id) +} + +/// What every Checkout session sends for tax: Stripe Tax, the billing address, tax IDs, and both saved on the customer. +#[must_use] +pub fn checkout_tax_fields() -> Vec<(&'static str, String)> { + vec![ + ("automatic_tax[enabled]", "true".to_string()), + ("billing_address_collection", "required".to_string()), + ("tax_id_collection[enabled]", "true".to_string()), + ("customer_update[address]", "auto".to_string()), + ("customer_update[name]", "auto".to_string()), + ] +} diff --git a/app/src/billing/webhook.rs b/app/src/billing/webhook.rs new file mode 100644 index 00000000..93fa2ef5 --- /dev/null +++ b/app/src/billing/webhook.rs @@ -0,0 +1,279 @@ +//! Stripe's webhook (`POST /webhooks/stripe`), ported from today's server. Every event is safe to receive twice. +//! +//! - `checkout.session.completed`: a subscription moves the organization to Team; a paid pack adds its credits. +//! - `customer.subscription.updated`: active keeps it on Team; past due or unpaid shows a billing problem. +//! - `customer.subscription.deleted`: back to Free. +//! - `invoice.paid`: an automatic reload's credits (if the reload itself didn't record them), and any billing problem +//! is over. +//! - `invoice.payment_failed`: shows the problem and pauses automatic reloads. +//! +//! Subscription events apply only to the organization's own subscription, and only when newer than the last one +//! applied: Stripe sends events in any order and retries them for days. + +use hmac::{Hmac, Mac}; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; +use sha2::Sha256; + +use super::{CREDIT_PACK, FREE, Stripe, TEAM, add_purchased_credits, plan_by_id}; +use crate::notify::{self, Kind, To}; + +/// `POST /webhooks/stripe`. +pub async fn handle( + stripe: laravel::config::Section, + headers: axum::http::HeaderMap, + body: axum::body::Bytes, +) -> laravel::Result> { + let Some(secret) = stripe.webhook_secret.as_deref().filter(|s| !s.is_empty()) else { + return Err(laravel::abort(404)); + }; + let signature = headers.get("stripe-signature").and_then(|v| v.to_str().ok()).unwrap_or_default(); + if !verify_signature(secret, signature, &body, laravel::now().timestamp().as_second()) { + return Err(laravel::abort_with(401, "bad signature")); + } + let event: Value = serde_json::from_slice(&body).map_err(|e| laravel::abort_with(400, e.to_string()))?; + // A test-mode event never changes a live account's plans or credits, nor a live event a test one's. + if let Some(live) = stripe.live() + && event["livemode"].as_bool() != Some(live) + { + return Err(laravel::abort_with(400, "the event's livemode doesn't match the Stripe key")); + } + let object = &event["data"]["object"]; + let text = |v: &Value| v.as_str().map(str::to_string); + let kind = event["type"].as_str().unwrap_or_default(); + let Some(org_id) = org_for(object).await? else { + return Ok(Json(json!({ "ignored": "not a VisualCI organization's" }))); + }; + let created = event["created"].as_i64().unwrap_or_default(); + match kind { + "checkout.session.completed" if object["mode"] == "subscription" => { + let subscription = text(&object["subscription"]); + match which_subscription(org_id, subscription.as_deref()).await? { + // A second checkout finished while the first is active (two tabs): keep the first, and say so + Which::Other => { + record_payment_problem(org_id, TWO_SUBSCRIPTIONS).await?; + } + Which::Current => { + let change = Change::Plan { plan: TEAM.id, customer: text(&object["customer"]), subscription }; + subscription_event(org_id, created, change).await?; + } + } + } + "checkout.session.completed" if object["mode"] == "payment" && object["metadata"]["kind"] == "credit_pack" => { + let packs: i64 = object["metadata"]["packs"].as_str().and_then(|s| s.parse().ok()).unwrap_or(0); + if packs == 0 { + return Err(laravel::abort_with(400, "session without VisualCI metadata")); + } + if object["payment_status"] != "paid" { + return Ok(Json(json!({ "ignored": "not paid" }))); + } + let reference = format!("packs: {}", object["id"].as_str().unwrap_or_default()); + add_purchased_credits(org_id, packs * CREDIT_PACK.credits, &reference).await?; + } + "customer.subscription.updated" | "customer.subscription.deleted" + if matches!(which_subscription(org_id, object["id"].as_str()).await?, Which::Other) => + { + return Ok(Json(json!({ "ignored": "another subscription" }))); + } + "customer.subscription.updated" => { + let change = match object["status"].as_str().unwrap_or_default() { + "active" | "trialing" => Change::Plan { + plan: TEAM.id, + customer: text(&object["customer"]), + subscription: text(&object["id"]), + }, + "past_due" | "unpaid" => Change::Problem(PAYMENT_FAILED), + _ => Change::Nothing, + }; + if !subscription_event(org_id, created, change).await? { + return Ok(Json(json!({ "ignored": "an older event" }))); + } + } + "customer.subscription.deleted" => { + let change = Change::Plan { plan: FREE.id, customer: None, subscription: None }; + if !subscription_event(org_id, created, change).await? { + return Ok(Json(json!({ "ignored": "an older event" }))); + } + } + "invoice.paid" => { + if object["metadata"]["kind"] == "auto_reload" + && let Some(invoice) = object["id"].as_str() + { + add_purchased_credits(org_id, CREDIT_PACK.credits, &format!("auto-reload: {invoice}")).await?; + } + // A paid invoice settles a payment problem, not a second subscription. + db::query!( + "UPDATE organizations SET billing_problem = NULL, updated_at = now() \ + WHERE id = {org_id} AND billing_problem IS DISTINCT FROM {TWO_SUBSCRIPTIONS}" + ) + .update() + .await?; + } + "invoice.payment_failed" => { + let number = object["number"].as_str().unwrap_or("an invoice"); + // Stripe emails the failed payment itself; a declined automatic pack has its own email (the reload) + record_payment_problem( + org_id, + &format!("Payment for {number} failed. Update the card in Manage billing, then turn reloads back on."), + ) + .await?; + } + _ => return Ok(Json(json!({ "ignored": true }))), + } + Ok(Json(json!({ "ok": true }))) +} + +/// The organization a Stripe object belongs to: its `metadata[organization_id]`, else its customer's organization. +async fn org_for(object: &Value) -> laravel::Result> { + if let Some(id) = object["metadata"]["organization_id"].as_str().and_then(|s| s.parse::().ok()) { + let exists: Option = db::query!("SELECT id FROM organizations WHERE id = {id}").scalar().await?; + return Ok(exists); + } + let customer = object["customer"].as_str().or_else(|| object["customer"]["id"].as_str()); + let Some(customer) = customer else { return Ok(None) }; + db::query!("SELECT id FROM organizations WHERE stripe_customer_id = {customer}").scalar().await +} + +const TWO_SUBSCRIPTIONS: &str = "This organization has two Team subscriptions. Cancel one in Manage billing."; +const PAYMENT_FAILED: &str = "The Team subscription's last payment failed. Update the card in Manage billing."; + +/// What a subscription event does. +enum Change { + /// Move to a plan, with the Stripe customer and subscription. + Plan { + plan: &'static str, + customer: Option, + subscription: Option, + }, + /// Show a billing problem and pause automatic reloads. + Problem(&'static str), + Nothing, +} + +/// Apply a subscription event created at `created` (Unix seconds) when it's newer than the last one applied: an older +/// one would undo a newer state (a late "active" after a cancellation). The check and the change happen in one +/// transaction with the organization's row locked, so two deliveries handled at once can't interleave. `false` when +/// it was older. A plan change emails the billing contact afterwards. +async fn subscription_event(org_id: i64, created: i64, change: Change) -> laravel::Result { + let changed = db::transaction(async |tx| { + let Some(row) = db::query!( + tx, + "SELECT plan, (stripe_event_at IS NULL OR stripe_event_at <= to_timestamp({created})) AS fresh \ + FROM organizations WHERE id = {org_id} FOR UPDATE" + ) + .select_one() + .await? + else { + return Ok(None); + }; + if !row.try_get::("fresh")? { + return Ok(None); + } + let before: String = row.try_get("plan")?; + db::query!(tx, "UPDATE organizations SET stripe_event_at = to_timestamp({created}) WHERE id = {org_id}") + .update() + .await?; + match &change { + Change::Plan { plan, customer, subscription } => { + let plan: &str = plan; + db::query!( + tx, + "UPDATE organizations SET plan = {plan}, \ + stripe_customer_id = COALESCE({customer}, stripe_customer_id), \ + stripe_subscription_id = {subscription}, updated_at = now() WHERE id = {org_id}" + ) + .update() + .await?; + } + Change::Problem(message) => { + let message: &str = message; + db::query!( + tx, + "UPDATE organizations SET billing_problem = {message}, reloads_paused_at = now(), \ + updated_at = now() WHERE id = {org_id}" + ) + .update() + .await?; + } + Change::Nothing => {} + } + Ok(Some(before)) + }) + .await?; + let Some(before) = changed else { return Ok(false) }; + match change { + Change::Plan { plan, .. } => { + tracing::info!(org_id, plan, "plan changed"); + if before != plan { + let kind = Kind::PlanChanged { + from: plan_by_id(&before).name.to_string(), + to: plan_by_id(plan).name.to_string(), + }; + notify::queue(&kind, To::Billing(org_id), None, &format!("plan_changed:{org_id}:{plan}:{created}")) + .await?; + } + } + Change::Problem(message) => tracing::warn!(org_id, message, "billing problem"), + Change::Nothing => {} + } + Ok(true) +} + +/// What an event about subscription `id` may do: `Current` when it's the organization's subscription (or it has +/// none), `Other` when the organization pays through another one. +enum Which { + Current, + Other, +} + +async fn which_subscription(org_id: i64, id: Option<&str>) -> laravel::Result { + let current: Option = db::query!("SELECT stripe_subscription_id FROM organizations WHERE id = {org_id}") + .scalar::>() + .await? + .flatten(); + Ok(match current { + Some(current) if Some(current.as_str()) != id => Which::Other, + _ => Which::Current, + }) +} + +/// Show a billing problem on the organization's pages, and pause automatic reloads. +/// +/// # Errors +/// On a database error. +pub async fn record_payment_problem(org_id: i64, message: &str) -> laravel::Result<()> { + db::query!( + "UPDATE organizations SET billing_problem = {message}, reloads_paused_at = now(), updated_at = now() \ + WHERE id = {org_id}" + ) + .update() + .await?; + tracing::warn!(org_id, message, "billing problem"); + Ok(()) +} + +/// Stripe's `t=,v1=` signature, within five minutes of `now`, compared in constant time. +#[must_use] +pub fn verify_signature(secret: &str, header: &str, payload: &[u8], now: i64) -> bool { + let mut timestamp = None; + let mut signatures = Vec::new(); + for part in header.split(',') { + match part.split_once('=') { + Some(("t", t)) => timestamp = t.parse::().ok(), + Some(("v1", s)) => signatures.push(s.to_string()), + _ => {} + } + } + let Some(t) = timestamp else { return false }; + if (now - t).abs() > 300 { + return false; + } + let Ok(mut mac) = Hmac::::new_from_slice(secret.as_bytes()) else { return false }; + mac.update(format!("{t}.").as_bytes()); + mac.update(payload); + let expected = hex::encode(mac.finalize().into_bytes()); + signatures + .iter() + .any(|s| s.len() == expected.len() && s.bytes().zip(expected.bytes()).fold(0u8, |a, (x, y)| a | (x ^ y)) == 0) +} diff --git a/app/src/config.rs b/app/src/config.rs index 635ffca6..16ee0e7c 100644 --- a/app/src/config.rs +++ b/app/src/config.rs @@ -21,3 +21,87 @@ pub struct Storage { #[env("S3_SECRET_ACCESS_KEY", required)] pub secret_access_key: String, } + +/// The renderers' API (`/internal/renderer`): the shared token renderers claim work with, the metrics scraper's own +/// token, and the renderer image's version, part of every render's cache key. +#[derive(Clone, Debug, Section)] +pub struct Renderer { + /// Required: without it, nobody could claim renders, and an empty token would match nothing anyway. + #[env("RENDERER_TOKEN", required)] + pub token: String, + /// The renderer version documents are drawn with: part of the render cache key, and what a renderer's claim must + /// match exactly. Required: the app doesn't start without it. + #[env("RENDERER_VERSION", required)] + pub version: String, + /// Empty turns the metrics endpoint off (no token matches it). + #[env("METRICS_TOKEN", default = "")] + pub metrics_token: String, +} + +/// Cloudflare, for purging public gallery URLs after a change (`jobs::purge_gallery`). Empty in development: nothing is +/// purged. +#[derive(Clone, Debug, Section)] +pub struct Cloudflare { + #[env("VISUALCI_CLOUDFLARE_ZONE_ID", default = "")] + pub zone_id: String, + #[env("VISUALCI_CLOUDFLARE_PURGE_TOKEN", default = "")] + pub purge_token: String, +} + +/// Cloudflare's published edge ranges (https://www.cloudflare.com/ips/), for [`Gallery::cloudflare_ip_ranges`]. +pub const CLOUDFLARE_IP_RANGES: &str = "173.245.48.0/20,103.21.244.0/22,103.22.200.0/22,103.31.4.0/22,141.101.64.0/18,\ +108.162.192.0/18,190.93.240.0/20,188.114.96.0/20,197.234.240.0/22,198.41.128.0/17,162.158.0.0/15,104.16.0.0/13,\ +104.24.0.0/14,172.64.0.0/13,131.0.72.0/22,2400:cb00::/32,2606:4700::/32,2803:f800::/32,2405:b500::/32,2405:8100::/32,\ +2a06:98c0::/29,2c0f:f248::/32"; + +/// The public gallery (`http::gallery`). +#[derive(Clone, Debug, Section)] +pub struct Gallery { + /// The networks whose `cf-connecting-ip` header is believed: Cloudflare's edge, comma-separated. A request from + /// anywhere else is limited by its own address, so a client can't rotate the header to dodge the rate limit. + #[env("VISUALCI_CLOUDFLARE_IP_RANGES", default = "")] + pub cloudflare_ip_ranges: String, + /// The most gallery credits one project is charged in a day: images past it are served free. + #[env("VISUALCI_GALLERY_DAILY_CREDITS", default = 50_000)] + pub daily_credits: i64, +} + +impl Gallery { + /// The Cloudflare networks: the configured ones, else the published list. + #[must_use] + pub fn cloudflare_networks(&self) -> Vec { + let list = + if self.cloudflare_ip_ranges.trim().is_empty() { CLOUDFLARE_IP_RANGES } else { &self.cloudflare_ip_ranges }; + list.split(',').filter_map(|n| n.trim().parse().ok()).collect() + } +} + +/// The proxies in front of the app whose `X-Forwarded-For` is believed (`TRUSTED_PROXIES`, comma-separated; the +/// cluster's network by default). Behind them, a request's address is the nearest one that isn't a trusted proxy: +/// Cloudflare's edge, or a client that reached the ingress directly. +#[must_use] +pub fn trusted_proxies() -> Vec { + std::env::var("TRUSTED_PROXIES") + .unwrap_or_else(|_| "10.0.0.0/8".to_string()) + .split(',') + .map(|p| p.trim().to_string()) + .filter(|p| !p.is_empty()) + .collect() +} + +/// The database: `Database::from_env` (`DATABASE_URL`, `DB_MAX_CONNECTIONS`, default 10 per process), with a short wait +/// for a pooled connection (`DB_ACQUIRE_TIMEOUT`, seconds, default 5). A burst of CI builds that takes every +/// connection then answers 503 with Retry-After at once (`http::busy`), rather than holding each request for the +/// framework's default 30 seconds while the queue grows (today's server hung on 3 Dec 2026, 16:02-16:07 UTC). +#[laravel::config::section] +fn database(env: &laravel::config::Env) -> laravel::config::database::Database { + let mut database = laravel::config::database::Database::from_env(env); + let seconds: u64 = env.get("DB_ACQUIRE_TIMEOUT").unwrap_or(5); + let default = database.default.clone(); + if let Some(connection) = database.connections.remove(&default) { + let seconds = i64::try_from(seconds).unwrap_or(5); + let connection = connection.acquire_timeout(laravel::time::SignedDuration::from_secs(seconds)); + database.connections.insert(default, connection); + } + database +} diff --git a/app/src/console/demo.rs b/app/src/console/demo.rs new file mode 100644 index 00000000..b48f5f37 --- /dev/null +++ b/app/src/console/demo.rs @@ -0,0 +1,28 @@ +//! `demo:reset`, daily: rebuild the public demo, visualci/demo, from scratch (`domain::demo`), undoing anything done to +//! it since. Pushes its result to `VISUALCI_DEMO_HEARTBEAT_URL` (and `_TOKEN`): Gatus alerts on a failed run and on a +//! day with no run. + +use laravel::console::{Console, clap, command}; + +use super::heartbeat; +use crate::domain::demo; +use crate::storage::BlobStore; + +#[derive(clap::Parser)] +#[command(name = "demo:reset")] +pub struct DemoReset; + +#[command] +impl DemoReset { + async fn handle(self, console: &mut Console) -> laravel::Result<()> { + let result = async { + let store = BlobStore::current().await?; + Box::pin(demo::reset(&store, &crate::http::api::builds::renderer_version())).await + } + .await; + heartbeat::push("VISUALCI_DEMO_HEARTBEAT", result.as_ref().map(|_| ()).map_err(ToString::to_string)).await; + let builds = result?; + console.line(format!("demo reset: {}/{} has {builds} builds", demo::ORG, demo::PROJECT)); + Ok(()) + } +} diff --git a/app/src/console/mod.rs b/app/src/console/mod.rs new file mode 100644 index 00000000..aceb8069 --- /dev/null +++ b/app/src/console/mod.rs @@ -0,0 +1,31 @@ +//! The schedule (`laravel schedule:run` every minute, in production a CronJob): the builds sweep every five minutes; +//! retention, the groups check and the demo reset daily. Each run pushes its result to a heartbeat, so a task that +//! failed or stopped running alerts. + +use laravel::schedule::{self, Schedule}; + +// The heartbeat every scheduled task pushes to (`crate::heartbeat`). +pub use crate::heartbeat; +pub mod demo; +pub mod retention; + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.call(sweep_builds).name("builds-sweep").every_five_minutes().without_overlapping().on_one_runner(); + schedule.command("retention:prune").daily_at("03:00").without_overlapping().on_one_runner(); + schedule.command("groups:check").daily_at("04:00").without_overlapping().on_one_runner(); + schedule.command("demo:reset").name("demo-reset").daily_at("05:00").without_overlapping().on_one_runner(); +} + +/// [`crate::domain::processing::sweep`], with its heartbeat (`VISUALCI_BUILDS_EXPIRE_HEARTBEAT_URL` and `_TOKEN`). +/// `/status` reports `oldest_processing_seconds` and `oldest_receiving_seconds`, which stay low while it runs. +async fn sweep_builds() -> laravel::Result<()> { + let outcome = crate::domain::processing::sweep().await; + match &outcome { + Ok(swept) => tracing::info!(?swept, "builds swept"), + Err(e) => tracing::error!(error = %e, "sweeping builds failed"), + } + heartbeat::push("VISUALCI_BUILDS_EXPIRE_HEARTBEAT", outcome.as_ref().map(|_| ()).map_err(ToString::to_string)) + .await; + outcome.map(|_| ()) +} diff --git a/app/src/console/retention.rs b/app/src/console/retention.rs new file mode 100644 index 00000000..959311de --- /dev/null +++ b/app/src/console/retention.rs @@ -0,0 +1,76 @@ +//! Retention's commands, run daily by the schedule (`console`), each pushing its result to its heartbeat. + +use laravel::console::{Console, clap, command}; + +use super::heartbeat; +use crate::domain::{downloads, retention}; +use crate::storage::BlobStore; + +/// `retention:prune`, daily: delete the images, PDFs, render rows and page texts nothing needs any more (see +/// `domain::retention` for what's kept), and bulk downloads older than a day (`domain::downloads`). Pushes its result +/// to `VISUALCI_RETENTION_HEARTBEAT_URL` (and `_TOKEN`): Gatus alerts on a failed run and on a day with no run. +#[derive(clap::Parser)] +#[command(name = "retention:prune")] +pub struct RetentionPrune { + /// Keep every build from this many days (at least 30). + #[arg(long, default_value_t = retention::RETENTION_DAYS)] + days: i32, + /// Only count what would go. + #[arg(long)] + dry_run: bool, +} + +#[command] +impl RetentionPrune { + async fn handle(self, console: &mut Console) -> laravel::Result<()> { + if self.days < 30 { + return Err(laravel::Error::msg("days must be at least 30")); + } + let store = BlobStore::current().await?; + let result = retention::prune(Some(&store), self.days, self.dry_run).await; + if self.dry_run { + console.line(format!("retention (dry run, {} days): would delete {}", self.days, result?)); + return Ok(()); + } + // Bulk downloads older than a day, and their archives. + let pruned = downloads::prune(Some(&store)).await; + let outcome = match (&result, &pruned) { + (Ok(report), _) if report.store_errors > 0 => Err(format!("{} store deletes failed", report.store_errors)), + (Err(e), _) => Err(e.to_string()), + (_, Err(e)) => Err(format!("pruning downloads: {e}")), + _ => Ok(()), + }; + if let Ok(n) = &pruned { + console.line(format!("downloads: deleted {n}")); + } + heartbeat::push("VISUALCI_RETENTION_HEARTBEAT", outcome.clone()).await; + console.line(format!("retention ({} days): deleted {}", self.days, result?)); + outcome.map_err(laravel::Error::msg) + } +} + +/// `groups:check`, nightly: every group a build reads from another build still has rows there +/// ([`retention::empty_groups`], docs/design-storage.md). A group that resolves to no rows shows its build with +/// snapshots missing, so any fails the run and its heartbeat (`VISUALCI_GROUPS_CHECK_HEARTBEAT_URL` and `_TOKEN`). +#[derive(clap::Parser)] +#[command(name = "groups:check")] +pub struct GroupsCheck; + +#[command] +impl GroupsCheck { + async fn handle(self, console: &mut Console) -> laravel::Result<()> { + let outcome = match retention::empty_groups().await { + Ok(empty) if empty.is_empty() => Ok(()), + Ok(empty) => { + let shown: Vec = + empty.iter().take(20).map(|(build, key)| format!("build {build} group {key:?}")).collect(); + Err(format!("{} groups resolve to no rows: {}", empty.len(), shown.join(", "))) + } + Err(e) => Err(e.to_string()), + }; + heartbeat::push("VISUALCI_GROUPS_CHECK_HEARTBEAT", outcome.clone()).await; + outcome.map_err(laravel::Error::msg)?; + console.line("groups:check: every sourced group has its rows"); + Ok(()) + } +} diff --git a/app/src/domain/baselines.rs b/app/src/domain/baselines.rs new file mode 100644 index 00000000..77970602 --- /dev/null +++ b/app/src/domain/baselines.rs @@ -0,0 +1,545 @@ +//! Per-snapshot baselines. +//! +//! A build compares each snapshot with its own baseline, worked out in two layers: +//! +//! 1. **The anchor**: the nearest ancestor commit's completed CI build of the same suite (else the default branch's +//! latest approved one). Every build holds every snapshot (its own rows and the groups it reads from earlier builds, +//! `effective_snapshots`), so the anchor knows each one's approved state at that commit: an approved change is its +//! new version, an unapproved change is the version it was compared with, an unchanged snapshot is itself. +//! 2. **Approvals since**: every approved change is a row in `baselines` (the snapshot, or its removal) with the +//! build, commit, branch, environment and mode it came from. Rows newer than the anchor are laid on top: CI +//! approvals on the build's ancestry, and any approval on the build's own branch. A local approval counts on its +//! own branch only, never through ancestry. +//! +//! Documents and text are the same everywhere and keep one shared set (environment `""`). Screenshots keep a set per +//! environment: CI's comes from the anchor and CI approvals; a laptop's from its own approvals on the branch (or CI +//! approvals on the default branch), falling back to the closest environment's. + +use std::collections::{HashMap, HashSet}; + +use laravel::db; + +use super::environments::{SHARED, search_order}; +use super::snapshots::is_config_item; +use crate::models::{Baseline, Build, Project, Snapshot}; + +/// A snapshot's baseline: the snapshot to compare with, and the approval row it came from (`None` when it came from the +/// anchor build). +#[derive(Clone, Debug)] +pub struct Resolved { + pub row: Option, + pub snapshot: Snapshot, +} + +/// The commit and its ancestors, nearest first. +#[must_use] +pub fn ancestry(build: &Build) -> Vec { + let mut commits = vec![build.commit_sha.clone()]; + commits.extend(build.parent_commits.iter().cloned()); + commits +} + +/// The anchor build: the nearest ancestor commit's completed CI build of this suite, else the default branch's latest +/// approved CI build. +/// +/// # Errors +/// On a database error. +pub async fn anchor(build: &Build, project: &Project) -> laravel::Result> { + let commits = ancestry(build); + let (project_id, name, id) = (build.project_id, build.name.as_str(), build.id); + let candidates: Vec = db::query!( + "SELECT * FROM builds WHERE project_id = {project_id} AND name = {name} AND mode = 'ci' \ + AND state = 'completed' AND id <> {id} AND commit_sha IN ({...commits}) ORDER BY id DESC" + ) + .select_as() + .await?; + if let Some(best) = commits.iter().find_map(|c| candidates.iter().find(|b| &b.commit_sha == c)) { + return Ok(Some(best.clone())); + } + let default_branch = project.default_branch.as_str(); + let fallback: Option = db::query!( + "SELECT * FROM builds WHERE project_id = {project_id} AND name = {name} AND mode = 'ci' \ + AND state = 'completed' AND id <> {id} AND branch = {default_branch} \ + AND review_state IN ('approved', 'auto_approved') AND id < {id} ORDER BY id DESC LIMIT 1" + ) + .select_one_as() + .await?; + Ok(fallback) +} + +/// What a build says about one snapshot's approved state. +enum Said { + /// This version is the approved one. + Is(Box), + /// Its removal was approved: it isn't expected any more. + Removed, + /// Nothing approved here: look in the build's own base. + LookFurther, +} + +/// What one build says about each of its snapshots, its own and those it reads from earlier builds. +async fn effective_one(build: &Build) -> laravel::Result> { + let list: Vec = + super::snapshots::of_build(build.id).await?.into_iter().filter(|s| !is_config_item(s)).collect(); + let all_approved = matches!(build.review_state.as_str(), "approved" | "auto_approved"); + let approved = |s: &Snapshot| all_approved || s.review.as_deref() == Some("approved"); + // Unapproved changes (and failures) stand for the version they were compared with. + let stands_for_base = + |s: &Snapshot| (matches!(s.state.as_str(), "changed" | "removed") && !approved(s)) || s.state == "failed"; + let base_ids: Vec = list.iter().filter(|s| stands_for_base(s)).filter_map(|s| s.base_snapshot_id).collect(); + let bases = load(&base_ids).await?; + Ok(list + .into_iter() + .map(|s| { + let key = (s.name.clone(), s.platform.clone()); + let said = if stands_for_base(&s) { + s.base_snapshot_id + .and_then(|id| bases.get(&id).cloned()) + .map_or(Said::LookFurther, |b| Said::Is(Box::new(b))) + } else if s.state == "removed" && approved(&s) { + Said::Removed + } else if s.state == "added" && !approved(&s) { + Said::LookFurther + } else { + Said::Is(Box::new(s)) + }; + (key, said) + }) + .collect()) +} + +/// Snapshots by id (real rows: a base or baseline id is always one). +async fn load(ids: &[i64]) -> laravel::Result> { + let mut out = HashMap::new(); + for chunk in ids.chunks(10_000) { + for s in Snapshot::query().filter(Snapshot::id.is_in(chunk.to_vec())).get().await? { + out.insert(s.id, s); + } + } + Ok(out) +} + +/// Each snapshot's approved state in the anchor build, keyed by (name, platform). An unapproved addition in a pending +/// build says nothing, so those snapshots are looked up in the anchor's own base build, and so on back: a chain of +/// unreviewed builds never hides an older approval. +async fn effective( + anchor: &Build, + for_build: &Build, + project: &Project, +) -> laravel::Result> { + // Only builds on the resolving build's history count: its ancestors, its branch, the default branch. + let ancestors: HashSet = ancestry(for_build).into_iter().collect(); + let counts = |b: &Build| { + ancestors.contains(&b.commit_sha) || b.branch == for_build.branch || b.branch == project.default_branch + }; + let mut out = HashMap::new(); + let mut pending: Option> = None; + let mut seen = HashSet::new(); + let mut build = anchor.clone(); + for _ in 0..50 { + if !seen.insert(build.id) { + break; + } + let mut still = HashSet::new(); + for (key, said) in effective_one(&build).await? { + if pending.as_ref().is_some_and(|p| !p.contains(&key)) { + continue; + } + match said { + Said::Is(s) => { + out.insert(key, *s); + } + Said::Removed => {} + Said::LookFurther => { + still.insert(key); + } + } + } + // Snapshots this build didn't have at all stay unresolved too. + if let Some(p) = &pending { + for key in p { + if !out.contains_key(key) && !still.contains(key) { + still.insert(key.clone()); + } + } + } + if still.is_empty() { + break; + } + let Some(base_id) = build.base_build_id else { break }; + let Some(base) = Build::find(base_id).await? else { break }; + if !counts(&base) { + break; + } + build = base; + pending = Some(still); + } + Ok(out) +} + +/// The baseline of every snapshot the build could compare against, keyed by (name, platform), and the anchor build. +/// Snapshots whose removal was approved are left out. +/// +/// # Errors +/// On a database error. +pub async fn resolve( + build: &Build, + project: &Project, +) -> laravel::Result<(HashMap<(String, String), Resolved>, Option)> { + let anchor = anchor(build, project).await?; + let from_anchor = match &anchor { + Some(a) => effective(a, build, project).await?, + None => HashMap::new(), + }; + let after = anchor.as_ref().map_or(0, |a| a.id); + + // Approvals newer than the anchor: CI ones on the ancestry, and any on this branch. A merged pull request's + // approvals count only through their merge commit's place in this build's history. For local environments also + // older ones, since the anchor (a CI build) doesn't carry their screenshots. Local approvals apply only to their + // own branch; on the default branch only CI approvals count for other branches. + let history = ancestry(build); + let (project_id, build_name, id, branch, default_branch) = + (build.project_id, build.name.as_str(), build.id, build.branch.as_str(), project.default_branch.as_str()); + let rows: Vec = db::query!( + "SELECT * FROM baselines WHERE project_id = {project_id} AND build_name = {build_name} AND build_id <> {id} \ + AND ( \ + (build_id > {after} AND approval <> 'merged' \ + AND ((mode = 'ci' AND commit_sha IN ({...history})) OR branch = {branch})) \ + OR (approval = 'merged' AND commit_sha IN ({...history})) \ + OR (environment NOT IN ('', 'ci') AND (branch = {branch} OR (branch = {default_branch} AND mode = 'ci'))) \ + ) ORDER BY id" + ) + .select_as() + .await?; + + // A merged pull request's approvals count until the anchor is at or past the merge: then the anchor carries them, + // and a later approval must win. + let anchor_history: HashSet = anchor.as_ref().map(ancestry).unwrap_or_default().into_iter().collect(); + let merged_and_new = |r: &Baseline| r.approval == "merged" && !anchor_history.contains(&r.commit_sha); + let rows: Vec = rows.into_iter().filter(|r| r.approval != "merged" || merged_and_new(r)).collect(); + + // The latest row per (name, platform, environment); rows newer than the anchor or on this branch win over older + // default-branch ones. + let mut latest: HashMap<(String, String, String), Baseline> = HashMap::new(); + let rank = |r: &Baseline| (r.build_id > after || r.branch == build.branch || merged_and_new(r), r.id); + // Between two merged pull requests' approvals, the nearer merge in this build's history wins (it was merged later + // on this line), whatever order the webhooks arrived in. + let nearness = |r: &Baseline| history.iter().position(|c| c == &r.commit_sha).unwrap_or(usize::MAX); + let better = |new: &Baseline, old: &Baseline| { + if new.approval == "merged" && old.approval == "merged" && nearness(new) != nearness(old) { + nearness(new) < nearness(old) + } else { + rank(old) < rank(new) + } + }; + for row in rows { + let key = (row.name.clone(), row.platform.clone(), row.environment.clone()); + if latest.get(&key).is_none_or(|existing| better(&row, existing)) { + latest.insert(key, row); + } + } + + let mut names: Vec<(String, String)> = from_anchor.keys().cloned().collect(); + names.extend(latest.keys().map(|(n, p, _)| (n.clone(), p.clone()))); + names.sort(); + names.dedup(); + + let mut chosen: HashMap<(String, String), (Option, Option)> = HashMap::new(); + for key in names { + let anchor_snapshot = from_anchor.get(&key); + let shared = anchor_snapshot.map_or_else( + || latest.keys().any(|(n, p, e)| (n, p) == (&key.0, &key.1) && e == SHARED), + |s| s.environment == SHARED, + ); + let order = if shared { search_order(SHARED) } else { search_order(&build.environment) }; + let pick = order.iter().find_map(|env| { + let row = latest.get(&(key.0.clone(), key.1.clone(), env.clone())); + if env == SHARED || env == "ci" { + // CI's set and the shared set: a newer approval, else the anchor's snapshot. + match row { + Some(r) => Some((Some(r.clone()), r.snapshot_id)), + None => anchor_snapshot.filter(|s| &s.environment == env).map(|s| (None, Some(s.id))), + } + } else { + row.map(|r| (Some(r.clone()), r.snapshot_id)) + } + }); + if let Some(p) = pick { + chosen.insert(key, p); + } + } + + // Last: a snapshot this build sent that has no baseline on its history takes the suite's latest current CI + // approval of it from any branch. That's a squash-merged pull request's approval: its commits aren't ancestors of + // the default branch's, but what it approved is what the default branch now has. + let sent: Vec<(String, String, String)> = Snapshot::query() + .filter(Snapshot::build_id.eq(build.id) & Snapshot::carried_forward.eq(false)) + .get() + .await? + .into_iter() + .filter(|s| !is_config_item(s)) + .map(|s| (s.name, s.platform, s.environment)) + .collect(); + let missing: Vec<&(String, String, String)> = + sent.iter().filter(|(n, p, _)| !chosen.contains_key(&(n.clone(), p.clone()))).collect(); + if !missing.is_empty() { + let mut names: Vec = missing.iter().map(|(n, _, _)| n.clone()).collect(); + names.sort(); + names.dedup(); + let mut rows: Vec = Vec::new(); + for chunk in names.chunks(10_000) { + let chunk = chunk.to_vec(); + let found: Vec = db::query!( + "SELECT DISTINCT ON (name, platform, environment) * FROM baselines bl \ + WHERE project_id = {project_id} AND build_name = {build_name} AND build_id <> {id} AND mode = 'ci' \ + AND name IN ({...chunk}) \ + AND NOT EXISTS (SELECT 1 FROM baselines b2 WHERE b2.project_id = bl.project_id \ + AND b2.build_name = bl.build_name AND b2.name = bl.name AND b2.platform = bl.platform \ + AND b2.environment = bl.environment AND b2.branch = bl.branch AND b2.id > bl.id) \ + ORDER BY name, platform, environment, id DESC" + ) + .select_as() + .await?; + rows.extend(found); + } + for (name, platform, environment) in missing { + let order = search_order(environment); + let row = order.iter().find_map(|env| { + rows.iter().find(|r| &r.name == name && &r.platform == platform && &r.environment == env) + }); + if let Some(r) = row.filter(|r| r.snapshot_id.is_some()) { + chosen.insert((name.clone(), platform.clone()), (Some(r.clone()), r.snapshot_id)); + } + } + } + + let ids: Vec = chosen.values().filter_map(|(_, id)| *id).collect(); + let mut snapshots = load(&ids).await?; + let resolved = chosen + .into_iter() + .filter_map(|(key, (row, id))| { + // A removal ends the lookup: the snapshot isn't expected any more. + let snapshot = id.and_then(|id| snapshots.remove(&id))?; + Some((key, Resolved { row, snapshot })) + }) + .collect(); + Ok((resolved, anchor)) +} + +/// Whether a build's working tree had uncommitted changes (local builds only). +fn dirty(build: &Build) -> bool { + build.mode == "local" && build.environment_info.get("dirty").and_then(serde_json::Value::as_bool) == Some(true) +} + +struct NewRow { + project_id: i64, + build_name: String, + name: String, + platform: String, + environment: String, + branch: String, + commit_sha: String, + build_id: i64, + snapshot_id: Option, + approved_by: Option, + review_id: Option, + approval: String, + mode: String, +} + +/// Record approved snapshots as baselines: changed and added ones as themselves, removed ones as their removal. +/// Unchanged snapshots already match a baseline and aren't recorded again. Returns how many were left out: a local +/// build with uncommitted changes can only approve its own environment's screenshots, never the shared set or CI's. +/// +/// # Errors +/// On a database error. +pub async fn record( + build: &Build, + approved: &[&Snapshot], + approved_by: Option, + review_id: Option, + approval: &str, +) -> laravel::Result { + let changes: Vec<&Snapshot> = approved + .iter() + .copied() + .filter(|s| matches!(s.state.as_str(), "changed" | "added" | "removed") && !is_config_item(s)) + .collect(); + let allowed = |s: &Snapshot| !dirty(build) || (s.environment != SHARED && s.environment != "ci"); + let rows: Vec = changes + .iter() + .filter(|s| allowed(s)) + .map(|s| NewRow { + project_id: build.project_id, + build_name: build.name.clone(), + name: s.name.clone(), + platform: s.platform.clone(), + environment: s.environment.clone(), + branch: build.branch.clone(), + commit_sha: build.commit_sha.clone(), + build_id: build.id, + snapshot_id: (s.state != "removed").then_some(s.id), + approved_by, + review_id, + approval: approval.to_string(), + mode: build.mode.clone(), + }) + .collect(); + let skipped = changes.len() - rows.len(); + // 13 parameters a row, well under PostgreSQL's 65,535. + for chunk in rows.chunks(4000) { + db::query!( + "INSERT INTO baselines (project_id, build_name, name, platform, environment, branch, commit_sha, build_id, \ + snapshot_id, approved_by, review_id, approval, mode) \ + VALUES {...chunk(project_id, build_name, name, platform, environment, branch, commit_sha, build_id, \ + snapshot_id, approved_by, review_id, approval, mode)}" + ) + .insert() + .await?; + } + Ok(skipped) +} + +/// A pull request was merged: its branch's current CI approvals become the base branch's at the merge commit, so the +/// base branch's next build compares with what the pull request approved, even after a squash merge. Safe to call twice +/// for the same merge. Returns how many it recorded. +/// +/// # Errors +/// On a database error. +pub async fn record_merge( + project_id: i64, + head_branch: &str, + base_branch: &str, + merge_commit: &str, +) -> laravel::Result { + let done = db::query!( + "INSERT INTO baselines (project_id, build_name, name, platform, environment, branch, commit_sha, build_id, \ + snapshot_id, approved_by, review_id, approval, mode, created_at) \ + SELECT project_id, build_name, name, platform, environment, {base_branch}, {merge_commit}, build_id, snapshot_id, \ + approved_by, review_id, 'merged', 'ci', now() \ + FROM (SELECT DISTINCT ON (build_name, name, platform, environment) * FROM baselines \ + WHERE project_id = {project_id} AND branch = {head_branch} AND mode = 'ci' \ + ORDER BY build_name, name, platform, environment, id DESC) latest \ + WHERE NOT EXISTS (SELECT 1 FROM baselines m WHERE m.project_id = {project_id} AND m.approval = 'merged' \ + AND m.commit_sha = {merge_commit})" + ) + .insert() + .await?; + Ok(done.rows_affected()) +} + +/// Withdraw the baselines a build's approval of these snapshots made: they were rejected after all. +/// +/// # Errors +/// On a database error. +pub async fn withdraw(build: &Build, rejected: &[&Snapshot]) -> laravel::Result<()> { + let id = build.id; + for s in rejected { + let (name, platform) = (s.name.as_str(), s.platform.as_str()); + db::query!("DELETE FROM baselines WHERE build_id = {id} AND name = {name} AND platform = {platform}") + .delete() + .await?; + } + Ok(()) +} + +/// For baseline rows that came from local approvals: "approved locally by nathan on macbook (local-mac)", by row id. +/// +/// # Errors +/// On a database error. +pub async fn local_notes(ids: &[i64]) -> laravel::Result> { + if ids.is_empty() { + return Ok(HashMap::new()); + } + let ids = ids.to_vec(); + let rows = db::query!( + "SELECT bl.id, b.environment, b.environment_info->>'user' AS who, b.environment_info->>'machine' AS machine \ + FROM baselines bl JOIN builds b ON b.id = bl.build_id WHERE bl.id IN ({...ids}) AND bl.mode = 'local'" + ) + .select() + .await?; + let mut out = HashMap::new(); + for r in rows { + let id: i64 = r.try_get("id")?; + let env: String = r.try_get("environment")?; + let who: Option = r.try_get("who")?; + let machine: Option = r.try_get("machine")?; + let mut note = "approved locally".to_string(); + if let Some(w) = who { + note.push_str(&format!(" by {w}")); + } + if let Some(m) = machine { + note.push_str(&format!(" on {m}")); + } + note.push_str(&format!(" ({env})")); + out.insert(id, note); + } + Ok(out) +} + +/// Where a snapshot's new version was already approved: the same name and platform, the same content (its +/// fingerprint), approved in a review on another branch. A hint for the reviewer: it approves nothing. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub struct ApprovedElsewhere { + pub branch: String, + pub pr_number: Option, + /// The build it was approved in, and the snapshot there. + pub build: i32, + pub snapshot_id: laravel::str::Uuid, + /// Who approved it ("Claude Code for Ada Lovelace"). + pub approved_by: Option, + pub approved_at: String, +} + +/// For a build's changed and added snapshots, and those that passed by matching an approval elsewhere, the newest +/// matching approval on another branch, by snapshot id. Changes are always the build's own rows. +/// +/// # Errors +/// On a database error. +pub async fn approved_elsewhere(build_id: i64) -> laravel::Result> { + let rows = db::query!( + "SELECT DISTINCT ON (s.id) s.id AS snapshot_id, bl.branch, b2.pr_number, b2.number, s2.pid AS other, \ + u.name AS approver, r.source, r.client_name, r.agent, r.token_name, bl.created_at \ + FROM snapshots s \ + JOIN builds b ON b.id = s.build_id \ + JOIN baselines bl ON bl.project_id = b.project_id AND bl.build_name = b.name AND bl.name = s.name \ + AND bl.platform = s.platform \ + AND bl.approval = 'review' AND bl.branch <> b.branch AND bl.snapshot_id IS NOT NULL \ + JOIN snapshots s2 ON s2.id = bl.snapshot_id AND s2.source_fingerprint = s.source_fingerprint \ + JOIN builds b2 ON b2.id = bl.build_id \ + LEFT JOIN users u ON u.id = bl.approved_by \ + LEFT JOIN reviews r ON r.id = bl.review_id \ + WHERE s.build_id = {build_id} AND (s.state IN ('changed', 'added') \ + OR EXISTS (SELECT 1 FROM snapshot_pages p WHERE p.snapshot_id = s.id AND p.state = 'variant')) \ + ORDER BY s.id, bl.created_at DESC" + ) + .select() + .await?; + let mut out = HashMap::new(); + for r in rows { + let at: laravel::time::Timestamp = r.try_get("created_at")?; + let person: Option = r.try_get("approver")?; + let approved_by = match r.try_get::>("source")? { + Some(source) => Some(super::reviews::by( + &source, + r.try_get::>("client_name")?.as_deref(), + r.try_get::>("agent")?.as_deref(), + r.try_get::>("token_name")?.as_deref(), + person.as_deref(), + )), + None => person, + }; + out.insert( + r.try_get::("snapshot_id")?, + ApprovedElsewhere { + branch: r.try_get("branch")?, + pr_number: r.try_get("pr_number")?, + build: r.try_get("number")?, + snapshot_id: r.try_get("other")?, + approved_by, + approved_at: at.to_string(), + }, + ); + } + Ok(out) +} diff --git a/app/src/domain/blobs.rs b/app/src/domain/blobs.rs index c35324d7..64b050e8 100644 --- a/app/src/domain/blobs.rs +++ b/app/src/domain/blobs.rs @@ -7,14 +7,19 @@ use laravel::model::update; use crate::models::Blob; use crate::storage::BlobStore; -/// Record a blob a client or renderer is about to upload (or already has). Returns it. +/// Record a blob a client or renderer is about to upload (or already has). Returns it. A blob retention marked for +/// deletion loses the mark and counts as not uploaded, so the client uploads it again. Registering also renews +/// `updated_at` (at most hourly), and retention doesn't mark a blob registered in the last day, so a file a build is +/// about to name is never deleted under it. /// /// # Errors /// On a database error. pub async fn register(sha256: &str, size: i64, content_type: &str) -> laravel::Result { db::query!( "INSERT INTO blobs (sha256, size, content_type) VALUES ({sha256}, {size}, {content_type}) \ - ON CONFLICT (sha256) DO NOTHING" + ON CONFLICT (sha256) DO UPDATE SET deleting = false, updated_at = now(), \ + uploaded_at = CASE WHEN blobs.deleting THEN NULL ELSE blobs.uploaded_at END \ + WHERE blobs.deleting OR blobs.updated_at < now() - interval '1 hour'" ) .insert() .await?; @@ -23,7 +28,7 @@ pub async fn register(sha256: &str, size: i64, content_type: &str) -> laravel::R #[must_use] pub fn is_uploaded(blob: &Blob) -> bool { - blob.uploaded_at.is_some() + blob.uploaded_at.is_some() && !blob.deleting } /// Which of these blobs exist (retention deletes old ones). diff --git a/app/src/domain/builds.rs b/app/src/domain/builds.rs index 8fdc2696..aedcfb46 100644 --- a/app/src/domain/builds.rs +++ b/app/src/domain/builds.rs @@ -132,6 +132,22 @@ pub async fn create(project: &Project, params: &CreateParams, creator: Option 255 || params.branch.chars().any(char::is_control) { + return invalid("branch must be at most 255 characters"); + } + if params.name.trim().is_empty() || params.name.len() > 100 { + return invalid("name must be 1 to 100 characters"); + } + if params.nonce.as_ref().is_some_and(|n| n.is_empty() || n.len() > 200) { + return invalid("nonce must be 1 to 200 characters"); + } if !(1..=1000).contains(¶ms.shard_total) { return invalid("shard_total must be 1 to 1000"); } @@ -347,3 +363,130 @@ pub async fn finalize_shard(build: Build, shard: Option, allow_empty: bool) .await; result.or_else(server) } + +/// Where the build ran, as someone outside the organization may see it on a public project: the CI provider and the +/// links to the job and the repository, never a local run's user name or machine. +#[must_use] +pub fn environment_info_for(build: &Build, member: bool) -> serde_json::Value { + let info = build.environment_info.clone(); + if member { + return info; + } + let keep = ["provider", "job_url", "repository_url"]; + match info { + serde_json::Value::Object(map) => { + serde_json::Value::Object(map.into_iter().filter(|(k, _)| keep.contains(&k.as_str())).collect()) + } + _ => serde_json::Value::Null, + } +} + +/// A project's build by number (`8` or `#8`) or id. +/// +/// # Errors +/// On a database error. +pub async fn find_by_ref(project_id: i64, reference: &str) -> laravel::Result> { + if let Ok(number) = reference.trim_start_matches('#').parse::() { + return Build::query().filter(Build::project_id.eq(project_id) & Build::number.eq(number)).first().await; + } + let Ok(pid) = laravel::str::Uuid::parse_str(reference) else { return Ok(None) }; + Build::query().filter(Build::project_id.eq(project_id) & Build::pid.eq(pid)).first().await +} + +/// A project's newest builds, newest first: of one branch, and only those waiting for a review, when asked. +/// +/// # Errors +/// On a database error. +pub async fn recent(project_id: i64, branch: Option<&str>, waiting: bool, limit: u64) -> laravel::Result> { + let mut q = Build::query().filter(Build::project_id.eq(project_id)); + if let Some(branch) = branch { + q = q.filter(Build::branch.eq(branch)); + } + if waiting { + q = q.filter(Build::review_state.eq("pending")); + } + q.order_by(Build::id.desc()).limit(limit).get().await +} + +/// The build once it can be reviewed: straight after a run it may still be comparing, so it's waited for up to +/// `timeout`. +/// +/// # Errors +/// `Ok(Err(message))` for a build that isn't finalized, failed, or is still comparing at the deadline; `Err` on a +/// database error. +pub async fn wait_until_reviewable( + build: Build, + timeout: std::time::Duration, +) -> laravel::Result> { + let deadline = std::time::Instant::now() + timeout; + let mut build = build; + loop { + match build.state.as_str() { + "completed" => return Ok(Ok(build)), + "receiving" => { + return Ok(Err(format!( + "build {} isn't finalized yet: run `visualci build finalize` first", + build.number + ))); + } + "failed" => return Ok(Err(format!("build {} failed, so it can't be reviewed", build.number))), + _ if std::time::Instant::now() >= deadline => { + return Ok(Err(format!("build {} is still comparing; try again in a moment", build.number))); + } + _ => { + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + build = Build::find_or_fail(build.id).await?; + } + } + } +} + +/// The warning on a build closed because its pull request was closed without merging. +pub const CLOSED_PULL_REQUEST: &str = "Closed without review: the pull request was closed without merging."; +/// The same, for a build whose branch was deleted. +pub const CLOSED_BRANCH_DELETED: &str = "Closed without review: the branch was deleted."; + +/// A branch's pull request closed without merging (`why` `pull_request`) or the branch deleted (`branch_deleted`): its +/// builds waiting for review in this project stop waiting, and their checks and pull request comment say so +/// (`BuildChanged`). Idempotent: a closed build isn't closed again. Returns how many. +/// +/// # Errors +/// On a database error. +pub async fn close_branch(project_id: i64, branch: &str, why: &str) -> laravel::Result { + let note = if why == "branch_deleted" { CLOSED_BRANCH_DELETED } else { CLOSED_PULL_REQUEST }; + let ids: Vec = db::query!( + "UPDATE builds SET review_state = 'closed', warnings = warnings || jsonb_build_array({note}::TEXT), \ + updated_at = now() \ + WHERE project_id = {project_id} AND branch = {branch} AND review_state = 'pending' RETURNING id" + ) + .select_as() + .await?; + for id in &ids { + crate::events::BuildChanged { build_id: *id }.dispatch().await?; + } + Ok(ids.len()) +} + +/// A closed pull request reopened: its branch's newest closed build waits for review again (older ones stay closed: +/// the newest covers them), without the closing warning. Idempotent: with no closed build, nothing changes. Returns +/// how many (0 or 1). +/// +/// # Errors +/// On a database error. +pub async fn reopen_branch(project_id: i64, branch: &str) -> laravel::Result { + let (pull_request, deleted) = (CLOSED_PULL_REQUEST, CLOSED_BRANCH_DELETED); + let id: Option = db::query!( + "UPDATE builds SET review_state = 'pending', updated_at = now(), \ + warnings = COALESCE((SELECT jsonb_agg(w) FROM jsonb_array_elements(warnings) w \ + WHERE w NOT IN (to_jsonb({pull_request}::TEXT), to_jsonb({deleted}::TEXT))), '[]'::jsonb) \ + WHERE id = (SELECT id FROM builds WHERE project_id = {project_id} AND branch = {branch} \ + AND review_state = 'closed' ORDER BY id DESC LIMIT 1) \ + RETURNING id" + ) + .scalar() + .await?; + if let Some(id) = id { + crate::events::BuildChanged { build_id: id }.dispatch().await?; + } + Ok(usize::from(id.is_some())) +} diff --git a/app/src/domain/changeset.rs b/app/src/domain/changeset.rs new file mode 100644 index 00000000..ae32ba41 --- /dev/null +++ b/app/src/domain/changeset.rs @@ -0,0 +1,163 @@ +//! "This PR vs base": everything a pull request (or branch) changes, across all of its builds, against the baseline +//! it forked from. A per-build diff loses things: a snapshot removed and approved in build 2 looks unchanged by build 5, +//! because build 5 compares with build 2's approvals. Here the base is fixed (what the PR's first build of each suite +//! compared with) and the head is the newest build, so in-PR approvals don't hide anything, and the answer stays the +//! same after the merge. + +use std::collections::{BTreeMap, HashMap}; + +use laravel::db; + +use super::baselines; +use super::snapshots::CONFIG_PLATFORM; +use crate::models::{Build, Project, Snapshot}; + +/// One snapshot the pull request adds, changes or removes. +#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)] +pub struct Entry { + pub name: String, + pub platform: String, + /// `added`, `changed` or `removed`. + pub change: &'static str, + /// Where review stands for it in the newest build: `approved` (there or in an earlier build of the PR), `pending`, + /// `rejected`, or `failed`. + pub review: &'static str, +} + +/// One suite's changeset. +#[derive(Debug, Clone, serde::Serialize)] +pub struct Suite { + pub name: String, + /// The default branch's build the PR forked from, if it had one. + pub base_build: Option, + /// The PR's first and newest builds of the suite. + pub first_build: i32, + pub head_build: i32, + pub builds: usize, + pub entries: Vec, +} + +impl Suite { + #[must_use] + pub fn count(&self, change: &str) -> usize { + self.entries.iter().filter(|e| e.change == change).count() + } +} + +/// What a pull request is: its number, or a branch. +#[derive(Debug, Clone)] +pub enum Target { + Pr(i32), + Branch(String), +} + +/// The changeset of a pull request or branch, one entry per suite (build name), suites by name. Empty when it has +/// no CI builds. +/// +/// # Errors +/// On a database error. +pub async fn changeset(project: &Project, target: &Target) -> laravel::Result> { + let project_id = project.id; + let all: Vec = + match target { + Target::Pr(n) => db::query!( + "SELECT * FROM builds WHERE project_id = {project_id} AND mode = 'ci' AND pr_number = {n} ORDER BY id" + ) + .select_as() + .await?, + Target::Branch(b) => { + db::query!( + "SELECT * FROM builds WHERE project_id = {project_id} AND mode = 'ci' AND branch = {b} ORDER BY id" + ) + .select_as() + .await? + } + }; + let mut by_suite: BTreeMap> = BTreeMap::new(); + for b in all { + by_suite.entry(b.name.clone()).or_default().push(b); + } + let mut out = Vec::new(); + for (name, list) in by_suite { + let (Some(first), Some(head)) = (list.first(), list.last()) else { continue }; + // The base: what the first build compared each snapshot with, at the fork point. + let (base, anchor) = baselines::resolve(first, project).await?; + let base: HashMap<(String, String), Snapshot> = base + .into_iter() + .filter(|(_, r)| r.snapshot.platform != CONFIG_PLATFORM) + .map(|(k, r)| (k, r.snapshot)) + .collect(); + let all_head = super::snapshots::of_build(head.id).await?; + let head_snaps: HashMap<(String, String), Snapshot> = all_head + .iter() + .filter(|&s| s.platform != CONFIG_PLATFORM && s.state != "removed") + .cloned() + .map(|s| ((s.name.clone(), s.platform.clone()), s)) + .collect(); + // Review state: the newest build's verdict, or "approved" when an earlier build of the PR approved it (the + // newest then shows it unchanged against that approval). + let review_of = |s: Option<&Snapshot>, head_removed: Option<&Snapshot>| -> &'static str { + let s = s.or(head_removed); + match s { + Some(s) if s.state == "failed" => "failed", + Some(s) if s.review.as_deref() == Some("rejected") || head.review_state == "rejected" => "rejected", + Some(s) if s.state == "unchanged" => "approved", + Some(s) + if s.review.as_deref() == Some("approved") + || matches!(head.review_state.as_str(), "approved" | "auto_approved") => + { + "approved" + } + Some(_) => "pending", + // Gone from the newest build without being reported removed there: removed and approved earlier. + None => "approved", + } + }; + let head_removed: HashMap<(String, String), Snapshot> = all_head + .into_iter() + .filter(|s| s.state == "removed") + .map(|s| ((s.name.clone(), s.platform.clone()), s)) + .collect(); + let mut keys: Vec<(String, String)> = base.keys().chain(head_snaps.keys()).cloned().collect(); + keys.sort(); + keys.dedup(); + let mut entries = Vec::new(); + for key in keys { + let change = match (base.get(&key), head_snaps.get(&key)) { + (None, Some(_)) => "added", + (Some(_), None) => "removed", + (Some(b), Some(h)) if b.source_fingerprint != h.source_fingerprint => "changed", + _ => continue, + }; + entries.push(Entry { + name: key.0.clone(), + platform: key.1.clone(), + change, + review: review_of(head_snaps.get(&key), head_removed.get(&key)), + }); + } + out.push(Suite { + name, + base_build: anchor.map(|a| a.number), + first_build: first.number, + head_build: head.number, + builds: list.len(), + entries, + }); + } + Ok(out) +} + +/// The changeset as JSON, for the web app and MCP. +#[must_use] +pub fn json(suites: &[Suite]) -> serde_json::Value { + serde_json::json!({ + "suites": suites.iter().map(|s| serde_json::json!({ + "name": s.name, "base_build": s.base_build, "first_build": s.first_build, "head_build": s.head_build, + "builds": s.builds, + "counts": { "added": s.count("added"), "changed": s.count("changed"), "removed": s.count("removed") }, + "pending": s.entries.iter().filter(|e| e.review == "pending").count(), + "entries": s.entries, + })).collect::>(), + }) +} diff --git a/app/src/domain/comments.rs b/app/src/domain/comments.rs new file mode 100644 index 00000000..d87326ab --- /dev/null +++ b/app/src/domain/comments.rs @@ -0,0 +1,380 @@ +//! Comment threads pinned to pixels. A thread is on one snapshot (name and platform) of a project's branch, so it +//! follows the branch: it shows on every newer build of that snapshot there. It's pinned to a point, a box or the whole +//! image, on a page's base or head side (coordinates in that image's pixels). An open thread blocks approving its +//! snapshot ([`open_on`]), so a person's question stops an agent's approval until someone answers and resolves it. + +use std::collections::HashMap; + +use laravel::db; +use laravel::model::{create, update}; +use laravel::str::Uuid; +use serde::Deserialize; + +use crate::models::{Build, Comment, CommentThread, Snapshot, User}; + +/// Where a thread is pinned, in pixels of the pinned side's own image (base or head), from its top left. Pixels, not +/// fractions: when a full-page screenshot grows at the bottom in a later build of the branch, a pin stays on the same +/// content. They're also the units of the regions `get_snapshot` gives. +#[derive(Debug, Clone, PartialEq, Deserialize, schemars::JsonSchema)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum Anchor { + /// The whole image. + Image, + /// A point. + Point { x: f64, y: f64 }, + /// A box: its top left corner, width and height. + Box { x: f64, y: f64, w: f64, h: f64 }, +} + +impl Anchor { + /// # Errors + /// A message when it isn't inside the image (`size` is the image's width and height, when known). + pub fn validate(&self, size: Option<(f64, f64)>) -> Result<(), String> { + let (w_max, h_max) = size.unwrap_or((f64::MAX, f64::MAX)); + let within = |x: f64, y: f64| x >= 0.0 && y >= 0.0 && x <= w_max && y <= h_max; + let ok = match self { + Self::Image => true, + Self::Point { x, y } => within(*x, *y), + Self::Box { x, y, w, h } => *w > 0.0 && *h > 0.0 && within(*x, *y) && within(x + w, y + h), + }; + if ok { + return Ok(()); + } + Err(match size { + Some((w, h)) => format!("the anchor is outside the image: it's {w}×{h} pixels, from the top left"), + None => "anchor coordinates are pixels from the image's top left, so they can't be negative".into(), + }) + } + + fn json(&self) -> serde_json::Value { + match self { + Self::Image => serde_json::json!({ "kind": "image" }), + Self::Point { x, y } => serde_json::json!({ "kind": "point", "x": x, "y": y }), + Self::Box { x, y, w, h } => serde_json::json!({ "kind": "box", "x": x, "y": y, "w": w, "h": h }), + } + } +} + +/// The pixel size of one side of a snapshot's page, when it has an image there. +async fn image_size(snapshot: &Snapshot, page: i32, side: &str) -> laravel::Result> { + let pages = super::pages::of_many(None, &[snapshot]).await?; + let row = pages.get(&snapshot.id).and_then(|p| p.iter().find(|r| r.position == page)).cloned(); + let sha = row.and_then(|r| if side == "base" { r.base_image } else { r.head_image }); + let Some(sha) = sha else { return Ok(None) }; + let blob = crate::models::Blob::find(sha).await?; + Ok(blob.and_then(|b| Some((f64::from(b.width?), f64::from(b.height?))))) +} + +/// Who wrote a comment: a person in the web app, or an agent (MCP or the API) acting for one or for a project token. +#[derive(Debug, Clone)] +pub struct Author { + pub user_id: Option, + pub agent: Option, +} + +impl Author { + const fn kind(&self) -> &'static str { + if self.agent.is_some() { "agent" } else { "person" } + } +} + +/// Where a new thread goes. +#[derive(Debug, Clone)] +pub struct Place { + pub page: Option, + pub side: String, + pub anchor: Anchor, +} + +const MAX_BODY: usize = 10_000; + +fn clean_body(body: &str) -> Result { + let body = body.trim(); + if body.is_empty() || body.len() > MAX_BODY { + return Err(format!("a comment is 1 to {MAX_BODY} characters of Markdown")); + } + Ok(body.to_string()) +} + +async fn add_comment(thread_id: i64, author: &Author, body: String) -> laravel::Result { + create!(Comment { + pid: laravel::str::uuid7(), + thread_id: thread_id, + user_id: author.user_id, + author_kind: author.kind(), + agent: author.agent.clone(), + body: body, + }) + .await +} + +/// Start a thread on a build's snapshot. +/// +/// # Errors +/// `Ok(Err(message))` for a bad anchor, side or body; `Err` on a database error. +pub async fn start( + build: &Build, + snapshot: &Snapshot, + place: &Place, + author: &Author, + body: &str, +) -> laravel::Result> { + if !matches!(place.side.as_str(), "base" | "head") { + return Ok(Err("side is base or head".into())); + } + // A pin is on one page: a single image's, unless the caller names another. + let page = match (&place.anchor, place.page) { + (Anchor::Image, p) => p, + (_, Some(p)) => Some(p), + (_, None) => Some(0), + }; + let size = match page { + Some(p) => image_size(snapshot, p, &place.side).await?, + None => None, + }; + if let Err(m) = place.anchor.validate(size) { + return Ok(Err(m)); + } + let body = match clean_body(body) { + Ok(b) => b, + Err(m) => return Ok(Err(m)), + }; + let thread = db::transaction(async |_| { + let thread = create!(CommentThread { + pid: laravel::str::uuid7(), + project_id: build.project_id, + branch: build.branch.as_str(), + snapshot_name: snapshot.name.as_str(), + platform: snapshot.platform.as_str(), + page: page, + side: place.side.as_str(), + anchor: place.anchor.json(), + build_id: Some(build.id), + resolved_at: None, + resolved_by: None, + }) + .await?; + add_comment(thread.id, author, body.clone()).await?; + Ok(thread) + }) + .await?; + Ok(Ok(thread)) +} + +/// The thread with this id in a project. +/// +/// # Errors +/// On a database error. +pub async fn thread(project_id: i64, pid: Uuid) -> laravel::Result> { + CommentThread::query().filter(CommentThread::pid.eq(pid) & CommentThread::project_id.eq(project_id)).first().await +} + +/// Reply in a thread (and reopen it, if it was resolved: a new question needs an answer). +/// +/// # Errors +/// `Ok(Err(message))` for a bad body; `Err` on a database error. +pub async fn reply(mut thread: CommentThread, author: &Author, body: &str) -> laravel::Result> { + let body = match clean_body(body) { + Ok(b) => b, + Err(m) => return Ok(Err(m)), + }; + let comment = add_comment(thread.id, author, body).await?; + update!(thread { resolved_at: None, resolved_by: None }).await?; + Ok(Ok(comment)) +} + +/// A comment in a project, with its thread. +/// +/// # Errors +/// On a database error. +pub async fn comment(project_id: i64, pid: Uuid) -> laravel::Result> { + let Some(c) = Comment::query().filter(Comment::pid.eq(pid)).first().await? else { return Ok(None) }; + let t = CommentThread::find(c.thread_id).await?.filter(|t| t.project_id == project_id); + Ok(t.map(|t| (c, t))) +} + +/// Whether `author` wrote the comment: the same person, or, for an agent's comment made with a project token (no +/// person), the project's tokens. Never a person's comment whose account is gone: that stays theirs, for an admin to +/// delete. +#[must_use] +pub fn wrote(c: &Comment, author: &Author) -> bool { + match c.user_id { + Some(id) => author.user_id == Some(id), + None => author.user_id.is_none() && c.author_kind == "agent", + } +} + +/// Edit a comment (its author only). +/// +/// # Errors +/// `Ok(Err(message))` when it's someone else's or the body is bad; `Err` on a database error. +pub async fn edit(mut c: Comment, author: &Author, body: &str) -> laravel::Result> { + if !wrote(&c, author) { + return Ok(Err("only its author can edit a comment".into())); + } + let body = match clean_body(body) { + Ok(b) => b, + Err(m) => return Ok(Err(m)), + }; + update!(c { body }).await?; + Ok(Ok(c)) +} + +/// Delete a comment (its author, or an admin). A thread left with no comments goes too. Returns whether the thread +/// went. +/// +/// # Errors +/// `Ok(Err(message))` when it's someone else's and the caller isn't an admin; `Err` on a database error. +pub async fn delete(c: Comment, author: &Author, admin: bool) -> laravel::Result> { + if !wrote(&c, author) && !admin { + return Ok(Err("only its author or an admin can delete a comment".into())); + } + let (id, thread_id) = (c.id, c.thread_id); + db::query!("DELETE FROM comments WHERE id = {id}").delete().await?; + let left = Comment::query().filter(Comment::thread_id.eq(thread_id)).count().await?; + if left == 0 { + db::query!("DELETE FROM comment_threads WHERE id = {thread_id}").delete().await?; + return Ok(Ok(true)); + } + Ok(Ok(false)) +} + +/// Resolve a thread, or reopen it. +/// +/// # Errors +/// On a database error. +pub async fn resolve( + mut thread: CommentThread, + resolved: bool, + user_id: Option, +) -> laravel::Result { + let resolved_at = resolved.then(|| laravel::now().timestamp()); + let resolved_by = if resolved { user_id } else { None }; + update!(thread { resolved_at, resolved_by }).await?; + Ok(thread) +} + +/// The open threads on these snapshots (name, platform) of a project's branch. +/// +/// # Errors +/// On a database error. +pub async fn open_on( + project_id: i64, + branch: &str, + snapshots: &[(String, String)], +) -> laravel::Result> { + if snapshots.is_empty() { + return Ok(vec![]); + } + let names: Vec = snapshots.iter().map(|(n, _)| n.clone()).collect(); + let rows: Vec = db::query!( + "SELECT * FROM comment_threads WHERE project_id = {project_id} AND branch = {branch} AND resolved_at IS NULL \ + AND snapshot_name IN ({...names}) ORDER BY id" + ) + .select_as() + .await?; + Ok(rows.into_iter().filter(|t| snapshots.iter().any(|(n, p)| &t.snapshot_name == n && &t.platform == p)).collect()) +} + +/// A thread's first comment's first line, to name it in a refusal. +/// +/// # Errors +/// On a database error. +pub async fn first_line(thread_id: i64) -> laravel::Result { + let c = Comment::query().filter(Comment::thread_id.eq(thread_id)).order_by(Comment::id.asc()).first().await?; + Ok(c.map(|c| c.body.lines().next().unwrap_or_default().chars().take(120).collect()).unwrap_or_default()) +} + +/// Threads (with their comments) for a project's branch, on one snapshot or all of them, open only unless +/// `include_resolved`. +/// +/// # Errors +/// On a database error. +pub async fn list( + project_id: i64, + branch: &str, + snapshot: Option<(&str, &str)>, + include_resolved: bool, +) -> laravel::Result> { + let mut q = + CommentThread::query().filter(CommentThread::project_id.eq(project_id) & CommentThread::branch.eq(branch)); + if let Some((name, platform)) = snapshot { + q = q.filter(CommentThread::snapshot_name.eq(name) & CommentThread::platform.eq(platform)); + } + if !include_resolved { + q = q.filter(CommentThread::resolved_at.is_null()); + } + let threads = q.order_by(CommentThread::id.asc()).get().await?; + let ids: Vec = threads.iter().map(|t| t.id).collect(); + let all = if ids.is_empty() { + Vec::new() + } else { + Comment::query().filter(Comment::thread_id.is_in(ids)).order_by(Comment::id.asc()).get().await? + }; + let user_ids: Vec = all.iter().filter_map(|c| c.user_id).collect(); + let people: HashMap = if user_ids.is_empty() { + HashMap::new() + } else { + User::query().filter(User::id.is_in(user_ids)).get().await?.into_iter().map(|u| (u.id, u.name)).collect() + }; + let build_ids: Vec = threads.iter().filter_map(|t| t.build_id).collect(); + let mut build_numbers: HashMap = HashMap::new(); + let mut drawn_on: HashMap<(i64, String, String), Uuid> = HashMap::new(); + if !build_ids.is_empty() { + for b in Build::query().filter(Build::id.is_in(build_ids.clone())).get().await? { + build_numbers.insert(b.id, b.number); + } + // Each thread's snapshot in the build it was drawn on (its own row, or one it reads from an earlier build), so + // the web app can link there. + let names: Vec = threads.iter().map(|t| t.snapshot_name.clone()).collect(); + let rows = db::query!( + "SELECT build_id, name, platform, pid FROM effective_snapshots \ + WHERE build_id IN ({...build_ids}) AND name IN ({...names})" + ) + .select() + .await?; + for r in rows { + drawn_on.insert((r.try_get("build_id")?, r.try_get("name")?, r.try_get("platform")?), r.try_get("pid")?); + } + } + Ok(threads + .iter() + .map(|t| { + let list: Vec = all + .iter() + .filter(|c| c.thread_id == t.id) + .map(|c| { + let person = c.user_id.and_then(|id| people.get(&id)).cloned(); + serde_json::json!({ + "id": c.pid, "author": { "kind": c.author_kind, "name": person, "agent": c.agent }, + "body": c.body, "created_at": c.created_at.to_string(), "updated_at": c.updated_at.to_string(), + }) + }) + .collect(); + serde_json::json!({ + "id": t.pid, "snapshot": t.snapshot_name, "platform": t.platform, "page": t.page, "side": t.side, + "anchor": t.anchor, "started_in_build": t.build_id.and_then(|id| build_numbers.get(&id)), + "started_in_snapshot": t.build_id.and_then(|id| drawn_on.get(&(id, t.snapshot_name.clone(), t.platform.clone()))), + "resolved": t.resolved_at.is_some(), "resolved_at": t.resolved_at.map(|d| d.to_string()), + "comments": list, + }) + }) + .collect()) +} + +/// The project's branches with open threads, and how many each: for `whoami` and `get_build`. +/// +/// # Errors +/// On a database error. +pub async fn open_by_branch(project_id: i64) -> laravel::Result> { + let rows = db::query!( + "SELECT branch, COUNT(*)::BIGINT AS open FROM comment_threads WHERE project_id = {project_id} \ + AND resolved_at IS NULL GROUP BY branch ORDER BY branch" + ) + .select() + .await?; + Ok(rows + .iter() + .filter_map(|r| Some((r.try_get::("branch").ok()?, r.try_get::("open").ok()?))) + .collect()) +} diff --git a/app/src/domain/compare.rs b/app/src/domain/compare.rs new file mode 100644 index 00000000..fd2d7309 --- /dev/null +++ b/app/src/domain/compare.rs @@ -0,0 +1,346 @@ +//! Comparing a snapshot with its baseline, page by page, and the "visualci.yml" item. + +use laravel::db; +use laravel::model::update; +use visualci_core::align::{PageOp, align_pages}; +use visualci_core::snapshot_text::{self, Format}; + +use super::build_settings::BuildSettings; +use super::pages::{self, Page}; +use super::renders::RenderPage; +use super::snapshots::{CONFIG_NAME, CONFIG_PLATFORM, text_format}; +use crate::models::{Blob, IgnoredChange, Project, Snapshot, Variant}; +use crate::storage::BlobStore; + +/// The exact-match passes below take a baseline row `bl` only when it's current for the snapshot's build: the same +/// suite, a CI approval or one from the build's own branch (local approvals count on their own branch only), and not +/// superseded by a later approval of the same snapshot on the same branch and environment. (Rejected approvals are +/// deleted.) +/// The snapshot's pages: a document's rendered pages, or an image or a text as a single page. +/// +/// # Errors +/// When a render or blob is missing. +pub async fn snapshot_pages(snapshot: &Snapshot, store: &BlobStore) -> laravel::Result> { + match snapshot.kind.as_str() { + "document" => { + let render_id = snapshot.render_id.ok_or_else(|| laravel::Error::msg("a document without a render"))?; + let render = crate::models::Render::find_or_fail(render_id).await?; + super::renders::with_text(super::renders::pages(&render)).await + } + "image" => { + let sha = snapshot.source_blob.clone().ok_or_else(|| laravel::Error::msg("an image without a file"))?; + let blob = + Blob::find(sha.clone()).await?.ok_or_else(|| laravel::Error::msg("the image's file is missing"))?; + let (fingerprint, width, height) = super::blobs::image_info(blob, store).await?; + Ok(vec![RenderPage { + image: sha, + image_fingerprint: fingerprint.clone(), + fingerprint, + width, + height, + text_sha: String::new(), + text: String::new(), + }]) + } + _ => { + let sha = snapshot.source_blob.clone().ok_or_else(|| laravel::Error::msg("a text without a file"))?; + let text = String::from_utf8_lossy(&store.get(&sha).await?).into_owned(); + Ok(vec![RenderPage { + image: String::new(), + image_fingerprint: String::new(), + fingerprint: snapshot.source_fingerprint.clone(), + width: 0, + height: 0, + text_sha: String::new(), + text, + }]) + } + } +} + +fn page_row( + position: usize, + op: &str, + state: &str, + head: Option<(usize, &RenderPage)>, + base: Option<(usize, &RenderPage)>, + diff_id: Option, +) -> Page { + let image = |p: &RenderPage| (!p.image.is_empty()).then(|| p.image.clone()); + let index = |i: usize| i32::try_from(i).unwrap_or(i32::MAX); + Page { + position: index(position), + op: op.to_string(), + state: state.to_string(), + head_index: head.map(|(i, _)| index(i)), + base_index: base.map(|(i, _)| index(i)), + head_image: head.and_then(|(_, p)| image(p)), + base_image: base.and_then(|(_, p)| image(p)), + head_text: head.map(|(_, p)| p.text.clone()), + base_text: base.map(|(_, p)| p.text.clone()), + diff_id, + } +} + +async fn set_state(snapshot: &mut Snapshot, state: &str, base_id: Option) -> laravel::Result<()> { + let state = state.to_string(); + update!(snapshot { state, base_snapshot_id: base_id, error: None }).await +} + +/// Mark a snapshot failed with the reason. +/// +/// # Errors +/// On a database error. +pub async fn mark_failed(snapshot: &mut Snapshot, error: &str) -> laravel::Result<()> { + let error = Some(error.to_string()); + update!(snapshot { state: "failed", error }).await +} + +/// Compare with the baseline snapshot (or record it as added), storing its pages unless every one is the same as the +/// base's ([`pages::plain_unchanged`]). Sets the snapshot's state. +/// +/// # Errors +/// When a page can't be loaded or diffed. +pub async fn compare( + snapshot: &mut Snapshot, + store: &BlobStore, + settings: &BuildSettings<'_>, + base: Option<&Snapshot>, +) -> laravel::Result<()> { + let project = settings.project; + // Text is compared in the head's format, base and head alike, after the head's ignore rules (its build's file or + // the project's, and the test's own). + let rules = settings.compiled_rules(snapshot); + let format = text_format(snapshot); + let normalize = |mut pages: Vec| { + if let Some(format) = format { + for p in &mut pages { + p.text = snapshot_text::normalize(format, &p.text, &rules).text; + } + } + pages + }; + let head_pages = normalize(snapshot_pages(snapshot, store).await?); + let mut rows = Vec::new(); + + let Some(base) = base else { + for (i, page) in head_pages.iter().enumerate() { + rows.push(page_row(i, "inserted", "changed", Some((i, page)), None, None)); + } + pages::store(snapshot.id, rows).await?; + return set_state(snapshot, "added", None).await; + }; + + let base_pages = if base.kind == snapshot.kind { + normalize(snapshot_pages(base, store).await?) + } else { + snapshot_pages(base, store).await? + }; + let fp = |pages: &[RenderPage]| pages.iter().map(|p| p.fingerprint.clone()).collect::>(); + let text = |pages: &[RenderPage]| pages.iter().map(|p| p.text.clone()).collect::>(); + let (base_text, head_text) = (text(&base_pages), text(&head_pages)); + let has_text = base_text.iter().chain(&head_text).any(|t| !t.is_empty()); + let ops = align_pages( + &fp(&base_pages), + &fp(&head_pages), + has_text.then_some(base_text.as_slice()), + has_text.then_some(head_text.as_slice()), + ); + + let options = settings.diff_options(snapshot); + let (mut changed, mut ignored) = (false, false); + let mut matched_environment: Option = None; + for (position, op) in ops.iter().enumerate() { + let row = match *op { + PageOp::Unchanged { base: b, head: h } => { + page_row(position, "unchanged", "unchanged", Some((h, &head_pages[h])), Some((b, &base_pages[b])), None) + } + PageOp::Inserted { head: h } => { + changed = true; + page_row(position, "inserted", "changed", Some((h, &head_pages[h])), None, None) + } + PageOp::Removed { base: b } => { + changed = true; + page_row(position, "removed", "changed", None, Some((b, &base_pages[b])), None) + } + PageOp::Changed { base: b, head: h } => { + let (bp, hp) = (&base_pages[b], &head_pages[h]); + let (state, diff_id, matched) = page_state(snapshot, store, project, h, bp, hp, options).await?; + if matched.is_some() { + matched_environment = matched; + } + match state { + "changed" => changed = true, + "ignored" => ignored = true, + _ => {} + } + page_row(position, "changed", state, Some((h, hp)), Some((b, bp)), diff_id) + } + }; + rows.push(row); + } + if pages::plain_unchanged(&rows) { + pages::store(snapshot.id, Vec::new()).await?; + } else { + pages::store(snapshot.id, rows).await?; + } + let state = if changed { + "changed" + } else if ignored { + "ignored" + } else { + "unchanged" + }; + // "matched local-mac": it passed on another environment's approved image, not its own baseline. + let matched_environment = if changed { None } else { matched_environment }; + if snapshot.matched_environment != matched_environment { + update!(snapshot { matched_environment }).await?; + } + set_state(snapshot, state, Some(base.id)).await +} + +/// The state of a page whose fingerprint changed: identical pixels, an accepted variant, an image approved before, +/// within the threshold, an ignored change, or a change. With the diff, and the other environment it matched. +async fn page_state( + snapshot: &Snapshot, + store: &BlobStore, + project: &Project, + head_index: usize, + base: &RenderPage, + head: &RenderPage, + options: visualci_core::diff::DiffOptions, +) -> laravel::Result<(&'static str, Option, Option)> { + let (project_id, build_id) = (project.id, snapshot.build_id); + let (name, platform) = (snapshot.name.as_str(), snapshot.platform.as_str()); + if snapshot.kind == "text" { + if base.text == head.text { + return Ok(("unchanged", None, None)); + } + // Exactly this text was approved for this snapshot elsewhere in the project (a squash-merged pull request's + // branch): it passes, as an image would. + let fingerprint = snapshot.source_fingerprint.as_str(); + let approved: Option = db::query!( + "SELECT 1 FROM baselines bl JOIN snapshots s ON s.id = bl.snapshot_id \ + WHERE bl.project_id = {project_id} AND bl.name = {name} AND bl.platform = {platform} \ + AND s.source_fingerprint = {fingerprint} AND bl.build_name = (SELECT name FROM builds WHERE id = {build_id}) \ + AND (bl.mode = 'ci' OR bl.branch = (SELECT branch FROM builds WHERE id = {build_id})) \ + AND NOT EXISTS (SELECT 1 FROM baselines b2 WHERE b2.project_id = bl.project_id \ + AND b2.build_name = bl.build_name AND b2.name = bl.name AND b2.platform = bl.platform \ + AND b2.environment = bl.environment AND b2.branch = bl.branch AND b2.id > bl.id) LIMIT 1" + ) + .scalar() + .await?; + return Ok((if approved.is_some() { "variant" } else { "changed" }, None, None)); + } + if base.image == head.image + || (!head.image_fingerprint.is_empty() && base.image_fingerprint == head.image_fingerprint) + { + return Ok(("unchanged", None, None)); + } + let page_index = i32::try_from(head_index).unwrap_or(i32::MAX); + let is_variant = Variant::query() + .filter( + Variant::project_id.eq(project_id) + & Variant::name.eq(name) + & Variant::platform.eq(platform) + & Variant::page_index.eq(page_index) + & Variant::image.eq(head.image.as_str()), + ) + .exists() + .await?; + if is_variant { + return Ok(("variant", None, None)); + } + // Approved before: a current baseline, in any environment, branch or commit of the suite, with exactly this image + // for this snapshot: its own environment's first, then CI's. Covers squash merges and other environments (a Linux + // agent's screenshot that matches the approved Mac one passes). + let image = head.image.as_str(); + let environment = snapshot.environment.as_str(); + let approved: Option = db::query!( + "SELECT s.environment FROM baselines bl \ + JOIN snapshots s ON s.id = bl.snapshot_id JOIN snapshot_pages p ON p.snapshot_id = s.id \ + WHERE bl.project_id = {project_id} AND bl.name = {name} AND bl.platform = {platform} AND p.head_image = {image} \ + AND bl.build_name = (SELECT name FROM builds WHERE id = {build_id}) \ + AND (bl.mode = 'ci' OR bl.branch = (SELECT branch FROM builds WHERE id = {build_id})) \ + AND NOT EXISTS (SELECT 1 FROM baselines b2 WHERE b2.project_id = bl.project_id \ + AND b2.build_name = bl.build_name AND b2.name = bl.name AND b2.platform = bl.platform \ + AND b2.environment = bl.environment AND b2.branch = bl.branch AND b2.id > bl.id) \ + ORDER BY (s.environment = {environment}) DESC, (s.environment = 'ci') DESC, bl.id DESC LIMIT 1" + ) + .scalar() + .await?; + if let Some(env) = approved { + let other = (env != snapshot.environment).then_some(env); + return Ok(("variant", None, other)); + } + let diff = super::diffs::find_or_compute(store, &base.image, &head.image, options).await?; + if !super::diffs::is_change(&diff) { + return Ok(("within_threshold", Some(diff.id), None)); + } + if let Some(fingerprint) = &diff.fingerprint { + let is_ignored = IgnoredChange::query() + .filter( + IgnoredChange::project_id.eq(project_id) + & IgnoredChange::name.eq(name) + & IgnoredChange::platform.eq(platform) + & IgnoredChange::fingerprint.eq(fingerprint.as_str()), + ) + .exists() + .await?; + if is_ignored { + return Ok(("ignored", Some(diff.id), None)); + } + } + Ok(("changed", Some(diff.id), None)) +} + +/// Add the "visualci.yml" item to a build: a changed text snapshot whose diff is the settings that decide what counts +/// as a change, base against head. It's reviewed like any change, so loosened rules can't pass unseen. +/// +/// # Errors +/// On a database error. +pub async fn record_config_change( + build_id: i64, + base_build_id: i64, + base_id: Option, + base: &serde_json::Value, + head: &serde_json::Value, +) -> laravel::Result { + let text = |v: &serde_json::Value| snapshot_text::normalize(Format::Json, &v.to_string(), &Default::default()).text; + let (base_text, head_text) = (text(base), text(head)); + let page = |t: &str| RenderPage { + image: String::new(), + image_fingerprint: String::new(), + fingerprint: visualci_core::sha256_hex(t.as_bytes()), + width: 0, + height: 0, + text_sha: String::new(), + text: t.to_string(), + }; + let snapshot = laravel::model::create!(Snapshot { + pid: laravel::str::uuid7(), + build_id: build_id, + name: CONFIG_NAME, + platform: CONFIG_PLATFORM, + kind: "text", + format: Some("json".to_string()), + source_fingerprint: visualci_core::sha256_hex(head_text.as_bytes()), + source_blob: None, + render_id: None, + engine: None, + threshold: None, + ignore_anti_aliasing: None, + meta: serde_json::json!({ "config": true, "base_build_id": base_build_id }), + state: "changed", + base_snapshot_id: base_id, + review: None, + error: None, + matched_environment: None, + baseline_id: None, + matches_build_id: None, + }) + .await?; + let (b, h) = (page(&base_text), page(&head_text)); + pages::store(snapshot.id, vec![page_row(0, "changed", "changed", Some((0, &h)), Some((0, &b)), None)]).await?; + Ok(snapshot) +} diff --git a/app/src/domain/credits.rs b/app/src/domain/credits.rs index 1fe803c5..d3d217c7 100644 --- a/app/src/domain/credits.rs +++ b/app/src/domain/credits.rs @@ -50,7 +50,421 @@ pub async fn add_purchased_credits(organization_id: i64, credits: i64, reference // (`credit_transactions_purchase_once`) refuses the second, and its transaction adds nothing. match add_credits(organization_id, credits, "purchase", Some(reference)).await { Ok(_) => Ok(true), - Err(e) if e.to_string().contains("credit_transactions_purchase_once") => Ok(false), + Err(e) if db::is_unique_violation(&e) => Ok(false), Err(e) => Err(e), } } + +/// A plan. Builds use credits: 1 per snapshot checked, 5 per text diff, 10 per image diff and 20 per PDF page drawn. +#[derive(Debug, Clone, Copy, serde::Serialize)] +pub struct Plan { + pub id: &'static str, + pub name: &'static str, + /// US cents per month. + pub price_cents: i64, + /// Credits included each calendar month (UTC). + pub included_credits: i64, + /// Whether the organization can buy credit packs for builds past the allowance. Without them, builds stop until + /// the month renews. + pub credit_packs: bool, + /// No allowance or limit at all: builds never stop for credits. Usage is still recorded. + pub unlimited: bool, +} + +pub const FREE: Plan = + Plan { id: "free", name: "Free", price_cents: 0, included_credits: 25_000, credit_packs: false, unlimited: false }; +pub const TEAM: Plan = Plan { + id: "team", + name: "Team", + price_cents: 2_900, + included_credits: 1_000_000, + credit_packs: true, + unlimited: false, +}; +/// DocSpring's own organizations: unlimited, free, and never offered. +pub const STAFF: Plan = + Plan { id: "staff", name: "Staff", price_cents: 0, included_credits: 0, credit_packs: false, unlimited: true }; + +/// The plans anyone can choose (Staff isn't one of them). +pub const PLANS: &[Plan] = &[FREE, TEAM]; + +/// The plan with this id (an organization's `plan` column). Anything unknown is Free. +#[must_use] +pub fn plan_by_id(id: &str) -> Plan { + [TEAM, STAFF].into_iter().find(|p| p.id == id).unwrap_or(FREE) +} + +/// Credits a month each organization gets for its open source projects, on any plan: their builds use this pool +/// first, then the plan's allowance and packs like any other project. +pub const OPEN_SOURCE_POOL: i64 = 1_000_000; + +/// A prepaid credit pack, used after the month's allowance. Pack credits don't expire. +#[derive(Debug, Clone, Copy, serde::Serialize)] +pub struct CreditPack { + pub credits: i64, + pub price_cents: i64, + /// An automatic reload buys a pack when the credits left (allowance and packs) fall below this. + pub reload_below: i64, +} + +pub const CREDIT_PACK: CreditPack = CreditPack { credits: 500_000, price_cents: 1_500, reload_below: 100_000 }; +/// Most automatic reloads an organization can allow in a month. +pub const MAX_AUTO_RELOAD_PACKS: i32 = 50; + +/// What each thing costs in credits, for the billing page and the MCP server. +#[must_use] +pub fn credit_rates() -> serde_json::Value { + use super::builds::{ + CREDITS_PER_IMAGE_DIFF, CREDITS_PER_RENDERED_PAGE, CREDITS_PER_SNAPSHOT_CHECK, CREDITS_PER_TEXT_DIFF, + }; + serde_json::json!({ + "snapshot_check": CREDITS_PER_SNAPSHOT_CHECK, + "text_diff": CREDITS_PER_TEXT_DIFF, + "image_diff": CREDITS_PER_IMAGE_DIFF, + "rendered_page": CREDITS_PER_RENDERED_PAGE, + }) +} + +/// Who a spend is for: the project, and whether it draws from the open source pool. +#[derive(Debug, Clone, Copy)] +pub struct Spender { + pub project_id: i64, + pub open_source: bool, +} + +impl Spender { + #[must_use] + pub fn of(project: &crate::models::Project) -> Self { + Self { project_id: project.id, open_source: counts_as_open_source(project) } + } +} + +/// Whether a project's credits come from the open source pool: the forge verified it, it's public on VisualCI, and +/// staff haven't withdrawn it. +#[must_use] +pub fn counts_as_open_source(p: &crate::models::Project) -> bool { + p.open_source && p.public && !p.open_source_withdrawn +} + +/// The time, as allowances count it. `VISUALCI_NOW` (RFC 3339) stands in for the clock for VisualCI's own screenshots +/// of seeded data; it's never set in production. Tests move Laravel's clock instead. +#[must_use] +pub fn now() -> laravel::time::Timestamp { + std::env::var("VISUALCI_NOW").ok().and_then(|v| v.parse().ok()).unwrap_or_else(|| laravel::now().timestamp()) +} + +/// The start of the current calendar month, UTC: when allowances renew. +#[must_use] +pub fn month_start() -> laravel::time::Timestamp { + use laravel::time::civil; + let now = now(); + let Ok(today) = now.in_tz("UTC").map(|z| z.date()) else { return now }; + civil::date(today.year(), today.month(), 1).at(0, 0, 0, 0).in_tz("UTC").map_or(now, |z| z.timestamp()) +} + +/// The start of next month: when this month's allowance renews. +#[must_use] +pub fn renews_at() -> Option { + use laravel::time::ToSpan; + month_start().in_tz("UTC").ok()?.checked_add(1.month()).ok().map(|z| z.timestamp()) +} + +/// "1,000,000". +#[must_use] +pub fn thousands(n: i64) -> String { + let digits = n.unsigned_abs().to_string(); + let mut out = String::new(); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i).is_multiple_of(3) { + out.push(','); + } + out.push(c); + } + if n < 0 { format!("-{out}") } else { out } +} + +/// The plan's credits used this month: everything open source projects didn't take from their pool. +/// +/// # Errors +/// On a database error. +pub async fn used_this_month(organization_id: i64) -> laravel::Result { + let since = month_start(); + Ok(db::query!( + "SELECT (COALESCE(-SUM(amount) - SUM(open_source_credits), 0))::BIGINT FROM credit_transactions \ + WHERE organization_id = {organization_id} AND kind IN ('build', 'render', 'gallery') AND created_at >= {since}" + ) + .scalar() + .await? + .unwrap_or(0)) +} + +/// Credits the organization's open source projects took from the pool this month. +/// +/// # Errors +/// On a database error. +pub async fn pool_used_this_month(organization_id: i64) -> laravel::Result { + let since = month_start(); + Ok(db::query!( + "SELECT (COALESCE(SUM(open_source_credits), 0))::BIGINT FROM credit_transactions \ + WHERE organization_id = {organization_id} AND created_at >= {since}" + ) + .scalar() + .await? + .unwrap_or(0)) +} + +/// Credits left: what's left of this month's allowance, plus pack credits. +/// +/// # Errors +/// On a database error. +pub async fn credits_left(org: &crate::models::Organization) -> laravel::Result { + let plan = plan_by_id(&org.plan); + if plan.unlimited { + return Ok(i64::MAX); + } + Ok((plan.included_credits - used_this_month(org.id).await?).max(0) + org.credits_balance.max(0)) +} + +/// Whether this month's allowance and every pack credit are used up: new builds stop until the month renews or +/// someone buys a pack. +/// +/// # Errors +/// On a database error. +pub async fn out_of_credits(org: &crate::models::Organization) -> laravel::Result { + let plan = plan_by_id(&org.plan); + if plan.unlimited { + return Ok(false); + } + Ok(org.credits_balance <= 0 && used_this_month(org.id).await? >= plan.included_credits) +} + +/// Whether a project's next build has nothing to spend: an open source project still has the pool while it lasts. +/// +/// # Errors +/// On a database error. +pub async fn out_of_credits_for(org: &crate::models::Organization, spender: Spender) -> laravel::Result { + if spender.open_source && pool_used_this_month(org.id).await? < OPEN_SOURCE_POOL { + return Ok(false); + } + out_of_credits(org).await +} + +/// Why an organization's builds can't be compared now, for an agent to act on: `None` while it has credits. `spender` +/// is the project asking (an open source one still has the pool); `None` asks about the plan's credits. The `message` +/// is one plain line an agent can pass on to its person as it is. +/// +/// # Errors +/// On a database error. +pub async fn blocked( + org: &crate::models::Organization, + app_url: &str, + spender: Option, +) -> laravel::Result> { + let out = match spender { + Some(s) => out_of_credits_for(org, s).await?, + None => out_of_credits(org).await?, + }; + if !out { + return Ok(None); + } + let plan = plan_by_id(&org.plan); + let used = used_this_month(org.id).await?; + let billing = format!("{}/{}/billing", app_url.trim_end_matches('/'), org.slug); + let renews_at = renews_at(); + let renews = renews_at + .map_or_else(String::new, |t| t.in_tz("UTC").map(|z| z.strftime("%-d %B %Y").to_string()).unwrap_or_default()); + let fix = |action: &str, label: &str| serde_json::json!({ "action": action, "label": label, "url": billing }); + let (fixes, what) = if plan.credit_packs { + // Automatic packs need a card; they pause after a declined payment, and stop at the monthly limit. + let auto = if org.stripe_customer_id.is_none() || org.auto_reload_packs == 0 { + fix("turn_on_auto_buy", "Turn on automatic packs, with a card") + } else if org.reloads_paused_at.is_some() { + fix("resume_auto_buy", "Update the card and resume automatic packs") + } else { + fix("raise_auto_buy_limit", "Raise the monthly limit on automatic packs") + }; + (vec![fix("buy_pack", "Buy a credit pack"), auto], "buy a credit pack or turn on automatic packs") + } else { + (vec![fix("upgrade", "Upgrade to Team")], "upgrade to Team") + }; + let message = format!( + "{} is out of VisualCI credits until {renews}: it has used all {} credits on the {} plan, so builds aren't \ + compared. An admin can {what} at {billing}", + org.name, + thousands(plan.included_credits), + plan.name, + ); + Ok(Some(serde_json::json!({ + "reason": "out_of_credits", + "plan": plan.name, + "credits_used": used, + "credits_limit": plan.included_credits, + "pack_credits": org.credits_balance.max(0), + "renews_at": renews_at.map(|t| t.to_string()), + "fixes": fixes, + "billing_url": billing, + "message": message, + }))) +} + +/// Spend credits: from the open source pool first (for an open source project), then this month's allowance, then +/// pack credits (which can go below zero by one build's worth). Records one transaction for the whole amount. +/// +/// # Errors +/// On a database error. +pub async fn spend( + organization_id: i64, + credits: i64, + kind: &str, + reference: Option<&str>, + spender: Option, + build_id: Option, +) -> laravel::Result<()> { + db::transaction(async |_| { + let (balance, from_pool) = take(organization_id, credits, spender).await?; + let (amount, project_id) = (-credits, spender.map(|s| s.project_id)); + db::query!( + "INSERT INTO credit_transactions (organization_id, amount, balance_after, kind, reference, project_id, \ + open_source_credits, build_id) \ + VALUES ({organization_id}, {amount}, {balance}, {kind}, {reference}, {project_id}, {from_pool}, {build_id})" + ) + .insert() + .await?; + Ok(()) + }) + .await +} + +/// Spend credits for gallery images served from VisualCI's own servers, as [`spend`] does, but added to one row per +/// project and UTC day (`kind = 'gallery'`, `day`), not one row per image: a busy public page would otherwise write a +/// row for every request. Kept even when the organization is out of credits, so a customer's page keeps working. Past +/// `daily_cap` credits in the project's day, nothing more is charged (`false`): a customer isn't billed without limit +/// for a page someone hammers. +/// +/// # Errors +/// On a database error. +pub async fn spend_gallery(project: &crate::models::Project, credits: i64, daily_cap: i64) -> laravel::Result { + let spender = Spender::of(project); + let (organization_id, project_id) = (project.organization_id, project.id); + // The day as allowances count time (`now`). + let day = now().in_tz("UTC").map_err(|e| laravel::Error::msg(e.to_string()))?.date(); + db::transaction(async |_| { + let today: i64 = db::query!( + "SELECT -amount FROM credit_transactions \ + WHERE organization_id = {organization_id} AND project_id = {project_id} AND day = {day} AND kind = 'gallery'" + ) + .scalar() + .await? + .unwrap_or(0); + if today + credits > daily_cap { + return Ok(false); + } + let (balance, from_pool) = take(organization_id, credits, Some(spender)).await?; + let amount = -credits; + db::query!( + "INSERT INTO credit_transactions (organization_id, amount, balance_after, kind, project_id, \ + open_source_credits, day) \ + VALUES ({organization_id}, {amount}, {balance}, 'gallery', {project_id}, {from_pool}, {day}) \ + ON CONFLICT (organization_id, project_id, day) WHERE kind = 'gallery' DO UPDATE SET \ + amount = credit_transactions.amount + EXCLUDED.amount, balance_after = EXCLUDED.balance_after, \ + open_source_credits = credit_transactions.open_source_credits + EXCLUDED.open_source_credits, \ + updated_at = now()" + ) + .insert() + .await?; + Ok(true) + }) + .await +} + +/// Take credits from the organization, inside the caller's transaction: from the open source pool first (for an open +/// source project), then this month's allowance, then pack credits. Returns the pack balance after and how many came +/// from the pool. +async fn take(organization_id: i64, credits: i64, spender: Option) -> laravel::Result<(i64, i64)> { + let plan: String = db::query!("SELECT plan FROM organizations WHERE id = {organization_id} FOR UPDATE") + .scalar() + .await? + .ok_or_else(|| laravel::Error::msg(format!("no organization {organization_id}")))?; + let plan = plan_by_id(&plan); + let from_pool = match spender { + Some(s) if s.open_source && credits > 0 => { + (OPEN_SOURCE_POOL - pool_used_this_month(organization_id).await?).clamp(0, credits) + } + _ => 0, + }; + let for_plan = credits - from_pool; + // Unlimited plans never touch pack credits; the transaction still records what was used. + let from_packs = if plan.unlimited { + 0 + } else { + let allowance_left = (plan.included_credits - used_this_month(organization_id).await?).max(0); + (for_plan - allowance_left).clamp(0, for_plan.max(0)) + }; + let balance: i64 = db::query!( + "UPDATE organizations SET credits_balance = credits_balance - {from_packs}, updated_at = now() \ + WHERE id = {organization_id} RETURNING credits_balance" + ) + .scalar() + .await? + .unwrap_or(0); + Ok((balance, from_pool)) +} + +/// Automatic reloads (pack purchases) this month. +/// +/// # Errors +/// On a database error. +pub async fn reloads_this_month(organization_id: i64) -> laravel::Result { + let since = month_start(); + Ok(db::query!( + "SELECT COUNT(*) FROM credit_transactions WHERE organization_id = {organization_id} AND kind = 'purchase' \ + AND reference LIKE 'auto-reload%' AND created_at >= {since}" + ) + .scalar() + .await? + .unwrap_or(0)) +} + +/// The organization's open source projects (verified, public, not withdrawn). +/// +/// # Errors +/// On a database error. +pub async fn open_source_projects(organization_id: i64) -> laravel::Result { + Ok(db::query!( + "SELECT COUNT(*) FROM projects WHERE organization_id = {organization_id} AND open_source AND public \ + AND NOT open_source_withdrawn" + ) + .scalar() + .await? + .unwrap_or(0)) +} + +/// The plan, this month's credits, pack credits and what things cost, as the web app and the MCP server show them. +/// +/// # Errors +/// On a database error. +pub async fn usage(org: &crate::models::Organization) -> laravel::Result { + let plan = plan_by_id(&org.plan); + let used = used_this_month(org.id).await?; + Ok(serde_json::json!({ + "plan": plan, + "credits_this_month": used, + "included_credits": plan.included_credits, + "pack_credits": org.credits_balance.max(0), + "credit_pack": CREDIT_PACK, + "auto_reload_packs": org.auto_reload_packs, + "reloads_this_month": reloads_this_month(org.id).await?, + "rates": credit_rates(), + "renews_at": renews_at().map(|t| t.to_string()), + "out_of_credits": !plan.unlimited && used >= plan.included_credits && org.credits_balance <= 0, + "unlimited": plan.unlimited, + "billing_problem": org.billing_problem, + // The open source pool: shown when the organization has open source projects or used the pool this month. + "open_source": { + "pool": OPEN_SOURCE_POOL, + "used": pool_used_this_month(org.id).await?, + "projects": open_source_projects(org.id).await?, + }, + "reloads_paused": org.reloads_paused_at.is_some(), + })) +} diff --git a/app/src/domain/demo.rs b/app/src/domain/demo.rs new file mode 100644 index 00000000..c7c744ba --- /dev/null +++ b/app/src/domain/demo.rs @@ -0,0 +1,419 @@ +//! The public demo, visualci/demo (app.visualci.com/visualci/demo): its builds show every kind of change (screenshots, a +//! PDF page, JSON, HTML and text; added and removed snapshots), so a new person or agent sees a real review before +//! sending anything. Anyone can read it; nobody outside the demo organization can change it, and [`reset`] (the daily +//! `demo:reset`) rebuilds it from scratch, undoing anything that did. +//! +//! The builds go through the real pipeline (snapshot registration, finalizing, processing), so the demo shows what the +//! app produces. PDFs are the exception: their renders are recorded as done, with page images drawn here, since +//! drawing needs the render node. The demo isn't charged: builds are processed directly, not by the job that charges. + +use std::io::Cursor; + +use image::{ImageFormat, Rgba, RgbaImage}; +use laravel::db; +use laravel::model::create; + +use super::build_settings::BuildSettings; +use super::builds::CreateParams; +use super::renders::RenderPage; +use super::snapshots::SnapshotParams; +use crate::models::{Build, Membership, Organization, Project, User}; +use crate::storage::BlobStore; + +/// The demo's organization and project: app.visualci.com/visualci/demo. +pub const ORG: &str = "visualci"; +pub const PROJECT: &str = "demo"; +/// The demo organization's only member, who approves one of its builds. +pub const OWNER_EMAIL: &str = "demo@visualci.com"; + +/// Rebuild the demo; returns how many builds it has. +/// +/// # Errors +/// On a database or storage error, or when the `visualci` organization exists and isn't the demo's. +pub async fn reset(store: &BlobStore, renderer_version: &str) -> laravel::Result { + let owner = match User::query().filter(User::email.eq(OWNER_EMAIL)).first().await? { + Some(u) => u, + None => { + create!(User { pid: laravel::str::uuid7(), name: "VisualCI demo", email: OWNER_EMAIL, staff: false }) + .await? + } + }; + // The demo's own account isn't a sign-up: nobody is emailed about it, and /status doesn't wait for it. + let owner_id = owner.id; + db::query!("UPDATE users SET signup_notified_at = now() WHERE id = {owner_id} AND signup_notified_at IS NULL") + .update() + .await?; + let org = match Organization::query().filter(Organization::slug.eq(ORG)).first().await? { + Some(org) => org, + None => { + let org = create!(Organization { pid: laravel::str::uuid7(), slug: ORG, name: "VisualCI" }).await?; + create!(Membership { organization_id: org.id, user_id: owner_id, role: "admin", source: "created" }) + .await?; + org + } + }; + let member = Membership::query() + .filter(Membership::organization_id.eq(org.id) & Membership::user_id.eq(owner_id)) + .exists() + .await?; + if !member { + return Err(laravel::Error::msg(format!("the {ORG} organization exists and isn't the demo's"))); + } + let project = + match Project::query().filter(Project::organization_id.eq(org.id) & Project::slug.eq(PROJECT)).first().await? { + Some(p) => p, + None => { + create!(Project { pid: laravel::str::uuid7(), organization_id: org.id, slug: PROJECT, name: "Demo" }) + .await? + } + }; + // Start over: the builds go, and their snapshots, pages and baselines with them. + let project_id = project.id; + db::query!("UPDATE projects SET public = true WHERE id = {project_id}").update().await?; + // Its builds read groups from each other (`build_groups.source_build_id`, which has no ON DELETE so a held build is + // never deleted from under a reader): every one goes, so their group rows go first, in the same transaction. + db::transaction(async |_| { + db::query!( + "DELETE FROM build_groups WHERE build_id IN (SELECT id FROM builds WHERE project_id = {project_id}) \ + OR source_build_id IN (SELECT id FROM builds WHERE project_id = {project_id})" + ) + .delete() + .await?; + db::query!("DELETE FROM builds WHERE project_id = {project_id}").delete().await + }) + .await?; + let project = Project::find_or_fail(project_id).await?; + Seeder { store, renderer_version }.web_builds(&project, owner_id).await?; + let builds: i64 = + db::query!("SELECT COUNT(*) FROM builds WHERE project_id = {project_id}").scalar().await?.unwrap_or(0); + Ok(usize::try_from(builds).unwrap_or_default()) +} + +struct Seeder<'a> { + store: &'a BlobStore, + renderer_version: &'a str, +} + +/// One snapshot to send in a build. +enum Item { + Image { name: &'static str, png: Vec }, + Text { name: &'static str, content_type: &'static str, text: String }, + Pdf { name: &'static str, pages: Vec }, +} + +#[derive(Clone)] +struct PdfPage { + /// Lines of text, drawn as bars and recorded as the page's text. + lines: Vec<&'static str>, + accent: [u8; 3], +} + +fn error(e: impl std::fmt::Display) -> laravel::Error { + laravel::Error::msg(e.to_string()) +} + +impl Seeder<'_> { + /// The web app: a baseline, an unchanged build, a PR with every kind of change, and a branch whose change + /// `reviewer` approves. + async fn web_builds(&self, web: &Project, reviewer: i64) -> laravel::Result<()> { + let base = || { + vec![ + Item::Image { name: "dashboard/1440-light", png: screen(720, 450, Screen::default()) }, + Item::Image { name: "dashboard/390-light", png: screen(195, 420, Screen::default()) }, + Item::Image { + name: "settings/1440-light", + png: screen(720, 450, Screen { cards: 2, ..Screen::default() }), + }, + Item::Image { + name: "signup/1440-light", + png: screen(720, 450, Screen { cards: 1, ..Screen::default() }), + }, + Item::Pdf { name: "receipt.pdf", pages: receipt(false) }, + Item::Text { name: "api/orders.json", content_type: "application/json", text: orders_json(false) }, + Item::Text { name: "emails/welcome.html", content_type: "text/html", text: welcome_html(false) }, + Item::Text { name: "cli/help.txt", content_type: "text/plain", text: help_text(false) }, + ] + }; + let c1 = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"; + let c2 = "b2c3d4e5f60718293a4b5c6d7e8f901234567890"; + self.build(web, c1, "main", None, &[], base()).await?; + self.build(web, c2, "main", None, &[c1], base()).await?; + + // PR #42: every kind of change. + let changed = vec![ + Item::Image { + name: "dashboard/1440-light", + png: screen(720, 450, Screen { button: [22, 163, 74], ..Screen::default() }), + }, + // The phone page grew taller: a resized pair. + Item::Image { + name: "dashboard/390-light", + png: screen(195, 520, Screen { footer: true, ..Screen::default() }), + }, + Item::Image { + name: "settings/1440-light", + png: screen(720, 450, Screen { cards: 2, ..Screen::default() }), + }, + Item::Image { + name: "checkout/1440-light", + png: screen(720, 450, Screen { cards: 4, ..Screen::default() }), + }, + Item::Pdf { name: "receipt.pdf", pages: receipt(true) }, + Item::Text { name: "api/orders.json", content_type: "application/json", text: orders_json(true) }, + Item::Text { name: "emails/welcome.html", content_type: "text/html", text: welcome_html(true) }, + Item::Text { name: "cli/help.txt", content_type: "text/plain", text: help_text(true) }, + ]; + let c3 = "c3d4e5f60718293a4b5c6d7e8f9012345678901a"; + self.build(web, c3, "checkout-redesign", Some(42), &[c2], changed).await?; + + // A branch whose changes are approved. + let mut footer = base(); + footer[2] = Item::Image { + name: "settings/1440-light", + png: screen(720, 450, Screen { cards: 2, footer: true, ..Screen::default() }), + }; + let c4 = "d4e5f60718293a4b5c6d7e8f9012345678901a2b"; + let reviewed = self.build(web, c4, "fix-footer", Some(41), &[c2], footer).await?; + let via = super::reviews::Via::default(); + Box::pin(super::reviews::review(reviewed, Some(reviewer), &via, "approve", None, None)) + .await? + .map_err(error)?; + Ok(()) + } + + /// Send a build through the pipeline and return it, completed. + async fn build( + &self, + project: &Project, + commit: &str, + branch: &str, + pr_number: Option, + parents: &[&str], + items: Vec, + ) -> laravel::Result { + let params = CreateParams { + commit: commit.to_string(), + branch: branch.to_string(), + pr_number, + parent_commits: parents.iter().map(ToString::to_string).collect(), + mode: "ci".to_string(), + name: "default".to_string(), + shard_total: 1, + subset: false, + nonce: None, + config: None, + environment: Some("ci".to_string()), + environment_info: None, + }; + let outcome = |r: Result>| match r { + Ok(b) => Ok(b), + Err(Ok(invalid)) => Err(error(invalid)), + Err(Err(e)) => Err(e), + }; + let build = outcome(super::builds::create(project, ¶ms, None).await)?; + let settings = BuildSettings::new(project, &build); + for item in items { + let snapshot = self.snapshot(project, item).await?; + snapshot.validate().map_err(error)?; + super::snapshots::register(&build, &settings, self.renderer_version, &snapshot).await?.map_err(error)?; + } + let build = outcome(super::builds::finalize_shard(build, None, false).await)?; + let id = build.id; + let concluded = Box::pin(db::transaction(async |_| { + super::processing::lock(id).await?; + let build = Build::find_or_fail(id).await?; + super::processing::process(build, self.store, self.renderer_version).await + })) + .await?; + if !concluded { + return Err(laravel::Error::msg(format!("demo build {id} didn't conclude"))); + } + Build::find_or_fail(id).await + } + + /// Store an item's bytes and describe it the way the CLI would. + async fn snapshot(&self, project: &Project, item: Item) -> laravel::Result { + let params = |name: &str, kind: &str, fingerprint: String, sha256: String, size: i64, content_type: &str| { + SnapshotParams { + name: name.to_string(), + platform: if kind == "image" { "chrome-linux".to_string() } else { String::new() }, + kind: kind.to_string(), + fingerprint, + sha256, + size, + content_type: content_type.to_string(), + threshold: None, + ignore_anti_aliasing: None, + engine: None, + format: None, + meta: serde_json::json!({}), + ignore: None, + } + }; + let size_of = |bytes: &[u8]| i64::try_from(bytes.len()).unwrap_or(i64::MAX); + Ok(match item { + Item::Image { name, png } => { + let fingerprint = visualci_core::image_hash::fingerprint_bytes(&png).map_err(error)?; + let size = size_of(&png); + let blob = super::blobs::put(self.store, png, "image/png").await?; + params(name, "image", fingerprint, blob.sha256, size, "image/png") + } + Item::Text { name, content_type, text } => { + let fingerprint = visualci_core::sha256_hex(text.as_bytes()); + let size = size_of(text.as_bytes()); + let blob = super::blobs::put(self.store, text.into_bytes(), content_type).await?; + params(name, "text", fingerprint, blob.sha256, size, content_type) + } + Item::Pdf { name, pages } => { + // The "PDF" is the pages' description; its render is recorded as done with the drawn pages. + let mut rendered = Vec::new(); + for page in &pages { + let png = page_png(page); + let image_fingerprint = visualci_core::image_hash::fingerprint_bytes(&png).map_err(error)?; + let text = page.lines.join("\n"); + let blob = super::blobs::put(self.store, png, "image/png").await?; + rendered.push(RenderPage { + image: blob.sha256, + image_fingerprint, + fingerprint: visualci_core::sha256_hex(text.as_bytes()), + width: PAGE_W, + height: PAGE_H, + text_sha: String::new(), + text, + }); + } + let source: String = rendered.iter().map(|p| p.fingerprint.as_str()).collect(); + let fingerprint = visualci_core::sha256_hex(source.as_bytes()); + let blob = super::blobs::put(self.store, source.into_bytes(), "application/pdf").await?; + let renderer_key = super::projects::renderer_key(&project.renderer, project.dpi, self.renderer_version); + let render = + super::renders::find_or_queue(project.id, &fingerprint, &renderer_key, &blob.sha256).await?; + if render.state != "done" { + super::renders::complete(render, &rendered).await?; + } + params(name, "document", fingerprint, blob.sha256, blob.size, "application/pdf") + } + }) + } +} + +// Drawing. Simple flat shapes, so the images are small and the same on every machine. + +const PAGE_W: u32 = 420; +const PAGE_H: u32 = 594; + +fn png(image: &RgbaImage) -> Vec { + let mut out = Cursor::new(Vec::new()); + image.write_to(&mut out, ImageFormat::Png).expect("encoding a PNG in memory"); + out.into_inner() +} + +fn rect(image: &mut RgbaImage, x: u32, y: u32, w: u32, h: u32, rgb: [u8; 3]) { + let (iw, ih) = image.dimensions(); + for py in y.min(ih)..(y + h).min(ih) { + for px in x.min(iw)..(x + w).min(iw) { + image.put_pixel(px, py, Rgba([rgb[0], rgb[1], rgb[2], 255])); + } + } +} + +#[derive(Clone, Copy)] +struct Screen { + cards: u32, + button: [u8; 3], + footer: bool, +} + +impl Default for Screen { + fn default() -> Self { + Self { cards: 3, button: [37, 99, 235], footer: false } + } +} + +/// A made-up app screen: a top bar, a heading, a button and a row of cards. +fn screen(w: u32, h: u32, s: Screen) -> Vec { + let mut image = RgbaImage::from_pixel(w, h, Rgba([248, 250, 252, 255])); + rect(&mut image, 0, 0, w, 36, [15, 23, 42]); + rect(&mut image, 16, 12, 60, 12, [226, 232, 240]); + rect(&mut image, 24, 60, w / 3, 18, [30, 41, 59]); + rect(&mut image, 24, 88, w / 2, 8, [148, 163, 184]); + rect(&mut image, 24, 110, 96.min(w - 48), 28, s.button); + let gap = 16; + let card_w = (w - 48 - gap * (s.cards - 1)) / s.cards; + for i in 0..s.cards { + let x = 24 + i * (card_w + gap); + rect(&mut image, x, 160, card_w, 140.min(h.saturating_sub(200)), [255, 255, 255]); + rect(&mut image, x + 12, 176, card_w.saturating_sub(24), 10, [100, 116, 139]); + rect(&mut image, x + 12, 196, card_w / 2, 8, [203, 213, 225]); + } + if s.footer { + rect(&mut image, 0, h - 40, w, 40, [226, 232, 240]); + rect(&mut image, 24, h - 26, 120, 10, [100, 116, 139]); + } + png(&image) +} + +/// A PDF page: a coloured header band and a grey bar per line of text, as wide as the line. +fn page_png(page: &PdfPage) -> Vec { + let mut image = RgbaImage::from_pixel(PAGE_W, PAGE_H, Rgba([255, 255, 255, 255])); + rect(&mut image, 32, 32, PAGE_W - 64, 40, page.accent); + for (i, line) in page.lines.iter().enumerate() { + let width = (u32::try_from(line.len()).unwrap_or(u32::MAX).saturating_mul(6)).min(PAGE_W - 64); + let y = 96 + u32::try_from(i).unwrap_or(0) * 22; + rect(&mut image, 32, y, width, 9, [71, 85, 105]); + } + png(&image) +} + +fn receipt(changed: bool) -> Vec { + let blue = [37, 99, 235]; + let mut pages = vec![ + PdfPage { + lines: vec!["Receipt #10422", "Acme Inc.", "20 November 2026", "Billed to: Example Customer"], + accent: blue, + }, + PdfPage { + lines: if changed { + vec!["Widget x 2 $40.00", "Gadget x 1 $25.00", "Subtotal $65.00", "Total $71.50"] + } else { + vec!["Widget x 2 $40.00", "Gadget x 1 $25.00", "Total $65.00"] + }, + accent: blue, + }, + ]; + if changed { + pages.push(PdfPage { + lines: vec!["Tax summary", "GST 10% $6.50", "Registered for GST"], + accent: [22, 163, 74], + }); + } + pages +} + +fn orders_json(changed: bool) -> String { + let currency = if changed { r#", "currency": "USD""# } else { "" }; + format!( + "{{\n \"orders\": [\n {{ \"id\": \"ord_1001\", \"status\": \"paid\", \"total\": 6500{currency} }},\n \ + {{ \"id\": \"ord_1002\", \"status\": \"{}\", \"total\": 1200{currency} }}\n ],\n \"has_more\": false\n}}\n", + if changed { "refunded" } else { "pending" } + ) +} + +fn welcome_html(changed: bool) -> String { + format!( + "\n\n

Welcome to Acme

\n

Thanks for signing up.

\n \ + {}\n\n\n", + if changed { "Start your trial" } else { "Get started" } + ) +} + +fn help_text(changed: bool) -> String { + let mut text = String::from( + "Usage: acme \n\nCommands:\n login Sign in\n deploy Deploy the current directory\n", + ); + if changed { + text.push_str(" rollback Go back to the previous deploy\n"); + } + text.push_str(" logs Show recent logs\n"); + text +} diff --git a/app/src/domain/detail.rs b/app/src/domain/detail.rs new file mode 100644 index 00000000..afd41367 --- /dev/null +++ b/app/src/domain/detail.rs @@ -0,0 +1,469 @@ +//! What a reviewer sees of a snapshot (the web app and the MCP server): its pages with image URLs and text diffs, the +//! lines that moved to another page, a text snapshot's format and JSON changes, the comparison with an earlier build, +//! and the review order of a build's snapshots. + +use std::collections::HashMap; + +use laravel::db; +use visualci_core::align::{PageOp, align_pages}; +use visualci_core::snapshot_text::{self, Format}; + +use super::pages::{self, Page}; +use super::snapshots::text_format; +use crate::models::{Blob, Build, Diff, Snapshot}; +use crate::storage::BlobStore; + +/// One page of a snapshot's comparison, for reviewers. +#[derive(Clone, Debug, serde::Serialize)] +pub struct PageDetail { + pub position: i32, + pub op: String, + pub state: String, + pub head_index: Option, + pub base_index: Option, + pub head_image: Option, + pub base_image: Option, + pub overlay_image: Option, + pub head_url: Option, + pub base_url: Option, + pub overlay_url: Option, + /// Retention deleted this page's images: the URLs are empty and the diff numbers remain. + pub expired: bool, + /// Each side's image size, `[width, height]`, when known: they differ when the page or screenshot was resized, and + /// the diff then covers the larger canvas, both images aligned top-left. + pub base_size: Option<[i32; 2]>, + pub head_size: Option<[i32; 2]>, + pub diff: Option, + pub text_diff: Vec, +} + +/// What a reviewer sees of a text snapshot beyond its line diff. +#[derive(Clone, Debug, serde::Serialize)] +pub struct TextDetail { + /// `text`, `json` or `html`: how it was normalized and compared. + pub format: String, + pub base_lines: usize, + pub head_lines: usize, + /// JSON: the changes by path (`items[3].price: 10 → 12`), at most [`JSON_CHANGE_LIMIT`]. + pub json_changes: Vec, + pub json_changes_truncated: bool, + /// Why it was compared differently from its format (JSON that didn't parse). + pub note: Option, + /// The unified diff (`@@` hunks), for agents. Left out of the web app's JSON, which has the lines. + #[serde(skip)] + pub unified: String, + /// Each side's whole normalized text: `None` for a side the snapshot doesn't have. + pub base: Option, + pub head: Option, +} + +pub const JSON_CHANGE_LIMIT: usize = 200; + +/// Everything a reviewer sees of a snapshot. +pub struct ReviewDetail { + pub pages: Vec, + pub moved: Vec, + pub text: Option, +} + +/// Unchanged lines shown around each change, unless the reviewer asks for the whole text. +pub const DEFAULT_CONTEXT: usize = 3; + +/// Every page of the comparison with presigned image URLs, text diffs (with `context` unchanged lines around each +/// change), the lines that moved to another page, and for text snapshots their format and JSON changes by path. +/// +/// # Errors +/// On a database error. +pub async fn review_detail(snapshot: &Snapshot, store: &BlobStore, context: usize) -> laravel::Result { + let rows = pages::of(store, snapshot).await?; + detail_of(snapshot, store, context, &rows).await +} + +/// This snapshot in an earlier build of the same project, suite (build name) and branch: build `number`, or the newest earlier one where +/// it wasn't failed, removed or pending. Read through `effective_snapshots`, so a build that holds it as a sourced +/// group counts. +/// +/// # Errors +/// On a database error. +pub async fn earlier( + snapshot: &Snapshot, + build: &Build, + number: Option, +) -> laravel::Result> { + let (project_id, branch, before, suite) = + (build.project_id, build.branch.as_str(), build.number, build.name.as_str()); + let (name, platform) = (snapshot.name.as_str(), snapshot.platform.as_str()); + let found: Option = db::query!( + "SELECT s.* FROM effective_snapshots s JOIN builds b ON b.id = s.build_id \ + WHERE b.project_id = {project_id} AND b.name = {suite} AND b.branch = {branch} AND b.number < {before} \ + AND ({number}::INT IS NULL OR b.number = {number}) \ + AND s.name = {name} AND s.platform = {platform} AND s.state NOT IN ('failed', 'removed', 'pending') \ + ORDER BY b.number DESC LIMIT 1" + ) + .select_one_as() + .await?; + let Some(found) = found else { return Ok(None) }; + let Some(earlier_build) = Build::find(found.build_id).await? else { return Ok(None) }; + Ok(Some((earlier_build, found))) +} + +/// The comparison of this snapshot's new side with an earlier build's new side (the previous build of the branch, +/// say): "did the fix answer the comment?". A view only: it changes no state, review or credits. Diffs are computed on +/// first use and cached like any other. +/// +/// # Errors +/// When an image is missing or can't be diffed. +pub async fn review_detail_against( + snapshot: &Snapshot, + store: &BlobStore, + earlier: &Snapshot, + options: visualci_core::diff::DiffOptions, + context: usize, +) -> laravel::Result { + let heads = async |s: &Snapshot| -> laravel::Result> { + let mut rows: Vec = pages::of(store, s).await?.into_iter().filter(|r| r.head_index.is_some()).collect(); + rows.sort_by_key(|r| r.head_index); + Ok(rows) + }; + let (old, new) = (heads(earlier).await?, heads(snapshot).await?); + let key = |r: &Page| r.head_image.clone().or_else(|| r.head_text.clone()).unwrap_or_default(); + let text = + |rows: &[Page]| -> Vec { rows.iter().map(|r| r.head_text.clone().unwrap_or_default()).collect() }; + let (old_text, new_text) = (text(&old), text(&new)); + let has_text = old_text.iter().chain(&new_text).any(|t| !t.is_empty()); + let ops = align_pages( + &old.iter().map(key).collect::>(), + &new.iter().map(key).collect::>(), + has_text.then_some(old_text.as_slice()), + has_text.then_some(new_text.as_slice()), + ); + let row = |position: usize, op: &str, state: &str, b: Option<&Page>, h: Option<&Page>, diff_id: Option| Page { + position: i32::try_from(position).unwrap_or(i32::MAX), + op: op.into(), + state: state.into(), + head_index: h.and_then(|h| h.head_index), + base_index: b.and_then(|b| b.head_index), + head_image: h.and_then(|h| h.head_image.clone()), + base_image: b.and_then(|b| b.head_image.clone()), + head_text: h.and_then(|h| h.head_text.clone()), + base_text: b.and_then(|b| b.head_text.clone()), + diff_id, + }; + let mut rows = Vec::new(); + for (position, op) in ops.iter().enumerate() { + rows.push(match *op { + PageOp::Unchanged { base: b, head: h } => { + row(position, "unchanged", "unchanged", Some(&old[b]), Some(&new[h]), None) + } + PageOp::Inserted { head: h } => row(position, "inserted", "changed", None, Some(&new[h]), None), + PageOp::Removed { base: b } => row(position, "removed", "changed", Some(&old[b]), None, None), + PageOp::Changed { base: b, head: h } => { + let (bp, hp) = (&old[b], &new[h]); + match (&bp.head_image, &hp.head_image) { + (Some(bi), Some(hi)) => { + let diff = super::diffs::find_or_compute(store, bi, hi, options).await?; + let state = if super::diffs::is_change(&diff) { "changed" } else { "within_threshold" }; + row(position, "changed", state, Some(bp), Some(hp), Some(diff.id)) + } + _ => { + let state = if bp.head_text == hp.head_text { "unchanged" } else { "changed" }; + row(position, "changed", state, Some(bp), Some(hp), None) + } + } + } + }); + } + detail_of(snapshot, store, context, &rows).await +} + +async fn detail_of( + snapshot: &Snapshot, + store: &BlobStore, + context: usize, + rows: &[Page], +) -> laravel::Result { + let mut pages = Vec::new(); + let (mut base_texts, mut head_texts) = (Vec::new(), Vec::new()); + // The images that still exist (retention deletes some), with their sizes where known. + let named: Vec = rows.iter().flat_map(|r| [r.head_image.clone(), r.base_image.clone()]).flatten().collect(); + let mut stored: HashMap> = HashMap::new(); + for chunk in named.chunks(10_000) { + for b in Blob::query().filter(Blob::sha256.is_in(chunk.to_vec())).get().await? { + stored.insert(b.sha256, b.width.zip(b.height).map(|(w, h)| [w, h])); + } + } + let size = |sha: &Option| sha.as_ref().and_then(|s| stored.get(s).copied().flatten()); + for row in rows { + if let (Some(i), Some(t)) = (row.base_index, &row.base_text) { + base_texts.push((i, t.clone())); + } + if let (Some(i), Some(t)) = (row.head_index, &row.head_text) { + head_texts.push((i, t.clone())); + } + let diff = match row.diff_id { + Some(id) => Diff::find(id).await?, + None => None, + }; + let text_diff = if row.state == "unchanged" { + Vec::new() + } else { + visualci_core::text::page_diff( + row.base_text.as_deref().unwrap_or(""), + row.head_text.as_deref().unwrap_or(""), + context, + ) + }; + let expired = [&row.head_image, &row.base_image].into_iter().flatten().any(|s| !stored.contains_key(s)); + let overlay = diff.as_ref().and_then(|d| d.overlay_blob.clone()).filter(|_| !expired); + let url = |s: &Option| s.as_ref().filter(|_| !expired).and_then(|s| store.download_url(s).ok()); + pages.push(PageDetail { + position: row.position, + op: row.op.clone(), + state: row.state.clone(), + head_index: row.head_index, + base_index: row.base_index, + head_url: url(&row.head_image), + base_url: url(&row.base_image), + overlay_url: overlay.as_ref().and_then(|s| store.download_url(s).ok()), + expired, + base_size: size(&row.base_image), + head_size: size(&row.head_image), + head_image: row.head_image.clone(), + base_image: row.base_image.clone(), + overlay_image: overlay, + diff: diff.as_ref().and_then(super::diffs::result), + text_diff, + }); + } + let ordered = |mut v: Vec<(i32, String)>| { + v.sort_by_key(|(i, _)| *i); + v.into_iter().map(|(_, t)| t).collect::>() + }; + let text = text_format(snapshot).map(|format| { + let row = rows.first(); + let base = row.and_then(|r| r.base_text.as_deref()).unwrap_or(""); + let head = row.and_then(|r| r.head_text.as_deref()).unwrap_or(""); + let mut detail = text_detail(format, base, head, row.is_some_and(|r| r.base_text.is_some())); + detail.base = row.and_then(|r| r.base_text.clone()); + detail.head = row.and_then(|r| r.head_text.clone()).filter(|_| snapshot.state != "removed"); + detail + }); + let moved = if text.is_some() { + Vec::new() + } else { + visualci_core::text::moved_lines(&ordered(base_texts), &ordered(head_texts)) + }; + Ok(ReviewDetail { pages, moved, text }) +} + +/// The format a text was compared in, its JSON changes by path, and its unified diff. The stored texts are already +/// normalized, so JSON that doesn't parse here was compared as plain text. +#[must_use] +pub fn text_detail(format: Format, base: &str, head: &str, has_base: bool) -> TextDetail { + let parse = |t: &str| serde_json::from_str::(t); + let (format, json_changes, truncated, note) = match format { + Format::Json => match (parse(head), has_base.then(|| parse(base))) { + (Ok(h), Some(Ok(b))) => { + let (changes, more) = snapshot_text::json_changes(&b, &h, JSON_CHANGE_LIMIT); + (Format::Json, changes, more, None) + } + (Ok(_), None) => (Format::Json, Vec::new(), false, None), + (Ok(_), Some(Err(_))) => ( + Format::Json, + Vec::new(), + false, + Some("the base wasn't valid JSON, so there are no changes by path".into()), + ), + (Err(e), _) => { + (Format::Text, Vec::new(), false, Some(format!("not valid JSON ({e}), compared as plain text"))) + } + }, + other => (other, Vec::new(), false, None), + }; + TextDetail { + format: format.as_str().to_string(), + base_lines: base.lines().count(), + head_lines: head.lines().count(), + json_changes, + json_changes_truncated: truncated, + note, + unified: snapshot_text::unified(base, head, DEFAULT_CONTEXT), + base: None, + head: None, + } +} + +/// How big a snapshot's change is, for putting the biggest in front of a reviewer first: the largest share of a page +/// that changed (an inserted or removed page counts whole; for text, the share of lines added or removed) and, to break +/// ties, how many pixels (or lines) changed. +#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize)] +pub struct ChangeSize { + pub fraction: f64, + pub amount: i64, +} + +/// The order snapshots are listed in for review. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum ReviewOrder { + /// Changed snapshots, the largest change first; then added, removed, failed and the rest. The default. + #[default] + Change, + /// By name. + Name, +} + +/// Each changed snapshot's [`ChangeSize`] in a build, by snapshot id. Changes are always the build's own rows. +/// +/// # Errors +/// On a database error. +pub async fn change_sizes(build_id: i64) -> laravel::Result> { + let mut sizes = HashMap::new(); + let pixels = db::query!( + "SELECT p.snapshot_id, \ + MAX(CASE WHEN p.op IN ('inserted', 'removed') THEN 1.0 ELSE COALESCE(d.changed_fraction, 0) END)::FLOAT8 \ + AS fraction, \ + COALESCE(SUM(d.changed_pixels), 0)::BIGINT AS amount \ + FROM snapshot_pages p JOIN snapshots s ON s.id = p.snapshot_id LEFT JOIN diffs d ON d.id = p.diff_id \ + WHERE s.build_id = {build_id} AND s.kind <> 'text' AND p.state = 'changed' GROUP BY p.snapshot_id" + ) + .select() + .await?; + for r in pixels { + sizes.insert( + r.try_get::("snapshot_id")?, + ChangeSize { fraction: r.try_get("fraction")?, amount: r.try_get("amount")? }, + ); + } + let texts = db::query!( + "SELECT p.snapshot_id, bt.body AS base_text, ht.body AS head_text FROM snapshot_pages p \ + JOIN snapshots s ON s.id = p.snapshot_id \ + LEFT JOIN texts bt ON bt.sha256 = p.base_text_sha LEFT JOIN texts ht ON ht.sha256 = p.head_text_sha \ + WHERE s.build_id = {build_id} AND s.kind = 'text' AND p.state = 'changed'" + ) + .select() + .await?; + for r in texts { + let base: String = r.try_get::>("base_text")?.unwrap_or_default(); + let head: String = r.try_get::>("head_text")?.unwrap_or_default(); + let changed = visualci_core::text::page_diff(&base, &head, 0).iter().filter(|l| l.tag != " ").count(); + let lines = base.lines().count().max(head.lines().count()).max(1); + let size = ChangeSize { + #[allow(clippy::cast_precision_loss)] + fraction: (changed as f64 / lines as f64).min(1.0), + amount: i64::try_from(changed).unwrap_or(i64::MAX), + }; + let entry = sizes.entry(r.try_get::("snapshot_id")?).or_default(); + if size.fraction > entry.fraction { + *entry = size; + } + } + Ok(sizes) +} + +/// The review order of a state: what needs a decision first. +fn state_rank(state: &str) -> u8 { + match state { + "changed" => 0, + "added" => 1, + "removed" => 2, + "failed" => 3, + "pending" => 4, + "ignored" => 5, + _ => 6, + } +} + +/// Sort a build's snapshots for review. Ties go by name and platform, so the order is the same every time. +pub fn sort_for_review(list: &mut [Snapshot], sizes: &HashMap, order: ReviewOrder) { + let by_name = |a: &Snapshot, b: &Snapshot| a.name.cmp(&b.name).then_with(|| a.platform.cmp(&b.platform)); + match order { + ReviewOrder::Name => list.sort_by(by_name), + ReviewOrder::Change => list.sort_by(|a, b| { + let (sa, sb) = + (sizes.get(&a.id).copied().unwrap_or_default(), sizes.get(&b.id).copied().unwrap_or_default()); + state_rank(&a.state) + .cmp(&state_rank(&b.state)) + .then_with(|| sb.fraction.total_cmp(&sa.fraction)) + .then_with(|| sb.amount.cmp(&sa.amount)) + .then_with(|| by_name(a, b)) + }), + } +} + +/// How many of a branch's newest builds the flaky hint looks at. +pub const FLAKY_WINDOW: i64 = 8; + +/// Whether a run of versions, oldest first, changed at least three times and came back to an earlier version. +#[must_use] +pub fn flips(versions: &[String]) -> bool { + let changes = versions.windows(2).filter(|w| w[0] != w[1]).count(); + let returned = + versions.iter().enumerate().skip(1).any(|(i, v)| versions[i - 1] != *v && versions[..i - 1].contains(v)); + changes >= 3 && returned +} + +/// The snapshots of this build that look flaky, by name and platform: over the newest builds of its suite on its +/// branch, up to this one ([`FLAKY_WINDOW`]), the content changed at least three times and came back to a version it +/// had before (A, B, A, B). Only a hint for whoever reviews. +/// +/// # Errors +/// On a database error. +pub async fn flaky_in(build: &Build) -> laravel::Result> { + let (project_id, name, branch, id) = (build.project_id, build.name.as_str(), build.branch.as_str(), build.id); + let recent: Vec = db::query!( + "SELECT id FROM builds WHERE project_id = {project_id} AND name = {name} AND branch = {branch} AND id <= {id} \ + ORDER BY id DESC LIMIT {FLAKY_WINDOW}" + ) + .select() + .await? + .iter() + .filter_map(|r| r.try_get("id").ok()) + .collect(); + // Three changes need at least four builds. + if recent.len() < 4 { + return Ok(std::collections::HashSet::new()); + } + let rows = db::query!( + "SELECT build_id, name, platform, source_fingerprint FROM effective_snapshots \ + WHERE build_id IN ({...recent}) AND source_fingerprint <> '' ORDER BY build_id" + ) + .select() + .await?; + let mut history: HashMap<(String, String), Vec> = HashMap::new(); + for r in rows { + history.entry((r.try_get("name")?, r.try_get("platform")?)).or_default().push(r.try_get("source_fingerprint")?); + } + Ok(history.into_iter().filter(|(_, versions)| flips(versions)).map(|(key, _)| key).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn flipping_back_and_forth_is_flaky() { + let run = |s: &str| s.chars().map(String::from).collect::>(); + assert!(flips(&run("ABAB"))); + assert!(flips(&run("AABBAAB"))); + assert!(flips(&run("ABCA"))); + assert!(!flips(&run("AAAA"))); + assert!(!flips(&run("ABCD"))); + assert!(!flips(&run("ABA"))); + assert!(!flips(&run("AABBA"))); + } + + #[test] + fn json_detail_lists_changes_by_path() { + let d = text_detail(Format::Json, "{\"price\": 10, \"x\": 1}", "{\"price\": 12, \"x\": 1}", true); + assert_eq!(d.format, "json"); + assert_eq!( + d.json_changes.iter().map(snapshot_text::PathChange::line).collect::>(), + vec!["price: 10 → 12"] + ); + assert!(d.unified.contains("@@")); + let bad = text_detail(Format::Json, "", "{oops", false); + assert_eq!(bad.format, "text"); + assert!(bad.note.unwrap().contains("not valid JSON")); + } +} diff --git a/app/src/domain/diffs.rs b/app/src/domain/diffs.rs new file mode 100644 index 00000000..2ab1e0a1 --- /dev/null +++ b/app/src/domain/diffs.rs @@ -0,0 +1,105 @@ +//! Image diffs, cached by (base image, head image, options): the same pair is never diffed twice. + +use std::io::Cursor; + +use laravel::db; +use laravel::model::update; +use visualci_core::diff::{DiffOptions, DiffResult}; + +use crate::models::Diff; +use crate::storage::BlobStore; + +#[must_use] +pub fn options_key(options: &DiffOptions) -> String { + format!("{}/t{}/aa{}", visualci_core::diff::ALGORITHM, options.threshold, u8::from(options.ignore_anti_aliasing)) +} + +#[must_use] +pub fn result(diff: &Diff) -> Option { + serde_json::from_value(diff.result.clone()).ok() +} + +#[must_use] +pub fn is_change(diff: &Diff) -> bool { + diff.size_changed || diff.changed_pixels > 0 +} + +async fn find(base_image: &str, head_image: &str, key: &str) -> laravel::Result> { + Diff::query() + .filter(Diff::base_image.eq(base_image) & Diff::head_image.eq(head_image) & Diff::options_key.eq(key)) + .first() + .await +} + +/// Note that a comparison reuses this diff now (at most once an hour): retention leaves its overlay alone for a day +/// after. +async fn mark_used(diff_id: i64) -> laravel::Result<()> { + db::query!( + "UPDATE diffs SET used_at = now() \ + WHERE id = {diff_id} AND (used_at IS NULL OR used_at < now() - interval '1 hour')" + ) + .update() + .await?; + Ok(()) +} + +/// The diff of two images, computed (with its overlay stored as a blob) on first use. A diff whose overlay retention +/// deleted is computed again, and keeps its row. +/// +/// # Errors +/// When an image is missing or can't be decoded. +pub async fn find_or_compute( + store: &BlobStore, + base_image: &str, + head_image: &str, + options: DiffOptions, +) -> laravel::Result { + let key = options_key(&options); + let stale = match find(base_image, head_image, &key).await? { + Some(diff) if diff.overlay_blob.is_some() || result(&diff).is_none_or(|r| r.is_identical()) => { + mark_used(diff.id).await?; + return Ok(diff); + } + other => other, + }; + let (base_bytes, head_bytes) = (store.get(base_image).await?, store.get(head_image).await?); + let (outcome, overlay_png) = laravel::task::spawn_blocking(move || -> Result<_, String> { + let base = visualci_core::image_hash::decode(&base_bytes).map_err(|e| e.to_string())?.to_rgba8(); + let head = visualci_core::image_hash::decode(&head_bytes).map_err(|e| e.to_string())?.to_rgba8(); + let (outcome, overlay) = visualci_core::diff::diff(&base, &head, options); + let overlay_png = if outcome.is_identical() { + None + } else { + let mut png = Vec::new(); + overlay.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| e.to_string())?; + Some(png) + }; + Ok((outcome, overlay_png)) + }) + .await + .map_err(|e| laravel::Error::msg(e.to_string()))? + .map_err(|e| laravel::Error::msg(format!("diffing {base_image} and {head_image}: {e}")))?; + + let overlay_blob = match overlay_png { + Some(png) => Some(super::blobs::put(store, png, "image/png").await?.sha256), + None => None, + }; + if let Some(mut diff) = stale { + update!(diff { overlay_blob }).await?; + return Ok(diff); + } + let changed_pixels = i64::try_from(outcome.changed_pixels).unwrap_or(i64::MAX); + let (fraction, size_changed, fingerprint) = + (outcome.changed_fraction, outcome.size_changed, outcome.fingerprint.clone()); + let json = serde_json::to_value(&outcome).unwrap_or_default(); + db::query!( + "INSERT INTO diffs (base_image, head_image, options_key, changed_pixels, changed_fraction, size_changed, \ + fingerprint, result, overlay_blob) \ + VALUES ({base_image}, {head_image}, {key}, {changed_pixels}, {fraction}, {size_changed}, {fingerprint}, \ + {json}, {overlay_blob}) \ + ON CONFLICT (base_image, head_image, options_key) DO NOTHING" + ) + .insert() + .await?; + find(base_image, head_image, &key).await?.ok_or_else(|| laravel::Error::msg("the diff vanished after its insert")) +} diff --git a/app/src/domain/downloads.rs b/app/src/domain/downloads.rs new file mode 100644 index 00000000..b090ce67 --- /dev/null +++ b/app/src/domain/downloads.rs @@ -0,0 +1,550 @@ +//! Bulk downloads (sc-8869): a build's images as one tar.zst, for a close look at a big build on disk or for checks +//! of one's own. A job builds the archive and streams it to the bucket in parts; it's handed out as a presigned URL. +//! A ready download of the same build and filter from the last hour is handed out again. Free: it's a read of what was +//! already compared. +//! +//! The archive holds `[@][/page-]/{base,head,diff,regions}.` (`regions` is the head cropped to +//! the changed regions) and `manifest.json`, which lists every snapshot with its state, pages, changed fraction, +//! regions, files and URL. Snapshots are read through `effective_snapshots`, so a build that reads a group from an +//! earlier build downloads that group's images too. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use laravel::db; +use laravel::model::create; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use visualci_core::bundle; + +use super::pages; +use crate::models::{Build, Diff, Download, Snapshot}; +use crate::storage::BlobStore; + +/// The most an archive may hold, compressed. A bigger one stops with an error that suggests a narrower glob. +pub const MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024; +/// How long a ready download is handed out again. +pub const REUSE_MINUTES: i32 = 60; +/// How long the archive stays in the bucket (the URL itself lasts an hour from each request). +pub const KEEP_HOURS: i32 = 24; +/// A download still building after this long has stopped (a worker restart): the next request starts another. +pub const STALE_MINUTES: i32 = 15; +/// How many downloads one project may have pending or building at once. +pub const MAX_BUILDING_PER_PROJECT: i64 = 3; +/// How long building one archive may take before it fails (an incomplete upload is cleared by the bucket's lifecycle +/// rule). +pub const BUILD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(14 * 60); +/// The bucket's parts: every part but the last must be at least 5 MiB. +const PART_BYTES: usize = 16 * 1024 * 1024; + +/// What to put in the archive. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Filter { + /// Which snapshots: `changed` (the default), `added`, `removed`, `unchanged`, or `all`. + #[serde(default)] + pub state: Option, + /// Which images of each page: `base`, `head`, `diff`, `regions` (the head cropped to the changes). Default: base, + /// head and diff. + #[serde(default)] + pub sides: Option>, + /// Only snapshots whose name matches this glob, like `v2/pdfjs/**`. + #[serde(default)] + pub glob: Option, +} + +pub const STATES: &[&str] = &["changed", "added", "removed", "unchanged", "all"]; +pub const SIDES: &[&str] = &["base", "head", "diff", "regions"]; + +impl Filter { + /// The filter with its defaults filled in and its sides in a fixed order, or an error that says what's wrong. + /// + /// # Errors + /// For an unknown state or side, or a glob that doesn't parse. + pub fn normalized(&self) -> Result { + let state = self.state.clone().unwrap_or_else(|| "changed".to_string()); + if !STATES.contains(&state.as_str()) { + return Err(format!("state must be one of {}", STATES.join(", "))); + } + let wanted = self.sides.clone().unwrap_or_else(|| vec!["base".into(), "head".into(), "diff".into()]); + if let Some(bad) = wanted.iter().find(|s| !SIDES.contains(&s.as_str())) { + return Err(format!("unknown side {bad:?}: sides are {}", SIDES.join(", "))); + } + let sides: Vec = + SIDES.iter().filter(|s| wanted.iter().any(|w| w == *s)).map(|s| (*s).to_string()).collect(); + if sides.is_empty() { + return Err(format!("sides needs at least one of {}", SIDES.join(", "))); + } + let glob = self.glob.clone().filter(|g| !g.trim().is_empty()); + if let Some(g) = &glob { + globset::Glob::new(g).map_err(|e| format!("glob {g:?}: {e}"))?; + } + Ok(Self { state: Some(state), sides: Some(sides), glob }) + } + + fn key(&self) -> String { + visualci_core::sha256_hex(serde_json::to_string(self).unwrap_or_default().as_bytes()) + } + + fn wants(&self, side: &str) -> bool { + self.sides.as_ref().is_some_and(|s| s.iter().any(|x| x == side)) + } +} + +/// Why a download wasn't started. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Refused { + /// The filter isn't valid. + Invalid(String), + /// The project already has [`MAX_BUILDING_PER_PROJECT`] downloads pending or building. + Busy(String), +} + +/// The download for this build and filter: a ready or building one from the last hour, or a new pending one (`true` +/// when it's new and needs a job). A project has at most [`MAX_BUILDING_PER_PROJECT`] building at once. +/// +/// # Errors +/// `Ok(Err(_))` when it's refused; `Err` on a database error. +pub async fn request(build: &Build, filter: &Filter) -> laravel::Result> { + let filter = match filter.normalized() { + Ok(f) => f, + Err(m) => return Ok(Err(Refused::Invalid(m))), + }; + let key = filter.key(); + let (build_id, reuse, stale) = (build.id, REUSE_MINUTES, STALE_MINUTES); + let recent: Option = db::query!( + "SELECT * FROM downloads WHERE build_id = {build_id} AND filter_key = {key} AND ( \ + (state = 'ready' AND ready_at > now() - make_interval(mins => {reuse})) \ + OR (state IN ('pending', 'building') AND updated_at > now() - make_interval(mins => {stale}))) \ + ORDER BY created_at DESC LIMIT 1" + ) + .select_one_as() + .await?; + if let Some(d) = recent { + return Ok(Ok((d, false))); + } + let project_id = build.project_id; + let building: i64 = db::query!( + "SELECT COUNT(*) FROM downloads d JOIN builds b ON b.id = d.build_id \ + WHERE b.project_id = {project_id} AND d.state IN ('pending', 'building') \ + AND d.updated_at > now() - make_interval(mins => {stale})" + ) + .scalar() + .await? + .unwrap_or(0); + if building >= MAX_BUILDING_PER_PROJECT { + return Ok(Err(Refused::Busy(format!( + "{building} downloads are being built for this project: wait for one to finish (at most \ + {MAX_BUILDING_PER_PROJECT} at once)" + )))); + } + let filter = serde_json::to_value(&filter).unwrap_or_default(); + let created = create!(Download { + pid: laravel::str::uuid7(), + build_id: build_id, + filter: filter, + filter_key: key, + state: "pending", + }) + .await?; + Ok(Ok((created, true))) +} + +/// What the API, MCP and the web app show: its state, and when it's ready the URL (an hour), files, size and the +/// manifest's summary. +#[must_use] +pub fn to_json(download: &Download, store: &BlobStore) -> serde_json::Value { + let url = + (download.state == "ready").then(|| download.object_key.as_deref().map(|k| store.object_url(k))).flatten(); + json!({ + "id": download.pid, + "state": download.state, + "filter": download.filter, + "url": url, + "files": download.files, + "bytes": download.bytes, + "summary": download.summary, + "error": download.error, + }) +} + +/// Build the archive and upload it. The download ends `ready`, or `failed` with the reason. +/// +/// # Errors +/// On a database error (a failed build of the archive is recorded on the download, not returned). +pub async fn build(download: Download, store: &BlobStore) -> laravel::Result<()> { + let id = download.id; + // One conditional update: a second job for the same download (a retry, a duplicate dispatch) finds it taken. + let taken = + db::query!("UPDATE downloads SET state = 'building', updated_at = now() WHERE id = {id} AND state = 'pending'") + .update() + .await?; + if taken == 0 { + return Ok(()); + } + let key = format!("downloads/{}.tar.zst", download.pid); + let written = + tokio::time::timeout(BUILD_TIMEOUT, write_archive(store, &download, &key)).await.unwrap_or_else(|_| { + Err(format!( + "Building the archive took longer than {} minutes: download part of the build with a narrower glob", + BUILD_TIMEOUT.as_secs() / 60 + )) + }); + match written { + Ok((files, bytes, summary)) => { + let bytes = i64::try_from(bytes).unwrap_or(i64::MAX); + db::query!( + "UPDATE downloads SET state = 'ready', object_key = {key}, files = {files}, bytes = {bytes}, \ + summary = {summary}, ready_at = now(), updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + } + Err(e) => { + tracing::warn!(download = %download.pid, error = %e, "building a download failed"); + db::query!("UPDATE downloads SET state = 'failed', error = {e}, updated_at = now() WHERE id = {id}") + .update() + .await?; + } + } + Ok(()) +} + +/// Delete downloads older than [`KEEP_HOURS`] and their archives (retention runs it daily). Returns how many it +/// deleted. +/// +/// # Errors +/// On a database error. An archive the store can't delete is logged and left for the next run. +pub async fn prune(store: Option<&BlobStore>) -> laravel::Result { + let keep = KEEP_HOURS; + let old: Vec = + db::query!("SELECT * FROM downloads WHERE created_at < now() - make_interval(hours => {keep})") + .select_as() + .await?; + let mut deleted = 0; + for d in old { + if let (Some(store), Some(key)) = (store, d.object_key.as_deref()) + && let Err(e) = store.delete_object(key).await + { + tracing::warn!(key, error = %e, "deleting an old download failed"); + continue; + } + let id = d.id; + db::query!("DELETE FROM downloads WHERE id = {id}").delete().await?; + deleted += 1; + } + Ok(deleted) +} + +/// A `Write` the archive goes into, from which full parts are taken and uploaded. +#[derive(Clone, Default)] +struct Parts(Arc>>); + +impl std::io::Write for Parts { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().map_err(|_| std::io::Error::other("poisoned"))?.extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl Parts { + /// The buffered bytes when there are at least `min` of them (all of them when `min` is 0). + fn take(&self, min: usize) -> Option> { + let mut buf = self.0.lock().ok()?; + (buf.len() >= min && !buf.is_empty()).then(|| std::mem::take(&mut *buf)) + } +} + +/// A path part made safe for a file name: `/` stays a directory separator, `.` and `..` parts and anything outside +/// letters, digits and a few marks become `_`. +fn path_part(name: &str) -> String { + name.split('/') + .filter(|p| !p.is_empty()) + .map(|p| { + let s: String = + p.chars().map(|c| if c.is_alphanumeric() || " ._-()+=,@".contains(c) { c } else { '_' }).collect(); + if s == "." || s == ".." { "_".to_string() } else { s } + }) + .collect::>() + .join("/") +} + +/// The archive's paths so far, so every snapshot and page directory is one of its own. Names made safe can meet (`a:b` +/// and `a?b` are both `a_b`), a snapshot can be named like another's page (`x/page-2` beside page 2 of `x`), and a name +/// can be another's file (`x/head.png` beside `x`'s head image). A directory that would meet one already used, as a +/// directory or as a file, or whose files would meet a directory, is suffixed `~2`, `~3`… (the manifest names each +/// snapshot's paths). +#[derive(Default)] +struct Layout { + /// Snapshot and page directories handed out. + taken: std::collections::HashSet, + /// Every directory above a path handed out. + parents: std::collections::HashSet, + /// Files a directory handed out may hold: `/.`. + files: std::collections::HashSet, +} + +const EXTENSIONS: &[&str] = &["png", "jpg", "webp"]; + +fn ancestors(path: &str) -> impl Iterator { + path.char_indices().filter(|(_, c)| *c == '/').map(move |(i, _)| &path[..i]) +} + +impl Layout { + fn planned_files(dir: &str) -> impl Iterator + '_ { + SIDES.iter().flat_map(move |side| EXTENSIONS.iter().map(move |ext| format!("{dir}/{side}.{ext}"))) + } + + /// Whether `dir` can be handed out, holding files (`with_files`) or only page directories. + fn free(&self, dir: &str, with_files: bool) -> bool { + !self.taken.contains(dir) + && !self.files.contains(dir) + && !ancestors(dir).any(|a| self.files.contains(a)) + && (!with_files || Self::planned_files(dir).all(|f| !self.taken.contains(&f) && !self.parents.contains(&f))) + } + + /// Hand out `dir`, or the first `dir~N` that's free. + fn take(&mut self, dir: &str, with_files: bool) -> String { + let chosen = if self.free(dir, with_files) { + dir.to_string() + } else { + (2..).map(|n| format!("{dir}~{n}")).find(|d| self.free(d, with_files)).unwrap_or_else(|| dir.to_string()) + }; + self.parents.extend(ancestors(&chosen).map(str::to_string)); + if with_files { + self.files.extend(Self::planned_files(&chosen)); + } + self.taken.insert(chosen.clone()); + chosen + } +} + +fn extension(bytes: &[u8]) -> &'static str { + match image::guess_format(bytes) { + Ok(image::ImageFormat::Jpeg) => "jpg", + Ok(image::ImageFormat::WebP) => "webp", + _ => "png", + } +} + +fn too_big() -> String { + format!( + "The archive would be larger than {} GB: download part of the build with a narrower glob (like `v2/**`) or \ + fewer sides", + MAX_BYTES / (1024 * 1024 * 1024) + ) +} + +fn text(e: impl std::fmt::Display) -> String { + e.to_string() +} + +/// The snapshots the filter picks from the build: every one it holds or reads, but not its settings item or text +/// snapshots (they have no images). +async fn chosen(build: &Build, filter: &Filter) -> Result, String> { + let glob = + filter.glob.as_deref().map(|g| globset::Glob::new(g).map(|g| g.compile_matcher())).transpose().map_err(text)?; + let state = filter.state.clone().unwrap_or_else(|| "changed".to_string()); + Ok(super::snapshots::of_build(build.id) + .await + .map_err(text)? + .into_iter() + .filter(|s| s.platform != super::snapshots::CONFIG_PLATFORM && s.kind != "text") + .filter(|s| state == "all" || s.state == state) + .filter(|s| glob.as_ref().is_none_or(|g| g.is_match(&s.name))) + .collect()) +} + +/// Write the archive to the bucket. Returns its files, its compressed size and the manifest's summary. +async fn write_archive( + store: &BlobStore, + download: &Download, + key: &str, +) -> Result<(i32, u64, serde_json::Value), String> { + let filter: Filter = serde_json::from_value(download.filter.clone()).map_err(text)?; + let build = Build::find_or_fail(download.build_id).await.map_err(text)?; + let chosen = chosen(&build, &filter).await?; + let refs: Vec<&Snapshot> = chosen.iter().collect(); + let pages_of = pages::of_many(None, &refs).await.map_err(text)?; + let diff_ids: Vec = pages_of.values().flatten().filter_map(|p| p.diff_id).collect(); + let mut diffs: HashMap = HashMap::new(); + for chunk in diff_ids.chunks(10_000) { + for d in Diff::query().filter(Diff::id.is_in(chunk.to_vec())).get().await.map_err(text)? { + diffs.insert(d.id, d); + } + } + + let parts = Parts::default(); + let mut writer = bundle::Writer::new(parts.clone()).map_err(text)?; + let mut upload = store.start_multipart(key, "application/zstd").await.map_err(text)?; + let mut sent: u64 = 0; + let mut files = 0i32; + let mut entries = Vec::new(); + let result: Result<(), String> = async { + let mut layout = Layout::default(); + for s in &chosen { + let mut dir = path_part(&s.name); + if !s.platform.is_empty() { + dir = format!("{dir}@{}", path_part(&s.platform)); + } + let pages = pages_of.get(&s.id).map(Vec::as_slice).unwrap_or_default(); + let several = pages.len() > 1; + // A single page's files go in the snapshot's directory; several pages each get one beneath it. + let dir = layout.take(&dir, !several); + let mut listed = Vec::new(); + for p in pages { + let page_dir = + if several { layout.take(&format!("{dir}/page-{}", p.position + 1), true) } else { dir.clone() }; + let diff = p.diff_id.and_then(|id| diffs.get(&id)); + let result = diff.and_then(super::diffs::result); + let regions = result.as_ref().map(|r| r.regions.as_slice()).unwrap_or_default(); + let mut written = Vec::new(); + for side in SIDES { + if !filter.wants(side) { + continue; + } + let sha = match *side { + "base" => p.base_image.as_deref(), + "head" | "regions" => p.head_image.as_deref(), + _ => diff.and_then(|d| d.overlay_blob.as_deref()), + }; + let Some(sha) = sha else { continue }; + if *side == "regions" && regions.is_empty() { + continue; + } + let mut bytes = store.get(sha).await.map_err(text)?; + if *side == "regions" { + bytes = crate::mcp::images::crop_png(&bytes, regions).unwrap_or(bytes); + } + let path = format!("{page_dir}/{side}.{}", extension(&bytes)); + writer.add(&path, &bytes).map_err(text)?; + files += 1; + written.push(path); + if let Some(part) = parts.take(PART_BYTES) { + sent += part.len() as u64; + if sent > MAX_BYTES { + return Err(too_big()); + } + upload.part(part).await.map_err(text)?; + } + } + listed.push(json!({ + "position": p.position, + "state": p.state, + "changed_fraction": result.as_ref().map(|r| r.changed_fraction), + "regions": result.as_ref().map(|r| &r.regions), + "files": written, + })); + } + entries.push(json!({ + "name": s.name, + "platform": s.platform, + "state": s.state, + "path": dir, + "pages": listed, + })); + } + Ok(()) + } + .await; + if let Err(e) = result { + upload.abort().await; + return Err(e); + } + let mut counts = std::collections::BTreeMap::::new(); + for s in &chosen { + *counts.entry(s.state.clone()).or_default() += 1; + } + let summary = json!({ + "build": build.number, + "snapshots": chosen.len(), + "by_state": counts, + "names": chosen.iter().take(20).map(|s| &s.name).collect::>(), + }); + let manifest = json!({ "build": build.number, "commit": build.commit_sha, "filter": filter, "snapshots": entries }); + let finished = async { + writer.add(bundle::MANIFEST, &serde_json::to_vec_pretty(&manifest).map_err(text)?).map_err(text)?; + writer.finish().map_err(text)?; + if let Some(last) = parts.take(0) { + sent += last.len() as u64; + if sent > MAX_BYTES { + return Err(too_big()); + } + upload.part(last).await.map_err(text)?; + } + Ok::<_, String>(()) + } + .await; + if let Err(e) = finished { + upload.abort().await; + return Err(e); + } + upload.complete().await.map_err(text)?; + Ok((files + 1, sent, summary)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn path_parts_stay_inside_the_archive() { + assert_eq!(path_part("v2/pdfjs/invoice page"), "v2/pdfjs/invoice page"); + assert_eq!(path_part("../../etc/passwd"), "_/_/etc/passwd"); + assert_eq!(path_part("/a//b:c"), "a/b_c"); + } + + #[test] + fn names_that_become_the_same_path_get_their_own_directories() { + let mut layout = Layout::default(); + let dirs: Vec = ["a:b", "a?b", "a_b", "c"].iter().map(|n| layout.take(&path_part(n), true)).collect(); + assert_eq!(dirs, ["a_b", "a_b~2", "a_b~3", "c"]); + } + + #[test] + fn a_snapshot_named_like_another_snapshots_page_gets_its_own_directory() { + // Page 2 of the two-page `x`, then a one-page snapshot named `x/page-2`. + let mut layout = Layout::default(); + let x = layout.take("x", false); + let pages: Vec = (1..=2).map(|n| layout.take(&format!("{x}/page-{n}"), true)).collect(); + assert_eq!(pages, ["x/page-1", "x/page-2"]); + assert_eq!(layout.take("x/page-2", true), "x/page-2~2"); + + // The other way round: the one-page `x/page-2` first, then the two-page `x`. + let mut layout = Layout::default(); + assert_eq!(layout.take("x/page-2", true), "x/page-2"); + let x = layout.take("x", false); + let pages: Vec = (1..=2).map(|n| layout.take(&format!("{x}/page-{n}"), true)).collect(); + assert_eq!(pages, ["x/page-1", "x/page-2~2"]); + } + + #[test] + fn a_snapshot_named_like_another_snapshots_file_gets_its_own_directory() { + // `x`'s head image is `x/head.png`: a snapshot named `x/head.png` can't be a directory there. + let mut layout = Layout::default(); + assert_eq!(layout.take("x", true), "x"); + assert_eq!(layout.take("x/head.png", true), "x/head.png~2"); + // And the other way round: once `x/head.png` is a directory, `x` can't hold a file of that name. + let mut layout = Layout::default(); + assert_eq!(layout.take("x/head.png", true), "x/head.png"); + assert_eq!(layout.take("x", true), "x~2"); + // Directories that only share a parent are fine. + assert_eq!(layout.take("x/other", true), "x/other"); + } + + #[test] + fn a_filter_fills_its_defaults_and_refuses_what_it_does_not_know() { + let f = Filter::default().normalized().unwrap(); + assert_eq!(f.state.as_deref(), Some("changed")); + assert_eq!(f.sides, Some(vec!["base".into(), "head".into(), "diff".into()])); + let same = Filter { sides: Some(vec!["diff".into(), "head".into(), "base".into()]), ..Default::default() }; + assert_eq!(same.normalized().unwrap().key(), f.key(), "the order of sides doesn't matter"); + assert!(Filter { state: Some("new".into()), ..Default::default() }.normalized().is_err()); + assert!(Filter { sides: Some(vec!["left".into()]), ..Default::default() }.normalized().is_err()); + assert!(Filter { glob: Some("a/[".into()), ..Default::default() }.normalized().is_err()); + } +} diff --git a/app/src/domain/feedback.rs b/app/src/domain/feedback.rs new file mode 100644 index 00000000..2e3ecde6 --- /dev/null +++ b/app/src/domain/feedback.rs @@ -0,0 +1,243 @@ +//! Feedback from agents about VisualCI itself: Standard Support level 1 (standardsupport.dev, draft 0.5). One-way: +//! nobody replies, and there's no status for an agent to read back. The team reads it, as data. + +use std::sync::OnceLock; + +use laravel::db; +use laravel::model::create; +use regex::Regex; +use serde::Deserialize; + +use crate::models::Feedback; + +/// `request` comes from people, through the setup page's "What do you need from VisualCI?" and "Ask for something". +pub const KINDS: &[&str] = + &["bug", "crash", "wrong_result", "confusing", "missing_feature", "docs", "question", "request", "other"]; +pub const IMPACTS: &[&str] = &["blocked", "worked_around", "friction"]; +/// Pieces of feedback per account per day. +pub const DAILY_LIMIT: i64 = 50; +/// What `support_send` with action `feedback` needs, for error messages. +pub const NEEDS: &str = "title (3 to 200 characters), kind (bug, crash, wrong_result, confusing, missing_feature, docs, question, other) and description (1 to 4000 characters)"; +/// The fixed line every result carries. +pub const FOLLOW_UP: &str = "Nobody replies to feedback. The VisualCI team may email the user if it acts on this."; + +/// The fields of a report, as the spec names them. Everything is optional here so that a missing field gets a +/// message that says what to send, not a parse error. +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Report { + pub title: Option, + pub kind: Option, + pub description: Option, + pub impact: Option, + pub task: Option, + pub request_ids: Option>, + pub tool: Option, + pub error: Option, + pub suggestion: Option, + pub category: Option, + pub source: Option, + pub session: Option, + pub agent: Option, + pub idempotency_key: Option, +} + +/// Who sent a report, filled in by the server: never taken from the call. +pub struct Sender { + pub user_id: Option, + pub project_id: Option, + /// `user:` or `project:`. + pub account: String, + /// `mcp` or `api`. + pub channel: &'static str, + pub client: Option, +} + +#[derive(Debug)] +pub enum FeedbackError { + /// The report is missing something or has a bad value: the message says what to send. + Invalid(String), + RateLimited(String), + Server(laravel::Error), +} + +impl std::fmt::Display for FeedbackError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Invalid(m) | Self::RateLimited(m) => f.write_str(m), + Self::Server(e) => write!(f, "{e}"), + } + } +} + +impl From for FeedbackError { + fn from(e: laravel::Error) -> Self { + Self::Server(e) + } +} + +fn len_ok(v: Option<&String>, max: usize) -> bool { + v.is_none_or(|s| s.chars().count() <= max) +} + +impl Report { + /// Every problem with the report, or none. + #[must_use] + pub fn problems(&self) -> Vec { + let mut out = Vec::new(); + match self.title.as_deref().map(str::trim) { + None | Some("") => out.push("title is missing".to_string()), + Some(t) if !(3..=200).contains(&t.chars().count()) => out.push("title must be 3 to 200 characters".into()), + _ => {} + } + match self.kind.as_deref() { + None => out.push("kind is missing".into()), + Some(k) if !KINDS.contains(&k) => out.push(format!("kind must be one of {}", KINDS.join(", "))), + _ => {} + } + match self.description.as_deref().map(str::trim) { + None | Some("") => out.push("description is missing".into()), + Some(d) if d.chars().count() > 4000 => out.push("description must be at most 4000 characters".into()), + _ => {} + } + if let Some(i) = self.impact.as_deref() + && !IMPACTS.contains(&i) + { + out.push(format!("impact must be one of {}", IMPACTS.join(", "))); + } + if let Some(s) = self.source.as_deref() + && !["user", "agent"].contains(&s) + { + out.push("source must be user or agent".into()); + } + for (name, value, max) in [ + ("task", &self.task, 200), + ("tool", &self.tool, 100), + ("error", &self.error, 4000), + ("suggestion", &self.suggestion, 2000), + ("category", &self.category, 50), + ("session", &self.session, 100), + ("idempotency_key", &self.idempotency_key, 64), + ] { + if !len_ok(value.as_ref(), max) { + out.push(format!("{name} must be at most {max} characters")); + } + } + if let Some(ids) = &self.request_ids + && (ids.len() > 10 || ids.iter().any(|i| i.len() > 200)) + { + out.push("request_ids takes at most 10 IDs".into()); + } + if self.agent.as_ref().is_some_and(|a| !a.is_object() || a.to_string().len() > 1000) { + out.push("agent must be an object such as {name, version, model}".into()); + } + out + } +} + +/// Tokens and keys we recognise, replaced before anything is stored. +fn scrub(text: &str) -> String { + static RE: OnceLock = OnceLock::new(); + let re = RE.get_or_init(|| { + Regex::new( + r"(?x) + \bvc[iu]_[A-Za-z0-9]{12,} + | \b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,} + | \bgithub_pat_[A-Za-z0-9_]{20,} + | \bsk-[A-Za-z0-9_-]{20,} + | \bxox[abprs]-[A-Za-z0-9-]{10,} + | \bAKIA[0-9A-Z]{16}\b + | (?i:bearer)\s+[A-Za-z0-9._~+/=-]{12,} + | -----BEGIN[A-Z\ ]*PRIVATE\ KEY-----[\s\S]*?-----END[A-Z\ ]*PRIVATE\ KEY-----", + ) + .expect("valid regex") + }); + re.replace_all(text, "[redacted]").into_owned() +} + +fn clean(v: Option) -> Option { + v.map(|s| scrub(s.trim())).filter(|s| !s.is_empty()) +} + +/// Store a report. A retry with the same idempotency key returns the first record, with `duplicate` true. +/// +/// # Errors +/// `Invalid` with what to send, `RateLimited` past the daily limit, or a database error. +pub async fn record(sender: Sender, report: Report) -> Result<(Feedback, bool), FeedbackError> { + let problems = report.problems(); + if !problems.is_empty() { + return Err(FeedbackError::Invalid(format!( + "support_send with action feedback needs {NEEDS}. Problem: {}.", + problems.join("; ") + ))); + } + let account = sender.account.as_str(); + if let Some(key) = &report.idempotency_key + && let Some(first) = + Feedback::query().filter(Feedback::account.eq(account) & Feedback::idempotency_key.eq(key)).first().await? + { + return Ok((first, true)); + } + let today: i64 = + db::query!("SELECT COUNT(*) FROM feedback WHERE account = {account} AND created_at > now() - interval '1 day'") + .scalar() + .await? + .unwrap_or(0); + if today >= DAILY_LIMIT { + return Err(FeedbackError::RateLimited(format!( + "This account has sent {DAILY_LIMIT} pieces of feedback in the last 24 hours, the limit. Try again \ + tomorrow, and carry on with the task." + ))); + } + let report_key = report.idempotency_key.clone(); + let created = create!(Feedback { + pid: laravel::str::uuid7(), + user_id: sender.user_id, + project_id: sender.project_id, + account: sender.account.clone(), + title: clean(report.title).unwrap_or_default(), + kind: report.kind.unwrap_or_default(), + description: clean(report.description).unwrap_or_default(), + impact: report.impact, + task: clean(report.task), + request_ids: serde_json::json!(report.request_ids.unwrap_or_default()), + tool: clean(report.tool), + error: clean(report.error), + suggestion: clean(report.suggestion), + category: clean(report.category), + source: report.source.unwrap_or_else(|| "agent".into()), + session: clean(report.session), + agent: report.agent, + idempotency_key: report.idempotency_key.clone(), + channel: sender.channel, + client: sender.client, + }) + .await; + let row = match created { + Ok(row) => row, + // The same idempotency key sent twice at once: the other request stored it. + Err(e) if db::is_unique_violation(&e) => { + let key = report_key.unwrap_or_default(); + let first = Feedback::query() + .filter(Feedback::account.eq(account) & Feedback::idempotency_key.eq(&key)) + .first() + .await? + .ok_or(e)?; + return Ok((first, true)); + } + Err(e) => return Err(e.into()), + }; + tracing::info!(feedback = %row.pid, kind = %row.kind, title = %row.title, account = %row.account, "feedback received"); + crate::events::FeedbackReceived { feedback_id: row.id }.dispatch().await?; + Ok((row, false)) +} + +/// The result both the MCP tool and the endpoint return. +#[must_use] +pub fn result(row: &Feedback, duplicate: bool) -> serde_json::Value { + serde_json::json!({ + "feedback": { "id": format!("fb_{}", row.pid.simple()), "received_at": row.created_at.to_string() }, + "follow_up": FOLLOW_UP, + "duplicate": duplicate, + }) +} diff --git a/app/src/domain/gallery.rs b/app/src/domain/gallery.rs new file mode 100644 index 00000000..d4ecc1ec --- /dev/null +++ b/app/src/domain/gallery.rs @@ -0,0 +1,380 @@ +//! Public galleries: the screenshots a project publishes (visualci.yml's `gallery`), each at a stable public URL that +//! always serves its approved version on the default branch. See "Public galleries" in docs/design.md. +//! +//! What's published is decided from the newest completed CI build of each suite on the default branch: its +//! visualci.yml names the groups, and each screenshot's approved state there (what the next default-branch build +//! would compare with) is the image served. A pending or rejected change keeps the old image, so a review is the +//! publish step. +//! +//! Each image the origin serves costs its organization a credit, added to one row per project and day +//! ([`super::credits::spend_gallery`]), and kept even when it's out of credits: a customer's page must keep working. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use laravel::db::{self, Json}; +use visualci_core::config::{Config, Gallery}; + +use crate::models::{Blob, Build, Organization, Project}; + +/// One published screenshot. +#[derive(Debug, Clone, serde::Serialize)] +pub struct Item { + pub group: String, + pub name: String, + pub platform: String, + /// Its path under the project's gallery: `screens/home-dark.png`, with `@` before the extension when + /// the name is published on more than one platform. + pub path: String, + #[serde(skip)] + pub sha256: String, + #[serde(skip)] + pub content_type: String, + pub width: Option, + pub height: Option, + /// When this version was approved (its snapshot was made): changes only when the image does. + pub since: String, +} + +/// A project's published gallery: its groups in order (name, title) and their items. +#[derive(Debug, Clone, Default)] +pub struct Published { + pub groups: Vec<(String, Option)>, + pub items: Vec, +} + +fn extension(content_type: &str) -> &'static str { + match content_type { + "image/jpeg" => "jpg", + "image/webp" => "webp", + "image/gif" => "gif", + "image/avif" => "avif", + _ => "png", + } +} + +/// A time as today's server wrote it (RFC 3339 in UTC, `+00:00`, with milli- or microseconds when there are any). +fn rfc3339(t: laravel::time::Timestamp) -> String { + let micros = t.subsec_microsecond(); + let fraction = if micros == 0 { + String::new() + } else if micros % 1000 == 0 { + format!(".{:03}", micros / 1000) + } else { + format!(".{micros:06}") + }; + let utc = t.in_tz("UTC").map(|z| z.strftime("%Y-%m-%dT%H:%M:%S").to_string()).unwrap_or_default(); + format!("{utc}{fraction}+00:00") +} + +/// The newest completed CI build of each suite on the default branch. +async fn newest_builds(project: &Project) -> laravel::Result> { + let (project_id, branch) = (project.id, project.default_branch.clone()); + let all: Vec = db::query!( + "SELECT * FROM builds WHERE project_id = {project_id} AND branch = {branch} AND mode = 'ci' \ + AND state = 'completed' ORDER BY id DESC" + ) + .select_as() + .await?; + let mut seen = HashSet::new(); + Ok(all.into_iter().filter(|b| seen.insert(b.name.clone())).collect()) +} + +/// The gallery a build's visualci.yml asks for, if any. +fn gallery_of(build: &Build) -> Option { + build.config.as_ref().and_then(|c| Config::from_json(c).ok()).and_then(|c| c.gallery) +} + +/// How long a computed gallery is reused when nothing it depends on changed. +const CACHE_FOR: std::time::Duration = std::time::Duration::from_secs(600); + +/// The galleries computed lately, by project pid: what they were computed from, when, and the result. +type Cache = std::collections::HashMap, String, std::time::Instant, Published)>; + +/// What a project's gallery depends on that changes when it may: its newest completed CI build and newest baseline (an +/// approval adds one). A cheap indexed read, so every web process sees a change at once. +async fn inputs(project: &Project) -> laravel::Result> { + let id = project.id; + let row = db::query!( + "SELECT (SELECT COALESCE(MAX(id), 0) FROM builds WHERE project_id = {id} AND mode = 'ci' AND state = 'completed') \ + AS build, \ + (SELECT COALESCE(MAX(id), 0) FROM baselines WHERE project_id = {id}) AS baseline" + ) + .select() + .await?; + let row = row.first().ok_or_else(|| laravel::Error::msg("no gallery inputs"))?; + Ok(vec![row.try_get::("build")?, row.try_get::("baseline")?]) +} + +/// Everything a project publishes. Empty when its gallery is off or no default-branch build has one. Cached per web +/// process while its inputs (the newest completed CI build, the newest baseline, the default branch) stay the same, +/// for at most [`CACHE_FOR`]: computing it resolves baselines, and the gallery is public. +/// +/// # Errors +/// On a database error. +pub async fn published(project: &Project) -> laravel::Result { + static CACHE: std::sync::OnceLock> = std::sync::OnceLock::new(); + if !project.gallery_enabled { + return Ok(Published::default()); + } + let cache = CACHE.get_or_init(|| std::sync::Mutex::new(Cache::new())); + let inputs = inputs(project).await?; + let hit = cache.lock().ok().and_then(|c| { + c.get(&project.pid) + .filter(|(i, branch, at, _)| *i == inputs && *branch == project.default_branch && at.elapsed() < CACHE_FOR) + .map(|(_, _, _, p)| p.clone()) + }); + if let Some(p) = hit { + return Ok(p); + } + let computed = compute(project).await?; + if let Ok(mut c) = cache.lock() { + if c.len() > 10_000 { + c.retain(|_, (_, _, at, _)| at.elapsed() < CACHE_FOR); + } + c.insert(project.pid, (inputs, project.default_branch.clone(), std::time::Instant::now(), computed.clone())); + } + Ok(computed) +} + +async fn compute(project: &Project) -> laravel::Result { + let mut out = Published::default(); + let mut found = Vec::new(); + for newest in newest_builds(project).await? { + let Some(gallery) = gallery_of(&newest) else { continue }; + for g in &gallery.groups { + if !out.groups.iter().any(|(n, _)| n == &g.name) { + out.groups.push((g.name.clone(), g.title.clone())); + } + } + // What the next build on the default branch would compare with: resolve as a build just after the newest. + let mut next = newest.clone(); + next.id = i64::MAX; + next.parent_commits = + Json(std::iter::once(newest.commit_sha.clone()).chain(newest.parent_commits.iter().cloned()).collect()); + next.environment = "ci".to_string(); + let (resolved, _) = super::baselines::resolve(&next, project).await?; + for ((name, _), r) in resolved { + if r.snapshot.kind != "image" || r.snapshot.environment != "ci" { + continue; + } + if let Some(group) = gallery.group_of(&name) { + found.push((group.name.clone(), r.snapshot)); + } + } + } + let shas: Vec = found.iter().filter_map(|(_, s)| s.source_blob.clone()).collect(); + let mut blobs: HashMap = HashMap::new(); + for chunk in shas.chunks(10_000) { + for b in Blob::query().filter(Blob::sha256.is_in(chunk.to_vec())).get().await? { + blobs.insert(b.sha256.clone(), b); + } + } + let mut platforms: BTreeMap = BTreeMap::new(); + for (_, s) in &found { + *platforms.entry(s.name.clone()).or_default() += 1; + } + for (group, s) in found { + let Some(blob) = s.source_blob.as_ref().and_then(|sha| blobs.get(sha)) else { continue }; + let ext = extension(&blob.content_type); + // A name that already ends in its extension (`home.png`) keeps it once. + let stem = s.name.strip_suffix(&format!(".{ext}")).unwrap_or(&s.name); + let path = if platforms.get(&s.name).copied().unwrap_or(0) > 1 && !s.platform.is_empty() { + format!("{stem}@{}.{ext}", s.platform) + } else { + format!("{stem}.{ext}") + }; + out.items.push(Item { + group, + name: s.name.clone(), + platform: s.platform.clone(), + path, + sha256: blob.sha256.clone(), + content_type: blob.content_type.clone(), + width: blob.width, + height: blob.height, + since: rfc3339(s.created_at), + }); + } + out.items.sort_by(|a, b| a.path.cmp(&b.path)); + Ok(out) +} + +/// The public URL of a project's manifest. +#[must_use] +pub fn manifest_url(app_url: &str, org: &str, project: &str) -> String { + format!("{app_url}/g/{org}/{project}.json") +} + +/// A path segment as today's server wrote it (the `url` crate's path segment set): controls, non-ASCII bytes, space +/// and `"#<>`?{}/%` are percent-encoded. +fn segment(s: &str) -> String { + s.bytes() + .map(|b| { + if !(0x20..0x7F).contains(&b) || b" \"#<>`?{}/%".contains(&b) { + format!("%{b:02X}") + } else { + (b as char).to_string() + } + }) + .collect() +} + +/// The public URL of one published screenshot. +#[must_use] +pub fn item_url(app_url: &str, org: &str, project: &str, path: &str) -> String { + let mut url = format!("{}/g/{}/{}", app_url.trim_end_matches('/'), segment(org), segment(project)); + for part in path.split('/') { + url.push('/'); + url.push_str(&segment(part)); + } + url +} + +impl Published { + /// The manifest: groups in order with their items, and nothing that changes unless the images do. + #[must_use] + pub fn manifest(&self, app_url: &str, org: &str, project: &str) -> serde_json::Value { + let groups: Vec = self + .groups + .iter() + .map(|(name, title)| { + let items: Vec = self + .items + .iter() + .filter(|i| &i.group == name) + .map(|i| { + serde_json::json!({ + "name": i.name, "platform": i.platform, "url": item_url(app_url, org, project, &i.path), + "width": i.width, "height": i.height, "sha256": i.sha256, "since": i.since, + }) + }) + .collect(); + serde_json::json!({ "name": name, "title": title, "items": items }) + }) + .collect(); + serde_json::json!({ "project": format!("{org}/{project}"), "groups": groups }) + } + + /// The item at a path, if it's published. + #[must_use] + pub fn find(&self, path: &str) -> Option<&Item> { + self.items.iter().find(|i| i.path == path) + } +} + +/// What a project makes public, for its settings: the manifest's URL and each published screenshot's. +/// +/// # Errors +/// On a database error. +pub async fn public_list(app_url: &str, org: &str, project: &Project) -> laravel::Result { + let published = published(project).await?; + let items: Vec = published + .groups + .iter() + .flat_map(|(group, _)| published.items.iter().filter(move |i| &i.group == group)) + .map(|i| { + serde_json::json!({ + "group": i.group, "name": i.name, "platform": i.platform, + "url": item_url(app_url, org, &project.slug, &i.path), + }) + }) + .collect(); + Ok(serde_json::json!({ + "enabled": project.gallery_enabled, + "manifest_url": (!items.is_empty()).then(|| manifest_url(app_url, org, &project.slug)), + "items": items, + })) +} + +/// The project at `/g//`, when its gallery is on. +/// +/// # Errors +/// On a database error. +pub async fn project_by_slugs(org: &str, project: &str) -> laravel::Result> { + let Some(organization) = Organization::query().filter(Organization::slug.eq(org)).first().await? else { + return Ok(None); + }; + let found = Project::query() + .filter(Project::organization_id.eq(organization.id) & Project::slug.eq(project)) + .first() + .await? + .filter(|p| p.gallery_enabled); + Ok(found.map(|p| (organization, p))) +} + +/// The URLs a build's change can make stale: its changed, added or removed published screenshots' (an unchanged one's +/// cached copy is still right, and purging it would only cost a credit), and the manifest. Empty when the build isn't +/// a CI build on the default branch or the project publishes nothing. +/// +/// # Errors +/// On a database error. +pub async fn stale_urls(app_url: &str, build: &Build) -> laravel::Result> { + let project = Project::find_or_fail(build.project_id).await?; + if build.mode != "ci" || build.branch != project.default_branch { + return Ok(vec![]); + } + let published = published(&project).await?; + if published.items.is_empty() { + return Ok(vec![]); + } + let org = Organization::find_or_fail(project.organization_id).await?; + let names: HashSet = super::snapshots::of_build(build.id) + .await? + .into_iter() + .filter(|s| s.state != "unchanged") + .map(|s| s.name) + .collect(); + let mut urls = vec![manifest_url(app_url, &org.slug, &project.slug)]; + urls.extend( + published + .items + .iter() + .filter(|i| names.contains(&i.name)) + .map(|i| item_url(app_url, &org.slug, &project.slug, &i.path)), + ); + Ok(urls) +} + +/// Purge every gallery URL a project publishes now or published at its last purge, in the background: call it before +/// the gallery is turned off. Does nothing when purges aren't configured. +/// +/// # Errors +/// On a database error, or when the job can't be queued. +pub async fn purge_project(project_id: i64) -> laravel::Result<()> { + if crate::jobs::purge_gallery::configured().is_none() { + return Ok(()); + } + let project = Project::find_or_fail(project_id).await?; + let urls = all_urls(&crate::http::api::builds::app_url(), &project).await?; + crate::jobs::purge_gallery::PurgeGallery { build_id: None, project_id: Some(project_id), urls }.dispatch().await?; + Ok(()) +} + +/// Every URL a project publishes now: what to purge before its gallery is turned off. +/// +/// # Errors +/// On a database error. +pub async fn all_urls(app_url: &str, project: &Project) -> laravel::Result> { + let published = published(project).await?; + if published.items.is_empty() { + return Ok(vec![]); + } + let org = Organization::find_or_fail(project.organization_id).await?; + let mut urls = vec![manifest_url(app_url, &org.slug, &project.slug)]; + urls.extend(published.items.iter().map(|i| item_url(app_url, &org.slug, &project.slug, &i.path))); + Ok(urls) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn item_urls_encode_each_segment() { + assert_eq!( + item_url("https://app.visualci.com/", "acme", "web", "screens/home page@ios.png"), + "https://app.visualci.com/g/acme/web/screens/home%20page@ios.png" + ); + assert_eq!(manifest_url("https://app.visualci.com", "acme", "web"), "https://app.visualci.com/g/acme/web.json"); + } +} diff --git a/app/src/domain/groups.rs b/app/src/domain/groups.rs index 9e0c075b..cb982922 100644 --- a/app/src/domain/groups.rs +++ b/app/src/domain/groups.rs @@ -11,3 +11,410 @@ pub fn grouping(depth: Option) -> Grouping { _ => Grouping::AllButLastTwo, } } + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use laravel::db; +use visualci_core::manifest::{self, Entry}; + +use super::snapshots::{CONFIG_PLATFORM, is_config_item}; +use crate::models::{Build, Project, Snapshot}; + +/// A group as a client sends it. +#[derive(Clone, Debug, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GroupParam { + pub key: String, + pub hash: String, + pub count: i32, +} + +/// What a build said about its groups. +#[derive(Clone, Debug, Default, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CheckParams { + /// The hash of every snapshot the run has (`manifest::manifest_hash`). + #[serde(default)] + pub manifest_hash: Option, + /// Absent for the default grouping (all but the last two segments), else the leading segments kept. + #[serde(default)] + pub group_depth: Option, + #[serde(default)] + pub groups: Vec, + /// The shard sending these groups, for a sharded build: groups must not span shards. + #[serde(default)] + pub shard: Option, +} + +/// The server's answer. +#[derive(Clone, Debug, Default, serde::Serialize)] +pub struct Checked { + /// The whole manifest matched this build's: nothing needs sending. + pub same_as_build: Option, + /// Groups whose files the client must send. + pub changed: Vec, + /// Groups carried forward from their baselines. + pub unchanged: Vec, +} + +/// A stored snapshot as a manifest entry: the same fields, normalized the same way, as the CLI hashes. +#[must_use] +pub fn entry_of(s: &Snapshot) -> Entry { + Entry { + name: s.name.clone(), + platform: s.platform.clone(), + kind: s.kind.clone(), + fingerprint: s.source_fingerprint.clone(), + format: s.format.clone(), + engine: s.engine.clone(), + threshold: s.threshold, + ignore_anti_aliasing: s.ignore_anti_aliasing, + ignore: s.ignore_rules.clone(), + } +} + +/// Compare a build's manifest and groups with its baseline's, record them, and say which groups the client must send. +/// A group is recorded once per build: a second shard naming a group another already sent is refused. +/// +/// # Errors +/// `Ok(Err(message))` for a build that isn't receiving any more, a bad group, or a group another shard sent; `Err` on +/// a database error. +pub async fn check(build: &Build, project: &Project, params: &CheckParams) -> laravel::Result> { + if build.state != "receiving" { + return Ok(Err("the build isn't receiving snapshots any more".into())); + } + if params.groups.len() > 100_000 { + return Ok(Err("at most 100000 groups".into())); + } + if build.group_depth.is_some() && build.group_depth != params.group_depth { + return Ok(Err("every shard must group names the same way (group_depth)".into())); + } + let grouping = grouping(params.group_depth); + // The baseline's side, from the server's own rows: each snapshot's approved version. + let (resolved, anchor) = super::baselines::resolve(build, project).await?; + let entries: Vec = + resolved.values().map(|r| &r.snapshot).filter(|s| s.platform != CONFIG_PLATFORM).map(entry_of).collect(); + let baseline_groups: HashMap = + manifest::groups(&entries, grouping).into_iter().map(|g| (g.key, g.hash)).collect(); + let manifest_matched = !entries.is_empty() + && params.manifest_hash.as_deref() == Some(manifest::manifest_hash(&entries).as_str()) + && anchor.is_some(); + + let mut out = Checked::default(); + let mut rows: BTreeMap = BTreeMap::new(); + if manifest_matched { + out.same_as_build = anchor.as_ref().map(|a| a.number); + // Every baseline group is unchanged: recorded from the server's own side. + for g in manifest::groups(&entries, grouping) { + out.unchanged.push(g.key.clone()); + rows.insert(g.key, (g.hash, i32::try_from(g.count).unwrap_or(i32::MAX), true)); + } + } else { + let mut seen = HashSet::new(); + for g in ¶ms.groups { + if !seen.insert(g.key.clone()) { + return Ok(Err(format!("group {:?} is listed twice", g.key))); + } + if g.key.len() > 1000 || g.hash.len() > 200 || g.count < 0 { + return Ok(Err(format!("group {:?} isn't valid", g.key))); + } + // A group matches only when the server's own baseline rows give the same hash; a claimed hash with no + // baseline behind it is a changed group. + let unchanged = baseline_groups.get(&g.key).is_some_and(|h| *h == g.hash); + if unchanged { + out.unchanged.push(g.key.clone()); + } else { + out.changed.push(g.key.clone()); + } + rows.insert(g.key.clone(), (g.hash.clone(), g.count, unchanged)); + } + } + + let (id, shard, depth) = (build.id, params.shard, params.group_depth); + let same_as = anchor.as_ref().filter(|_| manifest_matched).map(|a| a.id); + let recorded: Result<(), String> = db::transaction(async |_| { + for (key, (hash, count, matched)) in &rows { + let inserted = db::query!( + "INSERT INTO build_groups (build_id, key, hash, snapshot_count, matched, shard) \ + VALUES ({id}, {key}, {hash}, {count}, {matched}, {shard}) ON CONFLICT (build_id, key) DO NOTHING" + ) + .insert() + .await? + .rows_affected(); + if inserted == 0 { + return Err(laravel::Error::msg(format!( + "group {key:?} was already sent for this build (by another shard?): groups can't span shards; group \ + by a deeper prefix (group_depth) or keep each group's snapshots in one shard" + ))); + } + } + // A build that listed its groups has said what it holds: one whose groups all matched sends no files, and + // isn't an empty build. + db::query!( + "UPDATE builds SET group_depth = {depth}, allow_empty = true, \ + manifest_same_as_build_id = COALESCE({same_as}, manifest_same_as_build_id), updated_at = now() \ + WHERE id = {id}" + ) + .update() + .await?; + Ok(()) + }) + .await + .map_err(|e| e.to_string()); + Ok(recorded.map(|()| out)) +} + +/// Which baseline snapshots processing carries forward into a build besides a subset build's: all of them after a +/// whole-manifest match, else those in the groups that matched. +pub enum Carry { + Nothing, + All, + Groups(Grouping, HashSet), +} + +impl Carry { + #[must_use] + pub fn covers(&self, name: &str) -> bool { + match self { + Self::Nothing => false, + Self::All => true, + Self::Groups(grouping, keys) => keys.contains(&grouping.key(name)), + } + } +} + +/// A build's carry rule. +/// +/// # Errors +/// On a database error. +pub async fn carry(build: &Build) -> laravel::Result { + if build.manifest_same_as_build_id.is_some() { + return Ok(Carry::All); + } + let id = build.id; + let keys: Vec = db::query!("SELECT key FROM build_groups WHERE build_id = {id} AND matched") + .select() + .await? + .iter() + .filter_map(|r| r.try_get("key").ok()) + .collect(); + if keys.is_empty() { + return Ok(Carry::Nothing); + } + Ok(Carry::Groups(grouping(build.group_depth), keys.into_iter().collect())) +} + +/// Group checks to charge: one for a whole-manifest match, else one per matched group. +/// +/// # Errors +/// On a database error. +pub async fn checks(build: &Build) -> laravel::Result { + if build.manifest_same_as_build_id.is_some() { + return Ok(1); + } + let id = build.id; + Ok(db::query!("SELECT COUNT(*) FROM build_groups WHERE build_id = {id} AND matched").scalar().await?.unwrap_or(0)) +} + +/// A build's groups for the UI and `get_build`: how many matched (with their snapshot count) and the build they're +/// the same as, and the changed ones. `None` for a build that sent no groups. +/// +/// # Errors +/// On a database error. +pub async fn summary(build: &Build) -> laravel::Result> { + let id = build.id; + let rows = db::query!( + "SELECT key, snapshot_count, matched FROM build_groups WHERE build_id = {id} AND matched IS NOT NULL ORDER BY key" + ) + .select() + .await?; + if rows.is_empty() { + return Ok(None); + } + let (mut unchanged, mut snapshots_unchanged, mut changed) = (Vec::new(), 0i64, Vec::new()); + for r in &rows { + let key: String = r.try_get("key")?; + let count: i32 = r.try_get("snapshot_count")?; + if r.try_get::("matched")? { + snapshots_unchanged += i64::from(count); + unchanged.push(key); + } else { + changed.push(key); + } + } + let same_as = match build.manifest_same_as_build_id.or(build.base_build_id) { + Some(id) => Build::find(id).await?.map(|b| b.number), + None => None, + }; + Ok(Some(serde_json::json!({ + "manifest_matched": build.manifest_same_as_build_id.is_some(), + "unchanged_groups": unchanged.len(), + "unchanged_snapshots": snapshots_unchanged, + "same_as_build": same_as, + "changed_groups": changed, + "unchanged_group_keys": unchanged, + }))) +} + +/// Whether a snapshot holds the same content, with the same settings, as another: the one can stand for the other. +#[must_use] +pub fn same_content(a: &Snapshot, b: &Snapshot) -> bool { + a.name == b.name + && a.platform == b.platform + && a.kind == b.kind + && a.format == b.format + && a.source_fingerprint == b.source_fingerprint + && a.render_id == b.render_id + && a.engine == b.engine + && a.threshold == b.threshold + && a.ignore_anti_aliasing == b.ignore_anti_aliasing + && a.ignore_rules == b.ignore_rules + && a.environment == b.environment + && a.meta == b.meta +} + +/// A group a build could read from an earlier build instead of storing it. +pub struct Candidate { + /// Its snapshots' baselines: the rows that would stand for them. + pub base_ids: Vec, + /// Its manifest hash (`manifest::groups`), for the record. + pub hash: String, +} + +struct Wanted { + key: String, + base_id: i64, +} + +/// Of these groups, the ones one earlier build of the same project holds exactly (the same group key, every baseline +/// its own row, and no other row of the group there), with that build. Never another project's build: retention and the +/// demo reset rely on a group reading only from its own project. +/// +/// # Errors +/// On a database error. +pub async fn holders( + project_id: i64, + candidates: &BTreeMap, +) -> laravel::Result> { + let wanted: Vec = candidates + .iter() + .flat_map(|(key, c)| c.base_ids.iter().map(|id| Wanted { key: key.clone(), base_id: *id })) + .collect(); + let mut out = BTreeMap::new(); + if wanted.is_empty() { + return Ok(out); + } + // A group's rows all go in one query, so its whole membership is checked together. + let mut chunk: Vec = Vec::new(); + let mut groups = wanted.into_iter().peekable(); + while let Some(w) = groups.next() { + let last_of_group = groups.peek().is_none_or(|n| n.key != w.key); + chunk.push(w); + if last_of_group && (chunk.len() >= 20_000 || groups.peek().is_none()) { + let rows = db::query!( + "WITH wanted (key, base_id) AS (VALUES {...chunk(key, base_id)}), \ + found AS ( \ + SELECT w.key, MIN(b.build_id) AS holder, COUNT(*) AS n FROM wanted w \ + LEFT JOIN snapshots b ON b.id = w.base_id \ + GROUP BY w.key \ + HAVING bool_and(b.id IS NOT NULL AND b.group_key = w.key AND b.platform <> 'visualci') \ + AND COUNT(DISTINCT b.build_id) = 1) \ + SELECT f.key, f.holder FROM found f JOIN builds hb ON hb.id = f.holder AND hb.project_id = {project_id} \ + WHERE (SELECT COUNT(*) FROM snapshots h WHERE h.build_id = f.holder AND h.group_key = f.key \ + AND h.platform <> 'visualci') = f.n \ + AND NOT EXISTS (SELECT 1 FROM snapshots h WHERE h.build_id = f.holder AND h.group_key = f.key \ + AND h.state IN ('pending', 'failed', 'removed'))" + ) + .select() + .await?; + for r in rows { + out.insert(r.try_get::("key")?, r.try_get::("holder")?); + } + chunk.clear(); + } + } + Ok(out) +} + +/// Record groups as read from their holders. A group the client checked keeps its check. +/// +/// # Errors +/// On a database error. +pub async fn record_sources( + build_id: i64, + candidates: &BTreeMap, + sources: &BTreeMap, +) -> laravel::Result<()> { + for (key, holder) in sources { + let Some(c) = candidates.get(key) else { continue }; + let (hash, count) = (c.hash.as_str(), i32::try_from(c.base_ids.len()).unwrap_or(i32::MAX)); + db::query!( + "INSERT INTO build_groups (build_id, key, hash, snapshot_count, source_build_id) \ + VALUES ({build_id}, {key}, {hash}, {count}, {holder}) \ + ON CONFLICT (build_id, key) DO UPDATE SET source_build_id = EXCLUDED.source_build_id" + ) + .insert() + .await?; + } + Ok(()) +} + +/// After comparison: read every group of a CI build whose snapshots are all unchanged, and the same as their +/// baselines, from the build that holds those baselines, and delete the build's own rows of it. Runs while the build is +/// still processing, so no other build has anchored on it yet. Returns how many rows that saved. +/// +/// # Errors +/// On a database error. +pub async fn source_unchanged(build: &Build) -> laravel::Result { + if build.mode != "ci" { + return Ok(0); + } + let own = Snapshot::query().filter(Snapshot::build_id.eq(build.id)).get().await?; + let base_ids: Vec = own.iter().filter_map(|s| s.base_snapshot_id).collect(); + let mut bases: HashMap = HashMap::new(); + for chunk in base_ids.chunks(10_000) { + for b in Snapshot::query().filter(Snapshot::id.is_in(chunk.to_vec())).get().await? { + bases.insert(b.id, b); + } + } + let mut by_key: BTreeMap> = BTreeMap::new(); + for s in &own { + by_key.entry(s.group_key.clone()).or_default().push(s); + } + let grouping = grouping(build.group_depth); + let mut candidates = BTreeMap::new(); + for (key, list) in by_key { + let fits = |s: &&Snapshot| { + !is_config_item(s) + && s.state == "unchanged" + && s.matched_environment.is_none() + && s.base_snapshot_id.and_then(|id| bases.get(&id)).is_some_and(|b| same_content(s, b)) + }; + if !list.iter().all(fits) { + continue; + } + let entries: Vec = list.iter().map(|s| entry_of(s)).collect(); + let Some(g) = manifest::groups(&entries, grouping).into_iter().next() else { continue }; + let base_ids = list.iter().filter_map(|s| s.base_snapshot_id).collect(); + candidates.insert(key, Candidate { base_ids, hash: g.hash }); + } + let sources = holders(build.project_id, &candidates).await?; + if sources.is_empty() { + return Ok(0); + } + let (id, keys): (i64, Vec) = (build.id, sources.keys().cloned().collect()); + db::transaction(async |_| { + record_sources(id, &candidates, &sources).await?; + let mut deleted = 0; + for chunk in keys.chunks(10_000) { + let chunk = chunk.to_vec(); + deleted += db::query!( + "DELETE FROM snapshots WHERE build_id = {id} AND group_key IN ({...chunk}) AND platform <> 'visualci'" + ) + .delete() + .await?; + } + Ok(deleted) + }) + .await +} diff --git a/app/src/domain/inherited.rs b/app/src/domain/inherited.rs new file mode 100644 index 00000000..7be92c55 --- /dev/null +++ b/app/src/domain/inherited.rs @@ -0,0 +1,94 @@ +//! Changes a pull request build only inherited from its base branch. When the default branch's newest build (the one a +//! PR build is compared on top of) is still waiting for review, its changes aren't baselines yet, so every PR build +//! made after it shows them again: a reviewer can't tell the PR's own changes from main's backlog (2 Dec 2026, PR 3: +//! 98 changes, none of them the PR's). A PR build's change that's exactly the base build's unreviewed change (the same +//! snapshot, the same new content) is marked inherited, and the build says "N changes are already on main and +//! unreviewed (build #X)". Approval and the check still go by approved baselines: this only says where a change came +//! from. + +use std::collections::{HashMap, HashSet}; + +use super::snapshots::{is_change, is_config_item}; +use crate::models::{Build, Project, Snapshot}; + +/// A PR build's inherited changes: the base build they're unreviewed in, and which of this build's snapshots they are. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Inherited { + pub build: i32, + pub branch: String, + pub snapshot_ids: HashSet, +} + +impl Inherited { + /// "3 changes are already on main and unreviewed (build #77)". + #[must_use] + pub fn note(&self) -> String { + let n = self.snapshot_ids.len(); + let changes = if n == 1 { "change is" } else { "changes are" }; + format!("{n} {changes} already on {} and unreviewed (build #{})", self.branch, self.build) + } + + /// For an API answer: the base build, how many, and the sentence. + #[must_use] + pub fn json(&self) -> serde_json::Value { + serde_json::json!({ "build": self.build, "branch": self.branch, "count": self.snapshot_ids.len(), "note": self.note() }) + } +} + +/// The build's changes that are its base build's unreviewed changes, when its base is an unreviewed build of the +/// default branch and this build isn't on that branch. `None` when there are none. +/// +/// # Errors +/// On a database error. +pub async fn of_build(build: &Build, project: &Project) -> laravel::Result> { + if build.branch == project.default_branch { + return Ok(None); + } + let Some(base_id) = build.base_build_id else { return Ok(None) }; + let Some(base) = Build::find(base_id).await? else { return Ok(None) }; + if base.branch != project.default_branch || base.review_state != "pending" { + return Ok(None); + } + // The base build's changes that nobody has approved, by snapshot. + let pending: HashMap<(String, String), Snapshot> = super::snapshots::of_build(base.id) + .await? + .into_iter() + .filter(|s| is_change(s) && !is_config_item(s) && s.review.as_deref() != Some("approved")) + .map(|s| ((s.name.clone(), s.platform.clone()), s)) + .collect(); + if pending.is_empty() { + return Ok(None); + } + let snapshot_ids: HashSet = super::snapshots::of_build(build.id) + .await? + .into_iter() + .filter(|s| is_change(s) && !is_config_item(s)) + .filter(|s| { + pending.get(&(s.name.clone(), s.platform.clone())).is_some_and(|p| { + if s.state == "removed" { + p.state == "removed" + } else { + p.state != "removed" && p.source_fingerprint == s.source_fingerprint + } + }) + }) + .map(|s| s.id) + .collect(); + if snapshot_ids.is_empty() { + return Ok(None); + } + Ok(Some(Inherited { build: base.number, branch: base.branch, snapshot_ids })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn says_how_many_and_where() { + let one = Inherited { build: 77, branch: "main".into(), snapshot_ids: [1].into_iter().collect() }; + assert_eq!(one.note(), "1 change is already on main and unreviewed (build #77)"); + let three = Inherited { build: 77, branch: "main".into(), snapshot_ids: [1, 2, 3].into_iter().collect() }; + assert_eq!(three.note(), "3 changes are already on main and unreviewed (build #77)"); + } +} diff --git a/app/src/domain/matching.rs b/app/src/domain/matching.rs new file mode 100644 index 00000000..baa6a5d1 --- /dev/null +++ b/app/src/domain/matching.rs @@ -0,0 +1,234 @@ +//! Changes made of other pull requests' approved changes. Two pull requests that change the same screenshot and merge +//! separately leave an image neither of them showed: PR A approved its change without B's, B approved its change +//! without A's. The next build compares with one of those approvals and shows the other's change again, although it +//! was reviewed (main build #93 on 2 Dec 2026: PR #8's settings checkbox over PR #6's approved page). +//! +//! When every changed region of a snapshot's changed pages is exactly a region a merged pull request's build had +//! changed and that PR approved (the same box, the same old pixels and the same new pixels), the snapshot points at +//! that build (`snapshots.matches_build_id`): "matches PR #8's approved change". It's a hint and approves nothing; +//! `review` with `only: "matching"` approves those snapshots in one call. + +use std::collections::HashMap; + +use image::RgbaImage; +use laravel::db; +use visualci_core::diff::{DiffResult, Region}; + +use crate::models::{Build, Diff, Snapshot, SnapshotPage}; +use crate::storage::BlobStore; + +/// A page's change: the diff's canvas and regions, and its two images. +struct PageChange { + position: i32, + width: u32, + height: u32, + regions: Vec, + base_image: String, + head_image: String, +} + +/// The changed pages of a snapshot that has stored rows (a changed snapshot always does). +async fn page_changes(snapshot_id: i64) -> laravel::Result> { + let pages: Vec = SnapshotPage::query() + .filter(SnapshotPage::snapshot_id.eq(snapshot_id) & SnapshotPage::state.eq("changed")) + .order_by(SnapshotPage::position.asc()) + .get() + .await?; + let mut out = Vec::new(); + for p in pages { + let (Some(diff_id), Some(base_image), Some(head_image)) = (p.diff_id, p.base_image, p.head_image) else { + continue; + }; + let Some(diff) = Diff::find(diff_id).await? else { continue }; + let Ok(result) = serde_json::from_value::(diff.result) else { continue }; + out.push(PageChange { + position: p.position, + width: result.width, + height: result.height, + regions: result.regions, + base_image, + head_image, + }); + } + Ok(out) +} + +type Candidate = (usize, i64, i64); +/// Decoded images, by blob, so a page shared by several candidates is read once. +struct Images<'a> { + store: &'a BlobStore, + cache: HashMap>, +} + +impl Images<'_> { + async fn get(&mut self, sha: &str) -> Option<&RgbaImage> { + if !self.cache.contains_key(sha) { + let decoded = match self.store.get(sha).await { + Ok(bytes) => image::load_from_memory(&bytes).ok().map(|i| i.to_rgba8()), + Err(_) => None, + }; + self.cache.insert(sha.to_string(), decoded); + } + self.cache.get(sha).and_then(Option::as_ref) + } +} + +/// Whether two images have the same pixels inside a region (a pixel one has and the other doesn't is a difference). +#[must_use] +pub fn same_in(a: &RgbaImage, b: &RgbaImage, r: &Region) -> bool { + for y in r.y..r.y.saturating_add(r.height) { + for x in r.x..r.x.saturating_add(r.width) { + let pa = (x < a.width() && y < a.height()).then(|| a.get_pixel(x, y)); + let pb = (x < b.width() && y < b.height()).then(|| b.get_pixel(x, y)); + if pa != pb { + return false; + } + } + } + true +} + +/// Whether every region of `ours` is a region `theirs` changed, from the same old pixels to the same new ones. +async fn covered(images: &mut Images<'_>, ours: &PageChange, theirs: &PageChange) -> bool { + if (ours.width, ours.height) != (theirs.width, theirs.height) || ours.regions.is_empty() { + return false; + } + if !ours.regions.iter().all(|r| theirs.regions.contains(r)) { + return false; + } + for (a, b) in [(&ours.base_image, &theirs.base_image), (&ours.head_image, &theirs.head_image)] { + let Some(a) = images.get(a).await.cloned() else { return false }; + let Some(b) = images.get(b).await else { return false }; + if !ours.regions.iter().all(|r| same_in(&a, b, r)) { + return false; + } + } + true +} + +/// Mark the build's changed snapshots that are made only of changes merged pull requests approved. Returns how many. +/// +/// # Errors +/// On a database or blob store error. +pub async fn mark(store: &BlobStore, build: &Build) -> laravel::Result { + if build.mode != "ci" { + return Ok(0); + } + let changed: Vec = Snapshot::query() + .filter(Snapshot::build_id.eq(build.id) & Snapshot::state.eq("changed") & Snapshot::kind.ne("text")) + .get() + .await?; + if changed.is_empty() { + return Ok(0); + } + let names: Vec = changed.iter().map(|s| s.name.clone()).collect(); + let ancestry = super::baselines::ancestry(build); + let (project_id, build_name) = (build.project_id, build.name.as_str()); + // The pull requests' own snapshots behind each merged approval in this build's history, nearest merge first. + let rows = db::query!( + "SELECT bl.name, bl.platform, bl.commit_sha, bl.build_id, s.id AS snapshot_id \ + FROM baselines bl JOIN snapshots s ON s.id = bl.snapshot_id \ + WHERE bl.project_id = {project_id} AND bl.build_name = {build_name} AND bl.approval = 'merged' \ + AND bl.commit_sha IN ({...ancestry}) AND bl.name IN ({...names}) AND s.state = 'changed'" + ) + .select() + .await?; + let mut candidates: HashMap<(String, String), Vec> = HashMap::new(); + for r in rows { + let commit: String = r.try_get("commit_sha")?; + let near = ancestry.iter().position(|c| c == &commit).unwrap_or(usize::MAX); + candidates.entry((r.try_get("name")?, r.try_get("platform")?)).or_default().push(( + near, + r.try_get("build_id")?, + r.try_get("snapshot_id")?, + )); + } + let mut images = Images { store, cache: HashMap::new() }; + let mut marked = 0; + for s in changed { + let Some(mut theirs) = candidates.remove(&(s.name.clone(), s.platform.clone())) else { continue }; + theirs.sort_unstable(); + let ours = page_changes(s.id).await?; + if ours.is_empty() { + continue; + } + let mut matched = None; + for (_, their_build, their_snapshot) in theirs { + let their_pages = page_changes(their_snapshot).await?; + let mut all = true; + for page in &ours { + let Some(other) = their_pages.iter().find(|p| p.position == page.position) else { + all = false; + break; + }; + if !covered(&mut images, page, other).await { + all = false; + break; + } + } + if all { + matched = Some(their_build); + break; + } + } + if let Some(their_build) = matched { + let id = s.id; + db::query!("UPDATE snapshots SET matches_build_id = {their_build} WHERE id = {id}").update().await?; + marked += 1; + } + } + Ok(marked) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compares_pixels_inside_a_region_only() { + let mut a = RgbaImage::from_pixel(8, 8, image::Rgba([255, 255, 255, 255])); + let b = a.clone(); + a.put_pixel(6, 6, image::Rgba([0, 0, 0, 255])); + let inside = Region { x: 0, y: 0, width: 4, height: 4 }; + let around = Region { x: 4, y: 4, width: 4, height: 4 }; + assert!(same_in(&a, &b, &inside)); + assert!(!same_in(&a, &b, &around)); + // A pixel only one image has (a taller page) is a difference. + let tall = RgbaImage::from_pixel(8, 12, image::Rgba([255, 255, 255, 255])); + assert!(!same_in(&b, &tall, &Region { x: 0, y: 6, width: 8, height: 6 })); + } +} + +/// Where a matching change was approved: the pull request's build, for "matches PR #8's approved change". +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +pub struct Matches { + pub build: i32, + pub branch: String, + pub pr_number: Option, + /// "matches PR #8's approved change" (or "the change approved on sc-8740" with no pull request). + pub label: String, +} + +/// The build's matching changes, by snapshot id. +/// +/// # Errors +/// On a database error. +pub async fn of_build(build_id: i64) -> laravel::Result> { + let rows = db::query!( + "SELECT s.id, b.number, b.branch, b.pr_number FROM snapshots s JOIN builds b ON b.id = s.matches_build_id \ + WHERE s.build_id = {build_id} AND s.state = 'changed'" + ) + .select() + .await?; + let mut out = HashMap::new(); + for r in rows { + let pr_number: Option = r.try_get("pr_number")?; + let branch: String = r.try_get("branch")?; + let label = match pr_number { + Some(n) => format!("matches PR #{n}'s approved change"), + None => format!("matches the change approved on {branch}"), + }; + out.insert(r.try_get("id")?, Matches { build: r.try_get("number")?, branch, pr_number, label }); + } + Ok(out) +} diff --git a/app/src/domain/mod.rs b/app/src/domain/mod.rs index 9a84771a..516d3582 100644 --- a/app/src/domain/mod.rs +++ b/app/src/domain/mod.rs @@ -1,12 +1,30 @@ //! VisualCI's domain: builds, snapshots, baselines and the rules between them (sc-8900, the data side), on the //! models in `crate::models`. +pub mod baselines; pub mod blobs; pub mod build_settings; pub mod builds; +pub mod changeset; +pub mod comments; +pub mod compare; pub mod credits; +pub mod demo; +pub mod detail; +pub mod diffs; +pub mod downloads; pub mod environments; +pub mod feedback; +pub mod gallery; pub mod groups; +pub mod inherited; pub mod lenient; +pub mod matching; +pub mod pages; +pub mod processing; pub mod projects; +pub mod renders; +pub mod retention; +pub mod reviews; pub mod snapshots; +pub mod summary; diff --git a/app/src/domain/pages.rs b/app/src/domain/pages.rs new file mode 100644 index 00000000..3ed3b2ba --- /dev/null +++ b/app/src/domain/pages.rs @@ -0,0 +1,236 @@ +//! A snapshot's pages as compared with its baseline (docs/design-storage.md). +//! +//! Rows are stored only for a comparison that found something: an added snapshot, a change, a page within the +//! threshold or accepted as a variant, pages that moved. An unchanged snapshot (every page the same as its base, in +//! order) stores none, and neither do the snapshots a build reads from another build: their pages are read from the +//! snapshot itself ([`of_many`]). Page text is stored once in `texts`, by hash. + +use std::collections::HashMap; + +use laravel::db; + +use super::build_settings::BuildSettings; +use super::renders::RenderPage; +use crate::models::{Build, Project, Render, Snapshot, SnapshotPage}; +use crate::storage::{BlobStore, texts}; + +/// One page of a snapshot's comparison, with its text. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Page { + pub position: i32, + pub op: String, + pub state: String, + pub head_index: Option, + pub base_index: Option, + pub head_image: Option, + pub base_image: Option, + pub head_text: Option, + pub base_text: Option, + pub diff_id: Option, +} + +struct Row { + snapshot_id: i64, + position: i32, + op: String, + state: String, + head_index: Option, + base_index: Option, + head_image: Option, + base_image: Option, + head_text_sha: Option, + base_text_sha: Option, + diff_id: Option, +} + +/// Store a snapshot's page rows (replacing any it had), their texts first. +/// +/// # Errors +/// On a database error. +pub async fn store(snapshot_id: i64, pages: Vec) -> laravel::Result<()> { + db::query!("DELETE FROM snapshot_pages WHERE snapshot_id = {snapshot_id}").delete().await?; + if pages.is_empty() { + return Ok(()); + } + let bodies: Vec<&str> = + pages.iter().flat_map(|p| [p.head_text.as_deref(), p.base_text.as_deref()]).flatten().collect(); + texts::store(&bodies).await?; + let rows: Vec = pages + .into_iter() + .map(|p| Row { + snapshot_id, + position: p.position, + op: p.op, + state: p.state, + head_index: p.head_index, + base_index: p.base_index, + head_image: p.head_image, + base_image: p.base_image, + head_text_sha: p.head_text.as_deref().map(texts::sha), + base_text_sha: p.base_text.as_deref().map(texts::sha), + diff_id: p.diff_id, + }) + .collect(); + for chunk in rows.chunks(5000) { + db::query!( + "INSERT INTO snapshot_pages (snapshot_id, position, op, state, head_index, base_index, head_image, \ + base_image, head_text_sha, base_text_sha, diff_id) \ + VALUES {...chunk(snapshot_id, position, op, state, head_index, base_index, head_image, base_image, \ + head_text_sha, base_text_sha, diff_id)}" + ) + .insert() + .await?; + } + Ok(()) +} + +/// Whether a comparison's pages say nothing beyond "the same as the base": every page unchanged, in order, with the +/// same image and text. Those aren't stored. +#[must_use] +pub fn plain_unchanged(pages: &[Page]) -> bool { + pages.iter().enumerate().all(|(i, p)| { + let i = i32::try_from(i).ok(); + p.op == "unchanged" + && p.state == "unchanged" + && p.head_index == i + && p.base_index == i + && p.head_image == p.base_image + && p.head_text == p.base_text + && p.diff_id.is_none() + }) +} + +fn from_row(m: SnapshotPage, texts: &HashMap) -> Page { + let text = |sha: Option| sha.map(|s| texts.get(&s).cloned().unwrap_or_default()); + Page { + position: m.position, + op: m.op, + state: m.state, + head_index: m.head_index, + base_index: m.base_index, + head_image: m.head_image, + base_image: m.base_image, + head_text: text(m.head_text_sha), + base_text: text(m.base_text_sha), + diff_id: m.diff_id, + } +} + +/// Each snapshot's pages, by snapshot id, in order: its stored rows, or for an unchanged snapshot (one of its own +/// build's, or one read from another build) its pages as themselves. With `store`, every page's text too (text +/// snapshots' normalized as they were compared); without it, only stored rows' text. +/// +/// # Errors +/// On a database error, or when a text snapshot's file is missing. +pub async fn of_many(store: Option<&BlobStore>, list: &[&Snapshot]) -> laravel::Result>> { + let own: Vec = list.iter().filter(|s| !s.sourced).map(|s| s.id).collect(); + let mut rows: Vec = Vec::new(); + for chunk in own.chunks(10_000) { + let chunk = chunk.to_vec(); + let found: Vec = + db::query!("SELECT * FROM snapshot_pages WHERE snapshot_id IN ({...chunk}) ORDER BY snapshot_id, position") + .select_as() + .await?; + rows.extend(found); + } + let shas: Vec = + rows.iter().flat_map(|r| [r.head_text_sha.clone(), r.base_text_sha.clone()]).flatten().collect(); + let stored_texts = texts::load(&shas).await?; + let mut out: HashMap> = HashMap::new(); + for r in rows { + out.entry(r.snapshot_id).or_default().push(from_row(r, &stored_texts)); + } + + // The rest are unchanged (or have no pages: pending, failed, removed). + let plain: Vec<&Snapshot> = + list.iter().copied().filter(|s| s.state == "unchanged" && !out.contains_key(&s.id)).collect(); + let render_ids: Vec = plain.iter().filter_map(|s| s.render_id).collect(); + let mut renders_by_id: HashMap> = HashMap::new(); + for chunk in render_ids.chunks(10_000) { + for r in Render::query().filter(Render::id.is_in(chunk.to_vec())).get().await? { + renders_by_id.insert(r.id, super::renders::pages(&r)); + } + } + let with_text = store.is_some(); + let render_texts = if with_text { + let shas: Vec = renders_by_id.values().flatten().map(|p| p.text_sha.clone()).collect(); + texts::load(&shas).await? + } else { + HashMap::new() + }; + let mut settings_of: HashMap = HashMap::new(); + for s in plain { + let pages: Vec<(Option, Option)> = match s.kind.as_str() { + "document" => s + .render_id + .and_then(|id| renders_by_id.get(&id)) + .map(|pages| { + pages + .iter() + .map(|p| { + let image = (!p.image.is_empty()).then(|| p.image.clone()); + let text = with_text.then(|| render_texts.get(&p.text_sha).cloned().unwrap_or_default()); + (image, text) + }) + .collect() + }) + .unwrap_or_default(), + "image" => vec![(s.source_blob.clone(), with_text.then(String::new))], + _ => { + let text = match store { + Some(store) => Some(normalized_text(store, s, &mut settings_of).await?), + None => None, + }; + vec![(None, text)] + } + }; + let synthesized = pages + .into_iter() + .enumerate() + .map(|(i, (image, text))| { + let i = i32::try_from(i).unwrap_or(i32::MAX); + Page { + position: i, + op: "unchanged".into(), + state: "unchanged".into(), + head_index: Some(i), + base_index: Some(i), + head_image: image.clone(), + base_image: image, + head_text: text.clone(), + base_text: text, + diff_id: None, + } + }) + .collect(); + out.insert(s.id, synthesized); + } + Ok(out) +} + +/// One snapshot's pages, with their text ([`of_many`]). +/// +/// # Errors +/// On a database error, or when a text snapshot's file is missing. +pub async fn of(store: &BlobStore, snapshot: &Snapshot) -> laravel::Result> { + Ok(of_many(Some(store), &[snapshot]).await?.remove(&snapshot.id).unwrap_or_default()) +} + +/// A text snapshot's text as it was compared: normalized in its format with its build's ignore rules. +async fn normalized_text( + store: &BlobStore, + snapshot: &Snapshot, + settings_of: &mut HashMap, +) -> laravel::Result { + let sha = snapshot.source_blob.clone().ok_or_else(|| laravel::Error::msg("a text snapshot without a file"))?; + let raw = String::from_utf8_lossy(&store.get(&sha).await?).into_owned(); + let Some(format) = super::snapshots::text_format(snapshot) else { return Ok(raw) }; + if let std::collections::hash_map::Entry::Vacant(slot) = settings_of.entry(snapshot.build_id) { + let build = Build::find_or_fail(snapshot.build_id).await?; + let project = Project::find_or_fail(build.project_id).await?; + slot.insert((build, project)); + } + let (build, project) = &settings_of[&snapshot.build_id]; + let rules = BuildSettings::new(project, build).compiled_rules(snapshot); + Ok(visualci_core::snapshot_text::normalize(format, &raw, &rules).text) +} diff --git a/app/src/domain/processing.rs b/app/src/domain/processing.rs new file mode 100644 index 00000000..fe96067c --- /dev/null +++ b/app/src/domain/processing.rs @@ -0,0 +1,837 @@ +//! Processing a finalized build: confirm its uploads, wait for its renders, compare each snapshot with its baseline, +//! carry forward or source what it didn't send, conclude, and charge. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use laravel::db; +use laravel::model::update; +use visualci_core::manifest::{self, Entry}; + +use super::baselines::{self, Resolved}; +use super::build_settings::{BuildSettings, Source}; +use super::builds::{ + CREDITS_PER_GROUP_CHECK, CREDITS_PER_IMAGE_DIFF, CREDITS_PER_RENDERED_PAGE, CREDITS_PER_SNAPSHOT_CHECK, + CREDITS_PER_TEXT_DIFF, EMPTY_BUILD, Stats, +}; +use super::compare::{compare, mark_failed, record_config_change}; +use super::credits::{self, Spender}; +use super::groups::{self, Candidate}; +use super::snapshots::{CONFIG_PLATFORM, is_change, is_config_item}; +use crate::events::{BuildStoppedForCredits, CreditsRanOut}; +use crate::models::{Build, Organization, Project, Render, Snapshot}; +use crate::storage::BlobStore; + +/// A local run the expiry finished keeps saying so. +pub const LOCAL_FINISHED: &str = "Local run, finished without `visualci build finalize`: nothing new arrived for an \ +hour, so VisualCI compared what it had, as a subset (nothing counts as removed). `visualci test -- ` \ +finalizes a run when it ends."; + +/// `error_code` of a build that wasn't compared because its organization had no credits left. +pub const OUT_OF_CREDITS: &str = "out_of_credits"; + +/// What a build used, by kind of work. +#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] +pub struct Usage { + pub snapshot_checks: i64, + pub text_diffs: i64, + pub image_diffs: i64, + pub rendered_pages: i64, + /// Groups that matched their baselines, or 1 for a whole-manifest match. + #[serde(default)] + pub groups_checked: i64, +} + +impl Usage { + #[must_use] + pub fn credits(&self) -> i64 { + self.snapshot_checks * CREDITS_PER_SNAPSHOT_CHECK + + self.groups_checked * CREDITS_PER_GROUP_CHECK + + self.text_diffs * CREDITS_PER_TEXT_DIFF + + self.image_diffs * CREDITS_PER_IMAGE_DIFF + + self.rendered_pages * CREDITS_PER_RENDERED_PAGE + } + + /// "120 snapshots checked, 2 image diffs, 3 pages drawn", leaving out what's zero. + #[must_use] + pub fn describe(&self) -> String { + let plural = |n: i64, one: &str, many: &str| if n == 1 { format!("1 {one}") } else { format!("{n} {many}") }; + [ + (self.snapshot_checks, "snapshot checked", "snapshots checked"), + (self.groups_checked, "group checked", "groups checked"), + (self.text_diffs, "text diff", "text diffs"), + (self.image_diffs, "image diff", "image diffs"), + (self.rendered_pages, "page drawn", "pages drawn"), + ] + .into_iter() + .filter(|(n, _, _)| *n > 0) + .map(|(n, one, many)| plural(n, one, many)) + .collect::>() + .join(", ") + } +} + +/// Hold the build's lock until the transaction ends: one worker (or one early comparison) works on a build at a time. +/// +/// # Errors +/// On a database error. +pub async fn lock(build_id: i64) -> laravel::Result<()> { + // 1447249201 is "VCI1": a namespace for VisualCI's build locks. + db::query!("SELECT pg_advisory_xact_lock(1447249201, ({build_id} % 2147483647)::int)").select().await?; + Ok(()) +} + +/// A document's base, drawn the way the head is drawn. +enum Redraw { + Ready(Box), + Waiting, +} + +/// Documents compare with their base drawn the same way. When the head renders differently (its visualci.yml sets +/// another engine or DPI, or the renderer was upgraded), the base's PDF is drawn again with the head's settings. A base +/// that can't be drawn again (its file may be gone) compares with the render it has. +async fn redraw_base( + settings: &BuildSettings<'_>, + renderer_version: &str, + head: &Snapshot, + base: &Snapshot, +) -> laravel::Result { + if head.kind != "document" || base.kind != "document" { + return Ok(Redraw::Ready(Box::new(base.clone()))); + } + let head_key = settings.renderer_key(head.engine.as_deref(), renderer_version); + let base_key = match base.render_id { + Some(id) => Render::find(id).await?.map(|r| r.renderer), + None => None, + }; + let Some(blob) = base.source_blob.clone() else { return Ok(Redraw::Ready(Box::new(base.clone()))) }; + if base_key.as_deref() == Some(head_key.as_str()) { + return Ok(Redraw::Ready(Box::new(base.clone()))); + } + let render = super::renders::find_or_queue(settings.project.id, &base.source_fingerprint, &head_key, &blob).await?; + Ok(match render.state.as_str() { + "done" => { + let mut redrawn = base.clone(); + redrawn.render_id = Some(render.id); + Redraw::Ready(Box::new(redrawn)) + } + "failed" => Redraw::Ready(Box::new(base.clone())), + _ => Redraw::Waiting, + }) +} + +/// Record which approval row a snapshot was compared with (for "approved locally by …"). +async fn set_baseline_id(snapshot: &mut Snapshot, row: Option) -> laravel::Result<()> { + if snapshot.baseline_id != row { + update!(snapshot { baseline_id: row }).await?; + } + Ok(()) +} + +/// The build whose settings count as approved for builds anchored on `build`: the build itself, unless its +/// "visualci.yml" item wasn't approved, in which case the build that item was compared with (and so on). +async fn approved_settings_build(mut build: Build) -> laravel::Result { + for _ in 0..20 { + let item = Snapshot::query() + .filter(Snapshot::build_id.eq(build.id) & Snapshot::platform.eq(CONFIG_PLATFORM)) + .first() + .await?; + let approved = matches!(build.review_state.as_str(), "approved" | "auto_approved"); + let Some(item) = item.filter(|i| !approved && i.review.as_deref() != Some("approved")) else { + return Ok(build); + }; + let Some(base_id) = item.meta.get("base_build_id").and_then(serde_json::Value::as_i64) else { + return Ok(build); + }; + build = Build::find_or_fail(base_id).await?; + } + Ok(build) +} + +/// Process a finalized build as far as it can go: confirm uploads, queue renders, and once every render is done, +/// compare and conclude. Returns whether the build concluded (false while renders are outstanding). +/// +/// # Errors +/// On a database or storage error. +#[allow(clippy::too_many_lines)] +pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) -> laravel::Result { + if build.state != "processing" { + return Ok(build.state == "completed"); + } + let project = Project::find_or_fail(build.project_id).await?; + let settings = BuildSettings::new(&project, &build); + let id = build.id; + // The "visualci.yml" item is worked out again below. + db::query!("DELETE FROM snapshots WHERE build_id = {id} AND platform = 'visualci'").delete().await?; + let mut snapshots: Vec = Snapshot::query() + .filter(Snapshot::build_id.eq(id)) + .order_by(Snapshot::name.asc()) + .order_by(Snapshot::platform.asc()) + .get() + .await?; + + // Confirm the uploads the build needs: sources of snapshots that have no render. + let needed: Vec = snapshots + .iter() + .filter(|s| s.render_id.is_none() && s.state != "removed") + .filter_map(|s| s.source_blob.clone()) + .collect(); + let missing = super::blobs::confirm_uploads(store, &needed).await?; + + let mut waiting = false; + for snapshot in &mut snapshots { + if snapshot.state == "failed" || snapshot.state == "removed" { + continue; + } + let blob_missing = snapshot.source_blob.as_ref().is_some_and(|b| missing.contains(b)); + if snapshot.kind == "document" { + if snapshot.render_id.is_none() { + if blob_missing { + mark_failed(snapshot, "the file was never uploaded").await?; + continue; + } + let blob = snapshot.source_blob.clone().unwrap_or_default(); + let key = settings.renderer_key(snapshot.engine.as_deref(), renderer_version); + let render = + super::renders::find_or_queue(project.id, &snapshot.source_fingerprint, &key, &blob).await?; + let render_id = Some(render.id); + update!(snapshot { render_id }).await?; + } + let render = Render::find_or_fail(snapshot.render_id.unwrap_or_default()).await?; + match render.state.as_str() { + "done" => {} + "failed" => { + let error = format!("rendering failed: {}", render.error.unwrap_or_default()); + mark_failed(snapshot, &error).await?; + } + _ => waiting = true, + } + } else if blob_missing { + mark_failed(snapshot, "the file was never uploaded").await?; + } + } + if waiting { + return Ok(false); + } + + // Each snapshot's own baseline, and the anchor build ("compared with #N"). + let (resolved, anchor) = baselines::resolve(&build, &project).await?; + let base_build_id = anchor.as_ref().map(|a| a.id); + let baseline_rows: HashMap<(String, String), i64> = + resolved.iter().filter_map(|(k, r)| r.row.as_ref().map(|row| (k.clone(), row.id))).collect(); + let originals: HashMap<(String, String), Snapshot> = + resolved.iter().map(|(k, Resolved { snapshot, .. })| (k.clone(), snapshot.clone())).collect(); + let mut base_snapshots: HashMap<(String, String), Snapshot> = + resolved.into_iter().map(|(key, r)| (key, r.snapshot)).collect(); + + for snapshot in snapshots.iter().filter(|s| s.state != "failed") { + let key = (snapshot.name.clone(), snapshot.platform.clone()); + if let Some(base) = base_snapshots.get(&key) { + match redraw_base(&settings, renderer_version, snapshot, base).await? { + Redraw::Ready(b) => { + base_snapshots.insert(key, *b); + } + Redraw::Waiting => waiting = true, + } + } + } + if waiting { + return Ok(false); + } + + let mut seen = HashSet::new(); + for mut snapshot in snapshots { + seen.insert((snapshot.name.clone(), snapshot.platform.clone())); + if snapshot.state == "failed" { + continue; + } + let key = (snapshot.name.clone(), snapshot.platform.clone()); + match compare(&mut snapshot, store, &settings, base_snapshots.get(&key)).await { + Ok(()) => set_baseline_id(&mut snapshot, baseline_rows.get(&key).copied()).await?, + Err(e) => { + tracing::warn!(build = id, snapshot = snapshot.id, error = %e, "comparing a snapshot failed"); + mark_failed(&mut snapshot, &format!("comparison failed: {e}")).await?; + } + } + } + + // What the build didn't send: a subset build (CI skipped the jobs whose inputs didn't change) and the groups that + // matched their baselines carry it forward unchanged; anything else was removed. + let carry = groups::carry(&build).await?; + let grouping = groups::grouping(build.group_depth); + let sent_keys: HashSet = seen.iter().map(|(name, _)| grouping.key(name)).collect(); + let mut carried: BTreeMap> = BTreeMap::new(); + let mut removed: Vec<(String, String)> = Vec::new(); + for key in base_snapshots.keys() { + if seen.contains(key) { + continue; + } + if build.subset || carry.covers(&key.0) { + carried.entry(grouping.key(&key.0)).or_default().push(key.clone()); + } else { + removed.push(key.clone()); + } + } + // A carried group the build sent nothing of, whose baselines one earlier build holds exactly, is read from that + // build: no rows are written for it (docs/design-storage.md). + let mut candidates = BTreeMap::new(); + for (group, keys) in &carried { + if sent_keys.contains(group) || build.mode != "ci" { + continue; + } + let bases: Vec<&Snapshot> = keys.iter().filter_map(|k| base_snapshots.get(k)).collect(); + let unchanged_render = + keys.iter().all(|k| base_snapshots.get(k).map(|b| b.render_id) == originals.get(k).map(|o| o.render_id)); + if bases.len() != keys.len() || !unchanged_render { + continue; + } + let entries: Vec = bases.iter().map(|s| groups::entry_of(s)).collect(); + let Some(g) = manifest::groups(&entries, grouping).into_iter().next() else { continue }; + candidates.insert(group.clone(), Candidate { base_ids: bases.iter().map(|b| b.id).collect(), hash: g.hash }); + } + let sourced = groups::holders(build.project_id, &candidates).await?; + groups::record_sources(id, &candidates, &sourced).await?; + for (group, keys) in &carried { + if sourced.contains_key(group) { + continue; + } + for key in keys { + let Some(base) = base_snapshots.get(key) else { continue }; + carry_forward(&build, &settings, store, base).await?; + } + } + for (name, platform) in &removed { + let Some(base) = base_snapshots.get(&(name.clone(), platform.clone())) else { continue }; + let pid = laravel::str::uuid7(); + let (kind, fingerprint, blob, render_id, environment) = + (&base.kind, &base.source_fingerprint, &base.source_blob, base.render_id, &base.environment); + let group_key = grouping.key(name); + let (base_id, baseline_id) = (base.id, baseline_rows.get(&(name.clone(), platform.clone())).copied()); + db::query!( + "INSERT INTO snapshots (pid, build_id, group_key, name, platform, kind, source_fingerprint, source_blob, \ + render_id, environment, state, base_snapshot_id, baseline_id) \ + VALUES ({pid}, {id}, {group_key}, {name}, {platform}, {kind}, {fingerprint}, {blob}, {render_id}, \ + {environment}, 'removed', {base_id}, {baseline_id}) \ + ON CONFLICT (build_id, name, platform) DO NOTHING" + ) + .insert() + .await?; + } + + // The file's settings: a loosening ci_mode it can't use, ignore rules that matched nothing, and whether they hide + // more than the base build's (then the build gets a "visualci.yml" item to review). + let mut warnings = settings.config_warnings(); + let names: Vec = super::snapshots::of_build(id).await?.into_iter().map(|s| s.name).collect(); + if settings.scoped_rules().0 == Source::File { + for rule in settings.unmatched_rules(names.iter().map(String::as_str)) { + warnings.push(format!( + "The ignore rule for {:?} in visualci.yml matched no snapshot in this build. Globs match snapshot \ + names as VisualCI shows them, without the root of the uploaded path.", + rule.snapshots + )); + } + } + // Compare the settings with the anchor's approved ones: when the anchor's own visualci.yml item wasn't approved, + // with the settings that item was compared with. + if let Some(a) = &anchor { + let base = approved_settings_build(a.clone()).await?; + let base_settings = BuildSettings::new(&project, &base); + if settings.hides_more_than(&base_settings) { + let base_item = Snapshot::query() + .filter(Snapshot::build_id.eq(base.id) & Snapshot::platform.eq(CONFIG_PLATFORM)) + .first() + .await?; + record_config_change( + id, + base.id, + base_item.map(|s| s.id), + &base_settings.review_settings(), + &settings.review_settings(), + ) + .await?; + } + } + + // Changes made only of changes merged pull requests approved say so (a hint). A failure here costs the hint, never + // the build. + if let Err(e) = super::matching::mark(store, &build).await { + tracing::warn!(build = id, error = %e, "matching approved changes"); + } + + // A local run the expiry finished keeps saying so. + let earlier: Vec = serde_json::from_value(build.warnings.clone()).unwrap_or_default(); + if earlier.iter().any(|w| w == LOCAL_FINISHED) { + warnings.push(LOCAL_FINISHED.to_string()); + } + let has_base = !base_snapshots.is_empty(); + + // What depends on the build's own rows comes before sourcing deletes the unchanged ones: the charge, and whether + // it sent anything (an empty build fails). + charge(&build).await?; + let sent: i64 = db::query!( + "SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND state <> 'removed' \ + AND platform <> 'visualci'" + ) + .scalar() + .await? + .unwrap_or(0); + groups::source_unchanged(&build).await?; + + let mut build = build; + let warnings = serde_json::json!(warnings); + update!(build { warnings }).await?; + let build = conclude(build, base_build_id, has_base, sent).await?; + if build.review_state == "auto_approved" { + // Nothing to review (or the project's first build): its changes are the baselines now. + let all = super::snapshots::of_build(build.id).await?; + let changes: Vec<&Snapshot> = all.iter().filter(|s| !is_config_item(s)).collect(); + baselines::record(&build, &changes, None, None, "auto").await?; + } + Ok(true) +} + +/// Carry a base snapshot forward into a build as its own row, compared with the base (unchanged). +async fn carry_forward( + build: &Build, + settings: &BuildSettings<'_>, + store: &BlobStore, + base: &Snapshot, +) -> laravel::Result<()> { + let (id, pid) = (build.id, laravel::str::uuid7()); + let group_key = groups::grouping(build.group_depth).key(&base.name); + let (name, platform, kind, format, fingerprint, blob, render_id, engine, rules, environment, threshold, aa, meta) = ( + &base.name, + &base.platform, + &base.kind, + &base.format, + &base.source_fingerprint, + &base.source_blob, + base.render_id, + &base.engine, + &base.ignore_rules, + &base.environment, + base.threshold, + base.ignore_anti_aliasing, + &base.meta, + ); + // A second run of this processing (the job retried, or run twice at once) finds the row there already. + let inserted = db::query!( + "INSERT INTO snapshots (pid, build_id, group_key, name, platform, kind, format, source_fingerprint, source_blob, \ + render_id, engine, ignore_rules, environment, threshold, ignore_anti_aliasing, meta, state, carried_forward) \ + VALUES ({pid}, {id}, {group_key}, {name}, {platform}, {kind}, {format}, {fingerprint}, {blob}, {render_id}, \ + {engine}, {rules}, {environment}, {threshold}, {aa}, {meta}, 'pending', true) \ + ON CONFLICT (build_id, name, platform) DO NOTHING" + ) + .insert() + .await? + .rows_affected(); + if inserted == 0 { + return Ok(()); + } + let mut carried = Snapshot::query() + .filter(Snapshot::build_id.eq(id) & Snapshot::name.eq(name.as_str()) & Snapshot::platform.eq(platform.as_str())) + .first() + .await? + .ok_or_else(|| laravel::Error::msg("the carried snapshot wasn't saved"))?; + if let Err(e) = compare(&mut carried, store, settings, Some(base)).await { + tracing::warn!(build = id, snapshot = carried.id, error = %e, "carrying a snapshot forward failed"); + mark_failed(&mut carried, &format!("comparison failed: {e}")).await?; + } + Ok(()) +} + +/// Count snapshot states (a config item counts apart). +#[must_use] +pub fn stats_of(snapshots: &[Snapshot]) -> Stats { + let mut stats = Stats::default(); + for s in snapshots { + if is_config_item(s) { + stats.config += usize::from(is_change(s)); + continue; + } + stats.total += 1; + match s.state.as_str() { + "unchanged" => stats.unchanged += 1, + "changed" => stats.changed += 1, + "added" => stats.added += 1, + "removed" => stats.removed += 1, + "ignored" => stats.ignored += 1, + "failed" => stats.failed += 1, + _ => stats.pending += 1, + } + } + stats +} + +/// Count snapshot states, set the conclusion and review state, and mark the build completed. `sent` is how many +/// snapshots the build was sent itself: none means the upload found nothing, which mustn't pass as "unchanged". +async fn conclude(mut build: Build, base_build_id: Option, has_base: bool, sent: i64) -> laravel::Result { + let all = super::snapshots::of_build(build.id).await?; + let stats = stats_of(&all); + let empty = sent == 0 && !build.allow_empty; + let conclusion = if stats.failed > 0 || empty { + "failed" + } else if stats.changes() > 0 { + "changes" + } else { + "unchanged" + }; + // A local run's changes always wait for review, even in a project's first build: approving one sets the baseline + // for its branch and environment. + let review_state = match (build.mode.as_str(), conclusion, has_base) { + (_, "failed", _) => "none", + (_, "unchanged", _) | ("ci", _, false) => "auto_approved", + _ => "pending", + }; + let stats = serde_json::to_value(&stats).unwrap_or_default(); + let error = empty.then(|| EMPTY_BUILD.to_string()); + let (conclusion, review_state) = (Some(conclusion.to_string()), review_state.to_string()); + let completed_at = Some(laravel::now().timestamp()); + update!(build { state: "completed", conclusion, review_state, base_build_id, stats, completed_at, error }).await?; + Ok(build) +} + +/// Recount after a review action changed snapshot states (an ignored change, an accepted variant). +/// +/// # Errors +/// On a database error. +pub async fn recount(mut build: Build) -> laravel::Result { + let all = super::snapshots::of_build(build.id).await?; + let stats = stats_of(&all); + let changes = stats.changes(); + let stats = serde_json::to_value(&stats).unwrap_or_default(); + if build.conclusion.as_deref() == Some("changes") && changes == 0 { + let review_state = + if build.review_state == "pending" { "auto_approved".to_string() } else { build.review_state.clone() }; + update!(build { stats, conclusion: Some("unchanged".to_string()), review_state }).await?; + } else { + update!(build { stats }).await?; + } + Ok(build) +} + +/// Charge the organization for this build: every snapshot it sent (carried-forward snapshots weren't sent), the text +/// and image diffs it computed, the PDF pages it drew and the groups it checked. Charges only what wasn't charged +/// before (an early comparison charges as it goes), and records the total in `builds.charged`. +/// +/// # Errors +/// On a database error. +pub async fn charge(build: &Build) -> laravel::Result<()> { + let project = Project::find_or_fail(build.project_id).await?; + let mut fresh = Build::find_or_fail(build.id).await?; + let charged: Usage = serde_json::from_value(fresh.charged.clone()).unwrap_or_default(); + let (id, since) = (build.id, build.created_at); + let row = db::query!( + "SELECT \ + (SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND state <> 'removed')::BIGINT AS checks, \ + (SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND kind = 'text' AND state = 'changed')::BIGINT AS text_diffs, \ + (SELECT COALESCE(SUM(jsonb_array_length(r.pages)), 0) FROM renders r \ + WHERE r.id IN (SELECT render_id FROM snapshots WHERE build_id = {id}) AND r.created_at >= {since})::BIGINT AS pages, \ + (SELECT COUNT(DISTINCT d.id) FROM diffs d JOIN snapshot_pages p ON p.diff_id = d.id \ + JOIN snapshots s ON s.id = p.snapshot_id WHERE s.build_id = {id} AND d.created_at >= {since})::BIGINT AS image_diffs" + ) + .select_one() + .await?; + let get = |name: &str| -> i64 { row.as_ref().and_then(|r| r.try_get(name).ok()).unwrap_or(0) }; + let usage = Usage { + snapshot_checks: get("checks"), + text_diffs: get("text_diffs"), + image_diffs: get("image_diffs"), + rendered_pages: get("pages"), + groups_checked: groups::checks(&fresh).await?, + }; + let delta = Usage { + snapshot_checks: (usage.snapshot_checks - charged.snapshot_checks).max(0), + text_diffs: (usage.text_diffs - charged.text_diffs).max(0), + image_diffs: (usage.image_diffs - charged.image_diffs).max(0), + rendered_pages: (usage.rendered_pages - charged.rendered_pages).max(0), + groups_checked: (usage.groups_checked - charged.groups_checked).max(0), + }; + let amount = delta.credits(); + if amount > 0 { + let reference = format!("build {}/{}: {}", project.slug, build.number, delta.describe()); + credits::spend( + project.organization_id, + amount, + "build", + Some(&reference), + Some(Spender::of(&project)), + Some(build.id), + ) + .await?; + } + let total = Usage { + snapshot_checks: usage.snapshot_checks.max(charged.snapshot_checks), + text_diffs: usage.text_diffs.max(charged.text_diffs), + image_diffs: usage.image_diffs.max(charged.image_diffs), + rendered_pages: usage.rendered_pages.max(charged.rendered_pages), + groups_checked: usage.groups_checked.max(charged.groups_checked), + }; + let charged = serde_json::to_value(total).unwrap_or_default(); + update!(fresh { charged }).await?; + Ok(()) +} + +/// Fail a build that's processing when its organization is out of credits, after billing's chance to reload (the +/// `CreditsRanOut` event's listeners run first). Billing's listeners hear `BuildStoppedForCredits` (the monthly email). +/// +/// # Errors +/// On a database error. +pub async fn stop_if_out_of_credits(mut build: Build) -> laravel::Result { + if build.state != "processing" { + return Ok(build); + } + let project = Project::find_or_fail(build.project_id).await?; + let spender = Spender::of(&project); + let org = Organization::find_or_fail(project.organization_id).await?; + if !credits::out_of_credits_for(&org, spender).await? { + return Ok(build); + } + CreditsRanOut { organization_id: org.id }.dispatch().await?; + let org = Organization::find_or_fail(org.id).await?; + if !credits::out_of_credits_for(&org, spender).await? { + return Ok(build); + } + let plan = credits::plan_by_id(&org.plan); + let what_now = if plan.credit_packs { + "Buy a credit pack on the billing page, or raise the limit on automatic reloads." + } else { + "Upgrade to Team on the billing page, or wait for the allowance to renew on the 1st." + }; + let error = Some(format!( + "{} has used this month's {} credits on the {} plan and has no pack credits left, so this build wasn't \ + compared. {what_now}", + org.name, + credits::thousands(plan.included_credits), + plan.name + )); + update!(build { state: "failed", error_code: Some(OUT_OF_CREDITS.to_string()), error }).await?; + BuildStoppedForCredits { build_id: build.id, organization_id: org.id }.dispatch().await?; + Ok(build) +} + +/// A build stopped: its queued renders that no other receiving or processing build waits on aren't drawn. +/// +/// # Errors +/// On a database error. +pub async fn drop_unneeded_renders(build_id: i64) -> laravel::Result<()> { + let id = build_id; + db::query!( + "UPDATE renders SET state = 'failed', error = 'its build ran out of credits', updated_at = now() \ + WHERE state = 'queued' AND id IN (SELECT render_id FROM snapshots WHERE build_id = {id}) \ + AND NOT EXISTS (SELECT 1 FROM snapshots s JOIN builds b ON b.id = s.build_id \ + WHERE s.render_id = renders.id AND s.build_id <> {id} AND b.state IN ('receiving', 'processing'))" + ) + .update() + .await?; + Ok(()) +} + +/// How long a build may wait for its next upload or shard before it's given up on. +pub const ABANDON_AFTER_MINUTES: i32 = 60; + +/// The error an abandoned build carries. +pub const ABANDONED: &str = "Nothing arrived for this build for an hour, so VisualCI gave up on it: the CI job most \ +likely stopped (or failed) before `visualci build finalize`. Re-run the job to send a new build."; + +/// Builds nothing arrived for in [`ABANDON_AFTER_MINUTES`] (in one project, or everywhere): CI builds fail with +/// [`ABANDONED`]; local runs (which often end without finalizing) are finished as subsets and processed. Their checks +/// and pages follow (`BuildChanged`). Returns how many it expired. +/// +/// # Errors +/// On a database or queue error. +pub async fn expire_abandoned(project_id: Option) -> laravel::Result { + let minutes = ABANDON_AFTER_MINUTES; + let ids = + |rows: Vec| -> Vec { rows.iter().filter_map(|r| r.try_get("id").ok()).collect() }; + let failed = ids(db::query!( + "UPDATE builds b SET state = 'failed', conclusion = 'failed', review_state = 'none', error = {ABANDONED}, \ + completed_at = now(), updated_at = now() \ + WHERE b.mode <> 'local' AND b.state = 'receiving' AND ({project_id}::BIGINT IS NULL OR b.project_id = {project_id}) \ + AND GREATEST(b.updated_at, \ + COALESCE((SELECT MAX(s.updated_at) FROM snapshots s WHERE s.build_id = b.id), b.created_at)) \ + < now() - make_interval(mins => {minutes}) \ + RETURNING b.id" + ) + .select() + .await?); + let finished = ids(db::query!( + "UPDATE builds b SET state = 'processing', subset = true, allow_empty = true, \ + warnings = b.warnings || jsonb_build_array({LOCAL_FINISHED}::TEXT), finalized_at = now(), updated_at = now() \ + WHERE b.mode = 'local' AND b.state = 'receiving' AND ({project_id}::BIGINT IS NULL OR b.project_id = {project_id}) \ + AND GREATEST(b.updated_at, \ + COALESCE((SELECT MAX(s.updated_at) FROM snapshots s WHERE s.build_id = b.id), b.created_at)) \ + < now() - make_interval(mins => {minutes}) \ + RETURNING b.id" + ) + .select() + .await?); + for id in &failed { + crate::events::BuildChanged { build_id: *id }.dispatch().await?; + } + for id in &finished { + let build = stop_if_out_of_credits(Build::find_or_fail(*id).await?).await?; + if build.state == "processing" { + crate::jobs::process_build::ProcessBuild { build_id: *id }.dispatch().await?; + } else { + crate::events::BuildChanged { build_id: *id }.dispatch().await?; + } + } + Ok(failed.len() + finished.len()) +} + +/// Compare some of a build's snapshots now, before it's finalized: a local run checks each test's snapshots as the test +/// makes them. Snapshots whose files haven't arrived or whose PDFs are still rendering come back `pending`; ask again. +/// Finalizing compares everything again, so these results are never the final word. +/// +/// # Errors +/// `Ok(Err(message))` when the organization is out of credits; `Err` on a database or storage error. +pub async fn compare_now( + build: &Build, + store: &BlobStore, + renderer_version: &str, + wanted: &[(String, String)], +) -> laravel::Result, String>> { + let project = Project::find_or_fail(build.project_id).await?; + if build.state == "receiving" { + let org = Organization::find_or_fail(project.organization_id).await?; + if credits::out_of_credits_for(&org, Spender::of(&project)).await? { + return Ok(Err(format!( + "{} is out of VisualCI credits, so snapshots can't be compared: its billing page has the fix (the \ + build's `blocked` says more)", + org.name + ))); + } + } + let settings = BuildSettings::new(&project, build); + let snapshots: Vec = super::snapshots::of_build(build.id) + .await? + .into_iter() + .filter(|s| wanted.iter().any(|(n, p)| *n == s.name && *p == s.platform)) + .collect(); + if build.state != "receiving" { + return Ok(Ok(snapshots)); + } + let needed: Vec = + snapshots.iter().filter(|s| s.render_id.is_none()).filter_map(|s| s.source_blob.clone()).collect(); + let missing = super::blobs::confirm_uploads(store, &needed).await?; + let (resolved, _) = baselines::resolve(build, &project).await?; + let mut out = Vec::with_capacity(snapshots.len()); + for mut snapshot in snapshots { + if snapshot.source_blob.as_ref().is_some_and(|b| missing.contains(b)) { + out.push(snapshot); + continue; + } + if snapshot.kind == "document" { + if snapshot.render_id.is_none() { + let blob = snapshot.source_blob.clone().unwrap_or_default(); + let key = settings.renderer_key(snapshot.engine.as_deref(), renderer_version); + let render = + super::renders::find_or_queue(project.id, &snapshot.source_fingerprint, &key, &blob).await?; + let render_id = Some(render.id); + update!(snapshot { render_id }).await?; + } + let render = Render::find_or_fail(snapshot.render_id.unwrap_or_default()).await?; + match render.state.as_str() { + "done" => {} + "failed" => { + let error = format!("rendering failed: {}", render.error.unwrap_or_default()); + mark_failed(&mut snapshot, &error).await?; + out.push(snapshot); + continue; + } + _ => { + out.push(snapshot); + continue; + } + } + } + let key = (snapshot.name.clone(), snapshot.platform.clone()); + let row = resolved.get(&key).and_then(|r| r.row.as_ref().map(|row| row.id)); + let base = match resolved.get(&key) { + Some(r) => match redraw_base(&settings, renderer_version, &snapshot, &r.snapshot).await? { + Redraw::Ready(b) => Some(*b), + Redraw::Waiting => { + out.push(snapshot); + continue; + } + }, + None => None, + }; + match compare(&mut snapshot, store, &settings, base.as_ref()).await { + Ok(()) => set_baseline_id(&mut snapshot, row).await?, + Err(e) => { + tracing::warn!(build = build.id, snapshot = snapshot.id, error = %e, "comparing a snapshot early failed") + } + } + out.push(snapshot); + } + // Charge for what this did (snapshot checks, diffs, pages drawn); finalizing charges only the rest. + charge(build).await?; + Ok(Ok(out)) +} + +/// The warning on a local build nobody reviewed for [`LOCAL_IDLE_DAYS`]. +pub const LOCAL_IDLE: &str = "Closed without review: a local build, idle for 7 days."; +/// How long a local build waits for its own person's review before it leaves the waiting lists. +pub const LOCAL_IDLE_DAYS: i32 = 7; +/// A build still processing this long after its last change is run again: its job's dispatch may have been lost. +pub const RESTART_AFTER_MINUTES: i32 = 10; +/// A build still processing this long after it was finalized fails: something keeps it from finishing. +pub const GIVE_UP_AFTER_HOURS: i32 = 6; +/// The error on a build that never finished processing. +pub const STUCK: &str = "This build didn't finish comparing within 6 hours, so VisualCI stopped it. Re-run the CI job \ +to send it again; if it happens again, tell us with `support_send`."; + +/// What a sweep did. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Swept { + pub expired: usize, + pub idle_local_closed: usize, + pub restarted: usize, + pub stuck_failed: usize, +} + +/// The sweep the scheduler runs every few minutes: expire abandoned builds ([`expire_abandoned`]), close local builds +/// idle for a week, run again builds processing with no change for [`RESTART_AFTER_MINUTES`] (a lost dispatch, a +/// crashed worker), and fail builds still processing [`GIVE_UP_AFTER_HOURS`] after they were finalized. +/// +/// # Errors +/// On a database or queue error. +pub async fn sweep() -> laravel::Result { + let expired = expire_abandoned(None).await?; + let days = LOCAL_IDLE_DAYS; + let idle: Vec = db::query!( + "UPDATE builds b SET review_state = 'closed', warnings = b.warnings || jsonb_build_array({LOCAL_IDLE}::TEXT), \ + updated_at = now() \ + WHERE b.mode = 'local' AND b.review_state = 'pending' \ + AND GREATEST(b.updated_at, \ + COALESCE((SELECT MAX(s.updated_at) FROM snapshots s WHERE s.build_id = b.id), b.created_at)) \ + < now() - make_interval(days => {days}) \ + RETURNING b.id" + ) + .select_as() + .await?; + let hours = GIVE_UP_AFTER_HOURS; + let stuck: Vec = db::query!( + "UPDATE builds SET state = 'failed', conclusion = 'failed', review_state = 'none', error = {STUCK}, \ + completed_at = now(), updated_at = now() \ + WHERE state = 'processing' AND COALESCE(finalized_at, created_at) < now() - make_interval(hours => {hours}) \ + RETURNING id" + ) + .select_as() + .await?; + let minutes = RESTART_AFTER_MINUTES; + let restart: Vec = db::query!( + "SELECT id FROM builds WHERE state = 'processing' AND updated_at < now() - make_interval(mins => {minutes}) \ + ORDER BY id" + ) + .select_as() + .await?; + for id in idle.iter().chain(&stuck) { + crate::events::BuildChanged { build_id: *id }.dispatch().await?; + } + for id in &restart { + crate::jobs::process_build::ProcessBuild { build_id: *id }.dispatch().await?; + } + Ok(Swept { expired, idle_local_closed: idle.len(), restarted: restart.len(), stuck_failed: stuck.len() }) +} diff --git a/app/src/domain/projects.rs b/app/src/domain/projects.rs index 51397382..8f24539a 100644 --- a/app/src/domain/projects.rs +++ b/app/src/domain/projects.rs @@ -1,4 +1,5 @@ -//! Project settings the domain reads. +//! Projects: making one, its settings (as the MCP tools and the web app read and change them), and what the domain +//! reads from them. use visualci_core::config::ScopedIgnoreRule; @@ -39,3 +40,281 @@ pub fn diff_options( pub fn renderer_key(engine: &str, dpi: i32, renderer_version: &str) -> String { format!("{engine}/{dpi}dpi/{renderer_version}") } + +/// Lowercase letters, digits and dashes, at most 60, and not `billing` (the organization's billing page is +/// `app.visualci.com//billing`). +#[must_use] +pub fn valid_slug(s: &str) -> bool { + !s.is_empty() + && s.len() <= 60 + && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + && s != "billing" +} + +/// A project's settings, as the web app shows them and the MCP server returns them. +#[derive(Debug, Clone, serde::Serialize)] +pub struct Settings { + pub slug: String, + pub name: String, + /// The forge the repository is on (`github`), and the repository's URL. + pub forge: Option, + pub repository_url: Option, + /// Whether the forge's app is installed on the repository, so pull requests get VisualCI's check and people's + /// access follows their permission on it. + pub forge_app_installed: bool, + /// When the forge's webhook last delivered a verified event, or VisualCI added it (GitLab). + pub forge_webhook_at: Option, + /// Whether the screenshots visualci.yml's `gallery` names are public. + pub gallery_enabled: bool, + /// Whether project tokens may approve changes over MCP; off keeps approving with people. + pub tokens_can_approve: bool, + /// Whether VisualCI comments on a pull request whose builds are all unchanged. Off by default: the VisualCI check + /// still passes, and a comment already there (an earlier build had changes) keeps being updated. + pub comment_when_unchanged: bool, + /// Whether anyone, signed in or not, can read the project's builds and diffs (open source). Settings, tokens and + /// reviewing stay with its members. + pub public: bool, + /// The forge says the linked repository is public (checked on linking and once a day). Only then can the project + /// be public. + pub repository_public: bool, + /// The forge verified the repository as public with an OSI-approved licence (checked on linking and once a day). + pub open_source: bool, + /// Why it isn't open source, or its licence when it is. + pub open_source_note: Option, + /// Whether its builds draw from the open source pool now: open source, public, and not withdrawn by staff. + pub open_source_pool: bool, + pub open_source_withdrawn: bool, + /// A change VisualCI made on its own (made private when its repository went private), until it's dismissed. + pub notice: Option, + pub default_branch: String, + pub ci_mode: String, + pub renderer: String, + pub dpi: i32, + pub threshold: f64, + pub ignore_anti_aliasing: bool, + pub ignore_rules: Vec, +} + +impl From<&Project> for Settings { + fn from(p: &Project) -> Self { + Self { + slug: p.slug.clone(), + name: p.name.clone(), + forge: p.forge.clone(), + repository_url: p.repository_url.clone(), + forge_app_installed: p.forge_installation.is_some(), + forge_webhook_at: p.forge_webhook_at.map(|d| d.to_string()), + gallery_enabled: p.gallery_enabled, + tokens_can_approve: p.tokens_can_approve, + comment_when_unchanged: p.comment_when_unchanged, + public: p.public, + repository_public: p.repository_public, + open_source: p.open_source, + open_source_note: p.open_source_note.clone(), + open_source_pool: super::credits::counts_as_open_source(p), + open_source_withdrawn: p.open_source_withdrawn, + notice: p.notice.clone(), + default_branch: p.default_branch.clone(), + ci_mode: p.ci_mode.clone(), + renderer: p.renderer.clone(), + dpi: p.dpi, + threshold: p.threshold, + ignore_anti_aliasing: p.ignore_anti_aliasing, + ignore_rules: ignore_rules(p), + } + } +} + +/// Changes to a project's settings; fields left out stay as they are. +#[derive(Debug, Default, serde::Deserialize, schemars::JsonSchema)] +pub struct SettingsChange { + /// A new slug, renaming the project (`acme/old` → `acme/new`): lowercase letters, digits and dashes. Its builds, + /// baselines and tokens stay. The old address and `acme/old` stop working. + pub slug: Option, + /// The project's display name. + pub name: Option, + /// The repository this project tests, by URL (`https://github.com/acme/web`); an empty string unlinks it. + /// Linking needs the forge's VisualCI app installed on the repository and you to be an admin or maintainer of + /// it there. Its pull requests then get VisualCI's check, and people's access to this organization follows their + /// permission on it. + pub repository_url: Option, + /// A project on your organization's own GitLab instance: an access token for it (a project or group access token + /// with the `api` scope and the Developer role, or Maintainer to let VisualCI add its webhook), sent with + /// `repository_url`. Stored encrypted; never shown again. + pub forge_token: Option, + /// With `repository_url`: a repository belongs to one organization, so when another organization has it linked, + /// `true` moves the link here (you must maintain the repository; that organization's admins get an email). + #[serde(default)] + pub move_link: bool, + /// `false` takes the public gallery down (visualci.yml's `gallery` decides what's in it); `true` puts it back. + pub gallery_enabled: Option, + /// `false`: project tokens can't approve changes (people do); `true` lets CI's agents approve again. + pub tokens_can_approve: Option, + /// `true`: comment on pull requests even when nothing changed. `false` (the default): a pull request whose builds + /// are all unchanged gets no comment, only the passing check; a comment already there keeps being updated. + pub comment_when_unchanged: Option, + /// `true` lets anyone, signed in or not, read the project's builds and diffs (for open source projects); + /// settings, tokens and reviewing stay with its members. Only a project linked to a public repository can be + /// public. `false` makes it private again. + pub public: Option, + /// `true` dismisses the project's notice. + pub dismiss_notice: Option, + /// The branch whose builds become the baseline automatically. + pub default_branch: Option, + /// `review` (CI passes, the check waits for review), `strict` (CI fails on unreviewed changes) or `wait`. + pub ci_mode: Option, + /// The PDF renderer: `pdfbox` or `mutool`. + pub renderer: Option, + /// Render resolution for documents, 36 to 600. + pub dpi: Option, + /// The diff threshold, 0 to 1: 0 compares exactly; above 0 it's pixelmatch's colour threshold (how different a + /// pixel's colour must be to count), and anti-aliased pixels are ignored. + pub threshold: Option, + /// Ignore anti-aliasing differences in images. + pub ignore_anti_aliasing: Option, + /// Values in text snapshots that change on every run, ignored when comparing. Replaces the project's rules. Each + /// rule names the snapshots it applies to with a glob (`api/invoices/**`; `**` for every snapshot). A build's + /// `visualci.yml` replaces these rules when it has `ignore`. + pub ignore_rules: Option>, +} + +/// Make a project in an organization, with the default settings. +/// +/// # Errors +/// `Ok(Err(message))` for a slug that isn't valid or is taken; `Err` on a database error. +pub async fn create(organization_id: i64, slug: &str, name: &str) -> laravel::Result> { + if !valid_slug(slug) { + return Ok(Err("project slugs use lowercase letters, digits and dashes, and can't be billing".into())); + } + let taken = + Project::query().filter(Project::organization_id.eq(organization_id) & Project::slug.eq(slug)).exists().await?; + if taken { + return Ok(Err(format!("the organization already has a project called {slug}"))); + } + let name = name.trim(); + Ok(Ok(laravel::model::create!(Project { + pid: laravel::str::uuid7(), + organization_id: organization_id, + slug: slug, + name: name, + }) + .await?)) +} + +/// The repository its newest CI build named (`environment_info.repository_url`), for suggesting a link. +/// +/// # Errors +/// On a database error. +pub async fn repository_seen_in_ci(project: &Project) -> laravel::Result> { + let project_id = project.id; + let info: Option = laravel::db::query!( + "SELECT environment_info FROM builds WHERE project_id = {project_id} AND mode = 'ci' ORDER BY id DESC LIMIT 1" + ) + .scalar() + .await?; + Ok(info + .as_ref() + .and_then(|i| i.get("repository_url")) + .and_then(|v| v.as_str()) + .and_then(crate::forge::Repository::parse) + .map(|r| r.url)) +} + +/// Apply a settings change, checking every field first. The repository link isn't set here: it needs the forge to agree +/// (subdomains' `forge::link::link_repository`), which callers do first. Turning the gallery off purges what it +/// published first. +/// +/// # Errors +/// `Ok(Err(message))` for a value that isn't valid; `Err` on a database error. +pub async fn change_settings(project: Project, p: SettingsChange) -> laravel::Result> { + let new_slug = p.slug.as_deref().map(str::trim).filter(|s| *s != project.slug).map(str::to_string); + if let Some(slug) = &new_slug { + if !valid_slug(slug) { + return Ok(Err("slug must be lowercase letters, digits and dashes, at most 60 characters".into())); + } + let taken = Project::query() + .filter(Project::organization_id.eq(project.organization_id) & Project::slug.eq(slug.as_str())) + .exists() + .await?; + if taken { + return Ok(Err(format!("the organization already has a project called {slug}"))); + } + } + // A private repository's screenshots stay private: only a project whose repository the forge says is public can + // be made public. + if p.public == Some(true) && !project.public && !project.repository_public { + return Ok(Err("only a project linked to a public repository can be public".into())); + } + if let Some(m) = &p.ci_mode + && !["review", "strict", "wait"].contains(&m.as_str()) + { + return Ok(Err("ci_mode must be review, strict or wait".into())); + } + if let Some(r) = &p.renderer + && !["pdfbox", "mutool"].contains(&r.as_str()) + { + return Ok(Err("renderer must be pdfbox or mutool".into())); + } + if p.dpi.is_some_and(|d| !(36..=600).contains(&d)) { + return Ok(Err("dpi must be 36 to 600".into())); + } + if p.threshold.is_some_and(|t| !(0.0..=1.0).contains(&t)) { + return Ok(Err("threshold must be between 0 and 1".into())); + } + let ignore_rules = match p.ignore_rules { + Some(rules) => { + let clean = |v: Vec| -> Vec { + v.into_iter().map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect() + }; + let rules: Vec = rules + .into_iter() + .map(|r| ScopedIgnoreRule { + snapshots: r.snapshots.trim().to_string(), + json_paths: clean(r.json_paths), + text_patterns: clean(r.text_patterns), + }) + .collect(); + if let Err(e) = visualci_core::config::validate_ignore_rules(&rules) { + return Ok(Err(e)); + } + Some(serde_json::to_value(rules).unwrap_or_default()) + } + None => None, + }; + if p.gallery_enabled == Some(false) && project.gallery_enabled { + super::gallery::purge_project(project.id).await?; + } + let mut project = project; + let slug = new_slug.unwrap_or_else(|| project.slug.clone()); + let name = p.name.unwrap_or_else(|| project.name.clone()); + let tokens_can_approve = p.tokens_can_approve.unwrap_or(project.tokens_can_approve); + let comment_when_unchanged = p.comment_when_unchanged.unwrap_or(project.comment_when_unchanged); + let gallery_enabled = p.gallery_enabled.unwrap_or(project.gallery_enabled); + let public = p.public.unwrap_or(project.public); + let notice = if p.dismiss_notice == Some(true) { None } else { project.notice.clone() }; + let default_branch = p.default_branch.unwrap_or_else(|| project.default_branch.clone()); + let ci_mode = p.ci_mode.unwrap_or_else(|| project.ci_mode.clone()); + let renderer = p.renderer.unwrap_or_else(|| project.renderer.clone()); + let dpi = p.dpi.unwrap_or(project.dpi); + let threshold = p.threshold.unwrap_or(project.threshold); + let ignore_anti_aliasing = p.ignore_anti_aliasing.unwrap_or(project.ignore_anti_aliasing); + let ignore_rules = ignore_rules.unwrap_or_else(|| project.ignore_rules.clone()); + laravel::model::update!(project { + slug, + name, + tokens_can_approve, + comment_when_unchanged, + gallery_enabled, + public, + notice, + default_branch, + ci_mode, + renderer, + dpi, + threshold, + ignore_anti_aliasing, + ignore_rules, + }) + .await?; + Ok(Ok(project)) +} diff --git a/app/src/domain/renders.rs b/app/src/domain/renders.rs new file mode 100644 index 00000000..acb85651 --- /dev/null +++ b/app/src/domain/renders.rs @@ -0,0 +1,304 @@ +//! Renders: a source (a PDF) turned into page images by one renderer. Cached per project by (source fingerprint, +//! renderer), so a document that hasn't changed is never drawn twice, whichever build, branch or laptop sends it. +//! Never across projects: the fingerprint is the client's word, and another account's render under it would be +//! compared in place of the project's own PDF. + +use laravel::db; +use laravel::model::update; +use serde::{Deserialize, Serialize}; + +use crate::models::Render; + +/// A claim older than this is treated as abandoned (the renderer died) and the render is handed out again. +pub const CLAIM_TIMEOUT_SECONDS: i64 = 600; +pub const MAX_ATTEMPTS: i32 = 3; + +/// One rendered page, as stored in `renders.pages`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RenderPage { + /// SHA-256 of the page's PNG (a blob). + pub image: String, + /// Pixel fingerprint of the PNG. + pub image_fingerprint: String, + /// The page's PDF fingerprint (what it draws): the alignment key. + pub fingerprint: String, + pub width: u32, + pub height: u32, + /// SHA-256 of the page's extracted text (`texts`): what `renders.pages` stores. + #[serde(default)] + pub text_sha: String, + /// The page's extracted text: sent by the renderer, and filled from `texts` by [`with_text`]. Never stored here. + #[serde(default, skip_serializing)] + pub text: String, +} + +/// A render's pages, without their text. +#[must_use] +pub fn pages(render: &Render) -> Vec { + serde_json::from_value(render.pages.clone()).unwrap_or_default() +} + +/// Fill in pages' text from `texts`. +/// +/// # Errors +/// On a database error. +pub async fn with_text(mut pages: Vec) -> laravel::Result> { + let shas: Vec = pages.iter().map(|p| p.text_sha.clone()).collect(); + let texts = crate::storage::texts::load(&shas).await?; + for p in &mut pages { + if let Some(t) = texts.get(&p.text_sha) { + p.text.clone_from(t); + } + } + Ok(pages) +} + +/// The render for this source, queued when it doesn't exist yet (or failed before, under [`MAX_ATTEMPTS`]). +/// +/// # Errors +/// On a database error. +pub async fn find_or_queue( + project_id: i64, + fingerprint: &str, + renderer: &str, + source_blob: &str, +) -> laravel::Result { + db::query!( + "INSERT INTO renders (project_id, source_fingerprint, renderer, source_blob) \ + VALUES ({project_id}, {fingerprint}, {renderer}, {source_blob}) \ + ON CONFLICT (project_id, source_fingerprint, renderer) DO UPDATE SET used_at = now() \ + WHERE renders.used_at IS NULL OR renders.used_at < now() - interval '1 hour'" + ) + .insert() + .await?; + let mut render = Render::query() + .filter( + Render::project_id.eq(project_id) + & Render::source_fingerprint.eq(fingerprint) + & Render::renderer.eq(renderer), + ) + .first() + .await? + .ok_or_else(|| laravel::Error::msg("the queued render wasn't saved"))?; + if render.state == "failed" && render.attempts < MAX_ATTEMPTS { + let source_blob = source_blob.to_string(); + update!(render { state: "queued", source_blob }).await?; + } + Ok(render) +} + +/// Note that a snapshot reuses this render now (at most once an hour): retention leaves its images and texts alone for +/// a day after. +/// +/// # Errors +/// On a database error. +pub async fn mark_used(render_id: i64) -> laravel::Result<()> { + db::query!( + "UPDATE renders SET used_at = now() \ + WHERE id = {render_id} AND (used_at IS NULL OR used_at < now() - interval '1 hour')" + ) + .update() + .await?; + Ok(()) +} + +/// Record a render's pages: their texts go to `texts`, and the pages keep the hashes. +/// +/// # Errors +/// On a database error. +pub async fn complete(mut render: Render, pages: &[RenderPage]) -> laravel::Result { + let bodies: Vec<&str> = pages.iter().map(|p| p.text.as_str()).collect(); + let shas = crate::storage::texts::store(&bodies).await?; + let stored: Vec = + pages.iter().zip(shas).map(|(p, text_sha)| RenderPage { text_sha, text: String::new(), ..p.clone() }).collect(); + let pages = serde_json::to_value(stored).unwrap_or_default(); + let now = laravel::now().timestamp(); + let render_ms = render.claimed_at.map(|claimed| now.as_millisecond() - claimed.as_millisecond()); + update!(render { state: "done", pages, error: None, completed_at: Some(now), render_ms }).await?; + Ok(render) +} + +/// Record a failure. The render is drawn again by the next build that needs it, up to [`MAX_ATTEMPTS`]. +/// +/// # Errors +/// On a database error. +pub async fn fail(mut render: Render, error: &str) -> laravel::Result { + let now = laravel::now().timestamp(); + let render_ms = render.claimed_at.map(|claimed| now.as_millisecond() - claimed.as_millisecond()); + let error = Some(error.chars().take(4000).collect::()); + update!(render { state: "failed", error, completed_at: Some(now), render_ms }).await?; + Ok(render) +} + +/// The error a render gets when its claims ran out: every attempt was claimed and none finished. +pub const CLAIMS_RAN_OUT: &str = "the renderer stopped before finishing this PDF, on every attempt"; + +/// Renders whose last claim expired with no attempts left: they'd stay `rendering` forever. They fail, and the builds +/// waiting on them are processed again (their snapshots fail with the render). Run before each claim. Returns them. +/// +/// # Errors +/// On a database or queue error. +pub async fn fail_exhausted_claims() -> laravel::Result> { + let (timeout, attempts) = (CLAIM_TIMEOUT_SECONDS, MAX_ATTEMPTS); + let failed: Vec = db::query!( + "UPDATE renders SET state = 'failed', error = {CLAIMS_RAN_OUT}, completed_at = now(), updated_at = now(), \ + render_ms = (EXTRACT(EPOCH FROM (now() - claimed_at)) * 1000)::BIGINT, claim_token_hash = NULL \ + WHERE state = 'rendering' AND claimed_at < now() - make_interval(secs => {timeout}) \ + AND attempts >= {attempts} \ + RETURNING *" + ) + .select_as() + .await?; + for render in &failed { + wake_waiting(render).await?; + } + Ok(failed) +} + +/// Process again every build waiting on this render: renders are per project, so that's the project's processing builds +/// (the ones whose snapshots use it, and the ones waiting for their base's PDF to be drawn again with their own +/// renderer settings). Processing a build that's still waiting does nothing. +/// +/// # Errors +/// On a database or queue error. +pub async fn wake_waiting(render: &Render) -> laravel::Result<()> { + let render_id = render.id; + let rows = match render.project_id { + Some(project_id) => { + db::query!("SELECT id FROM builds WHERE project_id = {project_id} AND state = 'processing'") + .select() + .await? + } + None => { + db::query!( + "SELECT DISTINCT b.id FROM builds b JOIN snapshots s ON s.build_id = b.id \ + WHERE s.render_id = {render_id} AND b.state = 'processing'" + ) + .select() + .await? + } + }; + for build_id in rows.iter().filter_map(|r| r.try_get::("id").ok()) { + crate::jobs::process_build::ProcessBuild { build_id }.dispatch().await?; + } + Ok(()) +} + +/// Hand the oldest waiting render for `renderer_version` to a renderer, with the token its claim gets (the renderer +/// needs it to upload the render's pages and complete it), or `None` when there's nothing to do. Projects take turns: +/// the next render is the oldest from the project with the fewest being drawn now, so one account's flood of PDFs can't +/// hold the renderers from everyone else. A claim older than [`CLAIM_TIMEOUT_SECONDS`] is handed out again, until +/// [`MAX_ATTEMPTS`]; past that the render fails ([`fail_exhausted_claims`]). The version must match the render's +/// exactly (the last part of `engine/dpi/version`). +/// +/// # Errors +/// On a database error. +pub async fn claim(renderer_version: &str) -> laravel::Result> { + fail_exhausted_claims().await?; + let token = laravel::str::random(40); + let hash = visualci_core::sha256_hex(token.as_bytes()); + let (timeout, attempts) = (CLAIM_TIMEOUT_SECONDS, MAX_ATTEMPTS); + let render: Option = db::query!( + "UPDATE renders SET state = 'rendering', claimed_at = now(), attempts = attempts + 1, updated_at = now(), \ + claim_token_hash = {hash}, \ + wait_ms = COALESCE(wait_ms, (EXTRACT(EPOCH FROM (now() - created_at)) * 1000)::BIGINT) \ + WHERE id = (SELECT r.id FROM renders r \ + WHERE substring(r.renderer from '^[^/]*/[^/]*/(.*)$') = {renderer_version} \ + AND (r.state = 'queued' OR (r.state = 'rendering' AND r.claimed_at < now() - make_interval(secs => {timeout}))) \ + AND r.attempts < {attempts} \ + ORDER BY (SELECT COUNT(*) FROM renders o WHERE o.project_id IS NOT DISTINCT FROM r.project_id \ + AND o.state = 'rendering'), r.id \ + LIMIT 1 FOR UPDATE SKIP LOCKED) \ + RETURNING *" + ) + .select_one_as() + .await?; + Ok(render.map(|r| (r, token))) +} + +/// The most pages a render may report. +pub const MAX_PAGES: usize = 2000; +/// The most text one page may carry, in bytes. +pub const MAX_PAGE_TEXT_BYTES: usize = 256 * 1024; +/// The most entries one uploads request, and one render, may name. +pub const MAX_UPLOADS: usize = 5000; + +fn is_hex_sha256(s: &str) -> bool { + crate::storage::blobs::valid_sha256(s) +} + +/// Check a completed render's pages before anything is stored: a renderer runs untrusted PDFs, so a hostile one may +/// have taken it over. At most [`MAX_PAGES`] pages, each within the decoder's size limits, with hex fingerprints and at +/// most [`MAX_PAGE_TEXT_BYTES`] of text, and every image one of the PNGs this render uploaded itself (its `uploads`), +/// never another tenant's file named by its hash. +/// +/// # Errors +/// A message saying what's wrong. +pub fn validate_pages(render: &Render, pages: &[RenderPage]) -> Result<(), String> { + if pages.len() > MAX_PAGES { + return Err(format!("{} pages: a render has at most {MAX_PAGES}", pages.len())); + } + let uploads = render.uploads.as_object(); + for (i, p) in pages.iter().enumerate() { + let n = i + 1; + if p.width == 0 + || p.height == 0 + || p.width > visualci_core::image_hash::MAX_WIDTH + || p.height > visualci_core::image_hash::MAX_HEIGHT + { + return Err(format!("page {n}: {}x{} isn't a page size", p.width, p.height)); + } + if !is_hex_sha256(&p.fingerprint) || !is_hex_sha256(&p.image_fingerprint) { + return Err(format!("page {n}: fingerprints are 64 lowercase hex characters")); + } + if p.text.len() > MAX_PAGE_TEXT_BYTES { + return Err(format!("page {n}: more than {MAX_PAGE_TEXT_BYTES} bytes of text")); + } + if !uploads.is_some_and(|u| u.contains_key(&p.image)) { + return Err(format!("page {n}: image {:?} wasn't uploaded for this render", p.image)); + } + } + Ok(()) +} + +/// Record the PNGs a render's uploads named (`"blob"` or `"proof"`, see the migration), refusing past [`MAX_UPLOADS`]. +/// +/// # Errors +/// `Ok(Err(message))` past the limit; `Err` on a database error. +pub async fn record_uploads( + render_id: i64, + entries: &serde_json::Map, +) -> laravel::Result> { + let added = serde_json::Value::Object(entries.clone()); + let max = i64::try_from(MAX_UPLOADS).unwrap_or(i64::MAX); + let updated = db::query!( + "UPDATE renders SET uploads = uploads || {added}, updated_at = now() \ + WHERE id = {render_id} \ + AND (SELECT COUNT(*) FROM jsonb_object_keys(uploads || {added})) <= {max}" + ) + .update() + .await?; + Ok(if updated == 1 { Ok(()) } else { Err(format!("a render uploads at most {MAX_UPLOADS} images")) }) +} + +/// The proof key a render uploads an already stored PNG to: its bytes show the renderer drew it. +#[must_use] +pub fn proof_key(render_id: i64, sha256: &str) -> String { + format!("proofs/{render_id}/{sha256}") +} + +/// Whether `token` is this render's current claim's. +#[must_use] +pub fn claimed_with(render: &Render, token: &str) -> bool { + render.state == "rendering" + && render.claim_token_hash.as_deref().is_some_and(|h| h == visualci_core::sha256_hex(token.as_bytes())) +} + +/// The engine and DPI from the renderer key (`pdfbox/140dpi/`). +#[must_use] +pub fn engine_and_dpi(render: &Render) -> (String, u32) { + let mut parts = render.renderer.split('/'); + let engine = parts.next().unwrap_or("pdfbox").to_string(); + let dpi = parts.next().and_then(|d| d.trim_end_matches("dpi").parse().ok()).unwrap_or(140); + (engine, dpi) +} diff --git a/app/src/domain/retention.rs b/app/src/domain/retention.rs new file mode 100644 index 00000000..d700956b --- /dev/null +++ b/app/src/domain/retention.rs @@ -0,0 +1,417 @@ +//! Retention: deleting the images (and PDFs, render rows and page texts) that nothing needs any more. Build, snapshot, +//! page and diff rows stay, so history, counts and diff regions remain; their images show as expired. See "Retention +//! and garbage collection" in docs/design-storage.md. +//! +//! Kept: +//! - everything a build from the retention window (90 days) uses, plus its base build's, +//! - builds still receiving or processing, +//! - the newest completed CI build of each project and build name on the default branch, +//! - every build a kept build reads groups from (`build_groups.source_build_id`): their rows are the kept build's +//! unchanged snapshots, +//! - every current baseline: the newest baseline row per snapshot name on the default branch, and on each branch with +//! a build in the window, +//! - the snapshots those builds compared against (`base_snapshot_id`), +//! - renders those snapshots use, and any render made in the window or not finished, +//! - variants' images, and any blob created in the window (an upload a build hasn't claimed yet), +//! - page texts any page row or remaining render names, and any text from the last 24 hours (a comparison in flight). +//! +//! A build that registers snapshots while a prune runs isn't in its keep sets, so the prune leaves alone what any +//! snapshot touched in the last day names, and the images and texts of a render reused in the last day. A blob is +//! marked before its object goes, and registering it again clears the mark ([`prune`] has the steps). +//! +//! Ignored-change fingerprints are rows, not blobs, and are never deleted. Neither are build, snapshot or page rows: a +//! build other builds read groups from keeps its rows (deleting them would cascade, drop baselines and leave every +//! reader's groups empty), and its images too while any kept build reads from it. [`empty_groups`] is the nightly check +//! that no group lost its rows. + +use laravel::db; + +use crate::storage::BlobStore; + +/// How long a build's images are kept once nothing else needs them. +pub const RETENTION_DAYS: i32 = 90; +/// How old an unreferenced text must be before it's deleted. +pub const TEXT_GRACE_HOURS: i32 = 24; + +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Report { + pub renders: u64, + pub blobs: u64, + pub bytes: i64, + pub texts: u64, + /// Blob objects the store didn't delete (they stay as orphans; the rows are gone). + pub store_errors: u64, +} + +impl std::fmt::Display for Report { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + #[allow(clippy::cast_precision_loss)] + let mb = self.bytes as f64 / 1_000_000.0; + write!( + f, + "{} renders, {} blobs ({mb:.1} MB), {} texts{}", + self.renders, + self.blobs, + self.texts, + if self.store_errors > 0 { format!(", {} store deletes failed", self.store_errors) } else { String::new() } + ) + } +} + +/// Build the keep sets, as temporary tables dropped at the end of the transaction. +async fn keep_sets(days: i32) -> laravel::Result<()> { + // Left over when the caller's transaction is still open (a run inside a test's, or a dry run before a real one). + db::query!("DROP TABLE IF EXISTS keep_builds, keep_snapshots, keep_renders, keep_blobs, keep_texts") + .statement() + .await?; + db::query!("CREATE TEMP TABLE keep_builds (id BIGINT PRIMARY KEY) ON COMMIT DROP").statement().await?; + db::query!( + "INSERT INTO keep_builds \ + SELECT id FROM builds \ + WHERE COALESCE(completed_at, created_at) > now() - make_interval(days => {days}) \ + OR state IN ('receiving', 'processing') \ + UNION \ + SELECT id FROM ( \ + SELECT DISTINCT ON (b.project_id, b.name) b.id FROM builds b JOIN projects p ON p.id = b.project_id \ + WHERE b.branch = p.default_branch AND b.mode = 'ci' AND b.state = 'completed' \ + ORDER BY b.project_id, b.name, b.id DESC \ + ) newest \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + db::query!( + "INSERT INTO keep_builds \ + SELECT b.base_build_id FROM builds b JOIN keep_builds k ON k.id = b.id WHERE b.base_build_id IS NOT NULL \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + // The builds that hold the kept builds' sourced groups (one hop: a source is always a holder), base builds' + // included. Before snapshots, renders and blobs are kept from the set. + db::query!( + "INSERT INTO keep_builds \ + SELECT DISTINCT g.source_build_id FROM build_groups g JOIN keep_builds k ON k.id = g.build_id \ + WHERE g.source_build_id IS NOT NULL \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + + db::query!("CREATE TEMP TABLE keep_snapshots (id BIGINT PRIMARY KEY) ON COMMIT DROP").statement().await?; + db::query!("INSERT INTO keep_snapshots SELECT s.id FROM snapshots s JOIN keep_builds k ON k.id = s.build_id") + .statement() + .await?; + db::query!( + "INSERT INTO keep_snapshots \ + SELECT snapshot_id FROM ( \ + SELECT DISTINCT ON (bl.project_id, bl.build_name, bl.name, bl.platform, bl.environment, bl.branch) \ + bl.snapshot_id \ + FROM baselines bl JOIN projects p ON p.id = bl.project_id \ + WHERE bl.branch = p.default_branch OR EXISTS ( \ + SELECT 1 FROM builds b WHERE b.project_id = bl.project_id AND b.branch = bl.branch \ + AND b.created_at > now() - make_interval(days => {days})) \ + ORDER BY bl.project_id, bl.build_name, bl.name, bl.platform, bl.environment, bl.branch, bl.id DESC \ + ) current WHERE snapshot_id IS NOT NULL \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + db::query!( + "INSERT INTO keep_snapshots \ + SELECT s.base_snapshot_id FROM snapshots s JOIN keep_snapshots k ON k.id = s.id \ + WHERE s.base_snapshot_id IS NOT NULL \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + + db::query!("CREATE TEMP TABLE keep_renders (id BIGINT PRIMARY KEY) ON COMMIT DROP").statement().await?; + db::query!( + "INSERT INTO keep_renders \ + SELECT s.render_id FROM snapshots s JOIN keep_snapshots k ON k.id = s.id WHERE s.render_id IS NOT NULL \ + UNION \ + SELECT id FROM renders WHERE created_at > now() - make_interval(days => {days}) OR state <> 'done' \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + + db::query!("CREATE TEMP TABLE keep_blobs (sha256 TEXT PRIMARY KEY) ON COMMIT DROP").statement().await?; + db::query!( + "INSERT INTO keep_blobs \ + SELECT sha256 FROM blobs WHERE created_at > now() - make_interval(days => {days}) \ + UNION SELECT image FROM variants \ + UNION SELECT s.source_blob FROM snapshots s JOIN keep_snapshots k ON k.id = s.id \ + WHERE s.source_blob IS NOT NULL \ + UNION SELECT p.head_image FROM snapshot_pages p JOIN keep_snapshots k ON k.id = p.snapshot_id \ + WHERE p.head_image IS NOT NULL \ + UNION SELECT p.base_image FROM snapshot_pages p JOIN keep_snapshots k ON k.id = p.snapshot_id \ + WHERE p.base_image IS NOT NULL \ + UNION SELECT d.overlay_blob FROM snapshot_pages p JOIN keep_snapshots k ON k.id = p.snapshot_id \ + JOIN diffs d ON d.id = p.diff_id WHERE d.overlay_blob IS NOT NULL \ + UNION SELECT r.source_blob FROM renders r JOIN keep_renders k ON k.id = r.id \ + UNION SELECT pg->>'image' FROM renders r JOIN keep_renders k ON k.id = r.id, jsonb_array_elements(r.pages) pg \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + Ok(()) +} + +/// The texts still named after the renders go: every page row's, and every kept render's pages'. A temporary table, so +/// each source is scanned once rather than once per text. +async fn keep_texts() -> laravel::Result<()> { + db::query!("CREATE TEMP TABLE keep_texts (sha256 TEXT PRIMARY KEY) ON COMMIT DROP").statement().await?; + db::query!( + "INSERT INTO keep_texts \ + SELECT head_text_sha FROM snapshot_pages WHERE head_text_sha IS NOT NULL \ + UNION SELECT base_text_sha FROM snapshot_pages WHERE base_text_sha IS NOT NULL \ + UNION SELECT pg->>'text_sha' FROM renders r JOIN keep_renders k ON k.id = r.id, \ + jsonb_array_elements(r.pages) pg WHERE pg->>'text_sha' IS NOT NULL \ + ON CONFLICT DO NOTHING" + ) + .statement() + .await?; + Ok(()) +} + +/// How many renders, texts or blobs one transaction deletes. +pub const BATCH: usize = 1000; + +/// What a prune may delete, found in one pass over the keep sets. +struct Candidates { + renders: Vec, + texts: Vec, + blobs: Vec<(String, i64)>, +} + +/// Find what nothing keeps, in one read-only transaction (the keep sets are its temporary tables). +async fn candidates(days: i32) -> laravel::Result { + let grace = TEXT_GRACE_HOURS; + db::transaction(async |_| { + keep_sets(days).await?; + keep_texts().await?; + let renders = db::query!( + "SELECT id FROM renders WHERE NOT EXISTS (SELECT 1 FROM keep_renders k WHERE k.id = renders.id) ORDER BY id" + ) + .select() + .await? + .iter() + .filter_map(|r| r.try_get::("id").ok()) + .collect(); + let texts = db::query!( + "SELECT sha256 FROM texts WHERE created_at < now() - make_interval(hours => {grace}) \ + AND NOT EXISTS (SELECT 1 FROM keep_texts k WHERE k.sha256 = texts.sha256) ORDER BY sha256" + ) + .select() + .await? + .iter() + .filter_map(|r| r.try_get::("sha256").ok()) + .collect(); + let blobs = db::query!( + "SELECT sha256, size FROM blobs WHERE NOT EXISTS (SELECT 1 FROM keep_blobs k WHERE k.sha256 = blobs.sha256) \ + ORDER BY sha256" + ) + .select() + .await? + .iter() + .filter_map(|r| Some((r.try_get::("sha256").ok()?, r.try_get::("size").ok()?))) + .collect(); + // Gone with the transaction anyway, unless the caller's is still open (a test's). + db::query!("DROP TABLE IF EXISTS keep_builds, keep_snapshots, keep_renders, keep_blobs, keep_texts") + .statement() + .await?; + Ok(Candidates { renders, texts, blobs }) + }) + .await +} + +/// Delete what nothing needs, a batch of [`BATCH`] at a time, each batch in its own transaction, so a large prune never +/// holds locks across the whole database. The candidates come from one pass over the keep sets; each batch checks +/// again what may have changed since (a build registering now isn't in the keep sets): +/// +/// - a render goes only once no snapshot names it, and its snapshots' links go only when they're over a day old; +/// - a text goes only while it's over a day old (storing it again renews that) and no render reused in the last day +/// names it; +/// - an overlay goes only when its diff wasn't reused in the last day; +/// - a blob is marked `deleting` (rows locked, skipping any a registration holds) unless something registered it in the +/// last day or anything names it, then its object is deleted and the row with it, under the row's lock, only while +/// it's still marked and still unnamed. Registering the hash clears the mark and has the file uploaded again +/// ([`super::blobs::register`]), so a build reusing the file keeps it. Marks left over (a skipped row, a store that +/// refused) are cleared at the end of the batch, and any from a run that stopped are cleared at the start: no mark +/// outlives its run. +/// +/// With `dry_run`, only count. +/// +/// # Errors +/// On a database error. A failed store delete is counted in the report, not returned: the blob stays, and the next +/// prune tries again. +pub async fn prune(store: Option<&BlobStore>, days: i32, dry_run: bool) -> laravel::Result { + let grace = TEXT_GRACE_HOURS; + // Marks a run that stopped part way left behind (prunes never overlap: the schedule runs one at a time). + if !dry_run { + db::query!("UPDATE blobs SET deleting = false WHERE deleting").update().await?; + } + let found = candidates(days).await?; + let mut report = Report::default(); + if dry_run { + report.renders = found.renders.len() as u64; + report.texts = found.texts.len() as u64; + report.blobs = found.blobs.len() as u64; + report.bytes = found.blobs.iter().map(|(_, size)| size).sum(); + return Ok(report); + } + + for chunk in found.renders.chunks(BATCH) { + let ids = chunk.to_vec(); + report.renders += db::transaction(async |_| { + db::query!( + "UPDATE snapshots SET render_id = NULL \ + WHERE render_id IN ({...ids}) AND updated_at < now() - make_interval(hours => {grace})" + ) + .update() + .await?; + db::query!( + "DELETE FROM renders WHERE id IN ({...ids}) \ + AND (used_at IS NULL OR used_at < now() - make_interval(hours => {grace})) \ + AND NOT EXISTS (SELECT 1 FROM snapshots s WHERE s.render_id = renders.id)" + ) + .delete() + .await + }) + .await?; + } + + for chunk in found.texts.chunks(BATCH) { + let shas = chunk.to_vec(); + report.texts += db::query!( + "DELETE FROM texts WHERE sha256 IN ({...shas}) AND created_at < now() - make_interval(hours => {grace}) \ + AND NOT EXISTS (SELECT 1 FROM renders r, jsonb_array_elements(r.pages) pg \ + WHERE r.used_at >= now() - make_interval(hours => {grace}) AND pg->>'text_sha' = texts.sha256)" + ) + .delete() + .await?; + } + + for chunk in found.blobs.chunks(BATCH) { + let shas: Vec = chunk.iter().map(|(s, _)| s.clone()).collect(); + let marked: Vec<(String, i64)> = db::transaction(async |_| { + db::query!( + "UPDATE snapshots SET source_blob = NULL \ + WHERE source_blob IN ({...shas}) AND updated_at < now() - make_interval(hours => {grace})" + ) + .update() + .await?; + db::query!( + "UPDATE diffs SET overlay_blob = NULL \ + WHERE overlay_blob IN ({...shas}) AND (used_at IS NULL OR used_at < now() - make_interval(hours => {grace}))" + ) + .update() + .await?; + let rows = db::query!( + "UPDATE blobs SET deleting = true, updated_at = now() WHERE sha256 IN ( \ + SELECT b.sha256 FROM blobs b WHERE b.sha256 IN ({...shas}) \ + AND b.updated_at < now() - make_interval(hours => {grace}) \ + AND NOT EXISTS (SELECT 1 FROM snapshots s WHERE s.source_blob = b.sha256) \ + AND NOT EXISTS (SELECT 1 FROM diffs d WHERE d.overlay_blob = b.sha256) \ + AND NOT EXISTS (SELECT 1 FROM renders r WHERE r.source_blob = b.sha256) \ + AND NOT EXISTS (SELECT 1 FROM renders r, jsonb_array_elements(r.pages) pg \ + WHERE r.used_at >= now() - make_interval(hours => {grace}) AND pg->>'image' = b.sha256) \ + FOR UPDATE SKIP LOCKED) \ + RETURNING sha256, size" + ) + .select() + .await?; + Ok(rows + .iter() + .filter_map(|r| Some((r.try_get::("sha256").ok()?, r.try_get::("size").ok()?))) + .collect()) + }) + .await?; + for (sha256, size) in &marked { + match delete_marked(store, sha256).await? { + Deleted::Yes => { + report.blobs += 1; + report.bytes += size; + } + Deleted::KeptForNow => {} + Deleted::StoreFailed => report.store_errors += 1, + } + } + // No mark outlives its run: what wasn't deleted (named again, locked by a registration, or the store refused) + // is a blob like any other again. Waits for a registration holding a row. + let left: Vec = marked.into_iter().map(|(s, _)| s).collect(); + for chunk in left.chunks(BATCH) { + let chunk = chunk.to_vec(); + db::query!("UPDATE blobs SET deleting = false WHERE sha256 IN ({...chunk}) AND deleting").update().await?; + } + } + Ok(report) +} + +enum Deleted { + Yes, + /// Registered again since it was marked, or a registration holds its row: it stays. + KeptForNow, + /// The store refused: it stays marked. + StoreFailed, +} + +/// Delete a marked blob's object and then its row, holding the row's lock throughout, and only while it's still +/// marked. A registration of the same hash waits for the lock and then inserts a fresh row (to be uploaded again), or, +/// when it came first, has cleared the mark and this leaves it alone. +async fn delete_marked(store: Option<&BlobStore>, sha256: &str) -> laravel::Result { + db::transaction(async |_| { + let locked: Option = + db::query!("SELECT sha256 FROM blobs WHERE sha256 = {sha256} AND deleting FOR UPDATE SKIP LOCKED") + .scalar() + .await?; + if locked.is_none() { + return Ok(Deleted::KeptForNow); + } + // Named since it was marked (a snapshot or diff committed after a registration that found it uploaded, or a page + // image of a render reused since): it stays. + let named: Option = db::query!( + "SELECT 1::BIGINT WHERE EXISTS (SELECT 1 FROM snapshots WHERE source_blob = {sha256}) \ + OR EXISTS (SELECT 1 FROM renders WHERE source_blob = {sha256}) \ + OR EXISTS (SELECT 1 FROM diffs WHERE overlay_blob = {sha256}) \ + OR EXISTS (SELECT 1 FROM renders r, jsonb_array_elements(r.pages) pg \ + WHERE r.used_at >= now() - interval '24 hours' AND pg->>'image' = {sha256})" + ) + .scalar() + .await?; + if named.is_some() { + return Ok(Deleted::KeptForNow); + } + if let Some(store) = store + && let Err(e) = store.delete(sha256).await + { + tracing::warn!(sha256, error = %e, "retention: store delete failed"); + return Ok(Deleted::StoreFailed); + } + db::query!("DELETE FROM blobs WHERE sha256 = {sha256} AND deleting").delete().await?; + Ok(Deleted::Yes) + }) + .await +} + +/// Every group a build reads from another build that has no rows there: `(build id, group key)`. Each should be none; +/// one means a build shows with snapshots missing (docs/design-storage.md, "no group resolves to zero rows"). +/// +/// # Errors +/// On a database error. +pub async fn empty_groups() -> laravel::Result> { + let rows = db::query!( + "SELECT g.build_id, g.key FROM build_groups g \ + WHERE g.source_build_id IS NOT NULL AND NOT EXISTS ( \ + SELECT 1 FROM snapshots s WHERE s.build_id = g.source_build_id AND s.group_key = g.key) \ + ORDER BY g.build_id, g.key" + ) + .select() + .await?; + Ok(rows + .iter() + .filter_map(|r| Some((r.try_get::("build_id").ok()?, r.try_get::("key").ok()?))) + .collect()) +} diff --git a/app/src/domain/reviews.rs b/app/src/domain/reviews.rs new file mode 100644 index 00000000..71391576 --- /dev/null +++ b/app/src/domain/reviews.rs @@ -0,0 +1,328 @@ +//! Reviews: approving or rejecting a build's changes, who did it, and what follows (baselines, superseded builds). + +use laravel::db::{self, Json}; +use laravel::model::{create, update}; + +use super::snapshots::is_change; +use crate::models::{Build, Review, Snapshot, User}; + +/// How a review was made besides its person, for "Approved by Claude Code for Ada": where it came from (`web`, `oauth`, +/// `personal_token` or `project_token`), the OAuth app, the agent that sent it and the token's name. A review in the web +/// app is `Via::default()`: a person, nothing else. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Via { + pub source: &'static str, + /// The OAuth app's name. + pub client: Option, + /// The agent: an `X-Agent` header, or the MCP client's name and version. + pub agent: Option, + /// The personal or project token's name. + pub token: Option, +} + +impl Default for Via { + fn default() -> Self { + Self { source: "web", client: None, agent: None, token: None } + } +} + +/// Who made a review, as people read it after "Approved by": the person in the web app ("Ada Lovelace"), the agent for +/// its person ("Claude Code for Ada Lovelace"), or a project token ("a project token (GitHub Actions)"). VisualCI is +/// mostly used by agents, so an agent's review never reads as the person's own. +#[must_use] +pub fn by( + source: &str, + client: Option<&str>, + agent: Option<&str>, + token: Option<&str>, + person: Option<&str>, +) -> String { + let person = person.unwrap_or("someone"); + let agent_name = client.or(agent).map(str::trim).filter(|a| !a.is_empty()); + match source { + "web" => person.to_string(), + "oauth" => format!("{} for {person}", agent_name.unwrap_or("an agent")), + // A token's name is what its person called it ("Claude Code on the laptop"): it says more than the MCP + // client's library name ("rmcp 3.12.0"), so it comes first. + "personal_token" => format!("{} for {person}", token.or(agent_name).unwrap_or("an agent")), + _ => match token { + Some(t) => format!("a project token ({t})"), + None => "a project token".to_string(), + }, + } +} + +/// One review as it's shown: what, by whom ([`by`]), the reviewer's note, how many snapshots and when. +#[derive(Clone, Debug, serde::Serialize)] +pub struct Shown { + pub action: String, + pub by: String, + pub note: Option, + pub snapshots: usize, + pub created_at: String, +} + +impl Shown { + /// "approved by Claude Code for Ada Lovelace", for a status line. + #[must_use] + pub fn line(&self) -> String { + let done = if self.action == "reject" { "rejected" } else { "approved" }; + format!("{done} by {}", self.by) + } +} + +/// A build's reviews, newest first, at most `limit`. +/// +/// # Errors +/// On a database error. +pub async fn shown(build_id: i64, limit: i64) -> laravel::Result> { + let reviews: Vec = + db::query!("SELECT * FROM reviews WHERE build_id = {build_id} ORDER BY id DESC LIMIT {limit}") + .select_as() + .await?; + let user_ids: Vec = reviews.iter().filter_map(|r| r.user_id).collect(); + let people: std::collections::HashMap = if user_ids.is_empty() { + std::collections::HashMap::new() + } else { + User::query().filter(User::id.is_in(user_ids)).get().await?.into_iter().map(|u| (u.id, u.name)).collect() + }; + Ok(reviews + .into_iter() + .map(|r| { + let person = r.user_id.and_then(|id| people.get(&id)).map(String::as_str); + Shown { + by: by(&r.source, r.client_name.as_deref(), r.agent.as_deref(), r.token_name.as_deref(), person), + action: r.action, + note: r.note, + snapshots: r.snapshot_ids.len(), + created_at: r.created_at.to_string(), + } + }) + .collect()) +} + +/// The note on a build approved with uncommitted changes. +pub const DIRTY_APPROVAL: &str = "This build ran with uncommitted changes, so approving it set baselines for its own \ +environment's screenshots only: approved documents and text weren't made baselines. Commit, run again and approve that \ +build."; + +/// Approve or reject the build, or some of its changed snapshots (by id). Approving every change approves the build. +/// Only the build's own rows are ever written: a snapshot it reads from an earlier build is unchanged, so it's never a +/// target. +/// +/// # Errors +/// `Ok(Err(message))` when the build can't be reviewed (not completed, a bad action, an open comment thread on an +/// approval); `Err` on a database error. +pub async fn review( + mut build: Build, + user_id: Option, + via: &Via, + action: &str, + snapshot_ids: Option>, + note: Option<&str>, +) -> laravel::Result> { + if build.state != "completed" { + return Ok(Err("only completed builds can be reviewed".into())); + } + let verdict = match action { + "approve" => "approved", + "reject" => "rejected", + _ => return Ok(Err("action must be approve or reject".into())), + }; + let snapshots = super::snapshots::of_build(build.id).await?; + let targets: Vec<&Snapshot> = snapshots + .iter() + .filter(|s| is_change(s) && !s.sourced) + .filter(|s| snapshot_ids.as_ref().is_none_or(|ids| ids.contains(&s.id))) + .collect(); + // An open comment thread blocks approving its snapshot: someone asked something, and it needs an answer first. + // Rejecting still works. + if verdict == "approved" { + let keys: Vec<(String, String)> = targets.iter().map(|s| (s.name.clone(), s.platform.clone())).collect(); + let open = super::comments::open_on(build.project_id, &build.branch, &keys).await?; + if let Some(t) = open.first() { + let line = super::comments::first_line(t.id).await?; + let more = + if open.len() > 1 { format!(" (and {} more open threads)", open.len() - 1) } else { String::new() }; + let on = match t.build_id { + Some(id) if id != build.id => { + format!(" on build #{}", Build::find(id).await?.map(|b| b.number).unwrap_or_default()) + } + _ => String::new(), + }; + return Ok(Err(format!( + "{} has an open comment thread{on} ({}): \"{line}\"{more}. Answer it and resolve it (resolve_comment) \ + before approving, or reject.", + t.snapshot_name, t.pid + ))); + } + } + let ids: Vec = targets.iter().map(|s| s.id).collect(); + if !ids.is_empty() { + db::query!("UPDATE snapshots SET review = {verdict}, updated_at = now() WHERE id IN ({...ids})") + .update() + .await?; + } + let note = note.map(str::trim).filter(|n| !n.is_empty()).map(|n| n.chars().take(2000).collect::()); + let review = create!(Review { + build_id: build.id, + user_id: user_id, + action: action, + snapshot_ids: Json(ids.clone()), + client_name: via.client.clone(), + agent: via.agent.clone(), + source: via.source, + token_name: via.token.clone(), + note: note, + }) + .await?; + let mut skipped = 0; + if verdict == "approved" { + // Each approved snapshot is a baseline for this branch (and environment, for screenshots) from now on. + let fresh: Vec<&Snapshot> = + targets.iter().filter(|s| s.review.as_deref() != Some("approved")).copied().collect(); + skipped = super::baselines::record(&build, &fresh, user_id, Some(review.id), "review").await?; + } else { + // Rejecting what was approved withdraws the baselines that approval made. + let was_approved: Vec<&Snapshot> = + targets.iter().filter(|s| s.review.as_deref() == Some("approved")).copied().collect(); + super::baselines::withdraw(&build, &was_approved).await?; + } + + let snapshots = super::snapshots::of_build(build.id).await?; + let changes: Vec<&Snapshot> = snapshots.iter().filter(|s| is_change(s)).collect(); + let review_state = if changes.iter().any(|s| s.review.as_deref() == Some("rejected")) { + "rejected" + } else if changes.iter().all(|s| s.review.as_deref() == Some("approved")) { + "approved" + } else { + "pending" + }; + let mut warnings: Vec = serde_json::from_value(build.warnings.clone()).unwrap_or_default(); + if skipped > 0 && !warnings.iter().any(|w| w == DIRTY_APPROVAL) { + warnings.push(DIRTY_APPROVAL.to_string()); + } + let warnings = serde_json::json!(warnings); + let review_state = review_state.to_string(); + update!(build { review_state, warnings }).await?; + Ok(Ok(build)) +} + +/// Once this build is approved or rejected, the older pending builds it covers are superseded: the same project, build +/// name and environment, finished, and on this build's history (their commit is among its ancestors). Returns their ids, +/// for their checks. +/// +/// # Errors +/// On a database error. +pub async fn supersede_older(build: &Build) -> laravel::Result> { + if !matches!(build.review_state.as_str(), "approved" | "rejected") || build.parent_commits.is_empty() { + return Ok(Vec::new()); + } + let (id, project_id, name, environment) = + (build.id, build.project_id, build.name.as_str(), build.environment.as_str()); + let parents: Vec = build.parent_commits.to_vec(); + let rows = db::query!( + "UPDATE builds SET review_state = 'superseded', superseded_by_build_id = {id}, updated_at = now() \ + WHERE project_id = {project_id} AND name = {name} AND environment = {environment} AND id < {id} \ + AND state = 'completed' AND review_state = 'pending' AND commit_sha IN ({...parents}) \ + RETURNING id" + ) + .select() + .await?; + Ok(rows.iter().filter_map(|r| r.try_get::("id").ok()).collect()) +} + +/// Accept a changed page as a variant (an alternative baseline image for that page: both versions are fine), or ignore +/// its change (this exact diff, by fingerprint, in every later build). The snapshot stops being changed when none of +/// its pages are. Returns the build, recounted. A snapshot the build reads from an earlier build is unchanged there, +/// and its rows are that build's: it's refused. +/// +/// # Errors +/// `Ok(Err(message))` when the page isn't a changed page or the action is unknown; `Err` on a database error. +pub async fn page_action( + snapshot: Snapshot, + build: Build, + project_id: i64, + position: i32, + action: &str, + user_id: Option, +) -> laravel::Result> { + use crate::models::{IgnoredChange, SnapshotPage, Variant}; + let refused = || Ok(Err("only a changed page can be accepted as a variant or ignored".to_string())); + if snapshot.sourced { + return refused(); + } + let Some(mut page) = SnapshotPage::query() + .filter(SnapshotPage::snapshot_id.eq(snapshot.id) & SnapshotPage::position.eq(position)) + .first() + .await? + else { + return refused(); + }; + if page.state != "changed" || page.op != "changed" { + return refused(); + } + let new_state = match action { + "variant" => { + let Some(image) = page.head_image.clone() else { return Ok(Err("the page has no image".into())) }; + create!(Variant { + project_id: project_id, + name: snapshot.name.as_str(), + platform: snapshot.platform.as_str(), + page_index: page.head_index.unwrap_or(0), + image: image, + created_by: user_id, + }) + .await?; + "variant" + } + "ignore" => { + let Some(diff_id) = page.diff_id else { return Ok(Err("the page has no diff to ignore".into())) }; + let Some(fingerprint) = crate::models::Diff::find_or_fail(diff_id).await?.fingerprint else { + return Ok(Err("the diff has no fingerprint".into())); + }; + create!(IgnoredChange { + project_id: project_id, + name: snapshot.name.as_str(), + platform: snapshot.platform.as_str(), + fingerprint: fingerprint, + created_by: user_id, + }) + .await?; + "ignored" + } + _ => return Ok(Err("action must be variant or ignore".into())), + }; + update!(page { state: new_state }).await?; + let id = snapshot.id; + let remaining = SnapshotPage::query() + .filter(SnapshotPage::snapshot_id.eq(id) & SnapshotPage::state.eq("changed")) + .count() + .await?; + if remaining == 0 && snapshot.state == "changed" { + let ignored = SnapshotPage::query() + .filter(SnapshotPage::snapshot_id.eq(id) & SnapshotPage::state.eq("ignored")) + .count() + .await?; + let state = if ignored > 0 { "ignored" } else { "unchanged" }; + db::query!("UPDATE snapshots SET state = {state}, updated_at = now() WHERE id = {id}").update().await?; + } + Ok(Ok(super::processing::recount(build).await?)) +} + +#[cfg(test)] +mod tests { + use super::by; + + #[test] + fn says_who_and_through_what() { + assert_eq!(by("web", None, None, None, Some("Ada")), "Ada"); + assert_eq!(by("oauth", Some("Claude Code"), Some("claude-code 2.1"), None, Some("Ada")), "Claude Code for Ada"); + let named = by("personal_token", None, Some("rmcp 3.12.0"), Some("Claude Code on the laptop"), Some("Ada")); + assert_eq!(named, "Claude Code on the laptop for Ada"); + assert_eq!(by("personal_token", None, Some("codex 1.0"), None, Some("Ada")), "codex 1.0 for Ada"); + assert_eq!(by("personal_token", None, None, None, Some("Ada")), "an agent for Ada"); + assert_eq!(by("project_token", None, None, Some("GitHub Actions"), None), "a project token (GitHub Actions)"); + assert_eq!(by("project_token", None, Some("claude-code 2.1"), Some("CI"), None), "a project token (CI)"); + } +} diff --git a/app/src/domain/snapshots.rs b/app/src/domain/snapshots.rs index 2dd57ac2..6265e571 100644 --- a/app/src/domain/snapshots.rs +++ b/app/src/domain/snapshots.rs @@ -53,10 +53,16 @@ impl SnapshotParams { /// # Errors /// A message for the client when a field is invalid. pub fn validate(&self) -> std::result::Result<(), String> { - let hex64 = |s: &str| s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit()); + let hex64 = crate::storage::blobs::valid_sha256; if self.name.trim().is_empty() || self.name.len() > 500 { return Err(format!("snapshot name must be 1 to 500 characters: {:?}", self.name)); } + if self.content_type.is_empty() || self.content_type.len() > 255 { + return Err(format!("{}: content_type must be 1 to 255 characters", self.name)); + } + if self.meta.to_string().len() > 16 * 1024 { + return Err(format!("{}: meta must be under 16 KB", self.name)); + } if self.platform.len() > 200 { return Err(format!("{}: platform is too long", self.name)); } @@ -79,7 +85,7 @@ impl SnapshotParams { )); } if !hex64(&self.sha256) || !hex64(&self.fingerprint) { - return Err(format!("{}: sha256 and fingerprint must be hex SHA-256 digests", self.name)); + return Err(format!("{}: sha256 and fingerprint must be lowercase hex SHA-256 digests", self.name)); } if let Some(e) = &self.engine && !["pdfbox", "mutool"].contains(&e.as_str()) @@ -121,7 +127,7 @@ pub struct Registration { /// # Errors /// On a database error. pub async fn usable_render(project_id: i64, fingerprint: &str, renderer: &str) -> laravel::Result> { - Render::query() + let found = Render::query() .filter( Render::project_id.eq(project_id) & Render::source_fingerprint.eq(fingerprint) @@ -129,7 +135,12 @@ pub async fn usable_render(project_id: i64, fingerprint: &str, renderer: &str) - & Render::state.ne("failed"), ) .first() - .await + .await?; + // Reused: retention leaves its images and texts alone while this build is new. + if let Some(r) = &found { + super::renders::mark_used(r.id).await?; + } + Ok(found) } /// Record a snapshot in a build (replacing one with the same name and platform), and say whether its file must be @@ -144,25 +155,6 @@ pub async fn register( renderer_version: &str, params: &SnapshotParams, ) -> laravel::Result> { - let earlier = Snapshot::query() - .filter( - Snapshot::build_id.eq(build.id) - & Snapshot::name.eq(params.name.as_str()) - & Snapshot::platform.eq(params.platform.as_str()), - ) - .first() - .await?; - if let Some(e) = earlier - && !e.carried_forward - && e.source_blob.as_deref() != Some(params.sha256.as_str()) - { - let platform = if params.platform.is_empty() { String::new() } else { format!(" ({})", params.platform) }; - return Ok(Err(format!( - "{}{platform} was {ALREADY_UPLOADED} with other content: snapshot names must be unique across a build's \ - jobs and shards", - params.name - ))); - } let renderer_key = settings.renderer_key(params.engine.as_deref(), renderer_version); let render = if params.kind == "document" { usable_render(build.project_id, ¶ms.fingerprint, &renderer_key).await? @@ -190,7 +182,9 @@ pub async fn register( params.threshold, params.ignore_anti_aliasing, ); - db::query!( + // One statement, so two shards racing with different files can't both win: the update applies only over a row + // carried forward or holding the same file (a retried job), and no row back means another file already has the name. + let saved: Option = db::query!( "INSERT INTO snapshots (pid, build_id, group_key, name, platform, kind, format, source_fingerprint, source_blob, \ render_id, engine, threshold, ignore_anti_aliasing, meta, ignore_rules, environment, state, \ matched_environment, baseline_id) \ @@ -201,22 +195,45 @@ pub async fn register( render_id = EXCLUDED.render_id, engine = EXCLUDED.engine, threshold = EXCLUDED.threshold, \ ignore_anti_aliasing = EXCLUDED.ignore_anti_aliasing, meta = EXCLUDED.meta, \ ignore_rules = EXCLUDED.ignore_rules, environment = EXCLUDED.environment, state = EXCLUDED.state, \ - matched_environment = NULL, baseline_id = NULL, group_key = EXCLUDED.group_key, updated_at = now()" + matched_environment = NULL, baseline_id = NULL, group_key = EXCLUDED.group_key, carried_forward = false, \ + base_snapshot_id = NULL, review = NULL, error = NULL, updated_at = now() \ + WHERE snapshots.carried_forward OR snapshots.source_blob = EXCLUDED.source_blob \ + RETURNING id" ) - .insert() + .scalar() .await?; - let snapshot = Snapshot::query() - .filter( - Snapshot::build_id.eq(build_id) - & Snapshot::name.eq(name.as_str()) - & Snapshot::platform.eq(platform.as_str()), - ) - .first() - .await? - .ok_or_else(|| laravel::Error::msg("the registered snapshot wasn't saved"))?; + let Some(id) = saved else { + let platform = if params.platform.is_empty() { String::new() } else { format!(" ({})", params.platform) }; + return Ok(Err(format!( + "{}{platform} was {ALREADY_UPLOADED} with other content: snapshot names must be unique across a build's \ + jobs and shards", + params.name + ))); + }; + let snapshot = Snapshot::find_or_fail(id).await?; Ok(Ok(Registration { snapshot, needs_upload })) } +/// Every snapshot of a build, its own and those it reads from earlier builds (`effective_snapshots`), by name and +/// platform. A row read from another build is `sourced`: unchanged, compared with itself, never reviewed, and its +/// id and pid are the holder's. +/// +/// # Errors +/// On a database error. +pub async fn of_build(build_id: i64) -> laravel::Result> { + db::query!("SELECT * FROM effective_snapshots WHERE build_id = {build_id} ORDER BY name, platform") + .select_as() + .await +} + +/// A build's snapshot by pid: one of its own, or one it reads from another build. +/// +/// # Errors +/// On a database error. +pub async fn in_build(build_id: i64, pid: laravel::str::Uuid) -> laravel::Result> { + db::query!("SELECT * FROM effective_snapshots WHERE build_id = {build_id} AND pid = {pid}").select_one_as().await +} + /// A text snapshot's format (`None` for documents and images). Plain text when none was stored. #[must_use] pub fn text_format(snapshot: &Snapshot) -> Option { @@ -240,3 +257,41 @@ pub fn is_change(snapshot: &Snapshot) -> bool { pub fn own_ignore_rules(snapshot: &Snapshot) -> IgnoreRules { serde_json::from_value(snapshot.ignore_rules.clone()).unwrap_or_default() } + +/// The build's snapshots that `review`'s `only` picks: its `added` or `changed` ones, or the `matching` changes (made +/// only of changes a merged pull request approved). The visualci.yml item is never picked. +/// +/// # Errors +/// `Ok(Err(message))` for another `only`, or when nothing is picked; `Err` on a database error. +pub async fn picked_by(build_id: i64, only: &str) -> laravel::Result, String>> { + if !matches!(only, "added" | "changed" | "matching") { + return Ok(Err(format!("only must be added, changed or matching, not {only:?}"))); + } + let ids: Vec = of_build(build_id) + .await? + .into_iter() + .filter(|s| !is_config_item(s) && !s.sourced) + .filter( + |s| if only == "matching" { s.state == "changed" && s.matches_build_id.is_some() } else { s.state == only }, + ) + .map(|s| s.id) + .collect(); + if ids.is_empty() { + return Ok(Err(if only == "matching" { + "this build has no changes that match another pull request's approved change".to_string() + } else { + format!("this build has no {only} snapshots") + })); + } + Ok(Ok(ids)) +} + +/// A build's snapshots with this name (one per platform), its own and those it reads from earlier builds. +/// +/// # Errors +/// On a database error. +pub async fn named_in_build(build_id: i64, name: &str) -> laravel::Result> { + db::query!("SELECT * FROM effective_snapshots WHERE build_id = {build_id} AND name = {name} ORDER BY platform") + .select_as() + .await +} diff --git a/app/src/domain/summary.rs b/app/src/domain/summary.rs new file mode 100644 index 00000000..18e1c2a0 --- /dev/null +++ b/app/src/domain/summary.rs @@ -0,0 +1,151 @@ +//! A build's summary line, computed from its comparison: what changed and by how much, with no model call. +//! "invoice_typical: page 1 changed (2 regions); api/invoice.json: 3 JSON fields changed; 1 added". VisualCI never +//! runs a model: the customer's own agent reads the evidence over MCP. + +use visualci_core::snapshot_text; + +use super::snapshots::{CONFIG_PLATFORM, is_change, text_format}; +use crate::models::{Build, Diff, Snapshot}; + +/// At most this many changed snapshots are described one by one; the rest are counted. +const DESCRIBED: usize = 5; + +/// The build's summary line, or `None` while it's still comparing or when nothing needs a look. +/// +/// # Errors +/// On a database error. +pub async fn summary_line(build: &Build) -> laravel::Result> { + if build.state != "completed" { + return Ok(None); + } + let all = super::snapshots::of_build(build.id).await?; + let mut parts = Vec::new(); + // Finished with nothing of its own on purpose (a CI run that skipped the suite's jobs): say so, and where its + // baseline came from, rather than leave "0 unchanged" to read like something broke + // What it sent: its own rows, or (once its unchanged groups were read from an earlier build and its own rows of + // them deleted) the snapshot checks it was charged for. + let charged: super::processing::Usage = serde_json::from_value(build.charged.clone()).unwrap_or_default(); + let sent = charged.snapshot_checks > 0 + || all.iter().any(|s| !s.carried_forward && s.state != "removed" && s.platform != CONFIG_PLATFORM); + if build.allow_empty && !sent && build.conclusion.as_deref() != Some("failed") { + parts.push(nothing_sent(build).await?); + } + if all.iter().any(|s| s.platform == CONFIG_PLATFORM && is_change(s)) { + parts.push("visualci.yml could hide changes".to_string()); + } + let changed: Vec<&Snapshot> = + all.iter().filter(|s| s.state == "changed" && s.platform != CONFIG_PLATFORM).collect(); + for s in changed.iter().take(DESCRIBED) { + parts.push(format!("{}: {}", display_name(s), describe(s).await?)); + } + if changed.len() > DESCRIBED { + parts.push(format!("{} more changed", changed.len() - DESCRIBED)); + } + let count = |state: &str| all.iter().filter(|s| s.state == state && s.platform != CONFIG_PLATFORM).count(); + for (state, n) in [("added", count("added")), ("removed", count("removed")), ("failed", count("failed"))] { + if n > 0 { + parts.push(format!("{n} {state}")); + } + } + Ok((!parts.is_empty()).then(|| parts.join("; "))) +} + +/// "No snapshots this run (inputs unchanged): baseline from #12" +async fn nothing_sent(build: &Build) -> laravel::Result { + let reason = build.empty_reason.as_deref().map(|r| format!(" ({r})")).unwrap_or_default(); + let base = match build.base_build_id { + Some(id) => Build::find(id).await?.map(|b| b.number), + None => None, + }; + let baseline = base.map_or_else(|| "no baseline yet".to_string(), |n| format!("baseline from #{n}")); + Ok(format!("No snapshots this run{reason}: {baseline}")) +} + +fn display_name(s: &Snapshot) -> String { + if s.platform.is_empty() { s.name.clone() } else { format!("{} ({})", s.name, s.platform) } +} + +/// What changed in one snapshot: its pages and regions, its JSON fields, or its lines. +async fn describe(s: &Snapshot) -> laravel::Result { + let pages = super::pages::of_many(None, &[s]).await?.remove(&s.id).unwrap_or_default(); + if s.kind == "text" { + let page = pages.first(); + let base = page.and_then(|p| p.base_text.as_deref()).unwrap_or(""); + let head = page.and_then(|p| p.head_text.as_deref()).unwrap_or(""); + if text_format(s) == Some(snapshot_text::Format::Json) + && let (Ok(b), Ok(h)) = (serde_json::from_str(base), serde_json::from_str(head)) + { + let (changes, more) = snapshot_text::json_changes(&b, &h, 1000); + let n = changes.len(); + return Ok(format!("{n}{} JSON {} changed", if more { "+" } else { "" }, plural(n, "field", "fields"))); + } + let lines = visualci_core::text::page_diff(base, head, 0); + let added = lines.iter().filter(|l| l.tag == "+").count(); + let removed = lines.iter().filter(|l| l.tag == "-").count(); + return Ok(format!("+{added} −{removed} lines")); + } + let mut changed_pages = Vec::new(); + let mut regions = 0usize; + let (mut inserted, mut deleted) = (0usize, 0usize); + for p in &pages { + match (p.op.as_str(), p.state.as_str()) { + ("inserted", _) => inserted += 1, + ("removed", _) => deleted += 1, + (_, "changed") => { + changed_pages.push(p.head_index.or(p.base_index).map_or(0, |i| i + 1)); + if let Some(id) = p.diff_id + && let Some(d) = Diff::find(id).await? + { + regions += super::diffs::result(&d).map_or(0, |r| r.regions.len()); + } + } + _ => {} + } + } + let mut out = Vec::new(); + if !changed_pages.is_empty() { + let which = if s.kind == "image" { + "changed".to_string() + } else { + let list = changed_pages.iter().map(ToString::to_string).collect::>(); + format!("{} {} changed", plural(changed_pages.len(), "page", "pages"), join_and(&list)) + }; + out.push(if regions > 0 { + format!("{which} ({regions} {})", plural(regions, "region", "regions")) + } else { + which + }); + } + if inserted > 0 { + out.push(format!("{inserted} {} added", plural(inserted, "page", "pages"))); + } + if deleted > 0 { + out.push(format!("{deleted} {} removed", plural(deleted, "page", "pages"))); + } + Ok(if out.is_empty() { "changed".to_string() } else { out.join(", ") }) +} + +const fn plural<'a>(n: usize, one: &'a str, many: &'a str) -> &'a str { + if n == 1 { one } else { many } +} + +/// "1", "1 and 3", "1, 3 and 5". +fn join_and(items: &[String]) -> String { + match items { + [] => String::new(), + [one] => one.clone(), + [rest @ .., last] => format!("{} and {last}", rest.join(", ")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lists_read_naturally() { + assert_eq!(join_and(&["1".into()]), "1"); + assert_eq!(join_and(&["1".into(), "3".into()]), "1 and 3"); + assert_eq!(join_and(&["1".into(), "3".into(), "5".into()]), "1, 3 and 5"); + } +} diff --git a/app/src/events.rs b/app/src/events.rs new file mode 100644 index 00000000..13a42c96 --- /dev/null +++ b/app/src/events.rs @@ -0,0 +1,35 @@ +//! Events the domain fires for the other side's listeners (sc-8900): forge checks and PR comments, live updates, +//! billing and emails listen to them. Each listener decides whether to queue its work. + +/// A build's state, review or snapshots changed: its forge check, PR comment, live updates and gallery follow. +#[derive(laravel::event::Event, Clone, Debug)] +pub struct BuildChanged { + pub build_id: i64, +} + +/// A build spent credits: billing may reload a pack (Team, automatic packs) and notices may go out. +#[derive(laravel::event::Event, Clone, Debug)] +pub struct CreditsSpent { + pub organization_id: i64, +} + +/// An organization has no credits left for a build about to be compared. Its listeners run before the build is +/// stopped: billing tries an automatic reload, and the domain checks the credits again afterwards. +#[derive(laravel::event::Event, Clone, Debug)] +pub struct CreditsRanOut { + pub organization_id: i64, +} + +/// A build was stopped because its organization is out of credits: its admins hear about it (once a month). +#[derive(laravel::event::Event, Clone, Debug)] +pub struct BuildStoppedForCredits { + pub build_id: i64, + pub organization_id: i64, +} + +/// An agent or a person sent feedback about VisualCI (`support_send`, the API's feedback endpoint): the team hears +/// about it by email, once. +#[derive(laravel::event::Event, Clone, Debug)] +pub struct FeedbackReceived { + pub feedback_id: i64, +} diff --git a/app/src/forge/events.rs b/app/src/forge/events.rs new file mode 100644 index 00000000..ae1f4d4d --- /dev/null +++ b/app/src/forge/events.rs @@ -0,0 +1,38 @@ +//! What a forge's webhook tells the domain (sc-8900, the seam with visualci features): one event per linked project, +//! dispatched by `forge::webhooks`, with the domain's listeners doing the work. Every event may arrive twice (a forge +//! retries a delivery), so listeners must be idempotent. + +use serde::{Deserialize, Serialize}; + +/// A pull request merged: its approvals become the base branch's at the merge commit (`baselines::record_merge`). +#[derive(laravel::event::Event, Clone, Debug, Serialize, Deserialize)] +pub struct PullRequestMerged { + pub project_id: i64, + pub head: String, + pub base: String, + pub merge_commit: String, +} + +/// A pull request closed without merging (`why` "pull_request"), or its branch deleted ("branch_deleted"): the +/// branch's builds waiting for review stop waiting. +#[derive(laravel::event::Event, Clone, Debug, Serialize, Deserialize)] +pub struct BranchClosed { + pub project_id: i64, + pub branch: String, + pub why: String, +} + +/// A closed pull request reopened: its branch's newest closed build waits for review again. +#[derive(laravel::event::Event, Clone, Debug, Serialize, Deserialize)] +pub struct BranchReopened { + pub project_id: i64, + pub branch: String, +} + +/// The repository was made private (`private`), or public or edited: the project's open source status is checked +/// again (when private, GitHub's word is enough). +#[derive(laravel::event::Event, Clone, Debug, Serialize, Deserialize)] +pub struct RepositoryVisibilityChanged { + pub project_id: i64, + pub private: bool, +} diff --git a/app/src/forge/github_app.rs b/app/src/forge/github_app.rs new file mode 100644 index 00000000..301edf03 --- /dev/null +++ b/app/src/forge/github_app.rs @@ -0,0 +1,252 @@ +//! The VisualCI GitHub App acting as itself (sc-8900, the forge side), ported from today's server: a JWT signed with +//! the App's private key, installation tokens, and a person's permission on a repository through an installation. +//! Its webhook is in `forge::webhooks`. + +use laravel::http::client; +use serde_json::Value; + +use super::Permission; + +const API: &str = "https://api.github.com"; + +/// The App (`GITHUB_APP_ID`, `GITHUB_APP_PRIVATE_KEY_BASE64`: its PEM key, base64-encoded to fit one line) and its +/// webhook's secret (`GITHUB_WEBHOOK_SECRET`). Without the secret, the webhook answers 404. +#[derive(Clone, laravel::config::Section)] +pub struct GithubApp { + #[env("GITHUB_APP_ID")] + pub app_id: Option, + #[env("GITHUB_APP_PRIVATE_KEY_BASE64")] + pub private_key_base64: Option, + #[env("GITHUB_WEBHOOK_SECRET")] + pub webhook_secret: Option, +} + +fn err(e: impl std::fmt::Display) -> laravel::Error { + laravel::Error::msg(format!("GitHub: {e}")) +} + +#[derive(serde::Serialize)] +struct AppClaims { + iat: i64, + exp: i64, + iss: String, +} + +/// A JWT that authenticates as the App itself, for nine minutes. +fn app_jwt(app: &GithubApp) -> laravel::Result { + use base64::Engine; + let (Some(id), Some(key)) = (app.app_id.as_deref(), app.private_key_base64.as_deref()) else { + return Err(err("the GitHub App isn't configured (GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY_BASE64)")); + }; + let now = laravel::now().timestamp().as_second(); + let claims = AppClaims { iat: now - 60, exp: now + 540, iss: id.to_string() }; + let pem = base64::engine::general_purpose::STANDARD + .decode(key.trim()) + .map_err(|e| err(format!("the App's private key isn't base64: {e}")))?; + let key = jsonwebtoken::EncodingKey::from_rsa_pem(&pem).map_err(err)?; + jsonwebtoken::encode(&jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256), &claims, &key).map_err(err) +} + +/// GET a GitHub API path as JSON; `None` on 404. +async fn get(token: &str, path: &str) -> laravel::Result> { + let response = client::get(format!("{API}{path}")) + .token(token) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .await?; + if response.status() == 404 { + return Ok(None); + } + if !response.successful() { + return Err(err(format!("GET {path}: HTTP {}", response.status()))); + } + Ok(Some(response.json()?)) +} + +/// A token for one of the App's installations. +/// +/// # Errors +/// When the App isn't configured, or GitHub refuses its credentials. +pub async fn installation_token(app: &GithubApp, installation: &str) -> laravel::Result { + let response = client::post(format!("{API}/app/installations/{installation}/access_tokens")) + .token(app_jwt(app)?) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .await?; + if !response.successful() { + return Err(err(format!("installation token: HTTP {}", response.status()))); + } + let body: Value = response.json()?; + body["token"].as_str().map(str::to_string).ok_or_else(|| err("an installation token response without a token")) +} + +/// Whether the App's installation `id` exists (a delivery can be stale, or redelivered after the installation went). +/// +/// # Errors +/// When the App isn't configured, or GitHub can't be reached or refuses. +pub async fn installation_exists(app: &GithubApp, id: &str) -> laravel::Result { + if !id.bytes().all(|b| b.is_ascii_digit()) { + return Ok(false); + } + Ok(get(&app_jwt(app)?, &format!("/app/installations/{id}")).await?.is_some()) +} + +/// Below this many API calls left in the hour, a recheck stops instead of using up what webhooks and checks need. +pub const RATE_LIMIT_RESERVE: i64 = 500; + +/// Every collaborator on a repository (`owner/name`) with their permission, keyed by GitHub user ID: direct +/// collaborators, team members and organization members with access, as `affiliation=all` lists them. Public +/// visibility gives nobody a place on it. `Err` when it can't be read completely (a partial list would drop people); +/// also when GitHub's rate limit is down to [`RATE_LIMIT_RESERVE`]. +/// +/// # Errors +/// Those. +pub async fn collaborators(token: &str, repo: &str) -> laravel::Result> { + let mut out = Vec::new(); + for page in 1..=50 { + let response = client::get(format!("{API}/repos/{repo}/collaborators")) + .token(token) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .query([("affiliation", "all".to_string()), ("per_page", "100".to_string()), ("page", page.to_string())]) + .await?; + if !response.successful() { + return Err(err(format!("GET /repos/{repo}/collaborators: HTTP {}", response.status()))); + } + let remaining = response.header("x-ratelimit-remaining").and_then(|v| v.parse::().ok()); + let list: Vec = response.json()?; + let done = list.len() < 100; + for c in &list { + let (Some(id), Some(permission)) = ( + c["id"].as_i64(), + c["role_name"].as_str().and_then(permission_from).or_else(|| permission_from_flags(&c["permissions"])), + ) else { + continue; + }; + out.push((id.to_string(), permission)); + } + if remaining.is_some_and(|r| r < RATE_LIMIT_RESERVE) { + return Err(err(format!("the rate limit is down to {} calls", remaining.unwrap_or(0)))); + } + if done { + return Ok(out); + } + } + Err(err(format!("{repo} has more than 5,000 collaborators"))) +} + +/// The highest permission in a `permissions` object (`{admin, maintain, push, triage, pull}`). +fn permission_from_flags(flags: &Value) -> Option { + [ + ("admin", Permission::Admin), + ("maintain", Permission::Maintain), + ("push", Permission::Write), + ("triage", Permission::Triage), + ("pull", Permission::Read), + ] + .into_iter() + .find(|(flag, _)| flags[*flag] == true) + .map(|(_, p)| p) +} + +/// A repository's `owner/name` now, by its permanent ID (`None` when the installation can't see it). +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn repository_path(token: &str, id: &str) -> laravel::Result> { + if !id.bytes().all(|b| b.is_ascii_digit()) { + return Ok(None); + } + Ok(get(token, &format!("/repositories/{id}")).await?.and_then(|v| v["full_name"].as_str().map(str::to_string))) +} + +/// A repository as GitHub describes it (`GET /repos/{path}`: visibility, licence, ID); `None` when the installation +/// can't see it. +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn repository(token: &str, repo: &str) -> laravel::Result> { + get(token, &format!("/repos/{repo}")).await +} + +/// Whether a branch exists in a repository (`None` when the installation can't see the repository). +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn branch_exists(token: &str, repo: &str, branch: &str) -> laravel::Result> { + if get(token, &format!("/repos/{repo}")).await?.is_none() { + return Ok(None); + } + let branch: String = branch + .bytes() + .map(|b| { + if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { + (b as char).to_string() + } else { + format!("%{b:02X}") + } + }) + .collect(); + Ok(Some(get(token, &format!("/repos/{repo}/branches/{branch}")).await?.is_some())) +} + +/// A repository's permanent ID, by its path (`None` when the installation can't see it). +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn repository_id(token: &str, repo: &str) -> laravel::Result> { + Ok(get(token, &format!("/repos/{repo}")).await?.and_then(|v| v["id"].as_i64().map(|i| i.to_string()))) +} + +/// Whether an error is GitHub's rate limit running low ([`collaborators`]): the work waits for the next run. +#[must_use] +pub fn rate_limited(e: &laravel::Error) -> bool { + e.to_string().contains("the rate limit is down") +} + +/// GitHub's role name for a collaborator (`admin`, `maintain`, `write`, `triage`, `read`). +fn permission_from(role: &str) -> Option { + match role { + "admin" => Some(Permission::Admin), + "maintain" => Some(Permission::Maintain), + "write" | "push" => Some(Permission::Write), + "triage" => Some(Permission::Triage), + "read" | "pull" => Some(Permission::Read), + _ => None, + } +} + +/// A person's permission on a repository (`owner/name`) through an installation (organization base permission, +/// teams and direct access all count), from their permanent GitHub ID. Only for collaborators: on a public repository +/// GitHub answers `read` for anyone, which would make every GitHub user a member of every organization linking one. +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn permission( + app: &GithubApp, + repo: &str, + installation: &str, + user_id: &str, +) -> laravel::Result> { + let token = installation_token(app, installation).await?; + // The account's login now, from its permanent ID: a stored login may have been renamed and taken. + let Ok(id) = user_id.parse::() else { return Ok(None) }; + let Some(user) = get(&token, &format!("/user/{id}")).await? else { return Ok(None) }; + let Some(login) = user["login"].as_str() else { return Ok(None) }; + // 204 when they're a collaborator (directly, through a team, or by the organization's base permission), 404 not + let collaborator = client::get(format!("{API}/repos/{repo}/collaborators/{login}")) + .token(&token) + .header("accept", "application/vnd.github+json") + .header("user-agent", "visualci") + .await?; + match collaborator.status().as_u16() { + 204 | 200 => {} + 404 => return Ok(None), + s => return Err(err(format!("GET /repos/{repo}/collaborators/{login}: HTTP {s}"))), + } + let Some(v) = get(&token, &format!("/repos/{repo}/collaborators/{login}/permission")).await? else { + return Ok(None); + }; + // `role_name` says maintain and triage, which `permission` folds into write and read + Ok(v["role_name"].as_str().and_then(permission_from).or_else(|| v["permission"].as_str().and_then(permission_from))) +} diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index e2937e7e..0d8113fd 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -2,8 +2,13 @@ //! side). These are the forge-neutral types: kinds, permissions, repository URLs, and what a sign-in learns. Each //! forge's API calls are in its own module. +pub mod events; pub mod github; +pub mod github_app; pub mod gitlab; +pub mod open_source; +pub mod sync; +pub mod webhooks; use crate::auth::Role; diff --git a/app/src/forge/open_source.rs b/app/src/forge/open_source.rs new file mode 100644 index 00000000..9ac5ae12 --- /dev/null +++ b/app/src/forge/open_source.rs @@ -0,0 +1,289 @@ +//! What GitHub says about a project's repository (sc-8619; sc-8900, the forge side, ported from today's server), and +//! what follows from it: +//! +//! - Only a project whose repository is public can be public here: a private repository's screenshots stay private. +//! When a public project's repository goes private (or VisualCI can't see it), the project is made private, with a +//! notice for its members and an email to its admins. +//! - A public repository with an OSI-approved licence is open source; while the project is also public here, its +//! builds draw from the organization's open source pool (the domain's credits read `projects.open_source`). One +//! that stops qualifying uses the plan's credits from then on, with a notice on the billing page and an email. +//! +//! GitHub's `repository` webhook applies a change at once ([`visibility_changed`]), and every linked project is +//! checked again once a day, in an hour of its own so the checks spread over the day ([`recheck_due`], from the +//! hourly sync). When GitHub doesn't answer, nothing changes. Self-managed GitLab instances follow with sc-8634. + +use laravel::db; +use laravel::event::{Event, listener}; +use serde_json::Value; + +use super::Repository; +use super::events::RepositoryVisibilityChanged; +use super::github_app::{self, GithubApp}; +use crate::notify::{self, Kind, To}; + +/// OSI-approved licences, by the SPDX ids GitHub reports (the common ones; GitHub names only licences it recognises). +pub const OSI_LICENCES: &[&str] = &[ + "0BSD", + "AFL-3.0", + "AGPL-3.0", + "AGPL-3.0-only", + "AGPL-3.0-or-later", + "Apache-2.0", + "Artistic-2.0", + "BSD-2-Clause", + "BSD-3-Clause", + "BSD-3-Clause-Clear", + "BSD-4-Clause", + "BSL-1.0", + "CECILL-2.1", + "ECL-2.0", + "EPL-1.0", + "EPL-2.0", + "EUPL-1.1", + "EUPL-1.2", + "GPL-2.0", + "GPL-2.0-only", + "GPL-2.0-or-later", + "GPL-3.0", + "GPL-3.0-only", + "GPL-3.0-or-later", + "ISC", + "LGPL-2.1", + "LGPL-2.1-only", + "LGPL-2.1-or-later", + "LGPL-3.0", + "LGPL-3.0-only", + "LGPL-3.0-or-later", + "LPPL-1.3c", + "MIT", + "MIT-0", + "MPL-2.0", + "MS-PL", + "MS-RL", + "MulanPSL-2.0", + "NCSA", + "OFL-1.1", + "OSL-3.0", + "PostgreSQL", + "UPL-1.0", + "Unlicense", + "Zlib", +]; + +/// What a check found: whether the repository is public, whether the project is open source, and why not (or its +/// licence when it is). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Status { + pub repository_public: bool, + pub open_source: bool, + pub note: String, +} + +impl Status { + fn no(repository_public: bool, note: impl Into) -> Self { + Self { repository_public, open_source: false, note: note.into() } + } + + /// What GitHub's answer about a repository (`GET /repos/{path}`) means for a project. + #[must_use] + pub fn of(repo: &Value) -> Self { + let public = repo["private"] == false && repo["visibility"].as_str().is_none_or(|s| s == "public"); + if !public { + return Self::no(false, "Its repository is private."); + } + match repo["license"]["spdx_id"].as_str() { + Some(l) if OSI_LICENCES.contains(&l) => { + Self { repository_public: true, open_source: true, note: format!("Public, {l}.") } + } + Some("NOASSERTION") => Self::no(true, "Its forge can't tell which licence its repository has."), + Some(l) => Self::no(true, format!("Its licence ({l}) isn't OSI-approved.")), + None => Self::no(true, "Its repository has no licence its forge recognises."), + } + } +} + +/// A project as a check needs it. +struct Project { + id: i64, + organization_id: i64, + slug: String, + public: bool, + counts: bool, + repository_url: Option, + repository_id: Option, + installation: Option, +} + +async fn project(id: i64) -> laravel::Result> { + let Some(r) = db::query!( + "SELECT id, organization_id, slug, public, repository_url, repository_id, forge_installation, \ + (open_source AND public AND NOT open_source_withdrawn) AS counts \ + FROM projects WHERE id = {id} AND (forge = 'github' OR forge IS NULL)" + ) + .select_one() + .await? + else { + return Ok(None); + }; + Ok(Some(Project { + id: r.try_get("id")?, + organization_id: r.try_get("organization_id")?, + slug: r.try_get("slug")?, + public: r.try_get("public")?, + counts: r.try_get("counts")?, + repository_url: r.try_get("repository_url")?, + repository_id: r.try_get("repository_id")?, + installation: r.try_get("forge_installation")?, + })) +} + +/// Ask GitHub about a project's repository. `None` when GitHub couldn't answer: the project keeps what it had. +async fn check(app: &GithubApp, p: &Project) -> Option { + let Some(url) = p.repository_url.as_deref() else { + return Some(Status::no(false, "It isn't linked to a repository.")); + }; + let Some(installation) = p.installation.as_deref() else { + return Some(Status::no(false, "VisualCI's app or bot doesn't have access to its repository.")); + }; + let answer = async { + let token = github_app::installation_token(app, installation).await?; + // By GitHub's ID when known, so a rename can't mislead it + let path = match p.repository_id.as_deref() { + Some(id) => github_app::repository_path(&token, id).await?, + None => Repository::parse(url).map(|r| r.path), + }; + match path { + Some(path) => github_app::repository(&token, &path).await, + None => Ok(None), + } + }; + match answer.await { + Ok(Some(repo)) => Some(Status::of(&repo)), + Ok(None) => Some(Status::no(false, "VisualCI can't see its repository.")), + Err(e) => { + tracing::warn!(project_id = p.id, error = %e, "couldn't check a project's repository"); + None + } + } +} + +/// Record a check, and tell the organization what changed: a public project whose repository isn't public any more +/// is made private (a notice on the project, an email to its admins); one that was drawing from the pool and stops +/// qualifying leaves a notice on the billing page and emails the billing contact. Returns whether it changed either. +/// +/// # Errors +/// On a database error. +async fn record(p: &Project, status: &Status) -> laravel::Result { + let made_private = p.public && !status.repository_public; + let lost_pool = p.counts && !status.open_source && !made_private; + let (id, public, open_source, note) = (p.id, status.repository_public, status.open_source, status.note.clone()); + let notice = made_private.then(|| match p.repository_url { + Some(_) => format!("The repository for {} is private now, so its builds are no longer public.", p.slug), + None => format!("{} isn't linked to a repository now, so its builds are no longer public.", p.slug), + }); + db::query!( + "UPDATE projects SET repository_public = {public}, repository_checked_at = now(), open_source = {open_source}, \ + open_source_note = {note}, public = public AND NOT {made_private}, notice = COALESCE({notice}, notice), \ + updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + let org = p.organization_id; + let now = laravel::now().timestamp().as_second(); + if made_private { + tracing::info!(project_id = id, note = status.note, "project made private: its repository isn't public"); + let kind = Kind::MadePrivate { project: p.slug.clone() }; + notify::queue(&kind, To::Admins(org), None, &format!("made_private:{id}:{now}")).await?; + } else if lost_pool { + let problem = format!( + "{} is no longer an open source project: {} Its builds use the plan's credits from now on.", + p.slug, status.note + ); + db::query!("UPDATE organizations SET billing_problem = {problem}, updated_at = now() WHERE id = {org}") + .update() + .await?; + tracing::info!(project_id = id, note = status.note, "project no longer open source"); + let kind = Kind::OpenSourceLost { project: p.slug.clone(), reason: status.note.clone() }; + notify::queue(&kind, To::Billing(org), None, &format!("open_source_lost:{id}:{now}")).await?; + } + Ok(made_private || lost_pool) +} + +/// Check one project and record the result. Returns whether it was made private or stopped being open source. +/// +/// # Errors +/// On a database error. +pub async fn refresh(app: &GithubApp, project_id: i64) -> laravel::Result { + let Some(p) = project(project_id).await? else { return Ok(false) }; + match check(app, &p).await { + Some(status) => record(&p, &status).await, + None => Ok(false), + } +} + +/// GitHub's `repository` webhook: made private (GitHub's word is enough), or made public or edited (asked again). +#[listener] +pub async fn visibility_changed( + event: Event, + app: laravel::config::Section, +) -> laravel::Result<()> { + if event.private { + if let Some(p) = project(event.project_id).await? { + record(&p, &Status::no(false, "Its repository is private.")).await?; + } + } else { + refresh(&app, event.project_id).await?; + } + Ok(()) +} + +/// Projects checked once a day: the hour (UTC) a project is due in, from its id, so the checks spread over the day. +const HOURS: i64 = 24; + +/// The hourly sync's part: check the projects due now (linked to a repository, or still marked open source or +/// public, in this hour's share and not checked in the last hour, or not checked for over a day). Returns how many +/// were made private or stopped being open source. +/// +/// # Errors +/// On a database error. +pub async fn recheck_due(app: &GithubApp) -> laravel::Result { + let hour = laravel::now().timestamp().as_second().div_euclid(3600).rem_euclid(HOURS); + let (day, share) = (HOURS + 1, HOURS); + let due: Vec = db::query!( + "SELECT id FROM projects WHERE (forge = 'github' OR forge IS NULL) \ + AND (repository_url IS NOT NULL OR open_source OR repository_public) \ + AND (repository_checked_at IS NULL \ + OR repository_checked_at < now() - make_interval(hours => {day}::int) \ + OR (id % {share} = {hour} AND repository_checked_at < now() - interval '1 hour'))" + ) + .select() + .await? + .iter() + .map(|r| r.try_get("id")) + .collect::>()?; + let mut changed = 0; + for id in due { + changed += usize::from(refresh(app, id).await?); + } + Ok(changed) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn a_public_repository_with_an_osi_licence_is_open_source() { + let s = Status::of(&json!({ "private": false, "visibility": "public", "license": { "spdx_id": "MIT" } })); + assert!(s.repository_public && s.open_source); + let s = Status::of(&json!({ "private": false, "license": { "spdx_id": "BUSL-1.1" } })); + assert!(s.repository_public && !s.open_source && s.note.contains("BUSL-1.1")); + let s = Status::of(&json!({ "private": false, "license": null })); + assert!(!s.open_source); + let s = Status::of(&json!({ "private": true, "license": { "spdx_id": "MIT" } })); + assert!(!s.repository_public && !s.open_source); + let s = Status::of(&json!({ "private": false, "visibility": "internal" })); + assert!(!s.repository_public); + } +} diff --git a/app/src/forge/sync.rs b/app/src/forge/sync.rs new file mode 100644 index 00000000..cc211a16 --- /dev/null +++ b/app/src/forge/sync.rs @@ -0,0 +1,236 @@ +//! The hourly forge sync (sc-8900, the forge side), ported from today's `forge:sync` for GitHub: +//! +//! - links made before VisualCI stored GitHub's repository ID get it; +//! - every linked repository's collaborators are listed once ([`webhooks::reach`]) and everyone with a GitHub identity +//! is rechecked from that, so access lost without a webhook goes within the hour; +//! - a project whose linker no longer maintains its repository (or whose repository the App can't see) is unlinked, so +//! someone who lost access doesn't keep posting checks and comments through the App. +//! +//! Nothing changes unless GitHub answered for every repository. When its rate limit runs low the run stops and the +//! next one picks up; that isn't a failure. `VISUALCI_FORGE_SYNC_HEARTBEAT` fails when GitHub or the database can't +//! answer, and when the App isn't configured. Each linked repository's visibility and licence are checked once a day per project +//! (`open_source::recheck_due`). Branches deleted without a pull request (GitHub doesn't send that event: +//! the App has no Contents permission) are found by asking about each branch with builds waiting for review, once a +//! day, and closed through `BranchClosed` ([`close_deleted_branches`], sc-8797). Self-managed GitLab follows (sc-8634). + +use laravel::db; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; + +use super::Permission; +use super::github_app::{self, GithubApp}; +use super::webhooks::{self, Reach}; + +/// What a run did. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Synced { + pub people: usize, + pub changed: usize, + pub unlinked: usize, + /// Projects made private, or no longer open source, by the daily recheck. + pub open_source: usize, + /// Branches found deleted, whose builds waiting for review were closed. + pub branches_closed: usize, + /// GitHub's rate limit ran low: nothing changed, the next run tries again. + pub deferred: bool, +} + +/// Run the sync for GitHub. +/// +/// # Errors +/// When GitHub can't answer for some repository (other than a low rate limit), or on a database error. +pub async fn sync_github(app: &GithubApp) -> laravel::Result { + let unseen = match backfill_ids(app).await { + Ok(unseen) => unseen, + Err(e) if github_app::rate_limited(&e) => return Ok(Synced { deferred: true, ..Synced::default() }), + Err(e) => return Err(e), + }; + let reach = match webhooks::reach(app).await { + Ok(reach) => reach, + Err(e) if github_app::rate_limited(&e) => return Ok(Synced { deferred: true, ..Synced::default() }), + Err(e) => return Err(e), + }; + let people: Vec = db::query!("SELECT DISTINCT user_id FROM identities WHERE forge = 'github' AND site = ''") + .select() + .await? + .iter() + .map(|r| r.try_get("user_id")) + .collect::>()?; + let changed = webhooks::apply_reach(&reach, &people).await?; + let unlinked = recheck_links(&reach, &unseen).await?; + // Each linked repository's visibility and licence, once a day per project, in an hour of its own + let open_source = match super::open_source::recheck_due(app).await { + Ok(n) => n, + Err(e) if github_app::rate_limited(&e) => 0, + Err(e) => return Err(e), + }; + let branches_closed = match close_deleted_branches(app, 500).await { + Ok(n) => n, + Err(e) if github_app::rate_limited(&e) => 0, + Err(e) => return Err(e), + }; + Ok(Synced { people: people.len(), changed, unlinked, open_source, branches_closed, deferred: false }) +} + +/// Give links without GitHub's repository ID their ID. Returns the projects whose repository the App can't see. +async fn backfill_ids(app: &GithubApp) -> laravel::Result> { + let rows = db::query!( + "SELECT id, repository_url, forge_installation FROM projects \ + WHERE forge = 'github' AND repository_id IS NULL AND repository_url IS NOT NULL \ + AND forge_installation IS NOT NULL" + ) + .select() + .await?; + let mut unseen = Vec::new(); + for r in rows { + let (id, url, installation): (i64, String, String) = + (r.try_get("id")?, r.try_get("repository_url")?, r.try_get("forge_installation")?); + let Some(repository) = super::Repository::parse(&url) else { continue }; + let token = github_app::installation_token(app, &installation).await?; + match github_app::repository_id(&token, &repository.path).await? { + Some(repository_id) => { + db::query!("UPDATE projects SET repository_id = {repository_id}, updated_at = now() WHERE id = {id}") + .update() + .await?; + } + None => unseen.push(id), + } + } + Ok(unseen) +} + +/// Unlink projects whose linker no longer has Maintain or Admin on the repository, or whose repository the App can't +/// see. Returns how many. +async fn recheck_links(reach: &Reach, unseen: &[i64]) -> laravel::Result { + let rows = db::query!( + "SELECT p.id, p.repository_id, i.forge_user_id FROM projects p \ + LEFT JOIN identities i ON i.user_id = p.linked_by AND i.forge = 'github' AND i.site = '' \ + WHERE p.forge = 'github' AND p.forge_installation IS NOT NULL AND p.linked_by IS NOT NULL" + ) + .select() + .await?; + let mut lost: Vec = unseen.to_vec(); + for r in rows { + let (id, repository_id, linker): (i64, Option, Option) = + (r.try_get("id")?, r.try_get("repository_id")?, r.try_get("forge_user_id")?); + let Some(repository_id) = repository_id else { continue }; + let permission = linker + .as_ref() + .and_then(|linker| reach.repositories.get(&repository_id).and_then(|people| people.get(linker))); + if !permission.is_some_and(|p| *p >= Permission::Maintain) { + lost.push(id); + } + } + lost.sort_unstable(); + lost.dedup(); + for &id in &lost { + tracing::info!(project_id = id, "unlinked: its linker lost access, or the App can't see the repository"); + db::query!( + "UPDATE projects SET forge_installation = NULL, forge_token_enc = NULL, forge_webhook_at = NULL, \ + linked_by = NULL, updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + } + Ok(lost.len()) +} + +/// Ask GitHub about up to `limit` branches with CI builds waiting for review (not a fork's, not asked in the last +/// day), and close the ones that are gone through `BranchClosed { why: "branch_deleted" }`, which the domain handles. +/// Returns how many were gone. +/// +/// # Errors +/// When GitHub's rate limit is low, or on a database error; one branch GitHub can't answer for is skipped. +pub async fn close_deleted_branches(app: &GithubApp, limit: i64) -> laravel::Result { + let rows = db::query!( + "SELECT DISTINCT b.project_id, b.branch, p.repository_id, p.repository_url, p.forge_installation \ + FROM builds b JOIN projects p ON p.id = b.project_id \ + LEFT JOIN branch_checks c ON c.project_id = b.project_id AND c.branch = b.branch \ + WHERE b.review_state = 'pending' AND b.mode = 'ci' AND b.branch <> '' AND position(':' in b.branch) = 0 \ + AND p.forge = 'github' AND p.forge_installation IS NOT NULL \ + AND (c.checked_at IS NULL OR c.checked_at < now() - interval '1 day') \ + ORDER BY b.project_id, b.branch LIMIT {limit}" + ) + .select() + .await?; + let mut closed = 0; + let mut tokens: std::collections::HashMap = std::collections::HashMap::new(); + for r in rows { + let (project_id, branch, installation): (i64, String, String) = + (r.try_get("project_id")?, r.try_get("branch")?, r.try_get("forge_installation")?); + let (repository_id, url): (Option, Option) = + (r.try_get("repository_id")?, r.try_get("repository_url")?); + let token = match tokens.get(&installation) { + Some(t) => t.clone(), + None => { + let t = github_app::installation_token(app, &installation).await?; + tokens.insert(installation.clone(), t.clone()); + t + } + }; + let path = match repository_id.as_deref() { + Some(id) => github_app::repository_path(&token, id).await?, + None => url.as_deref().and_then(super::Repository::parse).map(|r| r.path), + }; + let Some(path) = path else { continue }; + match github_app::branch_exists(&token, &path, &branch).await { + Ok(Some(false)) => { + super::events::BranchClosed { project_id, branch: branch.clone(), why: "branch_deleted".into() } + .dispatch() + .await?; + closed += 1; + } + Ok(_) => {} + Err(e) if github_app::rate_limited(&e) => return Err(e), + Err(e) => { + tracing::warn!(error = %e, repo = path, branch, "asking whether a branch exists"); + continue; + } + } + db::query!( + "INSERT INTO branch_checks (project_id, branch, checked_at) VALUES ({project_id}, {branch}, now()) \ + ON CONFLICT (project_id, branch) DO UPDATE SET checked_at = now()" + ) + .statement() + .await?; + } + Ok(closed) +} + +/// The hourly run. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct SyncForges; + +#[job] +impl SyncForges { + async fn handle(self, app: laravel::config::Section) -> laravel::Result<()> { + if app.app_id.as_deref().is_none_or(str::is_empty) { + let health = Err("the GitHub App isn't configured (GITHUB_APP_ID), so nobody's access is rechecked".into()); + crate::heartbeat::push("VISUALCI_FORGE_SYNC_HEARTBEAT", health).await; + return Ok(()); + } + let result = sync_github(&app).await; + let health = match &result { + Err(e) => Err(e.to_string()), + Ok(s) => { + tracing::info!( + people = s.people, + changed = s.changed, + unlinked = s.unlinked, + open_source = s.open_source, + branches_closed = s.branches_closed, + deferred = s.deferred, + "forge sync" + ); + Ok(()) + } + }; + crate::heartbeat::push("VISUALCI_FORGE_SYNC_HEARTBEAT", health).await; + result.map(|_| ()) + } +} + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(SyncForges).hourly().without_overlapping(); +} diff --git a/app/src/forge/webhooks.rs b/app/src/forge/webhooks.rs new file mode 100644 index 00000000..930e2229 --- /dev/null +++ b/app/src/forge/webhooks.rs @@ -0,0 +1,492 @@ +//! The GitHub App's webhook, `POST /webhooks/github` on the API host (sc-8900, the forge side), ported from today's +//! server. A delivery is checked against `X-Hub-Signature-256` and read into a [`ForgeEvent`]: +//! +//! - merges, closed or reopened pull requests, deleted branches and repository visibility changes are dispatched to +//! the domain as `forge::events`, once per linked project; +//! - installation changes attach or detach the App's installation on linked projects, so checks stop without errors, +//! and recheck the access of the people whose memberships those organizations' repositories decide; +//! - membership changes (collaborators, teams, organization members) recheck the people they name ([`RecheckAccess`]). +//! +//! Every event is safe to receive twice. GitLab's project hooks come with the self-managed instances' port. + +use std::collections::{HashMap, HashSet}; + +use hmac::{Hmac, Mac}; +use laravel::db; +use laravel::prelude::*; +use laravel::queue::{Queueable, job}; +use serde_json::{Value, json}; +use sha2::Sha256; + +use super::events::{BranchClosed, BranchReopened, PullRequestMerged, RepositoryVisibilityChanged}; +use super::github_app::{self, GithubApp}; +use super::{ForgeKind, Permission, Repository}; + +/// One delivery, as VisualCI acts on it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ForgeEvent { + Merged { + repository: Repository, + head: String, + base: String, + merge_commit: String, + }, + Closed { + repository: Repository, + branch: String, + why: &'static str, + }, + Reopened { + repository: Repository, + branch: String, + }, + /// The App was installed on these repositories (`installation` set) or removed from them (`None`). + Installation { + installation: Option, + previous: Option, + repositories: Vec, + }, + /// These people's access may have changed (GitHub user IDs). + Access { + people: Vec, + }, + /// Anyone's access through this installation may have changed (a team's repositories changed). + AccessAll { + installation: String, + }, + RepositoryChanged { + repository: Repository, + private: bool, + }, + /// Renamed or transferred: the same repository (by ID) at a new URL. + Moved { + repository: Repository, + }, + Ignored, +} + +/// `X-Hub-Signature-256`: `sha256=` and the body's HMAC-SHA256 under the webhook's secret, compared in constant time. +#[must_use] +pub fn signed(secret: &str, header: &str, body: &[u8]) -> bool { + let Some(hex_sig) = header.strip_prefix("sha256=") else { return false }; + let Ok(sig) = hex::decode(hex_sig) else { return false }; + let Ok(mut mac) = Hmac::::new_from_slice(secret.as_bytes()) else { return false }; + mac.update(body); + mac.verify_slice(&sig).is_ok() +} + +fn repositories(list: &Value) -> Vec { + list.as_array() + .map(|l| { + l.iter() + .filter_map(|r| { + let id = r["id"].as_i64().map(|i| i.to_string()); + r["full_name"].as_str().and_then(Repository::parse).map(|repo| repo.with_id(id)) + }) + .collect() + }) + .unwrap_or_default() +} + +/// The repository an event names, with GitHub's ID for it (which survives a rename). +fn repository(event: &Value) -> Option { + event["repository"]["full_name"] + .as_str() + .and_then(Repository::parse) + .map(|r| r.with_id(event["repository"]["id"].as_i64().map(|i| i.to_string()))) +} + +/// A pull request's branch: a fork's goes by its head label (`octocat:main`), as the CLI names it, so a fork's `main` +/// isn't taken for the base repository's. +fn pr_branch(event: &Value) -> Option<&str> { + let pr = &event["pull_request"]; + let head_repo = pr["head"]["repo"]["full_name"].as_str(); + let from_fork = head_repo.is_some() && head_repo != event["repository"]["full_name"].as_str(); + if from_fork { pr["head"]["label"].as_str() } else { pr["head"]["ref"].as_str() } +} + +fn deleted_branch(event: &Value, branch: Option<&str>) -> ForgeEvent { + match (repository(event), branch) { + (Some(repository), Some(branch)) => { + ForgeEvent::Closed { repository, branch: branch.to_string(), why: "branch_deleted" } + } + _ => ForgeEvent::Ignored, + } +} + +/// One delivery (`X-GitHub-Event` and its body) as a [`ForgeEvent`]. +/// +/// # Errors +/// A message for a merged pull request without its branches or merge commit. +pub fn read_event(kind: &str, event: &Value) -> Result { + let action = event["action"].as_str().unwrap_or_default(); + let installation = event["installation"]["id"].as_i64().map(|i| i.to_string()); + let person = |v: &Value| v["id"].as_i64().map(|i| vec![i.to_string()]).unwrap_or_default(); + Ok(match (kind, action) { + ("pull_request", "closed") if event["pull_request"]["merged"] == true => { + let pr = &event["pull_request"]; + let (Some(repository), Some(head), Some(base), Some(merge)) = + (repository(event), pr_branch(event), pr["base"]["ref"].as_str(), pr["merge_commit_sha"].as_str()) + else { + return Err("a merged pull request without its branches or merge commit".into()); + }; + ForgeEvent::Merged { + repository, + head: head.to_string(), + base: base.to_string(), + merge_commit: merge.to_string(), + } + } + ("pull_request", "closed" | "reopened") => match (repository(event), pr_branch(event)) { + (Some(repository), Some(branch)) if action == "closed" => { + ForgeEvent::Closed { repository, branch: branch.to_string(), why: "pull_request" } + } + (Some(repository), Some(branch)) => ForgeEvent::Reopened { repository, branch: branch.to_string() }, + _ => ForgeEvent::Ignored, + }, + // A branch deleted: GitHub sends `delete` (ref_type branch) and a `push` with `deleted: true` + ("delete", _) if event["ref_type"] == "branch" => deleted_branch(event, event["ref"].as_str()), + ("push", _) if event["deleted"] == true => { + deleted_branch(event, event["ref"].as_str().and_then(|r| r.strip_prefix("refs/heads/"))) + } + ("installation", "created" | "unsuspend") => ForgeEvent::Installation { + installation, + previous: None, + repositories: repositories(&event["repositories"]), + }, + ("installation", "deleted" | "suspend") => ForgeEvent::Installation { + installation: None, + previous: installation, + repositories: repositories(&event["repositories"]), + }, + ("installation_repositories", "added") => ForgeEvent::Installation { + installation, + previous: None, + repositories: repositories(&event["repositories_added"]), + }, + ("installation_repositories", "removed") => ForgeEvent::Installation { + installation: None, + previous: installation, + repositories: repositories(&event["repositories_removed"]), + }, + // Made public or private, or edited: projects linked to it follow at once + ("repository", "publicized" | "privatized" | "edited") => match repository(event) { + Some(repository) => { + let private = event["repository"]["private"].as_bool().unwrap_or(action == "privatized"); + ForgeEvent::RepositoryChanged { repository, private } + } + None => ForgeEvent::Ignored, + }, + // The same repository at a new URL; links follow by its ID + ("repository", "renamed" | "transferred") => match repository(event) { + Some(repository) if repository.id.is_some() => ForgeEvent::Moved { repository }, + _ => ForgeEvent::Ignored, + }, + // A collaborator added, removed or changed; someone joined or left a team + ("member" | "membership", _) => ForgeEvent::Access { people: person(&event["member"]) }, + // Someone joined or left the organization + ("organization", "member_added" | "member_removed") => { + ForgeEvent::Access { people: person(&event["membership"]["user"]) } + } + // A team's repositories or permission changed, or it was deleted + ("team", "added_to_repository" | "removed_from_repository" | "edited" | "deleted") => match installation { + Some(installation) => ForgeEvent::AccessAll { installation }, + None => ForgeEvent::Ignored, + }, + _ => ForgeEvent::Ignored, + }) +} + +/// A project linked to a repository. +struct Linked { + id: i64, + organization_id: i64, + installation: Option, +} + +/// The GitHub projects linked to a repository: by GitHub's permanent ID when the delivery has it (a renamed repository +/// is still the same one, and a new repository that took the old name isn't), and links whose ID isn't known yet by +/// URL, which get the ID now. +async fn linked(repository: &Repository) -> laravel::Result> { + let (id, url) = (repository.id.clone(), repository.url.to_lowercase()); + if id.is_some() { + db::query!( + "UPDATE projects SET repository_id = {id}, updated_at = now() \ + WHERE forge = 'github' AND repository_id IS NULL AND lower(repository_url) = {url}" + ) + .update() + .await?; + } + let rows = db::query!( + "SELECT id, organization_id, forge_installation FROM projects WHERE forge = 'github' AND ( \ + ({id}::text IS NOT NULL AND repository_id = {id}) \ + OR (({id}::text IS NULL OR repository_id IS NULL) AND lower(repository_url) = {url}))" + ) + .select() + .await?; + rows.iter() + .map(|r| { + Ok(Linked { + id: r.try_get("id")?, + organization_id: r.try_get("organization_id")?, + installation: r.try_get("forge_installation")?, + }) + }) + .collect() +} + +/// `POST /webhooks/github`. +pub async fn github( + app: laravel::config::Section, + headers: axum::http::HeaderMap, + body: axum::body::Bytes, +) -> laravel::Result> { + let Some(secret) = app.webhook_secret.as_deref().filter(|s| !s.is_empty()) else { + return Err(laravel::abort(404)); + }; + let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).unwrap_or_default().to_string(); + if !signed(secret, &header("x-hub-signature-256"), &body) { + return Err(laravel::abort_with(401, "bad signature")); + } + let event: Value = serde_json::from_slice(&body).map_err(|e| laravel::abort_with(400, e.to_string()))?; + let (kind, delivery) = (header("x-github-event"), header("x-github-delivery")); + let read = read_event(&kind, &event).map_err(|e| laravel::abort_with(400, e))?; + let outcome = handle(&app, read).await?; + tracing::info!(forge = "github", kind, delivery, outcome = %outcome, "webhook"); + Ok(Json(outcome)) +} + +/// Act on one event; returns what happened, for the delivery's log on GitHub. +/// +/// # Errors +/// On a database error. +pub async fn handle(app: &GithubApp, event: ForgeEvent) -> laravel::Result { + Ok(match event { + ForgeEvent::Merged { repository, head, base, merge_commit } => { + let projects = linked(&repository).await?; + for p in &projects { + PullRequestMerged { + project_id: p.id, + head: head.clone(), + base: base.clone(), + merge_commit: merge_commit.clone(), + } + .dispatch() + .await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::Closed { repository, branch, why } => { + let projects = linked(&repository).await?; + for p in &projects { + BranchClosed { project_id: p.id, branch: branch.clone(), why: why.to_string() }.dispatch().await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::Reopened { repository, branch } => { + let projects = linked(&repository).await?; + for p in &projects { + BranchReopened { project_id: p.id, branch: branch.clone() }.dispatch().await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::RepositoryChanged { repository, private } => { + let projects = linked(&repository).await?; + for p in &projects { + RepositoryVisibilityChanged { project_id: p.id, private }.dispatch().await?; + } + json!({ "dispatched": projects.len() }) + } + ForgeEvent::Moved { repository } => { + let (id, url) = (repository.id.clone(), repository.url.clone()); + let moved = db::query!( + "UPDATE projects SET repository_url = {url}, updated_at = now() \ + WHERE forge = 'github' AND repository_id = {id} AND repository_url IS DISTINCT FROM {url}" + ) + .update() + .await?; + json!({ "moved": moved }) + } + ForgeEvent::Installation { installation, previous, repositories } => { + // A stale or redelivered "created" mustn't attach an installation that's gone + if let Some(id) = &installation + && !github_app::installation_exists(app, id).await? + { + return Ok(json!({ "ignored": "no such installation" })); + } + let mut changed = 0; + let mut affected = HashSet::new(); + for repository in &repositories { + for p in linked(repository).await? { + // Removal only from the installation being removed; a project already on another keeps it + if previous.is_some() && p.installation != previous { + continue; + } + if p.installation == installation { + continue; + } + let (id, to) = (p.id, installation.clone()); + db::query!("UPDATE projects SET forge_installation = {to}, updated_at = now() WHERE id = {id}") + .update() + .await?; + affected.insert(p.organization_id); + changed += 1; + } + } + recheck_organizations(affected.into_iter().collect()).await?; + if installation.is_some() { json!({ "linked": changed }) } else { json!({ "unlinked": changed }) } + } + ForgeEvent::Access { people } => { + let mut users = Vec::new(); + for person in people { + let found: Option = db::query!( + "SELECT user_id FROM identities WHERE forge = 'github' AND site = '' AND forge_user_id = {person}" + ) + .scalar() + .await?; + users.extend(found); + } + let n = users.len(); + if n > 0 { + RecheckAccess { user_ids: users }.dispatch().await?; + } + json!({ "rechecking": n }) + } + ForgeEvent::AccessAll { installation } => { + let orgs: Vec = db::query!( + "SELECT DISTINCT organization_id FROM projects WHERE forge = 'github' AND forge_installation = {installation}" + ) + .select() + .await? + .iter() + .map(|r| r.try_get("organization_id")) + .collect::>()?; + recheck_organizations(orgs).await?; + json!({ "rechecking": "installation" }) + } + ForgeEvent::Ignored => json!({ "ignored": true }), + }) +} + +/// Recheck everyone whose membership in these organizations GitHub decides. +async fn recheck_organizations(orgs: Vec) -> laravel::Result<()> { + let mut users = HashSet::new(); + for org in orgs { + let rows = db::query!("SELECT user_id FROM memberships WHERE organization_id = {org} AND source = 'github'") + .select() + .await?; + for r in rows { + users.insert(r.try_get::("user_id")?); + } + } + if !users.is_empty() { + RecheckAccess { user_ids: users.into_iter().collect() }.dispatch().await?; + } + Ok(()) +} + +/// Recheck people's memberships from GitHub through the App ([`recheck`]). +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct RecheckAccess { + pub user_ids: Vec, +} + +#[job] +impl RecheckAccess { + async fn handle(self, app: laravel::config::Section) -> laravel::Result<()> { + recheck(&app, &self.user_ids).await?; + Ok(()) + } +} + +/// Who can reach each linked GitHub repository, from one listing of its collaborators. +#[derive(Debug, Default)] +pub struct Reach { + /// GitHub user ID -> the repositories they're a collaborator on, with their permission. + pub people: HashMap>, + /// GitHub repository ID -> GitHub user ID -> permission. A repository the App can't see any more has no entry. + pub repositories: HashMap>, +} + +/// List every linked repository's collaborators once: one installation token per installation, each repository's +/// path looked up by GitHub's ID so a rename can't mislead it. A repository the installation can't see any more +/// gives nobody anything. +/// +/// # Errors +/// When GitHub can't answer for some repository (a partial answer would drop people), when its rate limit is low, or +/// on a database error. +pub async fn reach(app: &GithubApp) -> laravel::Result { + let rows = db::query!( + "SELECT DISTINCT repository_id, forge_installation FROM projects \ + WHERE forge = 'github' AND repository_id IS NOT NULL AND forge_installation IS NOT NULL" + ) + .select() + .await?; + let mut tokens: HashMap = HashMap::new(); + let mut reach = Reach::default(); + for r in rows { + let (repository_id, installation): (String, String) = + (r.try_get("repository_id")?, r.try_get("forge_installation")?); + let token = match tokens.get(&installation) { + Some(t) => t.clone(), + None => { + let t = github_app::installation_token(app, &installation).await?; + tokens.insert(installation.clone(), t.clone()); + t + } + }; + let Some(path) = github_app::repository_path(&token, &repository_id).await? else { continue }; + let Some(repository) = Repository::parse(&path) else { continue }; + let repository = repository.with_id(Some(repository_id.clone())); + let people = reach.repositories.entry(repository_id).or_default(); + for (person, permission) in github_app::collaborators(&token, &path).await? { + people.insert(person.clone(), permission); + reach.people.entry(person).or_default().push((repository.clone(), permission)); + } + } + Ok(reach) +} + +/// GitHub user IDs of these people, where they have one. +async fn github_ids(user_ids: &[i64]) -> laravel::Result> { + let mut ids = HashMap::new(); + for &user_id in user_ids { + if let Some(id) = db::query!( + "SELECT forge_user_id FROM identities WHERE user_id = {user_id} AND forge = 'github' AND site = '' \ + ORDER BY id LIMIT 1" + ) + .scalar::() + .await? + { + ids.insert(user_id, id); + } + } + Ok(ids) +} + +/// Apply what `reach` found to these people's memberships, as a sign-in does (`auth::memberships::apply`). Returns +/// how many changed. +/// +/// # Errors +/// On a database error. +pub async fn apply_reach(reach: &Reach, user_ids: &[i64]) -> laravel::Result { + let mut changed = 0; + for (user_id, github_id) in github_ids(user_ids).await? { + let list = reach.people.get(&github_id).cloned().unwrap_or_default(); + changed += crate::auth::memberships::apply(user_id, ForgeKind::Github, "", &list).await?; + } + Ok(changed) +} + +/// Recheck people's memberships from GitHub through the App: [`reach`], then [`apply_reach`]. Nobody's memberships +/// change unless every repository was read. Returns how many changed. +/// +/// # Errors +/// When GitHub can't answer for some repository (or its rate limit is low), or on a database error. +pub async fn recheck(app: &GithubApp, user_ids: &[i64]) -> laravel::Result { + if github_ids(user_ids).await?.is_empty() { + return Ok(0); + } + let reach = reach(app).await?; + apply_reach(&reach, user_ids).await +} diff --git a/app/src/heartbeat.rs b/app/src/heartbeat.rs new file mode 100644 index 00000000..abc91f2a --- /dev/null +++ b/app/src/heartbeat.rs @@ -0,0 +1,24 @@ +//! Scheduled work pushes its result to a Gatus external endpoint when one is configured (`_URL` and +//! `_TOKEN`, such as `VISUALCI_EMAILS_HEARTBEAT_URL`), so a run that failed, or no run at all, alerts. Ported +//! from today's server. + +use laravel::http::client; + +/// Push a run's result. A failed push only logs: Gatus alerts on the missing heartbeat instead. +pub async fn push(prefix: &str, result: Result<(), String>) { + let Ok(url) = std::env::var(format!("{prefix}_URL")) else { return }; + if url.is_empty() { + return; + } + let token = std::env::var(format!("{prefix}_TOKEN")).unwrap_or_default(); + let (success, error) = match result { + Ok(()) => ("true", String::new()), + Err(e) => ("false", e), + }; + let sent = client::post(url).token(token).query([("success", success), ("error", error.as_str())]).await; + match sent { + Ok(response) if response.successful() => {} + Ok(response) => tracing::warn!(prefix, status = %response.status(), "heartbeat refused"), + Err(e) => tracing::warn!(prefix, error = %e, "heartbeat failed"), + } +} diff --git a/app/src/http/api/builds.rs b/app/src/http/api/builds.rs index 052aec39..a0b33441 100644 --- a/app/src/http/api/builds.rs +++ b/app/src/http/api/builds.rs @@ -18,12 +18,15 @@ pub fn routes(route: &mut Router) { route.get("/v1/builds/{pid}", show); route.post("/v1/builds/{pid}/snapshots", add_snapshots); route.post("/v1/builds/{pid}/finalize", finalize); + route.post("/v1/builds/{pid}/groups", check_groups); + route.post("/v1/builds/{pid}/compare", compare); + route.get("/v1/builds/{pid}/snapshots", list_snapshots); } -/// The renderer version documents are drawn with: part of the render cache key. +/// The renderer version documents are drawn with: part of the render cache key (`RENDERER_VERSION`, required). #[must_use] pub fn renderer_version() -> String { - std::env::var("VISUALCI_RENDERER_VERSION").unwrap_or_else(|_| "1".to_string()) + laravel::config().section::().version.clone() } /// The web app's address, for links (`APP_URL`). @@ -80,6 +83,36 @@ impl BuildResponse { } } +impl BuildResponse { + /// The response with `blocked` filled in: for a build stopped for credits, and for one still receiving files while + /// its organization has none. A stopped build whose organization has credits again says so. + /// + /// # Errors + /// On a database error. + pub async fn with_blocked( + mut self, + build: &Build, + project: &Project, + organization: &Organization, + ) -> laravel::Result { + use crate::domain::{credits, processing::OUT_OF_CREDITS}; + let stopped = build.error_code.as_deref() == Some(OUT_OF_CREDITS); + if !stopped && build.state != "receiving" { + return Ok(self); + } + self.blocked = match credits::blocked(organization, &app_url(), Some(credits::Spender::of(project))).await? { + Some(b) => Some(b), + None if stopped => Some(serde_json::json!({ + "reason": OUT_OF_CREDITS, + "resolved": true, + "message": format!("{} has VisualCI credits again. Run CI again to compare this commit.", organization.name), + })), + None => None, + }; + Ok(self) + } +} + fn respond(result: Result) -> Response { match result { Ok(body) => axum::response::IntoResponse::into_response(axum::Json(body)), @@ -106,8 +139,13 @@ pub async fn create(auth: Result, Body(params): Body Some(user.id), _ => None, }; + // The project's earlier builds that stopped arriving are given up on now (also every few minutes by the expiry + // task), so they don't sit "receiving" beside this one. + crate::domain::processing::expire_abandoned(Some(project.id)).await?; let build = domain::create(&project, ¶ms, creator).await.map_err(ApiError::from)?; - Ok(BuildResponse::new(&build, &project, &organization)) + Ok(BuildResponse::new(&build, &project, &organization) + .with_blocked(&build, &project, &organization) + .await?) } .await, ) @@ -119,7 +157,9 @@ pub async fn show(auth: Result, Params(pid): Params) async { let ApiProject { project, organization, .. } = auth?; let build = own_build(&project, pid).await?; - Ok(BuildResponse::new(&build, &project, &organization)) + Ok(BuildResponse::new(&build, &project, &organization) + .with_blocked(&build, &project, &organization) + .await?) } .await, ) @@ -168,8 +208,11 @@ pub async fn add_snapshots( let settings = BuildSettings::new(&project, &build); let version = renderer_version(); let mut snapshots = Vec::with_capacity(params.snapshots.len()); + // Every snapshot is checked before any is written. for p in ¶ms.snapshots { p.validate().map_err(ApiError::bad_request)?; + } + for p in ¶ms.snapshots { let registration = crate::domain::snapshots::register(&build, &settings, &version, p) .await? .map_err(ApiError::conflict)?; @@ -218,9 +261,157 @@ pub async fn finalize( Some(reason) => domain::allow_empty_because(build, reason).await.map_err(ApiError::from)?, None => build, }; + let was_receiving = build.state == "receiving"; let allow_empty = params.allow_empty || params.empty_reason.is_some(); let build = domain::finalize_shard(build, params.shard, allow_empty).await.map_err(ApiError::from)?; - Ok(BuildResponse::new(&build, &project, &organization)) + let build = + if was_receiving { crate::domain::processing::stop_if_out_of_credits(build).await? } else { build }; + if was_receiving && build.state == "processing" { + crate::jobs::process_build::ProcessBuild { build_id: build.id }.dispatch().await?; + } else if was_receiving && build.state == "failed" { + crate::events::BuildChanged { build_id: build.id }.dispatch().await?; + } + // The job may have run already (a synchronous queue): answer with the build as it is now. + let build = Build::find(build.id).await?.unwrap_or(build); + Ok(BuildResponse::new(&build, &project, &organization) + .with_blocked(&build, &project, &organization) + .await?) + } + .await, + ) +} + +/// `POST /api/v1/builds/{pid}/groups`: large suites (sc-8868) send the run's manifest hash and one hash per group of +/// names before any files. The answer says which groups the client must send; the rest are carried forward from their +/// baselines (or read from the build that holds them) when the build processes. +pub async fn check_groups( + auth: Result, + Params(pid): Params, + Body(params): Body, +) -> Response { + respond( + async { + let ApiProject { project, .. } = auth?; + let build = own_build(&project, pid).await?; + crate::domain::groups::check(&build, &project, ¶ms).await?.map_err(ApiError::bad_request) + } + .await, + ) +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CompareParams { + /// The snapshots to compare now, by name (and platform). + snapshots: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct CompareTarget { + name: String, + #[serde(default)] + platform: String, +} + +/// `POST /api/v1/builds/{pid}/compare`: compare some snapshots of a build that's still receiving, for a local run that +/// checks each test as it goes. Each comes back with its state: `pending` while its file is missing or its PDF is +/// rendering (ask again), `unchanged`, `changed`, `added`, `ignored` or `failed`. +pub async fn compare( + auth: Result, + Params(pid): Params, + Body(params): Body, +) -> Response { + respond( + async { + let ApiProject { project, organization, .. } = auth?; + let store = BlobStore::current().await?; + let build = own_build(&project, pid).await?; + if params.snapshots.len() > 200 { + return Err(ApiError::bad_request("at most 200 snapshots per request")); + } + let wanted: Vec<(String, String)> = params.snapshots.into_iter().map(|t| (t.name, t.platform)).collect(); + let version = renderer_version(); + let compared = laravel::db::transaction(async |_| { + crate::domain::processing::lock(build.id).await?; + let build = Build::find_or_fail(build.id).await?; + crate::domain::processing::compare_now(&build, &store, &version, &wanted).await + }) + .await? + .map_err(ApiError::bad_request)?; + let missing: Vec<&str> = wanted + .iter() + .filter(|(n, p)| !compared.iter().any(|s| &s.name == n && &s.platform == p)) + .map(|(n, _)| n.as_str()) + .collect(); + if !missing.is_empty() { + return Err(ApiError::bad_request(format!("not in build {}: {}", build.number, missing.join(", ")))); + } + let build_url = format!("{}/{}/{}/builds/{}", app_url(), organization.slug, project.slug, build.number); + let list: Vec = compared + .iter() + .map(|s| { + serde_json::json!({ + "name": s.name, "platform": s.platform, "state": s.state, "environment": s.environment, + "matched_environment": s.matched_environment, "error": s.error, + "url": format!("{build_url}/snapshots/{}", s.pid), + }) + }) + .collect(); + Ok(serde_json::json!({ "snapshots": list })) + } + .await, + ) +} + +#[derive(Debug, Default, Deserialize)] +pub struct SnapshotFilter { + /// A state, or `changes` for changed, added and removed. + state: Option, +} + +#[derive(Debug, Serialize)] +struct SnapshotSummary { + id: Uuid, + name: String, + platform: String, + kind: String, + state: String, + review: Option, + error: Option, +} + +/// `GET /api/v1/builds/{pid}/snapshots?state=`: every snapshot of the build, its own and those it reads from earlier +/// builds. +pub async fn list_snapshots( + auth: Result, + Params(pid): Params, + filter: axum::extract::Query, +) -> Response { + respond( + async { + let ApiProject { project, .. } = auth?; + let build = own_build(&project, pid).await?; + let state = filter.0.state; + let list: Vec = crate::domain::snapshots::of_build(build.id) + .await? + .into_iter() + .filter(|s| { + state + .as_deref() + .is_none_or(|st| st == s.state || (st == "changes" && crate::domain::snapshots::is_change(s))) + }) + .map(|s| SnapshotSummary { + id: s.pid, + name: s.name, + platform: s.platform, + kind: s.kind, + state: s.state, + review: s.review, + error: s.error, + }) + .collect(); + Ok(serde_json::json!({ "snapshots": list })) } .await, ) diff --git a/app/src/http/api/downloads.rs b/app/src/http/api/downloads.rs new file mode 100644 index 00000000..28363d56 --- /dev/null +++ b/app/src/http/api/downloads.rs @@ -0,0 +1,80 @@ +//! Bulk downloads of a build's images (sc-8869): `POST /api/v1/builds/{id or number}/downloads` with a filter +//! (`state`, `sides`, `glob`) returns the download, building or ready; `GET /api/v1/downloads/{id}` polls it. A ready +//! one has a `url` (an hour) to the tar.zst. Free. + +use axum::response::Response; +use laravel::prelude::*; +use laravel::str::Uuid; + +use super::{ApiError, ApiProject, Body}; +use crate::domain::downloads::{self, Filter, Refused}; +use crate::jobs::build_download::BuildDownload; +use crate::models::{Build, Download, Project}; +use crate::storage::BlobStore; + +pub fn routes(route: &mut Router) { + route.post("/v1/builds/{build}/downloads", request); + route.get("/v1/downloads/{pid}", show); +} + +fn respond(result: Result) -> Response { + match result { + Ok(body) => axum::response::IntoResponse::into_response(axum::Json(body)), + Err(e) => axum::response::IntoResponse::into_response(e), + } +} + +/// The project's build with this id, or this number (`12` or `#12`). +async fn find_build(project: &Project, build: &str) -> Result { + let query = Build::query().filter(Build::project_id.eq(project.id)); + let found = match build.parse::() { + Ok(pid) => query.filter(Build::pid.eq(pid)).first().await?, + Err(_) => { + let number: i32 = build.trim_start_matches('#').parse().map_err(|_| ApiError::not_found())?; + query.filter(Build::number.eq(number)).first().await? + } + }; + found.ok_or_else(ApiError::not_found) +} + +/// `POST /api/v1/builds/{id or number}/downloads`. +pub async fn request( + auth: Result, + Params(build): Params, + Body(filter): Body, +) -> Response { + respond( + async { + let ApiProject { project, .. } = auth?; + let build = find_build(&project, &build).await?; + let (mut download, new) = downloads::request(&build, &filter).await?.map_err(|r| match r { + Refused::Invalid(m) => ApiError::bad_request(m), + Refused::Busy(m) => ApiError::too_many_requests(m), + })?; + if new { + BuildDownload { download_id: download.id }.dispatch().await?; + // A job that runs inline (or quickly) has already finished it. + download = Download::find_or_fail(download.id).await?; + } + Ok(downloads::to_json(&download, &BlobStore::current().await?)) + } + .await, + ) +} + +/// `GET /api/v1/downloads/{id}`. +pub async fn show(auth: Result, Params(pid): Params) -> Response { + respond( + async { + let ApiProject { project, .. } = auth?; + let download = + Download::query().filter(Download::pid.eq(pid)).first().await?.ok_or_else(ApiError::not_found)?; + let build = Build::find_or_fail(download.build_id).await?; + if build.project_id != project.id { + return Err(ApiError::not_found()); + } + Ok(downloads::to_json(&download, &BlobStore::current().await?)) + } + .await, + ) +} diff --git a/app/src/http/api/mod.rs b/app/src/http/api/mod.rs index ec458fd2..13f1edb5 100644 --- a/app/src/http/api/mod.rs +++ b/app/src/http/api/mod.rs @@ -3,6 +3,8 @@ //! is a 422 `{"error": "invalid body: …"}`. pub mod builds; +pub mod downloads; +pub mod support; use axum::extract::FromRequestParts; use axum::http::StatusCode; @@ -19,6 +21,9 @@ pub fn routes(route: &mut Router) { }); route.get("/v1/whoami", crate::auth::whoami); builds::routes(route); + route.post("/v1/support/feedback", support::feedback); + downloads::routes(route); + crate::auth::device::api_routes(route); route.fallback(async || laravel::abort(404)); } @@ -40,6 +45,14 @@ impl ApiError { Self { status: StatusCode::CONFLICT, body: json!({ "error": "conflict", "description": message.into() }) } } + #[must_use] + pub fn too_many_requests(message: impl Into) -> Self { + Self { + status: StatusCode::TOO_MANY_REQUESTS, + body: json!({ "error": "too_many_requests", "description": message.into() }), + } + } + #[must_use] pub fn unauthorized(message: impl Into) -> Self { Self { @@ -63,6 +76,13 @@ impl ApiError { #[must_use] pub fn server(e: &laravel::Error) -> Self { + if super::busy(e) { + tracing::warn!("API request: every database connection is busy"); + return Self { + status: StatusCode::SERVICE_UNAVAILABLE, + body: json!({ "error": "busy", "description": "VisualCI is busy right now: retry in a few seconds." }), + }; + } tracing::error!(error = %e, "API request failed"); Self { status: StatusCode::INTERNAL_SERVER_ERROR, @@ -89,7 +109,11 @@ impl From> for ApiError { impl axum::response::IntoResponse for ApiError { fn into_response(self) -> axum::response::Response { - axum::response::IntoResponse::into_response((self.status, axum::Json(self.body))) + let mut response = axum::response::IntoResponse::into_response((self.status, axum::Json(self.body))); + if self.status == StatusCode::SERVICE_UNAVAILABLE { + response.headers_mut().insert(axum::http::header::RETRY_AFTER, super::RETRY_AFTER_SECONDS.into()); + } + response } } @@ -122,10 +146,23 @@ impl FromRequestParts for ApiProject { type Rejection = ApiError; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { - let has_token = parts.headers.get(axum::http::header::AUTHORIZATION).is_some(); - let principal = Principal::from_request_parts(parts, state) - .await - .map_err(|_| ApiError::unauthorized(if has_token { "invalid token" } else { "missing project token" }))?; + let token = parts + .headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(str::trim) + .unwrap_or_default() + .to_string(); + let principal = Principal::from_request_parts(parts, state).await.map_err(|_| { + ApiError::unauthorized(if token.is_empty() { + "missing project token" + } else if token.starts_with("vcu_") { + "invalid personal access token" + } else { + "invalid project token" + }) + })?; let project = match &principal { Principal::Project { project_id, .. } => { Project::find(*project_id).await?.ok_or_else(ApiError::not_found)? diff --git a/app/src/http/api/support.rs b/app/src/http/api/support.rs new file mode 100644 index 00000000..a528ca65 --- /dev/null +++ b/app/src/http/api/support.rs @@ -0,0 +1,47 @@ +//! `POST /api/v1/support/feedback`: the same feedback as MCP's `support_send`, for agents that use the API. + +use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; +use serde_json::json; + +use super::ApiError; +use crate::auth::Principal; +use crate::domain::feedback::{self, FeedbackError}; + +pub async fn feedback( + principal: Result, + headers: axum::http::HeaderMap, + axum::Json(report): axum::Json, +) -> Response { + let Ok(principal) = principal else { + let token = headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(str::trim) + .unwrap_or_default(); + return ApiError::unauthorized(if token.starts_with("vcu_") { + "invalid token" + } else { + "a personal access token or a project token is required" + }) + .into_response(); + }; + let (user_id, project_id, account) = match &principal { + Principal::User { user, .. } => (Some(user.id), None, format!("user:{}", user.id)), + Principal::Project { project_id, .. } => (None, Some(*project_id), format!("project:{project_id}")), + }; + let client = headers + .get(axum::http::header::USER_AGENT) + .and_then(|v| v.to_str().ok()) + .map(|s| s.chars().take(200).collect()); + let sender = feedback::Sender { user_id, project_id, account, channel: "api", client }; + match feedback::record(sender, report).await { + Ok((row, duplicate)) => axum::Json(feedback::result(&row, duplicate)).into_response(), + Err(FeedbackError::Invalid(m)) => ApiError::bad_request(m).into_response(), + Err(FeedbackError::RateLimited(m)) => { + (StatusCode::TOO_MANY_REQUESTS, axum::Json(json!({ "error": m }))).into_response() + } + Err(FeedbackError::Server(e)) => ApiError::server(&e).into_response(), + } +} diff --git a/app/src/http/gallery.rs b/app/src/http/gallery.rs new file mode 100644 index 00000000..4d9c2e2c --- /dev/null +++ b/app/src/http/gallery.rs @@ -0,0 +1,190 @@ +//! Public galleries on the app host: `/g//.json` (the manifest) and `/g///` (one +//! published screenshot, always its approved default-branch version). See `domain::gallery`. +//! +//! Cloudflare caches both for a day (`s-maxage`) and VisualCI purges a URL when an approval changes it +//! (`jobs::purge_gallery`), so the origin sees only misses. Each image the origin serves costs its organization one +//! credit, added to the project's row for the day and recorded even when it's out of credits: a customer's page must +//! keep working. Nothing else is served: no query parameters, no other variants, and a per-address rate limit, so the +//! URLs can't be used to bill a customer for junk or as free image hosting. Every answer may be read from any origin. + +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use std::net::IpAddr; + +use axum::http::{HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use laravel::http::Request; +use laravel::prelude::*; + +use crate::domain::gallery; +use crate::storage::BlobStore; + +/// Cloudflare keeps a copy for a day; browsers check again after five minutes, since a purge doesn't reach them. +const CACHE: &str = "public, max-age=300, s-maxage=86400"; +/// Requests per address per minute, per web process. +const PER_MINUTE: u32 = 120; + +pub fn routes(route: &mut Router) { + route.get("/g/{org}/{file}", manifest); + route.get("/g/{org}/{project}/{*path}", image); +} + +/// The caller's address, for the rate limit. `hop` is the address that reached our ingress (the kernel reads it from +/// the trusted proxies' `X-Forwarded-For`): when it's Cloudflare's edge, the client is the one Cloudflare names in +/// `cf-connecting-ip`; from anywhere else that header is the client's own claim, so the hop itself is the caller. +#[must_use] +pub fn caller(hop: IpAddr, cf_connecting_ip: Option<&str>, cloudflare: &[ipnet::IpNet]) -> String { + let from_cloudflare = cloudflare.iter().any(|n| n.contains(&hop)); + match cf_connecting_ip.map(str::trim).and_then(|v| v.parse::().ok()) { + Some(client) if from_cloudflare => client.to_string(), + _ => hop.to_string(), + } +} + +/// Whether this address may make another request now. +fn allowed(address: &str) -> bool { + static WINDOWS: OnceLock>> = OnceLock::new(); + let mut windows = WINDOWS.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap_or_else(|e| e.into_inner()); + let now = Instant::now(); + if windows.len() > 50_000 { + windows.retain(|_, (start, _)| now.duration_since(*start) < Duration::from_secs(60)); + } + let entry = windows.entry(address.to_string()).or_insert((now, 0)); + if now.duration_since(entry.0) >= Duration::from_secs(60) { + *entry = (now, 0); + } + entry.1 += 1; + entry.1 <= PER_MINUTE +} + +/// Any page may read a gallery answer: an image in an ``, the manifest with `fetch`. +fn public(mut r: Response) -> Response { + let h = r.headers_mut(); + h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*")); + h.insert(header::HeaderName::from_static("cross-origin-resource-policy"), HeaderValue::from_static("cross-origin")); + r +} + +/// A refusal (404) is never cached: a screenshot published a minute later must show up at once, and the approval's +/// purge only knows the URLs it published. The rate limit keeps junk URLs off the origin instead. +fn status(code: StatusCode, message: &'static str) -> Response { + let mut r = (code, message).into_response(); + r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + public(r) +} + +fn server(e: &laravel::Error) -> Response { + tracing::error!(error = %e, "gallery request failed"); + status(StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error") +} + +fn guard(request: &Request) -> Option { + if request.uri().query().is_some() { + return Some(status(StatusCode::NOT_FOUND, "not found")); + } + let settings = laravel::config(); + let networks = settings.section::().cloudflare_networks(); + if !allowed(&caller(request.ip(), request.header("cf-connecting-ip"), &networks)) { + let mut r = status(StatusCode::TOO_MANY_REQUESTS, "slow down"); + r.headers_mut().insert(header::RETRY_AFTER, HeaderValue::from_static("60")); + return Some(r); + } + None +} + +/// `/g//.json` +pub async fn manifest(Params((org, file)): Params<(String, String)>, request: Request) -> Response { + if let Some(r) = guard(&request) { + return r; + } + let Some(slug) = file.strip_suffix(".json") else { return status(StatusCode::NOT_FOUND, "not found") }; + let published = async { + let Some((_, project)) = gallery::project_by_slugs(&org, slug).await? else { return Ok(None) }; + Ok::<_, laravel::Error>(Some(gallery::published(&project).await?)) + } + .await; + match published { + Ok(Some(p)) if !p.items.is_empty() => { + let body = p.manifest(&crate::http::api::builds::app_url(), &org, slug); + let mut r = axum::Json(body).into_response(); + r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(CACHE)); + public(r) + } + Ok(_) => status(StatusCode::NOT_FOUND, "no public gallery"), + Err(e) => server(&e), + } +} + +/// `/g///`: one published screenshot. +pub async fn image(Params((org, slug, path)): Params<(String, String, String)>, request: Request) -> Response { + if let Some(r) = guard(&request) { + return r; + } + match serve(&org, &slug, &path, request.header(header::IF_NONE_MATCH)).await { + Ok(r) => r, + Err(e) => server(&e), + } +} + +async fn serve(org: &str, slug: &str, path: &str, if_none_match: Option<&str>) -> laravel::Result { + let Some((_, project)) = gallery::project_by_slugs(org, slug).await? else { + return Ok(status(StatusCode::NOT_FOUND, "not found")); + }; + let published = gallery::published(&project).await?; + let Some(item) = published.find(path) else { return Ok(status(StatusCode::NOT_FOUND, "not found")) }; + let etag = format!("\"{}\"", item.sha256); + if if_none_match == Some(etag.as_str()) { + let mut r = StatusCode::NOT_MODIFIED.into_response(); + r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(CACHE)); + return Ok(public(r)); + } + let bytes = BlobStore::current().await?.get(&item.sha256).await?; + // The type the bytes are, never the one a client declared: this is the app's own origin, where HTML would run. + let content_type = match image::guess_format(&bytes) { + Ok(image::ImageFormat::Png) => "image/png", + Ok(image::ImageFormat::Jpeg) => "image/jpeg", + Ok(image::ImageFormat::WebP) => "image/webp", + _ => return Ok(status(StatusCode::NOT_FOUND, "not found")), + }; + // Served from VisualCI's own servers: a credit, kept even when the organization is out of them, up to the day's + // cap per project (past it, images are served free). + let cap = laravel::config().section::().daily_credits; + crate::domain::credits::spend_gallery(&project, 1, cap).await?; + let mut r = bytes.into_response(); + let h = r.headers_mut(); + h.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type)); + h.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); + h.insert(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static("default-src 'none'; sandbox")); + h.insert(header::CACHE_CONTROL, HeaderValue::from_static(CACHE)); + if let Ok(v) = HeaderValue::from_str(&etag) { + h.insert(header::ETAG, v); + } + Ok(public(r)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cloudflare_names_the_client_only_when_the_request_came_from_cloudflare() { + let cloudflare: Vec = vec!["173.245.48.0/20".parse().unwrap(), "2606:4700::/32".parse().unwrap()]; + let edge: IpAddr = "173.245.48.7".parse().unwrap(); + let elsewhere: IpAddr = "203.0.113.9".parse().unwrap(); + assert_eq!(caller(edge, Some("198.51.100.4"), &cloudflare), "198.51.100.4"); + assert_eq!(caller("2606:4700::1".parse().unwrap(), Some("2001:db8::5"), &cloudflare), "2001:db8::5"); + // A client that reaches the origin directly can't pick its own address, however it rotates the header. + assert_eq!(caller(elsewhere, Some("198.51.100.4"), &cloudflare), "203.0.113.9"); + assert_eq!(caller(elsewhere, Some("198.51.100.5"), &cloudflare), "203.0.113.9"); + assert_eq!(caller(edge, Some("not an address"), &cloudflare), "173.245.48.7"); + assert_eq!(caller(edge, None, &cloudflare), "173.245.48.7"); + } + + #[test] + fn the_published_cloudflare_ranges_parse() { + let gallery = crate::config::Gallery { cloudflare_ip_ranges: String::new(), daily_credits: 1 }; + assert_eq!(gallery.cloudflare_networks().len(), crate::config::CLOUDFLARE_IP_RANGES.split(',').count()); + } +} diff --git a/app/src/http/mod.rs b/app/src/http/mod.rs index 44cc1f01..02b9ee67 100644 --- a/app/src/http/mod.rs +++ b/app/src/http/mod.rs @@ -1,4 +1,17 @@ //! HTTP handlers. pub mod api; +pub mod gallery; pub mod hosts; +pub mod renderer; +pub mod status; + +/// Whether a request failed because every pooled database connection was in use for `DB_ACQUIRE_TIMEOUT`: the +/// answer is a 503 with Retry-After, so clients (the CLI retries) back off instead of piling on. +#[must_use] +pub fn busy(e: &laravel::Error) -> bool { + matches!(e.downcast_ref::(), Some(laravel::db::sqlx::Error::PoolTimedOut)) +} + +/// How long a client should wait before retrying a 503, in seconds. +pub const RETRY_AFTER_SECONDS: u32 = 5; diff --git a/app/src/http/renderer.rs b/app/src/http/renderer.rs new file mode 100644 index 00000000..6593246f --- /dev/null +++ b/app/src/http/renderer.rs @@ -0,0 +1,396 @@ +//! The renderer API (`/internal/renderer`). Renderers run in a sandbox with no database access: they claim a render +//! here, download the PDF from a presigned URL, upload page images to presigned URLs and report the pages. +//! +//! Every route checks its token itself, whatever the request's Host: the routes are reachable from any host the host +//! routing doesn't know (the cluster address the renderers use), and a client chooses its Host header. Claiming, +//! uploading and completing take the shared renderer token; uploading a render's pages and completing it also need the +//! token its claim was given (`X-Render-Token`), so a renderer acts only on the render it claimed. The metrics take the +//! scraper's own token: a renderer (which runs untrusted PDFs) can't read metrics, and the scraper can't claim renders. + +use axum::http::{HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use laravel::db; +use laravel::prelude::*; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +use crate::config::Renderer; +use crate::domain::renders::{self, RenderPage}; +use crate::models::Render; +use crate::storage::BlobStore; + +pub fn routes(route: &mut Router) { + route.prefix("/internal/renderer").group(|route| { + route.get("/metrics", metrics); + route.post("/claim", claim); + route.post("/renders/{id}/uploads", uploads); + route.post("/renders/{id}/complete", complete); + }); +} + +fn error(status: StatusCode, kind: &str, description: impl Into) -> Response { + (status, axum::Json(json!({ "error": kind, "description": description.into() }))).into_response() +} + +fn unauthorized(description: &str) -> Response { + error(StatusCode::UNAUTHORIZED, "unauthorized", description) +} + +fn server(e: &laravel::Error) -> Response { + tracing::error!(error = %e, "renderer API request failed"); + error(StatusCode::INTERNAL_SERVER_ERROR, "internal_server_error", "Internal Server Error") +} + +fn bearer(headers: &HeaderMap) -> &str { + headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .unwrap_or_default() +} + +/// A constant-time comparison; an empty expected secret matches nothing. +fn same_secret(given: &str, expected: &str) -> bool { + let expected = expected.as_bytes(); + !expected.is_empty() + && given.len() == expected.len() + && given.bytes().zip(expected).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0 +} + +/// `Err` with the 401 when the request doesn't carry the renderer token. +fn renderer_token(headers: &HeaderMap) -> Result<(), Response> { + let settings = laravel::config(); + let config = settings.section::(); + if same_secret(bearer(headers), &config.token) { Ok(()) } else { Err(unauthorized("invalid renderer token")) } +} + +/// The render `id`, when the request carries its current claim's token (`X-Render-Token`). +async fn claimed_render(headers: &HeaderMap, id: i64) -> Result { + let token = headers.get("x-render-token").and_then(|v| v.to_str().ok()).unwrap_or_default(); + let render = Render::find(id) + .await + .map_err(|e| server(&e))? + .ok_or_else(|| error(StatusCode::NOT_FOUND, "not_found", "Resource was not found"))?; + if renders::claimed_with(&render, token) { Ok(render) } else { Err(unauthorized("not this render's claim")) } +} + +#[derive(Debug, Deserialize)] +pub struct ClaimParams { + /// The renderer image's version; only renders keyed to it are handed out. + renderer_version: String, +} + +#[derive(Debug, Serialize)] +struct Job { + id: i64, + engine: String, + dpi: u32, + source_url: String, + source_sha256: String, + /// This claim's token: `X-Render-Token` on this render's uploads and completion. + token: String, +} + +/// `POST /internal/renderer/claim`: the next render to draw, or `{"job": null}`. +pub async fn claim(headers: HeaderMap, body: axum::body::Bytes) -> Response { + if let Err(r) = renderer_token(&headers) { + return r; + } + let params: ClaimParams = match serde_json::from_slice(&body) { + Ok(p) => p, + Err(e) => return error(StatusCode::UNPROCESSABLE_ENTITY, "invalid body", e.to_string()), + }; + let result = async { + let store = BlobStore::current().await?; + let Some((render, token)) = renders::claim(¶ms.renderer_version).await? else { + return Ok(json!({ "job": null })); + }; + let (engine, dpi) = renders::engine_and_dpi(&render); + let job = Job { + id: render.id, + engine, + dpi, + source_url: store.download_url(&render.source_blob)?, + source_sha256: render.source_blob.clone(), + token, + }; + Ok::<_, laravel::Error>(json!({ "job": job })) + } + .await; + match result { + Ok(body) => axum::Json(body).into_response(), + Err(e) => server(&e), + } +} + +#[derive(Debug, Deserialize)] +struct UploadFile { + sha256: String, + size: i64, + content_type: String, +} + +#[derive(Debug, Deserialize)] +struct UploadsParams { + files: Vec, +} + +/// `POST /internal/renderer/renders/{id}/uploads`: upload URLs for a render's page images (PNGs only). +pub async fn uploads(Params(id): Params, headers: HeaderMap, body: axum::body::Bytes) -> Response { + if let Err(r) = renderer_token(&headers) { + return r; + } + if let Err(r) = claimed_render(&headers, id).await { + return r; + } + let params: UploadsParams = match serde_json::from_slice(&body) { + Ok(p) => p, + Err(e) => return error(StatusCode::UNPROCESSABLE_ENTITY, "invalid body", e.to_string()), + }; + if params.files.len() > renders::MAX_UPLOADS { + return error( + StatusCode::BAD_REQUEST, + "Bad Request", + format!("{} files: a request names at most {}", params.files.len(), renders::MAX_UPLOADS), + ); + } + let max = i64::try_from(crate::storage::blobs::MAX_BLOB_BYTES).unwrap_or(i64::MAX); + for f in ¶ms.files { + // Page images only: a render uploads PNGs, never a type a browser would run. + if f.content_type != "image/png" + || f.size <= 0 + || f.size > max + || !crate::storage::blobs::valid_sha256(&f.sha256) + { + return error( + StatusCode::BAD_REQUEST, + "Bad Request", + format!("{}: page images are PNGs of at most 64 MiB", f.sha256), + ); + } + } + let result = async { + let store = BlobStore::current().await?; + let mut urls = serde_json::Map::new(); + let mut kinds = serde_json::Map::new(); + for f in ¶ms.files { + let blob = crate::domain::blobs::register(&f.sha256, f.size, &f.content_type).await?; + if crate::domain::blobs::is_uploaded(&blob) { + // Already stored (perhaps another tenant's): the renderer shows it drew the same PNG by uploading the + // bytes to a key of this render's own, checked when it completes. The URL takes exactly the declared + // size. + let size = u64::try_from(f.size).unwrap_or_default(); + urls.insert( + f.sha256.clone(), + store.upload_url_for_key(&renders::proof_key(id, &f.sha256), size).into(), + ); + kinds.insert(f.sha256.clone(), "proof".into()); + } else { + urls.insert(f.sha256.clone(), store.upload_url(&f.sha256)?.into()); + kinds.insert(f.sha256.clone(), "blob".into()); + } + } + if let Err(m) = renders::record_uploads(id, &kinds).await? { + return Ok(Err(m)); + } + Ok::<_, laravel::Error>(Ok(json!({ "upload_urls": urls }))) + } + .await; + match result { + Ok(Ok(body)) => axum::Json(body).into_response(), + Ok(Err(m)) => error(StatusCode::BAD_REQUEST, "Bad Request", m), + Err(e) => server(&e), + } +} + +/// Check that every page image is a PNG this render uploaded: a blob it uploaded (confirmed against its hash), or a +/// proof of one already stored (its bytes hash to it; the proof object is deleted). Returns what's wrong, if anything. +async fn check_images(store: &BlobStore, render: &Render, pages: &[RenderPage]) -> laravel::Result> { + let kinds = render.uploads.as_object().cloned().unwrap_or_default(); + let mut blobs = Vec::new(); + let mut proofs = Vec::new(); + for p in pages { + match kinds.get(&p.image).and_then(|k| k.as_str()) { + Some("proof") => proofs.push(p.image.clone()), + _ => blobs.push(p.image.clone()), + } + } + blobs.sort(); + blobs.dedup(); + proofs.sort(); + proofs.dedup(); + let missing = crate::domain::blobs::confirm_uploads(store, &blobs).await?; + if !missing.is_empty() { + return Ok(Some(format!("page images not uploaded: {}", missing.join(", ")))); + } + for sha in &proofs { + let key = renders::proof_key(render.id, sha); + let proven = store.verify_object(&key, sha).await?.is_some(); + store.delete_object(&key).await?; + if !proven { + return Ok(Some(format!("page image {sha} wasn't uploaded for this render"))); + } + } + let all: Vec = blobs.iter().chain(&proofs).cloned().collect(); + for chunk in all.chunks(1000) { + let wrong = crate::models::Blob::query() + .filter( + crate::models::Blob::sha256.is_in(chunk.to_vec()) & crate::models::Blob::content_type.ne("image/png"), + ) + .first() + .await?; + if let Some(b) = wrong { + return Ok(Some(format!("page image {} isn't a PNG", b.sha256))); + } + } + Ok(None) +} + +#[derive(Debug, Deserialize)] +struct CompleteParams { + #[serde(default)] + pages: Vec, + error: Option, +} + +/// `POST /internal/renderer/renders/{id}/complete`: the render's pages (their images uploaded first), or its error. +/// Every build waiting on it is processed again. +pub async fn complete(Params(id): Params, headers: HeaderMap, body: axum::body::Bytes) -> Response { + if let Err(r) = renderer_token(&headers) { + return r; + } + let render = match claimed_render(&headers, id).await { + Ok(r) => r, + Err(r) => return r, + }; + let params: CompleteParams = match serde_json::from_slice(&body) { + Ok(p) => p, + Err(e) => return error(StatusCode::UNPROCESSABLE_ENTITY, "invalid body", e.to_string()), + }; + let result = async { + let store = BlobStore::current().await?; + if params.error.is_none() + && let Err(m) = renders::validate_pages(&render, ¶ms.pages) + { + // A renderer that sends this has been taken over by its PDF, or is broken: the render fails. + let failed = renders::fail(render, &m).await?; + renders::wake_waiting(&failed).await?; + return Ok(Err(m)); + } + let result = if let Some(error) = params.error { + renders::fail(render, &error).await? + } else if params.pages.is_empty() { + renders::fail(render, "the renderer produced no pages").await? + } else if let Some(problem) = check_images(&store, &render, ¶ms.pages).await? { + renders::fail(render, &problem).await? + } else { + renders::complete(render, ¶ms.pages).await? + }; + renders::wake_waiting(&result).await?; + Ok::<_, laravel::Error>(Ok(json!({ "state": result.state }))) + } + .await; + match result { + Ok(Ok(body)) => axum::Json(body).into_response(), + Ok(Err(m)) => error(StatusCode::BAD_REQUEST, "Bad Request", m), + Err(e) => server(&e), + } +} + +/// `GET /internal/renderer/metrics`: Prometheus metrics for the renderers, from the last 24 hours of renders: seconds +/// per page and queue wait (quantiles), renders finished by state, pages drawn, and what's queued or rendering now. +/// Scraped with the metrics token. +pub async fn metrics(headers: HeaderMap) -> Response { + let settings = laravel::config(); + let config = settings.section::(); + if !same_secret(bearer(&headers), &config.metrics_token) { + return unauthorized("invalid metrics token"); + } + match metrics_text().await { + Ok(out) => ([(axum::http::header::CONTENT_TYPE, "text/plain; version=0.0.4")], out).into_response(), + Err(e) => server(&e), + } +} + +async fn metrics_text() -> laravel::Result { + let row = db::query!( + "WITH recent AS (SELECT * FROM renders WHERE completed_at > now() - interval '24 hours'), \ + done AS (SELECT render_ms / 1000.0 / GREATEST(jsonb_array_length(pages), 1) AS per_page, \ + jsonb_array_length(pages) AS pages, wait_ms / 1000.0 AS wait \ + FROM recent WHERE state = 'done' AND render_ms IS NOT NULL) \ + SELECT \ + (SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY per_page) FROM done)::FLOAT8 AS page_p50, \ + (SELECT percentile_cont(0.9) WITHIN GROUP (ORDER BY per_page) FROM done)::FLOAT8 AS page_p90, \ + (SELECT percentile_cont(0.99) WITHIN GROUP (ORDER BY per_page) FROM done)::FLOAT8 AS page_p99, \ + (SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY wait) FROM done)::FLOAT8 AS wait_p50, \ + (SELECT percentile_cont(0.9) WITHIN GROUP (ORDER BY wait) FROM done)::FLOAT8 AS wait_p90, \ + (SELECT percentile_cont(0.99) WITHIN GROUP (ORDER BY wait) FROM done)::FLOAT8 AS wait_p99, \ + (SELECT COUNT(*) FROM done)::BIGINT AS done_count, \ + (SELECT COALESCE(SUM(per_page), 0) FROM done)::FLOAT8 AS page_sum, \ + (SELECT COALESCE(SUM(wait), 0) FROM done)::FLOAT8 AS wait_sum, \ + (SELECT COALESCE(SUM(pages), 0) FROM done)::BIGINT AS pages, \ + (SELECT COUNT(*) FROM recent WHERE state = 'failed')::BIGINT AS failed_count, \ + (SELECT COUNT(*) FROM renders WHERE state = 'queued')::BIGINT AS queued, \ + (SELECT COUNT(*) FROM renders WHERE state = 'rendering')::BIGINT AS rendering, \ + (SELECT COUNT(*) FROM gallery_purge_failures WHERE created_at > now() - interval '7 days')::BIGINT \ + AS gallery_purges_failed" + ) + .select_one() + .await? + .ok_or_else(|| laravel::Error::msg("no metrics row"))?; + let f = |name: &str| row.try_get::>(name).ok().flatten(); + let n = |name: &str| row.try_get::(name).unwrap_or(0); + let mut out = String::new(); + // Quantiles appear once a render has finished in the window; _sum and _count always do. Every web pod reports the + // same database's numbers, so dashboards take max across pods, not sum. + let mut summary = |metric: &str, help: &str, values: [(&str, Option); 3], sum: f64, count: i64| { + out.push_str(&format!("# HELP {metric} {help}\n# TYPE {metric} summary\n")); + for (q, v) in values { + if let Some(v) = v { + out.push_str(&format!("{metric}{{quantile=\"{q}\"}} {v}\n")); + } + } + out.push_str(&format!("{metric}_sum {sum}\n{metric}_count {count}\n")); + }; + summary( + "visualci_render_page_seconds", + "Seconds from claim to completion per page drawn, renders finished in the last 24 hours.", + [("0.5", f("page_p50")), ("0.9", f("page_p90")), ("0.99", f("page_p99"))], + f("page_sum").unwrap_or(0.0), + n("done_count"), + ); + summary( + "visualci_render_queue_wait_seconds", + "Seconds a render waited in the queue before a renderer claimed it, renders finished in the last 24 hours.", + [("0.5", f("wait_p50")), ("0.9", f("wait_p90")), ("0.99", f("wait_p99"))], + f("wait_sum").unwrap_or(0.0), + n("done_count"), + ); + let gauge = |out: &mut String, metric: &str, help: &str, lines: &[(&str, i64)]| { + out.push_str(&format!("# HELP {metric} {help}\n# TYPE {metric} gauge\n")); + for (labels, v) in lines { + out.push_str(&format!("{metric}{labels} {v}\n")); + } + }; + gauge( + &mut out, + "visualci_renders_finished_24h", + "Renders finished in the last 24 hours, by state.", + &[("{state=\"done\"}", n("done_count")), ("{state=\"failed\"}", n("failed_count"))], + ); + gauge(&mut out, "visualci_render_pages_24h", "Pages drawn in the last 24 hours.", &[("", n("pages"))]); + // Alerted on a rise (a warning: Cloudflare may serve a stale public-gallery screenshot until its cache expires). + gauge( + &mut out, + "visualci_gallery_purges_failed_7d", + "Public gallery purges that used up their retries in the last 7 days.", + &[("", n("gallery_purges_failed"))], + ); + gauge( + &mut out, + "visualci_renders_now", + "Renders queued or being drawn now.", + &[("{state=\"queued\"}", n("queued")), ("{state=\"rendering\"}", n("rendering"))], + ); + Ok(out) +} diff --git a/app/src/http/status.rs b/app/src/http/status.rs new file mode 100644 index 00000000..81d8bb5f --- /dev/null +++ b/app/src/http/status.rs @@ -0,0 +1,79 @@ +//! `GET /status`: the deployed commit and how the background work is keeping up, for uptime checks and alerts (each +//! number has a threshold in Gatus). The data side's numbers; subdomains' (emails, sign-up notices, forge syncs) join +//! them in the same answer. + +use axum::Json; +use laravel::db; +use serde_json::{Value, json}; + +/// The commit this build of the app came from (`BUILD_SHA` at compile time). +pub const COMMIT: &str = match option_env!("BUILD_SHA") { + Some(sha) => sha, + None => "dev", +}; + +pub async fn status() -> axum::response::Response { + use axum::response::IntoResponse; + match numbers().await { + Ok(body) => body.into_response(), + // Every connection busy, or the database down: a fast 503 that Gatus alerts on, never a hang. + Err(e) => { + tracing::error!(error = %e, "status: the database didn't answer"); + let mut response = ( + axum::http::StatusCode::SERVICE_UNAVAILABLE, + Json(json!({ "ok": false, "commit": COMMIT, "database": if super::busy(&e) { "busy" } else { "error" } })), + ) + .into_response(); + response.headers_mut().insert(axum::http::header::RETRY_AFTER, super::RETRY_AFTER_SECONDS.into()); + response + } + } +} + +async fn numbers() -> laravel::Result> { + let row = db::query!( + "SELECT \ + (SELECT COUNT(*) FROM renders WHERE state = 'queued')::BIGINT AS renders_queued, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(created_at)) FROM renders \ + WHERE state IN ('queued', 'rendering')), 0)::BIGINT AS oldest_render_seconds, \ + (SELECT COUNT(*) FROM builds WHERE state = 'processing')::BIGINT AS builds_processing, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(finalized_at)) FROM builds WHERE state = 'processing'), 0)::BIGINT \ + AS oldest_processing_seconds, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MAX(updated_at)) FROM renders WHERE state = 'done'), -1)::BIGINT \ + AS last_render_seconds_ago, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(GREATEST(b.updated_at, COALESCE((SELECT MAX(s.updated_at) \ + FROM snapshots s WHERE s.build_id = b.id), b.created_at)))) FROM builds b WHERE b.state = 'receiving'), 0)::BIGINT \ + AS oldest_receiving_seconds, \ + (SELECT COUNT(*) FROM build_groups g WHERE g.source_build_id IS NOT NULL AND NOT EXISTS ( \ + SELECT 1 FROM snapshots s WHERE s.build_id = g.source_build_id AND s.group_key = g.key))::BIGINT \ + AS empty_groups, \ + (SELECT COUNT(*) FROM gallery_purge_failures WHERE created_at > now() - interval '7 days')::BIGINT \ + AS gallery_purges_failed, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(synced_at)) FROM memberships \ + WHERE source = 'github' AND synced_at IS NOT NULL), 0)::BIGINT AS oldest_forge_sync_seconds" + ) + .select_one() + .await? + .ok_or_else(|| laravel::Error::msg("no status row"))?; + let get = |k: &str| -> laravel::Result { row.try_get::(k) }; + Ok(Json(json!({ + "ok": true, + "commit": COMMIT, + "renders_queued": get("renders_queued")?, + "oldest_render_seconds": get("oldest_render_seconds")?, + "builds_processing": get("builds_processing")?, + // The builds sweep (every five minutes) runs a build again after 10 minutes without progress and fails it + // after 6 hours: past that, the sweep has stopped. + "oldest_processing_seconds": get("oldest_processing_seconds")?, + "last_render_seconds_ago": get("last_render_seconds_ago")?, + // A build left receiving: the sweep fails it after an hour without uploads, so past two hours it has stopped. + "oldest_receiving_seconds": get("oldest_receiving_seconds")?, + // Groups a build reads from another build that has no rows for them (`groups:check`): always 0. + "empty_groups": get("empty_groups")?, + // Gallery purges that used up their retries in the last week: Cloudflare may serve stale screenshots. + "gallery_purges_failed": get("gallery_purges_failed")?, + // The longest any GitHub-derived membership has gone unchecked: subdomains' hourly forge sync keeps it under an + // hour. With the scheduler down, this, the receiving and processing ages are what still alert. + "oldest_forge_sync_seconds": get("oldest_forge_sync_seconds")?, + }))) +} diff --git a/app/src/jobs/build_download.rs b/app/src/jobs/build_download.rs new file mode 100644 index 00000000..9e68bf7f --- /dev/null +++ b/app/src/jobs/build_download.rs @@ -0,0 +1,22 @@ +//! Builds a bulk download's archive (sc-8869, `domain::downloads`). Queued when a download is requested and no ready +//! or building one of the same build and filter is recent. A download left building by a job that stopped is replaced +//! on the next request after `downloads::STALE_MINUTES`. + +use laravel::queue::{Queueable, job}; + +use crate::domain::downloads; +use crate::models::Download; +use crate::storage::BlobStore; + +#[derive(Queueable)] +pub struct BuildDownload { + pub download_id: i64, +} + +#[job(name = "downloads.build")] +impl BuildDownload { + async fn handle(self) -> laravel::Result<()> { + let Some(download) = Download::find(self.download_id).await? else { return Ok(()) }; + downloads::build(download, &BlobStore::current().await?).await + } +} diff --git a/app/src/jobs/mod.rs b/app/src/jobs/mod.rs new file mode 100644 index 00000000..ac591519 --- /dev/null +++ b/app/src/jobs/mod.rs @@ -0,0 +1,5 @@ +//! Queued jobs. + +pub mod build_download; +pub mod process_build; +pub mod purge_gallery; diff --git a/app/src/jobs/process_build.rs b/app/src/jobs/process_build.rs new file mode 100644 index 00000000..2204c575 --- /dev/null +++ b/app/src/jobs/process_build.rs @@ -0,0 +1,83 @@ +//! Processes a finalized build: confirms uploads, queues renders, and once they're done compares and concludes. Queued +//! when a build's last shard finalizes, and again whenever a render it waits on finishes: dispatches for one build +//! within a few seconds run once (a build of 1,000 PDFs finishing its renders together is one run, not 1,000). + +use laravel::db; +use laravel::queue::{Queueable, job}; + +use crate::domain::processing; +use crate::events::{BuildChanged, CreditsSpent}; +use crate::models::Build; +use crate::storage::BlobStore; + +#[derive(Queueable)] +pub struct ProcessBuild { + pub build_id: i64, +} + +#[job(name = "builds.process", debounce_for = 3.seconds(), max_wait = 30.seconds())] +impl ProcessBuild { + fn debounce_id(&self) -> i64 { + self.build_id + } + + async fn handle(self) -> laravel::Result<()> { + let id = self.build_id; + let store = BlobStore::current().await?; + let version = crate::http::api::builds::renderer_version(); + // Charge what the build has used so far in a short transaction of its own: the organization's row is locked + // only while it's charged, never for a whole run, and what's charged stays charged if the run fails. + let charged = db::transaction(async |_| { + processing::lock(id).await?; + let build = Build::find_or_fail(id).await?; + if build.state == "processing" { + processing::charge(&build).await?; + } + Ok(build) + }) + .await?; + if charged.state != "processing" { + return Ok(()); + } + // Out of credits part-way (a large build's pages): stop here rather than draw the rest. Outside any + // transaction, so billing's listeners (an automatic reload charges the card) run on committed data. + let build = processing::stop_if_out_of_credits(charged).await?; + if build.state == "failed" { + processing::drop_unneeded_renders(id).await?; + finished(id, build.project_id).await?; + return Ok(()); + } + // One run at a time per build (the advisory lock), all its comparison writes together. + let result = db::transaction(async |_| { + processing::lock(id).await?; + let build = Build::find_or_fail(id).await?; + if build.state != "processing" { + return Ok(false); + } + processing::process(build, &store, &version).await + }) + .await; + match result { + Ok(true) => finished(id, build.project_id).await?, + Ok(false) => tracing::debug!(build_id = id, "build waiting for renders"), + Err(e) => { + tracing::error!(build_id = id, error = %e, "processing a build failed"); + let error = Some(e.to_string()); + if let Some(mut build) = Build::find(id).await? { + laravel::model::update!(build { state: "failed", error }).await?; + } + BuildChanged { build_id: id }.dispatch().await?; + } + } + Ok(()) + } +} + +/// The build concluded (or stopped): billing hears what was spent, and its checks, comment and pages follow. +async fn finished(build_id: i64, project_id: i64) -> laravel::Result<()> { + if let Some(project) = crate::models::Project::find(project_id).await? { + CreditsSpent { organization_id: project.organization_id }.dispatch().await?; + } + BuildChanged { build_id }.dispatch().await?; + Ok(()) +} diff --git a/app/src/jobs/purge_gallery.rs b/app/src/jobs/purge_gallery.rs new file mode 100644 index 00000000..d85428ed --- /dev/null +++ b/app/src/jobs/purge_gallery.rs @@ -0,0 +1,141 @@ +//! Purges Cloudflare's copies of public gallery URLs (`domain::gallery`): after a CI build changes (processed, approved, +//! rejected: the `BuildChanged` listener queues it), each published screenshot it changed and the project's manifest, +//! and every URL the project published at its last purge that it doesn't publish now (a screenshot removed, a group +//! dropped, the gallery turned off); or a list of URLs as they are (`gallery::purge_project`). One URL per screenshot, so +//! a purge is exact. Without `VISUALCI_CLOUDFLARE_ZONE_ID` and `VISUALCI_CLOUDFLARE_PURGE_TOKEN` (development) nothing is +//! queued. A failed purge is tried again; one that used up its tries is logged as an error and recorded in +//! `gallery_purge_failures`, which `/status` counts (`gallery_purges_failed`). + +use std::collections::BTreeSet; + +use laravel::db; +use laravel::queue::{Queueable, job}; + +use crate::config::Cloudflare; +use crate::domain::gallery; +use crate::models::{Build, Project}; + +#[derive(Queueable)] +pub struct PurgeGallery { + /// The build whose change may have made gallery URLs stale. + pub build_id: Option, + /// The project, when there's no build (`gallery::purge_project`). + pub project_id: Option, + /// URLs to purge as they are. + pub urls: Vec, +} + +/// Whether purges are configured: Cloudflare's zone and a token that may purge it. +#[must_use] +pub fn configured() -> Option { + let settings = laravel::config(); + let c = settings.section::().clone(); + (!c.zone_id.is_empty() && !c.purge_token.is_empty()).then_some(c) +} + +/// Ask Cloudflare to drop these URLs, 30 at a time (its limit per call). A client per purge: an HTTP client held +/// across the application's runtimes breaks. +async fn purge(cloudflare: &Cloudflare, urls: &[String]) -> laravel::Result<()> { + let client = reqwest::Client::new(); + for batch in urls.chunks(30) { + let response = client + .post(format!("https://api.cloudflare.com/client/v4/zones/{}/purge_cache", cloudflare.zone_id)) + .bearer_auth(&cloudflare.purge_token) + .json(&serde_json::json!({ "files": batch })) + .timeout(std::time::Duration::from_secs(20)) + .send() + .await + .map_err(|e| laravel::Error::msg(format!("Cloudflare purge: {e}")))?; + if !response.status().is_success() { + let status = response.status(); + let body = response.text().await.unwrap_or_default(); + return Err(laravel::Error::msg(format!( + "Cloudflare purge: HTTP {status}: {}", + body.chars().take(300).collect::() + ))); + } + } + Ok(()) +} + +/// What a purge does: the URLs to purge, and the project with what it publishes now (recorded once the purge worked). +pub struct Plan { + pub urls: Vec, + pub project: Option, + pub current: Vec, +} + +impl PurgeGallery { + /// Work out what to purge: the URLs given, the build's stale ones, and those published at the last purge but not + /// now. + /// + /// # Errors + /// On a database error. + pub async fn plan(&self) -> laravel::Result { + let app_url = crate::http::api::builds::app_url(); + let mut urls: BTreeSet = self.urls.iter().cloned().collect(); + let build = match self.build_id { + Some(id) => Build::find(id).await?, + None => None, + }; + let project_id = self.project_id.or(build.as_ref().map(|b| b.project_id)); + let project = match project_id { + Some(id) => Project::find(id).await?, + None => None, + }; + if let Some(build) = &build { + urls.extend(gallery::stale_urls(&app_url, build).await?); + } + let mut current = Vec::new(); + if let Some(project) = &project { + current = gallery::all_urls(&app_url, project).await?; + let previous: Vec = serde_json::from_value(project.gallery_urls.clone()).unwrap_or_default(); + urls.extend(previous.into_iter().filter(|u| !current.contains(u))); + } + Ok(Plan { urls: urls.into_iter().collect(), project, current }) + } + + /// Record a purge that used up its tries: an error in the log, and a row `/status` counts. + /// + /// # Errors + /// On a database error. + pub async fn record_failure(&self, error: &str) -> laravel::Result<()> { + tracing::error!(build_id = self.build_id, project_id = self.project_id, error, "gallery purge failed for good"); + let project_id = match (self.project_id, self.build_id) { + (Some(id), _) => Some(id), + (None, Some(build_id)) => Build::find(build_id).await?.map(|b| b.project_id), + (None, None) => None, + }; + let (build_id, urls) = (self.build_id, serde_json::json!(self.urls)); + db::query!( + "INSERT INTO gallery_purge_failures (project_id, build_id, urls, error) \ + VALUES ({project_id}, {build_id}, {urls}, {error})" + ) + .insert() + .await?; + Ok(()) + } +} + +#[job(name = "gallery.purge", tries = 5, backoff = [1.minutes(), 5.minutes(), 15.minutes(), 1.hours()])] +impl PurgeGallery { + async fn handle(self) -> laravel::Result<()> { + let Some(cloudflare) = configured() else { return Ok(()) }; + let plan = self.plan().await?; + if !plan.urls.is_empty() { + purge(&cloudflare, &plan.urls).await?; + tracing::info!(build_id = self.build_id, purged = plan.urls.len(), "gallery purged"); + } + if let Some(project) = plan.project { + let (id, current) = (project.id, serde_json::json!(plan.current)); + db::query!("UPDATE projects SET gallery_urls = {current} WHERE id = {id}").update().await?; + } + Ok(()) + } + + async fn failed(self, error: &laravel::Error) { + if let Err(e) = self.record_failure(&error.to_string()).await { + tracing::error!(error = %e, "recording a failed gallery purge failed"); + } + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs index 8afdb3a9..77b131e4 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -1,14 +1,23 @@ //! VisualCI's server on Laravel Rust. Who owns which module, and the seams between them, are in sc-8900. pub mod auth; +pub mod billing; pub mod config; +pub mod console; pub mod domain; +pub mod events; pub mod forge; +pub mod heartbeat; pub mod http; +pub mod jobs; pub mod listeners; +pub mod live; +pub mod mcp; pub mod models; +pub mod notify; #[path = "../database/seeders/mod.rs"] pub mod seeders; +pub mod skills; pub mod storage; pub mod testing; @@ -37,9 +46,13 @@ pub fn configure() -> ApplicationBuilder { config.app.env.is_production(), )?; http::hosts::check(config.section::(), config.app.env.is_production())?; + billing::check(config.section::(), config.app.env.is_production())?; Ok(()) }) .with_middleware(|middleware, _| { + if let Err(e) = middleware.try_trust_proxies(config::trusted_proxies()) { + tracing::error!(error = %e, "TRUSTED_PROXIES: trusting no proxies"); + } middleware.prepend(http::hosts::route_by_host); // The site's signed-in hint is read by its script: plain, not encrypted middleware.replace(laravel::cookie::EncryptCookies::except([auth::sign_in::SIGNED_IN_HINT])); @@ -49,6 +62,27 @@ pub fn configure() -> ApplicationBuilder { middleware.trust_hosts(["*"]); }) .with_routing(|routing, _| { - routing.web(auth::routes).api(http::api::routes).health("/up"); + routing + .web(auth::routes) + .api(http::api::routes) + .routes(|route| { + route.post("/webhooks/stripe", billing::webhook::handle); + route.get("/status", http::status::status); + // MCP clients: a person's OAuth token (the guard joins with the OAuth server, #57) or a personal + // or project token. + route.any("/mcp", mcp::handle); + // GitHub sends deliveries of up to 25 MB + route + .post("/webhooks/github", forge::webhooks::github) + .middleware(laravel::http::middleware::LimitBody::megabytes(25)); + }) + .routes(http::renderer::routes) + .routes(http::gallery::routes) + .health("/up"); + }) + .with_commands(|commands, _| { + commands.add::(); + commands.add::(); + commands.add::(); }) } diff --git a/app/src/listeners/mod.rs b/app/src/listeners/mod.rs index 9fa846c0..97ccbb14 100644 --- a/app/src/listeners/mod.rs +++ b/app/src/listeners/mod.rs @@ -1,4 +1,4 @@ -//! Listeners for the auth side's events (sc-8900). +//! Listeners for the domain's and the auth side's events (sc-8900). use laravel::event::{Event, listener}; @@ -12,3 +12,20 @@ pub async fn give_new_users_an_organization(event: Event) -> laravel:: Organization::create_personal(&user).await?; Ok(()) } + +/// A default-branch CI build changed: Cloudflare's copies of the gallery URLs it touches are purged in the background, +/// when purges are configured. +#[listener] +pub async fn purge_the_gallery(event: Event) -> laravel::Result<()> { + if crate::jobs::purge_gallery::configured().is_none() { + return Ok(()); + } + let Some(build) = crate::models::Build::find(event.build_id).await? else { return Ok(()) }; + if build.mode != "ci" { + return Ok(()); + } + crate::jobs::purge_gallery::PurgeGallery { build_id: Some(build.id), project_id: None, urls: vec![] } + .dispatch() + .await?; + Ok(()) +} diff --git a/app/src/live.rs b/app/src/live.rs new file mode 100644 index 00000000..e12b3d12 --- /dev/null +++ b/app/src/live.rs @@ -0,0 +1,226 @@ +//! Live updates between replicas (sc-8897, sc-8900): Postgres LISTEN/NOTIFY, fanned out in each process to whoever is +//! streaming server-sent events (`EventStream`) to a browser or the CLI's `--wait`. No WebSockets and no broadcaster +//! service: the database every replica already shares carries the signal. +//! +//! - [`notify`] sends a topic, such as `build:42`. Inside a transaction, Postgres delivers it on commit, so nobody is +//! told about a change they can't read yet. +//! - [`subscribe`] gets every topic sent from now on, from any replica. One connection per process LISTENs; it starts +//! with the first subscriber. +//! - A notification only says "look again": the stream's handler reads the current state, so payloads never carry data +//! a subscriber mightn't be allowed to see. Whenever notifications may have been missed, subscribers get +//! [`EVERYTHING`] and must re-read everything they show: after the listener (re)connects, and when a subscriber falls +//! behind (`RecvError::Lagged`). +//! - Each process checks its own listener every minute: it notifies a probe topic over a separate connection and, when +//! the probe doesn't come back within ten seconds (a half-open connection that hears nothing), restarts the listener. +//! [`healthy`] says whether the last probe came back, for the process's health check; [`CheckLive`] pushes +//! `VISUALCI_LIVE_HEARTBEAT` from the queue worker the same way. +//! +//! The connection must reach Postgres directly or through a session-mode pooler: LISTEN doesn't work through a +//! transaction-mode PgBouncer. + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicI64, Ordering}; +use std::time::Duration; + +use laravel::db; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; +use sqlx::Connection; +use tokio::sync::{broadcast, watch}; + +/// The one Postgres channel; topics travel as its payloads. +pub const CHANNEL: &str = "visualci_live"; +/// What subscribers get when they may have missed something: re-read everything. +pub const EVERYTHING: &str = "*"; +/// Postgres refuses payloads of 8000 bytes or more; topics are far shorter. +pub const MAX_TOPIC: usize = 1000; +/// How often each process probes its listener, and how long a probe may take. +const PROBE_EVERY: Duration = Duration::from_secs(60); +const PROBE_WITHIN: Duration = Duration::from_secs(10); + +/// Where the listener connects: the application's database. +#[derive(Clone, laravel::config::Section)] +pub struct LiveDatabase { + #[env("DATABASE_URL")] + pub url: Option, +} + +/// Tell every replica's subscribers that `topic` changed (`build:42`, `project:7`). On commit, inside a transaction. +/// +/// # Errors +/// On a database error, or a topic longer than [`MAX_TOPIC`]. +pub async fn notify(topic: &str) -> laravel::Result<()> { + if topic.len() > MAX_TOPIC { + return Err(laravel::Error::msg(format!("a live topic of {} bytes; topics name what changed", topic.len()))); + } + db::query!("SELECT pg_notify({CHANNEL}, {topic})").statement().await?; + Ok(()) +} + +struct Hub { + tx: broadcast::Sender, + ready: watch::Receiver, +} + +static HUB: OnceLock = OnceLock::new(); +/// When this process's last probe came back (Unix seconds); 0 before the first. +static LAST_PROBE_OK: AtomicI64 = AtomicI64::new(0); + +fn hub(database_url: &str) -> &'static Hub { + HUB.get_or_init(|| { + let (tx, _) = broadcast::channel(1024); + let (ready_tx, ready) = watch::channel(false); + tokio::spawn(supervise(database_url.to_string(), tx.clone(), ready_tx)); + Hub { tx, ready } + }) +} + +/// Every topic sent from now on. The first call starts this process's listener on `database_url`. +pub fn subscribe(database_url: &str) -> broadcast::Receiver { + hub(database_url).tx.subscribe() +} + +/// Wait up to `within` for this process's listener to be LISTENing. `false` when it isn't by then. +pub async fn ready(database_url: &str, within: Duration) -> bool { + let mut ready = hub(database_url).ready.clone(); + tokio::time::timeout(within, ready.wait_for(|r| *r)).await.is_ok_and(|r| r.is_ok()) +} + +/// Whether this process's listener answered its last probe within the last three minutes. +#[must_use] +pub fn healthy() -> bool { + let last = LAST_PROBE_OK.load(Ordering::Relaxed); + last > 0 && laravel::now().timestamp().as_second() - last < 180 +} + +/// Keep a listener running, restarting it when it stops or when a probe doesn't come back. +async fn supervise(url: String, tx: broadcast::Sender, ready: watch::Sender) { + loop { + let listener = tokio::spawn(listen(url.clone(), tx.clone(), ready.clone())); + let mut probes = tokio::time::interval(PROBE_EVERY); + probes.tick().await; + loop { + probes.tick().await; + if listener.is_finished() { + break; + } + if probe(&url, &tx).await { + LAST_PROBE_OK.store(laravel::now().timestamp().as_second(), Ordering::Relaxed); + } else { + tracing::warn!("live updates: a probe didn't come back; restarting the listener"); + break; + } + } + listener.abort(); + let _ = ready.send(false); + tokio::time::sleep(Duration::from_secs(1)).await; + } +} + +/// LISTEN, forwarding each payload. Tells subscribers to re-read everything after each (re)connection, since +/// notifications sent meanwhile are gone. Returns when the connection can't be used; `supervise` starts it again. +async fn listen(url: String, tx: broadcast::Sender, ready: watch::Sender) { + let mut wait = Duration::from_millis(500); + loop { + let connected = match sqlx::postgres::PgListener::connect(&url).await { + Ok(mut listener) => match listener.listen(CHANNEL).await { + Ok(()) => { + wait = Duration::from_millis(500); + let _ = ready.send(true); + let _ = tx.send(EVERYTHING.to_string()); + loop { + match listener.try_recv().await { + // No subscribers right now is fine: `send` only fails then + Ok(Some(n)) => drop(tx.send(n.payload().to_string())), + // The connection dropped and sqlx reconnected and LISTENs again: anything sent in between + // is lost + Ok(None) => drop(tx.send(EVERYTHING.to_string())), + Err(e) => { + tracing::warn!(error = %e, "live updates: the listener failed"); + break; + } + } + } + true + } + Err(e) => { + tracing::warn!(error = %e, "live updates: LISTEN failed"); + false + } + }, + Err(e) => { + tracing::warn!(error = %e, "live updates: can't connect"); + false + } + }; + let _ = ready.send(false); + if connected { + return; + } + tokio::time::sleep(wait).await; + wait = (wait * 2).min(Duration::from_secs(30)); + } +} + +/// Notify a fresh probe topic over a connection of its own and wait for this process's listener to hear it. +async fn probe(url: &str, tx: &broadcast::Sender) -> bool { + let mut rx = tx.subscribe(); + let topic = format!("probe:{}", laravel::str::random(12)); + let sent = async { + let mut connection = sqlx::PgConnection::connect(url).await?; + sqlx::query("SELECT pg_notify($1, $2)").bind(CHANNEL).bind(&topic).execute(&mut connection).await?; + connection.close().await + }; + match sent.await { + Ok(()) => arrives(&mut rx, &topic, PROBE_WITHIN).await, + Err(e) => { + tracing::warn!(error = %e, "live updates: the probe couldn't be sent"); + false + } + } +} + +/// Wait up to `within` for `topic` on `rx`, skipping others. `false` when it doesn't come (or the hub closed). +pub async fn arrives(rx: &mut broadcast::Receiver, topic: &str, within: Duration) -> bool { + tokio::time::timeout(within, async { + loop { + match rx.recv().await { + Ok(t) if t == topic => return true, + Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {} + Err(broadcast::error::RecvError::Closed) => return false, + } + } + }) + .await + .unwrap_or(false) +} + +/// Every minute in the queue worker: wait for its listener to be ready, notify a probe topic through the application's +/// database, check the listener hears it, and push the heartbeat. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct CheckLive; + +#[job] +impl CheckLive { + async fn handle(self, database: laravel::config::Section) -> laravel::Result<()> { + let Some(url) = database.url.as_deref().filter(|u| !u.is_empty()) else { return Ok(()) }; + let mut rx = subscribe(url); + let health = if ready(url, PROBE_WITHIN).await { + let probe = format!("probe:{}", laravel::str::random(12)); + match notify(&probe).await { + Err(e) => Err(e.to_string()), + Ok(()) if arrives(&mut rx, &probe, PROBE_WITHIN).await => Ok(()), + Ok(()) => Err("a notification didn't arrive within 10 seconds".to_string()), + } + } else { + Err("the listener isn't LISTENing".to_string()) + }; + crate::heartbeat::push("VISUALCI_LIVE_HEARTBEAT", health.clone()).await; + health.map_err(laravel::Error::msg) + } +} + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(CheckLive).every_minute().without_overlapping(); +} diff --git a/app/src/mcp/args.rs b/app/src/mcp/args.rs new file mode 100644 index 00000000..eaf8239f --- /dev/null +++ b/app/src/mcp/args.rs @@ -0,0 +1,493 @@ +//! The MCP tools' arguments, as their JSON schemas describe them to agents. + +#![allow(clippy::doc_markdown)] + +use schemars::JsonSchema; +use serde::Deserialize; + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct NoArgs {} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct SkillArgs { + /// A skill's name, such as `visualci-circleci`. Leave it out to list the skills. + #[serde(default)] + pub name: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct OrgArgs { + /// The organization's slug. + pub org: String, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct InviteArgs { + /// The organization's slug. + pub org: String, + /// An email address, or a GitHub login (`octocat` or `@octocat`). + pub invitee: String, + /// `admin` (settings, projects, tokens, billing, members), `member` (send builds, review and approve) or `read`. + pub role: InviteRole, +} + +/// A member's role, lowest first. +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum InviteRole { + /// Sees builds and snapshots; changes nothing. + Read, + /// Everything a build needs: uploads, review and approval. + Member, + /// Also settings, projects, tokens, billing and members. + Admin, +} + +impl From for crate::auth::Role { + fn from(r: InviteRole) -> Self { + match r { + InviteRole::Read => Self::Read, + InviteRole::Member => Self::Member, + InviteRole::Admin => Self::Admin, + } + } +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct CreateOrgArgs { + /// Lowercase letters, digits and dashes; used in URLs. + pub slug: String, + pub name: String, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct CreateProjectArgs { + pub org: String, + /// Lowercase letters, digits and dashes; used in URLs. + pub slug: String, + pub name: String, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ProjectArgs { + /// `org/project`. Optional with a project token. + pub project: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct UpdateProjectArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + #[serde(flatten)] + pub change: crate::domain::projects::SettingsChange, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct CreateTokenArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// What the token is for, e.g. `CircleCI`. + pub name: String, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct DeleteTokenArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The token's id, from `get_project`. + pub token_id: i64, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ListBuildsArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// Only builds of this branch. + pub branch: Option, + /// How many, newest first (default 20, at most 100). + pub limit: Option, + /// Only builds whose changes wait for a review (a local build only for the person whose run it was). + pub waiting_for_review: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct BuildArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The build number (as in the build's URL) or its id. + pub build: BuildRef, + /// Also list unchanged snapshots (by default they're only counted). + #[serde(default)] + pub include_unchanged: bool, + /// Skip this many listed snapshots (for the next page). Default 0. + pub offset: Option, + /// List at most this many snapshots, 1 to 200. Default 30. Longer lists also come grouped by state and name + /// prefix, so a build with hundreds of new snapshots reads in one answer. + pub limit: Option, + /// `change` (the default): changed snapshots with the largest change first, then added, removed, failed and the + /// rest. `name`: by name. + #[serde(default)] + pub order: crate::domain::detail::ReviewOrder, +} + +/// A build, by number (`12`, `"12"` or `"#12"`) or id: agents send either a number or a string. +#[derive(Debug, Clone)] +pub struct BuildRef(String); + +impl<'de> Deserialize<'de> for BuildRef { + fn deserialize>(d: D) -> Result { + match serde_json::Value::deserialize(d)? { + serde_json::Value::String(s) => Ok(Self(s)), + serde_json::Value::Number(n) => Ok(Self(n.to_string())), + other => Err(serde::de::Error::custom(format!("build must be a number or a string, not {other}"))), + } + } +} + +impl JsonSchema for BuildRef { + fn schema_name() -> std::borrow::Cow<'static, str> { + "BuildRef".into() + } + + fn inline_schema() -> bool { + true + } + + fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema { + schemars::json_schema!({ "type": ["integer", "string"] }) + } +} + +impl std::ops::Deref for BuildRef { + type Target = str; + + fn deref(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for BuildRef { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct SnapshotArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The build number or id. + pub build: BuildRef, + /// The snapshot's name, as `get_build` lists it, or its `id` from `get_build`. + #[serde(default)] + pub name: String, + /// The snapshot's id, as `get_build` lists it: instead of `name` and `platform`. + pub id: Option, + /// The snapshot's platform. Optional when the name is on one platform only. + #[serde(default)] + pub platform: String, + /// Positions of the pages to include images for (from a previous answer). Default: the first three changed pages. + pub pages: Option>, + /// Which images to include: `all` (base, head, diff; the default), `diff`, `head`, `base`, or `none`. + /// For text, JSON and HTML: `head`, `base` or `all` adds that whole version's text. + pub images: Option, + /// Scale images down to this width in pixels (default 1200). Large ones come back as JPEG. + pub max_width: Option, + /// `changed` crops each image to the changed regions with a margin, for a close look at a small change on a tall + /// page. + pub crop: Option, + /// What the new side is compared with: `baseline` (the default, what review uses), `previous` (the newest earlier + /// build of this snapshot on the branch: did a fix answer a comment there?), or an earlier build's number on the + /// branch. Only `baseline` decides the review; the others are a view. + pub against: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ContactSheetArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The build number or id. + pub build: BuildRef, + /// Which snapshots, by state: comma-separated, from `changed`, `added`, `removed`, `unchanged`, `ignored` + /// (default `changed,added`). + pub states: Option, + /// Skip this many (for the next sheet). Default 0. + pub offset: Option, + /// How many per sheet, at most 48. Default 24. + pub limit: Option, + /// Thumbnails per row, 1 to 8. Default 4. + pub columns: Option, + /// `change` (the default): the largest change first, then added and removed. `name`: by name. + #[serde(default)] + pub order: crate::domain::detail::ReviewOrder, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ChangesetArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The pull request's number. + pub pr: Option, + /// A branch, instead of a pull request number. + pub branch: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct HistoryArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + pub name: String, + #[serde(default)] + pub platform: String, + /// Only builds of this branch. + pub branch: Option, + /// How many builds to look back (default 20, at most 200). + pub limit: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ReviewArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + pub build: BuildRef, + /// `approve` or `reject`. + pub action: String, + /// Snapshot names to review; all changed snapshots when left out. + pub snapshots: Option>, + /// Only the build's `added` (new) snapshots, only its `changed` ones, or only its `matching` ones (changes made + /// only of changes merged pull requests approved: `get_build`'s `matches`), in one call. Not with `snapshots`. + pub only: Option, + /// With `reject`: why, as a comment thread on each rejected snapshot (Markdown), so the next person or agent sees + /// what's wrong. Approving a snapshot with an open thread is refused until the thread is resolved. + pub comment: Option, + /// Why you approved or rejected, in a sentence. It's shown wherever the review appears (the build's + /// reviews, the pull request comment). A note, not a thread: it never blocks anything. + pub note: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ListCommentsArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// A build: its branch's threads are listed (threads follow the branch). + pub build: BuildRef, + /// Only this snapshot's threads (its name, or its id from `get_build`). + pub snapshot: Option, + #[serde(default)] + pub platform: String, + /// Also resolved threads. Default: open ones only. + #[serde(default)] + pub include_resolved: bool, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct PostCommentArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The build being looked at. + pub build: BuildRef, + /// To reply: the thread's id. Leave out to start a thread. + pub thread: Option, + /// To start a thread: the snapshot's name (or its id from `get_build`). + pub snapshot: Option, + #[serde(default)] + pub platform: String, + /// The page's position (from `get_snapshot`); leave out for the whole snapshot. + pub page: Option, + /// `head` (the new image, the default) or `base`. + pub side: Option, + /// Where on the image: `{"kind": "image"}` (the default), `{"kind": "point", "x": 410, "y": 96}` or + /// `{"kind": "box", "x": 120, "y": 80, "w": 300, "h": 140}`, in pixels of that side's image from its top left: + /// the same units as `regions` in `get_snapshot`, so a region can be pinned as it is. + pub anchor: Option, + /// Markdown. + pub body: String, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct CommentIdArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The comment's id. + pub comment: String, + /// The new text (Markdown), for `update_comment`. + pub body: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ResolveArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The thread's id. + pub thread: String, + /// `false` reopens it. Default `true`. + pub resolved: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct ReviewPageArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + pub build: BuildRef, + pub name: String, + #[serde(default)] + pub platform: String, + /// The page's position, from `get_snapshot`. + pub position: i32, + /// `variant` (both the old and the new page are fine: keep both as baselines) or `ignore` (ignore this exact + /// change in later builds too). + pub action: String, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct CreateBuildArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + /// The commit SHA the files come from. + pub commit: String, + pub branch: String, + pub pr_number: Option, + /// Ancestor commits, nearest first, for finding the baseline. + #[serde(default)] + pub parent_commits: Vec, + /// `ci` (the default) or `local` (a check from a laptop that never becomes a baseline). + pub mode: Option, + /// Builds with different names (e.g. `pdfs`, `browser`) keep separate baselines. Default `default`. + pub name: Option, + /// The build has only some of the project's snapshots; missing ones are carried forward, not removed. + #[serde(default)] + pub subset: bool, + /// Calls with the same nonce get the same build back (for parallel shards). + pub nonce: Option, + /// Where the build runs: `ci` (the default), `local-mac`, `local-linux`. Screenshots keep a baseline set per + /// environment; documents and text share one. + pub environment: Option, + /// The repository's visualci.yml as JSON (the CLI sends it). Its fields override the project's settings for this + /// build; ignore rules must each name their snapshots. + pub config: Option, + /// How many shards will finalize the build (default 1). + pub shard_total: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct UploadFile { + /// The snapshot's name, unique in the build (e.g. the test's name). + pub name: String, + /// For screenshots: the browser or device, so each platform keeps its own baseline. + #[serde(default)] + pub platform: String, + /// The file's bytes, base64. PDFs, PNG, JPEG or WebP images, or text (plain text, JSON, HTML, a serialized + /// component tree). + pub content_base64: String, + /// The file's name or extension (e.g. `invoice.pdf`, `.png`, `response.json`), to tell images from text and JSON + /// or HTML from plain text. + pub filename: Option, + /// Text: `text`, `json` or `html`, overriding the file name. JSON is compared with keys sorted, HTML with + /// attributes sorted and whitespace collapsed. + pub format: Option, + /// The diff threshold (0 to 1), overriding the project's: 0 is exact, above 0 a perceptual colour threshold. + pub threshold: Option, + /// Documents: `pdfbox` or `mutool`, overriding the project's renderer. + pub engine: Option, + /// Anything to keep with the snapshot (test file, URL, viewport). + pub meta: Option, + /// Text: values to ignore in this snapshot only, `{json_paths, text_patterns}`, on top of the visualci.yml's or + /// project's rules. + pub ignore: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct UploadArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + pub build: BuildRef, + pub files: Vec, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct FinalizeArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + pub build: BuildRef, + /// The shard that finished, when the build has several. + pub shard: Option, + /// True when the build may have no snapshots on purpose. Otherwise a build that was sent none fails. + pub allow_empty: Option, + /// Why it has none, like "inputs unchanged" (the CI run skipped the tests): implies allow_empty, and shows in the + /// build's summary with the build its baseline came from. + pub empty_reason: Option, +} + +// Standard Support level 1 (standardsupport.dev): the schema names every field and its choices, with no field +// descriptions (so these structs have plain comments, not doc comments, which would become descriptions). +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum SendAction { + Feedback, +} + +#[derive(Debug, serde::Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum FeedbackKind { + Bug, + Crash, + WrongResult, + Confusing, + MissingFeature, + Docs, + Question, + Other, +} + +#[derive(Debug, serde::Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Impact { + Blocked, + WorkedAround, + Friction, +} + +#[derive(Debug, serde::Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Source { + User, + Agent, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct SupportSendArgs { + pub action: SendAction, + pub title: Option, + pub kind: Option, + pub description: Option, + pub impact: Option, + pub task: Option, + pub request_ids: Option>, + pub tool: Option, + pub error: Option, + pub suggestion: Option, + pub source: Option, + pub session: Option, + /// The agent sending it, as an object such as `{name, version, model}`. + // An object schema, not a bare `true`: MCP clients built on the TypeScript SDK refuse the whole tool list when + // a property's schema isn't an object. + #[schemars(with = "Option>")] + pub agent: Option, + pub idempotency_key: Option, +} + +#[derive(Debug, Deserialize, JsonSchema)] +pub struct DownloadArgs { + /// `org/project`. Optional with a project token. + pub project: Option, + pub build: BuildRef, + /// Which snapshots: `changed` (the default), `added`, `removed`, `unchanged`, or `all`. + pub state: Option, + /// Which images of each page: `base`, `head`, `diff`, `regions` (the head cropped to the changes). Default: base, + /// head and diff. + pub sides: Option>, + /// Only snapshots whose name matches this glob, like `v2/pdfjs/**`. + pub glob: Option, + /// Seconds to wait for the archive (default 50, at most 60). Not ready by then: call again with the same arguments. + pub wait: Option, +} diff --git a/app/src/mcp/context.rs b/app/src/mcp/context.rs new file mode 100644 index 00000000..6ce257bb --- /dev/null +++ b/app/src/mcp/context.rs @@ -0,0 +1,25 @@ +//! Running MCP tools inside Laravel's request context. +//! +//! rmcp's Streamable HTTP service runs each tool call on a task of its own, where Laravel's task-local context (the +//! database connection, the container, the config) is gone. The `/mcp` handler puts the request's context into the +//! HTTP request's extensions ([`carry`]), and `call_tool` runs the tool inside it ([`of`]). +//! +//! A workaround until a framework release mounts a tower service on a route with the context in place +//! (laravel/rust-framework#520, `routing::service`). Once that's released, this module goes and `/mcp` mounts rmcp's +//! service directly. + +use laravel::context::Context; +use rmcp::service::{RequestContext, RoleServer}; + +/// Put the current Laravel context into the request, for the tool calls rmcp makes from it. +pub fn carry(request: &mut axum::extract::Request) { + if let Some(context) = Context::current() { + request.extensions_mut().insert(context); + } +} + +/// The Laravel context of the HTTP request an MCP call came in on. +#[must_use] +pub fn of(rc: &RequestContext) -> Option { + rc.extensions.get::().and_then(|p| p.extensions.get::().cloned()) +} diff --git a/app/src/mcp/images.rs b/app/src/mcp/images.rs new file mode 100644 index 00000000..13936f56 --- /dev/null +++ b/app/src/mcp/images.rs @@ -0,0 +1,173 @@ +//! Images for MCP answers, sized for an agent to read: scaled to a width, optionally cropped to what changed, and +//! re-encoded as JPEG when a PNG would be large. And contact sheets: many snapshots' thumbnails in one image. + +use image::{DynamicImage, GenericImageView, ImageFormat, Rgba, RgbaImage, imageops::FilterType}; +use visualci_core::diff::Region; + +/// The default width of images in answers. +pub const DEFAULT_MAX_WIDTH: u32 = 1200; +/// Margin around the changed regions when cropping. +const CROP_MARGIN: u32 = 32; +/// A PNG bigger than this goes out as JPEG instead. +const PNG_LIMIT: usize = 300_000; + +/// The smallest rectangle around all the regions, with a margin, inside `width` × `height`. +pub fn crop_box(regions: &[Region], width: u32, height: u32) -> Option { + let first = regions.first()?; + let (mut x0, mut y0, mut x1, mut y1) = (first.x, first.y, first.x + first.width, first.y + first.height); + for r in ®ions[1..] { + x0 = x0.min(r.x); + y0 = y0.min(r.y); + x1 = x1.max(r.x + r.width); + y1 = y1.max(r.y + r.height); + } + let x0 = x0.saturating_sub(CROP_MARGIN).min(width.saturating_sub(1)); + let y0 = y0.saturating_sub(CROP_MARGIN).min(height.saturating_sub(1)); + let x1 = (x1 + CROP_MARGIN).min(width).max(x0 + 1); + let y1 = (y1 + CROP_MARGIN).min(height).max(y0 + 1); + Some(Region { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }) +} + +/// An image ready for an answer: cropped (when a box is given), scaled down to `max_width`, and encoded as PNG, or as +/// JPEG when the PNG would be large. Returns the bytes and their media type. Bytes that don't decode go out as they +/// are. +pub fn prepare(bytes: &[u8], crop: Option<&[Region]>, max_width: u32) -> (Vec, &'static str) { + let Ok(mut img) = visualci_core::image_hash::decode(bytes) else { return (bytes.to_vec(), "image/png") }; + if let Some(regions) = crop + && let Some(b) = crop_box(regions, img.width(), img.height()) + { + img = img.crop_imm(b.x, b.y, b.width, b.height); + } + if img.width() > max_width { + let height = (u64::from(img.height()) * u64::from(max_width) / u64::from(img.width())).max(1); + img = img.resize_exact(max_width, u32::try_from(height).unwrap_or(u32::MAX), FilterType::Triangle); + } + encode(&img) +} + +/// The image cropped to its changed regions (with a margin) at full size, as PNG: a bulk download's `regions` file. +/// `None` when the bytes don't decode or there are no regions. +pub fn crop_png(bytes: &[u8], regions: &[Region]) -> Option> { + let img = visualci_core::image_hash::decode(bytes).ok()?; + let b = crop_box(regions, img.width(), img.height())?; + let mut png = std::io::Cursor::new(Vec::new()); + img.crop_imm(b.x, b.y, b.width, b.height).write_to(&mut png, ImageFormat::Png).ok()?; + Some(png.into_inner()) +} + +fn encode(img: &DynamicImage) -> (Vec, &'static str) { + let mut png = std::io::Cursor::new(Vec::new()); + if img.write_to(&mut png, ImageFormat::Png).is_ok() && png.get_ref().len() <= PNG_LIMIT { + return (png.into_inner(), "image/png"); + } + let mut jpeg = std::io::Cursor::new(Vec::new()); + let rgb = DynamicImage::ImageRgb8(img.to_rgb8()); + let encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 80); + if rgb.write_with_encoder(encoder).is_ok() { + return (jpeg.into_inner(), "image/jpeg"); + } + (png.into_inner(), "image/png") +} + +/// Thumbnails laid out in a grid, left to right and top to bottom, `columns` wide, in a `width`-pixel image. Each +/// cell has a thin border so neighbouring white pages stay apart. Missing images leave their cell grey. +pub fn contact_sheet(images: &[Option>], columns: u32, width: u32) -> (Vec, &'static str) { + let columns = columns.clamp(1, 8); + let gap = 8u32; + let cell_w = (width.saturating_sub(gap * (columns + 1)) / columns).max(32); + // Cells are as tall as the tallest thumbnail in their row, capped at twice their width. + let thumbs: Vec> = images + .iter() + .map(|b| { + b.as_ref().and_then(|b| visualci_core::image_hash::decode(b).ok()).map(|img| { + let h = (u64::from(img.height()) * u64::from(cell_w) / u64::from(img.width().max(1))).max(1); + let h = u32::try_from(h).unwrap_or(u32::MAX).min(cell_w * 2); + img.resize(cell_w, h, FilterType::Triangle) + }) + }) + .collect(); + let rows = (u32::try_from(thumbs.len()).unwrap_or(0)).div_ceil(columns).max(1); + let row_heights: Vec = (0..rows) + .map(|r| { + (0..columns) + .filter_map(|c| thumbs.get((r * columns + c) as usize)) + .map(|t| t.as_ref().map_or(cell_w / 2, |t| t.height())) + .max() + .unwrap_or(cell_w / 2) + }) + .collect(); + let height = row_heights.iter().sum::() + gap * (rows + 1); + let mut sheet = RgbaImage::from_pixel(width, height, Rgba([246, 247, 249, 255])); + let mut y = gap; + for (r, row_h) in row_heights.iter().enumerate() { + for c in 0..columns { + let i = r * columns as usize + c as usize; + if i >= thumbs.len() { + break; + } + let x = gap + c * (cell_w + gap); + let (w, h) = thumbs[i].as_ref().map_or((cell_w, cell_w / 2), |t| t.dimensions()); + // Border, then the thumbnail (or grey when there's none). + for bx in x.saturating_sub(1)..(x + w + 1).min(width) { + for by in y.saturating_sub(1)..(y + h + 1).min(height) { + sheet.put_pixel(bx, by, Rgba([200, 204, 212, 255])); + } + } + match &thumbs[i] { + Some(t) => image::imageops::overlay(&mut sheet, &t.to_rgba8(), i64::from(x), i64::from(y)), + None => { + for bx in x..(x + w).min(width) { + for by in y..(y + h).min(height) { + sheet.put_pixel(bx, by, Rgba([225, 228, 233, 255])); + } + } + } + } + } + y += row_h + gap; + } + encode(&DynamicImage::ImageRgba8(sheet)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn png(w: u32, h: u32) -> Vec { + let img = RgbaImage::from_pixel(w, h, Rgba([10, 20, 30, 255])); + let mut out = std::io::Cursor::new(Vec::new()); + DynamicImage::ImageRgba8(img).write_to(&mut out, ImageFormat::Png).unwrap(); + out.into_inner() + } + + #[test] + fn scales_down_to_the_width() { + let (bytes, _) = prepare(&png(2400, 1000), None, 1200); + let img = image::load_from_memory(&bytes).unwrap(); + assert_eq!((img.width(), img.height()), (1200, 500)); + let (bytes, _) = prepare(&png(400, 100), None, 1200); + assert_eq!(image::load_from_memory(&bytes).unwrap().width(), 400, "small images aren't scaled up"); + } + + #[test] + fn crops_to_the_changed_regions_with_a_margin() { + let regions = + [Region { x: 100, y: 100, width: 10, height: 10 }, Region { x: 300, y: 150, width: 20, height: 5 }]; + assert_eq!(crop_box(®ions, 1000, 1000), Some(Region { x: 68, y: 68, width: 284, height: 119 })); + // Clamped to the image. + let edge = [Region { x: 0, y: 990, width: 10, height: 10 }]; + assert_eq!(crop_box(&edge, 1000, 1000), Some(Region { x: 0, y: 958, width: 42, height: 42 })); + let (bytes, _) = prepare(&png(1000, 1000), Some(®ions), 1200); + let img = image::load_from_memory(&bytes).unwrap(); + assert_eq!((img.width(), img.height()), (284, 119)); + } + + #[test] + fn a_contact_sheet_fits_its_width() { + let images = vec![Some(png(800, 600)), None, Some(png(400, 1600)), Some(png(1440, 900)), Some(png(10, 10))]; + let (bytes, _) = contact_sheet(&images, 4, 1200); + let img = image::load_from_memory(&bytes).unwrap(); + assert_eq!(img.width(), 1200); + assert!(img.height() > 200 && img.height() < 2000, "{}", img.height()); + } +} diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs new file mode 100644 index 00000000..264185f0 --- /dev/null +++ b/app/src/mcp/mod.rs @@ -0,0 +1,2288 @@ +//! The MCP server at `/mcp` (Streamable HTTP, stateless), for coding agents. It can do everything the web app and +//! the CI API can, except buy credits (a person adds a card and decides what to spend): organizations, projects and +//! their settings, project tokens, builds (create, upload, finalize), the comparison of each snapshot page by page +//! (base, head and diff images, regions, text diffs), snapshot history, and reviews, down to single pages. +//! +//! Who a request acts for is an [`auth::Principal`](crate::auth::Principal): a person (an MCP client's OAuth token, or +//! a personal access token `vcu_...`) or a project token (`vci_...`, that one project). + +pub mod args; +pub mod context; +pub mod images; +pub mod schema; + +use std::sync::OnceLock; + +use axum::response::{IntoResponse, Response}; +use base64::Engine; +use laravel::db; +use rmcp::{ + ErrorData, ServerHandler, + handler::server::{router::tool::ToolRouter, wrapper::Parameters}, + model::{CallToolResult, ContentBlock as Content, Implementation, ServerCapabilities, ServerConfig}, + service::{RequestContext, RoleServer}, + tool, tool_handler, tool_router, + transport::streamable_http_server::{ + StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager, + }, +}; +use serde_json::json; +use tower::ServiceExt; + +use self::args::*; +use crate::auth::{Principal, Role}; +use crate::domain::{self, build_settings::BuildSettings, builds::Invalid, comments, detail, snapshots as snaps}; +use crate::http::api::builds::{BuildResponse, app_url, renderer_version}; +use crate::models::{Build, Organization, Project, Snapshot}; +use crate::storage::BlobStore; + +const INSTRUCTIONS: &str = "VisualCI compares the PDFs, screenshots and images a test suite produces with approved \ +baselines, page by page. After a CI run: `list_builds`, then `get_build` for the changed snapshots, then \ +`get_snapshot` to look at a changed snapshot's pages (base, head and diff images, the changed regions, and the page's \ +text diff). Fix the code when a change is a regression. Approve with `review` (or `review_page` for one page) only \ +when the person you work for asked for the change. You can also run a comparison yourself (`create_build`, \ +`upload_snapshots`, `finalize_build`), manage organizations, projects, settings and tokens, and read each organization's plan and usage. \ +To set VisualCI up in a CI provider or test tool, or write visualci.yml, read the matching skill with `get_skill` first. Choosing a plan and paying are left to a person. Projects are named `org/project`; with a project token you can leave `project` out. \ +`whoami` lists the newest builds waiting for a review (`list_builds` with `waiting_for_review` lists a project's): \ +on a repository that pushes straight to main, review your push's build there. \ +When something about VisualCI got in your way (a confusing error, a missing feature, a bug you worked around), send it \ +with support_send, action feedback."; + +/// At most this many pages' images go into one `get_snapshot` answer, unless pages are named. +const DEFAULT_IMAGE_PAGES: usize = 3; +/// At most this many bytes of files in one `upload_snapshots` call (after base64 decoding). +const MAX_UPLOAD_BYTES: usize = 64 * 1024 * 1024; + +#[derive(Clone)] +pub struct VisualCi { + tool_router: ToolRouter, +} + +impl Default for VisualCi { + fn default() -> Self { + Self::new() + } +} + +/// An enum's snake_case name, as the spec spells the choices. +fn choice(v: Option<&T>) -> Option { + v.and_then(|v| serde_json::to_value(v).ok()).and_then(|v| v.as_str().map(str::to_string)) +} + +fn tool_error(message: impl Into) -> CallToolResult { + CallToolResult::error(vec![Content::text(message.into())]) +} + +fn internal(e: impl std::fmt::Display) -> ErrorData { + ErrorData::internal_error(e.to_string(), None) +} + +/// A JSON value with every object's keys in order. This app's JSON maps keep insertion order, and agents (and the +/// golden files) read the answers as they've always been: keys sorted. +fn sorted(value: serde_json::Value) -> serde_json::Value { + match value { + serde_json::Value::Object(map) => { + let mut entries: Vec<(String, serde_json::Value)> = map.into_iter().collect(); + entries.sort_by(|a, b| a.0.cmp(&b.0)); + serde_json::Value::Object(entries.into_iter().map(|(k, v)| (k, sorted(v))).collect()) + } + serde_json::Value::Array(items) => serde_json::Value::Array(items.into_iter().map(sorted).collect()), + other => other, + } +} + +/// A tool's structured answer, keys sorted ([`sorted`]). +fn structured(value: serde_json::Value) -> CallToolResult { + CallToolResult::structured(sorted(value)) +} + +/// A domain call's client mistake as a tool error, the server's as an internal error. +fn outcome(r: domain::builds::Outcome) -> Result, ErrorData> { + match r { + Ok(v) => Ok(Ok(v)), + Err(Ok(Invalid::Message(m) | Invalid::Conflict(m))) => Ok(Err(tool_error(m))), + Err(Err(e)) => Err(internal(e)), + } +} + +/// Who sent the request (the handler put it in the HTTP request's extensions). +fn principal_of(rc: &RequestContext) -> Option { + rc.extensions.get::().and_then(|p| p.extensions.get::().cloned()) +} + +fn user_id(rc: &RequestContext) -> Option { + principal_of(rc).and_then(|p| p.user().map(|u| u.id)) +} + +/// Kind, fingerprint and content type of an uploaded file, as the CLI works them out. +fn classify(filename: Option<&str>, bytes: &[u8]) -> Result<(&'static str, String, &'static str), String> { + if bytes.starts_with(b"%PDF") { + return Ok(("document", visualci_core::pdf::fingerprint_bytes(bytes).document, "application/pdf")); + } + let ext = filename.and_then(|f| f.rsplit('.').next()).unwrap_or("").to_ascii_lowercase(); + let image_type = match ext.as_str() { + "png" => Some("image/png"), + "jpg" | "jpeg" => Some("image/jpeg"), + "webp" => Some("image/webp"), + _ if bytes.starts_with(b"\x89PNG") => Some("image/png"), + _ if bytes.starts_with(b"\xff\xd8\xff") => Some("image/jpeg"), + _ => None, + }; + if let Some(content_type) = image_type { + let fp = visualci_core::image_hash::fingerprint_bytes(bytes).map_err(|e| format!("decoding the image: {e}"))?; + return Ok(("image", fp, content_type)); + } + let format = visualci_core::snapshot_text::Format::detect(None, None, filename); + Ok(("text", visualci_core::sha256_hex(bytes), format.content_type())) +} + +/// `let Some(x) = ... else return tool_error` for the `Result, ErrorData>` helpers. +macro_rules! need { + ($e:expr) => { + match $e.await? { + Ok(v) => v, + Err(message) => return Ok(tool_error(message)), + } + }; +} + +/// `?` for a domain call that answers `Ok(Err(message))` for the caller's mistake. +macro_rules! refuse { + ($e:expr) => { + match $e.await.map_err(internal)? { + Ok(v) => v, + Err(message) => return Ok(tool_error(message)), + } + }; +} + +impl VisualCi { + #[must_use] + pub fn new() -> Self { + let mut tool_router = Self::tool_router(); + schema::normalize_router(&mut tool_router); + Self { tool_router } + } + + async fn organization_of(project: &Project) -> Result { + Organization::find_or_fail(project.organization_id).await.map_err(internal) + } + + /// The caller's role in a project's organization: a person's membership; a project token acts for its own project + /// as a member would (sends builds, reviews, comments), never as an admin (no tokens, settings or members: a CI + /// secret that leaks must not mint itself new tokens or loosen the project's checks). + async fn role_in(rc: &RequestContext, project: &Project) -> Result, ErrorData> { + match principal_of(rc) { + Some(p) => p.role_in(project).await.map_err(internal), + None => Ok(None), + } + } + + /// `Err(message)` unless the caller's role is at least `needed`. + async fn need_role( + rc: &RequestContext, + project: &Project, + needed: Role, + what: &str, + ) -> Result, ErrorData> { + let role = Self::role_in(rc, project).await?; + if role.is_some_and(|r| r >= needed) { + return Ok(Ok(())); + } + let who = match needed { + Role::Admin => "an admin", + Role::Member => "a member (not read-only)", + Role::Read => "a member", + }; + Ok(Err(format!( + "only {who} of the organization can {what}; you're {}", + role.map_or("not a member", Role::as_str) + ))) + } + + /// Why a project token can't approve in this project (its `tokens_can_approve` is off), else `None`. + fn tokens_may_not_approve(rc: &RequestContext, project: &Project) -> Option { + (matches!(principal_of(rc), Some(Principal::Project { .. })) && !project.tokens_can_approve).then(|| { + "this project keeps approving with people: a project token can't approve, accept a variant or ignore a \ + change (rejecting and commenting still work); a person approves in the web app, or with their own \ + token" + .to_string() + }) + } + + /// The project a tool works on: `org/project`, or the project token's own project. + async fn project(rc: &RequestContext, arg: Option<&str>) -> Result, ErrorData> { + let Some(principal) = principal_of(rc) else { return Ok(Err("missing token".into())) }; + match principal { + Principal::Project { project_id, .. } => { + let p = Project::find_or_fail(project_id).await.map_err(internal)?; + if let Some(arg) = arg { + let own = format!("{}/{}", Self::organization_of(&p).await?.slug, p.slug); + if arg != own && arg != p.slug { + return Ok(Err(format!("this project token is for {own}, not {arg}"))); + } + } + Ok(Ok(p)) + } + Principal::User { .. } => { + let Some(arg) = arg else { + return Ok(Err("name the project as `org/project` (list_organizations lists them)".into())); + }; + let Some((org_slug, project_slug)) = arg.split_once('/') else { + return Ok(Err(format!("name the project as `org/project`, not {arg:?}"))); + }; + let not_found = || Err(format!("no project {arg} that you can see")); + let Some(p) = crate::http::api::project_by_slugs(org_slug, project_slug).await.map_err(internal)? + else { + return Ok(not_found()); + }; + // A public project (the demo) can be read by anyone; writes still need a role (`need_role`). + if !p.public && principal.role_in(&p).await.map_err(internal)?.is_none() { + return Ok(not_found()); + } + Ok(Ok(p)) + } + } + } + + /// How a review was made besides its person, for "Approved by Claude Code for Ada". + fn via(rc: &RequestContext) -> domain::reviews::Via { + let parts = rc.extensions.get::(); + let header = parts + .and_then(|p| p.headers.get("x-agent")) + .and_then(|v| v.to_str().ok()) + .map(|v| v.trim().chars().take(100).collect::()) + .filter(|v| !v.is_empty()); + let peer = rc.peer.peer_info().map(|i| { + let c = &i.client_info; + format!("{} {}", c.name, c.version).trim().chars().take(100).collect::() + }); + let agent = header.or(peer).filter(|a| !a.is_empty()); + match principal_of(rc) { + Some(Principal::User { via: crate::auth::Via::OAuth { client_id }, .. }) => { + let client = parts.and_then(|p| p.extensions.get::()).map(|c| c.0.clone()); + domain::reviews::Via { source: "oauth", client: client.or(Some(client_id)), agent, token: None } + } + Some(Principal::User { via: crate::auth::Via::Token { name, .. }, .. }) => { + domain::reviews::Via { source: "personal_token", client: None, agent, token: Some(name) } + } + Some(Principal::Project { token_name, .. }) => { + domain::reviews::Via { source: "project_token", client: None, agent, token: Some(token_name) } + } + _ => domain::reviews::Via { source: "personal_token", client: None, agent, token: None }, + } + } + + /// Who's commenting: an agent (an MCP call), acting for its person or project token. + fn author(rc: &RequestContext) -> comments::Author { + let via = Self::via(rc); + comments::Author { + user_id: user_id(rc), + agent: Some(via.agent.or(via.client).unwrap_or_else(|| "an agent".to_string())), + } + } + + /// Each project's branches with open comment threads: `[{project, branch, open}]`. + async fn open_threads(projects: &[Project]) -> Result, ErrorData> { + let mut out = Vec::new(); + for p in projects { + let org = Self::organization_of(p).await?.slug; + for (branch, open) in comments::open_by_branch(p.id).await.map_err(internal)? { + out.push(json!({ "project": format!("{org}/{}", p.slug), "branch": branch, "open": open })); + } + } + Ok(out) + } + + /// An organization the caller may see, with the caller's role as text: `admin`, `member` or `read`, or `project` + /// for a project token's own organization. + async fn org( + rc: &RequestContext, + slug: &str, + ) -> Result, ErrorData> { + let Some(principal) = principal_of(rc) else { return Ok(Err("missing token".into())) }; + let not_found = || Err(format!("no organization {slug} that this token can see")); + let Some(org) = Organization::query().filter(Organization::slug.eq(slug)).first().await.map_err(internal)? + else { + return Ok(not_found()); + }; + match principal { + Principal::User { user, .. } => match Self::role_of(org.id, user.id).await? { + Some(role) => Ok(Ok((org, role.as_str().to_string()))), + None => Ok(not_found()), + }, + Principal::Project { project_id, .. } => { + let project = Project::find_or_fail(project_id).await.map_err(internal)?; + if project.organization_id == org.id { Ok(Ok((org, "project".into()))) } else { Ok(not_found()) } + } + } + } + + /// A person's role in an organization. + async fn role_of(organization_id: i64, user_id: i64) -> Result, ErrorData> { + let role: Option = db::query!( + "SELECT role FROM memberships WHERE organization_id = {organization_id} AND user_id = {user_id}" + ) + .scalar() + .await + .map_err(internal)?; + Ok(role.as_deref().and_then(Role::parse)) + } + + /// A person's organizations, by slug. + async fn organizations_of(user_id: i64) -> Result, ErrorData> { + db::query!( + "SELECT o.* FROM organizations o JOIN memberships m ON m.organization_id = o.id \ + WHERE m.user_id = {user_id} ORDER BY o.slug" + ) + .select_as() + .await + .map_err(internal) + } + + /// An organization's projects, by slug. + async fn projects_of(organization_id: i64) -> Result, ErrorData> { + Project::query() + .filter(Project::organization_id.eq(organization_id)) + .order_by(Project::slug.asc()) + .get() + .await + .map_err(internal) + } + + /// What the caller runs as, for whoami: the token's name, or the MCP client's. + fn via_json(rc: &RequestContext) -> serde_json::Value { + let Some(principal) = principal_of(rc) else { return serde_json::Value::Null }; + // The words reviews record (`domain::reviews::Via::source`). + let client = principal.client(); + let source = match client.source { + "mcp" => "oauth", + "token" => "personal_token", + other => other, + }; + match client.token_name { + Some(name) => json!({ "source": source, "token_name": name }), + None => { + let parts = rc.extensions.get::(); + let name = parts.and_then(|p| p.extensions.get::()).map(|c| c.0.clone()); + json!({ "source": source, "client_name": name.or(client.client_id) }) + } + } + } + + /// For someone whose projects have no builds yet: the public demo project and its newest build, to look at with + /// `get_build` and `get_snapshot` before sending anything. + async fn demo_if_new(reachable: &[Project]) -> Result, ErrorData> { + let ids: Vec = reachable.iter().map(|p| p.id).collect(); + if !ids.is_empty() && Build::query().filter(Build::project_id.is_in(ids)).exists().await.map_err(internal)? { + return Ok(None); + } + let (org, slug) = (domain::demo::ORG, domain::demo::PROJECT); + let Some(demo) = crate::http::api::project_by_slugs(org, slug).await.map_err(internal)? else { + return Ok(None); + }; + if !demo.public { + return Ok(None); + } + let newest = domain::builds::recent(demo.id, None, false, 20) + .await + .map_err(internal)? + .into_iter() + .find(|b| b.conclusion.as_deref() == Some("changes")); + Ok(Some(json!({ + "project": format!("{org}/{slug}"), + "build": newest.as_ref().map(|b| b.number), + "url": format!("{}/{org}/{slug}", app_url()), + "note": "Your projects have no builds yet. This public demo shows what a review looks like: try get_build and get_snapshot on it (read-only).", + }))) + } + + /// A build in a list (sc-8891): only what tells builds apart, its counts (as words and as numbers) and whether + /// it's blocked. get_build has the rest. + async fn build_line( + organization: &Organization, + project: &Project, + b: &Build, + waits: bool, + ) -> Result { + let stats = domain::builds::stats(b); + let counts = [ + (stats.changed, "changed"), + (stats.added, "added"), + (stats.removed, "removed"), + (stats.failed, "failed"), + (stats.pending, "pending"), + ]; + let parts: Vec = counts.iter().filter(|(n, _)| *n > 0).map(|(n, what)| format!("{n} {what}")).collect(); + // "unchanged" only for a build that finished comparing: one still receiving (or failed) compared nothing yet. + let changes = match (parts.is_empty(), b.state.as_str()) { + (false, _) => parts.join(", "), + (true, "completed") => "unchanged".to_string(), + (true, _) => "not compared".to_string(), + }; + // Out of credits: why it wasn't compared, and what fixes it (null when it isn't blocked). + let blocked = BuildResponse::new(b, project, organization) + .with_blocked(b, project, organization) + .await + .map_err(internal)? + .blocked; + let mut v = json!({ + "number": b.number, + "branch": b.branch, + "commit": b.commit_sha, + "pr_number": b.pr_number, + "state": b.state, + "conclusion": b.conclusion, + "review_state": b.review_state, + "waiting_for_review": waits, + "changes": changes, + "stats": { + "changed": stats.changed, "added": stats.added, "removed": stats.removed, + "unchanged": stats.unchanged, "failed": stats.failed, + }, + "blocked": blocked, + "url": format!("{}/{}/{}/builds/{}", app_url(), organization.slug, project.slug, b.number), + "created_at": b.created_at.to_string(), + }); + if b.name != "default" { + v["name"] = json!(b.name); + } + if b.mode != "ci" { + v["mode"] = json!(b.mode); + } + Ok(v) + } + + async fn find_build(project: &Project, build: &str) -> Result, ErrorData> { + domain::builds::find_by_ref(project.id, build).await.map_err(internal) + } + + /// The build's snapshot with this name: on the given platform, or on its only platform when none is given. The + /// error says which platforms the name has when it's ambiguous or the platform is wrong. Snapshots the build reads + /// from an earlier build count. + async fn find_snapshot(build: &Build, name: &str, platform: &str) -> Result, ErrorData> { + // An id from `get_build` names one snapshot of the build. + if let Ok(pid) = laravel::str::Uuid::parse_str(name) { + return Ok(snaps::in_build(build.id, pid) + .await + .map_err(internal)? + .ok_or_else(|| format!("no snapshot {name} in build {}", build.number))); + } + let all = snaps::named_in_build(build.id, name).await.map_err(internal)?; + if let Some(s) = all.iter().find(|s| s.platform == platform) { + return Ok(Ok(s.clone())); + } + let platforms: Vec<&str> = all.iter().map(|s| s.platform.as_str()).collect(); + Ok(match (platform.is_empty(), platforms.as_slice()) { + (_, []) => Err(format!("no snapshot {name:?} in build {}", build.number)), + (true, [_]) => Ok(all[0].clone()), + (true, many) => Err(format!( + "{name:?} is in build {} on several platforms ({}): pass platform", + build.number, + many.join(", ") + )), + (false, found) => Err(format!( + "{name:?} isn't in build {} on platform {platform:?}; it is on {}", + build.number, + found + .iter() + .map(|p| if p.is_empty() { "no platform".to_string() } else { format!("{p:?}") }) + .collect::>() + .join(", ") + )), + }) + } + + /// A build as the tools show it. `member` is false for someone outside the organization reading a public + /// project, who doesn't see where a local build ran. + async fn build_json(project: &Project, build: &Build, member: bool) -> Result { + let organization = Self::organization_of(project).await?; + let response = BuildResponse::new(build, project, &organization) + .with_blocked(build, project, &organization) + .await + .map_err(internal)?; + let mut v = serde_json::to_value(response).map_err(internal)?; + v["name"] = json!(build.name); + v["branch"] = json!(build.branch); + v["commit"] = json!(build.commit_sha); + v["pr_number"] = json!(build.pr_number); + v["mode"] = json!(build.mode); + // Whether `review` can act on it now (it has finished comparing; review also waits up to a minute). + v["reviewable"] = json!(domain::builds::reviewable(build)); + v["environment"] = json!(build.environment); + v["environment_info"] = domain::builds::environment_info_for(build, member); + v["created_at"] = json!(build.created_at.to_string()); + // Who reviewed it and how: a person in the web app, or an agent for its person, or a project token. + v["reviews"] = json!(domain::reviews::shown(build.id, 10).await.map_err(internal)?); + // A large suite's groups (sc-8868): which matched their baselines and were carried forward unchanged. + if let Some(groups) = domain::groups::summary(build).await.map_err(internal)? { + v["groups"] = groups; + } + Ok(v) + } + + /// The newest builds of these projects whose changes wait for a review, at most 10: on a repository that pushes + /// straight to the default branch, nothing else would remind the agent that pushed. + /// A local build waits only for the person whose run it was (`user`; a project token sees none). + async fn waiting_for_review(reachable: &[Project], user: Option) -> Result, ErrorData> { + let ids: Vec = reachable.iter().map(|p| p.id).collect(); + if ids.is_empty() { + return Ok(Vec::new()); + } + let pending: Vec = Build::query() + .filter(Build::project_id.is_in(ids) & Build::review_state.eq("pending")) + .order_by(Build::id.desc()) + .limit(100) + .get() + .await + .map_err(internal)? + .into_iter() + .filter(|b| domain::builds::waits_for(b, user)) + .take(10) + .collect(); + let mut out = Vec::new(); + for b in pending { + let Some(project) = reachable.iter().find(|p| p.id == b.project_id) else { continue }; + let org = Self::organization_of(project).await?.slug; + out.push(json!({ + "project": format!("{org}/{}", project.slug), "build": b.number, "branch": b.branch, + "commit": b.commit_sha, + "url": format!("{}/{org}/{}/builds/{}", app_url(), project.slug, b.number), + })); + } + Ok(out) + } + + /// The build changed: its forge check, PR comment and live updates follow; and the older builds a review + /// superseded. + async fn changed(build: &Build) -> Result, ErrorData> { + crate::events::BuildChanged { build_id: build.id }.dispatch().await.map_err(internal)?; + let superseded = domain::reviews::supersede_older(build).await.map_err(internal)?; + for id in &superseded { + crate::events::BuildChanged { build_id: *id }.dispatch().await.map_err(internal)?; + } + Ok(superseded) + } +} + +/// A subdomains function's refusal (`abort_with(422 | 409 | 429, message)`) as the tool's error, with its message; +/// anything else is an internal error. +fn refusal(e: laravel::Error) -> Result { + if e.status().is_client_error() { Ok(e.to_string()) } else { Err(internal(e)) } +} + +/// The OAuth client's display name, when the request came through one (for "Approved by Claude Code for Ada"). +#[derive(Clone, Debug)] +pub struct ClientName(pub String); + +#[tool_router] +impl VisualCi { + #[tool( + description = "VisualCI's agent skills: setting VisualCI up in each CI provider and test tool, reviewing builds, local runs and visualci.yml. Without `name`, lists them; with it, returns that skill's SKILL.md.", + annotations(title = "Get a skill", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn get_skill(&self, Parameters(args): Parameters) -> Result { + let Some(name) = args.name else { + let list: Vec<_> = crate::skills::all() + .into_iter() + .map(|s| json!({ "name": s.name, "description": s.description })) + .collect(); + return Ok(structured(json!({ "skills": list }))); + }; + match crate::skills::get(&name) { + Some(skill) => Ok(CallToolResult::success(vec![Content::text(skill.text)])), + None => Ok(tool_error(format!("no skill {name}; call get_skill without a name to list them"))), + } + } + + #[tool( + description = "Who this token belongs to (a person or a project), how it reached VisualCI (`via`: `source` as reviews record it, `personal_token`, `project_token`, `oauth` or `web`, with the token's or the MCP client's name), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", + annotations(title = "Who am I", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn whoami( + &self, + Parameters(_): Parameters, + rc: RequestContext, + ) -> Result { + let via = Self::via_json(&rc); + match principal_of(&rc) { + Some(Principal::User { user, .. }) => { + let mut orgs = Vec::new(); + let mut reachable = Vec::new(); + for org in Self::organizations_of(user.id).await? { + let role = Self::role_of(org.id, user.id).await?.map(Role::as_str); + let projects = Self::projects_of(org.id).await?; + let names: Vec = projects.iter().map(|p| format!("{}/{}", org.slug, p.slug)).collect(); + let setup = crate::auth::setup::state(org.id, Some(user.pid)).await.map_err(internal)?; + // Out of credits: why builds aren't compared, and what fixes it. + let blocked = domain::credits::blocked(&org, &app_url(), None).await.map_err(internal)?; + orgs.push(json!({ + "slug": org.slug, "name": org.name, "role": role, "projects": names, "setup": setup, + "blocked": blocked, + })); + reachable.extend(projects); + } + let waiting = Self::waiting_for_review(&reachable, Some(user.id)).await?; + let user_id = user.id; + let identities: Vec = + db::query!("SELECT forge, login FROM identities WHERE user_id = {user_id} ORDER BY id") + .select() + .await + .map_err(internal)? + .iter() + .map(|r| { + json!({ "forge": r.try_get::("forge").ok(), "login": r.try_get::("login").ok() }) + }) + .collect(); + let mut out = json!({ + "kind": "user", "name": user.name, "email": user.email, "identities": identities, + "organizations": orgs, "waiting_for_review": waiting, "via": via, + }); + let threads = Self::open_threads(&reachable).await?; + if !threads.is_empty() { + // Branches where someone asked something: an open thread blocks approving its snapshot. + out["open_comment_threads"] = json!(threads); + } + // Nothing sent yet: point at the public demo, so the first look is a real review. + if let Some(demo) = Self::demo_if_new(&reachable).await? { + out["demo"] = demo; + } + Ok(structured(out)) + } + Some(Principal::Project { project_id, .. }) => { + let p = Project::find_or_fail(project_id).await.map_err(internal)?; + let org = Self::organization_of(&p).await?; + let waiting = Self::waiting_for_review(std::slice::from_ref(&p), None).await?; + let threads = Self::open_threads(std::slice::from_ref(&p)).await?; + let blocked = domain::credits::blocked(&org, &app_url(), Some(domain::credits::Spender::of(&p))) + .await + .map_err(internal)?; + Ok(structured(json!({ + "kind": "project", "project": format!("{}/{}", org.slug, p.slug), "waiting_for_review": waiting, + "open_comment_threads": threads, "blocked": blocked, "via": via, + }))) + } + None => Ok(tool_error("missing token")), + } + } + + #[tool( + description = "The organizations this token can reach, with each one's projects, the caller's role, and its plan and credits used this month.", + annotations( + title = "List organizations", + read_only_hint = true, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn list_organizations( + &self, + Parameters(_): Parameters, + rc: RequestContext, + ) -> Result { + let (orgs, only, user) = match principal_of(&rc) { + Some(Principal::User { user, .. }) => (Self::organizations_of(user.id).await?, None, Some(user.id)), + // A project token sees its own project, not the rest of the organization. + Some(Principal::Project { project_id, .. }) => { + let p = Project::find_or_fail(project_id).await.map_err(internal)?; + (vec![Self::organization_of(&p).await?], Some(p.id), None) + } + None => return Ok(tool_error("missing token")), + }; + let mut list = Vec::new(); + for org in orgs { + let projects: Vec = Self::projects_of(org.id) + .await? + .into_iter() + .filter(|p| only.is_none_or(|id| id == p.id)) + .map(|p| p.slug) + .collect(); + let role = match user { + Some(id) => Self::role_of(org.id, id).await?.map(|r| r.as_str().to_string()), + None => Some("project".to_string()), + }; + let usage = domain::credits::usage(&org).await.map_err(internal)?; + list.push( + json!({ "slug": org.slug, "name": org.name, "role": role, "usage": usage, "projects": projects }), + ); + } + Ok(structured(json!({ "organizations": list }))) + } + + #[tool( + description = "An organization: its members (role admin, member or read, and where each one's access came from: `github` when it follows their permission on the linked repositories, `invite`, `staff` or `created`), its projects (with each one's latest build), its plan, the credits used this month with what each thing costs (a snapshot check, a text diff, an image diff, a PDF page drawn) and its last 50 builds' usage. Choosing a plan and paying are left to a person in the web app.", + annotations( + title = "Get organization", + read_only_hint = true, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn get_organization( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let (org, role) = need!(Self::org(&rc, &args.org)); + // A project token sees its own project and the organization's plan and usage: not the members (their emails) + // or the other projects. + let only = match principal_of(&rc) { + Some(Principal::Project { project_id, .. }) => Some(project_id), + _ => None, + }; + let mut list = Vec::new(); + for p in Self::projects_of(org.id).await? { + if only.is_some_and(|id| id != p.id) { + continue; + } + let last = match domain::builds::recent(p.id, None, false, 1).await.map_err(internal)?.first() { + Some(b) => Some(Self::build_json(&p, b, true).await?), + None => None, + }; + list.push(json!({ "project": format!("{}/{}", org.slug, p.slug), "name": p.name, "last_build": last })); + } + let usage = domain::credits::usage(&org).await.map_err(internal)?; + // The usage history names other projects' builds. + let history: Vec = if only.is_some() { + Vec::new() + } else { + let org_id = org.id; + db::query!( + "SELECT amount, kind, reference, \ + to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"+00:00\"') AS created_at \ + FROM credit_transactions \ + WHERE organization_id = {org_id} AND kind IN ('build', 'render', 'gallery') ORDER BY id DESC LIMIT 50" + ) + .select() + .await + .map_err(internal)? + .iter() + .map(|t| { + json!({ + "credits": -t.try_get::("amount").unwrap_or_default(), + "kind": t.try_get::("kind").ok(), + "reference": t.try_get::>("reference").ok().flatten(), + "created_at": t.try_get::("created_at").ok(), + }) + }) + .collect() + }; + let user_pid = principal_of(&rc).and_then(|p| p.user().map(|u| u.pid)); + let setup = crate::auth::setup::state(org.id, user_pid).await.map_err(internal)?; + let admin = role == "admin"; + let members = if only.is_some() { + Vec::new() + } else { + crate::auth::invitations::members_json(org.id, admin).await.map_err(internal)? + }; + let pending = + if admin { crate::auth::invitations::pending(org.id).await.map_err(internal)? } else { Vec::new() }; + Ok(structured(json!({ + "slug": org.slug, "name": org.name, "role": role, "usage": usage, "members": members, + "invitations": pending, "billing_url": format!("{}/{}/billing", app_url(), org.slug), "projects": list, + "usage_history": history, "setup": setup, + }))) + } + + #[tool( + description = "Invite someone to an organization by email address or GitHub login (admins, with a personal access token). They're emailed, and join with `role` (admin, member or read) once they accept it in the web app, whether or not they already have an account. People with access to a linked repository on GitHub don't need an invitation: their access follows their permission there.", + annotations( + title = "Invite member", + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn invite_member( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let (org, role) = need!(Self::org(&rc, &args.org)); + let Some(Principal::User { user, .. }) = principal_of(&rc) else { + return Ok(tool_error("invitations need a personal access token")); + }; + if role != "admin" { + return Ok(tool_error(format!("only an organization's admins can invite people; you're {role}"))); + } + let role = crate::auth::Role::from(args.role).as_str(); + let invitation = match crate::auth::invitations::invite_to(org.id, &user, &args.invitee, role).await { + Ok(v) => v, + Err(e) => return Ok(tool_error(refusal(e)?)), + }; + Ok(structured(json!({ + "invitation": invitation, + "members": crate::auth::invitations::members_json(org.id, true).await.map_err(internal)?, + }))) + } + + #[tool( + description = "Create an organization with you as its admin (personal access tokens only), on the Free plan.", + annotations( + title = "Create organization", + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn create_organization( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let Some(Principal::User { user, .. }) = principal_of(&rc) else { + return Ok(tool_error("creating an organization needs a personal access token")); + }; + let slug = match crate::auth::orgs::create_org(&user, &args.slug, &args.name).await { + Ok(slug) => slug, + // Today's words for a slug that's taken. + Err(e) if e.status().as_u16() == 409 => return Ok(tool_error(format!("the slug {} is taken", args.slug))), + Err(e) => return Ok(tool_error(refusal(e)?)), + }; + let org = Organization::query() + .filter(Organization::slug.eq(slug.as_str())) + .first() + .await + .map_err(internal)? + .ok_or_else(|| internal("the new organization wasn't saved"))?; + let plan = domain::credits::plan_by_id(&org.plan); + Ok(structured(json!({ "slug": org.slug, "name": org.name, "plan": plan.name }))) + } + + #[tool( + description = "Create a project in an organization (owners and admins). Then `create_project_token` for CI, and `update_project` to link its GitHub repository.", + annotations( + title = "Create project", + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn create_project( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let (org, role) = need!(Self::org(&rc, &args.org)); + if role != "admin" { + return Ok(tool_error("only an organization's admins can create projects (with a personal access token)")); + } + match domain::projects::create(org.id, &args.slug, &args.name).await.map_err(internal)? { + Ok(p) => Ok(structured(json!({ + "project": format!("{}/{}", org.slug, p.slug), "settings": domain::projects::Settings::from(&p), + }))), + Err(m) => Ok(tool_error(m)), + } + } + + #[tool( + description = "A project's settings (renderer, dpi, threshold, CI mode, default branch, linked repository) and its tokens (names and prefixes; a token itself is shown only when it's created).", + annotations(title = "Get project", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn get_project( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let org = Self::organization_of(&project).await?.slug; + // A public project's tokens are its members' business. + let member = Self::role_in(&rc, &project).await?.is_some(); + let tokens: Vec = if member { + crate::models::ProjectToken::query() + .filter(crate::models::ProjectToken::project_id.eq(project.id)) + .order_by(crate::models::ProjectToken::id.asc()) + .get() + .await + .map_err(internal)? + .into_iter() + .map(|t| { + json!({ + "id": t.id, "name": t.name, "prefix": t.token_prefix, + "last_used_at": t.last_used_at.map(|d| d.to_string()), "created_at": t.created_at.to_string(), + }) + }) + .collect() + } else { + Vec::new() + }; + Ok(structured(json!({ + "project": format!("{org}/{}", project.slug), + "url": format!("{}/{org}/{}", app_url(), project.slug), + "settings": domain::projects::Settings::from(&project), + // The repository its CI builds come from, when the project isn't linked yet: link it with + // `update_project` (`repository_url`). + "repository_seen_in_ci": domain::projects::repository_seen_in_ci(&project).await.map_err(internal)?, + // What's public: the gallery's manifest and each published screenshot's URL (visualci.yml's `gallery`). + "gallery": domain::gallery::public_list(&app_url(), &org, &project).await.map_err(internal)?, + "tokens": tokens, + }))) + } + + #[tool( + description = "Change a project's settings. Fields left out stay as they are. These are defaults: a build's visualci.yml overrides them field by field. `ignore_rules` replaces the project's rules for values in text snapshots that change on every run, as a list of `{snapshots, json_paths, text_patterns}`: `snapshots` is a required glob over snapshot names (`api/invoices/**`, `**` for all), `json_paths` like `$.generated_at`, `$.items[*].id`, `$..request_id`, and `text_patterns` regular expressions.", + annotations( + title = "Update project", + read_only_hint = false, + destructive_hint = true, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn update_project( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + if let Err(e) = Self::need_role(&rc, &project, Role::Admin, "change a project's settings").await? { + return Ok(tool_error(e)); + } + let mut change = args.change; + if let Some(url) = change.repository_url.take() + && Some(url.trim()) != project.repository_url.as_deref() + { + if !matches!(principal_of(&rc), Some(Principal::User { .. })) { + return Ok(tool_error( + "linking a repository needs a person (signed in with the repository's forge, as an admin or \ + maintainer of it), not a project token", + )); + } + // TODO(subdomains): crate::forge::link::link_repository(project, &user, &url, change.forge_token, + // change.move_link) goes here once it's ported. Until then a link is refused as today's server refuses a + // forge it isn't set up for. + return Ok(tool_error(match crate::forge::Repository::parse(&url) { + Some(repository) => format!("{} isn't set up on this server", repository.forge.label()), + None => format!( + "{url:?} isn't a repository URL VisualCI knows: https://github.com/owner/name, \ + https://gitlab.com/group/project, or a project on a GitLab instance this organization added" + ), + })); + } + match domain::projects::change_settings(project, change).await.map_err(internal)? { + Ok(p) => Ok(structured(json!({ "settings": domain::projects::Settings::from(&p) }))), + Err(m) => Ok(tool_error(m)), + } + } + + #[tool( + description = "Create a project token (`vci_...`) for CI or the CLI. The token is in this answer only: store it where it's needed (e.g. as VISUALCI_TOKEN).", + annotations( + title = "Create project token", + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn create_project_token( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + if let Err(e) = Self::need_role(&rc, &project, Role::Admin, "create project tokens").await? { + return Ok(tool_error(e)); + } + let Some(Principal::User { user, .. }) = principal_of(&rc) else { + return Ok(tool_error("creating a project token needs a personal access token")); + }; + let name = args.name.trim(); + if name.is_empty() { + return Ok(tool_error("give the token a name")); + } + let (token, id) = match crate::auth::tokens::make_project_token(&user, project.id, name).await { + Ok(made) => made, + Err(e) => return Ok(tool_error(refusal(e)?)), + }; + Ok(structured(json!({ "id": id, "name": name, "token": token }))) + } + + #[tool( + description = "Delete a project token. Anything still using it (a CI variable) stops working.", + annotations( + title = "Delete project token", + read_only_hint = false, + destructive_hint = true, + open_world_hint = false + ) + )] + async fn delete_project_token( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + if let Err(e) = Self::need_role(&rc, &project, Role::Admin, "delete project tokens").await? { + return Ok(tool_error(e)); + } + if !crate::auth::tokens::remove_project_token(project.id, args.token_id).await.map_err(internal)? { + return Ok(tool_error(format!("no token {} in this project", args.token_id))); + } + Ok(structured(json!({ "deleted": args.token_id }))) + } + + #[tool( + description = "Download a build's images as one tar.zst, for a close look at a big build or for checks of your own: a URL (it lasts an hour) and a summary, never the images themselves. Filter by `state` (changed by default, added, removed, unchanged, all), `sides` (base, head, diff, regions: the head cropped to the changes) and a `glob` on snapshot names. The archive has `[@platform][/page-N]/{base,head,diff,regions}.png` and `manifest.json` (each snapshot's state, pages, changed fraction, regions and files). It's built in the background: when `state` is `building`, call again with the same arguments. Free.", + annotations( + title = "Download a build's images", + read_only_hint = true, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn download_build( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", &*args.build))); + }; + let filter = domain::downloads::Filter { state: args.state, sides: args.sides, glob: args.glob }; + let (mut download, new) = match domain::downloads::request(&build, &filter).await.map_err(internal)? { + Ok(d) => d, + Err(domain::downloads::Refused::Invalid(m) | domain::downloads::Refused::Busy(m)) => { + return Ok(tool_error(m)); + } + }; + if new { + crate::jobs::build_download::BuildDownload { download_id: download.id } + .dispatch() + .await + .map_err(internal)?; + } + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(args.wait.unwrap_or(50).min(60)); + loop { + download = crate::models::Download::find_or_fail(download.id).await.map_err(internal)?; + if !matches!(download.state.as_str(), "pending" | "building") || std::time::Instant::now() >= deadline { + break; + } + tokio::time::sleep(std::time::Duration::from_secs(2)).await; + } + let store = BlobStore::current().await.map_err(internal)?; + Ok(structured(domain::downloads::to_json(&download, &store))) + } + + #[tool( + description = "List a project's builds, newest first, one short line each: number, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, whether it waits for your review, its changes in a few words (`2 changed, 1 added`) and as numbers (`stats`), `blocked` when it's out of credits, and URL. get_build has the details (its snapshots, environment, reviews, groups, CI mode and warnings). waiting_for_review: only builds whose changes wait for a review.", + annotations(title = "List builds", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn list_builds( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let organization = Self::organization_of(&project).await?; + let limit = usize::try_from(args.limit.unwrap_or(20).clamp(1, 100)).unwrap_or(20); + let user = user_id(&rc); + let waiting = args.waiting_for_review == Some(true); + // Waiting builds include local ones that wait only for their own person: read a few more than asked for. + let scan = if waiting { 1000 } else { limit as u64 }; + let mut list = Vec::new(); + for b in domain::builds::recent(project.id, args.branch.as_deref(), waiting, scan).await.map_err(internal)? { + let waits = domain::builds::waits_for(&b, user); + if waiting && !waits { + continue; + } + list.push(Self::build_line(&organization, &project, &b, waits).await?); + if list.len() >= limit { + break; + } + } + Ok(structured(json!({ "builds": list }))) + } + + #[tool( + description = "A build's status and its snapshots that need attention, 30 at a time (offset and limit page through; longer lists also come grouped by state and name prefix) (changed, added, removed, failed), with how many pages changed in each, the largest change first (order: name to sort by name), and approved_elsewhere when the same new version was already approved on another branch (a hint: it approves nothing). Unchanged snapshots are only counted unless include_unchanged is set. `config` is the visualci.yml the build was sent (null when it had none: the project's settings applied). `flaky: true` marks a change whose content flipped back and forth over the branch's recent builds: often something that differs between runs (the time, an animation, a late font) rather than a real change, so check it before approving, and make the test deterministic. On a pull request's build, `on_main_unreviewed: true` marks a change that's the default branch's own unreviewed change (its newest build, still waiting for review, has it too), and `inherited` counts them: review those on main's build. `matches` marks a change made only of changes a merged pull request approved (two PRs that changed the same screen and merged separately): approve those with `review` and `only: \"matching\"`.", + annotations(title = "Get build", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn get_build( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let store = BlobStore::current().await.map_err(internal)?; + let org = Self::organization_of(&project).await?.slug; + let project_url = format!("{}/{org}/{}", app_url(), project.slug); + let build_url = format!("{project_url}/builds/{}", build.number); + let mut listed: Vec = snaps::of_build(build.id) + .await + .map_err(internal)? + .into_iter() + .filter(|s| args.include_unchanged || snaps::is_change(s) || s.state == "failed") + .collect(); + let sizes = detail::change_sizes(build.id).await.map_err(internal)?; + detail::sort_for_review(&mut listed, &sizes, args.order); + let elsewhere = domain::baselines::approved_elsewhere(build.id).await.map_err(internal)?; + let matching = domain::matching::of_build(build.id).await.map_err(internal)?; + let inherited = domain::inherited::of_build(&build, &project).await.map_err(internal)?; + let snapshot_url = |e: &domain::baselines::ApprovedElsewhere| { + format!("{project_url}/builds/{}/snapshots/{}", e.build, e.snapshot_id) + }; + // Long lists: a page of them (details only for those), with every listed snapshot grouped by state and the + // start of its name ("added: screenshots/landing/ ×110"). + let total = listed.len(); + let offset = args.offset.unwrap_or(0) as usize; + let limit = args.limit.unwrap_or(30).clamp(1, 200) as usize; + let paged = total > limit || offset > 0; + let mut groups: std::collections::BTreeMap<(String, String), usize> = std::collections::BTreeMap::new(); + if paged { + for s in &listed { + let prefix = s.name.rfind('/').map_or_else(String::new, |i| s.name[..=i].to_string()); + *groups.entry((s.state.clone(), prefix)).or_default() += 1; + } + } + let flaky = detail::flaky_in(&build).await.map_err(internal)?; + let mut items = Vec::new(); + for s in listed.into_iter().skip(offset).take(limit) { + let attention = snaps::is_change(&s) || s.state == "failed"; + let review_detail = if attention { + Some(detail::review_detail(&s, &store, detail::DEFAULT_CONTEXT).await.map_err(internal)?) + } else { + None + }; + let pages = review_detail.as_ref().map(|d| &d.pages); + let mut item = json!({ + "id": s.pid, "url": format!("{build_url}/snapshots/{}", s.pid), + "name": s.name, "platform": s.platform, "kind": s.kind, "state": s.state, "review": s.review, + "environment": s.environment, "matched_environment": s.matched_environment, + "error": s.error, + // How big the change is: the largest share of a page (or of the lines) that changed, and how many + // pixels (or lines). The list puts the biggest first. + "change": sizes.get(&s.id), + // The same new version was already approved on another branch: a hint, it approves nothing here. + "approved_elsewhere": elsewhere.get(&s.id).map(|e| { + let mut v = json!(e); + v["url"] = json!(snapshot_url(e)); + v + }), + "pages": pages.map(Vec::len), + "changed_pages": pages.map(|p| p.iter().filter(|p| p.state == "changed").count()), + "moved_lines": review_detail.as_ref().map_or(0, |d| d.moved.len()), + }); + if inherited.as_ref().is_some_and(|i| i.snapshot_ids.contains(&s.id)) { + // Not this pull request's change: the base build on the default branch has it too, unreviewed. + item["on_main_unreviewed"] = json!(true); + } + if let Some(m) = matching.get(&s.id) { + // Every changed region is exactly a change a merged pull request approved: `review` with + // `only: "matching"` approves these. A hint: it approves nothing by itself. + item["matches"] = json!(m); + } + if snaps::is_change(&s) && flaky.contains(&(s.name.clone(), s.platform.clone())) { + // Its content flipped back and forth over the branch's recent builds: a hint, not a verdict. + item["flaky"] = json!(true); + } + if let Some(format) = snaps::text_format(&s) { + item["format"] = json!(format.as_str()); + if let Some(text) = review_detail.as_ref().and_then(|d| d.text.as_ref()) { + let lines = pages.and_then(|p| p.first()).map(|p| &p.text_diff); + item["lines_added"] = json!(lines.map_or(0, |l| l.iter().filter(|l| l.tag == "+").count())); + item["lines_removed"] = json!(lines.map_or(0, |l| l.iter().filter(|l| l.tag == "-").count())); + if text.format == "json" { + item["json_changes"] = json!(text.json_changes.len()); + } + } + } + items.push(item); + } + let mut out = Self::build_json(&project, &build, Self::role_in(&rc, &project).await?.is_some()).await?; + if let Some(base) = build.base_build_id { + out["base_build"] = json!(Build::find(base).await.map_err(internal)?.map(|b| b.number)); + } + // The visualci.yml the build was sent (null without one), and the CI mode it ran under. + out["config"] = json!(build.config); + // What changed, computed from the comparison ("invoice: page 1 changed (2 regions); 3 added"). + out["summary"] = json!(domain::summary::summary_line(&build).await.map_err(internal)?); + out["warnings"] = build.warnings.clone(); + out["ci_mode"] = json!(BuildSettings::new(&project, &build).ci_mode()); + if paged { + out["groups"] = json!( + groups + .into_iter() + .map(|((state, prefix), count)| json!({ "state": state, "prefix": prefix, "count": count })) + .collect::>() + ); + out["listed"] = json!(format!("{} to {} of {total}", (offset + 1).min(total), (offset + limit).min(total))); + out["next_offset"] = json!((offset + limit < total).then_some(offset + limit)); + } + out["snapshots"] = json!(items); + if let Some(i) = &inherited { + // "3 changes are already on main and unreviewed (build #77)": they're main's, not this pull request's. + out["inherited"] = i.json(); + } + // Open comment threads on this build's branch: each blocks approving its snapshot until it's resolved. + let threads = comments::list(project.id, &build.branch, None, false).await.map_err(internal)?; + if !threads.is_empty() { + out["open_comment_threads"] = json!(threads); + } + Ok(structured(out)) + } + + #[tool( + description = "Many snapshots of a build at a glance: one image with a grid of thumbnails (each snapshot's first page, the new version, or the old one for a removed snapshot), and the list of what's in it in the same order, left to right and top to bottom, with each one's name, state and link. For checking a build with many added or changed snapshots in a few calls; page through with offset. Text snapshots have no thumbnail: look at them with get_snapshot.", + annotations(title = "Contact sheet", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn contact_sheet( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let states: Vec = args + .states + .as_deref() + .unwrap_or("changed,added") + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(); + let mut all: Vec = snaps::of_build(build.id) + .await + .map_err(internal)? + .into_iter() + .filter(|s| s.kind != "text" && !snaps::is_config_item(s) && states.contains(&s.state)) + .collect(); + let sizes = detail::change_sizes(build.id).await.map_err(internal)?; + detail::sort_for_review(&mut all, &sizes, args.order); + let offset = args.offset.unwrap_or(0) as usize; + let limit = args.limit.unwrap_or(24).clamp(1, 48) as usize; + let page: Vec<&Snapshot> = all.iter().skip(offset).take(limit).collect(); + let store = BlobStore::current().await.map_err(internal)?; + let org = Self::organization_of(&project).await?.slug; + let build_url = format!("{}/{org}/{}/builds/{}", app_url(), project.slug, build.number); + let pages = domain::pages::of_many(None, &page).await.map_err(internal)?; + let mut images = Vec::with_capacity(page.len()); + let mut list = Vec::with_capacity(page.len()); + for (i, s) in page.iter().enumerate() { + let first = pages.get(&s.id).and_then(|p| p.iter().min_by_key(|p| p.position)); + let sha = first.and_then(|p| p.head_image.clone().or_else(|| p.base_image.clone())); + let bytes = match sha { + Some(sha) => store.get(&sha).await.ok(), + None => None, + }; + images.push(bytes); + list.push(json!({ + "n": offset + i + 1, "name": s.name, "platform": s.platform, "state": s.state, "review": s.review, + "change": sizes.get(&s.id), + "url": format!("{build_url}/snapshots/{}", s.pid), + })); + } + let columns = args.columns.unwrap_or(4).clamp(1, 8); + let header = json!({ + "build": build.number, + "total": all.len(), + "showing": format!("{} to {} of {}", if page.is_empty() { 0 } else { offset + 1 }, offset + page.len(), all.len()), + "columns": columns, + "next_offset": (offset + page.len() < all.len()).then_some(offset + page.len()), + "snapshots": list, + }); + let mut content = vec![Content::text(serde_json::to_string_pretty(&sorted(header)).map_err(internal)?)]; + if !images.is_empty() { + let (bytes, media_type) = images::contact_sheet(&images, columns, 1200); + content.push(Content::image(base64::engine::general_purpose::STANDARD.encode(bytes), media_type)); + } + Ok(CallToolResult::success(content)) + } + + #[tool( + description = "Look at one snapshot's comparison. Documents and images: for every page its operation (unchanged, changed, inserted, removed), the diff's changed pixels and regions, and the text diff; lines that moved to another page; and the base, head and diff images of changed pages (the first three, or the pages you name). Each page's `embed_url` has week-long links to its images, for a pull request comment or a report. Text, JSON and HTML snapshots: the format, the changes by JSON path (`items[3].price: 10 → 12`) and a unified diff of the normalized text (sorted JSON keys, one HTML node per line, ignore rules applied); `images: head`, `base` or `all` adds that whole version. An unchanged snapshot's images come too (its first pages), so any build's version can be looked at. Also the snapshot's open comment threads, each with the build it was drawn on. `against: \"previous\"` compares with the branch's previous build instead of the baseline, to check a fix against a comment left there.", + annotations(title = "Get snapshot", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn get_snapshot( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let key = args.id.as_deref().unwrap_or(&args.name); + if key.is_empty() { + return Ok(tool_error("pass the snapshot's name (or its id from get_build)")); + } + let snapshot = need!(Self::find_snapshot(&build, key, &args.platform)); + let store = BlobStore::current().await.map_err(internal)?; + let settings = BuildSettings::new(&project, &build); + let earlier = match args.against.as_deref().map(str::trim) { + None | Some("" | "baseline") => None, + Some(other) => { + let number = match other { + "previous" => None, + n => match n.trim_start_matches('#').parse::() { + Ok(n) => Some(n), + Err(_) => return Ok(tool_error("against is baseline, previous, or an earlier build's number")), + }, + }; + match detail::earlier(&snapshot, &build, number).await.map_err(internal)? { + Some(found) => Some(found), + None => { + return Ok(tool_error(format!( + "{} has no {} on branch {} to compare with", + snapshot.name, + number.map_or("earlier build".to_string(), |n| format!("build #{n} before this one")), + build.branch + ))); + } + } + } + }; + let review_detail = match &earlier { + Some((_, e)) => { + let options = settings.diff_options(&snapshot); + detail::review_detail_against(&snapshot, &store, e, options, detail::DEFAULT_CONTEXT).await + } + None => detail::review_detail(&snapshot, &store, detail::DEFAULT_CONTEXT).await, + } + .map_err(internal)?; + let compared_with = match &earlier { + Some((b, _)) => json!({ "build": b.number, "note": "a view: review still compares with the baseline" }), + None => json!("baseline"), + }; + // Open threads on this snapshot of the branch, with the build each was drawn on. + let open_threads = comments::list(project.id, &build.branch, Some((&snapshot.name, &snapshot.platform)), false) + .await + .map_err(internal)?; + let org = Self::organization_of(&project).await?.slug; + let url = format!("{}/{org}/{}/builds/{}/snapshots/{}", app_url(), project.slug, build.number, snapshot.pid); + // Text, JSON and HTML: the unified diff and the JSON changes by path, with no images. + if let Some(text) = &review_detail.text { + let header = json!({ + "name": snapshot.name, "platform": snapshot.platform, "kind": snapshot.kind, "format": text.format, + "state": snapshot.state, "review": snapshot.review, "error": snapshot.error, "build": build.number, + "meta": snapshot.meta, "url": url, "note": text.note, "compared_with": compared_with, + "open_comment_threads": open_threads, + "base_lines": text.base_lines, "head_lines": text.head_lines, + "json_changes": (text.format == "json").then(|| text.json_changes.iter().map(visualci_core::snapshot_text::PathChange::line).collect::>()), + "json_changes_truncated": text.json_changes_truncated, + // The ignore rules applied to both sides, each with where it came from (file, test or project). + "ignore_rules": settings.applied_rules(&snapshot), + }); + let mut content = vec![Content::text(serde_json::to_string_pretty(&sorted(header)).map_err(internal)?)]; + let added = snapshot.state == "added"; + if !text.unified.is_empty() && !added { + content.push(Content::text(text.unified.clone())); + } else if added { + let head = review_detail + .pages + .first() + .map(|p| p.text_diff.iter().map(|l| l.text.as_str()).collect::>().join("\n")); + content.push(Content::text(format!( + "New snapshot, no baseline. Its content:\n{}", + head.unwrap_or_default() + ))); + } + // Either version as it was, on request: `images: head`, `base` or `all` (any snapshot, unchanged too). + let asked = args.images.as_deref(); + let side = |name: &str| asked == Some(name) || asked == Some("all"); + if side("head") + && !added + && let Some(head) = &text.head + { + content.push(Content::text(format!("This build's version:\n{head}"))); + } + if side("base") + && let Some(base) = &text.base + { + content.push(Content::text(format!("The baseline's version:\n{base}"))); + } + return Ok(CallToolResult::success(content)); + } + let (pages, moved) = (review_detail.pages, review_detail.moved); + + // Changed pages first; with none (an unchanged snapshot), the first pages, so any snapshot can be looked at. + let wanted: Vec = match &args.pages { + Some(p) => p.clone(), + None => { + let changed: Vec = pages + .iter() + .filter(|p| p.state == "changed") + .take(DEFAULT_IMAGE_PAGES) + .map(|p| p.position) + .collect(); + if changed.is_empty() { + pages.iter().take(DEFAULT_IMAGE_PAGES).map(|p| p.position).collect() + } else { + changed + } + } + }; + let which = args.images.as_deref().unwrap_or("all"); + let embed = |sha: &Option| sha.as_ref().and_then(|s| store.embed_url(s).ok()); + let summary: Vec = pages + .iter() + .map(|p| { + json!({ + "position": p.position, + "page": if snapshot.kind == "image" { None } else { p.head_index.or(p.base_index).map(|i| i + 1) }, + "op": p.op, "state": p.state, + "changed_pixels": p.diff.as_ref().map(|d| d.changed_pixels), + "changed_fraction": p.diff.as_ref().map(|d| d.changed_fraction), + // A resized page or screenshot: the diff covers the larger canvas, both aligned top-left, and the + // extra rows or columns count as changed. + "size_changed": p.diff.as_ref().map(|d| d.size_changed), + "base_size": p.base_size, + "head_size": p.head_size, + "regions": p.diff.as_ref().map(|d| &d.regions), + "text_diff": p.text_diff.iter().map(|l| format!("{}{}", l.tag, l.text)).collect::>(), + "images_included": wanted.contains(&p.position) && which != "none" && !p.expired, + "expired": p.expired, + // Week-long links to the page's images, for putting them in a pull request comment or a report. + "embed_url": (!p.expired).then(|| { + json!({ "base": embed(&p.base_image), "head": embed(&p.head_image), "diff": embed(&p.overlay_image) }) + }), + }) + }) + .collect(); + let header = json!({ + "name": snapshot.name, "platform": snapshot.platform, "kind": snapshot.kind, "state": snapshot.state, + "review": snapshot.review, "error": snapshot.error, "build": build.number, "meta": snapshot.meta, + "url": url, + "compared_with": compared_with, + "open_comment_threads": open_threads, + "pages": summary, + "moved_lines": moved.iter().map(|m| json!({ "text": m.text, "from_page": m.from_page + 1, "to_page": m.to_page + 1 })).collect::>(), + }); + + let mut content = vec![Content::text(serde_json::to_string_pretty(&sorted(header)).map_err(internal)?)]; + if which != "none" { + let b64 = base64::engine::general_purpose::STANDARD; + for p in pages.iter().filter(|p| wanted.contains(&p.position) && !p.expired) { + // A screenshot or image is one picture: "page" is a PDF's word. + let label = if snapshot.kind == "image" { + "image".to_string() + } else { + p.head_index.or(p.base_index).map_or(String::new(), |i| format!("page {}", i + 1)) + }; + let sides: Vec<(&str, &Option)> = match which { + "diff" => vec![("diff", &p.overlay_image)], + "head" => vec![("head", &p.head_image)], + "base" => vec![("base", &p.base_image)], + _ => vec![("base", &p.base_image), ("head", &p.head_image), ("diff", &p.overlay_image)], + }; + let regions = (args.crop.as_deref() == Some("changed")) + .then(|| p.diff.as_ref().map(|d| d.regions.clone()).filter(|r| !r.is_empty())) + .flatten(); + for (kind, sha) in sides { + let Some(sha) = sha else { continue }; + let bytes = store.get(sha).await.map_err(internal)?; + let (bytes, media_type) = images::prepare( + &bytes, + regions.as_deref(), + args.max_width.unwrap_or(images::DEFAULT_MAX_WIDTH).clamp(100, 4000), + ); + let cropped = if regions.is_some() { ", cropped to the changes" } else { "" }; + content.push(Content::text(format!("{label} ({}), {kind}{cropped}:", p.op))); + content.push(Content::image(b64.encode(bytes), media_type)); + } + } + } + Ok(CallToolResult::success(content)) + } + + #[tool( + description = "Everything a pull request (or branch) changes, across all of its builds, against the baseline it forked from: each suite's added, changed and removed snapshots, with where review stands for each (approved, here or in an earlier build of the PR; pending; rejected; failed). A per-build diff can hide a change approved in an earlier build; this doesn't. Use it as the final self-check before asking for a merge: nothing should be pending or unexpected.", + annotations( + title = "Get PR changeset", + read_only_hint = true, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn get_pr_changeset( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + use domain::changeset::{Target, changeset, json as changeset_json}; + let project = need!(Self::project(&rc, args.project.as_deref())); + let target = match (args.pr, args.branch) { + (Some(n), _) => Target::Pr(n), + (None, Some(b)) => Target::Branch(b), + (None, None) => return Ok(tool_error("name the pull request (`pr`) or a `branch`")), + }; + let suites = changeset(&project, &target).await.map_err(internal)?; + if suites.is_empty() { + return Ok(tool_error("no CI builds for that pull request or branch in this project")); + } + Ok(structured(changeset_json(&suites))) + } + + #[tool( + description = "One snapshot across recent builds, newest first: in each build its state (unchanged, changed, added, removed, failed) and review. Use it to find when a page started changing.", + annotations( + title = "Snapshot history", + read_only_hint = true, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn snapshot_history( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let limit = usize::try_from(args.limit.unwrap_or(20).clamp(1, 200)).unwrap_or(20); + let recent: Vec = + domain::builds::recent(project.id, args.branch.as_deref(), false, limit as u64).await.map_err(internal)?; + let ids: Vec = recent.iter().map(|b| b.id).collect(); + let (name, platform) = (args.name.as_str(), args.platform.as_str()); + let found: Vec = if ids.is_empty() { + Vec::new() + } else { + laravel::db::query!( + "SELECT * FROM effective_snapshots WHERE build_id IN ({...ids}) AND name = {name} \ + AND platform = {platform}" + ) + .select_as() + .await + .map_err(internal)? + }; + let history: Vec = recent + .iter() + .map(|b| { + let s = found.iter().find(|s| s.build_id == b.id); + json!({ + "build": b.number, "branch": b.branch, "commit": b.commit_sha, "created_at": b.created_at.to_string(), + "state": s.map(|s| s.state.clone()), "review": s.and_then(|s| s.review.clone()), + }) + }) + .collect(); + Ok(structured(json!({ "name": args.name, "platform": args.platform, "history": history }))) + } + + #[tool( + description = "Approve or reject a build's changes, some snapshots' changes (`snapshots`), or only its new or only its changed snapshots (`only`). Approved snapshots become the baseline, and the pull request's VisualCI check updates. Approve only changes the person you work for asked for. A build that's still comparing (straight after a run) is waited for, up to a minute.", + annotations(title = "Review build", read_only_hint = false, destructive_hint = true, open_world_hint = false) + )] + async fn review( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Member, "review builds")); + if args.action == "approve" + && let Some(refused) = Self::tokens_may_not_approve(&rc, &project) + { + return Ok(tool_error(refused)); + } + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + // Straight after a run the build may still be comparing: wait for it rather than refusing. + let build = refuse!(domain::builds::wait_until_reviewable(build, std::time::Duration::from_secs(60))); + let all = snaps::of_build(build.id).await.map_err(internal)?; + let ids = match (&args.snapshots, args.only.as_deref()) { + (Some(_), Some(_)) => return Ok(tool_error("pass `snapshots` or `only`, not both")), + (Some(names), None) => { + // A name that isn't in the build is a mistake to say, never an empty review. + if let Some(missing) = names.iter().find(|n| !all.iter().any(|s| &s.name == *n)) { + return Ok(tool_error(format!("no snapshot {missing:?} in build {}", build.number))); + } + Some(all.iter().filter(|s| names.contains(&s.name)).map(|s| s.id).collect()) + } + (None, Some(only)) => Some(refuse!(snaps::picked_by(build.id, only))), + (None, None) => None, + }; + if args.comment.is_some() && args.action != "reject" { + return Ok(tool_error("a comment goes with `reject`; to comment otherwise, use post_comment")); + } + // A review with a project token is recorded without a user. + let via = Self::via(&rc); + let rejected_ids = ids.clone(); + // Under the build's lock, so two approvals at once can't both record the same baselines. + let (user, action, note) = (user_id(&rc), args.action.clone(), args.note.clone()); + let reviewed = laravel::db::transaction(async |_| { + domain::processing::lock(build.id).await?; + let fresh = Build::find_or_fail(build.id).await?; + domain::reviews::review(fresh, user, &via, &action, ids.clone(), note.as_deref()).await + }) + .await + .map_err(internal)?; + let build = match reviewed { + Ok(b) => b, + Err(message) => return Ok(tool_error(message)), + }; + if let Some(body) = &args.comment { + let author = Self::author(&rc); + let place = comments::Place { page: None, side: "head".into(), anchor: comments::Anchor::Image }; + for s in all { + let named = rejected_ids.as_ref().is_none_or(|ids| ids.contains(&s.id)); + if named && snaps::is_change(&s) && !s.sourced { + refuse!(comments::start(&build, &s, &place, &author, body)); + } + } + } + let superseded = Self::changed(&build).await?; + let mut out = Self::build_json(&project, &build, true).await?; + if !superseded.is_empty() { + // The older pending builds this review covered. + out["superseded_builds"] = json!(superseded.len()); + } + Ok(structured(out)) + } + + #[tool( + description = "Comment threads on a build's branch: each with the build it was drawn on (`started_in_build`; its pin is on that build's image, and an open one still blocks approving the snapshot in newer builds), its snapshot, page, side (base or head), anchor (point, box or the whole image, in that image's pixels), whether it's resolved, and its comments with their authors (a person, or an agent and its name). Open threads only unless `include_resolved`. An open thread blocks approving its snapshot.", + annotations(title = "List comments", read_only_hint = true, idempotent_hint = true, open_world_hint = false) + )] + async fn list_comments( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let snapshot = match &args.snapshot { + Some(key) => Some(need!(Self::find_snapshot(&build, key, &args.platform))), + None => None, + }; + let threads = comments::list( + project.id, + &build.branch, + snapshot.as_ref().map(|s| (s.name.as_str(), s.platform.as_str())), + args.include_resolved, + ) + .await + .map_err(internal)?; + Ok(structured(json!({ "branch": build.branch, "threads": threads }))) + } + + #[tool( + description = "Comment on a snapshot: start a thread pinned to a point or a box (in that image's pixels, like get_snapshot's regions) or the whole image of a page's head (new) or base (old) side, or reply in a thread (`thread`). Markdown. Use it to ask about a change you can't judge, or to say why you rejected one; a person's open thread on a snapshot stops `review` from approving it until someone resolves the thread. Replying reopens a resolved thread.", + annotations(title = "Post comment", read_only_hint = false, destructive_hint = false, open_world_hint = false) + )] + async fn post_comment( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + // Members only, as in the web app: an open thread blocks approving its snapshot, and its text reaches the + // members' agents, so nobody outside (a public project's visitors) or read-only may start or reopen one. + need!(Self::need_role(&rc, &project, Role::Member, "comment")); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let author = Self::author(&rc); + if let Some(thread) = &args.thread { + let Ok(pid) = laravel::str::Uuid::parse_str(thread) else { + return Ok(tool_error("thread is the thread's id")); + }; + let Some(t) = comments::thread(project.id, pid).await.map_err(internal)? else { + return Ok(tool_error(format!("no thread {thread} in this project"))); + }; + let c = refuse!(comments::reply(t, &author, &args.body)); + return Ok(structured(json!({ "comment": c.pid, "thread": pid }))); + } + let Some(key) = &args.snapshot else { + return Ok(tool_error("name the snapshot to start a thread on, or the `thread` to reply in")); + }; + let snapshot = need!(Self::find_snapshot(&build, key, &args.platform)); + let place = comments::Place { + page: args.page, + side: args.side.unwrap_or_else(|| "head".into()), + anchor: args.anchor.unwrap_or(comments::Anchor::Image), + }; + let t = refuse!(comments::start(&build, &snapshot, &place, &author, &args.body)); + Ok(structured(json!({ "thread": t.pid, "snapshot": t.snapshot_name, "branch": t.branch }))) + } + + #[tool( + description = "Edit one of your own comments (`body`, Markdown).", + annotations( + title = "Update comment", + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn update_comment( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Read, "change comments")); + let Some(body) = &args.body else { return Ok(tool_error("give the new `body`")) }; + let Ok(pid) = laravel::str::Uuid::parse_str(&args.comment) else { + return Ok(tool_error("comment is the comment's id")); + }; + let Some((c, _)) = comments::comment(project.id, pid).await.map_err(internal)? else { + return Ok(tool_error(format!("no comment {} in this project", args.comment))); + }; + let c = refuse!(comments::edit(c, &Self::author(&rc), body)); + Ok(structured(json!({ "comment": c.pid, "body": c.body }))) + } + + #[tool( + description = "Resolve a comment thread once its question is answered (or reopen it with `resolved: false`). Resolving the open threads on a snapshot lets `review` approve it.", + annotations( + title = "Resolve comment", + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn resolve_comment( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Member, "resolve comment threads")); + let Ok(pid) = laravel::str::Uuid::parse_str(&args.thread) else { + return Ok(tool_error("thread is the thread's id")); + }; + let Some(t) = comments::thread(project.id, pid).await.map_err(internal)? else { + return Ok(tool_error(format!("no thread {} in this project", args.thread))); + }; + let resolved = args.resolved.unwrap_or(true); + let t = comments::resolve(t, resolved, user_id(&rc)).await.map_err(internal)?; + Ok(structured(json!({ "thread": t.pid, "resolved": t.resolved_at.is_some() }))) + } + + #[tool( + description = "Delete a comment (your own; an organization admin can delete anyone's). A thread left with no comments goes too.", + annotations( + title = "Delete comment", + read_only_hint = false, + destructive_hint = true, + open_world_hint = false + ) + )] + async fn delete_comment( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Read, "change comments")); + let Ok(pid) = laravel::str::Uuid::parse_str(&args.comment) else { + return Ok(tool_error("comment is the comment's id")); + }; + let Some((c, _)) = comments::comment(project.id, pid).await.map_err(internal)? else { + return Ok(tool_error(format!("no comment {} in this project", args.comment))); + }; + let admin = Self::role_in(&rc, &project).await? == Some(Role::Admin); + let thread_gone = refuse!(comments::delete(c, &Self::author(&rc), admin)); + Ok(structured(json!({ "deleted": pid, "thread_deleted": thread_gone }))) + } + + #[tool( + description = "Review one changed page: `variant` keeps the new page as another accepted baseline next to the old one (both are fine, e.g. a page that legitimately renders two ways); `ignore` ignores this exact change, in this build and later ones.", + annotations(title = "Review page", read_only_hint = false, destructive_hint = true, open_world_hint = false) + )] + async fn review_page( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Member, "review builds")); + if let Some(refused) = Self::tokens_may_not_approve(&rc, &project) { + return Ok(tool_error(refused)); + } + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let snapshot = need!(Self::find_snapshot(&build, &args.name, &args.platform)); + let build = refuse!(domain::reviews::page_action( + snapshot, + build, + project.id, + args.position, + &args.action, + user_id(&rc) + )); + let superseded = Self::changed(&build).await?; + let mut out = Self::build_json(&project, &build, true).await?; + if !superseded.is_empty() { + // The older pending builds this review covered. + out["superseded_builds"] = json!(superseded.len()); + } + Ok(structured(out)) + } + + #[tool( + description = "Start a build, as CI does: then `upload_snapshots` and `finalize_build`. VisualCI compares it with the baseline from the branch's ancestors (or the default branch).", + annotations(title = "Create build", read_only_hint = false, destructive_hint = false, open_world_hint = false) + )] + async fn create_build( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Member, "send builds")); + let params = domain::builds::CreateParams { + commit: args.commit, + branch: args.branch, + pr_number: args.pr_number, + parent_commits: args.parent_commits, + mode: args.mode.unwrap_or_else(|| "ci".into()), + name: args.name.unwrap_or_else(|| "default".into()), + shard_total: args.shard_total.unwrap_or(1), + subset: args.subset, + nonce: args.nonce, + config: args.config, + environment: args.environment, + environment_info: None, + }; + domain::processing::expire_abandoned(Some(project.id)).await.map_err(internal)?; + let build = match outcome(domain::builds::create(&project, ¶ms, user_id(&rc)).await)? { + Ok(b) => b, + Err(refused) => return Ok(refused), + }; + Ok(structured(Self::build_json(&project, &build, true).await?)) + } + + #[tool( + description = "Add files to a build that's still receiving: PDFs, PNG/JPEG/WebP images, or text snapshots (plain text, JSON, HTML, serialized component trees; `format` or the file name's extension decides), base64. Files VisualCI has seen before aren't stored again. Up to 64 MB per call; call it as often as needed.", + annotations( + title = "Upload snapshots", + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn upload_snapshots( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Member, "send builds")); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + if args.files.is_empty() || args.files.len() > 1000 { + return Ok(tool_error("send 1 to 1000 files per call")); + } + let b64 = base64::engine::general_purpose::STANDARD; + let mut decoded = Vec::with_capacity(args.files.len()); + let mut total = 0usize; + for f in &args.files { + let bytes = match b64.decode(f.content_base64.trim()) { + Ok(b) => b, + Err(e) => return Ok(tool_error(format!("{}: content_base64 isn't base64: {e}", f.name))), + }; + total += bytes.len(); + if total > MAX_UPLOAD_BYTES { + return Ok(tool_error("more than 64 MB of files in one call: split them over several calls")); + } + let (kind, fingerprint, content_type) = match classify(f.filename.as_deref(), &bytes) { + Ok(c) => c, + Err(e) => return Ok(tool_error(format!("{}: {e}", f.name))), + }; + decoded.push((bytes, kind, fingerprint, content_type)); + } + let params: Vec = args + .files + .iter() + .zip(&decoded) + .map(|(f, (bytes, kind, fingerprint, content_type))| snaps::SnapshotParams { + name: f.name.clone(), + platform: f.platform.clone(), + kind: (*kind).to_string(), + fingerprint: fingerprint.clone(), + sha256: visualci_core::sha256_hex(bytes), + size: i64::try_from(bytes.len()).unwrap_or(i64::MAX), + content_type: (*content_type).to_string(), + threshold: f.threshold, + ignore_anti_aliasing: None, + engine: f.engine.clone(), + format: f.format.clone(), + meta: f.meta.clone().unwrap_or(serde_json::Value::Null), + ignore: f.ignore.clone(), + }) + .collect(); + if build.state != "receiving" { + return Ok(tool_error(format!("build {} is {}, not receiving snapshots", build.number, build.state))); + } + // Every file is checked before any is written. + for p in ¶ms { + if let Err(e) = p.validate() { + return Ok(tool_error(e)); + } + } + let settings = BuildSettings::new(&project, &build); + let version = renderer_version(); + let store = BlobStore::current().await.map_err(internal)?; + let mut out = Vec::new(); + for (p, (bytes, _, _, content_type)) in params.iter().zip(decoded) { + let r = refuse!(snaps::register(&build, &settings, &version, p)); + if r.needs_upload { + domain::blobs::put(&store, bytes, content_type).await.map_err(internal)?; + } + out.push(json!({ "name": r.snapshot.name, "platform": r.snapshot.platform, "stored": r.needs_upload })); + } + Ok(structured(json!({ "build": build.number, "snapshots": out }))) + } + + #[tool( + description = "Finish a build (or one shard of it): VisualCI renders and compares what was uploaded. Then poll `get_build` until its state is completed. A build that was sent no snapshots fails, unless allow_empty is true or empty_reason says why it has none (\"inputs unchanged\").", + annotations( + title = "Finalize build", + read_only_hint = false, + destructive_hint = false, + open_world_hint = false + ) + )] + async fn finalize_build( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let project = need!(Self::project(&rc, args.project.as_deref())); + need!(Self::need_role(&rc, &project, Role::Member, "send builds")); + let Some(build) = Self::find_build(&project, &args.build).await? else { + return Ok(tool_error(format!("no build {} in this project", args.build))); + }; + let was_receiving = build.state == "receiving"; + let build = match args.empty_reason.as_deref() { + Some(reason) => match outcome(domain::builds::allow_empty_because(build, reason).await)? { + Ok(b) => b, + Err(refused) => return Ok(refused), + }, + None => build, + }; + let allow_empty = args.allow_empty.unwrap_or(false) || args.empty_reason.is_some(); + let build = match outcome(domain::builds::finalize_shard(build, args.shard, allow_empty).await)? { + Ok(b) => b, + Err(refused) => return Ok(refused), + }; + let build = if was_receiving { + domain::processing::stop_if_out_of_credits(build).await.map_err(internal)? + } else { + build + }; + if was_receiving && build.state == "processing" { + crate::jobs::process_build::ProcessBuild { build_id: build.id }.dispatch().await.map_err(internal)?; + } else if was_receiving && build.state == "failed" { + crate::events::BuildChanged { build_id: build.id }.dispatch().await.map_err(internal)?; + } + // The build as finalizing left it (`processing`): agents poll get_build, whether or not the job has run yet. + Ok(structured(Self::build_json(&project, &build, true).await?)) + } + + #[tool( + description = "Send something to the VisualCI team. Only about VisualCI itself. Never include secrets, credentials or the user's data. feedback: something got in your way and the work still got done (title, kind, description). Nobody replies. Send it without asking, once per problem, then tell the user what you sent. If a call fails, carry on and don't retry.", + annotations( + title = "Send to the VisualCI team", + read_only_hint = false, + destructive_hint = false, + idempotent_hint = false, + open_world_hint = false + ) + )] + async fn support_send( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + use domain::feedback::{self, FeedbackError}; + let SendAction::Feedback = args.action; + let Some(principal) = principal_of(&rc) else { return Ok(tool_error("missing token")) }; + let (user_id, project_id, account) = match &principal { + Principal::User { user, .. } => (Some(user.id), None, format!("user:{}", user.id)), + Principal::Project { project_id, .. } => (None, Some(*project_id), format!("project:{project_id}")), + }; + let client = rc + .extensions + .get::() + .and_then(|p| p.headers.get(axum::http::header::USER_AGENT)) + .and_then(|v| v.to_str().ok()) + .map(|s| s.chars().take(200).collect()); + let sender = feedback::Sender { user_id, project_id, account, channel: "mcp", client }; + let report = feedback::Report { + title: args.title, + kind: choice(args.kind.as_ref()), + description: args.description, + impact: choice(args.impact.as_ref()), + task: args.task, + request_ids: args.request_ids, + tool: args.tool, + error: args.error, + suggestion: args.suggestion, + category: None, + source: choice(args.source.as_ref()), + session: args.session, + agent: args.agent, + idempotency_key: args.idempotency_key, + }; + match feedback::record(sender, report).await { + Ok((row, duplicate)) => Ok(structured(feedback::result(&row, duplicate))), + Err(FeedbackError::Server(e)) => Err(internal(e)), + Err(e) => Ok(tool_error(e.to_string())), + } + } +} + +#[tool_handler(router = self.tool_router)] +impl ServerHandler for VisualCi { + async fn call_tool( + &self, + request: rmcp::model::CallToolRequestParams, + rc: rmcp::service::RequestContext, + ) -> Result { + let tool = self.tool_router.get(&request.name).cloned(); + if let Some(refused) = tool.as_ref().and_then(|t| unknown_arguments(t, request.arguments.as_ref())) { + return Ok(refused); + } + let mut request = request; + if let Some(t) = &tool { + coerce_numbers(t, request.arguments.as_mut()); + } + // rmcp runs the tool on a task of its own: run it in the HTTP request's Laravel context. + let in_app = context::of(&rc); + let call = self.tool_router.call(rmcp::handler::server::tool::ToolCallContext::new(self, request, rc)); + let result = match in_app { + Some(c) => c.scope(call).await, + None => Err(internal("no Laravel context for this MCP request")), + }; + explain_arguments(tool.as_ref(), result) + } + + fn get_info(&self) -> ServerConfig { + let mut capabilities = ServerCapabilities::builder().enable_tools().build(); + // Standard Support (standardsupport.dev): level 1, feedback only. + let mut support = serde_json::Map::new(); + support.insert("level".into(), json!(1)); + capabilities.extensions = Some([("dev.standardsupport/support".to_string(), support)].into_iter().collect()); + ServerConfig::new(capabilities) + .with_server_info(Implementation::new("visualci", env!("CARGO_PKG_VERSION"))) + .with_instructions(INSTRUCTIONS) + } +} + +/// rmcp answers arguments it can't read with serde's message alone ("missing field `build`"). Add the tool's real +/// fields and an example call, so an agent can fix its call without listing the tools again. +pub(crate) fn explain_arguments( + tool: Option<&rmcp::model::Tool>, + result: Result, +) -> Result { + let (Some(tool), Ok(rmcp::model::CallToolResponse::Complete(mut r))) = (tool, result.clone()) else { + return result; + }; + let Some(message) = r.content.first().and_then(|c| c.as_text()).map(|t| t.text.clone()) else { + return result; + }; + if r.is_error != Some(true) || !message.starts_with("failed to deserialize parameters:") { + return result; + } + r.content[0] = Content::text(format!("{message}\n\n{}", arguments_help(tool))); + Ok(rmcp::model::CallToolResponse::Complete(r)) +} + +/// Arguments the tool doesn't take are refused, never ignored: a misspelled or made-up argument (a `comment` on a tool +/// that has none) would otherwise do nothing without a word, and the caller would believe it had. The refusal names +/// them and lists what the tool takes. +pub(crate) fn unknown_arguments( + tool: &rmcp::model::Tool, + arguments: Option<&serde_json::Map>, +) -> Option { + let empty = serde_json::Map::new(); + let properties = tool.input_schema.get("properties").and_then(|p| p.as_object()).unwrap_or(&empty); + let mut unknown: Vec<&str> = + arguments?.keys().map(String::as_str).filter(|k| !properties.contains_key(*k)).collect(); + if unknown.is_empty() { + return None; + } + unknown.sort_unstable(); + let list = unknown.iter().map(|k| format!("`{k}`")).collect::>().join(", "); + let message = format!("{} doesn't take {list}.\n\n{}", tool.name, arguments_help(tool)); + Some(rmcp::model::CallToolResponse::Complete(CallToolResult::error(vec![Content::text(message)]))) +} + +/// Numbers sent as strings (`"500"` for an integer argument) are read as numbers: an agent whose copy of the tool's +/// schema is older, or that quotes everything, would otherwise get "expected u32" and have to try again. Only for +/// arguments whose schema says integer or number (and not also string), and only strings that are numbers; anything +/// else is left for the usual error naming the argument. +pub(crate) fn coerce_numbers( + tool: &rmcp::model::Tool, + arguments: Option<&mut serde_json::Map>, +) { + let Some(arguments) = arguments else { return }; + let empty = serde_json::Map::new(); + let properties = tool.input_schema.get("properties").and_then(|p| p.as_object()).unwrap_or(&empty); + for (name, value) in arguments.iter_mut() { + let Some(schema) = properties.get(name) else { continue }; + if let Some(kind) = numeric(schema) { + if let Some(n) = value.as_str().and_then(|s| parse_number(s, kind)) { + *value = n; + } + } else if schema_types(schema).contains(&"array") + && let Some(kind) = schema.get("items").and_then(numeric) + && let Some(items) = value.as_array_mut() + { + for item in items { + if let Some(n) = item.as_str().and_then(|s| parse_number(s, kind)) { + *item = n; + } + } + } + } +} + +fn schema_types(schema: &serde_json::Value) -> Vec<&str> { + match schema.get("type") { + Some(serde_json::Value::String(t)) => vec![t.as_str()], + Some(serde_json::Value::Array(ts)) => ts.iter().filter_map(serde_json::Value::as_str).collect(), + _ => vec![], + } +} + +/// `integer` or `number`, when that's what the argument is (an argument that also takes a string reads it itself). +fn numeric(schema: &serde_json::Value) -> Option<&'static str> { + let types = schema_types(schema); + if types.contains(&"string") { + return None; + } + if types.contains(&"integer") { + Some("integer") + } else if types.contains(&"number") { + Some("number") + } else { + None + } +} + +fn parse_number(s: &str, kind: &str) -> Option { + let s = s.trim(); + if kind == "integer" { + s.parse::().ok().map(serde_json::Value::from) + } else { + s.parse::().ok().filter(|f| f.is_finite()).map(serde_json::Value::from) + } +} + +/// "get_snapshot takes: build (required; integer or string): The build number…" and an example call with the +/// required fields. +fn arguments_help(tool: &rmcp::model::Tool) -> String { + let schema = &tool.input_schema; + let required: Vec<&str> = schema + .get("required") + .and_then(|r| r.as_array()) + .map(|r| r.iter().filter_map(|v| v.as_str()).collect()) + .unwrap_or_default(); + let empty = serde_json::Map::new(); + let properties = schema.get("properties").and_then(|p| p.as_object()).unwrap_or(&empty); + let mut lines = vec![format!("{} takes:", tool.name)]; + let mut example = serde_json::Map::new(); + let mut fields: Vec<(&String, &serde_json::Value)> = properties.iter().collect(); + // Required first, then by name (the JSON map keeps the schema's own order). + fields.sort_by_key(|(name, _)| (!required.contains(&name.as_str()), name.as_str())); + for (name, property) in fields { + let kind = property_kind(property); + let needed = required.contains(&name.as_str()); + let description = property + .get("description") + .and_then(|d| d.as_str()) + .map(|d| format!(": {}", d.split_whitespace().collect::>().join(" "))) + .unwrap_or_default(); + lines.push(format!("- {name} ({}{kind}){description}", if needed { "required; " } else { "" })); + if needed { + example.insert(name.clone(), example_value(name, &kind)); + } + } + if properties.is_empty() { + lines.push("- no arguments".to_string()); + } + lines.push(format!("Example: {}", serde_json::Value::Object(example))); + lines.join("\n") +} + +/// A property's JSON type in words: "string", "integer or string", "array", or "object" when the schema names a +/// definition. +fn property_kind(property: &serde_json::Value) -> String { + let types: Vec = match property.get("type") { + Some(serde_json::Value::String(t)) => vec![t.clone()], + Some(serde_json::Value::Array(ts)) => ts.iter().filter_map(|t| t.as_str()).map(str::to_string).collect(), + _ => vec![], + }; + let types: Vec = types.into_iter().filter(|t| t != "null").collect(); + if types.is_empty() { "object".to_string() } else { types.join(" or ") } +} + +fn example_value(name: &str, kind: &str) -> serde_json::Value { + match kind.split(" or ").next().unwrap_or_default() { + "integer" | "number" => json!(8), + "boolean" => json!(true), + "array" => json!([]), + "string" => json!(format!("<{name}>")), + _ => json!({}), + } +} + +type Service = StreamableHttpService; + +/// The MCP endpoint as a service: stateless, so any web process can answer any request. It answers only for our own +/// hosts (DNS rebinding protection): the app's host and localhost for development. +fn service() -> Service { + static SERVICE: OnceLock = OnceLock::new(); + SERVICE + .get_or_init(|| { + let mut hosts = vec!["localhost".to_string(), "127.0.0.1".to_string()]; + for url in [app_url(), laravel::config().app.url.clone()] { + if let Some(host) = url::Url::parse(&url).ok().and_then(|u| u.host_str().map(str::to_string)) { + hosts.push(host); + } + } + if let Ok(extra) = std::env::var("VISUALCI_MCP_HOSTS") { + hosts.extend(extra.split(',').map(str::trim).filter(|h| !h.is_empty()).map(str::to_string)); + } + hosts.sort(); + hosts.dedup(); + StreamableHttpService::new( + || Ok(VisualCi::new()), + std::sync::Arc::new(LocalSessionManager::default()), + StreamableHttpServerConfig::default() + .with_legacy_session_mode(false) + .with_json_response(true) + .with_allowed_hosts(hosts), + ) + }) + .clone() +} + +/// `/mcp`, any method: who the request acts for goes into its extensions, with the Laravel context, and rmcp's +/// service answers it. +pub async fn handle(principal: Result, request: axum::extract::Request) -> Response { + let Ok(principal) = principal else { return unauthorized() }; + let mut request = request; + request.extensions_mut().insert(principal); + context::carry(&mut request); + match service().oneshot(request).await { + Ok(response) => response.into_response(), + Err(never) => match never {}, + } +} + +/// No token, or one we don't know. +fn unauthorized() -> Response { + ( + axum::http::StatusCode::UNAUTHORIZED, + [(axum::http::header::WWW_AUTHENTICATE, "Bearer".to_string())], + "Connect with OAuth (your MCP client opens VisualCI's sign-in), or send a personal (vcu_...) or project \ + (vci_...) token as Authorization: Bearer .", + ) + .into_response() +} diff --git a/app/src/mcp/schema.rs b/app/src/mcp/schema.rs new file mode 100644 index 00000000..e9104ad7 --- /dev/null +++ b/app/src/mcp/schema.rs @@ -0,0 +1,260 @@ +//! Tool schemas as every MCP client and directory can read them. schemars writes `$ref`s into `$defs`, enums as +//! `oneOf` of `const`s, optional enums as `anyOf` with `null`, and nothing at all for a free-form value. Some clients +//! refuse those, and directories flag them ("Add a type to this parameter"). Each tool's input and output schema is +//! rewritten once, when the router is built: references inlined, `$defs` dropped, enums as `type` + `enum` (their +//! descriptions folded into the property's), optional values as a type list with `null`, and a `type` on every +//! property. + +use std::sync::Arc; + +use serde_json::{Map, Value, json}; + +/// Rewrite every tool's schemas in a router. +pub fn normalize_router(router: &mut rmcp::handler::server::router::tool::ToolRouter) { + for route in router.map.values_mut() { + let mut input = normalize_object(&route.attr.input_schema); + // Unknown arguments are refused (`mcp::unknown_arguments`); the schema says so up front. + input.insert("additionalProperties".into(), json!(false)); + route.attr.input_schema = Arc::new(input); + if let Some(out) = &route.attr.output_schema { + route.attr.output_schema = Some(Arc::new(normalize_object(out))); + } + } +} + +fn normalize_object(schema: &Map) -> Map { + let root = Value::Object(schema.clone()); + let defs = root.get("$defs").or_else(|| root.get("definitions")).cloned().unwrap_or(Value::Null); + let mut out = normalize(&root, &defs, 0); + if let Value::Object(m) = &mut out { + m.remove("$defs"); + m.remove("definitions"); + m.entry("type").or_insert_with(|| json!("object")); + return m.clone(); + } + schema.clone() +} + +/// The definition a `$ref` names (`#/$defs/Name`). +fn lookup<'a>(defs: &'a Value, reference: &str) -> Option<&'a Value> { + let name = reference.rsplit('/').next()?; + defs.get(name) +} + +/// The JSON type of a constant. +fn type_of(v: &Value) -> &'static str { + match v { + Value::Null => "null", + Value::Bool(_) => "boolean", + Value::Number(n) if n.is_i64() || n.is_u64() => "integer", + Value::Number(_) => "number", + Value::String(_) => "string", + Value::Array(_) => "array", + Value::Object(_) => "object", + } +} + +/// A list of types, as one string when there's one. +fn types(mut list: Vec) -> Value { + list.sort_by_key(|t| t == "null"); + list.dedup(); + if list.len() == 1 { json!(list[0]) } else { json!(list) } +} + +fn merge_description(target: &mut Map, extra: &str) { + if extra.is_empty() { + return; + } + let joined = match target.get("description").and_then(Value::as_str) { + Some(d) if !d.is_empty() => format!("{d} {extra}"), + _ => extra.to_string(), + }; + target.insert("description".into(), json!(joined)); +} + +fn normalize(node: &Value, defs: &Value, depth: usize) -> Value { + if depth > 32 { + return node.clone(); + } + let Value::Object(map) = node else { return node.clone() }; + // A reference: the definition, with the referring schema's own keys (its description) on top. + if let Some(reference) = map.get("$ref").and_then(Value::as_str) { + let mut resolved = match lookup(defs, reference).map(|d| normalize(d, defs, depth + 1)) { + Some(Value::Object(m)) => m, + _ => Map::new(), + }; + // The definition's own description (an enum's notes on each value) follows the referring one. + let inner = resolved.remove("description").and_then(|d| d.as_str().map(str::to_string)); + for (k, v) in map { + if k != "$ref" { + resolved.insert(k.clone(), normalize(v, defs, depth + 1)); + } + } + if let Some(d) = inner { + merge_description(&mut resolved, &d); + } + return Value::Object(resolved); + } + let mut out = Map::new(); + for (k, v) in map { + match k.as_str() { + "properties" => { + let props: Map = v + .as_object() + .map(|p| p.iter().map(|(n, s)| (n.clone(), typed(normalize(s, defs, depth + 1)))).collect()) + .unwrap_or_default(); + out.insert(k.clone(), Value::Object(props)); + } + "items" | "additionalProperties" if v.is_object() => { + out.insert(k.clone(), typed(normalize(v, defs, depth + 1))); + } + "oneOf" | "anyOf" => {} + _ => { + out.insert(k.clone(), v.clone()); + } + } + } + let variants = map.get("oneOf").or_else(|| map.get("anyOf")).and_then(Value::as_array); + if let Some(variants) = variants { + let variants: Vec = variants.iter().map(|v| normalize(v, defs, depth + 1)).collect(); + fold_variants(&mut out, &variants); + } + Value::Object(out) +} + +/// `oneOf`/`anyOf` folded into one schema: constants (and `null`) into `type` + `enum`, one real schema plus `null` +/// into that schema with `null` added to its type. Anything else keeps the first variant's shape, so a client still +/// sees a typed property. +fn fold_variants(out: &mut Map, variants: &[Value]) { + let is_null = |v: &Value| v.get("type") == Some(&json!("null")); + let constants: Option)>> = variants + .iter() + .map(|v| { + if let Some(c) = v.get("const") { + Some((c.clone(), v.get("description").and_then(Value::as_str).map(str::to_string))) + } else if is_null(v) { + Some((Value::Null, None)) + } else { + None + } + }) + .collect(); + let constants = constants.or_else(|| { + // Also plain enums (`{"type": "string", "enum": [...]}`) and null. + let mut all = Vec::new(); + for v in variants { + if is_null(v) { + all.push((Value::Null, None)); + } else { + for e in v.get("enum")?.as_array()? { + all.push((e.clone(), None)); + } + } + } + Some(all).filter(|a| !a.is_empty()) + }); + if let Some(constants) = constants { + let kinds: Vec = constants.iter().map(|(c, _)| type_of(c).to_string()).collect(); + out.insert("type".into(), types(kinds)); + out.insert("enum".into(), Value::Array(constants.iter().map(|(c, _)| c.clone()).collect())); + let notes: Vec = constants + .iter() + .filter_map(|(c, d)| { + d.as_ref().map(|d| format!("`{}`: {}", c.as_str().unwrap_or_default(), d.trim_end_matches('.'))) + }) + .collect(); + if !notes.is_empty() { + merge_description(out, &format!("{}.", notes.join("; "))); + } + return; + } + let real: Vec<&Value> = variants.iter().filter(|v| !is_null(v)).collect(); + let nullable = real.len() < variants.len(); + if let Some(Value::Object(first)) = real.first() { + for (k, v) in first { + if k == "description" { + if let Some(d) = v.as_str() { + merge_description(out, d); + } + } else { + out.entry(k.clone()).or_insert_with(|| v.clone()); + } + } + } + if nullable { + let mut list: Vec = match out.get("type") { + Some(Value::String(t)) => vec![t.clone()], + Some(Value::Array(ts)) => ts.iter().filter_map(|t| t.as_str().map(str::to_string)).collect(), + _ => vec!["object".to_string()], + }; + list.push("null".to_string()); + if let Some(Value::Array(e)) = out.get_mut("enum") + && !e.contains(&Value::Null) + { + e.push(Value::Null); + } + out.insert("type".into(), types(list)); + } +} + +/// A property schema with a `type`: from its constants or enum when it has them, `object` for a free-form value +/// (an object of anything is what those carry). +fn typed(schema: Value) -> Value { + let Value::Object(mut m) = schema else { + // `true` (anything): an object of anything. + return json!({ "type": "object" }); + }; + if !m.contains_key("type") { + let t = if let Some(c) = m.get("const") { + json!(type_of(c)) + } else if let Some(Value::Array(e)) = m.get("enum") { + types(e.iter().map(|v| type_of(v).to_string()).collect()) + } else if m.contains_key("properties") { + json!("object") + } else if m.contains_key("items") { + json!("array") + } else { + json!("object") + }; + m.insert("type".into(), t); + } + Value::Object(m) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn inlines_refs_and_folds_enums() { + let schema = json!({ + "type": "object", + "properties": { + "role": { "$ref": "#/$defs/Role", "description": "The role." }, + "kind": { "anyOf": [{ "$ref": "#/$defs/Kind" }, { "type": "null" }] }, + "config": { "description": "visualci.yml as JSON." }, + "build": { "type": ["integer", "string"] }, + "tags": { "type": "array", "items": { "$ref": "#/$defs/Kind" } } + }, + "$defs": { + "Role": { "oneOf": [ + { "const": "read", "description": "Looks only." }, + { "const": "admin", "description": "Everything." } + ] }, + "Kind": { "type": "string", "enum": ["bug", "idea"] } + } + }); + let out = normalize_object(schema.as_object().unwrap()); + let p = &out["properties"]; + assert!(out.get("$defs").is_none()); + assert_eq!(p["role"]["type"], "string"); + assert_eq!(p["role"]["enum"], json!(["read", "admin"])); + assert_eq!(p["role"]["description"], "The role. `read`: Looks only; `admin`: Everything."); + assert_eq!(p["kind"]["type"], json!(["string", "null"])); + assert_eq!(p["kind"]["enum"], json!(["bug", "idea", null])); + assert_eq!(p["config"]["type"], "object"); + assert_eq!(p["build"]["type"], json!(["integer", "string"])); + assert_eq!(p["tags"]["items"]["enum"], json!(["bug", "idea"])); + assert!(!serde_json::to_string(&out).unwrap().contains("$ref")); + } +} diff --git a/app/src/models/blobs.rs b/app/src/models/blobs.rs index 2be81aa2..1576d24e 100644 --- a/app/src/models/blobs.rs +++ b/app/src/models/blobs.rs @@ -14,4 +14,7 @@ pub struct Blob { pub height: Option, pub created_at: Timestamp, pub updated_at: Timestamp, + /// Marked by retention before it deletes the object; registering the hash again clears it. + #[default] + pub deleting: bool, } diff --git a/app/src/models/credit_transactions.rs b/app/src/models/credit_transactions.rs index d4da5e51..14afcc09 100644 --- a/app/src/models/credit_transactions.rs +++ b/app/src/models/credit_transactions.rs @@ -15,4 +15,6 @@ pub struct CreditTransaction { pub project_id: Option, #[default] pub open_source_credits: i64, + pub build_id: Option, + pub day: Option, } diff --git a/app/src/models/diffs.rs b/app/src/models/diffs.rs index 784795b5..0643fe17 100644 --- a/app/src/models/diffs.rs +++ b/app/src/models/diffs.rs @@ -16,4 +16,6 @@ pub struct Diff { pub overlay_blob: Option, pub created_at: Timestamp, pub updated_at: Timestamp, + /// When a comparison last reused it (retention leaves its overlay alone for a day after). + pub used_at: Option, } diff --git a/app/src/models/organizations.rs b/app/src/models/organizations.rs index d9c3bcc0..677d5d42 100644 --- a/app/src/models/organizations.rs +++ b/app/src/models/organizations.rs @@ -78,7 +78,7 @@ impl Organization { continue; } let name = user.name.clone(); - return laravel::db::transaction(async |_| { + let made = laravel::db::transaction(async |_| { let org = laravel::model::create!(Self { pid: laravel::str::uuid7(), slug: slug.as_str(), @@ -102,6 +102,12 @@ impl Organization { Ok((org, project)) }) .await; + // Another sign-up took the slug between the check and the insert: try the next one. + match made { + Ok(made) => return Ok(made), + Err(e) if laravel::db::is_unique_violation(&e) => {} + Err(e) => return Err(e), + } } Err(laravel::Error::msg("no free organization slug")) } diff --git a/app/src/models/projects.rs b/app/src/models/projects.rs index 8cd0bcb9..2e878064 100644 --- a/app/src/models/projects.rs +++ b/app/src/models/projects.rs @@ -47,7 +47,13 @@ pub struct Project { pub linked_by: Option, #[default] pub tokens_can_approve: bool, + /// Whether VisualCI comments on a pull request whose builds are all unchanged (off by default). + #[default] + pub comment_when_unchanged: bool, pub repository_id: Option, + /// The gallery URLs last purged as published (`jobs::purge_gallery`). + #[default] + pub gallery_urls: serde_json::Value, } impl crate::auth::InProject for Project { diff --git a/app/src/models/renders.rs b/app/src/models/renders.rs index 8b4e2932..207a4360 100644 --- a/app/src/models/renders.rs +++ b/app/src/models/renders.rs @@ -23,4 +23,9 @@ pub struct Render { pub render_ms: Option, pub project_id: Option, pub claim_token_hash: Option, + /// The PNGs this render's claims uploaded through its own uploads: the only page images completing it may name. + #[default] + pub uploads: serde_json::Value, + /// When a snapshot last reused it (retention leaves its images and texts alone for a day after). + pub used_at: Option, } diff --git a/app/src/notify/mod.rs b/app/src/notify/mod.rs new file mode 100644 index 00000000..2f29169e --- /dev/null +++ b/app/src/notify/mod.rs @@ -0,0 +1,30 @@ +//! Transactional emails (sc-8900, the emails side), ported from today's server. Each email is rendered from a +//! [`Kind`], recorded in the `emails` outbox under a `dedupe_key` that names the event and its period (so a threshold +//! emails once a month, an invoice once), and sent through Postmark by [`DeliverEmails`]: queued right after an email +//! is, and scheduled every five minutes for anything left over. A failed send stays pending and is retried; after five +//! attempts it's marked failed for staff to retry or dismiss. Billing emails go to an organization's billing email, or +//! else its admins; security emails go to the person concerned. People can turn off low-credit warnings and +//! receipt-style emails; security, billing problems and running out can't be. + +pub mod outbox; +pub mod postmark; +pub mod render; + +pub use outbox::{DeliverEmails, To, queue}; +pub use render::{About, Kind, Paused, Preference, Rendered, render}; + +use laravel::event::{Event, listener}; + +use crate::auth::memberships::MembershipChanged; + +/// Someone joined an organization or left it: tell them. +#[listener] +pub async fn membership_changed(event: Event) -> laravel::Result<()> { + let kind = match event.role { + Some(role) => Kind::AddedToOrg { role: role.as_str().to_string() }, + None => Kind::RemovedFromOrg, + }; + let key = format!("{}:{}:{}:{}", kind.name(), event.organization_id, event.user_id, event.changed_at); + queue(&kind, To::User(event.user_id), Some(event.organization_id), &key).await?; + Ok(()) +} diff --git a/app/src/notify/outbox.rs b/app/src/notify/outbox.rs new file mode 100644 index 00000000..a6638095 --- /dev/null +++ b/app/src/notify/outbox.rs @@ -0,0 +1,266 @@ +//! The `emails` outbox: queueing (once per dedupe key and recipient), delivery, and what staff and `/status` read. + +use laravel::db; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; + +use super::postmark::{self, Postmark}; +use super::render::{About, Kind, Preference, render}; + +/// Who gets an email. +#[derive(Clone, Debug)] +pub enum To { + /// The organization's billing email, or else its admins (each one's preferences apply). + Billing(i64), + /// One person, by user ID. + User(i64), + /// The organization's admins (each one's preferences apply). + Admins(i64), + /// An address with no account behind it yet (an invitation). + Address(String), +} + +/// The organization's admins who haven't turned this email off, with their user IDs. +async fn admins(org_id: i64, preference: Option) -> laravel::Result)>> { + let rows = match preference { + Some(Preference::LowCredits) => { + db::query!( + "SELECT u.id, u.email FROM memberships m JOIN users u ON u.id = m.user_id \ + WHERE m.organization_id = {org_id} AND m.role = 'admin' AND u.email_low_credits ORDER BY u.id" + ) + .select() + .await? + } + Some(Preference::Receipts) => { + db::query!( + "SELECT u.id, u.email FROM memberships m JOIN users u ON u.id = m.user_id \ + WHERE m.organization_id = {org_id} AND m.role = 'admin' AND u.email_receipts ORDER BY u.id" + ) + .select() + .await? + } + None => { + db::query!( + "SELECT u.id, u.email FROM memberships m JOIN users u ON u.id = m.user_id \ + WHERE m.organization_id = {org_id} AND m.role = 'admin' ORDER BY u.id" + ) + .select() + .await? + } + }; + rows.iter().map(|r| Ok((r.try_get::("email")?, Some(r.try_get::("id")?)))).collect() +} + +/// Record an email in the outbox, once per `dedupe_key` and recipient, and queue its delivery. It's rendered when it's +/// sent. Returns how many were queued: 0 when it was already queued, or everyone it would go to turned it off. +/// +/// # Errors +/// On a database error. +pub async fn queue(kind: &Kind, to: To, org_id: Option, dedupe_key: &str) -> laravel::Result { + let org_id = match to { + To::Billing(o) | To::Admins(o) => Some(o), + To::User(_) | To::Address(_) => org_id, + }; + let recipients: Vec<(String, Option)> = match to { + To::User(id) => db::query!("SELECT email FROM users WHERE id = {id}") + .scalar::() + .await? + .map(|e| vec![(e, Some(id))]) + .unwrap_or_default(), + To::Billing(o) => { + let billing: Option = db::query!("SELECT billing_email FROM organizations WHERE id = {o}") + .scalar::>() + .await? + .flatten() + .filter(|e| !e.trim().is_empty()); + match billing { + Some(e) => vec![(e.trim().to_string(), None)], + None => admins(o, kind.preference()).await?, + } + } + To::Admins(o) => admins(o, kind.preference()).await?, + To::Address(a) => vec![(a, None)], + }; + let data = serde_json::to_value(kind).map_err(|e| laravel::Error::msg(e.to_string()))?; + let name = kind.name(); + let mut queued = 0; + for (address, user_id) in recipients { + let key = format!("{dedupe_key}:{address}"); + let inserted: Option = db::query!( + "INSERT INTO emails (kind, dedupe_key, organization_id, user_id, recipient, data) \ + VALUES ({name}, {key}, {org_id}, {user_id}, {address}, {data}) \ + ON CONFLICT (dedupe_key) DO NOTHING RETURNING id" + ) + .scalar() + .await?; + queued += usize::from(inserted.is_some()); + } + if queued > 0 { + DeliverEmails.dispatch().await?; + } + Ok(queued) +} + +/// Send pending emails, up to 50 a run. Each is claimed just before it's sent, so two runs never send one twice; a +/// failure leaves it pending for the next run, and after five attempts it's marked failed. Without a Postmark token nothing is sent. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct DeliverEmails; + +#[job] +impl DeliverEmails { + async fn handle( + self, + postmark: laravel::config::Section, + app: laravel::config::Section, + ) -> laravel::Result<()> { + let delivered = deliver(&postmark, &app.url).await; + // The heartbeat checks the work, not just the run: an email waiting more than half an hour fails it + let health = match &delivered { + Err(e) => Err(e.to_string()), + Ok(_) => match oldest_unsent_seconds().await { + Ok(waited) if waited > STALE_SECONDS => Err(format!("the oldest unsent email has waited {waited}s")), + Ok(_) => Ok(()), + Err(e) => Err(e.to_string()), + }, + }; + crate::heartbeat::push("VISUALCI_EMAILS_HEARTBEAT", health).await; + delivered?; + Ok(()) + } +} + +/// How long an email may wait unsent before the heartbeat fails. +pub const STALE_SECONDS: i64 = 30 * 60; + +/// The web app's URL, for the links in emails. +#[derive(Clone, laravel::config::Section)] +pub struct AppUrl { + #[env("VISUALCI_APP_URL", default = "http://localhost")] + pub url: String, +} + +/// Anything left over (a failed send, a worker that stopped) goes out within five minutes. +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(DeliverEmails).every_five_minutes().without_overlapping(); +} + +/// How long a claimed email waits before another run may take it: far longer than one send can take. +pub const RECLAIM_MINUTES: i64 = 30; +/// How long a failed send waits before it's tried again. +pub const RETRY_MINUTES: i64 = 5; + +/// Send what's pending. Returns how many were sent. +/// +/// # Errors +/// On a database error. +pub async fn deliver(config: &Postmark, app_url: &str) -> laravel::Result { + let Some(token) = config.token.as_deref().filter(|t| !t.is_empty()) else { return Ok(0) }; + // Anything a crashed run left claimed after its fifth attempt has had its tries. + let window = RECLAIM_MINUTES; + db::query!( + "UPDATE emails SET state = 'failed', claimed_at = NULL, \ + last_error = COALESCE(last_error, 'no result after five attempts'), updated_at = now() \ + WHERE state = 'pending' AND attempts >= 5 AND claimed_at < now() - make_interval(mins => {window}::int)" + ) + .update() + .await?; + let mut sent = 0; + // One at a time, each claimed just before it's sent: a claim only lapses after RECLAIM_MINUTES, far longer than one + // send can take, so a slow run's later emails are never taken by the next run while it's still sending. + for _ in 0..50 { + let Some(r) = db::query!( + "UPDATE emails SET claimed_at = now(), attempts = attempts + 1 WHERE id = ( \ + SELECT id FROM emails WHERE state = 'pending' AND attempts < 5 \ + AND (claimed_at IS NULL OR claimed_at < now() - make_interval(mins => {window}::int)) \ + ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED) \ + RETURNING id, recipient, data, organization_id, attempts" + ) + .select_one() + .await? + else { + break; + }; + let id: i64 = r.try_get("id")?; + let to: String = r.try_get("recipient")?; + let attempts: i32 = r.try_get("attempts")?; + let org_id: Option = r.try_get("organization_id")?; + let data: serde_json::Value = r.try_get("data")?; + let Ok(kind) = serde_json::from_value::(data) else { + db::query!( + "UPDATE emails SET state = 'failed', last_error = 'unreadable data', updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + continue; + }; + let (org_name, org_slug) = match org_id { + Some(o) => db::query!("SELECT name, slug FROM organizations WHERE id = {o}") + .select_one() + .await? + .map(|row| { + ( + row.try_get::("name").unwrap_or_default(), + row.try_get::("slug").unwrap_or_default(), + ) + }) + .unwrap_or_default(), + None => (String::new(), String::new()), + }; + let rendered = + render(&kind, &About { org_name: &org_name, org_slug: &org_slug, app_url: app_url.trim_end_matches('/') }); + match postmark::send(config, token, &to, &rendered.subject, &rendered.text, &rendered.html, kind.reply_to()) + .await + { + Ok(()) => { + let (subject, text, html) = (rendered.subject, rendered.text, rendered.html); + db::query!( + "UPDATE emails SET state = 'sent', sent_at = now(), claimed_at = NULL, last_error = NULL, \ + subject = {subject}, text_body = {text}, html_body = {html}, updated_at = now() WHERE id = {id}" + ) + .update() + .await?; + sent += 1; + } + Err(e) => { + let state = if attempts >= 5 { "failed" } else { "pending" }; + let error = e.to_string(); + // Its claim lapses in RETRY_MINUTES, so the next run tries again, never this one. + let hold = RECLAIM_MINUTES - RETRY_MINUTES; + db::query!( + "UPDATE emails SET state = {state}, last_error = {error}, updated_at = now(), \ + claimed_at = CASE WHEN {state} = 'failed' THEN NULL \ + ELSE now() - make_interval(mins => {hold}::int) END WHERE id = {id}" + ) + .update() + .await?; + tracing::warn!(email_id = id, error = %e, "an email wasn't sent"); + } + } + } + Ok(sent) +} + +/// How long the oldest unsent email has waited, for `/status`. +/// +/// # Errors +/// On a database error. +pub async fn oldest_unsent_seconds() -> laravel::Result { + Ok(db::query!( + "SELECT COALESCE(EXTRACT(EPOCH FROM now() - MIN(created_at)), 0)::BIGINT FROM emails WHERE state = 'pending'" + ) + .scalar::() + .await? + .unwrap_or(0)) +} + +/// Failed emails nobody has retried or dismissed yet, for `/status` (`emails_failed_unresolved`). +/// +/// # Errors +/// On a database error. +pub async fn failed_unresolved_count() -> laravel::Result { + Ok(db::query!("SELECT count(*) FROM emails WHERE state = 'failed' AND dismissed_at IS NULL") + .scalar::() + .await? + .unwrap_or(0)) +} diff --git a/app/src/notify/postmark.rs b/app/src/notify/postmark.rs new file mode 100644 index 00000000..3dd43373 --- /dev/null +++ b/app/src/notify/postmark.rs @@ -0,0 +1,50 @@ +//! Sending one email through Postmark's API (`POSTMARK_SERVER_TOKEN`, `MAIL_FROM`, `MAIL_REPLY_TO`). Without a token, +//! nothing is sent and the outbox keeps the emails pending. + +use laravel::http::client; +use serde_json::json; + +#[derive(Clone, laravel::config::Section)] +pub struct Postmark { + #[env("POSTMARK_SERVER_TOKEN")] + pub token: Option, + #[env("MAIL_FROM", default = "VisualCI ")] + pub from: String, + #[env("MAIL_REPLY_TO", default = "support@visualci.com")] + pub reply_to: String, +} + +/// Send one email with its text and HTML bodies. +/// +/// # Errors +/// When Postmark can't be reached or refuses the message. +pub async fn send( + config: &Postmark, + token: &str, + to: &str, + subject: &str, + text: &str, + html: &str, + reply_to: Option<&str>, +) -> laravel::Result<()> { + let body = json!({ + "From": config.from, + "To": to, + "ReplyTo": reply_to.unwrap_or(&config.reply_to), + "Subject": subject, + "TextBody": text, + "HtmlBody": html, + "MessageStream": "outbound", + }); + let response = client::post("https://api.postmarkapp.com/email") + .header("X-Postmark-Server-Token", token) + .accept_json() + .timeout(std::time::Duration::from_secs(10)) + .json(&body) + .await?; + if !response.successful() { + let detail: serde_json::Value = response.json().unwrap_or_default(); + return Err(laravel::Error::msg(format!("Postmark: HTTP {}: {}", response.status(), detail["Message"]))); + } + Ok(()) +} diff --git a/app/src/notify/render.rs b/app/src/notify/render.rs new file mode 100644 index 00000000..b663f634 --- /dev/null +++ b/app/src/notify/render.rs @@ -0,0 +1,464 @@ +//! What each email VisualCI sends says (ported as is from today's server, sc-8900): every [`Kind`], rendered to a +//! subject, plain text and HTML ([`render`]). The outbox and delivery are in `notify::outbox`. + +use crate::billing::CREDIT_PACK; + +/// Why automatic packs stopped. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum Paused { + Declined(String), + LimitReached(i32), +} + +/// Every email VisualCI sends to customers, with what it says. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum Kind { + /// 80% or 95% of the plan's credits (or of the open source pool) used this month. + CreditsLow { + pool: bool, + percent: u8, + left: i64, + total: i64, + renews: String, + next: String, + }, + /// The plan's credits and packs are used up: builds fail with "out of credits". + OutOfCredits { + plan: String, + renews: String, + packs: bool, + }, + /// Automatic packs bought one. + PackBought { + packs_this_month: i64, + limit: i32, + invoice_url: Option, + }, + AutoBuyPaused(Paused), + PlanChanged { + from: String, + to: String, + }, + OpenSourceLost { + project: String, + reason: String, + }, + /// A public project's repository went private (or it was unlinked), so VisualCI made the project private. + MadePrivate { + project: String, + }, + /// A maintainer of the repository moved its link to their own organization: one organization per repository. + RepositoryMoved { + project: String, + repository: String, + to_org: String, + by: String, + }, + Welcome { + name: String, + }, + Invited { + inviter: String, + role: String, + }, + AddedToOrg { + role: String, + }, + RemovedFromOrg, + /// `client` is how the CLI names itself: `visualci CLI on ada-laptop`. + DeviceSignIn { + client: String, + at: String, + }, + TokenCreated { + name: String, + project: Option, + }, + /// To the team (`VISUALCI_TEAM_EMAIL`): someone signed up. Plain text; replying reaches them. + NewSignup { + subject: String, + text: String, + reply_to: String, + }, +} + +impl Kind { + /// The name the outbox, the admin MCP and the staff page use. + #[must_use] + pub const fn name(&self) -> &'static str { + match self { + Self::CreditsLow { .. } => "credits_low", + Self::OutOfCredits { .. } => "out_of_credits", + Self::PackBought { .. } => "pack_bought", + Self::AutoBuyPaused(_) => "auto_buy_paused", + Self::PlanChanged { .. } => "plan_changed", + Self::OpenSourceLost { .. } => "open_source_lost", + Self::MadePrivate { .. } => "made_private", + Self::RepositoryMoved { .. } => "repository_moved", + Self::Welcome { .. } => "welcome", + Self::Invited { .. } => "invited", + Self::AddedToOrg { .. } => "added_to_org", + Self::RemovedFromOrg => "removed_from_org", + Self::DeviceSignIn { .. } => "device_sign_in", + Self::TokenCreated { .. } => "token_created", + Self::NewSignup { .. } => "new_signup", + } + } + + /// Where a reply goes when it isn't VisualCI's support address. + #[must_use] + pub fn reply_to(&self) -> Option<&str> { + match self { + Self::NewSignup { reply_to, .. } => Some(reply_to), + _ => None, + } + } + + /// Which preference can turn it off, if any. + #[must_use] + pub const fn preference(&self) -> Option { + match self { + Self::CreditsLow { .. } => Some(Preference::LowCredits), + Self::PackBought { .. } | Self::PlanChanged { .. } => Some(Preference::Receipts), + _ => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Preference { + LowCredits, + Receipts, +} + +/// An email ready to send. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct Rendered { + pub subject: String, + pub text: String, + pub html: String, +} + +/// What an email is about: the organization (by name and slug) when it has one. +#[derive(Debug, Clone)] +pub struct About<'a> { + pub org_name: &'a str, + pub org_slug: &'a str, + pub app_url: &'a str, +} + +fn n(v: i64) -> String { + let s = v.abs().to_string(); + let mut out = String::new(); + for (i, c) in s.chars().enumerate() { + if i > 0 && (s.len() - i).is_multiple_of(3) { + out.push(','); + } + out.push(c); + } + if v < 0 { format!("-{out}") } else { out } +} + +fn money(cents: i64) -> String { + if cents % 100 == 0 { format!("${}", cents / 100) } else { format!("${}.{:02}", cents / 100, cents % 100) } +} + +fn escape(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +/// A paragraph that starts with this is a line to copy: monospace in a box in the HTML, on its own line in the text. +const COPY: &str = "copy:"; + +/// The one-line setup prompt for a coding agent, as the app shows it. +pub const AGENT_PROMPT: &str = "Fetch https://visualci.com/install.md and follow it"; + +/// The email's HTML: its paragraphs and one button, in a plain single column. +fn html(paragraphs: &[String], button: (&str, &str)) -> String { + let body: String = paragraphs + .iter() + .map(|p| match p.strip_prefix(COPY) { + Some(line) => format!( + "
{}
", + escape(line) + ), + None => { + format!("

{}

", escape(p)) + } + }) + .collect(); + format!( + "\ +
\ +

VisualCI

{body}\ +

\ + {label}

\ +

\ + Questions? Reply to this email.

", + url = escape(button.1), + label = escape(button.0), + ) +} + +fn text(paragraphs: &[String], button: (&str, &str)) -> String { + let lines: Vec<&str> = paragraphs.iter().map(|p| p.strip_prefix(COPY).unwrap_or(p)).collect(); + let mut out = lines.join("\n\n"); + out.push_str(&format!("\n\n{}: {}\n\nQuestions? Reply to this email.\n", button.0, button.1)); + out +} + +/// Render an email. +#[must_use] +pub fn render(kind: &Kind, about: &About<'_>) -> Rendered { + if let Kind::NewSignup { subject, text, .. } = kind { + let html = format!("
{}
", escape(text)); + return Rendered { subject: subject.clone(), text: text.clone(), html }; + } + let org = about.org_name; + let billing = format!("{}/{}/billing", about.app_url, about.org_slug); + let (subject, paragraphs, button): (String, Vec, (String, String)) = match kind { + Kind::CreditsLow { pool, percent, left, total, renews, next } => { + let what = if *pool { "open source credits" } else { "credits" }; + ( + format!("{org} has used {percent}% of this month's VisualCI {what}"), + vec![ + format!("{org} has {} of its {} {what} left this month. They renew on {renews}.", n(*left), n(*total)), + next.clone(), + ], + ("Open billing".into(), billing), + ) + } + Kind::OutOfCredits { plan, renews, packs } => ( + format!("{org} is out of VisualCI credits"), + vec![ + format!( + "{org} has used this month's credits on the {plan} plan and has no pack credits left. New builds \ + fail with an \"out of credits\" error instead of being compared, until the credits renew on {renews}." + ), + if *packs { + "Buy a credit pack, or turn on automatic packs, on the billing page.".to_string() + } else { + "Team includes 1,000,000 credits a month. Upgrade on the billing page.".to_string() + }, + ], + ("Open billing".into(), billing), + ), + Kind::PackBought { packs_this_month, limit, invoice_url } => ( + format!("VisualCI bought a credit pack for {org}"), + vec![ + format!( + "Credits were running low, so VisualCI bought a pack of {} credits for {} with {org}'s default card.", + n(CREDIT_PACK.credits), + money(CREDIT_PACK.price_cents) + ), + format!("That's {packs_this_month} of the {limit} automatic packs allowed this month."), + ], + match invoice_url { + Some(url) => ("View the invoice".into(), url.clone()), + None => ("Open billing".into(), billing), + }, + ), + Kind::AutoBuyPaused(Paused::Declined(reason)) => ( + format!("A VisualCI credit pack for {org} was declined"), + vec![ + format!("The card was declined ({reason}), so automatic credit packs are paused."), + "Update the card on the Payment methods tab, then save the automatic pack limit on the Plan tab to \ + turn them back on." + .to_string(), + ], + ("Payment methods".into(), format!("{billing}/payment-methods")), + ), + Kind::AutoBuyPaused(Paused::LimitReached(limit)) => ( + format!("{org} reached its limit of automatic credit packs"), + vec![ + format!("VisualCI has bought {limit} credit packs this month, the limit you set, so it won't buy more."), + "When the credits run out, builds stop being compared. Raise the limit or buy a pack on the billing page." + .to_string(), + ], + ("Open billing".into(), billing), + ), + Kind::PlanChanged { from, to } => ( + format!("{org} is now on the {to} plan"), + vec![format!("{org} moved from the {from} plan to the {to} plan. The change applies now.")], + ("Open billing".into(), billing), + ), + Kind::OpenSourceLost { project, reason } => ( + format!("{project} no longer uses VisualCI's open source credits"), + vec![ + format!("{project} isn't an open source project any more: {}.", sentence_part(reason)), + format!( + "Its builds use {org}'s plan credits from now on. If that's a mistake, fix the repository on \ + GitHub: VisualCI checks again when GitHub says it changed, and once a day." + ), + ], + ("Project settings".into(), format!("{}/{}/{project}?tab=settings", about.app_url, about.org_slug)), + ), + Kind::MadePrivate { project } => ( + format!("{project} is private now"), + vec![ + format!( + "The repository for {project} isn't public any more, so VisualCI made the project private too: \ + its builds, diffs and pull requests are no longer public." + ), + "If the repository is public again, an admin can make the project public in its settings.".to_string(), + ], + ("Project settings".into(), format!("{}/{}/{project}?tab=settings", about.app_url, about.org_slug)), + ), + Kind::RepositoryMoved { project, repository, to_org, by } => ( + format!("{repository} moved to another organization"), + vec![ + format!( + "{by}, a maintainer of {repository}, linked it to their organization {to_org} on VisualCI. A \ + repository belongs to one organization, so {project} isn't linked to it any more: its builds \ + no longer post checks or comments there." + ), + format!( + "If that's wrong, a maintainer of {repository} can link it to {project} again from the project's \ + settings, which moves it back." + ), + ], + ("Project settings".into(), format!("{}/{}/{project}?tab=settings", about.app_url, about.org_slug)), + ), + Kind::Welcome { name } => ( + "Welcome to VisualCI".to_string(), + vec![ + format!("Hi {name}, you're signed in to VisualCI."), + "To set it up, paste this into your coding agent:".to_string(), + format!("{COPY}{AGENT_PROMPT}"), + "It connects VisualCI's MCP server and adds a VisualCI step to your CI.".to_string(), + ], + ("Open VisualCI".into(), format!("{}/{}", about.app_url, about.org_slug).trim_end_matches('/').to_string()), + ), + Kind::Invited { inviter, role } => ( + format!("{inviter} invited you to {org} on VisualCI"), + vec![format!( + "{inviter} invited you to join {org} on VisualCI as {}. Sign in with this email address, or with GitHub, \ + and accept it there.", + article(role) + )], + ("See the invitation".into(), about.app_url.to_string()), + ), + Kind::AddedToOrg { role } => ( + format!("You joined {org} on VisualCI"), + vec![format!("You're now {} of {org} on VisualCI.", article(role))], + (format!("Open {org}"), format!("{}/{}", about.app_url, about.org_slug)), + ), + Kind::RemovedFromOrg => ( + format!("You were removed from {org} on VisualCI"), + vec![format!("You're no longer a member of {org} on VisualCI. Its admins can add you again.")], + ("Open VisualCI".into(), about.app_url.to_string()), + ), + Kind::DeviceSignIn { client, at } => ( + "The VisualCI CLI signed in as you".to_string(), + vec![ + format!("{client} signed in to your VisualCI account at {at}."), + "If that wasn't you, revoke it on your account page.".to_string(), + ], + ("Account".into(), format!("{}/account", about.app_url)), + ), + // Rendered as plain text above. + Kind::NewSignup { subject, text, .. } => (subject.clone(), vec![text.clone()], (String::new(), String::new())), + Kind::TokenCreated { name, project } => ( + format!("A new VisualCI token: {name}"), + vec![ + match project { + Some(p) => format!("A project token named \"{name}\" was created for {}/{p}.", about.org_slug), + None => format!("A personal token named \"{name}\" was created for your VisualCI account."), + }, + "If you didn't create it, delete it now.".to_string(), + ], + match project { + Some(p) => ("Project tokens".into(), format!("{}/{}/{p}?tab=tokens", about.app_url, about.org_slug)), + None => ("Account".into(), format!("{}/account", about.app_url)), + }, + ), + }; + let button = (button.0.as_str(), button.1.as_str()); + Rendered { text: text(¶graphs, button), html: html(¶graphs, button), subject } +} + +/// "Its repository is private." as part of a sentence: "its repository is private". +fn sentence_part(s: &str) -> String { + let s = s.trim().trim_end_matches('.'); + let mut c = s.chars(); + c.next().map_or_else(String::new, |f| f.to_lowercase().chain(c).collect()) +} + +fn article(role: &str) -> String { + let role = role.to_lowercase(); + if role.starts_with(['a', 'e', 'i', 'o', 'u']) { format!("an {role}") } else { format!("a {role}") } +} + +/// Every template with sample data, for the staff preview page and the snapshot tests. +#[must_use] +pub fn samples() -> Vec<(&'static str, Kind)> { + let renews = "1 January 2027".to_string(); + vec![ + ("Credits low (80%)", Kind::CreditsLow { + pool: false, + percent: 80, + left: 200_000, + total: 1_000_000, + renews: renews.clone(), + next: "When they run out, VisualCI buys a pack of 500,000 credits for $15 with the default card, up to 4 \ + packs this month." + .into(), + }), + ("Credits low (95%, Free)", Kind::CreditsLow { + pool: false, + percent: 95, + left: 1_250, + total: 25_000, + renews: renews.clone(), + next: "When they run out, builds aren't compared until the credits renew. Team includes 1,000,000 credits a month." + .into(), + }), + ("Open source credits low (80%)", Kind::CreditsLow { + pool: true, + percent: 80, + left: 200_000, + total: 1_000_000, + renews: renews.clone(), + next: "When they run out, open source projects use the plan's credits.".into(), + }), + ("Out of credits (Free)", Kind::OutOfCredits { plan: "Free".into(), renews: renews.clone(), packs: false }), + ("Out of credits (Team)", Kind::OutOfCredits { plan: "Team".into(), renews, packs: true }), + ("Pack bought", Kind::PackBought { + packs_this_month: 1, + limit: 4, + invoice_url: Some("https://invoice.stripe.com/i/acct_test/sample".into()), + }), + ("Automatic packs paused (declined)", Kind::AutoBuyPaused(Paused::Declined("your card has insufficient funds".into()))), + ("Automatic packs paused (limit)", Kind::AutoBuyPaused(Paused::LimitReached(4))), + ("Plan changed", Kind::PlanChanged { from: "Free".into(), to: "Team".into() }), + ("Open source status lost", Kind::OpenSourceLost { + project: "widgets".into(), + reason: "Its licence (BUSL-1.1) isn't OSI-approved.".into(), + }), + ("Project made private", Kind::MadePrivate { project: "widgets".into() }), + ( + "Repository moved", + Kind::RepositoryMoved { + project: "widgets".into(), + repository: "acme/widgets".into(), + to_org: "Acme".into(), + by: "Grace Hopper".into(), + }, + ), + ("Welcome", Kind::Welcome { name: "Ada".into() }), + ("Invitation", Kind::Invited { inviter: "Grace Hopper".into(), role: "member".into() }), + ("Added to an organization", Kind::AddedToOrg { role: "admin".into() }), + ("Removed from an organization", Kind::RemovedFromOrg), + ("CLI signed in", Kind::DeviceSignIn { + client: "visualci CLI on ada-laptop".into(), + at: "1 December 2026, 09:41 UTC".into(), + }), + ("Personal token created", Kind::TokenCreated { name: "Claude Code".into(), project: None }), + ("Project token created", Kind::TokenCreated { name: "GitHub Actions".into(), project: Some("web".into()) }), + ] +} diff --git a/app/src/skills.rs b/app/src/skills.rs new file mode 100644 index 00000000..b349227f --- /dev/null +++ b/app/src/skills.rs @@ -0,0 +1,58 @@ +//! VisualCI's agent skills (skills/ at the repository's root, generated from the docs pages by +//! server/frontend/scripts/skills.mjs), embedded at build time for the MCP server's `get_skill`. + +use include_dir::{Dir, include_dir}; + +static SKILLS: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/../skills"); + +/// One skill: its name, description and SKILL.md. +pub struct Skill { + pub name: &'static str, + pub description: String, + pub text: &'static str, +} + +/// Every skill, by name. +#[must_use] +pub fn all() -> Vec { + let mut skills: Vec = SKILLS + .dirs() + .filter_map(|dir| { + let name = dir.path().file_name()?.to_str()?; + let text = dir.get_file(dir.path().join("SKILL.md"))?.contents_utf8()?; + Some(Skill { name, description: description(text), text }) + }) + .collect(); + skills.sort_by_key(|s| s.name); + skills +} + +/// The SKILL.md of the skill called `name`. +#[must_use] +pub fn get(name: &str) -> Option { + all().into_iter().find(|s| s.name == name) +} + +/// The front matter's `description:`, a JSON string. +fn description(text: &str) -> String { + text.lines() + .find_map(|line| line.strip_prefix("description: ")) + .and_then(|raw| serde_json::from_str::(raw).ok()) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + #[test] + fn every_skill_has_a_description_and_the_main_one_lists_the_others() { + let skills = super::all(); + assert!(skills.len() > 10, "{}", skills.len()); + for s in &skills { + assert!(s.description.contains("Use when"), "{}", s.name); + } + let main = super::get("visualci").unwrap(); + for s in skills.iter().filter(|s| s.name != "visualci") { + assert!(main.text.contains(&format!("`{}`", s.name)), "{} isn't listed", s.name); + } + } +} diff --git a/app/src/storage/blobs.rs b/app/src/storage/blobs.rs index 35db6c83..a5c3eb13 100644 --- a/app/src/storage/blobs.rs +++ b/app/src/storage/blobs.rs @@ -129,14 +129,27 @@ impl BlobStore { /// # Errors /// When the store can't be reached. pub async fn verify(&self, sha256: &str) -> Result> { + let found = self.verify_object(&key(sha256)?, sha256).await?; + if found.is_none() { + self.delete(sha256).await?; + } + Ok(found) + } + + /// The size of the object at `key` when it's there, no larger than [`MAX_BLOB_BYTES`], and its bytes hash to + /// `sha256`; else `None`. Nothing is deleted. + /// + /// # Errors + /// When the store can't be reached. + pub async fn verify_object(&self, key: &str, sha256: &str) -> Result> { use sha2::Digest; - let url = self.bucket.get_object(Some(&self.credentials), &key(sha256)?).sign(URL_TTL); + let url = self.bucket.get_object(Some(&self.credentials), key).sign(URL_TTL); let mut response = self.http.get(url).send().await.map_err(|e| error(e.to_string()))?; if response.status().as_u16() == 404 { return Ok(None); } if !response.status().is_success() { - return Err(error(format!("blob {sha256}: HTTP {}", response.status()))); + return Err(error(format!("{key}: HTTP {}", response.status()))); } let limit = MAX_BLOB_BYTES; let mut hasher = sha2::Sha256::new(); @@ -147,11 +160,17 @@ impl BlobStore { too_big = read > limit; hasher.update(&chunk); } - if !too_big && hex::encode(hasher.finalize()) == sha256 { - return Ok(Some(read)); - } - self.delete(sha256).await?; - Ok(None) + Ok((!too_big && hex::encode(hasher.finalize()) == sha256).then_some(read)) + } + + /// A URL a client can PUT an object other than a blob to (a renderer's proof that it holds a PNG), for minutes. The + /// size is part of the signature (`Content-Length`), so the URL takes exactly that many bytes and nothing larger. + #[must_use] + pub fn upload_url_for_key(&self, key: &str, size: u64) -> String { + let length = size.to_string(); + let mut action = self.public_bucket.put_object(Some(&self.credentials), key); + action.headers_mut().insert("content-length", length.as_str()); + action.sign(UPLOAD_TTL).to_string() } /// Store bytes under their SHA-256 and return it. @@ -190,6 +209,48 @@ impl BlobStore { } } + /// A URL a client can GET a stored object other than a blob from (a bulk download's archive), for an hour. + pub fn object_url(&self, key: &str) -> String { + self.public_bucket.get_object(Some(&self.credentials), key).sign(URL_TTL).to_string() + } + + /// Delete a stored object other than a blob. Deleting one that isn't there succeeds. + /// + /// # Errors + /// When the store can't be reached or refuses. + pub async fn delete_object(&self, key: &str) -> Result<()> { + let url = self.bucket.delete_object(Some(&self.credentials), key).sign(URL_TTL); + let response = self.http.delete(url).send().await.map_err(|e| error(e.to_string()))?; + let status = response.status(); + if status.is_success() || status.as_u16() == 404 { + Ok(()) + } else { + Err(error(format!("deleting {key}: HTTP {status}"))) + } + } + + /// Start a multipart upload to `key`, for an object written in parts as it's made (a bulk download). + /// + /// # Errors + /// When the store can't be reached or refuses. + pub async fn start_multipart(&self, key: &str, content_type: &str) -> Result { + let url = self.bucket.create_multipart_upload(Some(&self.credentials), key).sign(URL_TTL); + let response = + self.http.post(url).header("content-type", content_type).send().await.map_err(|e| error(e.to_string()))?; + if !response.status().is_success() { + return Err(error(format!("starting upload of {key}: HTTP {}", response.status()))); + } + let body = response.text().await.map_err(|e| error(e.to_string()))?; + let parsed = rusty_s3::actions::CreateMultipartUpload::parse_response(&body) + .map_err(|e| error(format!("starting upload of {key}: {e}")))?; + Ok(Multipart { + store: self.clone(), + key: key.to_string(), + upload_id: parsed.upload_id().to_string(), + etags: vec![], + }) + } + /// Create the bucket if it doesn't exist (development and tests; production buckets are made by Terraform). /// /// # Errors @@ -215,6 +276,72 @@ impl BlobStore { } } +/// An upload in parts ([`BlobStore::start_multipart`]): every part but the last at least 5 MiB. +pub struct Multipart { + store: BlobStore, + key: String, + upload_id: String, + etags: Vec, +} + +impl Multipart { + /// Upload the next part. + /// + /// # Errors + /// When the store can't be reached or refuses. + pub async fn part(&mut self, bytes: Vec) -> Result<()> { + let number = u16::try_from(self.etags.len() + 1).map_err(|_| error("too many parts"))?; + let url = self + .store + .bucket + .upload_part(Some(&self.store.credentials), &self.key, number, &self.upload_id) + .sign(URL_TTL); + let response = self.store.http.put(url).body(bytes).send().await.map_err(|e| error(e.to_string()))?; + if !response.status().is_success() { + return Err(error(format!("uploading part {number} of {}: HTTP {}", self.key, response.status()))); + } + let etag = response + .headers() + .get("etag") + .and_then(|v| v.to_str().ok()) + .ok_or_else(|| error(format!("part {number} of {}: no ETag", self.key)))?; + self.etags.push(etag.to_string()); + Ok(()) + } + + /// Finish the upload: the object appears. + /// + /// # Errors + /// When the store can't be reached or refuses. + pub async fn complete(self) -> Result<()> { + let action = self.store.bucket.complete_multipart_upload( + Some(&self.store.credentials), + &self.key, + &self.upload_id, + self.etags.iter().map(String::as_str), + ); + let url = action.sign(URL_TTL); + let body = action.body(); + let response = self.store.http.post(url).body(body).send().await.map_err(|e| error(e.to_string()))?; + if !response.status().is_success() { + return Err(error(format!("finishing upload of {}: HTTP {}", self.key, response.status()))); + } + Ok(()) + } + + /// Give the upload up, so its parts don't stay in the bucket. + pub async fn abort(self) { + let url = self + .store + .bucket + .abort_multipart_upload(Some(&self.store.credentials), &self.key, &self.upload_id) + .sign(URL_TTL); + if let Err(e) = self.store.http.delete(url).send().await { + tracing::warn!(key = %self.key, error = %e, "aborting a multipart upload failed"); + } + } +} + /// The store's factory: the container builds it once per application. #[laravel::container::singleton] async fn blob_store(config: laravel::config::Section) -> laravel::Result { diff --git a/app/src/storage/texts.rs b/app/src/storage/texts.rs index 897b0377..7435c897 100644 --- a/app/src/storage/texts.rs +++ b/app/src/storage/texts.rs @@ -30,9 +30,15 @@ pub async fn store(bodies: &[&str]) -> laravel::Result> { let rows: Vec = unique.into_iter().map(|(s, b)| Row { sha256: s.to_string(), body: b.to_string() }).collect(); // Two parameters a row, well under PostgreSQL's 65,535. for chunk in rows.chunks(10_000) { - db::query!("INSERT INTO texts (sha256, body) VALUES {...chunk(sha256, body)} ON CONFLICT DO NOTHING") - .insert() - .await?; + // A text stored again that's older than a day gets a new `created_at`: retention deletes only texts older than + // a day that nothing names, and the page or render naming it now may not be in its keep sets. + db::query!( + "INSERT INTO texts (sha256, body) VALUES {...chunk(sha256, body)} \ + ON CONFLICT (sha256) DO UPDATE SET created_at = now() \ + WHERE texts.created_at < now() - interval '12 hours'" + ) + .insert() + .await?; } Ok(shas) } diff --git a/app/src/testing.rs b/app/src/testing.rs index db01bf8f..4370da6f 100644 --- a/app/src/testing.rs +++ b/app/src/testing.rs @@ -7,7 +7,7 @@ use laravel::Application; use laravel::foundation::ApplicationBuilder; -const CI_DATABASE: &str = "postgres://loco:loco@127.0.0.1:55433/visualci_app_test"; +const CI_DATABASE: &str = "postgres://visualci:visualci@127.0.0.1:55433/visualci_app_test"; pub fn create() -> Application { configure().create() @@ -36,6 +36,9 @@ pub fn configure() -> ApplicationBuilder { ("S3_ACCESS_KEY_ID", "visualci"), ("S3_SECRET_ACCESS_KEY", "visualci-dev-secret"), ("APP_URL", "https://app.visualci.test"), + ("RENDERER_TOKEN", "renderer-test-token"), + ("RENDERER_VERSION", "1"), + ("METRICS_TOKEN", "metrics-test-token"), ]) .with_env("DATABASE_URL", url) .refresh_database() diff --git a/app/target/debug/build/bigdecimal-0f52ef40f42fdf2c/out/default_precision.rs b/app/target/debug/build/bigdecimal-0f52ef40f42fdf2c/out/default_precision.rs deleted file mode 100644 index 9dbdfaba..00000000 --- a/app/target/debug/build/bigdecimal-0f52ef40f42fdf2c/out/default_precision.rs +++ /dev/null @@ -1 +0,0 @@ -const DEFAULT_PRECISION: u64 = 100; \ No newline at end of file diff --git a/app/target/debug/build/bigdecimal-0f52ef40f42fdf2c/out/default_rounding_mode.rs b/app/target/debug/build/bigdecimal-0f52ef40f42fdf2c/out/default_rounding_mode.rs deleted file mode 100644 index 7a5f069e..00000000 --- a/app/target/debug/build/bigdecimal-0f52ef40f42fdf2c/out/default_rounding_mode.rs +++ /dev/null @@ -1 +0,0 @@ -const DEFAULT_ROUNDING_MODE: RoundingMode = RoundingMode::HalfEven; \ No newline at end of file diff --git a/app/target/debug/build/bigdecimal-0f52ef40f42fdf2c/out/exponential_format_threshold.rs b/app/target/debug/build/bigdecimal-0f52ef40f42fdf2c/out/exponential_format_threshold.rs deleted file mode 100644 index 28909913..00000000 --- a/app/target/debug/build/bigdecimal-0f52ef40f42fdf2c/out/exponential_format_threshold.rs +++ /dev/null @@ -1,3 +0,0 @@ -const EXPONENTIAL_FORMAT_LEADING_ZERO_THRESHOLD: usize = 5; -const EXPONENTIAL_FORMAT_TRAILING_ZERO_THRESHOLD: usize = 15; -const FMT_MAX_INTEGER_PADDING: usize = 1000; \ No newline at end of file diff --git a/app/target/debug/build/bigdecimal-0f52ef40f42fdf2c/out/serde_scale_limit.rs b/app/target/debug/build/bigdecimal-0f52ef40f42fdf2c/out/serde_scale_limit.rs deleted file mode 100644 index f04f5f61..00000000 --- a/app/target/debug/build/bigdecimal-0f52ef40f42fdf2c/out/serde_scale_limit.rs +++ /dev/null @@ -1 +0,0 @@ -const SERDE_SCALE_LIMIT: i64 = 150000; \ No newline at end of file diff --git a/app/target/debug/build/mime_guess-3b56f0e01700d021/out/mime_types_generated.rs b/app/target/debug/build/mime_guess-3b56f0e01700d021/out/mime_types_generated.rs deleted file mode 100644 index 9b19ce41..00000000 --- a/app/target/debug/build/mime_guess-3b56f0e01700d021/out/mime_types_generated.rs +++ /dev/null @@ -1,2 +0,0 @@ -static REV_MAPPINGS: &'static [(UniCase<&'static str>, TopLevelExts)] = &[(UniCase::ascii("application"), TopLevelExts { start: 0, end: 941, subs: &[(UniCase::ascii("acad"), (0, 1)),(UniCase::ascii("andrew-inset"), (1, 2)),(UniCase::ascii("annodex"), (2, 3)),(UniCase::ascii("applixware"), (3, 4)),(UniCase::ascii("atom+xml"), (4, 5)),(UniCase::ascii("atomcat+xml"), (5, 6)),(UniCase::ascii("atomsvc+xml"), (6, 7)),(UniCase::ascii("bdoc"), (7, 8)),(UniCase::ascii("ccxml+xml"), (8, 9)),(UniCase::ascii("cdmi-capability"), (9, 10)),(UniCase::ascii("cdmi-container"), (10, 11)),(UniCase::ascii("cdmi-domain"), (11, 12)),(UniCase::ascii("cdmi-object"), (12, 13)),(UniCase::ascii("cdmi-queue"), (13, 14)),(UniCase::ascii("cu-seeme"), (14, 15)),(UniCase::ascii("dash+xml"), (15, 16)),(UniCase::ascii("davmount+xml"), (16, 17)),(UniCase::ascii("directx"), (17, 18)),(UniCase::ascii("docbook+xml"), (18, 19)),(UniCase::ascii("dssc+der"), (19, 20)),(UniCase::ascii("dssc+xml"), (20, 21)),(UniCase::ascii("emma+xml"), (21, 22)),(UniCase::ascii("envoy"), (22, 23)),(UniCase::ascii("epub+zip"), (23, 24)),(UniCase::ascii("etl"), (24, 25)),(UniCase::ascii("exi"), (25, 26)),(UniCase::ascii("font-sfnt"), (26, 28)),(UniCase::ascii("font-tdpfr"), (28, 29)),(UniCase::ascii("font-woff"), (29, 30)),(UniCase::ascii("fractals"), (30, 31)),(UniCase::ascii("fsharp-script"), (31, 33)),(UniCase::ascii("futuresplash"), (33, 34)),(UniCase::ascii("geo+json"), (34, 35)),(UniCase::ascii("gml+xml"), (35, 36)),(UniCase::ascii("gpx+xml"), (36, 37)),(UniCase::ascii("gxf"), (37, 38)),(UniCase::ascii("gzip"), (38, 39)),(UniCase::ascii("hjson"), (39, 40)),(UniCase::ascii("hta"), (40, 41)),(UniCase::ascii("hyperstudio"), (41, 42)),(UniCase::ascii("inkml+xml"), (42, 44)),(UniCase::ascii("internet-property-stream"), (44, 45)),(UniCase::ascii("ipfix"), (45, 46)),(UniCase::ascii("java-archive"), (46, 49)),(UniCase::ascii("java-serialized-object"), (49, 50)),(UniCase::ascii("javascript"), (50, 51)),(UniCase::ascii("json"), (51, 52)),(UniCase::ascii("json5"), (52, 53)),(UniCase::ascii("jsonml+json"), (53, 54)),(UniCase::ascii("ld+json"), (54, 55)),(UniCase::ascii("liquidmotion"), (55, 57)),(UniCase::ascii("lost+xml"), (57, 58)),(UniCase::ascii("mac-binhex40"), (58, 59)),(UniCase::ascii("mac-compactpro"), (59, 60)),(UniCase::ascii("mads+xml"), (60, 61)),(UniCase::ascii("manifest+json"), (61, 62)),(UniCase::ascii("marc"), (62, 63)),(UniCase::ascii("marcxml+xml"), (63, 64)),(UniCase::ascii("mathematica"), (64, 67)),(UniCase::ascii("mathml+xml"), (67, 68)),(UniCase::ascii("mbox"), (68, 69)),(UniCase::ascii("mediaservercontrol+xml"), (69, 70)),(UniCase::ascii("metalink+xml"), (70, 71)),(UniCase::ascii("metalink4+xml"), (71, 72)),(UniCase::ascii("mets+xml"), (72, 73)),(UniCase::ascii("mods+xml"), (73, 74)),(UniCase::ascii("mp21"), (74, 76)),(UniCase::ascii("mp4"), (76, 77)),(UniCase::ascii("mpeg"), (77, 78)),(UniCase::ascii("ms-vsi"), (78, 79)),(UniCase::ascii("msaccess"), (79, 86)),(UniCase::ascii("msaccess.addin"), (86, 87)),(UniCase::ascii("msaccess.cab"), (87, 88)),(UniCase::ascii("msaccess.ftemplate"), (88, 89)),(UniCase::ascii("msaccess.runtime"), (89, 90)),(UniCase::ascii("msaccess.webapplication"), (90, 91)),(UniCase::ascii("msword"), (91, 95)),(UniCase::ascii("mxf"), (95, 96)),(UniCase::ascii("n-quads"), (96, 97)),(UniCase::ascii("n-triples"), (97, 98)),(UniCase::ascii("octet-stream"), (98, 169)),(UniCase::ascii("oda"), (169, 170)),(UniCase::ascii("oebps-package+xml"), (170, 171)),(UniCase::ascii("ogg"), (171, 172)),(UniCase::ascii("olescript"), (172, 173)),(UniCase::ascii("omdoc+xml"), (173, 174)),(UniCase::ascii("onenote"), (174, 180)),(UniCase::ascii("opensearchdescription+xml"), (180, 181)),(UniCase::ascii("oxps"), (181, 182)),(UniCase::ascii("patch-ops-error+xml"), (182, 183)),(UniCase::ascii("pdf"), (183, 184)),(UniCase::ascii("pgp-encrypted"), (184, 185)),(UniCase::ascii("pgp-signature"), (185, 187)),(UniCase::ascii("pics-rules"), (187, 188)),(UniCase::ascii("pkcs10"), (188, 189)),(UniCase::ascii("pkcs7-mime"), (189, 191)),(UniCase::ascii("pkcs7-signature"), (191, 192)),(UniCase::ascii("pkcs8"), (192, 193)),(UniCase::ascii("pkix-attr-cert"), (193, 194)),(UniCase::ascii("pkix-crl"), (194, 195)),(UniCase::ascii("pkix-pkipath"), (195, 196)),(UniCase::ascii("pkixcmp"), (196, 197)),(UniCase::ascii("postscript"), (197, 200)),(UniCase::ascii("PowerShell"), (200, 201)),(UniCase::ascii("prs.cww"), (201, 202)),(UniCase::ascii("pskc+xml"), (202, 203)),(UniCase::ascii("raml+yaml"), (203, 204)),(UniCase::ascii("rat-file"), (204, 205)),(UniCase::ascii("rdf+xml"), (205, 206)),(UniCase::ascii("reginfo+xml"), (206, 207)),(UniCase::ascii("relax-ng-compact-syntax"), (207, 208)),(UniCase::ascii("resource-lists+xml"), (208, 209)),(UniCase::ascii("resource-lists-diff+xml"), (209, 210)),(UniCase::ascii("rpki-ghostbusters"), (210, 211)),(UniCase::ascii("rpki-manifest"), (211, 212)),(UniCase::ascii("rpki-roa"), (212, 213)),(UniCase::ascii("rsd+xml"), (213, 214)),(UniCase::ascii("rss+xml"), (214, 215)),(UniCase::ascii("rtf"), (215, 216)),(UniCase::ascii("sbml+xml"), (216, 217)),(UniCase::ascii("scvp-cv-request"), (217, 218)),(UniCase::ascii("scvp-cv-response"), (218, 219)),(UniCase::ascii("scvp-vp-request"), (219, 220)),(UniCase::ascii("scvp-vp-response"), (220, 221)),(UniCase::ascii("sdp"), (221, 222)),(UniCase::ascii("set-payment-initiation"), (222, 223)),(UniCase::ascii("set-registration-initiation"), (223, 224)),(UniCase::ascii("shf+xml"), (224, 225)),(UniCase::ascii("smil+xml"), (225, 226)),(UniCase::ascii("sparql-query"), (226, 227)),(UniCase::ascii("sparql-results+xml"), (227, 228)),(UniCase::ascii("srgs"), (228, 229)),(UniCase::ascii("srgs+xml"), (229, 230)),(UniCase::ascii("sru+xml"), (230, 231)),(UniCase::ascii("ssdl+xml"), (231, 232)),(UniCase::ascii("ssml+xml"), (232, 233)),(UniCase::ascii("step"), (233, 235)),(UniCase::ascii("streamingmedia"), (235, 236)),(UniCase::ascii("tei+xml"), (236, 238)),(UniCase::ascii("thraud+xml"), (238, 239)),(UniCase::ascii("timestamped-data"), (239, 240)),(UniCase::ascii("trig"), (240, 241)),(UniCase::ascii("vnd.3gpp.pic-bw-large"), (241, 242)),(UniCase::ascii("vnd.3gpp.pic-bw-small"), (242, 243)),(UniCase::ascii("vnd.3gpp.pic-bw-var"), (243, 244)),(UniCase::ascii("vnd.3gpp2.tcap"), (244, 245)),(UniCase::ascii("vnd.3m.post-it-notes"), (245, 246)),(UniCase::ascii("vnd.accpac.simply.aso"), (246, 247)),(UniCase::ascii("vnd.accpac.simply.imp"), (247, 248)),(UniCase::ascii("vnd.acucobol"), (248, 249)),(UniCase::ascii("vnd.acucorp"), (249, 251)),(UniCase::ascii("vnd.adobe.air-application-installer-package+zip"), (251, 252)),(UniCase::ascii("vnd.adobe.formscentral.fcdt"), (252, 253)),(UniCase::ascii("vnd.adobe.fxp"), (253, 255)),(UniCase::ascii("vnd.adobe.xdp+xml"), (255, 256)),(UniCase::ascii("vnd.adobe.xfdf"), (256, 257)),(UniCase::ascii("vnd.ahead.space"), (257, 258)),(UniCase::ascii("vnd.airzip.filesecure.azf"), (258, 259)),(UniCase::ascii("vnd.airzip.filesecure.azs"), (259, 260)),(UniCase::ascii("vnd.amazon.ebook"), (260, 261)),(UniCase::ascii("vnd.americandynamics.acc"), (261, 262)),(UniCase::ascii("vnd.amiga.ami"), (262, 263)),(UniCase::ascii("vnd.android.package-archive"), (263, 264)),(UniCase::ascii("vnd.anser-web-certificate-issue-initiation"), (264, 265)),(UniCase::ascii("vnd.anser-web-funds-transfer-initiation"), (265, 266)),(UniCase::ascii("vnd.antix.game-component"), (266, 267)),(UniCase::ascii("vnd.apache.parquet"), (267, 268)),(UniCase::ascii("vnd.apple.installer+xml"), (268, 269)),(UniCase::ascii("vnd.apple.pkpass"), (269, 270)),(UniCase::ascii("vnd.aristanetworks.swi"), (270, 271)),(UniCase::ascii("vnd.astraea-software.iota"), (271, 272)),(UniCase::ascii("vnd.audiograph"), (272, 273)),(UniCase::ascii("vnd.blueice.multipass"), (273, 274)),(UniCase::ascii("vnd.bmi"), (274, 275)),(UniCase::ascii("vnd.businessobjects"), (275, 276)),(UniCase::ascii("vnd.chemdraw+xml"), (276, 277)),(UniCase::ascii("vnd.chipnuts.karaoke-mmd"), (277, 278)),(UniCase::ascii("vnd.cinderella"), (278, 279)),(UniCase::ascii("vnd.citationstyles.style+xml"), (279, 280)),(UniCase::ascii("vnd.claymore"), (280, 281)),(UniCase::ascii("vnd.cloanto.rp9"), (281, 282)),(UniCase::ascii("vnd.clonk.c4group"), (282, 287)),(UniCase::ascii("vnd.cluetrust.cartomobile-config"), (287, 288)),(UniCase::ascii("vnd.cluetrust.cartomobile-config-pkg"), (288, 289)),(UniCase::ascii("vnd.commonspace"), (289, 290)),(UniCase::ascii("vnd.contact.cmsg"), (290, 291)),(UniCase::ascii("vnd.cosmocaller"), (291, 292)),(UniCase::ascii("vnd.crick.clicker"), (292, 293)),(UniCase::ascii("vnd.crick.clicker.keyboard"), (293, 294)),(UniCase::ascii("vnd.crick.clicker.palette"), (294, 295)),(UniCase::ascii("vnd.crick.clicker.template"), (295, 296)),(UniCase::ascii("vnd.crick.clicker.wordbank"), (296, 297)),(UniCase::ascii("vnd.criticaltools.wbs+xml"), (297, 298)),(UniCase::ascii("vnd.cups-ppd"), (298, 299)),(UniCase::ascii("vnd.curl.car"), (299, 300)),(UniCase::ascii("vnd.curl.pcurl"), (300, 301)),(UniCase::ascii("vnd.dart"), (301, 302)),(UniCase::ascii("vnd.data-vision.rdz"), (302, 303)),(UniCase::ascii("vnd.dece.data"), (303, 307)),(UniCase::ascii("vnd.dece.ttml+xml"), (307, 309)),(UniCase::ascii("vnd.dece.unspecified"), (309, 311)),(UniCase::ascii("vnd.dece.zip"), (311, 313)),(UniCase::ascii("vnd.denovo.fcselayout-link"), (313, 314)),(UniCase::ascii("vnd.dna"), (314, 315)),(UniCase::ascii("vnd.dolby.mlp"), (315, 316)),(UniCase::ascii("vnd.dpgraph"), (316, 317)),(UniCase::ascii("vnd.dreamfactory"), (317, 318)),(UniCase::ascii("vnd.ds-keypoint"), (318, 319)),(UniCase::ascii("vnd.dvb.ait"), (319, 320)),(UniCase::ascii("vnd.dynageo"), (320, 321)),(UniCase::ascii("vnd.ecowin.chart"), (321, 322)),(UniCase::ascii("vnd.enliven"), (322, 323)),(UniCase::ascii("vnd.epson.esf"), (323, 324)),(UniCase::ascii("vnd.epson.msf"), (324, 325)),(UniCase::ascii("vnd.epson.quickanime"), (325, 326)),(UniCase::ascii("vnd.epson.salt"), (326, 327)),(UniCase::ascii("vnd.epson.ssf"), (327, 328)),(UniCase::ascii("vnd.eszigno3+xml"), (328, 330)),(UniCase::ascii("vnd.ezpix-album"), (330, 331)),(UniCase::ascii("vnd.ezpix-package"), (331, 332)),(UniCase::ascii("vnd.fdf"), (332, 333)),(UniCase::ascii("vnd.fdsn.mseed"), (333, 334)),(UniCase::ascii("vnd.fdsn.seed"), (334, 336)),(UniCase::ascii("vnd.flographit"), (336, 337)),(UniCase::ascii("vnd.fluxtime.clip"), (337, 338)),(UniCase::ascii("vnd.framemaker"), (338, 342)),(UniCase::ascii("vnd.frogans.fnc"), (342, 343)),(UniCase::ascii("vnd.frogans.ltf"), (343, 344)),(UniCase::ascii("vnd.fsc.weblaunch"), (344, 345)),(UniCase::ascii("vnd.fujitsu.oasys"), (345, 346)),(UniCase::ascii("vnd.fujitsu.oasys2"), (346, 347)),(UniCase::ascii("vnd.fujitsu.oasys3"), (347, 348)),(UniCase::ascii("vnd.fujitsu.oasysgp"), (348, 349)),(UniCase::ascii("vnd.fujitsu.oasysprs"), (349, 350)),(UniCase::ascii("vnd.fujixerox.ddd"), (350, 351)),(UniCase::ascii("vnd.fujixerox.docuworks"), (351, 352)),(UniCase::ascii("vnd.fujixerox.docuworks.binder"), (352, 353)),(UniCase::ascii("vnd.fuzzysheet"), (353, 354)),(UniCase::ascii("vnd.genomatix.tuxedo"), (354, 355)),(UniCase::ascii("vnd.geogebra.file"), (355, 356)),(UniCase::ascii("vnd.geogebra.tool"), (356, 357)),(UniCase::ascii("vnd.geometry-explorer"), (357, 359)),(UniCase::ascii("vnd.geonext"), (359, 360)),(UniCase::ascii("vnd.geoplan"), (360, 361)),(UniCase::ascii("vnd.geospace"), (361, 362)),(UniCase::ascii("vnd.gmx"), (362, 363)),(UniCase::ascii("vnd.google-apps.document"), (363, 364)),(UniCase::ascii("vnd.google-apps.presentation"), (364, 365)),(UniCase::ascii("vnd.google-apps.spreadsheet"), (365, 366)),(UniCase::ascii("vnd.google-earth.kml+xml"), (366, 367)),(UniCase::ascii("vnd.google-earth.kmz"), (367, 368)),(UniCase::ascii("vnd.grafeq"), (368, 370)),(UniCase::ascii("vnd.groove-account"), (370, 371)),(UniCase::ascii("vnd.groove-help"), (371, 372)),(UniCase::ascii("vnd.groove-identity-message"), (372, 373)),(UniCase::ascii("vnd.groove-injector"), (373, 374)),(UniCase::ascii("vnd.groove-tool-message"), (374, 375)),(UniCase::ascii("vnd.groove-tool-template"), (375, 376)),(UniCase::ascii("vnd.groove-vcard"), (376, 377)),(UniCase::ascii("vnd.hal+xml"), (377, 378)),(UniCase::ascii("vnd.handheld-entertainment+xml"), (378, 379)),(UniCase::ascii("vnd.hbci"), (379, 380)),(UniCase::ascii("vnd.hhe.lesson-player"), (380, 381)),(UniCase::ascii("vnd.hp-hpgl"), (381, 382)),(UniCase::ascii("vnd.hp-hpid"), (382, 383)),(UniCase::ascii("vnd.hp-hps"), (383, 384)),(UniCase::ascii("vnd.hp-jlyt"), (384, 385)),(UniCase::ascii("vnd.hp-pcl"), (385, 386)),(UniCase::ascii("vnd.hp-pclxl"), (386, 387)),(UniCase::ascii("vnd.hydrostatix.sof-data"), (387, 388)),(UniCase::ascii("vnd.ibm.minipay"), (388, 389)),(UniCase::ascii("vnd.ibm.modcap"), (389, 392)),(UniCase::ascii("vnd.ibm.rights-management"), (392, 393)),(UniCase::ascii("vnd.ibm.secure-container"), (393, 394)),(UniCase::ascii("vnd.iccprofile"), (394, 396)),(UniCase::ascii("vnd.igloader"), (396, 397)),(UniCase::ascii("vnd.immervision-ivp"), (397, 398)),(UniCase::ascii("vnd.immervision-ivu"), (398, 399)),(UniCase::ascii("vnd.insors.igm"), (399, 400)),(UniCase::ascii("vnd.intercon.formnet"), (400, 402)),(UniCase::ascii("vnd.intergeo"), (402, 403)),(UniCase::ascii("vnd.intu.qbo"), (403, 404)),(UniCase::ascii("vnd.intu.qfx"), (404, 405)),(UniCase::ascii("vnd.ipunplugged.rcprofile"), (405, 406)),(UniCase::ascii("vnd.irepository.package+xml"), (406, 407)),(UniCase::ascii("vnd.is-xpr"), (407, 408)),(UniCase::ascii("vnd.isac.fcs"), (408, 409)),(UniCase::ascii("vnd.jam"), (409, 410)),(UniCase::ascii("vnd.jcp.javame.midlet-rms"), (410, 411)),(UniCase::ascii("vnd.jisp"), (411, 412)),(UniCase::ascii("vnd.joost.joda-archive"), (412, 413)),(UniCase::ascii("vnd.kahootz"), (413, 415)),(UniCase::ascii("vnd.kde.karbon"), (415, 416)),(UniCase::ascii("vnd.kde.kchart"), (416, 417)),(UniCase::ascii("vnd.kde.kformula"), (417, 418)),(UniCase::ascii("vnd.kde.kivio"), (418, 419)),(UniCase::ascii("vnd.kde.kontour"), (419, 420)),(UniCase::ascii("vnd.kde.kpresenter"), (420, 422)),(UniCase::ascii("vnd.kde.kspread"), (422, 423)),(UniCase::ascii("vnd.kde.kword"), (423, 425)),(UniCase::ascii("vnd.kenameaapp"), (425, 426)),(UniCase::ascii("vnd.kidspiration"), (426, 427)),(UniCase::ascii("vnd.kinar"), (427, 429)),(UniCase::ascii("vnd.koan"), (429, 432)),(UniCase::ascii("vnd.kodak-descriptor"), (432, 433)),(UniCase::ascii("vnd.las.las+xml"), (433, 434)),(UniCase::ascii("vnd.llamagraphics.life-balance.desktop"), (434, 435)),(UniCase::ascii("vnd.llamagraphics.life-balance.exchange+xml"), (435, 436)),(UniCase::ascii("vnd.lotus-1-2-3"), (436, 437)),(UniCase::ascii("vnd.lotus-approach"), (437, 438)),(UniCase::ascii("vnd.lotus-freelance"), (438, 439)),(UniCase::ascii("vnd.lotus-notes"), (439, 440)),(UniCase::ascii("vnd.lotus-organizer"), (440, 441)),(UniCase::ascii("vnd.lotus-screencam"), (441, 442)),(UniCase::ascii("vnd.lotus-wordpro"), (442, 443)),(UniCase::ascii("vnd.macports.portpkg"), (443, 444)),(UniCase::ascii("vnd.mcd"), (444, 445)),(UniCase::ascii("vnd.medcalcdata"), (445, 446)),(UniCase::ascii("vnd.mediastation.cdkey"), (446, 447)),(UniCase::ascii("vnd.mfer"), (447, 448)),(UniCase::ascii("vnd.mfmp"), (448, 449)),(UniCase::ascii("vnd.micrografx.flo"), (449, 450)),(UniCase::ascii("vnd.micrografx.igx"), (450, 451)),(UniCase::ascii("vnd.mif"), (451, 452)),(UniCase::ascii("vnd.mobius.daf"), (452, 453)),(UniCase::ascii("vnd.mobius.dis"), (453, 454)),(UniCase::ascii("vnd.mobius.mbk"), (454, 455)),(UniCase::ascii("vnd.mobius.mqy"), (455, 456)),(UniCase::ascii("vnd.mobius.msl"), (456, 457)),(UniCase::ascii("vnd.mobius.plc"), (457, 458)),(UniCase::ascii("vnd.mobius.txf"), (458, 459)),(UniCase::ascii("vnd.mophun.application"), (459, 460)),(UniCase::ascii("vnd.mophun.certificate"), (460, 461)),(UniCase::ascii("vnd.mozilla.xul+xml"), (461, 462)),(UniCase::ascii("vnd.ms-artgalry"), (462, 463)),(UniCase::ascii("vnd.ms-excel"), (463, 473)),(UniCase::ascii("vnd.ms-excel.addin.macroEnabled.12"), (473, 474)),(UniCase::ascii("vnd.ms-excel.sheet.binary.macroEnabled.12"), (474, 475)),(UniCase::ascii("vnd.ms-excel.sheet.macroEnabled.12"), (475, 476)),(UniCase::ascii("vnd.ms-excel.template.macroEnabled.12"), (476, 477)),(UniCase::ascii("vnd.ms-fontobject"), (477, 478)),(UniCase::ascii("vnd.ms-htmlhelp"), (478, 479)),(UniCase::ascii("vnd.ms-ims"), (479, 480)),(UniCase::ascii("vnd.ms-lrm"), (480, 481)),(UniCase::ascii("vnd.ms-mediapackage"), (481, 482)),(UniCase::ascii("vnd.ms-office.calx"), (482, 483)),(UniCase::ascii("vnd.ms-officetheme"), (483, 484)),(UniCase::ascii("vnd.ms-outlook"), (484, 486)),(UniCase::ascii("vnd.ms-pki.certstore"), (486, 487)),(UniCase::ascii("vnd.ms-pki.pko"), (487, 488)),(UniCase::ascii("vnd.ms-pki.seccat"), (488, 489)),(UniCase::ascii("vnd.ms-pki.stl"), (489, 490)),(UniCase::ascii("vnd.ms-powerpoint"), (490, 495)),(UniCase::ascii("vnd.ms-powerpoint.addin.macroEnabled.12"), (495, 496)),(UniCase::ascii("vnd.ms-powerpoint.presentation.macroEnabled.12"), (496, 497)),(UniCase::ascii("vnd.ms-powerpoint.slide.macroEnabled.12"), (497, 498)),(UniCase::ascii("vnd.ms-powerpoint.slideshow.macroEnabled.12"), (498, 499)),(UniCase::ascii("vnd.ms-powerpoint.template.macroEnabled.12"), (499, 500)),(UniCase::ascii("vnd.ms-project"), (500, 502)),(UniCase::ascii("vnd.ms-visio.viewer"), (502, 503)),(UniCase::ascii("vnd.ms-word.document.macroEnabled.12"), (503, 504)),(UniCase::ascii("vnd.ms-word.template.macroEnabled.12"), (504, 505)),(UniCase::ascii("vnd.ms-works"), (505, 509)),(UniCase::ascii("vnd.ms-wpl"), (509, 510)),(UniCase::ascii("vnd.ms-xpsdocument"), (510, 511)),(UniCase::ascii("vnd.mseq"), (511, 512)),(UniCase::ascii("vnd.musician"), (512, 513)),(UniCase::ascii("vnd.muvee.style"), (513, 514)),(UniCase::ascii("vnd.mynfc"), (514, 515)),(UniCase::ascii("vnd.neurolanguage.nlu"), (515, 516)),(UniCase::ascii("vnd.nitf"), (516, 518)),(UniCase::ascii("vnd.noblenet-directory"), (518, 519)),(UniCase::ascii("vnd.noblenet-sealer"), (519, 520)),(UniCase::ascii("vnd.noblenet-web"), (520, 521)),(UniCase::ascii("vnd.nokia.n-gage.data"), (521, 522)),(UniCase::ascii("vnd.nokia.n-gage.symbian.install"), (522, 523)),(UniCase::ascii("vnd.nokia.radio-preset"), (523, 524)),(UniCase::ascii("vnd.nokia.radio-presets"), (524, 525)),(UniCase::ascii("vnd.novadigm.edm"), (525, 526)),(UniCase::ascii("vnd.novadigm.edx"), (526, 527)),(UniCase::ascii("vnd.novadigm.ext"), (527, 528)),(UniCase::ascii("vnd.oasis.opendocument.chart"), (528, 529)),(UniCase::ascii("vnd.oasis.opendocument.chart-template"), (529, 530)),(UniCase::ascii("vnd.oasis.opendocument.database"), (530, 531)),(UniCase::ascii("vnd.oasis.opendocument.formula"), (531, 532)),(UniCase::ascii("vnd.oasis.opendocument.formula-template"), (532, 533)),(UniCase::ascii("vnd.oasis.opendocument.graphics"), (533, 534)),(UniCase::ascii("vnd.oasis.opendocument.graphics-template"), (534, 535)),(UniCase::ascii("vnd.oasis.opendocument.image"), (535, 536)),(UniCase::ascii("vnd.oasis.opendocument.image-template"), (536, 537)),(UniCase::ascii("vnd.oasis.opendocument.presentation"), (537, 538)),(UniCase::ascii("vnd.oasis.opendocument.presentation-template"), (538, 539)),(UniCase::ascii("vnd.oasis.opendocument.spreadsheet"), (539, 540)),(UniCase::ascii("vnd.oasis.opendocument.spreadsheet-template"), (540, 541)),(UniCase::ascii("vnd.oasis.opendocument.text"), (541, 542)),(UniCase::ascii("vnd.oasis.opendocument.text-master"), (542, 543)),(UniCase::ascii("vnd.oasis.opendocument.text-template"), (543, 544)),(UniCase::ascii("vnd.oasis.opendocument.text-web"), (544, 545)),(UniCase::ascii("vnd.olpc-sugar"), (545, 546)),(UniCase::ascii("vnd.oma.dd2+xml"), (546, 547)),(UniCase::ascii("vnd.openofficeorg.extension"), (547, 548)),(UniCase::ascii("vnd.openxmlformats-officedocument.presentationml.presentation"), (548, 549)),(UniCase::ascii("vnd.openxmlformats-officedocument.presentationml.slide"), (549, 550)),(UniCase::ascii("vnd.openxmlformats-officedocument.presentationml.slideshow"), (550, 551)),(UniCase::ascii("vnd.openxmlformats-officedocument.presentationml.template"), (551, 552)),(UniCase::ascii("vnd.openxmlformats-officedocument.spreadsheetml.sheet"), (552, 553)),(UniCase::ascii("vnd.openxmlformats-officedocument.spreadsheetml.template"), (553, 554)),(UniCase::ascii("vnd.openxmlformats-officedocument.wordprocessingml.document"), (554, 555)),(UniCase::ascii("vnd.openxmlformats-officedocument.wordprocessingml.template"), (555, 556)),(UniCase::ascii("vnd.osgeo.mapguide.package"), (556, 557)),(UniCase::ascii("vnd.osgi.dp"), (557, 558)),(UniCase::ascii("vnd.osgi.subsystem"), (558, 559)),(UniCase::ascii("vnd.palm"), (559, 562)),(UniCase::ascii("vnd.pawaafile"), (562, 563)),(UniCase::ascii("vnd.pg.format"), (563, 564)),(UniCase::ascii("vnd.pg.osasli"), (564, 565)),(UniCase::ascii("vnd.picsel"), (565, 566)),(UniCase::ascii("vnd.pmi.widget"), (566, 567)),(UniCase::ascii("vnd.pocketlearn"), (567, 568)),(UniCase::ascii("vnd.powerbuilder6"), (568, 569)),(UniCase::ascii("vnd.previewsystems.box"), (569, 570)),(UniCase::ascii("vnd.proteus.magazine"), (570, 571)),(UniCase::ascii("vnd.publishare-delta-tree"), (571, 572)),(UniCase::ascii("vnd.pvi.ptid1"), (572, 573)),(UniCase::ascii("vnd.quark.quarkxpress"), (573, 578)),(UniCase::ascii("vnd.realvnc.bed"), (578, 579)),(UniCase::ascii("vnd.recordare.musicxml"), (579, 580)),(UniCase::ascii("vnd.recordare.musicxml+xml"), (580, 581)),(UniCase::ascii("vnd.rig.cryptonote"), (581, 582)),(UniCase::ascii("vnd.rn-realmedia"), (582, 583)),(UniCase::ascii("vnd.rn-realmedia-vbr"), (583, 584)),(UniCase::ascii("vnd.rn-rn_music_package"), (584, 585)),(UniCase::ascii("vnd.route66.link66+xml"), (585, 586)),(UniCase::ascii("vnd.sailingtracker.track"), (586, 587)),(UniCase::ascii("vnd.seemail"), (587, 588)),(UniCase::ascii("vnd.sema"), (588, 589)),(UniCase::ascii("vnd.semd"), (589, 590)),(UniCase::ascii("vnd.semf"), (590, 591)),(UniCase::ascii("vnd.shana.informed.formdata"), (591, 592)),(UniCase::ascii("vnd.shana.informed.formtemplate"), (592, 593)),(UniCase::ascii("vnd.shana.informed.interchange"), (593, 594)),(UniCase::ascii("vnd.shana.informed.package"), (594, 595)),(UniCase::ascii("vnd.simtech-mindmapper"), (595, 597)),(UniCase::ascii("vnd.smart.teacher"), (597, 598)),(UniCase::ascii("vnd.solent.sdkm+xml"), (598, 600)),(UniCase::ascii("vnd.spotfire.dxp"), (600, 601)),(UniCase::ascii("vnd.spotfire.sfs"), (601, 602)),(UniCase::ascii("vnd.stardivision.calc"), (602, 603)),(UniCase::ascii("vnd.stardivision.draw"), (603, 604)),(UniCase::ascii("vnd.stardivision.impress"), (604, 605)),(UniCase::ascii("vnd.stardivision.math"), (605, 606)),(UniCase::ascii("vnd.stardivision.writer"), (606, 608)),(UniCase::ascii("vnd.stardivision.writer-global"), (608, 609)),(UniCase::ascii("vnd.stepmania.package"), (609, 610)),(UniCase::ascii("vnd.stepmania.stepchart"), (610, 611)),(UniCase::ascii("vnd.sun.wadl+xml"), (611, 612)),(UniCase::ascii("vnd.sun.xml.calc"), (612, 613)),(UniCase::ascii("vnd.sun.xml.calc.template"), (613, 614)),(UniCase::ascii("vnd.sun.xml.draw"), (614, 615)),(UniCase::ascii("vnd.sun.xml.draw.template"), (615, 616)),(UniCase::ascii("vnd.sun.xml.impress"), (616, 617)),(UniCase::ascii("vnd.sun.xml.impress.template"), (617, 618)),(UniCase::ascii("vnd.sun.xml.math"), (618, 619)),(UniCase::ascii("vnd.sun.xml.writer"), (619, 620)),(UniCase::ascii("vnd.sun.xml.writer.global"), (620, 621)),(UniCase::ascii("vnd.sun.xml.writer.template"), (621, 622)),(UniCase::ascii("vnd.sus-calendar"), (622, 624)),(UniCase::ascii("vnd.svd"), (624, 625)),(UniCase::ascii("vnd.symbian.install"), (625, 627)),(UniCase::ascii("vnd.syncml+xml"), (627, 628)),(UniCase::ascii("vnd.syncml.dm+wbxml"), (628, 629)),(UniCase::ascii("vnd.syncml.dm+xml"), (629, 630)),(UniCase::ascii("vnd.tao.intent-module-archive"), (630, 631)),(UniCase::ascii("vnd.tcpdump.pcap"), (631, 634)),(UniCase::ascii("vnd.tmobile-livetv"), (634, 635)),(UniCase::ascii("vnd.trid.tpt"), (635, 636)),(UniCase::ascii("vnd.triscape.mxs"), (636, 637)),(UniCase::ascii("vnd.trueapp"), (637, 638)),(UniCase::ascii("vnd.ufdl"), (638, 640)),(UniCase::ascii("vnd.uiq.theme"), (640, 641)),(UniCase::ascii("vnd.umajin"), (641, 642)),(UniCase::ascii("vnd.unity"), (642, 643)),(UniCase::ascii("vnd.uoml+xml"), (643, 644)),(UniCase::ascii("vnd.vcx"), (644, 645)),(UniCase::ascii("vnd.visio"), (645, 651)),(UniCase::ascii("vnd.visionary"), (651, 652)),(UniCase::ascii("vnd.vsf"), (652, 653)),(UniCase::ascii("vnd.wap.wbxml"), (653, 654)),(UniCase::ascii("vnd.wap.wmlc"), (654, 655)),(UniCase::ascii("vnd.wap.wmlscriptc"), (655, 656)),(UniCase::ascii("vnd.webturbo"), (656, 657)),(UniCase::ascii("vnd.wolfram.player"), (657, 658)),(UniCase::ascii("vnd.wordperfect"), (658, 659)),(UniCase::ascii("vnd.wqd"), (659, 660)),(UniCase::ascii("vnd.wt.stf"), (660, 661)),(UniCase::ascii("vnd.xara"), (661, 662)),(UniCase::ascii("vnd.xfdl"), (662, 663)),(UniCase::ascii("vnd.yamaha.hv-dic"), (663, 664)),(UniCase::ascii("vnd.yamaha.hv-script"), (664, 665)),(UniCase::ascii("vnd.yamaha.hv-voice"), (665, 666)),(UniCase::ascii("vnd.yamaha.openscoreformat"), (666, 667)),(UniCase::ascii("vnd.yamaha.openscoreformat.osfpvg+xml"), (667, 668)),(UniCase::ascii("vnd.yamaha.smaf-audio"), (668, 669)),(UniCase::ascii("vnd.yamaha.smaf-phrase"), (669, 670)),(UniCase::ascii("vnd.yellowriver-custom-menu"), (670, 671)),(UniCase::ascii("vnd.zul"), (671, 673)),(UniCase::ascii("vnd.zzazz.deck+xml"), (673, 674)),(UniCase::ascii("voicexml+xml"), (674, 675)),(UniCase::ascii("vsix"), (675, 676)),(UniCase::ascii("wasm"), (676, 677)),(UniCase::ascii("widget"), (677, 678)),(UniCase::ascii("windows-library+xml"), (678, 679)),(UniCase::ascii("windows-search-connector+xml"), (679, 680)),(UniCase::ascii("winhlp"), (680, 681)),(UniCase::ascii("wlmoviemaker"), (681, 682)),(UniCase::ascii("wspolicy+xml"), (682, 683)),(UniCase::ascii("x-7z-compressed"), (683, 684)),(UniCase::ascii("x-abiword"), (684, 685)),(UniCase::ascii("x-ace-compressed"), (685, 686)),(UniCase::ascii("x-arj"), (686, 687)),(UniCase::ascii("x-authorware-bin"), (687, 690)),(UniCase::ascii("x-authorware-map"), (690, 691)),(UniCase::ascii("x-authorware-seg"), (691, 692)),(UniCase::ascii("x-bcpio"), (692, 693)),(UniCase::ascii("x-bittorrent"), (693, 694)),(UniCase::ascii("x-blorb"), (694, 696)),(UniCase::ascii("x-bridge-url"), (696, 697)),(UniCase::ascii("x-bzip"), (697, 698)),(UniCase::ascii("x-bzip2"), (698, 700)),(UniCase::ascii("x-cbr"), (700, 705)),(UniCase::ascii("x-cdf"), (705, 706)),(UniCase::ascii("x-cdlink"), (706, 707)),(UniCase::ascii("x-cfs-compressed"), (707, 708)),(UniCase::ascii("x-chat"), (708, 709)),(UniCase::ascii("x-chess-pgn"), (709, 710)),(UniCase::ascii("x-chrome-extension"), (710, 711)),(UniCase::ascii("x-cocoa"), (711, 712)),(UniCase::ascii("x-compress"), (712, 713)),(UniCase::ascii("x-compressed"), (713, 714)),(UniCase::ascii("x-cpio"), (714, 715)),(UniCase::ascii("x-csh"), (715, 716)),(UniCase::ascii("x-debian-package"), (716, 717)),(UniCase::ascii("x-dgc-compressed"), (717, 718)),(UniCase::ascii("x-director"), (718, 727)),(UniCase::ascii("x-doom"), (727, 728)),(UniCase::ascii("x-dtbncx+xml"), (728, 729)),(UniCase::ascii("x-dtbook+xml"), (729, 730)),(UniCase::ascii("x-dtbresource+xml"), (730, 731)),(UniCase::ascii("x-dvi"), (731, 732)),(UniCase::ascii("x-dxf"), (732, 733)),(UniCase::ascii("x-endace-erf"), (733, 734)),(UniCase::ascii("x-eva"), (734, 735)),(UniCase::ascii("x-font-bdf"), (735, 736)),(UniCase::ascii("x-font-ghostscript"), (736, 737)),(UniCase::ascii("x-font-linux-psf"), (737, 738)),(UniCase::ascii("x-font-pcf"), (738, 739)),(UniCase::ascii("x-font-snf"), (739, 740)),(UniCase::ascii("x-font-ttf"), (740, 741)),(UniCase::ascii("x-font-type1"), (741, 742)),(UniCase::ascii("x-freearc"), (742, 743)),(UniCase::ascii("x-gca-compressed"), (743, 744)),(UniCase::ascii("x-glulx"), (744, 745)),(UniCase::ascii("x-gnumeric"), (745, 746)),(UniCase::ascii("x-gramps-xml"), (746, 747)),(UniCase::ascii("x-gtar"), (747, 748)),(UniCase::ascii("x-gzip"), (748, 749)),(UniCase::ascii("x-hdf"), (749, 750)),(UniCase::ascii("x-httpd-php"), (750, 751)),(UniCase::ascii("x-install-instructions"), (751, 752)),(UniCase::ascii("x-internet-signup"), (752, 754)),(UniCase::ascii("x-iphone"), (754, 755)),(UniCase::ascii("x-itunes-ipa"), (755, 756)),(UniCase::ascii("x-itunes-ipg"), (756, 757)),(UniCase::ascii("x-itunes-ipsw"), (757, 758)),(UniCase::ascii("x-itunes-ite"), (758, 759)),(UniCase::ascii("x-itunes-itlp"), (759, 760)),(UniCase::ascii("x-itunes-itms"), (760, 761)),(UniCase::ascii("x-itunes-itpc"), (761, 762)),(UniCase::ascii("x-java-applet"), (762, 763)),(UniCase::ascii("x-java-archive-diff"), (763, 764)),(UniCase::ascii("x-java-jnlp-file"), (764, 765)),(UniCase::ascii("x-koan"), (765, 766)),(UniCase::ascii("x-latex"), (766, 767)),(UniCase::ascii("x-lua-bytecode"), (767, 768)),(UniCase::ascii("x-lzh-compressed"), (768, 769)),(UniCase::ascii("x-makeself"), (769, 770)),(UniCase::ascii("x-mie"), (770, 771)),(UniCase::ascii("x-miva-compiled"), (771, 772)),(UniCase::ascii("x-mmxp"), (772, 773)),(UniCase::ascii("x-mobipocket-ebook"), (773, 775)),(UniCase::ascii("x-ms-application"), (775, 776)),(UniCase::ascii("x-ms-license"), (776, 777)),(UniCase::ascii("x-ms-manifest"), (777, 778)),(UniCase::ascii("x-ms-reader"), (778, 779)),(UniCase::ascii("x-ms-shortcut"), (779, 780)),(UniCase::ascii("x-ms-vsto"), (780, 781)),(UniCase::ascii("x-ms-wmd"), (781, 782)),(UniCase::ascii("x-ms-wmz"), (782, 783)),(UniCase::ascii("x-ms-xbap"), (783, 784)),(UniCase::ascii("x-msaccess"), (784, 785)),(UniCase::ascii("x-msbinder"), (785, 786)),(UniCase::ascii("x-mscardfile"), (786, 787)),(UniCase::ascii("x-msclip"), (787, 788)),(UniCase::ascii("x-msdownload"), (788, 791)),(UniCase::ascii("x-msmediaview"), (791, 794)),(UniCase::ascii("x-msmetafile"), (794, 796)),(UniCase::ascii("x-msmoney"), (796, 797)),(UniCase::ascii("x-mspublisher"), (797, 798)),(UniCase::ascii("x-msschedule"), (798, 799)),(UniCase::ascii("x-msterminal"), (799, 800)),(UniCase::ascii("x-mswrite"), (800, 801)),(UniCase::ascii("x-netcdf"), (801, 802)),(UniCase::ascii("x-ns-proxy-autoconfig"), (802, 803)),(UniCase::ascii("x-nzb"), (803, 804)),(UniCase::ascii("x-oleobject"), (804, 805)),(UniCase::ascii("x-parquet"), (805, 806)),(UniCase::ascii("x-perfmon"), (806, 811)),(UniCase::ascii("x-perl"), (811, 813)),(UniCase::ascii("x-pkcs12"), (813, 815)),(UniCase::ascii("x-pkcs7-certificates"), (815, 817)),(UniCase::ascii("x-pkcs7-certreqresp"), (817, 818)),(UniCase::ascii("x-podcast"), (818, 819)),(UniCase::ascii("x-quicktimeplayer"), (819, 820)),(UniCase::ascii("x-rar-compressed"), (820, 821)),(UniCase::ascii("x-research-info-systems"), (821, 822)),(UniCase::ascii("x-safari-safariextz"), (822, 823)),(UniCase::ascii("x-safari-webarchive"), (823, 824)),(UniCase::ascii("x-sgimb"), (824, 825)),(UniCase::ascii("x-sh"), (825, 826)),(UniCase::ascii("x-shar"), (826, 827)),(UniCase::ascii("x-shockwave-flash"), (827, 829)),(UniCase::ascii("x-silverlight-app"), (829, 830)),(UniCase::ascii("x-smaf"), (830, 831)),(UniCase::ascii("x-sql"), (831, 832)),(UniCase::ascii("x-stuffit"), (832, 833)),(UniCase::ascii("x-stuffitx"), (833, 834)),(UniCase::ascii("x-subrip"), (834, 835)),(UniCase::ascii("x-sv4cpio"), (835, 836)),(UniCase::ascii("x-sv4crc"), (836, 837)),(UniCase::ascii("x-t3vm-image"), (837, 838)),(UniCase::ascii("x-tads"), (838, 839)),(UniCase::ascii("x-tar"), (839, 840)),(UniCase::ascii("x-tcl"), (840, 842)),(UniCase::ascii("x-tex"), (842, 843)),(UniCase::ascii("x-tex-tfm"), (843, 844)),(UniCase::ascii("x-texinfo"), (844, 846)),(UniCase::ascii("x-tgif"), (846, 847)),(UniCase::ascii("x-troff"), (847, 850)),(UniCase::ascii("x-troff-man"), (850, 851)),(UniCase::ascii("x-troff-me"), (851, 852)),(UniCase::ascii("x-troff-ms"), (852, 853)),(UniCase::ascii("x-ustar"), (853, 854)),(UniCase::ascii("x-virtualbox-hdd"), (854, 855)),(UniCase::ascii("x-virtualbox-ova"), (855, 856)),(UniCase::ascii("x-virtualbox-ovf"), (856, 857)),(UniCase::ascii("x-virtualbox-vbox"), (857, 858)),(UniCase::ascii("x-virtualbox-vbox-extpack"), (858, 859)),(UniCase::ascii("x-virtualbox-vdi"), (859, 860)),(UniCase::ascii("x-virtualbox-vhd"), (860, 861)),(UniCase::ascii("x-virtualbox-vmdk"), (861, 862)),(UniCase::ascii("x-wais-source"), (862, 863)),(UniCase::ascii("x-web-app-manifest+json"), (863, 864)),(UniCase::ascii("x-wlpg-detect"), (864, 865)),(UniCase::ascii("x-wlpg3-detect"), (865, 866)),(UniCase::ascii("x-x509-ca-cert"), (866, 870)),(UniCase::ascii("x-xfig"), (870, 871)),(UniCase::ascii("x-xliff+xml"), (871, 872)),(UniCase::ascii("x-xpinstall"), (872, 873)),(UniCase::ascii("x-xz"), (873, 874)),(UniCase::ascii("x-zmachine"), (874, 882)),(UniCase::ascii("xaml+xml"), (882, 883)),(UniCase::ascii("xcap-diff+xml"), (883, 884)),(UniCase::ascii("xenc+xml"), (884, 885)),(UniCase::ascii("xhtml+xml"), (885, 887)),(UniCase::ascii("xml"), (887, 931)),(UniCase::ascii("xop+xml"), (931, 932)),(UniCase::ascii("xproc+xml"), (932, 933)),(UniCase::ascii("xspf+xml"), (933, 934)),(UniCase::ascii("xv+xml"), (934, 938)),(UniCase::ascii("yang"), (938, 939)),(UniCase::ascii("yin+xml"), (939, 940)),(UniCase::ascii("zip"), (940, 941)),] }),(UniCase::ascii("audio"), TopLevelExts { start: 941, end: 1007, subs: &[(UniCase::ascii("aac"), (941, 943)),(UniCase::ascii("ac3"), (943, 944)),(UniCase::ascii("aiff"), (944, 948)),(UniCase::ascii("annodex"), (948, 949)),(UniCase::ascii("audible"), (949, 950)),(UniCase::ascii("basic"), (950, 952)),(UniCase::ascii("flac"), (952, 953)),(UniCase::ascii("m4a"), (953, 954)),(UniCase::ascii("m4b"), (954, 955)),(UniCase::ascii("m4p"), (955, 956)),(UniCase::ascii("mid"), (956, 959)),(UniCase::ascii("midi"), (959, 960)),(UniCase::ascii("mp4"), (960, 961)),(UniCase::ascii("mpeg"), (961, 967)),(UniCase::ascii("ogg"), (967, 971)),(UniCase::ascii("s3m"), (971, 972)),(UniCase::ascii("scpls"), (972, 973)),(UniCase::ascii("silk"), (973, 974)),(UniCase::ascii("vnd.audible.aax"), (974, 975)),(UniCase::ascii("vnd.dece.audio"), (975, 977)),(UniCase::ascii("vnd.digital-winds"), (977, 978)),(UniCase::ascii("vnd.dlna.adts"), (978, 979)),(UniCase::ascii("vnd.dra"), (979, 980)),(UniCase::ascii("vnd.dts"), (980, 981)),(UniCase::ascii("vnd.dts.hd"), (981, 982)),(UniCase::ascii("vnd.lucent.voice"), (982, 983)),(UniCase::ascii("vnd.ms-playready.media.pya"), (983, 984)),(UniCase::ascii("vnd.nuera.ecelp4800"), (984, 985)),(UniCase::ascii("vnd.nuera.ecelp7470"), (985, 986)),(UniCase::ascii("vnd.nuera.ecelp9600"), (986, 987)),(UniCase::ascii("vnd.rip"), (987, 988)),(UniCase::ascii("wav"), (988, 990)),(UniCase::ascii("webm"), (990, 991)),(UniCase::ascii("x-caf"), (991, 992)),(UniCase::ascii("x-gsm"), (992, 993)),(UniCase::ascii("x-m4r"), (993, 994)),(UniCase::ascii("x-matroska"), (994, 995)),(UniCase::ascii("x-mpegurl"), (995, 997)),(UniCase::ascii("x-ms-wax"), (997, 998)),(UniCase::ascii("x-ms-wma"), (998, 999)),(UniCase::ascii("x-pn-realaudio"), (999, 1001)),(UniCase::ascii("x-pn-realaudio-plugin"), (1001, 1002)),(UniCase::ascii("x-sd2"), (1002, 1003)),(UniCase::ascii("x-smd"), (1003, 1006)),(UniCase::ascii("xm"), (1006, 1007)),] }),(UniCase::ascii("chemical"), TopLevelExts { start: 1007, end: 1013, subs: &[(UniCase::ascii("x-cdx"), (1007, 1008)),(UniCase::ascii("x-cif"), (1008, 1009)),(UniCase::ascii("x-cmdf"), (1009, 1010)),(UniCase::ascii("x-cml"), (1010, 1011)),(UniCase::ascii("x-csml"), (1011, 1012)),(UniCase::ascii("x-xyz"), (1012, 1013)),] }),(UniCase::ascii("drawing"), TopLevelExts { start: 1013, end: 1014, subs: &[(UniCase::ascii("x-dwf"), (1013, 1014)),] }),(UniCase::ascii("font"), TopLevelExts { start: 1014, end: 1017, subs: &[(UniCase::ascii("collection"), (1014, 1015)),(UniCase::ascii("ttf"), (1015, 1016)),(UniCase::ascii("woff2"), (1016, 1017)),] }),(UniCase::ascii("image"), TopLevelExts { start: 1017, end: 1119, subs: &[(UniCase::ascii("apng"), (1017, 1018)),(UniCase::ascii("avif"), (1018, 1019)),(UniCase::ascii("avif-sequence"), (1019, 1020)),(UniCase::ascii("bmp"), (1020, 1022)),(UniCase::ascii("cgm"), (1022, 1023)),(UniCase::ascii("cis-cod"), (1023, 1024)),(UniCase::ascii("g3fax"), (1024, 1025)),(UniCase::ascii("gif"), (1025, 1026)),(UniCase::ascii("heic"), (1026, 1027)),(UniCase::ascii("heic-sequence"), (1027, 1028)),(UniCase::ascii("heif"), (1028, 1029)),(UniCase::ascii("heif-sequence"), (1029, 1030)),(UniCase::ascii("ief"), (1030, 1031)),(UniCase::ascii("jp2"), (1031, 1033)),(UniCase::ascii("jpeg"), (1033, 1037)),(UniCase::ascii("jpm"), (1037, 1038)),(UniCase::ascii("jpx"), (1038, 1040)),(UniCase::ascii("jxl"), (1040, 1041)),(UniCase::ascii("ktx"), (1041, 1042)),(UniCase::ascii("pict"), (1042, 1045)),(UniCase::ascii("png"), (1045, 1047)),(UniCase::ascii("prs.btif"), (1047, 1048)),(UniCase::ascii("sgi"), (1048, 1049)),(UniCase::ascii("svg+xml"), (1049, 1051)),(UniCase::ascii("tiff"), (1051, 1053)),(UniCase::ascii("vnd.dece.graphic"), (1053, 1057)),(UniCase::ascii("vnd.djvu"), (1057, 1059)),(UniCase::ascii("vnd.fastbidsheet"), (1059, 1060)),(UniCase::ascii("vnd.fpx"), (1060, 1061)),(UniCase::ascii("vnd.fst"), (1061, 1062)),(UniCase::ascii("vnd.fujixerox.edmics-mmr"), (1062, 1063)),(UniCase::ascii("vnd.fujixerox.edmics-rlc"), (1063, 1064)),(UniCase::ascii("vnd.ms-modi"), (1064, 1065)),(UniCase::ascii("vnd.ms-photo"), (1065, 1066)),(UniCase::ascii("vnd.net-fpx"), (1066, 1067)),(UniCase::ascii("vnd.radiance"), (1067, 1068)),(UniCase::ascii("vnd.rn-realflash"), (1068, 1069)),(UniCase::ascii("vnd.wap.wbmp"), (1069, 1070)),(UniCase::ascii("vnd.xiff"), (1070, 1071)),(UniCase::ascii("webp"), (1071, 1072)),(UniCase::ascii("x-3ds"), (1072, 1073)),(UniCase::ascii("x-adobe-dng"), (1073, 1074)),(UniCase::ascii("x-canon-cr2"), (1074, 1075)),(UniCase::ascii("x-canon-cr3"), (1075, 1076)),(UniCase::ascii("x-canon-crw"), (1076, 1077)),(UniCase::ascii("x-cmu-raster"), (1077, 1078)),(UniCase::ascii("x-cmx"), (1078, 1079)),(UniCase::ascii("x-epson-erf"), (1079, 1080)),(UniCase::ascii("x-freehand"), (1080, 1085)),(UniCase::ascii("x-fuji-raf"), (1085, 1086)),(UniCase::ascii("x-icon"), (1086, 1087)),(UniCase::ascii("x-jg"), (1087, 1088)),(UniCase::ascii("x-jng"), (1088, 1089)),(UniCase::ascii("x-kodak-dcr"), (1089, 1090)),(UniCase::ascii("x-kodak-k25"), (1090, 1091)),(UniCase::ascii("x-kodak-kdc"), (1091, 1092)),(UniCase::ascii("x-macpaint"), (1092, 1095)),(UniCase::ascii("x-minolta-mrw"), (1095, 1096)),(UniCase::ascii("x-mrsid-image"), (1096, 1097)),(UniCase::ascii("x-nikon-nef"), (1097, 1098)),(UniCase::ascii("x-nikon-nrw"), (1098, 1099)),(UniCase::ascii("x-olympus-orf"), (1099, 1100)),(UniCase::ascii("x-panasonic-rw"), (1100, 1101)),(UniCase::ascii("x-panasonic-rw2"), (1101, 1103)),(UniCase::ascii("x-pentax-pef"), (1103, 1104)),(UniCase::ascii("x-portable-anymap"), (1104, 1105)),(UniCase::ascii("x-portable-bitmap"), (1105, 1106)),(UniCase::ascii("x-portable-graymap"), (1106, 1107)),(UniCase::ascii("x-portable-pixmap"), (1107, 1108)),(UniCase::ascii("x-quicktime"), (1108, 1110)),(UniCase::ascii("x-rgb"), (1110, 1111)),(UniCase::ascii("x-sigma-x3f"), (1111, 1112)),(UniCase::ascii("x-sony-arw"), (1112, 1113)),(UniCase::ascii("x-sony-sr2"), (1113, 1114)),(UniCase::ascii("x-sony-srf"), (1114, 1115)),(UniCase::ascii("x-tga"), (1115, 1116)),(UniCase::ascii("x-xbitmap"), (1116, 1117)),(UniCase::ascii("x-xpixmap"), (1117, 1118)),(UniCase::ascii("x-xwindowdump"), (1118, 1119)),] }),(UniCase::ascii("message"), TopLevelExts { start: 1119, end: 1129, subs: &[(UniCase::ascii("disposition-notification"), (1119, 1120)),(UniCase::ascii("global"), (1120, 1121)),(UniCase::ascii("global-delivery-status"), (1121, 1122)),(UniCase::ascii("global-disposition-notification"), (1122, 1123)),(UniCase::ascii("global-headers"), (1123, 1124)),(UniCase::ascii("rfc822"), (1124, 1129)),] }),(UniCase::ascii("model"), TopLevelExts { start: 1129, end: 1147, subs: &[(UniCase::ascii("gltf+json"), (1129, 1130)),(UniCase::ascii("gltf-binary"), (1130, 1131)),(UniCase::ascii("iges"), (1131, 1133)),(UniCase::ascii("mesh"), (1133, 1136)),(UniCase::ascii("vnd.collada+xml"), (1136, 1137)),(UniCase::ascii("vnd.gdl"), (1137, 1138)),(UniCase::ascii("vnd.gtw"), (1138, 1139)),(UniCase::ascii("vnd.vtu"), (1139, 1140)),(UniCase::ascii("vrml"), (1140, 1141)),(UniCase::ascii("x3d+binary"), (1141, 1143)),(UniCase::ascii("x3d+vrml"), (1143, 1145)),(UniCase::ascii("x3d+xml"), (1145, 1147)),] }),(UniCase::ascii("text"), TopLevelExts { start: 1147, end: 1330, subs: &[(UniCase::ascii("cache-manifest"), (1147, 1148)),(UniCase::ascii("calendar"), (1148, 1150)),(UniCase::ascii("coffeescript"), (1150, 1152)),(UniCase::ascii("css"), (1152, 1153)),(UniCase::ascii("csv"), (1153, 1154)),(UniCase::ascii("dlm"), (1154, 1155)),(UniCase::ascii("gemini"), (1155, 1157)),(UniCase::ascii("h323"), (1157, 1158)),(UniCase::ascii("html"), (1158, 1162)),(UniCase::ascii("iuls"), (1162, 1163)),(UniCase::ascii("jade"), (1163, 1164)),(UniCase::ascii("javascript"), (1164, 1169)),(UniCase::ascii("less"), (1169, 1170)),(UniCase::ascii("markdown"), (1170, 1172)),(UniCase::ascii("mathml"), (1172, 1173)),(UniCase::ascii("n3"), (1173, 1174)),(UniCase::ascii("plain"), (1174, 1242)),(UniCase::ascii("prs.lines.tag"), (1242, 1243)),(UniCase::ascii("richtext"), (1243, 1244)),(UniCase::ascii("scriptlet"), (1244, 1246)),(UniCase::ascii("sgml"), (1246, 1248)),(UniCase::ascii("shex"), (1248, 1249)),(UniCase::ascii("slim"), (1249, 1251)),(UniCase::ascii("stylus"), (1251, 1253)),(UniCase::ascii("tab-separated-values"), (1253, 1254)),(UniCase::ascii("turtle"), (1254, 1255)),(UniCase::ascii("uri-list"), (1255, 1258)),(UniCase::ascii("vbscript"), (1258, 1259)),(UniCase::ascii("vcard"), (1259, 1260)),(UniCase::ascii("vnd.curl"), (1260, 1261)),(UniCase::ascii("vnd.curl.dcurl"), (1261, 1262)),(UniCase::ascii("vnd.curl.mcurl"), (1262, 1263)),(UniCase::ascii("vnd.curl.scurl"), (1263, 1264)),(UniCase::ascii("vnd.dvb.subtitle"), (1264, 1265)),(UniCase::ascii("vnd.fly"), (1265, 1266)),(UniCase::ascii("vnd.fmi.flexstor"), (1266, 1267)),(UniCase::ascii("vnd.graphviz"), (1267, 1268)),(UniCase::ascii("vnd.in3d.3dml"), (1268, 1269)),(UniCase::ascii("vnd.in3d.spot"), (1269, 1270)),(UniCase::ascii("vnd.sun.j2me.app-descriptor"), (1270, 1271)),(UniCase::ascii("vnd.wap.wml"), (1271, 1272)),(UniCase::ascii("vnd.wap.wmlscript"), (1272, 1273)),(UniCase::ascii("vtt"), (1273, 1274)),(UniCase::ascii("webviewhtml"), (1274, 1275)),(UniCase::ascii("x-c"), (1275, 1276)),(UniCase::ascii("x-component"), (1276, 1277)),(UniCase::ascii("x-fortran"), (1277, 1281)),(UniCase::ascii("x-gherkin"), (1281, 1282)),(UniCase::ascii("x-handlebars-template"), (1282, 1283)),(UniCase::ascii("x-hdml"), (1283, 1284)),(UniCase::ascii("x-html-insertion"), (1284, 1286)),(UniCase::ascii("x-lua"), (1286, 1287)),(UniCase::ascii("x-markdown"), (1287, 1289)),(UniCase::ascii("x-ms-contact"), (1289, 1290)),(UniCase::ascii("x-ms-group"), (1290, 1291)),(UniCase::ascii("x-ms-iqy"), (1291, 1292)),(UniCase::ascii("x-ms-rqy"), (1292, 1293)),(UniCase::ascii("x-nfo"), (1293, 1294)),(UniCase::ascii("x-opml"), (1294, 1295)),(UniCase::ascii("x-pascal"), (1295, 1297)),(UniCase::ascii("x-processing"), (1297, 1298)),(UniCase::ascii("x-rust"), (1298, 1299)),(UniCase::ascii("x-sass"), (1299, 1300)),(UniCase::ascii("x-scss"), (1300, 1301)),(UniCase::ascii("x-setext"), (1301, 1302)),(UniCase::ascii("x-sfv"), (1302, 1303)),(UniCase::ascii("x-suse-ymp"), (1303, 1304)),(UniCase::ascii("x-toml"), (1304, 1305)),(UniCase::ascii("x-uuencode"), (1305, 1306)),(UniCase::ascii("x-vcard"), (1306, 1307)),(UniCase::ascii("x-yaml"), (1307, 1309)),(UniCase::ascii("xml"), (1309, 1330)),] }),(UniCase::ascii("video"), TopLevelExts { start: 1330, end: 1411, subs: &[(UniCase::ascii("3gpp"), (1330, 1332)),(UniCase::ascii("3gpp2"), (1332, 1334)),(UniCase::ascii("annodex"), (1334, 1335)),(UniCase::ascii("divx"), (1335, 1336)),(UniCase::ascii("h261"), (1336, 1337)),(UniCase::ascii("h263"), (1337, 1338)),(UniCase::ascii("h264"), (1338, 1339)),(UniCase::ascii("jpeg"), (1339, 1340)),(UniCase::ascii("jpm"), (1340, 1341)),(UniCase::ascii("mj2"), (1341, 1343)),(UniCase::ascii("mp4"), (1343, 1346)),(UniCase::ascii("mpeg"), (1346, 1357)),(UniCase::ascii("ogg"), (1357, 1358)),(UniCase::ascii("quicktime"), (1358, 1361)),(UniCase::ascii("vnd.dece.hd"), (1361, 1363)),(UniCase::ascii("vnd.dece.mobile"), (1363, 1365)),(UniCase::ascii("vnd.dece.pd"), (1365, 1367)),(UniCase::ascii("vnd.dece.sd"), (1367, 1369)),(UniCase::ascii("vnd.dece.video"), (1369, 1371)),(UniCase::ascii("vnd.dlna.mpeg-tts"), (1371, 1376)),(UniCase::ascii("vnd.dvb.file"), (1376, 1377)),(UniCase::ascii("vnd.fvt"), (1377, 1378)),(UniCase::ascii("vnd.mpegurl"), (1378, 1380)),(UniCase::ascii("vnd.ms-playready.media.pyv"), (1380, 1381)),(UniCase::ascii("vnd.uvvu.mp4"), (1381, 1383)),(UniCase::ascii("vnd.vivo"), (1383, 1384)),(UniCase::ascii("webm"), (1384, 1385)),(UniCase::ascii("x-dv"), (1385, 1387)),(UniCase::ascii("x-f4v"), (1387, 1388)),(UniCase::ascii("x-fli"), (1388, 1389)),(UniCase::ascii("x-flv"), (1389, 1390)),(UniCase::ascii("x-ivf"), (1390, 1391)),(UniCase::ascii("x-la-asf"), (1391, 1393)),(UniCase::ascii("x-m4v"), (1393, 1394)),(UniCase::ascii("x-matroska"), (1394, 1397)),(UniCase::ascii("x-mng"), (1397, 1398)),(UniCase::ascii("x-ms-asf"), (1398, 1402)),(UniCase::ascii("x-ms-vob"), (1402, 1403)),(UniCase::ascii("x-ms-wm"), (1403, 1404)),(UniCase::ascii("x-ms-wmp"), (1404, 1405)),(UniCase::ascii("x-ms-wmv"), (1405, 1406)),(UniCase::ascii("x-ms-wmx"), (1406, 1407)),(UniCase::ascii("x-ms-wvx"), (1407, 1408)),(UniCase::ascii("x-msvideo"), (1408, 1409)),(UniCase::ascii("x-sgi-movie"), (1409, 1410)),(UniCase::ascii("x-smv"), (1410, 1411)),] }),(UniCase::ascii("x-conference"), TopLevelExts { start: 1411, end: 1412, subs: &[(UniCase::ascii("x-cooltalk"), (1411, 1412)),] }),(UniCase::ascii("x-world"), TopLevelExts { start: 1412, end: 1417, subs: &[(UniCase::ascii("x-vrml"), (1412, 1417)),] }),]; -const EXTS: &'static [&'static str] = &["dwg", "ez", "anx", "aw", "atom", "atomcat", "atomsvc", "bdoc", "ccxml", "cdmia", "cdmic", "cdmid", "cdmio", "cdmiq", "cu", "mpd", "davmount", "x", "dbk", "dssc", "xdssc", "emma", "evy", "epub", "etl", "exi", "otf", "ttf", "pfr", "woff", "fif", "fsscript", "fsx", "spl", "geojson", "gml", "gpx", "gxf", "gz", "hjson", "hta", "stk", "ink", "inkml", "acx", "ipfix", "ear", "jar", "war", "ser", "mjs", "json", "json5", "jsonml", "jsonld", "jck", "jcz", "lostxml", "hqx", "cpt", "mads", "webmanifest", "mrc", "mrcx", "ma", "mb", "nb", "mathml", "mbox", "mscml", "metalink", "meta4", "mets", "mods", "m21", "mp21", "mp4s", "amc", "vsi", "accdb", "accde", "accdt", "ade", "adp", "mda", "mde", "accda", "accdc", "accft", "accdr", "accdw", "doc", "dot", "wbk", "wiz", "mxf", "nq", "nt", "aaf", "aca", "afm", "asd", "asi", "bin", "bpk", "buffer", "cab", "cur", "dat", "deb", "deploy", "dist", "distz", "dmg", "dms", "dsp", "dump", "dwp", "elc", "emz", "exe", "fla", "hhk", "hhp", "hxd", "hxh", "hxi", "hxq", "hxr", "hxs", "hxw", "img", "inf", "iso", "java", "jpb", "lpk", "lrf", "lzh", "mar", "mdp", "mix", "msi", "msm", "mso", "msp", "ocx", "pcx", "pcz", "pfb", "pfm", "pkg", "prm", "prx", "psd", "psm", "psp", "qxd", "rvt", "sea", "smi", "snp", "so", "thn", "toc", "u32", "xmp", "xsn", "xtp", "oda", "opf", "ogx", "axs", "omdoc", "one", "onea", "onepkg", "onetmp", "onetoc", "onetoc2", "osdx", "oxps", "xer", "pdf", "pgp", "asc", "sig", "prf", "p10", "p7c", "p7m", "p7s", "p8", "ac", "crl", "pkipath", "pki", "ai", "eps", "ps", "psc1", "cww", "pskcxml", "raml", "rat", "rdf", "rif", "rnc", "rl", "rld", "gbr", "mft", "roa", "rsd", "rss", "rtf", "sbml", "scq", "scs", "spq", "spp", "sdp", "setpay", "setreg", "shf", "smil", "rq", "srx", "gram", "grxml", "sru", "ssdl", "ssml", "step", "stp", "ssm", "tei", "teicorpus", "tfi", "tsd", "trig", "plb", "psb", "pvb", "tcap", "pwn", "aso", "imp", "acu", "acutc", "atc", "air", "fcdt", "fxp", "fxpl", "xdp", "xfdf", "ahead", "azf", "azs", "azw", "acc", "ami", "apk", "cii", "fti", "atx", "parquet", "mpkg", "pkpass", "swi", "iota", "aep", "mpm", "bmi", "rep", "cdxml", "mmd", "cdy", "csl", "cla", "rp9", "c4d", "c4f", "c4g", "c4p", "c4u", "c11amc", "c11amz", "csp", "cdbcmsg", "cmc", "clkx", "clkk", "clkp", "clkt", "clkw", "wbs", "ppd", "car", "pcurl", "dart", "rdz", "uvd", "uvf", "uvvd", "uvvf", "uvt", "uvvt", "uvvx", "uvx", "uvvz", "uvz", "fe_launch", "dna", "mlp", "dpg", "dfac", "kpxx", "ait", "geo", "mag", "nml", "esf", "msf", "qam", "slt", "ssf", "es3", "et3", "ez2", "ez3", "fdf", "mseed", "dataless", "seed", "gph", "ftc", "book", "fm", "frame", "maker", "fnc", "ltf", "fsc", "oas", "oa2", "oa3", "fg5", "bh2", "ddd", "xdw", "xbd", "fzs", "txd", "ggb", "ggt", "gex", "gre", "gxt", "g2w", "g3w", "gmx", "gdoc", "gslides", "gsheet", "kml", "kmz", "gqf", "gqs", "gac", "ghf", "gim", "grv", "gtm", "tpl", "vcg", "hal", "zmm", "hbci", "les", "hpgl", "hpid", "hps", "jlt", "pcl", "pclxl", "sfd-hdstx", "mpy", "afp", "list3820", "listafp", "irm", "sc", "icc", "icm", "igl", "ivp", "ivu", "igm", "xpw", "xpx", "i2g", "qbo", "qfx", "rcprofile", "irp", "xpr", "fcs", "jam", "rms", "jisp", "joda", "ktr", "ktz", "karbon", "chrt", "kfo", "flw", "kon", "kpr", "kpt", "ksp", "kwd", "kwt", "htke", "kia", "kne", "knp", "skd", "skm", "skt", "sse", "lasxml", "lbd", "lbe", "123", "apr", "pre", "nsf", "org", "scm", "lwp", "portpkg", "mcd", "mc1", "cdkey", "mwf", "mfm", "flo", "igx", "mif", "daf", "dis", "mbk", "mqy", "msl", "plc", "txf", "mpn", "mpc", "xul", "cil", "slk", "xla", "xlc", "xld", "xlk", "xll", "xlm", "xls", "xlt", "xlw", "xlam", "xlsb", "xlsm", "xltm", "eot", "chm", "ims", "lrm", "mpf", "calx", "thmx", "msg", "pst", "sst", "pko", "cat", "stl", "pot", "ppa", "pps", "ppt", "pwz", "ppam", "pptm", "sldm", "ppsm", "potm", "mpp", "mpt", "vdx", "docm", "dotm", "wcm", "wdb", "wks", "wps", "wpl", "xps", "mseq", "mus", "msty", "taglet", "nlu", "nitf", "ntf", "nnd", "nns", "nnw", "ngdat", "n-gage", "rpst", "rpss", "edm", "edx", "ext", "odc", "otc", "odb", "odf", "odft", "odg", "otg", "odi", "oti", "odp", "otp", "ods", "ots", "odt", "odm", "ott", "oth", "xo", "dd2", "oxt", "pptx", "sldx", "ppsx", "potx", "xlsx", "xltx", "docx", "dotx", "mgp", "dp", "esa", "oprc", "pdb", "pqa", "paw", "str", "ei6", "efif", "wg", "plf", "pbd", "box", "mgz", "qps", "ptid", "qwd", "qwt", "qxb", "qxl", "qxt", "bed", "mxl", "musicxml", "cryptonote", "rm", "rmvb", "rmp", "link66", "st", "see", "sema", "semd", "semf", "ifm", "itp", "iif", "ipk", "twd", "twds", "teacher", "sdkd", "sdkm", "dxp", "sfs", "sdc", "sda", "sdd", "smf", "sdw", "vor", "sgl", "smzip", "sm", "wadl", "sxc", "stc", "sxd", "std", "sxi", "sti", "sxm", "sxw", "sxg", "stw", "sus", "susp", "svd", "sis", "sisx", "xsm", "bdm", "xdm", "tao", "cap", "dmp", "pcap", "tmo", "tpt", "mxs", "tra", "ufd", "ufdl", "utz", "umj", "unityweb", "uoml", "vcx", "vsd", "vss", "vst", "vsw", "vsx", "vtx", "vis", "vsf", "wbxml", "wmlc", "wmlsc", "wtb", "nbp", "wpd", "wqd", "stf", "xar", "xfdl", "hvd", "hvs", "hvp", "osf", "osfpvg", "saf", "spf", "cmp", "zir", "zirz", "zaz", "vxml", "vsix", "wasm", "wgt", "library-ms", "searchconnector-ms", "hlp", "wlmp", "wspolicy", "7z", "abw", "ace", "arj", "aab", "vox", "x32", "aam", "aas", "bcpio", "torrent", "blb", "blorb", "adobebridge", "bz", "boz", "bz2", "cb7", "cba", "cbr", "cbt", "cbz", "cdf", "vcd", "cfs", "chat", "pgn", "crx", "cco", "z", "tgz", "cpio", "csh", "udeb", "dgc", "cct", "cst", "cxt", "dcr", "dir", "dxr", "fgd", "swa", "w3d", "wad", "ncx", "dtb", "res", "dvi", "dxf", "erf", "eva", "bdf", "gsf", "psf", "pcf", "snf", "ttf", "pfa", "arc", "gca", "ulx", "gnumeric", "gramps", "gtar", "gz", "hdf", "php", "install", "ins", "isp", "iii", "ipa", "ipg", "ipsw", "ite", "itlp", "itms", "itpc", "class", "jardiff", "jnlp", "skp", "latex", "luac", "lha", "run", "mie", "mvc", "mxp", "mobi", "prc", "application", "slupkg-ms", "manifest", "lit", "lnk", "vsto", "wmd", "wmz", "xbap", "mdb", "obd", "crd", "clp", "bat", "com", "dll", "m13", "m14", "mvb", "emf", "wmf", "mny", "pub", "scd", "trm", "wri", "nc", "pac", "nzb", "hhc", "parquet", "pma", "pmc", "pml", "pmr", "pmw", "pl", "pm", "p12", "pfx", "p7b", "spc", "p7r", "pcast", "qtl", "rar", "ris", "safariextz", "webarchive", "sgimb", "sh", "shar", "mfp", "swf", "xap", "mmf", "sql", "sit", "sitx", "srt", "sv4cpio", "sv4crc", "t3", "gam", "tar", "tcl", "tk", "tex", "tfm", "texi", "texinfo", "obj", "roff", "t", "tr", "man", "me", "ms", "ustar", "hdd", "ova", "ovf", "vbox", "vbox-extpack", "vdi", "vhd", "vmdk", "src", "webapp", "wlpginstall", "wlpginstall3", "cer", "crt", "der", "pem", "fig", "xlf", "xpi", "xz", "z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8", "xaml", "xdf", "xenc", "xht", "xhtml", "asa", "asax", "ascx", "ashx", "asmx", "aspx", "config", "coverage", "datasource", "dgml", "filters", "generictest", "hxa", "hxc", "hxe", "hxf", "hxk", "hxv", "loadtest", "master", "mtx", "orderedtest", "psess", "rdlc", "resx", "rng", "ruleset", "settings", "sitemap", "skin", "snippet", "svc", "testrunconfig", "testsettings", "trx", "vcproj", "vcxproj", "vscontent", "vsmdi", "webtest", "wiq", "xmta", "xsc", "xss", "xop", "xpl", "xspf", "mxml", "xhvml", "xvm", "xvml", "yang", "yin", "zip", "aac", "adts", "ac3", "aif", "aifc", "aiff", "cdda", "axa", "aa", "au", "snd", "flac", "m4a", "m4b", "m4p", "mid", "midi", "rmi", "kar", "mp4a", "m2a", "m3a", "mp2", "mp2a", "mp3", "mpga", "oga", "ogg", "opus", "spx", "s3m", "pls", "sil", "aax", "uva", "uvva", "eol", "adt", "dra", "dts", "dtshd", "lvp", "pya", "ecelp4800", "ecelp7470", "ecelp9600", "rip", "wav", "wave", "weba", "caf", "gsm", "m4r", "mka", "m3u", "m3u8", "wax", "wma", "ra", "ram", "rpm", "sd2", "smd", "smx", "smz", "xm", "cdx", "cif", "cmdf", "cml", "csml", "xyz", "dwf", "ttc", "ttf", "woff2", "apng", "avif", "avifs", "bmp", "dib", "cgm", "cod", "g3", "gif", "heic", "heics", "heif", "heifs", "ief", "jp2", "jpg2", "jfif", "jpe", "jpeg", "jpg", "jpm", "jpf", "jpx", "jxl", "ktx", "pct", "pic", "pict", "png", "pnz", "btif", "sgi", "svg", "svgz", "tif", "tiff", "uvg", "uvi", "uvvg", "uvvi", "djv", "djvu", "fbs", "fpx", "fst", "mmr", "rlc", "mdi", "wdp", "npx", "hdr", "rf", "wbmp", "xif", "webp", "3ds", "dng", "cr2", "cr3", "crw", "ras", "cmx", "erf", "fh", "fh4", "fh5", "fh7", "fhc", "raf", "ico", "art", "jng", "dcr", "k25", "kdc", "mac", "pnt", "pntg", "mrw", "sid", "nef", "nrw", "orf", "raw", "rw2", "rwl", "pef", "pnm", "pbm", "pgm", "ppm", "qti", "qtif", "rgb", "x3f", "arw", "sr2", "srf", "tga", "xbm", "xpm", "xwd", "disposition-notification", "u8msg", "u8dsn", "u8mdn", "u8hdr", "eml", "mht", "mhtml", "mime", "nws", "gltf", "glb", "iges", "igs", "mesh", "msh", "silo", "dae", "gdl", "gtw", "vtu", "vrml", "x3db", "x3dbz", "x3dv", "x3dvz", "x3d", "x3dz", "appcache", "ics", "ifb", "coffee", "litcoffee", "css", "csv", "dlm", "gemini", "gmi", "323", "htm", "html", "hxt", "shtml", "uls", "jade", "ecma", "es", "js", "jsm", "jsx", "less", "markdown", "md", "mml", "n3", "asm", "bas", "c", "cc", "cd", "cfg", "cmd", "cnf", "conf", "cpp", "cs", "csdproj", "csproj", "cxx", "dbproj", "def", "dsw", "h", "hh", "hpp", "hxx", "i", "idl", "in", "inc", "ini", "inl", "ipproj", "jsxbin", "list", "log", "lst", "mak", "map", "mk", "odh", "odl", "pkgdef", "pkgundef", "py", "rc", "rc2", "rct", "reg", "rgs", "s", "scr", "sln", "sol", "sor", "srf", "text", "tlh", "tli", "txt", "user", "vb", "vbdproj", "vbproj", "vcs", "vddproj", "vdp", "vdproj", "vspscc", "vsscc", "vssscc", "xdr", "xoml", "dsc", "rtx", "sct", "wsc", "sgm", "sgml", "shex", "slim", "slm", "styl", "stylus", "tsv", "ttl", "uri", "uris", "urls", "vbs", "vcard", "curl", "dcurl", "mcurl", "scurl", "sub", "fly", "flx", "gv", "3dml", "spot", "jad", "wml", "wmls", "vtt", "htt", "dic", "htc", "f", "f77", "f90", "for", "feature", "hbs", "hdml", "qht", "qhtm", "lua", "md", "mkd", "contact", "group", "iqy", "rqy", "nfo", "opml", "p", "pas", "pde", "rs", "sass", "scss", "etx", "sfv", "ymp", "toml", "uu", "vcf", "yaml", "yml", "addin", "disco", "dll.config", "dtd", "dtsconfig", "exe.config", "mno", "ssisdeploymentmanifest", "vml", "vsct", "vsixlangpack", "vsixmanifest", "vssettings", "vstemplate", "wsdl", "xml", "xrm-ms", "xsd", "xsf", "xsl", "xslt", "3gp", "3gpp", "3g2", "3gp2", "axv", "divx", "h261", "h263", "h264", "jpgv", "jpgm", "mj2", "mjp2", "mp4", "mp4v", "mpg4", "m1v", "m2v", "mod", "mp2", "mp2v", "mpa", "mpe", "mpeg", "mpg", "mpv2", "vbk", "ogv", "mov", "mqv", "qt", "uvh", "uvvh", "uvm", "uvvm", "uvp", "uvvp", "uvs", "uvvs", "uvv", "uvvv", "m2t", "m2ts", "mts", "ts", "tts", "dvb", "fvt", "m4u", "mxu", "pyv", "uvu", "uvvu", "viv", "webm", "dif", "dv", "f4v", "fli", "flv", "ivf", "lsf", "lsx", "m4v", "mk3d", "mks", "mkv", "mng", "asf", "asr", "asx", "nsc", "vob", "wm", "wmp", "wmv", "wmx", "wvx", "avi", "movie", "smv", "ice", "flr", "wrl", "wrz", "xaf", "xof"]; diff --git a/app/target/debug/build/serde-07b13cbb0fd598fc/out/private.rs b/app/target/debug/build/serde-07b13cbb0fd598fc/out/private.rs deleted file mode 100644 index 92008466..00000000 --- a/app/target/debug/build/serde-07b13cbb0fd598fc/out/private.rs +++ /dev/null @@ -1,6 +0,0 @@ -#[doc(hidden)] -pub mod __private229 { - #[doc(hidden)] - pub use crate::private::*; -} -use serde_core::__private229 as serde_core_private; diff --git a/app/target/debug/build/serde_core-99e7571ac0e43228/out/private.rs b/app/target/debug/build/serde_core-99e7571ac0e43228/out/private.rs deleted file mode 100644 index 2da7a58d..00000000 --- a/app/target/debug/build/serde_core-99e7571ac0e43228/out/private.rs +++ /dev/null @@ -1,5 +0,0 @@ -#[doc(hidden)] -pub mod __private229 { - #[doc(hidden)] - pub use crate::private::*; -} diff --git a/app/target/debug/build/thiserror-b16f062556d3d9bb/out/private.rs b/app/target/debug/build/thiserror-b16f062556d3d9bb/out/private.rs deleted file mode 100644 index 036d1e64..00000000 --- a/app/target/debug/build/thiserror-b16f062556d3d9bb/out/private.rs +++ /dev/null @@ -1,5 +0,0 @@ -#[doc(hidden)] -pub mod __private21 { - #[doc(hidden)] - pub use crate::private::*; -} diff --git a/app/tests/api_builds.rs b/app/tests/api_builds.rs index 49c2e6d3..395d667a 100644 --- a/app/tests/api_builds.rs +++ b/app/tests/api_builds.rs @@ -124,3 +124,48 @@ async fn a_token_names_its_project(app: Application) -> laravel::Result<()> { assert!(unknown.text().contains("unknown field `comitt`"), "{}", unknown.text()); Ok(()) } + +#[laravel::test] +async fn a_bad_token_or_build_is_refused_saying_why(app: Application) -> laravel::Result<()> { + let missing = app.post("/api/v1/builds").json(build_params(None)).await; + missing.assert_status(401); + assert_eq!(missing.json()["description"], "missing project token"); + let project = app.post("/api/v1/builds").header("authorization", "Bearer vci_nope").json(build_params(None)).await; + assert_eq!(project.json()["description"], "invalid project token"); + let personal = app.post("/api/v1/builds").header("authorization", "Bearer vcu_nope").json(build_params(None)).await; + assert_eq!(personal.json()["description"], "invalid personal access token"); + + let (token, _) = project_token("pdfs").await?; + let auth = format!("Bearer {token}"); + for (body, says) in [ + (json!({ "commit": "not a sha!", "branch": "main" }), "commit must be"), + (json!({ "commit": "abc", "branch": "main", "parent_commits": ["../x"] }), "parent_commits"), + (json!({ "commit": "abc", "branch": "x".repeat(300) }), "branch must be"), + (json!({ "commit": "abc", "branch": "main", "nonce": "" }), "nonce must be"), + ] { + let refused = app.post("/api/v1/builds").header("authorization", &auth).json(body).await; + refused.assert_status(400); + assert!(refused.text().contains(says), "{}", refused.text()); + } + Ok(()) +} + +#[laravel::test] +async fn no_snapshot_is_written_when_any_in_the_request_is_invalid(app: Application) -> laravel::Result<()> { + let (token, _) = project_token("pdfs").await?; + let auth = format!("Bearer {token}"); + let build = app.post("/api/v1/builds").header("authorization", &auth).json(build_params(None)).await.json().clone(); + let id = build["id"].as_str().unwrap().to_string(); + let good = json!({ "name": "a", "kind": "image", "fingerprint": "b".repeat(64), "sha256": "a".repeat(64), + "size": 1, "content_type": "image/png" }); + let bad = json!({ "name": "b", "kind": "image", "fingerprint": "b".repeat(64), "sha256": "A".repeat(64), + "size": 1, "content_type": "image/png" }); + app.post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": [good, bad] })) + .await + .assert_status(400); + let count: Option = db::query!("SELECT COUNT(*) FROM snapshots").scalar().await?; + assert_eq!(count, Some(0)); + Ok(()) +} diff --git a/app/tests/billing.rs b/app/tests/billing.rs new file mode 100644 index 00000000..634dc799 --- /dev/null +++ b/app/tests/billing.rs @@ -0,0 +1,207 @@ +//! Stripe's webhook: signed events only; a subscription moves the organization to Team and back; a paid pack is +//! credited once; an older subscription event never undoes a newer one. + +use app::billing::webhook::verify_signature; +use app::models::User; +use hmac::{Hmac, Mac}; +use laravel::db; +use laravel::http::client; +use laravel::model::create; +use laravel::testing::TestResponse; +use laravel::testing::prelude::*; +use sha2::Sha256; + +const SECRET: &str = "whsec_test"; + +fn stripe() -> Application { + app::testing::configure().with_env("STRIPE_WEBHOOK_SECRET", SECRET).create() +} + +fn signed(body: &str, t: i64) -> String { + let mut mac = Hmac::::new_from_slice(SECRET.as_bytes()).unwrap(); + mac.update(format!("{t}.{body}").as_bytes()); + format!("t={t},v1={}", hex::encode(mac.finalize().into_bytes())) +} + +async fn org() -> laravel::Result { + Ok(db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .expect("an id")) +} + +async fn post(app: &Application, event: serde_json::Value) -> TestResponse { + let body = event.to_string(); + let now = laravel::now().timestamp().as_second(); + app.post("/webhooks/stripe") + .header("stripe-signature", signed(&body, now)) + .header("content-type", "application/json") + .body(body) + .await +} + +#[test] +fn signatures_are_checked_with_their_time() { + let sig = signed("{}", 1_000); + assert!(verify_signature(SECRET, &sig, b"{}", 1_100)); + assert!(!verify_signature(SECRET, &sig, b"{}", 1_000 + 301), "too old"); + assert!(!verify_signature(SECRET, &sig, b"{ }", 1_100), "another body"); + assert!(!verify_signature("whsec_other", &sig, b"{}", 1_100)); +} + +#[laravel::test(app = stripe)] +async fn an_unsigned_event_is_refused(app: Application) { + app.post("/webhooks/stripe").header("stripe-signature", "t=1,v1=00").body("{}").await.assert_status(401); +} + +#[laravel::test(app = stripe)] +async fn subscriptions_move_the_plan_and_older_events_change_nothing(app: Application) -> laravel::Result<()> { + let org = org().await?; + let meta = json!({ "organization_id": org.to_string() }); + post( + &app, + json!({ "type": "checkout.session.completed", "created": 100, "data": { "object": { + "mode": "subscription", "subscription": "sub_1", "customer": "cus_1", "metadata": meta } } }), + ) + .await + .assert_ok(); + let plan = || async { db::query!("SELECT plan FROM organizations WHERE id = {org}").scalar::().await }; + assert_eq!(plan().await?.as_deref(), Some("team")); + post( + &app, + json!({ "type": "customer.subscription.deleted", "created": 300, "data": { "object": { + "id": "sub_1", "customer": "cus_1" } } }), + ) + .await + .assert_ok(); + assert_eq!(plan().await?.as_deref(), Some("free")); + // A late "active" from before the cancellation changes nothing + post( + &app, + json!({ "type": "customer.subscription.updated", "created": 200, "data": { "object": { + "id": "sub_1", "customer": "cus_1", "status": "active" } } }), + ) + .await + .assert_ok() + .assert_json_path("ignored", "an older event"); + assert_eq!(plan().await?.as_deref(), Some("free")); + Ok(()) +} + +#[laravel::test(app = stripe)] +async fn a_paid_pack_is_credited_once(app: Application) -> laravel::Result<()> { + let org = org().await?; + let event = json!({ "type": "checkout.session.completed", "created": 100, "data": { "object": { + "id": "cs_1", "mode": "payment", "payment_status": "paid", + "metadata": { "organization_id": org.to_string(), "kind": "credit_pack", "packs": "2" } } } }); + post(&app, event.clone()).await.assert_ok(); + post(&app, event).await.assert_ok(); + let balance: Option = + db::query!("SELECT credits_balance FROM organizations WHERE id = {org}").scalar().await?; + assert_eq!(balance, Some(2 * app::billing::CREDIT_PACK.credits), "Stripe's retry adds nothing"); + Ok(()) +} + +fn with_stripe_key() -> Application { + app::testing::configure() + .with_envs([("STRIPE_SECRET_KEY", "sk_test_x"), ("VISUALCI_APP_URL", "https://app.visualci.test")]) + .create() +} + +async fn member(org: i64, email: &str, role: &str) -> laravel::Result { + let user = create!(User { pid: laravel::str::uuid7(), name: "Someone", email: email, staff: false }).await?; + let id = user.id; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {id}, {role}, 'created', now(), now())" + ) + .insert() + .await?; + Ok(user) +} + +#[laravel::test(app = with_stripe_key)] +async fn only_admins_check_out_and_get_a_stripe_url(app: Application) -> laravel::Result<()> { + let org = org().await?; + let admin = member(org, "admin@example.com", "admin").await?; + let reader = member(org, "reader@example.com", "member").await?; + let outsider = + create!(User { pid: laravel::str::uuid7(), name: "Out", email: "out@example.com", staff: false }).await?; + // Every Stripe call answers with an object that has an ID, a URL and an empty list + let _stripe = client::fake() + .with("api.stripe.com/*", json!({ "id": "cs_1", "url": "https://checkout.stripe.test/cs_1", "data": [] })); + app.get("/api/ui/billing/plans").await.assert_ok().assert_json_path("stripe_enabled", true); + let checkout = |user: &User| { + app.post("/api/ui/orgs/acme/billing/checkout") + .acting_as(user) + .header("sec-fetch-site", "same-origin") + .json(json!({ "plan": "team" })) + }; + checkout(&outsider).await.assert_status(404); + checkout(&reader).await.assert_status(403); + checkout(&admin).await.assert_ok().assert_json_path("url", "https://checkout.stripe.test/cs_1"); + let customer: Option = db::query!("SELECT stripe_customer_id FROM organizations WHERE id = {org}") + .scalar::>() + .await? + .flatten(); + assert_eq!(customer.as_deref(), Some("cs_1"), "the Stripe customer is kept on the organization"); + Ok(()) +} + +#[test] +fn production_never_runs_on_a_test_key() { + let stripe = |key: &str| app::billing::Stripe { secret_key: Some(key.into()), webhook_secret: None }; + assert!(app::billing::check(&stripe("sk_test_x"), true).is_err()); + assert!(app::billing::check(&stripe("rk_test_x"), true).is_err()); + assert!(app::billing::check(&stripe("rk_live_x"), true).is_ok()); + assert!(app::billing::check(&stripe("sk_test_x"), false).is_ok()); +} + +fn stripe_test_key() -> Application { + app::testing::configure() + .with_envs([("STRIPE_WEBHOOK_SECRET", SECRET), ("STRIPE_SECRET_KEY", "sk_test_x")]) + .create() +} + +#[laravel::test(app = stripe_test_key)] +async fn an_event_from_the_other_mode_is_refused(app: Application) -> laravel::Result<()> { + let org = org().await?; + let event = |livemode: bool| { + json!({ + "type": "customer.subscription.deleted", "created": 1_800_000_000, "livemode": livemode, + "data": { "object": { "id": "sub_1", "metadata": { "organization_id": org.to_string() } } }, + }) + }; + post(&app, event(true)).await.assert_status(400); + post(&app, event(false)).await.assert_ok(); + Ok(()) +} + +#[laravel::test(app = stripe)] +async fn a_paid_invoice_keeps_the_two_subscriptions_notice(app: Application) -> laravel::Result<()> { + let org = org().await?; + let notice = "This organization has two Team subscriptions. Cancel one in Manage billing."; + db::query!("UPDATE organizations SET billing_problem = {notice} WHERE id = {org}").update().await?; + let paid = json!({ + "type": "invoice.paid", "created": 1_800_000_000, + "data": { "object": { "id": "in_1", "metadata": { "organization_id": org.to_string() } } }, + }); + post(&app, paid.clone()).await.assert_ok(); + let problem: Option = db::query!("SELECT billing_problem FROM organizations WHERE id = {org}") + .scalar::>() + .await? + .flatten(); + assert_eq!(problem.as_deref(), Some(notice)); + let failed = "Payment for INV-1 failed."; + db::query!("UPDATE organizations SET billing_problem = {failed} WHERE id = {org}").update().await?; + post(&app, paid).await.assert_ok(); + let problem: Option = db::query!("SELECT billing_problem FROM organizations WHERE id = {org}") + .scalar::>() + .await? + .flatten(); + assert_eq!(problem, None); + Ok(()) +} diff --git a/app/tests/branches.rs b/app/tests/branches.rs new file mode 100644 index 00000000..34b51238 --- /dev/null +++ b/app/tests/branches.rs @@ -0,0 +1,46 @@ +//! A pull request closed without merging (or its branch deleted) closes its builds waiting for review; reopening it +//! brings back the newest one. Both are idempotent: forges send the same event more than once. + +use app::domain::builds::{self, CLOSED_BRANCH_DELETED, CLOSED_PULL_REQUEST, CreateParams}; +use app::models::Build; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; + +async fn waiting_build(project: &app::models::Project, branch: &str, commit: &str) -> laravel::Result { + let params: CreateParams = serde_json::from_value(serde_json::json!({ "commit": commit, "branch": branch }))?; + let build = builds::create(project, ¶ms, None).await.map_err(|e| laravel::Error::msg(format!("{e:?}")))?; + let id = build.id; + db::query!("UPDATE builds SET state = 'completed', review_state = 'pending' WHERE id = {id}").update().await?; + Ok(id) +} + +#[laravel::test] +async fn closing_a_branch_closes_its_waiting_builds_and_reopening_brings_back_the_newest( + _app: Application, +) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let project = fixtures::project(&org, "docs").await?; + let older = waiting_build(&project, "feat", "a1").await?; + let newer = waiting_build(&project, "feat", "a2").await?; + let other = waiting_build(&project, "main", "b1").await?; + + assert_eq!(builds::close_branch(project.id, "feat", "pull_request").await?, 2); + assert_eq!(builds::close_branch(project.id, "feat", "pull_request").await?, 0, "a repeated event changes nothing"); + let closed = Build::find_or_fail(newer).await?; + assert_eq!(closed.review_state, "closed"); + assert_eq!(closed.warnings, serde_json::json!([CLOSED_PULL_REQUEST])); + assert_eq!(Build::find_or_fail(other).await?.review_state, "pending", "another branch is left alone"); + + assert_eq!(builds::reopen_branch(project.id, "feat").await?, 1); + let reopened = Build::find_or_fail(newer).await?; + assert_eq!(reopened.review_state, "pending"); + assert_eq!(reopened.warnings, serde_json::json!([])); + assert_eq!(Build::find_or_fail(older).await?.review_state, "closed", "the newest covers the older ones"); + assert_eq!(builds::reopen_branch(project.id, "feat").await?, 1, "the next closed one"); + assert_eq!(builds::reopen_branch(project.id, "feat").await?, 0); + + builds::close_branch(project.id, "main", "branch_deleted").await?; + assert_eq!(Build::find_or_fail(other).await?.warnings, serde_json::json!([CLOSED_BRANCH_DELETED])); + Ok(()) +} diff --git a/app/tests/credits.rs b/app/tests/credits.rs index 77c7defe..9c3457ff 100644 --- a/app/tests/credits.rs +++ b/app/tests/credits.rs @@ -17,3 +17,16 @@ async fn purchased_packs_are_credited_once_per_reference(_app: Application) -> l assert_eq!(rows, Some(2)); Ok(()) } + +#[laravel::test] +async fn usage_says_the_plan_credits_and_pool(_app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + credits::spend(org.id, 1200, "build", Some("build web/1: 1200 snapshots checked"), None, None).await?; + let usage = credits::usage(&org).await?; + assert_eq!(usage["plan"]["id"], "free"); + assert_eq!(usage["credits_this_month"], 1200); + assert_eq!(usage["included_credits"], 25_000); + assert_eq!(usage["out_of_credits"], false); + assert_eq!(usage["open_source"]["pool"], 1_000_000); + Ok(()) +} diff --git a/app/tests/demo.rs b/app/tests/demo.rs new file mode 100644 index 00000000..6dbccf70 --- /dev/null +++ b/app/tests/demo.rs @@ -0,0 +1,84 @@ +//! The public demo (visualci/demo): `demo:reset` rebuilds it through the real pipeline, the same every time, and +//! refuses a `visualci` organization that isn't the demo's. + +use app::domain::demo; +use app::models::{Build, Organization, Project}; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +/// Everything a visitor sees of the demo's builds, without ids or times. +async fn summary() -> laravel::Result { + let org = Organization::query().filter(Organization::slug.eq(demo::ORG)).first().await?.expect("the demo org"); + let project = Project::query() + .filter(Project::organization_id.eq(org.id) & Project::slug.eq(demo::PROJECT)) + .first() + .await? + .expect("the demo project"); + let mut builds = Vec::new(); + for b in Build::query().filter(Build::project_id.eq(project.id)).get().await? { + let snapshots: Vec = app::domain::snapshots::of_build(b.id) + .await? + .iter() + .map(|s| json!([s.name, s.platform, s.kind, s.state])) + .collect(); + builds.push(json!({ + "number": b.number, "branch": b.branch, "pr": b.pr_number, "state": b.state, + "review_state": b.review_state, "conclusion": b.conclusion, "snapshots": snapshots, + })); + } + builds.sort_by_key(|b| b["number"].as_i64()); + Ok(json!({ "public": project.public, "builds": builds })) +} + +#[laravel::test] +async fn the_demo_is_rebuilt_the_same_every_time(app: Application) -> laravel::Result<()> { + Box::pin(same_every_time(app)).await +} + +async fn same_every_time(app: Application) -> laravel::Result<()> { + let store = fixtures::blob_store().await?; + assert_eq!(Box::pin(demo::reset(&store, "1")).await?, 4); + let first = summary().await?; + assert_eq!(first["public"], true); + let builds = first["builds"].as_array().unwrap(); + assert!(builds.iter().all(|b| b["state"] == "completed"), "{first:#}"); + // The pull request shows every kind of change, and the reviewed branch is approved. + let pr = builds.iter().find(|b| b["pr"] == 42).expect("PR #42"); + let states: Vec<&str> = pr["snapshots"].as_array().unwrap().iter().filter_map(|s| s[3].as_str()).collect(); + for state in ["changed", "added", "removed"] { + assert!(states.contains(&state), "PR #42 has a {state} snapshot: {states:?}"); + } + let kinds: Vec<&str> = pr["snapshots"].as_array().unwrap().iter().filter_map(|s| s[2].as_str()).collect(); + for kind in ["image", "document", "text"] { + assert!(kinds.contains(&kind), "PR #42 has a {kind}: {kinds:?}"); + } + let reviewed = builds.iter().find(|b| b["pr"] == 41).expect("PR #41"); + assert_eq!(reviewed["review_state"], "approved", "{reviewed}"); + + // The owner isn't a sign-up anyone is told about. + let owner = demo::OWNER_EMAIL; + let notified: Option = + db::query!("SELECT COUNT(*) FROM users WHERE email = {owner} AND signup_notified_at IS NOT NULL") + .scalar() + .await?; + assert_eq!(notified, Some(1)); + + // Anything done to it since is undone, and a second run gives the same demo. + let changed = Build::query().first().await?.unwrap(); + let id = changed.id; + db::query!("UPDATE builds SET review_state = 'rejected' WHERE id = {id}").update().await?; + app.command("demo:reset").await.assert_successful().assert_output_contains("visualci/demo has 4 builds"); + assert_eq!(summary().await?, first); + Ok(()) +} + +#[laravel::test] +async fn the_demo_refuses_a_visualci_organization_that_is_not_its_own(_app: Application) -> laravel::Result<()> { + let store = fixtures::blob_store().await?; + fixtures::organization(demo::ORG).await?; + let refused = Box::pin(demo::reset(&store, "1")).await; + assert!(refused.is_err_and(|e| e.to_string().contains("isn't the demo's"))); + Ok(()) +} diff --git a/app/tests/device.rs b/app/tests/device.rs new file mode 100644 index 00000000..97ccf645 --- /dev/null +++ b/app/tests/device.rs @@ -0,0 +1,99 @@ +//! `visualci login`: the CLI gets a code pair, the person approves the user code, and the next poll gets a working +//! personal token, once, with a security notice; a denied code says so. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn an_approved_code_gives_the_cli_one_token(app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let pair = app.post("/api/v1/device/code").json(json!({ "name": "visualci CLI on ada-laptop" })).await; + pair.assert_ok().assert_json_path("interval", 3); + let device = pair.json()["device_code"].as_str().unwrap().to_string(); + let user_code = pair.json()["user_code"].as_str().unwrap().to_string(); + assert!(pair.json()["verification_uri_complete"].as_str().unwrap().ends_with(&format!("/device?code={user_code}"))); + + // Each poll as if the interval had passed (a quicker one gets slow_down, tested below) + let poll = || async { + db::query!("UPDATE device_logins SET last_polled_at = NULL").update().await.unwrap(); + app.post("/api/v1/device/token").json(json!({ "device_code": device.clone() })).await + }; + poll().await.assert_ok().assert_json_path("status", "pending"); + + let typed = user_code.to_lowercase().replace('-', ""); + app.get(format!("/api/ui/device/{typed}")) + .acting_as(&ada) + .await + .assert_ok() + .assert_json_path("label", "VisualCI command-line sign-in") + .assert_json_path("client", "visualci CLI on ada-laptop"); + app.post(format!("/api/ui/device/{user_code}")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "approve": true })) + .await + .assert_ok(); + app.get(format!("/api/ui/device/{user_code}")).acting_as(&ada).await.assert_status(404); + + let approved = poll().await; + approved.assert_ok().assert_json_path("status", "approved").assert_json_path("user", "Ada"); + let token = approved.json()["token"].as_str().unwrap().to_string(); + app.get("/api/v1/whoami") + .header("authorization", format!("Bearer {token}")) + .await + .assert_ok() + .assert_json_path("client.token_name", "visualci CLI on ada-laptop"); + poll().await.assert_json_path("status", "expired"); + let notices: Option = db::query!("SELECT count(*) FROM emails WHERE kind = 'device_sign_in'").scalar().await?; + assert_eq!(notices, Some(1)); + Ok(()) +} + +#[laravel::test] +async fn a_denied_code_says_so(app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let pair = app.post("/api/v1/device/code").json(json!({})).await; + let device = pair.json()["device_code"].as_str().unwrap().to_string(); + let user_code = pair.json()["user_code"].as_str().unwrap().to_string(); + app.get(format!("/api/ui/device/{user_code}")).header("accept", "application/json").await.assert_status(401); + app.post(format!("/api/ui/device/{user_code}")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "approve": false })) + .await + .assert_ok(); + app.post("/api/v1/device/token").json(json!({ "device_code": device })).await.assert_json_path("status", "denied"); + app.post("/api/v1/device/token") + .json(json!({ "device_code": "nothing-like-it" })) + .await + .assert_json_path("status", "expired"); + Ok(()) +} + +#[laravel::test] +async fn a_quick_poll_is_told_to_slow_down(app: Application) -> laravel::Result<()> { + let pair = app.post("/api/v1/device/code").json(json!({})).await; + let device = pair.json()["device_code"].as_str().unwrap().to_string(); + let poll = || app.post("/api/v1/device/token").json(json!({ "device_code": device.clone() })); + poll().await.assert_json_path("status", "pending"); + poll().await.assert_json_path("status", "slow_down"); + Ok(()) +} + +#[laravel::test] +async fn one_address_gets_a_few_codes_and_old_ones_are_pruned(app: Application) -> laravel::Result<()> { + for _ in 0..app::auth::device::CODES_PER_ADDRESS { + app.post("/api/v1/device/code").json(json!({})).await.assert_ok(); + } + app.post("/api/v1/device/code").json(json!({})).await.assert_status(429); + db::query!( + "UPDATE device_logins SET expires_at = now() - interval '2 days', created_at = now() - interval '2 days'" + ) + .update() + .await?; + assert_eq!(app::auth::device::prune().await?, app::auth::device::CODES_PER_ADDRESS as u64); + app.post("/api/v1/device/code").json(json!({})).await.assert_ok(); + Ok(()) +} diff --git a/app/tests/downloads.rs b/app/tests/downloads.rs new file mode 100644 index 00000000..4a1d3ace --- /dev/null +++ b/app/tests/downloads.rs @@ -0,0 +1,235 @@ +//! Bulk downloads (sc-8869): a build's images as one tar.zst, filtered by state, sides and glob, reused within the +//! hour, deleted by retention after a day, and only for the build's own project. + +use app::domain::downloads; +use app::models::Download; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +fn png(rgb: [u8; 3]) -> Vec { + // Big enough that the changed square, with the crop's margin, is smaller than the image. + let mut img = image::RgbImage::from_pixel(200, 150, image::Rgb([255, 255, 255])); + for x in 90..110 { + for y in 60..80 { + img.put_pixel(x, y, image::Rgb(rgb)); + } + } + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() +} + +const RED: [u8; 3] = [255, 0, 0]; +const GREEN: [u8; 3] = [0, 255, 0]; +const BLUE: [u8; 3] = [0, 0, 255]; + +async fn project_token() -> laravel::Result { + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "web").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + Ok(token) +} + +/// A finished build of these images on main. +async fn build(app: &Application, token: &str, commit: &str, parents: &[&str], files: &[(&str, [u8; 3])]) -> Value { + let auth = format!("Bearer {token}"); + let created = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": commit, "branch": "main", "parent_commits": parents })) + .await + .json() + .clone(); + let id = created["id"].as_str().unwrap().to_string(); + let mut list = Vec::new(); + let mut bodies = Vec::new(); + for (name, rgb) in files { + let bytes = png(*rgb); + let sha = visualci_core::sha256_hex(&bytes); + list.push(json!({ + "name": name, "kind": "image", "sha256": sha, "size": bytes.len(), "content_type": "image/png", + "fingerprint": visualci_core::image_hash::fingerprint_bytes(&bytes).unwrap(), + })); + bodies.push(bytes); + } + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": list })) + .await; + registered.assert_ok(); + let registered = registered.json().clone(); + for (s, bytes) in registered["snapshots"].as_array().unwrap().iter().zip(bodies) { + if let Some(url) = s["upload_url"].as_str() { + let r = + reqwest::Client::new().put(url).header("content-type", "image/png").body(bytes).send().await.unwrap(); + assert!(r.status().is_success()); + } + } + let done = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await.json().clone(); + assert_eq!(done["state"], "completed", "{done}"); + done +} + +#[laravel::test] +async fn a_builds_changed_images_download_as_one_archive(app: Application) -> laravel::Result<()> { + let store = fixtures::blob_store().await?; + let token = project_token().await?; + let auth = format!("Bearer {token}"); + build(&app, &token, "A", &[], &[("web/a", RED), ("web/b", BLUE), ("other/c", RED)]).await; + let b = build(&app, &token, "B", &["A"], &[("web/a", GREEN), ("web/b", BLUE), ("other/c", BLUE)]).await; + + // The changed snapshots under web/, by build number: the job runs inline in tests. + let r = app + .post(format!("/api/v1/builds/{}/downloads", b["number"])) + .header("authorization", &auth) + .json(json!({ "glob": "web/**", "sides": ["head", "regions"] })) + .await; + r.assert_ok(); + let first = r.json().clone(); + assert_eq!(first["state"], "ready", "{first}"); + assert_eq!(first["summary"]["snapshots"], 1, "only web/a changed under web/: {first}"); + assert_eq!(first["files"], 3, "head, regions and the manifest: {first}"); + assert_eq!(first["filter"], json!({ "state": "changed", "sides": ["head", "regions"], "glob": "web/**" })); + + let bytes = reqwest::get(first["url"].as_str().unwrap()).await.unwrap().bytes().await.unwrap(); + let mut files = std::collections::BTreeMap::new(); + visualci_core::bundle::for_each_entry(bytes.as_ref(), 64 << 20, |path, bytes| { + files.insert(path.to_string(), bytes); + Ok::<_, ()>(()) + }) + .unwrap(); + assert_eq!(files.keys().collect::>(), ["manifest.json", "web/a/head.png", "web/a/regions.png"]); + assert_eq!(files["web/a/head.png"], png(GREEN)); + let regions = image::load_from_memory(&files["web/a/regions.png"]).unwrap(); + assert!(regions.width() < 200 && regions.height() < 150, "cropped to the change"); + let manifest: Value = serde_json::from_slice(&files["manifest.json"]).unwrap(); + assert_eq!(manifest["snapshots"][0]["name"], "web/a"); + assert_eq!(manifest["snapshots"][0]["pages"][0]["files"].as_array().unwrap().len(), 2); + assert!(manifest["snapshots"][0]["pages"][0]["changed_fraction"].as_f64().unwrap() > 0.0, "{manifest}"); + + // Every unchanged snapshot, by id: base, head and no diff. + let unchanged = app + .post(format!("/api/v1/builds/{}/downloads", b["id"].as_str().unwrap())) + .header("authorization", &auth) + .json(json!({ "state": "unchanged" })) + .await + .json() + .clone(); + assert_eq!( + (unchanged["summary"]["snapshots"].clone(), unchanged["files"].clone()), + (json!(1), json!(3)), + "{unchanged}" + ); + + // The same filter within the hour: the same download, not built again. + let again = app + .post(format!("/api/v1/builds/%23{}/downloads", b["number"])) + .header("authorization", &auth) + .json(json!({ "glob": "web/**", "sides": ["regions", "head"] })) + .await + .json() + .clone(); + assert_eq!(again["id"], first["id"]); + let shown = + app.get(format!("/api/v1/downloads/{}", first["id"].as_str().unwrap())).header("authorization", &auth).await; + shown.assert_ok(); + assert_eq!(shown.json()["state"], "ready"); + + // A filter it doesn't know is refused, saying why. + let r = app + .post(format!("/api/v1/builds/{}/downloads", b["number"])) + .header("authorization", &auth) + .json(json!({ "state": "new" })) + .await; + r.assert_status(400); + assert!(r.text().contains("state must be one of"), "{}", r.text()); + + // After a day, retention deletes the download and its archive. + let pid: laravel::str::Uuid = first["id"].as_str().unwrap().parse().unwrap(); + let d = Download::query().filter(Download::pid.eq(pid)).first().await?.unwrap(); + let (id, key) = (d.id, d.object_key.clone().unwrap()); + db::query!("UPDATE downloads SET created_at = now() - interval '25 hours' WHERE id = {id}").update().await?; + assert_eq!(downloads::prune(Some(&store)).await?, 1); + assert_eq!(reqwest::get(store.object_url(&key)).await.unwrap().status().as_u16(), 404); + Ok(()) +} + +#[laravel::test] +async fn another_projects_token_can_not_download_a_build(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let b = build(&app, &token, "A", &[], &[("web/a", RED)]).await; + let other = project_token().await?; + let auth = format!("Bearer {other}"); + let r = app + .post(format!("/api/v1/builds/{}/downloads", b["id"].as_str().unwrap())) + .header("authorization", &auth) + .json(json!({})) + .await; + r.assert_status(404); + let r = app + .post(format!("/api/v1/builds/{}/downloads", b["number"])) + .header("authorization", &auth) + .json(json!({})) + .await; + r.assert_status(404); + Ok(()) +} + +/// A project builds at most three downloads at once, and a download is built once even when its job runs twice. +#[laravel::test] +async fn downloads_are_limited_per_project_and_built_once(app: Application) -> laravel::Result<()> { + Box::pin(limited_and_once(app)).await +} + +async fn limited_and_once(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let auth = format!("Bearer {token}"); + let b = build(&app, &token, "A", &[], &[("web/a", RED)]).await; + let number = b["number"].clone(); + + // Ready now (the job runs inline): building it again does nothing. + let first = app + .post(format!("/api/v1/builds/{number}/downloads")) + .header("authorization", &auth) + .json(json!({ "state": "all" })) + .await; + assert_eq!(first.json()["state"], "ready"); + let pid: laravel::str::Uuid = first.json()["id"].as_str().unwrap().parse().unwrap(); + let mut d = Download::query().filter(Download::pid.eq(pid)).first().await?.unwrap(); + d.state = "pending".to_string(); + downloads::build(d, &app::storage::BlobStore::current().await?).await?; + let again = Download::query().filter(Download::pid.eq(pid)).first().await?.unwrap(); + assert_eq!((again.state.as_str(), again.files), ("ready", first.json()["files"].as_i64().unwrap() as i32)); + + // Three still building: a fourth waits. + let build_id = Download::query().filter(Download::pid.eq(pid)).first().await?.unwrap().build_id; + for i in 0..3 { + let key = format!("busy-{i}"); + db::query!( + "INSERT INTO downloads (pid, build_id, filter, filter_key, state) \ + VALUES (gen_random_uuid(), {build_id}, '{{}}', {key}, 'building')" + ) + .insert() + .await?; + } + let r = app + .post(format!("/api/v1/builds/{number}/downloads")) + .header("authorization", &auth) + .json(json!({ "state": "added" })) + .await; + r.assert_status(429); + assert!(r.text().contains("at most 3 at once"), "{}", r.text()); + Ok(()) +} diff --git a/app/tests/emails.rs b/app/tests/emails.rs new file mode 100644 index 00000000..e791dc18 --- /dev/null +++ b/app/tests/emails.rs @@ -0,0 +1,117 @@ +//! Emails: every kind renders; the outbox queues once per dedupe key and recipient, respects people's choices, and +//! sends through Postmark (faked), keeping a failed send pending for the next run. + +use app::models::User; +use app::notify::{self, Kind, To, outbox}; +use laravel::db; +use laravel::http::client; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[test] +fn every_email_renders() { + let about = notify::About { org_name: "Acme", org_slug: "acme", app_url: "https://app.visualci.test" }; + for (label, kind) in notify::render::samples() { + let r = notify::render(&kind, &about); + assert!(!r.subject.is_empty() && !r.text.is_empty() && r.html.contains("<"), "{label}"); + } +} + +async fn org_with_admins() -> laravel::Result<(i64, User, User)> { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .expect("an id"); + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let bea = create!(User { pid: laravel::str::uuid7(), name: "Bea", email: "bea@example.com", staff: false }).await?; + for u in [ada.id, bea.id] { + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {u}, 'admin', 'created', now(), now())" + ) + .insert() + .await?; + } + Ok((org, ada, bea)) +} + +fn postmark() -> Application { + app::testing::configure().with_env("POSTMARK_SERVER_TOKEN", "test-token").create() +} + +#[laravel::test(app = postmark)] +async fn the_outbox_queues_once_respects_choices_and_sends(_app: Application) -> laravel::Result<()> { + let (org, _ada, bea) = org_with_admins().await?; + let bea_id = bea.id; + db::query!("UPDATE users SET email_low_credits = false WHERE id = {bea_id}").update().await?; + let low = Kind::CreditsLow { + pool: false, + percent: 80, + left: 200_000, + total: 1_000_000, + renews: "1 January 2027".into(), + next: "1 January 2027".into(), + }; + let postmark = client::fake().with("api.postmarkapp.com/*", json!({ "MessageID": "x" })); + // Only Ada: Bea turned low-credit warnings off. The delivery job runs at once in tests (sync queue). + assert_eq!(notify::queue(&low, To::Billing(org), None, "credits_low:80:2026-12").await?, 1); + assert_eq!(notify::queue(&low, To::Billing(org), None, "credits_low:80:2026-12").await?, 0, "once per period"); + postmark.assert_sent_count(1); + let sent: Option = + db::query!("SELECT state FROM emails WHERE recipient = 'ada@example.com'").scalar().await?; + assert_eq!(sent.as_deref(), Some("sent")); + Ok(()) +} + +#[laravel::test(app = postmark)] +async fn a_failed_send_stays_pending_for_the_next_run(_app: Application) -> laravel::Result<()> { + let (org, _ada, _bea) = org_with_admins().await?; + let _postmark = + client::fake().with("api.postmarkapp.com/*", client::response().status(500).json(json!({ "Message": "down" }))); + notify::queue(&Kind::RemovedFromOrg, To::Admins(org), None, "removed:1").await?; + let rows = db::query!("SELECT state, attempts, last_error FROM emails ORDER BY id").select().await?; + assert_eq!(rows.len(), 2); + for r in rows { + assert_eq!(r.try_get::("state")?, "pending"); + assert_eq!(r.try_get::("attempts")?, 1); + assert!(r.try_get::("last_error")?.contains("down")); + } + assert!(outbox::oldest_unsent_seconds().await? >= 0); + assert_eq!(outbox::failed_unresolved_count().await?, 0, "pending, not failed, after one attempt"); + Ok(()) +} + +#[laravel::test(app = postmark)] +async fn claims_are_per_email_and_attempts_end_at_five(_app: Application) -> laravel::Result<()> { + let postmark = client::fake().with("api.postmarkapp.com/*", json!({ "MessageID": "x" })); + // A run that crashed during its fifth attempt, half an hour ago: failed, not sent a sixth time. + db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data, attempts, claimed_at) \ + VALUES ('removed_from_org', 'crashed', 'ada@example.com', '\"RemovedFromOrg\"', 5, now() - interval '31 minutes')" + ) + .insert() + .await?; + // Another run is sending this one right now: left alone. + db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data, attempts, claimed_at) \ + VALUES ('removed_from_org', 'in-flight', 'bea@example.com', '\"RemovedFromOrg\"', 1, now() - interval '6 minutes')" + ) + .insert() + .await?; + let config = app::notify::postmark::Postmark { + token: Some("test-token".into()), + from: "VisualCI ".into(), + reply_to: "support@visualci.com".into(), + }; + assert_eq!(outbox::deliver(&config, "https://app.visualci.com").await?, 0); + postmark.assert_nothing_sent(); + let state = |key: &'static str| async move { + db::query!("SELECT state FROM emails WHERE dedupe_key = {key}").scalar::().await + }; + assert_eq!(state("crashed").await?.as_deref(), Some("failed")); + assert_eq!(state("in-flight").await?.as_deref(), Some("pending")); + Ok(()) +} diff --git a/app/tests/forge_sync.rs b/app/tests/forge_sync.rs new file mode 100644 index 00000000..29a4aada --- /dev/null +++ b/app/tests/forge_sync.rs @@ -0,0 +1,200 @@ +//! The hourly sync rechecks everyone with a GitHub identity: a membership GitHub no longer grants (here, its +//! organization's repository was unlinked) goes, one made by an invitation stays. + +use app::forge::github_app::GithubApp; +use app::forge::sync::{Synced, sync_github}; +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn access_github_no_longer_grants_goes_within_the_hour(_app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + let mut orgs = Vec::new(); + for (slug, source) in [("acme", "github"), ("invited", "invite")] { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, {slug}, now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'member', {source}, now(), now())" + ) + .insert() + .await?; + orgs.push(org); + } + let app = GithubApp { app_id: Some("1".into()), private_key_base64: None, webhook_secret: None }; + assert_eq!( + sync_github(&app).await?, + Synced { people: 1, changed: 1, unlinked: 0, open_source: 0, branches_closed: 0, deferred: false } + ); + let left: Vec = db::query!("SELECT organization_id FROM memberships WHERE user_id = {ada_id}") + .select() + .await? + .iter() + .map(|r| r.try_get("organization_id")) + .collect::>()?; + assert_eq!(left, vec![orgs[1]], "the invited membership stays"); + Ok(()) +} + +/// A GitHub App key made once per run (base64 of its PEM). +fn app_key() -> &'static str { + static KEY: std::sync::OnceLock = std::sync::OnceLock::new(); + KEY.get_or_init(|| { + use base64::Engine; + use rsa::pkcs1::EncodeRsaPrivateKey; + let key = rsa::RsaPrivateKey::new(&mut rsa::rand_core::OsRng, 2048).expect("a key"); + let pem = key.to_pkcs1_pem(rsa::pkcs1::LineEnding::LF).expect("its PEM"); + base64::engine::general_purpose::STANDARD.encode(pem.as_bytes()) + }) +} + +/// Someone who linked a repository and is now only a writer on it: the link goes, so checks and comments stop. +#[laravel::test] +async fn a_link_whose_linker_lost_maintain_is_removed(_app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let project: i64 = db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \ + forge_installation, linked_by, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, 'web', 'Web', 'github', 'https://github.com/acme/web', '42', '7', \ + {ada_id}, now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) + .with("api.github.com/repos/acme/web/collaborators*", json!([{ "id": 1001, "role_name": "write" }])); + let app = GithubApp { app_id: Some("1".into()), private_key_base64: Some(app_key().into()), webhook_secret: None }; + let synced = sync_github(&app).await?; + assert_eq!(synced.unlinked, 1); + let installation: Option = db::query!("SELECT forge_installation FROM projects WHERE id = {project}") + .scalar::>() + .await? + .flatten(); + assert_eq!(installation, None); + // Her write access still makes her a member + let role: Option = + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {ada_id}") + .scalar() + .await?; + assert_eq!(role.as_deref(), Some("member")); + Ok(()) +} + +/// GitHub says a public project's repository went private: the project is made private at once, with a notice on it +/// and an email to its admins. +#[laravel::test] +async fn a_repository_gone_private_makes_its_project_private(_app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'admin', 'created', now(), now())" + ) + .insert() + .await?; + let project: i64 = db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \ + forge_installation, public, repository_public, open_source, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, 'web', 'Web', 'github', 'https://github.com/acme/web', '42', '7', \ + true, true, true, now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + app::forge::events::RepositoryVisibilityChanged { project_id: project, private: true }.dispatch().await?; + let row = db::query!("SELECT public, open_source, notice FROM projects WHERE id = {project}") + .select_one() + .await? + .unwrap(); + assert!(!row.try_get::("public")? && !row.try_get::("open_source")?); + assert!(row.try_get::>("notice")?.unwrap_or_default().contains("private now")); + let emails: Option = + db::query!("SELECT count(*) FROM emails WHERE kind = 'made_private' AND recipient = 'ada@example.com'") + .scalar() + .await?; + assert_eq!(emails, Some(1)); + Ok(()) +} + +/// A branch deleted without a pull request (GitHub doesn't send that event): its builds waiting for review are closed +/// through BranchClosed, and it isn't asked about again for a day. +#[laravel::test] +async fn a_deleted_branchs_waiting_builds_are_closed(_app: Application) -> laravel::Result<()> { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let project: i64 = db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \ + forge_installation, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, 'web', 'Web', 'github', 'https://github.com/acme/web', '42', '7', \ + now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + for (number, branch) in [(1, "gone"), (2, "still-here")] { + db::query!( + "INSERT INTO builds (pid, project_id, number, commit_sha, branch, mode, review_state, created_at, updated_at) \ + VALUES (gen_random_uuid(), {project}, {number}, 'abc', {branch}, 'ci', 'pending', now(), now())" + ) + .insert() + .await?; + } + let events = laravel::event::fake(); + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) + .with("api.github.com/repos/acme/web/branches/still-here", json!({ "name": "still-here" })) + .with("api.github.com/repos/acme/web/branches/*", laravel::http::client::response().status(404).json(json!({}))) + .with("api.github.com/repos/acme/web", json!({ "id": 42 })); + let app = GithubApp { app_id: Some("1".into()), private_key_base64: Some(app_key().into()), webhook_secret: None }; + assert_eq!(app::forge::sync::close_deleted_branches(&app, 500).await?, 1); + events.assert_dispatched_where::(|e| { + e.project_id == project && e.branch == "gone" && e.why == "branch_deleted" + }); + events.assert_dispatched_times::(1); + // Both were asked about today: neither again until tomorrow + assert_eq!(app::forge::sync::close_deleted_branches(&app, 500).await?, 0); + Ok(()) +} diff --git a/app/tests/gallery.rs b/app/tests/gallery.rs new file mode 100644 index 00000000..d7d77340 --- /dev/null +++ b/app/tests/gallery.rs @@ -0,0 +1,275 @@ +//! Public galleries: only the approved default-branch version of a screenshot a `gallery` group includes is served, +//! at one stable URL each, with a manifest that doesn't change unless the images do. Each image served adds a credit +//! to its project's row for the day; a 304, a 404 or a URL with a query costs nothing. + +use app::domain::{gallery, reviews}; +use app::models::{Build, CreditTransaction, Organization, Project}; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +fn png(rgb: [u8; 3]) -> Vec { + let img = image::RgbImage::from_pixel(8, 6, image::Rgb(rgb)); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() +} + +const RED: [u8; 3] = [255, 0, 0]; +const GREEN: [u8; 3] = [0, 255, 0]; +const BLUE: [u8; 3] = [0, 0, 255]; +const PURPLE: [u8; 3] = [128, 0, 128]; + +struct World { + org: Organization, + project: Project, + token: String, +} + +async fn world() -> laravel::Result { + fixtures::blob_store().await?; + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "web").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + Ok(World { org, project, token }) +} + +impl World { + /// A finished CI build of these images, with a visualci.yml that publishes `web/**`. + async fn build( + &self, + app: &Application, + commit: &str, + branch: &str, + parents: &[&str], + files: &[(&str, [u8; 3])], + ) -> Build { + // Boxed: the test's own future would otherwise outgrow a test thread's stack. + Box::pin(self.build_inner(app, commit, branch, parents, files)).await + } + + async fn build_inner( + &self, + app: &Application, + commit: &str, + branch: &str, + parents: &[&str], + files: &[(&str, [u8; 3])], + ) -> Build { + let auth = format!("Bearer {}", self.token); + let created = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ + "commit": commit, "branch": branch, "parent_commits": parents, + "config": { "gallery": { "groups": [{ "name": "Web", "include": ["web/**"] }] } }, + })) + .await; + created.assert_ok(); + let id = created.json()["id"].as_str().unwrap().to_string(); + let mut list = Vec::new(); + let mut bodies = Vec::new(); + for (name, rgb) in files { + let bytes = png(*rgb); + let sha = visualci_core::sha256_hex(&bytes); + list.push(json!({ + "name": name, "kind": "image", "sha256": sha, "size": bytes.len(), "content_type": "image/png", + "fingerprint": visualci_core::image_hash::fingerprint_bytes(&bytes).unwrap(), + })); + bodies.push(bytes); + } + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": list })) + .await; + registered.assert_ok(); + for (s, bytes) in registered.json()["snapshots"].as_array().unwrap().iter().zip(bodies) { + if let Some(url) = s["upload_url"].as_str() { + let r = reqwest::Client::new() + .put(url) + .header("content-type", "image/png") + .body(bytes) + .send() + .await + .unwrap(); + assert!(r.status().is_success()); + } + } + let done = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await; + assert_eq!(done.json()["state"], "completed", "{}", done.text()); + let pid: laravel::str::Uuid = id.parse().unwrap(); + Build::query().filter(Build::pid.eq(pid)).first().await.unwrap().unwrap() + } + + async fn review(&self, build: Build, action: &str) -> Build { + Box::pin(reviews::review(build, None, &reviews::Via::default(), action, None, None)).await.unwrap().unwrap() + } + + /// The project's gallery rows: (rows, credits). + async fn gallery_credits(&self) -> (usize, i64) { + let rows = CreditTransaction::query() + .filter(CreditTransaction::organization_id.eq(self.org.id) & CreditTransaction::kind.eq("gallery")) + .get() + .await + .unwrap(); + (rows.len(), rows.iter().map(|r| -r.amount).sum()) + } +} + +fn header(r: &laravel::testing::TestResponse, name: &str) -> String { + r.header(name).unwrap_or_default().to_string() +} + +/// The ETag an image is served with: its SHA-256. +fn etag(rgb: [u8; 3]) -> String { + format!("\"{}\"", visualci_core::sha256_hex(&png(rgb))) +} + +#[laravel::test] +async fn only_approved_default_branch_screenshots_in_a_group_are_served(app: Application) -> laravel::Result<()> { + // On the heap: this test's future is larger than a test thread's stack. + Box::pin(only_approved_served(app)).await +} + +async fn only_approved_served(app: Application) -> laravel::Result<()> { + let w = world().await?; + let base = format!("/g/{}/web", w.org.slug); + w.build(&app, "A", "main", &[], &[("web/home", RED), ("web/about", GREEN), ("private/x", BLUE)]).await; + + // The manifest: the group with its two screenshots, nothing outside the globs, cacheable and readable anywhere. + let m = app.get(format!("{base}.json")).await; + m.assert_ok(); + assert_eq!(header(&m, "cache-control"), "public, max-age=300, s-maxage=86400"); + assert_eq!(header(&m, "access-control-allow-origin"), "*"); + assert_eq!(header(&m, "cross-origin-resource-policy"), "cross-origin"); + let manifest: Value = m.json().clone(); + let urls: Vec = manifest["groups"][0]["items"] + .as_array() + .unwrap() + .iter() + .map(|i| i["url"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(manifest["groups"][0]["name"], "Web"); + assert_eq!(manifest["project"], format!("{}/web", w.org.slug)); + assert_eq!(urls.len(), 2, "{manifest}"); + assert!(urls.iter().all(|u| u.contains("/web/web/")), "{urls:?}"); + assert!(manifest["groups"][0]["items"][0]["since"].as_str().unwrap().ends_with("+00:00"), "{manifest}"); + assert_eq!(app.get(format!("{base}.json")).await.text(), m.text(), "the manifest is stable"); + + // An image: its bytes, a credit, and an ETag that answers a revalidation for free. + let home = app.get(format!("{base}/web/home.png")).await; + home.assert_ok(); + assert_eq!(header(&home, "etag"), etag(RED)); + assert_eq!(header(&home, "content-length"), png(RED).len().to_string()); + assert_eq!(header(&home, "content-type"), "image/png"); + assert_eq!(w.gallery_credits().await, (1, 1)); + let again = app.get(format!("{base}/web/home.png")).header("if-none-match", header(&home, "etag")).await; + again.assert_status(304); + + // Outside the globs, unknown, or with a query: 404, and free. + for path in ["private/x.png", "web/missing.png", "web/home.jpg"] { + app.get(format!("{base}/{path}")).await.assert_status(404); + } + app.get(format!("{base}/web/home.png?width=10")).await.assert_status(404); + assert_eq!(header(&app.get(format!("{base}/private/x.png")).await, "cache-control"), "no-store", "never cached"); + app.get(format!("/g/{}/nope.json", w.org.slug)).await.assert_status(404); + assert_eq!(w.gallery_credits().await, (1, 1)); + + // More images the same day add to the project's one row for the day. + app.get(format!("{base}/web/about.png")).await.assert_ok(); + app.get(format!("{base}/web/home.png")).await.assert_ok(); + assert_eq!(w.gallery_credits().await, (1, 3), "one row for the day"); + + // A pending change keeps the approved image; approving it publishes the new one. + let b = w.build(&app, "B", "main", &["A"], &[("web/home", BLUE), ("web/about", GREEN), ("private/x", BLUE)]).await; + assert_eq!(header(&app.get(format!("{base}/web/home.png")).await, "etag"), etag(RED)); + let b = w.review(b, "approve").await; + assert_eq!(header(&app.get(format!("{base}/web/home.png")).await, "etag"), etag(BLUE)); + // The approval purges exactly the published URLs of its screenshots, and the manifest. + let mut stale = gallery::stale_urls("https://app.visualci.com", &b).await?; + stale.sort(); + let at = format!("https://app.visualci.com/g/{}/web", w.org.slug); + assert_eq!(stale, vec![format!("{at}.json"), format!("{at}/web/home.png")], "not the unchanged about.png"); + + // A rejected change keeps it too, and so does a change on another branch. + let c = w + .build(&app, "C", "main", &["B", "A"], &[("web/home", PURPLE), ("web/about", GREEN), ("private/x", BLUE)]) + .await; + w.review(c, "reject").await; + w.build(&app, "F", "feature", &["B", "A"], &[("web/home", GREEN), ("web/about", GREEN)]).await; + assert_eq!(header(&app.get(format!("{base}/web/home.png")).await, "etag"), etag(BLUE)); + + // Turned off, nothing is served. + let id = w.project.id; + db::query!("UPDATE projects SET gallery_enabled = false WHERE id = {id}").update().await?; + app.get(format!("{base}.json")).await.assert_status(404); + app.get(format!("{base}/web/home.png")).await.assert_status(404); + Ok(()) +} + +/// The gallery serves from the app's own origin, so an image goes out only as the image its bytes are, never as the +/// content type a client declared: an image declared as HTML would run script there, as anyone who opens the link. +#[laravel::test] +async fn an_image_is_served_as_its_bytes_never_as_a_declared_html_type(app: Application) -> laravel::Result<()> { + let w = world().await?; + w.build(&app, "A", "main", &[], &[("web/home", RED)]).await; + let sha = visualci_core::sha256_hex(&png(RED)); + db::query!("UPDATE blobs SET content_type = 'text/html' WHERE sha256 = {sha}").update().await?; + let home = app.get(format!("/g/{}/web/web/home.png", w.org.slug)).await; + home.assert_ok(); + assert_eq!(header(&home, "content-type"), "image/png"); + assert_eq!(header(&home, "x-content-type-options"), "nosniff"); + assert_eq!(header(&home, "access-control-allow-origin"), "*"); + assert!(header(&home, "content-security-policy").contains("sandbox")); + Ok(()) +} + +/// A project's gallery credits stop at the day's cap; a purge covers what dropped out of the gallery since the last +/// one; and a purge that used up its tries is counted in `/status`. +#[laravel::test] +async fn credits_stop_at_the_cap_and_purges_cover_what_dropped_out(app: Application) -> laravel::Result<()> { + Box::pin(cap_and_dropouts(app)).await +} + +async fn cap_and_dropouts(app: Application) -> laravel::Result<()> { + use app::jobs::purge_gallery::PurgeGallery; + let w = world().await?; + w.build(&app, "A", "main", &[], &[("web/home", RED), ("web/about", GREEN)]).await; + let project = Project::find_or_fail(w.project.id).await?; + + for _ in 0..3 { + assert!(app::domain::credits::spend_gallery(&project, 1, 3).await?); + } + assert!(!app::domain::credits::spend_gallery(&project, 1, 3).await?, "past the cap: served free"); + assert_eq!(w.gallery_credits().await, (1, 3)); + + // The first purge records what's published: the manifest and two screenshots. + let first = PurgeGallery { build_id: None, project_id: Some(project.id), urls: vec![] }.plan().await?; + assert_eq!(first.current.len(), 3, "{:?}", first.current); + let (id, current) = (project.id, json!(first.current)); + db::query!("UPDATE projects SET gallery_urls = {current} WHERE id = {id}").update().await?; + + // about.png leaves the gallery (removed, and the removal approved): the next purge includes it. + let b = w.build(&app, "B", "main", &["A"], &[("web/home", RED)]).await; + let b = w.review(b, "approve").await; + let plan = PurgeGallery { build_id: Some(b.id), project_id: None, urls: vec![] }.plan().await?; + let about = format!("https://app.visualci.test/g/{}/web/web/about.png", w.org.slug); + assert!(plan.urls.contains(&about), "{:?}", plan.urls); + assert!(!plan.current.contains(&about), "{:?}", plan.current); + + // A purge that used up its tries. + PurgeGallery { build_id: Some(b.id), project_id: None, urls: vec![about] } + .record_failure("Cloudflare purge: HTTP 500") + .await?; + assert_eq!(app.get("/status").await.json()["gallery_purges_failed"], 1); + Ok(()) +} diff --git a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-2.json b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-2.json index 892d005b..bf8c264c 100644 --- a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-2.json +++ b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-2.json @@ -162,7 +162,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.k0\",\"$.k1\",\"$.k2\",\"$.k3\",\"$.k4\",\"$.k5\",\"$.k6\",\"$.k7\",\"$.k8\",\"$.k9\",\"$.k10\",\"$.k11\",\"$.k12\",\"$.k13\",\"$.k14\",\"$.k15\",\"$.k16\",\"$.k17\",\"$.k18\",\"$.k19\",\"$.k20\",\"$.k21\",\"$.k22\",\"$.k23\",\"$.k24\",\"$.k25\",\"$.k26\",\"$.k27\",\"$.k28\",\"$.k29\",\"$.k30\",\"$.k31\",\"$.k32\",\"$.k33\",\"$.k34\",\"$.k35\",\"$.k36\",\"$.k37\",\"$.k38\",\"$.k39\",\"$.k40\",\"$.k41\",\"$.k42\",\"$.k43\",\"$.k44\",\"$.k45\",\"$.k46\",\"$.k47\",\"$.k48\",\"$.k49\",\"$.k50\",\"$.k51\",\"$.k52\",\"$.k53\",\"$.k54\",\"$.k55\",\"$.k56\",\"$.k57\",\"$.k58\",\"$.k59\",\"$.k60\",\"$.k61\",\"$.k62\",\"$.k63\",\"$.k64\",\"$.k65\",\"$.k66\",\"$.k67\",\"$.k68\",\"$.k69\",\"$.k70\",\"$.k71\",\"$.k72\",\"$.k73\",\"$.k74\",\"$.k75\",\"$.k76\",\"$.k77\",\"$.k78\",\"$.k79\",\"$.k80\",\"$.k81\",\"$.k82\",\"$.k83\",\"$.k84\",\"$.k85\",\"$.k86\",\"$.k87\",\"$.k88\",\"$.k89\",\"$.k90\",\"$.k91\",\"$.k92\",\"$.k93\",\"$.k94\",\"$.k95\",\"$.k96\",\"$.k97\",\"$.k98\",\"$.k99\",\"$.k100\",\"$.k101\",\"$.k102\",\"$.k103\",\"$.k104\",\"$.k105\",\"$.k106\",\"$.k107\",\"$.k108\",\"$.k109\",\"$.k110\",\"$.k111\",\"$.k112\",\"$.k113\",\"$.k114\",\"$.k115\",\"$.k116\",\"$.k117\",\"$.k118\",\"$.k119\",\"$.k120\",\"$.k121\",\"$.k122\",\"$.k123\",\"$.k124\",\"$.k125\",\"$.k126\",\"$.k127\",\"$.k128\",\"$.k129\",\"$.k130\",\"$.k131\",\"$.k132\",\"$.k133\",\"$.k134\",\"$.k135\",\"$.k136\",\"$.k137\",\"$.k138\",\"$.k139\",\"$.k140\",\"$.k141\",\"$.k142\",\"$.k143\",\"$.k144\",\"$.k145\",\"$.k146\",\"$.k147\",\"$.k148\",\"$.k149\"],\"snapshots\":\"**\"}],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.k0\",\"$.k1\",\"$.k2\",\"$.k3\",\"$.k4\",\"$.k5\",\"$.k6\",\"$.k7\",\"$.k8\",\"$.k9\",\"$.k10\",\"$.k11\",\"$.k12\",\"$.k13\",\"$.k14\",\"$.k15\",\"$.k16\",\"$.k17\",\"$.k18\",\"$.k19\",\"$.k20\",\"$.k21\",\"$.k22\",\"$.k23\",\"$.k24\",\"$.k25\",\"$.k26\",\"$.k27\",\"$.k28\",\"$.k29\",\"$.k30\",\"$.k31\",\"$.k32\",\"$.k33\",\"$.k34\",\"$.k35\",\"$.k36\",\"$.k37\",\"$.k38\",\"$.k39\",\"$.k40\",\"$.k41\",\"$.k42\",\"$.k43\",\"$.k44\",\"$.k45\",\"$.k46\",\"$.k47\",\"$.k48\",\"$.k49\",\"$.k50\",\"$.k51\",\"$.k52\",\"$.k53\",\"$.k54\",\"$.k55\",\"$.k56\",\"$.k57\",\"$.k58\",\"$.k59\",\"$.k60\",\"$.k61\",\"$.k62\",\"$.k63\",\"$.k64\",\"$.k65\",\"$.k66\",\"$.k67\",\"$.k68\",\"$.k69\",\"$.k70\",\"$.k71\",\"$.k72\",\"$.k73\",\"$.k74\",\"$.k75\",\"$.k76\",\"$.k77\",\"$.k78\",\"$.k79\",\"$.k80\",\"$.k81\",\"$.k82\",\"$.k83\",\"$.k84\",\"$.k85\",\"$.k86\",\"$.k87\",\"$.k88\",\"$.k89\",\"$.k90\",\"$.k91\",\"$.k92\",\"$.k93\",\"$.k94\",\"$.k95\",\"$.k96\",\"$.k97\",\"$.k98\",\"$.k99\",\"$.k100\",\"$.k101\",\"$.k102\",\"$.k103\",\"$.k104\",\"$.k105\",\"$.k106\",\"$.k107\",\"$.k108\",\"$.k109\",\"$.k110\",\"$.k111\",\"$.k112\",\"$.k113\",\"$.k114\",\"$.k115\",\"$.k116\",\"$.k117\",\"$.k118\",\"$.k119\",\"$.k120\",\"$.k121\",\"$.k122\",\"$.k123\",\"$.k124\",\"$.k125\",\"$.k126\",\"$.k127\",\"$.k128\",\"$.k129\",\"$.k130\",\"$.k131\",\"$.k132\",\"$.k133\",\"$.k134\",\"$.k135\",\"$.k136\",\"$.k137\",\"$.k138\",\"$.k139\",\"$.k140\",\"$.k141\",\"$.k142\",\"$.k143\",\"$.k144\",\"$.k145\",\"$.k146\",\"$.k147\",\"$.k148\",\"$.k149\"],\"snapshots\":\"**\"}],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -170,6 +170,7 @@ "structuredContent": { "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-3.json b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-3.json index fd1787cf..829eb23d 100644 --- a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-3.json +++ b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project-3.json @@ -6,7 +6,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"strict\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.k0\",\"$.k1\",\"$.k2\",\"$.k3\",\"$.k4\",\"$.k5\",\"$.k6\",\"$.k7\",\"$.k8\",\"$.k9\",\"$.k10\",\"$.k11\",\"$.k12\",\"$.k13\",\"$.k14\",\"$.k15\",\"$.k16\",\"$.k17\",\"$.k18\",\"$.k19\",\"$.k20\",\"$.k21\",\"$.k22\",\"$.k23\",\"$.k24\",\"$.k25\",\"$.k26\",\"$.k27\",\"$.k28\",\"$.k29\",\"$.k30\",\"$.k31\",\"$.k32\",\"$.k33\",\"$.k34\",\"$.k35\",\"$.k36\",\"$.k37\",\"$.k38\",\"$.k39\",\"$.k40\",\"$.k41\",\"$.k42\",\"$.k43\",\"$.k44\",\"$.k45\",\"$.k46\",\"$.k47\",\"$.k48\",\"$.k49\",\"$.k50\",\"$.k51\",\"$.k52\",\"$.k53\",\"$.k54\",\"$.k55\",\"$.k56\",\"$.k57\",\"$.k58\",\"$.k59\",\"$.k60\",\"$.k61\",\"$.k62\",\"$.k63\",\"$.k64\",\"$.k65\",\"$.k66\",\"$.k67\",\"$.k68\",\"$.k69\",\"$.k70\",\"$.k71\",\"$.k72\",\"$.k73\",\"$.k74\",\"$.k75\",\"$.k76\",\"$.k77\",\"$.k78\",\"$.k79\",\"$.k80\",\"$.k81\",\"$.k82\",\"$.k83\",\"$.k84\",\"$.k85\",\"$.k86\",\"$.k87\",\"$.k88\",\"$.k89\",\"$.k90\",\"$.k91\",\"$.k92\",\"$.k93\",\"$.k94\",\"$.k95\",\"$.k96\",\"$.k97\",\"$.k98\",\"$.k99\",\"$.k100\",\"$.k101\",\"$.k102\",\"$.k103\",\"$.k104\",\"$.k105\",\"$.k106\",\"$.k107\",\"$.k108\",\"$.k109\",\"$.k110\",\"$.k111\",\"$.k112\",\"$.k113\",\"$.k114\",\"$.k115\",\"$.k116\",\"$.k117\",\"$.k118\",\"$.k119\",\"$.k120\",\"$.k121\",\"$.k122\",\"$.k123\",\"$.k124\",\"$.k125\",\"$.k126\",\"$.k127\",\"$.k128\",\"$.k129\",\"$.k130\",\"$.k131\",\"$.k132\",\"$.k133\",\"$.k134\",\"$.k135\",\"$.k136\",\"$.k137\",\"$.k138\",\"$.k139\",\"$.k140\",\"$.k141\",\"$.k142\",\"$.k143\",\"$.k144\",\"$.k145\",\"$.k146\",\"$.k147\",\"$.k148\",\"$.k149\"],\"snapshots\":\"**\"}],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"settings\":{\"ci_mode\":\"strict\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.k0\",\"$.k1\",\"$.k2\",\"$.k3\",\"$.k4\",\"$.k5\",\"$.k6\",\"$.k7\",\"$.k8\",\"$.k9\",\"$.k10\",\"$.k11\",\"$.k12\",\"$.k13\",\"$.k14\",\"$.k15\",\"$.k16\",\"$.k17\",\"$.k18\",\"$.k19\",\"$.k20\",\"$.k21\",\"$.k22\",\"$.k23\",\"$.k24\",\"$.k25\",\"$.k26\",\"$.k27\",\"$.k28\",\"$.k29\",\"$.k30\",\"$.k31\",\"$.k32\",\"$.k33\",\"$.k34\",\"$.k35\",\"$.k36\",\"$.k37\",\"$.k38\",\"$.k39\",\"$.k40\",\"$.k41\",\"$.k42\",\"$.k43\",\"$.k44\",\"$.k45\",\"$.k46\",\"$.k47\",\"$.k48\",\"$.k49\",\"$.k50\",\"$.k51\",\"$.k52\",\"$.k53\",\"$.k54\",\"$.k55\",\"$.k56\",\"$.k57\",\"$.k58\",\"$.k59\",\"$.k60\",\"$.k61\",\"$.k62\",\"$.k63\",\"$.k64\",\"$.k65\",\"$.k66\",\"$.k67\",\"$.k68\",\"$.k69\",\"$.k70\",\"$.k71\",\"$.k72\",\"$.k73\",\"$.k74\",\"$.k75\",\"$.k76\",\"$.k77\",\"$.k78\",\"$.k79\",\"$.k80\",\"$.k81\",\"$.k82\",\"$.k83\",\"$.k84\",\"$.k85\",\"$.k86\",\"$.k87\",\"$.k88\",\"$.k89\",\"$.k90\",\"$.k91\",\"$.k92\",\"$.k93\",\"$.k94\",\"$.k95\",\"$.k96\",\"$.k97\",\"$.k98\",\"$.k99\",\"$.k100\",\"$.k101\",\"$.k102\",\"$.k103\",\"$.k104\",\"$.k105\",\"$.k106\",\"$.k107\",\"$.k108\",\"$.k109\",\"$.k110\",\"$.k111\",\"$.k112\",\"$.k113\",\"$.k114\",\"$.k115\",\"$.k116\",\"$.k117\",\"$.k118\",\"$.k119\",\"$.k120\",\"$.k121\",\"$.k122\",\"$.k123\",\"$.k124\",\"$.k125\",\"$.k126\",\"$.k127\",\"$.k128\",\"$.k129\",\"$.k130\",\"$.k131\",\"$.k132\",\"$.k133\",\"$.k134\",\"$.k135\",\"$.k136\",\"$.k137\",\"$.k138\",\"$.k139\",\"$.k140\",\"$.k141\",\"$.k142\",\"$.k143\",\"$.k144\",\"$.k145\",\"$.k146\",\"$.k147\",\"$.k148\",\"$.k149\"],\"snapshots\":\"**\"}],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -14,6 +14,7 @@ "structuredContent": { "settings": { "ci_mode": "strict", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project.json b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project.json index 557191ad..72435633 100644 --- a/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project.json +++ b/app/tests/golden/mcp/a_builds_visualci_yml_overrides_the_project_settings/update_project.json @@ -14,7 +14,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.project_rule\"],\"snapshots\":\"**\"}],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.project_rule\"],\"snapshots\":\"**\"}],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -22,6 +22,7 @@ "structuredContent": { "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami-2.json b/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami-2.json index c7600d59..d21f6ed3 100644 --- a/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami-2.json +++ b/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami-2.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"blocked\":null,\"kind\":\"project\",\"open_comment_threads\":[],\"project\":\"/pdfs\",\"waiting_for_review\":[]}", + "text": "{\"blocked\":null,\"kind\":\"project\",\"open_comment_threads\":[],\"project\":\"/pdfs\",\"via\":{\"source\":\"project_token\",\"token_name\":\"ci\"},\"waiting_for_review\":[]}", "type": "text" } ], @@ -13,6 +13,10 @@ "kind": "project", "open_comment_threads": [], "project": "/pdfs", + "via": { + "source": "project_token", + "token_name": "ci" + }, "waiting_for_review": [] } } diff --git a/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami.json b/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami.json index 0340a7ff..9062b2d1 100644 --- a/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami.json +++ b/app/tests/golden/mcp/a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why/whoami.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"blocked\":{\"billing_url\":\"https://app.visualci.test//billing\",\"credits_limit\":25000,\"credits_used\":25000,\"fixes\":[{\"action\":\"upgrade\",\"label\":\"Upgrade to Team\",\"url\":\"https://app.visualci.test//billing\"}],\"message\":\"Org is out of VisualCI credits until 1 January 2027: it has used all 25,000 credits on the Free plan, so builds aren't compared. An admin can upgrade to Team at https://app.visualci.test//billing\",\"pack_credits\":0,\"plan\":\"Free\",\"reason\":\"out_of_credits\",\"renews_at\":\"\"},\"kind\":\"project\",\"open_comment_threads\":[],\"project\":\"/pdfs\",\"waiting_for_review\":[]}", + "text": "{\"blocked\":{\"billing_url\":\"https://app.visualci.test//billing\",\"credits_limit\":25000,\"credits_used\":25000,\"fixes\":[{\"action\":\"upgrade\",\"label\":\"Upgrade to Team\",\"url\":\"https://app.visualci.test//billing\"}],\"message\":\"Org is out of VisualCI credits until 1 January 2027: it has used all 25,000 credits on the Free plan, so builds aren't compared. An admin can upgrade to Team at https://app.visualci.test//billing\",\"pack_credits\":0,\"plan\":\"Free\",\"reason\":\"out_of_credits\",\"renews_at\":\"\"},\"kind\":\"project\",\"open_comment_threads\":[],\"project\":\"/pdfs\",\"via\":{\"source\":\"project_token\",\"token_name\":\"ci\"},\"waiting_for_review\":[]}", "type": "text" } ], @@ -29,6 +29,10 @@ "kind": "project", "open_comment_threads": [], "project": "/pdfs", + "via": { + "source": "project_token", + "token_name": "ci" + }, "waiting_for_review": [] } } diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/create_project.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/create_project.json index bdd62ca9..df03619f 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/create_project.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/create_project.json @@ -7,7 +7,7 @@ "result": { "content": [ { - "text": "{\"project\":\"-b/docs\",\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"project\":\"-b/docs\",\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -16,6 +16,7 @@ "project": "-b/docs", "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_project.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_project.json index 5652ccc4..55a970ce 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_project.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_project.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"-b/docs\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.generated_at\"],\"snapshots\":\"api/**\",\"text_patterns\":[\"\\\\d{4}-\\\\d{2}-\\\\d{2}\"]}],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":3,\"last_used_at\":null,\"name\":\"CircleCI\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test/-b/docs\"}", + "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"-b/docs\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.generated_at\"],\"snapshots\":\"api/**\",\"text_patterns\":[\"\\\\d{4}-\\\\d{2}-\\\\d{2}\"]}],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":3,\"last_used_at\":null,\"name\":\"CircleCI\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test/-b/docs\"}", "type": "text" } ], @@ -20,6 +20,7 @@ "repository_seen_in_ci": null, "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 150, "forge": null, diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-4.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-4.json index aae6cbfa..63466abf 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-4.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-4.json @@ -17,7 +17,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.generated_at\"],\"snapshots\":\"api/**\",\"text_patterns\":[\"\\\\d{4}-\\\\d{2}-\\\\d{2}\"]}],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[{\"json_paths\":[\"$.generated_at\"],\"snapshots\":\"api/**\",\"text_patterns\":[\"\\\\d{4}-\\\\d{2}-\\\\d{2}\"]}],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -25,6 +25,7 @@ "structuredContent": { "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 150, "forge": null, diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-8.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-8.json index 9f352fdf..5335eac0 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-8.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project-8.json @@ -12,7 +12,7 @@ "result": { "content": [ { - "text": "failed to deserialize parameters: missing field `snapshots`\n\nupdate_project takes:\n- ci_mode (string): `review` (CI passes, the check waits for review), `strict` (CI fails on unreviewed changes) or `wait`.\n- default_branch (string): The branch whose builds become the baseline automatically.\n- dismiss_notice (boolean): `true` dismisses the project's notice.\n- dpi (integer): Render resolution for documents, 36 to 600.\n- forge_token (string): A project on your organization's own GitLab instance: an access token for it (a project or group access token with the `api` scope and the Developer role, or Maintainer to let VisualCI add its webhook), sent with `repository_url`. Stored encrypted; never shown again.\n- gallery_enabled (boolean): `false` takes the public gallery down (visualci.yml's `gallery` decides what's in it); `true` puts it back.\n- ignore_anti_aliasing (boolean): Ignore anti-aliasing differences in images.\n- ignore_rules (array): Values in text snapshots that change on every run, ignored when comparing. Replaces the project's rules. Each rule names the snapshots it applies to with a glob (`api/invoices/**`; `**` for every snapshot). A build's `visualci.yml` replaces these rules when it has `ignore`.\n- move_link (boolean): With `repository_url`: a repository belongs to one organization, so when another organization has it linked, `true` moves the link here (you must maintain the repository; that organization's admins get an email).\n- name (string): The project's display name.\n- project (string): `org/project`. Optional with a project token.\n- public (boolean): `true` lets anyone, signed in or not, read the project's builds and diffs (for open source projects); settings, tokens and reviewing stay with its members. Only a project linked to a public repository can be public. `false` makes it private again.\n- renderer (string): The PDF renderer: `pdfbox` or `mutool`.\n- repository_url (string): The repository this project tests, by URL (`https://github.com/acme/web`); an empty string unlinks it. Linking needs the forge's VisualCI app installed on the repository and you to be an admin or maintainer of it there. Its pull requests then get VisualCI's check, and people's access to this organization follows their permission on it.\n- slug (string): A new slug, renaming the project (`acme/old` → `acme/new`): lowercase letters, digits and dashes. Its builds, baselines and tokens stay. The old address and `acme/old` stop working.\n- threshold (number): The diff threshold, 0 to 1: 0 compares exactly; above 0 it's pixelmatch's colour threshold (how different a pixel's colour must be to count), and anti-aliased pixels are ignored.\n- tokens_can_approve (boolean): `false`: project tokens can't approve changes (people do); `true` lets CI's agents approve again.\nExample: {}", + "text": "failed to deserialize parameters: missing field `snapshots`\n\nupdate_project takes:\n- ci_mode (string): `review` (CI passes, the check waits for review), `strict` (CI fails on unreviewed changes) or `wait`.\n- comment_when_unchanged (boolean): `true`: comment on pull requests even when nothing changed. `false` (the default): a pull request whose builds are all unchanged gets no comment, only the passing check; a comment already there keeps being updated.\n- default_branch (string): The branch whose builds become the baseline automatically.\n- dismiss_notice (boolean): `true` dismisses the project's notice.\n- dpi (integer): Render resolution for documents, 36 to 600.\n- forge_token (string): A project on your organization's own GitLab instance: an access token for it (a project or group access token with the `api` scope and the Developer role, or Maintainer to let VisualCI add its webhook), sent with `repository_url`. Stored encrypted; never shown again.\n- gallery_enabled (boolean): `false` takes the public gallery down (visualci.yml's `gallery` decides what's in it); `true` puts it back.\n- ignore_anti_aliasing (boolean): Ignore anti-aliasing differences in images.\n- ignore_rules (array): Values in text snapshots that change on every run, ignored when comparing. Replaces the project's rules. Each rule names the snapshots it applies to with a glob (`api/invoices/**`; `**` for every snapshot). A build's `visualci.yml` replaces these rules when it has `ignore`.\n- move_link (boolean): With `repository_url`: a repository belongs to one organization, so when another organization has it linked, `true` moves the link here (you must maintain the repository; that organization's admins get an email).\n- name (string): The project's display name.\n- project (string): `org/project`. Optional with a project token.\n- public (boolean): `true` lets anyone, signed in or not, read the project's builds and diffs (for open source projects); settings, tokens and reviewing stay with its members. Only a project linked to a public repository can be public. `false` makes it private again.\n- renderer (string): The PDF renderer: `pdfbox` or `mutool`.\n- repository_url (string): The repository this project tests, by URL (`https://github.com/acme/web`); an empty string unlinks it. Linking needs the forge's VisualCI app installed on the repository and you to be an admin or maintainer of it there. Its pull requests then get VisualCI's check, and people's access to this organization follows their permission on it.\n- slug (string): A new slug, renaming the project (`acme/old` → `acme/new`): lowercase letters, digits and dashes. Its builds, baselines and tokens stay. The old address and `acme/old` stop working.\n- threshold (number): The diff threshold, 0 to 1: 0 compares exactly; above 0 it's pixelmatch's colour threshold (how different a pixel's colour must be to count), and anti-aliased pixels are ignored.\n- tokens_can_approve (boolean): `false`: project tokens can't approve changes (people do); `true` lets CI's agents approve again.\nExample: {}", "type": "text" } ], diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project.json index a37d3cef..6f5c94fb 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/update_project.json @@ -6,7 +6,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":150,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"Docs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"docs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -14,6 +14,7 @@ "structuredContent": { "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 150, "forge": null, diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json index 1896d6a6..f4429033 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"next\":\"install_github_app\",\"steps\":[{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"create_project\"},{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"waiting_for_review\":[]}", + "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"next\":\"install_github_app\",\"steps\":[{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"create_project\"},{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"via\":{\"source\":\"personal_token\",\"token_name\":\"agent\"},\"waiting_for_review\":[]}", "type": "text" } ], @@ -52,6 +52,10 @@ "slug": "" } ], + "via": { + "source": "personal_token", + "token_name": "agent" + }, "waiting_for_review": [] } } diff --git a/app/tests/golden/mcp/a_project_can_keep_approving_with_people/update_project.json b/app/tests/golden/mcp/a_project_can_keep_approving_with_people/update_project.json index 4cdd3c0b..b8e4c9ee 100644 --- a/app/tests/golden/mcp/a_project_can_keep_approving_with_people/update_project.json +++ b/app/tests/golden/mcp/a_project_can_keep_approving_with_people/update_project.json @@ -6,7 +6,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":false}}", + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":false}}", "type": "text" } ], @@ -14,6 +14,7 @@ "structuredContent": { "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/golden/mcp/agents_comment_on_snapshots_and_resolve_threads/whoami.json b/app/tests/golden/mcp/agents_comment_on_snapshots_and_resolve_threads/whoami.json index c873c983..d5508555 100644 --- a/app/tests/golden/mcp/agents_comment_on_snapshots_and_resolve_threads/whoami.json +++ b/app/tests/golden/mcp/agents_comment_on_snapshots_and_resolve_threads/whoami.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"blocked\":null,\"kind\":\"project\",\"open_comment_threads\":[{\"branch\":\"feat\",\"open\":1,\"project\":\"/pdfs\"}],\"project\":\"/pdfs\",\"waiting_for_review\":[]}", + "text": "{\"blocked\":null,\"kind\":\"project\",\"open_comment_threads\":[{\"branch\":\"feat\",\"open\":1,\"project\":\"/pdfs\"}],\"project\":\"/pdfs\",\"via\":{\"source\":\"project_token\",\"token_name\":\"ci\"},\"waiting_for_review\":[]}", "type": "text" } ], @@ -19,6 +19,10 @@ } ], "project": "/pdfs", + "via": { + "source": "project_token", + "token_name": "ci" + }, "waiting_for_review": [] } } diff --git a/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/get_project.json b/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/get_project.json new file mode 100644 index 00000000..fcfc5ff5 --- /dev/null +++ b/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/get_project.json @@ -0,0 +1,58 @@ +{ + "arguments": { + "project": "/pdfs" + }, + "result": { + "content": [ + { + "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"/pdfs\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":1,\"last_used_at\":null,\"name\":\"ci\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test//pdfs\"}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "gallery": { + "enabled": true, + "items": [], + "manifest_url": null + }, + "project": "/pdfs", + "repository_seen_in_ci": null, + "settings": { + "ci_mode": "review", + "comment_when_unchanged": false, + "default_branch": "main", + "dpi": 140, + "forge": null, + "forge_app_installed": false, + "forge_webhook_at": null, + "gallery_enabled": true, + "ignore_anti_aliasing": false, + "ignore_rules": [], + "name": "PDFs", + "notice": null, + "open_source": false, + "open_source_note": null, + "open_source_pool": false, + "open_source_withdrawn": false, + "public": false, + "renderer": "pdfbox", + "repository_public": false, + "repository_url": null, + "slug": "pdfs", + "threshold": 0.0, + "tokens_can_approve": true + }, + "tokens": [ + { + "created_at": "", + "id": 1, + "last_used_at": null, + "name": "ci", + "prefix": "" + } + ], + "url": "https://app.visualci.test//pdfs" + } + } +} diff --git a/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/update_project.json b/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/update_project.json new file mode 100644 index 00000000..989f0b76 --- /dev/null +++ b/app/tests/golden/mcp/comments_when_nothing_changed_are_off_until_turned_on/update_project.json @@ -0,0 +1,42 @@ +{ + "arguments": { + "comment_when_unchanged": true, + "project": "/pdfs" + }, + "result": { + "content": [ + { + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":true,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "settings": { + "ci_mode": "review", + "comment_when_unchanged": true, + "default_branch": "main", + "dpi": 140, + "forge": null, + "forge_app_installed": false, + "forge_webhook_at": null, + "gallery_enabled": true, + "ignore_anti_aliasing": false, + "ignore_rules": [], + "name": "PDFs", + "notice": null, + "open_source": false, + "open_source_note": null, + "open_source_pool": false, + "open_source_withdrawn": false, + "public": false, + "renderer": "pdfbox", + "repository_public": false, + "repository_url": null, + "slug": "pdfs", + "threshold": 0.0, + "tokens_can_approve": true + } + } + } +} diff --git a/app/tests/golden/mcp/create_organization_refuses_a_taken_slug/create_organization.json b/app/tests/golden/mcp/create_organization_refuses_a_taken_slug/create_organization.json new file mode 100644 index 00000000..7a89b6ef --- /dev/null +++ b/app/tests/golden/mcp/create_organization_refuses_a_taken_slug/create_organization.json @@ -0,0 +1,15 @@ +{ + "arguments": { + "name": "Again", + "slug": "" + }, + "result": { + "content": [ + { + "text": "the slug is taken", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/create_build.json b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/create_build.json new file mode 100644 index 00000000..560b7e67 --- /dev/null +++ b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/create_build.json @@ -0,0 +1,50 @@ +{ + "arguments": { + "branch": "main", + "commit": "abc" + }, + "result": { + "content": [ + { + "text": "{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":null,\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":null,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"none\",\"reviewable\":false,\"reviews\":[],\"state\":\"receiving\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "blocked": null, + "branch": "main", + "ci_mode": "review", + "commit": "abc", + "conclusion": null, + "created_at": "", + "environment": "ci", + "environment_info": {}, + "error": null, + "id": "", + "mode": "ci", + "name": "default", + "number": 1, + "passed": null, + "pr_number": null, + "project": "/pdfs", + "review_state": "none", + "reviewable": false, + "reviews": [], + "state": "receiving", + "stats": { + "added": 0, + "changed": 0, + "config": 0, + "failed": 0, + "ignored": 0, + "pending": 0, + "removed": 0, + "total": 0, + "unchanged": 0 + }, + "url": "https://app.visualci.test//pdfs/builds/1", + "warnings": [] + } + } +} diff --git a/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-2.json b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-2.json new file mode 100644 index 00000000..c7ade30a --- /dev/null +++ b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-2.json @@ -0,0 +1,15 @@ +{ + "arguments": { + "build": "1", + "state": "new" + }, + "result": { + "content": [ + { + "text": "state must be one of changed, added, removed, unchanged, all", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-3.json b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-3.json new file mode 100644 index 00000000..516dc496 --- /dev/null +++ b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build-3.json @@ -0,0 +1,14 @@ +{ + "arguments": { + "build": "9" + }, + "result": { + "content": [ + { + "text": "no build 9 in this project", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build.json b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build.json new file mode 100644 index 00000000..9004efdb --- /dev/null +++ b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/download_build.json @@ -0,0 +1,38 @@ +{ + "arguments": { + "build": "1", + "state": "all" + }, + "result": { + "content": [ + { + "text": "{\"bytes\":191,\"error\":null,\"files\":1,\"filter\":{\"glob\":null,\"sides\":[\"base\",\"head\",\"diff\"],\"state\":\"all\"},\"id\":\"\",\"state\":\"ready\",\"summary\":{\"build\":1,\"by_state\":{},\"names\":[],\"snapshots\":0},\"url\":\"http://127.0.0.1:59000/visualci-test/downloads/.tar.zst?\"}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "bytes": 191, + "error": null, + "files": 1, + "filter": { + "glob": null, + "sides": [ + "base", + "head", + "diff" + ], + "state": "all" + }, + "id": "", + "state": "ready", + "summary": { + "build": 1, + "by_state": {}, + "names": [], + "snapshots": 0 + }, + "url": "http://127.0.0.1:59000/visualci-test/downloads/.tar.zst?" + } + } +} diff --git a/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/finalize_build.json b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/finalize_build.json new file mode 100644 index 00000000..0517d2ba --- /dev/null +++ b/app/tests/golden/mcp/download_build_builds_an_archive_and_says_its_state/finalize_build.json @@ -0,0 +1,50 @@ +{ + "arguments": { + "allow_empty": true, + "build": "1" + }, + "result": { + "content": [ + { + "text": "{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":null,\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":null,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"none\",\"reviewable\":false,\"reviews\":[],\"state\":\"processing\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "blocked": null, + "branch": "main", + "ci_mode": "review", + "commit": "abc", + "conclusion": null, + "created_at": "", + "environment": "ci", + "environment_info": {}, + "error": null, + "id": "", + "mode": "ci", + "name": "default", + "number": 1, + "passed": null, + "pr_number": null, + "project": "/pdfs", + "review_state": "none", + "reviewable": false, + "reviews": [], + "state": "processing", + "stats": { + "added": 0, + "changed": 0, + "config": 0, + "failed": 0, + "ignored": 0, + "pending": 0, + "removed": 0, + "total": 0, + "unchanged": 0 + }, + "url": "https://app.visualci.test//pdfs/builds/1", + "warnings": [] + } + } +} diff --git a/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-2.json b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-2.json new file mode 100644 index 00000000..cb9b4fb6 --- /dev/null +++ b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-2.json @@ -0,0 +1,16 @@ +{ + "arguments": { + "invitee": "ada@example.com", + "org": "", + "role": "member" + }, + "result": { + "content": [ + { + "text": "only an organization's admins can invite people; you're member", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-3.json b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-3.json new file mode 100644 index 00000000..8821c157 --- /dev/null +++ b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-3.json @@ -0,0 +1,53 @@ +{ + "arguments": { + "invitee": "ada@example.com", + "org": "", + "role": "member" + }, + "result": { + "content": [ + { + "text": "{\"invitation\":{\"created_at\":\"\",\"email\":\"ada@example.com\",\"forge\":null,\"id\":\"\",\"invitee\":\"ada@example.com\",\"login\":null,\"role\":\"member\"},\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null},{\"avatar_url\":null,\"email\":\"member@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"member\",\"role\":\"member\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "invitation": { + "created_at": "", + "email": "ada@example.com", + "forge": null, + "id": "", + "invitee": "ada@example.com", + "login": null, + "role": "member" + }, + "members": [ + { + "avatar_url": null, + "email": "@example.com", + "id": "", + "identities": [], + "login": null, + "name": "owner", + "role": "admin", + "since": "", + "source": "created", + "synced_at": null + }, + { + "avatar_url": null, + "email": "member@example.com", + "id": "", + "identities": [], + "login": null, + "name": "member", + "role": "member", + "since": "", + "source": "created", + "synced_at": null + } + ] + } + } +} diff --git a/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-4.json b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-4.json new file mode 100644 index 00000000..8821c157 --- /dev/null +++ b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-4.json @@ -0,0 +1,53 @@ +{ + "arguments": { + "invitee": "ada@example.com", + "org": "", + "role": "member" + }, + "result": { + "content": [ + { + "text": "{\"invitation\":{\"created_at\":\"\",\"email\":\"ada@example.com\",\"forge\":null,\"id\":\"\",\"invitee\":\"ada@example.com\",\"login\":null,\"role\":\"member\"},\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null},{\"avatar_url\":null,\"email\":\"member@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"member\",\"role\":\"member\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "invitation": { + "created_at": "", + "email": "ada@example.com", + "forge": null, + "id": "", + "invitee": "ada@example.com", + "login": null, + "role": "member" + }, + "members": [ + { + "avatar_url": null, + "email": "@example.com", + "id": "", + "identities": [], + "login": null, + "name": "owner", + "role": "admin", + "since": "", + "source": "created", + "synced_at": null + }, + { + "avatar_url": null, + "email": "member@example.com", + "id": "", + "identities": [], + "login": null, + "name": "member", + "role": "member", + "since": "", + "source": "created", + "synced_at": null + } + ] + } + } +} diff --git a/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-5.json b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-5.json new file mode 100644 index 00000000..95b1e5b7 --- /dev/null +++ b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member-5.json @@ -0,0 +1,16 @@ +{ + "arguments": { + "invitee": "bea@example.com", + "org": "", + "role": "read" + }, + "result": { + "content": [ + { + "text": "that person has been invited too often in the last 24 hours; try again tomorrow", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member.json b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member.json new file mode 100644 index 00000000..4175f72c --- /dev/null +++ b/app/tests/golden/mcp/invite_member_checks_who_may_invite_and_its_limits/invite_member.json @@ -0,0 +1,16 @@ +{ + "arguments": { + "invitee": "ada@example.com", + "org": "", + "role": "member" + }, + "result": { + "content": [ + { + "text": "invitations need a personal access token", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build-2.json b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build-2.json new file mode 100644 index 00000000..b6ae254d --- /dev/null +++ b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build-2.json @@ -0,0 +1,52 @@ +{ + "arguments": { + "branch": "feat", + "commit": "b2c3d4e5f6", + "name": "docs", + "pr_number": 7 + }, + "result": { + "content": [ + { + "text": "{\"blocked\":null,\"branch\":\"feat\",\"ci_mode\":\"review\",\"commit\":\"b2c3d4e5f6\",\"conclusion\":null,\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"docs\",\"number\":2,\"passed\":null,\"pr_number\":7,\"project\":\"/pdfs\",\"review_state\":\"none\",\"reviewable\":false,\"reviews\":[],\"state\":\"receiving\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/2\",\"warnings\":[]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "blocked": null, + "branch": "feat", + "ci_mode": "review", + "commit": "b2c3d4e5f6", + "conclusion": null, + "created_at": "", + "environment": "ci", + "environment_info": {}, + "error": null, + "id": "", + "mode": "ci", + "name": "docs", + "number": 2, + "passed": null, + "pr_number": 7, + "project": "/pdfs", + "review_state": "none", + "reviewable": false, + "reviews": [], + "state": "receiving", + "stats": { + "added": 0, + "changed": 0, + "config": 0, + "failed": 0, + "ignored": 0, + "pending": 0, + "removed": 0, + "total": 0, + "unchanged": 0 + }, + "url": "https://app.visualci.test//pdfs/builds/2", + "warnings": [] + } + } +} diff --git a/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build.json b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build.json new file mode 100644 index 00000000..65fc0877 --- /dev/null +++ b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/create_build.json @@ -0,0 +1,50 @@ +{ + "arguments": { + "branch": "main", + "commit": "a1b2c3d4e5f60718293a" + }, + "result": { + "content": [ + { + "text": "{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"a1b2c3d4e5f60718293a\",\"conclusion\":null,\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":null,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"none\",\"reviewable\":false,\"reviews\":[],\"state\":\"receiving\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "blocked": null, + "branch": "main", + "ci_mode": "review", + "commit": "a1b2c3d4e5f60718293a", + "conclusion": null, + "created_at": "", + "environment": "ci", + "environment_info": {}, + "error": null, + "id": "", + "mode": "ci", + "name": "default", + "number": 1, + "passed": null, + "pr_number": null, + "project": "/pdfs", + "review_state": "none", + "reviewable": false, + "reviews": [], + "state": "receiving", + "stats": { + "added": 0, + "changed": 0, + "config": 0, + "failed": 0, + "ignored": 0, + "pending": 0, + "removed": 0, + "total": 0, + "unchanged": 0 + }, + "url": "https://app.visualci.test//pdfs/builds/1", + "warnings": [] + } + } +} diff --git a/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/finalize_build.json b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/finalize_build.json new file mode 100644 index 00000000..75843c41 --- /dev/null +++ b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/finalize_build.json @@ -0,0 +1,50 @@ +{ + "arguments": { + "allow_empty": true, + "build": "1" + }, + "result": { + "content": [ + { + "text": "{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"a1b2c3d4e5f60718293a\",\"conclusion\":null,\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":null,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"none\",\"reviewable\":false,\"reviews\":[],\"state\":\"processing\",\"stats\":{\"added\":0,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "blocked": null, + "branch": "main", + "ci_mode": "review", + "commit": "a1b2c3d4e5f60718293a", + "conclusion": null, + "created_at": "", + "environment": "ci", + "environment_info": {}, + "error": null, + "id": "", + "mode": "ci", + "name": "default", + "number": 1, + "passed": null, + "pr_number": null, + "project": "/pdfs", + "review_state": "none", + "reviewable": false, + "reviews": [], + "state": "processing", + "stats": { + "added": 0, + "changed": 0, + "config": 0, + "failed": 0, + "ignored": 0, + "pending": 0, + "removed": 0, + "total": 0, + "unchanged": 0 + }, + "url": "https://app.visualci.test//pdfs/builds/1", + "warnings": [] + } + } +} diff --git a/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/list_builds.json b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/list_builds.json new file mode 100644 index 00000000..dab2ae61 --- /dev/null +++ b/app/tests/golden/mcp/list_builds_answers_one_short_line_per_build/list_builds.json @@ -0,0 +1,59 @@ +{ + "arguments": {}, + "result": { + "content": [ + { + "text": "{\"builds\":[{\"blocked\":null,\"branch\":\"feat\",\"changes\":\"not compared\",\"commit\":\"b2c3d4e5f6\",\"conclusion\":null,\"created_at\":\"\",\"name\":\"docs\",\"number\":2,\"pr_number\":7,\"review_state\":\"none\",\"state\":\"receiving\",\"stats\":{\"added\":0,\"changed\":0,\"failed\":0,\"removed\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/2\",\"waiting_for_review\":false},{\"blocked\":null,\"branch\":\"main\",\"changes\":\"unchanged\",\"commit\":\"a1b2c3d4e5f60718293a\",\"conclusion\":\"unchanged\",\"created_at\":\"\",\"number\":1,\"pr_number\":null,\"review_state\":\"auto_approved\",\"state\":\"completed\",\"stats\":{\"added\":0,\"changed\":0,\"failed\":0,\"removed\":0,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"waiting_for_review\":false}]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "builds": [ + { + "blocked": null, + "branch": "feat", + "changes": "not compared", + "commit": "b2c3d4e5f6", + "conclusion": null, + "created_at": "", + "name": "docs", + "number": 2, + "pr_number": 7, + "review_state": "none", + "state": "receiving", + "stats": { + "added": 0, + "changed": 0, + "failed": 0, + "removed": 0, + "unchanged": 0 + }, + "url": "https://app.visualci.test//pdfs/builds/2", + "waiting_for_review": false + }, + { + "blocked": null, + "branch": "main", + "changes": "unchanged", + "commit": "a1b2c3d4e5f60718293a", + "conclusion": "unchanged", + "created_at": "", + "number": 1, + "pr_number": null, + "review_state": "auto_approved", + "state": "completed", + "stats": { + "added": 0, + "changed": 0, + "failed": 0, + "removed": 0, + "unchanged": 0 + }, + "url": "https://app.visualci.test//pdfs/builds/1", + "waiting_for_review": false + } + ] + } + } +} diff --git a/app/tests/golden/mcp/list_organizations_lists_a_persons_organizations/list_organizations.json b/app/tests/golden/mcp/list_organizations_lists_a_persons_organizations/list_organizations.json new file mode 100644 index 00000000..7e9b5af2 --- /dev/null +++ b/app/tests/golden/mcp/list_organizations_lists_a_persons_organizations/list_organizations.json @@ -0,0 +1,61 @@ +{ + "arguments": {}, + "result": { + "content": [ + { + "text": "{\"organizations\":[{\"name\":\"Org\",\"projects\":[\"pdfs\",\"shots\"],\"role\":\"admin\",\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false}}]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "organizations": [ + { + "name": "Org", + "projects": [ + "pdfs", + "shots" + ], + "role": "admin", + "slug": "", + "usage": { + "auto_reload_packs": 4, + "billing_problem": null, + "credit_pack": { + "credits": 500000, + "price_cents": 1500, + "reload_below": 100000 + }, + "credits_this_month": 0, + "included_credits": 25000, + "open_source": { + "pool": 1000000, + "projects": 0, + "used": 0 + }, + "out_of_credits": false, + "pack_credits": 0, + "plan": { + "credit_packs": false, + "id": "free", + "included_credits": 25000, + "name": "Free", + "price_cents": 0, + "unlimited": false + }, + "rates": { + "image_diff": 10, + "rendered_page": 20, + "snapshot_check": 1, + "text_diff": 5 + }, + "reloads_paused": false, + "reloads_this_month": 0, + "renews_at": "", + "unlimited": false + } + } + ] + } + } +} diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json index ac56be47..2569b463 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json @@ -332,6 +332,72 @@ }, "name": "delete_project_token" }, + { + "annotations": { + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": true, + "title": "Download a build's images" + }, + "description": "Download a build's images as one tar.zst, for a close look at a big build or for checks of your own: a URL (it lasts an hour) and a summary, never the images themselves. Filter by `state` (changed by default, added, removed, unchanged, all), `sides` (base, head, diff, regions: the head cropped to the changes) and a `glob` on snapshot names. The archive has `[@platform][/page-N]/{base,head,diff,regions}.png` and `manifest.json` (each snapshot's state, pages, changed fraction, regions and files). It's built in the background: when `state` is `building`, call again with the same arguments. Free.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "build": { + "type": [ + "integer", + "string" + ] + }, + "glob": { + "description": "Only snapshots whose name matches this glob, like `v2/pdfjs/**`.", + "type": [ + "string", + "null" + ] + }, + "project": { + "description": "`org/project`. Optional with a project token.", + "type": [ + "string", + "null" + ] + }, + "sides": { + "description": "Which images of each page: `base`, `head`, `diff`, `regions` (the head cropped to the changes). Default: base,\nhead and diff.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "state": { + "description": "Which snapshots: `changed` (the default), `added`, `removed`, `unchanged`, or `all`.", + "type": [ + "string", + "null" + ] + }, + "wait": { + "description": "Seconds to wait for the archive (default 50, at most 60). Not ready by then: call again with the same arguments.", + "format": "uint64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "build" + ], + "type": "object" + }, + "name": "download_build" + }, { "annotations": { "destructiveHint": false, @@ -703,7 +769,7 @@ "readOnlyHint": true, "title": "List builds" }, - "description": "List a project's builds, newest first: number, name, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, counts and URL. waiting_for_review: only builds whose changes wait for a review.", + "description": "List a project's builds, newest first, one short line each: number, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, whether it waits for your review, its changes in a few words (`2 changed, 1 added`) and as numbers (`stats`), `blocked` when it's out of credits, and URL. get_build has the details (its snapshots, environment, reviews, groups, CI mode and warnings). waiting_for_review: only builds whose changes wait for a review.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, @@ -1297,6 +1363,13 @@ "null" ] }, + "comment_when_unchanged": { + "description": "`true`: comment on pull requests even when nothing changed. `false` (the default): a pull request whose builds\nare all unchanged gets no comment, only the passing check; a comment already there keeps being updated.", + "type": [ + "boolean", + "null" + ] + }, "default_branch": { "description": "The branch whose builds become the baseline automatically.", "type": [ @@ -1567,7 +1640,7 @@ "readOnlyHint": true, "title": "Who am I" }, - "description": "Who this token belongs to (a person or a project), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", + "description": "Who this token belongs to (a person or a project), how it reached VisualCI (`via`: `source` as reviews record it, `personal_token`, `project_token`, `oauth` or `web`, with the token's or the MCP client's name), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json index ac56be47..2569b463 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json @@ -332,6 +332,72 @@ }, "name": "delete_project_token" }, + { + "annotations": { + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": true, + "title": "Download a build's images" + }, + "description": "Download a build's images as one tar.zst, for a close look at a big build or for checks of your own: a URL (it lasts an hour) and a summary, never the images themselves. Filter by `state` (changed by default, added, removed, unchanged, all), `sides` (base, head, diff, regions: the head cropped to the changes) and a `glob` on snapshot names. The archive has `[@platform][/page-N]/{base,head,diff,regions}.png` and `manifest.json` (each snapshot's state, pages, changed fraction, regions and files). It's built in the background: when `state` is `building`, call again with the same arguments. Free.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "build": { + "type": [ + "integer", + "string" + ] + }, + "glob": { + "description": "Only snapshots whose name matches this glob, like `v2/pdfjs/**`.", + "type": [ + "string", + "null" + ] + }, + "project": { + "description": "`org/project`. Optional with a project token.", + "type": [ + "string", + "null" + ] + }, + "sides": { + "description": "Which images of each page: `base`, `head`, `diff`, `regions` (the head cropped to the changes). Default: base,\nhead and diff.", + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "state": { + "description": "Which snapshots: `changed` (the default), `added`, `removed`, `unchanged`, or `all`.", + "type": [ + "string", + "null" + ] + }, + "wait": { + "description": "Seconds to wait for the archive (default 50, at most 60). Not ready by then: call again with the same arguments.", + "format": "uint64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "build" + ], + "type": "object" + }, + "name": "download_build" + }, { "annotations": { "destructiveHint": false, @@ -703,7 +769,7 @@ "readOnlyHint": true, "title": "List builds" }, - "description": "List a project's builds, newest first: number, name, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, counts and URL. waiting_for_review: only builds whose changes wait for a review.", + "description": "List a project's builds, newest first, one short line each: number, branch, commit, PR, state, conclusion (unchanged, changes or failed), review state, whether it waits for your review, its changes in a few words (`2 changed, 1 added`) and as numbers (`stats`), `blocked` when it's out of credits, and URL. get_build has the details (its snapshots, environment, reviews, groups, CI mode and warnings). waiting_for_review: only builds whose changes wait for a review.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, @@ -1297,6 +1363,13 @@ "null" ] }, + "comment_when_unchanged": { + "description": "`true`: comment on pull requests even when nothing changed. `false` (the default): a pull request whose builds\nare all unchanged gets no comment, only the passing check; a comment already there keeps being updated.", + "type": [ + "boolean", + "null" + ] + }, "default_branch": { "description": "The branch whose builds become the baseline automatically.", "type": [ @@ -1567,7 +1640,7 @@ "readOnlyHint": true, "title": "Who am I" }, - "description": "Who this token belongs to (a person or a project), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", + "description": "Who this token belongs to (a person or a project), how it reached VisualCI (`via`: `source` as reviews record it, `personal_token`, `project_token`, `oauth` or `web`, with the token's or the MCP client's name), the organizations and projects it can reach with each organization's setup checklist (`setup`: steps done and the next one), and the newest builds whose changes wait for a review (`waiting_for_review`, at most 10). With no builds yet, `demo` names the public demo project to look at first.", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, diff --git a/app/tests/golden/mcp/projects_can_be_renamed/get_project-2.json b/app/tests/golden/mcp/projects_can_be_renamed/get_project-2.json index dd8e7baf..3e7bbea9 100644 --- a/app/tests/golden/mcp/projects_can_be_renamed/get_project-2.json +++ b/app/tests/golden/mcp/projects_can_be_renamed/get_project-2.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"/monorepo\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"monorepo\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":1,\"last_used_at\":null,\"name\":\"ci\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test//monorepo\"}", + "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"/monorepo\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"monorepo\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":1,\"last_used_at\":null,\"name\":\"ci\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test//monorepo\"}", "type": "text" } ], @@ -20,6 +20,7 @@ "repository_seen_in_ci": null, "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/golden/mcp/projects_can_be_renamed/update_project.json b/app/tests/golden/mcp/projects_can_be_renamed/update_project.json index dc46ee3a..5edb2b80 100644 --- a/app/tests/golden/mcp/projects_can_be_renamed/update_project.json +++ b/app/tests/golden/mcp/projects_can_be_renamed/update_project.json @@ -6,7 +6,7 @@ "result": { "content": [ { - "text": "{\"settings\":{\"ci_mode\":\"review\",\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"monorepo\",\"threshold\":0.0,\"tokens_can_approve\":true}}", + "text": "{\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"monorepo\",\"threshold\":0.0,\"tokens_can_approve\":true}}", "type": "text" } ], @@ -14,6 +14,7 @@ "structuredContent": { "settings": { "ci_mode": "review", + "comment_when_unchanged": false, "default_branch": "main", "dpi": 140, "forge": null, diff --git a/app/tests/golden/mod.rs b/app/tests/golden/mod.rs index faa68750..2dafa973 100644 --- a/app/tests/golden/mod.rs +++ b/app/tests/golden/mod.rs @@ -7,7 +7,8 @@ use std::sync::LazyLock; use regex::Regex; -/// Assert that `value` matches the golden file `tests/golden///.json`. +/// Assert that `value` matches the golden file `tests/golden///.json`. With +/// `VISUALCI_GOLDEN_UPDATE=1`, write it instead (an answer changed on purpose; review the diff). /// /// # Panics /// When it doesn't, showing both. @@ -17,6 +18,13 @@ pub fn check(kind: &str, test: &str, name: &str, value: &serde_json::Value) { .join(kind) .join(test) .join(format!("{name}.json")); + // A deliberate change to an answer: `VISUALCI_GOLDEN_UPDATE=1` writes the new answer, to review in the diff. + if std::env::var("VISUALCI_GOLDEN_UPDATE").is_ok_and(|v| v == "1") { + std::fs::create_dir_all(path.parent().expect("a golden file's directory")).expect("making the directory"); + let text = serde_json::to_string_pretty(&normalize(value)).expect("JSON") + "\n"; + std::fs::write(&path, text).unwrap_or_else(|e| panic!("writing {}: {e}", path.display())); + return; + } let golden: serde_json::Value = serde_json::from_str( &std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display())), ) diff --git a/app/tests/groups.rs b/app/tests/groups.rs new file mode 100644 index 00000000..14897237 --- /dev/null +++ b/app/tests/groups.rs @@ -0,0 +1,38 @@ +//! A build reads a group only from an earlier build of its own project (`groups::holders`). Retention and the demo +//! reset delete one project's builds and group rows together, which is safe only because no other project reads them. + +use std::collections::BTreeMap; + +use app::domain::build_settings::BuildSettings; +use app::domain::builds::{self, CreateParams}; +use app::domain::groups::{self, Candidate}; +use app::domain::snapshots::{self, SnapshotParams}; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn a_group_is_read_only_from_a_build_of_its_own_project(_app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let mine = fixtures::project(&org, "docs").await?; + let theirs = fixtures::project(&org, "other").await?; + let params: CreateParams = + serde_json::from_value(serde_json::json!({ "commit": "a".repeat(40), "branch": "main" }))?; + let holder = builds::create(&mine, ¶ms, None).await.map_err(|e| laravel::Error::msg(format!("{e:?}")))?; + let snapshot: SnapshotParams = serde_json::from_value(serde_json::json!({ + "name": "suite/home", "kind": "text", "fingerprint": "c".repeat(64), "sha256": "d".repeat(64), "size": 2, + "content_type": "text/plain", + }))?; + let settings = BuildSettings::new(&mine, &holder); + let row = snapshots::register(&holder, &settings, "1", &snapshot).await?.expect("registered").snapshot; + let id = row.id; + db::query!("UPDATE snapshots SET state = 'unchanged' WHERE id = {id}").update().await?; + + let candidates: BTreeMap = + [(row.group_key.clone(), Candidate { base_ids: vec![row.id], hash: "h".into() })].into_iter().collect(); + let found = groups::holders(mine.id, &candidates).await?; + assert_eq!(found.get(&row.group_key), Some(&holder.id), "its own project's build holds it"); + let found = groups::holders(theirs.id, &candidates).await?; + assert!(found.is_empty(), "another project's build never holds a group: {found:?}"); + Ok(()) +} diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index 4787f8c1..20311864 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -43,6 +43,8 @@ fn in_production() -> laravel::foundation::ApplicationBuilder { ("S3_BUCKET", "visualci-test"), ("S3_ACCESS_KEY_ID", "visualci"), ("S3_SECRET_ACCESS_KEY", "visualci-dev-secret"), + ("RENDERER_TOKEN", "renderer-test-token"), + ("RENDERER_VERSION", "1"), ]) } diff --git a/app/tests/invitations.rs b/app/tests/invitations.rs new file mode 100644 index 00000000..8320270d --- /dev/null +++ b/app/tests/invitations.rs @@ -0,0 +1,265 @@ +//! Invitations wait for their invitee to accept; only admins invite and manage members; an organization keeps an +//! admin; the forge's memberships stay the forge's; invitation emails are limited per day. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +async fn person(name: &str, email: &str) -> laravel::Result { + let user = create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: false }).await?; + let id = user.id; + db::query!("UPDATE users SET email_verified_at = now() WHERE id = {id}").update().await?; + User::find_or_fail(id).await +} + +async fn org(slug: &str) -> laravel::Result { + Ok(db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap()) +} + +async fn join(org: i64, user: &User, role: &str, source: &str) -> laravel::Result<()> { + let id = user.id; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {id}, {role}, {source}, now(), now())" + ) + .insert() + .await?; + Ok(()) +} + +async fn role_of(org: i64, user: &User) -> laravel::Result> { + let id = user.id; + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {id}").scalar().await +} + +#[laravel::test] +async fn an_invitation_waits_for_its_invitee_to_accept(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + let ada = person("Ada", "ada@example.com").await?; + join(acme, &admin, "admin", "created").await?; + + let sent = app + .post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "Ada@Example.com", "role": "member" })) + .await; + sent.assert_ok().assert_json_path("invitee", "ada@example.com").assert_json_path("role", "member"); + let id = sent.json()["id"].as_str().unwrap().to_string(); + assert_eq!(role_of(acme, &ada).await?, None, "nobody joins without saying so"); + let emails: Option = + db::query!("SELECT count(*) FROM emails WHERE kind = 'invited' AND recipient = 'ada@example.com'") + .scalar() + .await?; + assert_eq!(emails, Some(1)); + + app.get("/api/ui/orgs/acme/members") + .acting_as(&admin) + .await + .assert_ok() + .assert_json_path("invitations.0.id", id.as_str()); + app.get("/api/ui/invitations") + .acting_as(&ada) + .await + .assert_ok() + .assert_json_path("invitations.0.organization.slug", "acme") + .assert_json_path("invitations.0.invited_by", "Grace"); + + // Someone else can't take it. + let eve = person("Eve", "eve@example.com").await?; + app.post(format!("/api/ui/invitations/{id}/accept")) + .acting_as(&eve) + .header("sec-fetch-site", "same-origin") + .await + .assert_status(404); + + app.post(format!("/api/ui/invitations/{id}/accept")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok() + .assert_json_path("slug", "acme"); + assert_eq!(role_of(acme, &ada).await?.as_deref(), Some("member")); + let added: Option = + db::query!("SELECT count(*) FROM emails WHERE kind = 'added_to_org' AND recipient = 'ada@example.com'") + .scalar() + .await?; + assert_eq!(added, Some(1), "she's told she joined"); + // A second click finds nothing to accept. + app.post(format!("/api/ui/invitations/{id}/accept")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .await + .assert_status(404); + app.get("/api/ui/invitations").acting_as(&ada).await.assert_json_path("invitations", json!([])); + let members = app.get("/api/ui/orgs/acme/members").acting_as(&ada).await; + members.assert_ok().assert_json_path("members.0.name", "Grace").assert_json_path("members.1.name", "Ada"); + assert!(members.json()["members"][0]["email"].is_null(), "a member doesn't see emails"); + Ok(()) +} + +#[laravel::test] +async fn only_admins_invite_and_an_invitation_never_lowers_a_role(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + let member = person("Ada", "ada@example.com").await?; + let outsider = person("Eve", "eve@example.com").await?; + join(acme, &admin, "admin", "created").await?; + join(acme, &member, "member", "github").await?; + for (who, status) in [(&member, 403), (&outsider, 404)] { + app.post("/api/ui/orgs/acme/invitations") + .acting_as(who) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "someone@example.com", "role": "admin" })) + .await + .assert_status(status); + } + + // By GitHub login, for someone who has signed in with it: it's recorded for their account. + let ada_id = member.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1', 'ada-l', now(), now())" + ) + .insert() + .await?; + let sent = app + .post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "@Ada-L", "role": "read" })) + .await; + sent.assert_ok().assert_json_path("invitee", "@Ada-L (GitHub)"); + let id = sent.json()["id"].as_str().unwrap().to_string(); + app.post(format!("/api/ui/invitations/{id}/accept")) + .acting_as(&member) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok(); + assert_eq!(role_of(acme, &member).await?.as_deref(), Some("member")); + + // Declining withdraws it. + let again = app + .post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "eve@example.com", "role": "member" })) + .await; + let id = again.json()["id"].as_str().unwrap().to_string(); + app.post(format!("/api/ui/invitations/{id}/decline")) + .acting_as(&outsider) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok(); + app.get("/api/ui/orgs/acme/members").acting_as(&admin).await.assert_json_path("invitations", json!([])); + Ok(()) +} + +#[laravel::test] +async fn admins_manage_members_and_the_organization_keeps_an_admin(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + let ada = person("Ada", "ada@example.com").await?; + let forge = person("Linus", "linus@example.com").await?; + join(acme, &admin, "admin", "created").await?; + join(acme, &ada, "member", "invite").await?; + join(acme, &forge, "member", "github").await?; + + app.patch(format!("/api/ui/orgs/acme/members/{}", admin.pid)) + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "role": "member" })) + .await + .assert_status(422); + app.patch(format!("/api/ui/orgs/acme/members/{}", forge.pid)) + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "role": "read" })) + .await + .assert_status(422); + app.patch(format!("/api/ui/orgs/acme/members/{}", ada.pid)) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "role": "admin" })) + .await + .assert_status(403); + app.patch(format!("/api/ui/orgs/acme/members/{}", ada.pid)) + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "role": "admin" })) + .await + .assert_ok(); + assert_eq!(role_of(acme, &ada).await?.as_deref(), Some("admin")); + + // With another admin now, Grace can leave; then Ada is the last admin and can't. + app.delete(format!("/api/ui/orgs/acme/members/{}", admin.pid)) + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok(); + assert_eq!(role_of(acme, &admin).await?, None); + app.delete(format!("/api/ui/orgs/acme/members/{}", ada.pid)) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .await + .assert_status(422); + let told: Option = + db::query!("SELECT count(*) FROM emails WHERE recipient = 'grace@example.com'").scalar().await?; + assert_eq!(told, Some(0), "someone removing themselves isn't emailed"); + Ok(()) +} + +#[laravel::test] +async fn invitation_emails_are_limited_per_recipient(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + join(acme, &admin, "admin", "created").await?; + for n in 0..3 { + let key = format!("old:{n}"); + db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data) VALUES ('invited', {key}, 'ada@example.com', '[]')" + ) + .insert() + .await?; + } + app.post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "ada@example.com", "role": "member" })) + .await + .assert_status(429); + app.post("/api/ui/orgs/acme/invitations") + .acting_as(&admin) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "not an address", "role": "member" })) + .await + .assert_status(422); + Ok(()) +} + +#[laravel::test] +async fn staff_are_no_admins_of_organizations_they_are_not_in(app: Application) -> laravel::Result<()> { + let acme = org("acme").await?; + let admin = person("Grace", "grace@example.com").await?; + join(acme, &admin, "admin", "created").await?; + let staff = person("Sam", "sam@example.com").await?; + let staff_id = staff.id; + db::query!("UPDATE users SET staff = true WHERE id = {staff_id}").update().await?; + let staff = User::find_or_fail(staff_id).await?; + app.get("/api/ui/orgs/acme/members").acting_as(&staff).await.assert_status(404); + app.post("/api/ui/orgs/acme/invitations") + .acting_as(&staff) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "eve@example.com", "role": "admin" })) + .await + .assert_status(404); + Ok(()) +} diff --git a/app/tests/live.rs b/app/tests/live.rs new file mode 100644 index 00000000..594e5e06 --- /dev/null +++ b/app/tests/live.rs @@ -0,0 +1,32 @@ +//! Live updates: a topic notified from any connection reaches every subscriber in this process, and only once it's +//! committed. Run against the database itself, outside a test's rolled-back transaction, where NOTIFY never arrives. + +use std::time::Duration; + +use sqlx::Connection; + +/// The test server's `postgres` database: LISTEN and NOTIFY only need both sides on one database, and the tests' own +/// databases are per-test copies. +fn database() -> String { + let url = std::env::var("VISUALCI_APP_TEST_DATABASE_URL") + .unwrap_or_else(|_| "postgres://loco:loco@127.0.0.1:55433/visualci_app_test".to_string()); + let server = url.rsplit_once('/').map_or(url.as_str(), |(server, _)| server); + format!("{server}/postgres") +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_committed_notification_reaches_subscribers() { + let url = database(); + let mut rx = app::live::subscribe(&url); + assert!(app::live::ready(&url, Duration::from_secs(10)).await, "the listener LISTENs"); + // Connecting tells subscribers to re-read everything, since anything sent before is gone + assert!(app::live::arrives(&mut rx, app::live::EVERYTHING, Duration::from_secs(5)).await); + let mut other = sqlx::PgConnection::connect(&url).await.expect("the test database"); + + // Inside a transaction: nothing until it commits + let mut tx = other.begin().await.unwrap(); + sqlx::query("SELECT pg_notify($1, 'build:42')").bind(app::live::CHANNEL).execute(&mut *tx).await.unwrap(); + assert!(!app::live::arrives(&mut rx, "build:42", Duration::from_millis(300)).await, "not before the commit"); + tx.commit().await.unwrap(); + assert!(app::live::arrives(&mut rx, "build:42", Duration::from_secs(5)).await, "after the commit"); +} diff --git a/app/tests/load.rs b/app/tests/load.rs new file mode 100644 index 00000000..e5e42de3 --- /dev/null +++ b/app/tests/load.rs @@ -0,0 +1,111 @@ +//! Load: the builds of a burst like the one before today's server hung (3 Dec 2026, about 20 builds of 331 snapshots +//! each in 30 minutes). Every build is unchanged, so the storage design writes no page rows for them, and all of them +//! finish within a bound on CI's Postgres. A pool that runs out answers 503 with Retry-After, never a hang. + +use std::time::{Duration, Instant}; + +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +const BUILDS: usize = 20; +const SNAPSHOTS: usize = 331; +/// The bound for the whole burst. Measured on docspring-dev and CI in a few seconds; the bound leaves room for a slow +/// runner while still catching a regression to per-snapshot work that grows with every build. +const WITHIN: Duration = Duration::from_secs(120); + +async fn project_token() -> laravel::Result { + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "web").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + Ok(token) +} + +fn snapshots() -> Vec { + (0..SNAPSHOTS) + .map(|i| { + let text = format!("snapshot {i}\nline two\n"); + let sha = visualci_core::sha256_hex(text.as_bytes()); + json!({ + "name": format!("suite/{:03}", i), "kind": "text", "fingerprint": sha, "sha256": sha, + "size": text.len(), "content_type": "text/plain", + }) + }) + .collect() +} + +/// One CI build of every snapshot, sent the way the CLI sends it: create, register in one request, finalize. +async fn build(app: &Application, token: &str, commit: &str, parent: &str) -> Value { + let auth = format!("Bearer {token}"); + let created = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": commit, "branch": "main", "parent_commits": [parent] })) + .await; + created.assert_ok(); + let id = created.json()["id"].as_str().unwrap().to_string(); + app.post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": snapshots() })) + .await + .assert_ok(); + let done = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await; + done.assert_ok(); + done.json().clone() +} + +#[laravel::test] +async fn twenty_unchanged_builds_of_331_snapshots_finish_without_page_rows(app: Application) -> laravel::Result<()> { + Box::pin(burst(app)).await +} + +async fn burst(app: Application) -> laravel::Result<()> { + let store = fixtures::blob_store().await?; + for i in 0..SNAPSHOTS { + let text = format!("snapshot {i}\nline two\n"); + app::domain::blobs::put(&store, text.into_bytes(), "text/plain").await?; + } + let token = project_token().await?; + let sha = |n: usize| format!("{n:040x}"); + let first = build(&app, &token, &sha(1000), &sha(999)).await; + assert_eq!(first["state"], "completed", "{first}"); + let pages_before: i64 = db::query!("SELECT COUNT(*) FROM snapshot_pages").scalar().await?.unwrap_or_default(); + + // One after another: a refreshed test database has one connection, so requests can't overlap here. The bound + // catches per-build work that grows (per-snapshot rows for unchanged groups); a pool that runs out is the 503 test + // below, and the concurrent burst is a benchmark against a dev server (see the PR). + let started = Instant::now(); + let mut done = Vec::with_capacity(BUILDS); + for n in 1..=BUILDS { + done.push(build(&app, &token, &sha(n), &sha(1000)).await); + } + let took = started.elapsed(); + + for b in &done { + assert_eq!(b["state"], "completed", "{b}"); + assert_eq!(b["conclusion"], "unchanged", "{b}"); + } + let pages_after: i64 = db::query!("SELECT COUNT(*) FROM snapshot_pages").scalar().await?.unwrap_or_default(); + assert_eq!(pages_after, pages_before, "unchanged builds store no page rows"); + println!("{BUILDS} builds of {SNAPSHOTS} unchanged snapshots in {took:?}"); + assert!(took < WITHIN, "{BUILDS} builds took {took:?}, over {WITHIN:?}"); + Ok(()) +} + +#[test] +fn a_pool_that_runs_out_answers_busy() { + let timed_out = laravel::Error::from(laravel::db::sqlx::Error::PoolTimedOut); + assert!(app::http::busy(&timed_out)); + assert!(!app::http::busy(&laravel::Error::msg("something else"))); + let response = axum::response::IntoResponse::into_response(app::http::api::ApiError::server(&timed_out)); + assert_eq!(response.status(), axum::http::StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(response.headers()[axum::http::header::RETRY_AFTER], "5"); +} diff --git a/app/tests/mcp.rs b/app/tests/mcp.rs new file mode 100644 index 00000000..5ed8fbab --- /dev/null +++ b/app/tests/mcp.rs @@ -0,0 +1,1153 @@ +//! The public MCP server's tools: today's answers (tests/golden/mcp) for the same calls. `whoami`'s `via` and +//! `list_builds`' compact lines are deliberate changes from today's answers. + +mod golden; + +use std::collections::HashMap; +use std::sync::Mutex; + +use app::models::{Feedback, Organization, User}; +use base64::Engine; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +struct Fixture { + org: String, + organization_id: i64, + project_id: i64, + user_token: String, + project_token: String, +} + +async fn token(table: &str, owner: i64, name: &str, prefix: &str) -> laravel::Result { + let token = format!("{prefix}_{}", laravel::str::uuid7().simple()); + let hash = app::models::token_hash(&token); + let short = &token[..6]; + if table == "user_tokens" { + db::query!( + "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({owner}, {name}, {hash}, {short}, now(), now())" + ) + .insert() + .await?; + } else { + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({owner}, {name}, {hash}, {short}, now(), now())" + ) + .insert() + .await?; + } + Ok(token) +} + +/// Today's fixture: an owner (admin) of `org-xxxxxxxx` with projects `pdfs` and `shots`, a personal token and a +/// project token for `pdfs`. +async fn fixture() -> laravel::Result { + // A hyphenated UUID, as today's fixture had: the golden files' normalizer replaces it. + let email = format!("{}@example.com", laravel::str::uuid7()); + let user = create!(User { pid: laravel::str::uuid7(), name: "owner", email: email, staff: false }).await?; + let slug = format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..]); + let org = create!(Organization { pid: laravel::str::uuid7(), slug: slug.clone(), name: "Org" }).await?; + app::testing::fixtures::member(&org, &user, "admin").await?; + let project = create!(app::models::Project { + pid: laravel::str::uuid7(), + organization_id: org.id, + slug: "pdfs", + name: "PDFs" + }) + .await?; + create!(app::models::Project { + pid: laravel::str::uuid7(), + organization_id: org.id, + slug: "shots", + name: "Screenshots" + }) + .await?; + // Token ids show in the answers. The test databases are reused with their rows rolled back, but sequences don't roll + // back, so they start again here: the project token is 1, and the next one 3, as with today's fixture (a fresh + // database, with a second project's token as 2). + db::query!("ALTER SEQUENCE project_tokens_id_seq RESTART WITH 1").statement().await?; + db::query!("ALTER SEQUENCE user_tokens_id_seq RESTART WITH 1").statement().await?; + let user_token = token("user_tokens", user.id, "agent", "vcu").await?; + let project_token = token("project_tokens", project.id, "ci", "vci").await?; + db::query!("SELECT setval('project_tokens_id_seq', 2)").statement().await?; + Ok(Fixture { org: slug, organization_id: org.id, project_id: project.id, user_token, project_token }) +} + +/// How many times each test has called each tool, for the golden files' names (`get_build-2.json`). +static CALLS: Mutex>> = Mutex::new(None); + +/// Call a tool, check the answer against today's (`tests/golden/mcp//[-n].json`), and return (is_error, +/// structured content or the first text block). +async fn call(app: &Application, test: &str, token: &str, tool: &str, args: Value) -> (bool, Value) { + let response = app + .post("/mcp") + .header("authorization", format!("Bearer {token}")) + // After the body: `json` sets `accept: application/json`, and MCP's Streamable HTTP wants both. + .json( + json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": tool, "arguments": args } }), + ) + .header("accept", "application/json, text/event-stream") + .await; + response.assert_ok(); + let body = response.json().clone(); + let result = body["result"].clone(); + assert!(result.is_object(), "{tool}: {body}"); + let n = { + let mut calls = CALLS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let n = calls.get_or_insert_with(HashMap::new).entry(format!("{test}/{tool}")).or_insert(0); + *n += 1; + *n + }; + let name = if n == 1 { tool.to_string() } else { format!("{tool}-{n}") }; + golden::check("mcp", test, &name, &json!({ "arguments": args, "result": result })); + let is_error = result["isError"].as_bool().unwrap_or(false); + let value = if result["structuredContent"].is_null() { + json!(result["content"][0]["text"]) + } else { + result["structuredContent"].clone() + }; + (is_error, value) +} + +/// A file the blob store already has, so registering it asks for no upload, and processing can read it. +async fn stored(text: &str) -> laravel::Result<()> { + let store = app::testing::fixtures::blob_store().await?; + app::domain::blobs::put(&store, text.as_bytes().to_vec(), "text/plain").await?; + Ok(()) +} + +#[laravel::test] +async fn rejects_requests_without_a_valid_token(app: Application) -> laravel::Result<()> { + app.post("/mcp") + .header("authorization", "Bearer vcu_wrong") + .header("accept", "application/json, text/event-stream") + .json(json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" })) + .await + .assert_status(401); + Ok(()) +} + +#[laravel::test] +async fn numbers_sent_as_strings_are_read_as_numbers(app: Application) -> laravel::Result<()> { + const TEST: &str = "numbers_sent_as_strings_are_read_as_numbers"; + let f = fixture().await?; + let t = &f.project_token; + let (err, r) = call(&app, TEST, t, "list_builds", json!({ "limit": "2" })).await; + assert!(!err, "{r}"); + let (err, r) = call(&app, TEST, t, "list_builds", json!({ "limit": "lots" })).await; + assert!(err && r.as_str().unwrap().contains("list_builds takes:"), "{r}"); + Ok(()) +} + +#[laravel::test] +async fn runs_a_build_from_uploaded_files(app: Application) -> laravel::Result<()> { + const TEST: &str = "runs_a_build_from_uploaded_files"; + let f = fixture().await?; + let t = &f.project_token; + let (err, build) = call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + assert!(!err, "{build}"); + assert_eq!(build["state"], "receiving"); + let text = "hello\nworld\n"; + stored(text).await?; + let content = base64::engine::general_purpose::STANDARD.encode(text); + let (err, up) = call( + &app, + TEST, + t, + "upload_snapshots", + json!({ "build": 1, "files": [{ "name": "greeting", "content_base64": content, "filename": "greeting.txt" }] }), + ) + .await; + assert!(!err, "{up}"); + assert_eq!(up["snapshots"][0]["name"], "greeting"); + assert_eq!(up["snapshots"][0]["stored"], false); + let (err, bad) = call( + &app, + TEST, + t, + "upload_snapshots", + json!({ "build": "1", "files": [{ "name": "x", "content_base64": "%%%" }] }), + ) + .await; + assert!(err, "{bad}"); + let (err, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "#1" })).await; + assert!(!err, "{done}"); + assert_ne!(done["state"], "receiving"); + + // One text snapshot was sent and nothing was drawn or diffed: one snapshot check, one credit. + let (_, build) = call(&app, TEST, t, "get_build", json!({ "build": "1" })).await; + assert_eq!(build["state"], "completed", "{build}"); + assert_eq!(app::domain::credits::used_this_month(f.organization_id).await?, 1); + // The usage history is the organization's people's to see (it names every project's builds). + let (_, org) = call(&app, TEST, &f.user_token, "get_organization", json!({ "org": f.org })).await; + assert_eq!(org["usage"]["credits_this_month"], 1, "{org}"); + assert_eq!(org["usage_history"][0]["credits"], 1, "{org}"); + Ok(()) +} + +/// Agents send a build as a number, a numeric string, "#N" or the build's id; every tool that takes a build reads +/// all four, and an argument it can't read gets the tool's real fields and an example call. +#[laravel::test] +async fn tools_that_take_a_build_read_every_form_and_explain_bad_arguments(app: Application) -> laravel::Result<()> { + const TEST: &str = "tools_that_take_a_build_read_every_form_and_explain_bad_arguments"; + let f = fixture().await?; + let t = &f.project_token; + let (err, build) = call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + assert!(!err, "{build}"); + let id = build["id"].as_str().unwrap().to_string(); + let forms = [json!(1), json!("1"), json!("#1"), json!(id)]; + for build in &forms { + let calls = [ + ("get_build", json!({ "build": build })), + ("get_snapshot", json!({ "build": build, "name": "missing" })), + ("review", json!({ "build": build, "action": "approve" })), + ("review_page", json!({ "build": build, "name": "missing", "position": 1, "action": "variant" })), + ]; + for (tool, args) in calls { + let (_, answer) = call(&app, TEST, t, tool, args).await; + assert!(!answer.to_string().contains("no build"), "{tool} {build}: {answer}"); + assert!(!answer.to_string().contains("failed to deserialize"), "{tool} {build}: {answer}"); + } + } + let (err, done) = call(&app, TEST, t, "finalize_build", json!({ "build": id, "allow_empty": true })).await; + assert!(!err, "{done}"); + + let (err, unknown) = call(&app, TEST, t, "get_snapshot", json!({ "build_number": 1 })).await; + assert!(err && unknown.as_str().unwrap().starts_with("get_snapshot doesn't take `build_number`."), "{unknown}"); + let (err, missing) = call(&app, TEST, t, "get_snapshot", json!({})).await; + assert!(err, "{missing}"); + let text = missing.as_str().unwrap(); + assert!(text.contains("missing field `build`"), "{text}"); + assert!(text.contains("get_snapshot takes:"), "{text}"); + assert!(text.contains("- build (required; integer or string)"), "{text}"); + assert!(text.contains("- id (string): The snapshot's id"), "{text}"); + assert!(text.contains(r#"Example: {"build":8}"#), "{text}"); + let (err, wrong) = call(&app, TEST, t, "review", json!({ "build": true, "action": "approve" })).await; + let text = wrong.as_str().unwrap(); + assert!(err && text.contains("review takes:\n- action (required; string)"), "{text}"); + assert!(text.contains(r#"Example: {"action":"","build":8}"#), "{text}"); + Ok(()) +} + +#[laravel::test] +async fn get_build_pages_long_lists_and_get_snapshot_finds_a_unique_name_without_its_platform( + app: Application, +) -> laravel::Result<()> { + const TEST: &str = "get_build_pages_long_lists_and_get_snapshot_finds_a_unique_name_without_its_platform"; + use app::domain::{build_settings::BuildSettings, snapshots}; + let f = fixture().await?; + let t = &f.project_token; + let (err, created) = call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + assert!(!err, "{created}"); + let project = app::models::Project::find_or_fail(f.project_id).await?; + let build = app::domain::builds::find_by_ref(project.id, "1").await?.expect("build 1"); + let snap = |name: String, platform: &str| { + serde_json::from_value::(json!({ + "name": name, "platform": platform, "kind": "text", "fingerprint": "c".repeat(64), + "sha256": "d".repeat(64), "size": 2, "content_type": "text/plain", + })) + .unwrap() + }; + let mut params: Vec = + (0..35).map(|i| snap(format!("screenshots/home/{i:02}"), "chrome")).collect(); + params.extend((0..5).map(|i| snap(format!("api/{i}"), ""))); + params.push(snap("twice".into(), "chrome")); + params.push(snap("twice".into(), "firefox")); + let settings = BuildSettings::new(&project, &build); + for p in ¶ms { + snapshots::register(&build, &settings, "test", p).await?.expect("registered"); + } + + let (err, got) = call(&app, TEST, t, "get_build", json!({ "build": "1", "include_unchanged": true })).await; + assert!(!err, "{got}"); + assert_eq!(got["snapshots"].as_array().unwrap().len(), 30); + assert_eq!(got["listed"], "1 to 30 of 42"); + assert_eq!(got["next_offset"], 30); + let groups = got["groups"].as_array().unwrap(); + assert!(groups.iter().any(|g| g["prefix"] == "screenshots/home/" && g["count"] == 35), "{groups:?}"); + assert!(got["snapshots"][0]["url"].as_str().unwrap().contains("/builds/1/snapshots/")); + let (_, rest) = + call(&app, TEST, t, "get_build", json!({ "build": "1", "include_unchanged": true, "offset": 30 })).await; + assert_eq!(rest["snapshots"].as_array().unwrap().len(), 12); + assert!(rest["next_offset"].is_null()); + + // A name on two platforms needs one; a wrong platform says which there are. + let (err, e) = call(&app, TEST, t, "get_snapshot", json!({ "build": "1", "name": "twice" })).await; + assert!(err && e.to_string().contains("several platforms"), "{e}"); + let (err, e) = + call(&app, TEST, t, "get_snapshot", json!({ "build": "1", "name": "api/1", "platform": "chrome" })).await; + assert!(err && e.to_string().contains("no platform"), "{e}"); + let (err, e) = call(&app, TEST, t, "get_snapshot", json!({ "build": "1", "name": "missing" })).await; + assert!(err && e.to_string().contains("no snapshot"), "{e}"); + + // A build number as a number, and a snapshot by the id get_build lists (no platform needed). + let (err, by_number) = call(&app, TEST, t, "get_build", json!({ "build": 1, "include_unchanged": true })).await; + assert!(!err, "{by_number}"); + let twice = by_number["snapshots"] + .as_array() + .unwrap() + .iter() + .chain(rest["snapshots"].as_array().unwrap()) + .find(|s| s["name"] == "twice") + .unwrap() + .clone(); + let (err, one) = call(&app, TEST, t, "get_snapshot", json!({ "build": 1, "id": twice["id"] })).await; + assert!(!err, "{one}"); + let (err, one) = call(&app, TEST, t, "get_snapshot", json!({ "build": "#1", "name": twice["id"] })).await; + assert!(!err, "{one}"); + Ok(()) +} + +#[laravel::test] +async fn takes_feedback_and_says_what_a_bad_report_is_missing(app: Application) -> laravel::Result<()> { + const TEST: &str = "takes_feedback_and_says_what_a_bad_report_is_missing"; + let f = fixture().await?; + let report = json!({ + "action": "feedback", "title": "Diff regions cover the whole page", "kind": "confusing", + "description": "A tiled watermark outlines every region. Token vci_abcdefghijklmnopqrstuvwxyz0123 leaked here.", + "impact": "friction", "idempotency_key": "k1", + }); + let (err, first) = call(&app, TEST, &f.user_token, "support_send", report.clone()).await; + assert!(!err, "{first}"); + assert!(first["feedback"]["id"].as_str().unwrap().starts_with("fb_")); + assert_eq!(first["duplicate"], false); + assert!(first["follow_up"].as_str().unwrap().starts_with("Nobody replies")); + let (_, again) = call(&app, TEST, &f.user_token, "support_send", report).await; + assert_eq!(again["duplicate"], true); + assert_eq!(again["feedback"]["id"], first["feedback"]["id"]); + + let stored = Feedback::query().first().await?.expect("the feedback"); + assert!(stored.description.contains("[redacted]"), "{}", stored.description); + assert!(!stored.description.contains("vci_abc")); + assert_eq!(stored.channel, "mcp"); + + let (err, msg) = call( + &app, + TEST, + &f.project_token, + "support_send", + json!({ "action": "feedback", "title": "Something", "description": "x" }), + ) + .await; + assert!(err); + let msg = msg.as_str().unwrap(); + assert!(msg.contains("needs title (3 to 200 characters), kind"), "{msg}"); + assert!(msg.contains("kind is missing"), "{msg}"); + + let auth = format!("Bearer {}", f.project_token); + app.post("/api/v1/support/feedback") + .header("authorization", &auth) + .json(json!({ "title": "CLI install", "kind": "docs", "description": "The README is out of date." })) + .await + .assert_ok(); + app.post("/api/v1/support/feedback") + .header("authorization", &auth) + .json(json!({ "title": "x" })) + .await + .assert_status(400); + Ok(()) +} + +#[laravel::test] +async fn get_skill_lists_the_skills_and_returns_one(app: Application) -> laravel::Result<()> { + const TEST: &str = "get_skill_lists_the_skills_and_returns_one"; + let f = fixture().await?; + let (err, list) = call(&app, TEST, &f.project_token, "get_skill", json!({})).await; + assert!(!err, "{list}"); + let names: Vec<&str> = list["skills"].as_array().unwrap().iter().filter_map(|s| s["name"].as_str()).collect(); + assert!(names.contains(&"visualci") && names.contains(&"visualci-jenkins"), "{names:?}"); + + let (err, skill) = call(&app, TEST, &f.project_token, "get_skill", json!({ "name": "visualci-jenkins" })).await; + assert!(!err, "{skill}"); + assert!(skill.as_str().unwrap().contains("# Jenkins"), "{skill}"); + + let (err, missing) = call(&app, TEST, &f.project_token, "get_skill", json!({ "name": "nope" })).await; + assert!(err, "{missing}"); + Ok(()) +} + +#[laravel::test] +async fn agents_comment_on_snapshots_and_resolve_threads(app: Application) -> laravel::Result<()> { + const TEST: &str = "agents_comment_on_snapshots_and_resolve_threads"; + let f = fixture().await?; + let t = &f.project_token; + let (err, build) = call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "feat" })).await; + assert!(!err, "{build}"); + let text = "hello\n"; + stored(text).await?; + let content = base64::engine::general_purpose::STANDARD.encode(text); + let (err, up) = call( + &app, + TEST, + t, + "upload_snapshots", + json!({ "build": 1, "files": [{ "name": "greeting", "content_base64": content, "filename": "greeting.txt" }] }), + ) + .await; + assert!(!err, "{up}"); + + let (err, started) = call( + &app, + TEST, + t, + "post_comment", + json!({ "build": 1, "snapshot": "greeting", "page": 0, "anchor": { "kind": "point", "x": 20, "y": 30 }, + "body": "Is this greeting **meant** to change?" }), + ) + .await; + assert!(!err, "{started}"); + let thread = started["thread"].as_str().unwrap().to_string(); + let (err, bad) = call( + &app, + TEST, + t, + "post_comment", + json!({ "build": 1, "snapshot": "greeting", "anchor": { "kind": "point", "x": -2, "y": 0 }, "body": "x" }), + ) + .await; + assert!(err && bad.to_string().contains("pixels from the image's top left"), "{bad}"); + + let (err, listed) = call(&app, TEST, t, "list_comments", json!({ "build": 1 })).await; + assert!(!err, "{listed}"); + assert_eq!(listed["branch"], "feat"); + let first = &listed["threads"][0]; + assert_eq!(first["snapshot"], "greeting"); + assert_eq!(first["anchor"]["kind"], "point"); + assert_eq!(first["comments"][0]["author"]["kind"], "agent", "{first}"); + let comment = first["comments"][0]["id"].as_str().unwrap().to_string(); + + let (err, edited) = + call(&app, TEST, t, "update_comment", json!({ "comment": comment, "body": "Is this change meant?" })).await; + assert!(!err && edited["body"] == "Is this change meant?", "{edited}"); + let (err, _) = call(&app, TEST, t, "post_comment", json!({ "build": 1, "thread": thread, "body": "Yes." })).await; + assert!(!err); + let (_, b) = call(&app, TEST, t, "get_build", json!({ "build": 1, "include_unchanged": true })).await; + assert_eq!(b["open_comment_threads"].as_array().map(Vec::len), Some(1), "{b}"); + let (_, me) = call(&app, TEST, t, "whoami", json!({})).await; + assert_eq!(me["open_comment_threads"][0]["branch"], "feat", "{me}"); + + let (err, r) = call(&app, TEST, t, "resolve_comment", json!({ "thread": thread })).await; + assert!(!err && r["resolved"] == true, "{r}"); + let (_, listed) = call(&app, TEST, t, "list_comments", json!({ "build": 1 })).await; + assert_eq!(listed["threads"], json!([]), "resolved threads are left out by default"); + let (_, listed) = call(&app, TEST, t, "list_comments", json!({ "build": 1, "include_resolved": true })).await; + assert_eq!(listed["threads"][0]["resolved"], true); + + let (err, d) = call(&app, TEST, t, "delete_comment", json!({ "comment": comment })).await; + assert!(!err && d["thread_deleted"] == false, "{d}"); + let (err, _) = call(&app, TEST, t, "review", json!({ "build": 1, "action": "approve", "comment": "nope" })).await; + assert!(err, "a comment goes with reject"); + + // `note` is an argument of `review` (its use is tested in comments.rs, on a finished build). + let (err, r) = call(&app, TEST, t, "review", json!({ "build": 1, "action": "approve", "note": "why" })).await; + assert!(err && r.to_string().contains("finalize"), "the build isn't finished, but the note was read: {r}"); + Ok(()) +} + +/// Every tool's argument help says what it takes, and an argument a tool doesn't take is refused, naming it. +#[laravel::test] +async fn every_tool_refuses_arguments_it_does_not_take(app: Application) -> laravel::Result<()> { + const TEST: &str = "every_tool_refuses_arguments_it_does_not_take"; + let f = fixture().await?; + let auth = format!("Bearer {}", f.user_token); + let list = app + .post("/mcp") + .header("authorization", &auth) + .json(json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" })) + .header("accept", "application/json, text/event-stream") + .await + .json() + .clone(); + let tools = list["result"]["tools"].as_array().expect("a tools list").clone(); + assert!(tools.len() >= 17, "{}", tools.len()); + for tool in &tools { + let name = tool["name"].as_str().unwrap(); + assert_eq!(tool["inputSchema"]["additionalProperties"], false, "{name} says it takes nothing else"); + let response = app + .post("/mcp") + .header("authorization", &auth) + .json(json!({ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": { "name": name, "arguments": { "not_an_argument": 1 } }, + })) + .header("accept", "application/json, text/event-stream") + .await + .json() + .clone(); + let result = &response["result"]; + assert_eq!(result["isError"], true, "{name}: {result}"); + let text = result["content"][0]["text"].as_str().unwrap_or_default(); + assert!(text.starts_with(&format!("{name} doesn't take `not_an_argument`.")), "{name}: {text}"); + assert!(text.contains(&format!("{name} takes:")) && text.contains("Example:"), "{name}: {text}"); + } + // A misspelt argument: refused, naming it, never silently dropped. + let (err, text) = + call(&app, TEST, &f.user_token, "review", json!({ "build": 1, "action": "approve", "notes": "x" })).await; + assert!(err && text.as_str().unwrap().contains("doesn't take `notes`"), "{text}"); + Ok(()) +} + +/// A project token reaches its own project and nothing else. (Today's test also checks create_organization and +/// get_project, which come with the organization tools.) +#[laravel::test] +async fn a_project_token_reaches_only_its_project(app: Application) -> laravel::Result<()> { + const TEST: &str = "a_project_token_reaches_only_its_project"; + let f = fixture().await?; + let (err, builds) = call(&app, TEST, &f.project_token, "list_builds", json!({})).await; + assert!(!err, "{builds}"); + let other = format!("{}/shots", f.org); + let (err, msg) = call(&app, TEST, &f.project_token, "list_builds", json!({ "project": other })).await; + assert!(err, "{msg}"); + // A person's token outside the organization doesn't see it either, nor its builds' tools. + let stranger = + create!(User { pid: laravel::str::uuid7(), name: "stranger", email: "stranger@example.com", staff: false }) + .await?; + let theirs = token("user_tokens", stranger.id, "agent", "vcu").await?; + let project = format!("{}/pdfs", f.org); + for (tool, args) in [ + ("list_builds", json!({ "project": project })), + ("get_build", json!({ "project": project, "build": 1 })), + ("review", json!({ "project": project, "build": 1, "action": "approve" })), + ("create_build", json!({ "project": project, "commit": "a", "branch": "b" })), + ] { + let response = app + .post("/mcp") + .header("authorization", format!("Bearer {theirs}")) + .json(json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": tool, "arguments": args } })) + .header("accept", "application/json, text/event-stream") + .await + .json() + .clone(); + let text = response["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string(); + assert!(response["result"]["isError"] == true && text.contains("that you can see"), "{tool}: {text}"); + } + Ok(()) +} + +/// With "Tokens can approve" off, a project token can't approve, accept a variant or ignore a change; it can still +/// reject. A person's token can turn it off and on. +#[laravel::test] +async fn a_project_can_keep_approving_with_people(app: Application) -> laravel::Result<()> { + const TEST: &str = "a_project_can_keep_approving_with_people"; + let f = fixture().await?; + let project = format!("{}/pdfs", f.org); + let (err, s) = + call(&app, TEST, &f.user_token, "update_project", json!({ "project": project, "tokens_can_approve": false })) + .await; + assert!(!err && s["settings"]["tokens_can_approve"] == false, "{s}"); + let t = &f.project_token; + let (err, r) = call(&app, TEST, t, "review", json!({ "build": 1, "action": "approve" })).await; + assert!(err && r.to_string().contains("approving with people"), "{r}"); + let (err, r) = + call(&app, TEST, t, "review_page", json!({ "build": 1, "name": "x", "position": 0, "action": "ignore" })).await; + assert!(err && r.to_string().contains("approving with people"), "{r}"); + // Rejecting isn't approving: it reaches the build (there's none here). + let (err, r) = call(&app, TEST, t, "review", json!({ "build": 1, "action": "reject" })).await; + assert!(err && r.to_string().contains("no build"), "{r}"); + Ok(()) +} + +async fn set_plan(organization_id: i64, plan: &str) -> laravel::Result<()> { + db::query!("UPDATE organizations SET plan = {plan} WHERE id = {organization_id}").update().await?; + Ok(()) +} + +#[laravel::test] +async fn a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why( + app: Application, +) -> laravel::Result<()> { + const TEST: &str = "a_free_organization_over_its_allowance_gets_a_failed_build_that_says_why"; + use app::domain::credits; + let f = fixture().await?; + credits::spend(f.organization_id, 25_000, "build", Some("earlier builds"), None, None).await?; + let t = &f.project_token; + // Out of credits from the start: whoami and the new build say so, with what fixes it. + let (_, me) = call(&app, TEST, t, "whoami", json!({})).await; + assert_eq!(me["blocked"]["reason"], "out_of_credits", "{me}"); + let (_, created) = call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + assert_eq!(created["blocked"]["reason"], "out_of_credits", "{created}"); + let (err, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "1" })).await; + assert!(!err, "{done}"); + assert_eq!(done["state"], "failed"); + assert!(done["error"].as_str().unwrap().contains("this month's 25,000 credits on the Free plan"), "{done}"); + let blocked = &done["blocked"]; + assert_eq!(blocked["credits_used"], 25_000, "{blocked}"); + assert_eq!(blocked["credits_limit"], 25_000); + assert_eq!(blocked["fixes"][0]["action"], "upgrade"); + assert!(blocked["fixes"][0]["url"].as_str().unwrap().ends_with(&format!("/{}/billing", f.org)), "{blocked}"); + let message = blocked["message"].as_str().unwrap(); + assert!(message.contains("is out of VisualCI credits until") && message.contains("upgrade to Team"), "{message}"); + assert!(blocked["renews_at"].is_string()); + + // On Team the same usage is fine. + set_plan(f.organization_id, "team").await?; + call(&app, TEST, t, "create_build", json!({ "commit": "def", "branch": "main" })).await; + let (_, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "2", "allow_empty": true })).await; + assert_ne!(done["state"], "failed", "{done}"); + assert!(done["blocked"].is_null(), "{done}"); + // The build that stopped says the organization has credits again. + let (_, first) = call(&app, TEST, t, "get_build", json!({ "build": "1" })).await; + assert_eq!(first["blocked"]["resolved"], true, "{first}"); + let (_, me) = call(&app, TEST, t, "whoami", json!({})).await; + assert!(me["blocked"].is_null(), "{me}"); + Ok(()) +} + +#[laravel::test] +async fn staff_plan_records_usage_but_never_runs_out(app: Application) -> laravel::Result<()> { + const TEST: &str = "staff_plan_records_usage_but_never_runs_out"; + use app::domain::credits; + let f = fixture().await?; + set_plan(f.organization_id, "staff").await?; + // Far past any allowance: pack credits untouched, usage still recorded, never out of credits. + credits::spend(f.organization_id, 50_000_000, "build", None, None, None).await?; + let o = Organization::find_or_fail(f.organization_id).await?; + assert_eq!(o.credits_balance, 0); + assert_eq!(credits::used_this_month(o.id).await?, 50_000_000); + assert!(!credits::out_of_credits(&o).await?); + let usage = credits::usage(&o).await?; + assert_eq!(usage["unlimited"], true); + assert_eq!(usage["out_of_credits"], false); + assert_eq!(usage["plan"]["id"], "staff", "{usage}"); + + // Builds still finish. + let t = &f.project_token; + call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + let (_, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "1", "allow_empty": true })).await; + assert_ne!(done["state"], "failed", "{done}"); + Ok(()) +} + +#[laravel::test] +async fn team_uses_its_allowance_first_then_pack_credits_and_stops_when_both_run_out( + app: Application, +) -> laravel::Result<()> { + const TEST: &str = "team_uses_its_allowance_first_then_pack_credits_and_stops_when_both_run_out"; + use app::domain::credits; + let f = fixture().await?; + let id = f.organization_id; + set_plan(id, "team").await?; + + // Within the allowance, pack credits aren't touched. + assert!(credits::add_purchased_credits(id, 500_000, "packs: cs_1").await?); + assert!(!credits::add_purchased_credits(id, 500_000, "packs: cs_1").await?); + credits::spend(id, 900_000, "build", None, None, None).await?; + assert_eq!(Organization::find_or_fail(id).await?.credits_balance, 500_000); + + // Past it, the rest comes from packs. + credits::spend(id, 300_000, "build", None, None, None).await?; + let o = Organization::find_or_fail(id).await?; + assert_eq!(o.credits_balance, 300_000); + assert_eq!(credits::credits_left(&o).await?, 300_000); + assert!(!credits::out_of_credits(&o).await?); + + // With both used up (and no Stripe here to reload), finalizing fails the build and says what to do. + credits::spend(id, 300_000, "build", None, None, None).await?; + let o = Organization::find_or_fail(id).await?; + assert!(credits::out_of_credits(&o).await?); + let usage = credits::usage(&o).await?; + assert_eq!(usage["out_of_credits"], true); + assert_eq!(usage["pack_credits"], 0); + let t = &f.project_token; + call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + let (_, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "1" })).await; + assert_eq!(done["state"], "failed", "{done}"); + assert!(done["error"].as_str().unwrap().contains("Buy a credit pack"), "{done}"); + let actions: Vec<&str> = + done["blocked"]["fixes"].as_array().unwrap().iter().filter_map(|f| f["action"].as_str()).collect(); + assert_eq!(actions, ["buy_pack", "turn_on_auto_buy"], "{done}"); + Ok(()) +} + +/// What the MCP TypeScript SDK checks (Executor and other clients built on it refuse the whole list otherwise): each +/// schema is an object, every property's schema is an object with a type, and arrays name their items' type. +fn check_schema(path: &str, schema: &Value) { + assert!(schema.is_object(), "{path} isn't an object: {schema}"); + if let Some(props) = schema.get("properties").and_then(Value::as_object) { + for (name, prop) in props { + assert!(prop.is_object(), "{path}.{name} isn't an object: {prop}"); + assert!(prop.get("type").is_some() || prop.get("anyOf").is_some(), "{path}.{name} has no type: {prop}"); + check_schema(&format!("{path}.{name}"), prop); + } + } + if let Some(items) = schema.get("items") { + assert!(items.get("type").is_some(), "{path}[] has no type: {items}"); + check_schema(&format!("{path}[]"), items); + } +} + +#[laravel::test] +async fn lists_the_tools_each_kind_of_token_can_use(app: Application) -> laravel::Result<()> { + const TEST: &str = "lists_the_tools_each_kind_of_token_can_use"; + let f = fixture().await?; + for (kind, token) in [("user", &f.user_token), ("project", &f.project_token)] { + let response = app + .post("/mcp") + .header("authorization", format!("Bearer {token}")) + .json(json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" })) + .header("accept", "application/json, text/event-stream") + .await; + response.assert_ok(); + let result = response.json()["result"].clone(); + let tools = result["tools"].as_array().expect("a tools list"); + assert!(!tools.is_empty()); + for tool in tools { + for key in ["inputSchema", "outputSchema"] { + let Some(schema) = tool.get(key) else { continue }; + assert_eq!(schema["type"], "object", "{} {key}", tool["name"]); + check_schema(&format!("{} {key}", tool["name"]), schema); + } + } + golden::check("mcp", TEST, &format!("tools-list-{kind}-token"), &result); + } + Ok(()) +} + +#[laravel::test] +async fn a_personal_token_manages_organizations_projects_and_tokens(app: Application) -> laravel::Result<()> { + Box::pin(personal_token_manages(app)).await +} + +async fn personal_token_manages(app: Application) -> laravel::Result<()> { + const TEST: &str = "a_personal_token_manages_organizations_projects_and_tokens"; + let f = fixture().await?; + let t = &f.user_token; + + let (err, me) = call(&app, TEST, t, "whoami", json!({})).await; + assert!(!err); + assert_eq!(me["kind"], "user"); + assert_eq!(me["organizations"][0]["projects"].as_array().unwrap().len(), 2); + assert_eq!(me["via"], json!({ "source": "personal_token", "token_name": "agent" }), "{me}"); + + let (err, org) = call(&app, TEST, t, "get_organization", json!({ "org": f.org })).await; + assert!(!err, "{org}"); + assert_eq!(org["usage"]["plan"]["id"], "free"); + assert_eq!(org["usage"]["included_credits"], 25000); + assert_eq!(org["usage"]["credits_this_month"], 0); + + let new_org = format!("{}-b", f.org); + let (err, _) = call(&app, TEST, t, "create_organization", json!({ "slug": new_org, "name": "B" })).await; + assert!(!err); + let (err, p) = + call(&app, TEST, t, "create_project", json!({ "org": new_org, "slug": "docs", "name": "Docs" })).await; + assert!(!err, "{p}"); + let project = format!("{new_org}/docs"); + + let (err, s) = call(&app, TEST, t, "update_project", json!({ "project": project, "dpi": 150 })).await; + assert!(!err, "{s}"); + assert_eq!(s["settings"]["dpi"], 150); + assert_eq!(s["settings"]["repository_url"], Value::Null); + // Linking a repository needs the forge to agree; a URL VisualCI doesn't know is refused. + let (err, s) = call( + &app, + TEST, + t, + "update_project", + json!({ "project": project, "repository_url": "https://example.com/a/b" }), + ) + .await; + assert!(err && s.to_string().contains("isn't a repository URL"), "{s}"); + let (err, s) = call(&app, TEST, t, "update_project", json!({ "project": project, "dpi": 9000 })).await; + assert!(err, "{s}"); + + // Ignore rules for text snapshots: each scoped to a snapshot glob, checked when saved, blank lines dropped. + let (err, s) = call( + &app, + TEST, + t, + "update_project", + json!({ "project": project, "ignore_rules": [{ "snapshots": "api/**", "json_paths": ["$.generated_at", " "], + "text_patterns": ["\\d{4}-\\d{2}-\\d{2}"] }] }), + ) + .await; + assert!(!err, "{s}"); + assert_eq!(s["settings"]["ignore_rules"][0]["snapshots"], "api/**"); + assert_eq!(s["settings"]["ignore_rules"][0]["json_paths"], json!(["$.generated_at"])); + assert_eq!(s["settings"]["ignore_rules"][0]["text_patterns"], json!(["\\d{4}-\\d{2}-\\d{2}"])); + for (rules, needle) in [ + (json!([{ "snapshots": "**", "json_paths": ["$.items["] }]), "JSON path"), + (json!([{ "snapshots": "**", "text_patterns": ["("] }]), "pattern"), + (json!([{ "snapshots": "", "json_paths": ["$.a"] }]), "names the snapshots"), + (json!([{ "json_paths": ["$.a"] }]), "snapshots"), + ] { + let (err, s) = + call(&app, TEST, t, "update_project", json!({ "project": project, "ignore_rules": rules })).await; + assert!(err, "{s}"); + assert!(s.to_string().contains(needle), "{needle}: {s}"); + } + + let (err, token) = + call(&app, TEST, t, "create_project_token", json!({ "project": project, "name": "CircleCI" })).await; + assert!(!err, "{token}"); + assert!(token["token"].as_str().unwrap().starts_with("vci_")); + let (_, got) = call(&app, TEST, t, "get_project", json!({ "project": project })).await; + assert_eq!(got["tokens"].as_array().unwrap().len(), 1); + let (err, _) = + call(&app, TEST, t, "delete_project_token", json!({ "project": project, "token_id": token["id"] })).await; + assert!(!err); + + // Someone else's organization stays invisible. + let (err, _) = call(&app, TEST, t, "get_organization", json!({ "org": "nobody-else" })).await; + assert!(err); + Ok(()) +} + +#[laravel::test] +async fn projects_can_be_renamed(app: Application) -> laravel::Result<()> { + const TEST: &str = "projects_can_be_renamed"; + let f = fixture().await?; + let old = format!("{}/pdfs", f.org); + let (err, s) = + call(&app, TEST, &f.user_token, "update_project", json!({ "project": old, "slug": "monorepo" })).await; + assert!(!err, "{s}"); + assert_eq!(s["settings"]["slug"], "monorepo"); + // The old reference is gone; the new one works. + let (err, _) = call(&app, TEST, &f.user_token, "get_project", json!({ "project": old })).await; + assert!(err, "the old slug no longer finds the project"); + // Taken or invalid slugs are refused. + let renamed = format!("{}/monorepo", f.org); + let (err, got) = call(&app, TEST, &f.user_token, "get_project", json!({ "project": renamed })).await; + assert!(!err, "{got}"); + for (slug, needle) in [("shots", "already has"), ("Not OK", "lowercase")] { + let (err, e) = + call(&app, TEST, &f.user_token, "update_project", json!({ "project": renamed, "slug": slug })).await; + assert!(err, "{e}"); + assert!(e.to_string().contains(needle), "{needle}: {e}"); + } + Ok(()) +} + +/// A project token is CI's: it sends builds, reviews and comments, but can't mint tokens, change the project's settings +/// or see the organization's members, so a leaked CI secret can't keep itself alive or loosen the checks. +#[laravel::test] +async fn a_project_token_acts_as_a_member_not_an_admin(app: Application) -> laravel::Result<()> { + const TEST: &str = "a_project_token_acts_as_a_member_not_an_admin"; + let f = fixture().await?; + let t = &f.project_token; + let (err, r) = call(&app, TEST, t, "create_project_token", json!({ "name": "spare" })).await; + assert!(err, "no new tokens: {r}"); + let (err, r) = call(&app, TEST, t, "update_project", json!({ "ci_mode": "review" })).await; + assert!(err, "no settings: {r}"); + let (err, org) = call(&app, TEST, t, "get_organization", json!({ "org": f.org })).await; + assert!(!err, "{org}"); + assert_eq!(org["members"], json!([]), "no members' emails"); + assert_eq!(org["projects"].as_array().map(Vec::len), Some(1), "only its own project: {org}"); + let (_, orgs) = call(&app, TEST, t, "list_organizations", json!({})).await; + assert_eq!(orgs["organizations"][0]["projects"], json!(["pdfs"])); + // A person's token still can. + let (err, r) = call( + &app, + TEST, + &f.user_token, + "create_project_token", + json!({ "project": format!("{}/pdfs", f.org), "name": "spare" }), + ) + .await; + assert!(!err, "{r}"); + Ok(()) +} + +#[laravel::test] +async fn a_builds_visualci_yml_overrides_the_project_settings(app: Application) -> laravel::Result<()> { + Box::pin(visualci_yml_overrides(app)).await +} + +async fn visualci_yml_overrides(app: Application) -> laravel::Result<()> { + use app::domain::build_settings::BuildSettings; + use app::domain::snapshots::SnapshotParams; + use app::models::{Build, Project}; + const TEST: &str = "a_builds_visualci_yml_overrides_the_project_settings"; + let f = fixture().await?; + let t = &f.project_token; + let pdfs = format!("{}/pdfs", f.org); + // The project's own rules apply only to builds without `ignore` in their file. + let (err, s) = call( + &app, + TEST, + &f.user_token, + "update_project", + json!({ "project": pdfs, "ci_mode": "review", "ignore_rules": [{ "snapshots": "**", "json_paths": ["$.project_rule"] }] }), + ) + .await; + assert!(!err, "{s}"); + + // A rule without a scope is refused, and so is the build. + let (err, e) = call( + &app, + TEST, + t, + "create_build", + json!({ "commit": "abc", "branch": "main", "config": { "ignore": [{ "json_paths": ["$.generated_at"] }] } }), + ) + .await; + assert!(err, "{e}"); + assert!(e.to_string().contains("visualci.yml"), "{e}"); + + let config = json!({ + "ignore": [{ "snapshots": "api/**", "json_paths": ["$.generated_at"] }], + "threshold": { "screenshots/**": 0.2 }, + "pdf": { "engine": "mutool", "dpi": 200 }, + "ci_mode": "strict", + }); + let (err, build) = + call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main", "config": config })).await; + assert!(!err, "{build}"); + let (_, got) = call(&app, TEST, t, "get_build", json!({ "build": "1" })).await; + assert_eq!(got["config"]["ci_mode"], "strict", "{got}"); + assert_eq!(got["ci_mode"], "strict", "{got}"); + + let project = Project::find_or_fail(f.project_id).await?; + let build = Build::query().filter(Build::project_id.eq(project.id) & Build::number.eq(1)).first().await?.unwrap(); + let text = |name: &str, ignore: Option| { + serde_json::from_value::(json!({ + "name": name, "kind": "text", "fingerprint": "c".repeat(64), "sha256": "d".repeat(64), "size": 2, + "content_type": "application/json", "ignore": ignore, + })) + .unwrap() + }; + let settings = BuildSettings::new(&project, &build); + let mut regs = Vec::new(); + for p in [text("api/invoice", Some(json!({ "json_paths": ["$.in_test"] }))), text("other", None)] { + p.validate().unwrap(); + regs.push(app::domain::snapshots::register(&build, &settings, "test", &p).await?.unwrap().snapshot); + } + let applied = |i: usize| serde_json::to_value(settings.applied_rules(®s[i])).unwrap(); + assert_eq!( + applied(0), + json!([ + { "source": "file", "snapshots": "api/**", "json_paths": ["$.generated_at"], "text_patterns": [] }, + { "source": "test", "snapshots": null, "json_paths": ["$.in_test"], "text_patterns": [] }, + ]) + ); + // The file has `ignore`, so the project's rule doesn't apply, and its glob doesn't match `other`. + assert_eq!(applied(1), json!([])); + assert_eq!(settings.ci_mode(), "strict"); + assert_eq!(settings.renderer_key(None, "v1"), "mutool/200dpi/v1"); + assert_eq!(settings.renderer_key(Some("pdfbox"), "v1"), "pdfbox/200dpi/v1"); + let mut shot = regs[1].clone(); + shot.name = "screenshots/home".into(); + assert!((settings.diff_options(&shot).threshold - 0.2).abs() < 1e-9); + assert!((settings.diff_options(®s[1]).threshold - project.threshold).abs() < 1e-9); + + // An invalid rule in the test is refused. + assert!(text("x", Some(json!({ "json_paths": ["$.a["] }))).validate().is_err()); + + // Several rules each within the cap but over it together still all apply (each is parsed on its own). + let many: Vec = (0..150).map(|i| format!("$.k{i}")).collect(); + let (err, s) = call( + &app, + TEST, + &f.user_token, + "update_project", + json!({ "project": pdfs, "ignore_rules": [{ "snapshots": "**", "json_paths": many }] }), + ) + .await; + assert!(!err, "{s}"); + + // The file can tighten the CI mode but not loosen it. + let (err, s) = + call(&app, TEST, &f.user_token, "update_project", json!({ "project": pdfs, "ci_mode": "strict" })).await; + assert!(!err, "{s}"); + let (err, loose) = call( + &app, + TEST, + t, + "create_build", + json!({ "commit": "lmn", "branch": "main", "config": { "ci_mode": "review" } }), + ) + .await; + assert!(!err, "{loose}"); + let project = Project::find_or_fail(f.project_id).await?; + let number = i32::try_from(loose["number"].as_i64().unwrap()).unwrap(); + let loose = + Build::query().filter(Build::project_id.eq(project.id) & Build::number.eq(number)).first().await?.unwrap(); + assert_eq!(BuildSettings::new(&project, &loose).ci_mode(), "strict"); + assert!(loose.warnings.to_string().contains("only make the mode"), "{}", loose.warnings); + + // A file that hides more than its base's needs review; one that hides less doesn't. + let make = |config: Value| { + let mut b = loose.clone(); + b.config = Some(config); + b + }; + let base = make(json!({ "ignore": [{ "snapshots": "api/**", "json_paths": ["$.a"] }], "threshold": 0.1 })); + let wider = make(json!({ "ignore": [{ "snapshots": "**", "json_paths": ["$.a"] }], "threshold": 0.1 })); + let higher = make(json!({ "ignore": [{ "snapshots": "api/**", "json_paths": ["$.a"] }], "threshold": 0.3 })); + let fewer = make(json!({ "ignore": [], "threshold": 0.05 })); + let (b, w, h, l) = ( + BuildSettings::new(&project, &base), + BuildSettings::new(&project, &wider), + BuildSettings::new(&project, &higher), + BuildSettings::new(&project, &fewer), + ); + assert!(w.hides_more_than(&b)); + assert!(h.hides_more_than(&b)); + assert!(!l.hides_more_than(&b)); + assert!(!b.hides_more_than(&b)); + assert_eq!(b.unmatched_rules(["invoices/show"]).len(), 1); + assert!(b.unmatched_rules(["api/invoices/show"]).is_empty()); + + // A build without a file uses the project's settings. + call(&app, TEST, t, "create_build", json!({ "commit": "def", "branch": "main" })).await; + let plain = Build::query().filter(Build::project_id.eq(project.id) & Build::number.eq(3)).first().await?.unwrap(); + let settings = BuildSettings::new(&project, &plain); + let other = + app::domain::snapshots::register(&plain, &settings, "test", &text("other", None)).await?.unwrap().snapshot; + assert_eq!(settings.ci_mode(), "strict"); + assert_eq!(serde_json::to_value(settings.applied_rules(&other)).unwrap()[0]["source"], "project"); + assert_eq!(settings.renderer_key(None, "v1"), format!("{}/{}dpi/v1", project.renderer, project.dpi)); + Ok(()) +} + +/// `list_builds` answers one short line per build (sc-8891): what tells builds apart, and their changes in a few words; +/// get_build has the rest. +#[laravel::test] +async fn list_builds_answers_one_short_line_per_build(app: Application) -> laravel::Result<()> { + const TEST: &str = "list_builds_answers_one_short_line_per_build"; + let f = fixture().await?; + let t = &f.project_token; + call(&app, TEST, t, "create_build", json!({ "commit": "a1b2c3d4e5f60718293a", "branch": "main" })).await; + let (err, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "1", "allow_empty": true })).await; + assert!(!err, "{done}"); + call( + &app, + TEST, + t, + "create_build", + json!({ "commit": "b2c3d4e5f6", "branch": "feat", "pr_number": 7, "name": "docs" }), + ) + .await; + let (err, list) = call(&app, TEST, t, "list_builds", json!({})).await; + assert!(!err, "{list}"); + let builds = list["builds"].as_array().unwrap(); + assert_eq!(builds.len(), 2); + assert_eq!(builds[0]["name"], "docs", "a suite's name shows when it isn't the default: {list}"); + assert!(builds[1].get("name").is_none() && builds[1].get("mode").is_none(), "{list}"); + assert_eq!(builds[1]["commit"], "a1b2c3d4e5f60718293a", "the whole commit, to compare with HEAD"); + assert_eq!(builds[1]["stats"], json!({ "changed": 0, "added": 0, "removed": 0, "unchanged": 0, "failed": 0 })); + assert!(builds[1]["blocked"].is_null(), "{list}"); + assert_eq!(builds[1]["changes"], "unchanged"); + assert_eq!(builds[0]["changes"], "not compared", "still receiving"); + for left_out in ["environment_info", "reviews", "groups", "ci_mode", "passed", "warnings"] { + assert!(builds[0].get(left_out).is_none(), "{left_out} is get_build's: {list}"); + } + Ok(()) +} + +/// A pull request where nothing changed gets no comment by default; `comment_when_unchanged` turns that on. +#[laravel::test] +async fn comments_when_nothing_changed_are_off_until_turned_on(app: Application) -> laravel::Result<()> { + const TEST: &str = "comments_when_nothing_changed_are_off_until_turned_on"; + let f = fixture().await?; + let project = format!("{}/pdfs", f.org); + let (err, s) = call(&app, TEST, &f.user_token, "get_project", json!({ "project": project })).await; + assert!(!err && s["settings"]["comment_when_unchanged"] == false, "off by default: {s}"); + let (err, s) = call( + &app, + TEST, + &f.user_token, + "update_project", + json!({ "project": project, "comment_when_unchanged": true }), + ) + .await; + assert!(!err && s["settings"]["comment_when_unchanged"] == true, "{s}"); + Ok(()) +} + +/// Only an organization's admins invite people, with a person's token, and a recipient is invited at most three times +/// a day. (New: today's server has no golden for invite_member.) +#[laravel::test] +async fn invite_member_checks_who_may_invite_and_its_limits(app: Application) -> laravel::Result<()> { + Box::pin(invite_member_checks(app)).await +} + +async fn invite_member_checks(app: Application) -> laravel::Result<()> { + const TEST: &str = "invite_member_checks_who_may_invite_and_its_limits"; + let f = fixture().await?; + let org = Organization::find_or_fail(f.organization_id).await?; + let member = + create!(User { pid: laravel::str::uuid7(), name: "member", email: "member@example.com", staff: false }).await?; + app::testing::fixtures::member(&org, &member, "member").await?; + let member_token = token("user_tokens", member.id, "member", "vcu").await?; + let invite = json!({ "org": f.org, "invitee": "ada@example.com", "role": "member" }); + + let (err, r) = call(&app, TEST, &f.project_token, "invite_member", invite.clone()).await; + assert!(err && r.to_string().contains("personal access token"), "a project token can't invite: {r}"); + let (err, r) = call(&app, TEST, &member_token, "invite_member", invite.clone()).await; + assert!(err && r.to_string().contains("only an organization's admins"), "a member can't: {r}"); + + let (err, r) = call(&app, TEST, &f.user_token, "invite_member", invite.clone()).await; + assert!(!err, "{r}"); + assert_eq!(r["invitation"]["invitee"], "ada@example.com", "{r}"); + assert_eq!(r["invitation"]["role"], "member"); + // Inviting the same person again keeps one invitation (and one email). Someone invited three times in a day (here by + // other organizations) isn't invited again until tomorrow. + let (err, r) = call(&app, TEST, &f.user_token, "invite_member", invite.clone()).await; + assert!(!err, "{r}"); + for n in 0..3 { + let key = format!("invited:elsewhere:{n}"); + db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data) VALUES ('invited', {key}, 'bea@example.com', '{{}}')" + ) + .insert() + .await?; + } + let bea = json!({ "org": f.org, "invitee": "bea@example.com", "role": "read" }); + let (err, r) = call(&app, TEST, &f.user_token, "invite_member", bea).await; + assert!(err && r.to_string().contains("invited too often"), "{r}"); + Ok(()) +} + +/// A build's images download as one archive, built in the background (inline in tests): the answer says its state and, +/// when ready, its URL. (New: today's server has no golden for download_build.) +#[laravel::test] +async fn download_build_builds_an_archive_and_says_its_state(app: Application) -> laravel::Result<()> { + const TEST: &str = "download_build_builds_an_archive_and_says_its_state"; + app::testing::fixtures::blob_store().await?; + let f = fixture().await?; + let t = &f.project_token; + call(&app, TEST, t, "create_build", json!({ "commit": "abc", "branch": "main" })).await; + let (err, done) = call(&app, TEST, t, "finalize_build", json!({ "build": "1", "allow_empty": true })).await; + assert!(!err, "{done}"); + let (err, d) = call(&app, TEST, t, "download_build", json!({ "build": "1", "state": "all" })).await; + assert!(!err, "{d}"); + assert_eq!(d["state"], "ready", "{d}"); + assert!(d["url"].is_string(), "{d}"); + assert_eq!(d["summary"]["snapshots"], 0, "{d}"); + let (err, r) = call(&app, TEST, t, "download_build", json!({ "build": "1", "state": "new" })).await; + assert!(err && r.to_string().contains("state must be one of"), "{r}"); + let (err, r) = call(&app, TEST, t, "download_build", json!({ "build": "9" })).await; + assert!(err && r.to_string().contains("no build"), "{r}"); + Ok(()) +} + +/// A person's organizations, with their role, usage and projects. (New: today's tests read it with a project token +/// only.) +#[laravel::test] +async fn list_organizations_lists_a_persons_organizations(app: Application) -> laravel::Result<()> { + const TEST: &str = "list_organizations_lists_a_persons_organizations"; + let f = fixture().await?; + let (err, orgs) = call(&app, TEST, &f.user_token, "list_organizations", json!({})).await; + assert!(!err, "{orgs}"); + assert_eq!(orgs["organizations"][0]["slug"], f.org); + assert_eq!(orgs["organizations"][0]["role"], "admin"); + assert_eq!(orgs["organizations"][0]["projects"], json!(["pdfs", "shots"])); + assert_eq!(orgs["organizations"][0]["usage"]["plan"]["id"], "free"); + Ok(()) +} + +/// A slug that's taken is refused in today's words. (New: today's server has no golden for it.) +#[laravel::test] +async fn create_organization_refuses_a_taken_slug(app: Application) -> laravel::Result<()> { + const TEST: &str = "create_organization_refuses_a_taken_slug"; + let f = fixture().await?; + let (err, r) = + call(&app, TEST, &f.user_token, "create_organization", json!({ "slug": f.org, "name": "Again" })).await; + assert!(err, "{r}"); + assert_eq!(r, json!(format!("the slug {} is taken", f.org))); + Ok(()) +} diff --git a/app/tests/me.rs b/app/tests/me.rs new file mode 100644 index 00000000..9ca33462 --- /dev/null +++ b/app/tests/me.rs @@ -0,0 +1,117 @@ +//! The person's own page: who they are, their organizations and invitations, their email choices, the billing email +//! (admins), and "How did you hear", which the team's sign-up email waits for. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +async fn person(name: &str, email: &str) -> laravel::Result { + create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: false }).await +} + +async fn org_with(user: &User, slug: &str, role: &str) -> laravel::Result { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let id = user.id; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {id}, {role}, 'created', now(), now())" + ) + .insert() + .await?; + Ok(org) +} + +#[laravel::test] +async fn me_shows_their_organizations_and_email_choices(app: Application) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + org_with(&ada, "acme", "admin").await?; + app.get("/api/ui/me") + .acting_as(&ada) + .await + .assert_ok() + .assert_json_path("user.name", "Ada") + .assert_json_path("organizations.0.slug", "acme") + .assert_json_path("organizations.0.role", "admin") + .assert_json_path("organizations.0.usage.plan.name", "Free") + .assert_json_path("notifications.low_credits", true) + .assert_json_path("heard_about_options.1.key", "ai_assistant") + .assert_json_path("forges", json!([])); + // Signed out, the React app (asking for JSON) gets a 401; a page would go to /login + app.get("/api/ui/me").header("accept", "application/json").await.assert_status(401); + + app.patch("/api/ui/me/notifications") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "receipts": false })) + .await + .assert_ok() + .assert_json_path("receipts", false) + .assert_json_path("low_credits", true); + Ok(()) +} + +#[laravel::test] +async fn only_admins_set_the_billing_email(app: Application) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + let bob = person("Bob", "bob@example.com").await?; + let org = org_with(&ada, "acme", "admin").await?; + let bob_id = bob.id; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {bob_id}, 'member', 'invite', now(), now())" + ) + .insert() + .await?; + let put = |who: &User, email: &str| { + app.put("/api/ui/orgs/acme/billing-email") + .acting_as(who) + .header("sec-fetch-site", "same-origin") + .json(json!({ "billing_email": email })) + }; + put(&bob, "ap@example.com").await.assert_status(403); + // Staff who aren't in it are nobody here. + let sam = create!(User { pid: laravel::str::uuid7(), name: "Sam", email: "sam@example.com", staff: true }).await?; + put(&sam, "ap@example.com").await.assert_status(404); + put(&ada, "not an address").await.assert_status(422); + put(&ada, " AP@Example.com ").await.assert_ok().assert_json_path("billing_email", "ap@example.com"); + put(&ada, "").await.assert_ok().assert_json_path("billing_email", json!(null)); + Ok(()) +} + +#[laravel::test] +async fn the_team_hears_about_a_sign_up_once_it_is_answered(app: Application) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + let id = ada.id; + db::query!("UPDATE users SET heard_about_pending = true WHERE id = {id}").update().await?; + app::auth::me::NotifySignups.dispatch().await?; + let queued = || async { + db::query!("SELECT count(*) FROM emails WHERE kind = 'new_signup' AND recipient = 'support@visualci.com'") + .scalar::() + .await + }; + assert_eq!(queued().await?, Some(0), "it waits for the answer"); + + app.post("/api/ui/me/heard-about") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "source": "ai_assistant", "detail": "Claude" })) + .await + .assert_ok(); + assert_eq!(queued().await?, Some(1)); + let data: Option = db::query!("SELECT data::text FROM emails WHERE kind = 'new_signup'").scalar().await?; + let data = data.unwrap(); + assert!(data.contains("AI assistant: Claude") && data.contains("ada@example.com"), "{data}"); + app.get("/api/ui/me").acting_as(&ada).await.assert_json_path("heard_about_pending", false); + + // Once only. + app::auth::me::NotifySignups.dispatch().await?; + assert_eq!(queued().await?, Some(1)); + Ok(()) +} diff --git a/app/tests/orgs.rs b/app/tests/orgs.rs new file mode 100644 index 00000000..cd40bce4 --- /dev/null +++ b/app/tests/orgs.rs @@ -0,0 +1,36 @@ +//! Creating an organization: its creator is its admin; slugs are checked and unique; five a day except for staff. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn the_creator_is_the_admin_and_creations_are_limited(app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let make = |slug: &str, name: &str| { + app.post("/api/ui/orgs") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "slug": slug, "name": name })) + }; + make("acme", " Acme ").await.assert_ok().assert_json_path("slug", "acme"); + let role: Option = db::query!( + "SELECT m.role FROM memberships m JOIN organizations o ON o.id = m.organization_id \ + WHERE o.slug = 'acme' AND o.name = 'Acme'" + ) + .scalar() + .await?; + assert_eq!(role.as_deref(), Some("admin")); + make("acme", "Another").await.assert_status(409); + make("api", "Reserved").await.assert_status(422); + make("Bad Slug", "x").await.assert_status(422); + make("blank", " ").await.assert_status(422); + // A new account's first organization is its own; four more today, then the limit. + for n in 2..=5 { + make(&format!("acme-{n}"), "Acme").await.assert_ok(); + } + make("acme-6", "Acme").await.assert_ok(); + make("acme-7", "Acme").await.assert_status(422); + Ok(()) +} diff --git a/app/tests/processing.rs b/app/tests/processing.rs new file mode 100644 index 00000000..37857da5 --- /dev/null +++ b/app/tests/processing.rs @@ -0,0 +1,246 @@ +//! Processing builds end to end through the CI API, against the blob store (RustFS in CI): baselines, comparisons, +//! page rows only for changes, and unchanged groups read from the build that holds them (docs/design-storage.md). + +use app::models::{Build, Snapshot, SnapshotPage}; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +async fn project_token() -> laravel::Result { + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "web").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + Ok(token) +} + +fn png(rgb: [u8; 3]) -> Vec { + let image = image::RgbaImage::from_pixel(16, 16, image::Rgba([rgb[0], rgb[1], rgb[2], 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).expect("a PNG encodes"); + bytes +} + +/// Send one build of these screenshots on commit `commit` (its parent `parent`), uploading new files, and finalize it. +async fn run(app: &Application, token: &str, commit: &str, parent: &str, shots: &[(&str, [u8; 3])]) -> Value { + let id = send(app, token, commit, parent, shots).await; + finalize(app, token, &id).await +} + +async fn finalize(app: &Application, token: &str, id: &str) -> Value { + let done = + app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", format!("Bearer {token}")).await; + done.assert_ok(); + done.json().clone() +} + +/// Create a build and send these screenshots (uploading new files), without finalizing it. Returns its id. +async fn send(app: &Application, token: &str, commit: &str, parent: &str, shots: &[(&str, [u8; 3])]) -> String { + let auth = format!("Bearer {token}"); + let build = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": commit, "branch": "main", "parent_commits": [parent] })) + .await; + build.assert_ok(); + let id = build.json()["id"].as_str().unwrap().to_string(); + let mut files = Vec::new(); + let mut snapshots = Vec::new(); + for (name, rgb) in shots { + let bytes = png(*rgb); + let sha = visualci_core::sha256_hex(&bytes); + let image = image::load_from_memory(&bytes).unwrap().to_rgba8(); + snapshots.push(json!({ + "name": name, "kind": "image", "fingerprint": visualci_core::image_hash::fingerprint_rgba(&image), + "sha256": sha, "size": bytes.len(), "content_type": "image/png" + })); + files.push(bytes); + } + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": snapshots })) + .await; + registered.assert_ok(); + let client = reqwest::Client::new(); + for (answer, bytes) in registered.json()["snapshots"].as_array().unwrap().iter().zip(files) { + if let Some(url) = answer["upload_url"].as_str() { + let put = client.put(url).header("content-type", "image/png").body(bytes).send().await.expect("an upload"); + assert!(put.status().is_success(), "uploading: {}", put.status()); + } + } + id +} + +async fn states(number: i32) -> laravel::Result> { + let build = Build::query().filter(Build::number.eq(number)).first().await?.expect("the build"); + let all = app::domain::snapshots::of_build(build.id).await?; + for s in &all { + if let Some(e) = &s.error { + eprintln!("{}: {e}", s.name); + } + } + Ok(all.into_iter().map(|s| (s.name, s.state, s.sourced)).collect()) +} + +#[laravel::test] +async fn builds_compare_with_their_baselines_and_read_unchanged_groups_from_the_build_that_holds_them( + app: Application, +) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let (red, green) = ([255, 0, 0], [0, 200, 0]); + + // #1: the first build adds both screenshots and is approved on its own. + let first = run(&app, &token, "c1", "c0", &[("home/hero/desktop.png", red), ("about/team/desktop.png", red)]).await; + let errors: Vec<(String, Option)> = + Snapshot::query().get().await?.into_iter().map(|s| (s.name, s.error)).collect(); + assert_eq!( + (first["state"].as_str(), first["review_state"].as_str()), + (Some("completed"), Some("auto_approved")), + "{first} {errors:?}" + ); + assert_eq!( + states(1).await?, + vec![ + ("about/team/desktop.png".into(), "added".into(), false), + ("home/hero/desktop.png".into(), "added".into(), false) + ] + ); + + // #2: nothing changed. Its groups are read from #1: it holds no snapshot rows of its own, and no page rows. + let second = + run(&app, &token, "c2", "c1", &[("home/hero/desktop.png", red), ("about/team/desktop.png", red)]).await; + assert_eq!(second["conclusion"], "unchanged"); + assert_eq!(second["stats"]["unchanged"], 2); + assert_eq!( + states(2).await?, + vec![ + ("about/team/desktop.png".into(), "unchanged".into(), true), + ("home/hero/desktop.png".into(), "unchanged".into(), true) + ] + ); + let two = Build::query().filter(Build::number.eq(2)).first().await?.unwrap(); + assert_eq!(Snapshot::query().filter(Snapshot::build_id.eq(two.id)).count().await?, 0, "no rows of its own"); + + // #3: the hero changed. Its group holds its own row (changed, with page rows and a diff); the other group is read + // from #1, which still holds it. + let third = + run(&app, &token, "c3", "c2", &[("home/hero/desktop.png", green), ("about/team/desktop.png", red)]).await; + assert_eq!(third["conclusion"], "changes"); + assert_eq!(third["review_state"], "pending"); + assert_eq!( + states(3).await?, + vec![ + ("about/team/desktop.png".into(), "unchanged".into(), true), + ("home/hero/desktop.png".into(), "changed".into(), false) + ] + ); + let hero = Snapshot::query() + .filter(Snapshot::name.eq("home/hero/desktop.png") & Snapshot::state.eq("changed")) + .first() + .await? + .unwrap(); + let pages = SnapshotPage::query().filter(SnapshotPage::snapshot_id.eq(hero.id)).get().await?; + assert_eq!(pages.len(), 1); + assert_eq!((pages[0].state.as_str(), pages[0].diff_id.is_some()), ("changed", true)); + Ok(()) +} + +async fn charges(number: i32) -> laravel::Result> { + let build = Build::query().filter(Build::number.eq(number)).first().await?.expect("the build"); + let id = build.id; + let rows = db::query!("SELECT amount FROM credit_transactions WHERE build_id = {id} ORDER BY id").select().await?; + Ok(rows.iter().map(|r| r.try_get::("amount").unwrap()).collect()) +} + +#[laravel::test] +async fn finalizing_twice_processes_and_charges_once(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let id = send(&app, &token, "c1", "c0", &[("home/hero/desktop.png", [255, 0, 0])]).await; + let first = finalize(&app, &token, &id).await; + let again = finalize(&app, &token, &id).await; + assert_eq!((first["state"].as_str(), again["state"].as_str()), (Some("completed"), Some("completed"))); + assert_eq!(charges(1).await?, vec![-1], "one snapshot check, charged once"); + Ok(()) +} + +#[laravel::test] +async fn shards_finalizing_at_once_process_the_build_once(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let id = send(&app, &token, "c1", "c0", &[("home/hero/desktop.png", [255, 0, 0])]).await; + let (a, b) = tokio::join!(finalize(&app, &token, &id), finalize(&app, &token, &id)); + assert_eq!((a["state"].as_str(), b["state"].as_str()), (Some("completed"), Some("completed"))); + assert_eq!(charges(1).await?, vec![-1]); + assert_eq!(states(1).await?, vec![("home/hero/desktop.png".into(), "added".into(), false)]); + Ok(()) +} + +#[laravel::test] +async fn an_organization_out_of_credits_gets_a_failed_build_that_says_why(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let org: i64 = db::query!("SELECT organization_id FROM projects LIMIT 1").scalar().await?.unwrap(); + db::query!( + "INSERT INTO credit_transactions (organization_id, amount, balance_after, kind) VALUES ({org}, -25000, 0, 'build')" + ) + .insert() + .await?; + let id = send(&app, &token, "c1", "c0", &[("home/hero/desktop.png", [255, 0, 0])]).await; + let done = finalize(&app, &token, &id).await; + assert_eq!(done["state"], "failed"); + let error = done["error"].as_str().unwrap(); + assert!(error.contains("has used this month's 25,000 credits on the Free plan"), "{error}"); + Ok(()) +} + +#[laravel::test] +async fn a_build_whose_manifest_matches_writes_no_snapshots_and_is_charged_one_group_check( + app: Application, +) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + run(&app, &token, "c1", "c0", &[("home/hero/desktop.png", [255, 0, 0]), ("about/team/desktop.png", [0, 0, 255])]) + .await; + // The client hashes the same entries the server does. + let one = Build::query().filter(Build::number.eq(1)).first().await?.unwrap(); + let entries: Vec = + app::domain::snapshots::of_build(one.id).await?.iter().map(app::domain::groups::entry_of).collect(); + let grouping = app::domain::groups::grouping(None); + let groups: Vec = visualci_core::manifest::groups(&entries, grouping) + .into_iter() + .map(|g| json!({ "key": g.key, "hash": g.hash, "count": g.count })) + .collect(); + let auth = format!("Bearer {token}"); + let build = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": "c2", "branch": "main", "parent_commits": ["c1"] })) + .await + .json() + .clone(); + let id = build["id"].as_str().unwrap().to_string(); + let checked = app + .post(format!("/api/v1/builds/{id}/groups")) + .header("authorization", &auth) + .json(json!({ "manifest_hash": visualci_core::manifest::manifest_hash(&entries), "groups": groups })) + .await; + checked.assert_ok(); + assert_eq!(checked.json()["same_as_build"], 1); + let done = finalize(&app, &token, &id).await; + assert_eq!((done["state"].as_str(), done["conclusion"].as_str()), (Some("completed"), Some("unchanged"))); + let two = Build::query().filter(Build::number.eq(2)).first().await?.unwrap(); + assert_eq!(Snapshot::query().filter(Snapshot::build_id.eq(two.id)).count().await?, 0, "no rows written"); + assert_eq!(states(2).await?.len(), 2); + assert_eq!(charges(2).await?, vec![-1], "one credit: the manifest's group check"); + Ok(()) +} diff --git a/app/tests/renderer.rs b/app/tests/renderer.rs new file mode 100644 index 00000000..6e4cb04c --- /dev/null +++ b/app/tests/renderer.rs @@ -0,0 +1,344 @@ +//! The renderer API: tokens on every route whatever the Host, claiming, uploading pages and completing a render, which +//! wakes the build waiting on it. + +use app::models::{Build, Render, Snapshot}; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::{Value, json}; + +const RENDERER: &str = "Bearer renderer-test-token"; + +async fn project_token() -> laravel::Result { + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "docs").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + Ok(token) +} + +fn png() -> Vec { + png_of([10, 20, 30, 255]) +} + +fn png_of(rgba: [u8; 4]) -> Vec { + let image = image::RgbaImage::from_pixel(8, 8, image::Rgba(rgba)); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +async fn put(url: &str, bytes: Vec, content_type: &str) { + let r = reqwest::Client::new().put(url).header("content-type", content_type).body(bytes).send().await.unwrap(); + assert!(r.status().is_success(), "uploading: {}", r.status()); +} + +#[laravel::test] +async fn every_renderer_route_needs_its_token_whatever_the_host(app: Application) -> laravel::Result<()> { + for host in ["renderer.cluster.local", "api.visualci.test", "evil.example.com"] { + app.post("/internal/renderer/claim") + .header("host", host) + .json(json!({ "renderer_version": "1" })) + .await + .assert_status(401); + app.post("/internal/renderer/renders/1/uploads") + .header("host", host) + .json(json!({ "files": [] })) + .await + .assert_status(401); + app.post("/internal/renderer/renders/1/complete") + .header("host", host) + .json(json!({ "pages": [] })) + .await + .assert_status(401); + app.get("/internal/renderer/metrics").header("host", host).await.assert_status(401); + } + // The renderer token doesn't read metrics, and the metrics token doesn't claim renders. + app.get("/internal/renderer/metrics").header("authorization", RENDERER).await.assert_status(401); + app.post("/internal/renderer/claim") + .header("authorization", "Bearer metrics-test-token") + .json(json!({ "renderer_version": "1" })) + .await + .assert_status(401); + let metrics = app.get("/internal/renderer/metrics").header("authorization", "Bearer metrics-test-token").await; + metrics.assert_ok(); + assert!(metrics.text().contains("visualci_renders_now{state=\"queued\"} 0"), "{}", metrics.text()); + assert!(metrics.text().contains("visualci_gallery_purges_failed_7d 0"), "{}", metrics.text()); + Ok(()) +} + +/// A build on main with one PDF, waiting for its render. Returns the build's id. +async fn waiting_build(app: &Application, token: &str, commit: &str) -> String { + let auth = format!("Bearer {token}"); + let build = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": commit, "branch": "main", "parent_commits": [] })) + .await + .json() + .clone(); + let id = build["id"].as_str().unwrap().to_string(); + let pdf = format!("%PDF-1.4 renderer test {id}").into_bytes(); + let sha = visualci_core::sha256_hex(&pdf); + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": [{ + "name": "invoice", "kind": "document", "fingerprint": sha, "sha256": sha, "size": pdf.len(), + "content_type": "application/pdf" + }]})) + .await + .json() + .clone(); + put(registered["snapshots"][0]["upload_url"].as_str().unwrap(), pdf, "application/pdf").await; + let waiting = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await.json().clone(); + assert_eq!(waiting["state"], "processing", "waiting for its render"); + id +} + +/// Claim the next render: its id and the claim's token. +async fn claim(app: &Application) -> (i64, String) { + let claimed = app + .post("/internal/renderer/claim") + .header("authorization", RENDERER) + .json(json!({ "renderer_version": "1" })) + .await; + claimed.assert_ok(); + let job: Value = claimed.json()["job"].clone(); + (job["id"].as_i64().unwrap(), job["token"].as_str().unwrap().to_string()) +} + +/// Ask for upload URLs for these PNGs: the answer's `upload_urls`. +async fn uploads(app: &Application, render_id: i64, claim: &str, pngs: &[&[u8]]) -> Value { + let files: Vec = pngs + .iter() + .map(|b| json!({ "sha256": visualci_core::sha256_hex(b), "size": b.len(), "content_type": "image/png" })) + .collect(); + let r = app + .post(format!("/internal/renderer/renders/{render_id}/uploads")) + .header("authorization", RENDERER) + .header("x-render-token", claim) + .json(json!({ "files": files })) + .await; + r.assert_ok(); + r.json()["upload_urls"].clone() +} + +/// A page as a renderer reports it. +fn page(png: &[u8], text: &str) -> Value { + json!({ + "image": visualci_core::sha256_hex(png), "image_fingerprint": visualci_core::image_hash::fingerprint_bytes(png).unwrap(), + "fingerprint": "f".repeat(64), "width": 8, "height": 8, "text": text, + }) +} + +async fn complete(app: &Application, render_id: i64, claim: &str, pages: Value) -> laravel::testing::TestResponse { + app.post(format!("/internal/renderer/renders/{render_id}/complete")) + .header("authorization", RENDERER) + .header("x-render-token", claim) + .json(json!({ "pages": pages })) + .await +} + +#[laravel::test] +async fn a_render_is_claimed_drawn_and_completed_and_its_build_finishes(app: Application) -> laravel::Result<()> { + Box::pin(claimed_drawn_completed(app)).await +} + +async fn claimed_drawn_completed(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + waiting_build(&app, &token, "c1").await; + + // A renderer claims it, uploads its page and completes it. + let claimed = app + .post("/internal/renderer/claim") + .header("authorization", RENDERER) + .json(json!({ "renderer_version": "1" })) + .await; + let job: Value = claimed.json()["job"].clone(); + assert_eq!((job["engine"].as_str(), job["dpi"].as_u64()), (Some("pdfbox"), Some(140))); + let (render_id, claim) = (job["id"].as_i64().unwrap(), job["token"].as_str().unwrap().to_string()); + let page_png = png(); + let page_sha = visualci_core::sha256_hex(&page_png); + // Another claim's token can't upload. + app.post(format!("/internal/renderer/renders/{render_id}/uploads")) + .header("authorization", RENDERER) + .header("x-render-token", "not-the-claim") + .json(json!({ "files": [{ "sha256": page_sha, "size": page_png.len(), "content_type": "image/png" }] })) + .await + .assert_status(401); + let urls = uploads(&app, render_id, &claim, &[&page_png]).await; + put(urls[&page_sha].as_str().unwrap(), page_png.clone(), "image/png").await; + let done = complete(&app, render_id, &claim, json!([page(&page_png, "Invoice 42")])).await; + done.assert_ok(); + assert_eq!(done.json()["state"], "done"); + + // The render keeps its text by hash, and the build that waited on it finished. + let render = Render::find_or_fail(render_id).await?; + assert_eq!(render.pages[0]["text_sha"], visualci_core::sha256_hex(b"Invoice 42")); + assert!(render.pages[0].get("text").is_none(), "{}", render.pages); + let build = Build::query().filter(Build::number.eq(1)).first().await?.unwrap(); + assert_eq!(build.state, "completed"); + let snapshot = Snapshot::query().filter(Snapshot::build_id.eq(build.id)).first().await?.unwrap(); + assert_eq!(snapshot.state, "added"); + Ok(()) +} + +/// A render whose claims all expired would stay `rendering` forever: the next claim fails it, and its build goes on. +#[laravel::test] +async fn a_render_out_of_attempts_fails_and_its_build_finishes(app: Application) -> laravel::Result<()> { + Box::pin(out_of_attempts(app)).await +} + +async fn out_of_attempts(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let build_id = waiting_build(&app, &token, "c1").await; + let (render_id, _) = claim(&app).await; + db::query!("UPDATE renders SET attempts = 3, claimed_at = now() - interval '1 hour' WHERE id = {render_id}") + .update() + .await?; + + let next = app + .post("/internal/renderer/claim") + .header("authorization", RENDERER) + .json(json!({ "renderer_version": "1" })) + .await; + assert_eq!(next.json()["job"], Value::Null, "nothing else to draw"); + let render = Render::find_or_fail(render_id).await?; + assert_eq!(render.state, "failed"); + assert_eq!(render.error.as_deref(), Some(app::domain::renders::CLAIMS_RAN_OUT)); + let pid: laravel::str::Uuid = build_id.parse().unwrap(); + let build = Build::query().filter(Build::pid.eq(pid)).first().await?.unwrap(); + assert_ne!(build.state, "processing", "the build stopped waiting"); + Ok(()) +} + +/// A claim's version must match a render's exactly: never a pattern. +#[laravel::test] +async fn a_claim_matches_the_renderer_version_exactly(app: Application) -> laravel::Result<()> { + Box::pin(version_exactly(app)).await +} + +async fn version_exactly(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + waiting_build(&app, &token, "c1").await; + for version in ["%", "_", "", "2", "pdfbox/140dpi/1"] { + let r = app + .post("/internal/renderer/claim") + .header("authorization", RENDERER) + .json(json!({ "renderer_version": version })) + .await; + assert_eq!(r.json()["job"], Value::Null, "{version:?} claims nothing"); + } + claim(&app).await; + Ok(()) +} + +/// A renderer runs untrusted PDFs, so completion trusts nothing it sends: page counts, sizes, fingerprints and text are +/// bounded, and a page image must be a PNG this render uploaded itself, never another tenant's file named by its hash. +#[laravel::test] +async fn a_completion_is_checked_before_anything_is_stored(app: Application) -> laravel::Result<()> { + Box::pin(completion_checked(app)).await +} + +async fn completion_checked(app: Application) -> laravel::Result<()> { + let store = fixtures::blob_store().await?; + let token = project_token().await?; + + // Another tenant's PNG, already stored. + let theirs = png_of([200, 1, 1, 255]); + let their_sha = store.put(theirs.clone(), "image/png").await?; + app::domain::blobs::register(&their_sha, i64::try_from(theirs.len()).unwrap(), "image/png").await?; + db::query!("UPDATE blobs SET uploaded_at = now() WHERE sha256 = {their_sha}").update().await?; + + let refused = |r: &laravel::testing::TestResponse, what: &str| { + assert_eq!(r.status().as_u16(), 400, "{what}: {}", r.text()); + }; + let mut commit = 0; + let mut fresh = async || { + commit += 1; + let c = format!("c{commit}"); + db::query!("UPDATE renders SET state = 'done' WHERE state IN ('queued', 'rendering')").update().await.unwrap(); + waiting_build(&app, &token, &c).await; + claim(&app).await + }; + + // Named without uploading it: refused, and the render fails. + let (render_id, claim_token) = fresh().await; + let r = complete(&app, render_id, &claim_token, json!([page(&theirs, "")])).await; + refused(&r, "another tenant's PNG"); + assert!(r.text().contains("wasn't uploaded for this render"), "{}", r.text()); + assert_eq!(Render::find_or_fail(render_id).await?.state, "failed"); + + // Named through the uploads, but its bytes never sent to the proof key: the render fails. + let (render_id, claim_token) = fresh().await; + let urls = uploads(&app, render_id, &claim_token, &[&theirs]).await; + assert!(urls[&their_sha].as_str().unwrap().contains(&format!("proofs/{render_id}/")), "{urls}"); + let r = complete(&app, render_id, &claim_token, json!([page(&theirs, "")])).await; + r.assert_ok(); + assert_eq!(r.json()["state"], "failed"); + + // Drawn for real (the same PNG, uploaded to the proof key): done. The proof URL takes exactly the declared size. + let (render_id, claim_token) = fresh().await; + let urls = uploads(&app, render_id, &claim_token, &[&theirs]).await; + let mut larger = theirs.clone(); + larger.extend_from_slice(&[0; 1024]); + let refused_upload = reqwest::Client::new() + .put(urls[&their_sha].as_str().unwrap()) + .header("content-type", "image/png") + .body(larger) + .send() + .await + .unwrap(); + assert!(!refused_upload.status().is_success(), "a larger body is refused: {}", refused_upload.status()); + put(urls[&their_sha].as_str().unwrap(), theirs.clone(), "image/png").await; + let r = complete(&app, render_id, &claim_token, json!([page(&theirs, "")])).await; + assert_eq!(r.json()["state"], "done", "{}", r.text()); + + // Bounds: pages, size, fingerprints, text. + let mine = png_of([1, 2, 200, 255]); + let mut bad: Vec<(&str, Value)> = Vec::new(); + bad.push(("too many pages", Value::Array(vec![page(&mine, ""); 2001]))); + let mut wide = page(&mine, ""); + wide["width"] = json!(1_000_000); + bad.push(("a page too wide", json!([wide]))); + let mut zero = page(&mine, ""); + zero["height"] = json!(0); + bad.push(("a page with no height", json!([zero]))); + let mut fingerprint = page(&mine, ""); + fingerprint["fingerprint"] = json!("../../not-hex"); + bad.push(("a fingerprint that isn't hex", json!([fingerprint]))); + bad.push(("too much text", json!([page(&mine, &"x".repeat(300 * 1024))]))); + for (what, pages) in bad { + let (render_id, claim_token) = fresh().await; + let urls = uploads(&app, render_id, &claim_token, &[&mine]).await; + if let Some(url) = urls[visualci_core::sha256_hex(&mine)].as_str() { + put(url, mine.clone(), "image/png").await; + } + let r = complete(&app, render_id, &claim_token, pages).await; + refused(&r, what); + assert_eq!(Render::find_or_fail(render_id).await?.state, "failed", "{what}"); + } + + // More than 5,000 upload entries are refused, not cut short. + let (render_id, claim_token) = fresh().await; + let files: Vec = + (0..5001).map(|i| json!({ "sha256": format!("{i:064x}"), "size": 1, "content_type": "image/png" })).collect(); + let r = app + .post(format!("/internal/renderer/renders/{render_id}/uploads")) + .header("authorization", RENDERER) + .header("x-render-token", &claim_token) + .json(json!({ "files": files })) + .await; + refused(&r, "5,001 uploads"); + Ok(()) +} diff --git a/app/tests/retention.rs b/app/tests/retention.rs new file mode 100644 index 00000000..df9f962b --- /dev/null +++ b/app/tests/retention.rs @@ -0,0 +1,345 @@ +//! Retention and expiry: what retention keeps (the builds a kept build reads groups from, referenced texts, recent +//! texts) and deletes, and the scheduled `builds:expire` and `retention:prune` commands. + +use app::domain::retention; +use app::models::{Blob, Build, Snapshot}; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; +use serde_json::json; + +fn png(rgb: [u8; 3]) -> Vec { + let img = image::RgbImage::from_pixel(8, 6, image::Rgb(rgb)); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() +} + +async fn project_token() -> laravel::Result { + let org = fixtures::organization(&format!("org-{}", &laravel::str::uuid7().simple().to_string()[24..])).await?; + let project = fixtures::project(&org, "web").await?; + let token = format!("vci_{}", laravel::str::uuid7().simple()); + let (hash, project_id) = (app::models::token_hash(&token), project.id); + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({project_id}, 'CI', {hash}, 'vci_ab', now(), now())" + ) + .insert() + .await?; + Ok(token) +} + +/// A finished build of one image, on its own branch. +async fn build(app: &Application, token: &str, branch: &str, rgb: [u8; 3]) -> Build { + Box::pin(build_inner(app, token, branch, rgb)).await +} + +async fn build_inner(app: &Application, token: &str, branch: &str, rgb: [u8; 3]) -> Build { + let auth = format!("Bearer {token}"); + let created = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": &visualci_core::sha256_hex(branch.as_bytes())[..40], "branch": branch, "parent_commits": [] })) + .await; + created.assert_ok(); + let id = created.json()["id"].as_str().unwrap().to_string(); + let bytes = png(rgb); + let sha = visualci_core::sha256_hex(&bytes); + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": [{ + "name": "web/home", "kind": "image", "sha256": sha, "size": bytes.len(), "content_type": "image/png", + "fingerprint": visualci_core::image_hash::fingerprint_bytes(&bytes).unwrap(), + }]})) + .await; + registered.assert_ok(); + if let Some(url) = registered.json()["snapshots"][0]["upload_url"].as_str() { + reqwest::Client::new().put(url).header("content-type", "image/png").body(bytes).send().await.unwrap(); + } + let done = app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", &auth).await; + assert_eq!(done.json()["state"], "completed", "{}", done.text()); + let pid: laravel::str::Uuid = id.parse().unwrap(); + Build::query().filter(Build::pid.eq(pid)).first().await.unwrap().unwrap() +} + +/// Make a build and its blobs older than the retention window, and nothing anyone needs: off the default branch, no +/// base, no baselines. +async fn age(build: &Build) -> laravel::Result<()> { + let (id, project_id) = (build.id, build.project_id); + db::query!( + "UPDATE builds SET created_at = now() - interval '200 days', completed_at = now() - interval '200 days', \ + base_build_id = NULL WHERE id = {id}" + ) + .update() + .await?; + db::query!( + "UPDATE blobs SET created_at = now() - interval '200 days', updated_at = now() - interval '200 days' \ + WHERE sha256 IN (SELECT source_blob FROM snapshots WHERE build_id = {id})" + ) + .update() + .await?; + db::query!("UPDATE snapshots SET updated_at = now() - interval '200 days' WHERE build_id = {id}").update().await?; + db::query!("DELETE FROM baselines WHERE project_id = {project_id}").delete().await?; + Ok(()) +} + +async fn blob_of(build: &Build) -> Option { + let snapshot = Snapshot::query().filter(Snapshot::build_id.eq(build.id)).first().await.unwrap().unwrap(); + let sha = snapshot.source_blob?; + Blob::query().filter(Blob::sha256.eq(sha)).first().await.unwrap() +} + +#[laravel::test] +async fn retention_keeps_the_builds_a_kept_build_reads_groups_from(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let holder = build(&app, &token, "old-holder", [255, 0, 0]).await; + let forgotten = build(&app, &token, "old-forgotten", [0, 0, 255]).await; + let reader = build(&app, &token, "recent", [0, 255, 0]).await; + age(&holder).await?; + age(&forgotten).await?; + // The recent build reads a group from the old one: the old build's rows are its unchanged snapshots. + let (reader_id, holder_id) = (reader.id, holder.id); + let key: String = + db::query!("SELECT group_key FROM snapshots WHERE build_id = {holder_id}").scalar().await?.unwrap(); + db::query!( + "INSERT INTO build_groups (build_id, key, hash, snapshot_count, source_build_id) \ + VALUES ({reader_id}, {key}, 'h', 1, {holder_id})" + ) + .insert() + .await?; + let read = |id: i64| async move { + db::query!("SELECT COUNT(*) FROM effective_snapshots WHERE build_id = {id} AND sourced").scalar::().await + }; + assert_eq!(read(reader_id).await?, Some(1), "the reader reads the holder's row"); + + let counted = retention::prune(None, retention::RETENTION_DAYS, true).await?; + assert!(blob_of(&forgotten).await.is_some(), "a dry run deletes nothing"); + assert!(counted.blobs >= 1, "{counted}"); + + retention::prune(None, retention::RETENTION_DAYS, false).await?; + assert!(blob_of(&holder).await.is_some(), "the source build's image stays"); + assert!(blob_of(&reader).await.is_some(), "the recent build's image stays"); + assert!(blob_of(&forgotten).await.is_none(), "an old build nothing reads loses its image"); + // The holder's rows stay, so the reader still reads its group, and no group resolves to no rows. + assert_eq!(read(reader_id).await?, Some(1), "the reader still reads the holder's row"); + assert!(retention::empty_groups().await?.is_empty()); + Ok(()) +} + +#[laravel::test] +async fn retention_deletes_only_unreferenced_texts_older_than_a_day(_app: Application) -> laravel::Result<()> { + let texts = ["referenced by a render", "old and unreferenced", "new and unreferenced"] + .map(|t| (visualci_core::sha256_hex(t.as_bytes()), t)); + for (i, (sha, body)) in texts.iter().enumerate() { + let body: &str = body; + let hours = if i == 2 { 1 } else { 48 }; + db::query!( + "INSERT INTO texts (sha256, body, created_at) VALUES ({sha}, {body}, now() - make_interval(hours => {hours}))" + ) + .insert() + .await?; + } + // A render from today names the first text on its page. + let pages = json!([{ "image": "", "fingerprint": "f", "width": 1, "height": 1, "text_sha": texts[0].0 }]); + let source = "a".repeat(64); + db::query!("INSERT INTO blobs (sha256, size, content_type) VALUES ({source}, 1, 'application/pdf')") + .insert() + .await?; + db::query!( + "INSERT INTO renders (source_fingerprint, renderer, source_blob, state, pages) \ + VALUES ('fp', 'pdfbox/140dpi/1', {source}, 'done', {pages})" + ) + .insert() + .await?; + + let report = retention::prune(None, retention::RETENTION_DAYS, false).await?; + let left: Vec = db::query!("SELECT body FROM texts ORDER BY body") + .select() + .await? + .iter() + .filter_map(|r| r.try_get::("body").ok()) + .collect(); + assert_eq!(left, ["new and unreferenced", "referenced by a render"]); + assert_eq!(report.texts, 1, "{report}"); + Ok(()) +} + +#[laravel::test] +async fn the_nightly_check_finds_groups_that_resolve_to_no_rows(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let holder = build(&app, &token, "holder", [1, 2, 3]).await; + let reader = build(&app, &token, "reader", [4, 5, 6]).await; + app.command("groups:check").await.assert_successful(); + + // A group the reader reads from the holder under a key the holder has no rows for. + let (reader_id, holder_id) = (reader.id, holder.id); + db::query!( + "INSERT INTO build_groups (build_id, key, hash, snapshot_count, source_build_id) \ + VALUES ({reader_id}, 'gone/', 'h', 1, {holder_id})" + ) + .insert() + .await?; + assert_eq!(retention::empty_groups().await?, vec![(reader_id, "gone/".to_string())]); + app.command("groups:check").await.assert_failed().assert_error_output_contains("1 groups resolve to no rows"); + assert_eq!(app.get("/status").await.json()["empty_groups"], 1, "and /status counts it"); + + // Retention's command: a dry run counts, and fewer than 30 days is refused. + app.command("retention:prune --dry-run").await.assert_successful().assert_output_contains("would delete"); + app.command("retention:prune --days 7").await.assert_failed(); + Ok(()) +} + +/// A build registering snapshots while a prune runs isn't in the prune's keep sets: what a snapshot touched in the last +/// day names stays, its file and its render alike. +#[laravel::test] +async fn retention_keeps_what_a_snapshot_registered_now_names(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + let old = build(&app, &token, "old", [10, 20, 30]).await; + age(&old).await?; + // The same file, just registered again by a build the keep sets don't know about yet (here: the old build's own + // row, touched now). + let id = old.id; + db::query!("UPDATE snapshots SET updated_at = now() WHERE build_id = {id}").update().await?; + retention::prune(None, retention::RETENTION_DAYS, false).await?; + let snapshot = Snapshot::query().filter(Snapshot::build_id.eq(id)).first().await?.expect("the snapshot"); + assert!(snapshot.source_blob.is_some(), "its file is still named"); + assert!(blob_of(&old).await.is_some(), "and still there"); + Ok(()) +} + +/// A file a new build registers while a prune has it marked for deletion keeps its row, and the build is asked to +/// upload it again: the prune deletes only rows still marked, and never what a new snapshot names. +#[laravel::test] +async fn a_blob_registered_again_while_marked_is_uploaded_again_and_kept(app: Application) -> laravel::Result<()> { + Box::pin(registered_while_marked(app)).await +} + +async fn registered_while_marked(app: Application) -> laravel::Result<()> { + let store = fixtures::blob_store().await?; + let token = project_token().await?; + let old = build(&app, &token, "old", [9, 9, 9]).await; + age(&old).await?; + let sha = visualci_core::sha256_hex(&png([9, 9, 9])); + // The prune's first step: marked for deletion. + db::query!("UPDATE blobs SET deleting = true WHERE sha256 = {sha}").update().await?; + + // A new build registers the same file: the mark goes, and the build is asked to upload it again. + let auth = format!("Bearer {token}"); + let created = app + .post("/api/v1/builds") + .header("authorization", &auth) + .json(json!({ "commit": "0123456789abcdef", "branch": "again", "parent_commits": [] })) + .await; + let id = created.json()["id"].as_str().unwrap().to_string(); + let bytes = png([9, 9, 9]); + let registered = app + .post(format!("/api/v1/builds/{id}/snapshots")) + .header("authorization", &auth) + .json(json!({ "snapshots": [{ + "name": "web/home", "kind": "image", "sha256": sha, "size": bytes.len(), "content_type": "image/png", + "fingerprint": visualci_core::image_hash::fingerprint_bytes(&bytes).unwrap(), + }]})) + .await; + registered.assert_ok(); + assert!(registered.json()["snapshots"][0]["upload_url"].is_string(), "uploaded again: {}", registered.text()); + let blob = Blob::query().filter(Blob::sha256.eq(sha.clone())).first().await?.unwrap(); + assert!(!blob.deleting && blob.uploaded_at.is_none(), "the mark is gone, and the file is awaited"); + + // The prune leaves it: a new snapshot names it, and it's no longer marked. + retention::prune(Some(&store), retention::RETENTION_DAYS, false).await?; + assert!(Blob::query().filter(Blob::sha256.eq(sha.clone())).first().await?.is_some(), "the row stays"); + assert!(store.exists(&sha).await?, "and the object"); + Ok(()) +} + +/// A prune works through more than one batch, each in its own transaction. +#[laravel::test] +async fn a_prune_deletes_in_batches(_app: Application) -> laravel::Result<()> { + let n = i64::try_from(retention::BATCH).unwrap() + 5; + db::query!( + "INSERT INTO blobs (sha256, size, content_type, created_at, updated_at) \ + SELECT encode(sha256(i::text::bytea), 'hex'), 1, 'image/png', now() - interval '200 days', \ + now() - interval '200 days' \ + FROM generate_series(1, {n}) i" + ) + .insert() + .await?; + let counted = retention::prune(None, retention::RETENTION_DAYS, true).await?; + assert_eq!(counted.blobs, u64::try_from(n).unwrap(), "{counted}"); + let report = retention::prune(None, retention::RETENTION_DAYS, false).await?; + assert_eq!(report.blobs, u64::try_from(n).unwrap(), "{report}"); + let left: Option = db::query!("SELECT COUNT(*) FROM blobs").scalar().await?; + assert_eq!(left, Some(0)); + Ok(()) +} + +/// An old blob, unnamed by any kept build: `n` picks its hash. +async fn old_blob(n: u32) -> laravel::Result { + let sha = visualci_core::sha256_hex(format!("old blob {n}").as_bytes()); + db::query!( + "INSERT INTO blobs (sha256, size, content_type, created_at, updated_at) \ + VALUES ({sha}, 1, 'image/png', now() - interval '200 days', now() - interval '200 days')" + ) + .insert() + .await?; + Ok(sha) +} + +/// A cached diff a comparison reused in the last day keeps its overlay (the build reusing it isn't in the keep sets); +/// one nobody reused loses it. +#[laravel::test] +async fn a_recently_reused_diff_keeps_its_overlay(_app: Application) -> laravel::Result<()> { + let (used, unused) = (old_blob(1).await?, old_blob(2).await?); + for (n, overlay, used_at) in [(1, &used, "now()"), (2, &unused, "NULL")] { + let (base, head) = (format!("base{n}"), format!("head{n}")); + let recent = used_at == "now()"; + db::query!( + "INSERT INTO diffs (base_image, head_image, options_key, changed_pixels, changed_fraction, size_changed, \ + result, overlay_blob, used_at) \ + VALUES ({base}, {head}, 'k', 1, 0.1, false, '{{}}', {overlay}, CASE WHEN {recent} THEN now() END)" + ) + .insert() + .await?; + } + retention::prune(None, retention::RETENTION_DAYS, false).await?; + let overlays: Vec> = db::query!("SELECT overlay_blob FROM diffs ORDER BY base_image") + .select() + .await? + .iter() + .map(|r| r.try_get::>("overlay_blob").unwrap()) + .collect(); + assert_eq!(overlays, [Some(used.clone()), None]); + assert!(Blob::query().filter(Blob::sha256.eq(used)).first().await?.is_some(), "the reused overlay stays"); + assert!(Blob::query().filter(Blob::sha256.eq(unused)).first().await?.is_none(), "the other goes"); + Ok(()) +} + +/// No mark outlives its run: a mark a stopped run left behind is cleared, and so is one on a blob that turns out to be +/// kept; a blob registered in the last day isn't marked at all. +#[laravel::test] +async fn no_deleting_mark_outlives_its_prune(app: Application) -> laravel::Result<()> { + Box::pin(no_mark_outlives(app)).await +} + +async fn no_mark_outlives(app: Application) -> laravel::Result<()> { + fixtures::blob_store().await?; + let token = project_token().await?; + // A kept build's blob, marked by a run that stopped. + let kept = build(&app, &token, "kept", [7, 7, 7]).await; + let kept_sha = blob_of(&kept).await.unwrap().sha256; + db::query!("UPDATE blobs SET deleting = true WHERE sha256 = {kept_sha}").update().await?; + // An old blob a client registered just now (the snapshot naming it not yet committed). + let registered = old_blob(3).await?; + app::domain::blobs::register(®istered, 1, "image/png").await?; + + retention::prune(None, retention::RETENTION_DAYS, false).await?; + let marked: Option = db::query!("SELECT COUNT(*) FROM blobs WHERE deleting").scalar().await?; + assert_eq!(marked, Some(0), "no mark left"); + assert!(blob_of(&kept).await.is_some_and(|b| b.uploaded_at.is_some()), "the kept blob is still uploaded"); + assert!(Blob::query().filter(Blob::sha256.eq(registered)).first().await?.is_some(), "registered just now: kept"); + Ok(()) +} diff --git a/app/tests/setup.rs b/app/tests/setup.rs new file mode 100644 index 00000000..16814712 --- /dev/null +++ b/app/tests/setup.rs @@ -0,0 +1,56 @@ +//! The setup checklist ticks itself from what happened, and an organization's admins can close it. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn the_checklist_follows_what_happened(app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'admin', 'created', now(), now())" + ) + .insert() + .await?; + let state = app::auth::setup::state(org, Some(ada.pid)).await?; + assert_eq!(state["next"], "connect_agent"); + // A used personal token ticks it for her; nobody's (a project token's view) never does + db::query!( + "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, last_used_at, created_at, updated_at) \ + VALUES ({ada_id}, 'laptop', 'h', 'vcu_abcdef', now(), now(), now())" + ) + .insert() + .await?; + assert_eq!(app::auth::setup::state(org, Some(ada.pid)).await?["steps"][0]["done"], true); + assert_eq!(app::auth::setup::state(org, None).await?["steps"][0]["done"], false); + db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge_installation, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, 'web', 'Web', '7', now(), now())" + ) + .insert() + .await?; + let state = app::auth::setup::state(org, Some(ada.pid)).await?; + assert_eq!(state["steps"][1]["done"], true); + assert_eq!(state["steps"][2]["done"], true); + assert_eq!(state["complete"], false); + + let close = |dismissed: bool| { + app.post("/api/ui/orgs/acme/setup") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "dismissed": dismissed })) + }; + close(true).await.assert_ok().assert_json_path("dismissed", true); + close(false).await.assert_ok().assert_json_path("dismissed", false); + Ok(()) +} diff --git a/app/tests/staff.rs b/app/tests/staff.rs new file mode 100644 index 00000000..11ee277b --- /dev/null +++ b/app/tests/staff.rs @@ -0,0 +1,49 @@ +//! Staff pages: the latest sign-ups, every email rendered, failed emails retried or dismissed; a 404 for anyone else. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn staff_see_sign_ups_and_emails_and_resolve_failures(app: Application) -> laravel::Result<()> { + let grace = + create!(User { pid: laravel::str::uuid7(), name: "Grace", email: "grace@example.com", staff: true }).await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "UPDATE users SET heard_about_source = 'ai_assistant', heard_about_detail = 'Claude' WHERE id = {ada_id}" + ) + .update() + .await?; + for path in ["/api/ui/staff/signups", "/api/ui/staff/emails"] { + app.get(path).acting_as(&ada).await.assert_status(404); + } + app.get("/api/ui/staff/signups") + .acting_as(&grace) + .await + .assert_ok() + .assert_json_path("signups.0.name", "Ada") + .assert_json_path("signups.0.heard_about", "AI assistant: Claude"); + + let failed: i64 = db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data, state, attempts, last_error) \ + VALUES ('welcome', 'w:1', 'ada@example.com', '[]', 'failed', 5, 'Postmark: HTTP 422') RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let page = app.get("/api/ui/staff/emails").acting_as(&grace).await; + page.assert_ok().assert_json_path("failed.0.id", failed).assert_json_path("emails.0.kind", "credits_low"); + let resolve = |who: &User, action: &str| { + app.post(format!("/api/ui/staff/emails/{failed}/resolve")) + .acting_as(who) + .header("sec-fetch-site", "same-origin") + .json(json!({ "action": action })) + }; + resolve(&ada, "dismiss").await.assert_status(404); + resolve(&grace, "dismiss").await.assert_ok(); + resolve(&grace, "dismiss").await.assert_status(404); + app.get("/api/ui/staff/emails").acting_as(&grace).await.assert_json_path("failed", json!([])); + Ok(()) +} diff --git a/app/tests/sweep.rs b/app/tests/sweep.rs new file mode 100644 index 00000000..4c6b945b --- /dev/null +++ b/app/tests/sweep.rs @@ -0,0 +1,80 @@ +//! The builds sweep (every five minutes): abandoned builds expire, idle local builds close, builds that stopped +//! progressing run again, and builds stuck for hours fail. `/status` reports how far behind the background work is. + +use app::domain::builds::{self, CreateParams}; +use app::domain::processing::{self, ABANDONED, LOCAL_IDLE, STUCK}; +use app::models::Build; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; + +async fn build(project: &app::models::Project, commit: &str, mode: &str) -> laravel::Result { + let params: CreateParams = + serde_json::from_value(serde_json::json!({ "commit": commit, "branch": "main", "mode": mode }))?; + let build = builds::create(project, ¶ms, None).await.map_err(|e| laravel::Error::msg(format!("{e:?}")))?; + Ok(build.id) +} + +#[laravel::test] +async fn the_sweep_expires_closes_restarts_and_gives_up(app: Application) -> laravel::Result<()> { + let org = fixtures::organization("acme").await?; + let project = fixtures::project(&org, "docs").await?; + let abandoned = build(&project, "a1", "ci").await?; + let idle_local = build(&project, "a2", "local").await?; + let stuck = build(&project, "a3", "ci").await?; + let slow = build(&project, "a4", "ci").await?; + let fresh = build(&project, "a5", "ci").await?; + db::query!( + "UPDATE builds SET updated_at = now() - interval '2 hours', created_at = now() - interval '2 hours' \ + WHERE id = {abandoned}" + ) + .update() + .await?; + db::query!( + "UPDATE builds SET state = 'completed', review_state = 'pending', updated_at = now() - interval '8 days', \ + created_at = now() - interval '8 days' WHERE id = {idle_local}" + ) + .update() + .await?; + db::query!( + "UPDATE builds SET state = 'processing', finalized_at = now() - interval '7 hours', \ + updated_at = now() - interval '7 hours' WHERE id = {stuck}" + ) + .update() + .await?; + db::query!( + "UPDATE builds SET state = 'processing', finalized_at = now() - interval '20 minutes', \ + updated_at = now() - interval '20 minutes' WHERE id = {slow}" + ) + .update() + .await?; + + let status = app.get("/status").await; + status.assert_ok(); + let status = status.json().clone(); + assert!(status["oldest_processing_seconds"].as_i64().unwrap() >= 7 * 3600, "{status}"); + assert!(status["oldest_receiving_seconds"].as_i64().unwrap() >= 2 * 3600, "{status}"); + assert_eq!(status["builds_processing"], 2); + assert_eq!(status["oldest_forge_sync_seconds"], 0, "no forge memberships: {status}"); + + let swept = processing::sweep().await?; + assert_eq!(swept.expired, 1); + assert_eq!(swept.idle_local_closed, 1); + assert_eq!(swept.stuck_failed, 1); + assert_eq!(swept.restarted, 1, "{swept:?}"); + + let b = Build::find_or_fail(abandoned).await?; + assert_eq!((b.state.as_str(), b.error.as_deref()), ("failed", Some(ABANDONED))); + let b = Build::find_or_fail(idle_local).await?; + assert_eq!(b.review_state, "closed"); + assert_eq!(b.warnings, serde_json::json!([LOCAL_IDLE])); + let b = Build::find_or_fail(stuck).await?; + assert_eq!((b.state.as_str(), b.error.as_deref()), ("failed", Some(STUCK))); + // Run again (the test queue runs it at once): an empty build concludes. + assert_ne!(Build::find_or_fail(slow).await?.state, "processing"); + assert_eq!(Build::find_or_fail(fresh).await?.state, "receiving", "a build still arriving is left alone"); + + let again = processing::sweep().await?; + assert_eq!(again, processing::Swept::default(), "a second sweep finds nothing"); + Ok(()) +} diff --git a/app/tests/tokens.rs b/app/tests/tokens.rs new file mode 100644 index 00000000..bf454a6a --- /dev/null +++ b/app/tests/tokens.rs @@ -0,0 +1,81 @@ +//! Tokens in the web app: a personal token works as its person until deleted; a project's admin makes its tokens, +//! a member can't; making one emails a notice. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +async fn person(email: &str) -> laravel::Result { + create!(User { pid: laravel::str::uuid7(), name: "Ada", email: email, staff: false }).await +} + +#[laravel::test] +async fn a_personal_token_works_until_it_is_deleted(app: Application) -> laravel::Result<()> { + let ada = person("ada@example.com").await?; + let made = app + .post("/api/ui/me/tokens") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "name": "laptop" })) + .await; + made.assert_ok(); + let token = made.json()["token"].as_str().unwrap().to_string(); + assert!(token.starts_with("vcu_") && token.len() == 44); + app.get("/api/v1/whoami") + .header("authorization", format!("Bearer {token}")) + .await + .assert_ok() + .assert_json_path("client.token_name", "laptop"); + let list = app.get("/api/ui/me/tokens").acting_as(&ada).await; + list.assert_ok().assert_json_path("tokens.0.name", "laptop").assert_json_path("tokens.0.prefix", &token[..10]); + let id = list.json()["tokens"][0]["id"].as_i64().unwrap(); + app.delete(format!("/api/ui/me/tokens/{id}")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok(); + app.get("/api/v1/whoami").header("authorization", format!("Bearer {token}")).await.assert_status(401); + let notices: Option = db::query!("SELECT count(*) FROM emails WHERE kind = 'token_created'").scalar().await?; + assert_eq!(notices, Some(1)); + Ok(()) +} + +#[laravel::test] +async fn only_a_projects_admins_make_its_tokens(app: Application) -> laravel::Result<()> { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, created_at, updated_at) VALUES (gen_random_uuid(), {org}, 'web', 'Web', now(), now())" + ) + .insert() + .await?; + let admin = person("admin@example.com").await?; + let member = person("member@example.com").await?; + for (u, role) in [(admin.id, "admin"), (member.id, "member")] { + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) VALUES ({org}, {u}, {role}, 'created', now(), now())" + ) + .insert() + .await?; + } + let make = |u: &User| { + app.post("/api/ui/orgs/acme/projects/web/tokens") + .acting_as(u) + .header("sec-fetch-site", "same-origin") + .json(json!({ "name": "CI" })) + }; + make(&member).await.assert_status(403); + let token = make(&admin).await.json()["token"].as_str().unwrap().to_string(); + assert!(token.starts_with("vci_")); + app.get("/api/v1/whoami") + .header("authorization", format!("Bearer {token}")) + .await + .assert_ok() + .assert_json_path("principal.kind", "project"); + Ok(()) +} diff --git a/app/tests/webhooks.rs b/app/tests/webhooks.rs new file mode 100644 index 00000000..27974837 --- /dev/null +++ b/app/tests/webhooks.rs @@ -0,0 +1,258 @@ +//! GitHub's webhook: signed deliveries only; merges and closed branches go to the domain once per linked project (by +//! GitHub's repository ID, else URL); installations attach to and detach from linked projects; membership changes +//! queue a recheck of the people they name. + +use app::forge::events::{BranchClosed, PullRequestMerged}; +use app::forge::webhooks::RecheckAccess; +use app::models::User; +use hmac::{Hmac, Mac}; +use laravel::db; +use laravel::model::create; +use laravel::testing::TestResponse; +use laravel::testing::prelude::*; +use sha2::Sha256; + +const SECRET: &str = "github-webhook-test"; + +/// A GitHub App key made once per run (base64 of its PEM, as GITHUB_APP_PRIVATE_KEY_BASE64 holds it). +fn app_key() -> &'static str { + static KEY: std::sync::OnceLock = std::sync::OnceLock::new(); + KEY.get_or_init(|| { + use base64::Engine; + use rsa::pkcs1::EncodeRsaPrivateKey; + let key = rsa::RsaPrivateKey::new(&mut rsa::rand_core::OsRng, 2048).expect("a key"); + let pem = key.to_pkcs1_pem(rsa::pkcs1::LineEnding::LF).expect("its PEM"); + base64::engine::general_purpose::STANDARD.encode(pem.as_bytes()) + }) +} + +fn github() -> Application { + app::testing::configure() + .with_envs([ + ("GITHUB_WEBHOOK_SECRET", SECRET), + ("GITHUB_APP_ID", "1"), + ("GITHUB_APP_PRIVATE_KEY_BASE64", app_key()), + ]) + .create() +} + +fn github_app() -> app::forge::github_app::GithubApp { + app::forge::github_app::GithubApp { + app_id: Some("1".into()), + private_key_base64: Some(app_key().into()), + webhook_secret: None, + } +} + +async fn deliver(app: &Application, kind: &str, event: serde_json::Value) -> TestResponse { + let body = event.to_string(); + let mut mac = Hmac::::new_from_slice(SECRET.as_bytes()).unwrap(); + mac.update(body.as_bytes()); + let signature = format!("sha256={}", hex::encode(mac.finalize().into_bytes())); + app.post("/webhooks/github") + .header("x-github-event", kind) + .header("x-github-delivery", "d-1") + .header("x-hub-signature-256", signature) + .header("content-type", "application/json") + .body(body) + .await +} + +/// Two organizations' projects linking acme/web: one by GitHub's repository ID, one by URL only. +async fn linked() -> laravel::Result<(i64, i64, i64)> { + let mut ids = Vec::new(); + for (slug, repository_id) in [("acme", Some("42")), ("other", None)] { + let org: i64 = db::query!( + "INSERT INTO organizations (pid, slug, name, created_at, updated_at) \ + VALUES (gen_random_uuid(), {slug}, {slug}, now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let project: i64 = db::query!( + "INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \ + forge_installation, created_at, updated_at) \ + VALUES (gen_random_uuid(), {org}, 'web', 'Web', 'github', 'https://github.com/acme/web', {repository_id}, \ + '7', now(), now()) RETURNING id" + ) + .scalar() + .await? + .unwrap(); + ids.push((org, project)); + } + Ok((ids[0].0, ids[0].1, ids[1].1)) +} + +fn repository() -> serde_json::Value { + json!({ "id": 42, "full_name": "acme/web" }) +} + +#[laravel::test(app = github)] +async fn an_unsigned_delivery_is_refused(app: Application) { + app.post("/webhooks/github") + .header("x-github-event", "ping") + .header("x-hub-signature-256", "sha256=00") + .json(json!({})) + .await + .assert_status(401); +} + +#[laravel::test(app = github)] +async fn a_merge_and_a_deleted_branch_reach_each_linked_project(app: Application) -> laravel::Result<()> { + let (_, by_id, by_url) = linked().await?; + let events = laravel::event::fake(); + let merged = json!({ + "action": "closed", "repository": repository(), + "pull_request": { "merged": true, "merge_commit_sha": "abc123", "base": { "ref": "main" }, + "head": { "ref": "feature", "repo": { "full_name": "acme/web" } } }, + }); + deliver(&app, "pull_request", merged).await.assert_ok().assert_json_path("dispatched", 2); + events.assert_dispatched_times::(2); + events.assert_dispatched_where::(|e| { + e.project_id == by_id && e.head == "feature" && e.base == "main" && e.merge_commit == "abc123" + }); + events.assert_dispatched_where::(|e| e.project_id == by_url); + + // A fork's branch goes by its label + let fork = json!({ + "action": "closed", "repository": repository(), + "pull_request": { "merged": false, "head": { "ref": "main", "label": "octocat:main", + "repo": { "full_name": "octocat/web" } } }, + }); + deliver(&app, "pull_request", fork).await.assert_ok(); + events.assert_dispatched_where::(|e| e.branch == "octocat:main" && e.why == "pull_request"); + let deleted = json!({ "ref": "old", "ref_type": "branch", "repository": repository() }); + deliver(&app, "delete", deleted).await.assert_ok(); + events.assert_dispatched_where::(|e| e.branch == "old" && e.why == "branch_deleted"); + Ok(()) +} + +#[laravel::test(app = github)] +async fn installations_attach_and_detach_and_membership_changes_recheck(app: Application) -> laravel::Result<()> { + let (org, by_id, _) = linked().await?; + let jobs = laravel::queue::fake(); + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/8", json!({ "id": 8 })) + .with("api.github.com/app/installations/*", laravel::http::client::response().status(404).json(json!({}))); + // A stale "created" for an installation that's gone attaches nothing + let stale = json!({ "action": "created", "installation": { "id": 5 }, "repositories": [repository()] }); + deliver(&app, "installation", stale).await.assert_ok().assert_json_path("ignored", "no such installation"); + let installation = |id: i64| async move { + db::query!("SELECT forge_installation FROM projects WHERE id = {id}").scalar::>().await + }; + // Removing another installation leaves the project's own alone + let other = json!({ "action": "deleted", "installation": { "id": 9 }, "repositories": [repository()] }); + deliver(&app, "installation", other).await.assert_ok().assert_json_path("unlinked", 0); + assert_eq!(installation(by_id).await?.flatten().as_deref(), Some("7")); + let removed = json!({ "action": "removed", "installation": { "id": 7 }, "repositories_removed": [repository()] }); + deliver(&app, "installation_repositories", removed).await.assert_ok().assert_json_path("unlinked", 2); + assert_eq!(installation(by_id).await?.flatten(), None); + let added = json!({ "action": "added", "installation": { "id": 8 }, "repositories_added": [repository()] }); + deliver(&app, "installation_repositories", added).await.assert_ok().assert_json_path("linked", 2); + assert_eq!(installation(by_id).await?.flatten().as_deref(), Some("8")); + + // A collaborator changed: the person with that GitHub ID is rechecked + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'member', 'github', now(), now())" + ) + .insert() + .await?; + let member = json!({ "action": "removed", "member": { "id": 1001 }, "repository": repository() }); + deliver(&app, "member", member).await.assert_ok().assert_json_path("rechecking", 1); + assert!(jobs.pushed::().iter().any(|j| j.job().user_ids == vec![ada_id])); + Ok(()) +} + +#[laravel::test(app = github)] +async fn a_recheck_reads_each_repositorys_collaborators_once(_app: Application) -> laravel::Result<()> { + let (org, _, _) = linked().await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + let github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) + .with( + "api.github.com/repos/acme/web/collaborators*", + json!([{ "id": 1001, "role_name": "maintain" }, { "id": 2002, "role_name": "read" }]), + ); + assert_eq!(app::forge::webhooks::recheck(&github_app(), &[ada_id]).await?, 1); + let role: Option = + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {ada_id}") + .scalar() + .await?; + assert_eq!(role.as_deref(), Some("admin"), "maintain is admin"); + github.assert_sent_count(3); + Ok(()) +} + +#[laravel::test(app = github)] +async fn a_listing_that_fails_changes_nobody(_app: Application) -> laravel::Result<()> { + let (org, _, _) = linked().await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ada_id = ada.id; + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({ada_id}, 'github', '', '1001', 'ada', now(), now())" + ) + .insert() + .await?; + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, created_at, updated_at) \ + VALUES ({org}, {ada_id}, 'member', 'github', now(), now())" + ) + .insert() + .await?; + let _github = laravel::http::client::fake() + .with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" })) + .with("api.github.com/repositories/42", json!({ "full_name": "acme/web" })) + .with( + "api.github.com/repos/acme/web/collaborators*", + laravel::http::client::response().status(502).json(json!({})), + ); + assert!(app::forge::webhooks::recheck(&github_app(), &[ada_id]).await.is_err()); + let role: Option = + db::query!("SELECT role FROM memberships WHERE organization_id = {org} AND user_id = {ada_id}") + .scalar() + .await?; + assert_eq!(role.as_deref(), Some("member"), "a partial answer drops nobody"); + Ok(()) +} + +#[laravel::test(app = github)] +async fn a_renamed_repository_moves_its_links_and_edits_say_whether_it_is_private( + app: Application, +) -> laravel::Result<()> { + let (_, by_id, by_url) = linked().await?; + let events = laravel::event::fake(); + let renamed = json!({ "action": "renamed", "repository": { "id": 42, "full_name": "acme/website" } }); + deliver(&app, "repository", renamed).await.assert_ok().assert_json_path("moved", 1); + let url: Option = db::query!("SELECT repository_url FROM projects WHERE id = {by_id}").scalar().await?; + assert_eq!(url.as_deref(), Some("https://github.com/acme/website")); + // A delivery naming the ID backfills a link that only had the URL + let edited = json!({ "action": "edited", "repository": { "id": 77, "full_name": "acme/web", "private": true } }); + deliver(&app, "repository", edited).await.assert_ok(); + events.assert_dispatched_where::(|e| { + e.project_id == by_url && e.private + }); + let id: Option = db::query!("SELECT repository_id FROM projects WHERE id = {by_url}") + .scalar::>() + .await? + .flatten(); + assert_eq!(id.as_deref(), Some("77")); + Ok(()) +} diff --git a/docker/server.Dockerfile b/docker/server.Dockerfile index 3ee54e9d..5693a7fd 100644 --- a/docker/server.Dockerfile +++ b/docker/server.Dockerfile @@ -10,8 +10,20 @@ ARG VISUALCI_ANALYTICS=0 ENV VISUALCI_ANALYTICS=${VISUALCI_ANALYTICS} RUN if [ -f pnpm-lock.yaml ]; then pnpm build; else npm run build; fi -FROM rust:1.99.1-trixie AS build +# Dependencies build in a layer of their own (cargo-chef), rebuilt only when Cargo.toml or Cargo.lock change: a commit +# that only changes our code compiles only our crates. +FROM rust:1.99.1-trixie AS chef +RUN cargo install cargo-chef --locked --version 0.1.78 WORKDIR /src + +FROM chef AS planner +COPY . . +RUN cargo chef prepare --recipe-path recipe.json + +FROM chef AS build +COPY --from=planner /src/recipe.json recipe.json +COPY rust-toolchain.toml ./ +RUN cargo chef cook --release --locked -p visualci_server --recipe-path recipe.json COPY . . ARG BUILD_SHA=dev ENV BUILD_SHA=${BUILD_SHA} diff --git a/gemini-extension.json b/gemini-extension.json index ae128fcb..648e042d 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "visualci", - "version": "0.1.45", + "version": "0.1.46", "description": "Visual regression and snapshot review for PDFs, screenshots, JSON, HTML and text: VisualCI's MCP server and its skills for each CI provider and test tool.", "mcpServers": { "visualci": { diff --git a/server/frontend/content/docs/agents.md b/server/frontend/content/docs/agents.md index 9699afea..198ecc9c 100644 --- a/server/frontend/content/docs/agents.md +++ b/server/frontend/content/docs/agents.md @@ -46,7 +46,7 @@ claude mcp add --transport http visualci https://mcp.visualci.com/mcp \ 5. `snapshot_history` shows one snapshot across recent builds, which helps find when a page started changing. `get_build` marks a change `flaky: true` when its content flipped back and forth over the branch's recent builds: often a test that isn't deterministic rather than a real change (see [Deterministic screenshots](/docs/screenshots/deterministic/)). 6. Before asking for a merge, `get_pr_changeset` (the project and the pull request's number, or a branch) lists everything the pull request adds, changes or removes across all of its builds, against the baseline it forked from, with where review stands for each. A change approved in an earlier build still shows there, so nothing slips through; nothing should be pending or unexpected. The web app shows the same at `///pulls/`. -On GitHub, VisualCI keeps one comment on each pull request up to date: each suite's newest build, its counts and review state, before and after images of the changed snapshots, and what was removed. To show images in a comment of your own, use the `embed_url` links `get_snapshot` gives for each page: they work for a week. +On GitHub, VisualCI keeps one comment on each pull request up to date when something changed: each suite's newest build, its counts and review state, before and after images of the changed snapshots, and what was removed. A pull request where nothing changed gets only the passing check, unless the project's `comment_when_unchanged` setting is on; a comment that's already there keeps being updated. To show images in a comment of your own, use the `embed_url` links `get_snapshot` gives for each page: they work for a week. ### Comment threads diff --git a/server/frontend/src/api/types.ts b/server/frontend/src/api/types.ts index 1bc44eb7..92ceb2fd 100644 --- a/server/frontend/src/api/types.ts +++ b/server/frontend/src/api/types.ts @@ -232,6 +232,8 @@ export type ProjectSettings = { gallery_enabled: boolean /** Whether project tokens (CI's agents) may approve changes; off keeps approving with people. */ tokens_can_approve: boolean + /** Whether VisualCI comments on pull requests when nothing changed (off: only the check). */ + comment_when_unchanged: boolean /** Anyone, signed in or not, can read its builds and diffs. */ public: boolean /** GitHub says its repository is public (checked on linking and once a day). Only then can it be public. */ diff --git a/server/frontend/src/pages/ProjectPage.tsx b/server/frontend/src/pages/ProjectPage.tsx index be3209ed..742a83f6 100644 --- a/server/frontend/src/pages/ProjectPage.tsx +++ b/server/frontend/src/pages/ProjectPage.tsx @@ -256,6 +256,7 @@ const toDraft = (s: ProjectSettings): Draft => ({ ignore_anti_aliasing: s.ignore_anti_aliasing, gallery_enabled: s.gallery_enabled, tokens_can_approve: s.tokens_can_approve, + comment_when_unchanged: s.comment_when_unchanged, public: s.public, rules: s.ignore_rules.map((r) => ({ snapshots: r.snapshots, @@ -555,6 +556,16 @@ function Settings({ +
diff --git a/server/migration/src/lib.rs b/server/migration/src/lib.rs index 36679cc8..c4338cad 100644 --- a/server/migration/src/lib.rs +++ b/server/migration/src/lib.rs @@ -49,6 +49,7 @@ mod m20261202_000042_build_groups; mod m20261203_000046_waitlist; mod m20261203_000047_empty_reason; mod m20261203_000048_downloads; +mod m20261203_000049_comment_when_unchanged; pub struct Migrator; @@ -104,6 +105,7 @@ impl MigratorTrait for Migrator { Box::new(m20261203_000046_waitlist::Migration), Box::new(m20261203_000047_empty_reason::Migration), Box::new(m20261203_000048_downloads::Migration), + Box::new(m20261203_000049_comment_when_unchanged::Migration), // inject-above (do not remove this comment) ] } diff --git a/server/migration/src/m20261203_000049_comment_when_unchanged.rs b/server/migration/src/m20261203_000049_comment_when_unchanged.rs new file mode 100644 index 00000000..34e8c507 --- /dev/null +++ b/server/migration/src/m20261203_000049_comment_when_unchanged.rs @@ -0,0 +1,29 @@ +//! VisualCI's pull request comment, only when something changed: with `comment_when_unchanged` off (the default), a +//! pull request whose builds are all unchanged gets no comment (its VisualCI check still passes), so nobody's inbox +//! fills with "nothing changed". A comment already there keeps being edited. +use sea_orm_migration::prelude::*; + +pub struct Migration; + +impl MigrationName for Migration { + fn name(&self) -> &str { + "m20261203_000049_comment_when_unchanged" + } +} + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection() + .execute_unprepared( + "ALTER TABLE projects ADD COLUMN comment_when_unchanged BOOLEAN NOT NULL DEFAULT false;", + ) + .await?; + Ok(()) + } + + async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> { + m.get_connection().execute_unprepared("ALTER TABLE projects DROP COLUMN comment_when_unchanged;").await?; + Ok(()) + } +} diff --git a/server/src/models/_entities/projects.rs b/server/src/models/_entities/projects.rs index ce8a014e..604b4941 100644 --- a/server/src/models/_entities/projects.rs +++ b/server/src/models/_entities/projects.rs @@ -29,6 +29,8 @@ pub struct Model { pub gallery_enabled: bool, /// Whether project tokens may approve changes over MCP (CI's agents); off keeps approving with people. pub tokens_can_approve: bool, + /// Whether VisualCI comments on a pull request whose builds are all unchanged; off by default (the check passes). + pub comment_when_unchanged: bool, #[sea_orm(column_type = "Text")] pub default_branch: String, #[sea_orm(column_type = "Text")] diff --git a/server/src/models/projects.rs b/server/src/models/projects.rs index 80f4cf87..51a3eeaf 100644 --- a/server/src/models/projects.rs +++ b/server/src/models/projects.rs @@ -136,6 +136,9 @@ pub struct Settings { pub gallery_enabled: bool, /// Whether project tokens may approve changes over MCP; off keeps approving with people. pub tokens_can_approve: bool, + /// Whether VisualCI comments on a pull request whose builds are all unchanged. Off by default: the VisualCI check + /// still passes, and a comment already there (an earlier build had changes) keeps being updated. + pub comment_when_unchanged: bool, /// Whether anyone, signed in or not, can read the project's builds and diffs (open source). Settings, tokens and /// reviewing stay with its members. pub public: bool, @@ -171,6 +174,7 @@ impl From<&Model> for Settings { forge_webhook_at: p.forge_webhook_at.map(|d| d.to_rfc3339()), gallery_enabled: p.gallery_enabled, tokens_can_approve: p.tokens_can_approve, + comment_when_unchanged: p.comment_when_unchanged, public: p.public, repository_public: p.repository_public, open_source: p.open_source, @@ -214,6 +218,9 @@ pub struct SettingsChange { pub gallery_enabled: Option, /// `false`: project tokens can't approve changes (people do); `true` lets CI's agents approve again. pub tokens_can_approve: Option, + /// `true`: comment on pull requests even when nothing changed. `false` (the default): a pull request whose builds + /// are all unchanged gets no comment, only the passing check; a comment already there keeps being updated. + pub comment_when_unchanged: Option, /// `true` lets anyone, signed in or not, read the project's builds and diffs (for open source projects); /// settings, tokens and reviewing stay with its members. Only a project linked to a public repository can be /// public. `false` makes it private again. @@ -349,6 +356,9 @@ impl Model { if let Some(v) = p.tokens_can_approve { a.tokens_can_approve = Set(v); } + if let Some(v) = p.comment_when_unchanged { + a.comment_when_unchanged = Set(v); + } if let Some(v) = p.gallery_enabled { a.gallery_enabled = Set(v); } diff --git a/server/src/workers/pr_comment.rs b/server/src/workers/pr_comment.rs index f1e56715..8f9c6a57 100644 --- a/server/src/workers/pr_comment.rs +++ b/server/src/workers/pr_comment.rs @@ -164,6 +164,27 @@ async fn embed(db: &DatabaseConnection, store: &BlobStore, sha: Option<&String>) } /// Each suite's newest build for this pull request, ready to render. +/// Whether to post or update the pull request's comment: always when there's something to look at, or a comment to +/// update; when every suite is unchanged, only with the project's `comment_when_unchanged` on. +#[must_use] +pub fn posts(has_comment: bool, comment_when_unchanged: bool, suites: &[Suite]) -> bool { + has_comment || comment_when_unchanged || !all_unchanged(suites) +} + +/// Whether every suite's newest build has finished with nothing to look at: no changed, added, removed or failed +/// snapshots, and no error. +#[must_use] +pub fn all_unchanged(suites: &[Suite]) -> bool { + suites.iter().all(|s| { + s.state == "completed" + && s.error.is_none() + && s.stats.changed == 0 + && s.stats.added == 0 + && s.stats.removed == 0 + && s.stats.failed == 0 + }) +} + async fn suites(ctx: &AppContext, project: &projects::Model, org: &str, pr_number: i32) -> Result> { use crate::models::_entities::builds::Column as B; let db = &ctx.db; @@ -258,13 +279,20 @@ impl BackgroundWorker for PrCommentWorker { }; let org = organizations::Entity::find_by_id(project.organization_id).one(db).await?.ok_or(Error::NotFound)?; let request = if repository.forge == crate::forge::ForgeKind::Gitlab { "MR" } else { "PR" }; - let body = render(&suites(&self.ctx, &project, &org.slug, pr_number).await?, request); - let hash = hex::encode(sha2::Sha256::digest(body.as_bytes())); + let suites = suites(&self.ctx, &project, &org.slug, pr_number).await?; let existing = pr_comments::Entity::find() .filter(pr_comments::Column::ProjectId.eq(project.id)) .filter(pr_comments::Column::PrNumber.eq(pr_number)) .one(db) .await?; + // Nothing changed: the VisualCI check says so, and a comment would only fill people's inboxes. One already + // there (an earlier build had changes) is still updated, to show the pull request is clean now; GitHub + // doesn't email about edits. + if !posts(existing.is_some(), project.comment_when_unchanged, &suites) { + return Ok(()); + } + let body = render(&suites, request); + let hash = hex::encode(sha2::Sha256::digest(body.as_bytes())); if existing.as_ref().and_then(|e| e.body_sha256.as_deref()) == Some(hash.as_str()) { return Ok(()); } @@ -313,6 +341,32 @@ impl BackgroundWorker for PrCommentWorker { mod tests { use super::*; + fn suite(state: &str, stats: builds::Stats) -> Suite { + Suite { name: "default".into(), state: state.into(), stats, ..Default::default() } + } + + #[test] + fn nothing_changed_gets_no_new_comment_unless_the_project_asks() { + let clean = [suite("completed", builds::Stats { unchanged: 40, total: 40, ..Default::default() })]; + assert!(!posts(false, false, &clean), "no comment for an unchanged pull request"); + assert!(posts(false, true, &clean), "with comment_when_unchanged on"); + assert!(posts(true, false, &clean), "a comment already there is still updated"); + for stats in [ + builds::Stats { changed: 1, ..Default::default() }, + builds::Stats { added: 1, ..Default::default() }, + builds::Stats { removed: 1, ..Default::default() }, + builds::Stats { failed: 1, ..Default::default() }, + ] { + assert!(posts(false, false, &[suite("completed", stats)]), "changes are always posted"); + } + // One suite clean, another with a change; a build still processing or one that failed isn't "unchanged" + let mixed = [clean[0].clone(), suite("completed", builds::Stats { changed: 2, ..Default::default() })]; + assert!(posts(false, false, &mixed)); + assert!(posts(false, false, &[suite("processing", builds::Stats::default())])); + let errored = Suite { error: Some("out of credits".into()), ..suite("failed", builds::Stats::default()) }; + assert!(posts(false, false, &[errored])); + } + #[test] fn renders_counts_images_and_removals() { let suite = Suite { diff --git a/server/tests/requests/mcp.rs b/server/tests/requests/mcp.rs index 72575228..fe776038 100644 --- a/server/tests/requests/mcp.rs +++ b/server/tests/requests/mcp.rs @@ -1033,6 +1033,27 @@ async fn a_project_token_acts_as_a_member_not_an_admin() { .await; } +/// A pull request where nothing changed gets no comment by default; `comment_when_unchanged` turns that on. +#[tokio::test] +#[serial] +async fn comments_when_nothing_changed_are_off_until_turned_on() { + request::(|request, ctx| async move { + let f = fixture(&ctx).await; + let project = format!("{}/pdfs", f.org); + let (err, s) = call(&request, &f.user_token, "get_project", serde_json::json!({ "project": project })).await; + assert!(!err && s["settings"]["comment_when_unchanged"] == false, "off by default: {s}"); + let (err, s) = call( + &request, + &f.user_token, + "update_project", + serde_json::json!({ "project": project, "comment_when_unchanged": true }), + ) + .await; + assert!(!err && s["settings"]["comment_when_unchanged"] == true, "{s}"); + }) + .await; +} + /// With "Tokens can approve" off, a project token can't approve, accept a variant or ignore a change; it can still /// reject. A person's token can turn it off and on. #[tokio::test] diff --git a/skills/visualci-review/SKILL.md b/skills/visualci-review/SKILL.md index b0a3212f..f3013676 100644 --- a/skills/visualci-review/SKILL.md +++ b/skills/visualci-review/SKILL.md @@ -51,7 +51,7 @@ claude mcp add --transport http visualci https://mcp.visualci.com/mcp \ 5. `snapshot_history` shows one snapshot across recent builds, which helps find when a page started changing. `get_build` marks a change `flaky: true` when its content flipped back and forth over the branch's recent builds: often a test that isn't deterministic rather than a real change (see [Deterministic screenshots](https://visualci.com/docs/screenshots/deterministic.md)). 6. Before asking for a merge, `get_pr_changeset` (the project and the pull request's number, or a branch) lists everything the pull request adds, changes or removes across all of its builds, against the baseline it forked from, with where review stands for each. A change approved in an earlier build still shows there, so nothing slips through; nothing should be pending or unexpected. The web app shows the same at `///pulls/`. -On GitHub, VisualCI keeps one comment on each pull request up to date: each suite's newest build, its counts and review state, before and after images of the changed snapshots, and what was removed. To show images in a comment of your own, use the `embed_url` links `get_snapshot` gives for each page: they work for a week. +On GitHub, VisualCI keeps one comment on each pull request up to date when something changed: each suite's newest build, its counts and review state, before and after images of the changed snapshots, and what was removed. A pull request where nothing changed gets only the passing check, unless the project's `comment_when_unchanged` setting is on; a comment that's already there keeps being updated. To show images in a comment of your own, use the `embed_url` links `get_snapshot` gives for each page: they work for a week. ### Comment threads