diff --git a/.cargo/config.toml b/.cargo/config.toml index 9741f113..ede7a488 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,6 @@ [alias] xtask = "run --quiet --package xtask --" + +[build] +# Limit peak memory when compiling large Rust dependencies and linking. +jobs = 2 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 511ba4bb..681a1e30 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,7 +30,7 @@ jobs: - name: Scan conventions run: cargo xtask check rules - name: Lint shell scripts - run: shellcheck scripts/*.sh deploy/plugin-stats/*.sh + run: shellcheck scripts/*.sh rust: name: Rust (${{ matrix.os }}) @@ -74,41 +74,6 @@ jobs: - name: Typecheck and build run: cargo xtask check web - plugin-stats: - name: Plugin statistics service - runs-on: ubuntu-latest - services: - mysql: - image: mysql:8.0 - env: - MYSQL_ROOT_PASSWORD: integration-only - MYSQL_DATABASE: toolforge_stats_test - ports: ["3306:3306"] - options: >- - --health-cmd="mysqladmin ping -h 127.0.0.1 -pintegration-only" - --health-interval=5s --health-timeout=5s --health-retries=20 - defaults: - run: - working-directory: apps/server - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 - with: - # setup-go v6 exports GOTOOLCHAIN=local, so pin the exact version - # go.mod requires; '1.26.x' may resolve to an older patch. - go-version: '1.26.10' - cache-dependency-path: apps/server/go.sum - - name: Format, vet and test against MySQL - env: - TEST_MYSQL_DSN: root:integration-only@tcp(127.0.0.1:3306)/toolforge_stats_test?parseTime=true - run: | - test -z "$(gofmt -l .)" - go vet ./... - go test -race ./... - go build ./cmd/plugin-stats - - name: Check dependency vulnerabilities - run: go run golang.org/x/vuln/cmd/govulncheck@v1.1.4 ./... - bundle: name: Bundle (${{ matrix.os }}) # 完整打包较慢,只在合入主干分支或手动触发时运行 diff --git a/.github/workflows/plugin-stats-deploy.yml b/.github/workflows/plugin-stats-deploy.yml deleted file mode 100644 index bd143668..00000000 --- a/.github/workflows/plugin-stats-deploy.yml +++ /dev/null @@ -1,128 +0,0 @@ -name: Deploy plugin stats - -on: - push: - branches: [dev] - paths: - - 'apps/server/**' - - 'deploy/plugin-stats/**' - - '.github/workflows/plugin-stats-deploy.yml' - workflow_dispatch: - -concurrency: - group: plugin-stats-production - cancel-in-progress: false - -jobs: - deploy: - runs-on: ubuntu-24.04 - services: - mysql: - image: mysql:8.0 - env: - MYSQL_ROOT_PASSWORD: integration-only-password - MYSQL_DATABASE: toolforge_stats_test - ports: ['3306:3306'] - options: >- - --health-cmd="mysqladmin ping -h127.0.0.1 -pintegration-only-password" - --health-interval=5s --health-timeout=3s --health-retries=20 - defaults: - run: - working-directory: apps/server - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - with: - persist-credentials: false - - uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0 - with: - go-version: '1.26.10' - check-latest: true - cache-dependency-path: apps/server/go.sum - - name: Test - env: - TEST_MYSQL_DSN: root:integration-only-password@tcp(127.0.0.1:3306)/toolforge_stats_test?parseTime=true - run: | - test -z "$(gofmt -l .)" - go mod download - go mod verify - go vet ./... - go test -race -count=1 ./... - - name: Build Linux amd64 binary - run: | - mkdir -p build - CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w -X main.buildSHA=$GITHUB_SHA" -o build/plugin-stats ./cmd/plugin-stats - sha256sum build/plugin-stats > build/plugin-stats.sha256 - - name: Generate runtime config - run: | - cp ../../deploy/plugin-stats/toolforge-plugin-stats.service build/ - # Single-quote every value: the file is sourced by dash (sh) during - # migration and parsed by systemd; unquoted parentheses break sh. - cat > build/runtime.env < install release $SHA" - sudo id toolforge-stats >/dev/null 2>&1 || sudo useradd --system --no-create-home --shell /usr/sbin/nologin toolforge-stats - sudo install -d -o root -g root -m 755 /opt/toolforge-plugin-stats/releases - sudo install -d -o root -g toolforge-stats -m 750 /etc/toolforge-plugin-stats - release=/opt/toolforge-plugin-stats/releases/$SHA - sudo install -d -o root -g root -m 755 "$release" - echo "$(cut -d ' ' -f 1 plugin-stats.sha256) plugin-stats" | sha256sum -c --status - sudo install -m 755 plugin-stats "$release/plugin-stats" - sudo install -m 640 -o root -g toolforge-stats runtime.env /etc/toolforge-plugin-stats/runtime.env - sudo install -m 644 toolforge-plugin-stats.service /etc/systemd/system/toolforge-plugin-stats.service - sudo systemctl daemon-reload - sudo systemctl enable toolforge-plugin-stats >/dev/null - echo "==> migrate" - sudo bash -c "set -a; . /etc/toolforge-plugin-stats/runtime.env; set +a; exec '$release/plugin-stats' migrate up" - echo "==> switch and restart" - previous=$(sudo readlink -f /opt/toolforge-plugin-stats/current 2>/dev/null || true) - sudo ln -sfn "$release" /opt/toolforge-plugin-stats/current.next - sudo mv -Tf /opt/toolforge-plugin-stats/current.next /opt/toolforge-plugin-stats/current - sudo systemctl restart toolforge-plugin-stats - ok=false - for _ in $(seq 1 30); do - if curl -fsS --max-time 2 http://127.0.0.1:8088/readyz 2>/dev/null | grep -q "\"buildSha\":\"$SHA\""; then ok=true; break; fi - sleep 1 - done - if [ "$ok" != true ]; then - if [ -n "$previous" ]; then - sudo ln -sfn "$previous" /opt/toolforge-plugin-stats/current.rollback - sudo mv -Tf /opt/toolforge-plugin-stats/current.rollback /opt/toolforge-plugin-stats/current - sudo systemctl restart toolforge-plugin-stats - echo 'New release failed readiness; rolled back to the previous release.' >&2 - else - sudo systemctl stop toolforge-plugin-stats || true - echo 'First deployment failed readiness; service stopped for inspection.' >&2 - fi - exit 1 - fi - sudo rm -rf /tmp/stats-deploy - echo "Deployed $SHA" diff --git a/.gitignore b/.gitignore index 5e20c4ae..7cc26953 100644 --- a/.gitignore +++ b/.gitignore @@ -28,14 +28,5 @@ docs/out/ docs/src/data/*.json .web_builder/ -# Local service credentials and Go build output -apps/server/.env -apps/server/.env.* -!apps/server/.env.example -apps/server/bin/ -apps/server/coverage.out -apps/server/plugin-stats -apps/server/build/ - # local pnpm store cache .pnpm-store/ diff --git a/Cargo.lock b/Cargo.lock index d506b501..c996f5fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -70,6 +70,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" dependencies = [ "cfg-if", + "const-random", "getrandom 0.3.4", "once_cell", "serde", @@ -92,13 +93,28 @@ version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" +[[package]] +name = "alloc-no-stdlib" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" + [[package]] name = "alloc-stdlib" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" dependencies = [ - "alloc-no-stdlib", + "alloc-no-stdlib 2.0.4", +] + +[[package]] +name = "alloc-stdlib" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" +dependencies = [ + "alloc-no-stdlib 3.0.0", ] [[package]] @@ -176,6 +192,130 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +[[package]] +name = "arrow-array" +version = "60.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a75080e8066219ed2d1e3b8fd2eb0b1a4b35d03b6fa87fb1035e93bd8dac95" +dependencies = [ + "ahash", + "arrow-buffer", + "arrow-data", + "arrow-schema", + "chrono", + "half", + "hashbrown 0.17.1", + "num-complex", + "num-integer", + "num-traits", +] + +[[package]] +name = "arrow-buffer" +version = "60.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c6bf2edf52662586214410c6030204215453eb86b8715037e8951326e173b19" +dependencies = [ + "bytes", + "half", + "num-bigint 0.5.1", + "num-traits", +] + +[[package]] +name = "arrow-cast" +version = "60.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcad6713dda348c245cd6ef36a578b4362c143c3a9dd829aa19e89f407c3e48b" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-data", + "arrow-ord", + "arrow-schema", + "arrow-select", + "atoi", + "base64 0.23.1", + "chrono", + "half", + "lexical-core", + "num-traits", + "ryu", +] + +[[package]] +name = "arrow-cmp" +version = "60.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e23e1092a61d7addfe57a69bf5cde7628b7b6685adea11731c19acdfd86695" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-schema", +] + +[[package]] +name = "arrow-data" +version = "60.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a7becabdb9bf3fa058b55845c52e0f792bedc88fd0e28d6580c9730a902b60" +dependencies = [ + "arrow-buffer", + "arrow-schema", + "half", + "num-integer", + "num-traits", +] + +[[package]] +name = "arrow-ipc" +version = "60.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d6fe9198046b67abf4e3e3ef70de2d705099975bdc2a7d9f0661675a978a083" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-data", + "arrow-schema", + "arrow-select", + "flatbuffers", +] + +[[package]] +name = "arrow-ord" +version = "60.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3935eb956aeb858ab67685e167e230facd7bf4b294cf003a72d85a80edac1d2" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-cmp", + "arrow-data", + "arrow-schema", + "arrow-select", +] + +[[package]] +name = "arrow-schema" +version = "60.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e7574c4175cc731e0d26a8384bc25d455c5e220250988a772c1af843592444b" + +[[package]] +name = "arrow-select" +version = "60.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d6a571e56e54b485b9f2d1dac4c3c34edcaffaa2668a23a7204108b66ef163d" +dependencies = [ + "ahash", + "arrow-array", + "arrow-buffer", + "arrow-cmp", + "arrow-data", + "arrow-schema", + "num-traits", +] + [[package]] name = "ascii" version = "1.1.0" @@ -375,6 +515,15 @@ dependencies = [ "system-deps", ] +[[package]] +name = "atoi" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d12c37257553c19e9aee6cba77814fdc9e07844abfc8b3a2c377cd920ee5a993" +dependencies = [ + "num-traits", +] + [[package]] name = "atoi_simd" version = "0.18.1" @@ -649,9 +798,20 @@ version = "8.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", - "brotli-decompressor", + "alloc-no-stdlib 2.0.4", + "alloc-stdlib 0.2.4", + "brotli-decompressor 5.0.3", +] + +[[package]] +name = "brotli" +version = "9.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", + "brotli-decompressor 6.4.1", ] [[package]] @@ -660,8 +820,18 @@ version = "5.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", + "alloc-no-stdlib 2.0.4", + "alloc-stdlib 0.2.4", +] + +[[package]] +name = "brotli-decompressor" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50986a054f56ca3e15382f3c09abee2bf494c00311b238daae118a06bc1c15f1" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", ] [[package]] @@ -1774,7 +1944,7 @@ dependencies = [ "asn1-rs", "displaydoc", "nom 7.1.3", - "num-bigint", + "num-bigint 0.4.8", "num-traits", "rusticata-macros", ] @@ -2402,6 +2572,16 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" +[[package]] +name = "flatbuffers" +version = "25.12.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" +dependencies = [ + "bitflags 2.13.2", + "rustc_version", +] + [[package]] name = "flate2" version = "1.1.10" @@ -2529,7 +2709,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e246562084dde8ebbcc943b261c406ce4f68e5032ec28029a251a47d6a295500" dependencies = [ "num", - "num-bigint", + "num-bigint 0.4.8", ] [[package]] @@ -3184,7 +3364,7 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d285dc30731c8485de5fa732fbdf2b3affdf01e4da7c2135022ca6fa664bf6" dependencies = [ - "brotli", + "brotli 8.0.4", "hayro-postscript", ] @@ -3885,7 +4065,7 @@ dependencies = [ "indexmap 2.14.2", "jaq-core", "jaq-std", - "num-bigint", + "num-bigint 0.4.8", "num-traits", "ryu", "self_cell", @@ -4130,7 +4310,7 @@ dependencies = [ "jsonschema-macros", "jsonschema-regex", "jsonschema-value", - "num-bigint", + "num-bigint 0.4.8", "num-cmp", "num-traits", "percent-encoding", @@ -4191,7 +4371,7 @@ dependencies = [ "bytecount", "fraction", "getrandom 0.3.4", - "num-bigint", + "num-bigint 0.4.8", "num-cmp", "num-traits", "serde_json", @@ -4296,6 +4476,63 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" +[[package]] +name = "lexical-core" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8d125a277f807e55a77304455eb7b1cb52f2b18c143b60e766c120bd64a594" +dependencies = [ + "lexical-parse-float", + "lexical-parse-integer", + "lexical-util", + "lexical-write-float", + "lexical-write-integer", +] + +[[package]] +name = "lexical-parse-float" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52a9f232fbd6f550bc0137dcb5f99ab674071ac2d690ac69704593cb4abbea56" +dependencies = [ + "lexical-parse-integer", + "lexical-util", +] + +[[package]] +name = "lexical-parse-integer" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a7a039f8fb9c19c996cd7b2fcce303c1b2874fe1aca544edc85c4a5f8489b34" +dependencies = [ + "lexical-util", +] + +[[package]] +name = "lexical-util" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2604dd126bb14f13fb5d1bd6a66155079cb9fa655b37f875b3a742c705dbed17" + +[[package]] +name = "lexical-write-float" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50c438c87c013188d415fbabbb1dceb44249ab81664efbd31b14ae55dabb6361" +dependencies = [ + "lexical-util", + "lexical-write-integer", +] + +[[package]] +name = "lexical-write-integer" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "409851a618475d2d5796377cad353802345cba92c867d9fbcde9cf4eac4e14df" +dependencies = [ + "lexical-util", +] + [[package]] name = "libappindicator" version = "0.9.0" @@ -4522,7 +4759,7 @@ checksum = "bfffda0fe1ab0157e1a13c14bebd3f28671f2fccb7922f0722ec53926e6922d3" dependencies = [ "aes 0.9.3", "bitflags 2.13.2", - "brotli-decompressor", + "brotli-decompressor 5.0.3", "cbc 0.2.1", "chrono", "ecb 0.2.1", @@ -4552,6 +4789,15 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "lz4_flex" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f56455fff36934a9500d69062aec1c77037179b6f0669e4d5d6b72b84722d6a3" +dependencies = [ + "twox-hash", +] + [[package]] name = "lzma-rust2" version = "0.16.5" @@ -5042,7 +5288,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" dependencies = [ - "num-bigint", + "num-bigint 0.4.8", "num-complex", "num-integer", "num-iter", @@ -5060,6 +5306,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-bigint-dig" version = "0.8.6" @@ -5133,7 +5389,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" dependencies = [ - "num-bigint", + "num-bigint 0.4.8", "num-integer", "num-traits", ] @@ -5626,6 +5882,35 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "parquet" +version = "60.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6701f0dd63f5ee23a0f1f2865ff76825c301759d6ab649e3e5686cc32d066957" +dependencies = [ + "ahash", + "arrow-array", + "arrow-buffer", + "arrow-data", + "arrow-ipc", + "arrow-schema", + "arrow-select", + "base64 0.23.1", + "brotli 9.1.3", + "bytes", + "chrono", + "flate2", + "half", + "hashbrown 0.17.1", + "lz4_flex", + "num-bigint 0.5.1", + "num-integer", + "num-traits", + "seq-macro", + "snap", + "twox-hash", +] + [[package]] name = "paste" version = "1.0.15" @@ -7113,6 +7398,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "seq-macro" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + [[package]] name = "serde" version = "1.0.229" @@ -7507,7 +7798,7 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" dependencies = [ - "num-bigint", + "num-bigint 0.4.8", "num-traits", "thiserror 2.0.20", "time", @@ -7602,6 +7893,12 @@ dependencies = [ "serde", ] +[[package]] +name = "snap" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886" + [[package]] name = "socket2" version = "0.6.5" @@ -8199,7 +8496,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08279169ff42f8fc45a1dbc9dcae888893ba95288142e5880c59b93a26d2cfc5" dependencies = [ "base64 0.22.1", - "brotli", + "brotli 8.0.4", "ico", "json-patch", "plist", @@ -8472,7 +8769,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e176a18e67764923c4f1ce66f25ae4abe5f688384d5eb1a0fa6c77f3d90f887" dependencies = [ "anyhow", - "brotli", + "brotli 8.0.4", "cargo_metadata", "ctor", "dom_query", @@ -8641,6 +8938,16 @@ dependencies = [ "wasmtime-wasi", ] +[[package]] +name = "tfm-address-parser" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-ambient-effects" version = "0.1.0" @@ -8663,11 +8970,21 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-avro-inspector" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-base-converter" version = "0.1.0" dependencies = [ - "num-bigint", + "num-bigint 0.4.8", "num-traits", "serde", "serde_json", @@ -8726,6 +9043,16 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-chat-mockup" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-chores" version = "0.1.0" @@ -8819,6 +9146,26 @@ dependencies = [ "url", ] +[[package]] +name = "tfm-css-generator" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + +[[package]] +name = "tfm-css-selector-inspector" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-csv-viewer" version = "0.1.0" @@ -8854,6 +9201,16 @@ dependencies = [ "tyme4rs", ] +[[package]] +name = "tfm-dep-graph" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-dev-directory" version = "0.1.0" @@ -8864,6 +9221,17 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-device-mockup" +version = "0.1.0" +dependencies = [ + "image", + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-dockerfile-lint" version = "0.1.0" @@ -8951,6 +9319,17 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-festival-avatar" +version = "0.1.0" +dependencies = [ + "image", + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-file-extension" version = "0.1.0" @@ -8961,6 +9340,16 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-file-permission-inspector" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-flashcards" version = "0.1.0" @@ -9053,6 +9442,16 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-git-hooks-manager" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-gitignore" version = "0.1.0" @@ -9095,6 +9494,16 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-hanzi-pinyin" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-health-calculator" version = "0.1.0" @@ -9159,6 +9568,37 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-icu-lint" +version = "0.1.1" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + +[[package]] +name = "tfm-id-photo-maker" +version = "0.1.0" +dependencies = [ + "image", + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + +[[package]] +name = "tfm-idiom-reference" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-image-converter" version = "0.1.0" @@ -9242,6 +9682,16 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-js-minify-beautify" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-json-formatter" version = "0.1.0" @@ -9320,6 +9770,16 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-keyword-density" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-kinship-calculator" version = "0.1.0" @@ -9352,6 +9812,16 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-license-plate" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-log-viewer" version = "0.1.0" @@ -9456,6 +9926,46 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-name-generator" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + +[[package]] +name = "tfm-native-deps-inspector" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + +[[package]] +name = "tfm-nginx-config-generator" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + +[[package]] +name = "tfm-nginx-log-analyzer" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-nonogram" version = "0.1.0" @@ -9526,6 +10036,21 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-parquet-inspector" +version = "0.1.0" +dependencies = [ + "arrow-array", + "arrow-cast", + "arrow-schema", + "bytes", + "parquet", + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-password" version = "0.1.0" @@ -9581,6 +10106,16 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-phone-region-lookup" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-physics-calculator" version = "0.1.0" @@ -9714,6 +10249,16 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-rewrite-converter" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-robots-sitemap" version = "0.1.0" @@ -9724,6 +10269,18 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-saml-inspector" +version = "0.1.0" +dependencies = [ + "flate2", + "roxmltree", + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-sarif-viewer" version = "0.1.1" @@ -9764,6 +10321,16 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-seo-auditor" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-shortcut-cheatsheet" version = "0.1.0" @@ -9887,7 +10454,7 @@ dependencies = [ [[package]] name = "tfm-text-tools" -version = "0.1.0" +version = "0.1.3" dependencies = [ "fastrand", "heck 0.5.0", @@ -9963,7 +10530,7 @@ dependencies = [ [[package]] name = "tfm-unicode" -version = "0.1.0" +version = "0.1.3" dependencies = [ "serde", "serde_json", @@ -9979,7 +10546,7 @@ dependencies = [ [[package]] name = "tfm-unit-converter" -version = "0.1.0" +version = "0.1.2" dependencies = [ "serde", "serde_json", @@ -10000,6 +10567,16 @@ dependencies = [ "url", ] +[[package]] +name = "tfm-url-rewrite-generator" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-uscc" version = "0.1.0" @@ -10037,6 +10614,16 @@ dependencies = [ "uuid", ] +[[package]] +name = "tfm-verse-checker" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-vertical-stationery" version = "0.1.0" @@ -10361,17 +10948,19 @@ dependencies = [ [[package]] name = "tfp-local-server" -version = "0.1.0" +version = "0.1.2" dependencies = [ "data-encoding", "dunce", "if-addrs", + "jiff", "mime_guess", "percent-encoding", "qrcode", "serde", "serde_json", "tf-plugin-api", + "tf-plugin-guest", "tiny_http", ] diff --git a/Cargo.toml b/Cargo.toml index 6a6dc27d..4400729a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,6 +68,11 @@ opt-level = "s" panic = "abort" strip = true +[profile.dev] +# Keep source locations in backtraces without retaining full debug information. +debug = "line-tables-only" +incremental = false + # 模型推理与图像编解码是热点:开发构建也要优化,发布构建不按体积优化这些 crate [profile.dev.package.tract-core] opt-level = 3 diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 13f22467..440b641a 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -8,7 +8,7 @@ "build": "pnpm typecheck && vite build", "preview": "vite preview", "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.node.json", - "test": "node --experimental-strip-types --experimental-test-module-mocks --test tests/update.test.mjs tests/task-errors.test.mjs tests/plugin-stats.test.mjs tests/install-queue.test.mjs tests/market-filter.test.mjs", + "test": "node --experimental-strip-types --experimental-test-module-mocks --test tests/update.test.mjs tests/task-errors.test.mjs tests/plugin-stats.test.mjs tests/install-queue.test.mjs tests/market-filter.test.mjs tests/app-tabs.test.mjs", "tauri": "tauri" }, "dependencies": { diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 41697e88..1a0b050e 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -8,9 +8,10 @@ import { CommandPalette } from './layout/CommandPalette' import { Sidebar } from './layout/Sidebar' import { TaskCenter } from './layout/TaskCenter' import { TitleBar } from './layout/TitleBar' +import { ToolTabs } from './layout/ToolTabs' import { QuitDialog } from './layout/QuitDialog' import { UpdateDialog } from './layout/UpdateDialog' -import { useApp, pluginById, type LoadProgress } from './stores/app' +import { useApp, pluginById, routeKey, type LoadProgress, type Route } from './stores/app' import { usePrefs } from './stores/prefs' import { subscribeTasks, useTasks } from './stores/tasks' import { useUpdate } from './stores/update' @@ -31,8 +32,7 @@ interface ExternalInstallEvent { error?: AppError | null } -function Content() { - const route = useApp((s) => s.route) +function View({ route }: { route: Route }) { switch (route.view) { case 'tool': return @@ -53,25 +53,58 @@ function Content() { } } +/** 标签页保活渲染:所有打开的标签保持挂载(hidden 切换),切换不丢工具状态 */ +function TabbedContent() { + const tabs = useApp((s) => s.tabs) + const activeTab = useApp((s) => s.activeTab) + return ( + <> + {tabs.map((tab, index) => ( + + ))} + + ) +} + export function App() { const { t, i18n } = useTranslation() const errorMessage = useErrorMessage('common') const ready = useApp((s) => s.ready) const load = useApp((s) => s.load) + useEffect(() => { + let timer: ReturnType | undefined + const refresh = () => { + clearTimeout(timer) + timer = undefined + useApp.getState().reloadPlugins().catch((error) => { + invoke('app_log', { level: 'error', message: `plugin list refresh failed: ${String(error)}` }).catch(() => {}) + }) + } + const offLoading = listen('plugins://loading', ({ payload }) => { + useApp.getState().setPluginProgress(payload) + // 每批刷新一次,让已加载的工具先出现,避免逐条事件都读取整个列表。 + timer ??= setTimeout(refresh, 250) + }) + const offPlugins = listen('plugins://changed', () => { + refresh() + void useApp.getState().refreshPluginProgress() + }) + return () => { + clearTimeout(timer) + offLoading.then((off) => off()) + offPlugins.then((off) => off()) + } + }, []) + useEffect(() => { // 退出请求:先应答 Rust(否则超时后直接退出),再弹出确认框 const offQuit = listen('app://close-requested', ({ payload }) => { invoke('app_close_ack', { seq: payload }).catch(() => {}) useApp.getState().setQuitRequest(payload) }) - // 在线插件加载完成、安装或卸载后刷新插件列表;进度事件驱动侧边栏的加载提示 - const offPlugins = listen('plugins://changed', () => { - void useApp.getState().reloadPlugins() - }) - const offLoading = listen('plugins://loading', ({ payload }) => { - useApp.getState().setPluginProgress(payload) - }) // 官网 toolforge:// 一键安装完成后的结果提示;名称优先用索引里的本地化名称, // 内置工具回退到插件列表中的名称 const displayName = (names?: Record | null, id?: string) => { @@ -104,8 +137,6 @@ export function App() { }) return () => { offQuit.then((off) => off()) - offPlugins.then((off) => off()) - offLoading.then((off) => off()) offNavigate.then((off) => off()) offPalette.then((off) => off()) offInstall.then((off) => off()) @@ -143,11 +174,12 @@ export function App() { return (
+
{ready ? ( - + ) : (
diff --git a/apps/desktop/src/layout/Sidebar.tsx b/apps/desktop/src/layout/Sidebar.tsx index 43638aab..3b99ab55 100644 --- a/apps/desktop/src/layout/Sidebar.tsx +++ b/apps/desktop/src/layout/Sidebar.tsx @@ -30,9 +30,9 @@ function NavItem({ onClick={onClick} aria-current={active ? 'page' : undefined} className={cn( - 'flex h-9 w-full items-center gap-3 rounded-control text-[13px] outline-none transition-colors', + 'flex h-9 w-full items-center gap-2.5 rounded-control text-[13px] outline-none transition-colors', 'focus-visible:ring-2 focus-visible:ring-ring [&_svg]:size-4 [&_svg]:shrink-0', - indent ? 'pr-2 pl-5' : 'px-3', + indent ? 'pr-2 pl-7' : 'px-3', active ? 'bg-primary font-medium text-fg-on-primary shadow-card' : 'text-fg hover:bg-hover', )} > @@ -56,7 +56,7 @@ export function Sidebar() { const seen = usePrefs((s) => s.seenVersions) const plugins = all.filter((p) => !hidden.includes(p.id)) const changed = all.filter((p) => toolStatus(p, seen) !== 'seen').length - const route = useApp((s) => s.route) + const route = useApp((s) => s.tabs[s.activeTab]) const info = useApp((s) => s.info) const navigate = useApp((s) => s.navigate) const openTool = useApp((s) => s.openTool) @@ -94,7 +94,7 @@ export function Sidebar() { {open && (
{items.length === 0 && ( -

{t('sidebar.emptyCategory')}

+

{t('sidebar.emptyCategory')}

)} {items.map((manifest) => ( string, pluginName: (id: string) => string | null): string { + switch (route.view) { + case 'tool': + return pluginName(route.pluginId) ?? route.pluginId + case 'home': + return t('nav.home') + case 'favorites': + return t('nav.favorites') + case 'recent': + return t('nav.recent') + case 'history': + return t('nav.history') + case 'market': + return t('nav.market') + case 'settings': + return t('nav.settings') + case 'about': + return t('tabs.about') + } +} + +export function ToolTabs() { + const { t } = useTranslation('app') + const text = usePluginText() + const tabs = useApp((s) => s.tabs) + const activeTab = useApp((s) => s.activeTab) + const navigate = useApp((s) => s.navigate) + const closeTab = useApp((s) => s.closeTab) + const closeOthers = useApp((s) => s.closeOthers) + const closeRight = useApp((s) => s.closeRight) + const plugins = useApp((s) => s.plugins) + const pluginName = (id: string) => { + const manifest = pluginById(plugins, id) + return manifest ? text(manifest, manifest.name) : null + } + + if (tabs.length <= 1) { + return null + } + + return ( +
+ {tabs.map((tab, index) => { + const active = index === activeTab + const closable = tab.view !== 'home' + const label = tabLabel(tab, (key) => t(key), pluginName) + return ( +
{ + event.preventDefault() + event.currentTarget.querySelector('[data-tab-menu]')?.click() + }} + > + + {closable && ( + + )} + + {'⋯'} + + } + placement="bottom-start" + items={[ + { key: 'close', label: t('tabs.close', { name: label }), disabled: !closable, onSelect: () => closeTab(index) }, + { key: 'closeOthers', label: t('tabs.closeOthers'), onSelect: () => closeOthers(index) }, + { key: 'closeRight', label: t('tabs.closeRight'), onSelect: () => closeRight(index) }, + ]} + /> +
+ ) + })} +
+ ) +} diff --git a/apps/desktop/src/locales/en-US.json b/apps/desktop/src/locales/en-US.json index 57ae2fa0..a4344446 100644 --- a/apps/desktop/src/locales/en-US.json +++ b/apps/desktop/src/locales/en-US.json @@ -423,6 +423,16 @@ "sensitiveBody": "{{name}} handles secrets such as keys and tokens. Once opened, AI agents can pass such data to it and read the results. Open it anyway?", "sensitiveConfirm": "Open anyway" } + }, + "tabs": { + "label": "Tabs", + "menu": "Actions for {{name}} tab", + "close": "Close \"{{name}}\"", + "closeOthers": "Close other tabs", + "closeRight": "Close tabs to the right", + "market": "Market", + "settings": "Settings", + "about": "About" } }, "common": { diff --git a/apps/desktop/src/locales/zh-CN.json b/apps/desktop/src/locales/zh-CN.json index f21fb552..93e89c8b 100644 --- a/apps/desktop/src/locales/zh-CN.json +++ b/apps/desktop/src/locales/zh-CN.json @@ -421,6 +421,16 @@ "sensitiveBody": "{{name}} 会处理密钥、令牌等敏感数据。开放后 AI Agent 可以把这些数据交给它并读取结果,确定要开放吗?", "sensitiveConfirm": "仍要开放" } + }, + "tabs": { + "label": "标签页", + "menu": "「{{name}}」标签页操作", + "close": "关闭「{{name}}」", + "closeOthers": "关闭其他标签页", + "closeRight": "关闭右侧标签页", + "market": "工具市场", + "settings": "设置", + "about": "关于" } }, "common": { diff --git a/apps/desktop/src/plugins/modules.ts b/apps/desktop/src/plugins/modules.ts index 06d68099..4adf4d9d 100644 --- a/apps/desktop/src/plugins/modules.ts +++ b/apps/desktop/src/plugins/modules.ts @@ -64,6 +64,8 @@ function installedUrl(id: string, file: string) { export const isBuiltin = (id: string) => uiById.has(id) +export const hasPluginResources = (plugin: Manifest) => isBuiltin(plugin.id) || installedVersions.get(plugin.id) === plugin.version + interface InstalledAssets { locales: Record icon: string | null @@ -71,10 +73,10 @@ interface InstalledAssets { } /** 注册在线插件的语言包、图标与样式(启动时与安装、更新后调用) */ -export async function registerInstalled(plugins: Manifest[]) { - await Promise.all( +export async function registerInstalled(plugins: Manifest[], onRegistered: () => void) { + await Promise.allSettled( plugins - .filter((p) => !isBuiltin(p.id) && installedVersions.get(p.id) !== p.version) + .filter((p) => !hasPluginResources(p)) .map(async (p) => { const assets = await invoke('plugin_assets', { pluginId: p.id }) addPluginResources(p.id, assets.locales) @@ -90,6 +92,7 @@ export async function registerInstalled(plugins: Manifest[]) { // 更新后重新加载界面模块(带版本参数避免命中旧模块) components.delete(p.id) installedVersions.set(p.id, p.version) + onRegistered() }), ) } diff --git a/apps/desktop/src/stores/app.ts b/apps/desktop/src/stores/app.ts index 884d6739..5fe7b000 100644 --- a/apps/desktop/src/stores/app.ts +++ b/apps/desktop/src/stores/app.ts @@ -1,7 +1,7 @@ import { invoke } from '@tauri-apps/api/core' import { create } from 'zustand' import type { Manifest } from '@toolforge/plugin-ui-sdk' -import { registerInstalled } from '../plugins/modules' +import { hasPluginResources, registerInstalled } from '../plugins/modules' import { usePrefs } from './prefs' export type Route = @@ -14,6 +14,8 @@ export type Route = | { view: 'settings' } | { view: 'about' } +export const routeKey = (route: Route) => (route.view === 'tool' ? `tool:${route.pluginId}` : route.view) + export interface AppInfo { version: string os: string @@ -39,7 +41,9 @@ interface AppState { pluginProgress: LoadProgress | null favorites: string[] recent: string[] - route: Route + /** 打开的标签页(首个固定为首页,不可关闭) */ + tabs: Route[] + activeTab: number paletteOpen: boolean /** 待交给工具的内容(带着内容打开工具时) */ launch: { pluginId: string; text: string; label: string | null; seq: number } | null @@ -47,10 +51,14 @@ interface AppState { quitRequest: number setQuitRequest: (seq: number) => void load: () => Promise - /** 在线插件安装、更新或卸载后重新读取插件列表 */ + /** 同步宿主已经可以使用的工具 */ reloadPlugins: () => Promise + refreshPluginProgress: () => Promise setPluginProgress: (progress: LoadProgress | null) => void navigate: (route: Route) => void + closeTab: (index: number) => void + closeOthers: (index: number) => void + closeRight: (index: number) => void openTool: (pluginId: string) => void openToolWith: (pluginId: string, text: string, label?: string) => void takeLaunch: (pluginId: string) => { text: string; label: string | null } | null @@ -58,6 +66,17 @@ interface AppState { setPaletteOpen: (open: boolean) => void } +let pluginRefresh: Promise | undefined +let refreshRequested = false +let progressRevision = 0 + +function withPlugins(state: AppState, plugins: Manifest[]) { + const ids = new Set(plugins.map((plugin) => plugin.id)) + const tabs = state.tabs.filter((tab) => tab.view !== 'tool' || ids.has(tab.pluginId)) + if (tabs.length === state.tabs.length) return { plugins } + return { plugins, tabs, activeTab: Math.max(0, tabs.indexOf(state.tabs[state.activeTab])) } +} + export const useApp = create((set, get) => ({ ready: false, info: null, @@ -65,52 +84,104 @@ export const useApp = create((set, get) => ({ pluginProgress: null, favorites: [], recent: [], - route: { view: 'home' }, + tabs: [{ view: 'home' }], + activeTab: 0, paletteOpen: false, launch: null, quitRequest: 0, setQuitRequest: (quitRequest) => set({ quitRequest }), load: async () => { - const [info, plugins, favorites, recent] = await Promise.all([ + const [info, favorites, recent] = await Promise.all([ invoke('app_info'), - invoke('plugin_list'), invoke('favorites_list'), invoke('recent_list'), ]) - await registerInstalled(plugins).catch(() => {}) - set({ info, plugins, favorites, recent, ready: true }) - // 后台线程可能在界面监听进度事件前就开始了,主动查询一次兜底 - try { - const progress = await invoke('plugin_load_progress') - if (!progress.finished) set({ pluginProgress: progress }) - } catch { - // 旧版本宿主没有这个命令,忽略 - } + set({ info, favorites, recent, ready: true }) + await Promise.all([get().reloadPlugins(), get().refreshPluginProgress()]) // 首次启动时把现有工具记为已看过,之后新增或更新的工具在工具市场中标出 const prefs = usePrefs.getState() - if (!prefs.seenVersions) prefs.markToolsSeen(plugins) + if (!prefs.seenVersions) prefs.markToolsSeen(get().plugins) + }, + + reloadPlugins: () => { + refreshRequested = true + pluginRefresh ??= (async () => { + try { + while (refreshRequested) { + refreshRequested = false + const plugins = await invoke('plugin_list') + // 新在线工具的界面资源在后台注册,内置和已打开的工具可以继续使用。 + const previous = new Map(get().plugins.map((plugin) => [plugin.id, plugin])) + const publishAvailable = () => { + const available = plugins.flatMap((plugin) => { + if (hasPluginResources(plugin)) return [plugin] + const existing = previous.get(plugin.id) + return existing ? [existing] : [] + }) + set((state) => withPlugins(state, available)) + } + publishAvailable() + await registerInstalled(plugins, publishAvailable) + } + } finally { + pluginRefresh = undefined + } + })() + return pluginRefresh + }, + + refreshPluginProgress: async () => { + const revision = progressRevision + const progress = await invoke('plugin_load_progress').catch(() => null) + if (revision === progressRevision) get().setPluginProgress(progress) }, - reloadPlugins: async () => { - const plugins = await invoke('plugin_list') - await registerInstalled(plugins).catch(() => {}) - const route = get().route - // 当前打开的插件被卸载时回到首页 - const gone = route.view === 'tool' && !plugins.some((p) => p.id === route.pluginId) - set({ plugins, pluginProgress: null, ...(gone ? { route: { view: 'home' } as Route } : {}) }) + setPluginProgress: (progress) => { + progressRevision += 1 + set({ pluginProgress: progress?.finished ? null : progress }) }, - setPluginProgress: (pluginProgress) => set({ pluginProgress }), + navigate: (route) => + set((state) => { + const index = state.tabs.findIndex((tab) => routeKey(tab) === routeKey(route)) + if (index >= 0) { + return { activeTab: index, paletteOpen: false } + } + return { tabs: [...state.tabs, route], activeTab: state.tabs.length, paletteOpen: false } + }), + + closeTab: (index) => + set((state) => { + const tab = state.tabs[index] + if (!tab || tab.view === 'home') return state + const tabs = state.tabs.filter((_, i) => i !== index) + let activeTab = state.activeTab + if (index < state.activeTab) activeTab -= 1 + else if (index === state.activeTab) activeTab = Math.min(activeTab, tabs.length - 1) + return { tabs, activeTab } + }), + + closeOthers: (index) => + set((state) => { + if (!state.tabs[index]) return state + const tabs = state.tabs.filter((_, i) => i === 0 || i === index) + return { tabs, activeTab: tabs.length - 1 } + }), - navigate: (route) => set({ route, paletteOpen: false }), + closeRight: (index) => + set((state) => { + if (!state.tabs[index]) return state + const tabs = state.tabs.filter((_, i) => i <= index) + const activeTab = Math.min(state.activeTab, tabs.length - 1) + return { tabs, activeTab } + }), openTool: (pluginId) => { const manifest = pluginById(get().plugins, pluginId) if (manifest) usePrefs.getState().markToolsSeen([manifest]) + get().navigate({ view: 'tool', pluginId }) set((state) => ({ - route: { view: 'tool', pluginId }, - paletteOpen: false, recent: [pluginId, ...state.recent.filter((id) => id !== pluginId)].slice(0, 12), })) invoke('recent_touch', { pluginId }).catch(() => {}) diff --git a/apps/desktop/tests/app-tabs.test.mjs b/apps/desktop/tests/app-tabs.test.mjs new file mode 100644 index 00000000..33e7e995 --- /dev/null +++ b/apps/desktop/tests/app-tabs.test.mjs @@ -0,0 +1,98 @@ +import assert from 'node:assert/strict' +import { registerHooks } from 'node:module' +import { mock, test } from 'node:test' +import { setImmediate } from 'node:timers/promises' +import { URL } from 'node:url' + +const appModule = new URL('../src/stores/app.ts', import.meta.url).href +const stubbedImports = new Set(['../plugins/modules', './prefs']) +const hooks = registerHooks({ + resolve(specifier, context, nextResolve) { + const path = context.parentURL === appModule && stubbedImports.has(specifier) ? `${specifier}.ts` : specifier + return nextResolve(path, context) + }, +}) + +let pluginList = [] +let progress = { done: 0, total: 3, finished: false } +const resources = new Set() +const assetRequests = new Map() +const touches = [] + +mock.module('@tauri-apps/api/core', { + namedExports: { + async invoke(command, args) { + if (command === 'plugin_list') return [...pluginList] + if (command === 'plugin_load_progress') return progress + if (command === 'app_info') return { os: 'macos', version: '0.2.5' } + if (command === 'favorites_list' || command === 'recent_list') return [] + if (command === 'recent_touch') touches.push(args.pluginId) + }, + }, +}) +mock.module(new URL('../src/stores/prefs.ts', import.meta.url), { + namedExports: { usePrefs: { getState: () => ({ seenVersions: {}, markToolsSeen() {} }) } }, +}) +mock.module(new URL('../src/plugins/modules.ts', import.meta.url), { + namedExports: { + hasPluginResources: (plugin) => plugin.id.startsWith('builtin.') || resources.has(plugin.id), + async registerInstalled(plugins, onRegistered) { + await Promise.all(plugins.map(async (plugin) => { + const pending = assetRequests.get(plugin.id) + if (!pending || resources.has(plugin.id)) return + await pending.promise + resources.add(plugin.id) + onRegistered() + })) + }, + }, +}) + +const { routeKey, useApp } = await import('../src/stores/app.ts') +hooks.deregister() + +const manifest = (id) => ({ id, name: id, version: '0.1.0' }) +const active = () => useApp.getState().tabs[useApp.getState().activeTab] + +test('opens tools while assets load, and a removed tool does not leave a stale active tab', async () => { + const assetA = Promise.withResolvers() + const assetB = Promise.withResolvers() + assetRequests.set('online.a', assetA) + assetRequests.set('online.b', assetB) + pluginList = ['builtin.qr', 'builtin.barcode', 'online.a', 'online.b'].map(manifest) + + const loading = useApp.getState().load() + await setImmediate() + assert.equal(useApp.getState().ready, true) + assert.deepEqual(useApp.getState().plugins.map((plugin) => plugin.id), ['builtin.qr', 'builtin.barcode']) + assert.equal(useApp.getState().pluginProgress.finished, false) + + useApp.getState().navigate({ view: 'market' }) + useApp.getState().openTool('builtin.qr') + assert.deepEqual(active(), { view: 'tool', pluginId: 'builtin.qr' }) + useApp.getState().openToolWith('builtin.barcode', 'sample') + assert.deepEqual(active(), { view: 'tool', pluginId: 'builtin.barcode' }) + assert.deepEqual(useApp.getState().takeLaunch('builtin.barcode'), { text: 'sample', label: null }) + + assetA.resolve() + await setImmediate() + assert.ok(useApp.getState().plugins.some((plugin) => plugin.id === 'online.a')) + assert.ok(!useApp.getState().plugins.some((plugin) => plugin.id === 'online.b')) + useApp.getState().openTool('online.a') + useApp.getState().openTool('builtin.barcode') + assert.deepEqual(useApp.getState().tabs.map(routeKey), ['home', 'market', 'tool:builtin.qr', 'tool:builtin.barcode', 'tool:online.a']) + assert.equal(touches.at(-1), 'builtin.barcode') + useApp.getState().closeTab(1) + assert.deepEqual(active(), { view: 'tool', pluginId: 'builtin.barcode' }) + + assetB.resolve() + await loading + pluginList = ['builtin.qr', 'online.a', 'online.b'].map(manifest) + await useApp.getState().reloadPlugins() + assert.deepEqual(active(), { view: 'home' }) + assert.ok(!useApp.getState().tabs.some((tab) => routeKey(tab) === 'tool:builtin.barcode')) + + progress = { done: 3, total: 3, finished: true } + await useApp.getState().refreshPluginProgress() + assert.equal(useApp.getState().pluginProgress, null) +}) diff --git a/apps/server/.env.example b/apps/server/.env.example deleted file mode 100644 index de149711..00000000 --- a/apps/server/.env.example +++ /dev/null @@ -1,18 +0,0 @@ -# Documentation only. Copy separately into restricted runtime.env, migrate.env, -# and catalog.env; never commit real credentials. EnvironmentFile format is not -# a shell script: do not add export, shell substitutions, or commands. -MYSQL_USER=toolforge_stats_runtime -MYSQL_PASSWORD=REPLACE_WITH_SEPARATELY_PROVISIONED_PASSWORD -MYSQL_DATABASE=toolforge_stats -MYSQL_SOCKET=/var/run/mysqld/mysqld.sock -# Optional local DSN alternative. MYSQL_DSN overrides the MYSQL_* components. -# MYSQL_DSN=toolforge_stats_runtime:REPLACE@unix(/var/run/mysqld/mysqld.sock)/toolforge_stats -STATS_LISTEN_ADDR=127.0.0.1:8088 -PLUGIN_ASSET_BASE_URL=https://plugins.toolforge.devlive.org -RECEIPT_ACTIVE_KID=first-production-key -# Replace the placeholder with standard base64 of >=32 cryptographically random -# bytes. The example is deliberately not a valid production keyring. -RECEIPT_KEYS_JSON='{"first-production-key":"REPLACE_WITH_BASE64_KEY"}' -# migrate.env/catalog.env need only the database settings, using distinct users. -# Test only: explicitly opt in to destructive tests in a dedicated *_test DB. -# TEST_MYSQL_DSN=toolforge_test:REPLACE@tcp(127.0.0.1:3306)/toolforge_stats_test?parseTime=true diff --git a/apps/server/README.md b/apps/server/README.md deleted file mode 100644 index f5d971ca..00000000 --- a/apps/server/README.md +++ /dev/null @@ -1,172 +0,0 @@ -# ToolForge 插件下载统计服务 - -Go 单二进制服务,使用 MySQL 8.0 / InnoDB。COS 负责文件流量,服务负责下载 302、客户端验证后的成功回报和下载量查询。不使用 COS 访问日志,不记录回报凭据,不提供公网管理写入接口。 - -## 统计口径 - -“下载量”是客户端完成文件下载,并校验包大小、SHA-256、官方签名以及插件 ID/版本后确认的下载次数。它不是安装成功量、独立用户数或浏览器点击数。公开客户端可以被修改,服务不能绝对证明真实下载或彻底防刷。 - -同一次逻辑下载使用同一个 128 位随机 `attempt_id`。发起下载和成功回报分别采用唯一键和 MySQL 事务幂等。不同次的实际下载可以分别计数。旧客户端可以自动跟随 302,但不能回报成功,因此仅增加发起次数。 - -服务正常回报期限为 7 天。客户端回报队列保留不超过 5 天;确认记录至少保留 30 天。过期尝试可删除,永久累计计数不随清理变化。用户重新操作时必须生成新的随机 ID;不得跨逻辑下载重用 ID。 - -## 配置与运行 - -最低 Go 1.26.10,后续使用受支持系列的最新补丁版本。该最低版本包含 [GO-2026-6809](https://pkg.go.dev/vuln/GO-2026-6809) 的 crypto/x509 修复;如改用 Go 1.27 系列,至少使用 1.27.3。间接依赖 edwards25519 固定到 1.1.1 以修复 [GO-2026-4503](https://pkg.go.dev/vuln/GO-2026-4503)。运行服务器不需要 Go 工具链。依赖由 `go.mod` / `go.sum` 固定。 - -在本目录执行: - -```sh -go test ./... -go test -race ./... -go vet ./... -CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w -X main.buildSHA=" -o plugin-stats ./cmd/plugin-stats -``` - -命令: - -```text -plugin-stats version -plugin-stats migrate up -plugin-stats catalog import -plugin-stats serve -``` - -不传参数等同 `serve`。`version` 输出构建提交。CLI 错误不打印 DSN、密码或回报密钥;数据库底层错误不透传到 HTTP。 - -配置见 `.env.example`。生产通过 systemd 的受限 `EnvironmentFile` 提供。`migrate` 和 `catalog` 命令只需要数据库设置,不读取或需要回报密钥。为常驻服务、迁移及目录导入使用三个不同 MySQL 用户,数据库独立于服务器现有业务数据库。 - -| 配置 | 说明 | -|---|---| -| `MYSQL_USER` / `MYSQL_PASSWORD` | 专用账号,不接受 root | -| `MYSQL_DATABASE` | 默认 `toolforge_stats` | -| `MYSQL_SOCKET` | 默认 `/var/run/mysqld/mysqld.sock` | -| `MYSQL_DSN` | 可选,覆盖分项;只允许本机 socket 或 IP loopback TCP | -| `STATS_LISTEN_ADDR` | 默认 `127.0.0.1:8088`,只允许 loopback | -| `PLUGIN_ASSET_BASE_URL` | 默认 `https://plugins.toolforge.devlive.org`,必须为 HTTPS origin | -| `RECEIPT_ACTIVE_KID` | 新下载使用的密钥编号 | -| `RECEIPT_KEYS_JSON` | 编号到标准 base64 密钥的 JSON 字典,每个密钥至少 32 随机字节,最多 8 个 | - -密钥仅存于服务器。轮换时先部署同时包含旧、新密钥的 keyring,再切换 active kid;旧密钥至少保留到所有旧凭据过期(7 天加时钟余量)。不得提前删除旧签名密钥。不得在日志、查询字符串、COS 请求或客户端持久化配置中暴露服务端密钥。 - -建议数据库授权(账号和密码由管理员单独创建,不写入仓库): - -- runtime:`plugin_versions`、`catalog_state`、`schema_migrations` 的 SELECT;`download_attempts` 的 SELECT/INSERT/UPDATE/DELETE;`plugin_stats`、`plugin_version_stats` 的 SELECT/UPDATE。 -- catalog:`plugin_versions` 的 SELECT/INSERT/UPDATE;`plugin_stats`、`plugin_version_stats` 的 SELECT/INSERT;`catalog_state` 的 SELECT/UPDATE。 -- migrate:仅该数据库所需的 CREATE/ALTER/DROP/INDEX/REFERENCES/SELECT/INSERT/UPDATE/DELETE;不授予跨库权限、FILE、GRANT OPTION 或服务器管理权限。 - -迁移库使用 MySQL advisory lock 防止并发迁移。DDL 有隐式提交,失败时迁移可能处于 dirty;停止发布并由管理员核验数据库及备份后修复,不自动 force 或执行 down。down SQL 仅用于隔离测试数据库。 - -## HTTP 接口 - -所有接口由 Nginx 经 HTTPS 暴露。生产 Nginx 应为新下载限流、设置 body 限制,只信任本机代理,并屏蔽 `/readyz` 的公网访问(部署在服务器本机检查)。服务仅监听 loopback;自身配置 8 秒请求上下文、明确连接超时、4096 字节成功回报 body、128 个并发请求上限和参数限制。无需浏览器 CORS,桌面 Rust 发起请求。 - -### 发起下载 - -```text -GET /v1/plugins/{id}/versions/{version}/download -Idempotency-Key: <32 个小写十六进制字符> -``` - -返回 `302`: - -```text -Location: https://plugins.toolforge.devlive.org/packages///.tfp -X-ToolForge-Attempt-Id: -X-ToolForge-Receipt: -X-ToolForge-Receipt-Expires: -Cache-Control: no-store -``` - -客户端必须关闭首跳的自动跳转,读取凭据后单独请求 COS,并严格校验预期主机和 HTTPS。不要把回报凭据转发给 COS。新客户端遇到统计入口故障时显示失败并允许重试,不绕过入口直连 COS。 - -相同 key 和相同版本返回同一套固定元数据、签发时间、到期时间及密钥编号;重试不延长寿命。key 对应其他插件/版本返回 `409`。未知版本 `404`;withdrawn 拒绝新下载,但已有尝试仍可重取有效凭据;revoked 拒绝全部下载和回报。缺少 key 时为兼容旧客户端由服务随机创建 ID。非空格式错误 key 返回 `400`;HEAD 不创建下载。 - -### 成功回报 - -```text -POST /v1/downloads/{attempt-id}/complete -Authorization: Bearer -Content-Type: application/json - -{"sha256":"<64 个小写十六进制字符>","size":12345} -``` - -返回 `200 {"attemptId":"...","status":"confirmed"}`。同一次回报重复提交同样返回 200,但版本及插件总数都只增加一次。单事务锁定尝试、更新状态及两张计数表。 - -- `401`:坏凭据;`404`:未知尝试;`409`:元数据或 attempt 不匹配;`410`:过期或安全撤销。 -- 请求过大或结构错误:`400`;错误 Content-Type:`415`。 -- 数据库/服务临时错误:`503`。客户端仅对网络错误、429、5xx 做有限退避重试并遵守 `Retry-After`,永久错误终止队列项目。 - -### 统计查询 - -下载计数是十进制 **JSON 字符串**,避免 JavaScript 数字精度损失。时间是 UTC RFC3339。所有查询采用一致性快照,返回 `countedSince` 与 `asOf`;公开查询可缓存 30 秒。 - -| 接口 | 结果 | -|---|---| -| `GET /v1/plugins/{id}/versions/{version}/stats` | `{pluginId,version,downloads,totalDownloads,countedSince,asOf}` | -| `GET /v1/plugins/{id}/stats?limit=50&offset=0` | `{pluginId,totalDownloads,versions:[{version,downloads}],limit,offset,hasMore,countedSince,asOf}` | -| `GET /v1/stats?ids=id1,id2` | `{plugins:[{pluginId,totalDownloads,versions:[{version,downloads}],versionsTruncated?}],countedSince,asOf}` | -| `GET /v1/stats/total` | `{totalDownloads,countedSince,asOf}` | -| `GET /healthz` | `{status:"ok",buildSha}` | -| `GET /readyz` | `{status:"ready",buildSha,catalogReady}`,schema/数据库失败时 503 | - -批量最多 100 个 ID,每插件最多最近 100 个版本(以发布时间、版本字符串稳定排序),更多时 `versionsTruncated:true`,可按插件详情继续分页。详情 limit 最大 100、offset 最大 100000。未知 ID 在批量结果中省略;单独查询返回 404。未发生下载的已发布版本为 `"0"`;临时查询失败不得在界面伪装为 0。 - -首次迁移后、目录尚未导入时,readyz 可以返回 `catalogReady:false`,允许先部署服务再完成插件发布。部署必须比较返回的 buildSha 与目标 SHA;目录导入成功后应验证 catalogReady 为 true。 - -## 全版本目录 - -本地管理命令导入完整目录: - -```json -{ - "schemaVersion": 1, - "sourceCommit": "0000000000000000000000000000000000000000", - "generation": 1, - "plugins": [ - { - "id": "example-plugin", - "version": "1.0.0", - "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "size": 42, - "objectKey": "packages/example-plugin/1.0.0/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.tfp", - "status": "active" - } - ] -} -``` - -`generation` 必须为正、单调增加的发布序列,例如同一 Plugins workflow 的 `GITHUB_RUN_NUMBER`。手动引导也必须使用同一发布序列,不能任意设置较大数值。`sourceCommit` 为 40 或 64 个小写十六进制字符。`publishedAt` 可选,省略时第一次导入时间固定为发布时间,重复导入不刷新。 - -同一 generation + 相同规范 JSON 摘要可幂等重跑;相同 generation 不同内容或较旧 generation 拒绝。包 size 最大 64 MiB,与桌面安装器一致。最多 10000 条、16 MiB 目录;插件 ID/版本和对象路径严格校验,对象路径必须按包 SHA 固定。已登记版本的 SHA、大小、objectKey 不可修改,必须升版。 - -完整目录中缺失的旧 active 版本自动 withdrawn,保留统计并接受已签发凭据。明确 revoked 的版本具有粘性,后续目录不能恢复为 active/withdrawn;安全撤销后恢复需新版本。管理命令不向数据库导入任意外部下载 URL。 - -发布顺序必须是:上传并读回验证所有不可变 COS 包 → 保存完整目录/索引快照 → 导入数据库目录 → 更新公共 registry。跨 COS/MySQL 无事务;任一步失败都保留既有公共索引,通过相同摘要对账重跑,不能用删除历史包来“回滚”。 - -## 数据、备份与恢复 - -- `plugin_versions`:全版本官方制品目录和 active/withdrawn/revoked 状态。 -- `download_attempts`:固定的签发元数据、过期时间、确认状态及幂等键。 -- `plugin_version_stats`、`plugin_stats`:永久累计计数。 -- `catalog_state`:全目录摘要、代次、来源提交、首次计数时间。 -- `schema_migrations`:迁移版本和 dirty 标记。 - -每小时删除一批(最多 1000 条)过期尝试;已确认的记录还必须确认超过 30 天。高负载时应观察清理积压,再按负载调整频率;不删除永久计数和版本历史。 - -定期备份全部统计数据库,并实际演练恢复。累计计数与幂等尝试状态必须从同一一致性备份一起恢复,不能单独还原其中一张表。尝试明细清理后,永久总量不能由短期明细完整重建。快照恢复会损失备份时间点之后的数据;不要宣称无损回滚。 - -服务回滚通过前一版本二进制加兼容 schema 完成。公共索引回滚到已保存快照;不删除已发布包、不执行生产 down、不重新签名历史同版本包。HMAC keyring 不随程序版本回退到缺少现存验证密钥的配置。 - -## 集成测试 - -普通 `go test` 会执行 HTTP/配置/目录/签名测试;真实 MySQL 测试仅在明确设置 `TEST_MYSQL_DSN` 时运行,未配置会报告 skip。 - -```sh -TEST_MYSQL_DSN=':@tcp(127.0.0.1:3306)/toolforge_stats_test?parseTime=true' go test -race ./... -``` - -测试会删除并重建已知表,数据库名必须以 `_test` 结尾。绝不能指向开发业务库或生产数据库。CI 应使用隔离 MySQL 8.0 服务;较新本机 MySQL 通过测试仅作为补充,不能替代准确版本兼容验证。 - -真实测试覆盖:并发相同请求只创建一次尝试、100 次并发确认仅计一次、计数表故障导致事务全回滚、不可变版本冲突、旧目录拒绝、普通下架、安全撤销不可复活、过期回报、明细清理、查询精度与分页。HTTP 单测覆盖旧版跳转、首跳凭据、篡改与过期、参数限制和错误脱敏。 diff --git a/apps/server/cmd/plugin-stats/main.go b/apps/server/cmd/plugin-stats/main.go deleted file mode 100644 index 6efad9b4..00000000 --- a/apps/server/cmd/plugin-stats/main.go +++ /dev/null @@ -1,179 +0,0 @@ -package main - -import ( - "context" - "database/sql" - "errors" - "fmt" - "log/slog" - "net/http" - "os" - "os/signal" - "syscall" - "time" - - "github.com/go-sql-driver/mysql" - "github.com/golang-migrate/migrate/v4" - mysqlmigrate "github.com/golang-migrate/migrate/v4/database/mysql" - "github.com/golang-migrate/migrate/v4/source/iofs" - "toolforge.dev/plugin-stats/internal/api" - "toolforge.dev/plugin-stats/internal/asset" - "toolforge.dev/plugin-stats/internal/catalog" - "toolforge.dev/plugin-stats/internal/config" - "toolforge.dev/plugin-stats/internal/registry" - "toolforge.dev/plugin-stats/internal/store" - "toolforge.dev/plugin-stats/migrations" -) - -var buildSHA = "development" - -func main() { - if err := run(os.Args[1:]); err != nil { - slog.Error("command failed", "reason", err.Error()) - os.Exit(1) - } -} -func run(args []string) error { - command := "serve" - if len(args) > 0 { - command = args[0] - } - if command == "version" { - fmt.Println(buildSHA) - return nil - } - serving := command == "serve" - if !(serving && (len(args) == 0 || len(args) == 1)) && !(command == "migrate" && len(args) == 2 && args[1] == "up") && !(command == "catalog" && len(args) == 3 && args[1] == "import") { - return errors.New("usage: plugin-stats [serve | version | migrate up | catalog import ]") - } - cfg, err := config.Read(serving) - if err != nil { - return err - } - if command == "migrate" { - migrationDB, parseErr := mysql.ParseDSN(cfg.DSN) - if parseErr != nil { - return errors.New("invalid migration database configuration") - } - migrationDB.MultiStatements = true - cfg.DSN = migrationDB.FormatDSN() - } - db, err := sql.Open("mysql", cfg.DSN) - if err != nil { - return errors.New("cannot initialize database") - } - defer db.Close() - db.SetMaxOpenConns(12) - db.SetMaxIdleConns(4) - db.SetConnMaxLifetime(3 * time.Minute) - ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) - defer cancel() - pingCtx, pingCancel := context.WithTimeout(ctx, 10*time.Second) - err = db.PingContext(pingCtx) - pingCancel() - if err != nil { - return errors.New("cannot connect to database") - } - if command == "migrate" { - return migrateUp(db) - } - storage := &store.Store{DB: db} - if command == "catalog" { - f, err := os.Open(args[2]) - if err != nil { - return errors.New("cannot open catalog file") - } - defer f.Close() - c, digest, err := catalog.Read(f) - if err != nil { - return err - } - importCtx, importCancel := context.WithTimeout(ctx, 2*time.Minute) - defer importCancel() - if err = storage.Import(importCtx, c, digest, time.Now().UTC()); err != nil { - if errors.Is(err, store.ErrConflict) { - return errors.New("catalog conflicts with immutable metadata or release generation") - } - return errors.New("catalog import failed") - } - slog.Info("catalog imported", "packages", len(c.Plugins), "generation", c.Generation) - return nil - } - // Schema readiness is required at startup; a catalog may be bootstrapped - // separately before /readyz becomes ready, without losing the first deploy. - var schema int - var dirty bool - if err = db.QueryRowContext(ctx, "SELECT version,dirty FROM schema_migrations LIMIT 1").Scan(&schema, &dirty); err != nil || schema != store.SchemaVersion || dirty { - return errors.New("database migration is required") - } - var presigner *asset.Presigner - if cfg.CosSecretID != "" { - presigner = &asset.Presigner{SecretID: cfg.CosSecretID, SecretKey: cfg.CosSecretKey} - slog.Info("download URLs are COS presigned for a private bucket") - } - var names *registry.Cache - if cfg.RegistryURL != "" { - names = ®istry.Cache{URL: cfg.RegistryURL, Client: &http.Client{Timeout: 15 * time.Second}} - // Names are display data: refresh in the background and never block serving. - go names.Run(ctx, 10*time.Minute, func(error) { slog.Warn("plugin registry refresh failed") }) - } - h := (&api.API{Store: storage, Signer: cfg.Signer, AssetBaseURL: cfg.AssetBaseURL, Presigner: presigner, Registry: names, BuildSHA: buildSHA, Logger: slog.Default()}).Handler() - srv := &http.Server{Addr: cfg.ListenAddr, Handler: h, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10, ErrorLog: slog.NewLogLogger(slog.Default().Handler(), slog.LevelError)} - done := make(chan error, 1) - go func() { done <- srv.ListenAndServe() }() - cleanupDone := make(chan struct{}) - go func() { - defer close(cleanupDone) - ticker := time.NewTicker(time.Hour) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case now := <-ticker.C: - cleanCtx, cleanCancel := context.WithTimeout(ctx, 10*time.Second) - err := storage.Cleanup(cleanCtx, now) - cleanCancel() - if err != nil { - slog.Error("attempt cleanup failed") - } - } - } - }() - slog.Info("plugin statistics listening", "buildSha", buildSHA) - select { - case err := <-done: - if !errors.Is(err, http.ErrServerClosed) { - return errors.New("HTTP listener failed") - } - case <-ctx.Done(): - shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 15*time.Second) - defer shutdownCancel() - if srv.Shutdown(shutdownCtx) != nil { - return errors.New("HTTP shutdown timed out") - } - <-cleanupDone - } - return nil -} -func migrateUp(db *sql.DB) error { - src, err := iofs.New(migrations.Files, ".") - if err != nil { - return errors.New("cannot initialize embedded migrations") - } - driver, err := mysqlmigrate.WithInstance(db, &mysqlmigrate.Config{}) - if err != nil { - return errors.New("cannot initialize migration driver") - } - m, err := migrate.NewWithInstance("iofs", src, "mysql", driver) - if err != nil { - return errors.New("cannot initialize migrations") - } - defer func() { _, _ = m.Close() }() - m.LockTimeout = 30 * time.Second - if err = m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) { - return errors.New("migration failed; inspect schema_migrations and backup before repair") - } - slog.Info("database migrations applied") - return nil -} diff --git a/apps/server/go.mod b/apps/server/go.mod deleted file mode 100644 index e2937ad7..00000000 --- a/apps/server/go.mod +++ /dev/null @@ -1,10 +0,0 @@ -module toolforge.dev/plugin-stats - -go 1.26.10 - -require ( - github.com/go-sql-driver/mysql v1.9.3 - github.com/golang-migrate/migrate/v4 v4.19.1 -) - -require filippo.io/edwards25519 v1.1.1 // indirect diff --git a/apps/server/go.sum b/apps/server/go.sum deleted file mode 100644 index 5e386e18..00000000 --- a/apps/server/go.sum +++ /dev/null @@ -1,66 +0,0 @@ -filippo.io/edwards25519 v1.1.1 h1:YpjwWWlNmGIDyXOn8zLzqiD+9TyIlPhGFG96P39uBpw= -filippo.io/edwards25519 v1.1.1/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= -github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= -github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= -github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= -github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= -github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= -github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= -github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dhui/dktest v0.4.6 h1:+DPKyScKSEp3VLtbMDHcUq6V5Lm5zfZZVb0Sk7Ahom4= -github.com/dhui/dktest v0.4.6/go.mod h1:JHTSYDtKkvFNFHJKqCzVzqXecyv+tKt8EzceOmQOgbU= -github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= -github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= -github.com/docker/docker v28.3.3+incompatible h1:Dypm25kh4rmk49v1eiVbsAtpAsYURjYkaKubwuBdxEI= -github.com/docker/docker v28.3.3+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= -github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c= -github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc= -github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= -github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= -github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= -github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo= -github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang-migrate/migrate/v4 v4.19.1 h1:OCyb44lFuQfYXYLx1SCxPZQGU7mcaZ7gH9yH4jSFbBA= -github.com/golang-migrate/migrate/v4 v4.19.1/go.mod h1:CTcgfjxhaUtsLipnLoQRWCrjYXycRz/g5+RWDuYgPrE= -github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= -github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= -github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= -github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= -github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= -github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= -github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= -github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= -github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= -github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug= -github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= -go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= -go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ= -go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I= -go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE= -go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E= -go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4= -go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/apps/server/internal/api/api.go b/apps/server/internal/api/api.go deleted file mode 100644 index b304e298..00000000 --- a/apps/server/internal/api/api.go +++ /dev/null @@ -1,334 +0,0 @@ -package api - -import ( - "context" - "crypto/rand" - "encoding/hex" - "encoding/json" - "errors" - "io" - "log/slog" - "mime" - "net/http" - "strconv" - "strings" - "time" - - "toolforge.dev/plugin-stats/internal/asset" - "toolforge.dev/plugin-stats/internal/catalog" - "toolforge.dev/plugin-stats/internal/dashboard" - "toolforge.dev/plugin-stats/internal/receipt" - "toolforge.dev/plugin-stats/internal/registry" - "toolforge.dev/plugin-stats/internal/store" -) - -type Repository interface { - Ready(context.Context) error - Issue(context.Context, string, string, string, string, time.Time) (store.Attempt, error) - Confirm(context.Context, receipt.Claims, string, uint64, time.Time) error - Version(context.Context, string, string) (store.VersionResult, error) - Plugin(context.Context, string, int, int) (store.PluginResult, error) - Batch(context.Context, []string) (store.Stats, error) - Total(context.Context) (store.TotalResult, error) - Dashboard(context.Context) (store.DashboardResult, error) -} -type API struct { - Store Repository - Signer *receipt.Signer - AssetBaseURL string - // Presigner signs COS download URLs for private buckets; when nil the - // plain asset URL is served and the bucket must allow anonymous reads. - Presigner *asset.Presigner - // Registry supplies plugin names for the dashboard; nil shows IDs only. - Registry *registry.Cache - BuildSHA string - Now func() time.Time - Logger *slog.Logger -} - -func (a *API) Handler() http.Handler { - mux := http.NewServeMux() - mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { - writeJSON(w, 200, map[string]string{"status": "ok", "buildSha": a.BuildSHA}) - }) - mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) { - if a.Store.Ready(r.Context()) != nil { - writeJSON(w, 503, map[string]string{"status": "unavailable", "buildSha": a.BuildSHA}) - return - } - catalogReady := false - if repo, ok := a.Store.(interface{ CatalogReady(context.Context) bool }); ok { - catalogReady = repo.CatalogReady(r.Context()) - } - writeJSON(w, 200, map[string]any{"status": "ready", "buildSha": a.BuildSHA, "catalogReady": catalogReady}) - }) - mux.HandleFunc("GET /v1/plugins/{id}/versions/{version}/download", a.download) - mux.HandleFunc("POST /v1/downloads/{attempt}/complete", a.complete) - mux.HandleFunc("GET /v1/plugins/{id}/versions/{version}/stats", a.version) - mux.HandleFunc("GET /v1/plugins/{id}/stats", a.plugin) - mux.HandleFunc("GET /v1/stats", a.batch) - mux.HandleFunc("GET /v1/stats/total", a.total) - mux.HandleFunc("GET /v1/dashboard", a.dashboard) - mux.HandleFunc("GET /{$}", dashboard.Index) - mux.HandleFunc("GET /assets/{file}", dashboard.Asset) - inFlight := make(chan struct{}, 128) - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "no-store") - w.Header().Set("X-Content-Type-Options", "nosniff") - w.Header().Set("Referrer-Policy", "no-referrer") - // Do not log URL queries, headers, bodies, tokens, or database errors. - defer func() { - if recover() != nil { - if a.Logger != nil { - a.Logger.Error("request panic") - } - writeError(w, 500, "internal_error") - } - }() - if len(r.URL.RawQuery) > 8192 { - writeError(w, 414, "query_too_long") - return - } - select { - case inFlight <- struct{}{}: - defer func() { <-inFlight }() - default: - w.Header().Set("Retry-After", "1") - writeError(w, 503, "busy") - return - } - ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) - defer cancel() - mux.ServeHTTP(w, r.WithContext(ctx)) - }) -} -func (a *API) now() time.Time { - if a.Now != nil { - return a.Now().UTC() - } - return time.Now().UTC() -} -func validPath(r *http.Request) bool { - return catalog.IDPattern.MatchString(r.PathValue("id")) && catalog.VersionPattern.MatchString(r.PathValue("version")) -} -func (a *API) download(w http.ResponseWriter, r *http.Request) { - // HEAD probes must not create attempts. Older clients without the new header - // still get a redirect, but only updated clients can confirm success. - if r.Method != http.MethodGet { - w.Header().Set("Allow", "GET") - writeError(w, 405, "method_not_allowed") - return - } - if !validPath(r) { - writeError(w, 400, "invalid_plugin_version") - return - } - attempt := r.Header.Get("Idempotency-Key") - if attempt == "" { - var b [16]byte - if _, err := rand.Read(b[:]); err != nil { - a.fail(w, err) - return - } - attempt = hex.EncodeToString(b[:]) - } - if !catalog.AttemptPattern.MatchString(attempt) { - writeError(w, 400, "invalid_idempotency_key") - return - } - issued, err := a.Store.Issue(r.Context(), r.PathValue("id"), r.PathValue("version"), attempt, a.Signer.ActiveKid(), a.now()) - if err != nil { - a.fail(w, err) - return - } - token, err := a.Signer.Sign(issued.Claims) - if err != nil { - a.fail(w, err) - return - } - location := strings.TrimRight(a.AssetBaseURL, "/") + "/" + issued.ObjectKey - if a.Presigner != nil { - location = a.Presigner.Presign(a.AssetBaseURL, issued.ObjectKey) - } - w.Header().Set("Location", location) - w.Header().Set("X-ToolForge-Attempt-Id", issued.AttemptID) - w.Header().Set("X-ToolForge-Receipt", token) - w.Header().Set("X-ToolForge-Receipt-Expires", strconv.FormatInt(issued.ExpiresAt, 10)) - w.WriteHeader(http.StatusFound) -} -func (a *API) complete(w http.ResponseWriter, r *http.Request) { - attempt := r.PathValue("attempt") - if !catalog.AttemptPattern.MatchString(attempt) { - writeError(w, 400, "invalid_attempt") - return - } - contentType, _, contentTypeErr := mime.ParseMediaType(r.Header.Get("Content-Type")) - if contentTypeErr != nil || contentType != "application/json" { - writeError(w, 415, "application_json_required") - return - } - auth := r.Header.Get("Authorization") - if !strings.HasPrefix(auth, "Bearer ") { - writeError(w, 401, "invalid_receipt") - return - } - claims, err := a.Signer.Verify(strings.TrimPrefix(auth, "Bearer "), a.now()) - if err != nil { - if errors.Is(err, receipt.ErrExpired) { - writeError(w, 410, "receipt_expired") - } else { - writeError(w, 401, "invalid_receipt") - } - return - } - if claims.AttemptID != attempt { - writeError(w, 409, "attempt_mismatch") - return - } - var body struct { - SHA256 string `json:"sha256"` - Size uint64 `json:"size"` - } - dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)) - dec.DisallowUnknownFields() - if dec.Decode(&body) != nil || dec.Decode(new(any)) != io.EOF || !catalog.SHAPattern.MatchString(body.SHA256) || body.Size == 0 || body.Size > catalog.MaxPackageSize { - writeError(w, 400, "invalid_body") - return - } - if err := a.Store.Confirm(r.Context(), claims, body.SHA256, body.Size, a.now()); err != nil { - a.fail(w, err) - return - } - writeJSON(w, 200, map[string]string{"attemptId": attempt, "status": "confirmed"}) -} -func (a *API) version(w http.ResponseWriter, r *http.Request) { - if !validPath(r) { - writeError(w, 400, "invalid_plugin_version") - return - } - out, err := a.Store.Version(r.Context(), r.PathValue("id"), r.PathValue("version")) - if err != nil { - a.fail(w, err) - return - } - cacheJSON(w, out) -} -func (a *API) plugin(w http.ResponseWriter, r *http.Request) { - if !catalog.IDPattern.MatchString(r.PathValue("id")) { - writeError(w, 400, "invalid_plugin") - return - } - limit, ok := intQuery(r, "limit", 50, 1, 100) - if !ok { - writeError(w, 400, "invalid_limit") - return - } - offset, ok := intQuery(r, "offset", 0, 0, 100000) - if !ok { - writeError(w, 400, "invalid_offset") - return - } - out, err := a.Store.Plugin(r.Context(), r.PathValue("id"), limit, offset) - if err != nil { - a.fail(w, err) - return - } - cacheJSON(w, out) -} -func intQuery(r *http.Request, key string, fallback, min, max int) (int, bool) { - v := r.URL.Query().Get(key) - if v == "" { - return fallback, true - } - n, err := strconv.Atoi(v) - return n, err == nil && n >= min && n <= max -} -func (a *API) batch(w http.ResponseWriter, r *http.Request) { - ids := strings.Split(r.URL.Query().Get("ids"), ",") - if len(ids) > 100 { - writeError(w, 400, "too_many_plugins") - return - } - seen := make(map[string]bool, len(ids)) - unique := make([]string, 0, len(ids)) - for _, id := range ids { - if !catalog.IDPattern.MatchString(id) { - writeError(w, 400, "invalid_plugin") - return - } - if !seen[id] { - unique = append(unique, id) - seen[id] = true - } - } - out, err := a.Store.Batch(r.Context(), unique) - if err != nil { - a.fail(w, err) - return - } - cacheJSON(w, out) -} -func (a *API) total(w http.ResponseWriter, r *http.Request) { - out, err := a.Store.Total(r.Context()) - if err != nil { - a.fail(w, err) - return - } - cacheJSON(w, out) -} - -// DashboardResponse adds display names from the plugin index to the aggregates. -type DashboardResponse struct { - store.DashboardResult - PluginInfo map[string]registry.Plugin `json:"pluginInfo"` -} - -func (a *API) dashboard(w http.ResponseWriter, r *http.Request) { - out, err := a.Store.Dashboard(r.Context()) - if err != nil { - a.fail(w, err) - return - } - ids := make([]string, 0, len(out.Ranking)+len(out.TopVersions)+len(out.Recent)) - for _, p := range out.Ranking { - ids = append(ids, p.PluginID) - } - for _, v := range out.TopVersions { - ids = append(ids, v.PluginID) - } - for _, d := range out.Recent { - ids = append(ids, d.PluginID) - } - cacheJSON(w, DashboardResponse{DashboardResult: out, PluginInfo: a.Registry.Lookup(ids)}) -} - -func (a *API) fail(w http.ResponseWriter, err error) { - switch { - case errors.Is(err, store.ErrNotFound): - writeError(w, 404, "not_found") - case errors.Is(err, store.ErrConflict): - writeError(w, 409, "metadata_conflict") - case errors.Is(err, store.ErrGone), errors.Is(err, store.ErrRevoked): - writeError(w, 410, "unavailable") - default: - if a.Logger != nil { - a.Logger.Error("request failed", "category", "storage_or_signing") - } - writeError(w, 503, "temporarily_unavailable") - } -} -func cacheJSON(w http.ResponseWriter, value any) { - w.Header().Set("Cache-Control", "public, max-age=30") - // These endpoints only expose aggregate download counts without credentials, - // so any origin (including the static docs site) may read them. - w.Header().Set("Access-Control-Allow-Origin", "*") - writeJSON(w, 200, value) -} -func writeError(w http.ResponseWriter, status int, code string) { - writeJSON(w, status, map[string]string{"error": code}) -} -func writeJSON(w http.ResponseWriter, status int, value any) { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - w.WriteHeader(status) - _ = json.NewEncoder(w).Encode(value) -} diff --git a/apps/server/internal/api/api_test.go b/apps/server/internal/api/api_test.go deleted file mode 100644 index e4bc0843..00000000 --- a/apps/server/internal/api/api_test.go +++ /dev/null @@ -1,269 +0,0 @@ -package api - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "toolforge.dev/plugin-stats/internal/asset" - "toolforge.dev/plugin-stats/internal/receipt" - "toolforge.dev/plugin-stats/internal/registry" - "toolforge.dev/plugin-stats/internal/store" -) - -type fakeRepo struct { - issued int - confirmed int - err error - last receipt.Claims -} - -func (f *fakeRepo) Ready(context.Context) error { return f.err } -func (f *fakeRepo) Issue(_ context.Context, id, ver, attempt, kid string, now time.Time) (store.Attempt, error) { - f.issued++ - f.last = receipt.Claims{Kid: kid, AttemptID: attempt, PluginID: id, Version: ver, SHA256: strings.Repeat("a", 64), Size: 42, IssuedAt: now.Unix(), ExpiresAt: now.Add(receipt.Lifetime).Unix()} - return store.Attempt{Claims: f.last, ObjectKey: "packages/plugin/1.0.0/file.tfp"}, f.err -} -func (f *fakeRepo) Confirm(_ context.Context, c receipt.Claims, sha string, size uint64, _ time.Time) error { - if c.SHA256 != sha || c.Size != size { - return store.ErrConflict - } - f.confirmed++ - return f.err -} -func (f *fakeRepo) Version(context.Context, string, string) (store.VersionResult, error) { - return store.VersionResult{Downloads: "9007199254740993"}, f.err -} -func (f *fakeRepo) Plugin(context.Context, string, int, int) (store.PluginResult, error) { - return store.PluginResult{}, f.err -} -func (f *fakeRepo) Batch(context.Context, []string) (store.Stats, error) { - return store.Stats{Plugins: []store.PluginStats{}}, f.err -} -func (f *fakeRepo) Total(context.Context) (store.TotalResult, error) { - return store.TotalResult{TotalDownloads: "9007199254740993"}, f.err -} -func (f *fakeRepo) Dashboard(context.Context) (store.DashboardResult, error) { - return store.DashboardResult{ - TotalDownloads: "9007199254740993", - Ranking: []store.RankedPlugin{{PluginID: "org.devlive.toolforge.hash", Downloads: "3"}, {PluginID: "org.devlive.toolforge.unknown", Downloads: "1"}}, - TopVersions: []store.RankedVersion{}, - Daily: []store.DailyDownloads{}, - Recent: []store.RecentDownload{}, - }, f.err -} -func fixtureAPI() (*API, *fakeRepo) { - signer, _ := receipt.New("k1", map[string][]byte{"k1": bytes.Repeat([]byte{7}, 32)}) - repo := &fakeRepo{} - return &API{Store: repo, Signer: signer, AssetBaseURL: "https://plugins.toolforge.devlive.org", BuildSHA: "test-sha", Now: func() time.Time { return time.Unix(1700000000, 0) }}, repo -} -func TestDownloadPresignsForPrivateBucket(t *testing.T) { - a, _ := fixtureAPI() - a.Presigner = &asset.Presigner{SecretID: "AKIDexample", SecretKey: "secret-key", Now: a.Now} - h := a.Handler() - req := httptest.NewRequest("GET", "/v1/plugins/plugin/versions/1.0.0/download", nil) - req.Header.Set("Idempotency-Key", strings.Repeat("d", 32)) - w := httptest.NewRecorder() - h.ServeHTTP(w, req) - location := w.Header().Get("Location") - if w.Code != 302 { - t.Fatalf("download status %d", w.Code) - } - for _, part := range []string{ - "packages/plugin/1.0.0/file.tfp", - "q-sign-algorithm=sha1", - "q-ak=AKIDexample", - "q-sign-time=1700000000;1700000600", - "q-url-param-list=&q-signature=", - } { - if !strings.Contains(location, part) { - t.Fatalf("presigned location missing %q: %s", part, location) - } - } -} - -func TestDownloadAndReceiptHTTPContract(t *testing.T) { - a, repo := fixtureAPI() - h := a.Handler() - req := httptest.NewRequest("GET", "/v1/plugins/plugin/versions/1.0.0/download", nil) - req.Header.Set("Idempotency-Key", strings.Repeat("c", 32)) - w := httptest.NewRecorder() - h.ServeHTTP(w, req) - if w.Code != 302 || w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("Location") != "https://plugins.toolforge.devlive.org/packages/plugin/1.0.0/file.tfp" { - t.Fatalf("download status/headers: %d %v", w.Code, w.Header()) - } - if w.Header().Get("X-ToolForge-Attempt-Id") != strings.Repeat("c", 32) || w.Header().Get("X-ToolForge-Receipt-Expires") == "" { - t.Fatal("missing attempt headers") - } - token := w.Header().Get("X-ToolForge-Receipt") - complete := func(body, auth string) int { - r := httptest.NewRequest("POST", "/v1/downloads/"+repo.last.AttemptID+"/complete", strings.NewReader(body)) - r.Header.Set("Content-Type", "application/json") - r.Header.Set("Authorization", auth) - rr := httptest.NewRecorder() - h.ServeHTTP(rr, r) - return rr.Code - } - body := `{"sha256":"` + strings.Repeat("a", 64) + `","size":42}` - if code := complete(body, "Bearer "+token); code != 200 { - t.Fatalf("complete status %d", code) - } - if repo.confirmed != 1 { - t.Fatal("confirmation not stored") - } - if code := complete(body, "Bearer bad"); code != 401 { - t.Fatalf("bad auth %d", code) - } - if code := complete(`{"sha256":"`+strings.Repeat("b", 64)+`","size":42}`, "Bearer "+token); code != 409 { - t.Fatalf("bad hash %d", code) - } - if code := complete(body+"{}", "Bearer "+token); code != 400 { - t.Fatalf("trailing data %d", code) - } - if code := complete(strings.Repeat(" ", 5000)+body, "Bearer "+token); code != 400 { - t.Fatalf("oversized data %d", code) - } - a.Now = func() time.Time { return time.Unix(repo.last.ExpiresAt, 0) } - if code := complete(body, "Bearer "+token); code != 410 { - t.Fatalf("expired receipt %d", code) - } -} -func TestLegacyRedirectHeadAndBadParameters(t *testing.T) { - a, repo := fixtureAPI() - h := a.Handler() - r := httptest.NewRequest("GET", "/v1/plugins/plugin/versions/1.0.0/download", nil) - w := httptest.NewRecorder() - h.ServeHTTP(w, r) - if w.Code != 302 || len(repo.last.AttemptID) != 32 { - t.Fatal("legacy request did not redirect") - } - before := repo.issued - r = httptest.NewRequest("HEAD", "/v1/plugins/plugin/versions/1.0.0/download", nil) - w = httptest.NewRecorder() - h.ServeHTTP(w, r) - if w.Code != 405 || repo.issued != before { - t.Fatal("HEAD created an attempt") - } - for _, url := range []string{"/v1/stats?ids=", "/v1/stats?ids=" + strings.Repeat("a,", 100) + "b", "/v1/plugins/plugin/stats?limit=101", "/v1/plugins/plugin/stats?offset=-1"} { - w = httptest.NewRecorder() - h.ServeHTTP(w, httptest.NewRequest("GET", url, nil)) - if w.Code != 400 { - t.Fatalf("accepted %q: %d", url, w.Code) - } - } - r = httptest.NewRequest("GET", "/v1/plugins/plugin/versions/1.0.0/download", nil) - r.Header.Set("Idempotency-Key", "BAD") - w = httptest.NewRecorder() - h.ServeHTTP(w, r) - if w.Code != 400 { - t.Fatal("accepted bad key") - } -} -func TestStatsCountPrecisionReadinessAndSafeErrors(t *testing.T) { - a, repo := fixtureAPI() - h := a.Handler() - w := httptest.NewRecorder() - h.ServeHTTP(w, httptest.NewRequest("GET", "/v1/stats/total", nil)) - var body map[string]any - if json.Unmarshal(w.Body.Bytes(), &body) != nil || body["totalDownloads"] != "9007199254740993" { - t.Fatal("count precision lost") - } - if w.Header().Get("Cache-Control") != "public, max-age=30" { - t.Fatal("missing statistics cache") - } - if w.Header().Get("Access-Control-Allow-Origin") != "*" { - t.Fatal("missing cross-origin read permission") - } - repo.err = errors.New("password=must-not-leak") - for _, path := range []string{"/readyz", "/v1/stats/total"} { - w = httptest.NewRecorder() - h.ServeHTTP(w, httptest.NewRequest("GET", path, nil)) - if w.Code != 503 || strings.Contains(w.Body.String(), "must-not-leak") { - t.Fatal("unsafe failure response") - } - } - repo.err = store.ErrNotFound - w = httptest.NewRecorder() - h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/v1/plugins/unknown/stats", nil)) - if w.Code != 404 { - t.Fatal("unknown plugin is not 404") - } -} - -func TestDashboardMergesPluginNames(t *testing.T) { - index := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _, _ = w.Write([]byte(`{"plugins":[{"id":"org.devlive.toolforge.hash","category":"dev","names":{"zh-CN":"哈希计算","en-US":"Hash"}}]}`)) - })) - defer index.Close() - a, repo := fixtureAPI() - a.Registry = ®istry.Cache{URL: index.URL, Client: index.Client()} - if err := a.Registry.Refresh(context.Background()); err != nil { - t.Fatal(err) - } - w := httptest.NewRecorder() - a.Handler().ServeHTTP(w, httptest.NewRequest("GET", "/v1/dashboard", nil)) - if w.Code != 200 || w.Header().Get("Access-Control-Allow-Origin") != "*" || !strings.Contains(w.Header().Get("Cache-Control"), "max-age") { - t.Fatalf("dashboard response %d %v", w.Code, w.Header()) - } - var body struct { - TotalDownloads string `json:"totalDownloads"` - PluginInfo map[string]struct { - Names map[string]string `json:"names"` - } `json:"pluginInfo"` - } - if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { - t.Fatal(err) - } - if body.TotalDownloads != "9007199254740993" || body.PluginInfo["org.devlive.toolforge.hash"].Names["zh-CN"] != "哈希计算" { - t.Fatalf("dashboard body: %s", w.Body.String()) - } - if _, ok := body.PluginInfo["org.devlive.toolforge.unknown"]; ok { - t.Fatal("unknown plugin got metadata") - } - - a.Registry = nil - w = httptest.NewRecorder() - a.Handler().ServeHTTP(w, httptest.NewRequest("GET", "/v1/dashboard", nil)) - if w.Code != 200 || !strings.Contains(w.Body.String(), `"pluginInfo":{}`) { - t.Fatalf("dashboard without registry: %d %s", w.Code, w.Body.String()) - } - repo.err = errors.New("database down") - w = httptest.NewRecorder() - a.Handler().ServeHTTP(w, httptest.NewRequest("GET", "/v1/dashboard", nil)) - if w.Code != 503 { - t.Fatalf("storage failure returned %d", w.Code) - } -} - -func TestDashboardPageAndAssets(t *testing.T) { - a, _ := fixtureAPI() - h := a.Handler() - for _, tc := range []struct{ path, contentType, cache string }{ - {"/", "text/html", "no-cache"}, - {"/assets/dashboard.js", "text/javascript", "max-age=300"}, - {"/assets/dashboard.css", "text/css", "max-age=300"}, - {"/assets/logo.png", "image/png", "max-age=300"}, - } { - w := httptest.NewRecorder() - h.ServeHTTP(w, httptest.NewRequest("GET", tc.path, nil)) - if w.Code != 200 || !strings.HasPrefix(w.Header().Get("Content-Type"), tc.contentType) || !strings.Contains(w.Header().Get("Cache-Control"), tc.cache) { - t.Fatalf("%s: %d %v", tc.path, w.Code, w.Header()) - } - if !strings.Contains(w.Header().Get("Content-Security-Policy"), "script-src 'self'") { - t.Fatalf("%s: missing CSP", tc.path) - } - } - for _, path := range []string{"/assets/index.html", "/assets/../go.mod", "/index.html", "/other"} { - w := httptest.NewRecorder() - h.ServeHTTP(w, httptest.NewRequest("GET", path, nil)) - if w.Code == 200 { - t.Fatalf("%s served", path) - } - } -} diff --git a/apps/server/internal/asset/asset.go b/apps/server/internal/asset/asset.go deleted file mode 100644 index b6f60595..00000000 --- a/apps/server/internal/asset/asset.go +++ /dev/null @@ -1,63 +0,0 @@ -// Package asset builds download URLs for COS objects. A private bucket needs -// a presigned URL; public buckets keep the plain base URL untouched. -package asset - -import ( - "crypto/hmac" - "crypto/sha1" - "encoding/hex" - "net/url" - "strconv" - "strings" - "time" -) - -// Presigner signs COS object GET URLs with the XML API presign algorithm. -type Presigner struct { - SecretID string - SecretKey string - // TTL is the validity window of one URL; it defaults to ten minutes. - TTL time.Duration - Now func() time.Time -} - -func (p *Presigner) now() time.Time { - if p.Now != nil { - return p.Now().UTC() - } - return time.Now().UTC() -} - -func (p *Presigner) ttl() time.Duration { - if p.TTL > 0 { - return p.TTL - } - return 10 * time.Minute -} - -// Presign returns a signed GET URL for key (given without a leading slash) -// served from host. The signature covers only the request path, so custom -// COS domains work as long as they resolve to the same bucket. -func (p *Presigner) Presign(host, key string) string { - host = strings.TrimRight(host, "/") - key = strings.TrimLeft(key, "/") - now := p.now().Unix() - keyTime := strconv.FormatInt(now, 10) + ";" + strconv.FormatInt(now+int64(p.ttl().Seconds()), 10) - signKey := hex.EncodeToString(hmacSHA1([]byte(p.SecretKey), []byte(keyTime))) - // Lowercase verb, URI path, empty query and header lists: exactly what a - // plain GET from any HTTP client produces for this URL. - httpString := "get\n/" + key + "\n\n\n" - sum := sha1.Sum([]byte(httpString)) - stringToSign := "sha1\n" + keyTime + "\n" + hex.EncodeToString(sum[:]) + "\n" - signature := hex.EncodeToString(hmacSHA1([]byte(signKey), []byte(stringToSign))) - return host + "/" + key + - "?q-sign-algorithm=sha1&q-ak=" + url.QueryEscape(p.SecretID) + - "&q-sign-time=" + keyTime + "&q-key-time=" + keyTime + - "&q-header-list=&q-url-param-list=&q-signature=" + signature -} - -func hmacSHA1(key, message []byte) []byte { - mac := hmac.New(sha1.New, key) - mac.Write(message) - return mac.Sum(nil) -} diff --git a/apps/server/internal/asset/asset_test.go b/apps/server/internal/asset/asset_test.go deleted file mode 100644 index 089ad7c9..00000000 --- a/apps/server/internal/asset/asset_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package asset - -import ( - "crypto/sha1" - "encoding/hex" - "net/url" - "strings" - "testing" - "time" -) - -func TestPresignProducesSignedCOSURL(t *testing.T) { - now := time.Unix(1767225600, 0) - p := &Presigner{SecretID: "AKIDexample", SecretKey: "secret-key", Now: func() time.Time { return now }} - got := p.Presign("https://plugins.example.com/", "packages/x/1.0.0/abc.tfp") - - if !strings.HasPrefix(got, "https://plugins.example.com/packages/x/1.0.0/abc.tfp?") { - t.Fatalf("URL must target the object key: %s", got) - } - // 签名有效期 10 分钟:1767225600 到 1767226200 - if !strings.Contains(got, "q-sign-time=1767225600;1767226200") || !strings.Contains(got, "q-key-time=1767225600;1767226200") { - t.Fatalf("missing key time window: %s", got) - } - if !strings.Contains(got, "q-ak=AKIDexample") || !strings.Contains(got, "q-header-list=&q-url-param-list=&q-signature=") { - t.Fatalf("missing ak or signature parts: %s", got) - } - // 独立复算签名:SignKey = HMAC(SecretKey, KeyTime);Signature = HMAC(SignKey, StringToSign) - keyTime := "1767225600;1767226200" - signKey := hex.EncodeToString(hmacSHA1([]byte("secret-key"), []byte(keyTime))) - sum := sha1.Sum([]byte("get\n/packages/x/1.0.0/abc.tfp\n\n\n")) - stringToSign := "sha1\n" + keyTime + "\n" + hex.EncodeToString(sum[:]) + "\n" - want := hex.EncodeToString(hmacSHA1([]byte(signKey), []byte(stringToSign))) - if !strings.HasSuffix(got, "q-signature="+want) { - t.Fatalf("signature mismatch:\n got %s\nwant suffix %s", got, want) - } -} - -func TestPresignEscapesAndTrims(t *testing.T) { - p := &Presigner{SecretID: "AKID needs/escape", SecretKey: "k", TTL: time.Minute, Now: func() time.Time { return time.Unix(0, 0) }} - got := p.Presign("https://host.example//", "/leading/slash/key") - if strings.HasPrefix(got, "https://host.example//") { - t.Fatalf("double slash must be trimmed: %s", got) - } - if !strings.Contains(got, "q-ak="+url.QueryEscape("AKID needs/escape")) { - t.Fatalf("secret id must be query escaped: %s", got) - } - if !strings.Contains(got, "q-sign-time=0;60") { - t.Fatalf("one minute TTL not applied: %s", got) - } -} diff --git a/apps/server/internal/catalog/catalog.go b/apps/server/internal/catalog/catalog.go deleted file mode 100644 index efae6ed4..00000000 --- a/apps/server/internal/catalog/catalog.go +++ /dev/null @@ -1,98 +0,0 @@ -// Package catalog validates the immutable official release catalog. Import is a -// local administrative operation, never an HTTP endpoint. -package catalog - -import ( - "bytes" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "io" - "path" - "regexp" - "strings" - "time" -) - -const MaxCatalogBytes = 16 << 20 -const MaxPackages = 10000 -const MaxPackageSize = 64 * 1024 * 1024 - -var IDPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,190}$`) -var VersionPattern = regexp.MustCompile(`^[0-9A-Za-z][0-9A-Za-z.+-]{0,63}$`) -var SHAPattern = regexp.MustCompile(`^[0-9a-f]{64}$`) -var AttemptPattern = regexp.MustCompile(`^[0-9a-f]{32}$`) -var CommitPattern = regexp.MustCompile(`^[0-9a-f]{40}([0-9a-f]{24})?$`) - -// Generation is a monotonically increasing release sequence, normally the -// GitHub run number. It prevents delayed workflows publishing an older catalog. -type Catalog struct { - SchemaVersion int `json:"schemaVersion"` - SourceCommit string `json:"sourceCommit"` - Generation uint64 `json:"generation"` - Plugins []Package `json:"plugins"` -} -type Package struct { - ID string `json:"id"` - Version string `json:"version"` - SHA256 string `json:"sha256"` - Size uint64 `json:"size"` - ObjectKey string `json:"objectKey"` - Status string `json:"status"` - PublishedAt time.Time `json:"publishedAt,omitempty"` -} - -func Read(r io.Reader) (Catalog, string, error) { - var c Catalog - raw, err := io.ReadAll(io.LimitReader(r, MaxCatalogBytes+1)) - if err != nil || len(raw) > MaxCatalogBytes { - return c, "", errors.New("catalog cannot be read or exceeds limit") - } - dec := json.NewDecoder(bytes.NewReader(raw)) - dec.DisallowUnknownFields() - if err := dec.Decode(&c); err != nil { - return c, "", errors.New("invalid catalog JSON") - } - if dec.Decode(new(any)) != io.EOF { - return c, "", errors.New("unexpected trailing catalog data") - } - if err := c.Validate(); err != nil { - return c, "", err - } - // Digest canonical JSON, so harmless whitespace changes remain idempotent. - canonical, _ := json.Marshal(c) - digest := sha256.Sum256(canonical) - return c, hex.EncodeToString(digest[:]), nil -} - -func (c Catalog) Validate() error { - if c.SchemaVersion != 1 || !CommitPattern.MatchString(c.SourceCommit) || c.Generation == 0 { - return errors.New("catalog requires schemaVersion 1, sourceCommit and positive generation") - } - if len(c.Plugins) == 0 || len(c.Plugins) > MaxPackages { - return errors.New("catalog package count out of range") - } - seen := make(map[string]bool, len(c.Plugins)) - for _, p := range c.Plugins { - if !IDPattern.MatchString(p.ID) || !VersionPattern.MatchString(p.Version) || !SHAPattern.MatchString(p.SHA256) || p.Size == 0 || p.Size > MaxPackageSize { - return fmt.Errorf("invalid metadata for %q version %q", p.ID, p.Version) - } - if p.Status != "active" && p.Status != "withdrawn" && p.Status != "revoked" { - return errors.New("invalid package status") - } - // This is a path, never a client-supplied URL. Prevent encoded traversal, - // fragments, queries, backslashes, and escape outside the package prefix. - expected := "packages/" + p.ID + "/" + p.Version + "/" + p.SHA256 + ".tfp" - if p.ObjectKey != expected || path.Clean(p.ObjectKey) != p.ObjectKey || strings.ContainsAny(p.ObjectKey, "%?#\\") { - return errors.New("objectKey must match immutable package path") - } - key := p.ID + "\x00" + p.Version - if seen[key] { - return errors.New("duplicate plugin version") - } - seen[key] = true - } - return nil -} diff --git a/apps/server/internal/catalog/catalog_test.go b/apps/server/internal/catalog/catalog_test.go deleted file mode 100644 index d03ff60b..00000000 --- a/apps/server/internal/catalog/catalog_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package catalog - -import ( - "encoding/json" - "strings" - "testing" -) - -func fixture() Catalog { - sha := strings.Repeat("a", 64) - return Catalog{SchemaVersion: 1, SourceCommit: strings.Repeat("b", 40), Generation: 1, Plugins: []Package{{ID: "json-formatter", Version: "1.0.0", SHA256: sha, Size: 42, ObjectKey: "packages/json-formatter/1.0.0/" + sha + ".tfp", Status: "active"}}} -} -func TestCatalogCanonicalDigestAndValidation(t *testing.T) { - c := fixture() - raw, _ := json.Marshal(c) - _, digest, err := Read(strings.NewReader(string(raw))) - if err != nil { - t.Fatal(err) - } - _, digest2, err := Read(strings.NewReader(" \n" + string(raw) + "\n")) - if err != nil || digest != digest2 { - t.Fatal("whitespace changed digest") - } - cases := []struct { - name string - mutate func(*Catalog) - }{ - {"traversal", func(c *Catalog) { c.Plugins[0].ObjectKey = "packages/../secret" }}, - {"external", func(c *Catalog) { c.Plugins[0].ObjectKey = "https://attacker.invalid/file" }}, - {"duplicate", func(c *Catalog) { c.Plugins = append(c.Plugins, c.Plugins[0]) }}, - {"generation", func(c *Catalog) { c.Generation = 0 }}, - {"sha", func(c *Catalog) { c.Plugins[0].SHA256 = "bad" }}, - {"status", func(c *Catalog) { c.Plugins[0].Status = "deleted" }}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - c := fixture() - tc.mutate(&c) - if c.Validate() == nil { - t.Fatal("accepted invalid catalog") - } - }) - } - if _, _, err := Read(strings.NewReader(string(raw) + "{}")); err == nil { - t.Fatal("accepted trailing JSON") - } - if _, _, err := Read(strings.NewReader(`{"schemaVersion":1,"unknown":true}`)); err == nil { - t.Fatal("accepted unknown field") - } -} diff --git a/apps/server/internal/config/config.go b/apps/server/internal/config/config.go deleted file mode 100644 index 46b78645..00000000 --- a/apps/server/internal/config/config.go +++ /dev/null @@ -1,125 +0,0 @@ -package config - -import ( - "encoding/base64" - "encoding/json" - "errors" - "net" - "net/url" - "os" - "strings" - "time" - - "github.com/go-sql-driver/mysql" - "toolforge.dev/plugin-stats/internal/receipt" -) - -type Config struct { - ListenAddr, AssetBaseURL, DSN string - Signer *receipt.Signer - // COS credentials enable presigned download URLs for private buckets; - // both values must be set together, otherwise plain URLs are served. - CosSecretID, CosSecretKey string - // RegistryURL is the public plugin index read for dashboard names; empty disables names. - RegistryURL string -} - -func env(key, fallback string) string { - if value, ok := os.LookupEnv(key); ok { - return value - } - return fallback -} - -// Read never includes environment values in an error. The same binary uses -// independently protected runtime, migration, and catalog environment files. -func Read(serving bool) (Config, error) { - var c Config - rawDSN := os.Getenv("MYSQL_DSN") - var db *mysql.Config - var err error - if rawDSN != "" { - db, err = mysql.ParseDSN(rawDSN) - if err != nil { - return c, errors.New("invalid MYSQL_DSN") - } - } else { - db = mysql.NewConfig() - db.User = os.Getenv("MYSQL_USER") - db.Passwd = os.Getenv("MYSQL_PASSWORD") - db.DBName = env("MYSQL_DATABASE", "toolforge_stats") - db.Net = "unix" - db.Addr = env("MYSQL_SOCKET", "/var/run/mysqld/mysqld.sock") - } - if db.User == "" || db.DBName == "" || db.User == "root" || db.AllowAllFiles || db.AllowCleartextPasswords || db.AllowNativePasswords == false { - return c, errors.New("invalid or unsafe MySQL account configuration") - } - if db.Net != "unix" && (db.Net != "tcp" || !loopbackHostPort(db.Addr)) { - return c, errors.New("MySQL must use a local socket or loopback address") - } - db.ParseTime = true - db.Loc = time.UTC - db.Timeout = 5 * time.Second - db.ReadTimeout = 5 * time.Second - db.WriteTimeout = 5 * time.Second - db.MultiStatements = false - db.InterpolateParams = false - if db.Params == nil { - db.Params = map[string]string{} - } - db.Params["time_zone"] = "'+00:00'" - c.DSN = db.FormatDSN() - if !serving { - return c, nil - } - c.ListenAddr = env("STATS_LISTEN_ADDR", "127.0.0.1:8088") - if !loopbackHostPort(c.ListenAddr) { - return c, errors.New("STATS_LISTEN_ADDR must bind a loopback address") - } - c.AssetBaseURL = strings.TrimRight(env("PLUGIN_ASSET_BASE_URL", "https://plugins.toolforge.devlive.org"), "/") - asset, err := url.Parse(c.AssetBaseURL) - if err != nil || asset.Scheme != "https" || asset.Host == "" || asset.User != nil || asset.RawQuery != "" || asset.Fragment != "" || asset.Path != "" || asset.Opaque != "" { - return c, errors.New("PLUGIN_ASSET_BASE_URL requires an HTTPS origin") - } - var encoded map[string]string - if err := json.Unmarshal([]byte(os.Getenv("RECEIPT_KEYS_JSON")), &encoded); err != nil { - return c, errors.New("invalid RECEIPT_KEYS_JSON") - } - keys := make(map[string][]byte, len(encoded)) - for kid, value := range encoded { - key, err := base64.StdEncoding.DecodeString(value) - if err != nil { - return c, errors.New("receipt key must be standard base64") - } - keys[kid] = key - } - c.Signer, err = receipt.New(os.Getenv("RECEIPT_ACTIVE_KID"), keys) - if err != nil { - return c, errors.New("invalid receipt keyring") - } - // Unset keeps the public plugin index; an explicitly empty value disables - // dashboard names without failing the deployment. - if value, ok := os.LookupEnv("PLUGIN_REGISTRY_URL"); ok { - c.RegistryURL = value - } - if c.RegistryURL != "" { - index, err := url.Parse(c.RegistryURL) - if err != nil || index.Scheme != "https" || index.Host == "" || index.User != nil || index.Fragment != "" { - return c, errors.New("PLUGIN_REGISTRY_URL requires an HTTPS URL") - } - } - c.CosSecretID = os.Getenv("COS_SECRET_ID") - c.CosSecretKey = os.Getenv("COS_SECRET_KEY") - if (c.CosSecretID == "") != (c.CosSecretKey == "") { - return c, errors.New("COS_SECRET_ID and COS_SECRET_KEY must be set together") - } - return c, nil -} -func loopbackHostPort(addr string) bool { - host, port, err := net.SplitHostPort(addr) - if err != nil || port == "" || port == "0" { - return false - } - ip := net.ParseIP(host) - return ip != nil && ip.IsLoopback() -} diff --git a/apps/server/internal/config/config_test.go b/apps/server/internal/config/config_test.go deleted file mode 100644 index 1bef5bba..00000000 --- a/apps/server/internal/config/config_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package config - -import ( - "strings" - "testing" -) - -func baseEnv(t *testing.T) { - t.Helper() - t.Setenv("MYSQL_DSN", "") - t.Setenv("MYSQL_USER", "toolforge_runtime") - t.Setenv("MYSQL_PASSWORD", "test-password") - t.Setenv("MYSQL_DATABASE", "toolforge_stats") - t.Setenv("MYSQL_SOCKET", "/tmp/mysql.sock") - t.Setenv("STATS_LISTEN_ADDR", "127.0.0.1:8088") - t.Setenv("PLUGIN_ASSET_BASE_URL", "https://plugins.toolforge.devlive.org") - t.Setenv("RECEIPT_ACTIVE_KID", "k1") - t.Setenv("RECEIPT_KEYS_JSON", `{"k1":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}`) -} -func TestSafeConfiguration(t *testing.T) { - baseEnv(t) - c, err := Read(true) - if err != nil { - t.Fatal(err) - } - if !strings.Contains(c.DSN, "parseTime=true") || c.Signer == nil { - t.Fatal("missing configuration") - } - t.Setenv("PLUGIN_REGISTRY_URL", "") - c, err = Read(true) - if err != nil || c.RegistryURL != "" { - t.Fatal("explicitly empty registry URL must disable dashboard names") - } - t.Setenv("RECEIPT_KEYS_JSON", "not-secret-json") - if _, err := Read(false); err != nil { - t.Fatal("administrative CLI required receipt keys") - } -} -func TestUnsafeConfigurationRejected(t *testing.T) { - for _, tc := range []struct{ key, value string }{{"STATS_LISTEN_ADDR", "0.0.0.0:8088"}, {"PLUGIN_ASSET_BASE_URL", "http://insecure.invalid"}, {"PLUGIN_ASSET_BASE_URL", "https://user:password@host.invalid"}, {"MYSQL_USER", "root"}, {"PLUGIN_REGISTRY_URL", "http://plugins.invalid/registry.json"}, {"PLUGIN_REGISTRY_URL", "https://user:password@plugins.invalid/registry.json"}, {"PLUGIN_REGISTRY_URL", "https://plugins.invalid/registry.json#frag"}, {"MYSQL_DSN", "user:secret@tcp(remote.invalid:3306)/db"}, {"RECEIPT_KEYS_JSON", `{"k1":"c2hvcnQ="}`}} { - t.Run(tc.key+tc.value, func(t *testing.T) { - baseEnv(t) - t.Setenv(tc.key, tc.value) - if _, err := Read(true); err == nil { - t.Fatal("unsafe configuration accepted") - } else if strings.Contains(err.Error(), tc.value) { - t.Fatal("configuration value leaked in error") - } - }) - } -} diff --git a/apps/server/internal/dashboard/dashboard.go b/apps/server/internal/dashboard/dashboard.go deleted file mode 100644 index a7a122cb..00000000 --- a/apps/server/internal/dashboard/dashboard.go +++ /dev/null @@ -1,52 +0,0 @@ -// Package dashboard serves the public statistics dashboard at the site root. -// The page is static and embedded in the binary; data comes from /v1/dashboard. -package dashboard - -import ( - "embed" - "io/fs" - "net/http" - "path" -) - -//go:embed static -var files embed.FS - -// Only the embedded page, script and stylesheet can load; no inline code, -// external hosts, frames or form submissions. -const contentSecurityPolicy = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; frame-ancestors 'none'; form-action 'none'" - -var contentTypes = map[string]string{ - ".html": "text/html; charset=utf-8", - ".css": "text/css; charset=utf-8", - ".js": "text/javascript; charset=utf-8", - ".png": "image/png", -} - -func serve(w http.ResponseWriter, name, cache string) { - data, err := fs.ReadFile(files, "static/"+name) - contentType, known := contentTypes[path.Ext(name)] - if err != nil || !known { - http.NotFound(w, nil) - return - } - w.Header().Set("Content-Type", contentType) - w.Header().Set("Content-Security-Policy", contentSecurityPolicy) - w.Header().Set("Cache-Control", cache) - _, _ = w.Write(data) -} - -// Index serves the dashboard page; it is revalidated so a deploy shows at once. -func Index(w http.ResponseWriter, _ *http.Request) { - serve(w, "index.html", "no-cache") -} - -// Asset serves the dashboard script, stylesheet and logo. -func Asset(w http.ResponseWriter, r *http.Request) { - name := r.PathValue("file") - if name != "dashboard.js" && name != "dashboard.css" && name != "logo.png" { - http.NotFound(w, r) - return - } - serve(w, name, "public, max-age=300") -} diff --git a/apps/server/internal/dashboard/static/dashboard.css b/apps/server/internal/dashboard/static/dashboard.css deleted file mode 100644 index 315a793e..00000000 --- a/apps/server/internal/dashboard/static/dashboard.css +++ /dev/null @@ -1,509 +0,0 @@ -:root { - --bg: #070d0a; - --panel: #0e1813; - --panel-2: #13211a; - --line: #1f3328; - --ink: #e8f3ec; - --sub: #9db3a6; - --quiet: #6b8376; - --brand: #3ddc84; - --brand-2: #24b366; - --brand-soft: rgba(61, 220, 132, 0.14); - --warn: #f5b84a; - --radius: 14px; - font-family: - 'Inter', - -apple-system, - 'PingFang SC', - 'Microsoft YaHei', - system-ui, - sans-serif; -} -* { - box-sizing: border-box; -} -html, -body { - margin: 0; - min-height: 100%; -} -body { - background: - radial-gradient(1200px 600px at 10% -10%, rgba(61, 220, 132, 0.12), transparent 60%), - radial-gradient(900px 500px at 110% 10%, rgba(36, 179, 102, 0.1), transparent 60%), - var(--bg); - color: var(--ink); - padding: 24px clamp(16px, 3vw, 40px) 20px; - display: flex; - flex-direction: column; - gap: 20px; -} -h1, -h2, -p { - margin: 0; -} -.top { - display: flex; - align-items: center; - justify-content: space-between; - gap: 16px; - flex-wrap: wrap; -} -.brand { - display: flex; - align-items: center; - gap: 14px; -} -.logo { - display: block; - width: 40px; - height: 40px; - border-radius: 11px; - filter: drop-shadow(0 0 14px rgba(61, 220, 132, 0.35)); -} -.brand h1 { - font-size: clamp(20px, 2.2vw, 28px); - font-weight: 700; - letter-spacing: -0.3px; -} -.brand p { - color: var(--sub); - font-size: 13px; - margin-top: 2px; -} -.status { - display: flex; - align-items: center; - gap: 8px; - color: var(--sub); - font-size: 13px; - padding: 8px 14px; - border: 1px solid var(--line); - border-radius: 999px; - background: rgba(14, 24, 19, 0.7); -} -.live { - width: 8px; - height: 8px; - border-radius: 50%; - background: var(--brand); - box-shadow: 0 0 0 0 rgba(61, 220, 132, 0.6); - animation: pulse 2s infinite; -} -.status.error .live { - background: var(--warn); - animation: none; -} -@keyframes pulse { - 70% { - box-shadow: 0 0 0 8px rgba(61, 220, 132, 0); - } - 100% { - box-shadow: 0 0 0 0 rgba(61, 220, 132, 0); - } -} -main { - display: flex; - flex-direction: column; - gap: 20px; - flex: 1; -} -.kpis { - display: grid; - grid-template-columns: repeat(6, minmax(0, 1fr)); - gap: 14px; -} -.kpi, -.card { - background: linear-gradient(180deg, var(--panel-2), var(--panel)); - border: 1px solid var(--line); - border-radius: var(--radius); -} -.kpi { - padding: 16px 18px; - min-width: 0; -} -.kpi h2 { - font-size: 13px; - font-weight: 500; - color: var(--sub); -} -.kpi .value { - font-size: clamp(26px, 2.6vw, 38px); - font-weight: 700; - letter-spacing: -0.5px; - margin-top: 8px; - font-variant-numeric: tabular-nums; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} -.kpi .hint { - font-size: 12px; - color: var(--quiet); - margin-top: 6px; - min-height: 1em; -} -.kpi-primary { - border-color: rgba(61, 220, 132, 0.45); - box-shadow: inset 0 0 0 1px rgba(61, 220, 132, 0.08), 0 0 40px rgba(61, 220, 132, 0.08); -} -.kpi-primary .value { - color: var(--brand); - font-size: clamp(30px, 3.2vw, 46px); -} -.up { - color: var(--brand); -} -.down { - color: var(--warn); -} -.grid { - display: grid; - grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); - grid-template-areas: - 'trend ranking' - 'versions recent'; - gap: 16px; - flex: 1; -} -.trend { - grid-area: trend; -} -.ranking { - grid-area: ranking; -} -.versions { - grid-area: versions; -} -.recent { - grid-area: recent; -} -.card { - padding: 16px 18px; - display: flex; - flex-direction: column; - min-width: 0; - min-height: 0; -} -.card > header { - display: flex; - align-items: center; - justify-content: space-between; - gap: 10px; - margin-bottom: 12px; -} -.card h2 { - font-size: 15px; - font-weight: 600; -} -.tag { - font-size: 11px; - color: var(--brand); - background: var(--brand-soft); - border-radius: 6px; - padding: 3px 8px; - letter-spacing: 0.3px; -} -.chart { - flex: 1; - min-height: 240px; - position: relative; -} -.chart svg { - width: 100%; - height: 100%; - display: block; - overflow: visible; -} -.chart .grid-line { - stroke: var(--line); - stroke-dasharray: 3 4; -} -.chart .axis { - fill: var(--quiet); - font-size: 11px; -} -.chart .bar { - fill: url(#barFill); - transition: opacity 0.2s; - pointer-events: none; -} -.chart .bar.active { - opacity: 0.8; -} -.chart .bar.pinned { - stroke: var(--brand); - stroke-width: 1.5; -} -.chart .hit { - fill: transparent; - cursor: pointer; -} -.chart .area, -.chart .line, -.chart .dot { - pointer-events: none; -} -.chart-tip { - position: absolute; - z-index: 2; - pointer-events: none; - background: rgba(10, 20, 15, 0.95); - border: 1px solid var(--line); - color: var(--ink); - font-size: 12px; - line-height: 1.5; - padding: 7px 10px; - border-radius: 8px; - box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4); - white-space: nowrap; - transform: translate(-50%, calc(-100% - 10px)); - font-variant-numeric: tabular-nums; -} -.chart .area { - fill: url(#areaFill); -} -.chart .line { - fill: none; - stroke: var(--brand); - stroke-width: 2; -} -.chart .dot { - fill: var(--bg); - stroke: var(--brand); - stroke-width: 2; -} -.bars { - list-style: none; - margin: 0; - padding: 0; - display: flex; - flex-direction: column; - gap: 10px; -} -.bars li { - display: grid; - grid-template-columns: 26px minmax(0, 1fr) auto; - align-items: center; - gap: 4px 10px; -} -.rank { - width: 22px; - height: 22px; - border-radius: 6px; - display: inline-flex; - align-items: center; - justify-content: center; - font-size: 12px; - font-weight: 700; - background: var(--panel-2); - color: var(--sub); - border: 1px solid var(--line); -} -.bars li:nth-child(1) .rank { - background: linear-gradient(135deg, #ffd66b, #f5a524); - color: #2a1a00; - border: 0; -} -.bars li:nth-child(2) .rank { - background: linear-gradient(135deg, #e6edf0, #aab7bf); - color: #1d2428; - border: 0; -} -.bars li:nth-child(3) .rank { - background: linear-gradient(135deg, #f0b88a, #c97b43); - color: #2a1404; - border: 0; -} -.name { - font-size: 13px; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} -.count { - font-size: 13px; - font-weight: 600; - font-variant-numeric: tabular-nums; -} -.track { - grid-column: 2 / 4; - height: 6px; - background: var(--panel-2); - border-radius: 999px; - overflow: hidden; -} -.fill { - height: 100%; - background: linear-gradient(90deg, var(--brand-2), var(--brand)); - border-radius: 999px; - transition: width 0.6s ease; -} -.share { - color: var(--quiet); - font-weight: 400; - margin-left: 6px; -} -table { - width: 100%; - border-collapse: collapse; - font-size: 13px; -} -th, -td { - text-align: left; - padding: 8px 4px; - border-bottom: 1px solid var(--line); - white-space: nowrap; -} -th { - color: var(--quiet); - font-weight: 500; - font-size: 12px; -} -td:first-child { - max-width: 0; - width: 60%; - overflow: hidden; - text-overflow: ellipsis; -} -.num { - text-align: right; - font-variant-numeric: tabular-nums; -} -code { - font-family: ui-monospace, 'SF Mono', Menlo, monospace; - font-size: 12px; - color: var(--brand); - background: var(--brand-soft); - padding: 1px 6px; - border-radius: 5px; -} -.feed { - list-style: none; - margin: 0; - padding: 0; - display: flex; - flex-direction: column; -} -.feed li { - display: flex; - align-items: center; - gap: 10px; - padding: 9px 2px; - border-bottom: 1px solid var(--line); - font-size: 13px; - animation: enter 0.4s ease; -} -.feed li:last-child { - border-bottom: 0; -} -.feed .dot { - width: 7px; - height: 7px; - border-radius: 50%; - background: var(--brand); - flex-shrink: 0; -} -.feed .name { - flex: 1; -} -.feed time { - color: var(--quiet); - font-size: 12px; - white-space: nowrap; -} -@keyframes enter { - from { - opacity: 0; - transform: translateY(-4px); - } -} -/* 加载与错误状态:数据到达前显示骨架,失败后图表区给出占位文案 */ -@keyframes shimmer { - from { - background-position: 200% 0; - } - to { - background-position: -200% 0; - } -} -body.loading .kpi .value { - color: transparent; -} -body.loading .kpi .value::after, -body.loading .bars::before, -body.loading .versions tbody::after, -body.loading .feed::before { - content: ''; - display: block; - border-radius: 6px; - background: linear-gradient(90deg, var(--panel-2) 25%, #1d3025 45%, var(--panel-2) 65%); - background-size: 200% 100%; - animation: shimmer 1.1s infinite linear; -} -body.loading .kpi .value::after { - height: 24px; - margin-top: 8px; -} -body.loading .bars::before { - height: 200px; -} -body.loading .versions tbody::after { - height: 180px; -} -body.loading .feed::before { - height: 200px; -} -body.loading .chart::after, -body.load-error .chart::after { - content: '正在加载…'; - position: absolute; - inset: 0; - display: grid; - place-items: center; - color: var(--quiet); - font-size: 13px; -} -body.load-error .chart::after { - content: '数据暂时不可用,稍后自动重试'; -} -html:lang(en-US) body.loading .chart::after { - content: 'Loading…'; -} -html:lang(en-US) body.load-error .chart::after { - content: 'Data is temporarily unavailable; retrying automatically'; -} -.empty { - color: var(--quiet); - font-size: 13px; - padding: 20px 0; - text-align: center; -} -.foot { - color: var(--quiet); - font-size: 12px; - text-align: center; -} -@media (max-width: 1200px) { - .kpis { - grid-template-columns: repeat(3, minmax(0, 1fr)); - } -} -@media (max-width: 860px) { - .grid { - grid-template-columns: minmax(0, 1fr); - grid-template-areas: 'trend' 'ranking' 'versions' 'recent'; - } - .kpis { - grid-template-columns: repeat(2, minmax(0, 1fr)); - } -} -@media (prefers-reduced-motion: reduce) { - * { - animation: none !important; - transition: none !important; - } -} diff --git a/apps/server/internal/dashboard/static/dashboard.js b/apps/server/internal/dashboard/static/dashboard.js deleted file mode 100644 index 368bef8a..00000000 --- a/apps/server/internal/dashboard/static/dashboard.js +++ /dev/null @@ -1,335 +0,0 @@ -// ToolForge plugin statistics dashboard. Reads /v1/dashboard every 30 seconds. -// Counts arrive as decimal strings and are handled with BigInt to keep precision. -// All text is inserted with textContent; no HTML is built from data. -;(() => { - 'use strict' - const REFRESH_MS = 30000 - const zh = (navigator.language || 'zh').toLowerCase().startsWith('zh') - const lang = zh ? 'zh-CN' : 'en-US' - const T = zh - ? { - title: 'ToolForge 插件数据', - subtitle: '官方在线插件的下载情况', - loading: '正在加载…', - total: '累计下载', - today: '今日下载', - week: '近 7 天', - weekHint: '最近 7 天合计', - month: '近 30 天', - monthHint: '最近 30 天合计', - plugins: '在线插件', - downloaded: '有下载的插件', - trend: '近 30 天下载趋势', - timezone: '北京时间', - ranking: '插件下载排行', - versions: '热门版本', - plugin: '插件', - version: '版本', - downloads: '下载', - recent: '最近下载', - liveTag: '实时', - note: '下载量为客户端完整下载并通过大小、SHA-256 与官方签名校验后确认的次数,不等于设备数或安装量。', - since: (d) => `自 ${d} 起累计`, - updated: (t) => `更新于 ${t} · 每 30 秒刷新`, - failed: '数据暂时不可用,稍后自动重试', - versionsCount: (n) => `${n} 个已发布版本`, - coverage: (p) => `占在线插件 ${p}`, - vsYesterday: (d) => `较昨日 ${d}`, - noData: '暂无数据', - justNow: '刚刚', - minutes: (n) => `${n} 分钟前`, - hours: (n) => `${n} 小时前`, - days: (n) => `${n} 天前`, - daily: (date, n) => `${date}:${n} 次下载`, - } - : { - title: 'ToolForge plugin statistics', - subtitle: 'Downloads of official online plugins', - loading: 'Loading…', - total: 'Total downloads', - today: 'Today', - week: 'Last 7 days', - weekHint: 'Sum of the last 7 days', - month: 'Last 30 days', - monthHint: 'Sum of the last 30 days', - plugins: 'Online plugins', - downloaded: 'Downloaded plugins', - trend: 'Downloads in the last 30 days', - timezone: 'Beijing time', - ranking: 'Plugin ranking', - versions: 'Popular versions', - plugin: 'Plugin', - version: 'Version', - downloads: 'Downloads', - recent: 'Recent downloads', - liveTag: 'Live', - note: 'A download counts once the client fully downloads a package and verifies its size, SHA-256 and official signature. It is not a count of devices or installations.', - since: (d) => `Counting since ${d}`, - updated: (t) => `Updated ${t} · refreshes every 30 s`, - failed: 'Data is temporarily unavailable; retrying automatically', - versionsCount: (n) => `${n} published versions`, - coverage: (p) => `${p} of online plugins`, - vsYesterday: (d) => `${d} vs yesterday`, - noData: 'No data yet', - justNow: 'just now', - minutes: (n) => `${n} min ago`, - hours: (n) => `${n} h ago`, - days: (n) => `${n} d ago`, - daily: (date, n) => `${date}: ${n} downloads`, - } - - document.documentElement.lang = lang - document.title = T.title - for (const el of document.querySelectorAll('[data-i18n]')) { - const value = T[el.dataset.i18n] - if (typeof value === 'string') el.textContent = value - } - - const $ = (id) => document.getElementById(id) - const big = (s) => { - try { - return BigInt(s) - } catch { - return 0n - } - } - const fmt = (n) => (typeof n === 'bigint' ? n : big(String(n))).toLocaleString(lang) - const el = (tag, className, text) => { - const node = document.createElement(tag) - if (className) node.className = className - if (text !== undefined) node.textContent = text - return node - } - const pluginName = (info, id) => { - const names = info[id] && info[id].names - if (names) return names[lang] || names['en-US'] || names['zh-CN'] || id - return id.replace(/^org\.devlive\.toolforge\./, '') - } - const relative = (iso) => { - const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000) - if (seconds < 60) return T.justNow - if (seconds < 3600) return T.minutes(Math.floor(seconds / 60)) - if (seconds < 86400) return T.hours(Math.floor(seconds / 3600)) - return T.days(Math.floor(seconds / 86400)) - } - - function renderKpis(d) { - const daily = d.daily.map((x) => big(x.downloads)) - const sum = (list) => list.reduce((a, b) => a + b, 0n) - const today = daily[daily.length - 1] ?? 0n - const yesterday = daily[daily.length - 2] ?? 0n - $('kpi-total').textContent = fmt(d.totalDownloads) - $('kpi-since').textContent = T.since(new Date(d.countedSince).toLocaleDateString(lang)) - $('kpi-today').textContent = fmt(today) - const delta = today - yesterday - const deltaEl = $('kpi-today-delta') - deltaEl.textContent = T.vsYesterday((delta > 0n ? '+' : '') + fmt(delta)) - deltaEl.className = 'hint ' + (delta > 0n ? 'up' : delta < 0n ? 'down' : '') - $('kpi-week').textContent = fmt(sum(daily.slice(-7))) - $('kpi-month').textContent = fmt(sum(daily)) - $('kpi-plugins').textContent = fmt(d.plugins) - $('kpi-versions').textContent = T.versionsCount(fmt(d.versions)) - $('kpi-downloaded').textContent = fmt(d.downloadedPlugins) - $('kpi-coverage').textContent = d.plugins > 0 ? T.coverage(Math.round((d.downloadedPlugins / d.plugins) * 100) + '%') : '' - } - - const SVG = 'http://www.w3.org/2000/svg' - const svgEl = (tag, attrs) => { - const node = document.createElementNS(SVG, tag) - for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, String(v)) - return node - } - - let hoverIndex = null - let pinnedIndex = null - - function renderTrend(daily) { - const box = $('trend') - const width = Math.max(320, box.clientWidth) - const height = Math.max(220, box.clientHeight) - const pad = { top: 16, right: 12, bottom: 26, left: 40 } - const values = daily.map((x) => Number(big(x.downloads))) - const max = Math.max(1, ...values) - const step = niceStep(max) - const top = Math.ceil(max / step) * step - const plotW = width - pad.left - pad.right - const plotH = height - pad.top - pad.bottom - const x = (i) => pad.left + (plotW * (i + 0.5)) / values.length - const y = (v) => pad.top + plotH - (plotH * v) / top - const svg = svgEl('svg', { viewBox: `0 0 ${width} ${height}`, preserveAspectRatio: 'none' }) - const defs = svgEl('defs', {}) - defs.append(gradient('barFill', '#3ddc84', 0.85, '#24b366', 0.35), gradient('areaFill', '#3ddc84', 0.25, '#3ddc84', 0)) - svg.append(defs) - for (let v = 0; v <= top; v += step) { - svg.append(svgEl('line', { x1: pad.left, x2: width - pad.right, y1: y(v), y2: y(v), class: 'grid-line' })) - const label = svgEl('text', { x: pad.left - 8, y: y(v) + 4, 'text-anchor': 'end', class: 'axis' }) - label.textContent = v.toLocaleString(lang) - svg.append(label) - } - const barW = Math.max(3, (plotW / values.length) * 0.56) - const bars = values.map((v, i) => { - const bar = svgEl('rect', { x: x(i) - barW / 2, y: y(v), width: barW, height: Math.max(0, pad.top + plotH - y(v)), rx: 3, class: 'bar' }) - svg.append(bar) - return bar - }) - const points = values.map((v, i) => `${x(i)},${y(v)}`) - svg.append(svgEl('path', { d: `M${x(0)},${pad.top + plotH} L${points.join(' L')} L${x(values.length - 1)},${pad.top + plotH} Z`, class: 'area' })) - svg.append(svgEl('polyline', { points: points.join(' '), class: 'line' })) - const last = values.length - 1 - svg.append(svgEl('circle', { cx: x(last), cy: y(values[last]), r: 4, class: 'dot' })) - const every = values.length > 20 ? 5 : 2 - daily.forEach((d, i) => { - if (i % every !== (values.length - 1) % every) return - const label = svgEl('text', { x: x(i), y: height - 6, 'text-anchor': 'middle', class: 'axis' }) - label.textContent = d.date.slice(5) - svg.append(label) - }) - // 悬停显示详情,点击把详情钉住;命中区覆盖整个列,0 高度的柱也能选中 - hoverIndex = null - const hitW = plotW / values.length - values.forEach((_, i) => { - const hit = svgEl('rect', { x: pad.left + hitW * i, y: pad.top, width: hitW, height: plotH, class: 'hit' }) - hit.addEventListener('pointerenter', () => { - hoverIndex = i - syncTip() - }) - hit.addEventListener('pointerleave', () => { - if (hoverIndex === i) { - hoverIndex = null - syncTip() - } - }) - hit.addEventListener('click', () => { - pinnedIndex = pinnedIndex === i ? null : i - syncTip() - }) - svg.append(hit) - }) - const tip = el('div', 'chart-tip') - tip.hidden = true - const syncTip = () => { - const index = hoverIndex ?? pinnedIndex - bars.forEach((bar, i) => { - bar.classList.toggle('pinned', pinnedIndex === i) - bar.classList.toggle('active', hoverIndex === i) - }) - if (index === null) { - tip.hidden = true - return - } - tip.textContent = T.daily(daily[index].date, values[index].toLocaleString(lang)) - tip.style.left = Math.min(width - 80, Math.max(80, x(index))) + 'px' - tip.style.top = Math.max(30, y(values[index])) + 'px' - tip.hidden = false - } - box.replaceChildren(svg, tip) - syncTip() - box.setAttribute('aria-label', T.trend) - } - function gradient(id, from, fromOpacity, to, toOpacity) { - const g = svgEl('linearGradient', { id, x1: 0, y1: 0, x2: 0, y2: 1 }) - g.append(svgEl('stop', { offset: '0%', 'stop-color': from, 'stop-opacity': fromOpacity }), svgEl('stop', { offset: '100%', 'stop-color': to, 'stop-opacity': toOpacity })) - return g - } - function niceStep(max) { - const raw = max / 4 - const power = 10 ** Math.floor(Math.log10(raw || 1)) - for (const m of [1, 2, 5, 10]) if (raw <= m * power) return Math.max(1, m * power) - return Math.max(1, 10 * power) - } - - function renderRanking(d) { - const list = $('ranking') - const total = big(d.totalDownloads) - const top = d.ranking.slice(0, 10) - if (top.length === 0) return list.replaceChildren(el('li', 'empty', T.noData)) - const max = big(top[0].downloads) || 1n - list.replaceChildren( - ...top.map((item, i) => { - const n = big(item.downloads) - const li = el('li') - const count = el('span', 'count', fmt(n)) - if (total > 0n) count.append(el('span', 'share', ((Number((n * 10000n) / total) / 100).toFixed(1)) + '%')) - const track = el('div', 'track') - const fill = el('div', 'fill') - fill.style.width = Number((n * 1000n) / max) / 10 + '%' - track.append(fill) - li.append(el('span', 'rank', String(i + 1)), el('span', 'name', pluginName(d.pluginInfo, item.pluginId)), count, track) - li.title = item.pluginId - return li - }), - ) - } - - function renderVersions(d) { - const body = $('versions') - if (d.topVersions.length === 0) { - const row = el('tr') - const cell = el('td', 'empty', T.noData) - cell.colSpan = 3 - row.append(cell) - return body.replaceChildren(row) - } - body.replaceChildren( - ...d.topVersions.map((item) => { - const row = el('tr') - const version = el('td') - version.append(el('code', '', 'v' + item.version)) - row.append(el('td', '', pluginName(d.pluginInfo, item.pluginId)), version, el('td', 'num', fmt(item.downloads))) - return row - }), - ) - } - - function renderRecent(d) { - const list = $('recent') - if (d.recent.length === 0) return list.replaceChildren(el('li', 'empty', T.noData)) - list.replaceChildren( - ...d.recent.slice(0, 8).map((item) => { - const li = el('li') - const name = el('span', 'name', pluginName(d.pluginInfo, item.pluginId)) - name.append(' ', el('code', '', 'v' + item.version)) - const time = el('time', '', relative(item.at)) - time.dateTime = item.at - li.append(el('span', 'dot'), name, time) - return li - }), - ) - } - - let latest = null - async function load() { - const status = document.querySelector('.status') - try { - const response = await fetch('/v1/dashboard', { cache: 'no-store' }) - if (!response.ok) throw new Error(String(response.status)) - latest = await response.json() - latest.pluginInfo = latest.pluginInfo || {} - renderKpis(latest) - renderTrend(latest.daily) - renderRanking(latest) - renderVersions(latest) - renderRecent(latest) - // 首次渲染成功才撤掉骨架;之后刷新失败保留旧数据,只在状态区提示 - document.body.classList.remove('loading', 'load-error') - status.classList.remove('error') - $('updated').textContent = T.updated(new Date(latest.asOf).toLocaleTimeString(lang)) - } catch { - status.classList.add('error') - $('updated').textContent = T.failed - if (!latest) { - document.body.classList.remove('loading') - document.body.classList.add('load-error') - } - } - } - - let resizeTimer = 0 - window.addEventListener('resize', () => { - clearTimeout(resizeTimer) - resizeTimer = setTimeout(() => latest && renderTrend(latest.daily), 150) - }) - document.body.classList.add('loading') - load() - setInterval(load, REFRESH_MS) -})() diff --git a/apps/server/internal/dashboard/static/index.html b/apps/server/internal/dashboard/static/index.html deleted file mode 100644 index 4449d4bc..00000000 --- a/apps/server/internal/dashboard/static/index.html +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - - ToolForge 插件数据 - - - - - -
-
- -
-

ToolForge 插件数据

-

官方在线插件的下载情况

-
-
-
- - 正在加载… -
-
- -
-
-
-

累计下载

-

—

-

-
-
-

今日下载

-

—

-

-
-
-

近 7 天

-

—

-

最近 7 天合计

-
-
-

近 30 天

-

—

-

最近 30 天合计

-
-
-

在线插件

-

—

-

-
-
-

有下载的插件

-

—

-

-
-
- -
-
-
-

近 30 天下载趋势

- 北京时间 -
- -
- -
-
-

插件下载排行

- TOP 10 -
-
    -
    - -
    -
    -

    热门版本

    - TOP 10 -
    - - - - - - - - - -
    插件版本下载
    -
    - -
    -
    -

    最近下载

    - 实时 -
    -
      -
      -
      -
      - -
      -

      下载量为客户端完整下载并通过大小、SHA-256 与官方签名校验后确认的次数,不等于设备数或安装量。

      -
      - - - diff --git a/apps/server/internal/dashboard/static/logo.png b/apps/server/internal/dashboard/static/logo.png deleted file mode 100644 index 206a2cdf..00000000 Binary files a/apps/server/internal/dashboard/static/logo.png and /dev/null differ diff --git a/apps/server/internal/receipt/receipt.go b/apps/server/internal/receipt/receipt.go deleted file mode 100644 index 309eb805..00000000 --- a/apps/server/internal/receipt/receipt.go +++ /dev/null @@ -1,107 +0,0 @@ -// Package receipt implements bounded HMAC signed download receipts. Receipts are -// bearer credentials and must never appear in URLs or logs. -package receipt - -import ( - "crypto/hmac" - "crypto/sha256" - "encoding/base64" - "encoding/json" - "errors" - "io" - "strings" - "time" - - "toolforge.dev/plugin-stats/internal/catalog" -) - -var ErrInvalid = errors.New("invalid receipt") -var ErrExpired = errors.New("expired receipt") - -const Lifetime = 7 * 24 * time.Hour - -type Claims struct { - Kid string `json:"kid"` - AttemptID string `json:"attemptId"` - PluginID string `json:"pluginId"` - Version string `json:"version"` - SHA256 string `json:"sha256"` - Size uint64 `json:"size"` - IssuedAt int64 `json:"iat"` - ExpiresAt int64 `json:"exp"` -} -type Signer struct { - active string - keys map[string][]byte -} - -func New(active string, keys map[string][]byte) (*Signer, error) { - if len(active) == 0 || len(active) > 32 || len(keys) == 0 || len(keys) > 8 { - return nil, ErrInvalid - } - copied := make(map[string][]byte, len(keys)) - for kid, key := range keys { - if len(kid) == 0 || len(kid) > 32 || len(key) < 32 { - return nil, ErrInvalid - } - copied[kid] = append([]byte(nil), key...) - } - if _, ok := copied[active]; !ok { - return nil, ErrInvalid - } - return &Signer{active: active, keys: copied}, nil -} -func (s *Signer) ActiveKid() string { return s.active } -func (s *Signer) Sign(c Claims) (string, error) { - key, ok := s.keys[c.Kid] - if !ok || !valid(c) { - return "", ErrInvalid - } - payload, err := json.Marshal(c) - if err != nil { - return "", ErrInvalid - } - body := base64.RawURLEncoding.EncodeToString(payload) - mac := hmac.New(sha256.New, key) - _, _ = mac.Write([]byte(body)) - return body + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil -} -func (s *Signer) Verify(token string, now time.Time) (Claims, error) { - var c Claims - if len(token) > 2048 { - return c, ErrInvalid - } - parts := strings.Split(token, ".") - if len(parts) != 2 { - return c, ErrInvalid - } - raw, err := base64.RawURLEncoding.DecodeString(parts[0]) - if err != nil { - return c, ErrInvalid - } - dec := json.NewDecoder(strings.NewReader(string(raw))) - dec.DisallowUnknownFields() - if dec.Decode(&c) != nil || dec.Decode(new(any)) != io.EOF || !valid(c) { - return Claims{}, ErrInvalid - } - key, ok := s.keys[c.Kid] - if !ok { - return Claims{}, ErrInvalid - } - sig, err := base64.RawURLEncoding.DecodeString(parts[1]) - if err != nil { - return Claims{}, ErrInvalid - } - mac := hmac.New(sha256.New, key) - _, _ = mac.Write([]byte(parts[0])) - if !hmac.Equal(sig, mac.Sum(nil)) || c.IssuedAt > now.Unix()+60 { - return Claims{}, ErrInvalid - } - if c.ExpiresAt <= now.Unix() { - return Claims{}, ErrExpired - } - return c, nil -} -func valid(c Claims) bool { - return len(c.Kid) > 0 && len(c.Kid) <= 32 && catalog.AttemptPattern.MatchString(c.AttemptID) && catalog.IDPattern.MatchString(c.PluginID) && catalog.VersionPattern.MatchString(c.Version) && catalog.SHAPattern.MatchString(c.SHA256) && c.Size > 0 && c.Size <= catalog.MaxPackageSize && c.IssuedAt > 0 && c.ExpiresAt > c.IssuedAt && c.ExpiresAt-c.IssuedAt <= int64(Lifetime/time.Second) -} diff --git a/apps/server/internal/receipt/receipt_test.go b/apps/server/internal/receipt/receipt_test.go deleted file mode 100644 index 31026b05..00000000 --- a/apps/server/internal/receipt/receipt_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package receipt - -import ( - "bytes" - "strings" - "testing" - "time" -) - -func testClaims() Claims { - return Claims{Kid: "old", AttemptID: strings.Repeat("a", 32), PluginID: "json-formatter", Version: "1.0.0", SHA256: strings.Repeat("b", 64), Size: 42, IssuedAt: 1700000000, ExpiresAt: 1700000000 + int64(Lifetime/time.Second)} -} -func TestSigningRotationAndTampering(t *testing.T) { - oldKey := bytes.Repeat([]byte{1}, 32) - newKey := bytes.Repeat([]byte{2}, 32) - old, err := New("old", map[string][]byte{"old": oldKey}) - if err != nil { - t.Fatal(err) - } - c := testClaims() - token, err := old.Sign(c) - if err != nil { - t.Fatal(err) - } - rotating, err := New("new", map[string][]byte{"old": oldKey, "new": newKey}) - if err != nil { - t.Fatal(err) - } - now := time.Unix(c.IssuedAt+1, 0) - got, err := rotating.Verify(token, now) - if err != nil || got != c { - t.Fatalf("rotation lost old receipt: %v", err) - } - tests := []string{token + "x", "x" + token, strings.Repeat("x", 4096), "", token + ".extra"} - for i, token := range tests { - if _, err := rotating.Verify(token, now); err == nil { - t.Fatalf("accepted tampered token %d", i) - } - } - if _, err := rotating.Verify(token, time.Unix(c.ExpiresAt, 0)); err != ErrExpired { - t.Fatalf("expiry: %v", err) - } - retired, _ := New("new", map[string][]byte{"new": newKey}) - if _, err := retired.Verify(token, now); err != ErrInvalid { - t.Fatalf("retired key: %v", err) - } -} -func TestClaimsBounds(t *testing.T) { - s, _ := New("old", map[string][]byte{"old": bytes.Repeat([]byte{1}, 32)}) - c := testClaims() - c.ExpiresAt++ - if _, err := s.Sign(c); err == nil { - t.Fatal("accepted excessive lifetime") - } - if _, err := New("bad", map[string][]byte{"bad": []byte("short")}); err == nil { - t.Fatal("accepted short key") - } -} diff --git a/apps/server/internal/registry/registry.go b/apps/server/internal/registry/registry.go deleted file mode 100644 index 9e231724..00000000 --- a/apps/server/internal/registry/registry.go +++ /dev/null @@ -1,110 +0,0 @@ -// Package registry caches plugin names from the public plugin index for the -// dashboard. The statistics database stores IDs only; names are display data -// and a failed refresh keeps the previous names (or none) without failing requests. -package registry - -import ( - "context" - "encoding/json" - "errors" - "io" - "net/http" - "sync" - "time" -) - -// MaxIndexBytes bounds the downloaded index. -const MaxIndexBytes = 4 << 20 - -type Plugin struct { - Names map[string]string `json:"names"` - Category string `json:"category"` - Accent string `json:"accent,omitempty"` - Version string `json:"version"` -} - -type Cache struct { - URL string - Client *http.Client - - mu sync.RWMutex - plugins map[string]Plugin -} - -// Lookup returns cached metadata for the given plugin IDs; unknown IDs are omitted. -func (c *Cache) Lookup(ids []string) map[string]Plugin { - out := make(map[string]Plugin, len(ids)) - if c == nil { - return out - } - c.mu.RLock() - defer c.mu.RUnlock() - for _, id := range ids { - if p, ok := c.plugins[id]; ok { - out[id] = p - } - } - return out -} - -// Refresh downloads and parses the index, replacing the cache only on success. -func (c *Cache) Refresh(ctx context.Context) error { - ctx, cancel := context.WithTimeout(ctx, 10*time.Second) - defer cancel() - req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.URL, nil) - if err != nil { - return err - } - req.Header.Set("User-Agent", "toolforge-plugin-stats") - client := c.Client - if client == nil { - client = http.DefaultClient - } - resp, err := client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return errors.New("registry index unavailable") - } - var index struct { - Plugins []struct { - ID string `json:"id"` - Plugin - } `json:"plugins"` - } - if err := json.NewDecoder(io.LimitReader(resp.Body, MaxIndexBytes)).Decode(&index); err != nil { - return errors.New("invalid registry index") - } - plugins := make(map[string]Plugin, len(index.Plugins)) - for _, entry := range index.Plugins { - if entry.ID != "" { - plugins[entry.ID] = entry.Plugin - } - } - c.mu.Lock() - c.plugins = plugins - c.mu.Unlock() - return nil -} - -// Run refreshes immediately and then on every interval until ctx ends. -func (c *Cache) Run(ctx context.Context, interval time.Duration, onError func(error)) { - refresh := func() { - if err := c.Refresh(ctx); err != nil && onError != nil && ctx.Err() == nil { - onError(err) - } - } - refresh() - ticker := time.NewTicker(interval) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - refresh() - } - } -} diff --git a/apps/server/internal/registry/registry_test.go b/apps/server/internal/registry/registry_test.go deleted file mode 100644 index 8cb8b4ba..00000000 --- a/apps/server/internal/registry/registry_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package registry - -import ( - "bytes" - "context" - "net/http" - "net/http/httptest" - "sync/atomic" - "testing" - "time" -) - -func TestRefreshKeepsNamesAndSurvivesFailures(t *testing.T) { - status := http.StatusOK - body := `{"plugins":[{"id":"org.devlive.toolforge.hash","version":"0.1.2","category":"dev","accent":"orange","names":{"en-US":"Hash","zh-CN":"哈希计算"},"sha256":"x"}]}` - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(status) - _, _ = w.Write([]byte(body)) - })) - defer server.Close() - c := &Cache{URL: server.URL, Client: server.Client()} - if got := c.Lookup([]string{"org.devlive.toolforge.hash"}); len(got) != 0 { - t.Fatal("empty cache returned names") - } - if err := c.Refresh(context.Background()); err != nil { - t.Fatal(err) - } - got := c.Lookup([]string{"org.devlive.toolforge.hash", "unknown"}) - if len(got) != 1 || got["org.devlive.toolforge.hash"].Names["zh-CN"] != "哈希计算" || got["org.devlive.toolforge.hash"].Category != "dev" { - t.Fatalf("lookup: %+v", got) - } - status = http.StatusBadGateway - if err := c.Refresh(context.Background()); err == nil { - t.Fatal("failed refresh reported success") - } - if len(c.Lookup([]string{"org.devlive.toolforge.hash"})) != 1 { - t.Fatal("failed refresh dropped cached names") - } - status, body = http.StatusOK, `not json` - if err := c.Refresh(context.Background()); err == nil { - t.Fatal("invalid index accepted") - } - var nilCache *Cache - if len(nilCache.Lookup([]string{"x"})) != 0 { - t.Fatal("nil cache returned names") - } -} - -func TestRefreshRejectsOversizedIndex(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, _ = w.Write(bytes.Repeat([]byte("a"), MaxIndexBytes+1)) - })) - defer server.Close() - c := &Cache{URL: server.URL, Client: server.Client()} - if err := c.Refresh(context.Background()); err == nil { - t.Fatal("oversized index accepted") - } -} - -func TestRunRefreshesUntilContextEnds(t *testing.T) { - var calls atomic.Int32 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - calls.Add(1) - _, _ = w.Write([]byte(`{"plugins":[]}`)) - })) - defer server.Close() - c := &Cache{URL: server.URL, Client: server.Client()} - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - done := make(chan struct{}) - go func() { - // Refresh failures are reported, never fatal; the loop stops on ctx. - c.Run(ctx, 15*time.Millisecond, func(error) { t.Error("refresh failed") }) - close(done) - }() - deadline := time.Now().Add(2 * time.Second) - for calls.Load() < 2 && time.Now().Before(deadline) { - time.Sleep(5 * time.Millisecond) - } - cancel() - select { - case <-done: - case <-time.After(time.Second): - t.Fatal("refresh loop ignored context cancellation") - } - if calls.Load() < 2 { - t.Fatalf("refresh ran %d times", calls.Load()) - } -} diff --git a/apps/server/internal/store/mysql.go b/apps/server/internal/store/mysql.go deleted file mode 100644 index f6fe4fc8..00000000 --- a/apps/server/internal/store/mysql.go +++ /dev/null @@ -1,580 +0,0 @@ -package store - -import ( - "context" - "database/sql" - "encoding/hex" - "errors" - "fmt" - "sort" - "strconv" - "strings" - "time" - - driver "github.com/go-sql-driver/mysql" - "toolforge.dev/plugin-stats/internal/catalog" - "toolforge.dev/plugin-stats/internal/receipt" -) - -var ( - ErrNotFound = errors.New("not found") - ErrConflict = errors.New("conflicting metadata") - ErrGone = errors.New("expired or withdrawn") - ErrRevoked = errors.New("revoked package") -) - -const SchemaVersion = 1 - -type Store struct{ DB *sql.DB } -type Attempt struct { - receipt.Claims - ObjectKey string - Confirmed bool -} -type VersionStats struct { - Version string `json:"version"` - Downloads string `json:"downloads"` -} -type PluginStats struct { - PluginID string `json:"pluginId"` - TotalDownloads string `json:"totalDownloads"` - Versions []VersionStats `json:"versions"` - VersionsTruncated bool `json:"versionsTruncated,omitempty"` -} -type Stats struct { - Plugins []PluginStats `json:"plugins"` - CountedSince time.Time `json:"countedSince"` - AsOf time.Time `json:"asOf"` -} -type VersionResult struct { - PluginID string `json:"pluginId"` - Version string `json:"version"` - Downloads string `json:"downloads"` - TotalDownloads string `json:"totalDownloads"` - CountedSince time.Time `json:"countedSince"` - AsOf time.Time `json:"asOf"` -} -type PluginResult struct { - PluginStats - CountedSince time.Time `json:"countedSince"` - AsOf time.Time `json:"asOf"` - Limit int `json:"limit"` - Offset int `json:"offset"` - HasMore bool `json:"hasMore"` -} -type TotalResult struct { - TotalDownloads string `json:"totalDownloads"` - CountedSince time.Time `json:"countedSince"` - AsOf time.Time `json:"asOf"` -} - -func (s *Store) Ready(ctx context.Context) error { - var v int - var dirty bool - if err := s.DB.QueryRowContext(ctx, "SELECT version,dirty FROM schema_migrations LIMIT 1").Scan(&v, &dirty); err != nil { - return errors.New("schema unavailable") - } - if v != SchemaVersion || dirty { - return errors.New("schema incompatible") - } - return nil -} - -func (s *Store) CatalogReady(ctx context.Context) bool { - var generation uint64 - return s.DB.QueryRowContext(ctx, "SELECT generation FROM catalog_state WHERE id=1").Scan(&generation) == nil && generation > 0 -} - -func (s *Store) Issue(ctx context.Context, id, version, attempt, kid string, now time.Time) (Attempt, error) { - var out Attempt - now = now.UTC().Truncate(time.Second) - err := s.transaction(ctx, func(tx *sql.Tx) error { - var p catalog.Package - if err := tx.QueryRowContext(ctx, `SELECT plugin_id,version,LOWER(HEX(sha256)),size_bytes,object_key,status FROM plugin_versions WHERE plugin_id=? AND version=? FOR SHARE`, id, version).Scan(&p.ID, &p.Version, &p.SHA256, &p.Size, &p.ObjectKey, &p.Status); err != nil { - return notFound(err) - } - if p.Status == "revoked" { - return ErrRevoked - } - var a Attempt - var issued, expires time.Time - var status string - err := tx.QueryRowContext(ctx, `SELECT LOWER(HEX(attempt_id)),plugin_id,version,LOWER(HEX(sha256)),size_bytes,receipt_kid,issued_at,expires_at,status FROM download_attempts WHERE attempt_id=UNHEX(?) FOR UPDATE`, attempt).Scan(&a.AttemptID, &a.PluginID, &a.Version, &a.SHA256, &a.Size, &a.Kid, &issued, &expires, &status) - if err == nil { - if a.PluginID != id || a.Version != version || a.SHA256 != p.SHA256 || a.Size != p.Size { - return ErrConflict - } - if !expires.After(now) { - return ErrGone - } - a.IssuedAt = issued.Unix() - a.ExpiresAt = expires.Unix() - a.ObjectKey = p.ObjectKey - a.Confirmed = status == "confirmed" - out = a - return nil - } - if !errors.Is(err, sql.ErrNoRows) { - return err - } - if p.Status != "active" { - return ErrGone - } - out = Attempt{Claims: receipt.Claims{Kid: kid, AttemptID: attempt, PluginID: id, Version: version, SHA256: p.SHA256, Size: p.Size, IssuedAt: now.Unix(), ExpiresAt: now.Add(receipt.Lifetime).Unix()}, ObjectKey: p.ObjectKey} - if _, err := tx.ExecContext(ctx, `INSERT INTO download_attempts (attempt_id,plugin_id,version,sha256,size_bytes,receipt_kid,issued_at,expires_at) VALUES (UNHEX(?),?,?,UNHEX(?),?,?,?,?)`, attempt, id, version, p.SHA256, p.Size, kid, now, now.Add(receipt.Lifetime)); err != nil { - return err - } - return increment(ctx, tx, id, version, "attempts", now) - }) - return out, err -} - -func (s *Store) Confirm(ctx context.Context, c receipt.Claims, sha string, size uint64, now time.Time) error { - if c.SHA256 != sha || c.Size != size { - return ErrConflict - } - return s.transaction(ctx, func(tx *sql.Tx) error { - var packageStatus string - if err := tx.QueryRowContext(ctx, `SELECT status FROM plugin_versions WHERE plugin_id=? AND version=? FOR SHARE`, c.PluginID, c.Version).Scan(&packageStatus); err != nil { - return notFound(err) - } - if packageStatus == "revoked" { - return ErrRevoked - } - var a Attempt - var issued, expires time.Time - var status string - err := tx.QueryRowContext(ctx, `SELECT LOWER(HEX(attempt_id)),plugin_id,version,LOWER(HEX(sha256)),size_bytes,receipt_kid,issued_at,expires_at,status FROM download_attempts WHERE attempt_id=UNHEX(?) FOR UPDATE`, c.AttemptID).Scan(&a.AttemptID, &a.PluginID, &a.Version, &a.SHA256, &a.Size, &a.Kid, &issued, &expires, &status) - if err != nil { - return notFound(err) - } - a.IssuedAt = issued.Unix() - a.ExpiresAt = expires.Unix() - if a.Claims != c { - return ErrConflict - } - if !expires.After(now) { - return ErrGone - } - if status == "confirmed" { - return nil - } - if _, err := tx.ExecContext(ctx, `UPDATE download_attempts SET status='confirmed',confirmed_at=? WHERE attempt_id=UNHEX(?)`, now.UTC(), c.AttemptID); err != nil { - return err - } - return increment(ctx, tx, c.PluginID, c.Version, "downloads", now.UTC()) - }) -} - -// Both totals always change in the same transaction and lock order. -func increment(ctx context.Context, tx *sql.Tx, id, version, column string, now time.Time) error { - if column != "attempts" && column != "downloads" { - return errors.New("invalid counter") - } - r, err := tx.ExecContext(ctx, `UPDATE plugin_stats SET `+column+`=`+column+`+1,updated_at=? WHERE plugin_id=?`, now, id) - if err != nil { - return err - } - n, err := r.RowsAffected() - if err != nil { - return err - } - if n != 1 { - return errors.New("missing plugin counter") - } - r, err = tx.ExecContext(ctx, `UPDATE plugin_version_stats SET `+column+`=`+column+`+1,updated_at=? WHERE plugin_id=? AND version=?`, now, id, version) - if err != nil { - return err - } - n, err = r.RowsAffected() - if err != nil { - return err - } - if n != 1 { - return errors.New("missing version counter") - } - return nil -} - -func (s *Store) Import(ctx context.Context, c catalog.Catalog, digest string, now time.Time) error { - if err := c.Validate(); err != nil { - return err - } - if !catalog.SHAPattern.MatchString(digest) { - return ErrConflict - } - packages := append([]catalog.Package(nil), c.Plugins...) - sort.Slice(packages, func(i, j int) bool { - if packages[i].ID == packages[j].ID { - return packages[i].Version < packages[j].Version - } - return packages[i].ID < packages[j].ID - }) - return s.transaction(ctx, func(tx *sql.Tx) error { - var priorDigest string - var generation uint64 - if err := tx.QueryRowContext(ctx, `SELECT LOWER(HEX(digest)),generation FROM catalog_state WHERE id=1 FOR UPDATE`).Scan(&priorDigest, &generation); err != nil { - return err - } - if priorDigest == digest { - return nil - } - if c.Generation <= generation { - return ErrConflict - } - // Absence in a complete catalog withdraws a version, preserving history and - // allowing already issued receipts. Explicit revocations remain revoked. - if _, err := tx.ExecContext(ctx, `UPDATE plugin_versions SET status='withdrawn' WHERE status='active'`); err != nil { - return err - } - for _, p := range packages { - var sha, key, priorStatus string - var size uint64 - err := tx.QueryRowContext(ctx, `SELECT LOWER(HEX(sha256)),size_bytes,object_key,status FROM plugin_versions WHERE plugin_id=? AND version=? FOR UPDATE`, p.ID, p.Version).Scan(&sha, &size, &key, &priorStatus) - if err == nil { - if sha != p.SHA256 || size != p.Size || key != p.ObjectKey || (priorStatus == "revoked" && p.Status != "revoked") { - return ErrConflict - } - if _, err = tx.ExecContext(ctx, `UPDATE plugin_versions SET status=? WHERE plugin_id=? AND version=?`, p.Status, p.ID, p.Version); err != nil { - return err - } - } else if errors.Is(err, sql.ErrNoRows) { - published := p.PublishedAt.UTC() - if published.IsZero() { - published = now.UTC() - } - if _, err = tx.ExecContext(ctx, `INSERT INTO plugin_versions (plugin_id,version,sha256,size_bytes,object_key,status,published_at) VALUES (?,?,UNHEX(?),?,?,?,?)`, p.ID, p.Version, p.SHA256, p.Size, p.ObjectKey, p.Status, published); err != nil { - return err - } - } else { - return err - } - if _, err := tx.ExecContext(ctx, `INSERT IGNORE INTO plugin_stats (plugin_id,updated_at) VALUES (?,?)`, p.ID, now.UTC()); err != nil { - return err - } - if _, err := tx.ExecContext(ctx, `INSERT IGNORE INTO plugin_version_stats (plugin_id,version,updated_at) VALUES (?,?,?)`, p.ID, p.Version, now.UTC()); err != nil { - return err - } - } - _, err := tx.ExecContext(ctx, `UPDATE catalog_state SET digest=UNHEX(?),source_commit=?,generation=?,imported_at=? WHERE id=1`, digest, c.SourceCommit, c.Generation, now.UTC()) - return err - }) -} - -func (s *Store) transaction(ctx context.Context, fn func(*sql.Tx) error) error { - for i := 0; i < 4; i++ { - tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted}) - if err != nil { - return err - } - err = fn(tx) - if err == nil { - err = tx.Commit() - } else { - _ = tx.Rollback() - } - if err == nil { - return nil - } - _ = tx.Rollback() - var me *driver.MySQLError - if !errors.As(err, &me) || (me.Number != 1213 && me.Number != 1205 && me.Number != 1062) { - return err - } - select { - case <-ctx.Done(): - return ctx.Err() - case <-time.After(time.Duration(i+1) * 10 * time.Millisecond): - } - } - return errors.New("database transaction retry limit reached") -} -func notFound(err error) error { - if errors.Is(err, sql.ErrNoRows) { - return ErrNotFound - } - return err -} - -func (s *Store) read(ctx context.Context, fn func(*sql.Tx, time.Time, time.Time) error) error { - tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead}) - if err != nil { - return err - } - defer func() { _ = tx.Rollback() }() - var since, asof time.Time - if err = tx.QueryRowContext(ctx, `SELECT counted_since,UTC_TIMESTAMP(6) FROM catalog_state WHERE id=1`).Scan(&since, &asof); err != nil { - return err - } - if err = fn(tx, since.UTC(), asof.UTC()); err != nil { - return err - } - return tx.Commit() -} -func (s *Store) Version(ctx context.Context, id, version string) (VersionResult, error) { - out := VersionResult{PluginID: id, Version: version} - err := s.read(ctx, func(tx *sql.Tx, since, asof time.Time) error { - var n, total uint64 - err := tx.QueryRowContext(ctx, `SELECT v.downloads,p.downloads FROM plugin_version_stats v JOIN plugin_stats p USING(plugin_id) WHERE v.plugin_id=? AND v.version=?`, id, version).Scan(&n, &total) - if err != nil { - return notFound(err) - } - out.Downloads = strconv.FormatUint(n, 10) - out.TotalDownloads = strconv.FormatUint(total, 10) - out.CountedSince = since - out.AsOf = asof - return nil - }) - return out, err -} -func (s *Store) Plugin(ctx context.Context, id string, limit, offset int) (PluginResult, error) { - out := PluginResult{PluginStats: PluginStats{PluginID: id, Versions: []VersionStats{}}, Limit: limit, Offset: offset} - err := s.read(ctx, func(tx *sql.Tx, since, asof time.Time) error { - var n uint64 - if err := tx.QueryRowContext(ctx, `SELECT downloads FROM plugin_stats WHERE plugin_id=?`, id).Scan(&n); err != nil { - return notFound(err) - } - out.TotalDownloads = strconv.FormatUint(n, 10) - out.CountedSince = since - out.AsOf = asof - rows, err := tx.QueryContext(ctx, `SELECT v.version,s.downloads FROM plugin_versions v JOIN plugin_version_stats s USING(plugin_id,version) WHERE v.plugin_id=? ORDER BY v.published_at DESC,v.version DESC LIMIT ? OFFSET ?`, id, limit+1, offset) - if err != nil { - return err - } - defer rows.Close() - for rows.Next() { - var v VersionStats - var count uint64 - if err := rows.Scan(&v.Version, &count); err != nil { - return err - } - v.Downloads = strconv.FormatUint(count, 10) - if len(out.Versions) < limit { - out.Versions = append(out.Versions, v) - } else { - out.HasMore = true - } - } - return rows.Err() - }) - return out, err -} -func (s *Store) Batch(ctx context.Context, ids []string) (Stats, error) { - out := Stats{Plugins: []PluginStats{}} - if len(ids) == 0 || len(ids) > 100 { - return out, ErrConflict - } - args := make([]any, len(ids)) - for i, id := range ids { - args[i] = id - } - placeholders := strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",") - err := s.read(ctx, func(tx *sql.Tx, since, asof time.Time) error { - out.CountedSince = since - out.AsOf = asof - rows, err := tx.QueryContext(ctx, `SELECT plugin_id,downloads FROM plugin_stats WHERE plugin_id IN (`+placeholders+`)`, args...) - if err != nil { - return err - } - m := make(map[string]*PluginStats, len(ids)) - for rows.Next() { - var p PluginStats - var n uint64 - if err := rows.Scan(&p.PluginID, &n); err != nil { - rows.Close() - return err - } - p.TotalDownloads = strconv.FormatUint(n, 10) - p.Versions = []VersionStats{} - m[p.PluginID] = &p - } - err = rows.Err() - _ = rows.Close() - if err != nil { - return err - } - rows, err = tx.QueryContext(ctx, `WITH ranked AS (SELECT v.plugin_id,v.version,s.downloads,ROW_NUMBER() OVER (PARTITION BY v.plugin_id ORDER BY v.published_at DESC,v.version DESC) AS rn FROM plugin_versions v JOIN plugin_version_stats s USING(plugin_id,version) WHERE v.plugin_id IN (`+placeholders+`)) SELECT plugin_id,version,downloads,rn FROM ranked WHERE rn<=101 ORDER BY plugin_id,rn`, args...) - if err != nil { - return err - } - defer rows.Close() - for rows.Next() { - var id string - var v VersionStats - var n, rn uint64 - if err := rows.Scan(&id, &v.Version, &n, &rn); err != nil { - return err - } - if p := m[id]; p != nil { - if rn > 100 { - p.VersionsTruncated = true - } else { - v.Downloads = strconv.FormatUint(n, 10) - p.Versions = append(p.Versions, v) - } - } - } - if err := rows.Err(); err != nil { - return err - } - // Unknown IDs are omitted, never invented as zero-download official plugins. - for _, id := range ids { - if p := m[id]; p != nil { - out.Plugins = append(out.Plugins, *p) - } - } - return nil - }) - return out, err -} -func (s *Store) Total(ctx context.Context) (TotalResult, error) { - var out TotalResult - err := s.read(ctx, func(tx *sql.Tx, since, asof time.Time) error { - // SUM of BIGINT may exceed uint64; MySQL DECIMAL is safely read as text. - if err := tx.QueryRowContext(ctx, `SELECT CAST(COALESCE(SUM(downloads),0) AS CHAR) FROM plugin_stats`).Scan(&out.TotalDownloads); err != nil { - return err - } - out.CountedSince = since - out.AsOf = asof - return nil - }) - return out, err -} - -// Cleanup only deletes bounded batches of expired attempts. Confirmed attempts -// live at least 30 days. Aggregate counts and catalog history are never deleted. -func (s *Store) Cleanup(ctx context.Context, now time.Time) error { - _, err := s.DB.ExecContext(ctx, `DELETE FROM download_attempts WHERE expires_at0 THEN 1 END) FROM plugin_stats`).Scan(&out.TotalDownloads, &out.DownloadedPlugins); err != nil { - return err - } - if err := tx.QueryRowContext(ctx, `SELECT COUNT(DISTINCT plugin_id), COUNT(*) FROM plugin_versions WHERE status='active'`).Scan(&out.Plugins, &out.Versions); err != nil { - return err - } - rows, err := tx.QueryContext(ctx, `SELECT plugin_id, downloads FROM plugin_stats WHERE downloads>0 ORDER BY downloads DESC, plugin_id LIMIT 20`) - if err != nil { - return err - } - for rows.Next() { - var r RankedPlugin - var n uint64 - if err := rows.Scan(&r.PluginID, &n); err != nil { - rows.Close() - return err - } - r.Downloads = strconv.FormatUint(n, 10) - out.Ranking = append(out.Ranking, r) - } - rows.Close() - rows, err = tx.QueryContext(ctx, `SELECT plugin_id, version, downloads FROM plugin_version_stats WHERE downloads>0 ORDER BY downloads DESC, plugin_id, version LIMIT 10`) - if err != nil { - return err - } - for rows.Next() { - var r RankedVersion - var n uint64 - if err := rows.Scan(&r.PluginID, &r.Version, &n); err != nil { - rows.Close() - return err - } - r.Downloads = strconv.FormatUint(n, 10) - out.TopVersions = append(out.TopVersions, r) - } - rows.Close() - // Day buckets in Beijing time; the oldest bucket starts at its local midnight. - local := asof.Add(dashboardOffset) - firstDay := time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, time.UTC).AddDate(0, 0, -(DashboardDays - 1)) - counts := make(map[string]uint64, DashboardDays) - rows, err = tx.QueryContext(ctx, `SELECT DATE_FORMAT(DATE_ADD(confirmed_at, INTERVAL 8 HOUR), '%Y-%m-%d') AS day, COUNT(*) FROM download_attempts WHERE status='confirmed' AND confirmed_at>=? GROUP BY day`, firstDay.Add(-dashboardOffset)) - if err != nil { - return err - } - for rows.Next() { - var day string - var n uint64 - if err := rows.Scan(&day, &n); err != nil { - rows.Close() - return err - } - counts[day] = n - } - rows.Close() - for i := 0; i < DashboardDays; i++ { - day := firstDay.AddDate(0, 0, i).Format("2006-01-02") - out.Daily = append(out.Daily, DailyDownloads{Date: day, Downloads: strconv.FormatUint(counts[day], 10)}) - } - rows, err = tx.QueryContext(ctx, `SELECT plugin_id, version, confirmed_at FROM download_attempts WHERE status='confirmed' ORDER BY confirmed_at DESC LIMIT 12`) - if err != nil { - return err - } - defer rows.Close() - for rows.Next() { - var r RecentDownload - if err := rows.Scan(&r.PluginID, &r.Version, &r.At); err != nil { - return err - } - r.At = r.At.UTC() - out.Recent = append(out.Recent, r) - } - return rows.Err() - }) - return out, err -} diff --git a/apps/server/internal/store/mysql_test.go b/apps/server/internal/store/mysql_test.go deleted file mode 100644 index 0ecefb76..00000000 --- a/apps/server/internal/store/mysql_test.go +++ /dev/null @@ -1,346 +0,0 @@ -package store - -import ( - "context" - "database/sql" - "encoding/json" - "errors" - "fmt" - "os" - "strconv" - "strings" - "sync" - "testing" - "time" - - driver "github.com/go-sql-driver/mysql" - "github.com/golang-migrate/migrate/v4" - mysqlmigrate "github.com/golang-migrate/migrate/v4/database/mysql" - "github.com/golang-migrate/migrate/v4/source/iofs" - "toolforge.dev/plugin-stats/internal/catalog" - "toolforge.dev/plugin-stats/migrations" -) - -// The caller explicitly opts into destructive tests using a dedicated *_test -// database. Never point TEST_MYSQL_DSN at a development or production database. -func integrationStore(t *testing.T) *Store { - t.Helper() - dsn := os.Getenv("TEST_MYSQL_DSN") - if dsn == "" { - t.Skip("TEST_MYSQL_DSN not configured; MySQL integration tests skipped") - } - cfg, err := driver.ParseDSN(dsn) - if err != nil || !strings.HasSuffix(cfg.DBName, "_test") { - t.Fatal("TEST_MYSQL_DSN must name an isolated database ending in _test") - } - cfg.ParseTime = true - cfg.Loc = time.UTC - cfg.MultiStatements = true - if cfg.Params == nil { - cfg.Params = map[string]string{} - } - cfg.Params["time_zone"] = "'+00:00'" - db, err := sql.Open("mysql", cfg.FormatDSN()) - if err != nil { - t.Fatal("open test database failed") - } - db.SetMaxOpenConns(20) - t.Cleanup(func() { _ = db.Close() }) - for _, table := range []string{"download_attempts", "plugin_version_stats", "plugin_stats", "plugin_versions", "catalog_state", "schema_migrations"} { - if _, err := db.Exec("DROP TABLE IF EXISTS " + table); err != nil { - t.Fatal("reset test schema failed") - } - } - src, err := iofs.New(migrations.Files, ".") - if err != nil { - t.Fatal(err) - } - md, err := mysqlmigrate.WithInstance(db, &mysqlmigrate.Config{}) - if err != nil { - t.Fatal(err) - } - m, err := migrate.NewWithInstance("iofs", src, "mysql", md) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _, _ = m.Close() }) - if err := m.Up(); err != nil { - t.Fatal(err) - } - return &Store{DB: db} -} -func testPackage(id, version string) catalog.Package { - sha := strings.Repeat("a", 64) - return catalog.Package{ID: id, Version: version, SHA256: sha, Size: 42, ObjectKey: "packages/" + id + "/" + version + "/" + sha + ".tfp", Status: "active"} -} -func importCatalog(t *testing.T, s *Store, generation uint64, packages []catalog.Package) catalog.Catalog { - t.Helper() - c := catalog.Catalog{SchemaVersion: 1, SourceCommit: strings.Repeat("b", 40), Generation: generation, Plugins: packages} - raw, _ := json.Marshal(c) - c, digest, err := catalog.Read(strings.NewReader(string(raw))) - if err != nil { - t.Fatal(err) - } - if err = s.Import(context.Background(), c, digest, time.Now().UTC()); err != nil { - t.Fatal(err) - } - return c -} -func expectCounters(t *testing.T, s *Store, attempts, downloads uint64) { - t.Helper() - var a, d uint64 - if err := s.DB.QueryRow(`SELECT attempts,downloads FROM plugin_stats WHERE plugin_id='plugin'`).Scan(&a, &d); err != nil { - t.Fatal(err) - } - if a != attempts || d != downloads { - t.Fatalf("plugin counters = %d/%d; want %d/%d", a, d, attempts, downloads) - } - var va, vd uint64 - if err := s.DB.QueryRow(`SELECT attempts,downloads FROM plugin_version_stats WHERE plugin_id='plugin' AND version='1.0.0'`).Scan(&va, &vd); err != nil { - t.Fatal(err) - } - if va != a || vd != d { - t.Fatalf("version/total divergence: %d/%d vs %d/%d", va, vd, a, d) - } -} -func TestMySQLTransactionsAndStatistics(t *testing.T) { - s := integrationStore(t) - ctx := context.Background() - now := time.Now().UTC().Truncate(time.Second) - if err := s.Ready(ctx); err != nil { - t.Fatal(err) - } - if s.CatalogReady(ctx) { - t.Fatal("empty catalog reported ready") - } - packages := []catalog.Package{testPackage("plugin", "1.0.0"), testPackage("other", "1.0.0")} - c := importCatalog(t, s, 1, packages) - if !s.CatalogReady(ctx) { - t.Fatal("imported catalog not ready") - } - t.Run("parallel issue is idempotent", func(t *testing.T) { - errs := make(chan error, 50) - var wg sync.WaitGroup - for i := 0; i < 50; i++ { - wg.Go(func() { _, err := s.Issue(ctx, "plugin", "1.0.0", strings.Repeat("c", 32), "k1", now); errs <- err }) - } - wg.Wait() - close(errs) - for err := range errs { - if err != nil { - t.Fatal(err) - } - } - expectCounters(t, s, 1, 0) - }) - a, err := s.Issue(ctx, "plugin", "1.0.0", strings.Repeat("c", 32), "k1", now) - if err != nil { - t.Fatal(err) - } - t.Run("parallel confirmation increments once", func(t *testing.T) { - errs := make(chan error, 100) - var wg sync.WaitGroup - for i := 0; i < 100; i++ { - wg.Go(func() { errs <- s.Confirm(ctx, a.Claims, a.SHA256, a.Size, now.Add(time.Second)) }) - } - wg.Wait() - close(errs) - for err := range errs { - if err != nil { - t.Fatal(err) - } - } - expectCounters(t, s, 1, 1) - if err := s.Confirm(ctx, a.Claims, strings.Repeat("f", 64), a.Size, now); !errors.Is(err, ErrConflict) { - t.Fatalf("tampered body: %v", err) - } - if _, err := s.Issue(ctx, "other", "1.0.0", a.AttemptID, "k1", now); !errors.Is(err, ErrConflict) { - t.Fatalf("cross plugin key collision: %v", err) - } - }) - b, err := s.Issue(ctx, "plugin", "1.0.0", strings.Repeat("d", 32), "k1", now) - if err != nil { - t.Fatal(err) - } - t.Run("failed counter update rolls back confirmation", func(t *testing.T) { - if _, err := s.DB.Exec(`DELETE FROM plugin_version_stats WHERE plugin_id='plugin' AND version='1.0.0'`); err != nil { - t.Fatal(err) - } - if err := s.Confirm(ctx, b.Claims, b.SHA256, b.Size, now); err == nil { - t.Fatal("missing aggregate did not fail") - } - var status string - if err := s.DB.QueryRow(`SELECT status FROM download_attempts WHERE attempt_id=UNHEX(?)`, b.AttemptID).Scan(&status); err != nil { - t.Fatal(err) - } - if status != "issued" { - t.Fatal("partial confirmation committed") - } - var downloads uint64 - if err := s.DB.QueryRow(`SELECT downloads FROM plugin_stats WHERE plugin_id='plugin'`).Scan(&downloads); err != nil { - t.Fatal(err) - } - if downloads != 1 { - t.Fatal("partial plugin increment committed") - } - if _, err := s.DB.Exec(`INSERT INTO plugin_version_stats(plugin_id,version,attempts,downloads,updated_at) VALUES ('plugin','1.0.0',2,1,UTC_TIMESTAMP(6))`); err != nil { - t.Fatal(err) - } - expectCounters(t, s, 2, 1) - }) - t.Run("catalog import idempotence conflicts and withdrawal", func(t *testing.T) { - raw, _ := json.Marshal(c) - same, digest, _ := catalog.Read(strings.NewReader(string(raw))) - if err := s.Import(ctx, same, digest, now); err != nil { - t.Fatal(err) - } - conflict := c - conflict.Generation = 2 - conflict.Plugins = append([]catalog.Package(nil), c.Plugins...) - conflict.Plugins[0].SHA256 = strings.Repeat("f", 64) - conflict.Plugins[0].ObjectKey = "packages/plugin/1.0.0/" + conflict.Plugins[0].SHA256 + ".tfp" - raw, _ = json.Marshal(conflict) - conflict, digest, _ = catalog.Read(strings.NewReader(string(raw))) - if err := s.Import(ctx, conflict, digest, now); !errors.Is(err, ErrConflict) { - t.Fatalf("immutable metadata changed: %v", err) - } - withdrawn := append([]catalog.Package(nil), packages...) - withdrawn[0].Status = "withdrawn" - importCatalog(t, s, 2, withdrawn) - if _, err := s.Issue(ctx, "plugin", "1.0.0", strings.Repeat("e", 32), "k1", now); !errors.Is(err, ErrGone) { - t.Fatalf("withdrawn download allowed: %v", err) - } - if err := s.Confirm(ctx, b.Claims, b.SHA256, b.Size, now); err != nil { - t.Fatal("withdrawal rejected issued receipt", err) - } - expectCounters(t, s, 2, 2) - raw, _ = json.Marshal(c) - stale, digest, _ := catalog.Read(strings.NewReader(string(raw))) - if err := s.Import(ctx, stale, digest, now); !errors.Is(err, ErrConflict) { - t.Fatal("old generation imported") - } - }) - t.Run("revoked and expired receipts", func(t *testing.T) { - active := append([]catalog.Package(nil), packages...) - importCatalog(t, s, 3, active) - issued, err := s.Issue(ctx, "other", "1.0.0", strings.Repeat("e", 32), "k1", now) - if err != nil { - t.Fatal(err) - } - revoked := append([]catalog.Package(nil), packages...) - revoked[1].Status = "revoked" - importCatalog(t, s, 4, revoked) - if err := s.Confirm(ctx, issued.Claims, issued.SHA256, issued.Size, now); !errors.Is(err, ErrRevoked) { - t.Fatal("revocation did not reject receipt") - } - raw, _ := json.Marshal(catalog.Catalog{SchemaVersion: 1, SourceCommit: strings.Repeat("b", 40), Generation: 5, Plugins: active}) - revert, digest, _ := catalog.Read(strings.NewReader(string(raw))) - if err := s.Import(ctx, revert, digest, now); !errors.Is(err, ErrConflict) { - t.Fatal("revoked package resurrected", err) - } - packages[1].Status = "revoked" - active[1].Status = "revoked" - importCatalog(t, s, 5, active) - expired, err := s.Issue(ctx, "plugin", "1.0.0", strings.Repeat("f", 32), "k1", now.Add(-8*24*time.Hour)) - if err != nil { - t.Fatal(err) - } - if err := s.Confirm(ctx, expired.Claims, expired.SHA256, expired.Size, now); !errors.Is(err, ErrGone) { - t.Fatal("expired attempt confirmed") - } - }) - t.Run("version pagination precision and cleanup", func(t *testing.T) { - full := append([]catalog.Package(nil), packages...) - for i := 1; i < 103; i++ { - full = append(full, testPackage("plugin", fmt.Sprintf("2.0.%d", i))) - } - importCatalog(t, s, 6, full) - batch, err := s.Batch(ctx, []string{"plugin", "unknown"}) - if err != nil { - t.Fatal(err) - } - if len(batch.Plugins) != 1 || len(batch.Plugins[0].Versions) != 100 || !batch.Plugins[0].VersionsTruncated { - t.Fatal("batch was not bounded") - } - detail, err := s.Plugin(ctx, "plugin", 50, 50) - if err != nil || len(detail.Versions) != 50 || !detail.HasMore { - t.Fatal("pagination failed", err) - } - v, err := s.Version(ctx, "plugin", "1.0.0") - if err != nil || v.Downloads != "2" || v.TotalDownloads != "2" { - t.Fatal("version totals wrong", err) - } - if _, err := s.Plugin(ctx, "unknown", 10, 0); !errors.Is(err, ErrNotFound) { - t.Fatal("unknown plugin not distinguished") - } - if err := s.Cleanup(ctx, now.Add(40*24*time.Hour)); err != nil { - t.Fatal(err) - } - total, err := s.Total(ctx) - if err != nil || total.TotalDownloads != "2" { - t.Fatal("cleanup changed aggregate", err) - } - // Cleanup cannot turn an old signed receipt into a new confirmation. - if err := s.Confirm(ctx, a.Claims, a.SHA256, a.Size, now); !errors.Is(err, ErrNotFound) { - t.Fatal("deleted receipt recreated", err) - } - }) -} - -func TestMySQLDashboard(t *testing.T) { - s := integrationStore(t) - ctx := context.Background() - empty, err := s.Dashboard(ctx) - if err != nil { - t.Fatal(err) - } - if empty.TotalDownloads != "0" || len(empty.Ranking) != 0 || len(empty.Recent) != 0 || len(empty.Daily) != DashboardDays { - t.Fatalf("empty dashboard: %+v", empty) - } - importCatalog(t, s, 1, []catalog.Package{testPackage("plugin", "1.0.0"), testPackage("plugin", "1.1.0"), testPackage("other", "1.0.0")}) - now := time.Now().UTC().Truncate(time.Second) - confirm := func(id, version, key string, at time.Time) { - t.Helper() - a, err := s.Issue(ctx, id, version, key, "k1", at) - if err != nil { - t.Fatal(err) - } - if err := s.Confirm(ctx, a.Claims, a.SHA256, a.Size, at); err != nil { - t.Fatal(err) - } - } - confirm("plugin", "1.1.0", strings.Repeat("1", 32), now) - confirm("plugin", "1.1.0", strings.Repeat("2", 32), now) - confirm("other", "1.0.0", strings.Repeat("3", 32), now.Add(-48*time.Hour)) - if _, err := s.Issue(ctx, "other", "1.0.0", strings.Repeat("4", 32), "k1", now); err != nil { - t.Fatal(err) - } - - d, err := s.Dashboard(ctx) - if err != nil { - t.Fatal(err) - } - if d.TotalDownloads != "3" || d.Plugins != 2 || d.Versions != 3 || d.DownloadedPlugins != 2 { - t.Fatalf("totals: %+v", d) - } - if len(d.Ranking) != 2 || d.Ranking[0] != (RankedPlugin{"plugin", "2"}) || d.Ranking[1] != (RankedPlugin{"other", "1"}) { - t.Fatalf("ranking: %+v", d.Ranking) - } - if d.TopVersions[0] != (RankedVersion{"plugin", "1.1.0", "2"}) { - t.Fatalf("top versions: %+v", d.TopVersions) - } - if len(d.Daily) != DashboardDays || d.Daily[DashboardDays-1].Downloads != "2" { - t.Fatalf("daily: %+v", d.Daily) - } - var sum int - for _, day := range d.Daily { - n, _ := strconv.Atoi(day.Downloads) - sum += n - } - if sum != 3 { - t.Fatalf("daily total %d; unconfirmed attempts must not count", sum) - } - if len(d.Recent) != 3 || d.Recent[0].PluginID != "plugin" || d.Recent[2].PluginID != "other" { - t.Fatalf("recent: %+v", d.Recent) - } -} diff --git a/apps/server/migrations/000001_initial.down.sql b/apps/server/migrations/000001_initial.down.sql deleted file mode 100644 index 92338a05..00000000 --- a/apps/server/migrations/000001_initial.down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- Destructive: reserved for isolated tests, never executed by production CLI. -DROP TABLE IF EXISTS download_attempts; -DROP TABLE IF EXISTS plugin_version_stats; -DROP TABLE IF EXISTS plugin_stats; -DROP TABLE IF EXISTS plugin_versions; -DROP TABLE IF EXISTS catalog_state; diff --git a/apps/server/migrations/000001_initial.up.sql b/apps/server/migrations/000001_initial.up.sql deleted file mode 100644 index e51c4864..00000000 --- a/apps/server/migrations/000001_initial.up.sql +++ /dev/null @@ -1,55 +0,0 @@ -CREATE TABLE plugin_versions ( - plugin_id VARCHAR(191) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, - version VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, - sha256 BINARY(32) NOT NULL, - size_bytes BIGINT UNSIGNED NOT NULL, - object_key VARCHAR(1024) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, - status ENUM('active','withdrawn','revoked') NOT NULL, - published_at DATETIME(6) NOT NULL, - PRIMARY KEY (plugin_id,version), - KEY idx_plugin_versions_published (plugin_id,published_at) -) ENGINE=InnoDB; -CREATE TABLE plugin_stats ( - plugin_id VARCHAR(191) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, - attempts BIGINT UNSIGNED NOT NULL DEFAULT 0, - downloads BIGINT UNSIGNED NOT NULL DEFAULT 0, - updated_at DATETIME(6) NOT NULL, - PRIMARY KEY (plugin_id) -) ENGINE=InnoDB; -CREATE TABLE plugin_version_stats ( - plugin_id VARCHAR(191) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, - version VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, - attempts BIGINT UNSIGNED NOT NULL DEFAULT 0, - downloads BIGINT UNSIGNED NOT NULL DEFAULT 0, - updated_at DATETIME(6) NOT NULL, - PRIMARY KEY (plugin_id,version), - CONSTRAINT fk_version_stats FOREIGN KEY (plugin_id,version) REFERENCES plugin_versions(plugin_id,version) -) ENGINE=InnoDB; -CREATE TABLE download_attempts ( - attempt_id BINARY(16) NOT NULL, - plugin_id VARCHAR(191) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, - version VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, - sha256 BINARY(32) NOT NULL, - size_bytes BIGINT UNSIGNED NOT NULL, - receipt_kid VARCHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, - issued_at DATETIME(6) NOT NULL, - expires_at DATETIME(6) NOT NULL, - confirmed_at DATETIME(6) NULL, - status ENUM('issued','confirmed') NOT NULL DEFAULT 'issued', - PRIMARY KEY (attempt_id), - KEY idx_attempts_expiry (expires_at), - KEY idx_attempts_confirmed (confirmed_at), - CONSTRAINT fk_attempt_version FOREIGN KEY (plugin_id,version) REFERENCES plugin_versions(plugin_id,version) -) ENGINE=InnoDB; -CREATE TABLE catalog_state ( - id TINYINT UNSIGNED NOT NULL, - digest BINARY(32) NOT NULL, - source_commit VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, - generation BIGINT UNSIGNED NOT NULL, - imported_at DATETIME(6) NOT NULL, - counted_since DATETIME(6) NOT NULL, - PRIMARY KEY (id), - CONSTRAINT chk_catalog_singleton CHECK (id=1) -) ENGINE=InnoDB; -INSERT INTO catalog_state (id,digest,source_commit,generation,imported_at,counted_since) -VALUES (1,UNHEX(REPEAT('00',32)),'',0,UTC_TIMESTAMP(6),UTC_TIMESTAMP(6)); diff --git a/apps/server/migrations/embed.go b/apps/server/migrations/embed.go deleted file mode 100644 index 381665ad..00000000 --- a/apps/server/migrations/embed.go +++ /dev/null @@ -1,6 +0,0 @@ -package migrations - -import "embed" - -//go:embed *.sql -var Files embed.FS diff --git a/crates/tf-wasm/src/lib.rs b/crates/tf-wasm/src/lib.rs index b362cde0..15a575b1 100644 --- a/crates/tf-wasm/src/lib.rs +++ b/crates/tf-wasm/src/lib.rs @@ -36,6 +36,8 @@ const CALL_TICKS: u64 = 300; /// 任务不设超时(取消由插件轮询 is-cancelled 完成) const TASK_TICKS: u64 = u64::MAX / 2; const MEMORY_LIMIT: usize = 1 << 30; +const MEMORY_RESERVATION: u64 = 32 << 20; +const MEMORY_GROWTH_RESERVATION: u64 = 64 << 20; /// 单次 read-file 的上限 const MAX_READ: u32 = 4 * 1024 * 1024; pub const FS_PERMISSION: &str = "fs:user-selected"; @@ -60,6 +62,12 @@ fn engine() -> &'static Engine { let mut config = Config::new(); config.wasm_component_model(true); config.epoch_interruption(true); + // 每个已加载插件都保留实例。默认每个线性内存预留 4 GiB 地址空间, + // 插件多时会累积到数百 GiB。缩小预留,内存仍可增长至 Store 的上限。 + config.memory_reservation(MEMORY_RESERVATION); + config.memory_reservation_for_growth(MEMORY_GROWTH_RESERVATION); + // 启动或升级时可能需要重编译大量插件,限制单次 JIT 编译的内存峰值。 + config.parallel_compilation(false); let engine = Engine::new(&config).expect("valid wasmtime config"); let ticker = engine.clone(); std::thread::Builder::new() @@ -450,14 +458,13 @@ fn write_cache(component: &Component, path: &Path) { } impl WasmPlugin { - /// 编译组件并检查导出;实例在第一次调用时创建 + /// 编译组件并实例化,加载时即可发现不兼容的导入或导出 pub fn load(manifest: Manifest, wasm: &[u8]) -> PluginResult { Self::load_cached(manifest, wasm, None) } /// 带编译缓存加载:cache 存在则直接反序列化(毫秒级),未命中时编译并写回。 - /// 启动时要加载大量在线插件,Cranelift 编译每个都会占满所有核心, - /// 缓存把重复启动的编译成本降为零 + /// 兼容的缓存可避免每次启动重新编译在线插件。 pub fn load_cached( manifest: Manifest, wasm: &[u8], diff --git a/crates/tf-wasm/src/lib_test.rs b/crates/tf-wasm/src/lib_test.rs index 34bbb9f2..170de443 100644 --- a/crates/tf-wasm/src/lib_test.rs +++ b/crates/tf-wasm/src/lib_test.rs @@ -40,6 +40,29 @@ fn load() -> WasmPlugin { WasmPlugin::load(Manifest::from_static(MANIFEST), fixture()).unwrap() } +#[test] +fn linear_memory_can_grow_past_its_reservation_within_the_guest_limit() { + let engine = engine(); + let mut store = Store::new( + engine, + StoreLimitsBuilder::new().memory_size(MEMORY_LIMIT).build(), + ); + store.limiter(|limits| limits); + let memory = wasmtime::Memory::new(&mut store, wasmtime::MemoryType::new(1, None)).unwrap(); + memory.write(&mut store, 0, b"toolforge").unwrap(); + + let page_bytes = memory.page_size(&store); + memory + .grow(&mut store, MEMORY_RESERVATION / page_bytes) + .unwrap(); + assert!(memory.data_size(&store) as u64 > MEMORY_RESERVATION); + assert_eq!(&memory.data(&store)[..9], b"toolforge"); + + let pages_over_limit = MEMORY_LIMIT as u64 / page_bytes + 1; + let pages_to_grow = pages_over_limit - memory.size(&store); + assert!(memory.grow(&mut store, pages_to_grow).is_err()); +} + #[derive(Default)] struct Ctx { logs: Mutex>, @@ -399,12 +422,16 @@ fn file_scope_limits_reads_and_writes_to_granted_folders() { std::fs::remove_dir_all(root).unwrap(); } -/// 编译缓存:第一次写入缓存文件,第二次直接反序列化;缓存损坏时自动重编译 +/// 编译缓存:正常加载、旧引擎配置和文件损坏恢复。 +/// 恢复用例使用独立缓存路径——反序列化会 mmap 缓存文件,覆盖已映射文件在 +/// Windows 报共享冲突、在 Linux 触发 SIGBUS。 #[test] fn compile_cache_roundtrip_and_recovery() { let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/tf-wasm-cache-test"); std::fs::create_dir_all(&root).unwrap(); let cache = root.join("plugin.compiled"); + let corrupt = root.join("plugin-corrupt.compiled"); + let old_cache = root.join("plugin-old.compiled"); let manifest = Manifest::from_static(MANIFEST); let wasm = fixture(); @@ -419,14 +446,32 @@ fn compile_cache_roundtrip_and_recovery() { json!(42) ); - // 缓存损坏:回退重新编译并重写缓存 - std::fs::write(&cache, b"not a compiled artifact").unwrap(); - let plugin = WasmPlugin::load_cached(manifest, wasm, Some(&cache)).unwrap(); + let mut old_config = Config::new(); + old_config.wasm_component_model(true); + old_config.epoch_interruption(true); + old_config.parallel_compilation(false); + let old_engine = Engine::new(&old_config).unwrap(); + let old_bytes = Component::new(&old_engine, wasm) + .unwrap() + .serialize() + .unwrap(); + std::fs::write(&old_cache, &old_bytes).unwrap(); + let plugin = WasmPlugin::load_cached(manifest.clone(), wasm, Some(&old_cache)).unwrap(); + assert_eq!( + plugin.call("sum", json!({"values": [21, 21]})).unwrap(), + json!(42) + ); + assert_ne!(std::fs::read(&old_cache).unwrap(), old_bytes); + assert!(cached_component(engine(), &old_cache).is_some()); + + // 缓存损坏(独立文件):回退重新编译并重写缓存 + std::fs::write(&corrupt, b"not a compiled artifact").unwrap(); + let plugin = WasmPlugin::load_cached(manifest, wasm, Some(&corrupt)).unwrap(); assert_eq!( plugin.call("sum", json!({"values": [1, 2, 39]})).unwrap(), json!(42) ); - assert_ne!(std::fs::read(&cache).unwrap(), b"not a compiled artifact"); + assert_ne!(std::fs::read(&corrupt).unwrap(), b"not a compiled artifact"); - std::fs::remove_dir_all(root).unwrap(); + // 首个缓存文件仍被映射,不在此处删除(临时目录由系统清理) } diff --git a/deploy/plugin-stats/README.md b/deploy/plugin-stats/README.md deleted file mode 100644 index f4342e47..00000000 --- a/deploy/plugin-stats/README.md +++ /dev/null @@ -1,187 +0,0 @@ -# ToolForge 插件统计服务部署 - -本文和目录内文件是部署模板;提交代码或运行本地检查不会自动初始化服务器、修改现有 Nginx 站点、读取服务器凭据或部署。首次上线由管理员核对后执行。 - -## 快速开始(推 dev 自动部署) - -服务器只需要 MySQL 和一个能用 sudo 的 SSH 账号(root 也行);服务安装、迁移、重启全部由 workflow 远程完成。 - -1. 服务器建库建账号(执行一次,密码建议只用字母数字,避免 `@` 和引号): - -```sql -CREATE DATABASE toolforge_stats CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; -CREATE USER 'toolforge_stats'@'localhost' IDENTIFIED BY '换成你自己的密码'; -GRANT ALL PRIVILEGES ON toolforge_stats.* TO 'toolforge_stats'@'localhost'; -FLUSH PRIVILEGES; -``` - -2. 生成回报签名密钥:`openssl rand -base64 32`。 -3. 仓库 Settings → Secrets and variables → Actions 填写: - -| 类型 | 名称 | 值 | -| --- | --- | --- | -| secret | `SSH_HOST` | `43.162.108.186` | -| secret | `SSH_USER` | 服务器 SSH 账号(root 或有 sudo 的账号) | -| secret | `SSH_KEY` | 对应私钥全文 | -| secret | `DB_HOST` | `127.0.0.1`(服务必须连本机回环) | -| secret | `DB_PORT` | `3306` | -| secret | `DB_USER` | `toolforge_stats` | -| secret | `DB_PASSWORD` | 上面建账号时设置的密码 | -| secret | `DB_NAME` | `toolforge_stats` | -| secret | `RECEIPT_KEY` | 第 2 步生成的 base64 密钥 | -| secret | `COS_SECRET_ID` / `COS_SECRET_KEY` | 腾讯云密钥;桶为**私有读写**时必需——服务用它给 302 目标生成 10 分钟有效的预签名下载 URL,与 Plugins 发布用同一组即可(不填则要求桶公开读) | - -部署脚本不会改动 Nginx 与 `stats.toolforge.devlive.org` 的任何配置(HTTPS、证书、站点文件都归你自己管理);它只安装二进制、写入 `/etc/toolforge-plugin-stats/runtime.env` 并重启 `toolforge-plugin-stats` 服务。 - -4. 推送改动 `apps/server/**` 的提交到 `dev` → 自动测试、构建、上传、迁移、重启、健康检查,失败自动回滚旧版本;`workflow_dispatch` 可手动补部署。 - -需要收紧安全(专用受限 SSH 登录、独立数据库角色)时再参考下文加固,不是必需步骤。 - -## 架构与顺序 - -- `plugins.toolforge.devlive.org` 保持腾讯云 COS 内容域名;桶为 `toolforge-1258585472`,地域先按 `ap-singapore` 配置,上线前确认。 -- `stats.toolforge.devlive.org` 新增 A 记录至 `43.162.108.186`,由该机现有 Nginx 提供 TLS,反代 `127.0.0.1:8088`。 -- App 插件索引中的下载 `url` 字段统一为统计 API;首跳 302 后才下载 COS,不提供统计故障时的 COS 直连降级。 -- 顺序:数据库及账号 → 管理员安装受限入口/systemd → 部署服务 → 设置新站点和 TLS → Plugins workflow 首次 bootstrap → 新 App。 -- `/readyz` 用于本机部署,确认 schema 和运行提交 SHA。首次还没有目录时 `catalogReady:false`,服务可以启动;目录及索引上线后再检查 `catalogReady:true`。 - -## 首次服务器准备 - -先检查已有进程、端口、数据库备份和 Nginx include 结构;不得覆盖现有站点或改 MySQL 监听。既有 MySQL TCP 端口不是默认 3306,本服务优先使用 `/var/run/mysqld/mysqld.sock`。服务器不需要安装 Go,基础工具需要 `bash`, `curl`, `jq`, `flock`, `sha256sum`, `runuser`。 - -建议创建三个 `--system --no-create-home --shell /usr/sbin/nologin` OS 用户及对应同名组: - -| OS 用户 | 用途 | -| --- | --- | -| `toolforge-stats` | 常驻 HTTP 服务 | -| `toolforge-stats-migrate` | 独立数据库迁移进程 | -| `toolforge-stats-catalog` | 可信全版本目录导入 | - -管理员安装: - -- `deploy.sh` → `/usr/local/sbin/toolforge-plugin-stats-deploy`,`root:root 0755`。 -- `toolforge-plugin-stats.service` → `/etc/systemd/system/toolforge-plugin-stats.service`,`root:root 0644`。 -- `/opt/toolforge-plugin-stats/releases/` 和 `/opt/toolforge-plugin-stats/current` 只允许管理员写;部署入口维护它们。 -- `/etc/toolforge-plugin-stats/`:`root:toolforge-stats 0750`。 -- `runtime.env`:`root:toolforge-stats 0640`;`migrate.env`、`catalog.env`:`root:root 0600`。 -- 执行 `systemctl daemon-reload` 和 `systemctl enable toolforge-plugin-stats`。首次二进制到达前不要启动空服务。 - -`migrate.env`、`catalog.env` 仅由管理员入口读取,再以干净环境执行相应低权限用户;无需让这些用户读取配置文件。 - -### 数据库及配置 - -新建 `toolforge_stats` 数据库(InnoDB、utf8mb4);不要复用已有业务库、root 或已有应用账号。凭据通过管理员的安全配置流程产生,不写入 Git、不贴到 issue/chat。密码如含 shell 特殊字符需使用正确引用。配置格式使用 systemd 和 shell 都支持的单行 `KEY=value`/`KEY='value'`,不使用命令替换、变量展开或可执行脚本。 - -每份文件使用各自的 MySQL 用户: - -```dotenv -MYSQL_SOCKET=/var/run/mysqld/mysqld.sock -MYSQL_DATABASE=toolforge_stats -MYSQL_USER= -MYSQL_PASSWORD='' -``` - -`runtime.env` 另外配置: - -```dotenv -STATS_LISTEN_ADDR=127.0.0.1:8088 -PLUGIN_ASSET_BASE_URL=https://plugins.toolforge.devlive.org -RECEIPT_ACTIVE_KID=2026-01 -RECEIPT_KEYS_JSON='{"2026-01":""}' -# 可选:看板插件名来源;未设置时使用公共插件索引,显式置空则看板只显示插件 ID -PLUGIN_REGISTRY_URL=https://plugins.toolforge.devlive.org/registry.json -``` - -服务进程内嵌公共统计看板(`/` 页面与 `/assets/dashboard.js|css`),数据来自 `/v1/dashboard` 聚合接口;Nginx 站点需放行 `location = /` 与 `location /assets/` 两个前缀(见模板),其余路径仍返回 404。 - -不要把占位符直接投入生产。HMAC 密钥只属于服务运行配置,迁移和目录导入无需此密钥;轮换保留旧密钥至所有旧凭据过期。MySQL 用户为本机 `localhost` 连接授权,先以对应 OS 身份测试 socket 权限。 - -权限建议(以实际迁移及服务文档为准,全部仅限新数据库): - -| MySQL 角色 | 所需权限 | -| --- | --- | -| runtime | `plugin_versions` 查询;`download_attempts` 查询/插入/更新/清理;`plugin_version_stats`、`plugin_stats` 查询/插入/更新;`catalog_state`、`schema_migrations` 查询 | -| catalog | `plugin_versions`、`plugin_version_stats`、`plugin_stats`、`catalog_state` 查询/插入/更新;`schema_migrations` 查询 | -| migrate | 本库内建表、改表、索引及迁移状态读写;不授予其他库或全局权限 | - -上线前启用现有备份或为本库配置备份,确认恢复演练。计数表和幂等记录需恢复到同一备份时间点;不能只恢复一方。迁移采用兼容旧程序的新增方式,生产不自动执行 `down`。 - -### SSH 身份隔离 - -不要将日常 `ubuntu` 通用 SSH 私钥放入 Actions。建议创建专用部署与目录导入登录账号,密码锁定,SSH key 仅允许受限 forced command。两个账号使用两把不同的 key,禁止 PTY、端口/代理/X11 转发及用户 rc(OpenSSH `restrict`)。 - -部署 key 对应 `authorized_keys` 的 forced command: - -```text -restrict,command="sudo -n /usr/local/sbin/toolforge-plugin-stats-deploy ssh deploy \"$SSH_ORIGINAL_COMMAND\"" -``` - -目录 key: - -```text -restrict,command="sudo -n /usr/local/sbin/toolforge-plugin-stats-deploy ssh catalog \"$SSH_ORIGINAL_COMMAND\"" -``` - -sudoers 只允许各自入口,使用 `visudo -cf` 验证后安装(账号名称按管理员实际选择替换): - -```sudoers - ALL=(root) NOPASSWD: /usr/local/sbin/toolforge-plugin-stats-deploy ssh deploy * - ALL=(root) NOPASSWD: /usr/local/sbin/toolforge-plugin-stats-deploy ssh catalog * -``` - -入口不使用 `eval`,拒绝任意路径和其他命令,校验提交 SHA、内容摘要和流大小;catalog 身份无法上传/运行新二进制。服务器文件由管理员持有,Actions 不更新入口、sudoers、Nginx、systemd 或环境配置。 - -从已经信任的管理连接核对服务器主机公钥,将完整 known_hosts 内容配置到 GitHub Environment;不要在流水线中以未验证的 `ssh-keyscan` 替代验证。 - -## Nginx 与 TLS - -先确认 DNS、生效的站点目录与证书管理方式。新增独立站点 `nginx.conf`,保留其他站点;模板里的 `limit_req_zone`/`log_format` 必须位于 `http` 上下文。首次证书不存在时只启用 HTTP/ACME 段,取得证书后再启用 HTTPS 段。适配已有 ACME 自动续期和实际证书路径。 - -执行 `nginx -t` 成功后 reload。API 进程只监听回环,`/healthz`、`/readyz` 不公开;代理覆盖来源头,服务只信任本机代理。模板限制请求体为 4 KiB,分别限制下载、回报、查询请求;不缓存 302 和回报,不写 IP、查询串、请求体、Authorization 或响应凭据到访问日志。服务器异常日志保留必要诊断。**不启用 COS 访问日志。** - -## GitHub 配置 - -部署 workflow 直接读取仓库 Actions secrets(见快速开始表格);数据库密码与回报 HMAC 密钥也由 secrets 注入并在每次部署时写入服务器 `/etc/toolforge-plugin-stats/runtime.env`(`root:toolforge-stats 0640`)。使用受保护 Environment 或仓库级 secret 均可,workflow 未绑定 Environment。 - -| 类型 | 名称 | 用途 | -| --- | --- | --- | -| secret | `TOOLFORGE_PLUGIN_KEY` | 既有官方插件签名种子;只给独立签名步骤(Plugins 发布用) | -| secret | `COS_SECRET_ID` / `COS_SECRET_KEY` | 腾讯云 COS 上传身份,限制桶及必要对象前缀,优先临时凭据(Plugins 发布用) | -| secret | `COS_SESSION_TOKEN` | 使用临时凭据时配置,长期受限凭据可留空 | -| secret | `PLUGIN_CATALOG_SSH_KEY` | 只给插件发布的受限导入 key | -| variable | `COS_REGION` | 默认 `ap-singapore`,上线前核实 | -| variable | `PLUGIN_CATALOG_SSH_TARGET` | `@43.162.108.186` | - -统计服务部署所需 secrets 见「快速开始」表格(`SSH_*`、`DB_*`、`RECEIPT_KEY`)。上表 COS 与目录导入凭据属于 Plugins 发布 workflow;若沿用旧的受限部署入口(`deploy.sh`),再补充 `STATS_DEPLOY_SSH_KEY`、`STATS_DEPLOY_SSH_TARGET`、`PLUGIN_SSH_KNOWN_HOSTS` 三项。 - -数据库密码与回报 HMAC 密钥通过 secrets 注入并随每次部署写入服务器 `/etc/toolforge-plugin-stats/runtime.env`(`root:toolforge-stats 0640`);`DB_PASSWORD` 建议只用字母数字(DSN 中不能安全携带 `@` 与引号)。Secrets 未就绪时应失败,不能静默改为未签名包、空历史目录、HTTP 下载或直接 COS 降级。 - -## 插件发布与历史搬迁 - -Plugins workflow 固定 COSCLI **v1.0.8 Linux amd64**,固定官方 GitHub release 资产 SHA-256 `7165f2ae16c5f7ac495864c963ca574a76e04ec72680d7bc8a8eee3234d8cf91`。升级须重新核实官方发行文件/摘要和 CLI 参数。上传配置在临时 0600 YAML 中,凭据不作为命令行参数、不输出;结束删除配置。COSCLI 关闭日志和失败请求文件。参考 [官方发行资产](https://github.com/tencentyun/coscli/releases/expanded_assets/v1.0.8)、[官方 cp 实现与参数](https://github.com/tencentyun/coscli/blob/v1.0.8/cmd/cp.go)。 - -首次从 `dev` 手动运行 Plugins 并选择 `bootstrap=true`: - -1. 校验仓库访问权限,完整下载固定 `plugins` Release 的全部历史 `.tfp`。网络/鉴权/读取失败停止;仅已确认的 Release 404 可以作为无历史版本。 -2. 原字节搬迁历史包,逐包检查官方签名;不重新构建/重签,不导入历史 GitHub 下载量。 -3. 新版本在无生产凭据、只读 token 的独立 job 构建;干净 runner 只构建受信 xtask 并下载候选产物再单独签名,不运行插件 Cargo/Vite。签名私钥只提供给签名步骤,构建进程无法替换另一台 runner 的签名工具。 -4. 全版本目录保留旧撤销/下架状态;缺历史文件、同版本内容冲突或签名异常停止。 -5. `packages/{id}/{version}/{sha256}.tfp` 使用 COS `--forbid-overwrite`;已有对象只接受大小与 SHA-256 一致。HTTPS 自定义域名读回必须匹配。 -6. 上传按摘要命名的不可变 catalog/registry 快照,导入 MySQL 目录,再更新短缓存 catalog/registry 指针。 -7. 最后补 GitHub 兼容镜像;`.tfp` 永不 `--clobber`,仅两个 JSON 允许替换。 - -后续由 `dev` 相关路径推送触发。插件、共享 SDK、前端锁文件或该插件 WASM 依赖闭包中的 Cargo.lock 记录发生变化但版本没升时失败;App 原生依赖独有的 Cargo.lock 变化不会要求市场插件升版,不能覆盖现有版本。首次 COS catalog 404 只在显式 bootstrap 下允许,403/网络失败永远停止。全版本目录使用 Plugins workflow 的 `GITHUB_RUN_NUMBER` 作递增 generation;不要重建/更名该 workflow 后重置计数。迁移其他仓库或调整 generation 时先确认现有服务代次,不能绕过过期发布保护。 - -失败重跑会重新读取历史;COS 目录中已有但 GitHub 尚未镜像的版本从 COS 取回原始签名字节,不重新构建。已成功上传的同摘要 COS 对象跳过,GitHub 已镜像版本不会覆盖。同一 generation 仅接受目录内容完全相同的幂等重跑。目录已导入而索引未发出不会删除制品,重新发布会对账。GitHub 镜像中断时 COS 正式索引可能已经生效;重跑补镜像,不回滚成功统计。旧 App 可以跟随 302,但无法提交成功回报,完整口径从新 App 起生效。 - -## 部署和回滚 - -推送 `dev` 且涉及服务端路径时自动执行:先 Go 格式、依赖、vet、race 单元/真实 MySQL 集成检查,再构建 `CGO_ENABLED=0` Linux amd64 二进制并带提交 SHA。通过固定 known_hosts 的受限 SSH 按字节流上传,服务器不安装 Go。并发由 `plugin-stats-production` 组串行化,不会交错部署。 - -需要与 CI 相同产物的本地构建用 `deploy/plugin-stats/build.sh`(默认完整测试,`--skip-tests` 跳过;输出二进制与 `plugin-stats.sha256`,`-X main.buildSHA` 注入与 workflow 一致——缺失会导致 `/readyz` 校验失败并触发回滚)。 - -服务端入口依次获得同一把部署/导入锁、验证 SHA-256、安装不可变版本目录、使用独立迁移角色执行 `migrate up`、原子切换 `current`、重启、轮询本机 `/readyz` 的 `buildSha`。失败恢复旧链接并检查旧服务;首次无旧版则停止失败服务。数据库迁移绝不自动 down。旧二进制兼容迁移是回滚前提。 - -人工回滚应使用已保留旧制品,通过受限部署入口提交旧 SHA 与对应摘要;不要手工执行破坏性数据库回滚。当前代码不提供删除历史制品/统计数据的自动任务。索引回滚从 `snapshots/registry/.json` 恢复已知良好内容,仍需保持统计 API URL;撤销恶意版本应先更新可信目录状态,不能只把索引降版。 - -验收包括新服务首次启动、新版失败自动回退、并发回报计数幂等、签名/摘要错误零成功量、App 重启继续回报、API 故障不直连 COS、目录旧 generation 拒绝、同版本不同制品拒绝、撤销不复活及发布中断重跑。跨系统不存在事务,MySQL 目录、COS 指针、GitHub 镜像的各阶段要分开验证。 diff --git a/deploy/plugin-stats/bootstrap-server.sh b/deploy/plugin-stats/bootstrap-server.sh deleted file mode 100755 index 0c5de3ec..00000000 --- a/deploy/plugin-stats/bootstrap-server.sh +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env bash -# One-time server bootstrap for the plugin statistics service (run as root). -# Creates the database, OS users, /etc config, deployment entry and systemd -# service so that a dev push deploys automatically afterwards. -# -# Copy this file together with deploy.sh and toolforge-plugin-stats.service -# to the server, then run: -# sudo bash bootstrap-server.sh --deploy-key "$(cat stats-deploy.pub)" -# -# Flags: -# --deploy-key public SSH key allowed to deploy (required) -# --asset-base COS download domain (default plugins.toolforge.devlive.org) -# --listen API listen address (default 127.0.0.1:8088) -set -euo pipefail -umask 077 - -deploy_key= -asset_base=https://plugins.toolforge.devlive.org -listen=127.0.0.1:8088 -while [[ $# -gt 0 ]]; do - case $1 in - --deploy-key) - shift - deploy_key=${1:?--deploy-key requires a value} - ;; - --asset-base) - shift - asset_base=${1:?--asset-base requires a value} - ;; - --listen) - shift - listen=${1:?--listen requires a value} - ;; - *) echo "Unknown flag: $1" >&2; exit 1 ;; - esac - shift -done - -[[ $EUID == 0 ]] || { echo 'Run as root' >&2; exit 1; } -here=$(cd "$(dirname "$0")" && pwd) -[[ -f $here/deploy.sh && -f $here/toolforge-plugin-stats.service ]] || { - echo 'Put bootstrap-server.sh next to deploy.sh and toolforge-plugin-stats.service from the repository' >&2 - exit 1 -} -[[ -n $deploy_key ]] || { echo 'A deploy public key is required for automated deployment' >&2; exit 1; } - -for tool in mysql jq flock sha256sum; do - command -v "$tool" >/dev/null || { echo "Missing $tool; install it first" >&2; exit 1; } -done - -echo '==> Creating OS users' -for name in toolforge-stats toolforge-stats-migrate toolforge-stats-catalog; do - id "$name" >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin "$name" -done -id stats-deploy >/dev/null 2>&1 || useradd -m -s /bin/bash stats-deploy - -echo '==> Creating database and application account' -# One MySQL account covers runtime, migrations and catalog import; split roles -# later by editing the three env files if you need tighter privileges. -stats_password=$(openssl rand -base64 24 | tr -d '/+=') -mysql < Writing /etc/toolforge-plugin-stats' -install -d -o root -g root -m 750 /etc/toolforge-plugin-stats -install -o root -g toolforge-stats -m 640 /dev/null /etc/toolforge-plugin-stats/runtime.env -cat > /etc/toolforge-plugin-stats/runtime.env < /etc/toolforge-plugin-stats/migrate.env < Installing deployment entry and systemd service' -install -o root -g root -m 755 "$here/deploy.sh" /usr/local/sbin/toolforge-plugin-stats-deploy -install -o root -g root -m 644 "$here/toolforge-plugin-stats.service" /etc/systemd/system/toolforge-plugin-stats.service -install -d -o root -g root -m 755 /opt/toolforge-plugin-stats/releases -install -d -o toolforge-stats -g toolforge-stats -m 700 /var/lib/toolforge-plugin-stats -install -d -o root -g root -m 700 /var/lib/toolforge-plugin-stats-deploy - -install -d -o stats-deploy -g stats-deploy -m 700 ~stats-deploy/.ssh -key_file=$(mktemp) -printf '%s\n' "$deploy_key" > "$key_file" -cat "$key_file" >> ~stats-deploy/.ssh/authorized_keys -rm -f "$key_file" -chmod 600 ~stats-deploy/.ssh/authorized_keys -chown -R stats-deploy:stats-deploy ~stats-deploy/.ssh -echo 'stats-deploy ALL=(root) NOPASSWD: /usr/local/sbin/toolforge-plugin-stats-deploy *' \ - > /etc/sudoers.d/toolforge-plugin-stats -chmod 440 /etc/sudoers.d/toolforge-plugin-stats -visudo -cf /etc/sudoers.d/toolforge-plugin-stats - -systemctl daemon-reload -systemctl enable toolforge-plugin-stats - -host_key=$(ssh-keyscan -t ed25519 127.0.0.1 2>/dev/null | head -1 || true) -echo -echo 'Bootstrap complete. Fill these in GitHub Environment plugin-stats-production:' -echo " STATS_DEPLOY_SSH_KEY = the PRIVATE key matching the public key you passed" -echo " STATS_DEPLOY_SSH_TARGET = stats-deploy@" -echo " PLUGIN_SSH_KNOWN_HOSTS = this server public host key:" -[[ -n $host_key ]] && echo "$host_key" -echo -echo 'The service starts on the first automated deploy (push server changes to dev).' diff --git a/deploy/plugin-stats/build.sh b/deploy/plugin-stats/build.sh deleted file mode 100755 index 26ff6aba..00000000 --- a/deploy/plugin-stats/build.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env bash -# Build the plugin statistics service binary exactly like the deploy workflow. -# Usage: build.sh [--skip-tests] [output-dir] -# Produces /plugin-stats and /plugin-stats.sha256. -# The commit SHA is injected via -X main.buildSHA; deploy.sh readiness check -# compares it against the deployed commit, so omitting it breaks deployment. -set -euo pipefail -cd "$(dirname "$0")/../.." # repository root - -skip_tests=false -out=build -while [[ $# -gt 0 ]]; do - case $1 in - --skip-tests) skip_tests=true ;; - -h|--help) echo "Usage: build.sh [--skip-tests] [output-dir]"; exit 0 ;; - *) out=$1 ;; - esac - shift -done - -[[ -f apps/server/go.mod ]] || { echo 'apps/server/go.mod not found; run from the repository' >&2; exit 1; } -commit=$(git rev-parse HEAD) -# Keep the regex in a variable: bash 3.2 brace-expands {40} inside [[ =~ ]]. -sha_re='^[a-f0-9]{40}$' -[[ $commit =~ $sha_re ]] || { echo 'Could not resolve a full commit SHA; build inside a git checkout' >&2; exit 1; } - -cd apps/server -if [[ $skip_tests != true ]]; then - test -z "$(gofmt -l .)" || { echo 'gofmt differences found; run gofmt first' >&2; exit 1; } - go mod download - go mod verify - go vet ./... - go test -race -count=1 ./... -fi -mkdir -p "$out" -# Keep every flag identical to .github/workflows/plugin-stats-deploy.yml. -CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \ - go build -trimpath -ldflags "-s -w -X main.buildSHA=$commit" \ - -o "$out/plugin-stats" ./cmd/plugin-stats -sha256sum "$out/plugin-stats" > "$out/plugin-stats.sha256" -echo "Built $out/plugin-stats ($(cut -d ' ' -f 1 "$out/plugin-stats.sha256")) for commit $commit" -echo 'Deploy: ssh "deploy '"$commit"' " < '"$out/plugin-stats" diff --git a/deploy/plugin-stats/deploy.sh b/deploy/plugin-stats/deploy.sh deleted file mode 100755 index fb896be5..00000000 --- a/deploy/plugin-stats/deploy.sh +++ /dev/null @@ -1,119 +0,0 @@ -#!/usr/bin/env bash -# Install root-owned as /usr/local/sbin/toolforge-plugin-stats-deploy. -# All input is streamed on stdin; neither identity can choose a filesystem path. -set -euo pipefail -umask 077 -[[ $EUID == 0 ]] || { echo 'Run through the restricted administrator-installed entrypoint' >&2; exit 1; } -if [[ ${1:-} == ssh ]]; then - allowed=${2:-} - original=${3:-} - read -r -a request <<< "$original" - [[ $allowed == deploy || $allowed == catalog ]] || exit 1 - [[ ${request[0]:-} == "$allowed" ]] || { echo 'SSH identity is not authorized for this operation' >&2; exit 1; } - set -- "${request[@]}" -fi -operation=${1:-} -base=/opt/toolforge-plugin-stats -state=/var/lib/toolforge-plugin-stats-deploy -config=/etc/toolforge-plugin-stats -install -d -o root -g root -m 700 "$state" -install -d -o root -g root -m 755 "$base" "$base/releases" -exec 9> "$state/deploy.lock" -flock -w 120 9 -scratch=$(mktemp -d "$state/request.XXXXXX") -trap 'rm -rf "$scratch"' EXIT -with_env() ( - local file=$1 user=$2 - shift 2 - [[ -f $file && ! -L $file && $(stat -c %u "$file") == 0 ]] || { echo 'Unsafe service configuration ownership' >&2; exit 1; } - local mode - mode=$(stat -c %a "$file") - (( (8#$mode & 0027) == 0 )) || { echo 'Service configuration must not be group writable or accessible to other users' >&2; exit 1; } - # Start with a clean environment: SSH and deployment variables never reach DB commands. - exec env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin /bin/bash --noprofile --norc -c " - set -aeuo pipefail - source \"\$1\" - shift - role=\$1 - shift - exec /usr/sbin/runuser -u \"\$role\" -- \"\$@\" - " toolforge-config "$file" "$user" "$@" -) -ready() { - local expected=$1 - curl --fail --silent --show-error --connect-timeout 1 --max-time 2 http://127.0.0.1:8088/readyz 2>/dev/null | jq -e --arg sha "$expected" '.status == "ready" and .buildSha == $sha' >/dev/null -} -case "$operation" in - deploy) - [[ $# == 3 && $2 =~ ^[a-f0-9]{40}$ && $3 =~ ^[a-f0-9]{64}$ ]] || { echo 'Usage: deploy ' >&2; exit 1; } - commit=$2 - checksum=$3 - head -c 67108865 > "$scratch/plugin-stats" - [[ $(stat -c %s "$scratch/plugin-stats") -le 67108864 ]] || { echo 'Binary exceeds upload limit' >&2; exit 1; } - printf '%s %s\n' "$checksum" "$scratch/plugin-stats" | sha256sum --check --status - release="$base/releases/$commit" - if [[ -e $release ]]; then - [[ -d $release && ! -L $release ]] || exit 1 - printf '%s %s\n' "$checksum" "$release/plugin-stats" | sha256sum --check --status - else - install -d -o root -g root -m 755 "$release" - install -o root -g root -m 755 "$scratch/plugin-stats" "$release/plugin-stats" - fi - # Additive migrations only; credentials belong to a separate low-privilege OS/DB identity. - with_env "$config/migrate.env" toolforge-stats-migrate "$release/plugin-stats" migrate up - previous='' - if [[ -L $base/current ]]; then - previous=$(readlink -f "$base/current") - elif [[ -e $base/current ]]; then - echo 'Current release must be a symlink' >&2 - exit 1 - fi - if [[ -n $previous ]]; then - [[ $previous == "$base/releases/"* && -x $previous/plugin-stats ]] || { echo 'Unsafe previous release link' >&2; exit 1; } - fi - ln -sfn "$release" "$base/current.next" - mv -Tf "$base/current.next" "$base/current" - success=false - if systemctl restart toolforge-plugin-stats; then - for ((attempt=0; attempt<30; attempt++)); do - if ready "$commit"; then success=true; break; fi - sleep 1 - done - fi - if [[ $success != true ]]; then - if [[ -n $previous ]]; then - ln -sfn "$previous" "$base/current.rollback" - mv -Tf "$base/current.rollback" "$base/current" - systemctl restart toolforge-plugin-stats - restored=false - for ((attempt=0; attempt<15; attempt++)); do - if ready "$(basename "$previous")"; then restored=true; break; fi - sleep 1 - done - [[ $restored == true ]] || { echo 'Deployment and service rollback both failed; administrator attention required' >&2; exit 1; } - else - systemctl stop toolforge-plugin-stats - rm -f "$base/current" - fi - echo 'New service failed readiness; previous release restored. Database migrations were not reversed.' >&2 - exit 1 - fi - logger -t toolforge-plugin-stats "deployed build $commit" - echo "Ready: $commit" - ;; - catalog) - [[ $# == 2 && $2 =~ ^[a-f0-9]{64}$ ]] || { echo 'Usage: catalog ' >&2; exit 1; } - head -c 16777217 > "$scratch/catalog.json" - [[ $(stat -c %s "$scratch/catalog.json") -le 16777216 ]] || { echo 'Catalog exceeds upload limit' >&2; exit 1; } - printf '%s %s\n' "$2" "$scratch/catalog.json" | sha256sum --check --status - # Give the import user read access only to this verified catalog, never to the root staging tree. - import_dir=$(mktemp -d /tmp/toolforge-catalog.XXXXXX) - trap 'rm -rf "$scratch" "$import_dir"' EXIT - chown toolforge-stats-catalog:toolforge-stats-catalog "$import_dir" - install -o toolforge-stats-catalog -g toolforge-stats-catalog -m 400 "$scratch/catalog.json" "$import_dir/catalog.json" - with_env "$config/catalog.env" toolforge-stats-catalog "$base/current/plugin-stats" catalog import "$import_dir/catalog.json" - install -o root -g root -m 600 "$scratch/catalog.json" "$state/catalog-$2.json" - logger -t toolforge-plugin-stats "imported catalog $2" - ;; - *) echo 'Only deploy and catalog operations are supported' >&2; exit 1 ;; -esac diff --git a/deploy/plugin-stats/nginx.conf b/deploy/plugin-stats/nginx.conf deleted file mode 100644 index a7ed97e8..00000000 --- a/deploy/plugin-stats/nginx.conf +++ /dev/null @@ -1,91 +0,0 @@ -# This file is included inside nginx's http context; keep existing sites intact. -limit_req_zone $binary_remote_addr zone=toolforge_stats_download:10m rate=20r/m; -limit_req_zone $binary_remote_addr zone=toolforge_stats_report:10m rate=120r/m; -limit_req_zone $binary_remote_addr zone=toolforge_stats_read:10m rate=120r/m; -log_format toolforge_stats '$time_iso8601 $request_method $uri $status $request_time'; - -server { - listen 80; - server_name stats.toolforge.devlive.org; - # Use the administrator's existing ACME webroot and certificate automation. - location /.well-known/acme-challenge/ { root /var/www/letsencrypt; } - location / { return 301 https://stats.toolforge.devlive.org$request_uri; } -} - -server { - listen 443 ssl; - server_name stats.toolforge.devlive.org; - ssl_certificate /etc/letsencrypt/live/stats.toolforge.devlive.org/fullchain.pem; - ssl_certificate_key /etc/letsencrypt/live/stats.toolforge.devlive.org/privkey.pem; - ssl_protocols TLSv1.2 TLSv1.3; - server_tokens off; - client_max_body_size 4k; - client_body_timeout 10s; - access_log /var/log/nginx/toolforge-stats.access.log toolforge_stats; - error_log /var/log/nginx/toolforge-stats.error.log warn; - limit_req_status 429; - add_header X-Content-Type-Options nosniff always; - - location = /readyz { return 404; } - location = /healthz { return 404; } - location ~ ^/v1/plugins/[^/]+/versions/[^/]+/download$ { - limit_req zone=toolforge_stats_download burst=20 nodelay; - proxy_pass http://127.0.0.1:8088; - proxy_set_header Host stats.toolforge.devlive.org; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $remote_addr; - proxy_set_header X-Forwarded-Proto https; - proxy_connect_timeout 2s; - proxy_read_timeout 10s; - proxy_send_timeout 10s; - proxy_cache off; - } - location ~ ^/v1/downloads/[^/]+/complete$ { - limit_req zone=toolforge_stats_report burst=40 nodelay; - proxy_pass http://127.0.0.1:8088; - proxy_set_header Host stats.toolforge.devlive.org; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $remote_addr; - proxy_set_header X-Forwarded-Proto https; - proxy_connect_timeout 2s; - proxy_read_timeout 10s; - proxy_send_timeout 10s; - proxy_cache off; - add_header Cache-Control no-store always; - } - location /v1/ { - limit_req zone=toolforge_stats_read burst=40 nodelay; - proxy_pass http://127.0.0.1:8088; - proxy_set_header Host stats.toolforge.devlive.org; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $remote_addr; - proxy_set_header X-Forwarded-Proto https; - proxy_connect_timeout 2s; - proxy_read_timeout 10s; - proxy_send_timeout 10s; - } - # 公共统计看板:服务进程内嵌的静态页与脚本/样式,仅这两个前缀可到达 - location = / { - limit_req zone=toolforge_stats_read burst=40 nodelay; - proxy_pass http://127.0.0.1:8088; - proxy_set_header Host stats.toolforge.devlive.org; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $remote_addr; - proxy_set_header X-Forwarded-Proto https; - proxy_connect_timeout 2s; - proxy_read_timeout 10s; - proxy_send_timeout 10s; - } - location /assets/ { - limit_req zone=toolforge_stats_read burst=40 nodelay; - proxy_pass http://127.0.0.1:8088; - proxy_set_header Host stats.toolforge.devlive.org; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $remote_addr; - proxy_set_header X-Forwarded-Proto https; - proxy_connect_timeout 2s; - proxy_read_timeout 10s; - proxy_send_timeout 10s; - } - location / { return 404; } -} diff --git a/deploy/plugin-stats/toolforge-plugin-stats.service b/deploy/plugin-stats/toolforge-plugin-stats.service deleted file mode 100644 index 9eb0aca5..00000000 --- a/deploy/plugin-stats/toolforge-plugin-stats.service +++ /dev/null @@ -1,37 +0,0 @@ -[Unit] -Description=ToolForge official plugin download statistics -After=network.target mysql.service -Wants=mysql.service - -[Service] -Type=simple -User=toolforge-stats -Group=toolforge-stats -WorkingDirectory=/opt/toolforge-plugin-stats/current -EnvironmentFile=/etc/toolforge-plugin-stats/runtime.env -ExecStart=/opt/toolforge-plugin-stats/current/plugin-stats serve -Restart=on-failure -RestartSec=3 -TimeoutStopSec=20 -NoNewPrivileges=true -PrivateTmp=true -ProtectSystem=strict -ProtectHome=true -ProtectKernelTunables=true -ProtectKernelModules=true -ProtectControlGroups=true -RestrictSUIDSGID=true -LockPersonality=true -MemoryDenyWriteExecute=true -RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 -CapabilityBoundingSet= -AmbientCapabilities= -UMask=0077 -MemoryMax=256M -TasksMax=64 -LimitNOFILE=4096 -StandardOutput=journal -StandardError=journal - -[Install] -WantedBy=multi-user.target diff --git a/docs/plugin-download-statistics.md b/docs/plugin-download-statistics.md index 419436c6..d5cec9d1 100644 --- a/docs/plugin-download-statistics.md +++ b/docs/plugin-download-statistics.md @@ -1,6 +1,10 @@ # 官方插件下载与统计 -服务源码位于 `apps/server`,与 `apps/desktop` 同级。 +统计服务已拆分为独立仓库 [ForgeStats](https://github.com/devlive-community/forgestats)(多应用插件下载统计,本地目录 `~/Code/forgestats`),ToolForge 是其中的 `toolforge` 应用。 + +- `https://stats.toolforge.devlive.org` 保持不变:其无前缀 `/v1/...` 接口按 Host 解析为 toolforge 应用,已安装的客户端、文档站下载数和响应头 `X-ToolForge-*` 都不用改。 +- Plugins workflow 仍调用服务器上的 `/usr/local/sbin/toolforge-plugin-stats-deploy catalog `;ForgeStats 切换脚本把它替换为转发到 `forgestats-admin catalog toolforge` 的入口,目录格式(schema 1)不变。 +- 服务的部署、迁移、备份与接口说明见 ForgeStats 的 README;本仓库不再包含服务源码和部署 workflow。 ## 下载链路 diff --git a/market/address-parser/backend/Cargo.toml b/market/address-parser/backend/Cargo.toml new file mode 100644 index 00000000..6276a989 --- /dev/null +++ b/market/address-parser/backend/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "tfm-address-parser" +description = "ToolForge market plugin: license plate parser" +version = "0.1.0" +edition.workspace = true +license.workspace = true +authors.workspace = true + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +serde.workspace = true +serde_json.workspace = true +tf-plugin-api.workspace = true +tf-plugin-guest = { path = "../../../crates/tf-plugin-guest" } diff --git a/market/address-parser/backend/src/lib.rs b/market/address-parser/backend/src/lib.rs new file mode 100644 index 00000000..f4e3ecda --- /dev/null +++ b/market/address-parser/backend/src/lib.rs @@ -0,0 +1,494 @@ +//! 中国地址解析后端:把自由文本地址拆解为省/市/区县/街道/详情五级结构。 +//! 基于内置行政区划样例库(精选常用区划,完整库为数据扩充项),按最长 +//! 前缀匹配逐级剥离,后缀(省/市/区/县)可省略;不做别名与新旧区划 +//! 映射(保持严肃解析)。 + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use tf_plugin_api::{ + Manifest, PluginError, PluginResult, ToolPlugin, parse_args, to_value, unknown_function, +}; + +const MANIFEST: &str = include_str!("../../manifest.json"); + +pub struct AddressParser { + manifest: Manifest, +} + +impl Default for AddressParser { + fn default() -> Self { + Self { + manifest: Manifest::from_static(MANIFEST), + } + } +} + +impl ToolPlugin for AddressParser { + fn manifest(&self) -> &Manifest { + &self.manifest + } + + fn call(&self, function: &str, args: Value) -> PluginResult { + match function { + "parse" => to_value(parse(parse_args(args)?)?), + other => Err(unknown_function(other)), + } + } +} + +tf_plugin_guest::export_plugin!(AddressParser); + +const MAX_LENGTH: usize = 500; + +/// 城市:(名称, 下辖区县列表) +type City = (&'static str, &'static [&'static str]); +/// 行政区划样例库:省 → 下辖市;精选常用区划演示,完整民政部区划库为数据扩充项 +const DIVISIONS: &[(&str, &[City])] = &[ + ( + "北京市", + &[( + "北京", + &[ + "东城区", + "西城区", + "朝阳区", + "海淀区", + "丰台区", + "石景山区", + "通州区", + "顺义区", + "昌平区", + "大兴区", + ], + )], + ), + ( + "上海市", + &[( + "上海", + &[ + "黄浦区", + "徐汇区", + "长宁区", + "静安区", + "普陀区", + "虹口区", + "杨浦区", + "闵行区", + "宝山区", + "嘉定区", + "浦东新区", + "松江区", + "青浦区", + ], + )], + ), + ( + "天津市", + &[( + "天津", + &[ + "和平区", + "河东区", + "河西区", + "南开区", + "河北区", + "红桥区", + "滨海新区", + ], + )], + ), + ( + "重庆市", + &[( + "重庆", + &[ + "渝中区", + "江北区", + "南岸区", + "九龙坡区", + "沙坪坝区", + "渝北区", + "巴南区", + ], + )], + ), + ( + "广东省", + &[ + ( + "广州市", + &[ + "天河区", + "越秀区", + "海珠区", + "荔湾区", + "白云区", + "黄埔区", + "番禺区", + "花都区", + "南沙区", + ], + ), + ( + "深圳市", + &[ + "福田区", + "罗湖区", + "南山区", + "盐田区", + "宝安区", + "龙岗区", + "龙华区", + "坪山区", + ], + ), + ("珠海市", &["香洲区", "斗门区", "金湾区"]), + ("佛山市", &["禅城区", "南海区", "顺德区", "三水区"]), + ("东莞市", &["莞城街道", "南城街道", "东城街道"]), + ], + ), + ( + "浙江省", + &[ + ( + "杭州市", + &[ + "上城区", + "拱墅区", + "西湖区", + "滨江区", + "萧山区", + "余杭区", + "临平区", + "钱塘区", + ], + ), + ( + "宁波市", + &["海曙区", "江北区", "北仑区", "镇海区", "鄞州区"], + ), + ], + ), + ( + "江苏省", + &[ + ( + "南京市", + &[ + "玄武区", + "秦淮区", + "鼓楼区", + "建邺区", + "栖霞区", + "雨花台区", + "江宁区", + ], + ), + ( + "苏州市", + &["姑苏区", "虎丘区", "吴中区", "相城区", "吴江区"], + ), + ("无锡市", &["梁溪区", "锡山区", "惠山区", "滨湖区"]), + ], + ), + ( + "四川省", + &[ + ( + "成都市", + &[ + "锦江区", + "青羊区", + "金牛区", + "武侯区", + "成华区", + "龙泉驿区", + "双流区", + ], + ), + ("绵阳市", &["涪城区", "游仙区"]), + ], + ), + ( + "湖北省", + &[ + ( + "武汉市", + &[ + "江岸区", + "江汉区", + "硚口区", + "汉阳区", + "武昌区", + "洪山区", + "东西湖区", + ], + ), + ("宜昌市", &["西陵区", "伍家岗区"]), + ], + ), + ( + "陕西省", + &[ + ( + "西安市", + &[ + "新城区", + "碑林区", + "莲湖区", + "雁塔区", + "未央区", + "灞桥区", + "长安区", + ], + ), + ("宝鸡市", &["渭滨区", "金台区"]), + ], + ), + ( + "辽宁省", + &[ + ( + "沈阳市", + &["和平区", "沈河区", "大东区", "皇姑区", "铁西区", "浑南区"], + ), + ("大连市", &["中山区", "西岗区", "沙河口区", "甘井子区"]), + ], + ), + ( + "山东省", + &[ + ( + "济南市", + &["历下区", "市中区", "槐荫区", "天桥区", "历城区"], + ), + ( + "青岛市", + &["市南区", "市北区", "黄岛区", "崂山区", "城阳区"], + ), + ], + ), +]; + +/// 街道/镇/乡后缀 +const STREET_SUFFIXES: [&str; 6] = ["街道", "镇", "乡", "街道办事处", "苏木", "社区"]; + +fn normalize(raw: &str) -> String { + raw.chars() + .filter(|c| !c.is_whitespace()) + .map(|c| match c { + ',' | '、' => ',', + _ => c, + }) + .collect() +} + +/// 在文本开头剥离 "XX省"/"XX市"/"XX区" 形式的最长匹配(后缀可省略) +/// 返回 (剩余文本, 命中的候选名) +fn strip_level<'a>(text: &'a str, candidates: &[&'a str]) -> Option<(&'a str, &'a str)> { + let mut best: Option<(usize, &'a str)> = None; + for candidate in candidates { + // 完整形式(存储名)+ 去掉一个后缀的简称(深圳 ↔ 深圳市) + let mut forms = vec![candidate.to_string()]; + if let Some(short) = candidate + .strip_suffix('省') + .or_else(|| candidate.strip_suffix('市')) + .or_else(|| candidate.strip_suffix('区')) + .or_else(|| candidate.strip_suffix('县')) + { + forms.push(short.to_owned()); + } + for form in forms { + if text.starts_with(&form) { + let len = form.len(); + if best.map(|(best_len, _)| len > best_len).unwrap_or(true) { + best = Some((len, candidate)); + } + } + } + } + best.map(|(len, name)| (&text[len..], name)) +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Entry { + pub input: String, + pub province: String, + pub city: String, + pub district: String, + pub street: String, + pub detail: String, + /// 省市区是否全部命中 + pub matched: bool, + /// 无法归入区划的文本 + pub unmatched: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Output { + pub entries: Vec, + pub total: usize, + pub matched: usize, + pub corpus: usize, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Args { + /// 地址列表(每行一条) + pub addresses: Vec, + /// 上限(默认 100) + #[serde(default)] + pub limit: Option, +} + +pub fn parse(args: Args) -> PluginResult { + let limit = args.limit.unwrap_or(100).clamp(1, 100) as usize; + let mut entries = Vec::new(); + let mut matched_count = 0usize; + for raw in args.addresses.iter().take(limit) { + let normalized = normalize(raw); + if normalized.is_empty() { + continue; + } + if normalized.chars().count() > MAX_LENGTH { + return Err(PluginError::new("addr.too_long").with("max", MAX_LENGTH)); + } + let mut text = normalized.as_str(); + let mut province = String::new(); + let mut city = String::new(); + let mut district = String::new(); + let mut street = String::new(); + // 省(或直辖市) + let mut all_province_names: Vec<&str> = Vec::new(); + for (province_name, cities) in DIVISIONS { + all_province_names.push(province_name); + for (short, _) in cities.iter() { + all_province_names.push(short); + } + } + if let Some((rest, name)) = strip_level(text, &all_province_names) { + // 判断命中的是省级名还是直辖简称 + let province_name = DIVISIONS + .iter() + .find(|(province, _)| *province == name || cities_contain(province, name)) + .map(|(province, _)| (*province).to_owned()) + .unwrap_or_default(); + if !province_name.is_empty() { + province = province_name; + text = rest; + // 直辖市:省即市 + if is_municipality(&province) { + city = province.clone(); + // 直辖市下辖区 + if let Some((rest, district_name)) = strip_level(text, &districts_of(&province)) + { + district = district_name.to_owned(); + text = rest; + } + } else if let Some((rest, city_name)) = strip_level(text, &cities_of(&province)) { + city = city_name.to_owned(); + text = rest; + if let Some((rest, district_name)) = + strip_level(text, &districts_of_city(&province, &city)) + { + district = district_name.to_owned(); + text = rest; + } + } + } + } + // 街道/镇:文本开头到首个后缀(前缀不含数字且不超过 15 字) + let mut detail = text.to_owned(); + for suffix in STREET_SUFFIXES { + if let Some(byte_end) = text.find(suffix) { + let prefix = &text[..byte_end]; + let prefix_chars = prefix.chars().count(); + if prefix_chars > 0 + && prefix_chars <= 15 + && !prefix.chars().any(|c| c.is_ascii_digit()) + { + let end = byte_end + suffix.len(); + street = text[..end].to_owned(); + detail = text[end..].to_owned(); + break; + } + } + } + let matched = !district.is_empty(); + if matched { + matched_count += 1; + } + entries.push(Entry { + input: raw.clone(), + province, + city, + district, + street, + detail, + matched, + unmatched: if matched { + String::new() + } else { + text.to_owned() + }, + }); + } + if entries.is_empty() { + return Err(PluginError::new("addr.empty_list")); + } + Ok(Output { + total: entries.len(), + matched: matched_count, + corpus: DIVISIONS.len(), + entries, + }) +} + +fn is_municipality(province: &str) -> bool { + matches!(province, "北京市" | "上海市" | "天津市" | "重庆市") +} + +fn cities_contain(province: &str, short: &str) -> bool { + DIVISIONS + .iter() + .find(|(name, _)| *name == province) + .map(|(_, cities)| cities.iter().any(|(city, _)| city == &short)) + .unwrap_or(false) +} + +fn cities_of(province: &str) -> Vec<&'static str> { + DIVISIONS + .iter() + .find(|(name, _)| *name == province) + .map(|(_, cities)| cities.iter().map(|(city, _)| *city).collect()) + .unwrap_or_default() +} + +fn districts_of(province: &str) -> Vec<&'static str> { + // 直辖市:cities 第一个元素即该市,districts 为其下辖区 + match DIVISIONS.iter().find(|entry| entry.0 == province) { + Some(entry) => match entry.1.first() { + Some(city) => city.1.to_vec(), + None => Vec::new(), + }, + None => Vec::new(), + } +} + +fn districts_of_city(province: &str, city: &str) -> Vec<&'static str> { + match DIVISIONS.iter().find(|entry| entry.0 == province) { + Some(entry) => match entry.1.iter().find(|candidate| candidate.0 == city) { + Some(district_entry) => district_entry.1.to_vec(), + None => Vec::new(), + }, + None => Vec::new(), + } +} + +#[cfg(test)] +#[path = "lib_test.rs"] +mod tests; diff --git a/market/address-parser/backend/src/lib_test.rs b/market/address-parser/backend/src/lib_test.rs new file mode 100644 index 00000000..b246f39a --- /dev/null +++ b/market/address-parser/backend/src/lib_test.rs @@ -0,0 +1,141 @@ +use super::*; +use serde_json::json; + +fn parse_one(address: &str) -> Entry { + parse(Args { + addresses: vec![address.into()], + limit: None, + }) + .unwrap() + .entries + .remove(0) +} + +#[test] +fn municipality_full_form() { + let entry = parse_one("北京市朝阳区望京街道阜通东大街6号"); + assert_eq!(entry.province, "北京市"); + assert_eq!(entry.city, "北京市"); + assert_eq!(entry.district, "朝阳区"); + assert_eq!(entry.street, "望京街道"); + assert_eq!(entry.detail, "阜通东大街6号"); + assert!(entry.matched); +} + +#[test] +fn municipality_short_form() { + // 缺省 "市" 后缀 + let entry = parse_one("北京朝阳区大屯路"); + assert_eq!(entry.province, "北京市"); + assert_eq!(entry.district, "朝阳区"); + assert_eq!(entry.detail, "大屯路"); + assert!(entry.matched); +} + +#[test] +fn province_city_district_full() { + let entry = parse_one("广东省广州市天河区珠江新城华夏路10号"); + assert_eq!(entry.province, "广东省"); + assert_eq!(entry.city, "广州市"); + assert_eq!(entry.district, "天河区"); + assert_eq!(entry.detail, "珠江新城华夏路10号"); + assert!(entry.matched); +} + +#[test] +fn suffixes_omitted() { + // 省市区后缀全部省略 + let entry = parse_one("广东广州天河珠江新城"); + assert_eq!(entry.province, "广东省"); + assert_eq!(entry.city, "广州市"); + assert_eq!(entry.district, "天河区"); + assert!(entry.detail.contains("珠江新城")); + assert!(entry.matched); +} + +#[test] +fn district_only_unknown_province_rejected() { + // 区名不在已知省内:不猜省,matched=false,文本留在 unmatched + let entry = parse_one("中关村大街27号"); + assert!(!entry.matched); + assert_eq!(entry.province, ""); + assert!(entry.unmatched.contains("中关村")); +} + +#[test] +fn shanghai_pudong() { + let entry = parse_one("上海市浦东新区世纪大道100号"); + assert_eq!(entry.province, "上海市"); + assert_eq!(entry.district, "浦东新区"); + assert_eq!(entry.detail, "世纪大道100号"); +} + +#[test] +fn town_suffix_extracted() { + let entry = parse_one("浙江省杭州市西湖区转塘街道美院南路"); + assert_eq!(entry.province, "浙江省"); + assert_eq!(entry.city, "杭州市"); + assert_eq!(entry.district, "西湖区"); + assert_eq!(entry.street, "转塘街道"); + assert_eq!(entry.detail, "美院南路"); +} + +#[test] +fn batch_parse_preserves_order_and_counts() { + let out = parse(Args { + addresses: vec![ + "北京市海淀区中关村大街27号".into(), + "广东深圳南山科技园".into(), + "".into(), + ], + limit: None, + }) + .unwrap(); + assert_eq!(out.total, 2); + assert_eq!(out.matched, 2); + assert_eq!(out.entries[0].district, "海淀区"); + assert_eq!(out.entries[1].city, "深圳市"); +} + +#[test] +fn empty_list_rejected() { + assert!( + parse(Args { + addresses: vec!["".into(), " ".into()], + limit: None, + }) + .is_err() + ); +} + +#[test] +fn corpus_covers_municipalities_and_provinces() { + assert_eq!(DIVISIONS.len(), 12); + // 四个直辖市都在 + for municipality in ["北京市", "上海市", "天津市", "重庆市"] { + assert!(DIVISIONS.iter().any(|(name, _)| *name == municipality)); + } +} + +#[test] +fn dispatches_via_plugin() { + let tool = AddressParser::default(); + let out = tool + .call( + "parse", + json!({"addresses": ["上海市静安区南京西路1266号"]}), + ) + .unwrap(); + assert_eq!(out["matched"], 1); + assert_eq!( + tool.call("nope", json!({})).unwrap_err().code, + "plugin.function_not_found" + ); +} + +#[test] +fn declared_interfaces_match_backend_args() { + let checked = + tf_plugin_api::interface::check_declared_interfaces(&AddressParser::default()).unwrap(); + assert_eq!(checked, 1); +} diff --git a/market/address-parser/icon.svg b/market/address-parser/icon.svg new file mode 100644 index 00000000..258be13f --- /dev/null +++ b/market/address-parser/icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/market/address-parser/locales/en-US.json b/market/address-parser/locales/en-US.json new file mode 100644 index 00000000..408d9c8f --- /dev/null +++ b/market/address-parser/locales/en-US.json @@ -0,0 +1,30 @@ +{ + "name": "Address Parser", + "description": "Parse free-text Chinese addresses into province/city/district/street/detail: built-in sample division database, omittable suffixes (Guangdong-Guangzhou-Tianhe resolves fully), for batch data cleaning.", + "api": { + "parse": { + "summary": "Parse Chinese addresses into structured fields", + "addresses": "Address list (one per line)", + "limit": "Result limit (default 100)" + } + }, + "errors": { + "addr.empty_list": "Address list is empty", + "addr.too_long": "A single address exceeds 500 chars" + }, + "ui": { + "input": "Addresses (one per line)", + "parse": "Parse", + "result": "Results ({{count}})", + "matched": "{{count}} matched", + "province": "Province", + "city": "City", + "district": "District", + "street": "Street/Town", + "detail": "Detail", + "unmatched": "Unmatched text", + "corpusNote": "Division database is a curated sample ({{count}} provinces); full database is a data extension; no aliases or renamed-division mapping", + "matchedOne": "Matched", + "unmatchedOne": "Unmatched" + } +} diff --git a/market/address-parser/locales/zh-CN.json b/market/address-parser/locales/zh-CN.json new file mode 100644 index 00000000..378cc365 --- /dev/null +++ b/market/address-parser/locales/zh-CN.json @@ -0,0 +1,30 @@ +{ + "name": "地址解析器", + "description": "把自由文本中国地址拆解为省/市/区县/街道/详情结构:内置行政区划样例库,后缀可省略(广东广州天河→广东省广州市天河区),批量清洗场景。", + "api": { + "parse": { + "summary": "解析中国地址为结构化字段", + "addresses": "地址列表(每行一条)", + "limit": "数量上限(默认 100)" + } + }, + "errors": { + "addr.empty_list": "地址列表为空", + "addr.too_long": "单条地址超过 500 字" + }, + "ui": { + "input": "地址列表(每行一条)", + "parse": "解析", + "result": "结果({{count}})", + "matched": "命中 {{count}}", + "province": "省", + "city": "市", + "district": "区/县", + "street": "街道/镇", + "detail": "详情", + "unmatched": "未识别区划", + "corpusNote": "区划库为精选样例({{count}} 省级),完整库为数据扩充项;不做别名与新旧区划映射", + "matchedOne": "命中", + "unmatchedOne": "未命中" + } +} diff --git a/market/address-parser/manifest.json b/market/address-parser/manifest.json new file mode 100644 index 00000000..480f383d --- /dev/null +++ b/market/address-parser/manifest.json @@ -0,0 +1,58 @@ +{ + "id": "org.devlive.toolforge.address-parser", + "version": "0.1.0", + "name": "i18n:name", + "description": "i18n:description", + "category": "life", + "keywords": [ + "address", + "地址", + "解析", + "行政区划", + "清洗" + ], + "accent": "lime", + "locales": [ + "zh-CN", + "en-US" + ], + "minAppVersion": "0.2.0", + "permissions": [], + "functions": { + "parse": { + "history": true, + "interface": { + "expose": [ + "cli", + "agent" + ], + "summary": "i18n:api.parse.summary", + "effect": "read", + "params": { + "type": "object", + "required": [ + "addresses" + ], + "properties": { + "addresses": { + "type": "array", + "items": { + "type": "string" + }, + "description": "i18n:api.parse.addresses" + }, + "limit": { + "type": "integer", + "description": "i18n:api.parse.limit", + "default": 100 + } + } + }, + "examples": [ + "printf '北京市朝阳区望京街道阜通东大街6号\\n' | tfp-address-parser parse" + ] + } + } + }, + "sensitive": false +} diff --git a/market/address-parser/ui/package.json b/market/address-parser/ui/package.json new file mode 100644 index 00000000..d820e893 --- /dev/null +++ b/market/address-parser/ui/package.json @@ -0,0 +1,28 @@ +{ + "private": true, + "version": "0.1.0", + "type": "module", + "exports": { + ".": "./src/index.tsx" + }, + "scripts": { + "typecheck": "tsc -p tsconfig.json" + }, + "peerDependencies": { + "react": "^19" + }, + "dependencies": { + "@toolforge/plugin-ui-sdk": "workspace:*", + "@toolforge/ui": "workspace:*", + "lucide-react": "1.47.0", + "react-i18next": "17.0.15" + }, + "devDependencies": { + "@types/react": "19.3.0", + "react": "19.3.0", + "typescript": "5.9.3", + "vite": "8.3.0", + "tailwindcss": "4.3.3" + }, + "name": "@toolforge-market/address-parser" +} diff --git a/market/address-parser/ui/src/index.tsx b/market/address-parser/ui/src/index.tsx new file mode 100644 index 00000000..a0206b15 --- /dev/null +++ b/market/address-parser/ui/src/index.tsx @@ -0,0 +1,94 @@ +import { useState } from 'react' +import { Badge, Panel, Spinner } from '@toolforge/ui' +import { useDebouncedCall, usePlugin } from '@toolforge/plugin-ui-sdk' +import { MapPin } from 'lucide-react' + +interface Entry { + input: string + province: string + city: string + district: string + street: string + detail: string + matched: boolean + unmatched: string +} +interface ParseOut { + entries: Entry[] + total: number + matched: number + corpus: number +} + +const SAMPLE = `北京市朝阳区望京街道阜通东大街6号 +广东广州天河珠江新城华夏路10号 +浙江杭州西湖区转塘街道美院南路 +上海市浦东新区世纪大道100号 +中关村大街27号` // tf-allow: 示例输入 + +export default function AddressParser() { + const { t, errorMessage } = usePlugin() + const [text, setText] = useState(SAMPLE) // tf-allow: 默认值 + const parsed = useDebouncedCall( + text.trim() ? 'parse' : null, + { addresses: text.split('\n').map((line) => line.trim()).filter(Boolean) }, + [text], + ) + + const field = (label: string, value: string) => + value ? ( + + {label} + {value} + + ) : null + + return ( +
      + } title={t('ui.input')} bodyClassName="p-3"> +