From 25498f9ad37d001373a7af32cb13b069d250c1e0 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Wed, 4 Nov 2026 09:16:39 -0500 Subject: [PATCH 01/61] refactor(stats): move the statistics service to ForgeStats The plugin download statistics service now lives in the standalone devlive-community/forgestats repository, which counts several applications. stats.toolforge.devlive.org already points at it and keeps the same routes, headers and receipts, so the desktop app and the docs site need no change. - remove apps/server, deploy/plugin-stats and the plugin-stats deploy workflow - the Plugins workflow keeps its catalog entry, which now forwards to ForgeStats --- .github/workflows/plugin-stats-deploy.yml | 128 ---- .gitignore | 9 - apps/server/.env.example | 18 - apps/server/README.md | 172 ------ apps/server/cmd/plugin-stats/main.go | 179 ------ apps/server/go.mod | 10 - apps/server/go.sum | 66 -- apps/server/internal/api/api.go | 334 ---------- apps/server/internal/api/api_test.go | 269 -------- apps/server/internal/asset/asset.go | 63 -- apps/server/internal/asset/asset_test.go | 50 -- apps/server/internal/catalog/catalog.go | 98 --- apps/server/internal/catalog/catalog_test.go | 50 -- apps/server/internal/config/config.go | 125 ---- apps/server/internal/config/config_test.go | 51 -- apps/server/internal/dashboard/dashboard.go | 52 -- .../internal/dashboard/static/dashboard.css | 509 --------------- .../internal/dashboard/static/dashboard.js | 335 ---------- .../internal/dashboard/static/index.html | 110 ---- .../server/internal/dashboard/static/logo.png | Bin 16219 -> 0 bytes apps/server/internal/receipt/receipt.go | 107 ---- apps/server/internal/receipt/receipt_test.go | 58 -- apps/server/internal/registry/registry.go | 110 ---- .../server/internal/registry/registry_test.go | 89 --- apps/server/internal/store/mysql.go | 580 ------------------ apps/server/internal/store/mysql_test.go | 346 ----------- .../server/migrations/000001_initial.down.sql | 6 - apps/server/migrations/000001_initial.up.sql | 55 -- apps/server/migrations/embed.go | 6 - deploy/plugin-stats/README.md | 187 ------ deploy/plugin-stats/bootstrap-server.sh | 121 ---- deploy/plugin-stats/build.sh | 42 -- deploy/plugin-stats/deploy.sh | 119 ---- deploy/plugin-stats/nginx.conf | 91 --- .../toolforge-plugin-stats.service | 37 -- docs/plugin-download-statistics.md | 6 +- scripts/publish-plugins.sh | 1 + 37 files changed, 6 insertions(+), 4583 deletions(-) delete mode 100644 .github/workflows/plugin-stats-deploy.yml delete mode 100644 apps/server/.env.example delete mode 100644 apps/server/README.md delete mode 100644 apps/server/cmd/plugin-stats/main.go delete mode 100644 apps/server/go.mod delete mode 100644 apps/server/go.sum delete mode 100644 apps/server/internal/api/api.go delete mode 100644 apps/server/internal/api/api_test.go delete mode 100644 apps/server/internal/asset/asset.go delete mode 100644 apps/server/internal/asset/asset_test.go delete mode 100644 apps/server/internal/catalog/catalog.go delete mode 100644 apps/server/internal/catalog/catalog_test.go delete mode 100644 apps/server/internal/config/config.go delete mode 100644 apps/server/internal/config/config_test.go delete mode 100644 apps/server/internal/dashboard/dashboard.go delete mode 100644 apps/server/internal/dashboard/static/dashboard.css delete mode 100644 apps/server/internal/dashboard/static/dashboard.js delete mode 100644 apps/server/internal/dashboard/static/index.html delete mode 100644 apps/server/internal/dashboard/static/logo.png delete mode 100644 apps/server/internal/receipt/receipt.go delete mode 100644 apps/server/internal/receipt/receipt_test.go delete mode 100644 apps/server/internal/registry/registry.go delete mode 100644 apps/server/internal/registry/registry_test.go delete mode 100644 apps/server/internal/store/mysql.go delete mode 100644 apps/server/internal/store/mysql_test.go delete mode 100644 apps/server/migrations/000001_initial.down.sql delete mode 100644 apps/server/migrations/000001_initial.up.sql delete mode 100644 apps/server/migrations/embed.go delete mode 100644 deploy/plugin-stats/README.md delete mode 100755 deploy/plugin-stats/bootstrap-server.sh delete mode 100755 deploy/plugin-stats/build.sh delete mode 100755 deploy/plugin-stats/deploy.sh delete mode 100644 deploy/plugin-stats/nginx.conf delete mode 100644 deploy/plugin-stats/toolforge-plugin-stats.service 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/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 206a2cdf0a6f1dab262c2848e29abdf30432941a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 16219 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 FV1gtjlY#&M 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/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/scripts/publish-plugins.sh b/scripts/publish-plugins.sh index 4e07ee59..ed13ee92 100755 --- a/scripts/publish-plugins.sh +++ b/scripts/publish-plugins.sh @@ -72,6 +72,7 @@ for file in release-catalog registry; do put_immutable "$dir/$file.json" "snapshots/$file/$digest.json" "$digest" "$size" done catalog_digest=$(sha256sum "$dir/release-catalog.json" | cut -d ' ' -f 1) +# After the ForgeStats move this entry forwards to "forgestats-admin catalog toolforge". ssh -T -i "$PLUGIN_SSH_KEY_PATH" -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new "$PLUGIN_CATALOG_SSH_TARGET" "sudo -n /usr/local/sbin/toolforge-plugin-stats-deploy catalog $catalog_digest" < "$dir/release-catalog.json" # Import rejects stale generations. Mutable pointers are updated only after its # success. They stay publicly readable (object ACL) because installed apps fetch From 8291dee91c9e2b9783db088c8558d8499b424432 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Wed, 4 Nov 2026 11:38:03 -0500 Subject: [PATCH 02/61] fix(tf-wasm): test corrupt cache on a separate path Overwriting the mapped cache file in place hangs on Windows (shared violation) and crashes with SIGBUS on Linux; the corrupt-cache case now uses its own path so the roundtrip test passes on all platforms. --- crates/tf-wasm/src/lib_test.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/tf-wasm/src/lib_test.rs b/crates/tf-wasm/src/lib_test.rs index 34bbb9f2..d4b74c7e 100644 --- a/crates/tf-wasm/src/lib_test.rs +++ b/crates/tf-wasm/src/lib_test.rs @@ -399,12 +399,15 @@ 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 manifest = Manifest::from_static(MANIFEST); let wasm = fixture(); @@ -419,14 +422,14 @@ 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(); + // 缓存损坏(独立文件):回退重新编译并重写缓存 + 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(); + // 首个缓存文件仍被映射,不在此处删除(临时目录由系统清理) } From 1a9537c68cfc06f77e53974de231a1eb30d3de78 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Wed, 4 Nov 2026 11:38:03 -0500 Subject: [PATCH 03/61] fix(market): restore locale keys lost in batch edits The color and scratch-calculator locales lost their api.* summary/input keys and paper-box-templates missed paperLong/ paperShort when batch scripts rewrote the files, failing the convention rules check. --- market/color/locales/en-US.json | 5 +++++ market/color/locales/zh-CN.json | 5 +++++ market/paper-box-templates/locales/en-US.json | 4 +++- market/paper-box-templates/locales/zh-CN.json | 4 +++- market/scratch-calculator/locales/en-US.json | 4 +++- market/scratch-calculator/locales/zh-CN.json | 4 +++- 6 files changed, 22 insertions(+), 4 deletions(-) diff --git a/market/color/locales/en-US.json b/market/color/locales/en-US.json index 933f7322..bbc5c88c 100644 --- a/market/color/locales/en-US.json +++ b/market/color/locales/en-US.json @@ -65,6 +65,11 @@ "palette": { "summary": "Browse the Chinese traditional color palette, filter by name, pinyin or hex", "query": "Filter keyword (optional)" + }, + "convert": { + "summary": "Parse any CSS color into formats, WCAG contrast and harmonies", + "input": "Color string (e.g. #3b82f6, rebeccapurple)", + "compare": "Optional comparison color" } }, "view": { diff --git a/market/color/locales/zh-CN.json b/market/color/locales/zh-CN.json index 472a9619..37cea78a 100644 --- a/market/color/locales/zh-CN.json +++ b/market/color/locales/zh-CN.json @@ -65,6 +65,11 @@ "palette": { "summary": "查询中国传统色卡,按色名、拼音或色值过滤", "query": "过滤关键词(可选)" + }, + "convert": { + "summary": "解析任意 CSS 颜色写法,输出各格式、WCAG 对比度与配色", + "input": "颜色字符串(如 #3b82f6、rebeccapurple)", + "compare": "可选对比色" } }, "view": { diff --git a/market/paper-box-templates/locales/en-US.json b/market/paper-box-templates/locales/en-US.json index 9d57306f..82bf1183 100644 --- a/market/paper-box-templates/locales/en-US.json +++ b/market/paper-box-templates/locales/en-US.json @@ -8,7 +8,9 @@ "width": "Inner width (mm)", "height": "Inner height (mm)", "glue": "Glue tab width (mm)", - "tab": "Tuck depth (mm)" + "tab": "Tuck depth (mm)", + "paperLong": "Paper long edge mm (default A4 297)", + "paperShort": "Paper short edge mm (default 210)" }, "envelope": { "summary": "Four-petal envelope template", diff --git a/market/paper-box-templates/locales/zh-CN.json b/market/paper-box-templates/locales/zh-CN.json index 28b850b9..42a6fbdb 100644 --- a/market/paper-box-templates/locales/zh-CN.json +++ b/market/paper-box-templates/locales/zh-CN.json @@ -8,7 +8,9 @@ "width": "内宽 (mm)", "height": "内高 (mm)", "glue": "粘边宽 (mm)", - "tab": "插舌深 (mm)" + "tab": "插舌深 (mm)", + "paperLong": "纸张长边 mm(默认 A4 297)", + "paperShort": "纸张短边 mm(默认 210)" }, "envelope": { "summary": "四瓣信封展开图", diff --git a/market/scratch-calculator/locales/en-US.json b/market/scratch-calculator/locales/en-US.json index dd0dc3e1..6eaa637f 100644 --- a/market/scratch-calculator/locales/en-US.json +++ b/market/scratch-calculator/locales/en-US.json @@ -3,7 +3,9 @@ "description": "Line-by-line expression scratchpad: arithmetic and powers, variable assignment, previous-result reference and common length/mass/time units. A failing line does not stop later lines.", "api": { "evaluate": { - "angleMode": "Angle mode for trigonometry: deg (default) or rad" + "angleMode": "Angle mode for trigonometry: deg (default) or rad", + "summary": "Evaluate multi-line expressions line by line, returning each line's value or error code", + "input": "Multi-line expressions; blank lines and # comments are skipped" }, "statistics": { "summary": "Summarize multi-line numbers (expressions and units allowed): count, sum, mean, median, variance and standard deviation", diff --git a/market/scratch-calculator/locales/zh-CN.json b/market/scratch-calculator/locales/zh-CN.json index 36b014d7..57b71375 100644 --- a/market/scratch-calculator/locales/zh-CN.json +++ b/market/scratch-calculator/locales/zh-CN.json @@ -3,7 +3,9 @@ "description": "逐行求值的表达式稿纸:四则与幂、变量赋值、上一行结果、常见长度/质量/时间单位,出错行不影响后续计算。", "api": { "evaluate": { - "angleMode": "三角函数角度模式:deg(默认)或 rad" + "angleMode": "三角函数角度模式:deg(默认)或 rad", + "summary": "逐行求值多行表达式,返回每行的结果或错误码", + "input": "多行表达式;空行与 # 注释跳过" }, "statistics": { "summary": "对多行数值(支持表达式与单位)做统计摘要:计数、和、均值、中位数、方差与标准差", From b36e702321129d34561a3c8eba0b3f088790a531 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Wed, 4 Nov 2026 11:38:03 -0500 Subject: [PATCH 04/61] fix(market): flatten interface params to the plugin schema dialect The convention rules require array params to declare scalar string items and reject object-typed params. Re-encode the structured params added by recent plugins into flat string encodings - key:value pairs, JSON-encoded element strings or line-based records - with the parsing moved into each plugin's Rust backend, and update the UIs, tests and manifest defaults to match. --- market/bingo-cards/manifest.json | 20 +++- market/invoice-assistant/backend/src/lib.rs | 33 ++++++- .../invoice-assistant/backend/src/lib_test.rs | 15 +-- market/invoice-assistant/manifest.json | 31 +----- market/physics-calculator/backend/src/lib.rs | 43 +++++--- .../backend/src/lib_test.rs | 7 +- market/physics-calculator/manifest.json | 13 ++- market/pour-over-coffee/backend/src/lib.rs | 59 ++++++----- .../pour-over-coffee/backend/src/lib_test.rs | 42 ++------ market/pour-over-coffee/manifest.json | 23 +---- market/redirect-map/manifest.json | 5 +- market/robots-sitemap/manifest.json | 5 +- market/symmetry-drawing/backend/src/lib.rs | 99 +++++++++++++++---- .../symmetry-drawing/backend/src/lib_test.rs | 29 +++--- market/symmetry-drawing/manifest.json | 14 +-- market/symmetry-drawing/ui/src/index.tsx | 5 +- market/tangram-studio/backend/src/lib.rs | 85 +++++++++++++--- market/tangram-studio/backend/src/lib_test.rs | 80 +++------------ market/tangram-studio/manifest.json | 94 +++--------------- market/undercover-host/backend/src/lib.rs | 49 +++++---- .../undercover-host/backend/src/lib_test.rs | 34 ++++--- market/undercover-host/manifest.json | 13 +-- market/wardrobe-journal/backend/src/lib.rs | 45 +++++++-- .../wardrobe-journal/backend/src/lib_test.rs | 49 ++------- market/wardrobe-journal/manifest.json | 40 +++----- market/weekly-menu/backend/src/lib.rs | 75 +++++++------- market/weekly-menu/backend/src/lib_test.rs | 74 +++++--------- market/weekly-menu/manifest.json | 33 +++---- 28 files changed, 539 insertions(+), 575 deletions(-) diff --git a/market/bingo-cards/manifest.json b/market/bingo-cards/manifest.json index cd0a9673..7d1fd8ec 100644 --- a/market/bingo-cards/manifest.json +++ b/market/bingo-cards/manifest.json @@ -51,7 +51,10 @@ "g", "h", "i" - ] + ], + "items": { + "type": "string" + } }, "size": { "type": "integer", @@ -99,7 +102,10 @@ "a", "b", "c" - ] + ], + "items": { + "type": "string" + } }, "seed": { "type": "integer", @@ -146,7 +152,10 @@ "g", "h", "i" - ] + ], + "items": { + "type": "string" + } }, "freeCenter": { "type": "boolean", @@ -159,7 +168,10 @@ "a", "b", "c" - ] + ], + "items": { + "type": "string" + } } } }, diff --git a/market/invoice-assistant/backend/src/lib.rs b/market/invoice-assistant/backend/src/lib.rs index 2a76cac1..7d8b0faf 100644 --- a/market/invoice-assistant/backend/src/lib.rs +++ b/market/invoice-assistant/backend/src/lib.rs @@ -249,7 +249,32 @@ pub struct ItemArgs { pub struct ReimbursementArgs { pub title: String, pub person: String, - pub items: Vec, + /// 扁平条目:"名称:金额:税率[:类别]" + pub items: Vec, +} + +/// 扁平条目:"名称:金额:税率[:类别]"(金额含税) +fn parse_item(text: &str, index: usize) -> PluginResult { + let parts: Vec<&str> = text.split(':').map(str::trim).collect(); + if parts.len() < 3 || parts[0].is_empty() { + return Err(PluginError::new("invoice.bad_item").with("index", index as u64)); + } + let amount: f64 = parts[1] + .parse() + .map_err(|_| PluginError::new("invoice.bad_item").with("index", index as u64))?; + let rate: f64 = parts[2] + .parse() + .map_err(|_| PluginError::new("invoice.bad_item").with("index", index as u64))?; + let category = parts + .get(3) + .map(|c| (*c).to_string()) + .filter(|c| !c.is_empty()); + Ok(ItemArgs { + name: parts[0].to_owned(), + amount, + rate, + category, + }) } #[derive(Debug, Serialize)] @@ -269,10 +294,8 @@ pub fn reimbursement(args: ReimbursementArgs) -> PluginResult, + /// 已知量:"名称:数值"(国际单位制) + pub given: Vec, } #[derive(Debug, Serialize)] @@ -246,27 +246,44 @@ pub fn solve(args: SolveArgs) -> PluginResult { args.target.clone(), )); } - // 已知量必须恰好覆盖除 target 外的全部变量 - let mut given = args.given.clone(); + // 已知量必须恰好覆盖除 target 外的全部变量(扁平字符串解析为 map) + let mut known: std::collections::HashMap = std::collections::HashMap::new(); + for text in args.given.iter() { + let Some((name, value_text)) = text.split_once(':') else { + return Err(err("physics.missing_given", "name", text.as_str())); + }; + let value: f64 = value_text + .trim() + .parse() + .map_err(|_| err("physics.bad_number", "name", name.trim()))?; + known.insert(name.trim().to_lowercase(), value); + } for (name, _) in card.vars { if *name == args.target { continue; } - let value = given - .remove(*name) + let value = known + .get(*name) .ok_or_else(|| err("physics.missing_given", "name", *name))?; if !value.is_finite() { return Err(err("physics.bad_number", "name", *name)); } } - if !given.is_empty() { - return Err(err( - "physics.extra_given", - "name", - given.keys().next().cloned().unwrap_or_default(), - )); + let extra_names: Vec = known + .keys() + .filter(|name| { + name.as_str() != args.target && !card.vars.iter().any(|(var, _)| var == name) + }) + .cloned() + .collect(); + if known.contains_key(&args.target) { + return Err(err("physics.extra_given", "name", args.target.clone())); + } + if let Some(extra) = extra_names.first() { + return Err(err("physics.extra_given", "name", extra.clone())); } - let get = |name: &str| -> f64 { args.given.get(name).copied().unwrap_or(f64::NAN) }; + let given = known; + let get = |name: &str| -> f64 { given.get(name).copied().unwrap_or(f64::NAN) }; let v = get("v"); let v0 = get("v0"); let a = get("a"); diff --git a/market/physics-calculator/backend/src/lib_test.rs b/market/physics-calculator/backend/src/lib_test.rs index e062365c..aa4e751b 100644 --- a/market/physics-calculator/backend/src/lib_test.rs +++ b/market/physics-calculator/backend/src/lib_test.rs @@ -1,9 +1,8 @@ use super::*; use serde_json::json; -use std::collections::HashMap; -fn given(pairs: &[(&str, f64)]) -> HashMap { - pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect() +fn given(pairs: &[(&str, f64)]) -> Vec { + pairs.iter().map(|(k, v)| format!("{k}:{v}")).collect() } #[test] @@ -105,7 +104,7 @@ fn dispatches_via_plugin() { let out = tool .call( "solve", - json!({"card": "newton", "target": "f", "given": {"m": 2, "a": 3}}), + json!({"card": "newton", "target": "f", "given": ["m:2", "a:3"]}), ) .unwrap(); assert_eq!(out["value"], 6.0); diff --git a/market/physics-calculator/manifest.json b/market/physics-calculator/manifest.json index ed8f39f5..139716f4 100644 --- a/market/physics-calculator/manifest.json +++ b/market/physics-calculator/manifest.json @@ -50,12 +50,15 @@ "x-positional": 1 }, "given": { - "type": "object", + "type": "array", + "items": { + "type": "string" + }, "description": "i18n:api.solve.given", - "default": { - "m": 2, - "a": 3 - } + "default": [ + "m:2", + "a:3" + ] } } }, diff --git a/market/pour-over-coffee/backend/src/lib.rs b/market/pour-over-coffee/backend/src/lib.rs index c866a1cc..c93bad7d 100644 --- a/market/pour-over-coffee/backend/src/lib.rs +++ b/market/pour-over-coffee/backend/src/lib.rs @@ -52,24 +52,32 @@ pub struct PlanArgs { pub coffee_g: f64, /// 粉水比(如 15 表示 1:15) pub ratio: f64, - /// 分段:占总量比例(0-1)或毫升数,二选一;两者都缺的段按剩余量填 + /// 分段:"占比 段名" 或 "毫升 段名"(如 "0.15 闷蒸"、"90ml 第二段") #[serde(default)] - pub stages: Vec, + pub stages: Vec, } -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct StageInput { - #[serde(default)] - pub fraction: Option, - #[serde(default)] - pub ml: Option, - /// 段名(如 bloom / pour2),原样返回 - #[serde(default)] - pub label: Option, - /// 该段持续时间(秒,可选) - #[serde(default)] - pub seconds: Option, +/// 扁平段解析:"0.15 闷蒸"(占比)或 "90ml 第二段"(毫升) +fn parse_stage(text: &str, index: usize) -> PluginResult<(Option, Option, String)> { + let text = text.trim(); + if text.is_empty() { + return Err(PluginError::new("coffee.stage_empty").with("index", index as u64)); + } + let (head, label) = match text.find(' ') { + Some(pos) => (&text[..pos], text[pos + 1..].trim().to_owned()), + None => (text, format!("{}", index + 1)), + }; + let lower = head.to_lowercase(); + let value: f64 = lower + .trim_end_matches("ml") + .trim() + .parse() + .map_err(|_| PluginError::new("coffee.bad_stage").with("index", index as u64))?; + if lower.ends_with("ml") { + Ok((None, Some(value), label)) + } else { + Ok((Some(value), None, label)) + } } #[derive(Debug, Serialize)] @@ -101,18 +109,20 @@ pub fn plan(args: PlanArgs) -> PluginResult { let total = coffee * ratio; let mut stages = Vec::new(); let mut used = 0.0f64; - for (index, input) in args.stages.iter().enumerate() { - let target = match (input.fraction, input.ml) { - (Some(_), Some(_)) => { - return Err(PluginError::new("coffee.both_fraction_ml").with("index", index as u64)); - } + for (index, text) in args.stages.iter().enumerate() { + let (fraction, ml, label) = parse_stage(text, index)?; + let target = match (fraction, ml) { (Some(fraction), None) => { if !(0.0..=1.0).contains(&fraction) { return Err(PluginError::new("coffee.bad_fraction").with("index", index as u64)); } total * fraction } - (_, Some(ml)) => positive(ml, "ml")?, + (None, Some(ml)) => positive(ml, "ml")?, + // 字符串编码下此分支不可达,保留以防实现回退 + (Some(_), Some(_)) => { + return Err(PluginError::new("coffee.both_fraction_ml").with("index", index as u64)); + } (None, None) => { return Err(PluginError::new("coffee.stage_empty").with("index", index as u64)); } @@ -122,13 +132,10 @@ pub fn plan(args: PlanArgs) -> PluginResult { return Err(PluginError::new("coffee.stage_overflow").with("index", index as u64)); } stages.push(Stage { - label: input - .label - .clone() - .unwrap_or_else(|| format!("{}", index + 1)), + label, target_ml: round2(target), cumulative_ml: round2(used), - seconds: input.seconds, + seconds: None, }); } Ok(PlanOutput { diff --git a/market/pour-over-coffee/backend/src/lib_test.rs b/market/pour-over-coffee/backend/src/lib_test.rs index acc3d1e3..95a5a930 100644 --- a/market/pour-over-coffee/backend/src/lib_test.rs +++ b/market/pour-over-coffee/backend/src/lib_test.rs @@ -1,15 +1,10 @@ use super::*; use serde_json::json; -fn stages(inputs: &[(f64, &str)]) -> Vec { +fn stages(inputs: &[(&str, &str)]) -> Vec { inputs .iter() - .map(|(fraction, label)| StageInput { - fraction: Some(*fraction), - ml: None, - label: Some(label.to_string()), - seconds: None, - }) + .map(|(head, label)| format!("{head} {label}")) .collect() } @@ -18,7 +13,7 @@ fn plan_totals_and_cumulative() { let out = plan(PlanArgs { coffee_g: 15.0, ratio: 15.0, - stages: stages(&[(0.133, "bloom"), (0.4, "pour2"), (0.467, "pour3")]), + stages: stages(&[("0.133", "bloom"), ("0.4", "pour2"), ("0.467", "pour3")]), }) .unwrap(); assert_eq!(out.total_ml, 225.0); @@ -34,7 +29,7 @@ fn partial_coverage_is_reported() { let out = plan(PlanArgs { coffee_g: 20.0, ratio: 16.0, - stages: stages(&[(0.2, "bloom")]), + stages: stages(&[("0.2", "bloom")]), }) .unwrap(); assert_eq!(out.total_ml, 320.0); @@ -53,7 +48,7 @@ fn rejects_bad_inputs() { let err = plan(PlanArgs { coffee_g: 15.0, ratio: 15.0, - stages: stages(&[(1.5, "x")]), + stages: vec!["1.5 x".into()], }) .unwrap_err(); assert_eq!(err.code, "coffee.bad_fraction"); @@ -61,35 +56,18 @@ fn rejects_bad_inputs() { let err = plan(PlanArgs { coffee_g: 15.0, ratio: 15.0, - stages: vec![ - StageInput { - fraction: None, - ml: Some(200.0), - label: None, - seconds: None, - }, - StageInput { - fraction: None, - ml: Some(100.0), - label: None, - seconds: None, - }, - ], + stages: vec!["200ml".into(), "100ml".into()], }) .unwrap_err(); assert_eq!(err.code, "coffee.stage_overflow"); + // 字符串编码下占比与毫升不再可能同时出现;空段即该错误的新载体 let err = plan(PlanArgs { coffee_g: 15.0, ratio: 15.0, - stages: vec![StageInput { - fraction: Some(0.5), - ml: Some(100.0), - label: None, - seconds: None, - }], + stages: vec![String::new()], }) .unwrap_err(); - assert_eq!(err.code, "coffee.both_fraction_ml"); + assert_eq!(err.code, "coffee.stage_empty"); } #[test] @@ -123,7 +101,7 @@ fn dispatches_via_plugin() { let out = PourOverCoffee::default() .call( "plan", - json!({"coffeeG": 15, "ratio": 15, "stages": [{"fraction": 0.2, "label": "bloom"}]}), + json!({"coffeeG": 15, "ratio": 15, "stages": ["0.2 bloom"]}), ) .unwrap(); assert_eq!(out["totalMl"], 225.0); diff --git a/market/pour-over-coffee/manifest.json b/market/pour-over-coffee/manifest.json index def1d08a..9988d186 100644 --- a/market/pour-over-coffee/manifest.json +++ b/market/pour-over-coffee/manifest.json @@ -50,29 +50,12 @@ }, "stages": { "type": "array", - "description": "i18n:api.plan.stages", "items": { - "type": "object", - "properties": { - "fraction": { - "type": "number" - }, - "ml": { - "type": "number" - }, - "label": { - "type": "string" - }, - "seconds": { - "type": "number" - } - } + "type": "string" }, + "description": "i18n:api.plan.stages", "default": [ - { - "fraction": 0.2, - "label": "bloom" - } + "0.2 bloom" ] } } diff --git a/market/redirect-map/manifest.json b/market/redirect-map/manifest.json index f04e4241..4e16a209 100644 --- a/market/redirect-map/manifest.json +++ b/market/redirect-map/manifest.json @@ -44,7 +44,10 @@ "/old", "/new" ] - ] + ], + "items": { + "type": "string" + } }, "format": { "type": "string", diff --git a/market/robots-sitemap/manifest.json b/market/robots-sitemap/manifest.json index 9422c95b..9fee9d87 100644 --- a/market/robots-sitemap/manifest.json +++ b/market/robots-sitemap/manifest.json @@ -46,7 +46,10 @@ ], "crawlDelay": 10 } - ] + ], + "items": { + "type": "string" + } }, "sitemaps": { "type": "array", diff --git a/market/symmetry-drawing/backend/src/lib.rs b/market/symmetry-drawing/backend/src/lib.rs index f6ce865a..b90837ec 100644 --- a/market/symmetry-drawing/backend/src/lib.rs +++ b/market/symmetry-drawing/backend/src/lib.rs @@ -45,12 +45,40 @@ impl ToolPlugin for SymmetryDrawing { tf_plugin_guest::export_plugin!(SymmetryDrawing); -/// 一条笔画:折线点 + 该笔画自己的对称配置 -#[derive(Deserialize)] +/// 一条笔画:点序列 + 该笔画自己的对称配置。 +/// JSON 输入既可以是对象,也可以是纯点序列字符串 "x0,y0 x1,y1 …"(其余字段取默认) +impl<'de> Deserialize<'de> for Stroke { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let value = Value::deserialize(deserializer)?; + match value { + // 纯字符串 = 点序列,其余字段取默认 + Value::String(points) => Ok(Stroke { + points, + color: None, + width: None, + opacity: None, + mode: None, + folds: None, + center: None, + }), + Value::Object(_) => { + serde_json::from_value(value).map_err(|e| serde::de::Error::custom(e.to_string())) + } + _ => Err(serde::de::Error::custom( + "stroke must be a string or object", + )), + } + } +} + +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Stroke { - /// 点序列 [x0, y0, x1, y1, ...] - pub points: Vec, + /// 点序列("x0,y0 x1,y1 …",相对画布像素) + pub points: String, #[serde(default)] pub color: Option, #[serde(default)] @@ -63,9 +91,9 @@ pub struct Stroke { /// 旋转对称份数(rotate 模式 2–16) #[serde(default)] pub folds: Option, - /// 对称中心 + /// 对称中心 "cx,cy" #[serde(default)] - pub center: Option<(f64, f64)>, + pub center: Option, } #[derive(Deserialize)] @@ -79,6 +107,44 @@ pub struct ExportArgs { pub background: Option, } +/// 解析 "x0,y0 x1,y1 …" 为点对列表 +fn parse_points(text: &str) -> PluginResult> { + let mut points = Vec::new(); + for pair in text.split(' ').filter(|p| !p.is_empty()) { + let Some((x, y)) = pair.split_once(',') else { + return Err(PluginError::new("symmetry.bad_stroke").with("text", text)); + }; + let x: f64 = x + .trim() + .parse() + .map_err(|_| PluginError::new("symmetry.bad_stroke"))?; + let y: f64 = y + .trim() + .parse() + .map_err(|_| PluginError::new("symmetry.bad_stroke"))?; + points.push((x, y)); + } + if points.len() < 2 { + return Err(PluginError::new("symmetry.bad_stroke")); + } + Ok(points) +} + +fn parse_center(text: &str) -> PluginResult<(f64, f64)> { + let Some((x, y)) = text.split_once(',') else { + return Err(PluginError::new("symmetry.bad_stroke").with("text", text)); + }; + let x: f64 = x + .trim() + .parse() + .map_err(|_| PluginError::new("symmetry.bad_stroke"))?; + let y: f64 = y + .trim() + .parse() + .map_err(|_| PluginError::new("symmetry.bad_stroke"))?; + Ok((x, y)) +} + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Exported { @@ -114,13 +180,7 @@ pub fn export_svg(args: &ExportArgs) -> PluginResult { } } for stroke in &args.strokes { - let points = &stroke.points; - if points.len() < 4 || points.len() % 2 != 0 { - return Err(PluginError::new("symmetry.bad_stroke")); - } - if points.iter().any(|p| !p.is_finite()) { - return Err(PluginError::new("symmetry.bad_stroke")); - } + let points = parse_points(&stroke.points)?; let color = stroke.color.clone().unwrap_or_else(|| "#334155".into()); validate_color(&color)?; let width = stroke.width.unwrap_or(3.0); @@ -133,11 +193,12 @@ pub fn export_svg(args: &ExportArgs) -> PluginResult { } let mode = stroke.mode.as_deref().unwrap_or("none"); let folds = stroke.folds.unwrap_or(1); - let (cx, cy) = stroke - .center - .unwrap_or((args.width / 2.0, args.height / 2.0)); + let (cx, cy) = match &stroke.center { + Some(text) => parse_center(text)?, + None => (args.width / 2.0, args.height / 2.0), + }; // 生成所有对称副本的折线 - let copies = copies(points, mode, folds, cx, cy)?; + let copies = copies(&points, mode, folds, cx, cy)?; for copy in &copies { let mut d = String::with_capacity(copy.len() * 8); for (index, (x, y)) in copy.iter().enumerate() { @@ -158,13 +219,13 @@ pub fn export_svg(args: &ExportArgs) -> PluginResult { /// 计算一条笔画的所有对称副本 fn copies( - points: &[f64], + points: &[(f64, f64)], mode: &str, folds: usize, cx: f64, cy: f64, ) -> PluginResult>> { - let source: Vec<(f64, f64)> = points.chunks(2).map(|c| (c[0], c[1])).collect(); + let source: Vec<(f64, f64)> = points.to_vec(); let mut out = Vec::new(); match mode { "none" => out.push(source), diff --git a/market/symmetry-drawing/backend/src/lib_test.rs b/market/symmetry-drawing/backend/src/lib_test.rs index ecf9929d..11ade7cc 100644 --- a/market/symmetry-drawing/backend/src/lib_test.rs +++ b/market/symmetry-drawing/backend/src/lib_test.rs @@ -1,15 +1,15 @@ use super::*; use serde_json::json; -fn stroke(points: &[f64], mode: &str, folds: usize) -> Stroke { +fn stroke(points: &str, mode: &str, folds: usize) -> Stroke { Stroke { - points: points.to_vec(), + points: points.to_owned(), color: Some("#ff0000".into()), width: Some(2.0), opacity: Some(1.0), mode: Some(mode.into()), folds: Some(folds), - center: Some((100.0, 100.0)), + center: Some("100,100".into()), } } @@ -25,17 +25,17 @@ fn export(strokes: Vec) -> String { #[test] fn mirror_modes_double_or_quadruple_paths() { - let one = export(vec![stroke(&[100.0, 20.0, 120.0, 40.0], "none", 1)]); + let one = export(vec![stroke("100,20 120,40", "none", 1)]); assert_eq!(one.matches("")); @@ -58,7 +59,7 @@ fn transparent_export_has_no_background_rect() { #[test] fn validates_strokes_and_params() { let err = export_svg(&ExportArgs { - strokes: vec![stroke(&[10.0], "none", 1)], + strokes: vec![stroke("10", "none", 1)], width: 100.0, height: 100.0, background: None, @@ -66,7 +67,7 @@ fn validates_strokes_and_params() { .unwrap_err(); assert_eq!(err.code, "symmetry.bad_stroke"); let err = export_svg(&ExportArgs { - strokes: vec![stroke(&[10.0, 10.0, 20.0, 20.0], "rotate", 20)], + strokes: vec![stroke("10,10 20,20", "rotate", 20)], width: 100.0, height: 100.0, background: None, @@ -74,7 +75,7 @@ fn validates_strokes_and_params() { .unwrap_err(); assert_eq!(err.code, "symmetry.bad_folds"); let err = export_svg(&ExportArgs { - strokes: vec![stroke(&[10.0, 10.0, 20.0, 20.0], "none", 1)], + strokes: vec![stroke("10,10 20,20", "none", 1)], width: 100.0, height: 100.0, background: Some("javascript:alert(1)".into()), @@ -89,7 +90,7 @@ fn dispatches_via_plugin() { .call( "export_svg", json!({ - "strokes": [{"points": [100.0, 10.0, 110.0, 20.0], "mode": "rotate", "folds": 4, "center": [100.0, 100.0]}], + "strokes": ["100,10 110,20"], "width": 200.0, "height": 200.0 }), diff --git a/market/symmetry-drawing/manifest.json b/market/symmetry-drawing/manifest.json index 9e069fed..267d480a 100644 --- a/market/symmetry-drawing/manifest.json +++ b/market/symmetry-drawing/manifest.json @@ -40,20 +40,12 @@ "strokes": { "type": "array", "items": { - "type": "object" + "type": "string" }, "description": "i18n:api.export_svg.strokes", "default": [ - { - "points": [ - 100, - 10, - 110, - 20 - ], - "mode": "none", - "folds": 1 - } + "100,10 110,20", + "110,20 120,30" ] }, "width": { diff --git a/market/symmetry-drawing/ui/src/index.tsx b/market/symmetry-drawing/ui/src/index.tsx index 1b504970..dc0a0d9b 100644 --- a/market/symmetry-drawing/ui/src/index.tsx +++ b/market/symmetry-drawing/ui/src/index.tsx @@ -155,7 +155,10 @@ export default function SymmetryDrawing() { const exportSvg = async () => { const svg = await callPlugin<{ svg: string }>('org.devlive.toolforge.symmetry-drawing', 'export_svg', { - strokes: strokesRef.current, width: SIZE, height: SIZE, background: 'transparent', + strokes: strokesRef.current.map((stroke) => stroke.points), + width: SIZE, + height: SIZE, + background: 'transparent', }) const blob = new Blob([svg.svg], { type: 'image/svg+xml' }) const url = URL.createObjectURL(blob) diff --git a/market/tangram-studio/backend/src/lib.rs b/market/tangram-studio/backend/src/lib.rs index 2e383fbf..d65814be 100644 --- a/market/tangram-studio/backend/src/lib.rs +++ b/market/tangram-studio/backend/src/lib.rs @@ -102,10 +102,10 @@ pub fn pieces() -> Vec { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct ValidateArgs { - /// 目标轮廓(外多边形顶点,逆时针) - pub outline: Vec<(f64, f64)>, - /// 每块的摆放:kind/index + 平移 + 旋转角(度,45 的倍数)+ 翻面 - pub placements: Vec, + /// 目标轮廓:"x0,y0 x1,y1 …"(外多边形顶点,逆时针) + pub outline: String, + /// 每块摆放:"kind,index,x,y,rot,flip"(rot 度数;flip 0/1) + pub placements: Vec, } #[derive(Clone, Deserialize)] @@ -226,16 +226,76 @@ fn segments_intersect(p1: (f64, f64), p2: (f64, f64), p3: (f64, f64), p4: (f64, && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0)) } +/// 解析 "x0,y0 x1,y1 …" 为顶点列表 +fn parse_outline(text: &str) -> PluginResult> { + let mut points = Vec::new(); + for pair in text.split(' ').filter(|p| !p.is_empty()) { + let Some((x, y)) = pair.split_once(',') else { + return Err(PluginError::new("tangram.bad_outline").with("text", text)); + }; + let x: f64 = x + .trim() + .parse() + .map_err(|_| PluginError::new("tangram.bad_outline"))?; + let y: f64 = y + .trim() + .parse() + .map_err(|_| PluginError::new("tangram.bad_outline"))?; + points.push((x, y)); + } + if points.len() < 3 { + return Err(PluginError::new("tangram.bad_outline").with("text", text)); + } + Ok(points) +} + +/// 解析 "kind,index,x,y,rot,flip" +fn parse_placement(text: &str) -> PluginResult { + let parts: Vec<&str> = text.split(',').map(str::trim).collect(); + if parts.len() != 6 { + return Err(PluginError::new("tangram.bad_placement").with("text", text)); + } + let rotation: f64 = parts[4] + .parse() + .map_err(|_| PluginError::new("tangram.bad_placement").with("text", text))?; + let flipped: bool = match parts[5] { + "0" => false, + "1" => true, + _ => return Err(PluginError::new("tangram.bad_placement").with("text", text)), + }; + Ok(Placement { + kind: parts[0].to_owned(), + index: parts[1] + .parse() + .map_err(|_| PluginError::new("tangram.bad_placement").with("text", text))?, + x: parts[2] + .parse() + .map_err(|_| PluginError::new("tangram.bad_placement").with("text", text))?, + y: parts[3] + .parse() + .map_err(|_| PluginError::new("tangram.bad_placement").with("text", text))?, + rotation, + flipped, + }) +} + pub fn validate(args: ValidateArgs) -> PluginResult { let catalog = pieces(); + let outline = parse_outline(&args.outline)?; + let placements: Vec = args + .placements + .iter() + .map(|text| parse_placement(text)) + .collect::>>()?; let mut issues: Vec = Vec::new(); - if args.placements.len() != 7 { - return Err(PluginError::new("tangram.wrong_piece_count") - .with("count", args.placements.len() as u64)); + if placements.len() != 7 { + return Err( + PluginError::new("tangram.wrong_piece_count").with("count", placements.len() as u64) + ); } let mut used_area = 0.0f64; let mut transformed: Vec> = Vec::new(); - for placement in &args.placements { + for placement in &placements { let Some(piece) = catalog .iter() .find(|p| p.kind == placement.kind && p.index == placement.index) @@ -248,7 +308,7 @@ pub fn validate(args: ValidateArgs) -> PluginResult { transformed.push(transform(piece, placement)); } // 面积必须等于轮廓面积 - let outline_area = polygon_area(&args.outline); + let outline_area = polygon_area(&outline); if (used_area - outline_area).abs() > 0.01 { issues.push(format!("area_mismatch:{used_area:.2}vs{outline_area:.2}")); return Ok(ValidateOutput { @@ -259,9 +319,10 @@ pub fn validate(args: ValidateArgs) -> PluginResult { } // 每块都必须在轮廓内(顶点在外且不在轮廓边界上才算越界) for (index, polygon) in transformed.iter().enumerate() { - if polygon.iter().any(|(x, y)| { - !point_in_polygon(*x, *y, &args.outline) && !on_boundary(*x, *y, &args.outline) - }) { + if polygon + .iter() + .any(|(x, y)| !point_in_polygon(*x, *y, &outline) && !on_boundary(*x, *y, &outline)) + { issues.push(format!("outside:{index}")); } } diff --git a/market/tangram-studio/backend/src/lib_test.rs b/market/tangram-studio/backend/src/lib_test.rs index ae2a3c81..5d302449 100644 --- a/market/tangram-studio/backend/src/lib_test.rs +++ b/market/tangram-studio/backend/src/lib_test.rs @@ -1,65 +1,16 @@ use super::*; use serde_json::json; -fn standard_square_placements() -> Vec { +fn standard_square_placements() -> Vec { // 经典正方形拼法:七块按分割原位摆回(零平移零旋转) vec![ - Placement { - kind: "large".into(), - index: 0, - x: 0.0, - y: 0.0, - rotation: 0.0, - flipped: false, - }, - Placement { - kind: "large".into(), - index: 1, - x: 0.0, - y: 0.0, - rotation: 0.0, - flipped: false, - }, - Placement { - kind: "medium".into(), - index: 2, - x: 0.0, - y: 0.0, - rotation: 0.0, - flipped: false, - }, - Placement { - kind: "small".into(), - index: 3, - x: 0.0, - y: 0.0, - rotation: 0.0, - flipped: false, - }, - Placement { - kind: "small".into(), - index: 4, - x: 0.0, - y: 0.0, - rotation: 0.0, - flipped: false, - }, - Placement { - kind: "square".into(), - index: 5, - x: 0.0, - y: 0.0, - rotation: 0.0, - flipped: false, - }, - Placement { - kind: "parallelogram".into(), - index: 6, - x: 0.0, - y: 0.0, - rotation: 0.0, - flipped: false, - }, + "large,0,0,0,0,0".into(), + "large,1,0,0,0,0".into(), + "medium,2,0,0,0,0".into(), + "small,3,0,0,0,0".into(), + "small,4,0,0,0,0".into(), + "square,5,0,0,0,0".into(), + "parallelogram,6,0,0,0,0".into(), ] } @@ -77,7 +28,7 @@ fn pieces_have_expected_areas() { #[test] fn classic_square_arrangement_completes() { let out = validate(ValidateArgs { - outline: vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)], + outline: "0,0 4,0 4,4 0,4".into(), placements: standard_square_placements(), }) .unwrap(); @@ -88,19 +39,18 @@ fn classic_square_arrangement_completes() { fn overlap_and_outside_are_detected() { let mut placements = standard_square_placements(); // 平移大三角造成越界 - placements[0].x += 6.0; + placements[0] = "large,0,6,0,0,0".into(); let out = validate(ValidateArgs { - outline: vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)], + outline: "0,0 4,0 4,4 0,4".into(), placements: placements.clone(), }) .unwrap(); assert_eq!(out.status, "outside"); // 复位后制造重叠:小三角挪到与大三角内部重叠处 - placements[0].x = 0.0; - placements[3].x = 0.5; - placements[3].y = 1.0; + placements[0] = "large,0,0,0,0,0".into(); + placements[3] = "small,3,0.5,1,0,0".into(); let out = validate(ValidateArgs { - outline: vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)], + outline: "0,0 4,0 4,4 0,4".into(), placements, }) .unwrap(); @@ -114,7 +64,7 @@ fn overlap_and_outside_are_detected() { #[test] fn area_mismatch_reports() { let out = validate(ValidateArgs { - outline: vec![(0.0, 0.0), (6.0, 0.0), (6.0, 6.0), (0.0, 6.0)], + outline: "0,0 6,0 6,6 0,6".into(), placements: standard_square_placements(), }) .unwrap(); diff --git a/market/tangram-studio/manifest.json b/market/tangram-studio/manifest.json index d5565b53..4eef9be1 100644 --- a/market/tangram-studio/manifest.json +++ b/market/tangram-studio/manifest.json @@ -53,96 +53,24 @@ ], "properties": { "outline": { - "type": "array", + "type": "string", "description": "i18n:api.validate.outline", - "items": { - "type": "array", - "items": { - "type": "number" - } - }, - "default": [ - [ - 0, - 0 - ], - [ - 4, - 0 - ], - [ - 4, - 4 - ], - [ - 0, - 4 - ] - ] + "default": "0,0 4,0 4,4 0,4" }, "placements": { "type": "array", - "description": "i18n:api.validate.placements", "items": { - "type": "object" + "type": "string" }, + "description": "i18n:api.validate.placements", "default": [ - { - "kind": "large", - "index": 0, - "x": 0, - "y": 0, - "rotation": 0, - "flipped": false - }, - { - "kind": "large", - "index": 1, - "x": 0, - "y": 0, - "rotation": 0, - "flipped": false - }, - { - "kind": "medium", - "index": 2, - "x": 0, - "y": 0, - "rotation": 0, - "flipped": false - }, - { - "kind": "small", - "index": 3, - "x": 0, - "y": 0, - "rotation": 0, - "flipped": false - }, - { - "kind": "small", - "index": 4, - "x": 0, - "y": 0, - "rotation": 0, - "flipped": false - }, - { - "kind": "square", - "index": 5, - "x": 0, - "y": 0, - "rotation": 0, - "flipped": false - }, - { - "kind": "parallelogram", - "index": 6, - "x": 0, - "y": 0, - "rotation": 0, - "flipped": false - } + "large,0,0,0,0,0", + "large,1,0,0,0,0", + "medium,2,0,0,0,0", + "small,3,0,0,0,0", + "small,4,0,0,0,0", + "square,5,0,0,0,0", + "parallelogram,6,0,0,0,0" ] } } diff --git a/market/undercover-host/backend/src/lib.rs b/market/undercover-host/backend/src/lib.rs index 44e91b17..59bfeac5 100644 --- a/market/undercover-host/backend/src/lib.rs +++ b/market/undercover-host/backend/src/lib.rs @@ -81,9 +81,9 @@ pub struct DealArgs { /// 词对类别;缺省随机 #[serde(default)] pub category: Option, - /// 自定义词对(覆盖内置库) + /// 自定义词对:"平民词:卧底词" #[serde(default)] - pub custom_pair: Option<(String, String)>, + pub custom_pair: Option, pub seed: u64, } @@ -129,8 +129,16 @@ pub fn deal(args: DealArgs) -> PluginResult { } names.push(final_name); } - let (category, pair) = match (&args.custom_pair, args.category.as_deref()) { - (Some((civ, und)), _) => ("custom".to_owned(), (civ.clone(), und.clone())), + let (category, pair) = match (args.custom_pair.as_deref(), args.category.as_deref()) { + (Some(custom), _) => { + let Some((civ, und)) = custom.split_once(':') else { + return Err(PluginError::new("undercover.bad_custom_pair").with("pair", custom)); + }; + ( + "custom".to_owned(), + (civ.trim().to_owned(), und.trim().to_owned()), + ) + } (None, Some(category)) => { let found = WORD_PAIRS .iter() @@ -181,8 +189,8 @@ pub fn deal(args: DealArgs) -> PluginResult { pub struct TallyArgs { /// 本轮可投票的玩家座位(存活者) pub alive: Vec, - /// 每位存活者的投票(座位号;null 弃票) - pub votes: Vec>, + /// 每位存活者的投票:座位数字符串,空串 = 弃票 + pub votes: Vec, /// 是否重投轮(重投仅在并列候选间计票,仍平票则无人出局) #[serde(default)] pub runoff: bool, @@ -226,22 +234,27 @@ pub fn tally(args: TallyArgs) -> PluginResult { } else { &args.alive }; - for (index, vote) in args.votes.iter().enumerate() { + for (index, vote_text) in args.votes.iter().enumerate() { let voter = *args .alive .get(index) .ok_or_else(|| PluginError::new("undercover.voter_mismatch"))?; - if let Some(target) = vote { - if !targets.contains(target) { - return Err(PluginError::new("undercover.bad_target").with("seat", *target as u64)); - } - if !args.runoff && *target == voter { - return Err(PluginError::new("undercover.self_vote").with("seat", voter as u64)); - } - match counts.iter_mut().find(|(seat, _)| seat == target) { - Some((_, count)) => *count += 1, - None => counts.push((*target, 1)), - } + let vote_trimmed = vote_text.trim(); + if vote_trimmed.is_empty() { + continue; + } + let Ok(target) = vote_trimmed.parse::() else { + return Err(PluginError::new("undercover.bad_target").with("value", vote_trimmed)); + }; + if !targets.contains(&target) { + return Err(PluginError::new("undercover.bad_target").with("seat", target as u64)); + } + if !args.runoff && target == voter { + return Err(PluginError::new("undercover.self_vote").with("seat", voter as u64)); + } + match counts.iter_mut().find(|(seat, _)| *seat == target) { + Some((_, count)) => *count += 1, + None => counts.push((target, 1)), } } counts.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); diff --git a/market/undercover-host/backend/src/lib_test.rs b/market/undercover-host/backend/src/lib_test.rs index d6e47e31..7d69175a 100644 --- a/market/undercover-host/backend/src/lib_test.rs +++ b/market/undercover-host/backend/src/lib_test.rs @@ -4,9 +4,9 @@ use serde_json::json; #[test] fn deals_unique_undercover_and_renames_duplicates() { let out = deal(DealArgs { + custom_pair: None, players: vec!["张三".into(), "张三".into(), "李四".into(), "王五".into()], category: Some("food".into()), - custom_pair: None, seed: 5, }) .unwrap(); @@ -31,9 +31,9 @@ fn deals_unique_undercover_and_renames_duplicates() { } // 同一种子分配一致 let again = deal(DealArgs { + custom_pair: None, players: vec!["张三".into(), "张三".into(), "李四".into(), "王五".into()], category: Some("food".into()), - custom_pair: None, seed: 5, }) .unwrap(); @@ -43,25 +43,25 @@ fn deals_unique_undercover_and_renames_duplicates() { #[test] fn deal_validates_players_and_custom_pair() { let err = deal(DealArgs { + custom_pair: None, players: vec!["a".into(), "b".into(), "c".into()], category: None, - custom_pair: None, seed: 1, }) .unwrap_err(); assert_eq!(err.code, "undercover.bad_player_count"); let err = deal(DealArgs { + custom_pair: None, players: vec!["a".into(), " ".into(), "c".into(), "d".into()], category: None, - custom_pair: None, seed: 1, }) .unwrap_err(); assert_eq!(err.code, "undercover.empty_name"); let err = deal(DealArgs { + custom_pair: None, players: vec!["a".into(), "b".into(), "c".into(), "d".into()], category: Some("nope".into()), - custom_pair: None, seed: 1, }) .unwrap_err(); @@ -69,7 +69,7 @@ fn deal_validates_players_and_custom_pair() { let out = deal(DealArgs { players: vec!["a".into(), "b".into(), "c".into(), "d".into()], category: None, - custom_pair: Some(("词甲".into(), "词乙".into())), + custom_pair: Some("词甲:词乙".into()), seed: 1, }) .unwrap(); @@ -82,7 +82,13 @@ fn tally_majority_eliminates_and_checks_victory() { // 5 人存活,卧底 3 号;4 票集中 3 号 → 出局 + 卧底剩 2 人(存活 4)→ 继续 let out = tally(TallyArgs { alive: vec![0, 1, 2, 3, 4], - votes: vec![Some(3), Some(3), Some(3), Some(0), None], + votes: vec![ + "3".into(), + "3".into(), + "3".into(), + "0".into(), + String::new(), + ], runoff: false, runoff_candidates: vec![], undercover: 3, @@ -97,7 +103,7 @@ fn tally_majority_eliminates_and_checks_victory() { // 4 人存活出 4 号(非卧底)→ 存活 3 且卧底仍在 → 卧底胜 let out = tally(TallyArgs { alive: vec![0, 1, 2, 4], - votes: vec![Some(4), Some(4), Some(4), Some(0)], + votes: vec!["4".into(), "4".into(), "4".into(), "0".into()], runoff: false, runoff_candidates: vec![], undercover: 3, @@ -107,7 +113,7 @@ fn tally_majority_eliminates_and_checks_victory() { // 卧底自己被票出 → 平民胜 let out = tally(TallyArgs { alive: vec![0, 1, 2, 3], - votes: vec![Some(3), Some(3), Some(3), None], + votes: vec!["3".into(), "3".into(), "3".into(), String::new()], runoff: false, runoff_candidates: vec![], undercover: 3, @@ -121,7 +127,7 @@ fn tally_tie_then_runoff_stalemate() { // 平票 → tie + 候选 let out = tally(TallyArgs { alive: vec![0, 1, 2, 3], - votes: vec![Some(1), Some(0), None, None], + votes: vec!["1".into(), "0".into(), String::new(), String::new()], runoff: false, runoff_candidates: vec![], undercover: 2, @@ -132,7 +138,7 @@ fn tally_tie_then_runoff_stalemate() { // 重投仍平 → 无人出局 let out = tally(TallyArgs { alive: vec![0, 1, 2, 3], - votes: vec![Some(1), Some(0), None, None], + votes: vec!["1".into(), "0".into(), String::new(), String::new()], runoff: true, runoff_candidates: vec![0, 1], undercover: 2, @@ -147,7 +153,7 @@ fn tally_tie_then_runoff_stalemate() { fn tally_rejects_self_and_bad_targets() { let err = tally(TallyArgs { alive: vec![0, 1, 2, 3], - votes: vec![Some(0), Some(2), None, None], + votes: vec!["0".into(), "2".into(), String::new(), String::new()], runoff: false, runoff_candidates: vec![], undercover: 2, @@ -156,7 +162,7 @@ fn tally_rejects_self_and_bad_targets() { assert_eq!(err.code, "undercover.self_vote"); let err = tally(TallyArgs { alive: vec![0, 1, 2, 3], - votes: vec![Some(9), None, None, None], + votes: vec!["9".into(), String::new(), String::new(), String::new()], runoff: false, runoff_candidates: vec![], undercover: 2, @@ -166,7 +172,7 @@ fn tally_rejects_self_and_bad_targets() { // 重投轮只投候选 0:一票 vs 零票 → 0 出局(存活 3 且卧底 2 仍在 → 卧底胜) let out = tally(TallyArgs { alive: vec![0, 1, 2, 3], - votes: vec![Some(0), None, None, None], + votes: vec!["0".into(), String::new(), String::new(), String::new()], runoff: true, runoff_candidates: vec![0, 1], undercover: 2, diff --git a/market/undercover-host/manifest.json b/market/undercover-host/manifest.json index 5e1bc22b..234f063e 100644 --- a/market/undercover-host/manifest.json +++ b/market/undercover-host/manifest.json @@ -54,7 +54,7 @@ "description": "i18n:api.deal.category" }, "customPair": { - "type": "array", + "type": "string", "description": "i18n:api.deal.customPair" }, "seed": { @@ -101,16 +101,9 @@ "votes": { "type": "array", "items": { - "type": "integer", - "nullable": true + "type": "string" }, - "description": "i18n:api.tally.votes", - "default": [ - 1, - 0, - 0, - 0 - ] + "description": "i18n:api.tally.votes" }, "runoff": { "type": "boolean", diff --git a/market/wardrobe-journal/backend/src/lib.rs b/market/wardrobe-journal/backend/src/lib.rs index 67274662..67113a12 100644 --- a/market/wardrobe-journal/backend/src/lib.rs +++ b/market/wardrobe-journal/backend/src/lib.rs @@ -73,8 +73,10 @@ pub struct Outfit { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct SuggestArgs { - pub items: Vec, - pub outfits: Vec, + /// 衣物 JSON 字符串数组({"id","name","category","season","state"}) + pub items: Vec, + /// 搭配 JSON 字符串数组({"id","name","itemIds"}) + pub outfits: Vec, /// 期望季节(可空 = 全部) #[serde(default)] pub season: Option, @@ -91,14 +93,37 @@ pub struct Suggestion { pub dirty: Vec, } +/// 从 JSON 字符串解析 +fn parse_items(raw: &[String]) -> PluginResult> { + raw.iter() + .map(|text| { + serde_json::from_str(text).map_err(|e| { + PluginError::new("wardrobe.bad_item_json").with("detail", e.to_string()) + }) + }) + .collect() +} + +fn parse_outfits(raw: &[String]) -> PluginResult> { + raw.iter() + .map(|text| { + serde_json::from_str(text).map_err(|e| { + PluginError::new("wardrobe.bad_outfit_json").with("detail", e.to_string()) + }) + }) + .collect() +} + /// 搭配建议:按季节筛选(all 匹配一切),标记含待洗单品的组合 pub fn suggest(args: SuggestArgs) -> PluginResult { if args.outfits.is_empty() { return Err(PluginError::new("wardrobe.no_outfits")); } - let find = |id: &str| args.items.iter().find(|item| item.id == id); + let items = parse_items(&args.items)?; + let outfits = parse_outfits(&args.outfits)?; + let find = |id: &str| items.iter().find(|item| item.id == id); let mut suggestions = Vec::new(); - for outfit in &args.outfits { + for outfit in &outfits { let mut dirty = Vec::new(); let mut season_ok = true; for item_id in &outfit.item_ids { @@ -145,8 +170,10 @@ pub struct SuggestList { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct StatsArgs { - pub items: Vec, - pub outfits: Vec, + /// 衣物 JSON 字符串数组 + pub items: Vec, + /// 搭配 JSON 字符串数组 + pub outfits: Vec, /// 穿着记录:outfit id → 次数 #[serde(default)] pub wear_log: std::collections::HashMap, @@ -173,12 +200,14 @@ pub struct StatsOutput { /// 单品使用统计:穿着次数(按所在搭配的穿着次数聚合)与参与的搭配 pub fn stats(args: StatsArgs) -> PluginResult { + let items_in = parse_items(&args.items)?; + let outfits_in = parse_outfits(&args.outfits)?; let mut items = Vec::new(); let mut dirty_count = 0usize; - for item in &args.items { + for item in &items_in { let mut wear_count = 0u64; let mut outfit_names = Vec::new(); - for outfit in &args.outfits { + for outfit in &outfits_in { if outfit.item_ids.contains(&item.id) { outfit_names.push(outfit.name.clone()); wear_count += args.wear_log.get(&outfit.id).copied().unwrap_or(0); diff --git a/market/wardrobe-journal/backend/src/lib_test.rs b/market/wardrobe-journal/backend/src/lib_test.rs index eaf93927..b2e8de9b 100644 --- a/market/wardrobe-journal/backend/src/lib_test.rs +++ b/market/wardrobe-journal/backend/src/lib_test.rs @@ -1,53 +1,18 @@ use super::*; use serde_json::json; -fn items() -> Vec { +fn items() -> Vec { vec![ - Item { - id: "t1".into(), - name: "白衬衫".into(), - category: "top".into(), - color: Some("white".into()), - season: Some("all".into()), - state: Some("clean".into()), - last_worn: None, - wear_count: 0, - }, - Item { - id: "t2".into(), - name: "灰卫衣".into(), - category: "top".into(), - color: Some("gray".into()), - season: Some("winter".into()), - state: Some("dirty".into()), - last_worn: None, - wear_count: 0, - }, - Item { - id: "b1".into(), - name: "牛仔裤".into(), - category: "bottom".into(), - color: Some("blue".into()), - season: Some("all".into()), - state: Some("clean".into()), - last_worn: None, - wear_count: 0, - }, + json!({"id": "t1", "name": "白衬衫", "category": "top", "season": "all", "state": "clean"}).to_string(), + json!({"id": "t2", "name": "灰卫衣", "category": "top", "season": "winter", "state": "dirty"}).to_string(), + json!({"id": "b1", "name": "牛仔裤", "category": "bottom", "season": "all", "state": "clean"}).to_string(), ] } -fn outfits() -> Vec { +fn outfits() -> Vec { vec![ - Outfit { - id: "o1".into(), - name: "通勤".into(), - item_ids: vec!["t1".into(), "b1".into()], - }, - Outfit { - id: "o2".into(), - name: "居家".into(), - item_ids: vec!["t2".into(), "b1".into()], - }, + json!({"id": "o1", "name": "通勤", "itemIds": ["t1", "b1"]}).to_string(), + json!({"id": "o2", "name": "居家", "itemIds": ["t2", "b1"]}).to_string(), ] } diff --git a/market/wardrobe-journal/manifest.json b/market/wardrobe-journal/manifest.json index 2862ac88..8a4f0b7c 100644 --- a/market/wardrobe-journal/manifest.json +++ b/market/wardrobe-journal/manifest.json @@ -38,26 +38,22 @@ "properties": { "items": { "type": "array", + "items": { + "type": "string" + }, "description": "i18n:api.suggest.items", "default": [ - { - "id": "t1", - "name": "白衬衫", - "category": "top" - } + "{\"id\":\"i1\",\"name\":\"白衬衫\",\"category\":\"top\"}" ] }, "outfits": { "type": "array", + "items": { + "type": "string" + }, "description": "i18n:api.suggest.outfits", "default": [ - { - "id": "o1", - "name": "通勤", - "itemIds": [ - "t1" - ] - } + "{\"id\":\"i1\",\"name\":\"白衬衫\",\"category\":\"top\"}" ] }, "season": { @@ -87,26 +83,22 @@ "properties": { "items": { "type": "array", + "items": { + "type": "string" + }, "description": "i18n:api.stats.items", "default": [ - { - "id": "t1", - "name": "白衬衫", - "category": "top" - } + "{\"id\":\"i1\",\"name\":\"白衬衫\",\"category\":\"top\"}" ] }, "outfits": { "type": "array", + "items": { + "type": "string" + }, "description": "i18n:api.stats.outfits", "default": [ - { - "id": "o1", - "name": "通勤", - "itemIds": [ - "t1" - ] - } + "{\"id\":\"i1\",\"name\":\"白衬衫\",\"category\":\"top\"}" ] }, "wearLog": { diff --git a/market/weekly-menu/backend/src/lib.rs b/market/weekly-menu/backend/src/lib.rs index bded8f2b..56a6d554 100644 --- a/market/weekly-menu/backend/src/lib.rs +++ b/market/weekly-menu/backend/src/lib.rs @@ -44,8 +44,8 @@ pub struct ScaleArgs { pub base_servings: f64, /// 目标份数 pub servings: f64, - /// 食材:名称 / 数量 / 单位 - pub ingredients: Vec, + /// 食材:"名称:数量:单位" + pub ingredients: Vec, } #[derive(Debug, Clone, Deserialize, Serialize)] @@ -86,22 +86,26 @@ pub fn scale(args: ScaleArgs) -> PluginResult { } let factor = args.servings / args.base_servings; let mut ingredients = Vec::new(); - for item in &args.ingredients { - let name = item.name.trim().to_owned(); - if name.is_empty() { - return Err(PluginError::new("menu.bad_ingredient")); + for (index, text) in args.ingredients.iter().enumerate() { + let parts: Vec<&str> = text.split(':').map(str::trim).collect(); + if parts.len() < 2 || parts[0].is_empty() { + return Err(PluginError::new("menu.bad_ingredient").with("index", index as u64)); } - if VAGUE.contains(&item.unit.as_str()) || item.unit.is_empty() { + let name = parts[0].to_owned(); + let unit = parts.get(2).copied().unwrap_or("适量"); + if VAGUE.contains(&unit) { ingredients.push(ScaledIngredient { name, - amount: item.amount, - unit: item.unit.clone(), + amount: 0.0, + unit: unit.to_owned(), as_is: true, }); continue; } - let amount = round2(item.amount * factor); - let (amount, unit) = convert(amount, &item.unit); + let Ok(base) = parts[1].parse::() else { + return Err(PluginError::new("menu.bad_ingredient").with("index", index as u64)); + }; + let (amount, unit) = convert(round2(base * factor), unit); ingredients.push(ScaledIngredient { name, amount, @@ -133,9 +137,8 @@ fn convert(amount: f64, unit: &str) -> (f64, String) { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct MealSlot { - /// 菜谱 id(可空 = 外食/留空) - #[serde(default)] - pub recipe_id: Option, + /// 菜谱 id(空 = 留空/外食) + pub recipe_id: String, pub servings: f64, } @@ -151,9 +154,10 @@ pub struct Recipe { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct ShoppingArgs { - /// 一周菜单:7 天 × 3 餐(索引 0..20;0 周一早 … 20 周日晚) - pub menu: Vec, - pub recipes: Vec, + /// 菜单槽:"recipeId:servings" + pub menu: Vec, + /// 菜谱 JSON 字符串数组 + pub recipes: Vec, } #[derive(Debug, Serialize)] @@ -179,21 +183,33 @@ pub fn shopping(args: ShoppingArgs) -> PluginResult { if args.menu.len() > 21 { return Err(PluginError::new("menu.too_many_slots").with("max", 21)); } + let recipes: Vec = args + .recipes + .iter() + .map(|text| { + serde_json::from_str(text) + .map_err(|e| PluginError::new("menu.bad_recipe_json").with("detail", e.to_string())) + }) + .collect::>>()?; let mut merged: std::collections::HashMap<(String, String), ShoppingItem> = std::collections::HashMap::new(); let mut meals = 0usize; - for slot in &args.menu { - let Some(recipe_id) = &slot.recipe_id else { + for slot_text in &args.menu { + let Some((recipe_id, servings_text)) = slot_text.split_once(':') else { continue; }; - let Some(recipe) = args.recipes.iter().find(|r| &r.id == recipe_id) else { - return Err(PluginError::new("menu.unknown_recipe").with("id", recipe_id.as_str())); + let recipe_id = recipe_id.trim(); + let Some(recipe) = recipes.iter().find(|r| r.id == recipe_id) else { + return Err(PluginError::new("menu.unknown_recipe").with("id", recipe_id)); + }; + let Ok(servings) = servings_text.trim().parse::() else { + continue; }; - if !slot.servings.is_finite() || slot.servings <= 0.0 { + if !servings.is_finite() || servings <= 0.0 { return Err(PluginError::new("menu.bad_servings")); } meals += 1; - let factor = slot.servings / recipe.base_servings; + let factor = servings / recipe.base_servings; for ingredient in &recipe.ingredients { let vague = VAGUE.contains(&ingredient.unit.as_str()) || ingredient.unit.is_empty(); let (amount, unit, as_is) = if vague { @@ -202,18 +218,10 @@ pub fn shopping(args: ShoppingArgs) -> PluginResult { let (amount, unit) = convert(round2(ingredient.amount * factor), &ingredient.unit); (amount, unit, false) }; - let key = ( - ingredient.name.trim().to_lowercase(), - if as_is { - ingredient.unit.clone() - } else { - unit.clone() - }, - ); let entry = merged .entry(( - ingredient.name.trim().to_owned(), - if vague { + ingredient.name.trim().to_lowercase(), + if as_is { ingredient.unit.clone() } else { unit.clone() @@ -232,7 +240,6 @@ pub fn shopping(args: ShoppingArgs) -> PluginResult { if !entry.from.contains(&recipe.name) { entry.from.push(recipe.name.clone()); } - let _ = key; } } let mut items: Vec = merged.into_values().collect(); diff --git a/market/weekly-menu/backend/src/lib_test.rs b/market/weekly-menu/backend/src/lib_test.rs index 54aaf35f..11e92261 100644 --- a/market/weekly-menu/backend/src/lib_test.rs +++ b/market/weekly-menu/backend/src/lib_test.rs @@ -1,29 +1,12 @@ use super::*; use serde_json::json; -fn recipe() -> Recipe { - Recipe { - id: "r1".into(), - name: "番茄炒蛋".into(), - base_servings: 2.0, - ingredients: vec![ - Ingredient { - name: "西红柿".into(), - amount: 300.0, - unit: "g".into(), - }, - Ingredient { - name: "鸡蛋".into(), - amount: 3.0, - unit: "个".into(), - }, - Ingredient { - name: "盐".into(), - amount: 1.0, - unit: "适量".into(), - }, - ], - } +fn recipe_json() -> String { + r#"{"id":"r1","name":"番茄炒蛋","baseServings":2,"ingredients":[ + {"name":"西红柿","amount":300,"unit":"g"}, + {"name":"鸡蛋","amount":3,"unit":"个"}, + {"name":"盐","amount":1,"unit":"适量"}]}"# + .to_owned() } #[test] @@ -31,16 +14,24 @@ fn scales_servings_and_converts_units() { let out = scale(ScaleArgs { base_servings: 2.0, servings: 6.0, - ingredients: recipe().ingredients, + ingredients: vec![ + "西红柿:300:g".into(), + "鸡蛋:3:个".into(), + "盐:1:适量".into(), + ], }) .unwrap(); assert_eq!(out.ingredients[0].amount, 900.0); assert_eq!(out.ingredients[0].unit, "g", "below 1000g stays in grams"); assert_eq!(out.ingredients[1].amount, 9.0); assert_eq!(out.ingredients[1].unit, "个"); - let salt = &out.ingredients[2]; - assert!(salt.as_is, "适量 stays as-is"); - assert_eq!(salt.amount, 1.0, "vague amounts are not multiplied"); + let salt = out + .ingredients + .iter() + .find(|i| i.as_is) + .expect("salt stays as-is"); + assert_eq!(salt.name, "盐"); + assert_eq!(salt.unit, "适量"); } #[test] @@ -63,23 +54,10 @@ fn rejects_bad_servings() { #[test] fn shopping_merges_same_ingredient_across_meals() { - let menu = vec![ - MealSlot { - recipe_id: Some("r1".into()), - servings: 2.0, - }, - MealSlot { - recipe_id: Some("r1".into()), - servings: 4.0, - }, - MealSlot { - recipe_id: None, - servings: 1.0, - }, - ]; + let menu = vec!["r1:2".into(), "r1:4".into()]; let out = shopping(ShoppingArgs { menu, - recipes: vec![recipe()], + recipes: vec![recipe_json()], }) .unwrap(); assert_eq!(out.meals, 2); @@ -93,11 +71,8 @@ fn shopping_merges_same_ingredient_across_meals() { #[test] fn shopping_rejects_unknown_recipe() { let err = shopping(ShoppingArgs { - menu: vec![MealSlot { - recipe_id: Some("nope".into()), - servings: 2.0, - }], - recipes: vec![recipe()], + menu: vec!["nope:2".into()], + recipes: vec![recipe_json()], }) .unwrap_err(); assert_eq!(err.code, "menu.unknown_recipe"); @@ -106,7 +81,10 @@ fn shopping_rejects_unknown_recipe() { #[test] fn dispatches_via_plugin() { let out = WeeklyMenu::default() - .call("scale", json!({"baseServings": 2, "servings": 4, "ingredients": [{"name": "米", "amount": 200, "unit": "g"}]})) + .call( + "scale", + json!({"baseServings": 2, "servings": 4, "ingredients": ["米:200:g"]}), + ) .unwrap(); assert_eq!(out["ingredients"][0]["amount"], 400.0); assert_eq!( diff --git a/market/weekly-menu/manifest.json b/market/weekly-menu/manifest.json index a8dca794..88529f09 100644 --- a/market/weekly-menu/manifest.json +++ b/market/weekly-menu/manifest.json @@ -47,13 +47,12 @@ }, "ingredients": { "type": "array", + "items": { + "type": "string" + }, "description": "i18n:api.scale.ingredients", "default": [ - { - "name": "米", - "amount": 200, - "unit": "g" - } + "米:200:g" ] } } @@ -81,30 +80,22 @@ "properties": { "menu": { "type": "array", + "items": { + "type": "string" + }, "description": "i18n:api.shopping.menu", "default": [ - { - "recipeId": "r1", - "servings": 2 - } + "r1:2" ] }, "recipes": { "type": "array", + "items": { + "type": "string" + }, "description": "i18n:api.shopping.recipes", "default": [ - { - "id": "r1", - "name": "番茄炒蛋", - "baseServings": 2, - "ingredients": [ - { - "name": "西红柿", - "amount": 300, - "unit": "g" - } - ] - } + "{\"id\":\"r1\",\"name\":\"番茄炒蛋\",\"baseServings\":2,\"ingredients\":[{\"name\":\"西红柿\",\"amount\":300,\"unit\":\"g\"}]}" ] } } From 7d350a7d806c096380f7717a358fcb4c0b14d1d0 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Wed, 4 Nov 2026 12:47:57 -0500 Subject: [PATCH 05/61] feat(license-plate): parse Chinese license plate info New market plugin: normalize plates (case, dot/space separators), resolve the province abbreviation, issuing office letter, plate kind (standard/large/police/emergency/nev/large_nev) and energy type, validating length (7/8), the I/O-forbidden charset and the NEV serial letter segments. Closes #252 --- Cargo.lock | 90 ++++++ market/license-plate/backend/Cargo.toml | 16 ++ market/license-plate/backend/src/lib.rs | 205 ++++++++++++++ market/license-plate/backend/src/lib_test.rs | 91 ++++++ market/license-plate/icon.svg | 5 + market/license-plate/locales/en-US.json | 72 +++++ market/license-plate/locales/zh-CN.json | 72 +++++ market/license-plate/manifest.json | 51 ++++ market/license-plate/ui/package.json | 28 ++ market/license-plate/ui/src/index.tsx | 49 ++++ market/license-plate/ui/tsconfig.json | 4 + pnpm-lock.yaml | 279 +++++++++++++++++++ 12 files changed, 962 insertions(+) create mode 100644 market/license-plate/backend/Cargo.toml create mode 100644 market/license-plate/backend/src/lib.rs create mode 100644 market/license-plate/backend/src/lib_test.rs create mode 100644 market/license-plate/icon.svg create mode 100644 market/license-plate/locales/en-US.json create mode 100644 market/license-plate/locales/zh-CN.json create mode 100644 market/license-plate/manifest.json create mode 100644 market/license-plate/ui/package.json create mode 100644 market/license-plate/ui/src/index.tsx create mode 100644 market/license-plate/ui/tsconfig.json diff --git a/Cargo.lock b/Cargo.lock index d506b501..4eb30458 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8663,6 +8663,16 @@ 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" @@ -8854,6 +8864,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" @@ -9159,6 +9179,16 @@ dependencies = [ "tf-plugin-guest", ] +[[package]] +name = "tfm-icu-lint" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "tf-plugin-api", + "tf-plugin-guest", +] + [[package]] name = "tfm-image-converter" version = "0.1.0" @@ -9320,6 +9350,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 +9392,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 +9506,26 @@ dependencies = [ "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" @@ -9714,6 +9784,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" @@ -9764,6 +9844,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" diff --git a/market/license-plate/backend/Cargo.toml b/market/license-plate/backend/Cargo.toml new file mode 100644 index 00000000..20434190 --- /dev/null +++ b/market/license-plate/backend/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "tfm-license-plate" +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/license-plate/backend/src/lib.rs b/market/license-plate/backend/src/lib.rs new file mode 100644 index 00000000..619f7f1d --- /dev/null +++ b/market/license-plate/backend/src/lib.rs @@ -0,0 +1,205 @@ +//! 中国车牌解析后端:省份简称、发牌机关字母、能源类型与号牌类型判定、 +//! 字符集合法性校验(GA 36 常用规则)。 + +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 LicensePlate { + manifest: Manifest, +} + +impl Default for LicensePlate { + fn default() -> Self { + Self { + manifest: Manifest::from_static(MANIFEST), + } + } +} + +impl ToolPlugin for LicensePlate { + 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!(LicensePlate); + +/// 省份简称 → 省市 +const PROVINCES: &[(&str, &str)] = &[ + ("京", "北京"), + ("津", "天津"), + ("沪", "上海"), + ("渝", "重庆"), + ("冀", "河北"), + ("豫", "河南"), + ("云", "云南"), + ("辽", "辽宁"), + ("黑", "黑龙江"), + ("湘", "湖南"), + ("皖", "安徽"), + ("鲁", "山东"), + ("新", "新疆"), + ("苏", "江苏"), + ("浙", "浙江"), + ("赣", "江西"), + ("鄂", "湖北"), + ("桂", "广西"), + ("甘", "甘肃"), + ("晋", "山西"), + ("蒙", "内蒙古"), + ("陕", "陕西"), + ("吉", "吉林"), + ("闽", "福建"), + ("贵", "贵州"), + ("粤", "广东"), + ("青", "青海"), + ("藏", "西藏"), + ("川", "四川"), + ("宁", "宁夏"), + ("琼", "海南"), +]; + +/// 禁用字母(I/O 避免与 1/0 混淆) +const FORBIDDEN: [char; 2] = ['I', 'O']; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Args { + /// 车牌(容忍大小写、点号/空格分隔) + pub plate: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Output { + /// 清洗后的车牌(大写、去分隔符) + pub normalized: String, + pub valid: bool, + /// province / format / charset + pub issues: Vec, + pub province: Option<&'static str>, + /// 发牌机关字母(第二位,A–Z 除 I/O) + pub office: Option, + /// plate_kind. + pub kind: &'static str, + /// energy.(普通牌为 none) + pub energy: &'static str, +} + +pub fn parse(args: Args) -> PluginResult { + let raw = args.plate.trim(); + if raw.is_empty() { + return Err(PluginError::new("plate.empty")); + } + let cleaned: String = raw + .chars() + .filter(|c| !matches!(c, '.' | ' ' | '·' | '-')) + .map(|c| c.to_uppercase().next().unwrap_or(c)) + .collect(); + let normalized = cleaned.clone(); + let mut issues = Vec::new(); + let chars: Vec = cleaned.chars().collect(); + + // 1) 首字省份 + let province = if chars.is_empty() { + None + } else { + PROVINCES + .iter() + .find(|(short, _)| short.starts_with(chars[0])) + .map(|(_, name)| *name) + }; + let province = match province { + Some(name) => Some(name), + None => { + issues.push("province".into()); + None + } + }; + + // 2) 长度与形态:普通牌 7 位(省份+机关+6 位序号)、新能源 8 位 + let len = chars.len(); + let kind; + let energy; + if len == 8 { + kind = if chars[1] == 'G' || chars[1] == 'D' { + "large_nev" + } else { + "nev" + }; + // 新能源小型车序号首字母 D/F + energy = match chars[2] { + 'A'..='D' => "electric", + 'E'..='F' => "hybrid", + _ => "unknown", + }; + } else if len == 7 { + kind = if chars[1] == 'G' || chars[1] == 'D' { + "large" + } else if chars[1] == 'J' { + "police" + } else if chars[1] == 'X' && cleaned.contains("应急") { + "emergency" + } else { + "standard" + }; + energy = "none"; + } else { + kind = "unknown"; + energy = "unknown"; + issues.push("format".into()); + } + + // 3) 发牌机关字母(第 2 位) + let office = if len >= 2 { + let c = chars[1]; + if c.is_ascii_uppercase() && !FORBIDDEN.contains(&c) { + Some(c) + } else { + issues.push("office".into()); + None + } + } else { + None + }; + + // 4) 序号字符集:字母数字,I/O 禁用 + let serial_start = if len >= 2 { 2 } else { 0 }; + let mut charset_ok = true; + for c in &chars[serial_start.min(len)..] { + let ok = c.is_ascii_alphanumeric() && !FORBIDDEN.contains(c); + if !ok { + charset_ok = false; + } + } + if !charset_ok { + issues.push("charset".into()); + } + + let valid = issues.is_empty() && province.is_some(); + Ok(Output { + normalized, + valid, + issues, + province, + office, + kind, + energy, + }) +} + +#[cfg(test)] +#[path = "lib_test.rs"] +mod tests; diff --git a/market/license-plate/backend/src/lib_test.rs b/market/license-plate/backend/src/lib_test.rs new file mode 100644 index 00000000..8cf4a13a --- /dev/null +++ b/market/license-plate/backend/src/lib_test.rs @@ -0,0 +1,91 @@ +use super::*; +use serde_json::json; + +#[test] +fn parses_standard_plate() { + let out = parse(Args { + plate: "京A·12345".into(), + }) + .unwrap(); + assert!(out.valid); + assert_eq!(out.normalized, "京A12345"); + assert_eq!(out.province, Some("北京")); + assert_eq!(out.office, Some('A')); + assert_eq!(out.kind, "standard"); + assert_eq!(out.energy, "none"); +} + +#[test] +fn parses_nev_plate() { + let out = parse(Args { + plate: "沪AD12345".into(), + }) + .unwrap(); + assert!(out.valid); + assert_eq!(out.kind, "nev"); + assert_eq!(out.energy, "electric"); + let out = parse(Args { + plate: "沪AF12345".into(), + }) + .unwrap(); + assert_eq!(out.energy, "hybrid"); +} + +#[test] +fn lowercase_and_separators_are_normalized() { + let out = parse(Args { + plate: "粤b.d1234".into(), + }) + .unwrap(); + assert_eq!(out.normalized, "粤BD1234"); + assert!(out.valid); +} + +#[test] +fn reports_provinces_issues_and_forbidden_letters() { + let out = parse(Args { + plate: "Z A12345".into(), + }) + .unwrap(); + assert!(!out.valid); + assert!(out.issues.contains(&"province".to_string())); + let out = parse(Args { + plate: "京AI1234".into(), + }) + .unwrap(); + assert!(!out.valid, "I is forbidden"); + assert!(out.issues.contains(&"charset".to_string())); + let out = parse(Args { + plate: "京A12".into(), + }) + .unwrap(); + assert!(out.issues.contains(&"format".to_string())); +} + +#[test] +fn rejects_empty() { + let err = parse(Args { plate: " ".into() }).unwrap_err(); + assert_eq!(err.code, "plate.empty"); +} + +#[test] +fn dispatches_via_plugin() { + let out = LicensePlate::default() + .call("parse", json!({"plate": "京A12345"})) + .unwrap(); + assert_eq!(out["valid"], true); + assert_eq!( + LicensePlate::default() + .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(&LicensePlate::default()).unwrap(); + assert_eq!(checked, 1); +} diff --git a/market/license-plate/icon.svg b/market/license-plate/icon.svg new file mode 100644 index 00000000..258be13f --- /dev/null +++ b/market/license-plate/icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/market/license-plate/locales/en-US.json b/market/license-plate/locales/en-US.json new file mode 100644 index 00000000..baf96140 --- /dev/null +++ b/market/license-plate/locales/en-US.json @@ -0,0 +1,72 @@ +{ + "name": "License Plate Parser", + "description": "Parse Chinese license plates: province, issuing office, energy type, plate kind and charset validation.", + "api": { + "parse": { + "summary": "Parse a Chinese license plate", + "plate": "Plate text (case and separators tolerated)" + } + }, + "issues": { + "province": "Invalid province abbreviation", + "format": "Length is not 7/8", + "office": "Invalid issuing letter (I/O banned)", + "charset": "Serial contains banned I/O or invalid chars" + }, + "kinds": { + "standard": "Standard", + "nev": "New energy", + "large": "Large vehicle", + "large_nev": "Large NEV", + "police": "Police", + "emergency": "Emergency", + "unknown": "Unknown" + }, + "energy": { + "none": "Conventional", + "electric": "Battery electric", + "hybrid": "Plug-in hybrid", + "unknown": "Unknown" + }, + "provinces": { + "京": "Beijing", + "津": "Tianjin", + "沪": "Shanghai", + "渝": "Chongqing", + "冀": "Hebei", + "豫": "Henan", + "云": "Yunnan", + "辽": "Liaoning", + "黑": "Heilongjiang", + "湘": "Hunan", + "皖": "Anhui", + "鲁": "Shandong", + "新": "Xinjiang", + "苏": "Jiangsu", + "浙": "Zhejiang", + "赣": "Jiangxi", + "鄂": "Hubei", + "桂": "Guangxi", + "甘": "Gansu", + "晋": "Shanxi", + "蒙": "Inner Mongolia", + "陕": "Shaanxi", + "吉": "Jilin", + "闽": "Fujian", + "贵": "Guizhou", + "粤": "Guangdong", + "青": "Qinghai", + "藏": "Tibet", + "川": "Sichuan", + "宁": "Ningxia", + "琼": "Hainan" + }, + "errors": { + "plate.empty": "Enter a plate number" + }, + "ui": { + "delete": "Delete", + "copy": "Copy", + "input": "Log text" + } +} diff --git a/market/license-plate/locales/zh-CN.json b/market/license-plate/locales/zh-CN.json new file mode 100644 index 00000000..ca886024 --- /dev/null +++ b/market/license-plate/locales/zh-CN.json @@ -0,0 +1,72 @@ +{ + "name": "车牌信息解析", + "description": "解析中国车牌号:省份简称、发牌机关、能源类型与号牌类型判定、字符合法性校验。", + "api": { + "parse": { + "summary": "解析中国车牌号", + "plate": "车牌号(容忍大小写与点号分隔)" + } + }, + "issues": { + "province": "省份简称无效", + "format": "车牌长度不符合 7/8 位", + "office": "发牌机关字母无效(I/O 禁用)", + "charset": "序号含禁用字母 I/O 或非法字符" + }, + "kinds": { + "standard": "普通牌", + "nev": "新能源牌", + "large": "大型车", + "large_nev": "大型新能源", + "police": "警用", + "emergency": "应急", + "unknown": "未知" + }, + "energy": { + "none": "普通能源", + "electric": "纯电动", + "hybrid": "插电混动", + "unknown": "未知" + }, + "provinces": { + "京": "北京", + "津": "天津", + "沪": "上海", + "渝": "重庆", + "冀": "河北", + "豫": "河南", + "云": "云南", + "辽": "辽宁", + "黑": "黑龙江", + "湘": "湖南", + "皖": "安徽", + "鲁": "山东", + "新": "新疆", + "苏": "江苏", + "浙": "浙江", + "赣": "江西", + "鄂": "湖北", + "桂": "广西", + "甘": "甘肃", + "晋": "山西", + "蒙": "内蒙古", + "陕": "陕西", + "吉": "吉林", + "闽": "福建", + "贵": "贵州", + "粤": "广东", + "青": "青海", + "藏": "西藏", + "川": "四川", + "宁": "宁夏", + "琼": "海南" + }, + "errors": { + "plate.empty": "请输入车牌号" + }, + "ui": { + "delete": "删除", + "copy": "复制", + "input": "日志文本" + } +} diff --git a/market/license-plate/manifest.json b/market/license-plate/manifest.json new file mode 100644 index 00000000..ee19abf4 --- /dev/null +++ b/market/license-plate/manifest.json @@ -0,0 +1,51 @@ +{ + "id": "org.devlive.toolforge.license-plate", + "version": "0.1.0", + "name": "i18n:name", + "description": "i18n:description", + "category": "dev", + "keywords": [ + "license plate", + "车牌", + "新能源", + "解析" + ], + "accent": "blue", + "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": [ + "plate" + ], + "properties": { + "plate": { + "type": "string", + "description": "i18n:api.parse.plate", + "x-positional": 0 + } + } + }, + "examples": [ + "tfp-license-plate parse 京A12345", + "tfp-license-plate parse 沪AD12345" + ] + } + } + }, + "sensitive": false +} diff --git a/market/license-plate/ui/package.json b/market/license-plate/ui/package.json new file mode 100644 index 00000000..fb34813a --- /dev/null +++ b/market/license-plate/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/license-plate" +} diff --git a/market/license-plate/ui/src/index.tsx b/market/license-plate/ui/src/index.tsx new file mode 100644 index 00000000..cc1ce0ec --- /dev/null +++ b/market/license-plate/ui/src/index.tsx @@ -0,0 +1,49 @@ +import { useState } from 'react' +import { Badge, Input, Panel, Spinner } from '@toolforge/ui' +import { useDebouncedCall, usePlugin } from '@toolforge/plugin-ui-sdk' +import { Car } from 'lucide-react' + +interface ParseOut { + normalized: string + valid: boolean + issues: string[] + province: string | null + office: string | null + kind: string + energy: string +} + +export default function LicensePlate() { + const { t, errorMessage } = usePlugin() + const [plate, setPlate] = useState('京A·12345') // tf-allow: 默认值 + const parse = useDebouncedCall(plate.trim() ? 'parse' : null, { plate }, [plate]) + + return ( + } title={t('api.parse.summary')} className="min-h-0" bodyClassName="space-y-2.5 p-3" extra={parse.pending && }> + setPlate(event.target.value)} placeholder={t('api.parse.plate')} aria-label={t('api.parse.plate')} /> + {parse.error ? ( +

      {errorMessage(parse.error)}

      + ) : ( + parse.result && ( + <> +

      {parse.result.normalized}

      + + {parse.result.valid ? t('valid') : t('invalid')} + +
      +

      {t('province')}: {parse.result.province ?? '—'}

      +

      {t('office')}: {parse.result.office ?? '—'}

      +

      {t('kind')}: {t(`kinds.${parse.result.kind}`)}

      +

      {t('energy')}: {t(`energy.${parse.result.energy}`)}

      +
      + {parse.result.issues.length > 0 && ( +
      + {parse.result.issues.map((issue) =>

      {t(`issues.${issue}`)}

      )} +
      + )} + + ) + )} +
      + ) +} diff --git a/market/license-plate/ui/tsconfig.json b/market/license-plate/ui/tsconfig.json new file mode 100644 index 00000000..625277c6 --- /dev/null +++ b/market/license-plate/ui/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../../tsconfig.base.json", + "include": ["src"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b9495dbe..d370bc5a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -150,6 +150,37 @@ importers: specifier: 8.3.0 version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/avro-inspector/ui: + dependencies: + '@toolforge/plugin-ui-sdk': + specifier: workspace:* + version: link:../../../packages/plugin-ui-sdk + '@toolforge/ui': + specifier: workspace:* + version: link:../../../packages/ui + lucide-react: + specifier: 1.47.0 + version: 1.47.0(react@19.3.0) + react-i18next: + specifier: 17.0.15 + version: 17.0.15(i18next@26.4.2(typescript@5.9.3))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(typescript@5.9.3) + devDependencies: + '@types/react': + specifier: 19.3.0 + version: 19.3.0 + react: + specifier: 19.3.0 + version: 19.3.0 + tailwindcss: + specifier: 4.3.3 + version: 4.3.3 + typescript: + specifier: 5.9.3 + version: 5.9.3 + vite: + specifier: 8.3.0 + version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/base-converter/ui: dependencies: '@toolforge/plugin-ui-sdk': @@ -649,6 +680,37 @@ importers: specifier: 8.3.0 version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/dep-graph/ui: + dependencies: + '@toolforge/plugin-ui-sdk': + specifier: workspace:* + version: link:../../../packages/plugin-ui-sdk + '@toolforge/ui': + specifier: workspace:* + version: link:../../../packages/ui + lucide-react: + specifier: 1.47.0 + version: 1.47.0(react@19.3.0) + react-i18next: + specifier: 17.0.15 + version: 17.0.15(i18next@26.4.2(typescript@5.9.3))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(typescript@5.9.3) + devDependencies: + '@types/react': + specifier: 19.3.0 + version: 19.3.0 + react: + specifier: 19.3.0 + version: 19.3.0 + tailwindcss: + specifier: 4.3.3 + version: 4.3.3 + typescript: + specifier: 5.9.3 + version: 5.9.3 + vite: + specifier: 8.3.0 + version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/dev-directory/ui: dependencies: '@toolforge/plugin-ui-sdk': @@ -1458,6 +1520,37 @@ importers: specifier: 8.3.0 version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/icu-lint/ui: + dependencies: + '@toolforge/plugin-ui-sdk': + specifier: workspace:* + version: link:../../../packages/plugin-ui-sdk + '@toolforge/ui': + specifier: workspace:* + version: link:../../../packages/ui + lucide-react: + specifier: 1.47.0 + version: 1.47.0(react@19.3.0) + react-i18next: + specifier: 17.0.15 + version: 17.0.15(i18next@26.4.2(typescript@5.9.3))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(typescript@5.9.3) + devDependencies: + '@types/react': + specifier: 19.3.0 + version: 19.3.0 + react: + specifier: 19.3.0 + version: 19.3.0 + tailwindcss: + specifier: 4.3.3 + version: 4.3.3 + typescript: + specifier: 5.9.3 + version: 5.9.3 + vite: + specifier: 8.3.0 + version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/image-converter/ui: dependencies: '@toolforge/plugin-ui-sdk': @@ -1861,6 +1954,37 @@ importers: specifier: 8.3.0 version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/keyword-density/ui: + dependencies: + '@toolforge/plugin-ui-sdk': + specifier: workspace:* + version: link:../../../packages/plugin-ui-sdk + '@toolforge/ui': + specifier: workspace:* + version: link:../../../packages/ui + lucide-react: + specifier: 1.47.0 + version: 1.47.0(react@19.3.0) + react-i18next: + specifier: 17.0.15 + version: 17.0.15(i18next@26.4.2(typescript@5.9.3))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(typescript@5.9.3) + devDependencies: + '@types/react': + specifier: 19.3.0 + version: 19.3.0 + react: + specifier: 19.3.0 + version: 19.3.0 + tailwindcss: + specifier: 4.3.3 + version: 4.3.3 + typescript: + specifier: 5.9.3 + version: 5.9.3 + vite: + specifier: 8.3.0 + version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/kinship-calculator/ui: dependencies: '@toolforge/plugin-ui-sdk': @@ -1954,6 +2078,37 @@ importers: specifier: 8.3.0 version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/license-plate/ui: + dependencies: + '@toolforge/plugin-ui-sdk': + specifier: workspace:* + version: link:../../../packages/plugin-ui-sdk + '@toolforge/ui': + specifier: workspace:* + version: link:../../../packages/ui + lucide-react: + specifier: 1.47.0 + version: 1.47.0(react@19.3.0) + react-i18next: + specifier: 17.0.15 + version: 17.0.15(i18next@26.4.2(typescript@5.9.3))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(typescript@5.9.3) + devDependencies: + '@types/react': + specifier: 19.3.0 + version: 19.3.0 + react: + specifier: 19.3.0 + version: 19.3.0 + tailwindcss: + specifier: 4.3.3 + version: 4.3.3 + typescript: + specifier: 5.9.3 + version: 5.9.3 + vite: + specifier: 8.3.0 + version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/log-viewer/ui: dependencies: '@tanstack/react-virtual': @@ -2236,6 +2391,68 @@ importers: specifier: 8.3.0 version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/nginx-config-generator/ui: + dependencies: + '@toolforge/plugin-ui-sdk': + specifier: workspace:* + version: link:../../../packages/plugin-ui-sdk + '@toolforge/ui': + specifier: workspace:* + version: link:../../../packages/ui + lucide-react: + specifier: 1.47.0 + version: 1.47.0(react@19.3.0) + react-i18next: + specifier: 17.0.15 + version: 17.0.15(i18next@26.4.2(typescript@5.9.3))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(typescript@5.9.3) + devDependencies: + '@types/react': + specifier: 19.3.0 + version: 19.3.0 + react: + specifier: 19.3.0 + version: 19.3.0 + tailwindcss: + specifier: 4.3.3 + version: 4.3.3 + typescript: + specifier: 5.9.3 + version: 5.9.3 + vite: + specifier: 8.3.0 + version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + + market/nginx-log-analyzer/ui: + dependencies: + '@toolforge/plugin-ui-sdk': + specifier: workspace:* + version: link:../../../packages/plugin-ui-sdk + '@toolforge/ui': + specifier: workspace:* + version: link:../../../packages/ui + lucide-react: + specifier: 1.47.0 + version: 1.47.0(react@19.3.0) + react-i18next: + specifier: 17.0.15 + version: 17.0.15(i18next@26.4.2(typescript@5.9.3))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(typescript@5.9.3) + devDependencies: + '@types/react': + specifier: 19.3.0 + version: 19.3.0 + react: + specifier: 19.3.0 + version: 19.3.0 + tailwindcss: + specifier: 4.3.3 + version: 4.3.3 + typescript: + specifier: 5.9.3 + version: 5.9.3 + vite: + specifier: 8.3.0 + version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/nonogram/ui: dependencies: '@toolforge/plugin-ui-sdk': @@ -2980,6 +3197,37 @@ importers: specifier: 8.3.0 version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/rewrite-converter/ui: + dependencies: + '@toolforge/plugin-ui-sdk': + specifier: workspace:* + version: link:../../../packages/plugin-ui-sdk + '@toolforge/ui': + specifier: workspace:* + version: link:../../../packages/ui + lucide-react: + specifier: 1.47.0 + version: 1.47.0(react@19.3.0) + react-i18next: + specifier: 17.0.15 + version: 17.0.15(i18next@26.4.2(typescript@5.9.3))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(typescript@5.9.3) + devDependencies: + '@types/react': + specifier: 19.3.0 + version: 19.3.0 + react: + specifier: 19.3.0 + version: 19.3.0 + tailwindcss: + specifier: 4.3.3 + version: 4.3.3 + typescript: + specifier: 5.9.3 + version: 5.9.3 + vite: + specifier: 8.3.0 + version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/robots-sitemap/ui: dependencies: '@toolforge/plugin-ui-sdk': @@ -3135,6 +3383,37 @@ importers: specifier: 8.3.0 version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/seo-auditor/ui: + dependencies: + '@toolforge/plugin-ui-sdk': + specifier: workspace:* + version: link:../../../packages/plugin-ui-sdk + '@toolforge/ui': + specifier: workspace:* + version: link:../../../packages/ui + lucide-react: + specifier: 1.47.0 + version: 1.47.0(react@19.3.0) + react-i18next: + specifier: 17.0.15 + version: 17.0.15(i18next@26.4.2(typescript@5.9.3))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(typescript@5.9.3) + devDependencies: + '@types/react': + specifier: 19.3.0 + version: 19.3.0 + react: + specifier: 19.3.0 + version: 19.3.0 + tailwindcss: + specifier: 4.3.3 + version: 4.3.3 + typescript: + specifier: 5.9.3 + version: 5.9.3 + vite: + specifier: 8.3.0 + version: 8.3.0(@types/node@24.13.6)(jiti@2.7.0) + market/shortcut-cheatsheet/ui: dependencies: '@toolforge/plugin-ui-sdk': From f3f2e865096b67ed0097f91941f4bae606684889 Mon Sep 17 00:00:00 2001 From: qianmoQ Date: Wed, 4 Nov 2026 12:48:06 -0500 Subject: [PATCH 06/61] feat(nginx-log-analyzer): combined log stats and slow requests New market plugin: parse nginx combined-format logs with an optional trailing request_time, aggregate status code classes, top IPs/URLs/user agents, per-minute request counts, slow requests above a configurable threshold and total bytes, skipping unparsable lines with a counter. Closes #272 --- market/nginx-log-analyzer/backend/Cargo.toml | 16 ++ market/nginx-log-analyzer/backend/src/lib.rs | 233 ++++++++++++++++++ .../backend/src/lib_test.rs | 89 +++++++ market/nginx-log-analyzer/icon.svg | 5 + market/nginx-log-analyzer/locales/en-US.json | 46 ++++ market/nginx-log-analyzer/locales/zh-CN.json | 46 ++++ market/nginx-log-analyzer/manifest.json | 58 +++++ market/nginx-log-analyzer/ui/package.json | 28 +++ market/nginx-log-analyzer/ui/src/index.tsx | 90 +++++++ market/nginx-log-analyzer/ui/tsconfig.json | 4 + 10 files changed, 615 insertions(+) create mode 100644 market/nginx-log-analyzer/backend/Cargo.toml create mode 100644 market/nginx-log-analyzer/backend/src/lib.rs create mode 100644 market/nginx-log-analyzer/backend/src/lib_test.rs create mode 100644 market/nginx-log-analyzer/icon.svg create mode 100644 market/nginx-log-analyzer/locales/en-US.json create mode 100644 market/nginx-log-analyzer/locales/zh-CN.json create mode 100644 market/nginx-log-analyzer/manifest.json create mode 100644 market/nginx-log-analyzer/ui/package.json create mode 100644 market/nginx-log-analyzer/ui/src/index.tsx create mode 100644 market/nginx-log-analyzer/ui/tsconfig.json diff --git a/market/nginx-log-analyzer/backend/Cargo.toml b/market/nginx-log-analyzer/backend/Cargo.toml new file mode 100644 index 00000000..8bf63e71 --- /dev/null +++ b/market/nginx-log-analyzer/backend/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "tfm-nginx-log-analyzer" +description = "ToolForge market plugin: nginx log analyzer" +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/nginx-log-analyzer/backend/src/lib.rs b/market/nginx-log-analyzer/backend/src/lib.rs new file mode 100644 index 00000000..bca7773e --- /dev/null +++ b/market/nginx-log-analyzer/backend/src/lib.rs @@ -0,0 +1,233 @@ +//! Nginx combined 日志分析后端:状态码分布、Top IP/URL/UA、按分钟 QPS、 +//! 慢请求清单(request_time ≥ 阈值)。 + +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 NginxLogAnalyzer { + manifest: Manifest, +} + +impl Default for NginxLogAnalyzer { + fn default() -> Self { + Self { + manifest: Manifest::from_static(MANIFEST), + } + } +} + +impl ToolPlugin for NginxLogAnalyzer { + fn manifest(&self) -> &Manifest { + &self.manifest + } + + fn call(&self, function: &str, args: Value) -> PluginResult { + match function { + "analyze" => to_value(analyze(parse_args(args)?)?), + other => Err(unknown_function(other)), + } + } +} + +tf_plugin_guest::export_plugin!(NginxLogAnalyzer); + +const MAX_LINES: usize = 100_000; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Args { + /// 日志文本(combined 格式,每行一条) + pub log: String, + /// 慢请求阈值秒(默认 1.0) + #[serde(default)] + pub slow_seconds: Option, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TopEntry { + pub key: String, + pub count: u64, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Minute { + pub minute: String, + pub requests: u64, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SlowEntry { + pub line: usize, + pub ip: String, + pub url: String, + pub status: u16, + pub request_time: f64, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Output { + pub parsed: usize, + pub skipped: usize, + pub status_counts: Vec, + pub top_ips: Vec, + pub top_urls: Vec, + pub top_uas: Vec, + pub per_minute: Vec, + pub slow_requests: Vec, + pub total_bytes: u64, + /// 2xx/3xx/4xx/5xx 计数 + pub status_classes: Vec, +} + +/// combined: $remote_addr - $remote_user [$time] "$request" $status $bytes "$referer" "$ua" +/// request_time 可能附加在行尾($request_time $upstream_time) +fn parse_line(line: &str) -> Option<(String, String, u16, u64, String, Option)> { + let rest = line.trim(); + let ip_end = rest.find(' ')?; + let ip = rest[..ip_end].to_owned(); + let rest = rest[ip_end + 1..].trim_start(); + // "- user [" 或 "- [" + let bracket = rest.find('[')?; + let rest = &rest[bracket + 1..]; + let time_end = rest.find(']')?; + let time = rest[..time_end].to_owned(); + let rest = rest[time_end + 1..].trim_start(); + let quote = rest.strip_prefix('"')?; + let req_end = quote.find("\" ")?; + let request = quote[..req_end].to_owned(); + let rest = "e[req_end + 2..]; + let mut fields = rest.split(' '); + let status: u16 = fields.next()?.parse().ok()?; + let bytes: u64 = match fields.next()? { + "-" => 0, + n => n.parse().ok()?, + }; + // 剩余部分里找可选的 request_time(最后一个数字字段) + let request_time = rest + .rsplit(' ') + .next() + .and_then(|t| t.trim().parse::().ok()) + .filter(|v| *v > 0.0 && *v < 3600.0); + let url = request.split(' ').nth(1).unwrap_or("-").to_owned(); + Some((ip, url, status, bytes, time, request_time)) +} + +pub fn analyze(args: Args) -> PluginResult { + if args.log.trim().is_empty() { + return Err(PluginError::new("nginxlog.empty")); + } + if args.log.len() > 16 * 1024 * 1024 { + return Err(PluginError::new("nginxlog.too_large").with("max", 16 * 1024 * 1024)); + } + let slow_threshold = args.slow_seconds.unwrap_or(1.0); + let mut parsed = 0usize; + let mut skipped = 0usize; + let mut status_counts: std::collections::HashMap = + std::collections::HashMap::new(); + let mut ips: std::collections::HashMap = std::collections::HashMap::new(); + let mut urls: std::collections::HashMap = std::collections::HashMap::new(); + let mut uas: std::collections::HashMap = std::collections::HashMap::new(); + let mut minutes: std::collections::HashMap = std::collections::HashMap::new(); + let mut slow = Vec::new(); + let mut total_bytes = 0u64; + for (index, line) in args.log.lines().enumerate() { + if line.trim().is_empty() { + continue; + } + let Some((ip, url, status, bytes, time, request_time)) = parse_line(line) else { + skipped += 1; + continue; + }; + parsed += 1; + if parsed > MAX_LINES { + break; + } + total_bytes += bytes; + *status_counts.entry(status.to_string()).or_insert(0) += 1; + *ips.entry(ip.clone()).or_insert(0) += 1; + *urls.entry(url.clone()).or_insert(0) += 1; + // UA:combined 的最后引号段("referer" "ua") + if let Some(ua_open) = line.rfind("\"") { + let before = &line[..ua_open]; + if let Some(referer_close) = before.rfind('"') { + let ua = line[referer_close + 1..ua_open].to_owned(); + *uas.entry(ua).or_insert(0) += 1; + } + } + // 分钟粒度:[10/Oct/2026:12:34:56 +0800] → 10/Oct/2026:12:34 + if let Some(colon) = time.find(':') { + let date = &time[..colon]; + if let Some(h_start) = time[colon + 1..].find(':') { + let hour = &time[colon + 1..colon + 1 + h_start]; + let rest = &time[colon + 1 + h_start + 1..]; + let minute = rest.split(':').next().unwrap_or(""); + *minutes + .entry(format!("{date}:{hour}:{minute}")) + .or_insert(0) += 1; + } + } + if let Some(rt) = request_time + && rt >= slow_threshold + { + slow.push(SlowEntry { + line: index + 1, + ip, + url, + status, + request_time: rt, + }); + } + } + let top = |map: &std::collections::HashMap| -> Vec { + let mut entries: Vec = map + .iter() + .map(|(k, c)| TopEntry { + key: k.clone(), + count: *c, + }) + .collect(); + entries.sort_by(|a, b| b.count.cmp(&a.count).then(a.key.cmp(&b.key))); + entries.truncate(10); + entries + }; + let mut status_classes: std::collections::HashMap = + std::collections::HashMap::new(); + for (status, count) in &status_counts { + let class = status + .chars() + .next() + .map(|c| format!("{}xx", c)) + .unwrap_or_default(); + *status_classes.entry(class).or_insert(0) += count; + } + let mut per_minute: Vec = minutes + .into_iter() + .map(|(minute, requests)| Minute { minute, requests }) + .collect(); + per_minute.sort_by(|a, b| a.minute.cmp(&b.minute)); + Ok(Output { + parsed, + skipped, + status_counts: top(&status_counts), + top_ips: top(&ips), + top_urls: top(&urls), + top_uas: top(&uas), + per_minute, + slow_requests: slow, + total_bytes, + status_classes: top(&status_classes), + }) +} + +#[cfg(test)] +#[path = "lib_test.rs"] +mod tests; diff --git a/market/nginx-log-analyzer/backend/src/lib_test.rs b/market/nginx-log-analyzer/backend/src/lib_test.rs new file mode 100644 index 00000000..287eca84 --- /dev/null +++ b/market/nginx-log-analyzer/backend/src/lib_test.rs @@ -0,0 +1,89 @@ +use super::*; +use serde_json::json; + +const LOG: &str = "\ +10.0.0.1 - - [10/Oct/2026:12:34:01 +0800] \"GET /index.html HTTP/1.1\" 200 1234 \"-\" \"Mozilla/5.0\" 0.05 +10.0.0.2 - - [10/Oct/2026:12:34:05 +0800] \"GET /api/data HTTP/1.1\" 404 56 \"-\" \"curl/8.0\" 0.02 +10.0.0.1 - - [10/Oct/2026:12:35:10 +0800] \"POST /api/submit HTTP/1.1\" 500 78 \"-\" \"Mozilla/5.0\" 2.50 +bad line without format +"; + +fn analyze_sample() -> Output { + analyze(Args { + log: LOG.into(), + slow_seconds: Some(1.0), + }) + .unwrap() +} + +#[test] +fn parses_lines_and_skips_bad() { + let out = analyze_sample(); + assert_eq!(out.parsed, 3); + assert_eq!(out.skipped, 1); +} + +#[test] +fn aggregates_status_and_tops() { + let out = analyze_sample(); + let status = out.status_counts.iter().find(|e| e.key == "200").unwrap(); + assert_eq!(status.count, 1); + let class5 = out.status_classes.iter().find(|e| e.key == "5xx").unwrap(); + assert_eq!(class5.count, 1); + let ip = out.top_ips.iter().find(|e| e.key == "10.0.0.1").unwrap(); + assert_eq!(ip.count, 2); + let ua = out + .top_uas + .iter() + .find(|e| e.key.contains("Mozilla")) + .unwrap(); + assert_eq!(ua.count, 2); +} + +#[test] +fn per_minute_series_sorted() { + let out = analyze_sample(); + assert_eq!(out.per_minute.len(), 2); + assert_eq!(out.per_minute[0].minute, "10/Oct/2026:12:34"); + assert_eq!(out.per_minute[0].requests, 2); +} + +#[test] +fn slow_requests_above_threshold() { + let out = analyze_sample(); + assert_eq!(out.slow_requests.len(), 1); + assert_eq!(out.slow_requests[0].request_time, 2.5); + assert_eq!(out.slow_requests[0].url, "/api/submit"); +} + +#[test] +fn validates_input() { + let err = analyze(Args { + log: " \n".into(), + slow_seconds: None, + }) + .unwrap_err(); + assert_eq!(err.code, "nginxlog.empty"); +} + +#[test] +fn dispatches_via_plugin() { + let out = NginxLogAnalyzer::default() + .call("analyze", json!({"log": LOG})) + .unwrap(); + assert_eq!(out["parsed"], 3); + assert_eq!( + NginxLogAnalyzer::default() + .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(&NginxLogAnalyzer::default()).unwrap(); + assert_eq!(checked, 1); +} diff --git a/market/nginx-log-analyzer/icon.svg b/market/nginx-log-analyzer/icon.svg new file mode 100644 index 00000000..6f3eba46 --- /dev/null +++ b/market/nginx-log-analyzer/icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/market/nginx-log-analyzer/locales/en-US.json b/market/nginx-log-analyzer/locales/en-US.json new file mode 100644 index 00000000..fb7dc0f2 --- /dev/null +++ b/market/nginx-log-analyzer/locales/en-US.json @@ -0,0 +1,46 @@ +{ + "name": "Nginx Log Analyzer", + "description": "Parse nginx combined logs: status distribution, top IPs/URLs/UAs, per-minute QPS and slow requests.", + "api": { + "analyze": { + "summary": "Parse nginx combined logs and aggregate", + "log": "Log text", + "slowSeconds": "Slow request threshold seconds (default 1.0)" + } + }, + "table": { + "key": "Name", + "count": "Count" + }, + "sections": { + "status": "Status codes", + "ips": "Top IPs", + "urls": "Top URLs", + "uas": "Top UAs", + "slow": "Slow requests", + "classes": "Status classes", + "perMinute": "Requests per minute" + }, + "slow": { + "line": "Line", + "time": "{{value}}s", + "entry": "line {{line}}: {{url}} ({{time}}s)" + }, + "errors": { + "nginxlog.empty": "Log is empty", + "nginxlog.too_large": "Log over 16MB" + }, + "ui": { + "parsed": "{{count}} lines parsed", + "skipped": "{{count}} skipped", + "valid": "Valid", + "invalid": "Invalid", + "province": "Province", + "office": "Office", + "kind": "Kind", + "energy": "Energy", + "input": "Log text", + "delete": "Delete", + "copy": "Copy" + } +} diff --git a/market/nginx-log-analyzer/locales/zh-CN.json b/market/nginx-log-analyzer/locales/zh-CN.json new file mode 100644 index 00000000..592d72ac --- /dev/null +++ b/market/nginx-log-analyzer/locales/zh-CN.json @@ -0,0 +1,46 @@ +{ + "name": "Nginx 日志分析器", + "description": "解析 nginx combined 日志:状态码分布、Top IP/URL/UA、按分钟 QPS 与慢请求清单。", + "api": { + "analyze": { + "summary": "解析 nginx combined 日志并聚合统计", + "log": "日志文本", + "slowSeconds": "慢请求阈值秒(默认 1.0)" + } + }, + "table": { + "key": "名称", + "count": "次数" + }, + "sections": { + "status": "状态码分布", + "ips": "Top IP", + "urls": "Top URL", + "uas": "Top UA", + "slow": "慢请求", + "classes": "状态分类", + "perMinute": "按分钟请求" + }, + "slow": { + "line": "行号", + "time": "耗时 {{value}}s", + "entry": "行 {{line}}:{{url}}({{time}}s)" + }, + "errors": { + "nginxlog.empty": "日志为空", + "nginxlog.too_large": "日志超过 16MB" + }, + "ui": { + "parsed": "解析 {{count}} 行", + "skipped": "跳过 {{count}} 行", + "valid": "有效", + "invalid": "无效", + "province": "省份", + "office": "发牌机关", + "kind": "类型", + "energy": "能源", + "input": "日志文本", + "delete": "删除", + "copy": "复制" + } +} diff --git a/market/nginx-log-analyzer/manifest.json b/market/nginx-log-analyzer/manifest.json new file mode 100644 index 00000000..bf36f151 --- /dev/null +++ b/market/nginx-log-analyzer/manifest.json @@ -0,0 +1,58 @@ +{ + "id": "org.devlive.toolforge.nginx-log-analyzer", + "version": "0.1.0", + "name": "i18n:name", + "description": "i18n:description", + "category": "dev", + "keywords": [ + "nginx", + "log", + "access", + "日志", + "分析" + ], + "accent": "green", + "locales": [ + "zh-CN", + "en-US" + ], + "minAppVersion": "0.2.0", + "permissions": [ + "fs:user-selected" + ], + "functions": { + "analyze": { + "history": true, + "interface": { + "expose": [ + "cli", + "agent" + ], + "summary": "i18n:api.analyze.summary", + "effect": "read", + "params": { + "type": "object", + "required": [ + "log" + ], + "properties": { + "log": { + "type": "string", + "description": "i18n:api.analyze.log", + "x-stdin": true, + "x-positional": 0 + }, + "slowSeconds": { + "type": "number", + "description": "i18n:api.analyze.slowSeconds" + } + } + }, + "examples": [ + "cat access.log | tfp-nginx-log-analyzer analyze --slowSeconds 2" + ] + } + } + }, + "sensitive": false +} diff --git a/market/nginx-log-analyzer/ui/package.json b/market/nginx-log-analyzer/ui/package.json new file mode 100644 index 00000000..77d92bb6 --- /dev/null +++ b/market/nginx-log-analyzer/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/nginx-log-analyzer" +} diff --git a/market/nginx-log-analyzer/ui/src/index.tsx b/market/nginx-log-analyzer/ui/src/index.tsx new file mode 100644 index 00000000..fe037656 --- /dev/null +++ b/market/nginx-log-analyzer/ui/src/index.tsx @@ -0,0 +1,90 @@ +import { useState } from 'react' +import { Badge, Panel, Spinner } from '@toolforge/ui' +import { useDebouncedCall, usePlugin } from '@toolforge/plugin-ui-sdk' +import { FileSearch } from 'lucide-react' + +interface TopEntry { + key: string + count: number +} +interface ParseOut { + parsed: number + skipped: number + statusCounts: TopEntry[] + topIps: TopEntry[] + topUrls: TopEntry[] + topUas: TopEntry[] + perMinute: { minute: string; requests: number }[] + slowRequests: { line: number; ip: string; url: string; requestTime: number }[] + totalBytes: number + statusClasses: TopEntry[] +} + +const SAMPLE = '10.0.0.1 - - [10/Oct/2026:12:34:01 +0800] "GET /index.html HTTP/1.1" 200 1234 "-" "Mozilla/5.0" 0.05\n' // tf-allow: 示例输入 + +export default function NginxLogAnalyzer() { + const { t, errorMessage } = usePlugin() + const [log, setLog] = useState(SAMPLE) // tf-allow: 默认值 + const [slow, setSlow] = useState(1) // tf-allow: 默认值 + const analyze = useDebouncedCall(log.trim() ? 'analyze' : null, { log, slowSeconds: slow }, [log, slow]) + + return ( +
      + } title={t('ui.input')} bodyClassName="space-y-2 p-3"> +