diff --git a/.github/ci-filters.json b/.github/ci-filters.json index 98a44f501..9de1835cf 100644 --- a/.github/ci-filters.json +++ b/.github/ci-filters.json @@ -1,6 +1,7 @@ { "worker": [ "apps/worker/**", + "packages/api/**", "packages/db/**", ".github/workflows/ci.yml", ".github/ci-filters.json", @@ -10,6 +11,7 @@ ], "server": [ "apps/server/**", + "packages/api/**", "packages/db/**", ".github/workflows/ci.yml", ".github/ci-filters.json", @@ -64,6 +66,7 @@ ], "contracts": [ "docs/testing/fixtures/**", + "packages/api/**", "apps/server/**", "packages/db/**", "apps/collection/lib/collection/**", diff --git a/.github/workflows/api-rewrite.yml b/.github/workflows/api-rewrite.yml new file mode 100644 index 000000000..ed3d569c9 --- /dev/null +++ b/.github/workflows/api-rewrite.yml @@ -0,0 +1,98 @@ +name: API rewrite +on: + pull_request: + paths: + - "apps/api/**" + - "apps/server/**" + - "packages/api/**" + - "packages/db/**" + - "packages/games/**" + - ".github/workflows/api-rewrite.yml" + push: + branches: [main] + paths: + - "apps/api/**" + - "packages/api/**" + - "packages/db/**" + - "packages/games/**" + - ".github/workflows/api-rewrite.yml" +permissions: + contents: read +jobs: + contracts-and-api: + runs-on: ubuntu-latest + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: lovat_test + POSTGRES_PASSWORD: lovat_test + POSTGRES_DB: lovat_test + ports: ["5432:5432"] + options: >- + --health-cmd "pg_isready -U lovat_test" --health-interval 5s --health-timeout 5s --health-retries 10 + redis: + image: redis:7.4 + ports: ["6379:6379"] + options: >- + --health-cmd "redis-cli ping" --health-interval 5s --health-timeout 5s --health-retries 10 + env: + DATABASE_URL: postgresql://lovat_test:lovat_test@127.0.0.1:5432/lovat_test + REDIS_URL: redis://127.0.0.1:6379 + LOVAT_DB_TEST: "1" + LOVAT_REDIS_TEST: "1" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22.20.0 + cache: npm + cache-dependency-path: | + packages/api/package-lock.json + packages/db/package-lock.json + packages/games/package-lock.json + + - run: npm ci + working-directory: packages/db + - run: npm run build + working-directory: packages/db + - run: npm run db:deploy + working-directory: packages/db + - run: npm ci + working-directory: packages/api + - run: npm test && npm run generate:check && npm run lint && npm run format:check + working-directory: packages/api + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.4 + - run: bun install --frozen-lockfile + working-directory: apps/api + - run: npm test && npm run lint && npm run format:check + working-directory: packages/games + - run: bun run test && bun run test:integration && bun run lint && bun run format:check && bun run inventory:check + working-directory: apps/api + + - name: Build legacy Server for local rollback rehearsal + run: npm ci && npm run build + working-directory: apps/server + - name: Rehearse traffic rollback without schema rollback + run: bun run test:rollout + working-directory: apps/api + - name: Build production Bun image + run: docker build -t lovat-api:qualification -f apps/api/Dockerfile . + - name: Smoke test bounded container and graceful shutdown + shell: bash + run: | + set -euo pipefail + trap 'docker logs lovat-api-smoke; docker rm -f lovat-api-smoke' EXIT + docker run --detach --name lovat-api-smoke --network host --memory=512m --cpus=1 \ + --env DATABASE_URL --env REDIS_URL \ + --env AUTH0_ISSUER=https://auth.test.invalid/ \ + --env AUTH0_AUDIENCE=https://api.lovat.app \ + --env REDIS_KEY_PREFIX=lovat:container:${{ github.run_id }}: \ + --env HOST=127.0.0.1 --env PORT=3001 lovat-api:qualification + node apps/api/tools/smoke-container.mjs http://127.0.0.1:3001 + docker stats --no-stream lovat-api-smoke + docker image inspect --format '{{.Size}}' lovat-api:qualification + docker stop --time 20 lovat-api-smoke + test "$(docker inspect --format '{{.State.ExitCode}}' lovat-api-smoke)" = 0 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 13998d252..f7b9f1c05 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -119,6 +119,7 @@ jobs: cache: npm cache-dependency-path: | apps/server/package-lock.json + packages/api/package-lock.json packages/db/package-lock.json - run: npm ci - run: npm run format:check @@ -205,6 +206,8 @@ jobs: bun-version: 1.3.14 - run: npm --prefix ../../packages/db ci --include=dev - run: npm --prefix ../../packages/db run build + - run: npm --prefix ../../packages/api ci --include=dev + - run: npm --prefix ../../packages/api run build - run: bun install --frozen-lockfile --ignore-scripts - run: bun run typecheck - name: Test worker against disposable PostgreSQL diff --git a/.railway/railway.ts b/.railway/railway.ts index 68939107d..0e1d74b2b 100644 --- a/.railway/railway.ts +++ b/.railway/railway.ts @@ -96,7 +96,12 @@ export default defineRailway((ctx) => { ...(!production ? { nixpacksPlan: { repo: "MangoSwirl/lovat-server" } } : {}), - watchPatterns: ["/apps/server/**", "/packages/db/**", "/.railway/**"], + watchPatterns: [ + "/apps/server/**", + "/packages/api/**", + "/packages/db/**", + "/.railway/**", + ], }, deploy: { runtime: "V2", @@ -163,7 +168,12 @@ export default defineRailway((ctx) => { build: { builder: "DOCKERFILE", dockerfilePath: "apps/worker/Dockerfile", - watchPatterns: ["/apps/worker/**", "/packages/db/**", "/.railway/**"], + watchPatterns: [ + "/apps/worker/**", + "/packages/api/**", + "/packages/db/**", + "/.railway/**", + ], }, deploy: { runtime: "V2", diff --git a/apps/api/.env.example b/apps/api/.env.example new file mode 100644 index 000000000..e43f60bae --- /dev/null +++ b/apps/api/.env.example @@ -0,0 +1,16 @@ +DATABASE_URL=postgresql://lovat_test:lovat_test@127.0.0.1:5432/lovat_test +AUTH0_ISSUER=https://your-tenant.auth0.com/ +AUTH0_AUDIENCE=https://api.lovat.app +PORT=3001 +CORS_ALLOWED_ORIGINS=http://localhost:8080 + +REDIS_URL=redis://127.0.0.1:6379 +REDIS_KEY_PREFIX=lovat:rewrite: +BASE_URL=http://localhost:3001 +LOVAT_WEBSITE=https://lovat.app +# Optional external integrations; use private local values when exercising them. +# TBA_KEY= +# LOVAT_SIGNING_KEY= +# SLACK_SIGNING_SECRET= +# SLACK_CLIENT_ID= +# SLACK_CLIENT_SECRET= diff --git a/apps/api/.prettierignore b/apps/api/.prettierignore new file mode 100644 index 000000000..8e6da5133 --- /dev/null +++ b/apps/api/.prettierignore @@ -0,0 +1,3 @@ +dist/ +node_modules/ +legacy-routes.json diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md new file mode 100644 index 000000000..6e63d2ce0 --- /dev/null +++ b/apps/api/AGENTS.md @@ -0,0 +1,7 @@ +# Replacement API + +- This is the independent replacement for apps/server. Never import legacy handlers across application boundaries. +- Consume public schemas from @lovat/api and database models from @lovat/db. +- Run bun run build, bun test ./test/*.test.mjs, bun run lint, bun run format:check, and bun run inventory:check. Use Bun 1.4.4 and Hono; preserve the app Bun lockfile. +- Keep analysis data access behind the scoped repository; preserve training, reliability, source-team, tournament, and season restrictions. +- Treat v3 metric semantics as versioned. Add fixtures and document intentional differences from legacy outputs. diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile new file mode 100644 index 000000000..fc6bb554a --- /dev/null +++ b/apps/api/Dockerfile @@ -0,0 +1,28 @@ +# Build from repository root; production traffic stays on apps/server until cutover. +FROM oven/bun:1.4.4 AS bun +FROM node:22.20.0-bookworm-slim AS build +COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun +RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates && rm -rf /var/lib/apt/lists/* +WORKDIR /app +COPY packages/api ./packages/api +COPY packages/games ./packages/games +COPY packages/db ./packages/db +COPY apps/api ./apps/api +# Shared packages retain their independent npm lockfiles. +RUN npm --prefix packages/api ci --ignore-scripts && npm --prefix packages/api run build +RUN npm --prefix packages/games ci --ignore-scripts && npm --prefix packages/games run build +RUN npm --prefix packages/db ci --include=dev && npm --prefix packages/db run build +WORKDIR /app/apps/api +RUN bun install --frozen-lockfile --ignore-scripts && bun run build +# Remove compilers, Prisma tooling and test dependencies from the runtime image. +RUN npm --prefix /app/packages/api prune --omit=dev --ignore-scripts && npm --prefix /app/packages/games prune --omit=dev --ignore-scripts && npm --prefix /app/packages/db prune --omit=dev --ignore-scripts && bun install --production --frozen-lockfile --ignore-scripts + +FROM oven/bun:1.4.4-debian AS runtime +RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates && rm -rf /var/lib/apt/lists/* +WORKDIR /app +COPY --from=build --chown=bun:bun /app/packages ./packages +COPY --from=build --chown=bun:bun /app/apps/api ./apps/api +WORKDIR /app/apps/api +ENV NODE_ENV=production +USER bun +CMD ["bun", "--smol", "dist/server.js"] diff --git a/apps/api/Dockerfile.dockerignore b/apps/api/Dockerfile.dockerignore new file mode 100644 index 000000000..63646e522 --- /dev/null +++ b/apps/api/Dockerfile.dockerignore @@ -0,0 +1,6 @@ +**/node_modules +**/dist +**/coverage +**/.env +**/.env.* +.git diff --git a/apps/api/README.md b/apps/api/README.md new file mode 100644 index 000000000..12b050405 --- /dev/null +++ b/apps/api/README.md @@ -0,0 +1,90 @@ +# Replacement Lovat API + +Ground-up implementation for [LVT-243](https://linear.app/highlander-robotics/issue/LVT-243). This application does not import or delegate to legacy handlers. Existing production deployment still uses `apps/server`; changing the traffic target is a separate release action. + +## Structure + +- `app.ts` registers Hono routes and `runtime.ts` serves them with Bun. `http/` owns endpoint declarations, payload limits and authorization policies. +- `services/` owns accounts, API keys, Collection, reports, schedules, onboarding, training, analysis, predictions, events, exports and Slack. The composition root lists each module and records route ownership. +- `repository.ts` owns source-scoped analysis reads and dataset limits. +- `@lovat/games` owns versioned rules, report validation, metrics, facts, aggregation and prediction. `metrics/` exposes 2026 compatibility adapters. +- `domain/` owns report validation/persistence, grading and transactional effect creation. +- `identity.ts`, `state.ts`, `signatures.ts` and `sockets.ts` provide identity, Redis, signed callbacks and training transport. +- `@lovat/api` owns reusable report, Collection lifecycle, training, metric and error schemas. Its optional legacy export supplies the extracted OpenAPI definitions; its effects export defines the worker protocol. + +All 137 inventoried HTTP routes have registered replacement handlers, plus v3 analysis/metadata and the training WebSocket transport. Registration coverage is checked automatically. It does not establish complete behavioral parity: see [qualification evidence](../../docs/server-rewrite-qualification.md). + +## Local setup + +Use Bun 1.4.4 for this app and Node 22.20.0 for shared package tooling. Run `npm ci && npm run build` in `packages/db` with a verified database URL, then `bun install --frozen-lockfile && bun run build` here. The install script installs/builds the API and games packages using their own npm lockfiles. Bun path links ensure that rebuilding a game cannot leave copied code stale. Copy `.env.example` to a private `.env`, verify the database URL, and apply reviewed migrations through the release/database owner. The API never runs migrations or provider imports during startup or requests. + +Start with `bun run start` (Bun loads the private local environment). Readiness probes PostgreSQL and Redis; liveness remains available while draining. Configure the worker with `API_EFFECTS_ENABLED=true`, matching Redis URL/prefix, and the relevant delivery credentials when testing the replacement. The existing Server does not enable this flag automatically. + +Auth0 JWT signatures use cached JWKS. Existing users require one authoritative local identity read; only a new subject fetches its initial profile. API keys are hashed and checked against current ownership on every request, so revocation takes effect immediately. Collection uses a team code and scout identity independently of Auth0. Training browser/attempt tokens are stored as hashes. v1 signed-in analysts retain analysis access without team membership; v3 requires a verified team. + +Slack callbacks verify the raw request HMAC. OAuth states are random, expire after ten minutes and are consumed atomically. Configure the exact allowed browser origins for HTTP and training sockets. Native clients may omit Origin. + +## Resource and latency controls + +The API admits four HTTP requests and uses a four-connection PostgreSQL pool with an eight-second statement timeout. Expensive cold analyses share one work slot and at most four queued calculations, with a five-second queue wait. Cache hits bypass that queue. The executable uses Bun `--smol` mode for slower heap growth and more frequent garbage collection. This is not a hard memory cap; qualify RSS and set deployment/container limits separately. + +Analysis reads at most 5,000 reports and 100,000 events, with at most 10,000 events per report. Legacy events are hydrated in batches of at most 1,000 reports / 20,000 events. Short repeatable-read snapshots recheck source visibility before payload reads, then release the SQL connection before calculating metrics. Generic JSON reports use 512 KiB payload batches (up to 2 MiB for an individual stored report) and a 16 MiB dataset preflight. Detailed exports also check the combined note/description size before loading text, with a 4 MiB limit. Oversized requests return 413 rather than silently averaging a truncated dataset. Analysis bodies are limited to 64 KiB; report/lifecycle/legacy bodies to 1 MiB. Catalog requests are paginated, with a maximum page of 500. + +Source, role, team, formula version and dataset revisions participate in analysis cache keys. Cache lifetime is 15 seconds, in-flight requests coalesce, and Redis cache failures fall back to current calculations. Report writes and invalidation revisions commit together in PostgreSQL. The worker publishes monotonic revisions and delivers durable email/Slack effects with retries. Training submissions create neither competition revisions nor robot warnings. + +Identity and public recovery/Collection rate limits use atomic Redis budgets and fail closed if controls are unavailable. Public limits currently use the socket peer address; a reverse proxy must be considered during deployment qualification. + +## Adding a metric or feature + +Define a metric with `defineMetric` or `defineDerivedMetric`: + +1. Declare its stable ID, aliases, season, formula version, unit, precision and required facts. +2. Supply its Zod output schema, including structured output when needed. +3. Calculate a pure per-report state. +4. Reduce report states into a match value. +5. Define how match and tournament values combine. + +Register it in the season registry and add representative fixtures. The registry publishes output JSON Schema, resolves dependencies once, detects cycles and exposes the metric through the generic endpoint. The loader fetches events only when required, and shared facts avoid scanning the same timeline for each metric. + +For a new API feature, put reusable request/response definitions in `packages/api`, add its owning service module, register its authorization policy in the composition root, and add behavior coverage. Do not import another application's source. + +## Annual game updates + +See [game-module development](../../packages/games/README.md). The v3 game catalog, report envelope, analysis and prediction endpoints select a game contract. New payloads use versioned JSON storage. Legacy uploads reject non-2026 seasons with a client-update error. Clients and 2026-specific training/schedule adapters still need deliberate annual updates. + +## Metric semantics + +All 22 numeric metrics and nine categorical breakdowns are implemented for 2026. Reports contribute equally within a match; matches contribute equally within a tournament. Rates pool quantities and valid durations before dividing. Later tournaments receive 80% weight at each recency step, ordered by date and key. Missing values stay distinct from measured zero. Points apply the accuracy scale once and keep climb bonuses separate. + +Autonomous ends at 23 elapsed seconds. Successful climb timing uses time remaining. Multi-select categories describe prevalence and can sum above one. Internal calculations retain precision; v3 rounds at the response boundary. These consistent formulas resolve legacy endpoint disagreements, so v1 analysis/CSV differences must be reviewed before switching existing clients. + +## Verification + +Run: + +```sh +bun run test +bun run lint +bun run format:check +bun run inventory:check +``` + +For disposable loopback services named `lovat_test`: + +```sh +LOVAT_DB_TEST=1 LOVAT_REDIS_TEST=1 DATABASE_URL=postgresql://lovat_test:lovat_test@127.0.0.1:5432/lovat_test REDIS_URL=redis://127.0.0.1:6379 bun run test:integration +``` + +The database suite exercises native HTTP, lifecycle retries, tenant denial, analysis, exports, API keys, signed verification, joining, training and authenticated WebSockets. Redis tests cover atomic budgets, one-time OAuth state and cache expiry. CI provisions disposable PostgreSQL and Redis. + +`bun run inventory` records each legacy route's replacement module and policy. Its coverage field explicitly describes registration only. `bun run benchmark` measures the pure engine. `tools/benchmark-http.mjs` measures local HTTP, PostgreSQL and Redis with synthetic identity; use the same disposable-service guard above. Neither benchmark establishes production latency or an old/new comparison. + +Build the image from the repository root with `docker build -f apps/api/Dockerfile .`. External-provider staging, consumer compatibility, soak tests, rollback rehearsal and traffic cutover remain release gates. + +## Local rollout qualification + +Build the legacy Server with its Node 22.20.0 toolchain, then run `bun run test:rollout` here with the disposable-service flags above. Node 22.20.0 must be on PATH (or set LOVAT_NODE_EXECUTABLE). The test runs both real server compositions over loopback HTTP, checks report/key/tenant compatibility, stops the replacement gracefully and verifies the legacy server can continue without a schema rollback. Helpers use a clean scratch directory and explicit synthetic configuration; external HTTP is blocked. + +The API workflow also builds the pruned production image, starts it under a 512 MiB / one-CPU container limit, checks readiness/catalog/authentication and verifies clean shutdown. This is local/CI qualification; live Auth0, Slack, email and production traffic changes are separately deferred. + +The HTTP benchmark now measures a separate server process. BENCHMARK_MATCHES controls unique team/match groups; BENCHMARK_SOAK_SECONDS adds cold/warm soak and liveness checks. Fixture setup and the HTTP client are excluded from server RSS/CPU. See the qualification document for exact workloads and observed limits. diff --git a/apps/api/bun.lock b/apps/api/bun.lock new file mode 100644 index 000000000..ead1214e8 --- /dev/null +++ b/apps/api/bun.lock @@ -0,0 +1,63 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "lovat-api", + "dependencies": { + "@lovat/api": "link:../../packages/api", + "@lovat/db": "link:../../packages/db", + "@lovat/games": "link:../../packages/games", + "hono": "4.13.19", + "jose": "6.2.12", + "redis": "6.2.1", + "zod": "4.6.7", + }, + "devDependencies": { + "@types/bun": "1.4.4", + "@types/node": "22.20.4", + "prettier": "3.9.9", + "typescript": "5.9.3", + }, + }, + }, + "packages": { + "@lovat/api": ["@lovat/api@link:../../packages/api", {}], + + "@lovat/db": ["@lovat/db@link:../../packages/db", {}], + + "@lovat/games": ["@lovat/games@link:../../packages/games", { "hasInstallScript": true }], + + "@redis/bloom": ["@redis/bloom@6.2.1", "", { "peerDependencies": { "@redis/client": "^6.2.1" } }, "sha512-huQgNLaCIZfQ9SeLn4q9124uOUd8HbZDYHwwUzNcRgHqCHiHKl2dDxMqJCeWh8cMqZAoWuHR8XnWbDMIf+o7ag=="], + + "@redis/client": ["@redis/client@6.2.1", "", { "dependencies": { "cluster-key-slot": "1.1.2" }, "peerDependencies": { "@node-rs/xxhash": "^1.1.0", "@opentelemetry/api": ">=1 <2" }, "optionalPeers": ["@node-rs/xxhash", "@opentelemetry/api"] }, "sha512-LzxBY7SIBvvJiyCgcaJZZakE3fJrZZ++i24+EDW9fKpCl68D35uJcKFpZZwCfOoG9WZTbyZlMzMeM0gtOAMU9Q=="], + + "@redis/json": ["@redis/json@6.2.1", "", { "peerDependencies": { "@redis/client": "^6.2.1" } }, "sha512-AFIUJ8Gj0DaaSBHYuSt8+O0oYWM+50OK1c0OmodB7XERIA8+BbyV3O4v76f9iccWasd1/7qjfZTpuzexUaZtrQ=="], + + "@redis/search": ["@redis/search@6.2.1", "", { "peerDependencies": { "@redis/client": "^6.2.1" } }, "sha512-2vfOAOyYFE7UUw3sBBlkqqruBtOUS4HRY5MtW4hp83llrwvtrTE4r22CEqXddlV+54zkLxBE4nmsIJ/dpezQrQ=="], + + "@redis/time-series": ["@redis/time-series@6.2.1", "", { "peerDependencies": { "@redis/client": "^6.2.1" } }, "sha512-kiYniph04dJOole+L359B6C9E+jYS2uDP7hca6Onj0xF38ZIpyxARO0Iq0W4ZRn1e8Q6vqW00QFZVSMRA/2Ijw=="], + + "@types/bun": ["@types/bun@1.4.4", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="], + + "@types/node": ["@types/node@22.20.4", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-zJRE40jpHtKqE/C4fgHrAKQLJuSpzEnP9ff9Y7YtoR3Wd2pwqzlekDeEuUQXjRd+QCYnVnNwuJYmhdk9XV8gvA=="], + + "bun-types": ["bun-types@1.4.4", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="], + + "cluster-key-slot": ["cluster-key-slot@1.1.2", "", {}, "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA=="], + + "hono": ["hono@4.13.19", "", {}, "sha512-KmXvQAXwcAHV+muzbIwoJ23niEB5nMoDVr9WcRkU8mvjUECm/1+7v4Jgp7P7a+H6MLFrh+vXrGonGrGS+RQfkA=="], + + "jose": ["jose@6.2.12", "", {}, "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw=="], + + "prettier": ["prettier@3.9.9", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-Z/CJHIkdujO/OtN7nXUii0Rf3VT5SRuhjBA82Xvu2XhBUgX3nhP67T0LHceBdQLex7OOFGTox+Q5Yg8Jk2Qivg=="], + + "redis": ["redis@6.2.1", "", { "dependencies": { "@redis/bloom": "6.2.1", "@redis/client": "6.2.1", "@redis/json": "6.2.1", "@redis/search": "6.2.1", "@redis/time-series": "6.2.1" } }, "sha512-Z9VHtgYs48PiQC77X9O2Er8Hj4T+5BtFjT91/vi5Is1D04N72cA946ZslM1ImJw8ZctFBZWAVjM7S5wJNeHMpg=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="], + + "zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], + } +} diff --git a/apps/api/legacy-routes.json b/apps/api/legacy-routes.json new file mode 100644 index 000000000..7af4ae63b --- /dev/null +++ b/apps/api/legacy-routes.json @@ -0,0 +1,2417 @@ +[ + { + "method": "GET", + "path": "/collection/checkcode", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "checkCodeScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/collection/end", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "endMatch" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/collection/load", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "preMatch" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/collection/load/:match/:team", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "preMatch" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/collection/schedules/:tournament", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "getScheduleForScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/collection/scouter", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "getScoutersOnTeam" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/collection/scouter", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "addNewScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/collection/scoutreports", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "addScoutReport" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/collection/start", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "startMatch" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/collection/submit", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "submitReport" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/collection/tournament", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "getScouterTournaments" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/collection/train/:session", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/collection/training/:session/submit", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/collection/training/sessions", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/collection/training/sessions/:session", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/collection/training/sessions/:session/control", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/collection/training/sessions/:session/grade", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "DELETE", + "path": "/collection/training/sessions/:session/participants/:attempt", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/collection/training/sessions/:session/ready", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/collection/training/videos", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/status", + "source": "apps/server/src/app.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/index.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/alliance", + "source": "apps/server/src/routes/analysis/analysis.routes.ts", + "handlers": [ + "alliancePageResponse" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/predictions.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/breakdown/team/:team", + "source": "apps/server/src/routes/analysis/teamLookup.routes.ts", + "handlers": [ + "breakdownMetrics" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/analysis.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/breakdown/team/:team/:breakdown", + "source": "apps/server/src/routes/analysis/teamLookup.routes.ts", + "handlers": [ + "breakdownDetails" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/analysis.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/category/team/:team", + "source": "apps/server/src/routes/analysis/teamLookup.routes.ts", + "handlers": [ + "categoryMetrics" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/analysis.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/csvplain", + "source": "apps/server/src/routes/analysis/csv.routes.ts", + "handlers": [ + "getTeamCSV" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/predictions.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/flag/team/:team", + "source": "apps/server/src/routes/analysis/teamLookup.routes.ts", + "handlers": [ + "multipleFlags" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/analysis.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/matchprediction", + "source": "apps/server/src/routes/analysis/analysis.routes.ts", + "handlers": [ + "matchPrediction" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/predictions.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/metric/:metric/team/:team", + "source": "apps/server/src/routes/analysis/teamLookup.routes.ts", + "handlers": [ + "detailsPage" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/analysis.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/metrics/scoutreport/:uuid", + "source": "apps/server/src/routes/analysis/scoutreport.routes.ts", + "handlers": [ + "matchPageSpecificScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/analysis.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/notes/team/:team", + "source": "apps/server/src/routes/analysis/teamLookup.routes.ts", + "handlers": [ + "getNotes" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/analysis.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/picklist", + "source": "apps/server/src/routes/analysis/analysis.routes.ts", + "handlers": [ + "picklistShell" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/predictions.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/pitdisplay", + "source": "apps/server/src/routes/analysis/analysis.routes.ts", + "handlers": [ + "pitDisplay" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/events.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/qualrankingprediction", + "source": "apps/server/src/routes/analysis/analysis.routes.ts", + "handlers": [ + "qualRankingPrediction" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/predictions.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/reportcsv", + "source": "apps/server/src/routes/analysis/csv.routes.ts", + "handlers": [ + "getReportCSV" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/predictions.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/scoutreports/match/:match", + "source": "apps/server/src/routes/analysis/scoutreport.routes.ts", + "handlers": [ + "scoutReportForMatch" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/analysis.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/analysis/timeline/scoutreport/:uuid", + "source": "apps/server/src/routes/analysis/scoutreport.routes.ts", + "handlers": [ + "timelineForScoutReport" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/analysis.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/doc.json", + "source": "apps/server/src/routes/index.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/index.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/analysts", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "getAnalysts" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "DELETE", + "path": "/v1/manager/apikey", + "source": "apps/server/src/routes/manager/apikey.routes.ts", + "handlers": [ + "revokeApiKey" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/apiKeys.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/apikey", + "source": "apps/server/src/routes/manager/apikey.routes.ts", + "handlers": [ + "getApiKeys" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/apiKeys.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "PATCH", + "path": "/v1/manager/apikey", + "source": "apps/server/src/routes/manager/apikey.routes.ts", + "handlers": [ + "renameApiKey" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/apiKeys.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/apikey", + "source": "apps/server/src/routes/manager/apikey.routes.ts", + "handlers": [ + "addApiKey" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/apiKeys.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/archive/uuid/:uuid", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "archiveScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/checkmatch", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "checkMatchExists" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/catalog.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/code", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "getTeamCode" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/dashboard/scoutreport", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "addScoutReportDashboard" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/emailTeamCode", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "emailTeamCode" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/onboarding.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/match-results-page", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "getMatchResults" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/events.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/matches/:tournament", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "getMatches" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/events.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/matchschedule/:tournament", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "getMatchSchedule" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/mutablepicklists", + "source": "apps/server/src/routes/manager/mutablepicklists.routes.ts", + "handlers": [ + "getMutablePicklists" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/picklists.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/mutablepicklists", + "source": "apps/server/src/routes/manager/mutablepicklists.routes.ts", + "handlers": [ + "addMutablePicklist" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/picklists.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "DELETE", + "path": "/v1/manager/mutablepicklists/:uuid", + "source": "apps/server/src/routes/manager/mutablepicklists.routes.ts", + "handlers": [ + "deleteMutablePicklist" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/picklists.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/mutablepicklists/:uuid", + "source": "apps/server/src/routes/manager/mutablepicklists.routes.ts", + "handlers": [ + "getSingleMutablePicklist" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/picklists.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "PUT", + "path": "/v1/manager/mutablepicklists/:uuid", + "source": "apps/server/src/routes/manager/mutablepicklists.routes.ts", + "handlers": [ + "updateMutablePicklist" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/picklists.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/name/uuid/:uuid", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "changeNameScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/noteam", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "addNotOnTeam" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "jwt", + "coverage": "registration" + } + }, + { + "method": "PUT", + "path": "/v1/manager/notes/:uuid", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "updateNotes" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/onboarding/resendverificationemail", + "source": "apps/server/src/routes/manager/onboarding.routes.ts", + "handlers": [ + "resendEmailLimiter", + "resendEmail" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/onboarding.ts", + "policy": "jwt", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/onboarding/team", + "source": "apps/server/src/routes/manager/onboarding.routes.ts", + "handlers": [ + "addRegisteredTeam" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/onboarding.ts", + "policy": "jwt", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/onboarding/teamcode", + "source": "apps/server/src/routes/manager/onboarding.routes.ts", + "handlers": [ + "checkCode" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "jwt", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/onboarding/teamwebsite", + "source": "apps/server/src/routes/manager/onboarding.routes.ts", + "handlers": [ + "addWebsite" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "jwt", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/onboarding/username", + "source": "apps/server/src/routes/manager/onboarding.routes.ts", + "handlers": [ + "addUsername" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "jwt", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/onboarding/verifyemail", + "source": "apps/server/src/routes/manager/onboarding.routes.ts", + "handlers": [ + "requireLovatSignature", + "approveTeamEmail" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/onboarding.ts", + "policy": "signed", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/picklists", + "source": "apps/server/src/routes/manager/picklists.routes.ts", + "handlers": [ + "getPicklists" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/picklists.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/picklists", + "source": "apps/server/src/routes/manager/picklists.routes.ts", + "handlers": [ + "addPicklist" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/picklists.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "DELETE", + "path": "/v1/manager/picklists/:uuid", + "source": "apps/server/src/routes/manager/picklists.routes.ts", + "handlers": [ + "deletePicklist" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/picklists.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/picklists/:uuid", + "source": "apps/server/src/routes/manager/picklists.routes.ts", + "handlers": [ + "getSinglePicklist" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/picklists.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "PUT", + "path": "/v1/manager/picklists/:uuid", + "source": "apps/server/src/routes/manager/picklists.routes.ts", + "handlers": [ + "updatePicklist" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/picklists.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/profile", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "getProfile" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/registeredteams/:team/approve", + "source": "apps/server/src/routes/manager/registeredteams.routes.ts", + "handlers": [ + "approveRegisteredTeam" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireLovatSignature" + ], + "replacement": { + "source": "apps/api/src/services/onboarding.ts", + "policy": "signed", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/registeredteams/:team/registrationstatus", + "source": "apps/server/src/routes/manager/registeredteams.routes.ts", + "handlers": [ + "requireAuth", + "checkRegisteredTeam" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/onboarding.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/registeredteams/:team/reject", + "source": "apps/server/src/routes/manager/registeredteams.routes.ts", + "handlers": [ + "rejectRegisteredTeam" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireLovatSignature" + ], + "replacement": { + "source": "apps/api/src/services/onboarding.ts", + "policy": "signed", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/scouter", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "addNewScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/scouter/checkcode", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "checkCodeScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/scouter/tournaments", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "getTournamentForScouterWithSchedule" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "DELETE", + "path": "/v1/manager/scouterdashboard", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "deleteScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/scouterdashboard", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "addScouterDashboard" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "PUT", + "path": "/v1/manager/scoutername", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "updateScouterName" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/scouterreports", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "scouterScoutReports" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/events.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/scouters", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "getScoutersOnTeam" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/scouters/:uuid/tournaments", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "getScouterTournaments" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/scouterschedules/:tournament", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "getScheduleForScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/scoutershift/scouters", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "getScouters" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "DELETE", + "path": "/v1/manager/scoutershifts/:uuid", + "source": "apps/server/src/routes/manager/scoutershifts.routes.ts", + "handlers": [ + "deleteScouterShift" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/shifts.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/scoutershifts/:uuid", + "source": "apps/server/src/routes/manager/scoutershifts.routes.ts", + "handlers": [ + "updateScouterShift" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/shifts.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/scoutershifts/generate", + "source": "apps/server/src/routes/manager/scoutershifts.routes.ts", + "handlers": [ + "superScoutingSchedule" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/shifts.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/scouterspage", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "scoutingLeadProgressPage" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/shifts.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/scoutreports", + "source": "apps/server/src/routes/manager/scoutreports.routes.ts", + "handlers": [ + "addScoutReport" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "DELETE", + "path": "/v1/manager/scoutreports/:uuid", + "source": "apps/server/src/routes/manager/scoutreports.routes.ts", + "handlers": [ + "deleteScoutReport" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/scoutreports/:uuid", + "source": "apps/server/src/routes/manager/scoutreports.routes.ts", + "handlers": [ + "getScoutReport" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/scoutreports/setflag/:report", + "source": "apps/server/src/routes/manager/scoutreports.routes.ts", + "handlers": [ + "setScoutReportFlag" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth", + "requireVerifiedTeam" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "PUT", + "path": "/v1/manager/settings", + "source": "apps/server/src/routes/manager/settings.routes.ts", + "handlers": [ + "updateSettings" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/settings.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/settings/teamemail", + "source": "apps/server/src/routes/manager/settings.routes.ts", + "handlers": [ + "requireVerifiedTeam", + "getTeamEmail" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/settings.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "PUT", + "path": "/v1/manager/settings/teamemail", + "source": "apps/server/src/routes/manager/settings.routes.ts", + "handlers": [ + "updateTeamEmails", + "updateTeamEmail" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/settings.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/settings/teamsource", + "source": "apps/server/src/routes/manager/settings.routes.ts", + "handlers": [ + "getTeamSource" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/settings.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/settings/teamsource", + "source": "apps/server/src/routes/manager/settings.routes.ts", + "handlers": [ + "addTeamSource" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/settings.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/settings/tournamentsource", + "source": "apps/server/src/routes/manager/settings.routes.ts", + "handlers": [ + "getTournamentSource" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/settings.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/settings/tournamentsource", + "source": "apps/server/src/routes/manager/settings.routes.ts", + "handlers": [ + "addTournamentSource" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/settings.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/team-tournament-status", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "getTeamTournamentStatus" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/events.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/teams", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "getTeams" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/catalog.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/tournament/:tournament/rankedTeams", + "source": "apps/server/src/routes/manager/tournaments.routes.ts", + "handlers": [ + "getTeamRankings" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/events.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/tournament/:tournament/scoutershifts", + "source": "apps/server/src/routes/manager/tournaments.routes.ts", + "handlers": [ + "requireVerifiedTeam", + "getScouterSchedule" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/shifts.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/tournament/:tournament/scoutershifts", + "source": "apps/server/src/routes/manager/tournaments.routes.ts", + "handlers": [ + "requireVerifiedTeam", + "addScouterShift" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/shifts.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/tournament/:tournament/teams", + "source": "apps/server/src/routes/manager/tournaments.routes.ts", + "handlers": [ + "getTeamsInTournament" + ], + "middleware": [ + "errorResponses", + "posthogReporter", + "requireAuth" + ], + "replacement": { + "source": "apps/api/src/services/catalog.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/tournaments", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "getTournaments" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/catalog.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/unarchive/uuid/:uuid", + "source": "apps/server/src/routes/manager/scouters.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "unarchiveScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/upcoming-entered-tournaments", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "getUpcomingTeamTournaments" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/events.ts", + "policy": "session", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/manager/upgradeuser", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "updateRoleToScoutingLead" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "lead", + "coverage": "registration" + } + }, + { + "method": "DELETE", + "path": "/v1/manager/user", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "deleteUser" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/manager/users", + "source": "apps/server/src/routes/manager/manager.routes.ts", + "handlers": [ + "requireAuth", + "requireVerifiedTeam", + "getUsers" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/accounts.ts", + "policy": "verified", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/slack-invite", + "source": "apps/server/src/routes/index.ts", + "handlers": [ + "onboardingRedirect" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/slack.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v1/slack/add-workspace", + "source": "apps/server/src/routes/slack/slack.routes.ts", + "handlers": [ + "addSlackWorkspace" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/slack.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/slack/command", + "source": "apps/server/src/routes/slack/slack.routes.ts", + "handlers": [ + "requireSlackToken", + "processCommand" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/slack.ts", + "policy": "slack", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v1/slack/event", + "source": "apps/server/src/routes/slack/slack.routes.ts", + "handlers": [ + "requireSlackToken", + "processEvent" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/slack.ts", + "policy": "slack", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v2/collection/checkcode", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "checkCodeScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v2/collection/end", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "endMatch" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v2/collection/load", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "preMatch" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v2/collection/load/:match/:team", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "preMatch" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v2/collection/schedules/:tournament", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "getScheduleForScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v2/collection/scouter", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "getScoutersOnTeam" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v2/collection/scouter", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "addNewScouter" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v2/collection/scoutreports", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "addScoutReport" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v2/collection/start", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "startMatch" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v2/collection/submit", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "submitReport" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/reports.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v2/collection/tournament", + "source": "apps/server/src/routes/collection/collection.routes.ts", + "handlers": [ + "getScouterTournaments" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/collection.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v2/collection/train/:session", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v2/collection/training/:session/submit", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "collection", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v2/collection/training/sessions", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v2/collection/training/sessions/:session", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v2/collection/training/sessions/:session/control", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v2/collection/training/sessions/:session/grade", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "DELETE", + "path": "/v2/collection/training/sessions/:session/participants/:attempt", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "POST", + "path": "/v2/collection/training/sessions/:session/ready", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/v2/collection/training/videos", + "source": "apps/server/src/handler/training/training.routes.ts", + "handlers": [], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/training.ts", + "policy": "public", + "coverage": "registration" + } + }, + { + "method": "GET", + "path": "/version", + "source": "apps/server/src/app.ts", + "handlers": [ + "getVersion" + ], + "middleware": [ + "errorResponses", + "posthogReporter" + ], + "replacement": { + "source": "apps/api/src/services/index.ts", + "policy": "public", + "coverage": "registration" + } + } +] diff --git a/apps/api/package.json b/apps/api/package.json new file mode 100644 index 000000000..73c343c18 --- /dev/null +++ b/apps/api/package.json @@ -0,0 +1,40 @@ +{ + "name": "lovat-api", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "bun x tsc", + "typecheck": "tsc --noEmit", + "test": "bun run build && bun test ./test/*.test.mjs", + "start": "bun --smol dist/server.js", + "benchmark": "bun run build && bun tools/benchmark.mjs", + "prebuild": "bun run --cwd ../../packages/games build", + "postinstall": "npm --prefix ../../packages/api ci --ignore-scripts && npm --prefix ../../packages/games ci --ignore-scripts && bun run --cwd ../../packages/games build", + "lint": "tsc --noEmit --noUnusedLocals --noUnusedParameters", + "format:check": "prettier --check .", + "inventory": "bun tools/inventory.mjs", + "inventory:check": "bun tools/inventory.mjs --check", + "test:integration": "bun run build && bun test --smol ./test/*.integration.mjs", + "test:rollout": "bun run build && bun test --smol ./test/*.qualification.mjs" + }, + "engines": { + "bun": "1.4.4" + }, + "dependencies": { + "@lovat/api": "link:../../packages/api", + "@lovat/db": "link:../../packages/db", + "jose": "6.2.12", + "redis": "6.2.1", + "zod": "4.6.7", + "@lovat/games": "link:../../packages/games", + "hono": "4.13.19" + }, + "devDependencies": { + "@types/node": "22.20.4", + "prettier": "3.9.9", + "typescript": "5.9.3", + "@types/bun": "1.4.4" + }, + "packageManager": "bun@1.4.4" +} diff --git a/apps/api/src/analysis.ts b/apps/api/src/analysis.ts new file mode 100644 index 000000000..95c4bd6d3 --- /dev/null +++ b/apps/api/src/analysis.ts @@ -0,0 +1,73 @@ +import { analysisBudget } from "./budget.js"; +import type { AnalysisRequest } from "@lovat/api"; +import { games, type GameCatalog, type GamePack } from "@lovat/games"; +import type { AccessScope } from "./auth.js"; +import type { AnalysisRepository } from "./repository.js"; +import { createAnalysisCache, type CacheStore } from "./cache.js"; +import { HttpError } from "./errors.js"; +export function createAnalysisService( + repository: AnalysisRepository, + store?: CacheStore, + catalog: GameCatalog = games, +) { + const caches = new Map>(); + return async (scope: AccessScope, request: AnalysisRequest) => { + const game = catalog.get(request.season, request.gameVersion); + let definitions; + try { + definitions = game.metrics.resolve(request.metrics); + } catch { + throw new HttpError( + 400, + "UNKNOWN_METRIC", + "One or more metrics are unknown", + ); + } + const compute = () => + analysisBudget(async () => { + if (repository.streamReports) + return game.analyzeStream( + repository.streamReports( + scope, + request, + new Set( + definitions.flatMap( + (definition) => definition.metadata.requires, + ), + ), + ), + request, + ); + const reports = await repository.loadReports( + scope, + request, + new Set( + definitions.flatMap((definition) => definition.metadata.requires), + ), + ); + return game.analyze(reports, request); + }); + if (!store) return compute(); + let cached = caches.get(game); + if (!cached) { + cached = createAnalysisCache( + store, + (ids) => + game.descriptor.id + + "@" + + game.descriptor.version + + ":" + + game.metrics + .resolve(ids) + .map( + (definition) => + definition.metadata.id + "@" + definition.metadata.version, + ) + .sort() + .join(","), + ); + caches.set(game, cached); + } + return cached(scope, request, compute); + }; +} diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts new file mode 100644 index 000000000..50d927798 --- /dev/null +++ b/apps/api/src/app.ts @@ -0,0 +1,250 @@ +import { Hono } from "hono"; +import { randomUUID } from "node:crypto"; +import { + routes, + type AnalysisRequest, + type AnalysisResponse, +} from "@lovat/api"; +import { games, type GameCatalog } from "@lovat/games"; +import type { AccessScope, Authenticate } from "./auth.js"; +import type { AnalysisRepository } from "./repository.js"; +import { HttpError, publicError } from "./errors.js"; +import { dispatch, type ServiceDependencies } from "./http/dispatch.js"; +import { readServicePayload } from "./http/payload.js"; +import { Reply } from "./http/router.js"; + +export interface Dependencies { + gameCatalog?: GameCatalog; + analyze?: ( + scope: AccessScope, + request: AnalysisRequest, + ) => Promise; + services?: ServiceDependencies; + authenticate: Authenticate; + repository: AnalysisRepository; + ready: () => Promise; + origins?: readonly string[]; + maxConcurrent?: number; + log?: (event: { + requestId: string; + route: string; + status: number; + durationMs: number; + }) => void; +} +export type ApiEnvironment = { + Bindings: { remoteAddress?: string }; + Variables: { requestId: string }; +}; +export function createApi(deps: Dependencies) { + const catalog = deps.gameCatalog ?? games; + const app = new Hono({ strict: false }); + let draining = false; + let active = 0; + app.onError((error, c) => { + const failure = publicError(error); + return c.json( + { + code: failure.code, + message: failure.message, + displayError: failure.message, + }, + failure.status as 400, + ); + }); + app.use("*", async (c, next) => { + const requestId = randomUUID(); + const started = performance.now(); + c.set("requestId", requestId); + c.header("X-Request-ID", requestId); + c.header("Cache-Control", "no-store"); + c.header("X-Content-Type-Options", "nosniff"); + let admitted = false; + try { + const origin = c.req.header("origin"); + if (origin) { + if (!deps.origins?.includes(origin)) + throw new HttpError( + 403, + "ORIGIN_NOT_ALLOWED", + "Origin is not allowed", + ); + c.header("Access-Control-Allow-Origin", origin); + c.header("Vary", "Origin"); + } + if (c.req.method === "OPTIONS") { + c.header( + "Access-Control-Allow-Methods", + "GET, POST, PUT, PATCH, DELETE", + ); + c.header( + "Access-Control-Allow-Headers", + "Authorization, Content-Type, X-Team-Code, X-Scouter-Uuid, X-Device-Id, X-Timestamp, X-Signature", + ); + return c.body(null, 204); + } + if (c.req.method === "GET" && c.req.path === "/health/live") + return c.json({ status: "ok" }); + if (draining || active >= (deps.maxConcurrent ?? 4)) + throw new HttpError(503, "UNAVAILABLE", "Service is busy or draining"); + active++; + admitted = true; + await next(); + } catch (error) { + const failure = publicError(error); + return c.json( + { + code: failure.code, + message: failure.message, + displayError: failure.message, + }, + failure.status as 400, + ); + } finally { + if (admitted) active--; + try { + deps.log?.({ + requestId, + route: c.req.routePath ?? "unmatched", + status: c.res.status, + durationMs: performance.now() - started, + }); + } catch { + /* Optional telemetry must not break a request. */ + } + } + }); + app.get("/health/ready", async (c) => { + const ready = await deps.ready(); + return c.json({ status: ready ? "ok" : "unavailable" }, ready ? 200 : 503); + }); + // Hono compiles the route table once; domain modules only declare endpoints. + if (deps.services) { + const services = deps.services; + for (const endpoint of services.router.endpoints) { + app.on(endpoint.method, endpoint.path, async (c) => { + let params: Record; + try { + for (const segment of c.req.path.split("/")) + decodeURIComponent(segment); + params = c.req.param(); + } catch { + throw new HttpError(400, "INVALID_PATH", "Invalid URL encoding"); + } + const payload = await readServicePayload(c.req.raw); + const url = new URL(c.req.url); + const value = await dispatch( + services, + { endpoint, params }, + { + ...payload, + headers: Object.fromEntries(c.req.raw.headers), + query: Object.fromEntries(url.searchParams), + method: c.req.method, + path: url.pathname + url.search, + remoteAddress: c.env?.remoteAddress, + }, + ); + const reply = value instanceof Reply ? value : new Reply(value); + const isText = typeof reply.body === "string"; + return new Response( + isText ? (reply.body as string) : JSON.stringify(reply.body), + { + status: reply.status, + headers: { + "Content-Type": isText + ? "text/plain; charset=utf-8" + : "application/json; charset=utf-8", + ...reply.headers, + }, + }, + ); + }); + } + } + app.get(routes.games.path, (c) => + c.json(routes.games.output.parse(catalog.list())), + ); + app.get(routes.metrics.path, async (c) => { + await deps.authenticate(c.req.header("authorization")); + const selection = routes.metrics.input.safeParse(c.req.query()); + if (!selection.success) + throw new HttpError(400, "INVALID_REQUEST", "Invalid game selection"); + const game = catalog.get( + selection.data.season ?? 2026, + selection.data.gameVersion, + ); + return c.json(routes.metrics.output.parse(game.metrics.metadata())); + }); + app.post(routes.analyze.path, async (c) => { + const scope = await deps.authenticate(c.req.header("authorization")); + const { body } = await readServicePayload(c.req.raw, 64 * 1024, true); + const parsed = routes.analyze.input.safeParse(body); + if (!parsed.success) + throw new HttpError(400, "INVALID_REQUEST", "Invalid request parameters"); + const input = parsed.data; + const game = catalog.get(input.season, input.gameVersion); + let definitions; + try { + definitions = game.metrics.resolve(input.metrics); + } catch { + throw new HttpError( + 400, + "UNKNOWN_METRIC", + "One or more metrics are unknown", + ); + } + const requires = new Set( + definitions.flatMap((definition) => definition.metadata.requires), + ); + const reports = deps.analyze + ? [] + : await deps.repository.loadReports(scope, input, requires); + const output = deps.analyze + ? await deps.analyze(scope, input) + : game.analyze(reports, input); + for (const team of Object.values(output.teams)) { + for (const result of [ + team.metrics, + ...(team.timeline?.map((match) => match.metrics) ?? []), + ]) { + for (const [id, metric] of Object.entries(result)) { + const precision = game.metrics.get(id).metadata.precision; + const round = (value: unknown): unknown => + typeof value === "number" + ? Number(value.toFixed(precision)) + : Array.isArray(value) + ? value.map(round) + : value && typeof value === "object" + ? Object.fromEntries( + Object.entries(value).map(([key, child]) => [ + key, + round(child), + ]), + ) + : value; + metric.value = round(metric.value) as typeof metric.value; + } + } + } + return c.json(routes.analyze.output.parse(output)); + }); + for (const route of [routes.submitGameReport, routes.predictGame]) { + app.post(route.path, () => { + throw new HttpError( + 503, + "REPORT_SERVICE_UNAVAILABLE", + "Report storage is unavailable", + ); + }); + } + app.notFound(() => { + throw new HttpError(404, "NOT_FOUND", "Route not found"); + }); + return { + app, + drain: () => { + draining = true; + }, + }; +} diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts new file mode 100644 index 000000000..f6c214dca --- /dev/null +++ b/apps/api/src/auth.ts @@ -0,0 +1,127 @@ +import { createRemoteJWKSet, jwtVerify, customFetch } from "jose"; +import { z } from "zod"; +import { HttpError } from "./errors.js"; + +const teamRule = z.object({ + mode: z.enum(["INCLUDE", "EXCLUDE"]), + items: z.array(z.number().int().positive()), +}); +const tournamentRule = z.object({ + mode: z.enum(["INCLUDE", "EXCLUDE"]), + items: z.array(z.string().min(1)), +}); +export interface StoredIdentity { + email?: string; + emailVerified?: boolean; + username?: string | null; + id: string; + teamNumber: number | null; + role: string; + teamSourceRule: unknown; + tournamentSourceRule: unknown; + team: { emailVerified: boolean } | null; +} +export interface AccessScope { + userId: string; + teamNumber: number; + role: string; + sources: { + teams: z.infer; + tournaments: z.infer; + }; +} +export interface AuthRepository { + userById(id: string): Promise; +} +export type Authenticate = ( + authorization: string | undefined, +) => Promise; +export function accessScope(user: StoredIdentity): AccessScope { + if (!user.teamNumber || !user.team?.emailVerified) + throw new HttpError( + 403, + "TEAM_NOT_VERIFIED", + "A verified team is required", + ); + return legacyAnalysisScope(user); +} +/** v1 permits signed-in analysts without team membership; source rules still apply. */ +export function legacyAnalysisScope(user: StoredIdentity): AccessScope { + const teams = teamRule.safeParse(user.teamSourceRule); + const tournaments = tournamentRule.safeParse(user.tournamentSourceRule); + if (!teams.success || !tournaments.success) + throw new HttpError( + 503, + "INVALID_ACCESS_SCOPE", + "Access settings are unavailable", + ); + return { + userId: user.id, + teamNumber: user.teamNumber ?? 0, + role: user.role, + sources: { teams: teams.data, tournaments: tournaments.data }, + }; +} +export function createJwtVerifier(options: { + fetch?: typeof fetch; + issuer: string; + audience: string; +}) { + const issuer = new URL(options.issuer); + if ( + issuer.protocol !== "https:" || + issuer.username || + issuer.password || + issuer.search || + issuer.hash + ) + throw new Error("AUTH0_ISSUER must be an HTTPS issuer URL"); + const keys = createRemoteJWKSet(new URL(".well-known/jwks.json", issuer), { + timeoutDuration: 3000, + [customFetch]: options.fetch, + }); + return async (token: string) => + ( + await jwtVerify(token, keys, { + issuer: issuer.href, + audience: options.audience, + }) + ).payload; +} +export function createAuthenticator( + repository: AuthRepository, + options: { + issuer: string; + audience: string; + verify?: (token: string) => Promise<{ sub?: string }>; + }, +): Authenticate { + const verify = options.verify ?? createJwtVerifier(options); + return async (authorization) => { + const match = /^Bearer ([^\s]+)$/i.exec(authorization ?? ""); + if (!match) + throw new HttpError(401, "UNAUTHORIZED", "A bearer token is required"); + if (match[1].startsWith("lvt-")) + throw new HttpError( + 401, + "JWT_REQUIRED", + "This API version requires a Dashboard token", + ); + let subject: string | undefined; + try { + subject = (await verify(match[1])).sub; + } catch { + throw new HttpError(401, "UNAUTHORIZED", "Invalid authorization token"); + } + if (!subject) + throw new HttpError(401, "UNAUTHORIZED", "Token has no subject"); + const user = await repository.userById(subject); + if (!user) + throw new HttpError( + 401, + "IDENTITY_NOT_PROVISIONED", + "Complete account onboarding first", + ); + return accessScope(user); + }; +} diff --git a/apps/api/src/batches.ts b/apps/api/src/batches.ts new file mode 100644 index 000000000..59941b086 --- /dev/null +++ b/apps/api/src/batches.ts @@ -0,0 +1,21 @@ +/** A large item gets its own batch; callers enforce each item's absolute limit. */ +export function* boundedBatches( + rows: readonly T[], + weight: (row: T) => number, + maxItems = 250, + maxWeight = 4096, +): Generator { + let batch: T[] = [], + size = 0; + for (const row of rows) { + const next = weight(row); + if (batch.length && (batch.length >= maxItems || size + next > maxWeight)) { + yield batch; + batch = []; + size = 0; + } + batch.push(row); + size += next; + } + if (batch.length) yield batch; +} diff --git a/apps/api/src/budget.ts b/apps/api/src/budget.ts new file mode 100644 index 000000000..f4df0f9f9 --- /dev/null +++ b/apps/api/src/budget.ts @@ -0,0 +1,53 @@ +import { HttpError } from "./errors.js"; +/** Serialize expensive cold analyses; cached responses never enter this queue. */ +export function createAnalysisBudget( + maxConcurrent = 1, + maxQueued = 4, + waitMs = 5000, +) { + let active = 0; + const queue: (() => void)[] = []; + const release = () => { + active--; + queue.shift()?.(); + }; + const acquire = (): Promise<() => void> => { + if (active < maxConcurrent) { + active++; + return Promise.resolve(release); + } + if (queue.length >= maxQueued) + return Promise.reject( + new HttpError(503, "ANALYSIS_BUSY", "Analysis is busy; retry shortly"), + ); + return new Promise((resolve, reject) => { + const grant = () => { + clearTimeout(timer); + active++; + resolve(release); + }; + const timer = setTimeout(() => { + const index = queue.indexOf(grant); + if (index >= 0) queue.splice(index, 1); + reject( + new HttpError( + 503, + "ANALYSIS_BUSY", + "Analysis is busy; retry shortly", + ), + ); + }, waitMs); + queue.push(grant); + }); + }; + return async (work: () => Promise) => { + const done = await acquire(); + try { + return await work(); + } finally { + done(); + } + }; +} + +export const analysisBudget = createAnalysisBudget(); diff --git a/apps/api/src/cache.ts b/apps/api/src/cache.ts new file mode 100644 index 000000000..4cdef4031 --- /dev/null +++ b/apps/api/src/cache.ts @@ -0,0 +1,82 @@ +import { createHash } from "node:crypto"; +import { + analysisResponseSchema, + type AnalysisRequest, + type AnalysisResponse, +} from "@lovat/api"; +import type { AccessScope } from "./auth.js"; +export interface CacheStore { + generations(teams: readonly number[]): Promise; + get(key: string): Promise; + set(key: string, value: string, ttl: number): Promise; +} +export function createAnalysisCache( + store: CacheStore, + formulaVersions: (ids: readonly string[]) => string, +) { + const inFlight = new Map>(); + return async ( + scope: AccessScope, + request: AnalysisRequest, + compute: () => Promise, + ): Promise => { + let key: string; + try { + const teams = [...new Set(request.teams)].sort((a, b) => a - b); + const generations = await store.generations([0, ...teams]); + const canonical = { + scope: { + userId: scope.userId, + teamNumber: scope.teamNumber, + role: scope.role, + teams: { + ...scope.sources.teams, + items: [...scope.sources.teams.items].sort((a, b) => a - b), + }, + tournaments: { + ...scope.sources.tournaments, + items: [...scope.sources.tournaments.items].sort(), + }, + }, + request: { + ...request, + teams, + metrics: [...new Set(request.metrics)].sort(), + }, + generations, + formulas: formulaVersions(request.metrics), + }; + key = createHash("sha256") + .update(JSON.stringify(canonical)) + .digest("hex"); + const cached = await store.get(key); + if (cached) { + try { + const parsed = analysisResponseSchema.safeParse(JSON.parse(cached)); + if (parsed.success) return parsed.data; + } catch { + /* Replace malformed cache values after computing a fresh result. */ + } + } + } catch { + return compute(); + } + const existing = inFlight.get(key); + if (existing) return structuredClone(await existing); + if (inFlight.size >= 16) return compute(); + const pending = (async () => { + const result = await compute(); + // TTL bounds stale results if delivery is delayed or revision keys are evicted. + try { + await store.set(key, JSON.stringify(result), 15); + } catch {} + return result; + })(); + inFlight.set(key, pending); + try { + return structuredClone(await pending); + } finally { + inFlight.delete(key); + } + }; +} diff --git a/apps/api/src/domain/effects.ts b/apps/api/src/domain/effects.ts new file mode 100644 index 000000000..83c7dba7c --- /dev/null +++ b/apps/api/src/domain/effects.ts @@ -0,0 +1,47 @@ +import type { Prisma } from "@lovat/db"; +import { effectSchema, type Effect } from "@lovat/api/effects"; + +export async function enqueue( + tx: Prisma.TransactionClient, + dedupeKey: string, + effect: Effect, +) { + const payload = effectSchema.parse(effect); + await tx.apiOutbox.upsert({ + where: { dedupeKey }, + update: {}, + create: { dedupeKey, kind: effect.kind, payload }, + }); +} +export async function recordAnalysisChange( + tx: Prisma.TransactionClient, + teamNumber: number, +) { + const row = await tx.analysisRevision.upsert({ + where: { teamNumber }, + create: { teamNumber, revision: 1n }, + update: { revision: { increment: 1n } }, + }); + await enqueue(tx, "analysis:" + teamNumber + ":" + row.revision, { + kind: "cache.revision", + teamNumber, + revision: row.revision.toString(), + }); +} +export async function reportEffects( + tx: Prisma.TransactionClient, + report: { + uuid: string; + teamNumber: number; + robotBrokeDescription?: string | null; + }, + sourceTeamNumber: number, +) { + await recordAnalysisChange(tx, report.teamNumber); + if (report.robotBrokeDescription?.trim()) + await enqueue(tx, "break:" + report.uuid, { + kind: "slack.warning", + reportUuid: report.uuid, + sourceTeamNumber, + }); +} diff --git a/apps/api/src/domain/email.ts b/apps/api/src/domain/email.ts new file mode 100644 index 000000000..b0f13453c --- /dev/null +++ b/apps/api/src/domain/email.ts @@ -0,0 +1,40 @@ +import { randomBytes } from "node:crypto"; +import type { Prisma } from "@lovat/db"; +import { enqueue } from "./effects.js"; +import { HttpError } from "../errors.js"; +export async function verificationEmail( + tx: Prisma.TransactionClient, + email: string, + teamNumber: number, + website: string, +) { + // Team lock makes the resend budget effective across API replicas. + await tx.$queryRawUnsafe( + 'SELECT number FROM "RegisteredTeam" WHERE number = $1 FOR UPDATE', + teamNumber, + ); + const recent = await tx.emailVerificationRequest.count({ + where: { teamNumber, expiresAt: { gt: new Date(Date.now() + 18 * 60000) } }, + }); + if (recent >= 2) + throw new HttpError( + 429, + "EMAIL_RATE_LIMITED", + "Wait two minutes before requesting another email", + ); + const code = randomBytes(16).toString("hex"); + await tx.emailVerificationRequest.create({ + data: { + verificationCode: code, + email, + teamNumber, + expiresAt: new Date(Date.now() + 20 * 60000), + }, + }); + await enqueue(tx, "verify:" + code, { + kind: "email.send", + to: email, + subject: "Lovat Email Verification", + text: "Verify your team email: " + new URL("/verify/" + code, website).href, + }); +} diff --git a/apps/api/src/domain/grading.ts b/apps/api/src/domain/grading.ts new file mode 100644 index 000000000..3e8d9da92 --- /dev/null +++ b/apps/api/src/domain/grading.ts @@ -0,0 +1,196 @@ +import type { PrismaClient } from "@lovat/db"; +type Event = { + time: number; + action: string; + position: string; + quantity: number | null; +}; +type Report = { events: readonly Event[]; [key: string]: unknown }; +export const rubric = "training-v3"; +const allowance = (n: number, action: string) => + n === 0 ? 0 : action === "STOP_SCORING" ? 30 : 10; +const credit = (expected: number, actual: number, action: string) => + expected > 0 && actual === 0 + ? 0 + : Math.max( + 0, + 1 - + Math.max( + 0, + Math.abs(expected - actual) - allowance(expected, action), + ) / + Math.max(expected - allowance(expected, action), 1), + ); +/** Match each expected event to one nearest unused observation within five seconds. */ +export function grade( + actual: Report, + expected: Report, + excluded: readonly string[] = [], +) { + const available = new Set(actual.events.map((_, i) => i)); + const pairs = new Map(); + for (const target of expected.events) { + let nearest = -1, + distance = Infinity; + for (const i of available) { + const observed = actual.events[i], + delta = Math.abs(observed.time - target.time); + if ( + observed.action === target.action && + observed.position === target.position && + delta <= 5 && + delta < distance + ) { + nearest = i; + distance = delta; + } + } + if (nearest >= 0) { + pairs.set(target, actual.events[nearest]); + available.delete(nearest); + } + } + const quantities = ["STOP_SCORING", "STOP_FEEDING"].map((action) => { + const targets = expected.events.filter((e) => e.action === action), + observations = actual.events.filter((e) => e.action === action); + const total = (events: readonly Event[]) => + events.reduce((n, e) => n + (e.quantity ?? 0), 0); + const target = total(targets), + observed = total(observations); + const runScore = targets.length + ? targets.reduce( + (n, e) => + n + + (pairs.has(e) + ? credit(e.quantity ?? 0, pairs.get(e)!.quantity ?? 0, action) + : 0), + 0, + ) / targets.length + : observations.length + ? 0 + : 1; + return { + action, + expected: target, + actual: observed, + score: (credit(target, observed, action) + runScore) / 2, + allowance: allowance(target, action), + differences: targets + .filter((e) => !pairs.has(e) || e.quantity !== pairs.get(e)?.quantity) + .map((e) => ({ + time: e.time, + expected: e.quantity ?? 0, + actual: pairs.get(e)?.quantity ?? null, + allowance: allowance(e.quantity ?? 0, action), + })), + }; + }); + const timeline = { + matched: pairs.size, + expected: expected.events.length, + actual: actual.events.length, + toleranceSeconds: 5, + score: + expected.events.length + actual.events.length + ? (2 * pairs.size) / (expected.events.length + actual.events.length) + : 1, + differences: [ + ...expected.events + .filter((e) => !pairs.has(e) || pairs.get(e)?.time !== e.time) + .map((e) => ({ + action: e.action, + position: e.position, + expectedTime: e.time, + actualTime: pairs.get(e)?.time ?? null, + deltaSeconds: pairs.has(e) ? pairs.get(e)!.time - e.time : null, + })), + ...[...available].map((i) => ({ + action: actual.events[i].action, + position: actual.events[i].position, + expectedTime: null, + actualTime: actual.events[i].time, + deltaSeconds: null, + })), + ], + }; + const normalize = (value: unknown) => + JSON.stringify(Array.isArray(value) ? [...value].sort() : value); + const fields = [ + "robotRoles", + "mobility", + "autoClimb", + "endgameClimb", + "intakeType", + "beached", + "scoresWhileMoving", + ] + .filter((field) => !excluded.includes(field)) + .map((field) => ({ + field, + expected: expected[field], + actual: actual[field], + correct: normalize(expected[field]) === normalize(actual[field]), + })); + return { + overallScore: + Math.round( + (25 * quantities.reduce((n, q) => n + q.score, 0) + + 30 * timeline.score + + (20 * fields.filter((f) => f.correct).length) / + Math.max(fields.length, 1)) * + 100, + ) / 100, + breakdown: { rubricVersion: rubric, quantities, timeline, fields }, + }; +} +export async function gradeReport(db: PrismaClient, uuid: string) { + await db.$transaction(async (tx) => { + await tx.$queryRawUnsafe( + 'SELECT uuid FROM "ScoutReport" WHERE uuid = $1 FOR UPDATE', + uuid, + ); + const report = await tx.scoutReport.findUnique({ + where: { uuid }, + include: { + events: true, + trainingScores: { where: { rubricVersion: rubric } }, + trainingSession: { + include: { + trainingVideo: { + include: { answerKeyReports: { include: { events: true } } }, + }, + }, + }, + }, + }); + if (!report?.training || report.trainingScores.length) return; + const video = report.trainingSession?.trainingVideo, + answer = video?.answerKeyReports.find( + (r) => r.teamMatchKey === report.teamMatchKey, + ); + if (!video || !answer) throw new Error("Training answer key unavailable"); + const result = grade( + { ...report, mobility: report.fieldTraversal }, + { ...answer, mobility: answer.fieldTraversal }, + Array.isArray(video.excludedFields) + ? video.excludedFields.filter((x): x is string => typeof x === "string") + : [], + ); + const json = (value: unknown) => JSON.parse(JSON.stringify(value)); + await tx.trainingScore.create({ + data: { + reportUuid: uuid, + answerKeyReportUuid: answer.uuid, + rubricVersion: rubric, + overallScore: result.overallScore, + breakdown: json(result.breakdown), + answerKeySnapshot: json(answer), + submittedReportSnapshot: json({ + ...report, + trainingSession: undefined, + trainingScores: undefined, + }), + }, + }); + }); +} diff --git a/apps/api/src/domain/prediction.ts b/apps/api/src/domain/prediction.ts new file mode 100644 index 000000000..0f59481a3 --- /dev/null +++ b/apps/api/src/domain/prediction.ts @@ -0,0 +1,66 @@ +import { HttpError } from "../errors.js"; +export function prediction(series: readonly (readonly number[])[]) { + if (series.length !== 6 || series.some((a) => a.length < 2)) + throw new HttpError( + 422, + "INSUFFICIENT_DATA", + "At least two matches are needed for each team", + ); + const means = series.map((a) => a.reduce((sum, n) => sum + n, 0) / a.length); + const variance = series.map( + (a, i) => a.reduce((sum, n) => sum + (n - means[i]) ** 2, 0) / a.length, + ); + const difference = + means.slice(0, 3).reduce((s, n) => s + n, 0) - + means.slice(3).reduce((s, n) => s + n, 0); + const deviation = Math.sqrt(variance.reduce((s, n) => s + n, 0)); + const redWinning = + deviation === 0 + ? difference === 0 + ? 0.5 + : difference > 0 + ? 1 + : 0 + : normalCdf(difference / deviation); + return { + redWinning, + blueWinning: 1 - redWinning, + winningAlliance: redWinning >= 0.5 ? 0 : 1, + }; +} +export function normalCdf(value: number) { + const x = Math.abs(value), + t = 1 / (1 + 0.2316419 * x); + const density = Math.exp((-x * x) / 2) / Math.sqrt(2 * Math.PI); + const tail = + density * + t * + (0.31938153 + + t * + (-0.356563782 + + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429)))); + return value >= 0 ? 1 - tail : tail; +} +export function csv( + rows: readonly Record[], + columns: string[], +) { + const cell = (value: unknown) => { + const text = + typeof value === "object" && value !== null + ? JSON.stringify(value) + : String(value ?? ""); + // Prevent spreadsheet formula execution when users export scouting notes. + const safe = /^[=+\-@\t\r]/.test(text) ? "'" + text : text; + return '"' + safe.replaceAll('"', '""') + '"'; + }; + return ( + "\uFEFF" + + [ + columns.map(cell).join(","), + ...rows.map((row) => + columns.map((column) => cell(row[column])).join(","), + ), + ].join("\r\n") + ); +} diff --git a/apps/api/src/domain/reports.ts b/apps/api/src/domain/reports.ts new file mode 100644 index 000000000..3ed1ee678 --- /dev/null +++ b/apps/api/src/domain/reports.ts @@ -0,0 +1,78 @@ +import { + eventActions, + eventPositions, + type ReportSubmission, +} from "@lovat/api"; +import type { Prisma } from "@lovat/db"; +import { plausible2026 } from "@lovat/games/2026"; + +export { normalizeTimeline } from "@lovat/games/2026"; +export function canonicalPayload( + report: ReportSubmission, +): Prisma.InputJsonObject { + return JSON.parse(JSON.stringify(report)) as Prisma.InputJsonObject; +} +export function persistenceData( + report: ReportSubmission, + teamMatchKey: string, + training = false, + session: string | null = null, +) { + const { + uuid, + scouterUuid, + notes, + robotRoles, + driverAbility, + autoClimb, + endgameClimb, + beached, + feederTypes, + intakeType, + defenseEffectiveness, + scoresWhileMoving, + climbPosition, + climbSide, + disrupts, + } = report; + return { + uuid, + scouterUuid, + teamMatchKey, + startTime: new Date(report.startTime), + training, + trainingSessionUuid: session, + notes, + robotRoles, + driverAbility, + autoClimb, + endgameClimb, + beached, + feederTypes, + intakeType, + defenseEffectiveness, + scoresWhileMoving, + climbPosition, + climbSide, + disrupts, + accuracy: report.accuracy ?? null, + robotBrokeDescription: report.robotBrokeDescription ?? null, + fieldTraversal: report.mobility, + reliability: !plausible2026(report) + ? ("FLAGGED_SYSTEM" as const) + : ("UNVERIFIED" as const), + events: { + create: report.events.map(([time, action, position, quantity]) => ({ + time, + action: eventActions[action], + position: eventPositions[position], + points: eventActions[action] === "STOP_SCORING" ? (quantity ?? 0) : 0, + quantity: ["STOP_SCORING", "STOP_FEEDING"].includes( + eventActions[action], + ) + ? (quantity ?? 0) + : 0, + })), + }, + }; +} diff --git a/apps/api/src/errors.ts b/apps/api/src/errors.ts new file mode 100644 index 000000000..ec947a796 --- /dev/null +++ b/apps/api/src/errors.ts @@ -0,0 +1,34 @@ +import { GameError } from "@lovat/games"; +export class HttpError extends Error { + constructor( + readonly status: number, + readonly code: string, + message: string, + ) { + super(message); + } +} + +export function publicError(error: unknown): HttpError { + if (error instanceof HttpError) return error; + if (error instanceof GameError) + return new HttpError(error.status, error.code, error.message); + if (error instanceof Error && "code" in error) { + const code = String(error.code); + if (code === "P2025") + return new HttpError(404, "NOT_FOUND", "Resource not found"); + if (["P2002", "P2003", "P2034"].includes(code)) + return new HttpError( + 409, + "CONFLICT", + "Request conflicts with current data", + ); + if (["P2024", "P1001", "P1002"].includes(code)) + return new HttpError( + 503, + "DATABASE_UNAVAILABLE", + "Database temporarily unavailable", + ); + } + return new HttpError(500, "INTERNAL_SERVER_ERROR", "Internal server error"); +} diff --git a/apps/api/src/gameAdapters/2026.ts b/apps/api/src/gameAdapters/2026.ts new file mode 100644 index 000000000..9c73d0f22 --- /dev/null +++ b/apps/api/src/gameAdapters/2026.ts @@ -0,0 +1,294 @@ +import { compareReportGroups } from "@lovat/games"; +import { boundedBatches } from "../batches.js"; +import type { PrismaClient, Prisma } from "@lovat/db"; +import type { AnalysisRequest } from "@lovat/api"; +import type { AccessScope, AuthRepository } from "../auth.js"; +import type { ReportInput } from "../metrics/facts.js"; +import { HttpError } from "../errors.js"; + +export interface AnalysisRepository { + streamReports( + scope: AccessScope, + request: AnalysisRequest, + requires: ReadonlySet, + ): AsyncIterable; + loadReports( + scope: AccessScope, + request: AnalysisRequest, + requires: ReadonlySet, + ): Promise; +} +const filter = (rule: { + mode: "INCLUDE" | "EXCLUDE"; + items: T[]; +}) => (rule.mode === "INCLUDE" ? { in: rule.items } : { notIn: rule.items }); + +/** This is the only analysis database boundary; callers cannot supply their own source scope. */ +export function createLegacy2026Repository( + db: PrismaClient, +): AnalysisRepository & AuthRepository { + const repository: AnalysisRepository & AuthRepository = { + async loadReports(scope, request, requires) { + const reports: ReportInput[] = []; + for await (const report of repository.streamReports( + scope, + request, + requires, + )) + reports.push(report); + return reports; + }, + userById: (id) => + db.user.findUnique({ + where: { id }, + select: { + id: true, + teamNumber: true, + role: true, + teamSourceRule: true, + tournamentSourceRule: true, + team: { select: { emailVerified: true } }, + }, + }), + async *streamReports(scope, request, requires) { + const scopedWhere: Prisma.ScoutReportWhereInput = { + training: false, + reliability: { in: ["VERIFIED", "UNVERIFIED"] }, + scouter: { sourceTeamNumber: filter(scope.sources.teams) }, + teamMatchData: { + teamNumber: { in: [...new Set(request.teams)] }, + matchType: { not: "PRACTICE" }, + tournamentKey: filter(scope.sources.tournaments), + tournament: { seasonYear: request.season }, + }, + }; + const rows = await db.scoutReport.findMany({ + where: scopedWhere, + select: { + uuid: true, + driverAbility: true, + defenseEffectiveness: true, + accuracy: true, + autoClimb: true, + endgameClimb: true, + robotRoles: true, + feederTypes: true, + fieldTraversal: true, + beached: true, + scoresWhileMoving: true, + disrupts: true, + intakeType: true, + teamMatchData: { + select: { + teamNumber: true, + matchKey: true, + key: true, + tournamentKey: true, + tournament: { select: { date: true } }, + }, + }, + }, + orderBy: { uuid: "asc" }, + take: 5001, + }); + if (rows.length > 5000) { + throw new HttpError( + 413, + "ANALYSIS_TOO_LARGE", + "Request fewer teams or narrower source tournaments", + ); + } + const reports = rows + .map((row) => ({ + ...row, + teamNumber: row.teamMatchData.teamNumber, + matchKey: row.teamMatchData.key, + tournamentKey: row.teamMatchData.tournamentKey, + tournamentDate: row.teamMatchData.tournament.date ?? "0000-01-01", + })) + .sort(compareReportGroups); + const counts = + requires.has("events") && reports.length + ? await db.event.groupBy({ + by: ["scoutReportUuid"], + where: { + scoutReportUuid: { in: reports.map((row) => row.uuid) }, + }, + _count: { _all: true }, + }) + : []; + const countById = new Map( + counts.map((row) => [row.scoutReportUuid, row._count._all]), + ); + if ( + counts.reduce((sum, row) => sum + row._count._all, 0) > 100000 || + counts.some((row) => row._count._all > 10000) + ) + throw new HttpError( + 413, + "ANALYSIS_TOO_LARGE", + "Request fewer teams or narrower source tournaments", + ); + for (const batch of boundedBatches( + reports, + (row) => countById.get(row.uuid) ?? 0, + 1000, + 20000, + )) { + const expected = batch.reduce( + (sum, row) => sum + (countById.get(row.uuid) ?? 0), + 0, + ); + // Recheck visibility and fetch events in one short snapshot. This avoids + // a costly relation join per event without racing tenant/reliability changes. + const { events, visible } = await db.$transaction( + async (tx) => { + const current = await tx.scoutReport.findMany({ + where: { + AND: [ + scopedWhere, + { uuid: { in: batch.map((row) => row.uuid) } }, + ], + }, + select: { uuid: true, teamMatchKey: true }, + }); + const expectedMatch = new Map( + batch.map((row) => [row.uuid, row.matchKey]), + ); + if ( + current.some( + (row) => expectedMatch.get(row.uuid) !== row.teamMatchKey, + ) + ) + throw new HttpError( + 409, + "ANALYSIS_CHANGED", + "Reports changed during analysis; retry shortly", + ); + const visible = new Set(current.map((row) => row.uuid)); + const events = + requires.has("events") && expected && visible.size + ? await tx.event.findMany({ + where: { scoutReportUuid: { in: [...visible] } }, + select: { + scoutReportUuid: true, + action: true, + position: true, + time: true, + quantity: true, + points: true, + }, + orderBy: [{ scoutReportUuid: "asc" }, { time: "asc" }], + take: expected + 1, + }) + : []; + return { events, visible }; + }, + { isolationLevel: "RepeatableRead", timeout: 8000, maxWait: 5000 }, + ); + if (events.length > expected) + throw new HttpError( + 409, + "ANALYSIS_CHANGED", + "Reports changed during analysis; retry shortly", + ); + const byReport = new Map(); + for (const event of events) { + if (!byReport.has(event.scoutReportUuid)) + byReport.set(event.scoutReportUuid, []); + byReport.get(event.scoutReportUuid)!.push(event); + } + for (const row of batch) + if (visible.has(row.uuid)) + yield { ...row, events: byReport.get(row.uuid) ?? [] }; + } + }, + }; + return repository; +} + +/** Bounded, source-scoped report data for exports and legacy analysis views. */ +export async function loadDetailedReports( + db: PrismaClient, + scope: AccessScope, + where: import("@lovat/db").Prisma.ScoutReportWhereInput = {}, + options: { text?: boolean; events?: boolean } = {}, +) { + const rows = await db.scoutReport.findMany({ + where: { + AND: [ + where, + { + training: false, + reliability: { in: ["VERIFIED", "UNVERIFIED"] }, + scouter: { sourceTeamNumber: filter(scope.sources.teams) }, + teamMatchData: { + matchType: { not: "PRACTICE" }, + tournamentKey: filter(scope.sources.tournaments), + tournament: { seasonYear: 2026 }, + }, + }, + ], + }, + omit: { notes: true, robotBrokeDescription: true }, + include: { + scouter: { select: { name: true, sourceTeamNumber: true } }, + teamMatchData: { include: { tournament: true } }, + }, + orderBy: { uuid: "asc" }, + take: 5001, + }); + if (rows.length > 5000) + throw new HttpError( + 413, + "ANALYSIS_TOO_LARGE", + "Narrow your team or tournament selection", + ); + const sizes = + options.text && rows.length + ? await db.$queryRaw< + { bytes: bigint }[] + >`SELECT COALESCE(sum(octet_length("notes")+COALESCE(octet_length("robotBrokeDescription"),0)),0) AS bytes FROM "ScoutReport" WHERE uuid=ANY(${rows.map((r) => r.uuid)}::text[])` + : []; + if (Number(sizes[0]?.bytes ?? 0) > 4 * 1024 * 1024) + throw new HttpError( + 413, + "ANALYSIS_TOO_LARGE", + "Narrow your team or tournament selection", + ); + const notes = + options.text && rows.length + ? await db.scoutReport.findMany({ + where: { uuid: { in: rows.map((r) => r.uuid) } }, + select: { uuid: true, notes: true, robotBrokeDescription: true }, + }) + : []; + const textById = new Map(notes.map((r) => [r.uuid, r])); + const events = + options.events !== false && rows.length + ? await db.event.findMany({ + where: { scoutReportUuid: { in: rows.map((r) => r.uuid) } }, + orderBy: [{ time: "asc" }, { eventUuid: "asc" }], + take: 100001, + }) + : []; + if (events.length > 100000) + throw new HttpError( + 413, + "ANALYSIS_TOO_LARGE", + "Narrow your team or tournament selection", + ); + const byReport = new Map(); + for (const event of events) { + if (!byReport.has(event.scoutReportUuid)) + byReport.set(event.scoutReportUuid, []); + byReport.get(event.scoutReportUuid)!.push(event); + } + return rows.map((row) => ({ + ...row, + notes: textById.get(row.uuid)?.notes ?? "", + robotBrokeDescription: + textById.get(row.uuid)?.robotBrokeDescription ?? null, + events: byReport.get(row.uuid) ?? [], + })); +} diff --git a/apps/api/src/gameAdapters/2026Write.ts b/apps/api/src/gameAdapters/2026Write.ts new file mode 100644 index 000000000..ca3fe31ba --- /dev/null +++ b/apps/api/src/gameAdapters/2026Write.ts @@ -0,0 +1,99 @@ +import type { Prisma } from "@lovat/db"; +import type { ReportSubmission, GameReportEnvelope } from "@lovat/api"; +import { reportSchema } from "@lovat/api"; +import { isDeepStrictEqual } from "node:util"; +import { + normalizeTimeline, + persistenceData, + canonicalPayload, +} from "../domain/reports.js"; +import { reportEffects } from "../domain/effects.js"; +import { HttpError } from "../errors.js"; +export async function write2026Report( + tx: Prisma.TransactionClient, + report: ReportSubmission, + actor: { uuid: string; sourceTeamNumber: number }, + match: { key: string; tournament: { seasonYear: number | null } }, + deviceId: string, + endTime?: number, +) { + await tx.$queryRaw`SELECT 1 FROM pg_advisory_xact_lock(hashtextextended(${report.uuid},0))`; + if ( + await tx.gameReport.findUnique({ + where: { uuid: report.uuid }, + select: { uuid: true }, + }) + ) + throw new HttpError( + 409, + "REPORT_ID_CONFLICT", + "Report UUID is already in use", + ); + const receipt = await tx.scoutReportInProgress.findUnique({ + where: { uuid: report.uuid }, + }); + if (receipt) { + if ( + receipt.sourceTeamNumber !== actor.sourceTeamNumber || + receipt.scouterUuid !== actor.uuid + ) + throw new HttpError(404, "NOT_FOUND", "Report not found"); + if ( + receipt.status !== "SUBMITTED" || + !isDeepStrictEqual(receipt.payload, canonicalPayload(report)) || + (endTime !== undefined && + receipt.endedAt !== null && + receipt.endedAt.getTime() !== endTime) + ) + throw new HttpError( + 409, + "REPORT_PAYLOAD_CONFLICT", + "UUID was submitted with different data", + ); + return false; + } + await tx.scoutReport.create({ data: persistenceData(report, match.key) }); + await tx.scoutReportInProgress.create({ + data: { + uuid: report.uuid, + sourceTeamNumber: actor.sourceTeamNumber, + scouterUuid: actor.uuid, + deviceId, + seasonYear: + match.tournament.seasonYear ?? Number(report.tournamentKey.slice(0, 4)), + schemaVersion: 1, + mode: "COMPETITION", + status: "SUBMITTED", + tournamentKey: report.tournamentKey, + matchType: report.matchType, + matchNumber: report.matchNumber, + teamNumber: report.teamNumber, + payload: canonicalPayload(report), + startedAt: new Date(report.startTime), + endedAt: endTime === undefined ? null : new Date(endTime), + submittedAt: new Date(), + expiresAt: new Date(Date.now() + 7 * 86400000), + finalizedReportUuid: report.uuid, + }, + }); + await reportEffects(tx, report, actor.sourceTeamNumber); + return true; +} +export function gameEnvelope2026( + envelope: GameReportEnvelope, + data: Record, +) { + return normalizeTimeline( + reportSchema.parse({ + ...data, + uuid: envelope.uuid, + scouterUuid: envelope.scouterUuid, + tournamentKey: envelope.tournamentKey, + matchType: envelope.matchType, + matchNumber: envelope.matchNumber, + teamNumber: envelope.teamNumber, + startTime: envelope.startTime, + }), + (envelope.endTime - envelope.startTime) / 1000, + ); +} diff --git a/apps/api/src/gameStorage.ts b/apps/api/src/gameStorage.ts new file mode 100644 index 000000000..e050823ac --- /dev/null +++ b/apps/api/src/gameStorage.ts @@ -0,0 +1,111 @@ +import { compareReportGroups } from "@lovat/games"; +import { boundedBatches } from "./batches.js"; +import type { PrismaClient, Prisma } from "@lovat/db"; +import type { GamePack, StoredGameReport } from "@lovat/games"; +import type { AnalysisRequest } from "@lovat/api"; +import type { AccessScope } from "./auth.js"; +import { HttpError } from "./errors.js"; +export const sourceRule = (rule: { + mode: "INCLUDE" | "EXCLUDE"; + items: T[]; +}) => (rule.mode === "INCLUDE" ? { in: rule.items } : { notIn: rule.items }); +export async function* streamGameReports( + db: PrismaClient, + scope: AccessScope, + request: AnalysisRequest, + game: GamePack, +): AsyncGenerator { + const scopedWhere: Prisma.GameReportWhereInput = { + seasonYear: request.season, + gameId: game.descriptor.id, + gameVersion: game.descriptor.version, + training: false, + reliability: { in: ["VERIFIED", "UNVERIFIED"] }, + scouter: { sourceTeamNumber: sourceRule(scope.sources.teams) }, + teamMatchData: { + teamNumber: { in: [...new Set(request.teams)] }, + matchType: { not: "PRACTICE" }, + tournamentKey: sourceRule(scope.sources.tournaments), + tournament: { seasonYear: request.season }, + }, + }; + const rows = await db.gameReport.findMany({ + where: scopedWhere, + select: { + uuid: true, + gameId: true, + gameVersion: true, + reportVersion: true, + teamMatchData: { + select: { + key: true, + teamNumber: true, + tournamentKey: true, + tournament: { select: { date: true } }, + }, + }, + }, + orderBy: { uuid: "asc" }, + take: 5001, + }); + if (rows.length > 5000) + throw new HttpError( + 413, + "ANALYSIS_TOO_LARGE", + "Request fewer teams or narrower source tournaments", + ); + const reports = rows + .map((row) => ({ + uuid: row.uuid, + gameId: row.gameId, + gameVersion: row.gameVersion, + reportVersion: row.reportVersion, + teamNumber: row.teamMatchData.teamNumber, + matchKey: row.teamMatchData.key, + tournamentKey: row.teamMatchData.tournamentKey, + tournamentDate: row.teamMatchData.tournament.date ?? "0000-01-01", + })) + .sort(compareReportGroups); + const sizes = reports.length + ? await db.$queryRaw< + { uuid: string; bytes: number }[] + >`SELECT uuid, octet_length("data"::text) AS bytes FROM "GameReport" WHERE uuid=ANY(${reports.map((row) => row.uuid)}::text[])` + : []; + if ( + sizes.reduce((sum, row) => sum + row.bytes, 0) > 16 * 1024 * 1024 || + sizes.some((row) => row.bytes > 2 * 1024 * 1024) + ) + throw new HttpError( + 413, + "ANALYSIS_TOO_LARGE", + "Request fewer teams or narrower source tournaments", + ); + const bytes = new Map(sizes.map((row) => [row.uuid, row.bytes])); + for (const batch of boundedBatches( + reports, + (row) => bytes.get(row.uuid) ?? 0, + 250, + 512 * 1024, + )) { + const data = await db.gameReport.findMany({ + where: { + AND: [scopedWhere, { uuid: { in: batch.map((row) => row.uuid) } }], + }, + select: { uuid: true, data: true }, + }); + const byId = new Map(data.map((row) => [row.uuid, row.data])); + for (const row of batch) + if (byId.has(row.uuid)) yield { ...row, data: byId.get(row.uuid) }; + } +} +export async function loadGameReports( + db: PrismaClient, + scope: AccessScope, + request: AnalysisRequest, + game: GamePack, +): Promise { + const rows: StoredGameReport[] = []; + for await (const report of streamGameReports(db, scope, request, game)) + rows.push(report); + return rows; +} diff --git a/apps/api/src/gameWrite.ts b/apps/api/src/gameWrite.ts new file mode 100644 index 000000000..fad09d968 --- /dev/null +++ b/apps/api/src/gameWrite.ts @@ -0,0 +1,74 @@ +import { isDeepStrictEqual } from "node:util"; +import type { Prisma } from "@lovat/db"; +import type { GameReportEnvelope } from "@lovat/api"; +import type { GamePack } from "@lovat/games"; +import { recordAnalysisChange } from "./domain/effects.js"; +import { HttpError } from "./errors.js"; +export async function writeGameReport( + tx: Prisma.TransactionClient, + game: GamePack, + envelope: GameReportEnvelope, + matchKey: string, + sourceTeamNumber: number, +) { + await tx.$queryRaw`SELECT 1 FROM pg_advisory_xact_lock(hashtextextended(${envelope.uuid},0))`; + if ( + await tx.scoutReport.findUnique({ + where: { uuid: envelope.uuid }, + select: { uuid: true }, + }) + ) + throw new HttpError( + 409, + "REPORT_ID_CONFLICT", + "Report UUID is already in use", + ); + const existing = await tx.gameReport.findUnique({ + where: { uuid: envelope.uuid }, + include: { scouter: { select: { sourceTeamNumber: true } } }, + }); + if (existing) { + if ( + existing.scouter.sourceTeamNumber !== sourceTeamNumber || + existing.scouterUuid !== envelope.scouterUuid + ) + throw new HttpError(404, "NOT_FOUND", "Report not found"); + if ( + existing.teamMatchKey !== matchKey || + existing.gameId !== envelope.gameId || + existing.gameVersion !== envelope.gameVersion || + existing.seasonYear !== envelope.season || + existing.startTime.getTime() !== envelope.startTime || + existing.endTime.getTime() !== envelope.endTime || + !isDeepStrictEqual( + game.validate(existing.data, existing.reportVersion), + game.validate(envelope.data, envelope.reportVersion), + ) + ) + throw new HttpError( + 409, + "REPORT_PAYLOAD_CONFLICT", + "UUID was submitted with different data", + ); + return false; + } + await tx.gameReport.create({ + data: { + uuid: envelope.uuid, + scouterUuid: envelope.scouterUuid, + teamMatchKey: matchKey, + seasonYear: envelope.season, + gameId: envelope.gameId, + gameVersion: envelope.gameVersion, + reportVersion: envelope.reportVersion, + startTime: new Date(envelope.startTime), + endTime: new Date(envelope.endTime), + data: envelope.data, + reliability: game.plausible(envelope.data, envelope.reportVersion) + ? "UNVERIFIED" + : "FLAGGED_SYSTEM", + }, + }); + await recordAnalysisChange(tx, envelope.teamNumber); + return true; +} diff --git a/apps/api/src/http/dispatch.ts b/apps/api/src/http/dispatch.ts new file mode 100644 index 000000000..c4945c5ba --- /dev/null +++ b/apps/api/src/http/dispatch.ts @@ -0,0 +1,145 @@ +import { createHash } from "node:crypto"; +import type { RateLimiter } from "../identity.js"; +import type { PrismaClient } from "@lovat/db"; +import type { IncomingHttpHeaders } from "node:http"; +import { HttpError } from "../errors.js"; +import { + type ServiceRouter, + type Context, + type Session, + type Endpoint, +} from "./router.js"; + +export interface ServiceDependencies { + router: ServiceRouter; + limiter?: RateLimiter; + db: PrismaClient; + authenticate: (authorization: string | undefined) => Promise; + verifySignature?: ( + headers: IncomingHttpHeaders, + raw: string, + slack: boolean, + method: string, + path: string, + body: unknown, + ) => Promise; +} +export async function dispatch( + deps: ServiceDependencies, + match: { endpoint: Endpoint; params: Record }, + request: { + headers: IncomingHttpHeaders; + query: Record; + body: unknown; + rawBody: string; + method: string; + path: string; + remoteAddress?: string; + }, +): Promise { + const { endpoint } = match; + let session: Session | null = null; + const peer = createHash("sha256") + .update(request.remoteAddress ?? "unknown") + .digest("hex"); + const limitedPublic = + endpoint.policy === "public" && + (endpoint.path.endsWith("/checkcode") || + endpoint.path.endsWith("/emailTeamCode") || + (endpoint.method === "POST" && + endpoint.path.endsWith("/training/sessions"))); + if ( + limitedPublic && + deps.limiter && + !(await deps.limiter.consume( + "public:" + endpoint.path + ":" + peer, + 20, + 60, + )) + ) + throw new HttpError( + 429, + "RATE_LIMITED", + "Too many requests; retry shortly", + ); + if (["session", "jwt", "verified", "lead"].includes(endpoint.policy)) { + session = await deps.authenticate(request.headers.authorization); + if (endpoint.policy === "jwt" && session.tokenType !== "jwt") + throw new HttpError( + 403, + "JWT_REQUIRED", + "A Dashboard session is required", + ); + if ( + ["verified", "lead"].includes(endpoint.policy) && + (!session.user.teamNumber || !session.user.team?.emailVerified) + ) { + throw new HttpError( + 403, + "TEAM_NOT_VERIFIED", + "A verified team is required", + ); + } + if ( + endpoint.policy === "lead" && + (session.tokenType !== "jwt" || session.user.role !== "SCOUTING_LEAD") + ) { + throw new HttpError( + 403, + "SCOUTING_LEAD_REQUIRED", + "A scouting lead is required", + ); + } + } + if (endpoint.policy === "signed" || endpoint.policy === "slack") { + if ( + !deps.verifySignature || + !(await deps.verifySignature( + request.headers, + request.rawBody, + endpoint.policy === "slack", + request.method, + request.path, + request.body, + )) + ) { + throw new HttpError( + 403, + "INVALID_SIGNATURE", + "Invalid request signature", + ); + } + } + const ctx: Context = { + ...request, + db: deps.db, + params: match.params, + session, + }; + if (endpoint.policy === "collection") { + const code = request.headers["x-team-code"]; + if (typeof code !== "string" || !code) + throw new HttpError(401, "TEAM_CODE_REQUIRED", "A team code is required"); + const team = await deps.db.registeredTeam.findUnique({ + where: { code }, + select: { number: true }, + }); + if (!team) + throw new HttpError(401, "INVALID_TEAM_CODE", "Team code is not correct"); + if ( + deps.limiter && + !(await deps.limiter.consume( + "collection:" + team.number + ":" + peer, + 300, + 60, + )) + ) + throw new HttpError( + 429, + "RATE_LIMITED", + "Too many Collection requests; retry shortly", + ); + ctx.collectionTeam = team.number; + } + return endpoint.handle(ctx); +} diff --git a/apps/api/src/http/payload.ts b/apps/api/src/http/payload.ts new file mode 100644 index 000000000..4e07d6f6c --- /dev/null +++ b/apps/api/src/http/payload.ts @@ -0,0 +1,79 @@ +import { HttpError } from "../errors.js"; + +export async function readServicePayload( + req: Request, + maximum = 1024 * 1024, + jsonOnly = false, +): Promise<{ body: unknown; rawBody: string }> { + const encoding = req.headers.get("content-encoding"); + if (encoding && encoding !== "identity") + throw new HttpError( + 415, + "UNSUPPORTED_ENCODING", + "Compressed request bodies are unsupported", + ); + if (Number(req.headers.get("content-length")) > maximum) + throw new HttpError(413, "REQUEST_TOO_LARGE", "Request body is too large"); + const reader = req.body?.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + if (reader) { + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > maximum) { + await reader.cancel(); + throw new HttpError( + 413, + "REQUEST_TOO_LARGE", + "Request body is too large", + ); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + } + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + const rawBody = new TextDecoder().decode(bytes); + const contentType = req.headers.get("content-type")?.split(";")[0].trim(); + if (!rawBody && !jsonOnly) return { body: {}, rawBody }; + if (contentType === "application/json") { + let body: unknown; + try { + body = JSON.parse(rawBody); + } catch { + throw new HttpError(400, "INVALID_JSON", "Invalid JSON body"); + } + // Bound recursive schema work for arbitrary game JSON. + const pending: { value: unknown; depth: number }[] = [ + { value: body, depth: 0 }, + ]; + let nodes = 0; + while (pending.length) { + const { value, depth } = pending.pop()!; + if (++nodes > 100000 || depth > 64) + throw new HttpError(400, "INVALID_JSON", "JSON is too complex"); + if (value && typeof value === "object") { + for (const child of Object.values(value)) + pending.push({ value: child, depth: depth + 1 }); + } + } + return { body, rawBody }; + } + if (!jsonOnly && contentType === "application/x-www-form-urlencoded") + return { body: Object.fromEntries(new URLSearchParams(rawBody)), rawBody }; + throw new HttpError( + 415, + "UNSUPPORTED_MEDIA_TYPE", + jsonOnly ? "Use application/json" : "Use application/json or form encoding", + ); +} diff --git a/apps/api/src/http/router.ts b/apps/api/src/http/router.ts new file mode 100644 index 000000000..755639701 --- /dev/null +++ b/apps/api/src/http/router.ts @@ -0,0 +1,94 @@ +import type { IncomingHttpHeaders } from "node:http"; +import type { PrismaClient } from "@lovat/db"; +import { z } from "zod"; +import { HttpError } from "../errors.js"; +import type { StoredIdentity } from "../auth.js"; + +export interface Session { + user: StoredIdentity; + tokenType: "jwt" | "apiKey"; +} +export interface Context { + db: PrismaClient; + session: Session | null; + params: Record; + query: Record; + headers: IncomingHttpHeaders; + body: unknown; + rawBody: string; + collectionTeam?: number; +} +export type Policy = + | "public" + | "session" + | "jwt" + | "verified" + | "lead" + | "collection" + | "signed" + | "slack"; +export interface Endpoint { + module?: string; + method: string; + path: string; + policy: Policy; + handle: (ctx: Context) => Promise; +} +export class Reply { + constructor( + readonly body: unknown, + readonly status = 200, + readonly headers: Record = {}, + ) {} +} +export class ServiceRouter { + readonly endpoints: Endpoint[] = []; + add( + method: string, + path: string, + policy: Policy, + handle: Endpoint["handle"], + ) { + if (this.endpoints.some((e) => e.method === method && e.path === path)) + throw new Error("Duplicate endpoint: " + method + " " + path); + const endpoint = { method, path, policy, handle }; + this.endpoints.push(endpoint); + } +} + +export function input( + schema: S, + value: unknown, +): z.output { + const parsed = schema.safeParse(value); + if (!parsed.success) + throw new HttpError(400, "INVALID_REQUEST", "Invalid request parameters"); + return parsed.data; +} +export function user(ctx: Context): StoredIdentity { + if (!ctx.session) throw new HttpError(401, "UNAUTHORIZED", "Sign in first"); + return ctx.session.user; +} +export function team(ctx: Context): number { + const number = user(ctx).teamNumber; + if (!number) throw new HttpError(403, "TEAM_REQUIRED", "A team is required"); + return number; +} +export function writable(ctx: Context) { + if (ctx.session?.tokenType !== "jwt") + throw new HttpError( + 403, + "JWT_REQUIRED", + "This action requires a Dashboard session", + ); +} +export const identifier = z.string().min(1).max(256); +export const positive = z.coerce.number().int().positive(); +export const pageSchema = z.object({ + take: z.coerce.number().int().min(1).max(500).default(100), + skip: z.coerce.number().int().min(0).max(100000).default(0), + filter: z.string().max(200).optional(), +}); +export function notFound(message = "Resource not found"): never { + throw new HttpError(404, "NOT_FOUND", message); +} diff --git a/apps/api/src/identity.ts b/apps/api/src/identity.ts new file mode 100644 index 000000000..e4f7cb1d7 --- /dev/null +++ b/apps/api/src/identity.ts @@ -0,0 +1,82 @@ +import { createHash } from "node:crypto"; +import { createJwtVerifier } from "./auth.js"; +import type { PrismaClient } from "@lovat/db"; +import { HttpError } from "./errors.js"; +import type { Session } from "./http/router.js"; + +export interface RateLimiter { + consume(key: string, limit: number, windowSeconds: number): Promise; +} +export function createIdentityService( + db: PrismaClient, + options: { + issuer: string; + audience: string; + limiter: RateLimiter; + verify?: (token: string) => Promise<{ sub?: string }>; + provision?: (token: string, subject: string) => Promise; + }, +) { + const verify = options.verify ?? createJwtVerifier(options); + const select = { + id: true, + teamNumber: true, + role: true, + email: true, + emailVerified: true, + username: true, + teamSourceRule: true, + tournamentSourceRule: true, + team: { select: { emailVerified: true } }, + } as const; + return async (authorization: string | undefined): Promise => { + const match = /^Bearer ([^\s]+)$/i.exec(authorization ?? ""); + if (!match) + throw new HttpError(401, "UNAUTHORIZED", "A bearer token is required"); + const token = match[1]; + if (token.startsWith("lvt-")) { + const hash = createHash("sha256").update(token).digest("hex"); + const key = await db.apiKey.findUnique({ + where: { keyHash: hash }, + select: { user: { select } }, + }); + if (!key) throw new HttpError(401, "UNAUTHORIZED", "Invalid API key"); + if (!(await options.limiter.consume("apikey:" + hash, 1, 3))) + throw new HttpError( + 429, + "RATE_LIMITED", + "Wait three seconds before another API-key request", + ); + return { user: key.user, tokenType: "apiKey" }; + } + let subject: string | undefined; + try { + subject = (await verify(token)).sub; + } catch { + throw new HttpError(401, "UNAUTHORIZED", "Invalid authorization token"); + } + if (!subject) + throw new HttpError(401, "UNAUTHORIZED", "Token has no subject"); + let user = await db.user.findUnique({ where: { id: subject }, select }); + if (!user && options.provision) { + await options.provision(token, subject); + user = await db.user.findUnique({ where: { id: subject }, select }); + } + if (!user) + throw new HttpError( + 401, + "IDENTITY_NOT_PROVISIONED", + "Complete account onboarding", + ); + if ( + !(await options.limiter.consume( + "user:" + createHash("sha256").update(user.id).digest("hex"), + 600, + 60, + )) + ) { + throw new HttpError(429, "RATE_LIMITED", "Too many requests"); + } + return { user, tokenType: "jwt" }; + }; +} diff --git a/apps/api/src/metrics/engine.ts b/apps/api/src/metrics/engine.ts new file mode 100644 index 000000000..c65d16ae3 --- /dev/null +++ b/apps/api/src/metrics/engine.ts @@ -0,0 +1,12 @@ +import { analyzeGameReports } from "@lovat/games"; +import { prepareFacts, type Facts, type ReportInput } from "@lovat/games/2026"; +import type { MetricRegistry } from "@lovat/games"; +import type { AnalysisRequest } from "@lovat/api"; +// Compatibility entrypoint; new game modules use the generic engine directly. +export function analyzeReports( + reports: readonly ReportInput[], + request: AnalysisRequest, + registry: MetricRegistry, +) { + return analyzeGameReports(reports, request, registry, prepareFacts); +} diff --git a/apps/api/src/metrics/facts.ts b/apps/api/src/metrics/facts.ts new file mode 100644 index 000000000..9ed7bbda4 --- /dev/null +++ b/apps/api/src/metrics/facts.ts @@ -0,0 +1,2 @@ +export { prepareFacts } from "@lovat/games/2026"; +export type { Facts, ReportInput, AnalysisEvent } from "@lovat/games/2026"; diff --git a/apps/api/src/metrics/registry.ts b/apps/api/src/metrics/registry.ts new file mode 100644 index 000000000..015cbf9a4 --- /dev/null +++ b/apps/api/src/metrics/registry.ts @@ -0,0 +1,11 @@ +import type { Facts } from "@lovat/games/2026"; +import { + MetricRegistry as GenericRegistry, + defineMetricFor, + defineDerivedMetricFor, +} from "@lovat/games"; +export { mean, recencyWeightedMean } from "@lovat/games"; +export type MetricDefinition = import("@lovat/games").MetricDefinition; +export class MetricRegistry extends GenericRegistry {} +export const defineMetric = defineMetricFor(); +export const defineDerivedMetric = defineDerivedMetricFor(); diff --git a/apps/api/src/metrics/season2026.ts b/apps/api/src/metrics/season2026.ts new file mode 100644 index 000000000..5c1c9c3d4 --- /dev/null +++ b/apps/api/src/metrics/season2026.ts @@ -0,0 +1 @@ +export { season2026 } from "@lovat/games/2026"; diff --git a/apps/api/src/official.ts b/apps/api/src/official.ts new file mode 100644 index 000000000..0b1e69901 --- /dev/null +++ b/apps/api/src/official.ts @@ -0,0 +1,124 @@ +import { z } from "zod"; +import { HttpError } from "./errors.js"; +const eventKey = z.string().regex(/^[a-zA-Z0-9_-]{1,100}$/); +export const rankingSchema = z.object({ + rankings: z + .array( + z.object({ + team_key: z.string(), + rank: z.number(), + matches_played: z.number().optional(), + sort_orders: z.array(z.number()).optional(), + extra_stats: z.array(z.number()).optional(), + }), + ) + .max(10000) + .nullable(), +}); +export type OfficialReader = ( + event: string, + resource: string, + schema: z.ZodType, +) => Promise; +async function readJson(response: Response) { + if (!response.body) throw Error("Missing provider response"); + const reader = response.body.getReader(), + chunks: Uint8Array[] = []; + let size = 0; + try { + while (true) { + const next = await reader.read(); + if (next.done) break; + size += next.value.byteLength; + if (size > 2_000_000) { + await reader.cancel(); + throw Error("Provider response exceeds limit"); + } + chunks.push(next.value); + } + } finally { + reader.releaseLock(); + } + return { + value: JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown, + size, + }; +} +/** Bound both provider work and retained response bytes, independently of entry count. */ +export function createOfficialReader( + key: string | undefined, + fetcher: typeof fetch = fetch, +): OfficialReader { + const entries = new Map< + string, + { expires: number; value: unknown; size: number } + >(); + const pending = new Map>(); + let retained = 0; + const remove = (id: string) => { + const entry = entries.get(id); + if (entry) retained -= entry.size; + entries.delete(id); + }; + return async ( + event: string, + resource: string, + schema: z.ZodType, + ): Promise => { + if ( + !eventKey.safeParse(event).success || + !["", "rankings", "teams/statuses"].includes(resource) + ) + throw new HttpError(400, "INVALID_EVENT", "Invalid event"); + const id = event + (resource ? "/" + resource : ""), + cached = entries.get(id); + if (cached && cached.expires > Date.now()) + return schema.parse(cached.value); + if (cached) remove(id); + let work = pending.get(id); + if (!work) { + if (!key) + throw new HttpError( + 503, + "PROVIDER_UNAVAILABLE", + "Official event data is unavailable", + ); + if (pending.size >= 4) + throw new HttpError( + 503, + "PROVIDER_BUSY", + "Official event data is busy", + ); + work = (async () => { + const response = await fetcher( + "https://www.thebluealliance.com/api/v3/event/" + id, + { + headers: { "X-TBA-Auth-Key": key }, + signal: AbortSignal.timeout(5000), + redirect: "error", + }, + ); + if (!response.ok) throw Error("Official event data is unavailable"); + const data = await readJson(response); + schema.parse(data.value); + if (data.size <= 128 * 1024) { + while (entries.size >= 32 || retained + data.size > 1024 * 1024) + remove(entries.keys().next().value!); + entries.set(id, { expires: Date.now() + 30000, ...data }); + retained += data.size; + } + return data.value; + })() + .catch(() => { + throw new HttpError( + 502, + "PROVIDER_UNAVAILABLE", + "Official event data is unavailable", + ); + }) + .finally(() => pending.delete(id)); + pending.set(id, work); + } + return schema.parse(await work); + }; +} diff --git a/apps/api/src/provision.ts b/apps/api/src/provision.ts new file mode 100644 index 000000000..f590323fc --- /dev/null +++ b/apps/api/src/provision.ts @@ -0,0 +1,50 @@ +import { z } from "zod"; +import type { PrismaClient } from "@lovat/db"; +import { HttpError } from "./errors.js"; +/** Profile hydration happens only for a new subject, never on the normal request path. */ +export function createProvisioner( + db: PrismaClient, + issuer: string, + fetcher: typeof fetch = fetch, +) { + const endpoint = new URL( + "userinfo", + issuer.endsWith("/") ? issuer : issuer + "/", + ); + if (endpoint.protocol !== "https:") + throw new Error("Identity issuer must use HTTPS"); + return async (token: string, subject: string) => { + const response = await fetcher(endpoint, { + headers: { Authorization: "Bearer " + token }, + signal: AbortSignal.timeout(5000), + }); + if (!response.ok) + throw new HttpError( + 503, + "IDENTITY_UNAVAILABLE", + "Account onboarding is temporarily unavailable", + ); + const profile = z + .object({ + sub: z.literal(subject), + email: z.email(), + email_verified: z.boolean().default(false), + }) + .safeParse(await response.json()); + if (!profile.success) + throw new HttpError( + 401, + "INVALID_IDENTITY", + "Identity profile does not match the token", + ); + await db.user.upsert({ + where: { id: subject }, + create: { + id: subject, + email: profile.data.email, + emailVerified: profile.data.email_verified, + }, + update: {}, + }); + }; +} diff --git a/apps/api/src/repository.ts b/apps/api/src/repository.ts new file mode 100644 index 000000000..b6252193c --- /dev/null +++ b/apps/api/src/repository.ts @@ -0,0 +1,80 @@ +import type { PrismaClient } from "@lovat/db"; +import type { AnalysisRequest } from "@lovat/api"; +import { games, type GameCatalog, type StoredGameReport } from "@lovat/games"; +import { legacyAnalysisInput } from "@lovat/games/2026"; +import type { AccessScope, AuthRepository } from "./auth.js"; +import { createLegacy2026Repository } from "./gameAdapters/2026.js"; +import { streamGameReports } from "./gameStorage.js"; +export { loadDetailedReports } from "./gameAdapters/2026.js"; +export interface AnalysisRepository { + streamReports?( + scope: AccessScope, + request: AnalysisRequest, + requires: ReadonlySet, + ): AsyncIterable; + loadReports( + scope: AccessScope, + request: AnalysisRequest, + requires: ReadonlySet, + ): Promise; +} +type Reader = ( + scope: AccessScope, + request: AnalysisRequest, + requires: ReadonlySet, +) => AsyncIterable; +export function createRepository( + db: PrismaClient, + catalog: GameCatalog = games, +): AnalysisRepository & AuthRepository { + const legacy = createLegacy2026Repository(db); + // Compatibility adapters are explicit. Every new game uses versioned JSON storage by default. + const readers = new Map([ + [ + "frc-2026:1", + async function* (scope, request, requires) { + for await (const report of legacy.streamReports( + scope, + request, + requires, + )) + yield legacyAnalysisInput(report); + }, + ], + ]); + const repository: AnalysisRepository & AuthRepository = { + async loadReports(scope, request, requires) { + const rows: StoredGameReport[] = []; + for await (const report of repository.streamReports!( + scope, + request, + requires, + )) + rows.push(report); + return rows; + }, + userById: (id) => + db.user.findUnique({ + where: { id }, + select: { + id: true, + teamNumber: true, + role: true, + teamSourceRule: true, + tournamentSourceRule: true, + team: { select: { emailVerified: true } }, + }, + }), + streamReports(scope, request, requires) { + const game = catalog.get(request.season, request.gameVersion); + return ( + readers.get(game.descriptor.id + ":" + game.descriptor.version)?.( + scope, + request, + requires, + ) ?? streamGameReports(db, scope, request, game) + ); + }, + }; + return repository; +} diff --git a/apps/api/src/runtime.ts b/apps/api/src/runtime.ts new file mode 100644 index 000000000..312be83d3 --- /dev/null +++ b/apps/api/src/runtime.ts @@ -0,0 +1,46 @@ +import type { PrismaClient } from "@lovat/db"; +import type { createApi } from "./app.js"; +import { createTrainingSockets, type TrainingSocketData } from "./sockets.js"; + +/** Shared by production and HTTP integration tests: no Node HTTP adapter. */ +export function startApi( + api: ReturnType, + options: { + port: number; + hostname?: string; + db?: PrismaClient; + origins?: readonly string[]; + }, +) { + const sockets = options.db + ? createTrainingSockets(options.db, options.origins ?? []) + : undefined; + const server = Bun.serve({ + port: options.port, + hostname: options.hostname ?? "0.0.0.0", + maxRequestBodySize: 1024 * 1024, + idleTimeout: 10, + websocket: sockets?.websocket ?? { message() {} }, + fetch(request, server) { + if ( + sockets && + request.headers.get("upgrade")?.toLowerCase() === "websocket" + ) { + const result = sockets.upgrade(request, server); + if (result !== false) return result; + } + return api.app.fetch(request, { + remoteAddress: server.requestIP(request)?.address, + }); + }, + }); + return { + server, + url: server.url.href.replace(/\/$/, ""), + async stop(force = false) { + api.drain(); + sockets?.close(); + await server.stop(force); + }, + }; +} diff --git a/apps/api/src/server.ts b/apps/api/src/server.ts new file mode 100644 index 000000000..ad9a2b241 --- /dev/null +++ b/apps/api/src/server.ts @@ -0,0 +1,119 @@ +import { createProvisioner } from "./provision.js"; +import { startApi } from "./runtime.js"; +import { createOfficialReader } from "./official.js"; +import { createAnalysisService } from "./analysis.js"; +import { createApi } from "./app.js"; +import { accessScope } from "./auth.js"; +import { createIdentityService } from "./identity.js"; +import { createState } from "./state.js"; +import { createSignatureVerifier } from "./signatures.js"; +import { createServices } from "./services/index.js"; +import { createRepository } from "./repository.js"; + +const issuer = process.env.AUTH0_ISSUER; +const audience = process.env.AUTH0_AUDIENCE; +if (!issuer || !audience) { + throw new Error("AUTH0_ISSUER and AUTH0_AUDIENCE are required"); +} +const port = Number(process.env.PORT ?? 3001); +if (!Number.isInteger(port) || port < 0 || port > 65535) { + throw new Error("Invalid PORT"); +} + +// Only the executable entrypoint imports the connection-owning database package. +const { createDb } = await import("@lovat/db"); +const db = createDb(process.env.DATABASE_URL, { + maxConnections: 4, + idleTimeoutMs: 30_000, + statementTimeoutMs: 8_000, +}); +const repository = createRepository(db); +const state = createState( + process.env.REDIS_URL ?? "redis://127.0.0.1:6379", + process.env.REDIS_KEY_PREFIX ?? "lovat:rewrite:", +); +const identity = createIdentityService(db, { + issuer, + audience, + limiter: state.limiter, + provision: createProvisioner(db, issuer), +}); +const analyze = createAnalysisService(repository, state.cache); +const services = createServices({ + slack: { + baseUrl: process.env.BASE_URL ?? "https://api.lovat.app", + state: state.oauth, + clientId: process.env.SLACK_CLIENT_ID, + clientSecret: process.env.SLACK_CLIENT_SECRET, + }, + analyze, + official: createOfficialReader(process.env.TBA_KEY), + website: process.env.LOVAT_WEBSITE ?? "https://lovat.app", + baseUrl: process.env.BASE_URL ?? "https://api.lovat.app", + commit: process.env.RAILWAY_GIT_COMMIT_SHA ?? "no commit id", +}); +const api = createApi({ + analyze, + repository, + authenticate: async (authorization) => + accessScope((await identity(authorization)).user), + services: { + limiter: state.limiter, + router: services, + db, + authenticate: identity, + verifySignature: createSignatureVerifier({ + lovatKey: process.env.LOVAT_SIGNING_KEY, + slackSecret: process.env.SLACK_SIGNING_SECRET, + }), + }, + ready: async () => { + try { + await db.$queryRaw`SELECT 1`; + return await state.ready(); + } catch { + return false; + } + }, + origins: (process.env.CORS_ALLOWED_ORIGINS ?? "") + .split(",") + .map((x) => x.trim()) + .filter(Boolean), + log: (event) => console.log(JSON.stringify(event)), +}); +export const runtime = startApi(api, { + port, + hostname: process.env.HOST ?? "0.0.0.0", + db, + origins: (process.env.CORS_ALLOWED_ORIGINS ?? "") + .split(",") + .map((s) => s.trim()) + .filter(Boolean), +}); +console.log( + JSON.stringify({ + event: "listening", + port: runtime.server.port, + runtime: "bun", + }), +); +let stopping = false; +async function shutdown() { + if (stopping) return; + stopping = true; + api.drain(); + const deadline = setTimeout(() => { + void runtime.stop(true); + process.exit(1); + }, 15000); + deadline.unref(); + try { + await runtime.stop(); + await Promise.all([db.$disconnect(), state.close()]); + clearTimeout(deadline); + } catch { + process.exit(1); + } +} +process.once("SIGINT", () => void shutdown()); +process.once("SIGTERM", () => void shutdown()); diff --git a/apps/api/src/services/accounts.ts b/apps/api/src/services/accounts.ts new file mode 100644 index 000000000..fa1b3966c --- /dev/null +++ b/apps/api/src/services/accounts.ts @@ -0,0 +1,261 @@ +import { createHash } from "node:crypto"; +import { recordAnalysisChange, enqueue } from "../domain/effects.js"; +import { z } from "zod"; +import { + ServiceRouter, + Reply, + input, + team, + user, + writable, + notFound, +} from "../http/router.js"; +import { HttpError } from "../errors.js"; + +export function registerAccounts(router: ServiceRouter) { + router.add("GET", "/v1/manager/profile", "session", async (ctx) => + ctx.db.user.findUnique({ + where: { id: user(ctx).id }, + select: { + id: true, + username: true, + email: true, + role: true, + team: { select: { team: { select: { number: true, name: true } } } }, + }, + }), + ); + router.add("GET", "/v1/manager/users", "verified", async (ctx) => + ctx.db.user.findMany({ + where: { teamNumber: team(ctx) }, + select: { teamNumber: true, username: true, email: true, id: true }, + take: 1000, + }), + ); + router.add("GET", "/v1/manager/analysts", "lead", async (ctx) => + ctx.db.user.findMany({ + where: { teamNumber: team(ctx), role: "ANALYST" }, + select: { id: true, username: true, email: true }, + take: 1000, + }), + ); + router.add("POST", "/v1/manager/upgradeuser", "lead", async (ctx) => { + const data = input(z.object({ user: z.string().min(1) }), ctx.body); + await ctx.db.user.update({ + where: { id: data.user, teamNumber: team(ctx) }, + data: { role: "SCOUTING_LEAD" }, + }); + return "user role updated to scouting lead"; + }); + router.add("POST", "/v1/manager/noteam", "jwt", async (ctx) => { + return ctx.db.$transaction(async (tx) => { + const actor = user(ctx); + if (actor.teamNumber) { + await tx.$queryRawUnsafe( + 'SELECT number FROM "RegisteredTeam" WHERE number = $1 FOR UPDATE', + actor.teamNumber, + ); + if ( + actor.role === "SCOUTING_LEAD" && + (await tx.user.count({ + where: { teamNumber: actor.teamNumber, role: "SCOUTING_LEAD" }, + })) <= 1 + ) + throw new HttpError( + 409, + "LAST_SCOUTING_LEAD", + "Assign another scouting lead before leaving", + ); + } + return tx.user.update({ + where: { id: actor.id }, + data: { teamNumber: null, role: "ANALYST" }, + }); + }); + }); + router.add("DELETE", "/v1/manager/user", "verified", async (ctx) => { + writable(ctx); + const actor = user(ctx); + await ctx.db.$transaction(async (tx) => { + // Serialize membership changes for this team so two leads cannot both delete the last lead. + await tx.$queryRaw`SELECT "number" FROM "RegisteredTeam" WHERE "number" = ${team(ctx)} FOR UPDATE`; + if ( + actor.role === "SCOUTING_LEAD" && + (await tx.user.count({ + where: { teamNumber: team(ctx), role: "SCOUTING_LEAD" }, + })) <= 1 + ) { + throw new HttpError( + 409, + "LAST_SCOUTING_LEAD", + "Assign another scouting lead before deleting your account", + ); + } + await tx.user.delete({ where: { id: actor.id, teamNumber: team(ctx) } }); + }); + return "User deleted"; + }); + router.add("GET", "/v1/manager/code", "lead", async (ctx) => { + const row = await ctx.db.registeredTeam.findUnique({ + where: { number: team(ctx) }, + select: { code: true, teamApproved: true }, + }); + if (!row) notFound(); + if (!row.teamApproved) + throw new HttpError( + 403, + "TEAM_NOT_APPROVED", + "Team approval is required", + ); + return row.code; + }); + router.add("POST", "/v1/manager/onboarding/username", "jwt", async (ctx) => { + const data = input( + z.object({ username: z.string().trim().min(1).max(200) }), + ctx.body, + ); + await ctx.db.user.update({ where: { id: user(ctx).id }, data }); + return "Username added"; + }); + router.add( + "POST", + "/v1/manager/onboarding/teamwebsite", + "jwt", + async (ctx) => { + if (user(ctx).role !== "SCOUTING_LEAD") + throw new HttpError( + 403, + "LEAD_REQUIRED", + "A scouting lead is required", + ); + const data = input(z.object({ website: z.url() }), ctx.body); + await ctx.db.$transaction(async (tx) => { + const row = await tx.registeredTeam.update({ + where: { number: team(ctx) }, + data, + }); + const fingerprint = createHash("sha256") + .update(row.email + " " + row.website) + .digest("hex"); + await enqueue(tx, "registration:" + row.number + ":" + fingerprint, { + kind: "slack.registration", + teamNumber: row.number, + }); + }); + return "Website added"; + }, + ); + router.add("POST", "/v1/manager/onboarding/teamcode", "jwt", async (ctx) => { + const data = input( + z.object({ + code: z.string().min(1).max(256), + team: z.coerce.number().int().positive().optional(), + }), + Object.keys(ctx.query).length ? ctx.query : ctx.body, + ); + const row = await ctx.db.registeredTeam.findUnique({ + where: { code: data.code }, + select: { number: true }, + }); + if (!row || (data.team !== undefined && row.number !== data.team)) + throw new HttpError(404, "INVALID_TEAM_CODE", "Team code does not exist"); + if (user(ctx).teamNumber && user(ctx).teamNumber !== row.number) + throw new HttpError( + 409, + "ALREADY_ON_TEAM", + "Account already belongs to a team", + ); + await ctx.db.user.update({ + where: { id: user(ctx).id }, + data: { + teamNumber: row.number, + teamSourceRule: { mode: "INCLUDE", items: [row.number] }, + }, + }); + return true; + }); + router.add("POST", "/v1/manager/scouterdashboard", "lead", async (ctx) => { + const data = input( + z.object({ name: z.string().trim().min(1).max(200) }), + ctx.body, + ); + return new Reply( + await ctx.db.scouter.create({ + data: { name: data.name, sourceTeamNumber: team(ctx) }, + }), + 201, + ); + }); + router.add( + "GET", + "/v1/manager/scoutershift/scouters", + "verified", + async (ctx) => { + const archived = + ctx.query.archived === undefined + ? undefined + : ctx.query.archived === "true"; + return ctx.db.scouter.findMany({ + where: { sourceTeamNumber: team(ctx), archived }, + select: { uuid: true, name: true }, + orderBy: { name: "asc" }, + take: 10000, + }); + }, + ); + for (const [path, archived] of [ + ["archive", true], + ["unarchive", false], + ] as const) { + router.add( + "POST", + "/v1/manager/" + path + "/uuid/:uuid", + "lead", + async (ctx) => { + await ctx.db.scouter.update({ + where: { uuid: ctx.params.uuid, sourceTeamNumber: team(ctx) }, + data: { archived }, + }); + return "done " + (archived ? "archiving" : "unarchiving") + " scouter"; + }, + ); + } + router.add("PUT", "/v1/manager/scoutername", "lead", async (ctx) => { + const data = input( + z.object({ + scouterUuid: z.string().min(1), + newName: z.string().trim().min(1).max(200), + }), + ctx.body, + ); + await ctx.db.scouter.update({ + where: { uuid: data.scouterUuid, sourceTeamNumber: team(ctx) }, + data: { name: data.newName }, + }); + return "Scouter name updated"; + }); + router.add("DELETE", "/v1/manager/scouterdashboard", "lead", async (ctx) => { + const data = input(z.object({ scouterUuid: z.string().min(1) }), ctx.body); + await ctx.db.$transaction(async (tx) => { + const affected = await tx.teamMatchData.findMany({ + where: { + scoutReports: { + some: { + scouterUuid: data.scouterUuid, + scouter: { sourceTeamNumber: team(ctx) }, + training: false, + }, + }, + }, + distinct: ["teamNumber"], + select: { teamNumber: true }, + }); + await tx.scouter.delete({ + where: { uuid: data.scouterUuid, sourceTeamNumber: team(ctx) }, + }); + for (const row of affected) + await recordAnalysisChange(tx, row.teamNumber); + }); + return "Scouter deleted"; + }); +} diff --git a/apps/api/src/services/analysis.ts b/apps/api/src/services/analysis.ts new file mode 100644 index 000000000..b5f70f4cf --- /dev/null +++ b/apps/api/src/services/analysis.ts @@ -0,0 +1,494 @@ +import { analysisBudget } from "../budget.js"; +import { loadDetailedReports } from "../repository.js"; +import { rankingSchema, type OfficialReader } from "../official.js"; +import type { AnalysisRequest, AnalysisResponse } from "@lovat/api"; +import { eventActions, eventPositions } from "@lovat/api"; +import { z } from "zod"; +import { + legacyAnalysisScope as accessScope, + type AccessScope, +} from "../auth.js"; +import { + ServiceRouter, + input, + user, + positive, + type Context, +} from "../http/router.js"; +import { sourceFilter } from "./reports.js"; +import { season2026 } from "../metrics/season2026.js"; +import { analyzeReports } from "../metrics/engine.js"; +import type { ReportInput } from "../metrics/facts.js"; +import { HttpError } from "../errors.js"; + +export type Analyze = ( + scope: AccessScope, + request: AnalysisRequest, +) => Promise; +const numeric = season2026 + .metadata() + .filter((m) => m.kind === "number") + .map((m) => m.id); +const categorical = season2026 + .metadata() + .filter((m) => m.kind === "distribution") + .map((m) => m.id); +const valid = { + reliability: { + in: ["VERIFIED", "UNVERIFIED"] as ("VERIFIED" | "UNVERIFIED")[], + }, + training: false, +}; +const fields = { + robotRole: "robotRoles", + fieldTraversal: "fieldTraversal", + climbResult: "endgameClimb", + beached: "beached", + scoresWhileMoving: "scoresWhileMoving", + disrupts: "disrupts", + autoClimb: "autoClimb", + feederType: "feederTypes", + intakeType: "intakeType", +} as const; +type Breakdown = keyof typeof fields; +const roles = ["CYCLING", "SCORING", "FEEDING", "DEFENDING", "IMMOBILE"]; +const climbs = ["NOT_ATTEMPTED", "L1", "L2", "L3", "FAILED"]; +const autoClimbs = ["NOT_ATTEMPTED", "SUCCEEDED", "FAILED"]; +export function parseJson( + schema: z.ZodType, + value: string | undefined, + fallback: unknown, +): T { + try { + return input(schema, value === undefined ? fallback : JSON.parse(value)); + } catch { + throw new HttpError(400, "INVALID_QUERY", "Invalid JSON query parameter"); + } +} +const scalar = (response: AnalysisResponse, team: number, id: string) => { + const result = + response.teams[String(team)]?.metrics[season2026.get(id).metadata.id] + ?.value; + return typeof result === "number" ? result : 0; +}; +export function autoPath(report: { + events: readonly { + time: number; + action: string; + position: string; + quantity: number | null; + points: number; + }[]; + teamMatchKey: string; + autoClimb: string; + teamMatchData: { tournament: { name: string } }; +}) { + const events = report.events + .filter((e) => e.time <= 23) + .sort((a, b) => a.time - b.time); + return { + autoPoints: events.reduce((sum, e) => sum + e.points, 0), + positions: events.map((event) => ({ + location: eventPositions.indexOf( + event.position as (typeof eventPositions)[number], + ), + event: eventActions.indexOf( + event.action as (typeof eventActions)[number], + ), + time: event.time, + quantity: event.quantity ?? 0, + })), + match: report.teamMatchKey, + tournamentName: report.teamMatchData.tournament.name, + climb: autoClimbs.indexOf(report.autoClimb), + }; +} +export function autoPaths(ctx: Context, team: number) { + return analysisBudget(() => calculateAutoPaths(ctx, team)); +} +async function calculateAutoPaths(ctx: Context, team: number) { + const reports = await loadDetailedReports(ctx.db, accessScope(user(ctx)), { + teamMatchData: { teamNumber: team }, + }); + const groups: { + positions: ReturnType["positions"]; + matches: { matchKey: string; tournamentName: string }[]; + score: number[]; + frequency: number; + maxScore: number; + }[] = []; + for (const report of reports) { + const path = autoPath(report); + if (!path.positions.length) continue; + const group = groups.find((g) => { + const length = Math.min(g.positions.length, path.positions.length); + return Array.from({ length }, (_, i) => i).every( + (i) => + g.positions[i].event === path.positions[i].event && + g.positions[i].location === path.positions[i].location, + ); + }); + if (group) { + if (path.positions.length > group.positions.length) + group.positions = path.positions; + if (!group.matches.some((m) => m.matchKey === path.match)) + group.matches.push({ + matchKey: path.match, + tournamentName: path.tournamentName, + }); + group.score.push(path.autoPoints); + group.frequency++; + group.maxScore = Math.max(group.maxScore, path.autoPoints); + } else + groups.push({ + positions: path.positions, + matches: [ + { matchKey: path.match, tournamentName: path.tournamentName }, + ], + score: [path.autoPoints], + frequency: 1, + maxScore: path.autoPoints, + }); + } + return groups.sort( + (a, b) => b.frequency - a.frequency || b.maxScore - a.maxScore, + ); +} +export function registerAnalysis( + router: ServiceRouter, + analyze: Analyze, + official: OfficialReader, +) { + const request = ( + ctx: Context, + teams: number[], + metrics: string[], + timeline = false, + ) => + analyze(accessScope(user(ctx)), { teams, metrics, timeline, season: 2026 }); + for (const [suffix, metrics] of [ + ["category", numeric], + ["breakdown", categorical], + ] as const) { + router.add( + "GET", + "/v1/analysis/" + suffix + "/team/:team", + "session", + async (ctx) => { + const team = input(positive, ctx.params.team); + const response = await request(ctx, [team], [...metrics]); + const result = response.teams[String(team)].metrics; + if (!Object.values(result).some((v) => v.samples)) { + return (await ctx.db.team.findUnique({ + where: { number: team }, + select: { number: true }, + })) + ? "NO_DATA_FOR_TEAM" + : "TEAM_DOES_NOT_EXIST"; + } + return Object.fromEntries( + Object.entries(result).map(([key, value]) => [key, value.value ?? 0]), + ); + }, + ); + } + router.add( + "GET", + "/v1/analysis/metric/:metric/team/:team", + "session", + async (ctx) => { + const team = input(positive, ctx.params.team); + let metric: string; + try { + metric = season2026.get(ctx.params.metric).metadata.id; + } catch { + throw new HttpError(400, "UNKNOWN_METRIC", "Unknown metric"); + } + if (metric === "autoPoints") return { paths: await autoPaths(ctx, team) }; + const response = await request(ctx, [team], [metric], true); + const timeline = response.teams[String(team)].timeline ?? []; + const result = scalar(response, team, metric); + const allTeams = await ctx.db.teamMatchData.groupBy({ + by: ["teamNumber"], + where: { + scoutReports: { some: { AND: [sourceFilter(ctx), valid] } }, + matchType: { not: "PRACTICE" }, + }, + }); + const teams = allTeams.map((row) => row.teamNumber); + const population: number[] = []; + if (teams.length) { + const populationRequest = { + teams, + metrics: [metric], + season: 2026, + timeline: false, + }; + const data = await analyze(accessScope(user(ctx)), populationRequest); + for (const number of teams) + if (data.teams[String(number)].metrics[metric].samples) + population.push(scalar(data, number, metric)); + } + const all = population.length + ? population.reduce((sum, v) => sum + v, 0) / population.length + : 0; + const names = await ctx.db.tournament.findMany({ + where: { key: { in: timeline.map((p) => p.tournamentKey) } }, + select: { key: true, name: true }, + take: 5000, + }); + const byKey = new Map(names.map((row) => [row.key, row.name])); + return { + array: timeline.map((point) => ({ + match: point.matchKey, + dataPoint: point.metrics[metric].value ?? 0, + tournamentName: byKey.get(point.tournamentKey) ?? point.tournamentKey, + })), + result, + all, + difference: result - all, + team, + }; + }, + ); + router.add( + "GET", + "/v1/analysis/breakdown/team/:team/:breakdown", + "session", + async (ctx) => { + const team = input(positive, ctx.params.team); + const breakdown = ctx.params.breakdown as Breakdown; + const field = fields[breakdown]; + if (!field) + throw new HttpError( + 400, + "UNKNOWN_BREAKDOWN", + "Unknown breakdown metric", + ); + const rows = await ctx.db.scoutReport.findMany({ + where: { + AND: [ + sourceFilter(ctx), + valid, + { + teamMatchData: { + teamNumber: team, + matchType: { not: "PRACTICE" }, + }, + }, + ], + }, + select: { + teamMatchKey: true, + robotRoles: true, + fieldTraversal: true, + endgameClimb: true, + beached: true, + scoresWhileMoving: true, + disrupts: true, + autoClimb: true, + feederTypes: true, + intakeType: true, + scouter: { select: { sourceTeamNumber: true, name: true } }, + teamMatchData: { select: { tournament: { select: { name: true } } } }, + }, + orderBy: [ + { teamMatchData: { tournament: { date: "desc" } } }, + { startTime: "desc" }, + ], + take: 5000, + }); + return rows.flatMap((row) => { + const value = row[field]; + const values = Array.isArray(value) + ? value + : [ + typeof value === "boolean" + ? String(value).toUpperCase() + : String(value), + ]; + return values.map((value) => ({ + key: row.teamMatchKey, + tournamentName: row.teamMatchData.tournament.name, + breakdown: value, + sourceTeam: row.scouter.sourceTeamNumber, + scouter: + row.scouter.sourceTeamNumber === user(ctx).teamNumber + ? row.scouter.name + : undefined, + })); + }); + }, + ); + router.add("GET", "/v1/analysis/notes/team/:team", "session", async (ctx) => + analysisBudget(async () => { + const team = input(positive, ctx.params.team); + const rows = await loadDetailedReports( + ctx.db, + accessScope(user(ctx)), + { teamMatchData: { teamNumber: team }, notes: { not: "" } }, + { text: true, events: false }, + ); + return rows.map((row) => ({ + notes: row.notes, + robotBrokeDescription: row.robotBrokeDescription, + match: row.teamMatchKey, + tournamentName: row.teamMatchData.tournament.name, + sourceTeam: row.scouter.sourceTeamNumber, + scouterName: + row.scouter.sourceTeamNumber === user(ctx).teamNumber + ? row.scouter.name + : undefined, + })); + }), + ); + router.add("GET", "/v1/analysis/flag/team/:team", "session", async (ctx) => { + const flags = parseJson(z.array(z.string()).max(64), ctx.query.flags, []); + const team = input(positive, ctx.params.team); + const known = flags.filter( + (f) => + f !== "rank" && + season2026.metadata().some((m) => m.id === f || m.aliases.includes(f)), + ); + const response = known.length ? await request(ctx, [team], known) : null; + const ranks = + flags.includes("rank") && (ctx.query.tournamentKey || ctx.query.eventKey) + ? (( + await official( + ctx.query.tournamentKey ?? ctx.query.eventKey ?? "", + "rankings", + rankingSchema, + ) + ).rankings ?? []) + : []; + return flags.map((flag) => + flag === "rank" + ? (ranks.find((r) => r.team_key === "frc" + team)?.rank ?? 0) + : response && known.includes(flag) + ? scalar(response, team, flag) + : null, + ); + }); + router.add( + "GET", + "/v1/analysis/timeline/scoutreport/:uuid", + "session", + async (ctx) => { + const rows = await ctx.db.event.findMany({ + where: { + scoutReportUuid: ctx.params.uuid, + scoutReport: { AND: [sourceFilter(ctx), valid] }, + }, + orderBy: { time: "asc" }, + take: 10000, + }); + return rows.map((event) => [ + event.time, + eventActions.indexOf(event.action), + eventPositions.indexOf(event.position), + ...(["STOP_SCORING", "STOP_FEEDING"].includes(event.action) + ? [event.quantity ?? event.points] + : []), + ]); + }, + ); + router.add( + "GET", + "/v1/analysis/scoutreports/match/:match", + "session", + async (ctx) => { + const rows = await ctx.db.scoutReport.findMany({ + where: { + AND: [sourceFilter(ctx), valid, { teamMatchKey: ctx.params.match }], + }, + select: { + uuid: true, + scouterUuid: true, + startTime: true, + notes: true, + robotBrokeDescription: true, + reliability: true, + scouter: { select: { name: true, sourceTeamNumber: true } }, + }, + take: 1000, + }); + return rows.map((r) => ({ + ...r, + scouter: { + ...r.scouter, + name: + r.scouter.sourceTeamNumber === user(ctx).teamNumber + ? r.scouter.name + : "Scouter from " + r.scouter.sourceTeamNumber, + }, + canModify: + r.scouter.sourceTeamNumber === user(ctx).teamNumber && + user(ctx).role === "SCOUTING_LEAD", + })); + }, + ); + router.add( + "GET", + "/v1/analysis/metrics/scoutreport/:uuid", + "session", + async (ctx) => { + const report = await ctx.db.scoutReport.findFirst({ + where: { AND: [sourceFilter(ctx), valid, { uuid: ctx.params.uuid }] }, + include: { + events: { orderBy: { time: "asc" } }, + teamMatchData: { include: { tournament: true } }, + }, + }); + if (!report) return {}; + const reportInput: ReportInput = { + ...report, + teamNumber: report.teamMatchData.teamNumber, + matchKey: report.teamMatchKey, + tournamentKey: report.teamMatchData.tournamentKey, + tournamentDate: report.teamMatchData.tournament.date ?? "0000", + }; + const response = analyzeReports( + [reportInput], + { + teams: [reportInput.teamNumber], + metrics: numeric, + season: 2026, + timeline: false, + }, + season2026, + ); + const number = (id: string) => + scalar(response, reportInput.teamNumber, id); + return { + totalPoints: Math.round(number("totalPoints")), + autoPoints: number("autoPoints"), + driverAbility: report.driverAbility, + accuracy: report.accuracy, + totalBallsFed: number("totalBallsFed"), + volleys: number("volleysPerMatch"), + defenseEffectiveness: report.defenseEffectiveness, + robotRoles: report.robotRoles.map((r) => roles.indexOf(r)), + climb: climbs.indexOf(report.endgameClimb), + autoClimb: autoClimbs.indexOf(report.autoClimb), + autoClimbStartTime: + report.events.find((e) => e.action === "CLIMB" && e.time <= 23) + ?.time ?? 0, + contactDefenseTime: number("contactDefenseTime"), + campingDefenseTime: number("campingDefenseTime"), + totalDefenseTime: number("totalDefenseTime"), + scoringRate: number("fuelPerSecond"), + feedingRate: number("feedingRate"), + feeds: number("feedsPerMatch"), + feederType: report.feederTypes.map((f) => + ["CONTINUOUS", "STOP_TO_SHOOT", "DUMP"].indexOf(f), + ), + climbResult: climbs.indexOf(report.endgameClimb), + climbStartTime: number("l1StartTime"), + autoPath: autoPath(report), + note: report.notes, + robotBrokeDescription: report.robotBrokeDescription, + timeStamp: report.startTime, + }; + }, + ); +} diff --git a/apps/api/src/services/apiKeys.ts b/apps/api/src/services/apiKeys.ts new file mode 100644 index 000000000..9798ee086 --- /dev/null +++ b/apps/api/src/services/apiKeys.ts @@ -0,0 +1,79 @@ +import { createHash, randomBytes } from "node:crypto"; +import { z } from "zod"; +import { + ServiceRouter, + input, + user, + writable, + notFound, +} from "../http/router.js"; +import { HttpError } from "../errors.js"; + +export function registerApiKeys(router: ServiceRouter) { + const path = "/v1/manager/apikey"; + router.add("GET", path, "verified", async (ctx) => + ctx.db.apiKey.findMany({ + where: { userId: user(ctx).id }, + select: { + uuid: true, + name: true, + createdAt: true, + lastUsed: true, + requests: true, + }, + orderBy: { createdAt: "desc" }, + take: 1000, + }), + ); + router.add("POST", path, "verified", async (ctx) => { + writable(ctx); + const { name } = input( + z.object({ name: z.string().trim().min(1).max(200) }), + ctx.query, + ); + const apiKey = "lvt-" + randomBytes(32).toString("hex"); + await ctx.db.apiKey.create({ + data: { + name, + userId: user(ctx).id, + keyHash: createHash("sha256").update(apiKey).digest("hex"), + }, + }); + return { apiKey }; + }); + router.add("PATCH", path, "verified", async (ctx) => { + writable(ctx); + const data = input( + z.object({ + uuid: z.string().min(1), + name: z.string().trim().min(1).max(200), + }), + ctx.query, + ); + await ctx.db.apiKey.update({ + where: { uuid: data.uuid, userId: user(ctx).id }, + data: { name: data.name }, + }); + return "Key successfully renamed"; + }); + router.add("DELETE", path, "verified", async (ctx) => { + writable(ctx); + const { uuid } = input(z.object({ uuid: z.string().min(1) }), ctx.query); + const key = await ctx.db.apiKey.findUnique({ + where: { uuid }, + select: { userId: true, user: { select: { teamNumber: true } } }, + }); + if (!key) notFound("API key not found"); + if ( + key.userId !== user(ctx).id && + !( + user(ctx).role === "SCOUTING_LEAD" && + key.user.teamNumber === user(ctx).teamNumber + ) + ) { + throw new HttpError(403, "FORBIDDEN", "You cannot revoke this API key"); + } + await ctx.db.apiKey.delete({ where: { uuid } }); + return "Key successfully revoked"; + }); +} diff --git a/apps/api/src/services/catalog.ts b/apps/api/src/services/catalog.ts new file mode 100644 index 000000000..1f67e38f3 --- /dev/null +++ b/apps/api/src/services/catalog.ts @@ -0,0 +1,117 @@ +import { z } from "zod"; +import { + ServiceRouter, + input, + pageSchema, + user, + notFound, +} from "../http/router.js"; + +export function registerCatalog(router: ServiceRouter) { + router.add("GET", "/v1/manager/teams", "session", async (ctx) => { + const page = input(pageSchema, ctx.query); + const pattern = (page.filter ?? "") + "%"; + const [teams, counts] = await Promise.all([ + ctx.db.$queryRaw< + { number: number; name: string }[] + >`SELECT "number", "name" FROM "Team" + WHERE "number"::text LIKE ${pattern} OR "name" ILIKE ${pattern} + ORDER BY "number" LIMIT ${page.take} OFFSET ${page.skip}`, + ctx.db.$queryRaw<{ count: bigint }[]>`SELECT COUNT(*) AS count FROM "Team" + WHERE "number"::text LIKE ${pattern} OR "name" ILIKE ${pattern}`, + ]); + const own = teams.findIndex((row) => row.number === user(ctx).teamNumber); + if (own > 0) teams.unshift(...teams.splice(own, 1)); + return { teams, count: Number(counts[0]?.count ?? 0) }; + }); + router.add("GET", "/v1/manager/tournaments", "session", async (ctx) => { + const page = input(pageSchema, ctx.query); + const where = page.filter + ? { + OR: [ + { key: { contains: page.filter, mode: "insensitive" as const } }, + { name: { contains: page.filter, mode: "insensitive" as const } }, + ], + } + : {}; + const [rows, count, participated] = await Promise.all([ + ctx.db.tournament.findMany({ + where, + take: page.take, + skip: page.skip, + orderBy: [{ date: "asc" }, { key: "asc" }], + }), + ctx.db.tournament.count({ where }), + user(ctx).teamNumber + ? ctx.db.teamMatchData.groupBy({ + by: ["tournamentKey"], + where: { teamNumber: user(ctx).teamNumber! }, + }) + : [], + ]); + const keys = new Set(participated.map((row) => row.tournamentKey)); + const tournaments = rows.map((row) => ({ + ...row, + isParticipant: keys.has(row.key), + })); + tournaments.sort( + (a, b) => Number(b.isParticipant) - Number(a.isParticipant), + ); + return { tournaments, count }; + }); + router.add( + "GET", + "/v1/manager/tournament/:tournament/teams", + "session", + async (ctx) => + ctx.db.team.findMany({ + where: { + matchData: { + some: { + tournamentKey: ctx.params.tournament, + matchType: { not: "PRACTICE" }, + }, + }, + }, + orderBy: { number: "asc" }, + take: 1000, + }), + ); + router.add("GET", "/v1/manager/checkmatch", "public", async (ctx) => { + const data = input( + z + .object({ + tournamentKey: z.string().min(1), + teamNumber: z.coerce.number().int().positive(), + matchNumber: z.coerce.number().int().positive(), + matchType: z + .enum(["QUALIFICATION", "ELIMINATION", "PRACTICE"]) + .optional(), + isElim: z.enum(["true", "false"]).optional(), + }) + .refine((v) => v.matchType || v.isElim !== undefined), + ctx.query, + ); + const matchType = + data.matchType ?? + (data.isElim === "true" ? "ELIMINATION" : "QUALIFICATION"); + const match = await ctx.db.teamMatchData.findFirst({ + where: { + tournamentKey: data.tournamentKey, + teamNumber: data.teamNumber, + matchNumber: data.matchNumber, + matchType, + ...(matchType === "PRACTICE" ? { practiceScheduled: true } : {}), + }, + }); + if (!match) notFound("MATCH_NOT_FOUND"); + return { + match, + alliance: + matchType === "PRACTICE" + ? null + : (match.alliance?.toLowerCase() ?? + (Number(match.key.at(-1)) < 3 ? "red" : "blue")), + }; + }); +} diff --git a/apps/api/src/services/collection.ts b/apps/api/src/services/collection.ts new file mode 100644 index 000000000..271033219 --- /dev/null +++ b/apps/api/src/services/collection.ts @@ -0,0 +1,293 @@ +import { createHash } from "node:crypto"; +import { z } from "zod"; +import { + ServiceRouter, + input, + pageSchema, + notFound, + type Context, +} from "../http/router.js"; +import { HttpError } from "../errors.js"; + +export const stationFields = [ + "team1", + "team2", + "team3", + "team4", + "team5", + "team6", +] as const; +export const stationSelect = { + team1: { select: { uuid: true, name: true } }, + team2: { select: { uuid: true, name: true } }, + team3: { select: { uuid: true, name: true } }, + team4: { select: { uuid: true, name: true } }, + team5: { select: { uuid: true, name: true } }, + team6: { select: { uuid: true, name: true } }, +} as const; +export const matchTypes = { + QUALIFICATION: 0, + ELIMINATION: 1, + PRACTICE: 2, +} as const; +export async function shiftsFor( + ctx: Context, + sourceTeamNumber: number, + tournamentKey: string, +) { + return ctx.db.scouterScheduleShift.findMany({ + where: { sourceTeamNumber, tournamentKey }, + include: stationSelect, + orderBy: { startMatchOrdinalNumber: "asc" }, + take: 1000, + }); +} +export async function collectionSchedule(ctx: Context) { + const tournamentKey = ctx.params.tournament; + const [shifts, slots] = await Promise.all([ + shiftsFor(ctx, ctx.collectionTeam!, tournamentKey), + ctx.db.teamMatchData.findMany({ + where: { tournamentKey, matchType: { not: "PRACTICE" } }, + orderBy: [{ matchNumber: "asc" }, { key: "asc" }], + take: 10000, + }), + ]); + const lastQual = Math.max( + 0, + ...slots + .filter((s) => s.matchType === "QUALIFICATION") + .map((s) => s.matchNumber), + ); + if (!lastQual) + throw new HttpError( + 404, + "MATCHES_NOT_AVAILABLE", + "Matches are not available for this tournament", + ); + const matches = new Map(); + for (const row of slots) { + const key = row.matchType + ":" + row.matchNumber; + if (!matches.has(key)) matches.set(key, []); + matches.get(key)!.push(row); + } + const data = []; + for (const shift of shifts) + for ( + let ordinal = shift.startMatchOrdinalNumber; + ordinal <= shift.endMatchOrdinalNumber; + ordinal++ + ) { + const elim = ordinal > lastQual; + const matchNumber = elim ? ordinal - lastQual : ordinal; + const rows = matches.get( + (elim ? "ELIMINATION" : "QUALIFICATION") + ":" + matchNumber, + ); + if (!rows?.length) continue; + if (rows.length !== 6) + throw new HttpError( + 409, + "INCOMPLETE_MATCH", + "Match assignments are incomplete", + ); + const scouters: Record = {}; + rows.sort((a, b) => Number(a.key.at(-1)) - Number(b.key.at(-1))); + for (let station = 0; station < 6; station++) { + for (const scouter of shift[stationFields[station]]) + scouters[scouter.uuid] = { + team: rows[station].teamNumber, + alliance: station < 3 ? "red" : "blue", + }; + } + data.push({ matchNumber, matchType: elim ? 1 : 0, scouters }); + } + return { + hash: createHash("sha256").update(JSON.stringify(shifts)).digest("hex"), + data, + }; +} +export function registerCollection(router: ServiceRouter) { + const checkCode = async (ctx: Context) => { + const code = input(z.string().min(1).max(256), ctx.query.code); + return ( + (await ctx.db.registeredTeam.findUnique({ + where: { code }, + select: { number: true, emailVerified: true, teamApproved: true }, + })) ?? false + ); + }; + const listScouters = async (ctx: Context) => + ctx.db.scouter.findMany({ + where: { sourceTeamNumber: ctx.collectionTeam!, archived: false }, + orderBy: { name: "asc" }, + take: 10000, + }); + const addScout = async (ctx: Context) => { + const data = input( + z.object({ + name: z.string().trim().min(1).max(200), + teamNumber: z.number().int().positive(), + }), + ctx.body, + ); + if (data.teamNumber !== ctx.collectionTeam) + throw new HttpError( + 403, + "TEAM_MISMATCH", + "Scout must belong to this team", + ); + return ctx.db.scouter.create({ + data: { sourceTeamNumber: ctx.collectionTeam, name: data.name }, + }); + }; + const tournaments = async (ctx: Context) => { + const page = input(pageSchema, ctx.query); + const year = new Date().getUTCFullYear(); + const where = { + seasonYear: year, + ...(page.filter + ? { + OR: [ + { key: { contains: page.filter } }, + { name: { contains: page.filter } }, + ], + } + : {}), + }; + const [rows, count, own] = await Promise.all([ + ctx.db.tournament.findMany({ + where, + take: page.take, + skip: page.skip, + orderBy: [{ date: "asc" }, { key: "asc" }], + }), + ctx.db.tournament.count({ where }), + ctx.db.teamMatchData.groupBy({ + by: ["tournamentKey"], + where: { teamNumber: ctx.collectionTeam }, + }), + ]); + const keys = new Set(own.map((row) => row.tournamentKey)); + rows.sort((a, b) => Number(keys.has(b.key)) - Number(keys.has(a.key))); + return { tournaments: rows, count }; + }; + for (const prefix of ["/collection", "/v2/collection"]) { + router.add("GET", prefix + "/checkcode", "public", checkCode); + router.add("GET", prefix + "/scouter", "collection", listScouters); + router.add("POST", prefix + "/scouter", "collection", addScout); + router.add("GET", prefix + "/tournament", "collection", tournaments); + router.add( + "GET", + prefix + "/schedules/:tournament", + "collection", + collectionSchedule, + ); + } + router.add("GET", "/v1/manager/scouter/checkcode", "public", checkCode); + router.add("GET", "/v1/manager/scouters", "collection", listScouters); + router.add("POST", "/v1/manager/scouter", "collection", addScout); + router.add( + "GET", + "/v1/manager/scouters/:uuid/tournaments", + "collection", + tournaments, + ); + router.add( + "GET", + "/v1/manager/scouterschedules/:tournament", + "collection", + collectionSchedule, + ); + router.add( + "GET", + "/v1/manager/scouter/tournaments", + "collection", + async (ctx) => + ctx.db.tournament.findMany({ + where: { + scouterScheduleShifts: { + some: { sourceTeamNumber: ctx.collectionTeam }, + }, + }, + orderBy: { date: "asc" }, + take: 5000, + }), + ); + router.add( + "POST", + "/v1/manager/name/uuid/:uuid", + "collection", + async (ctx) => { + const data = input( + z.object({ name: z.string().trim().min(1).max(200) }), + ctx.body, + ); + const scout = await ctx.db.scouter.findFirst({ + where: { + uuid: ctx.params.uuid, + sourceTeamNumber: ctx.collectionTeam, + archived: false, + }, + }); + if (!scout) notFound(); + await ctx.db.scouter.update({ + where: { uuid: scout.uuid, sourceTeamNumber: ctx.collectionTeam }, + data, + }); + return "done changing name to provided scouter"; + }, + ); + router.add( + "GET", + "/v1/manager/matchschedule/:tournament", + "collection", + async (ctx) => { + const slots = await ctx.db.teamMatchData.findMany({ + where: { + tournamentKey: ctx.params.tournament, + OR: [ + { matchType: { not: "PRACTICE" } }, + { matchType: "PRACTICE", practiceScheduled: true }, + ], + }, + select: { + teamNumber: true, + matchNumber: true, + matchType: true, + key: true, + alliance: true, + }, + orderBy: [{ matchType: "asc" }, { matchNumber: "asc" }, { key: "asc" }], + take: 10000, + }); + const matches = new Map< + string, + { + matchNumber: number; + matchType: number; + teams: { number: number; alliance: string | null }[]; + } + >(); + for (const row of slots) { + const key = row.matchType + ":" + row.matchNumber; + if (!matches.has(key)) + matches.set(key, { + matchNumber: row.matchNumber, + matchType: matchTypes[row.matchType], + teams: [], + }); + matches.get(key)!.teams.push({ + number: row.teamNumber, + alliance: + row.matchType === "PRACTICE" + ? null + : (row.alliance?.toLowerCase() ?? + (Number(row.key.at(-1)) < 3 ? "red" : "blue")), + }); + } + return { + tournamentKey: ctx.params.tournament, + matches: [...matches.values()], + }; + }, + ); +} diff --git a/apps/api/src/services/events.ts b/apps/api/src/services/events.ts new file mode 100644 index 000000000..7ca2ae6d4 --- /dev/null +++ b/apps/api/src/services/events.ts @@ -0,0 +1,553 @@ +import { loadDetailedReports } from "../repository.js"; +import { analysisBudget } from "../budget.js"; +import { prediction } from "../domain/prediction.js"; +import { HttpError } from "../errors.js"; +import { z } from "zod"; +import { + ServiceRouter, + input, + identifier, + positive, + team, + user, + notFound, +} from "../http/router.js"; +import { stationFields, stationSelect, matchTypes } from "./collection.js"; +import { sourceFilter } from "./reports.js"; +import { parseJson, type Analyze } from "./analysis.js"; +import { rankingSchema, type OfficialReader } from "../official.js"; +import { legacyAnalysisScope as accessScope } from "../auth.js"; +import { analyzeReports } from "../metrics/engine.js"; +import { season2026 } from "../metrics/season2026.js"; + +const statusSchema = z.record( + z.string(), + z.object({ + qual: z + .object({ + ranking: z + .object({ + rank: z.number().nullish(), + ranking_points: z.number().nullish(), + matches_played: z.number().nullish(), + sort_orders: z.array(z.number()).nullish(), + }) + .nullish(), + }) + .nullish(), + }), +); +export function registerEvents( + router: ServiceRouter, + analyze: Analyze, + official: OfficialReader, +) { + router.add( + "GET", + "/v1/manager/upcoming-entered-tournaments", + "session", + async (ctx) => { + if (!user(ctx).teamNumber) return []; + const rows = await ctx.db.tournament.findMany({ + where: { + teams: { some: { teamNumber: user(ctx).teamNumber! } }, + startDate: { gte: new Date(Date.now() - 86400000) }, + }, + orderBy: [{ startDate: "asc" }, { key: "asc" }], + take: 20, + }); + return rows + .filter((row) => { + const parts = new Intl.DateTimeFormat("en-CA", { + timeZone: row.timezone ?? "UTC", + year: "numeric", + month: "2-digit", + day: "2-digit", + }).formatToParts(new Date()); + const get = (type: string) => + parts.find((p) => p.type === type)?.value; + return ( + row.date !== null && + row.date > get("year") + "-" + get("month") + "-" + get("day") + ); + }) + .slice(0, 2) + .map((row) => ({ + key: row.key, + name: row.name, + city: row.location, + startDate: row.date, + week: row.week === null ? null : row.week + 1, + })); + }, + ); + router.add( + "GET", + "/v1/manager/tournament/:tournament/rankedTeams", + "session", + async (ctx) => { + const event = input(identifier, ctx.params.tournament); + const rows = await ctx.db.team.findMany({ + where: { matchData: { some: { tournamentKey: event } } }, + include: { + seasons: { + where: { seasonYear: Number(event.slice(0, 4)) }, + select: { avatar: true }, + take: 1, + }, + }, + take: 1000, + }); + if (!rows.length) notFound("Tournament or teams not found"); + const statuses = await official(event, "teams/statuses", statusSchema); + return rows.map(({ seasons, ...row }) => { + const rank = statuses["frc" + row.number]?.qual?.ranking; + return { + ...row, + avatar: seasons[0]?.avatar ?? null, + rank: rank?.rank ?? null, + rankingPoints: + rank?.ranking_points ?? + (rank?.sort_orders?.length && + rank.matches_played !== null && + rank.matches_played !== undefined + ? Math.round(rank.sort_orders[0] * rank.matches_played) + : null), + matchesPlayed: rank?.matches_played ?? null, + }; + }); + }, + ); + router.add( + "GET", + "/v1/manager/team-tournament-status", + "verified", + async (ctx) => { + const data = input( + z.object({ tournamentKey: identifier, teamNumber: positive }), + ctx.query, + ); + const [row, count, statuses] = await Promise.all([ + ctx.db.team.findUnique({ + where: { number: data.teamNumber }, + select: { number: true, name: true }, + }), + ctx.db.teamMatchData.count({ + where: { + tournamentKey: data.tournamentKey, + teamNumber: data.teamNumber, + matchType: "QUALIFICATION", + }, + }), + official(data.tournamentKey, "teams/statuses", statusSchema), + ]); + if (!row || !count) notFound("Team not in tournament"); + const r = statuses["frc" + row.number]?.qual?.ranking; + return { + ...row, + rank: r?.rank ?? null, + rankingPoints: + r?.ranking_points ?? + (r?.sort_orders?.length && r.matches_played != null + ? Math.round(r.sort_orders[0] * r.matches_played) + : null), + matchesPlayed: r?.matches_played ?? null, + matchesTotal: count, + }; + }, + ); + router.add( + "GET", + "/v1/manager/matches/:tournament", + "verified", + async (ctx) => { + const event = input(identifier, ctx.params.tournament), + filter = parseJson(z.array(positive).max(6), ctx.query.teams, []); + const own = team(ctx), + sources = sourceFilter(ctx); + const [slots, shifts] = await Promise.all([ + ctx.db.teamMatchData.findMany({ + where: { + tournamentKey: event, + ...(ctx.query.includePractice === "true" + ? {} + : { matchType: { not: "PRACTICE" } }), + }, + include: { + match: { select: { status: true } }, + scoutReports: { + where: { + training: false, + OR: [sources, { scouter: { sourceTeamNumber: own } }], + }, + select: { + scouter: { + select: { name: true, uuid: true, sourceTeamNumber: true }, + }, + }, + }, + }, + orderBy: [{ matchNumber: "asc" }, { key: "asc" }], + take: 10000, + }), + ctx.db.scouterScheduleShift.findMany({ + where: { sourceTeamNumber: own, tournamentKey: event }, + include: stationSelect, + take: 1000, + }), + ]); + const lastQual = Math.max( + 0, + ...slots + .filter((s) => s.matchType === "QUALIFICATION") + .map((s) => s.matchNumber), + ); + const groups = new Map(); + for (const slot of slots) { + if ( + slot.matchType === "PRACTICE" && + !slot.practiceScheduled && + !slot.scoutReports.length + ) + continue; + const key = slot.matchType + ":" + slot.matchNumber; + if (!groups.has(key)) groups.set(key, []); + groups.get(key)!.push(slot); + } + const rows = [...groups.values()].sort( + (a, b) => + (a[0].matchType === "PRACTICE" + ? -1 + : a[0].matchType === "QUALIFICATION" + ? 0 + : 1) - + (b[0].matchType === "PRACTICE" + ? -1 + : b[0].matchType === "QUALIFICATION" + ? 0 + : 1) || a[0].matchNumber - b[0].matchNumber, + ); + return rows + .filter((rows) => + filter.every((n) => rows.some((s) => s.teamNumber === n)), + ) + .map((rows) => { + rows.sort( + (a, b) => + (a.alliance === "BLUE" ? 3 : 0) + + (a.station ?? Number(a.key.at(-1))) - + ((b.alliance === "BLUE" ? 3 : 0) + + (b.station ?? Number(b.key.at(-1)))), + ); + const first = rows[0], + ordinal = + first.matchType === "QUALIFICATION" + ? first.matchNumber + : lastQual + first.matchNumber; + const shift = shifts.find( + (s) => + s.startMatchOrdinalNumber <= ordinal && + s.endMatchOrdinalNumber >= ordinal, + ); + const teams = rows.map((row, i) => { + const ownReports = row.scoutReports.filter( + (r) => r.scouter.sourceTeamNumber === own, + ); + const scouters = ownReports.map((r) => ({ + name: r.scouter.name, + scouted: true, + })); + for (const scout of first.matchType !== "PRACTICE" + ? (shift?.[stationFields[i]] ?? []) + : []) { + if (!ownReports.some((r) => r.scouter.uuid === scout.uuid)) + scouters.push({ name: scout.name, scouted: false }); + } + return { + number: row.teamNumber, + scouters, + externalReports: row.scoutReports.length - ownReports.length, + }; + }); + return { + matchNumber: first.matchNumber, + matchType: matchTypes[first.matchType], + scouted: rows.some((s) => s.scoutReports.length > 0), + finished: first.match?.status === "COMPLETED", + ...(first.matchType === "PRACTICE" + ? { teams } + : Object.fromEntries( + teams.map((value, i) => ["team" + (i + 1), value]), + )), + }; + }); + }, + ); + router.add("GET", "/v1/manager/scouterreports", "lead", async (ctx) => { + const data = input( + z.object({ + scouterUuid: identifier.optional(), + tournamentKey: identifier.optional(), + }), + ctx.query, + ); + return ctx.db.scoutReport.findMany({ + where: { + training: false, + scouter: { sourceTeamNumber: team(ctx) }, + ...(data.scouterUuid ? { scouterUuid: data.scouterUuid } : {}), + ...(data.tournamentKey + ? { teamMatchData: { tournamentKey: data.tournamentKey } } + : {}), + }, + select: { + uuid: true, + teamMatchKey: true, + startTime: true, + reliability: true, + scouter: { select: { uuid: true, name: true } }, + teamMatchData: { + select: { + key: true, + teamNumber: true, + matchType: true, + matchNumber: true, + tournamentKey: true, + tournament: { select: { key: true, name: true } }, + }, + }, + }, + orderBy: { startTime: "desc" }, + take: 500, + }); + }); + router.add("GET", "/v1/manager/match-results-page", "verified", async (ctx) => + analysisBudget(async () => { + const key = input(identifier, ctx.query.matchKey); + const metrics = [ + "totalPoints", + "totalDefenseTime", + "totalFuelOutputted", + "autoPoints", + "teleopPoints", + ]; + const slots = await ctx.db.teamMatchData.findMany({ + where: { + OR: [ + { matchKey: key }, + { key: { in: Array.from({ length: 6 }, (_, i) => key + "_" + i) } }, + ], + }, + include: { tournament: true }, + take: 6, + }); + if (slots.length !== 6) notFound("Match not found"); + const reports = await loadDetailedReports( + ctx.db, + accessScope(user(ctx)), + { teamMatchKey: { in: slots.map((s) => s.key) } }, + { text: true }, + ); + const rows = slots.map((slot) => ({ + ...slot, + scoutReports: reports.filter( + (report) => report.teamMatchKey === slot.key, + ), + })); + const results = rows.map((row) => { + const reports = row.scoutReports.map((report) => ({ + ...report, + teamNumber: row.teamNumber, + matchKey: row.key, + tournamentKey: row.tournamentKey, + tournamentDate: row.tournament.date ?? "", + })); + const data = analyzeReports( + reports, + { teams: [row.teamNumber], metrics, season: 2026, timeline: false }, + season2026, + ).teams[String(row.teamNumber)].metrics; + return { + row, + values: Object.fromEntries( + metrics.map((m) => [ + m, + typeof data[m].value === "number" ? data[m].value : 0, + ]), + ), + }; + }); + const alliance = (color: string) => { + const selected = results.filter( + (r) => + r.row.alliance === color || + (r.row.alliance === null && + Number(r.row.key.at(-1)) < 3 === (color === "RED")), + ); + return { + teams: selected.map(({ row, values }) => ({ + teamNumber: row.teamNumber, + pointsScored: values.totalPoints, + reports: row.scoutReports.map(({ scouter, events, ...report }) => ({ + ...report, + scouterUuid: + scouter.sourceTeamNumber === team(ctx) + ? report.scouterUuid + : undefined, + events, + })), + role: [ + ...new Set(row.scoutReports.flatMap((r) => r.robotRoles)), + ].map((r) => + [ + "CYCLING", + "SCORING", + "FEEDING", + "DEFENDING", + "IMMOBILE", + ].indexOf(r), + ), + })), + ...Object.fromEntries( + metrics.map((m) => [ + m, + selected.reduce((sum, r) => sum + r.values[m], 0), + ]), + ), + }; + }; + return { red: alliance("RED"), blue: alliance("BLUE") }; + }), + ); + router.add("GET", "/v1/analysis/pitdisplay", "session", async (ctx) => { + const data = input( + z.object({ + team: positive, + tournamentKey: identifier, + topTeamCount: z.coerce.number().int().min(0).max(100).default(10), + teamsAboveCount: z.coerce.number().int().min(0).max(100).default(3), + }), + ctx.query, + ); + const [matches, event, ranks] = await Promise.all([ + ctx.db.match.findMany({ + where: { tournamentKey: data.tournamentKey }, + include: { teamSlots: true }, + orderBy: { displayOrder: "asc" }, + take: 1000, + }), + official( + data.tournamentKey, + "", + z.object({ webcasts: z.array(z.json()).default([]) }), + ), + official(data.tournamentKey, "rankings", rankingSchema), + ]); + if ( + !matches.some((m) => m.teamSlots.some((s) => s.teamNumber === data.team)) + ) + notFound("Team not in tournament"); + const rankRows = (ranks.rankings ?? []).map((r) => ({ + type: "team", + number: Number(r.team_key.slice(3)), + rank: r.rank, + rankingPoints: r.extra_stats?.[0] ?? r.sort_orders?.[0] ?? 0, + })); + const index = rankRows.findIndex((r) => r.number === data.team); + const rankingBlocks = + index < data.topTeamCount + data.teamsAboveCount + ? rankRows + : [ + ...rankRows.slice(0, data.topTeamCount), + { + type: "collapsedDivider", + teamCount: index - data.teamsAboveCount - data.topTeamCount, + }, + ...rankRows.slice(index - data.teamsAboveCount), + ]; + const current = matches.findIndex( + (m) => !["COMPLETED", "CANCELED"].includes(m.status), + ); + const next = + current < 0 + ? -1 + : matches.findIndex( + (m, i) => + i >= current && + m.status !== "COMPLETED" && + m.teamSlots.some((s) => s.teamNumber === data.team), + ); + const chosen = [current, current < 0 ? -1 : current + 1, next].map( + (i) => matches[i], + ); + const teams = [ + ...new Set( + chosen.flatMap((m) => m?.teamSlots.map((s) => s.teamNumber) ?? []), + ), + ]; + const predictionData = teams.length + ? await analyze(accessScope(user(ctx)), { + teams, + metrics: ["totalPoints"], + season: 2026, + timeline: true, + }) + : null; + const format = (i: number) => { + const match = matches[i]; + if (!match) return null; + const red = match.teamSlots + .filter((s) => s.alliance === "RED") + .sort((a, b) => (a.station ?? 0) - (b.station ?? 0)) + .map((s) => s.teamNumber); + const blue = match.teamSlots + .filter((s) => s.alliance === "BLUE") + .sort((a, b) => (a.station ?? 0) - (b.station ?? 0)) + .map((s) => s.teamNumber); + let odds: ReturnType | undefined; + if (predictionData) { + try { + odds = prediction( + [...red, ...blue].map((team) => + (predictionData.teams[String(team)]?.timeline ?? []).flatMap( + (point) => + typeof point.metrics.totalPoints.value === "number" + ? [point.metrics.totalPoints.value] + : [], + ), + ), + ); + } catch (error) { + if (!(error instanceof HttpError) || error.status !== 422) + throw error; + } + } + return { + key: match.key, + alliances: { + red: { teams: red, winPrediction: odds?.redWinning }, + blue: { teams: blue, winPrediction: odds?.blueWinning }, + }, + }; + }; + const previous = matches.findLastIndex( + (m, i) => i < next && m.teamSlots.some((s) => s.teamNumber === data.team), + ); + return { + matches: { + nowPlaying: format(current), + next: format(current < 0 ? -1 : current + 1), + teamNext: format(next), + }, + teamMatchTimeline: + next >= 0 + ? { + matchCount: next - Math.max(0, previous), + currentMatchCount: current - Math.max(0, previous) + 1, + } + : {}, + webcasts: event.webcasts, + rankingBlocks, + }; + }); +} diff --git a/apps/api/src/services/gamePredictions.ts b/apps/api/src/services/gamePredictions.ts new file mode 100644 index 000000000..3d510af47 --- /dev/null +++ b/apps/api/src/services/gamePredictions.ts @@ -0,0 +1,44 @@ +import { gamePredictionRequestSchema } from "@lovat/api"; +import { games, type GameCatalog } from "@lovat/games"; +import { accessScope } from "../auth.js"; +import { ServiceRouter, input, user } from "../http/router.js"; +import { HttpError } from "../errors.js"; +import type { Analyze } from "./analysis.js"; +export function registerGamePredictions( + router: ServiceRouter, + analyze: Analyze, + catalog: GameCatalog = games, +) { + router.add("POST", "/v3/prediction", "session", async (ctx) => { + const request = input(gamePredictionRequestSchema, ctx.body), + game = catalog.get(request.season, request.gameVersion); + const size = game.descriptor.rules.allianceSize; + if ( + request.red.length !== size || + request.blue.length !== size || + new Set([...request.red, ...request.blue]).size !== size * 2 + ) + throw new HttpError( + 400, + "INVALID_ALLIANCES", + "Select the required number of distinct teams for this game", + ); + if (!game.prediction) + throw new HttpError( + 409, + "PREDICTION_UNAVAILABLE", + "Predictions are not configured for this game", + ); + const data = await analyze(accessScope(user(ctx)), { + teams: [...request.red, ...request.blue], + metrics: [...game.prediction.metrics], + season: request.season, + gameVersion: game.descriptor.version, + timeline: true, + }); + return game.prediction.calculate({ + red: request.red.map((number) => data.teams[String(number)]), + blue: request.blue.map((number) => data.teams[String(number)]), + }); + }); +} diff --git a/apps/api/src/services/gameReports.ts b/apps/api/src/services/gameReports.ts new file mode 100644 index 000000000..7814844e6 --- /dev/null +++ b/apps/api/src/services/gameReports.ts @@ -0,0 +1,110 @@ +import { z } from "zod"; +import { gameReportEnvelopeSchema } from "@lovat/api"; +import { games, type GameCatalog } from "@lovat/games"; +import { ServiceRouter, Reply, input, notFound } from "../http/router.js"; +import { HttpError } from "../errors.js"; +import { writeGameReport } from "../gameWrite.js"; +import { + write2026Report, + gameEnvelope2026, +} from "../gameAdapters/2026Write.js"; +export function registerGameReports( + router: ServiceRouter, + catalog: GameCatalog = games, +) { + router.add("POST", "/v3/reports", "collection", async (ctx) => { + const envelope = input(gameReportEnvelopeSchema, ctx.body); + const deviceId = input( + z.string().min(1).max(200), + ctx.headers["x-device-id"], + ); + const game = catalog.get(envelope.season, envelope.gameVersion); + if (game.descriptor.id !== envelope.gameId) + throw new HttpError( + 400, + "GAME_ID_MISMATCH", + "Game does not match the selected season/version", + ); + if (ctx.headers["x-scouter-uuid"] !== envelope.scouterUuid) + throw new HttpError( + 403, + "SCOUTER_MISMATCH", + "Report must belong to the selected scout", + ); + const actor = + (await ctx.db.scouter.findFirst({ + where: { + uuid: envelope.scouterUuid, + sourceTeamNumber: ctx.collectionTeam, + archived: false, + }, + })) ?? notFound("Scout not found on this team"); + const tournament = await ctx.db.tournament.findUnique({ + where: { key: envelope.tournamentKey }, + select: { seasonYear: true }, + }); + if (!tournament || tournament.seasonYear !== envelope.season) + throw new HttpError( + 409, + "GAME_SEASON_MISMATCH", + "Tournament does not match the report's season", + ); + const identity = { + tournamentKey: envelope.tournamentKey, + teamNumber: envelope.teamNumber, + matchNumber: envelope.matchNumber, + matchType: envelope.matchType, + }; + let slot = await ctx.db.teamMatchData.findFirst({ where: identity }); + if (!slot && envelope.matchType === "PRACTICE") { + const key = + envelope.tournamentKey + + "_pm" + + envelope.matchNumber + + "_" + + envelope.teamNumber; + slot = await ctx.db.teamMatchData.upsert({ + where: { key }, + create: { key, ...identity }, + update: {}, + }); + } + if (!slot) notFound("Team not found in match"); + const data = game.validate(envelope.data, envelope.reportVersion, { + startTime: envelope.startTime, + endTime: envelope.endTime, + }); + const writers = new Map([ + [ + "frc-2026:1", + () => + ctx.db.$transaction((tx) => + write2026Report( + tx, + gameEnvelope2026(envelope, data), + actor, + { key: slot!.key, tournament }, + deviceId, + envelope.endTime, + ), + ), + ], + ]); + const created = await (writers.get( + game.descriptor.id + ":" + game.descriptor.version, + )?.() ?? + ctx.db.$transaction((tx) => + writeGameReport(tx, game, envelope, slot!.key, actor.sourceTeamNumber), + )); + return new Reply( + { + uuid: envelope.uuid, + created, + gameId: envelope.gameId, + gameVersion: envelope.gameVersion, + reportVersion: envelope.reportVersion, + }, + created ? 201 : 200, + ); + }); +} diff --git a/apps/api/src/services/index.ts b/apps/api/src/services/index.ts new file mode 100644 index 000000000..80d197db0 --- /dev/null +++ b/apps/api/src/services/index.ts @@ -0,0 +1,85 @@ +import { registerGamePredictions } from "./gamePredictions.js"; +import { registerGameReports } from "./gameReports.js"; +import type { GameCatalog } from "@lovat/games"; +import { createLegacyOpenApiDocument } from "@lovat/api/legacy"; +import { createOfficialReader, type OfficialReader } from "../official.js"; +import { ServiceRouter } from "../http/router.js"; +import { registerAccounts } from "./accounts.js"; +import { registerAnalysis, type Analyze } from "./analysis.js"; +import { registerApiKeys } from "./apiKeys.js"; +import { registerCatalog } from "./catalog.js"; +import { registerCollection } from "./collection.js"; +import { registerEvents } from "./events.js"; +import { registerOnboarding } from "./onboarding.js"; +import { registerPicklists } from "./picklists.js"; +import { registerPredictions } from "./predictions.js"; +import { registerReports } from "./reports.js"; +import { registerSettings } from "./settings.js"; +import { registerShifts } from "./shifts.js"; +import { registerSlack, type SlackOptions } from "./slack.js"; +import { registerTraining } from "./training.js"; +export interface ServiceOptions { + baseUrl: string; + commit: string; + analyze: Analyze; + gameCatalog?: GameCatalog; + official?: OfficialReader; + website?: string; + slack?: SlackOptions; +} +export function createServices(options: ServiceOptions) { + const router = new ServiceRouter(); + const official = options.official ?? createOfficialReader(undefined); + const website = options.website ?? "https://lovat.app"; + const legacyAnalyze: Analyze = (scope, request) => + options.analyze(scope, { ...request, gameVersion: 1 }); + const modules: [string, () => void][] = [ + ["accounts", () => registerAccounts(router)], + ["apiKeys", () => registerApiKeys(router)], + ["catalog", () => registerCatalog(router)], + ["collection", () => registerCollection(router)], + ["picklists", () => registerPicklists(router)], + ["reports", () => registerReports(router)], + ["gameReports", () => registerGameReports(router, options.gameCatalog)], + [ + "gamePredictions", + () => + registerGamePredictions(router, options.analyze, options.gameCatalog), + ], + ["settings", () => registerSettings(router, website)], + ["shifts", () => registerShifts(router)], + ["analysis", () => registerAnalysis(router, legacyAnalyze, official)], + ["predictions", () => registerPredictions(router, legacyAnalyze, official)], + ["training", () => registerTraining(router)], + ["events", () => registerEvents(router, legacyAnalyze, official)], + ["onboarding", () => registerOnboarding(router, website)], + [ + "slack", + () => + registerSlack(router, options.slack ?? { baseUrl: options.baseUrl }), + ], + [ + "index", + () => { + router.add("GET", "/status", "public", async () => "Server running"); + router.add("GET", "/version", "public", async () => ({ + version: "26.0.0", + gitCommit: options.commit, + })); + router.add("GET", "/v1/doc.json", "public", async () => + createLegacyOpenApiDocument({ + version: "26.0.0", + baseUrl: options.baseUrl, + }), + ); + }, + ], + ]; + for (const [name, register] of modules) { + const start = router.endpoints.length; + register(); + for (const endpoint of router.endpoints.slice(start)) + endpoint.module = "apps/api/src/services/" + name + ".ts"; + } + return router; +} diff --git a/apps/api/src/services/onboarding.ts b/apps/api/src/services/onboarding.ts new file mode 100644 index 000000000..1c351b9e7 --- /dev/null +++ b/apps/api/src/services/onboarding.ts @@ -0,0 +1,190 @@ +import { randomBytes } from "node:crypto"; +import { z } from "zod"; +import { + ServiceRouter, + input, + user, + team, + positive, + notFound, +} from "../http/router.js"; +import { verificationEmail } from "../domain/email.js"; +import { enqueue, recordAnalysisChange } from "../domain/effects.js"; +import { HttpError } from "../errors.js"; +export function registerOnboarding(router: ServiceRouter, website: string) { + router.add("POST", "/v1/manager/onboarding/team", "jwt", async (ctx) => { + const data = input( + z.object({ number: positive, email: z.email() }), + ctx.body, + ); + if (user(ctx).teamNumber) + throw new HttpError( + 409, + "ALREADY_ON_TEAM", + "Leave your current team before registering another", + ); + await ctx.db.$transaction(async (tx) => { + const toggle = await tx.featureToggle.findUnique({ + where: { feature: "fullRegistration" }, + }); + await tx.registeredTeam.create({ + data: { + number: data.number, + email: data.email, + code: randomBytes(6).toString("hex").toUpperCase(), + teamApproved: toggle?.enabled === false, + }, + }); + await tx.user.update({ + where: { id: user(ctx).id }, + data: { + teamNumber: data.number, + role: "SCOUTING_LEAD", + teamSourceRule: { mode: "INCLUDE", items: [data.number] }, + }, + }); + await verificationEmail(tx, data.email, data.number, website); + }); + return "verification email sent"; + }); + router.add( + "POST", + "/v1/manager/onboarding/resendverificationemail", + "jwt", + async (ctx) => { + const number = team(ctx); + if (user(ctx).role !== "SCOUTING_LEAD") + throw new HttpError( + 403, + "LEAD_REQUIRED", + "A scouting lead is required", + ); + const row = + (await ctx.db.registeredTeam.findUnique({ where: { number } })) ?? + notFound(); + await ctx.db.$transaction((tx) => + verificationEmail(tx, row.email, number, website), + ); + return "verification email sent"; + }, + ); + router.add( + "POST", + "/v1/manager/onboarding/verifyemail", + "signed", + async (ctx) => { + const data = input( + z.object({ code: z.string().min(1).max(128) }), + ctx.body, + ); + await ctx.db.$transaction(async (tx) => { + const row = + (await tx.emailVerificationRequest.findUnique({ + where: { verificationCode: data.code.toLowerCase() }, + })) ?? notFound("CODE_NOT_RECOGNIZED"); + if (row.expiresAt.getTime() <= Date.now()) + throw new HttpError(400, "CODE_EXPIRED", "Verification code expired"); + const changed = await tx.registeredTeam.updateMany({ + where: { number: row.teamNumber, email: row.email }, + data: { emailVerified: true }, + }); + if (!changed.count) + throw new HttpError( + 409, + "EMAIL_CHANGED", + "Request verification for your current email", + ); + await tx.emailVerificationRequest.deleteMany({ + where: { teamNumber: row.teamNumber }, + }); + }); + return "Team email successfully verified"; + }, + ); + router.add( + "GET", + "/v1/manager/registeredteams/:team/registrationstatus", + "session", + async (ctx) => { + const number = input(positive, ctx.params.team); + const [row, toggle] = await Promise.all([ + ctx.db.registeredTeam.findUnique({ where: { number } }), + ctx.db.featureToggle.findUnique({ + where: { feature: "fullRegistration" }, + }), + ]); + if (!row) return { status: "NOT_STARTED" }; + const owner = + user(ctx).teamNumber === number && user(ctx).role === "SCOUTING_LEAD"; + if (row.emailVerified && row.teamApproved) + return { + status: + user(ctx).teamNumber === number + ? "REGISTERED_ON_TEAM" + : "REGISTERED_OFF_TEAM", + }; + if (!owner) return { status: "PENDING" }; + if (!row.emailVerified) + return { status: "PENDING_EMAIL_VERIFICATION", email: row.email }; + if (toggle?.enabled !== false && !row.website) + return { status: "PENDING_WEBSITE" }; + return { status: "PENDING_TEAM_VERIFICATION", teamEmail: row.email }; + }, + ); + router.add( + "POST", + "/v1/manager/registeredteams/:team/approve", + "signed", + async (ctx) => { + const number = input(positive, ctx.params.team); + await ctx.db.registeredTeam.update({ + where: { number }, + data: { teamApproved: true }, + }); + return { number, teamApproved: true }; + }, + ); + router.add( + "POST", + "/v1/manager/registeredteams/:team/reject", + "signed", + async (ctx) => { + const number = input(positive, ctx.params.team); + await ctx.db.$transaction(async (tx) => { + const affected = await tx.teamMatchData.findMany({ + where: { + scoutReports: { some: { scouter: { sourceTeamNumber: number } } }, + }, + distinct: ["teamNumber"], + select: { teamNumber: true }, + }); + await tx.user.updateMany({ + where: { teamNumber: number }, + data: { teamNumber: null, role: "ANALYST" }, + }); + await tx.registeredTeam.delete({ where: { number } }); + for (const team of affected) + await recordAnalysisChange(tx, team.teamNumber); + }); + return "Team removed"; + }, + ); + router.add("POST", "/v1/manager/emailTeamCode", "public", async (ctx) => { + const number = input(positive, ctx.query.teamNumber); + + const row = + (await ctx.db.registeredTeam.findUnique({ where: { number } })) ?? + notFound(); + const window = Math.floor(Date.now() / 120000); + await ctx.db.$transaction((tx) => + enqueue(tx, "team-code:" + number + ":" + window, { + kind: "email.send", + to: row.email, + subject: "Lovat Team Code", + text: "Your Lovat team code is: " + row.code, + }), + ); + const [local, domain] = row.email.split("@"); + return { email: local.slice(0, 1) + "***@" + domain }; + }); +} diff --git a/apps/api/src/services/picklists.ts b/apps/api/src/services/picklists.ts new file mode 100644 index 000000000..e648ad482 --- /dev/null +++ b/apps/api/src/services/picklists.ts @@ -0,0 +1,123 @@ +import { z } from "zod"; +import { + ServiceRouter, + input, + team, + user, + writable, + notFound, + type Context, +} from "../http/router.js"; + +const weightNames = [ + "totalPoints", + "autoPoints", + "teleopPoints", + "climbResult", + "autoClimb", + "defenseEffectiveness", + "driverAbility", + "contactDefenseTime", + "campingDefenseTime", + "totalDefensiveTime", + "totalFuelThroughput", + "totalFuelFed", + "feedingRate", + "scoringRate", + "estimatedSuccessfulFuelRate", + "estimatedTotalFuelScored", +] as const; +const weightShape = Object.fromEntries( + weightNames.map((name) => [name, z.number().default(0)]), +) as Record<(typeof weightNames)[number], z.ZodDefault>; +const sharedSchema = z.object({ + name: z.string().min(1).max(200), + ...weightShape, +}); +const mutableSchema = z.object({ + name: z.string().min(1).max(200), + teams: z.array(z.number().int().nonnegative()).max(1000), + tournamentKey: z.string().optional(), +}); +export function registerPicklists(router: ServiceRouter) { + for (const mutable of [false, true]) { + const path = mutable + ? "/v1/manager/mutablepicklists" + : "/v1/manager/picklists"; + const label = mutable ? "mutable picklist" : "picklist"; + const scope = (ctx: Context) => ({ author: { teamNumber: team(ctx) } }); + router.add("GET", path, "verified", async (ctx) => + mutable + ? ctx.db.mutablePicklist.findMany({ + where: scope(ctx), + select: { + name: true, + uuid: true, + tournamentKey: true, + author: { select: { username: true } }, + }, + take: 1000, + }) + : ctx.db.sharedPicklist.findMany({ + where: scope(ctx), + select: { + name: true, + uuid: true, + author: { select: { username: true } }, + }, + take: 1000, + }), + ); + router.add("GET", path + "/:uuid", "verified", async (ctx) => { + const where = { uuid: ctx.params.uuid, ...scope(ctx) }; + const row = mutable + ? await ctx.db.mutablePicklist.findFirst({ where }) + : await ctx.db.sharedPicklist.findFirst({ where }); + return row ?? notFound("Picklist not found"); + }); + router.add("POST", path, "verified", async (ctx) => { + writable(ctx); + team(ctx); + if (mutable) + await ctx.db.mutablePicklist.create({ + data: { ...input(mutableSchema, ctx.body), authorId: user(ctx).id }, + }); + else { + const data = input(sharedSchema, ctx.body); + + await ctx.db.sharedPicklist.create({ + data: { ...data, authorId: user(ctx).id }, + }); + } + return label + " added"; + }); + router.add("PUT", path + "/:uuid", "verified", async (ctx) => { + writable(ctx); + const where = { uuid: ctx.params.uuid, ...scope(ctx) }; + if (mutable) { + const data = input( + mutableSchema.omit({ tournamentKey: true }), + ctx.body, + ); + await ctx.db.mutablePicklist.update({ + where, + data: { ...data, authorId: user(ctx).id }, + }); + } else { + const data = input(sharedSchema, ctx.body); + await ctx.db.sharedPicklist.update({ + where, + data: { ...data, authorId: user(ctx).id }, + }); + } + return label + " updated"; + }); + router.add("DELETE", path + "/:uuid", "verified", async (ctx) => { + writable(ctx); + const where = { uuid: ctx.params.uuid, ...scope(ctx) }; + if (mutable) await ctx.db.mutablePicklist.delete({ where }); + else await ctx.db.sharedPicklist.delete({ where }); + return label + " deleted"; + }); + } +} diff --git a/apps/api/src/services/predictions.ts b/apps/api/src/services/predictions.ts new file mode 100644 index 000000000..606dc2124 --- /dev/null +++ b/apps/api/src/services/predictions.ts @@ -0,0 +1,516 @@ +import { rankingPoints2026, rules2026 } from "@lovat/games/2026"; +import { analysisBudget } from "../budget.js"; +import { loadDetailedReports } from "../repository.js"; +import { z } from "zod"; +import { + ServiceRouter, + Reply, + input, + user, + positive, + identifier, + type Context, +} from "../http/router.js"; +import { legacyAnalysisScope as accessScope } from "../auth.js"; +import type { AnalysisResponse } from "@lovat/api"; +import type { Analyze } from "./analysis.js"; +import { autoPaths, parseJson } from "./analysis.js"; +import { season2026 } from "../metrics/season2026.js"; +import { analyzeReports } from "../metrics/engine.js"; +import { sourceFilter } from "./reports.js"; +import { prediction, csv } from "../domain/prediction.js"; +import { rankingSchema, type OfficialReader } from "../official.js"; +import { HttpError } from "../errors.js"; +const names = ["red1", "red2", "red3", "blue1", "blue2", "blue3"] as const; +const numeric = season2026 + .metadata() + .filter((m) => m.kind === "number") + .map((m) => m.id); +const value = (data: AnalysisResponse, team: number, id: string) => { + const n = data.teams[String(team)]?.metrics[id]?.value; + return typeof n === "number" ? n : 0; +}; +const weights: Record = { + totalPoints: "totalPoints", + autoPoints: "autoPoints", + teleopPoints: "teleopPoints", + driverAbility: "driverAbility", + autoClimb: "autoClimbStartTime", + defenseEffectiveness: "defenseEffectiveness", + contactDefenseTime: "contactDefenseTime", + campingDefenseTime: "campingDefenseTime", + totalDefensiveTime: "totalDefenseTime", + totalFuelThroughput: "totalFuelOutputted", + totalFuelFed: "totalBallsFed", + feedingRate: "feedingRate", + scoringRate: "fuelPerSecond", +}; +const valid = { + training: false, + reliability: { + in: ["VERIFIED", "UNVERIFIED"] as ("VERIFIED" | "UNVERIFIED")[], + }, +}; +export function registerPredictions( + router: ServiceRouter, + analyze: Analyze, + official: OfficialReader, +) { + const calculate = ( + ctx: Context, + teams: number[], + metrics: string[], + timeline = false, + ) => + analyze(accessScope(user(ctx)), { + teams: [...new Set(teams)], + metrics, + season: 2026, + timeline, + }); + const alliance = async ( + ctx: Context, + teams: number[], + data?: AnalysisResponse, + ) => { + const result = + data ?? + (await calculate(ctx, teams, [ + "totalPoints", + "robotRole", + "l1StartTime", + "l2StartTime", + "l3StartTime", + "totalFuelOutputted", + "totalBallThroughput", + ])); + const paths = await Promise.all(teams.map((team) => autoPaths(ctx, team))); + const sum = (metric: string) => + teams.reduce((s, team) => s + value(result, team, metric), 0); + return { + totalPoints: sum("totalPoints"), + teams: teams.map((team, i) => { + const distribution = + result.teams[String(team)].metrics.robotRole?.value; + const role = + distribution && + typeof distribution === "object" && + !Array.isArray(distribution) + ? Object.entries(distribution).sort( + (a, b) => Number(b[1]) - Number(a[1]), + )[0]?.[0] + : "IMMOBILE"; + return { + team, + role: [ + "CYCLING", + "SCORING", + "FEEDING", + "DEFENDING", + "IMMOBILE", + ].indexOf(role ?? "IMMOBILE"), + averagePoints: value(result, team, "totalPoints"), + paths: paths[i], + }; + }), + ...Object.fromEntries( + ["l1StartTime", "l2StartTime", "l3StartTime"].map((metric) => [ + metric, + teams.map((team) => value(result, team, metric) || null), + ]), + ), + totalFuelOutputted: sum("totalFuelOutputted"), + totalBallThroughput: sum("totalBallThroughput"), + }; + }; + router.add("GET", "/v1/analysis/alliance", "session", async (ctx) => + alliance( + ctx, + ["team1", "team2", "team3"].map((name) => + input(positive, ctx.query[name]), + ), + ), + ); + router.add("GET", "/v1/analysis/matchprediction", "session", async (ctx) => { + const teams = names.map((name) => input(positive, ctx.query[name])); + const data = await calculate(ctx, teams, ["totalPoints"], true); + const odds = prediction( + teams.map((team) => + (data.teams[String(team)].timeline ?? []).flatMap((point) => { + const n = point.metrics.totalPoints.value; + return typeof n === "number" ? [n] : []; + }), + ), + ); + return { + ...Object.fromEntries(names.map((name, i) => [name, teams[i]])), + ...odds, + redAlliance: await alliance(ctx, teams.slice(0, 3)), + blueAlliance: await alliance(ctx, teams.slice(3)), + }; + }); + router.add("GET", "/v1/analysis/picklist", "session", async (ctx) => { + if (!ctx.query.tournamentKey) return { teams: [] }; + const event = input(identifier, ctx.query.tournamentKey); + const slots = await ctx.db.teamMatchData.groupBy({ + by: ["teamNumber"], + where: { tournamentKey: event, matchType: { not: "PRACTICE" } }, + }); + const teams = slots.map((s) => s.teamNumber); + if (teams.length > 100) + throw new HttpError(413, "TOO_MANY_TEAMS", "Select a smaller event"); + if (!teams.length) return { teams: [] }; + const active = Object.entries(weights) + .map(([name, metric]) => ({ + name, + metric, + weight: input( + z.coerce.number().finite().min(-1000).max(1000), + ctx.query[name] ?? 0, + ), + })) + .filter((w) => w.weight !== 0); + if (!active.length) + throw new HttpError( + 400, + "EMPTY_WEIGHTS", + "Choose at least one metric weight", + ); + const flags = parseJson(z.array(z.string()).max(64), ctx.query.flags, []); + const known = flags.filter((flag) => numeric.includes(flag)); + const data = await calculate(ctx, teams, [ + ...new Set([...active.map((w) => w.metric), ...known]), + ]); + const ranks = flags.includes("rank") + ? ((await official(event, "rankings", rankingSchema)).rankings ?? []) + : []; + const stats = active.map((w) => { + const values = teams.map((team) => value(data, team, w.metric)), + mean = values.reduce((s, n) => s + n, 0) / values.length; + return { + ...w, + mean, + sd: + Math.sqrt( + values.reduce((s, n) => s + (n - mean) ** 2, 0) / values.length, + ) || 0.1, + }; + }); + return { + teams: teams + .map((team) => { + const unweighted = stats.map((w) => ({ + type: w.name, + result: + value(data, team, w.metric) === 0 + ? 0 + : (value(data, team, w.metric) - w.mean) / w.sd, + })); + const breakdown = unweighted.map((w, i) => ({ + ...w, + result: w.result * stats[i].weight, + })); + return { + team, + result: breakdown.reduce((s, w) => s + w.result, 0), + breakdown, + unweighted, + flags: [ + ...known.map((flag) => ({ + type: flag, + result: value(data, team, flag), + })), + ...(flags.includes("rank") + ? [ + { + type: "rank", + result: + ranks.find((r) => r.team_key === "frc" + team)?.rank ?? + 0, + }, + ] + : []), + ], + }; + }) + .sort((a, b) => b.result - a.result || a.team - b.team), + }; + }); + router.add( + "GET", + "/v1/analysis/qualrankingprediction", + "session", + async (ctx) => { + const event = input(identifier, ctx.query.tournamentKey); + const matches = await ctx.db.match.findMany({ + where: { tournamentKey: event, competitionLevel: "QUALIFICATION" }, + include: { teamSlots: true, alliances: true }, + orderBy: { displayOrder: "asc" }, + take: 1000, + }); + const teams = [ + ...new Set( + matches.flatMap((m) => m.teamSlots.map((s) => s.teamNumber)), + ), + ]; + if (!teams.length) return []; + if (teams.length > 100) + throw new HttpError(413, "TOO_MANY_TEAMS", "Select a smaller event"); + const data = await calculate(ctx, teams, ["totalPoints"], true); + const rankings = new Map( + teams.map((teamNumber) => [ + teamNumber, + { + teamNumber, + wins: 0, + losses: 0, + ties: 0, + rankingPoints: 0, + matchesPlayed: 0, + combinedScore: 0, + averageScore: 0, + highScore: 0, + }, + ]), + ); + for (const match of matches) { + const red = match.teamSlots + .filter((s) => s.alliance === "RED") + .map((s) => s.teamNumber), + blue = match.teamSlots + .filter((s) => s.alliance === "BLUE") + .map((s) => s.teamNumber); + if (red.length !== 3 || blue.length !== 3) continue; + const completed = match.status === "COMPLETED"; + let winner = match.winningAlliance; + if (!completed) { + const odds = prediction( + [...red, ...blue].map((team) => + (data.teams[String(team)].timeline ?? []).flatMap((p) => + typeof p.metrics.totalPoints.value === "number" + ? [p.metrics.totalPoints.value] + : [], + ), + ), + ); + winner = odds.winningAlliance === 0 ? "RED" : "BLUE"; + } + for (const [color, allianceTeams] of [ + ["RED", red], + ["BLUE", blue], + ] as const) { + const officialAlliance = match.alliances.find( + (a) => a.color === color, + ); + const score = completed + ? (officialAlliance?.score ?? 0) + : allianceTeams.reduce( + (s, t) => s + value(data, t, "totalPoints"), + 0, + ) * rules2026.ranking.forecastScale; + const breakdown = officialAlliance?.scoreBreakdown; + const recordedRp = + breakdown && + typeof breakdown === "object" && + !Array.isArray(breakdown) && + typeof breakdown.rp === "number" + ? breakdown.rp + : 0; + const projected = allianceTeams.reduce( + (s, t) => s + value(data, t, "totalPoints"), + 0, + ); + const rp = completed + ? recordedRp + : rankingPoints2026( + projected, + winner === null ? "tie" : winner === color ? "win" : "loss", + ); + for (const team of allianceTeams) { + const row = rankings.get(team)!; + row.matchesPlayed++; + row.combinedScore += score; + row.highScore = Math.max(row.highScore, score); + row.rankingPoints += rp; + if (!winner) row.ties++; + else if (winner === color) row.wins++; + else row.losses++; + } + } + } + return [...rankings.values()] + .map((r) => ({ + ...r, + averageScore: r.combinedScore / (r.matchesPlayed || 1), + })) + .sort( + (a, b) => + b.rankingPoints - a.rankingPoints || + b.averageScore - a.averageScore || + b.highScore - a.highScore || + a.teamNumber - b.teamNumber, + ); + }, + ); + router.add("GET", "/v1/analysis/csvplain", "verified", async (ctx) => { + const event = input(identifier, ctx.query.tournamentKey); + const slots = await ctx.db.teamMatchData.groupBy({ + by: ["teamNumber"], + where: { + tournamentKey: event, + matchType: { not: "PRACTICE" }, + scoutReports: { some: { AND: [sourceFilter(ctx), valid] } }, + }, + }); + const teams = slots.map((s) => s.teamNumber); + if (teams.length > 100) + throw new HttpError(413, "TOO_MANY_TEAMS", "Select a smaller event"); + if (!teams.length) + return new Reply(csv([], ["teamNumber", ...numeric]), 200, { + "Content-Type": "text/csv", + "Content-Disposition": 'attachment; filename="teamDataDownload.csv"', + }); + const scope = accessScope(user(ctx)); + if ( + (scope.sources.tournaments.mode === "EXCLUDE" && + !scope.sources.tournaments.items.includes(event)) || + (scope.sources.tournaments.mode === "INCLUDE" && + scope.sources.tournaments.items.includes(event)) + ) { + scope.sources.tournaments = { mode: "INCLUDE", items: [event] }; + } else + throw new HttpError( + 403, + "SOURCE_FORBIDDEN", + "Event is outside your data sources", + ); + let data: AnalysisResponse; + if (ctx.query.auto !== undefined || ctx.query.teleop !== undefined) { + data = await analysisBudget(async () => { + const reports = await loadDetailedReports(ctx.db, scope, { + teamMatchData: { tournamentKey: event }, + }); + const auto = ctx.query.auto !== undefined, + teleop = ctx.query.teleop !== undefined; + const selected = reports.map((report) => ({ + ...report, + teamNumber: report.teamMatchData.teamNumber, + matchKey: report.teamMatchKey, + tournamentKey: event, + tournamentDate: report.teamMatchData.tournament.date ?? "", + autoClimb: auto ? report.autoClimb : "NOT_ATTEMPTED", + endgameClimb: teleop ? report.endgameClimb : "NOT_ATTEMPTED", + events: report.events.filter((e) => + auto && !teleop + ? e.time <= rules2026.autoEnd + : teleop && !auto + ? e.time > rules2026.autoEnd + : true, + ), + })); + return analyzeReports( + selected, + { teams, metrics: numeric, season: 2026, timeline: false }, + season2026, + ); + }); + } else + data = await analyze(scope, { + teams, + metrics: numeric, + season: 2026, + timeline: false, + }); + + return new Reply( + csv( + teams.map((team) => ({ + teamNumber: team, + ...Object.fromEntries( + numeric.map((id) => [id, value(data, team, id)]), + ), + })), + ["teamNumber", ...numeric], + ), + 200, + { + "Content-Type": "text/csv", + "Content-Disposition": 'attachment; filename="teamDataDownload.csv"', + }, + ); + }); + router.add("GET", "/v1/analysis/reportcsv", "verified", async (ctx) => + analysisBudget(async () => { + const event = input(identifier, ctx.query.tournamentKey); + const reports = await loadDetailedReports( + ctx.db, + accessScope(user(ctx)), + { teamMatchData: { tournamentKey: event } }, + { text: true }, + ); + const rows = reports.map((report) => { + const team = report.teamMatchData.teamNumber; + const events = report.events.filter((e) => + ctx.query.auto !== undefined && ctx.query.teleop === undefined + ? e.time <= rules2026.autoEnd + : ctx.query.teleop !== undefined && ctx.query.auto === undefined + ? e.time > rules2026.autoEnd + : true, + ); + const data = analyzeReports( + [ + { + ...report, + autoClimb: + ctx.query.teleop !== undefined && ctx.query.auto === undefined + ? "NOT_ATTEMPTED" + : report.autoClimb, + endgameClimb: + ctx.query.auto !== undefined && ctx.query.teleop === undefined + ? "NOT_ATTEMPTED" + : report.endgameClimb, + events, + teamNumber: team, + matchKey: report.teamMatchKey, + tournamentKey: event, + tournamentDate: report.teamMatchData.tournament.date ?? "", + }, + ], + { teams: [team], metrics: numeric, season: 2026, timeline: false }, + season2026, + ); + return { + uuid: report.uuid, + teamNumber: team, + match: report.teamMatchKey, + sourceTeam: report.scouter.sourceTeamNumber, + scouter: + report.scouter.sourceTeamNumber === user(ctx).teamNumber + ? report.scouter.name + : "", + notes: report.notes, + ...Object.fromEntries( + numeric.map((id) => [id, value(data, team, id)]), + ), + }; + }); + return new Reply( + csv(rows, [ + "uuid", + "teamNumber", + "match", + "sourceTeam", + "scouter", + "notes", + ...numeric, + ]), + 200, + { + "Content-Type": "text/csv", + "Content-Disposition": + 'attachment; filename="reportDataDownload.csv"', + }, + ); + }), + ); +} diff --git a/apps/api/src/services/reports.ts b/apps/api/src/services/reports.ts new file mode 100644 index 000000000..221b707ea --- /dev/null +++ b/apps/api/src/services/reports.ts @@ -0,0 +1,540 @@ +import { write2026Report } from "../gameAdapters/2026Write.js"; +import { recordAnalysisChange, reportEffects } from "../domain/effects.js"; +import { isDeepStrictEqual } from "node:util"; +import { z } from "zod"; +import { + reportSchema, + loadReportSchema, + startReportSchema, + endReportSchema, + type ReportSubmission, +} from "@lovat/api"; +import type { Prisma } from "@lovat/db"; +import { + ServiceRouter, + Reply, + input, + user, + team, + writable, + notFound, + type Context, +} from "../http/router.js"; +import { + normalizeTimeline, + persistenceData, + canonicalPayload, +} from "../domain/reports.js"; +import { HttpError } from "../errors.js"; + +const ttl = () => new Date(Date.now() + 7 * 86400000); +const legacySubmission = reportSchema.extend({ + uuid: z.string().min(1), + scouterUuid: z.string().min(1), + events: reportSchema.shape.events.max(10000), +}); +const rule = (schema: S) => + z.object({ mode: z.enum(["INCLUDE", "EXCLUDE"]), items: z.array(schema) }); +export function sourceFilter(ctx: Context): Prisma.ScoutReportWhereInput { + const actor = user(ctx); + const teams = rule(z.number()).safeParse(actor.teamSourceRule); + const tournaments = rule(z.string()).safeParse(actor.tournamentSourceRule); + if (!teams.success || !tournaments.success) + throw new HttpError( + 503, + "INVALID_ACCESS_SCOPE", + "Access settings unavailable", + ); + return { + training: false, + scouter: { + sourceTeamNumber: + teams.data.mode === "INCLUDE" + ? { in: teams.data.items } + : { notIn: teams.data.items }, + }, + teamMatchData: { + tournamentKey: + tournaments.data.mode === "INCLUDE" + ? { in: tournaments.data.items } + : { notIn: tournaments.data.items }, + }, + }; +} +async function scout(ctx: Context, uuid?: string) { + const id = uuid ?? input(z.string().min(1), ctx.headers["x-scouter-uuid"]); + const sourceTeamNumber = ctx.collectionTeam ?? team(ctx); + return ( + (await ctx.db.scouter.findFirst({ + where: { uuid: id, sourceTeamNumber, archived: false }, + })) ?? notFound("Scout not found on this team") + ); +} +async function ownedDraft(ctx: Context, uuid: string) { + const actor = await scout(ctx); + const row = await ctx.db.scoutReportInProgress.findFirst({ + where: { + uuid, + sourceTeamNumber: actor.sourceTeamNumber, + scouterUuid: actor.uuid, + }, + include: { trainingSession: { select: { expiresAt: true, status: true } } }, + }); + if (!row) notFound("Report not found"); + if ( + row.status !== "SUBMITTED" && + (row.status === "ABANDONED" || + row.expiresAt.getTime() <= Date.now() || + (row.mode === "TRAINING" && + (!row.trainingSession || + row.trainingSession.expiresAt.getTime() <= Date.now() || + row.trainingSession.status === "INTERRUPTED"))) + ) { + throw new HttpError( + 410, + "REPORT_EXPIRED", + "Report or training session expired", + ); + } + return row; +} +async function slot( + ctx: Context, + report: Pick< + ReportSubmission, + "teamNumber" | "matchType" | "matchNumber" | "tournamentKey" + >, +) { + let row = await ctx.db.teamMatchData.findFirst({ + where: report, + include: { tournament: { select: { seasonYear: true } } }, + }); + if (!row && report.matchType === "PRACTICE") { + const tournament = await ctx.db.tournament.findUnique({ + where: { key: report.tournamentKey }, + select: { seasonYear: true }, + }); + if (!tournament) notFound("Tournament not found"); + if (tournament.seasonYear !== 2026) + throw new HttpError( + 409, + "CLIENT_UPDATE_REQUIRED", + "Use the versioned game report API for this season", + ); + const key = + report.tournamentKey + + "_pm" + + report.matchNumber + + "_" + + report.teamNumber; + row = await ctx.db.teamMatchData.upsert({ + where: { key }, + create: { key, ...report }, + update: {}, + include: { tournament: { select: { seasonYear: true } } }, + }); + } + if (row && row.tournament.seasonYear !== 2026) + throw new HttpError( + 409, + "CLIENT_UPDATE_REQUIRED", + "Use the versioned game report API for this season", + ); + return row ?? notFound("Match not found"); +} +export function registerReports(router: ServiceRouter) { + const load = async (ctx: Context) => { + const data = input(loadReportSchema, ctx.body); + const actor = await scout(ctx); + const deviceId = input( + z.string().min(1).max(200), + ctx.headers["x-device-id"], + ); + const teamNumber = input( + z.coerce.number().int().positive(), + ctx.params.team ?? data.teamNumber, + ); + const matchKey = + ctx.params.match ?? + (data.matchIdentity + ? ( + await ctx.db.teamMatchData.findFirst({ + where: { ...data.matchIdentity, teamNumber }, + select: { matchKey: true }, + }) + )?.matchKey + : null); + if (!matchKey) notFound("Match not found"); + const match = await ctx.db.match.findUnique({ + where: { key: matchKey }, + include: { + teamSlots: { where: { teamNumber } }, + tournament: { select: { seasonYear: true } }, + }, + }); + const selected = match?.teamSlots[0]; + if (!match || !selected) notFound("Team not in match"); + if (match.tournament.seasonYear !== 2026) + throw new HttpError( + 409, + "CLIENT_UPDATE_REQUIRED", + "Use the versioned game report API for this season", + ); + const existing = await ctx.db.scoutReportInProgress.findUnique({ + where: { uuid: data.uuid }, + }); + if (existing) { + if ( + existing.sourceTeamNumber !== actor.sourceTeamNumber || + existing.scouterUuid !== actor.uuid + ) + notFound(); + if ( + existing.teamNumber !== teamNumber || + existing.tournamentKey !== match.tournamentKey || + existing.matchType !== selected.matchType || + existing.matchNumber !== selected.matchNumber || + existing.trainingAttemptUuid !== (data.trainingAttemptUuid ?? null) + ) { + throw new HttpError( + 409, + "REPORT_ID_CONFLICT", + "Report UUID belongs to a different match or training attempt", + ); + } + await ownedDraft(ctx, existing.uuid); + return { uuid: existing.uuid }; + } + let trainingSessionUuid: string | null = null; + if (data.trainingAttemptUuid) { + const attempt = await ctx.db.trainingAttempt.findFirst({ + where: { + uuid: data.trainingAttemptUuid, + scouterUuid: actor.uuid, + session: { sourceTeamNumber: actor.sourceTeamNumber }, + }, + include: { session: { include: { trainingVideo: true } } }, + }); + if (!attempt) notFound("Training attempt not found"); + if ( + attempt.submittedAt || + attempt.session.status === "INTERRUPTED" || + attempt.session.expiresAt.getTime() <= Date.now() || + attempt.session.trainingVideo?.matchKey !== matchKey || + (attempt.session.targetTeamNumber !== null && + attempt.session.targetTeamNumber !== teamNumber) + ) { + throw new HttpError( + 409, + "TRAINING_ATTEMPT_CONFLICT", + "Training attempt is expired, submitted or bound to a different match", + ); + } + trainingSessionUuid = attempt.sessionUuid; + } + const seasonYear = + match.tournament.seasonYear ?? Number(match.tournamentKey.slice(0, 4)); + if (!Number.isInteger(seasonYear) || seasonYear < 1992) + throw new HttpError( + 409, + "SEASON_UNAVAILABLE", + "Match season unavailable", + ); + await ctx.db.scoutReportInProgress.create({ + data: { + uuid: data.uuid, + scouterUuid: actor.uuid, + sourceTeamNumber: actor.sourceTeamNumber, + deviceId, + seasonYear, + schemaVersion: 1, + mode: trainingSessionUuid ? "TRAINING" : "COMPETITION", + trainingSessionUuid, + trainingAttemptUuid: data.trainingAttemptUuid, + tournamentKey: match.tournamentKey, + matchType: selected.matchType, + matchNumber: selected.matchNumber, + teamNumber, + payload: { + uuid: data.uuid, + scouterUuid: actor.uuid, + tournamentKey: match.tournamentKey, + matchType: selected.matchType, + matchNumber: selected.matchNumber, + teamNumber, + events: [], + }, + expiresAt: ttl(), + }, + }); + return new Reply({ uuid: data.uuid }, 201); + }; + const transition = (ending: boolean) => async (ctx: Context) => { + const data = input(ending ? endReportSchema : startReportSchema, ctx.body); + const row = await ownedDraft(ctx, data.uuid); + const time = "endTime" in data ? data.endTime : data.startTime; + const previous = ending ? row.endedAt : row.startedAt; + if (ending && (!row.startedAt || time < row.startedAt.getTime())) + throw new HttpError( + 409, + "REPORT_STATE_CONFLICT", + "Report must start before ending", + ); + if (previous) { + if (previous.getTime() !== time) + throw new HttpError( + 409, + "REPORT_TIME_CONFLICT", + "Report already has a different timestamp", + ); + return { uuid: row.uuid }; + } + const changed = await ctx.db.scoutReportInProgress.updateMany({ + where: { + uuid: row.uuid, + sourceTeamNumber: row.sourceTeamNumber, + scouterUuid: row.scouterUuid, + status: ending ? "STARTED" : "LOADED", + expiresAt: { gt: new Date() }, + }, + data: { + status: ending ? "ENDED" : "STARTED", + ...(ending + ? { endedAt: new Date(time) } + : { startedAt: new Date(time) }), + revision: { increment: 1 }, + expiresAt: ttl(), + }, + }); + if (!changed.count) + throw new HttpError( + 409, + "REPORT_STATE_CONFLICT", + "Report changed; retry the same UUID", + ); + return { uuid: row.uuid }; + }; + const submit = async (ctx: Context) => { + let report = input(reportSchema, ctx.body); + const draft = await ownedDraft(ctx, report.uuid); + if ( + draft.scouterUuid !== report.scouterUuid || + draft.teamNumber !== report.teamNumber || + draft.tournamentKey !== report.tournamentKey || + draft.matchType !== report.matchType || + draft.matchNumber !== report.matchNumber || + draft.startedAt?.getTime() !== report.startTime + ) { + throw new HttpError( + 409, + "REPORT_IDENTITY_CONFLICT", + "Report identity does not match its draft", + ); + } + report = normalizeTimeline( + report, + draft.endedAt && draft.startedAt + ? (draft.endedAt.getTime() - draft.startedAt.getTime()) / 1000 + : Infinity, + ); + const payload = canonicalPayload(report); + if (draft.status === "SUBMITTED") { + if (!isDeepStrictEqual(draft.payload, payload)) + throw new HttpError( + 409, + "REPORT_PAYLOAD_CONFLICT", + "Report was submitted with different data", + ); + return { uuid: draft.uuid }; + } + if (draft.status !== "ENDED" || !draft.endedAt || draft.schemaVersion !== 1) + throw new HttpError( + 409, + "REPORT_NOT_ENDED", + "End the report before submitting", + ); + const match = await slot(ctx, { + teamNumber: report.teamNumber, + tournamentKey: report.tournamentKey, + matchType: report.matchType, + matchNumber: report.matchNumber, + }); + const training = draft.mode === "TRAINING"; + await ctx.db.$transaction(async (tx) => { + const now = new Date(); + const changed = await tx.scoutReportInProgress.updateMany({ + where: { + uuid: draft.uuid, + status: "ENDED", + expiresAt: { gt: now }, + ...(training + ? { + trainingSession: { + is: { + expiresAt: { gt: now }, + status: { not: "INTERRUPTED" }, + }, + }, + } + : {}), + }, + data: { + status: "SUBMITTED", + payload, + submittedAt: now, + revision: { increment: 1 }, + }, + }); + if (changed.count !== 1) + throw new HttpError( + 409, + "REPORT_STATE_CONFLICT", + "Report changed; retry the same UUID", + ); + await tx.scoutReport.create({ + data: persistenceData( + report, + match.key, + training, + draft.trainingSessionUuid, + ), + }); + await tx.scoutReportInProgress.update({ + where: { uuid: draft.uuid }, + data: { finalizedReportUuid: report.uuid }, + }); + if (training) + await tx.trainingAttempt.update({ + where: { uuid: draft.trainingAttemptUuid! }, + data: { submittedAt: now, payload }, + }); + else await reportEffects(tx, report, draft.sourceTeamNumber); + }); + return { uuid: report.uuid }; + }; + const legacy = async (ctx: Context) => { + if (ctx.session) writable(ctx); + const report = normalizeTimeline(input(legacySubmission, ctx.body)); + const actor = await scout(ctx, report.scouterUuid); + const match = await slot(ctx, { + teamNumber: report.teamNumber, + tournamentKey: report.tournamentKey, + matchType: report.matchType, + matchNumber: report.matchNumber, + }); + await ctx.db.$transaction((tx) => + write2026Report( + tx, + report, + actor, + match, + String(ctx.headers["x-device-id"] ?? "legacy"), + ), + ); + return "done adding data"; + }; + for (const prefix of ["/collection", "/v2/collection"]) { + router.add("POST", prefix + "/load", "collection", load); + router.add("POST", prefix + "/load/:match/:team", "collection", load); + router.add("POST", prefix + "/start", "collection", transition(false)); + router.add("POST", prefix + "/end", "collection", transition(true)); + router.add("POST", prefix + "/submit", "collection", submit); + router.add("POST", prefix + "/scoutreports", "collection", legacy); + } + router.add("POST", "/v1/manager/scoutreports", "verified", legacy); + router.add("POST", "/v1/manager/dashboard/scoutreport", "verified", legacy); + router.add( + "GET", + "/v1/manager/scoutreports/:uuid", + "session", + async (ctx) => { + const row = await ctx.db.scoutReport.findFirst({ + where: { AND: [sourceFilter(ctx), { uuid: ctx.params.uuid }] }, + include: { + events: { orderBy: { time: "asc" } }, + scouter: { select: { sourceTeamNumber: true, name: true } }, + }, + }); + if (!row) notFound(); + const { events, scouter, ...report } = row; + const sameTeam = scouter.sourceTeamNumber === user(ctx).teamNumber; + return { + scoutReport: { + ...report, + scouterName: sameTeam ? scouter.name : undefined, + }, + events, + canModify: sameTeam && user(ctx).role === "SCOUTING_LEAD", + }; + }, + ); + router.add( + "DELETE", + "/v1/manager/scoutreports/:uuid", + "lead", + async (ctx) => { + await ctx.db.$transaction(async (tx) => { + const row = await tx.scoutReport.delete({ + where: { + uuid: ctx.params.uuid, + scouter: { sourceTeamNumber: team(ctx) }, + }, + include: { teamMatchData: { select: { teamNumber: true } } }, + }); + if (!row.training) + await recordAnalysisChange(tx, row.teamMatchData.teamNumber); + }); + return "Data deleted successfully"; + }, + ); + router.add("PUT", "/v1/manager/notes/:uuid", "lead", async (ctx) => { + const data = input(z.object({ note: z.string().max(50000) }), ctx.body); + await ctx.db.scoutReport.update({ + where: { + uuid: ctx.params.uuid, + scouter: { sourceTeamNumber: team(ctx) }, + }, + data: { notes: data.note }, + }); + return "Note updated"; + }); + router.add( + "POST", + "/v1/manager/scoutreports/setflag/:report", + "session", + async (ctx) => { + const flag = input(z.enum(["true", "false"]), ctx.query.flag) === "true"; + const visible = await ctx.db.scoutReport.findFirst({ + where: { AND: [sourceFilter(ctx), { uuid: ctx.params.report }] }, + select: { uuid: true, teamMatchData: { select: { teamNumber: true } } }, + }); + if (!visible) notFound(); + return ctx.db.$transaction(async (tx) => { + await tx.$queryRaw`SELECT "uuid" FROM "ScoutReport" WHERE "uuid" = ${visible.uuid} FOR UPDATE`; + const row = await tx.scoutReport.update({ + where: { uuid: visible.uuid }, + data: { + flaggedBy: flag + ? { connect: { id: user(ctx).id } } + : { disconnect: { id: user(ctx).id } }, + }, + include: { _count: { select: { flaggedBy: true } } }, + }); + if ( + !["VERIFIED", "BAD_REPORT", "FLAGGED_SYSTEM"].includes( + row.reliability, + ) + ) { + await tx.scoutReport.update({ + where: { uuid: row.uuid }, + data: { + reliability: row._count.flaggedBy > 2 ? "FLAGGED" : "UNVERIFIED", + }, + }); + } + await recordAnalysisChange(tx, visible.teamMatchData.teamNumber); + return { flagged: flag, flagCount: row._count.flaggedBy }; + }); + }, + ); +} diff --git a/apps/api/src/services/settings.ts b/apps/api/src/services/settings.ts new file mode 100644 index 000000000..bdf2de471 --- /dev/null +++ b/apps/api/src/services/settings.ts @@ -0,0 +1,159 @@ +import { verificationEmail } from "../domain/email.js"; +import { z } from "zod"; +import { ServiceRouter, input, team, user, writable } from "../http/router.js"; +import { HttpError } from "../errors.js"; + +const storedRule = (schema: S) => + z.object({ mode: z.enum(["INCLUDE", "EXCLUDE"]), items: z.array(schema) }); +export function registerSettings(router: ServiceRouter, website: string) { + router.add("PUT", "/v1/manager/settings", "session", async (ctx) => { + writable(ctx); + const data = input( + z.object({ + teamSource: z.array(z.number().int().positive()).max(10000), + tournamentSource: z.array(z.string()).max(5000), + }), + ctx.body, + ); + await ctx.db.user.update({ + where: { id: user(ctx).id }, + data: { + teamSourceRule: { + mode: "INCLUDE", + items: [...new Set(data.teamSource)], + }, + tournamentSourceRule: { + mode: "INCLUDE", + items: [...new Set(data.tournamentSource)], + }, + }, + }); + return "Settings successfully updated"; + }); + router.add( + "GET", + "/v1/manager/settings/teamsource", + "session", + async (ctx) => { + const rule = input(storedRule(z.number()), user(ctx).teamSourceRule); + if (rule.mode === "EXCLUDE" && !rule.items.length) return "ALL_TEAMS"; + if ( + rule.mode === "INCLUDE" && + rule.items.length === 1 && + rule.items[0] === user(ctx).teamNumber + ) + return "THIS_TEAM"; + const teams = await ctx.db.team.findMany({ + where: { + number: + rule.mode === "INCLUDE" + ? { in: rule.items } + : { notIn: rule.items }, + }, + select: { number: true, name: true }, + take: 10000, + }); + return teams.map((row) => row.number); + }, + ); + router.add( + "POST", + "/v1/manager/settings/teamsource", + "session", + async (ctx) => { + writable(ctx); + const data = input( + z.object({ + mode: z.string().optional(), + teams: z.array(z.number().int().positive()).max(10000).default([]), + }), + ctx.body, + ); + const rule = + data.mode === "ALL_TEAMS" + ? { mode: "EXCLUDE", items: [] } + : { + mode: "INCLUDE", + items: + data.mode === "THIS_TEAM" + ? [team(ctx)] + : [...new Set(data.teams)], + }; + await ctx.db.user.update({ + where: { id: user(ctx).id }, + data: { teamSourceRule: rule }, + }); + return "team sources added"; + }, + ); + router.add( + "GET", + "/v1/manager/settings/tournamentsource", + "session", + async (ctx) => { + const rule = input( + storedRule(z.string()), + user(ctx).tournamentSourceRule, + ); + const rows = await ctx.db.tournament.findMany({ + select: { key: true }, + where: { + key: + rule.mode === "INCLUDE" + ? { in: rule.items } + : { notIn: rule.items }, + }, + orderBy: { date: "asc" }, + take: 5000, + }); + return rows.map((row) => row.key); + }, + ); + router.add( + "POST", + "/v1/manager/settings/tournamentsource", + "session", + async (ctx) => { + writable(ctx); + const data = input( + z.object({ tournaments: z.array(z.string()).max(5000) }), + ctx.body, + ); + await ctx.db.user.update({ + where: { id: user(ctx).id }, + data: { + tournamentSourceRule: { + mode: "INCLUDE", + items: [...new Set(data.tournaments)], + }, + }, + }); + return "tournament sources added"; + }, + ); + router.add("GET", "/v1/manager/settings/teamemail", "lead", async (ctx) => { + const row = await ctx.db.registeredTeam.findUnique({ + where: { number: team(ctx) }, + select: { email: true }, + }); + return row?.email ?? null; + }); + router.add("PUT", "/v1/manager/settings/teamemail", "lead", async (ctx) => { + writable(ctx); + if (user(ctx).role !== "SCOUTING_LEAD") + throw new HttpError( + 403, + "SCOUTING_LEAD_REQUIRED", + "A scouting lead is required", + ); + const data = input(z.object({ email: z.email() }), ctx.body); + await ctx.db.$transaction(async (tx) => { + await tx.registeredTeam.update({ + where: { number: team(ctx) }, + data: { email: data.email, emailVerified: false }, + }); + await verificationEmail(tx, data.email, team(ctx), website); + }); + return "Team email updated; verification required"; + }); +} diff --git a/apps/api/src/services/shifts.ts b/apps/api/src/services/shifts.ts new file mode 100644 index 000000000..3d0d7e3cd --- /dev/null +++ b/apps/api/src/services/shifts.ts @@ -0,0 +1,289 @@ +import { csv } from "../domain/prediction.js"; +import { createHash } from "node:crypto"; +import { z } from "zod"; +import { + ServiceRouter, + Reply, + input, + team, + notFound, + type Context, +} from "../http/router.js"; +import { stationFields, stationSelect, shiftsFor } from "./collection.js"; +import { HttpError } from "../errors.js"; + +const shiftShape = { + startMatchOrdinalNumber: z.number().int().positive(), + endMatchOrdinalNumber: z.number().int().positive(), + team1: z.array(z.string()).max(20), + team2: z.array(z.string()).max(20), + team3: z.array(z.string()).max(20), + team4: z.array(z.string()).max(20), + team5: z.array(z.string()).max(20), + team6: z.array(z.string()).max(20), +}; +const shiftSchema = z + .object(shiftShape) + .refine( + (s) => s.endMatchOrdinalNumber >= s.startMatchOrdinalNumber, + "Shift end precedes its start", + ); +async function saveShift(ctx: Context, tournamentKey: string, uuid?: string) { + const data = input(shiftSchema, ctx.body); + const scouters = stationFields.flatMap((field) => data[field]); + if (new Set(scouters).size !== scouters.length) + throw new HttpError( + 400, + "DUPLICATE_SCOUTER", + "A scouter can occupy only one station per shift", + ); + await ctx.db.$transaction(async (tx) => { + // Team-row locking also protects an event's empty schedule against simultaneous inserts. + await tx.$queryRaw`SELECT "number" FROM "RegisteredTeam" WHERE "number" = ${team(ctx)} FOR UPDATE`; + const eligible = await tx.scouter.count({ + where: { + uuid: { in: scouters }, + sourceTeamNumber: team(ctx), + archived: false, + }, + }); + if (eligible !== scouters.length) + throw new HttpError( + 403, + "INVALID_SCOUTER", + "All scouters must be active members of this team", + ); + const overlap = await tx.scouterScheduleShift.findFirst({ + where: { + sourceTeamNumber: team(ctx), + tournamentKey, + ...(uuid ? { uuid: { not: uuid } } : {}), + startMatchOrdinalNumber: { lte: data.endMatchOrdinalNumber }, + endMatchOrdinalNumber: { gte: data.startMatchOrdinalNumber }, + }, + }); + if (overlap) + throw new HttpError( + 409, + "OVERLAPPING_SHIFT", + "Shift overlaps another shift", + ); + const assignment = Object.fromEntries( + stationFields.map((field) => [ + field, + { + ...(uuid ? { set: [] } : {}), + connect: data[field].map((id) => ({ uuid: id })), + }, + ]), + ); + if (uuid) + await tx.scouterScheduleShift.update({ + where: { uuid, sourceTeamNumber: team(ctx) }, + data: { + startMatchOrdinalNumber: data.startMatchOrdinalNumber, + endMatchOrdinalNumber: data.endMatchOrdinalNumber, + ...assignment, + }, + }); + else + await tx.scouterScheduleShift.create({ + data: { + tournamentKey, + sourceTeamNumber: team(ctx), + startMatchOrdinalNumber: data.startMatchOrdinalNumber, + endMatchOrdinalNumber: data.endMatchOrdinalNumber, + ...assignment, + }, + }); + }); + return uuid + ? "Scouter shift updated successfully" + : "done adding scouter shift"; +} +export function registerShifts(router: ServiceRouter) { + router.add( + "GET", + "/v1/manager/scoutershifts/generate", + "lead", + async (ctx) => { + const tournamentKey = input( + z.string().min(1).max(100), + ctx.query.tournamentKey, + ); + const [matches, scouts, gaps] = await Promise.all([ + ctx.db.match.findMany({ + where: { tournamentKey, competitionLevel: "QUALIFICATION" }, + include: { teamSlots: true }, + orderBy: { matchNumber: "asc" }, + take: 1000, + }), + ctx.db.scouter.findMany({ + where: { sourceTeamNumber: team(ctx), archived: false }, + select: { uuid: true, name: true }, + orderBy: { uuid: "asc" }, + take: 1000, + }), + ctx.db.tournamentGap.findMany({ + where: { tournamentKey }, + select: { beforeMatchKey: true, type: true }, + take: 1000, + }), + ]); + if (!matches.length) notFound("No schedule available"); + if (scouts.length < 3) + throw new HttpError( + 409, + "INSUFFICIENT_SCOUTERS", + "At least three active scouts are required", + ); + const counts = new Map(), + boundaries = new Map(gaps.map((g) => [g.beforeMatchKey, g.type])); + let shift = 0, + within = 0; + const rows: Record[] = []; + for (const match of matches) { + if (boundaries.has(match.key) || within === 10) { + shift++; + within = 0; + } + const chosen = match.teamSlots + .map((s) => s.teamNumber) + .sort((a, b) => (counts.get(a) ?? 0) - (counts.get(b) ?? 0) || a - b) + .slice(0, 3); + const current = Array.from( + { length: 3 }, + (_, i) => scouts[(shift * 3 + i) % scouts.length], + ); + const row: Record = { + "Match Number": match.matchNumber, + }; + for (let i = 0; i < 3; i++) { + row["Scouter " + (i + 1)] = current[i].name ?? current[i].uuid; + row["Team " + (i + 1)] = chosen[i] ?? ""; + if (chosen[i]) + counts.set(chosen[i], (counts.get(chosen[i]) ?? 0) + 1); + } + row["Expected Time"] = match.scheduledTime?.toISOString() ?? ""; + rows.push(row); + within++; + } + return new Reply( + csv(rows, [ + "Match Number", + "Scouter 1", + "Team 1", + "Scouter 2", + "Team 2", + "Scouter 3", + "Team 3", + "Expected Time", + ]), + 200, + { "Content-Type": "text/csv" }, + ); + }, + ); + + router.add( + "GET", + "/v1/manager/tournament/:tournament/scoutershifts", + "verified", + async (ctx) => { + const data = await shiftsFor(ctx, team(ctx), ctx.params.tournament); + return { + data, + hash: createHash("sha256").update(JSON.stringify(data)).digest("hex"), + }; + }, + ); + router.add( + "POST", + "/v1/manager/tournament/:tournament/scoutershifts", + "lead", + (ctx) => saveShift(ctx, ctx.params.tournament), + ); + router.add("POST", "/v1/manager/scoutershifts/:uuid", "lead", async (ctx) => { + const row = await ctx.db.scouterScheduleShift.findFirst({ + where: { uuid: ctx.params.uuid, sourceTeamNumber: team(ctx) }, + }); + if (!row) notFound(); + return saveShift(ctx, row.tournamentKey, row.uuid); + }); + router.add( + "DELETE", + "/v1/manager/scoutershifts/:uuid", + "lead", + async (ctx) => { + await ctx.db.scouterScheduleShift.delete({ + where: { uuid: ctx.params.uuid, sourceTeamNumber: team(ctx) }, + }); + return "Scouter shift deleted successfully"; + }, + ); + router.add("GET", "/v1/manager/scouterspage", "lead", async (ctx) => { + const tournamentKey = ctx.query.tournamentKey; + const archived = + ctx.query.archived === undefined + ? undefined + : ctx.query.archived === "true"; + const sourceTeamNumber = team(ctx); + const [scouters, reports, shifts, matchRows] = await Promise.all([ + ctx.db.scouter.findMany({ + where: { sourceTeamNumber, archived }, + select: { uuid: true, name: true }, + orderBy: { name: "asc" }, + take: 10000, + }), + ctx.db.scoutReport.groupBy({ + by: ["scouterUuid", "teamMatchKey"], + where: { + training: false, + scouter: { sourceTeamNumber }, + ...(tournamentKey ? { teamMatchData: { tournamentKey } } : {}), + }, + }), + tournamentKey + ? ctx.db.scouterScheduleShift.findMany({ + where: { sourceTeamNumber, tournamentKey }, + include: stationSelect, + take: 1000, + }) + : [], + tournamentKey + ? ctx.db.teamMatchData.groupBy({ + by: ["matchType", "matchNumber"], + where: { + tournamentKey, + scoutReports: { some: { training: false } }, + }, + }) + : [], + ]); + const completed = matchRows.length; + const counts = new Map(); + for (const row of reports) + counts.set(row.scouterUuid, (counts.get(row.scouterUuid) ?? 0) + 1); + const assigned = new Map(); + for (const shift of shifts) { + const matches = Math.max( + 0, + Math.min(completed, shift.endMatchOrdinalNumber) - + shift.startMatchOrdinalNumber + + 1, + ); + for (const field of stationFields) + for (const scout of shift[field]) + assigned.set(scout.uuid, (assigned.get(scout.uuid) ?? 0) + matches); + } + return scouters.map((scout) => ({ + scouterUuid: scout.uuid, + scouterName: scout.name, + matchesScouted: counts.get(scout.uuid) ?? 0, + missedMatches: Math.max( + 0, + (assigned.get(scout.uuid) ?? 0) - (counts.get(scout.uuid) ?? 0), + ), + })); + }); +} diff --git a/apps/api/src/services/slack.ts b/apps/api/src/services/slack.ts new file mode 100644 index 000000000..17a9db0a5 --- /dev/null +++ b/apps/api/src/services/slack.ts @@ -0,0 +1,207 @@ +import { randomBytes } from "node:crypto"; +import { z } from "zod"; +import { ServiceRouter, Reply, input, notFound } from "../http/router.js"; +import { HttpError } from "../errors.js"; +export interface OAuthState { + put(key: string, value: string, ttl: number): Promise; + take(key: string): Promise; +} +export interface SlackOptions { + clientId?: string; + clientSecret?: string; + baseUrl: string; + state?: OAuthState; + fetcher?: typeof fetch; +} +export function registerSlack(router: ServiceRouter, options: SlackOptions) { + const redirect = (location: string) => + new Reply("", 302, { Location: location }); + router.add("GET", "/v1/slack-invite", "public", async (ctx) => { + if (!options.clientId || !options.state) + throw new HttpError( + 503, + "SLACK_UNAVAILABLE", + "Slack integration is not configured", + ); + const code = input(z.string().min(1).max(128), ctx.query.team_code); + const team = await ctx.db.registeredTeam.findUnique({ + where: { code }, + select: { number: true }, + }); + if (!team) notFound("Team code not associated with a team"); + const state = randomBytes(24).toString("base64url"); + await options.state.put(state, String(team.number), 600); + const url = new URL("https://slack.com/oauth/v2/authorize"); + url.search = new URLSearchParams({ + client_id: options.clientId, + scope: + "channels:join,channels:read,chat:write,chat:write.public,commands", + state, + redirect_uri: new URL("/v1/slack/add-workspace", options.baseUrl).href, + }).toString(); + return redirect(url.href); + }); + router.add("GET", "/v1/slack/add-workspace", "public", async (ctx) => { + if (!options.clientId || !options.clientSecret || !options.state) + throw new HttpError( + 503, + "SLACK_UNAVAILABLE", + "Slack integration is not configured", + ); + const data = input( + z.object({ + code: z.string().min(1).max(1000), + state: z.string().regex(/^[A-Za-z0-9_-]{32}$/), + }), + ctx.query, + ); + const owner = await options.state.take(data.state); + if (!owner) + throw new HttpError( + 400, + "INVALID_OAUTH_STATE", + "Invalid or expired OAuth state", + ); + const response = await (options.fetcher ?? fetch)( + "https://slack.com/api/oauth.v2.access", + { + method: "POST", + body: new URLSearchParams({ + code: data.code, + client_id: options.clientId, + client_secret: options.clientSecret, + redirect_uri: new URL("/v1/slack/add-workspace", options.baseUrl) + .href, + }), + signal: AbortSignal.timeout(5000), + }, + ); + if (!response.ok) + throw new HttpError( + 502, + "SLACK_UNAVAILABLE", + "Slack authorization failed", + ); + const parsed = z + .object({ + ok: z.literal(true), + access_token: z.string(), + team: z.object({ id: z.string(), name: z.string() }), + bot_user_id: z.string(), + authed_user: z.object({ id: z.string() }), + }) + .safeParse(await response.json()); + if (!parsed.success) + throw new HttpError( + 502, + "SLACK_UNAVAILABLE", + "Slack authorization failed", + ); + const dataRow = parsed.data; + // A workspace cannot silently move to another team on an OAuth retry. + await ctx.db.$transaction(async (tx) => { + const existing = await tx.slackWorkspace.findUnique({ + where: { workspaceId: dataRow.team.id }, + }); + if (existing && existing.owner !== Number(owner)) + throw new HttpError( + 409, + "WORKSPACE_ALREADY_LINKED", + "Slack workspace belongs to another team", + ); + const values = { + owner: Number(owner), + name: dataRow.team.name, + authToken: dataRow.access_token, + botUserId: dataRow.bot_user_id, + authUserId: dataRow.authed_user.id, + }; + await tx.slackWorkspace.upsert({ + where: { workspaceId: dataRow.team.id, owner: Number(owner) }, + create: { workspaceId: dataRow.team.id, ...values }, + update: values, + }); + }); + return redirect( + "https://lovat-learn.highlanderrobotics.com/guides/slack-notifcations", + ); + }); + router.add("POST", "/v1/slack/command", "slack", async (ctx) => { + const data = input( + z.object({ + text: z.string().max(1000), + team_id: z.string(), + channel_id: z.string(), + command: z.literal("/lovat"), + }), + ctx.body, + ); + const [action, kind] = data.text.trim().split(/\s+/); + if (!action || action === "help") + return "Use /lovat subscribe break or /lovat unsubscribe break to manage robot break notifications."; + if ( + !["subscribe", "unsubscribe"].includes(action) || + (kind && kind !== "break") + ) + return "Unknown command. Use /lovat help."; + const workspace = await ctx.db.slackWorkspace.findUnique({ + where: { workspaceId: data.team_id }, + select: { owner: true }, + }); + if (!workspace) + return "Connect your Slack workspace to a Lovat team first."; + if (action === "subscribe") + await ctx.db.slackSubscription.upsert({ + where: { subscriptionId: data.channel_id + "_B" }, + create: { + subscriptionId: data.channel_id + "_B", + channelId: data.channel_id, + workspaceId: data.team_id, + subscribedEvent: "BREAK", + }, + update: { + channelId: data.channel_id, + workspaceId: data.team_id, + subscribedEvent: "BREAK", + }, + }); + else + await ctx.db.slackSubscription.deleteMany({ + where: { + workspaceId: data.team_id, + channelId: data.channel_id, + subscribedEvent: "BREAK", + }, + }); + return action === "subscribe" + ? "Successfully subscribed to 'break' notifications" + : "Successfully unsubscribed from 'break' notifications"; + }); + router.add("POST", "/v1/slack/event", "slack", async (ctx) => { + const challenge = z + .object({ + type: z.literal("url_verification"), + challenge: z.string().max(1000), + }) + .safeParse(ctx.body); + if (challenge.success) return { challenge: challenge.data.challenge }; + const data = input( + z.object({ + type: z.literal("event_callback"), + team_id: z.string(), + event_id: z.string(), + event: z.object({ type: z.string(), channel: z.string().optional() }), + }), + ctx.body, + ); + if (data.event.type === "app_uninstalled") + await ctx.db.slackWorkspace.deleteMany({ + where: { workspaceId: data.team_id }, + }); + else if (data.event.type === "channel_deleted" && data.event.channel) + await ctx.db.slackSubscription.deleteMany({ + where: { workspaceId: data.team_id, channelId: data.event.channel }, + }); + return "Event processed"; + }); +} diff --git a/apps/api/src/services/training.ts b/apps/api/src/services/training.ts new file mode 100644 index 000000000..b519ca79a --- /dev/null +++ b/apps/api/src/services/training.ts @@ -0,0 +1,474 @@ +import { + trainingSessionCreateSchema, + trainingPairSchema, + trainingReadySchema, + trainingControlSchema, +} from "@lovat/api"; +import { createHash, randomBytes } from "node:crypto"; +import { z } from "zod"; +import type { Prisma, PrismaClient } from "@lovat/db"; +import { + ServiceRouter, + Reply, + input, + notFound, + type Context, +} from "../http/router.js"; +import { HttpError } from "../errors.js"; +import { gradeReport } from "../domain/grading.js"; +const hash = (token: string) => + createHash("sha256").update(token).digest("hex"); +const token = () => randomBytes(32).toString("base64url"); +const conflict = (message: string): never => { + throw new HttpError(409, "TRAINING_STATE_CONFLICT", message); +}; +const videoInclude = { + answerKeyReports: { include: { teamMatchData: true } }, +} as const; +const include = { + trainingVideo: { include: videoInclude }, + attempts: { + include: { + scouter: { select: { name: true, sourceTeamNumber: true } }, + report: { + select: { + status: true, + finalizedReport: { + select: { + uuid: true, + trainingScores: { orderBy: { gradedAt: "desc" }, take: 1 }, + }, + }, + }, + }, + }, + orderBy: { createdAt: "asc" }, + take: 100, + }, +} as const satisfies Prisma.TrainingSessionInclude; +type Video = Prisma.TrainingVideoGetPayload<{ include: typeof videoInclude }>; +export function videoDetails(video: Video) { + const key = video.answerKeyReports[0]; + if (!key || video.answerKeyReports.length !== 1 || !key.training) + conflict("Exercise needs exactly one training answer key"); + return { + uuid: video.uuid, + matchKey: video.matchKey, + videoLink: video.videoLink, + teamNumber: key.teamMatchData.teamNumber, + tournamentKey: key.teamMatchData.tournamentKey, + matchType: key.teamMatchData.matchType, + matchNumber: key.teamMatchData.matchNumber, + alliance: video.alliance, + startOffsetSeconds: video.startOffsetSeconds, + durationSeconds: video.durationSeconds, + postMatchSeconds: 15, + }; +} +export async function readTraining( + db: PrismaClient, + id: string, + access: string, + attempt?: string, +) { + const row = await db.trainingSession.findUnique({ + where: { uuid: id }, + include, + }); + if ( + !row || + !access || + (attempt + ? !row.attempts.some( + (a) => a.uuid === attempt && a.accessTokenHash === hash(access), + ) + : row.browserTokenHash !== hash(access)) + ) + notFound("Training session not found"); + if (row.expiresAt.getTime() <= Date.now()) + throw new HttpError(410, "TRAINING_EXPIRED", "Training session expired"); + return row; +} +export async function trainingSnapshot( + db: PrismaClient, + id: string, + access: string, + attempt?: string, +) { + const row = await readTraining(db, id, access, attempt); + return formatTraining(row, attempt); +} +export function formatTraining( + row: Awaited>, + attempt?: string, +) { + if (!row.trainingVideo) conflict("Training video unavailable"); + return { + uuid: row.uuid, + status: row.status, + serverTime: Date.now(), + startedAt: row.startedAt?.getTime() ?? null, + endedAt: row.endedAt?.getTime() ?? null, + expiresAt: row.expiresAt.getTime(), + video: videoDetails(row.trainingVideo!), + participants: row.attempts + .filter((a) => !attempt || a.uuid === attempt) + .map((a) => ({ + uuid: a.uuid, + name: a.scouter.name, + teamNumber: a.scouter.sourceTeamNumber, + deviceName: a.deviceName, + ready: a.ready, + connected: Date.now() - a.lastSeenAt.getTime() < 20000, + status: a.report?.status ?? "CONNECTING", + reportUuid: a.report?.finalizedReport?.uuid ?? null, + score: a.report?.finalizedReport?.trainingScores[0] + ? { + overallScore: Number( + a.report.finalizedReport.trainingScores[0].overallScore, + ), + breakdown: a.report.finalizedReport.trainingScores[0].breakdown, + } + : null, + })), + }; +} +const access = (ctx: Context) => + ctx.headers.authorization?.replace(/^Bearer /i, "") ?? ""; +export function registerTraining(router: ServiceRouter) { + // Collection submission uses the same lifecycle handler as competition reports. + const submit = router.endpoints.find( + (e) => e.path === "/collection/submit" && e.method === "POST", + )!.handle; + for (const prefix of ["/collection", "/v2/collection"]) { + router.add("GET", prefix + "/training/videos", "public", async (ctx) => + ( + await ctx.db.trainingVideo.findMany({ + include: videoInclude, + orderBy: { createdAt: "asc" }, + take: 500, + }) + ) + .filter( + (v) => + v.answerKeyReports.length === 1 && v.answerKeyReports[0].training, + ) + .map(videoDetails), + ); + router.add("POST", prefix + "/training/sessions", "public", async (ctx) => { + const data = input(trainingSessionCreateSchema, ctx.body); + const video = + (await ctx.db.trainingVideo.findUnique({ + where: { uuid: data.videoUuid }, + include: videoInclude, + })) ?? notFound("Training exercise unavailable"); + const details = videoDetails(video), + browserToken = token(), + pairingToken = token(); + const session = await ctx.db.trainingSession.create({ + data: { + trainingVideoUuid: video.uuid, + targetTeamNumber: details.teamNumber, + browserTokenHash: hash(browserToken), + pairingTokenHash: hash(pairingToken), + expiresAt: new Date(Date.now() + 6 * 3600000), + }, + }); + return new Reply({ uuid: session.uuid, browserToken, pairingToken }, 201); + }); + router.add( + "POST", + prefix + "/train/:session", + "collection", + async (ctx) => { + const data = input(trainingPairSchema, ctx.body); + const scouterUuid = input(z.uuid(), ctx.headers["x-scouter-uuid"]), + deviceId = input( + z.string().min(1).max(200), + ctx.headers["x-device-id"], + ); + const scout = + (await ctx.db.scouter.findFirst({ + where: { + uuid: scouterUuid, + sourceTeamNumber: ctx.collectionTeam, + archived: false, + }, + })) ?? notFound("Scout not found"); + const attemptToken = token(); + const attempt = await ctx.db.$transaction(async (tx) => { + await tx.$queryRawUnsafe( + 'SELECT uuid FROM "TrainingSession" WHERE uuid = $1 FOR UPDATE', + ctx.params.session, + ); + const row = await tx.trainingSession.findUnique({ + where: { uuid: ctx.params.session }, + }); + if (!row || row.pairingTokenHash !== hash(data.pairingToken)) + notFound("Invalid training QR code"); + if (row.expiresAt.getTime() <= Date.now()) + throw new HttpError( + 410, + "TRAINING_EXPIRED", + "Training QR code expired", + ); + if (row.status !== "LOBBY") conflict("Session has already started"); + if ( + row.sourceTeamNumber !== null && + row.sourceTeamNumber !== ctx.collectionTeam + ) + throw new HttpError( + 403, + "WRONG_TEAM", + "Session belongs to another team", + ); + if ( + (await tx.trainingAttempt.count({ + where: { sessionUuid: row.uuid }, + })) >= 100 + ) + conflict("Session is full"); + await tx.trainingSession.update({ + where: { uuid: row.uuid }, + data: { sourceTeamNumber: ctx.collectionTeam }, + }); + const existing = await tx.trainingAttempt.findFirst({ + where: { sessionUuid: row.uuid, scouterUuid, deviceId }, + }); + const values = { + accessTokenHash: hash(attemptToken), + deviceName: data.deviceName, + lastSeenAt: new Date(), + }; + return existing + ? tx.trainingAttempt.update({ + where: { uuid: existing.uuid }, + data: values, + }) + : tx.trainingAttempt.create({ + data: { + ...values, + sessionUuid: row.uuid, + scouterUuid: scout.uuid, + deviceId, + }, + }); + }); + return { + attemptUuid: attempt.uuid, + attemptToken, + snapshot: await trainingSnapshot( + ctx.db, + ctx.params.session, + attemptToken, + attempt.uuid, + ), + }; + }, + ); + router.add( + "GET", + prefix + "/training/sessions/:session", + "public", + async (ctx) => { + const attempt = ctx.query.attempt; + const row = await readTraining( + ctx.db, + ctx.params.session, + access(ctx), + attempt, + ); + if (attempt) + await ctx.db.trainingAttempt.updateMany({ + where: { + uuid: attempt, + sessionUuid: ctx.params.session, + lastSeenAt: { lt: new Date(Date.now() - 5000) }, + }, + data: { lastSeenAt: new Date() }, + }); + return formatTraining(row, attempt); + }, + ); + router.add( + "POST", + prefix + "/training/sessions/:session/ready", + "public", + async (ctx) => { + const data = input(trainingReadySchema, ctx.body); + await readTraining( + ctx.db, + ctx.params.session, + access(ctx), + data.attemptUuid, + ); + await ctx.db.$transaction(async (tx) => { + await tx.$queryRawUnsafe( + 'SELECT uuid FROM "TrainingSession" WHERE uuid = $1 FOR UPDATE', + ctx.params.session, + ); + const row = await tx.trainingSession.findUniqueOrThrow({ + where: { uuid: ctx.params.session }, + }); + if ( + !["LOBBY", "ARMED"].includes(row.status) || + (data.stage !== undefined && data.stage !== row.status) + ) + conflict("Training moved to the next step"); + const draft = await tx.scoutReportInProgress.findUnique({ + where: { trainingAttemptUuid: data.attemptUuid }, + }); + if ( + !draft || + draft.status !== "LOADED" || + draft.teamNumber !== row.targetTeamNumber + ) + conflict("Load the training robot before marking ready"); + await tx.trainingAttempt.update({ + where: { uuid: data.attemptUuid }, + data: { ready: true, lastSeenAt: new Date() }, + }); + }); + return { ready: true }; + }, + ); + router.add( + "POST", + prefix + "/training/sessions/:session/control", + "public", + async (ctx) => { + const data = input(trainingControlSchema, ctx.body); + await readTraining(ctx.db, ctx.params.session, access(ctx)); + await ctx.db.$transaction(async (tx) => { + await tx.$queryRawUnsafe( + 'SELECT uuid FROM "TrainingSession" WHERE uuid = $1 FOR UPDATE', + ctx.params.session, + ); + const row = await tx.trainingSession.findUniqueOrThrow({ + where: { uuid: ctx.params.session }, + include, + }); + if (row.expiresAt.getTime() <= Date.now()) + conflict("Training session expired"); + if (data.action === "arm" || data.action === "play") { + const target = data.action === "arm" ? "ARMED" : "PLAYING", + previous = data.action === "arm" ? "LOBBY" : "ARMED"; + if (row.status === target) return; + if ( + row.status !== previous || + !row.attempts.length || + row.attempts.some( + (a) => !a.ready || Date.now() - a.lastSeenAt.getTime() > 20000, + ) + ) + conflict("Every scout must be connected and ready"); + await tx.trainingSession.update({ + where: { uuid: row.uuid }, + data: { + status: target, + ...(target === "PLAYING" ? { startedAt: new Date() } : {}), + }, + }); + if (target === "ARMED") + await tx.trainingAttempt.updateMany({ + where: { sessionUuid: row.uuid }, + data: { ready: false }, + }); + } else if (!["ENDED", "INTERRUPTED"].includes(row.status)) { + const end = + row.startedAt && row.trainingVideo + ? new Date( + row.startedAt.getTime() + + row.trainingVideo.durationSeconds * 1000, + ) + : null; + if ( + data.action === "end" && + (!end || + row.status !== "PLAYING" || + Date.now() + 2000 < end.getTime() + 15000) + ) + conflict("Wait for the match video to finish"); + const completed = + data.action === "end" || + (end && + Date.now() >= end.getTime() && + (data.playbackSeconds ?? 0) >= + (row.trainingVideo?.durationSeconds ?? Infinity)); + await tx.trainingSession.update({ + where: { uuid: row.uuid }, + data: completed + ? { status: "ENDED", endedAt: end } + : { status: "INTERRUPTED" }, + }); + } + }); + return trainingSnapshot(ctx.db, ctx.params.session, access(ctx)); + }, + ); + router.add( + "DELETE", + prefix + "/training/sessions/:session/participants/:attempt", + "public", + async (ctx) => { + await readTraining(ctx.db, ctx.params.session, access(ctx)); + await ctx.db.$transaction(async (tx) => { + await tx.$queryRawUnsafe( + 'SELECT uuid FROM "TrainingSession" WHERE uuid = $1 FOR UPDATE', + ctx.params.session, + ); + const changed = await tx.trainingAttempt.deleteMany({ + where: { + uuid: ctx.params.attempt, + sessionUuid: ctx.params.session, + session: { status: "LOBBY" }, + }, + }); + if (!changed.count) + conflict("Participant cannot be removed after the session starts"); + }); + return new Reply(null, 204); + }, + ); + router.add( + "POST", + prefix + "/training/sessions/:session/grade", + "public", + async (ctx) => { + const session = await readTraining( + ctx.db, + ctx.params.session, + access(ctx), + ); + for (const attempt of session.attempts) { + const uuid = attempt.report?.finalizedReport?.uuid; + if (uuid) await gradeReport(ctx.db, uuid); + } + return trainingSnapshot(ctx.db, ctx.params.session, access(ctx)); + }, + ); + router.add( + "POST", + prefix + "/training/:session/submit", + "collection", + async (ctx) => { + const uuid = input(z.uuid(), (ctx.body as { uuid?: unknown })?.uuid); + const draft = await ctx.db.scoutReportInProgress.findUnique({ + where: { uuid }, + include: { trainingSession: true }, + }); + if ( + !draft || + draft.mode !== "TRAINING" || + draft.trainingSessionUuid !== ctx.params.session + ) + notFound("Training report not found"); + if (draft.trainingSession?.status !== "ENDED") + conflict("Wait for the video to finish"); + const result = await submit(ctx); + await gradeReport(ctx.db, uuid); + return result; + }, + ); + } +} diff --git a/apps/api/src/signatures.ts b/apps/api/src/signatures.ts new file mode 100644 index 000000000..69d62b8e0 --- /dev/null +++ b/apps/api/src/signatures.ts @@ -0,0 +1,51 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; +import type { IncomingHttpHeaders } from "node:http"; +export function createSignatureVerifier(options: { + lovatKey?: string; + slackSecret?: string; + now?: () => number; +}) { + return async ( + headers: IncomingHttpHeaders, + rawBody: string, + slack: boolean, + method: string, + path: string, + body: unknown, + ): Promise => { + const time = headers[slack ? "x-slack-request-timestamp" : "x-timestamp"]; + const signature = headers[slack ? "x-slack-signature" : "x-signature"]; + const key = slack ? options.slackSecret : options.lovatKey; + if ( + !key || + typeof time !== "string" || + typeof signature !== "string" || + !/^\d+$/.test(time) + ) + return false; + const timestamp = Number(time); + if ( + !Number.isSafeInteger(timestamp) || + Math.abs(Math.floor((options.now?.() ?? Date.now()) / 1000) - timestamp) > + 300 + ) + return false; + const text = JSON.stringify(body); + const payload = slack + ? "v0:" + time + ":" + rawBody + : JSON.stringify({ + path, + method, + body: text === "{}" ? "" : text, + timestamp, + }); + const expected = createHmac("sha256", key).update(payload).digest(); + const received = slack ? signature.replace(/^v0=/, "") : signature; + if ( + !/^[a-fA-F0-9]{64}$/.test(received) || + (slack && !signature.startsWith("v0=")) + ) + return false; + return timingSafeEqual(expected, Buffer.from(received, "hex")); + }; +} diff --git a/apps/api/src/sockets.ts b/apps/api/src/sockets.ts new file mode 100644 index 000000000..c53117417 --- /dev/null +++ b/apps/api/src/sockets.ts @@ -0,0 +1,164 @@ +import type { Server, ServerWebSocket, WebSocketHandler } from "bun"; +import type { PrismaClient } from "@lovat/db"; +import { trainingSocketCredentialsSchema } from "@lovat/api"; +import { readTraining, trainingSnapshot } from "./services/training.js"; +type Credentials = { sessionUuid: string; token: string; attemptUuid?: string }; +export type TrainingSocketData = { + ip: string; + authenticating?: boolean; + groupKey?: string; + lastPong: number; + timeout?: ReturnType; +}; +type Socket = ServerWebSocket; +export function createTrainingSockets( + db: PrismaClient, + origins: readonly string[], +) { + const clients = new Set(); + const counts = new Map(); + const groups = new Map< + string, + { + credentials: Credentials; + clients: Set; + busy: boolean; + lastBeat: number; + } + >(); + let closed = false; + const websocket: WebSocketHandler = { + maxPayloadLength: 2048, + perMessageDeflate: false, + idleTimeout: 15, + backpressureLimit: 65536, + closeOnBackpressureLimit: true, + open(ws) { + clients.add(ws); + ws.data.timeout = setTimeout( + () => ws.close(1008, "Authentication required"), + 5000, + ); + }, + pong(ws) { + ws.data.lastPong = Date.now(); + }, + async message(ws, raw) { + if (ws.data.groupKey || ws.data.authenticating) return; + ws.data.authenticating = true; + try { + const credentials = trainingSocketCredentialsSchema.parse( + JSON.parse(typeof raw === "string" ? raw : raw.toString()), + ); + await readTraining( + db, + credentials.sessionUuid, + credentials.token, + credentials.attemptUuid, + ); + if (!clients.has(ws) || closed) return; + const key = JSON.stringify(credentials); + let group = groups.get(key); + if (!group) { + group = { credentials, clients: new Set(), busy: false, lastBeat: 0 }; + groups.set(key, group); + } + ws.data.groupKey = key; + group.clients.add(ws); + clearTimeout(ws.data.timeout); + const snapshot = await trainingSnapshot( + db, + credentials.sessionUuid, + credentials.token, + credentials.attemptUuid, + ); + if (clients.has(ws)) ws.send(JSON.stringify(snapshot)); + } catch { + ws.close(1008, "Session unavailable"); + } + }, + close(ws) { + clearTimeout(ws.data.timeout); + clients.delete(ws); + const count = (counts.get(ws.data.ip) ?? 1) - 1; + if (count) counts.set(ws.data.ip, count); + else counts.delete(ws.data.ip); + if (ws.data.groupKey) { + const group = groups.get(ws.data.groupKey); + group?.clients.delete(ws); + if (!group?.clients.size) groups.delete(ws.data.groupKey); + } + }, + }; + const tick = setInterval(() => { + for (const group of groups.values()) { + if (group.busy) continue; + group.busy = true; + void (async () => { + try { + const { sessionUuid, token, attemptUuid } = group.credentials; + const state = await trainingSnapshot( + db, + sessionUuid, + token, + attemptUuid, + ); + if (attemptUuid && Date.now() - group.lastBeat >= 5000) { + await db.trainingAttempt.updateMany({ + where: { uuid: attemptUuid, sessionUuid }, + data: { lastSeenAt: new Date() }, + }); + group.lastBeat = Date.now(); + } + const message = JSON.stringify(state); + for (const ws of group.clients) { + if (Date.now() - ws.data.lastPong > 15000) { + ws.terminate(); + continue; + } + ws.ping(); + ws.send(message); + } + } catch { + for (const ws of group.clients) ws.close(1008, "Session unavailable"); + } finally { + group.busy = false; + } + })(); + } + }, 1000); + tick.unref(); + return { + websocket, + upgrade( + request: Request, + server: Server, + ): Response | undefined | false { + if ( + ![ + "/collection/training/socket", + "/v2/collection/training/socket", + ].includes(new URL(request.url).pathname) + ) + return false; + const origin = request.headers.get("origin"); + const ip = server.requestIP(request)?.address ?? "unknown"; + if (closed || (origin && !origins.includes(origin))) + return new Response("Forbidden", { status: 403 }); + if (clients.size >= 200 || (counts.get(ip) ?? 0) >= 20) + return new Response("Too many connections", { status: 503 }); + if (server.upgrade(request, { data: { ip, lastPong: Date.now() } })) { + counts.set(ip, (counts.get(ip) ?? 0) + 1); + return undefined; + } + return new Response("WebSocket upgrade required", { status: 426 }); + }, + close() { + if (closed) return; + closed = true; + clearInterval(tick); + for (const ws of clients) ws.terminate(); + groups.clear(); + }, + }; +} diff --git a/apps/api/src/state.ts b/apps/api/src/state.ts new file mode 100644 index 000000000..7402fbbc1 --- /dev/null +++ b/apps/api/src/state.ts @@ -0,0 +1,92 @@ +import { createClient } from "redis"; +import type { RateLimiter } from "./identity.js"; +import { HttpError } from "./errors.js"; +const consumeScript = + "local n=redis.call('INCR',KEYS[1]); if n==1 then redis.call('EXPIRE',KEYS[1],ARGV[2]) end; return n<=tonumber(ARGV[1]) and 1 or 0"; +export function createState(url: string, prefix: string) { + if (!prefix || /[*?\[\]\\]/.test(prefix)) + throw new Error("A non-glob Redis key prefix is required"); + const client = createClient({ + url, + disableOfflineQueue: true, + socket: { + connectTimeout: 2000, + reconnectStrategy: (retries) => (retries > 1 ? false : 250), + }, + }); + client.on("error", () => {}); + let connecting: Promise | undefined; + const connect = async () => { + if (!client.isReady) { + if (!connecting) + connecting = client.connect().finally(() => { + connecting = undefined; + }); + await connecting; + } + }; + const limiter: RateLimiter = { + async consume(key, limit, seconds) { + try { + await connect(); + return ( + Number( + await client.eval(consumeScript, { + keys: [prefix + "rate:" + key], + arguments: [String(limit), String(seconds)], + }), + ) === 1 + ); + } catch { + throw new HttpError( + 503, + "RATE_LIMIT_UNAVAILABLE", + "Authorization controls are temporarily unavailable", + ); + } + }, + }; + return { + client, + prefix, + connect, + limiter, + oauth: { + async put(key: string, value: string, ttl: number) { + await connect(); + await client.set(prefix + "oauth:" + key, value, { EX: ttl }); + }, + async take(key: string) { + await connect(); + return client.getDel(prefix + "oauth:" + key); + }, + }, + cache: { + async generations(teams: readonly number[]) { + await connect(); + return ( + await client.mGet(teams.map((team) => prefix + "revision:" + team)) + ).map((value) => value ?? "0"); + }, + async get(key: string) { + await connect(); + return client.get(prefix + "analysis:" + key); + }, + async set(key: string, value: string, ttl: number) { + await connect(); + await client.set(prefix + "analysis:" + key, value, { EX: ttl }); + }, + }, + async ready() { + try { + await connect(); + return (await client.ping()) === "PONG"; + } catch { + return false; + } + }, + async close() { + if (client.isOpen) await client.quit(); + }, + }; +} diff --git a/apps/api/test/auth.test.mjs b/apps/api/test/auth.test.mjs new file mode 100644 index 000000000..324d0d432 --- /dev/null +++ b/apps/api/test/auth.test.mjs @@ -0,0 +1,51 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createAuthenticator } from "../dist/auth.js"; +const user = { + id: "auth0|test", + teamNumber: 8033, + role: "ANALYST", + team: { emailVerified: true }, + teamSourceRule: { mode: "INCLUDE", items: [] }, + tournamentSourceRule: { mode: "EXCLUDE", items: [] }, +}; +function auth(value = user, verify = async () => ({ sub: user.id })) { + return createAuthenticator( + { userById: async () => value }, + { + issuer: "https://issuer.example/", + audience: "lovat", + verify, + }, + ); +} +test("valid JWT identity uses authoritative source rules without provisioning writes", async () => { + const scope = await auth()("Bearer token"); + assert.equal(scope.userId, user.id); + assert.deepEqual(scope.sources.teams, { mode: "INCLUDE", items: [] }); +}); +test("invalid, absent and subjectless tokens fail closed", async () => { + await assert.rejects(auth()(undefined), { status: 401 }); + await assert.rejects(auth()("Bearer lvt-key"), { code: "JWT_REQUIRED" }); + await assert.rejects( + auth(user, async () => { + throw new Error("secret"); + })("Bearer token"), + { code: "UNAUTHORIZED" }, + ); + await assert.rejects(auth(user, async () => ({}))("Bearer token"), { + status: 401, + }); +}); +test("missing identity, unverified team and corrupt scope never grant access", async () => { + await assert.rejects(auth(null)("Bearer token"), { + code: "IDENTITY_NOT_PROVISIONED", + }); + await assert.rejects( + auth({ ...user, team: { emailVerified: false } })("Bearer token"), + { status: 403 }, + ); + await assert.rejects(auth({ ...user, teamSourceRule: {} })("Bearer token"), { + code: "INVALID_ACCESS_SCOPE", + }); +}); diff --git a/apps/api/test/fixtures.mjs b/apps/api/test/fixtures.mjs new file mode 100644 index 000000000..37b88f5e7 --- /dev/null +++ b/apps/api/test/fixtures.mjs @@ -0,0 +1,35 @@ +export const scope = { + userId: "auth0|example", + teamNumber: 8033, + role: "ANALYST", + sources: { + teams: { mode: "INCLUDE", items: [8033] }, + tournaments: { mode: "EXCLUDE", items: [] }, + }, +}; +export function report(overrides = {}) { + return { + uuid: "report1", + teamNumber: 8033, + matchKey: "qm1", + tournamentKey: "2026test", + tournamentDate: "2026-03-01", + events: [], + driverAbility: 3, + defenseEffectiveness: 2, + accuracy: null, + autoClimb: "NOT_ATTEMPTED", + endgameClimb: "NOT_ATTEMPTED", + robotRoles: ["CYCLING"], + feederTypes: [], + fieldTraversal: "TRENCH", + beached: "NEITHER", + scoresWhileMoving: false, + disrupts: false, + intakeType: "GROUND", + ...overrides, + }; +} +export function event(action, time, quantity = null) { + return { action, time, quantity, points: quantity ?? 0, position: "NONE" }; +} diff --git a/apps/api/test/games.integration.mjs b/apps/api/test/games.integration.mjs new file mode 100644 index 000000000..4d9f35473 --- /dev/null +++ b/apps/api/test/games.integration.mjs @@ -0,0 +1,314 @@ +import { startApi } from "../dist/runtime.js"; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { once } from "node:events"; +import { randomUUID } from "node:crypto"; +import { GameCatalog } from "@lovat/games"; +import { game2026 } from "@lovat/games/2026"; +import { createApiClient } from "@lovat/api"; +import { fictionalGame } from "../../../packages/games/test/fixtures.mjs"; +import { createApi } from "../dist/app.js"; +import { createRepository } from "../dist/repository.js"; +import { createServices } from "../dist/services/index.js"; +import { createAnalysisService } from "../dist/analysis.js"; +const url = new URL( + process.env.DATABASE_URL ?? "postgresql://localhost/missing", +); +if ( + process.env.LOVAT_DB_TEST !== "1" || + !["localhost", "127.0.0.1"].includes(url.hostname) || + url.pathname !== "/lovat_test" +) + throw Error("Use a disposable loopback lovat_test database"); +const { createDb } = await import("@lovat/db"); +test("a second game validates, persists and analyzes through unchanged HTTP and storage infrastructure", async (t) => { + const db = createDb(url.href, { + maxConnections: 4, + statementTimeoutMs: 8000, + }), + suffix = randomUUID(); + const own = 1300000000 + Math.floor(Math.random() * 10000000), + other = own + 1, + robot = own + 2, + fourth = own + 3, + scout = randomUUID(); + const event = "2099-game-fixture-" + suffix, + slot = event + "_qm1_0"; + const catalog = new GameCatalog([game2026, fictionalGame]); + await db.season.upsert({ + where: { year: 2099 }, + create: { year: 2099 }, + update: {}, + }); + await db.team.createMany({ + data: [own, other, robot, fourth].map((number) => ({ + number, + name: "Synthetic game fixture", + })), + }); + await db.registeredTeam.createMany({ + data: [own, other].map((number) => ({ + number, + code: suffix + number, + email: number + "@example.invalid", + emailVerified: true, + teamApproved: true, + })), + }); + await db.scouter.create({ + data: { uuid: scout, name: "Synthetic game scout", sourceTeamNumber: own }, + }); + await db.tournament.create({ + data: { + key: event, + name: "Synthetic different game", + seasonYear: 2099, + date: "2099-03-01", + }, + }); + await db.teamMatchData.create({ + data: { + key: slot, + tournamentKey: event, + teamNumber: robot, + matchNumber: 1, + matchType: "QUALIFICATION", + }, + }); + const scope = { + userId: suffix, + teamNumber: own, + role: "SCOUTING_LEAD", + sources: { + teams: { mode: "INCLUDE", items: [own] }, + tournaments: { mode: "INCLUDE", items: [event] }, + }, + }; + const repository = createRepository(db, catalog), + analyze = createAnalysisService(repository, undefined, catalog); + let sessionReads = 0; + const api = createApi({ + gameCatalog: catalog, + repository, + analyze, + authenticate: async (auth) => + auth === "Bearer other" + ? { + ...scope, + teamNumber: other, + sources: { + ...scope.sources, + teams: { mode: "INCLUDE", items: [other] }, + }, + } + : scope, + ready: async () => true, + services: { + router: createServices({ + baseUrl: "https://example.invalid", + commit: "fixture", + analyze, + gameCatalog: catalog, + }), + db, + authenticate: async () => { + sessionReads++; + return { + user: { + id: suffix, + teamNumber: own, + role: "SCOUTING_LEAD", + teamSourceRule: scope.sources.teams, + tournamentSourceRule: scope.sources.tournaments, + team: { emailVerified: true }, + }, + tokenType: "jwt", + }; + }, + }, + }); + const runtime = startApi(api, { port: 0, hostname: "127.0.0.1" }); + const base = runtime.url; + t.after(async () => { + await runtime.stop(true); + await db.tournament.deleteMany({ where: { key: event } }); + await db.registeredTeam.deleteMany({ + where: { number: { in: [own, other] } }, + }); + await db.team.deleteMany({ + where: { number: { in: [own, other, robot, fourth] } }, + }); + await db.apiOutbox.deleteMany({ + where: { dedupeKey: { startsWith: "analysis:" + robot + ":" } }, + }); + await db.analysisRevision.deleteMany({ where: { teamNumber: robot } }); + await db.season.deleteMany({ + where: { + year: 2099, + tournaments: { none: {} }, + teamSeasons: { none: {} }, + districtSeasons: { none: {} }, + gameReports: { none: {} }, + }, + }); + await db.$disconnect(); + }); + const headers = { + "Content-Type": "application/json", + "X-Team-Code": suffix + own, + "X-Scouter-Uuid": scout, + "X-Device-Id": suffix, + }; + const report = { + uuid: randomUUID(), + scouterUuid: scout, + teamNumber: robot, + tournamentKey: event, + matchType: "QUALIFICATION", + matchNumber: 1, + season: 2099, + gameId: "fixture-glyphs", + gameVersion: 1, + reportVersion: 2, + startTime: Date.now() - 80000, + endTime: Date.now() - 5000, + data: { + throws: [ + { zone: "high", count: 2 }, + { zone: "low", count: 3 }, + ], + balanced: true, + }, + }; + const submit = (data, extra = {}) => + fetch(base + "/v3/reports", { + method: "POST", + headers: { ...headers, ...extra }, + body: JSON.stringify(data), + }); + const [first, replay] = await Promise.all([submit(report), submit(report)]); + assert.deepEqual([first.status, replay.status].sort(), [200, 201]); + assert.equal(sessionReads, 0); + assert.equal(await db.gameReport.count({ where: { uuid: report.uuid } }), 1); + assert.equal(await db.scoutReport.count({ where: { uuid: report.uuid } }), 0); + const saved = await db.gameReport.findUniqueOrThrow({ + where: { uuid: report.uuid }, + }); + assert.deepEqual(saved.data, report.data); + assert.equal(saved.seasonYear, 2099); + assert.equal( + ( + await db.analysisRevision.findUniqueOrThrow({ + where: { teamNumber: robot }, + }) + ).revision, + 1n, + ); + assert.equal( + (await submit({ ...report, data: { ...report.data, balanced: false } })) + .status, + 409, + ); + assert.equal( + ( + await submit( + { ...report, uuid: randomUUID() }, + { "X-Team-Code": suffix + other }, + ) + ).status, + 404, + ); + assert.equal( + ( + await submit({ + ...report, + uuid: randomUUID(), + data: { ...report.data, accuracy: 5 }, + }) + ).status, + 400, + ); + assert.equal((await submit({ ...report, reportVersion: 99 })).status, 409); + assert.equal( + ( + await submit({ + ...report, + uuid: randomUUID(), + endTime: report.endTime + 10000, + }) + ).status, + 400, + ); + assert.equal((await submit({ ...report, gameId: "frc-2026" })).status, 400); + assert.equal( + ( + await submit({ + ...report, + reportVersion: 1, + data: { high: 2, low: 3, balanced: true }, + }) + ).status, + 200, + ); + const client = createApiClient({ + baseUrl: base, + token: () => "own", + collection: () => headers, + }); + const publicClient = createApiClient({ baseUrl: base }); + const available = await publicClient.request("games", {}); + assert.equal( + available + .find((game) => game.season === 2099) + .rules.periods.reduce((n, period) => n + period.durationSeconds, 0), + 75, + ); + const metrics = await client.request("metrics", { season: 2099 }); + assert.deepEqual( + metrics.map((metric) => metric.id), + ["glyphScore", "capability"], + ); + const result = await client.request("analyze", { + season: 2099, + gameVersion: 1, + teams: [robot], + metrics: ["points", "capability"], + }); + assert.equal(result.teams[String(robot)].metrics.glyphScore.value, 33); + assert.deepEqual(result.teams[String(robot)].metrics.capability.value, { + canBalance: true, + capacity: 5, + }); + const predicted = await client.request("predictGame", { + season: 2099, + red: [robot, own], + blue: [other, fourth], + }); + assert.equal(predicted.redScore, 33); + assert.equal(predicted.winningAlliance, "red"); + assert.equal(predicted.redRankingPoints, 3); + const suspect = { + ...report, + uuid: randomUUID(), + data: { throws: [{ zone: "high", count: 1000 }], balanced: true }, + }; + assert.equal((await submit(suspect)).status, 201); + assert.equal( + (await db.gameReport.findUniqueOrThrow({ where: { uuid: suspect.uuid } })) + .reliability, + "FLAGGED_SYSTEM", + ); + const denied = await fetch(base + "/v3/analysis", { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer other", + }, + body: JSON.stringify({ season: 2099, teams: [robot], metrics: ["points"] }), + }); + assert.equal(denied.status, 200); + assert.equal( + (await denied.json()).teams[String(robot)].metrics.glyphScore.value, + null, + ); +}); diff --git a/apps/api/test/http.test.mjs b/apps/api/test/http.test.mjs new file mode 100644 index 000000000..b6a1227ee --- /dev/null +++ b/apps/api/test/http.test.mjs @@ -0,0 +1,202 @@ +import { startApi } from "../dist/runtime.js"; +import { legacyAnalysisInput } from "@lovat/games/2026"; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createApi } from "../dist/app.js"; +import { HttpError } from "../dist/errors.js"; +import { report, scope } from "./fixtures.mjs"; + +async function fixture(t, overrides = {}) { + const loads = []; + const logs = []; + const api = createApi({ + authenticate: async (header) => { + if (header !== "Bearer token") + throw new HttpError(401, "UNAUTHORIZED", "Denied"); + return scope; + }, + repository: { + loadReports: async (...args) => { + loads.push(args); + return [legacyAnalysisInput(report())]; + }, + }, + ready: async () => true, + log: (event) => logs.push(event), + ...overrides, + }); + const runtime = startApi(api, { port: 0, hostname: "127.0.0.1" }); + t.after(() => runtime.stop(true)); + return { + ...api, + loads, + logs, + url: runtime.url, + }; +} +const post = (body) => ({ + method: "POST", + headers: { + Authorization: "Bearer token", + "Content-Type": "application/json", + }, + body: JSON.stringify(body), +}); +test("analysis loads once for many metrics and forwards mandatory auth scope", async (t) => { + const api = await fixture(t); + const response = await fetch( + api.url + "/v3/analysis", + post({ teams: [8033], metrics: ["totalPoints", "driverAbility"] }), + ); + assert.equal(response.status, 200); + assert.equal( + (await response.json()).teams["8033"].metrics.driverAbility.value, + 3, + ); + assert.equal(api.loads.length, 1); + assert.deepEqual(api.loads[0][0], scope); + assert.equal(api.loads[0][2].has("events"), true); + assert.equal(response.headers.get("cache-control"), "no-store"); +}); +test("validation rejects unknown metrics, source overrides and excessive bodies before loading", async (t) => { + const api = await fixture(t); + for (const body of [ + { teams: [8033], metrics: ["unknown"] }, + { teams: [8033], metrics: ["totalPoints"], sources: {} }, + ]) { + assert.equal( + (await fetch(api.url + "/v3/analysis", post(body))).status, + 400, + ); + } + assert.equal( + ( + await fetch( + api.url + "/v3/analysis", + post({ padding: "x".repeat(70000) }), + ) + ).status, + 413, + ); + assert.equal(api.loads.length, 0); +}); +test("authentication, origin policy and unexpected failures are sanitized", async (t) => { + const api = await fixture(t, { + repository: { + loadReports: async () => { + throw new Error("database password"); + }, + }, + }); + assert.equal((await fetch(api.url + "/v3/metrics")).status, 401); + assert.equal( + ( + await fetch(api.url + "/v3/metrics", { + headers: { origin: "https://untrusted.example" }, + }) + ).status, + 403, + ); + const response = await fetch( + api.url + "/v3/analysis", + post({ teams: [8033], metrics: ["driverAbility"] }), + ); + assert.equal(response.status, 500); + assert.equal((await response.text()).includes("password"), false); + assert.equal( + api.logs.some((log) => JSON.stringify(log).includes("token")), + false, + ); +}); +test("readiness reflects dependencies and draining preserves liveness", async (t) => { + const api = await fixture(t, { ready: async () => false }); + assert.equal((await fetch(api.url + "/health/ready")).status, 503); + api.drain(); + assert.equal((await fetch(api.url + "/health/live")).status, 200); + assert.equal( + ( + await fetch(api.url + "/v3/metrics", { + headers: { Authorization: "Bearer token" }, + }) + ).status, + 503, + ); +}); + +test("internal metric validation failures return sanitized server errors", async (t) => { + const api = await fixture(t, { + repository: { + loadReports: async () => [ + legacyAnalysisInput(report({ driverAbility: NaN })), + ], + }, + }); + const response = await fetch( + api.url + "/v3/analysis", + post({ teams: [8033], metrics: ["driverAbility"] }), + ); + assert.equal(response.status, 500); + assert.equal((await response.json()).code, "INTERNAL_SERVER_ERROR"); +}); +test("concurrency admission stays bounded while a repository call is in flight", async (t) => { + let release; + let signalStarted; + const gate = new Promise((resolve) => { + release = resolve; + }); + const started = new Promise((resolve) => { + signalStarted = resolve; + }); + const api = await fixture(t, { + maxConcurrent: 1, + repository: { + loadReports: async () => { + signalStarted(); + await gate; + return [legacyAnalysisInput(report())]; + }, + }, + }); + const first = fetch( + api.url + "/v3/analysis", + post({ teams: [8033], metrics: ["driverAbility"] }), + ); + await started; + try { + const overloaded = await fetch(api.url + "/v3/metrics", { + headers: { Authorization: "Bearer token" }, + }); + assert.equal(overloaded.status, 503); + } finally { + release(); + assert.equal((await first).status, 200); + } +}); + +test("Hono decodes route parameters once and rejects malformed path encoding", async (t) => { + const { ServiceRouter } = await import("../dist/http/router.js"); + const router = new ServiceRouter(); + router.add("GET", "/encoded/:id", "public", async (ctx) => ctx.params); + const api = await fixture(t, { + services: { + router, + db: {}, + authenticate: async () => { + throw Error("Unexpected authentication"); + }, + }, + }); + assert.deepEqual(await (await fetch(api.url + "/encoded/a%252Fb")).json(), { + id: "a%2Fb", + }); + assert.equal((await fetch(api.url + "/encoded/%ZZ")).status, 400); +}); +test("JSON depth is bounded before recursive game schema validation", async (t) => { + const api = await fixture(t); + let body = {}; + for (let i = 0; i < 70; i++) body = { nested: body }; + const response = await fetch(api.url + "/v3/analysis", post(body)); + assert.equal(response.status, 400); + assert.equal((await response.json()).code, "INVALID_JSON"); + assert.equal(api.loads.length, 0); +}); diff --git a/apps/api/test/metrics.test.mjs b/apps/api/test/metrics.test.mjs new file mode 100644 index 000000000..4f5a5add7 --- /dev/null +++ b/apps/api/test/metrics.test.mjs @@ -0,0 +1,184 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { z } from "zod"; +import { analyzeReports } from "../dist/metrics/engine.js"; +import { season2026 } from "../dist/metrics/season2026.js"; +import { prepareFacts } from "../dist/metrics/facts.js"; +import { defineMetric, MetricRegistry } from "../dist/metrics/registry.js"; +import { report, event } from "./fixtures.mjs"; + +const request = (metrics, extras = {}) => ({ + teams: [8033], + metrics, + season: 2026, + timeline: false, + ...extras, +}); +const values = (reports, metrics) => + analyzeReports(reports, request(metrics), season2026).teams["8033"].metrics; +test("rates pool quantities and durations across reports before computing a match", () => { + const a = report({ + events: [event("START_FEEDING", 1), event("STOP_FEEDING", 11, 10)], + }); + const b = report({ + uuid: "report2", + events: [event("START_FEEDING", 1), event("STOP_FEEDING", 6, 30)], + }); + assert.equal(values([a, b], ["feedingRate"]).feedingRate.value, 40 / 15); + assert.equal(values([report()], ["feedingRate"]).feedingRate.value, null); + assert.equal(values([report()], ["totalBallsFed"]).totalBallsFed.value, 0); +}); +test("matches have equal weight regardless of the number of scouts", () => { + const reports = [ + report({ driverAbility: 5 }), + report({ uuid: "b", driverAbility: 5 }), + report({ uuid: "c", matchKey: "qm2", driverAbility: 1 }), + ]; + const result = values(reports, ["driverAbility"]).driverAbility; + assert.deepEqual(result, { value: 3, samples: 2, version: 1 }); +}); +test("recency weighting is deterministic for shuffled input and tied dates", () => { + const a = report({ + driverAbility: 1, + tournamentKey: "a", + tournamentDate: "2026-01-01", + }); + const b = report({ + uuid: "b", + driverAbility: 5, + tournamentKey: "b", + tournamentDate: "2026-03-01", + }); + assert.equal(values([b, a], ["driverAbility"]).driverAbility.value, 4.2); + assert.deepEqual( + values([a, b], ["driverAbility"]), + values([b, a], ["driverAbility"]), + ); +}); +test("facts pair valid intervals once and preserve input ordering", () => { + const input = report({ + events: [ + event("STOP_FEEDING", 10), + event("START_FEEDING", 1), + event("START_FEEDING", 4), + event("STOP_FEEDING", 11), + event("START_SCORING", 20), + event("STOP_SCORING", 20.2, 1), + ], + }); + const before = structuredClone(input); + assert.equal(prepareFacts(input).durations.START_FEEDING, 9); + assert.equal(prepareFacts(input).durations.START_SCORING, undefined); + assert.deepEqual(input, before); +}); +test("dependencies and aliases evaluate once and hidden dependencies stay hidden", () => { + const r = values( + [ + report({ + events: [ + event("START_DEFENDING", 1), + event("STOP_DEFENDING", 5), + event("START_CAMPING", 10), + event("STOP_CAMPING", 12), + ], + }), + ], + ["totalDefenseTime", "totalBallThroughPut"], + ); + assert.equal(r.totalDefenseTime.value, 6); + assert.equal(r.totalBallThroughput.value, 0); + assert.equal(r.contactDefenseTime, undefined); +}); +test("categorical metrics count match proportions and preserve zero categories", () => { + const result = values( + [report(), report({ uuid: "b", robotRoles: ["DEFENDING"] })], + ["robotRole"], + ).robotRole.value; + assert.equal(result.CYCLING, 0.5); + assert.equal(result.DEFENDING, 0.5); + assert.equal(result.IMMOBILE, 0); +}); +test("points apply accuracy once and keep climb points separate", () => { + const r = report({ + accuracy: 1, + autoClimb: "SUCCEEDED", + endgameClimb: "L2", + events: [event("STOP_SCORING", 20, 10), event("STOP_SCORING", 40, 20)], + }); + assert.equal(values([r], ["totalPoints"]).totalPoints.value, 51.5); + assert.equal(values([r], ["autoPoints"]).autoPoints.value, 20.5); +}); +test("climb metrics distinguish missing, failed and successful attempts", () => { + const a = report({ events: [event("CLIMB", 20), event("CLIMB", 140)] }); + assert.equal( + values([a], ["autoClimbStartTime"]).autoClimbStartTime.value, + null, + ); + assert.equal( + values([report({ ...a, autoClimb: "SUCCEEDED" })], ["autoClimbStartTime"]) + .autoClimbStartTime.value, + 3, + ); + assert.equal( + values([report({ ...a, endgameClimb: "L2" })], ["l2StartTime"]).l2StartTime + .value, + 18, + ); +}); +test("no data returns null with zero samples and timeline is optional", () => { + const result = analyzeReports([], request(["totalPoints"]), season2026).teams[ + "8033" + ]; + assert.deepEqual(result.metrics.totalPoints, { + value: null, + samples: 0, + version: 1, + }); + assert.equal(result.timeline, undefined); + assert.equal( + analyzeReports( + [report()], + request(["totalPoints"], { timeline: true }), + season2026, + ).teams["8033"].timeline.length, + 1, + ); +}); +test("registry rejects cycles, alias collisions and unknown dependencies", () => { + const base = season2026.get("totalPoints"); + const def = (id, dependencies = [], aliases = []) => ({ + ...base, + metadata: { ...base.metadata, id, dependencies, aliases }, + }); + assert.throws( + () => new MetricRegistry([def("a", ["b"]), def("b", ["a"])]), + /cycle/, + ); + assert.throws( + () => new MetricRegistry([def("a"), def("b", [], ["a"])]), + /Duplicate/, + ); + assert.throws(() => new MetricRegistry([def("a", ["missing"])]), /Unknown/); +}); +test("custom structured metrics are schema validated", () => { + const custom = defineMetric({ + metadata: { + ...season2026.get("totalPoints").metadata, + id: "custom", + kind: "structured", + }, + output: z.object({ maximum: z.number() }), + calculate: (f) => f.report.driverAbility, + reports: (v) => ({ maximum: Math.max(...v) }), + aggregate: (v) => + v.length ? { maximum: Math.max(...v.map((x) => x.maximum)) } : null, + }); + assert.deepEqual( + analyzeReports( + [report()], + request(["custom"]), + new MetricRegistry([custom]), + ).teams["8033"].metrics.custom.value, + { maximum: 3 }, + ); +}); diff --git a/apps/api/test/providers.test.mjs b/apps/api/test/providers.test.mjs new file mode 100644 index 000000000..1251fe4ed --- /dev/null +++ b/apps/api/test/providers.test.mjs @@ -0,0 +1,87 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { generateKeyPair, exportJWK, SignJWT } from "jose"; +import { createJwtVerifier } from "../dist/auth.js"; +import { createProvisioner } from "../dist/provision.js"; + +test("JWT verification uses real signatures and cached JWKS while rejecting invalid claims", async () => { + const { publicKey, privateKey } = await generateKeyPair("RS256"); + const jwk = { + ...(await exportJWK(publicKey)), + kid: "fixture", + alg: "RS256", + use: "sig", + }; + let fetches = 0; + const issuer = "https://auth.test.invalid/", + audience = "https://api.lovat.app"; + const verify = createJwtVerifier({ + issuer, + audience, + fetch: async (url, init) => { + assert.equal(String(url), issuer + ".well-known/jwks.json"); + assert.equal(new Headers(init?.headers).has("authorization"), false); + fetches++; + return Response.json({ keys: [jwk] }); + }, + }); + const token = (claims = {}, key = privateKey) => + new SignJWT({ sub: "synthetic-user" }) + .setProtectedHeader({ alg: "RS256", kid: "fixture" }) + .setIssuer(claims.issuer ?? issuer) + .setAudience(claims.audience ?? audience) + .setExpirationTime(claims.expires ?? "5m") + .sign(key); + const valid = await token(); + assert.equal((await verify(valid)).sub, "synthetic-user"); + assert.equal((await verify(valid)).sub, "synthetic-user"); + assert.equal(fetches, 1); + for (const claims of [ + { issuer: "https://wrong.test.invalid/" }, + { audience: "wrong" }, + { expires: 0 }, + ]) + await assert.rejects(verify(await token(claims))); + const wrong = await generateKeyPair("RS256"); + await assert.rejects(verify(await token({}, wrong.privateKey))); + await assert.rejects(verify("malformed")); + assert.equal(fetches, 1); +}); +test("profile hydration checks subject and provider failures before any database write", async () => { + let writes = 0; + const db = { + user: { + upsert: async () => { + writes++; + }, + }, + }; + const provision = (body) => + createProvisioner(db, "https://auth.test.invalid/", async (url, init) => { + assert.equal(String(url), "https://auth.test.invalid/userinfo"); + assert.equal(init.headers.Authorization, "Bearer synthetic"); + return Response.json(body); + }); + await provision({ + sub: "subject", + email: "fixture@example.invalid", + email_verified: true, + })("synthetic", "subject"); + assert.equal(writes, 1); + await assert.rejects( + provision({ sub: "another", email: "fixture@example.invalid" })( + "synthetic", + "subject", + ), + { code: "INVALID_IDENTITY" }, + ); + const unavailable = createProvisioner( + db, + "https://auth.test.invalid/", + async () => new Response("", { status: 503 }), + ); + await assert.rejects(unavailable("synthetic", "subject"), { + code: "IDENTITY_UNAVAILABLE", + }); + assert.equal(writes, 1); +}); diff --git a/apps/api/test/qualification-process.mjs b/apps/api/test/qualification-process.mjs new file mode 100644 index 000000000..7b383c08f --- /dev/null +++ b/apps/api/test/qualification-process.mjs @@ -0,0 +1,94 @@ +import { fileURLToPath } from "node:url"; +import { mkdir, mkdtemp } from "node:fs/promises"; +import { join } from "node:path"; +export async function startQualificationService(executable, app, env) { + let resolveReady, rejectReady; + const ready = new Promise((resolve, reject) => { + resolveReady = resolve; + rejectReady = reject; + }); + const scratch = fileURLToPath( + new URL("../../../.migration-work/", import.meta.url), + ); + await mkdir(scratch, { recursive: true }); + // An empty cwd and explicit environment prevent loading any private app .env. + const cwd = await mkdtemp(join(scratch, "qualification-")); + const inherited = Object.fromEntries( + ["PATH", "SystemRoot", "TEMP", "TMP", "LOCALAPPDATA"] + .filter((name) => process.env[name]) + .map((name) => [name, process.env[name]]), + ); + const child = Bun.spawn( + [ + executable, + fileURLToPath( + new URL( + "../../" + app + "/tools/serve-qualification.mjs", + import.meta.url, + ), + ), + ], + { + cwd, + env: { ...inherited, ...env, LOVAT_LOCAL_QUALIFICATION: "1" }, + stdin: "pipe", + stdout: "pipe", + stderr: "pipe", + }, + ); + const diagnostics = new Response(child.stderr).text(); + void (async () => { + const decoder = new TextDecoder(); + let buffer = ""; + for await (const chunk of child.stdout) { + buffer += decoder.decode(chunk, { stream: true }); + let end; + while ((end = buffer.indexOf("\n")) >= 0) { + const line = buffer.slice(0, end); + buffer = buffer.slice(end + 1); + try { + const message = JSON.parse(line); + if (message.type === "ready") resolveReady(message.url); + } catch { + /* Other process logs are not protocol messages. */ + } + } + } + })().catch(rejectReady); + child.exited.then((code) => + rejectReady(Error("Qualification service exited " + code)), + ); + const timer = setTimeout(() => { + child.kill(); + rejectReady(Error("Qualification startup timed out")); + }, 30000); + let url; + try { + url = await ready; + } catch (error) { + child.kill(); + throw Error(error.message + ": " + (await diagnostics).slice(-2000)); + } finally { + clearTimeout(timer); + } + return { + url, + async stop() { + if (child.exitCode === 0) return; + if (child.exitCode !== null) + throw Error("Qualification service exited unexpectedly"); + child.stdin.write(JSON.stringify({ type: "stop" }) + "\n"); + child.stdin.end(); + const deadline = setTimeout(() => child.kill(), 20000); + try { + if ((await child.exited) !== 0) + throw Error( + "Qualification shutdown failed: " + + (await diagnostics).slice(-2000), + ); + } finally { + clearTimeout(deadline); + } + }, + }; +} diff --git a/apps/api/test/repository.test.mjs b/apps/api/test/repository.test.mjs new file mode 100644 index 000000000..bb38218bc --- /dev/null +++ b/apps/api/test/repository.test.mjs @@ -0,0 +1,42 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createRepository } from "../dist/repository.js"; +import { scope } from "./fixtures.mjs"; +test("repository applies source, reliability, training and season restrictions", async () => { + const calls = []; + const repository = createRepository({ + scoutReport: { + findMany: async (query) => { + calls.push(query); + return []; + }, + }, + event: { + findMany: async () => { + throw new Error("Scalar metric must not load events"); + }, + }, + }); + await repository.loadReports( + scope, + { teams: [8033], season: 2026 }, + new Set(["driverAbility"]), + ); + const where = calls[0].where; + assert.deepEqual(where.scouter.sourceTeamNumber, { in: [8033] }); + assert.deepEqual(where.teamMatchData.tournamentKey, { notIn: [] }); + assert.deepEqual(where.reliability.in, ["VERIFIED", "UNVERIFIED"]); + assert.equal(where.training, false); + assert.equal(where.teamMatchData.matchType.not, "PRACTICE"); + assert.equal(where.teamMatchData.tournament.seasonYear, 2026); + assert.equal(calls[0].take, 5001); +}); +test("repository refuses oversized datasets rather than silently truncating", async () => { + const repository = createRepository({ + scoutReport: { findMany: async () => Array(5001).fill({ uuid: "x" }) }, + }); + await assert.rejects( + repository.loadReports(scope, { teams: [8033], season: 2026 }, new Set()), + { code: "ANALYSIS_TOO_LARGE" }, + ); +}); diff --git a/apps/api/test/rollback.qualification.mjs b/apps/api/test/rollback.qualification.mjs new file mode 100644 index 000000000..418e2e913 --- /dev/null +++ b/apps/api/test/rollback.qualification.mjs @@ -0,0 +1,251 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { randomUUID, createHash } from "node:crypto"; +import { startQualificationService } from "./qualification-process.mjs"; +import { createState } from "../dist/state.js"; + +const database = new URL( + process.env.DATABASE_URL ?? "postgresql://localhost/missing", +); +const redis = new URL(process.env.REDIS_URL ?? "redis://localhost/missing"); +if ( + process.env.LOVAT_DB_TEST !== "1" || + database.hostname !== "127.0.0.1" || + database.pathname !== "/lovat_test" || + redis.hostname !== "127.0.0.1" +) + throw Error("Use disposable loopback lovat_test and Redis"); +const node = process.env.LOVAT_NODE_EXECUTABLE ?? Bun.which("node"); +if ( + !node || + new TextDecoder().decode(Bun.spawnSync([node, "--version"]).stdout).trim() !== + "v22.20.0" +) + throw Error("Run with Node 22.20.0 on PATH or LOVAT_NODE_EXECUTABLE"); +const { createDb } = await import("@lovat/db"); +test( + "traffic rollback retains reports, API keys and tenant boundaries without rolling back schema", + { timeout: 60000 }, + async (t) => { + const db = createDb(database.href, { maxConnections: 4 }); + const suffix = randomUUID(), + prefix = "lovat:qualification:" + suffix + ":"; + const state = createState(redis.href, prefix); + const own = 1500000000 + Math.floor(Math.random() * 10000000), + other = own + 1, + robot = own + 2; + const event = "2026-qualification-" + suffix, + slot = event + "_qm1_0", + scout = randomUUID(); + const user = "qualification|" + suffix, + foreignUser = user + "-foreign"; + const uuids = [randomUUID(), randomUUID()]; + let native, legacy; + const keys = Array.from( + { length: 4 }, + () => + "lvt-" + + randomUUID().replaceAll("-", "") + + randomUUID().replaceAll("-", ""), + ); + t.after(async () => { + try { + await native?.stop(); + } finally { + try { + await legacy?.stop(); + } finally { + await state.connect(); + for await (const names of state.client.scanIterator({ + MATCH: prefix + "*", + COUNT: 100, + })) { + if (names.some((name) => !name.startsWith(prefix))) + throw Error("Unexpected Redis namespace"); + if (names.length) await state.client.del(names); + } + await state.close(); + await db.scoutReportInProgress.deleteMany({ + where: { uuid: { in: uuids } }, + }); + await db.apiOutbox.deleteMany({ + where: { dedupeKey: { startsWith: "analysis:" + robot + ":" } }, + }); + await db.analysisRevision.deleteMany({ + where: { teamNumber: robot }, + }); + await db.tournament.deleteMany({ where: { key: event } }); + await db.user.deleteMany({ + where: { id: { in: [user, foreignUser] } }, + }); + await db.registeredTeam.deleteMany({ + where: { number: { in: [own, other] } }, + }); + await db.team.deleteMany({ + where: { number: { in: [own, other, robot] } }, + }); + await db.$disconnect(); + } + } + }); + const migrations = + await db.$queryRaw`SELECT migration_name FROM "_prisma_migrations" WHERE finished_at IS NOT NULL ORDER BY migration_name`; + await db.season.upsert({ + where: { year: 2026 }, + create: { year: 2026 }, + update: {}, + }); + await db.team.createMany({ + data: [own, other, robot].map((number) => ({ + number, + name: "Synthetic rollback fixture", + })), + }); + for (const number of [own, other]) + await db.registeredTeam.create({ + data: { + number, + code: suffix + number, + email: suffix + number + "@example.invalid", + emailVerified: true, + }, + }); + await db.scouter.create({ + data: { uuid: scout, sourceTeamNumber: own, name: "Synthetic scouter" }, + }); + for (const [id, number] of [ + [user, own], + [foreignUser, other], + ]) + await db.user.create({ + data: { + id, + email: id.replace("|", "-") + "@example.invalid", + teamNumber: number, + role: "SCOUTING_LEAD", + teamSourceRule: { mode: "INCLUDE", items: [number] }, + tournamentSourceRule: { mode: "INCLUDE", items: [event] }, + }, + }); + for (const [index, key] of keys.entries()) + await db.apiKey.create({ + data: { + name: "Synthetic rollback key", + userId: index === 3 ? foreignUser : user, + keyHash: createHash("sha256").update(key).digest("hex"), + }, + }); + await db.tournament.create({ + data: { + key: event, + name: "Synthetic rollback fixture", + seasonYear: 2026, + }, + }); + await db.teamMatchData.create({ + data: { + key: slot, + tournamentKey: event, + teamNumber: robot, + matchType: "QUALIFICATION", + matchNumber: 1, + }, + }); + const env = { + DATABASE_URL: database.href, + REDIS_URL: redis.href, + REDIS_KEY_PREFIX: prefix, + LOVAT_DB_TEST: "1", + AUTH0_ISSUER: "https://auth.test.invalid/", + AUTH0_AUDIENCE: "https://api.lovat.app", + AUTH0_DOMAIN: "auth.test.invalid", + POSTHOG_PROJECT_API_KEY: "synthetic-qualification", + NODE_ENV: "test", + HOST: "127.0.0.1", + PORT: "0", + }; + native = await startQualificationService(process.execPath, "api", env); + legacy = await startQualificationService(node, "server", env); + assert.equal((await fetch(native.url + "/health/ready")).status, 200); + const startTime = Date.now() - 50000; + const data = { + notes: "Synthetic rollback note", + robotRoles: ["SCORING"], + mobility: "NONE", + beached: "NEITHER", + feederTypes: [], + intakeType: "NEITHER", + driverAbility: 3, + accuracy: null, + disrupts: false, + defenseEffectiveness: 0, + scoresWhileMoving: false, + autoClimb: "NOT_ATTEMPTED", + endgameClimb: "NOT_ATTEMPTED", + events: [ + [0, 2, 8], + [10, 0, 2], + [20, 1, 2, 5], + ], + }; + const envelope = { + uuid: uuids[0], + scouterUuid: scout, + teamNumber: robot, + tournamentKey: event, + matchType: "QUALIFICATION", + matchNumber: 1, + season: 2026, + gameId: "frc-2026", + gameVersion: 1, + reportVersion: 1, + startTime, + endTime: startTime + 30000, + data, + }; + const response = await fetch(native.url + "/v3/reports", { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Team-Code": suffix + own, + "X-Scouter-Uuid": scout, + "X-Device-Id": suffix, + }, + body: JSON.stringify(envelope), + }); + assert.equal(response.status, 201, JSON.stringify(await response.json())); + const read = (base, uuid, key) => + fetch(base + "/v1/manager/scoutreports/" + uuid, { + headers: { Authorization: "Bearer " + key }, + }); + const before = await read(legacy.url, uuids[0], keys[0]); + assert.equal(before.status, 200); + const saved = await before.json(); + assert.equal(saved.scoutReport.notes, data.notes); + assert.equal(saved.events.length, data.events.length); + assert.equal((await read(legacy.url, uuids[0], keys[3])).status, 404); + assert.equal((await read(native.url, uuids[0], keys[3])).status, 404); + const oldUpload = await fetch(legacy.url + "/collection/scoutreports", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ ...data, ...envelope, uuid: uuids[1] }), + }); + assert.equal(oldUpload.status, 200, await oldUpload.text()); + const forward = await read(native.url, uuids[1], keys[2]); + assert.equal(forward.status, 200); + assert.equal((await forward.json()).scoutReport.notes, data.notes); + await native.stop(); + native = undefined; + const after = await read(legacy.url, uuids[0], keys[1]); + assert.equal(after.status, 200); + assert.equal((await after.json()).scoutReport.uuid, uuids[0]); + assert.equal( + await db.scoutReport.count({ where: { uuid: { in: uuids } } }), + 2, + ); + assert.deepEqual( + await db.$queryRaw`SELECT migration_name FROM "_prisma_migrations" WHERE finished_at IS NOT NULL ORDER BY migration_name`, + migrations, + ); + }, +); diff --git a/apps/api/test/services.integration.mjs b/apps/api/test/services.integration.mjs new file mode 100644 index 000000000..1fc349c95 --- /dev/null +++ b/apps/api/test/services.integration.mjs @@ -0,0 +1,730 @@ +import { startApi } from "../dist/runtime.js"; +import { createSignatureVerifier } from "../dist/signatures.js"; +import { createAnalysisService } from "../dist/analysis.js"; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { randomUUID, createHmac } from "node:crypto"; +import { once } from "node:events"; +import { createApi } from "../dist/app.js"; +import { createServices } from "../dist/services/index.js"; +import { createRepository } from "../dist/repository.js"; +import { accessScope } from "../dist/auth.js"; + +const url = new URL( + process.env.DATABASE_URL ?? "postgresql://localhost/missing", +); +if ( + process.env.LOVAT_DB_TEST !== "1" || + !["127.0.0.1", "localhost"].includes(url.hostname) || + url.pathname !== "/lovat_test" +) { + throw new Error( + "Use a disposable loopback lovat_test database with LOVAT_DB_TEST=1", + ); +} +const { createDb } = await import("@lovat/db"); +const db = createDb(url.href, { maxConnections: 4, statementTimeoutMs: 8000 }); +test("rewritten services preserve atomic report lifecycle, idempotency and tenant boundaries", async (t) => { + const suffix = randomUUID(); + const own = 1000000000 + Math.floor(Math.random() * 100000000); + const other = own + 1; + const robot = own + 2; + const scout = randomUUID(); + const eventKey = "2026-rewrite-" + suffix; + const matchKey = eventKey + "_qm1"; + const actorId = "rewrite|" + suffix; + const actor = { + id: actorId, + teamNumber: own, + role: "SCOUTING_LEAD", + teamSourceRule: { mode: "INCLUDE", items: [own] }, + tournamentSourceRule: { mode: "EXCLUDE", items: [] }, + team: { emailVerified: true }, + }; + await db.season.upsert({ + where: { year: 2026 }, + create: { year: 2026 }, + update: {}, + }); + for (const number of [own, other, robot]) + await db.team.create({ data: { number, name: "Synthetic rewrite test" } }); + for (const number of [own, other]) + await db.registeredTeam.create({ + data: { + number, + code: suffix + number, + email: number + "@example.invalid", + emailVerified: true, + teamApproved: true, + }, + }); + await db.user.create({ + data: { + id: actorId, + teamNumber: own, + email: suffix + "@example.invalid", + role: "SCOUTING_LEAD", + teamSourceRule: actor.teamSourceRule, + tournamentSourceRule: actor.tournamentSourceRule, + }, + }); + await db.scouter.create({ + data: { uuid: scout, sourceTeamNumber: own, name: "Synthetic scout" }, + }); + await db.tournament.create({ + data: { + key: eventKey, + name: "Synthetic rewrite test", + seasonYear: 2026, + date: "2026-03-01", + }, + }); + await db.match.create({ + data: { + key: matchKey, + tournamentKey: eventKey, + competitionLevel: "QUALIFICATION", + setNumber: 1, + matchNumber: 1, + }, + }); + await db.teamMatchData.create({ + data: { + key: matchKey + "_0", + matchKey, + tournamentKey: eventKey, + matchType: "QUALIFICATION", + matchNumber: 1, + teamNumber: robot, + alliance: "RED", + station: 1, + }, + }); + const repository = createRepository(db); + const api = createApi({ + repository, + authenticate: async () => accessScope(actor), + ready: async () => true, + services: { + router: createServices({ + baseUrl: "https://api.example", + commit: "test", + analyze: createAnalysisService(repository), + }), + db, + verifySignature: createSignatureVerifier({ + lovatKey: "test-signing-key", + }), + authenticate: async (authorization) => ({ + user: + authorization === "Bearer newbie" || authorization === "Bearer join" + ? await db.user.findUniqueOrThrow({ + where: { + id: + actorId + + (authorization === "Bearer newbie" + ? "-onboarding" + : "-join"), + }, + include: { team: { select: { emailVerified: true } } }, + }) + : authorization === "Bearer other" + ? { + ...actor, + id: actorId, + teamNumber: other, + teamSourceRule: { mode: "INCLUDE", items: [other] }, + } + : actor, + tokenType: "jwt", + }), + }, + }); + const runtime = startApi(api, { + port: 0, + hostname: "127.0.0.1", + db, + origins: ["https://allowed.example"], + }); + const base = runtime.url; + async function call(method, path, body, extras = {}) { + return fetch(base + path, { + method, + headers: { + "Content-Type": "application/json", + Authorization: "Bearer own", + "X-Team-Code": suffix + own, + "X-Scouter-Uuid": scout, + "X-Device-Id": suffix, + ...extras, + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + } + t.after(async () => { + await runtime.stop(true); + await db.trainingVideo.deleteMany({ where: { matchKey } }); + await db.analysisRevision.deleteMany({ where: { teamNumber: robot } }); + await db.apiOutbox.deleteMany({ + where: { dedupeKey: { startsWith: "analysis:" + robot + ":" } }, + }); + await db.tournament.delete({ where: { key: eventKey } }); + const codes = await db.emailVerificationRequest.findMany({ + where: { teamNumber: { in: [own, other, robot] } }, + select: { verificationCode: true }, + }); + await db.apiOutbox.deleteMany({ + where: { + OR: [ + { + dedupeKey: { + in: codes.map((row) => "verify:" + row.verificationCode), + }, + }, + { + payload: { path: ["to"], equals: suffix + "-team@example.invalid" }, + }, + ], + }, + }); + await db.emailVerificationRequest.deleteMany({ + where: { teamNumber: { in: [own, other, robot] } }, + }); + await db.registeredTeam.deleteMany({ + where: { number: { in: [own, other, robot] } }, + }); + await db.team.deleteMany({ + where: { number: { in: [own, other, robot] } }, + }); + await db.$disconnect(); + }); + const uuid = randomUUID(); + const startTime = Date.now() - 180000; + const endTime = startTime + 150000; + const report = { + uuid, + scouterUuid: scout, + tournamentKey: eventKey, + matchType: "QUALIFICATION", + matchNumber: 1, + teamNumber: robot, + startTime, + notes: "Synthetic test", + robotRoles: ["SCORING"], + mobility: "NONE", + beached: "NEITHER", + feederTypes: [], + intakeType: "NEITHER", + driverAbility: 3, + accuracy: null, + disrupts: false, + defenseEffectiveness: 0, + scoresWhileMoving: false, + autoClimb: "NOT_ATTEMPTED", + endgameClimb: "NOT_ATTEMPTED", + events: [ + [0, 2, 8], + [10, 0, 2], + [20, 1, 2, 5], + ], + }; + assert.equal( + (await call("POST", "/collection/load/" + matchKey + "/" + robot, { uuid })) + .status, + 201, + ); + assert.equal( + (await call("POST", "/collection/start", { uuid, startTime })).status, + 200, + ); + assert.equal( + (await call("POST", "/collection/start", { uuid, startTime })).status, + 200, + ); + assert.equal( + ( + await call("POST", "/collection/start", { + uuid, + startTime: startTime + 1, + }) + ).status, + 409, + ); + assert.equal((await call("POST", "/collection/submit", report)).status, 409); + assert.equal( + (await call("POST", "/collection/end", { uuid, endTime })).status, + 200, + ); + assert.equal((await call("POST", "/collection/submit", report)).status, 200); + assert.equal((await call("POST", "/collection/submit", report)).status, 200); + assert.equal( + ( + await call("POST", "/collection/submit", { + ...report, + notes: "different", + }) + ).status, + 409, + ); + assert.equal(await db.scoutReport.count({ where: { uuid } }), 1); + assert.equal(await db.event.count({ where: { scoutReportUuid: uuid } }), 3); + assert.equal( + ( + await call("GET", "/v1/manager/scoutreports/" + uuid, undefined, { + Authorization: "Bearer other", + }) + ).status, + 404, + ); + assert.equal( + ( + await call("DELETE", "/v1/manager/scoutreports/" + uuid, undefined, { + Authorization: "Bearer other", + }) + ).status, + 404, + ); + const analysis = await call("POST", "/v3/analysis", { + teams: [robot], + metrics: ["totalPoints"], + }); + assert.equal(analysis.status, 200); + assert.equal( + (await analysis.json()).teams[String(robot)].metrics.totalPoints.value, + 5, + ); + const picklist = await call("POST", "/v1/manager/mutablepicklists", { + name: "Synthetic", + teams: [robot], + }); + assert.equal(picklist.status, 200); + const lists = await ( + await call("GET", "/v1/manager/mutablepicklists") + ).json(); + assert.equal(lists.length, 1); + assert.equal( + ( + await call( + "PUT", + "/v1/manager/mutablepicklists/" + lists[0].uuid, + { name: "stolen", teams: [] }, + { Authorization: "Bearer other" }, + ) + ).status, + 404, + ); + assert.equal( + ( + await call("POST", "/collection/scouter", { + name: "foreign", + teamNumber: other, + }) + ).status, + 403, + ); + + assert.equal( + await db.analysisRevision.count({ where: { teamNumber: robot } }), + 1, + ); + const revision = await db.analysisRevision.findUniqueOrThrow({ + where: { teamNumber: robot }, + }); + assert.equal(revision.revision, 1n); + assert.equal( + await db.apiOutbox.count({ + where: { dedupeKey: "analysis:" + robot + ":1" }, + }), + 1, + ); + const minimal = await ( + await call("GET", "/v1/analysis/scoutreports/match/" + matchKey + "_0") + ).json(); + assert.equal(minimal[0].scouter.name, "Synthetic scout"); + assert.equal(minimal[0].canModify, true); + assert.equal(typeof minimal[0].startTime, "string"); + assert.equal( + ( + await ( + await call("GET", "/v1/manager/scouterreports?scouterUuid=" + scout) + ).json() + )[0].teamMatchData.tournament.name, + "Synthetic rewrite test", + ); + const metric = await ( + await call("GET", "/v1/analysis/category/team/" + robot) + ).json(); + assert.equal(metric.totalPoints, 5); + const badSignature = await call( + "POST", + "/v1/manager/onboarding/verifyemail", + { code: "invalid" }, + ); + assert.equal(badSignature.status, 403); + const keyReply = await call("POST", "/v1/manager/apikey?name=Synthetic"); + const apiKey = (await keyReply.json()).apiKey; + assert.ok(apiKey.startsWith("lvt-")); + const storedKeys = await (await call("GET", "/v1/manager/apikey")).json(); + assert.equal(storedKeys[0].keyHash, undefined); + const keyRow = await db.apiKey.findFirstOrThrow({ + where: { userId: actorId }, + }); + assert.notEqual(keyRow.keyHash, apiKey); + assert.equal( + (await call("DELETE", "/v1/manager/apikey?uuid=" + keyRow.uuid)).status, + 200, + ); + assert.equal((await call("POST", "/v1/manager/noteam", {})).status, 409); + const answerUuid = randomUUID(), + videoUuid = randomUUID(); + const original = await db.scoutReport.findUniqueOrThrow({ where: { uuid } }); + await db.scoutReport.create({ + data: { + ...original, + uuid: answerUuid, + training: true, + events: { + create: [ + { + time: 0, + action: "START_MATCH", + position: "NONE", + points: 0, + quantity: 0, + }, + ], + }, + }, + }); + await db.trainingVideo.create({ + data: { + uuid: videoUuid, + matchKey, + videoLink: "https://example.invalid/video", + durationSeconds: 1, + answerKeyReports: { connect: { uuid: answerUuid } }, + }, + }); + const created = await call("POST", "/collection/training/sessions", { + videoUuid, + }); + assert.equal(created.status, 201); + const session = await created.json(); + const paired = await call("POST", "/collection/train/" + session.uuid, { + pairingToken: session.pairingToken, + deviceName: "Synthetic device", + }); + assert.equal(paired.status, 200); + const participant = await paired.json(); + assert.equal(participant.snapshot.video.postMatchSeconds, 15); + const attemptHeaders = { + Authorization: "Bearer " + participant.attemptToken, + }; + const trainingUuid = randomUUID(); + assert.equal( + ( + await call("POST", "/collection/load/" + matchKey + "/" + robot, { + uuid: trainingUuid, + trainingAttemptUuid: participant.attemptUuid, + }) + ).status, + 201, + ); + assert.equal( + ( + await call( + "POST", + "/collection/training/sessions/" + session.uuid + "/ready", + { attemptUuid: participant.attemptUuid, stage: "LOBBY" }, + attemptHeaders, + ) + ).status, + 200, + ); + const browser = { Authorization: "Bearer " + session.browserToken }; + assert.equal( + ( + await call( + "POST", + "/collection/training/sessions/" + session.uuid + "/control", + { action: "arm" }, + browser, + ) + ).status, + 200, + ); + assert.equal( + ( + await call( + "POST", + "/collection/training/sessions/" + session.uuid + "/control", + { action: "play" }, + browser, + ) + ).status, + 409, + ); + assert.equal( + ( + await call( + "POST", + "/collection/training/sessions/" + session.uuid + "/ready", + { attemptUuid: participant.attemptUuid, stage: "ARMED" }, + attemptHeaders, + ) + ).status, + 200, + ); + assert.equal( + ( + await call( + "POST", + "/collection/training/sessions/" + session.uuid + "/control", + { action: "play" }, + browser, + ) + ).status, + 200, + ); + assert.equal( + ( + await call( + "POST", + "/collection/training/sessions/" + session.uuid + "/control", + { action: "end" }, + browser, + ) + ).status, + 409, + ); + await db.trainingSession.update({ + where: { uuid: session.uuid }, + data: { startedAt: new Date(Date.now() - 30000) }, + }); + assert.equal( + ( + await call( + "POST", + "/collection/training/sessions/" + session.uuid + "/control", + { action: "end" }, + browser, + ) + ).status, + 200, + ); + const trainingStart = Date.now() - 30000; + assert.equal( + ( + await call("POST", "/collection/start", { + uuid: trainingUuid, + startTime: trainingStart, + }) + ).status, + 200, + ); + assert.equal( + ( + await call("POST", "/collection/end", { + uuid: trainingUuid, + endTime: trainingStart + 1000, + }) + ).status, + 200, + ); + const trainingReport = { + ...report, + uuid: trainingUuid, + startTime: trainingStart, + events: [[0, 2, 8]], + }; + assert.equal( + ( + await call( + "POST", + "/collection/training/" + session.uuid + "/submit", + trainingReport, + ) + ).status, + 200, + ); + assert.equal( + await db.trainingScore.count({ where: { reportUuid: trainingUuid } }), + 1, + ); + assert.equal( + ( + await call( + "POST", + "/collection/training/" + session.uuid + "/submit", + trainingReport, + ) + ).status, + 200, + ); + assert.equal( + await db.trainingScore.count({ where: { reportUuid: trainingUuid } }), + 1, + ); + assert.equal( + ( + await db.analysisRevision.findUniqueOrThrow({ + where: { teamNumber: robot }, + }) + ).revision, + 1n, + ); + const privateSnapshot = await call( + "GET", + "/collection/training/sessions/" + + session.uuid + + "?attempt=" + + participant.attemptUuid, + undefined, + attemptHeaders, + ); + assert.equal(privateSnapshot.status, 200); + assert.equal((await privateSnapshot.json()).participants.length, 1); + assert.equal( + ( + await call( + "GET", + "/collection/training/sessions/" + session.uuid, + undefined, + { Authorization: "Bearer invalid" }, + ) + ).status, + 404, + ); + + const socket = new WebSocket( + base.replace("http:", "ws:") + "/collection/training/socket", + { headers: { Origin: "https://allowed.example" } }, + ); + await once(socket, "open"); + const initial = once(socket, "message"); + socket.send( + JSON.stringify({ sessionUuid: session.uuid, token: session.browserToken }), + ); + const [raw] = await initial; + assert.equal(JSON.parse(raw.data).uuid, session.uuid); + const closing = once(socket, "close"); + socket.close(); + await closing; + const rejected = new WebSocket( + base.replace("http:", "ws:") + "/collection/training/socket", + { headers: { Origin: "https://allowed.example" } }, + ); + await once(rejected, "open"); + const denial = once(rejected, "close"); + rejected.send( + JSON.stringify({ sessionUuid: session.uuid, token: "x".repeat(43) }), + ); + assert.equal((await denial)[0].code, 1008); + + const pathsResponse = await call( + "GET", + "/v1/analysis/metric/autoPoints/team/" + robot, + ); + assert.equal(pathsResponse.status, 200); + assert.equal((await pathsResponse.json()).paths.length, 1); + const reportExport = await call( + "GET", + "/v1/analysis/reportcsv?tournamentKey=" + eventKey, + ); + assert.equal(reportExport.status, 200); + assert.ok((await reportExport.text()).includes("Synthetic test")); + const partialExport = await call( + "GET", + "/v1/analysis/csvplain?tournamentKey=" + eventKey + "&auto=true", + ); + assert.equal(partialExport.status, 200); + assert.ok((await partialExport.text()).includes(String(robot))); + assert.equal( + (await call("GET", "/v1/analysis/metric/not-a-metric/team/" + robot)) + .status, + 400, + ); + assert.deepEqual( + await ( + await call( + "GET", + "/v1/analysis/flag/team/" + + robot + + "?flags=" + + encodeURIComponent(JSON.stringify(["rank"])), + ) + ).json(), + [0], + ); + const onboardingActor = actorId + "-onboarding"; + await db.user.create({ + data: { id: onboardingActor, email: suffix + "-new@example.invalid" }, + }); + const newbie = { Authorization: "Bearer newbie" }; + assert.equal( + ( + await call( + "POST", + "/v1/manager/onboarding/team", + { number: robot, email: suffix + "-team@example.invalid" }, + newbie, + ) + ).status, + 200, + ); + const verification = await db.emailVerificationRequest.findFirstOrThrow({ + where: { teamNumber: robot }, + }); + assert.equal( + await db.apiOutbox.count({ + where: { dedupeKey: "verify:" + verification.verificationCode }, + }), + 1, + ); + const path = "/v1/manager/onboarding/verifyemail", + verifyBody = { code: verification.verificationCode }, + timestamp = Math.floor(Date.now() / 1000); + const signature = createHmac("sha256", "test-signing-key") + .update( + JSON.stringify({ + path, + method: "POST", + body: JSON.stringify(verifyBody), + timestamp, + }), + ) + .digest("hex"); + assert.equal( + ( + await call("POST", path, verifyBody, { + "X-Timestamp": String(timestamp), + "X-Signature": signature, + }) + ).status, + 200, + ); + assert.equal( + (await db.registeredTeam.findUniqueOrThrow({ where: { number: robot } })) + .emailVerified, + true, + ); + const joinActor = actorId + "-join"; + await db.user.create({ + data: { id: joinActor, email: suffix + "-join@example.invalid" }, + }); + assert.equal( + ( + await call( + "POST", + "/v1/manager/onboarding/teamcode?team=" + own + "&code=" + suffix + own, + undefined, + { Authorization: "Bearer join" }, + ) + ).status, + 200, + ); + assert.equal( + (await db.user.findUniqueOrThrow({ where: { id: joinActor } })).teamNumber, + own, + ); +}); diff --git a/apps/api/test/services.test.mjs b/apps/api/test/services.test.mjs new file mode 100644 index 000000000..93c5874a6 --- /dev/null +++ b/apps/api/test/services.test.mjs @@ -0,0 +1,333 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createHash, createHmac } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { createServices } from "../dist/services/index.js"; +import { createAnalysisCache } from "../dist/cache.js"; +import { createIdentityService } from "../dist/identity.js"; +import { createSignatureVerifier } from "../dist/signatures.js"; +import { grade } from "../dist/domain/grading.js"; +import { prediction, csv } from "../dist/domain/prediction.js"; +import { createOfficialReader, rankingSchema } from "../dist/official.js"; +const scope = { + userId: "a", + teamNumber: 1, + role: "ANALYST", + sources: { + teams: { mode: "INCLUDE", items: [1] }, + tournaments: { mode: "EXCLUDE", items: [] }, + }, +}; +const request = { + teams: [8033], + metrics: ["totalPoints"], + season: 2026, + timeline: false, +}; +const response = { + season: 2026, + teams: { + 8033: { metrics: { totalPoints: { value: 10, samples: 1, version: 1 } } }, + }, +}; +test("every inventoried legacy HTTP route has exactly one replacement", () => { + const router = createServices({ + baseUrl: "http://example.invalid", + commit: "test", + analyze: async () => response, + }); + const routes = JSON.parse( + readFileSync(new URL("../legacy-routes.json", import.meta.url)), + ); + for (const route of routes) + assert.equal( + router.endpoints.filter( + (e) => e.method === route.method && e.path === route.path, + ).length, + 1, + route.method + " " + route.path, + ); + assert.equal(router.endpoints.length, routes.length + 2); +}); +test("cache shares concurrent calculations and isolates scopes and revisions", async () => { + let computes = 0, + revision = "0"; + const values = new Map(); + const store = { + generations: async (teams) => teams.map(() => revision), + get: async (key) => values.get(key) ?? null, + set: async (key, value, ttl) => { + assert.equal(ttl, 15); + values.set(key, value); + }, + }; + const cache = createAnalysisCache(store, () => "v1"); + const compute = async () => { + computes++; + await new Promise((r) => setTimeout(r, 5)); + return structuredClone(response); + }; + const [a, b] = await Promise.all([ + cache(scope, request, compute), + cache(scope, request, compute), + ]); + a.teams["8033"].metrics.totalPoints.value = 999; + assert.equal(b.teams["8033"].metrics.totalPoints.value, 10); + assert.equal(computes, 1); + await cache(scope, request, compute); + assert.equal(computes, 1); + await cache( + { + ...scope, + sources: { ...scope.sources, teams: { mode: "INCLUDE", items: [2] } }, + }, + request, + compute, + ); + assert.equal(computes, 2); + revision = "1"; + await cache(scope, request, compute); + assert.equal(computes, 3); +}); +test("corrupt cache is repaired and Redis failure falls back to computation", async () => { + let stored; + const cache = createAnalysisCache( + { + generations: async () => ["0"], + get: async () => "{", + set: async (_k, v) => { + stored = v; + }, + }, + () => "v1", + ); + assert.deepEqual(await cache(scope, request, async () => response), response); + assert.deepEqual(JSON.parse(stored), response); + const unavailable = createAnalysisCache( + { + generations: async () => { + throw Error("offline"); + }, + }, + () => "v1", + ); + assert.deepEqual( + await unavailable(scope, request, async () => response), + response, + ); +}); +test("API keys use hashes and fresh ownership lookup for immediate revocation", async () => { + const token = "lvt-" + "ab".repeat(32); + let revoked = false, + lookups = 0; + const actor = { + id: "a", + teamNumber: 1, + role: "ANALYST", + teamSourceRule: { mode: "INCLUDE", items: [1] }, + tournamentSourceRule: { mode: "EXCLUDE", items: [] }, + team: { emailVerified: true }, + }; + const identity = createIdentityService( + { + apiKey: { + findUnique: async (args) => { + lookups++; + assert.equal( + args.where.keyHash, + createHash("sha256").update(token).digest("hex"), + ); + return revoked ? null : { user: actor }; + }, + }, + }, + { + issuer: "https://identity.example/", + audience: "test", + verify: async () => { + throw Error("JWT should not be used"); + }, + limiter: { + consume: async (_key, limit, window) => { + assert.equal(limit, 1); + assert.equal(window, 3); + return true; + }, + }, + }, + ); + assert.equal((await identity("Bearer " + token)).tokenType, "apiKey"); + revoked = true; + await assert.rejects(identity("Bearer " + token), (e) => e.status === 401); + assert.equal(lookups, 2); +}); +test("JWT accounts hydrate only once and rate limits fail closed", async () => { + let actor = null, + provisions = 0; + const identity = createIdentityService( + { user: { findUnique: async () => actor } }, + { + issuer: "https://identity.example/", + audience: "test", + verify: async () => ({ sub: "a" }), + provision: async () => { + provisions++; + actor = { id: "a" }; + }, + limiter: { consume: async () => true }, + }, + ); + await identity("Bearer jwt"); + await identity("Bearer jwt"); + assert.equal(provisions, 1); + const limited = createIdentityService( + { user: { findUnique: async () => actor } }, + { + issuer: "https://identity.example/", + audience: "test", + verify: async () => ({ sub: "a" }), + limiter: { consume: async () => false }, + }, + ); + await assert.rejects(limited("Bearer jwt"), (e) => e.status === 429); +}); +test("Slack signature binds raw payload and rejects replay and mutation", async () => { + const verify = createSignatureVerifier({ slackSecret: "test-secret" }), + timestamp = String(Math.floor(Date.now() / 1000)), + raw = "text=subscribe+break"; + const signature = + "v0=" + + createHmac("sha256", "test-secret") + .update("v0:" + timestamp + ":" + raw) + .digest("hex"); + const headers = { + "x-slack-request-timestamp": timestamp, + "x-slack-signature": signature, + }; + assert.equal( + await verify(headers, raw, true, "POST", "/v1/slack/command", {}), + true, + ); + assert.equal( + await verify(headers, raw + "x", true, "POST", "/v1/slack/command", {}), + false, + ); + assert.equal( + await verify( + { ...headers, "x-slack-request-timestamp": "1" }, + raw, + true, + "POST", + "/v1/slack/command", + {}, + ), + false, + ); +}); +test("training grading penalizes duplicate and missing events and preserves exclusions", () => { + const expected = { + events: [ + { time: 10, action: "STOP_SCORING", position: "HUB", quantity: 100 }, + ], + robotRoles: ["SCORING"], + mobility: "NONE", + autoClimb: "NOT_ATTEMPTED", + endgameClimb: "L1", + intakeType: "GROUND", + beached: "NEITHER", + scoresWhileMoving: false, + }; + assert.equal(grade(expected, expected).overallScore, 100); + const duplicate = { + ...expected, + events: [...expected.events, ...expected.events], + }; + assert.ok(grade(duplicate, expected).overallScore < 100); + assert.ok(grade({ ...expected, events: [] }, expected).overallScore < 50); + assert.equal( + grade({ ...expected, beached: "BOTH" }, expected, ["beached"]).overallScore, + 100, + ); +}); +test("predictions handle deterministic ties and reject insufficient data", () => { + assert.deepEqual(prediction(Array.from({ length: 6 }, () => [10, 10])), { + redWinning: 0.5, + blueWinning: 0.5, + winningAlliance: 0, + }); + assert.equal( + prediction([ + [20, 20], + [20, 20], + [20, 20], + [10, 10], + [10, 10], + [10, 10], + ]).redWinning, + 1, + ); + assert.throws( + () => prediction(Array.from({ length: 6 }, () => [10])), + (e) => e.status === 422, + ); +}); +test("CSV escapes scouting notes and spreadsheet formulas", () => { + const output = csv( + [{ note: '=HYPERLINK("bad")', value: "a,b\nc" }], + ["note", "value"], + ); + assert.ok(output.includes("\"'=HYPERLINK(")); + assert.ok(output.includes("a,b\nc")); +}); +test("official data is shared, cached and bounded to allowed event paths", async () => { + let calls = 0; + const official = createOfficialReader("test", async () => { + calls++; + return new Response( + JSON.stringify({ rankings: [{ team_key: "frc8033", rank: 1 }] }), + ); + }); + const results = await Promise.all([ + official("2026test", "rankings", rankingSchema), + official("2026test", "rankings", rankingSchema), + ]); + assert.equal(results[0].rankings[0].rank, 1); + assert.equal(calls, 1); + await official("2026test", "rankings", rankingSchema); + assert.equal(calls, 1); + await assert.rejects( + official("../other", "rankings", rankingSchema), + (e) => e.status === 400, + ); + await assert.rejects( + official("2026test", "private", rankingSchema), + (e) => e.status === 400, + ); +}); + +test("cold-analysis budget bounds parallel work, releases failures and expires queued work", async () => { + const { createAnalysisBudget } = await import("../dist/budget.js"); + const budget = createAnalysisBudget(1, 1, 30); + let finish; + const first = budget( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + await new Promise((resolve) => setImmediate(resolve)); + const queued = budget(async () => 2); + await assert.rejects( + budget(async () => 3), + (e) => e.code === "ANALYSIS_BUSY", + ); + await assert.rejects(queued, (e) => e.code === "ANALYSIS_BUSY"); + finish(1); + assert.equal(await first, 1); + await assert.rejects( + budget(async () => { + throw Error("calculation failed"); + }), + ); + assert.equal(await budget(async () => 4), 4); +}); diff --git a/apps/api/test/state.integration.mjs b/apps/api/test/state.integration.mjs new file mode 100644 index 000000000..2d753aad3 --- /dev/null +++ b/apps/api/test/state.integration.mjs @@ -0,0 +1,44 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import { createState } from "../dist/state.js"; +const url = new URL(process.env.REDIS_URL ?? "redis://127.0.0.1:6379"); +if ( + process.env.LOVAT_REDIS_TEST !== "1" || + !["localhost", "127.0.0.1"].includes(url.hostname) +) + throw new Error("Enable LOVAT_REDIS_TEST with a loopback Redis service"); +test("Redis enforces atomic budgets, consumes OAuth state once and expires cached values", async (t) => { + const prefix = "lovat:rewrite-test:" + randomUUID() + ":", + state = createState(url.href, prefix); + const keys = [ + prefix + "rate:budget", + prefix + "oauth:test", + prefix + "analysis:test", + prefix + "revision:8033", + ]; + t.after(async () => { + await state.client.del(keys); + await state.close(); + }); + assert.equal(await state.ready(), true); + const accepted = await Promise.all( + Array.from({ length: 30 }, () => state.limiter.consume("budget", 3, 60)), + ); + assert.equal(accepted.filter(Boolean).length, 3); + assert.ok((await state.client.ttl(keys[0])) <= 60); + await state.oauth.put("test", "8033", 600); + const claims = await Promise.all([ + state.oauth.take("test"), + state.oauth.take("test"), + ]); + assert.deepEqual(claims.sort(), ["8033", null].sort()); + await state.cache.set("test", "{}", 15); + assert.equal(await state.cache.get("test"), "{}"); + assert.ok((await state.client.ttl(keys[2])) <= 15); + await state.client.set(keys[3], "1234567890123456789"); + assert.deepEqual(await state.cache.generations([8033, 1]), [ + "1234567890123456789", + "0", + ]); +}); diff --git a/apps/api/test/streaming.test.mjs b/apps/api/test/streaming.test.mjs new file mode 100644 index 000000000..abe927793 --- /dev/null +++ b/apps/api/test/streaming.test.mjs @@ -0,0 +1,298 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { game2026, legacyAnalysisInput, season2026 } from "@lovat/games/2026"; +import { compareReportGroups } from "@lovat/games"; +import { createRepository } from "../dist/repository.js"; +import { streamGameReports } from "../dist/gameStorage.js"; +import { createAnalysisService } from "../dist/analysis.js"; +import { fictionalGame } from "../../../packages/games/test/fixtures.mjs"; +import { report, event, scope } from "./fixtures.mjs"; + +test("streamed 2026 metrics preserve every value, missing sample, dependency and recency weight", async () => { + const reports = Array.from({ length: 90 }, (_, i) => + legacyAnalysisInput( + report({ + uuid: String(i), + teamNumber: 8033 + (i % 3), + matchKey: "qm" + (Math.floor(i / 3) % 5), + tournamentKey: "event" + Math.floor(i / 30), + tournamentDate: "2026-03-0" + (1 + Math.floor(i / 30)), + accuracy: i % 7 === 0 ? null : i % 6, + autoClimb: i % 2 ? "SUCCEEDED" : "FAILED", + endgameClimb: i % 2 ? "L2" : "NOT_ATTEMPTED", + robotRoles: i % 2 ? ["SCORING", "FEEDING"] : ["DEFENDING"], + events: [ + event("START_SCORING", 10), + event("STOP_SCORING", 20, i), + event("START_SCORING", 25), + event("STOP_SCORING", 35, 10), + event("CLIMB", 140), + ], + }), + ), + ); + const request = { + teams: [8033, 8034, 8035, 9999], + season: 2026, + metrics: season2026.metadata().map((metric) => metric.id), + timeline: true, + }; + const expected = game2026.analyze([...reports].reverse(), request); + async function* stream() { + for (const row of [...reports].reverse().sort(compareReportGroups)) + yield row; + } + assert.deepEqual(await game2026.analyzeStream(stream(), request), expected); +}); +test("unordered streams fail closed and close their source", async () => { + let closed = false; + const rows = [ + legacyAnalysisInput(report({ matchKey: "qm2" })), + legacyAnalysisInput(report({ matchKey: "qm1" })), + ]; + async function* stream() { + try { + yield* rows; + } finally { + closed = true; + } + } + await assert.rejects( + game2026.analyzeStream(stream(), { + teams: [8033], + season: 2026, + metrics: ["totalPoints"], + timeline: true, + }), + /must be ordered/, + ); + assert.equal(closed, true); +}); +test("analysis service consumes the stream without calling the buffering fallback", async () => { + let read = 0; + const analyze = createAnalysisService({ + loadReports: async () => { + throw Error("Unexpected buffering"); + }, + async *streamReports() { + read++; + yield legacyAnalysisInput(report()); + }, + }); + const response = await analyze(scope, { + teams: [8033], + season: 2026, + metrics: ["driverAbility"], + timeline: false, + }); + assert.equal(response.teams["8033"].metrics.driverAbility.value, 3); + assert.equal(read, 1); +}); +const metadata = (count) => + Array.from({ length: count }, (_, i) => ({ + ...report({ uuid: String(i).padStart(4, "0") }), + teamMatchData: { + teamNumber: 8033, + key: "qm1", + tournamentKey: "2026test", + tournament: { date: "2026-03-01" }, + }, + })); +function legacyDb(rows, event, snapshots = []) { + const db = { + scoutReport: { + findMany: async (query) => { + if (!query.select.teamMatchKey) return rows; + snapshots.push(query); + return rows + .filter((row) => query.where.AND[1].uuid.in.includes(row.uuid)) + .map((row) => ({ + uuid: row.uuid, + teamMatchKey: row.teamMatchData.key, + })); + }, + }, + event, + $transaction: async (callback, options) => { + assert.equal(options.isolationLevel, "RepeatableRead"); + return callback(db); + }, + }; + return db; +} +test("legacy stream bounds hydrated events and stops fetching when its consumer closes", async () => { + const rows = metadata(1600), + queries = [], + snapshots = []; + const repository = createRepository( + legacyDb( + rows, + { + groupBy: async () => + rows.map((row) => ({ + scoutReportUuid: row.uuid, + _count: { _all: 20 }, + })), + findMany: async (query) => { + queries.push(query); + return query.where.scoutReportUuid.in.flatMap((uuid) => + Array.from({ length: 20 }, (_, time) => ({ + scoutReportUuid: uuid, + ...event("INTAKE", time), + })), + ); + }, + }, + snapshots, + ), + ); + const iterator = repository + .streamReports(scope, { teams: [8033], season: 2026 }, new Set(["events"])) + [Symbol.asyncIterator](); + assert.equal((await iterator.next()).value.uuid, "0000"); + await iterator.return(); + assert.equal(queries.length, 1); + assert.ok(queries[0].where.scoutReportUuid.in.length <= 1000); + assert.ok(queries[0].take <= 20001); + assert.equal(snapshots[0].where.AND[0].training, false); + assert.deepEqual(snapshots[0].where.AND[0].scouter.sourceTeamNumber, { + in: [8033], + }); +}); +test("event preflight rejects total and individual limits before hydrating payloads", async () => { + for (const [count, perReport] of [ + [20, 6000], + [1, 10001], + ]) { + const rows = metadata(count); + const repository = createRepository({ + scoutReport: { findMany: async () => rows }, + event: { + groupBy: async () => + rows.map((row) => ({ + scoutReportUuid: row.uuid, + _count: { _all: perReport }, + })), + findMany: async () => { + throw Error("Must reject before reading events"); + }, + }, + }); + await assert.rejects( + repository.loadReports( + scope, + { teams: [8033], season: 2026 }, + new Set(["events"]), + ), + { code: "ANALYSIS_TOO_LARGE" }, + ); + } +}); +test("a report that grows after event preflight is rejected before producing a result", async () => { + const repository = createRepository( + legacyDb(metadata(1), { + groupBy: async () => [{ scoutReportUuid: "0000", _count: { _all: 1 } }], + findMany: async () => [{}, {}], + }), + ); + await assert.rejects( + repository.loadReports( + scope, + { teams: [8033], season: 2026 }, + new Set(["events"]), + ), + { code: "ANALYSIS_CHANGED" }, + ); +}); +const genericRows = () => + metadata(3).map((row) => ({ + ...row, + gameId: fictionalGame.descriptor.id, + gameVersion: 1, + reportVersion: 2, + })); +test("generic JSON streams use byte budgets and repeat tenant restrictions on each payload read", async () => { + const rows = genericRows(), + queries = []; + const db = { + $queryRaw: async () => + rows.map((row) => ({ uuid: row.uuid, bytes: 300000 })), + gameReport: { + findMany: async (query) => { + if (!query.select.data) return rows; + queries.push(query); + return query.where.AND[1].uuid.in.map((uuid) => ({ + uuid, + data: { throws: [], balanced: false }, + })); + }, + }, + }; + const stream = streamGameReports( + db, + scope, + { teams: [8033], season: 2099 }, + fictionalGame, + ); + const response = await fictionalGame.analyzeStream(stream, { + teams: [8033], + season: 2099, + metrics: ["points"], + timeline: true, + }); + assert.equal(response.teams["8033"].metrics.glyphScore.value, 0); + assert.equal(queries.length, 3); + for (const query of queries) { + assert.deepEqual(query.where.AND[0].scouter.sourceTeamNumber, { + in: [8033], + }); + assert.equal(query.where.AND[0].training, false); + assert.equal(query.where.AND[0].gameId, fictionalGame.descriptor.id); + } +}); +test("generic JSON preflight rejects oversized report payloads before loading data", async () => { + const db = { + $queryRaw: async () => [{ uuid: "0000", bytes: 3 * 1024 * 1024 }], + gameReport: { + findMany: async (query) => { + if (query.select.data) throw Error("Unexpected payload read"); + return genericRows(); + }, + }, + }; + await assert.rejects( + fictionalGame.analyzeStream( + streamGameReports( + db, + scope, + { teams: [8033], season: 2099 }, + fictionalGame, + ), + { teams: [8033], season: 2099, metrics: ["points"], timeline: false }, + ), + { code: "ANALYSIS_TOO_LARGE" }, + ); +}); + +test("visibility changes between metadata and payload snapshots exclude the entire report", async () => { + const db = legacyDb(metadata(1), { + groupBy: async () => [{ scoutReportUuid: "0000", _count: { _all: 1 } }], + findMany: async () => { + throw Error("Invisible report events must not load"); + }, + }); + db.$transaction = async (callback) => + callback({ ...db, scoutReport: { findMany: async () => [] } }); + const analyze = createAnalysisService(createRepository(db)); + const response = await analyze(scope, { + teams: [8033], + season: 2026, + metrics: ["totalPoints"], + timeline: false, + }); + assert.deepEqual(response.teams["8033"].metrics.totalPoints, { + value: null, + samples: 0, + version: 1, + }); +}); diff --git a/apps/api/tools/benchmark-http.mjs b/apps/api/tools/benchmark-http.mjs new file mode 100644 index 000000000..229e3323c --- /dev/null +++ b/apps/api/tools/benchmark-http.mjs @@ -0,0 +1,322 @@ +import { startBenchmarkServer } from "./benchmark-process.mjs"; +import { randomUUID } from "node:crypto"; +import { performance } from "node:perf_hooks"; +import { createState } from "../dist/state.js"; +import { season2026 } from "../dist/metrics/season2026.js"; +const url = new URL( + process.env.DATABASE_URL ?? "postgresql://localhost/missing", +); +const redisUrl = new URL(process.env.REDIS_URL ?? "redis://127.0.0.1:6379"); +if ( + process.env.LOVAT_DB_TEST !== "1" || + !["localhost", "127.0.0.1"].includes(url.hostname) || + url.pathname !== "/lovat_test" || + !["localhost", "127.0.0.1"].includes(redisUrl.hostname) +) + throw Error("Use disposable loopback lovat_test PostgreSQL and Redis"); +const bounded = (name, fallback, min, max) => { + const value = + process.env[name] === undefined ? fallback : Number(process.env[name]); + if (!Number.isInteger(value) || value < min || value > max) + throw Error("Invalid " + name); + return value; +}; +const counts = process.env.BENCHMARK_REPORTS + ? [bounded("BENCHMARK_REPORTS", 1000, 1, 5000)] + : [100, 1000]; +const iterations = bounded("BENCHMARK_ITERATIONS", 20, 1, 100); +const matches = bounded("BENCHMARK_MATCHES", 1, 1, Math.max(...counts)); +const soakSeconds = bounded("BENCHMARK_SOAK_SECONDS", 0, 0, 600); +const concurrencies = process.env.BENCHMARK_CONCURRENCY + ? [bounded("BENCHMARK_CONCURRENCY", 1, 1, 4)] + : [1, 4]; +const cacheMode = process.env.BENCHMARK_CACHE ?? "both"; +if (!["cold", "warm", "both"].includes(cacheMode)) + throw Error("Invalid BENCHMARK_CACHE"); +const cases = cacheMode === "both" ? [false, true] : [cacheMode === "warm"]; +const { createDb } = await import("@lovat/db"); +const db = createDb(url.href, { maxConnections: 4, statementTimeoutMs: 8000 }); +const id = randomUUID(), + own = 1200000000 + Math.floor(Math.random() * 10000000), + robot = own + 1; +const eventKey = "rewrite-benchmark-" + id; +const slots = Array.from( + { length: matches }, + (_, i) => eventKey + "_qm" + (i + 1) + "_0", +); +const state = createState(redisUrl.href, "lovat:rewrite-benchmark:" + id + ":"); +const scope = { + userId: "benchmark-" + id, + teamNumber: own, + role: "ANALYST", + sources: { + teams: { mode: "INCLUDE", items: [own] }, + tournaments: { mode: "INCLUDE", items: [eventKey] }, + }, +}; +const body = JSON.stringify({ + teams: [robot], + metrics: season2026.metadata().map((m) => m.id), + season: 2026, + timeline: false, +}); +let runtime; +const percentile = (a, p) => + a[Math.min(a.length - 1, Math.ceil(a.length * p) - 1)]; +try { + await db.season.upsert({ + where: { year: 2026 }, + create: { year: 2026 }, + update: {}, + }); + await db.team.createMany({ + data: [ + { number: own, name: "Synthetic benchmark source" }, + { number: robot, name: "Synthetic benchmark robot" }, + ], + }); + await db.registeredTeam.create({ + data: { number: own, email: id + "@example.invalid", code: id }, + }); + const scout = await db.scouter.create({ + data: { sourceTeamNumber: own, name: "Synthetic benchmark" }, + }); + await db.tournament.create({ + data: { + key: eventKey, + name: "Synthetic benchmark", + seasonYear: 2026, + date: "2026-03-01", + }, + }); + await db.teamMatchData.createMany({ + data: slots.map((key, i) => ({ + key, + tournamentKey: eventKey, + teamNumber: robot, + matchType: "QUALIFICATION", + matchNumber: i + 1, + })), + }); + for (const count of counts) { + await db.scoutReport.deleteMany({ + where: { teamMatchData: { tournamentKey: eventKey } }, + }); + const ids = Array.from({ length: count }, () => randomUUID()); + await db.scoutReport.createMany({ + data: ids.map((uuid, index) => ({ + uuid, + scouterUuid: scout.uuid, + teamMatchKey: slots[index % slots.length], + startTime: new Date(), + notes: "", + robotRoles: ["SCORING"], + driverAbility: 3, + autoClimb: "NOT_ATTEMPTED", + endgameClimb: "NOT_ATTEMPTED", + beached: "NEITHER", + feederTypes: [], + intakeType: "NEITHER", + defenseEffectiveness: 0, + fieldTraversal: "NONE", + scoresWhileMoving: false, + disrupts: false, + })), + }); + for (let start = 0; start < count; start += 50) { + const events = ids.slice(start, start + 50).flatMap((uuid) => + Array.from({ length: 10 }, (_, i) => [ + { + scoutReportUuid: uuid, + time: 24 + i * 10, + action: "START_SCORING", + position: "HUB", + points: 0, + quantity: 0, + }, + { + scoutReportUuid: uuid, + time: 29 + i * 10, + action: "STOP_SCORING", + position: "HUB", + points: 10, + quantity: 10, + }, + ]).flat(), + ); + await db.event.createMany({ data: events }); + } + for (const cached of cases) { + runtime = await startBenchmarkServer({ + scope, + prefix: state.prefix, + cached, + }); + const endpoint = runtime.url + "/v3/analysis"; + const call = async () => { + const start = performance.now(); + const response = await fetch(endpoint, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer synthetic", + }, + body, + }); + const data = await response.json(); + if ( + !response.ok || + data.teams[String(robot)].metrics.totalPoints.value !== 100 || + data.teams[String(robot)].metrics.totalPoints.samples !== + Math.min(count, slots.length) + ) + throw Error("Benchmark request failed: " + JSON.stringify(data)); + return performance.now() - start; + }; + for (let i = 0; i < 3; i++) await call(); + for (const concurrency of concurrencies) { + const timings = [], + before = await runtime.stats(); + for (let i = 0; i < iterations; i++) { + const batch = await Promise.allSettled( + Array.from({ length: concurrency }, call), + ); + const failure = batch.find((result) => result.status === "rejected"); + if (failure) throw failure.reason; + timings.push(...batch.map((result) => result.value)); + } + timings.sort((a, b) => a - b); + const after = await runtime.stats(); + console.log( + JSON.stringify({ + workload: "http-postgres" + (cached ? "-redis-warm" : ""), + reports: count, + matches: Math.min(count, slots.length), + events: count * 20, + metrics: 31, + concurrency, + requests: timings.length, + runtime: "bun", + bun: Bun.version, + p50Ms: percentile(timings, 0.5), + p95Ms: percentile(timings, 0.95), + p99Ms: percentile(timings, 0.99), + cpuMicroseconds: { + user: after.cpuMicroseconds.user - before.cpuMicroseconds.user, + system: + after.cpuMicroseconds.system - before.cpuMicroseconds.system, + }, + memory: after.memory, + maxRssKiB: after.maxRssKiB, + idleMemory: runtime.initial.memory, + queries: after.queries, + identity: + "injected synthetic scope; no JWKS or identity database read", + notes: + "server isolated from fixture/client process; full service composition, synthetic identity; local warm database", + }), + ); + } + if (soakSeconds) { + const timings = [], + liveness = [], + rssSamples = []; + const before = await runtime.stats(), + start = performance.now(); + let stopped = false, + lastSample = -5000; + const probe = (async () => { + while (!stopped) { + const at = performance.now(); + const response = await fetch(runtime.url + "/health/live", { + signal: AbortSignal.timeout(2000), + }); + await response.text(); + if (!response.ok) throw Error("Liveness failed during soak"); + liveness.push(performance.now() - at); + await new Promise((resolve) => setTimeout(resolve, 100)); + } + })(); + try { + while (performance.now() - start < soakSeconds * 1000) { + const batch = await Promise.allSettled( + Array.from({ length: 4 }, call), + ); + const failure = batch.find( + (result) => result.status === "rejected", + ); + if (failure) throw failure.reason; + timings.push(...batch.map((result) => result.value)); + const elapsed = performance.now() - start; + if (elapsed - lastSample >= 5000) { + const sample = await runtime.stats(); + rssSamples.push({ elapsedMs: elapsed, rss: sample.memory.rss }); + lastSample = elapsed; + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } + } finally { + stopped = true; + await probe; + } + const after = await runtime.stats(); + timings.sort((a, b) => a - b); + liveness.sort((a, b) => a - b); + console.log( + JSON.stringify({ + workload: "http-postgres-soak" + (cached ? "-redis" : ""), + runtime: "bun", + bun: Bun.version, + reports: count, + matches: Math.min(count, slots.length), + events: count * 20, + metrics: 31, + concurrency: 4, + requests: timings.length, + errors: 0, + durationMs: performance.now() - start, + p50Ms: percentile(timings, 0.5), + p95Ms: percentile(timings, 0.95), + p99Ms: percentile(timings, 0.99), + livenessRequests: liveness.length, + livenessP95Ms: percentile(liveness, 0.95), + livenessMaxMs: liveness.at(-1), + memory: after.memory, + maxRssKiB: after.maxRssKiB, + rssSamples, + cpuMicroseconds: { + user: after.cpuMicroseconds.user - before.cpuMicroseconds.user, + system: + after.cpuMicroseconds.system - before.cpuMicroseconds.system, + }, + queries: after.queries, + identity: + "synthetic scope; fixture/client excluded from server metrics", + }), + ); + } + await runtime.stop(); + runtime = undefined; + // Remove only this run's explicitly namespaced cache entries. + await state.connect(); + for await (const keys of state.client.scanIterator({ + MATCH: state.prefix + "analysis:*", + COUNT: 100, + })) { + if (keys.some((key) => !key.startsWith(state.prefix))) + throw Error("Unexpected cache key"); + if (keys.length) await state.client.del(keys); + } + } + } +} finally { + try { + if (runtime) await runtime.stop(); + } finally { + await db.tournament.deleteMany({ where: { key: eventKey } }); + await db.registeredTeam.deleteMany({ where: { number: own } }); + await db.team.deleteMany({ where: { number: { in: [own, robot] } } }); + await state.close(); + await db.$disconnect(); + } +} diff --git a/apps/api/tools/benchmark-process.mjs b/apps/api/tools/benchmark-process.mjs new file mode 100644 index 000000000..bd436e3d1 --- /dev/null +++ b/apps/api/tools/benchmark-process.mjs @@ -0,0 +1,82 @@ +import { fileURLToPath } from "node:url"; + +/** The measured process never creates fixtures or executes the HTTP client. */ +export async function startBenchmarkServer(config) { + const pending = new Map(); + let sequence = 0; + let resolveReady, rejectReady; + const ready = new Promise((resolve, reject) => { + resolveReady = resolve; + rejectReady = reject; + }); + const child = Bun.spawn( + [ + process.execPath, + "--smol", + fileURLToPath(new URL("./benchmark-server.mjs", import.meta.url)), + ], + { + env: { ...process.env, BENCHMARK_CONFIG: JSON.stringify(config) }, + stdout: "ignore", + stderr: "inherit", + ipc(message) { + if (message.type === "ready") resolveReady(message); + if (message.type === "stats") { + pending.get(message.id)?.resolve(message); + pending.delete(message.id); + } + }, + }, + ); + child.exited.then((code) => { + const error = Error("Benchmark server exited: " + code); + rejectReady(error); + for (const waiter of pending.values()) waiter.reject(error); + pending.clear(); + }); + const timeout = setTimeout(() => { + child.kill(); + rejectReady(Error("Benchmark startup timed out")); + }, 15000); + let initial; + try { + initial = await ready; + } finally { + clearTimeout(timeout); + } + return { + url: initial.url, + initial, + stats() { + const id = ++sequence; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + pending.delete(id); + reject(Error("Benchmark stats timed out")); + }, 10000); + pending.set(id, { + resolve: (message) => { + clearTimeout(timer); + resolve(message); + }, + reject: (error) => { + clearTimeout(timer); + reject(error); + }, + }); + child.send({ type: "stats", id }); + }); + }, + async stop() { + if (child.exitCode !== null) return; + child.send({ type: "stop" }); + const deadline = setTimeout(() => child.kill(), 15000); + try { + if ((await child.exited) !== 0) + throw Error("Benchmark server failed during shutdown"); + } finally { + clearTimeout(deadline); + } + }, + }; +} diff --git a/apps/api/tools/benchmark-server.mjs b/apps/api/tools/benchmark-server.mjs new file mode 100644 index 000000000..b59950c61 --- /dev/null +++ b/apps/api/tools/benchmark-server.mjs @@ -0,0 +1,110 @@ +import { startApi } from "../dist/runtime.js"; +import { createApi } from "../dist/app.js"; +import { createRepository } from "../dist/repository.js"; +import { createAnalysisService } from "../dist/analysis.js"; +import { createState } from "../dist/state.js"; +import { createServices } from "../dist/services/index.js"; +import { HttpError } from "../dist/errors.js"; + +if (!process.send || process.env.LOVAT_DB_TEST !== "1") + throw Error("Run through the isolated benchmark"); +const url = new URL(process.env.DATABASE_URL ?? ""); +const redis = new URL(process.env.REDIS_URL ?? ""); +if ( + !["localhost", "127.0.0.1"].includes(url.hostname) || + url.pathname !== "/lovat_test" || + !["localhost", "127.0.0.1"].includes(redis.hostname) +) + throw Error("Use disposable loopback services"); +const { scope, prefix, cached } = JSON.parse( + process.env.BENCHMARK_CONFIG ?? "{}", +); +if ( + !prefix?.startsWith("lovat:rewrite-benchmark:") || + !scope?.userId?.startsWith("benchmark-") +) + throw Error("Invalid synthetic scope"); +const { createDb } = await import("@lovat/db"); +const queryStats = {}; +const db = createDb(url.href, { + maxConnections: 4, + statementTimeoutMs: 8000, +}).$extends({ + query: { + $allModels: { + async $allOperations({ model, operation, args, query }) { + const started = performance.now(); + try { + return await query(args); + } finally { + const elapsed = performance.now() - started; + const stats = (queryStats[model + "." + operation] ??= { + count: 0, + totalMs: 0, + maxMs: 0, + }); + stats.count++; + stats.totalMs += elapsed; + stats.maxMs = Math.max(stats.maxMs, elapsed); + } + }, + }, + }, +}); +const state = createState(redis.href, prefix); +const repository = createRepository(db); +const analyze = createAnalysisService( + repository, + cached ? state.cache : undefined, +); +const api = createApi({ + repository, + analyze, + authenticate: async () => scope, + services: { + router: createServices({ + analyze, + baseUrl: "http://127.0.0.1", + commit: "benchmark", + }), + db, + authenticate: async () => { + throw new HttpError( + 401, + "UNAUTHORIZED", + "Benchmark service access is disabled", + ); + }, + }, + ready: async () => true, +}); +const runtime = startApi(api, { port: 0, hostname: "127.0.0.1" }); +const snapshot = () => ({ + memory: process.memoryUsage(), + cpuMicroseconds: process.cpuUsage(), + maxRssKiB: process.resourceUsage().maxRSS, + queries: queryStats, +}); +let stopping = false; +async function stop() { + if (stopping) return; + stopping = true; + await runtime.stop(); + await state.close(); + await db.$disconnect(); + process.disconnect(); +} +process.on("message", async (message) => { + if (message.type === "stats") + process.send({ type: "stats", id: message.id, ...snapshot() }); + if (message.type === "stop") await stop(); +}); +process.on("disconnect", () => { + void stop(); +}); +process.send({ + type: "ready", + url: runtime.url, + pid: process.pid, + ...snapshot(), +}); diff --git a/apps/api/tools/benchmark.mjs b/apps/api/tools/benchmark.mjs new file mode 100644 index 000000000..112efa8b6 --- /dev/null +++ b/apps/api/tools/benchmark.mjs @@ -0,0 +1,52 @@ +import { performance } from "node:perf_hooks"; +import { analyzeReports } from "../dist/metrics/engine.js"; +import { season2026 } from "../dist/metrics/season2026.js"; +import { report, event } from "../test/fixtures.mjs"; + +const counts = [100, 1000, 5000]; +const metrics = season2026.metadata().map((m) => m.id); +const percentile = (sorted, p) => + sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * p) - 1)]; +for (const count of counts) { + const reports = Array.from({ length: count }, (_, i) => + report({ + uuid: "report-" + i, + teamNumber: 1 + (i % 40), + matchKey: "match-" + Math.floor(i / 40), + events: Array.from({ length: 10 }, (_, cycle) => [ + event("START_SCORING", 24 + cycle * 10), + event("STOP_SCORING", 29 + cycle * 10, 10), + ]).flat(), + }), + ); + const request = { + teams: Array.from({ length: 40 }, (_, i) => i + 1), + metrics, + season: 2026, + timeline: false, + }; + for (let i = 0; i < 5; i++) analyzeReports(reports, request, season2026); + const timings = []; + const cpuStart = process.cpuUsage(); + for (let i = 0; i < 20; i++) { + const started = performance.now(); + analyzeReports(reports, request, season2026); + timings.push(performance.now() - started); + } + timings.sort((a, b) => a - b); + console.log( + JSON.stringify({ + workload: "pure-engine", + reports: count, + events: count * 20, + metrics: metrics.length, + iterations: timings.length, + node: process.version, + p50Ms: percentile(timings, 0.5), + p95Ms: percentile(timings, 0.95), + p99Ms: percentile(timings, 0.99), + cpuMicroseconds: process.cpuUsage(cpuStart), + memory: process.memoryUsage(), + }), + ); +} diff --git a/apps/api/tools/inventory.mjs b/apps/api/tools/inventory.mjs new file mode 100644 index 000000000..fa492ae98 --- /dev/null +++ b/apps/api/tools/inventory.mjs @@ -0,0 +1,141 @@ +import ts from "typescript"; +import { readFileSync, writeFileSync } from "node:fs"; +import { resolve, dirname, relative, sep } from "node:path"; +const root = resolve(import.meta.dirname, "../../.."); +const inventory = []; +function strings(node) { + if (ts.isStringLiteral(node)) return [node.text]; + if (ts.isArrayLiteralExpression(node)) return node.elements.flatMap(strings); + return []; +} +function visit(file, prefix = "", inherited = [], stack = []) { + if (stack.includes(file)) throw new Error("Router import cycle"); + const source = ts.createSourceFile( + file, + readFileSync(file, "utf8"), + ts.ScriptTarget.Latest, + true, + ); + const imports = new Map(); + const routerNames = new Set(); + const calls = []; + function scan(node) { + if ( + ts.isImportDeclaration(node) && + ts.isStringLiteral(node.moduleSpecifier) && + node.moduleSpecifier.text.startsWith(".") + ) { + const target = resolve( + dirname(file), + node.moduleSpecifier.text.replace(/\.js$/, ".ts"), + ); + if (node.importClause?.name) + imports.set(node.importClause.name.text, target); + for (const binding of node.importClause?.namedBindings && + ts.isNamedImports(node.importClause.namedBindings) + ? node.importClause.namedBindings.elements + : []) + imports.set(binding.name.text, target); + } + if ( + ts.isVariableDeclaration(node) && + ts.isIdentifier(node.name) && + node.initializer && + ts.isCallExpression(node.initializer) + ) { + const name = node.initializer.expression.getText(source); + if (name === "Router" || name === "express") + routerNames.add(node.name.text); + } + if ( + ts.isCallExpression(node) && + ts.isPropertyAccessExpression(node.expression) + ) + calls.push(node); + ts.forEachChild(node, scan); + } + scan(source); + let middleware = [...inherited]; + for (const call of calls) { + if (!routerNames.has(call.expression.expression.getText(source))) continue; + const method = call.expression.name.text; + if (!["get", "post", "put", "patch", "delete", "use"].includes(method)) + continue; + const paths = call.arguments[0] ? strings(call.arguments[0]) : []; + const handlers = [...call.arguments].slice(paths.length ? 1 : 0); + if (method === "use") { + for (const handler of handlers) { + const target = ts.isIdentifier(handler) + ? imports.get(handler.text) + : undefined; + if ( + target && + (target.endsWith("routes.ts") || target.endsWith("index.ts")) + ) { + for (const path of paths.length ? paths : [""]) + visit(target, (prefix + path).replace(/\/$/, ""), middleware, [ + ...stack, + file, + ]); + } + } + if (!paths.length) + middleware = [ + ...middleware, + ...handlers + .filter(ts.isIdentifier) + .map((h) => h.text) + .filter((h) => !imports.get(h)?.endsWith("routes.ts")), + ]; + continue; + } + for (const path of paths) + inventory.push({ + method: method.toUpperCase(), + path: (prefix + path).replace(/\/$/, "") || "/", + source: relative(root, file).split(sep).join("/"), + handlers: handlers + .map((h) => h.getText(source)) + .filter((h) => /^[a-zA-Z_$][\w.$]*$/.test(h)), + middleware, + replacement: null, + }); + } +} +visit(resolve(root, "apps/server/src/app.ts")); +inventory.sort( + (a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method), +); +const { createServices } = await import("../dist/services/index.js"); +const replacement = createServices({ + baseUrl: "https://api.lovat.app", + commit: "inventory", + analyze: async () => { + throw new Error("Inventory must not invoke handlers"); + }, +}); +for (const entry of inventory) { + const handler = replacement.endpoints.find( + (endpoint) => + endpoint.method === entry.method && endpoint.path === entry.path, + ); + entry.replacement = handler + ? { + source: handler.module, + policy: handler.policy, + coverage: "registration", + } + : null; +} +const content = JSON.stringify(inventory, null, 2) + "\n"; +const destination = resolve(import.meta.dirname, "../legacy-routes.json"); +if (process.argv.includes("--check")) { + if (readFileSync(destination, "utf8") !== content) + throw new Error("Legacy route inventory changed; run npm run inventory"); +} else writeFileSync(destination, content); +console.log( + inventory.length + + " legacy HTTP routes inventoried; " + + inventory.filter((entry) => entry.replacement).length + + " replacement handlers registered. Registration does not establish behavioral parity.", +); diff --git a/apps/api/tools/serve-qualification.mjs b/apps/api/tools/serve-qualification.mjs new file mode 100644 index 000000000..b908322f8 --- /dev/null +++ b/apps/api/tools/serve-qualification.mjs @@ -0,0 +1,31 @@ +import { createInterface } from "node:readline"; +if ( + process.env.LOVAT_DB_TEST !== "1" || + process.env.LOVAT_LOCAL_QUALIFICATION !== "1" +) + throw Error("Use the rollout qualification runner"); +const database = new URL(process.env.DATABASE_URL ?? ""); +const redis = new URL(process.env.REDIS_URL ?? ""); +if ( + database.hostname !== "127.0.0.1" || + database.pathname !== "/lovat_test" || + redis.hostname !== "127.0.0.1" +) + throw Error("Use disposable loopback services"); +const originalFetch = globalThis.fetch; +globalThis.fetch = (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + if (!["127.0.0.1", "localhost"].includes(url.hostname)) + throw Error("External providers are disabled during local qualification"); + return originalFetch(input, init); +}; +const { runtime } = await import("../dist/server.js"); +console.log(JSON.stringify({ type: "ready", url: runtime.url })); +const commands = createInterface({ input: process.stdin }); +commands.on("line", (line) => { + const message = JSON.parse(line); + if (message.type === "stop") { + process.emit("SIGTERM"); + commands.close(); + } +}); diff --git a/apps/api/tools/smoke-container.mjs b/apps/api/tools/smoke-container.mjs new file mode 100644 index 000000000..0191f94db --- /dev/null +++ b/apps/api/tools/smoke-container.mjs @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +const base = new URL(process.argv[2] ?? "http://127.0.0.1:3001"); +if (base.hostname !== "127.0.0.1") + throw Error("Smoke tests require a loopback container"); +let ready = false; +const deadline = Date.now() + 30000; +while (Date.now() < deadline) { + try { + const response = await fetch(new URL("/health/ready", base), { + signal: AbortSignal.timeout(1000), + }); + if (response.ok) { + ready = true; + break; + } + } catch { + /* The process may still be starting. */ + } + await new Promise((resolve) => setTimeout(resolve, 250)); +} +assert.equal(ready, true, "Container never became ready"); +assert.equal((await fetch(new URL("/health/live", base))).status, 200); +const games = await (await fetch(new URL("/v3/games", base))).json(); +assert.ok(games.some((game) => game.id === "frc-2026" && game.version === 1)); +assert.equal((await fetch(new URL("/v3/metrics", base))).status, 401); +console.log( + "Container readiness, game catalog and authentication smoke checks passed", +); diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json new file mode 100644 index 000000000..c720c45c4 --- /dev/null +++ b/apps/api/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2023", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "declaration": false, + "outDir": "dist", + "rootDir": "src", + "skipLibCheck": true, + "types": ["bun", "node"] + }, + "include": ["src/**/*.ts"] +} diff --git a/apps/server/Dockerfile b/apps/server/Dockerfile index 6b226db40..3e358b770 100644 --- a/apps/server/Dockerfile +++ b/apps/server/Dockerfile @@ -2,6 +2,7 @@ FROM node:22.20.0-bookworm-slim RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates && rm -rf /var/lib/apt/lists/* WORKDIR /app +COPY packages/api ./packages/api COPY packages/db ./packages/db COPY apps/server ./apps/server WORKDIR /app/apps/server diff --git a/apps/server/package-lock.json b/apps/server/package-lock.json index 60b465490..064369c66 100644 --- a/apps/server/package-lock.json +++ b/apps/server/package-lock.json @@ -10,7 +10,7 @@ "hasInstallScript": true, "license": "ISC", "dependencies": { - "@asteasolutions/zod-to-openapi": "^9.1.0", + "@lovat/api": "file:../../packages/api", "@lovat/db": "file:../../packages/db", "@slack/web-api": "^8.1.1", "axios": "^1.20.0", @@ -30,7 +30,7 @@ "swagger-ui-express": "^5.0.1", "ts-node": "^10.9.2", "ws": "^8.22.0", - "zod": "^4.6.5" + "zod": "4.6.7" }, "devDependencies": { "@eslint/js": "^10.0.1", @@ -63,6 +63,21 @@ "node": "22.20.0" } }, + "../../packages/api": { + "name": "@lovat/api", + "version": "0.1.0", + "dependencies": { + "@asteasolutions/zod-to-openapi": "9.1.0", + "zod": "4.6.7" + }, + "devDependencies": { + "prettier": "3.9.9", + "typescript": "5.9.3" + }, + "engines": { + "node": ">=22.20.0 <23 || >=24" + } + }, "../../packages/db": { "name": "@lovat/db", "version": "0.0.0", @@ -107,18 +122,6 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/@asteasolutions/zod-to-openapi": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/@asteasolutions/zod-to-openapi/-/zod-to-openapi-9.1.0.tgz", - "integrity": "sha512-pLMeRgRYS7/vZIgAAkOe2P6+XGTifR1MT9pqDoxZ11EmcJJ+DPmdPqLN8ZZF4U8R9KHCCQCS9c2wtuE8wSrfkw==", - "license": "MIT", - "dependencies": { - "openapi3-ts": "^4.6.0" - }, - "peerDependencies": { - "zod": "^4.0.0" - } - }, "node_modules/@babel/helper-string-parser": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", @@ -981,6 +984,10 @@ "dev": true, "license": "MIT" }, + "node_modules/@lovat/api": { + "resolved": "../../packages/api", + "link": true + }, "node_modules/@lovat/db": { "resolved": "../../packages/db", "link": true @@ -4669,15 +4676,6 @@ "wrappy": "1" } }, - "node_modules/openapi3-ts": { - "version": "4.6.1", - "resolved": "https://registry.npmjs.org/openapi3-ts/-/openapi3-ts-4.6.1.tgz", - "integrity": "sha512-XW9MOldkhoICNeXVzzmXzmOW5G73ppOEGmh7fLCqHjgfdEYCGGN+00MlVCeUZgovjjfC56j9tvtDt1zGabNjjA==", - "license": "MIT", - "dependencies": { - "yaml": "^2.9.0" - } - }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -6418,21 +6416,6 @@ } } }, - "node_modules/yaml": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", - "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", - "license": "ISC", - "bin": { - "yaml": "bin.mjs" - }, - "engines": { - "node": ">= 14.6" - }, - "funding": { - "url": "https://github.com/sponsors/eemeli" - } - }, "node_modules/yn": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", @@ -6456,9 +6439,9 @@ } }, "node_modules/zod": { - "version": "4.6.5", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", - "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==", + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/apps/server/package.json b/apps/server/package.json index 308c3b00d..633f494df 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -18,8 +18,8 @@ "lint": "eslint .", "format": "prettier --write .", "format:check": "prettier --check .", - "postinstall": "npm --prefix ../../packages/db ci --include=dev && npm --prefix ../../packages/db run build", - "prebuild": "npm --prefix ../../packages/db run build", + "postinstall": "npm --prefix ../../packages/api ci --include=dev && npm --prefix ../../packages/api run build && npm --prefix ../../packages/db ci --include=dev && npm --prefix ../../packages/db run build", + "prebuild": "npm --prefix ../../packages/api run build && npm --prefix ../../packages/db run build", "db:seed": "tsx src/seed.ts", "test:coverage:unit": "vitest run --coverage", "test:report:preview": "vite preview --outDir test-report --host 127.0.0.1", @@ -29,7 +29,7 @@ "author": "", "license": "ISC", "dependencies": { - "@asteasolutions/zod-to-openapi": "^9.1.0", + "@lovat/api": "file:../../packages/api", "@lovat/db": "file:../../packages/db", "@slack/web-api": "^8.1.1", "axios": "^1.20.0", @@ -49,7 +49,7 @@ "swagger-ui-express": "^5.0.1", "ts-node": "^10.9.2", "ws": "^8.22.0", - "zod": "^4.6.5" + "zod": "4.6.7" }, "devDependencies": { "@eslint/js": "^10.0.1", diff --git a/apps/server/src/handler/collection/reportSchema.ts b/apps/server/src/handler/collection/reportSchema.ts index b00e81c9a..4292226ba 100644 --- a/apps/server/src/handler/collection/reportSchema.ts +++ b/apps/server/src/handler/collection/reportSchema.ts @@ -1,75 +1 @@ -import z from "zod"; -import { - AutoClimb, - Beached, - ClimbPosition, - ClimbSide, - EndgameClimb, - FeederType, - FieldTraversal, - IntakeType, - MatchType, - RobotRole, -} from "@lovat/db"; -import { EventActionMap, PositionMap } from "../manager/managerConstants.js"; -import { timestampSchema } from "./ownedReport.js"; - -const eventSchema = z - .union([ - z.tuple([z.number().nonnegative(), z.number().int(), z.number().int()]), - z.tuple([ - z.number().nonnegative(), - z.number().int(), - z.number().int(), - z.number().int().nonnegative(), - ]), - ]) - .superRefine((event, ctx) => { - const action = EventActionMap[event[1]]; - - if (!action || !PositionMap[event[2]]) { - ctx.addIssue({ - code: "custom", - message: "Unknown event action or position.", - }); - } - - if ( - ["STOP_SCORING", "STOP_FEEDING"].includes(action) && - event[3] === undefined - ) { - ctx.addIssue({ - code: "custom", - message: "Scoring and feeding stop events require a quantity.", - }); - } - }); - -export const reportSchema = z.object({ - uuid: z.uuid(), - scouterUuid: z.uuid(), - tournamentKey: z.string().min(1), - matchType: z.nativeEnum(MatchType), - matchNumber: z.number().int().positive(), - teamNumber: z.number().int().positive(), - startTime: timestampSchema, - - notes: z.string(), - robotRoles: z.array(z.nativeEnum(RobotRole)), - mobility: z.nativeEnum(FieldTraversal), - climbPosition: z.nativeEnum(ClimbPosition).optional(), - climbSide: z.nativeEnum(ClimbSide).optional(), - beached: z.nativeEnum(Beached), - feederTypes: z.array(z.nativeEnum(FeederType)), - intakeType: z.nativeEnum(IntakeType), - robotBrokeDescription: z.string().nullable().optional(), - driverAbility: z.number().int(), - accuracy: z.number().int().nullable().optional(), - disrupts: z.boolean(), - defenseEffectiveness: z.number().int(), - scoresWhileMoving: z.boolean(), - autoClimb: z.nativeEnum(AutoClimb), - endgameClimb: z.nativeEnum(EndgameClimb), - appVersion: z.string().optional(), - events: z.array(eventSchema), -}); +export { reportSchema } from "@lovat/api"; diff --git a/apps/server/src/lib/openapi.ts b/apps/server/src/lib/openapi.ts index 2b7a8e6ab..3ebe29fc5 100644 --- a/apps/server/src/lib/openapi.ts +++ b/apps/server/src/lib/openapi.ts @@ -1,153 +1,11 @@ -import { - OpenAPIRegistry, - OpenApiGeneratorV31, - extendZodWithOpenApi, -} from "@asteasolutions/zod-to-openapi"; -import { z } from "zod"; -import pkg from "./../../package.json" with { type: "json" }; +import { createLegacyOpenApiDocument } from "@lovat/api/legacy"; +import pkg from "../../package.json" with { type: "json" }; -// Enable .openapi() on Zod types -extendZodWithOpenApi(z); - -// Shared OpenAPI registry for the app. Other modules can import and register. -export const registry = new OpenAPIRegistry(); - -export const ApiErrorSchema = registry.register( - "ApiError", - z.object({ - code: z.string().openapi({ - description: - "Machine-readable error identifier. Use the HTTP status and code for program decisions; messages may change.", - example: "INVALID_QUERY_PARAMETERS", - }), - message: z.string().openapi({ - description: "Safe, human-readable explanation.", - example: "Invalid team query parameters", - }), - displayError: z.string().openapi({ - description: - "Compatibility alias of message, with the same value, for existing clients.", - example: "Invalid team query parameters", - }), - invalidFields: z.array(z.string()).optional().openapi({ - description: - "Optional field names to correct. Submitted values are never included.", - }), - retryAfterSeconds: z.number().optional().openapi({ - description: - "Optional retry delay in seconds. Also respect Retry-After when provided.", - }), - }), -); - -const apiErrorContent = { - "application/json": { schema: { $ref: "#/components/schemas/ApiError" } }, -}; - -registry.registerComponent("responses", "ApiErrorResponse", { - description: - "Request failed. The HTTP status describes the failure category; code identifies the error. Unexpected server failures use INTERNAL_SERVER_ERROR and a generic message.", - content: apiErrorContent, -}); - -// Import and register Prisma-derived schemas -import { registerPrismaSchemas } from "./prisma-zod.js"; -registerPrismaSchemas(registry); - -// Register security schemes -registry.registerComponent("securitySchemes", "bearerAuth", { - type: "http", - scheme: "bearer", - description: - "Accepts either a JWT token from Auth0 or an API key (prefixed with 'lvt-'). " + - "Use format: Authorization: Bearer ", -}); -registry.registerComponent("securitySchemes", "slackToken", { - type: "apiKey", - in: "header", - name: "x-slack-signature", - description: - "Slack signature header (requires accompanying x-slack-request-timestamp)", -}); -registry.registerComponent("securitySchemes", "lovatSignature", { - type: "apiKey", - in: "header", - name: "x-signature", - description: "HMAC signature header (requires accompanying x-timestamp)", -}); - -// Reusable header parameter schema for x-timestamp (used with lovatSignature) -export const LovatTimestampHeader = z.object({ - "x-timestamp": z.string().openapi({ - description: "Unix timestamp (seconds) used in HMAC signature generation", - }), -}); - -// Minimal example: document the /status health check route -registry.registerPath({ - method: "get", - path: "/status", - summary: "Health check", - description: "Returns a simple message indicating the server is running.", - responses: { - 200: { - description: "Server is running", - content: { - "text/plain": { - schema: z.string().openapi({ example: "Server running" }), - }, - }, - }, - }, -}); +export { apiErrorSchema as ApiErrorSchema } from "@lovat/api"; export function generateOpenApiDocument() { - const generator = new OpenApiGeneratorV31(registry.definitions); - const document = generator.generateDocument({ - openapi: "3.1.0", - info: { - title: "Lovat API", - version: pkg.version, - description: - "API Documentation for Lovat, a scouting system used to scout teams and matches in the First Robotics Competition. Clients request the shared format using X-Lovat-Error-Format: json-v1. Without that header, direct guard responses retain their legacy formats for installed clients; unexpected failures are still sanitized. Negotiated HTTP error responses (400–599) use application/json and the ApiError schema. message and displayError contain the same safe text. invalidFields and retryAfterSeconds appear only when applicable. Authentication, validation, missing resources, rate limits and unexpected failures share this format. Success responses, including legacy domain messages returned with status 200, retain their documented shapes. Internal exception details and submitted values are not part of the error response.", - }, - servers: [{ url: `${process.env.BASE_URL || "https://api.lovat.app"}` }], + return createLegacyOpenApiDocument({ + version: pkg.version, + baseUrl: process.env.BASE_URL || "https://api.lovat.app", }); - - // Keep each endpoint's status descriptions and headers while documenting the - // response contract enforced by errorResponses and errorHandler. - for (const path of Object.values(document.paths ?? {})) { - if (!path) { - continue; - } - for (const method of [ - "get", - "post", - "put", - "patch", - "delete", - "options", - "head", - "trace", - ] as const) { - const operation = path[method]; - if (!operation) { - continue; - } - operation.responses ??= {}; - for (const [status, response] of Object.entries(operation.responses)) { - if ( - /^[45](?:\d{2}|XX)$/.test(status) && - response && - !("$ref" in response) - ) { - response.content = apiErrorContent; - } - } - operation.responses.default ??= { - $ref: "#/components/responses/ApiErrorResponse", - }; - } - } - return document; } diff --git a/apps/server/src/routes/analysis/analysis.routes.ts b/apps/server/src/routes/analysis/analysis.routes.ts index 14cf3993f..895a94ff2 100644 --- a/apps/server/src/routes/analysis/analysis.routes.ts +++ b/apps/server/src/routes/analysis/analysis.routes.ts @@ -7,210 +7,10 @@ import { Router } from "express"; import teamLookup from "./teamLookup.routes.js"; import csv from "./csv.routes.js"; import scoutReport from "./scoutreport.routes.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; import { qualRankingPrediction } from "../../handler/analysis/predictions/qualRankingPrediction.js"; const router = Router(); -// OpenAPI docs for analysis endpoints -const AlliancePathPosition = z.object({ - location: z.number(), - event: z.number(), - time: z.number().optional(), -}); -const AlliancePath = z.object({ - positions: z.array(AlliancePathPosition), - matches: z.array( - z.object({ matchKey: z.string(), tournamentName: z.string() }), - ), - score: z.array(z.number()), - frequency: z.number(), - maxScore: z.number(), -}); -const AllianceTeam = z.object({ - team: z.number(), - role: z.number(), - averagePoints: z.number(), - paths: z.array(AlliancePath), -}); -const AllianceResponseSchema = z.object({ - totalPoints: z.number(), - teams: z.array(AllianceTeam), - l1StartTime: z.array(z.number().nullable()).length(3), - l2StartTime: z.array(z.number().nullable()).length(3), - l3StartTime: z.array(z.number().nullable()).length(3), - totalFuelOutputted: z.number(), - totalBallThroughput: z.number(), -}); - -registry.registerPath({ - method: "get", - path: "/v1/analysis/pitdisplay", - tags: ["Analysis"], - summary: "Public pit display data for a team/event", - request: { - query: z.object({ - team: z.coerce.number().int(), - tournamentKey: z.string(), - topTeamCount: z.coerce.number().int(), - teamsAboveCount: z.coerce.number().int(), - }), - }, - responses: { - 200: { - description: "Pit display payload", - content: { "application/json": { schema: z.any() } }, - }, - 400: { description: "Invalid parameters" }, - 500: { description: "Error generating display" }, - }, -}); - -registry.registerPath({ - method: "get", - path: "/v1/analysis/alliance", - tags: ["Analysis"], - summary: "Alliance analysis for three teams", - request: { - query: z.object({ - teamOne: z.coerce.number().int(), - teamTwo: z.coerce.number().int(), - teamThree: z.coerce.number().int(), - }), - }, - responses: { - 200: { - description: "Alliance composition and metrics", - content: { "application/json": { schema: AllianceResponseSchema } }, - }, - 400: { description: "Invalid parameters" }, - 500: { description: "Internal server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -const MatchPredictionResponseSchema = z.union([ - z.object({ - red1: z.number(), - red2: z.number(), - red3: z.number(), - blue1: z.number(), - blue2: z.number(), - blue3: z.number(), - redWinning: z.number(), - blueWinning: z.number(), - winningAlliance: z.number(), - redAlliance: AllianceResponseSchema, - blueAlliance: AllianceResponseSchema, - }), - z.object({ error: z.literal("not enough data") }), -]); - -registry.registerPath({ - method: "get", - path: "/v1/analysis/matchprediction", - tags: ["Analysis"], - summary: "Predict match outcome for two alliances", - request: { - query: z.object({ - red1: z.coerce.number().int(), - red2: z.coerce.number().int(), - red3: z.coerce.number().int(), - blue1: z.coerce.number().int(), - blue2: z.coerce.number().int(), - blue3: z.coerce.number().int(), - }), - }, - responses: { - 200: { - description: "Prediction and alliance details", - content: { - "application/json": { schema: MatchPredictionResponseSchema }, - }, - }, - 400: { description: "Invalid parameters" }, - 401: { description: "Unauthorized" }, - 500: { description: "Internal server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "get", - path: "/v1/analysis/qualrankingprediction", - tags: ["Analysis"], - summary: "Predict qual ranking for a tournament", - request: { - query: z.object({ - tournamentKey: z.string(), - }), - }, - responses: { - 200: { - description: "Qual ranking prediction", - content: { - "application/json": { schema: z.array(z.any()) }, - }, - }, - 400: { description: "Invalid parameters" }, - 401: { description: "Unauthorized" }, - 500: { description: "Internal server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -const PicklistEntrySchema = z.object({ - team: z.number(), - result: z.number(), - breakdown: z.array(z.object({ type: z.string(), result: z.number() })), - unweighted: z.array(z.object({ type: z.string(), result: z.number() })), - flags: z.array(z.object({ type: z.string(), result: z.number() })), -}); - -registry.registerPath({ - method: "get", - path: "/v1/analysis/picklist", - tags: ["Analysis"], - summary: "Compute picklist rankings for a tournament", - request: { - query: z.object({ - tournamentKey: z.string().optional(), - flags: z.string().optional(), - stage: z.string().optional(), - totalPoints: z.coerce.number().optional(), - autoPoints: z.coerce.number().optional(), - teleopPoints: z.coerce.number().optional(), - driverAbility: z.coerce.number().optional(), - climbResult: z.coerce.number().optional(), - autoClimb: z.coerce.number().optional(), - defenseEffectiveness: z.coerce.number().optional(), - contactDefenseTime: z.coerce.number().optional(), - campingDefenseTime: z.coerce.number().optional(), - totalDefensiveTime: z.coerce.number().optional(), - totalFuelThroughput: z.coerce.number().optional(), - totalFuelFed: z.coerce.number().optional(), - feedingRate: z.coerce.number().optional(), - scoringRate: z.coerce.number().optional(), - estimatedSuccessfulFuelRate: z.coerce.number().optional(), - estimatedTotalFuelScored: z.coerce.number().optional(), - }), - }, - responses: { - 200: { - description: "Picklist ranking results", - content: { - "application/json": { - schema: z.object({ teams: z.array(PicklistEntrySchema) }), - }, - }, - }, - 400: { description: "Invalid parameters" }, - 500: { description: "Internal server error" }, - }, - security: [{ bearerAuth: [] }], -}); - router.get("/pitdisplay", pitDisplay); router.use(requireAuth); diff --git a/apps/server/src/routes/analysis/csv.routes.ts b/apps/server/src/routes/analysis/csv.routes.ts index 7771134ab..6f3dc92df 100644 --- a/apps/server/src/routes/analysis/csv.routes.ts +++ b/apps/server/src/routes/analysis/csv.routes.ts @@ -1,50 +1,10 @@ import { Router } from "express"; import { getReportCSV } from "../../handler/analysis/csv/getReportCSV.js"; import { getTeamCSV } from "../../handler/analysis/csv/getTeamCSV.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; import { requireVerifiedTeam } from "../../lib/middleware/requireVerifiedTeam.js"; const router = Router(); -registry.registerPath({ - method: "get", - path: "/v1/analysis/csvplain", - tags: ["Analysis - CSV"], - summary: "Team CSV", - request: { - query: z.object({ - team: z.coerce.number().int(), - tournamentKey: z.string().optional(), - }), - }, - responses: { - 200: { - description: "CSV", - content: { "text/csv": { schema: z.string() } }, - }, - 400: { description: "Invalid parameters or not enough scouting data" }, - 500: { description: "Internal server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "get", - path: "/v1/analysis/reportcsv", - tags: ["Analysis - CSV"], - summary: "Report CSV", - request: { query: z.object({ tournamentKey: z.string() }) }, - responses: { - 200: { - description: "CSV", - content: { "text/csv": { schema: z.string() } }, - }, - 400: { description: "Invalid parameters or not enough scouting data" }, - 500: { description: "Internal server error" }, - }, - security: [{ bearerAuth: [] }], -}); - router.use(requireVerifiedTeam); router.get("/csvplain", getTeamCSV); diff --git a/apps/server/src/routes/analysis/scoutreport.routes.ts b/apps/server/src/routes/analysis/scoutreport.routes.ts index f42773e5a..472b5e30e 100644 --- a/apps/server/src/routes/analysis/scoutreport.routes.ts +++ b/apps/server/src/routes/analysis/scoutreport.routes.ts @@ -2,67 +2,10 @@ import { Router } from "express"; import { matchPageSpecificScouter } from "../../handler/analysis/specificMatchPage/matchPageSpecificScouter.js"; import { scoutReportForMatch } from "../../handler/analysis/specificMatchPage/scoutReportForMatch.js"; import { timelineForScoutReport } from "../../handler/analysis/specificMatchPage/timelineForScoutReport.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; import { requireVerifiedTeam } from "../../lib/middleware/requireVerifiedTeam.js"; const router = Router(); -registry.registerPath({ - method: "get", - path: "/v1/analysis/metrics/scoutreport/{uuid}", - security: [{ bearerAuth: [] }], - tags: ["Analysis - Scout Report"], - summary: "Metrics for specific scout report", - request: { params: z.object({ uuid: z.string() }) }, - responses: { - 200: { - description: "Metrics", - content: { - "application/json": { schema: z.record(z.string(), z.any()) }, - }, - }, - 400: { description: "Invalid parameters" }, - 500: { description: "Internal server error" }, - }, -}); -registry.registerPath({ - method: "get", - path: "/v1/analysis/scoutreports/match/{match}", - security: [{ bearerAuth: [] }], - tags: ["Analysis - Scout Report"], - summary: "All scout reports for a match", - request: { params: z.object({ match: z.coerce.number().int() }) }, - responses: { - 200: { - description: "Reports", - content: { - "application/json": { schema: z.array(z.record(z.string(), z.any())) }, - }, - }, - 400: { description: "Invalid parameters" }, - 500: { description: "Internal server error or not authorized" }, - }, -}); -registry.registerPath({ - method: "get", - path: "/v1/analysis/timeline/scoutreport/{uuid}", - security: [{ bearerAuth: [] }], - tags: ["Analysis - Scout Report"], - summary: "Timeline data for scout report", - request: { params: z.object({ uuid: z.string() }) }, - responses: { - 200: { - description: "Timeline", - content: { - "application/json": { schema: z.record(z.string(), z.any()) }, - }, - }, - 400: { description: "Invalid parameters" }, - 500: { description: "Internal server error" }, - }, -}); - router.use(requireVerifiedTeam); router.get("/metrics/scoutreport/:uuid", matchPageSpecificScouter); diff --git a/apps/server/src/routes/analysis/teamLookup.routes.ts b/apps/server/src/routes/analysis/teamLookup.routes.ts index 9ccd4e08a..265f39257 100644 --- a/apps/server/src/routes/analysis/teamLookup.routes.ts +++ b/apps/server/src/routes/analysis/teamLookup.routes.ts @@ -5,124 +5,9 @@ import { categoryMetrics } from "../../handler/analysis/teamLookUp/categoryMetri import { detailsPage } from "../../handler/analysis/teamLookUp/detailsPage.js"; import { getNotes } from "../../handler/analysis/teamLookUp/getNotes.js"; import { multipleFlags } from "../../handler/analysis/teamLookUp/multipleFlags.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; const router = Router(); -const TeamParam = z.object({ team: z.string() }); -const MetricTeamParam = z.object({ metric: z.string(), team: z.string() }); -const BreakdownParam = z.object({ team: z.string(), breakdown: z.string() }); - -registry.registerPath({ - method: "get", - path: "/v1/analysis/metric/{metric}/team/{team}", - security: [{ bearerAuth: [] }], - tags: ["Analysis - Team Lookup"], - summary: "Metric details for team", - request: { params: MetricTeamParam }, - responses: { - 200: { - description: "Details", - content: { - "application/json": { schema: z.record(z.string(), z.any()) }, - }, - }, - 400: { description: "Invalid parameters" }, - 500: { description: "Internal server error" }, - }, -}); -registry.registerPath({ - method: "get", - path: "/v1/analysis/category/team/{team}", - security: [{ bearerAuth: [] }], - tags: ["Analysis - Team Lookup"], - summary: "Category metrics for team", - request: { params: TeamParam }, - responses: { - 200: { - description: "Categories", - content: { - "application/json": { schema: z.record(z.string(), z.any()) }, - }, - }, - 400: { description: "Invalid parameters" }, - 500: { description: "Internal server error" }, - }, -}); -registry.registerPath({ - method: "get", - path: "/v1/analysis/breakdown/team/{team}", - security: [{ bearerAuth: [] }], - tags: ["Analysis - Team Lookup"], - summary: "Breakdown metrics for team", - request: { params: TeamParam }, - responses: { - 200: { - description: "Breakdown", - content: { - "application/json": { schema: z.record(z.string(), z.any()) }, - }, - }, - 400: { description: "Invalid parameters" }, - 500: { description: "Internal server error" }, - }, -}); -registry.registerPath({ - method: "get", - path: "/v1/analysis/breakdown/team/{team}/{breakdown}", - security: [{ bearerAuth: [] }], - tags: ["Analysis - Team Lookup"], - summary: "Specific breakdown details", - request: { params: BreakdownParam }, - responses: { - 200: { - description: "Details", - content: { - "application/json": { schema: z.record(z.string(), z.any()) }, - }, - }, - 400: { description: "Invalid parameters" }, - 500: { description: "Internal server error" }, - }, -}); -registry.registerPath({ - method: "get", - path: "/v1/analysis/notes/team/{team}", - security: [{ bearerAuth: [] }], - tags: ["Analysis - Team Lookup"], - summary: "Notes for team", - request: { params: TeamParam }, - responses: { - 200: { - description: "Notes", - content: { - "application/json": { schema: z.array(z.object({ note: z.string() })) }, - }, - }, - 400: { description: "Invalid parameters" }, - 500: { description: "Internal server error" }, - }, -}); -registry.registerPath({ - method: "get", - path: "/v1/analysis/flag/team/{team}", - security: [{ bearerAuth: [] }], - tags: ["Analysis - Team Lookup"], - summary: "Flags for team", - request: { params: TeamParam }, - responses: { - 200: { - description: "Flags", - content: { - "application/json": { schema: z.array(z.object({ flag: z.string() })) }, - }, - }, - 400: { description: "Invalid parameters" }, - 500: { description: "Internal server error" }, - }, -}); - router.get("/metric/:metric/team/:team", detailsPage); router.get("/category/team/:team", categoryMetrics); router.get("/breakdown/team/:team", breakdownMetrics); diff --git a/apps/server/src/routes/manager/apikey.routes.ts b/apps/server/src/routes/manager/apikey.routes.ts index 88791b862..5a9b5ddd3 100644 --- a/apps/server/src/routes/manager/apikey.routes.ts +++ b/apps/server/src/routes/manager/apikey.routes.ts @@ -4,107 +4,8 @@ import { addApiKey } from "../../handler/manager/apikey/addApiKey.js"; import { getApiKeys } from "../../handler/manager/apikey/getApiKeys.js"; import { renameApiKey } from "../../handler/manager/apikey/renameApiKey.js"; import { revokeApiKey } from "../../handler/manager/apikey/revokeApiKey.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; import { requireVerifiedTeam } from "../../lib/middleware/requireVerifiedTeam.js"; -// OpenAPI docs for API key management (JWT required) -registry.registerPath({ - method: "post", - path: "/v1/manager/apikey", - tags: ["Manager - API Keys"], - summary: "Create a new API key", - description: - "JWT required; API keys (lvt-...) are not permitted for this endpoint.", - request: { query: z.object({ name: z.string() }) }, - responses: { - 200: { - description: "Created", - content: { - "application/json": { schema: z.object({ apiKey: z.string() }) }, - }, - }, - 400: { description: "Invalid request parameters" }, - 401: { description: "Unauthorized" }, - 403: { description: "Forbidden for API key auth" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "delete", - path: "/v1/manager/apikey", - tags: ["Manager - API Keys"], - summary: "Revoke an API key", - description: - "JWT required; API keys (lvt-...) are not permitted for this endpoint.", - request: { query: z.object({ uuid: z.string() }) }, - responses: { - 404: { description: "API key not found" }, - 200: { - description: "Revoked", - content: { "application/json": { schema: z.string() } }, - }, - 400: { description: "Invalid request parameters" }, - 401: { description: "Unauthorized" }, - 403: { description: "Forbidden for API key auth" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "patch", - path: "/v1/manager/apikey", - tags: ["Manager - API Keys"], - summary: "Rename an API key", - description: - "JWT required; API keys (lvt-...) are not permitted for this endpoint.", - request: { query: z.object({ uuid: z.string(), newName: z.string() }) }, - responses: { - 404: { description: "API key not found" }, - 200: { - description: "Renamed", - content: { "application/json": { schema: z.string() } }, - }, - 400: { description: "Invalid request parameters" }, - 401: { description: "Unauthorized" }, - 403: { description: "Forbidden for API key auth" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "get", - path: "/v1/manager/apikey", - tags: ["Manager - API Keys"], - summary: "List API keys", - description: "Returns current user's API keys. Accepts JWT or API keys.", - responses: { - 200: { - description: "Keys", - content: { - "application/json": { - schema: z.object({ - apiKeys: z.array( - z.object({ - uuid: z.string(), - name: z.string(), - createdAt: z.string().datetime(), - lastUsed: z.string().datetime().nullable(), - requests: z.number().int(), - user: z.object({ username: z.string().nullable() }), - }), - ), - }), - }, - }, - }, - 401: { description: "Unauthorized" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - const router = Router(); router.use(requireAuth, requireVerifiedTeam); diff --git a/apps/server/src/routes/manager/manager.routes.ts b/apps/server/src/routes/manager/manager.routes.ts index fca0002d0..ef8a73e64 100644 --- a/apps/server/src/routes/manager/manager.routes.ts +++ b/apps/server/src/routes/manager/manager.routes.ts @@ -29,511 +29,16 @@ import { getTeamCode } from "../../handler/manager/getTeamCode.js"; import { addScoutReportDashboard } from "../../handler/manager/scoutreports/addScoutReportDashboard.js"; import { getTeamTournamentStatus } from "../../handler/manager/getTeamTournamentStatus.js"; import { getMatchResults } from "../../handler/manager/getMatchResults.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; -import { - TeamMatchDataSchema, - TeamSchema, - TournamentSchema, -} from "../../lib/prisma-zod.js"; import { requireVerifiedTeam } from "../../lib/middleware/requireVerifiedTeam.js"; import { checkMatchExists } from "../../handler/manager/checkMatchExists.js"; const router = Router(); - -registry.registerPath({ - method: "get", - path: "/v1/manager/upcoming-entered-tournaments", - tags: ["Manager - Tournaments"], - summary: "Next two future Blue Alliance events for the signed-in user's team", - security: [{ bearerAuth: [] }], - responses: { - 200: { - description: "Events in start-date order; week numbers start at one", - }, - 401: { description: "Unauthorized" }, - 502: { description: "Blue Alliance event data unavailable" }, - }, -}); router.get( "/upcoming-entered-tournaments", requireAuth, getUpcomingTeamTournaments, ); -// OpenAPI documentation for selected manager endpoints -const PaginationQuery = z.object({ - take: z.coerce.number().int().optional(), - skip: z.coerce.number().int().optional(), -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/teams", - tags: ["Manager - Teams"], - summary: "List teams with optional pagination and filter", - request: { - query: PaginationQuery.extend({ filter: z.string().optional() }), - }, - responses: { - 200: { - description: "Teams and total count", - content: { - "application/json": { - schema: z.object({ teams: z.array(TeamSchema), count: z.number() }), - }, - }, - }, - 401: { description: "Unauthorized" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/tournaments", - tags: ["Manager - Tournaments"], - summary: "List tournaments with optional pagination and filter", - request: { - query: PaginationQuery.extend({ filter: z.string().optional() }), - }, - responses: { - 200: { - description: "Tournaments and total count", - content: { - "application/json": { - schema: z.object({ - tournaments: z.array(TournamentSchema), - count: z.number(), - }), - }, - }, - }, - 401: { description: "Unauthorized" }, - }, - security: [{ bearerAuth: [] }], -}); - -const MatchTeamSchema = z.object({ - number: z.number().int(), - scouters: z.array(z.object({ name: z.string(), scouted: z.boolean() })), - externalReports: z.number().int(), -}); - -const MatchSchema = z.object({ - matchNumber: z.number().int(), - matchType: z.number().int(), - scouted: z.boolean(), - finished: z.boolean(), - team1: MatchTeamSchema, - team2: MatchTeamSchema, - team3: MatchTeamSchema, - team4: MatchTeamSchema, - team5: MatchTeamSchema, - team6: MatchTeamSchema, -}); - -const PracticeMatchSchema = z.object({ - matchNumber: z.number().int(), - matchType: z.literal(2), - scouted: z.boolean(), - finished: z.literal(false), - teams: z - .array(MatchTeamSchema) - .describe( - "Publicly scheduled or visibly reported practice teams, sorted by team number; no alliance slots", - ), -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/matches/{tournament}", - tags: ["Manager - Matches"], - summary: "List matches for a tournament", - request: { - params: z.object({ tournament: z.string() }), - query: z.object({ - teams: z.string().optional(), - includePractice: z - .enum(["true", "false"]) - .optional() - .describe( - "Defaults to false. When true, append practice matches (matchType 2) with a teams array instead of team1–team6. Official scouting-shift numbering is unchanged.", - ), - }), - }, - responses: { - 200: { - description: "Formatted match list", - content: { - "application/json": { - schema: z.array(z.union([MatchSchema, PracticeMatchSchema])), - }, - }, - }, - 400: { description: "Invalid parameters" }, - 401: { description: "Unauthorized" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/checkmatch", - tags: ["Manager - Matches"], - summary: "Check if a match exists and if a team is in the match", - request: { - query: z.object({ - tournamentKey: z.string(), - teamNumber: z.coerce.number().int(), - matchNumber: z.coerce.number().int(), - isElim: z - .union([z.literal("true"), z.literal("false"), z.boolean()]) - .transform((value) => value === true || value === "true") - .optional() - .describe("Legacy match selector; provide this or matchType."), - matchType: z - .enum(["QUALIFICATION", "ELIMINATION", "PRACTICE"]) - .optional(), - }), - }, - responses: { - 200: { - description: "Match data row and alliance", - content: { - "application/json": { - schema: z.object({ - match: TeamMatchDataSchema, - alliance: z.enum(["red", "blue"]).nullable(), - }), - }, - }, - }, - 400: { description: "Invalid parameters" }, - 404: { description: "Match not found" }, - }, - security: [], -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/matchschedule/{tournament}", - tags: ["Manager - Matches"], - summary: - "Fetch public match assignments for Collection, including scheduled practice matches", - request: { - params: z.object({ tournament: z.string().min(1) }), - headers: z.object({ "x-team-code": z.string().min(1) }), - }, - responses: { - 200: { - description: - "Official and publicly scheduled practice assignments, without private scouting data", - content: { - "application/json": { - schema: z.object({ - tournamentKey: z.string(), - matches: z.array( - z.object({ - matchNumber: z.number().int(), - matchType: z.union([z.literal(0), z.literal(1), z.literal(2)]), - teams: z.array( - z.object({ - number: z.number().int(), - alliance: z.enum(["red", "blue"]).nullable(), - }), - ), - }), - ), - }), - }, - }, - }, - 400: { description: "Missing team code or tournament" }, - 401: { description: "Invalid team code" }, - 500: { description: "Unable to fetch schedule" }, - }, - security: [], -}); - -// Profile -const ProfileSchema = z.object({ - id: z.string(), - username: z.string().nullable(), - email: z.string().email(), - role: z.string(), - team: z - .object({ - team: z.object({ number: z.number().int(), name: z.string().nullable() }), - }) - .nullable(), -}); -registry.registerPath({ - method: "get", - path: "/v1/manager/profile", - tags: ["Manager - Account"], - summary: "Get current user profile", - responses: { - 200: { - description: "Profile", - content: { "application/json": { schema: ProfileSchema.nullable() } }, - }, - 401: { description: "Unauthorized" }, - }, - security: [{ bearerAuth: [] }], -}); - -// Users list -registry.registerPath({ - method: "get", - path: "/v1/manager/users", - tags: ["Manager - Users"], - summary: "List users", - responses: { - 200: { - description: "Users", - content: { - "application/json": { - schema: z.array( - z.object({ - id: z.string(), - email: z.string().email(), - username: z.string().nullable(), - role: z.string(), - }), - ), - }, - }, - }, - 401: { description: "Unauthorized" }, - }, - security: [{ bearerAuth: [] }], -}); - -// Delete user -registry.registerPath({ - method: "delete", - path: "/v1/manager/user", - tags: ["Manager - Users"], - summary: "Delete the current user", - responses: { - 200: { description: "Deleted" }, - 401: { description: "Unauthorized" }, - 403: { description: "Cannot be performed using an API key" }, - }, - security: [{ bearerAuth: [] }], -}); - -// Upgrade user role to scouting lead -registry.registerPath({ - method: "post", - path: "/v1/manager/upgradeuser", - tags: ["Manager - Users"], - summary: "Upgrade current user to Scouting Lead", - responses: { - 200: { description: "Upgraded" }, - 401: { description: "Unauthorized" }, - 403: { description: "Forbidden" }, - 400: { description: "Invalid request" }, - }, - security: [{ bearerAuth: [] }], -}); - -// Analysts -registry.registerPath({ - method: "get", - path: "/v1/manager/analysts", - tags: ["Manager - Users"], - summary: "List analysts", - responses: { - 200: { - description: "Analysts", - content: { - "application/json": { - schema: z.array( - z.object({ id: z.string(), username: z.string().nullable() }), - ), - }, - }, - }, - 401: { description: "Unauthorized" }, - 403: { description: "Not a scouting lead" }, - }, - security: [{ bearerAuth: [] }], -}); - -// Team code -registry.registerPath({ - method: "get", - path: "/v1/manager/code", - tags: ["Manager - Teams"], - summary: "Get team code for current user", - responses: { - 200: { - description: "Team code", - content: { - "application/json": { schema: z.object({ code: z.string() }) }, - }, - }, - 401: { description: "Unauthorized" }, - 403: { description: "Not authorized to get the team code" }, - }, - security: [{ bearerAuth: [] }], -}); - -// Dashboard scoutreport creation -registry.registerPath({ - method: "post", - path: "/v1/manager/dashboard/scoutreport", - tags: ["Manager - Scout Reports"], - summary: "Create scout report from dashboard", - request: { - body: { - content: { - "application/json": { - schema: z.object({ - match: z.number().int(), - team: z.number().int(), - notes: z.string().optional(), - }), - }, - }, - }, - }, - responses: { - 200: { - description: "Created", - content: { - "application/json": { schema: z.object({ uuid: z.string() }) }, - }, - }, - 401: { description: "Unauthorized" }, - 403: { description: "Cannot be performed using an API key" }, - 400: { description: "Invalid request" }, - }, - security: [{ bearerAuth: [] }], -}); - -// Team tournament status -registry.registerPath({ - method: "get", - path: "/v1/manager/team-tournament-status", - tags: ["Manager - Tournaments"], - summary: "Get status of current team in tournaments", - responses: { - 200: { - description: "Status", - content: { - "application/json": { - schema: z.object({ - tournaments: z.array( - z.object({ - id: z.string(), - code: z.string(), - status: z.string(), - }), - ), - }), - }, - }, - }, - 401: { description: "Unauthorized" }, - }, - security: [{ bearerAuth: [] }], -}); - -// Match results page -registry.registerPath({ - method: "get", - path: "/v1/manager/match-results-page", - tags: ["Manager - Matches"], - summary: "Get match results page data", - responses: { - 200: { - description: "Results", - content: { - "application/json": { - schema: z.object({ matches: z.array(MatchSchema) }), - }, - }, - }, - 401: { description: "Unauthorized" }, - }, - security: [{ bearerAuth: [] }], -}); - -// Update notes (Scouting Lead only) -registry.registerPath({ - method: "put", - path: "/v1/manager/notes/{uuid}", - tags: ["Manager - Notes"], - summary: "Update scout report notes (SCOUTING_LEAD)", - request: { - params: z.object({ uuid: z.string() }), - body: { - content: { - "application/json": { schema: z.object({ note: z.string() }) }, - }, - }, - }, - responses: { - 200: { description: "Note updated" }, - 400: { description: "Invalid request" }, - 401: { description: "Unauthorized" }, - 403: { description: "Not authorized" }, - }, - security: [{ bearerAuth: [] }], -}); - -// Scoutershift scouters -registry.registerPath({ - method: "get", - path: "/v1/manager/scoutershift/scouters", - tags: ["Manager - Scouters"], - summary: "List scouters for current team", - request: { query: z.object({ archived: z.string().optional() }) }, - responses: { - 200: { - description: "Scouters", - content: { - "application/json": { - schema: z.array( - z.object({ uuid: z.string(), name: z.string().nullable() }), - ), - }, - }, - }, - 401: { description: "Unauthorized" }, - 403: { description: "User not affiliated with a team" }, - }, - security: [{ bearerAuth: [] }], -}); - -// Set user as not on a team -registry.registerPath({ - method: "post", - path: "/v1/manager/noteam", - tags: ["Manager - Users"], - summary: "Set current user to ANALYST and remove team", - responses: { - 200: { - description: "Updated", - content: { - "application/json": { - schema: z.object({ - id: z.string(), - role: z.string(), - teamNumber: z.number().nullable(), - }), - }, - }, - }, - 401: { description: "Unauthorized" }, - 403: { description: "Cannot be performed using an API key" }, - }, - security: [{ bearerAuth: [] }], -}); - router.use("/onboarding", onboarding); router.use("/picklists", picklists); router.use("/mutablepicklists", mutablepicklist); diff --git a/apps/server/src/routes/manager/mutablepicklists.routes.ts b/apps/server/src/routes/manager/mutablepicklists.routes.ts index 8d6b1f50d..a10f47800 100644 --- a/apps/server/src/routes/manager/mutablepicklists.routes.ts +++ b/apps/server/src/routes/manager/mutablepicklists.routes.ts @@ -5,159 +5,8 @@ import { deleteMutablePicklist } from "../../handler/manager/mutablepicklists/de import { getMutablePicklists } from "../../handler/manager/mutablepicklists/getMutablePicklists.js"; import { getSingleMutablePicklist } from "../../handler/manager/mutablepicklists/getSingleMutablePicklist.js"; import { updateMutablePicklist } from "../../handler/manager/mutablepicklists/updateMutablePicklist.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; -import { MutablePicklistSchema } from "../../lib/prisma-zod.js"; import { requireVerifiedTeam } from "../../lib/middleware/requireVerifiedTeam.js"; -/* - -mutablepicklists.routes.ts - -POST /manager/mutablepicklists -GET /manager/mutablepicklists -GET /manager/mutablepicklists/:uuid -PUT /manager/mutablepicklists/:uuid -DELETE /manager/mutablepicklists/:uuid - -*/ - -const MutablePicklistCreateSchema = z.object({ - name: z.string(), - teams: z.array(z.number().int()), - tournamentKey: z.string().optional(), -}); - -const MutablePicklistListItemSchema = z.object({ - uuid: z.string(), - name: z.string(), - tournamentKey: z.string().nullable().optional(), - author: z.object({ username: z.string().nullable().optional() }), -}); - -registry.registerPath({ - method: "post", - path: "/v1/manager/mutablepicklists", - tags: ["Manager - Mutable Picklists"], - summary: "Create mutable picklist", - request: { - body: { - content: { "application/json": { schema: MutablePicklistCreateSchema } }, - }, - }, - responses: { - 200: { - description: "Created", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid request" }, - 401: { description: "Unauthorized" }, - 403: { - description: - "Cannot be performed using an API key, or user is not on a team", - }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/mutablepicklists", - tags: ["Manager - Mutable Picklists"], - summary: "List mutable picklists", - responses: { - 200: { - description: "List", - content: { - "application/json": { schema: z.array(MutablePicklistListItemSchema) }, - }, - }, - 401: { description: "Unauthorized" }, - 403: { description: "User is not on a team" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/mutablepicklists/{uuid}", - tags: ["Manager - Mutable Picklists"], - summary: "Get mutable picklist", - request: { params: z.object({ uuid: z.string() }) }, - responses: { - 200: { - description: "Detail", - content: { - "application/json": { schema: MutablePicklistSchema.nullable() }, - }, - }, - 400: { description: "Invalid request" }, - 404: { description: "Not found" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "put", - path: "/v1/manager/mutablepicklists/{uuid}", - tags: ["Manager - Mutable Picklists"], - summary: "Update mutable picklist", - request: { - params: z.object({ uuid: z.string() }), - body: { - content: { - "application/json": { - schema: z.object({ - name: z.string(), - teams: z.array(z.number().int()), - }), - }, - }, - }, - }, - responses: { - 200: { - description: "Updated", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid request" }, - 404: { description: "Picklist not found or not on same team" }, - 401: { description: "Unauthorized" }, - 403: { - description: - "Cannot be performed using an API key, or not authorized to update", - }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "delete", - path: "/v1/manager/mutablepicklists/{uuid}", - tags: ["Manager - Mutable Picklists"], - summary: "Delete mutable picklist", - request: { params: z.object({ uuid: z.string() }) }, - responses: { - 200: { - description: "Deleted", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid request" }, - 401: { description: "Unauthorized" }, - 403: { - description: - "Cannot be performed using an API key, or not authorized to delete", - }, - 404: { description: "Not found" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - const router = Router(); router.use(requireAuth, requireVerifiedTeam); diff --git a/apps/server/src/routes/manager/onboarding.routes.ts b/apps/server/src/routes/manager/onboarding.routes.ts index 95d96dafe..6bd3e3809 100644 --- a/apps/server/src/routes/manager/onboarding.routes.ts +++ b/apps/server/src/routes/manager/onboarding.routes.ts @@ -8,21 +8,6 @@ import { addRegisteredTeam } from "../../handler/manager/registeredteams/addRegi import rateLimit from "express-rate-limit"; import { addWebsite } from "../../handler/manager/onboarding/addWebsite.js"; import { resendEmail } from "../../handler/manager/onboarding/resendEmail.js"; -import { registry, LovatTimestampHeader } from "../../lib/openapi.js"; -import { z } from "zod"; - -/* - -onboarding.routes.ts - -POST /manager/onboarding/verifyemail -POST /manager/onboarding/username -POST /manager/onboarding/teamcode -POST /manager/onboarding/team -POST /manager/onboarding/teamwebsite -POST /manager/onboarding/resendverificationemail - -*/ const resendEmailLimiter = rateLimit({ windowMs: 2 * 60 * 1000, @@ -32,128 +17,6 @@ const resendEmailLimiter = rateLimit({ validate: { trustProxy: false }, }); -registry.registerPath({ - method: "post", - path: "/v1/manager/onboarding/verifyemail", - tags: ["Manager - Onboarding"], - summary: "Approve team email (signed)", - request: { - headers: LovatTimestampHeader, - body: { - content: { - "application/json": { schema: z.object({ code: z.string() }) }, - }, - }, - }, - responses: { - 200: { description: "Approved" }, - 400: { description: "Invalid" }, - 403: { description: "Invalid signature" }, - 404: { description: "Code not recognized" }, - 500: { description: "Server error" }, - }, - security: [{ lovatSignature: [] }], -}); -registry.registerPath({ - method: "post", - path: "/v1/manager/onboarding/username", - tags: ["Manager - Onboarding"], - summary: "Set username", - request: { - body: { - content: { - "application/json": { schema: z.object({ username: z.string() }) }, - }, - }, - }, - responses: { - 200: { description: "Updated" }, - 400: { description: "Invalid" }, - 401: { description: "Unauthorized" }, - 403: { description: "Cannot be performed using an API key" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "post", - path: "/v1/manager/onboarding/teamcode", - tags: ["Manager - Onboarding"], - summary: "Check team code", - request: { query: z.object({ team: z.string(), code: z.string() }) }, - responses: { - 200: { description: "Valid" }, - 400: { description: "Invalid" }, - 401: { description: "Unauthorized" }, - 403: { description: "Cannot be performed using an API key" }, - 404: { description: "Team/code not found" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "post", - path: "/v1/manager/onboarding/team", - tags: ["Manager - Onboarding"], - summary: "Add registered team", - request: { - body: { - content: { - "application/json": { - schema: z.object({ - number: z.number().int(), - name: z.string().optional(), - }), - }, - }, - }, - }, - responses: { - 200: { description: "Added" }, - 400: { description: "Invalid" }, - 401: { description: "Unauthorized" }, - 403: { description: "Cannot be performed using an API key" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "post", - path: "/v1/manager/onboarding/teamwebsite", - tags: ["Manager - Onboarding"], - summary: "Add team website", - request: { - body: { - content: { - "application/json": { schema: z.object({ website: z.string() }) }, - }, - }, - }, - responses: { - 200: { description: "Added" }, - 400: { description: "Invalid" }, - 401: { description: "Unauthorized" }, - 403: { description: "Cannot be performed using an API key" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "post", - path: "/v1/manager/onboarding/resendverificationemail", - tags: ["Manager - Onboarding"], - summary: "Resend verification email", - responses: { - 200: { description: "Sent" }, - 401: { description: "Unauthorized" }, - 403: { description: "Cannot be performed using an API key" }, - 404: { description: "Team not found" }, - 429: { description: "Rate limited" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - const router = Router(); router.post("/verifyemail", requireLovatSignature, approveTeamEmail); diff --git a/apps/server/src/routes/manager/picklists.routes.ts b/apps/server/src/routes/manager/picklists.routes.ts index a09693ef6..1429e88a0 100644 --- a/apps/server/src/routes/manager/picklists.routes.ts +++ b/apps/server/src/routes/manager/picklists.routes.ts @@ -5,194 +5,8 @@ import { deletePicklist } from "../../handler/manager/picklists/deletePicklist.j import { getPicklists } from "../../handler/manager/picklists/getPicklists.js"; import { getSinglePicklist } from "../../handler/manager/picklists/getSinglePicklist.js"; import { updatePicklist } from "../../handler/manager/picklists/updatePicklist.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; import { requireVerifiedTeam } from "../../lib/middleware/requireVerifiedTeam.js"; -/* - -picklists.routes.ts - -POST /manager/picklists -GET /manager/picklists -GET /manager/picklists/:uuid -PUT /manager/picklists/:uuid -DELETE /manager/picklists/:uuid - -*/ - -// Schemas for requests/responses -const PicklistCreateBodySchema = z.object({ - name: z.string(), - totalPoints: z.number().default(0).optional(), - autoPoints: z.number().default(0).optional(), - teleopPoints: z.number().default(0).optional(), - climbResult: z.number().default(0).optional(), - autoClimb: z.number().default(0).optional(), - defenseEffectiveness: z.number().default(0).optional(), - contactDefenseTime: z.number().default(0).optional(), - campingDefenseTime: z.number().default(0).optional(), - totalDefensiveTime: z.number().default(0).optional(), - totalFuelThroughput: z.number().default(0).optional(), - totalFuelFed: z.number().default(0).optional(), - feedingRate: z.number().default(0).optional(), - scoringRate: z.number().default(0).optional(), - estimatedSuccessfulFuelRate: z.number().default(0).optional(), - estimatedTotalFuelScored: z.number().default(0).optional(), - driverAbility: z.number().default(0).optional(), -}); - -const PicklistSummarySchema = z.object({ - name: z.string(), - uuid: z.string(), - author: z.object({ username: z.string().nullable().optional() }), -}); - -const PicklistDetailSchema = z.object({ - uuid: z.string(), - name: z.string(), - authorId: z.string(), - driverAbility: z.number(), - totalPoints: z.number(), - autoPoints: z.number(), - teleopPoints: z.number(), - climbResult: z.number(), - autoClimb: z.number(), - defenseEffectiveness: z.number(), - contactDefenseTime: z.number(), - campingDefenseTime: z.number(), - totalDefensiveTime: z.number(), - totalFuelThroughput: z.number(), - totalFuelFed: z.number(), - feedingRate: z.number(), - scoringRate: z.number(), - estimatedSuccessfulFuelRate: z.number(), - estimatedTotalFuelScored: z.number(), -}); - -const PicklistUpdateBodySchema = PicklistCreateBodySchema; - -// OpenAPI: Register paths for these routes -registry.registerPath({ - method: "post", - path: "/v1/manager/picklists", - tags: ["Manager - Picklists"], - summary: "Create shared picklist", - request: { - body: { - content: { - "application/json": { schema: PicklistCreateBodySchema }, - }, - required: true, - }, - }, - responses: { - 200: { - description: "Picklist created", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid body" }, - 401: { description: "Unauthorized" }, - 403: { - description: - "Cannot be performed using an API key, or user is not on a team", - }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/picklists", - tags: ["Manager - Picklists"], - summary: "List picklists by team", - responses: { - 200: { - description: "List of picklists", - content: { - "application/json": { schema: z.array(PicklistSummarySchema) }, - }, - }, - 401: { description: "Unauthorized" }, - 403: { description: "User is not on a team" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/picklists/{uuid}", - tags: ["Manager - Picklists"], - summary: "Get picklist by UUID", - request: { - params: z.object({ uuid: z.string() }), - }, - responses: { - 200: { - description: "Picklist detail", - content: { "application/json": { schema: PicklistDetailSchema } }, - }, - 400: { description: "Invalid UUID" }, - 401: { description: "Unauthorized" }, - 404: { description: "Picklist not found or not on same team" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "put", - path: "/v1/manager/picklists/{uuid}", - tags: ["Manager - Picklists"], - summary: "Update picklist", - request: { - params: z.object({ uuid: z.string() }), - body: { - content: { "application/json": { schema: PicklistUpdateBodySchema } }, - }, - }, - responses: { - 200: { - description: "Picklist updated", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid input" }, - 404: { description: "Picklist not found or not on same team" }, - 401: { description: "Unauthorized" }, - 403: { - description: - "Cannot be performed using an API key, or not authorized to update", - }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "delete", - path: "/v1/manager/picklists/{uuid}", - tags: ["Manager - Picklists"], - summary: "Delete picklist", - request: { params: z.object({ uuid: z.string() }) }, - responses: { - 200: { - description: "Deleted", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid UUID" }, - 401: { description: "Unauthorized" }, - 403: { - description: - "Cannot be performed using an API key, or unauthorized to delete this picklist", - }, - 404: { description: "Not found" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - const router = Router(); router.use(requireAuth, requireVerifiedTeam); diff --git a/apps/server/src/routes/manager/registeredteams.routes.ts b/apps/server/src/routes/manager/registeredteams.routes.ts index 76b397a1f..d6b0e43dc 100644 --- a/apps/server/src/routes/manager/registeredteams.routes.ts +++ b/apps/server/src/routes/manager/registeredteams.routes.ts @@ -4,88 +4,6 @@ import { rejectRegisteredTeam } from "../../handler/manager/registeredteams/reje import { approveRegisteredTeam } from "../../handler/manager/registeredteams/approveRegisteredTeam.js"; import { checkRegisteredTeam } from "../../handler/manager/registeredteams/checkRegisteredTeam.js"; import requireLovatSignature from "../../lib/middleware/requireLovatSignature.js"; -import { registry, LovatTimestampHeader } from "../../lib/openapi.js"; -import { z } from "zod"; -import { RegisteredTeamSchema } from "../../lib/prisma-zod.js"; - -const TeamParamSchema = z.object({ team: z.string() }); - -// Status variants returned by checkRegisteredTeam handler -const RegistrationStatusSchema = z.discriminatedUnion("status", [ - z.object({ status: z.literal("NOT_STARTED") }), - z.object({ - status: z.literal("PENDING_EMAIL_VERIFICATION"), - email: z.string(), - }), - z.object({ status: z.literal("PENDING_WEBSITE") }), - z.object({ - status: z.literal("PENDING_TEAM_VERIFICATION"), - teamEmail: z.string(), - }), - z.object({ status: z.literal("REGISTERED_ON_TEAM") }), - z.object({ status: z.literal("REGISTERED_OFF_TEAM") }), - z.object({ status: z.literal("PENDING") }), -]); - -registry.registerPath({ - method: "get", - path: "/v1/manager/registeredteams/{team}/registrationstatus", - tags: ["Manager - Registered Teams"], - summary: "Check team registration status", - request: { params: TeamParamSchema }, - responses: { - 200: { - description: "Registration status", - content: { "application/json": { schema: RegistrationStatusSchema } }, - }, - 400: { description: "Invalid team" }, - 401: { description: "Unauthorized" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "post", - path: "/v1/manager/registeredteams/{team}/approve", - tags: ["Manager - Registered Teams"], - summary: "Approve team", - description: - "Requires `x-signature` and `x-timestamp` headers. Signs request body, method, path.", - request: { params: TeamParamSchema, headers: LovatTimestampHeader }, - responses: { - 200: { - description: "Approved registered team row", - content: { "application/json": { schema: RegisteredTeamSchema } }, - }, - 400: { description: "Invalid team" }, - 401: { description: "Unauthorized or signature expired" }, - 403: { description: "Invalid signature" }, - 500: { description: "Server error" }, - }, - security: [{ lovatSignature: [] }], -}); - -registry.registerPath({ - method: "post", - path: "/v1/manager/registeredteams/{team}/reject", - tags: ["Manager - Registered Teams"], - summary: "Reject team", - description: - "Requires `x-signature` and `x-timestamp` headers. Signs request body, method, path.", - request: { params: TeamParamSchema, headers: LovatTimestampHeader }, - responses: { - 200: { - description: "Rejection message", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid team" }, - 401: { description: "Unauthorized or signature expired" }, - 403: { description: "Invalid signature" }, - 500: { description: "Server error" }, - }, - security: [{ lovatSignature: [] }], -}); const router = Router(); diff --git a/apps/server/src/routes/manager/scouters.routes.ts b/apps/server/src/routes/manager/scouters.routes.ts index 98b486e39..51d8d4cb1 100644 --- a/apps/server/src/routes/manager/scouters.routes.ts +++ b/apps/server/src/routes/manager/scouters.routes.ts @@ -15,9 +15,6 @@ import { scouterScoutReports } from "../../handler/analysis/scoutingLead/scouter import { deleteScouter } from "../../handler/manager/scouters/deleteScouter.js"; import { scoutingLeadProgressPage } from "../../handler/manager/scouters/scoutingLeadProgressPage.js"; import { updateScouterName } from "../../handler/manager/scouters/updateScouterName.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; -import { ScouterSchema } from "../../lib/prisma-zod.js"; import { requireVerifiedTeam } from "../../lib/middleware/requireVerifiedTeam.js"; const router = Router(); @@ -33,270 +30,6 @@ router.get("/scouters/:uuid/tournaments", getScouterTournaments); router.get("/scouterschedules/:tournament", getScheduleForScouter); router.get("/scouter/tournaments", getTournamentForScouterWithSchedule); -// Public/unauthenticated endpoints docs -registry.registerPath({ - method: "post", - path: "/v1/manager/emailTeamCode", - tags: ["Manager - Scouters (Public)"], - summary: "Email team code to registered address", - request: { query: z.object({ teamNumber: z.number().int() }) }, - responses: { - 200: { - description: "Email sent", - content: { - "application/json": { schema: z.object({ email: z.string().email() }) }, - }, - }, - 400: { description: "Invalid request" }, - 500: { description: "Server error" }, - }, -}); -registry.registerPath({ - method: "get", - path: "/v1/manager/scouter/checkcode", - tags: ["Manager - Scouters (Public)"], - summary: "Check team code", - request: { query: z.object({ code: z.string() }) }, - responses: { - 200: { - description: "Valid or team row", - content: { "application/json": { schema: z.any() } }, - }, - 400: { description: "Invalid request" }, - 500: { description: "Server error" }, - }, -}); -registry.registerPath({ - method: "post", - path: "/v1/manager/name/uuid/{uuid}", - tags: ["Manager - Scouters (Public)"], - summary: "Change scouter name by UUID", - request: { - params: z.object({ uuid: z.string() }), - body: { - content: { - "application/json": { schema: z.object({ name: z.string() }) }, - }, - }, - }, - responses: { - 200: { description: "Updated" }, - 400: { description: "Invalid request" }, - 500: { description: "Server error" }, - }, -}); -registry.registerPath({ - method: "get", - path: "/v1/manager/scouters", - tags: ["Manager - Scouters (Public)"], - summary: "List active scouters for team code", - request: { headers: z.object({ "x-team-code": z.string() }) }, - responses: { - 200: { - description: "Scouters", - content: { "application/json": { schema: z.array(ScouterSchema) } }, - }, - 400: { description: "Invalid request" }, - 404: { description: "Team code not found" }, - 500: { description: "Server error" }, - }, -}); -registry.registerPath({ - method: "post", - path: "/v1/manager/scouter", - tags: ["Manager - Scouters (Public)"], - summary: "Create scouter", - request: { - body: { - content: { - "application/json": { - schema: z.object({ teamNumber: z.number().int(), name: z.string() }), - }, - }, - }, - }, - responses: { - 200: { - description: "Created", - content: { "application/json": { schema: z.any() } }, - }, - 400: { description: "Invalid request" }, - 500: { description: "Server error" }, - }, -}); -registry.registerPath({ - method: "get", - path: "/v1/manager/scouters/{uuid}/tournaments", - tags: ["Manager - Scouters (Public)"], - summary: "List tournaments", - request: { params: z.object({ uuid: z.string() }) }, - responses: { - 200: { - description: "Tournaments", - content: { "application/json": { schema: z.array(z.any()) } }, - }, - 500: { description: "Server error" }, - }, -}); -registry.registerPath({ - method: "get", - path: "/v1/manager/scouterschedules/{tournament}", - tags: ["Manager - Scouters (Public)"], - summary: "Get scouter schedule", - request: { - params: z.object({ tournament: z.string() }), - headers: z.object({ "x-team-code": z.string() }), - }, - responses: { - 200: { - description: "Schedule", - content: { "application/json": { schema: z.any() } }, - }, - 400: { description: "Invalid request" }, - 500: { description: "Server error" }, - }, -}); -registry.registerPath({ - method: "get", - path: "/v1/manager/scouter/tournaments", - tags: ["Manager - Scouters (Public)"], - summary: "List scouter tournaments with schedule", - request: { headers: z.object({ "x-team-code": z.string() }) }, - responses: { - 200: { - description: "Tournaments", - content: { "application/json": { schema: z.array(z.any()) } }, - }, - 400: { description: "Invalid request" }, - 500: { description: "Server error" }, - }, -}); - -// OpenAPI docs for protected scouters endpoints -registry.registerPath({ - method: "post", - path: "/v1/manager/unarchive/uuid/{uuid}", - tags: ["Manager - Scouters"], - summary: "Unarchive scouter", - request: { params: z.object({ uuid: z.string() }) }, - responses: { - 200: { description: "Unarchived" }, - 401: { description: "Unauthorized" }, - 403: { description: "Forbidden" }, - 404: { description: "Not found" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "post", - path: "/v1/manager/archive/uuid/{uuid}", - tags: ["Manager - Scouters"], - summary: "Archive scouter", - request: { params: z.object({ uuid: z.string() }) }, - responses: { - 200: { description: "Archived" }, - 401: { description: "Unauthorized" }, - 403: { description: "Forbidden" }, - 404: { description: "Not found" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "put", - path: "/v1/manager/scoutername", - tags: ["Manager - Scouters"], - summary: "Update scouter name", - request: { - body: { - content: { - "application/json": { - schema: z.object({ uuid: z.string().optional(), name: z.string() }), - }, - }, - }, - }, - responses: { - 200: { description: "Updated" }, - 400: { description: "Invalid request" }, - 401: { description: "Unauthorized" }, - 403: { description: "Forbidden" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "delete", - path: "/v1/manager/scouterdashboard", - tags: ["Manager - Scouters"], - summary: "Delete scouter from dashboard", - responses: { - 200: { description: "Deleted" }, - 401: { description: "Unauthorized" }, - 403: { description: "Forbidden" }, - 404: { description: "Not found" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "get", - path: "/v1/manager/scouterspage", - tags: ["Manager - Scouters"], - summary: "Scouting lead progress page", - responses: { - 200: { - description: "Page data", - content: { "application/json": { schema: z.any() } }, - }, - 401: { description: "Unauthorized" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "post", - path: "/v1/manager/scouterdashboard", - tags: ["Manager - Scouters"], - summary: "Add scouter on dashboard", - request: { - body: { - content: { - "application/json": { - schema: z.object({ - scouterId: z.string(), - tournament: z.string().optional(), - }), - }, - }, - }, - }, - responses: { - 200: { description: "Created" }, - 400: { description: "Invalid request" }, - 401: { description: "Unauthorized" }, - 403: { description: "Forbidden" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "get", - path: "/v1/manager/scouterreports", - tags: ["Manager - Scouters"], - summary: "List scouter reports", - responses: { - 200: { - description: "Reports", - content: { "application/json": { schema: z.any() } }, - }, - 401: { description: "Unauthorized" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - router.post( "/unarchive/uuid/:uuid", requireAuth, diff --git a/apps/server/src/routes/manager/scoutershifts.routes.ts b/apps/server/src/routes/manager/scoutershifts.routes.ts index cca6dc0bd..0225a14ab 100644 --- a/apps/server/src/routes/manager/scoutershifts.routes.ts +++ b/apps/server/src/routes/manager/scoutershifts.routes.ts @@ -2,63 +2,10 @@ import { Router } from "express"; import { requireAuth } from "../../lib/middleware/requireAuth.js"; import { updateScouterShift } from "../../handler/manager/scoutershifts/updateScouterShift.js"; import { deleteScouterShift } from "../../handler/manager/scoutershifts/deleteScouterShift.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; import { requireVerifiedTeam } from "../../lib/middleware/requireVerifiedTeam.js"; import { superScoutingSchedule } from "../../handler/manager/scoutershifts/generateSchedule.js"; const router = Router(); - -const ScouterShiftUpdateSchema = z.object({ - startMatchOrdinalNumber: z.number().int(), - endMatchOrdinalNumber: z.number().int(), - team1: z.array(z.string()), - team2: z.array(z.string()), - team3: z.array(z.string()), - team4: z.array(z.string()), - team5: z.array(z.string()), - team6: z.array(z.string()), -}); - -registry.registerPath({ - method: "post", - path: "/v1/manager/scoutershifts/{uuid}", - tags: ["Manager - Scouter Shifts"], - summary: "Update scouter shift", - request: { - params: z.object({ uuid: z.string() }), - body: { - content: { "application/json": { schema: ScouterShiftUpdateSchema } }, - }, - }, - responses: { - 200: { description: "Updated" }, - 400: { description: "Invalid request" }, - 401: { description: "Unauthorized" }, - 403: { - description: - "Cannot be performed using an API key, or not a scouting lead", - }, - 404: { description: "Shift not found" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "delete", - path: "/v1/manager/scoutershifts/{uuid}", - tags: ["Manager - Scouter Shifts"], - summary: "Delete scouter shift", - request: { params: z.object({ uuid: z.string() }) }, - responses: { - 200: { description: "Deleted" }, - 401: { description: "Unauthorized" }, - 403: { description: "Forbidden" }, - 404: { description: "Not found" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); router.get("/generate", superScoutingSchedule); router.use(requireAuth, requireVerifiedTeam); diff --git a/apps/server/src/routes/manager/scoutreports.routes.ts b/apps/server/src/routes/manager/scoutreports.routes.ts index 336e3ef6d..ed9e84f68 100644 --- a/apps/server/src/routes/manager/scoutreports.routes.ts +++ b/apps/server/src/routes/manager/scoutreports.routes.ts @@ -4,150 +4,8 @@ import { addScoutReport } from "../../handler/collection/addScoutReport.js"; import { deleteScoutReport } from "../../handler/manager/scoutreports/deleteScoutReport.js"; import { getScoutReport } from "../../handler/manager/scoutreports/getScoutReport.js"; import { setScoutReportFlag } from "../../handler/manager/scoutreports/setScoutReportFlag.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; - -import { - EventSchema, - ScoutReportSchema as PrismaScoutReportSchema, -} from "../../lib/prisma-zod.js"; import { requireVerifiedTeam } from "../../lib/middleware/requireVerifiedTeam.js"; -const ScoutReportCreateSchema = z.object({ - uuid: z.string(), - tournamentKey: z.string(), - matchType: z.enum(["QUALIFICATION", "ELIMINATION", "PRACTICE"]), - matchNumber: z.number().int(), - startTime: z.number().int(), - notes: z.string(), - robotRoles: z.array( - z.enum(["CYCLING", "SCORING", "FEEDING", "DEFENDING", "IMMOBILE"]), - ), - mobility: z.enum(["TRENCH", "BUMP", "BOTH", "NONE"]), - climbPosition: z.enum(["SIDE", "MIDDLE"]).optional(), - climbSide: z.enum(["FRONT", "BACK"]).optional(), - beached: z.enum(["ON_FUEL", "ON_BUMP", "BOTH", "NEITHER"]), - feederTypes: z.array(z.enum(["CONTINUOUS", "STOP_TO_SHOOT", "DUMP"])), - intakeType: z.enum(["GROUND", "OUTPOST", "BOTH", "NEITHER"]), - robotBrokeDescription: z.string().nullable().optional(), - driverAbility: z.number().int(), - accuracy: z.number().int().optional(), - disrupts: z.boolean(), - defenseEffectiveness: z.number().int(), - scoresWhileMoving: z.boolean(), - autoClimb: z.enum(["NOT_ATTEMPTED", "FAILED", "SUCCEEDED"]), - endgameClimb: z.enum(["NOT_ATTEMPTED", "FAILED", "L1", "L2", "L3"]), - scouterUuid: z.string(), - teamNumber: z.number().int(), - events: z.array( - z.tuple([ - z.number().int(), // time - z.number().int(), // action index - z.number().int(), // position index - z.number().int().optional(), // points/quantity (optional) - ]), - ), -}); - -registry.registerPath({ - method: "post", - path: "/v1/manager/scoutreports", - tags: ["Manager - Scout Reports"], - summary: "Create scout report", - request: { - body: { - content: { "application/json": { schema: ScoutReportCreateSchema } }, - }, - }, - responses: { - 200: { - description: "Created", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid request" }, - 404: { description: "Match not found" }, - 500: { description: "Server error" }, - }, -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/scoutreports/{uuid}", - security: [{ bearerAuth: [] }], - tags: ["Manager - Scout Reports"], - summary: "Get scout report", - request: { params: z.object({ uuid: z.string() }) }, - responses: { - 200: { - description: "Scout report and events", - content: { - "application/json": { - schema: z.object({ - scoutReport: PrismaScoutReportSchema, - events: z.array(EventSchema), - }), - }, - }, - }, - 400: { description: "Invalid request" }, - 404: { description: "Not found" }, - 500: { description: "Server error" }, - }, -}); - -registry.registerPath({ - method: "delete", - path: "/v1/manager/scoutreports/{uuid}", - security: [{ bearerAuth: [] }], - tags: ["Manager - Scout Reports"], - summary: "Delete scout report", - request: { params: z.object({ uuid: z.string() }) }, - responses: { - 200: { - description: "Deleted", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid request" }, - 403: { description: "Forbidden" }, - 404: { description: "Not found" }, - 500: { description: "Server error" }, - }, -}); - -registry.registerPath({ - method: "post", - path: "/v1/manager/scoutreports/setflag/{report}", - security: [{ bearerAuth: [] }], - tags: ["Manager - Scout Reports"], - summary: "Set or remove your flag on a scout report", - request: { - params: z.object({ - report: z.string().min(1), - }), - query: z.object({ - flag: z.enum(["true", "false"]), - }), - }, - responses: { - 200: { - description: "Flag updated", - content: { - "application/json": { - schema: z.object({ - flagged: z.boolean(), - flagCount: z.number().int().nonnegative(), - }), - }, - }, - }, - 400: { description: "Invalid report parameter or flag value" }, - 401: { description: "Authentication required or no team assigned" }, - 403: { description: "Team is not verified" }, - 404: { description: "Report not found or outside allowed sources" }, - 500: { description: "Server error" }, - }, -}); - const router = Router(); router.post("/", addScoutReport); diff --git a/apps/server/src/routes/manager/settings.routes.ts b/apps/server/src/routes/manager/settings.routes.ts index 3fe56968d..751540f02 100644 --- a/apps/server/src/routes/manager/settings.routes.ts +++ b/apps/server/src/routes/manager/settings.routes.ts @@ -7,8 +7,6 @@ import { getTeamSource } from "../../handler/manager/settings/getTeamSource.js"; import { addTeamSource } from "../../handler/manager/settings/addTeamSource.js"; import { getTournamentSource } from "../../handler/manager/settings/getTournamentSource.js"; import { addTournamentSource } from "../../handler/manager/settings/addTournamentSource.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; import { getTeamEmail } from "../../handler/manager/settings/getTeamEmail.js"; import { requireVerifiedTeam } from "../../lib/middleware/requireVerifiedTeam.js"; @@ -22,173 +20,6 @@ const updateTeamEmails = rateLimit({ const router = Router(); -registry.registerPath({ - method: "put", - path: "/v1/manager/settings", - tags: ["Manager - Settings"], - summary: "Update sources", - request: { - body: { - content: { - "application/json": { - schema: z.object({ - teamSource: z.array(z.number().int()), - tournamentSource: z.array(z.string()), - }), - }, - }, - }, - }, - responses: { - 200: { - description: "Updated", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid request" }, - 401: { description: "Unauthorized" }, - 403: { description: "Cannot be performed using an API key" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/settings/teamsource", - tags: ["Manager - Settings"], - summary: "Get team source", - responses: { - 200: { - description: "Team source", - content: { - "application/json": { - schema: z.union([ - z.literal("THIS_TEAM"), - z.literal("ALL_TEAMS"), - z.array(z.number().int()), - ]), - }, - }, - }, - 401: { description: "Unauthorized" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "post", - path: "/v1/manager/settings/teamsource", - tags: ["Manager - Settings"], - summary: "Add team source", - request: { - body: { - content: { - "application/json": { - schema: z.union([ - z.object({ mode: z.literal("ALL_TEAMS") }), - z.object({ mode: z.literal("THIS_TEAM") }), - z.object({ teams: z.array(z.number().int()) }), - ]), - }, - }, - }, - }, - responses: { - 200: { - description: "Added", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid request" }, - 401: { description: "Unauthorized" }, - 403: { description: "Not affiliated with a team" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/settings/tournamentsource", - tags: ["Manager - Settings"], - summary: "Get tournament source", - responses: { - 200: { - description: "Tournament source", - content: { "application/json": { schema: z.array(z.string()) } }, - }, - 401: { description: "Unauthorized" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "post", - path: "/v1/manager/settings/tournamentsource", - tags: ["Manager - Settings"], - summary: "Add tournament source", - request: { - body: { - content: { - "application/json": { - schema: z.object({ tournaments: z.array(z.string()) }), - }, - }, - }, - }, - responses: { - 200: { - description: "Added", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid request" }, - 401: { description: "Unauthorized" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/settings/teamemail", - tags: ["Manager - Settings"], - summary: "Get team email", - responses: { - 200: { - description: "Team email", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid request" }, - 401: { description: "Unauthorized" }, - 403: { description: "Forbidden" }, - 404: { description: "Team not found" }, - 429: { description: "Rate limited" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - -registry.registerPath({ - method: "put", - path: "/v1/manager/settings/teamemail", - tags: ["Manager - Settings"], - summary: "Update team email", - request: { query: z.object({ email: z.string().email() }) }, - responses: { - 200: { - description: "Verification sent", - content: { "text/plain": { schema: z.string() } }, - }, - 400: { description: "Invalid request" }, - 401: { description: "Unauthorized" }, - 404: { description: "Team not found" }, - 429: { description: "Rate limited" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - router.use(requireAuth); router.put("/", updateSettings); diff --git a/apps/server/src/routes/manager/tournaments.routes.ts b/apps/server/src/routes/manager/tournaments.routes.ts index ca667400f..c12d0b857 100644 --- a/apps/server/src/routes/manager/tournaments.routes.ts +++ b/apps/server/src/routes/manager/tournaments.routes.ts @@ -4,146 +4,8 @@ import { getTeamsInTournament } from "../../handler/manager/tournament/getTeamsI import { getTeamRankings } from "../../handler/manager/tournament/getTeamRankings.js"; import { addScouterShift } from "../../handler/manager/tournament/addScouterShift.js"; import { getScouterSchedule } from "../../handler/manager/tournament/getScouterSchedule.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; -import { - TeamSchema, - ScouterScheduleShiftSchema, -} from "../../lib/prisma-zod.js"; import { requireVerifiedTeam } from "../../lib/middleware/requireVerifiedTeam.js"; -/* - - tournaments.routes.ts - - GET /manager/tournaments - GET /manager/tournament/:tournament/teams - GET /manager/tournament/:tournament/rankedTeams - GET /manager/tournament/:tournament/scoutershifts - - */ - -const TournamentParamSchema = z.object({ tournament: z.string() }); - -const ScouterTeamRelationSchema = z - .object({ name: z.string().nullable(), uuid: z.string() }) - .nullable(); - -const ScouterScheduleShiftWithTeamsSchema = ScouterScheduleShiftSchema.extend({ - team1: ScouterTeamRelationSchema, - team2: ScouterTeamRelationSchema, - team3: ScouterTeamRelationSchema, - team4: ScouterTeamRelationSchema, - team5: ScouterTeamRelationSchema, - team6: ScouterTeamRelationSchema, -}); - -registry.registerPath({ - method: "get", - path: "/v1/manager/tournament/{tournament}/teams", - tags: ["Manager - Tournaments"], - summary: "List teams in tournament", - request: { params: TournamentParamSchema }, - responses: { - 200: { - description: "Teams", - content: { "application/json": { schema: z.array(TeamSchema) } }, - }, - 401: { description: "Unauthorized" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "get", - path: "/v1/manager/tournament/{tournament}/rankedTeams", - tags: ["Manager - Tournaments"], - summary: "Ranked teams", - request: { params: TournamentParamSchema }, - responses: { - 200: { - description: "Rankings", - content: { - "application/json": { - schema: z.array( - z.object({ - number: z.number().int(), - name: z.string(), - rank: z.number().int().nullable(), - rankingPoints: z.number().int().nullable(), - matchesPlayed: z.number().int().nullable(), - avatar: z.string().nullable(), - }), - ), - }, - }, - }, - 404: { description: "Tournament or teams not found" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "post", - path: "/v1/manager/tournament/{tournament}/scoutershifts", - tags: ["Manager - Tournaments"], - summary: "Create scouter shift", - request: { - params: TournamentParamSchema, - body: { - content: { - "application/json": { - schema: z.object({ - startMatchOrdinalNumber: z.number().int(), - endMatchOrdinalNumber: z.number().int(), - team1: z.array(z.string()), - team2: z.array(z.string()), - team3: z.array(z.string()), - team4: z.array(z.string()), - team5: z.array(z.string()), - team6: z.array(z.string()), - }), - }, - }, - }, - }, - responses: { - 200: { description: "Created" }, - 400: { - description: - "Invalid request, overlapping scouters, or overlapping shift matches", - }, - 401: { description: "Unauthorized" }, - 403: { description: "API key forbidden or user role not SCOUTING_LEAD" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); -registry.registerPath({ - method: "get", - path: "/v1/manager/tournament/{tournament}/scoutershifts", - tags: ["Manager - Tournaments"], - summary: "List scouter shifts", - request: { params: TournamentParamSchema }, - responses: { - 200: { - description: "Shifts", - content: { - "application/json": { - schema: z.object({ - hash: z.string(), - data: z.array(ScouterScheduleShiftWithTeamsSchema), - }), - }, - }, - }, - 401: { description: "Unauthorized" }, - 403: { description: "User not affiliated with a team" }, - 500: { description: "Server error" }, - }, - security: [{ bearerAuth: [] }], -}); - const router = Router(); router.use(requireAuth); diff --git a/apps/server/src/routes/slack/slack.routes.ts b/apps/server/src/routes/slack/slack.routes.ts index aad54ca6f..0f788aaa0 100644 --- a/apps/server/src/routes/slack/slack.routes.ts +++ b/apps/server/src/routes/slack/slack.routes.ts @@ -5,8 +5,6 @@ import { requireSlackToken } from "../../lib/middleware/requireSlackToken.js"; import { addSlackWorkspace } from "../../handler/slack/addSlackWorkspace.js"; import { processCommand } from "../../handler/slack/processCommands.js"; import { processEvent } from "../../handler/slack/processEvents.js"; -import { registry } from "../../lib/openapi.js"; -import { z } from "zod"; /* @@ -20,55 +18,6 @@ POST /slack/event const router = Router(); -registry.registerPath({ - method: "get", - path: "/v1/slack/add-workspace", - tags: ["Slack"], - summary: "Add Slack workspace (OAuth flow)", - responses: { 200: { description: "Redirect or JSON" } }, - security: [{ slackToken: [] }], -}); -registry.registerPath({ - method: "post", - path: "/v1/slack/command", - tags: ["Slack"], - summary: "Slack slash command", - request: { - body: { - content: { - "application/x-www-form-urlencoded": { - schema: z.object({ - command: z.string(), - text: z.string().optional(), - }), - }, - }, - }, - }, - responses: { 200: { description: "Processed" } }, - security: [{ slackToken: [] }], -}); -registry.registerPath({ - method: "post", - path: "/v1/slack/event", - tags: ["Slack"], - summary: "Slack event callback", - request: { - body: { - content: { - "application/json": { - schema: z.object({ - type: z.string(), - event: z.record(z.string(), z.any()), - }), - }, - }, - }, - }, - responses: { 200: { description: "Processed" } }, - security: [{ slackToken: [] }], -}); - router.get("/add-workspace", addSlackWorkspace); router.post( diff --git a/apps/server/test/openapiErrors.unit.test.ts b/apps/server/test/openapiErrors.unit.test.ts index 033976ee1..6d0e2141a 100644 --- a/apps/server/test/openapiErrors.unit.test.ts +++ b/apps/server/test/openapiErrors.unit.test.ts @@ -1,8 +1,6 @@ -import { afterEach, expect, it, vi } from "vitest"; -import { OpenApiGeneratorV31 } from "@asteasolutions/zod-to-openapi"; -import { generateOpenApiDocument } from "../src/lib/openapi.js"; +import { expect, it } from "vitest"; +import { normalizeLegacyErrorResponses } from "@lovat/api/legacy"; -afterEach(() => vi.restoreAllMocks()); it("preserves referenced/default/success responses while filling sparse error documentation", () => { const originalDefault = { description: "Existing default" }; const success = { description: "OK", content: { "text/plain": {} } }; @@ -25,10 +23,7 @@ it("preserves referenced/default/success responses while filling sparse error do }, }, }; - vi.spyOn(OpenApiGeneratorV31.prototype, "generateDocument").mockReturnValue( - generated as never, - ); - const document = generateOpenApiDocument(); + const document = normalizeLegacyErrorResponses(generated as never); expect(document.paths?.["/mixed"]?.post?.responses).toMatchObject({ "200": success, "400": referenced, @@ -48,8 +43,5 @@ it("preserves referenced/default/success responses while filling sparse error do }); }); it("supports a document with no registered paths", () => { - vi.spyOn(OpenApiGeneratorV31.prototype, "generateDocument").mockReturnValue( - {} as never, - ); - expect(generateOpenApiDocument().paths).toBeUndefined(); + expect(normalizeLegacyErrorResponses({} as never).paths).toBeUndefined(); }); diff --git a/apps/server/tools/serve-qualification.mjs b/apps/server/tools/serve-qualification.mjs new file mode 100644 index 000000000..f804b7234 --- /dev/null +++ b/apps/server/tools/serve-qualification.mjs @@ -0,0 +1,71 @@ +import { createInterface } from "node:readline"; +// Test tooling only; this is never the deployment entrypoint. +import { once } from "node:events"; +import http from "node:http"; +import https from "node:https"; +import { syncBuiltinESMExports } from "node:module"; +if ( + process.env.LOVAT_DB_TEST !== "1" || + process.env.LOVAT_LOCAL_QUALIFICATION !== "1" +) { + throw new Error("Use the rollout qualification runner"); +} +const database = new URL(process.env.DATABASE_URL ?? ""); +const redis = new URL(process.env.REDIS_URL ?? ""); +if ( + database.hostname !== "127.0.0.1" || + database.pathname !== "/lovat_test" || + redis.hostname !== "127.0.0.1" +) { + throw new Error("Use disposable loopback services"); +} +const local = (input) => { + const host = + typeof input === "string" || input instanceof URL + ? new URL(input).hostname + : (input.hostname ?? input.host?.split(":")[0] ?? "localhost"); + if (!["localhost", "127.0.0.1"].includes(host)) { + throw new Error( + "External providers are disabled during local qualification", + ); + } +}; +for (const transport of [http, https]) { + for (const method of ["request", "get"]) { + const original = transport[method]; + transport[method] = function (input, ...rest) { + local(input); + return original.call(this, input, ...rest); + }; + } +} +syncBuiltinESMExports(); +const originalFetch = globalThis.fetch; +globalThis.fetch = (input, init) => { + local(input instanceof Request ? input.url : input); + return originalFetch(input, init); +}; +const { posthog } = await import("../dist/src/posthogClient.js"); +await posthog.disable(); +const { app } = await import("../dist/src/app.js"); +const { db } = await import("@lovat/db"); +const { closeRedis } = await import("../dist/src/redisClient.js"); +const server = app.listen(0, "127.0.0.1"); +await once(server, "listening"); +console.log( + JSON.stringify({ + type: "ready", + url: "http://127.0.0.1:" + server.address().port, + }), +); +const commands = createInterface({ input: process.stdin }); +commands.on("line", async (line) => { + const message = JSON.parse(line); + if (message.type === "stop") { + await new Promise((resolve) => server.close(resolve)); + await closeRedis(); + await posthog.shutdown(); + await db.$disconnect(); + commands.close(); + } +}); diff --git a/apps/worker/Dockerfile b/apps/worker/Dockerfile index 22b3abe21..0664f3613 100644 --- a/apps/worker/Dockerfile +++ b/apps/worker/Dockerfile @@ -6,6 +6,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-cert COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun WORKDIR /app +COPY packages/api ./packages/api +RUN npm --prefix packages/api ci --include=dev && npm --prefix packages/api run build COPY packages/db ./packages/db RUN npm --prefix packages/db ci --include=dev && npm --prefix packages/db run build diff --git a/apps/worker/Dockerfile.dockerignore b/apps/worker/Dockerfile.dockerignore index b0ef99570..498140d1d 100644 --- a/apps/worker/Dockerfile.dockerignore +++ b/apps/worker/Dockerfile.dockerignore @@ -1,5 +1,7 @@ ** !packages/ +!packages/api/ +!packages/api/** !packages/db/ !packages/db/** !apps/ diff --git a/apps/worker/README.md b/apps/worker/README.md index 42e4814c5..4eebf9e06 100644 --- a/apps/worker/README.md +++ b/apps/worker/README.md @@ -298,6 +298,13 @@ data. A fresh empty response clears withdrawn data, while HTTP 304 preserves it. Run `bun run backfill 1992 2025` with the target database and TBA credentials configured to queue archived season imports. With no arguments, it queues every season from 1992 through the current year. Existing jobs keep their leases and retry schedules. Tournament and district imports queue event and district details through the existing scheduler, so the backfill continues on the worker. +## Replacement API effects + +Set `WORKER_MODE=continuous API_EFFECTS_ENABLED=true` only when running the replacement API with the two additive outbox migrations applied. Set `REDIS_URL` and `REDIS_KEY_PREFIX` to the API's values (default prefix `lovat:rewrite:`), and `RESEND_KEY` / `EMAIL_FROM` for onboarding email delivery. Finite batch/scheduled modes reject this flag to avoid disconnecting Prisma beneath the effect consumer or silently delaying delivery. Use a continuously running consumer when qualifying the replacement; for Railway-managed configuration, set the IaC input `RAILWAY_WORKER_CRON=""` to retain continuous mode. This loop shares the worker process but has one consumer; it does not run in the API request path. + +Reports and analysis revisions commit with durable outbox records. Consumers claim records with a 60-second lease and retry failures with exponential backoff, up to ten attempts. Slack warning fan-out creates one durable child per subscribed channel so a failed channel does not resend every successful channel. External delivery is at least once; email idempotency keys and Slack client message IDs reduce duplicates, but cannot guarantee exactly-once delivery after a remote timeout. Failed records retain a sanitized error and can be inspected by an operator before replay. Cache revisions increase monotonically; the API's 15-second cache lifetime also bounds staleness if Redis delivery is unavailable. + +The loop abandons expired drafts, scrubs old abandoned payloads, and removes expired verification requests and delivered outbox records. Training reports never create competition cache revisions or warnings. Keep this flag disabled for the existing Server deployment until cutover qualification is complete. ## Finite batches (LVT-382) @@ -331,7 +338,6 @@ timers and needs no TBA key. Read-time report and verification expiry checks sta in the API. Import ownership overlaps LVT-335; resource/pool tuning remains with LVT-376. See [batch rollout](../../docs/worker-batch-rollout.md) before cutover. - `WORKER_MODE=scheduled` combines six-hour external Cron with automatic event-day continuous runs. Outside competition dates it exits after the batch. On an event's local dates it keeps the minute-level loop until all current events finish, then diff --git a/apps/worker/bun.lock b/apps/worker/bun.lock index 6f91422e2..ecef55fb7 100644 --- a/apps/worker/bun.lock +++ b/apps/worker/bun.lock @@ -5,9 +5,10 @@ "": { "name": "worker", "dependencies": { + "@lovat/api": "file:../../packages/api", "@lovat/db": "file:../../packages/db", "hono": "^4.13.13", - "zod": "4.6.5", + "zod": "4.6.7", }, "devDependencies": { "@types/bun": "latest", @@ -18,12 +19,16 @@ }, }, "packages": { + "@asteasolutions/zod-to-openapi": ["@asteasolutions/zod-to-openapi@9.1.0", "", { "dependencies": { "openapi3-ts": "^4.6.0" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-pLMeRgRYS7/vZIgAAkOe2P6+XGTifR1MT9pqDoxZ11EmcJJ+DPmdPqLN8ZZF4U8R9KHCCQCS9c2wtuE8wSrfkw=="], + "@electric-sql/pglite": ["@electric-sql/pglite@0.4.3", "", {}, "sha512-ichuWTgtd4mOM1G4SpyGJa5trT03lWbMypDV0fUXUCXg5hiHqVAz/bZyV68NqmkLB7WcYmj1RMJVSp8HV/v/ZQ=="], "@electric-sql/pglite-socket": ["@electric-sql/pglite-socket@0.1.3", "", { "peerDependencies": { "@electric-sql/pglite": "0.4.3" }, "bin": { "pglite-server": "dist/scripts/server.js" } }, "sha512-LAciWM0M1dCL8hlsxu2venbVZcdxema0BtDfpWYVqr+Y468UADw0pFWidhKw1M8sfJ8rdLT71tjMmnirf/IZRQ=="], "@electric-sql/pglite-tools": ["@electric-sql/pglite-tools@0.3.3", "", { "peerDependencies": { "@electric-sql/pglite": "0.4.3" } }, "sha512-AlzLJTRJ8+UFgK8CmxIpyIpJ0+YaFw02IiOSdYrqxwPXdSyeIShz8aa9Tq+tYFXdPwcaMp/Fc80mQZ1dkOQ/wg=="], + "@lovat/api": ["@lovat/api@file:../../packages/api", { "dependencies": { "@asteasolutions/zod-to-openapi": "9.1.0", "zod": "4.6.5" }, "devDependencies": { "prettier": "3.9.9", "typescript": "5.9.3" } }], + "@lovat/db": ["@lovat/db@file:../../packages/db", { "dependencies": { "@prisma/adapter-pg": "7.10.0", "@prisma/client": "7.10.0", "dotenv": "16.6.1", "pg": "8.16.3" }, "devDependencies": { "@types/node": "^22.20.2", "@types/pg": "^8.15.0", "prisma": "7.10.0", "typescript": "5.9.3" } }], "@prisma/adapter-pg": ["@prisma/adapter-pg@7.10.0", "", { "dependencies": { "@prisma/driver-adapter-utils": "7.10.0", "@types/pg": "^8.16.0", "pg": "^8.16.3", "postgres-array": "3.0.4" } }, "sha512-N7nwSor0HO1Kz6xBv0TPAjAPysKK0fac6p4fVN3ensLOuzc/83Fgmln5k92eK/cvzqdkSR/2kkAqlbcdwVrwpw=="], @@ -240,6 +245,8 @@ "ohash": ["ohash@2.0.12", "", {}, "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw=="], + "openapi3-ts": ["openapi3-ts@4.6.2", "", { "dependencies": { "yaml": "^2.9.1" } }, "sha512-gyyil3DweqhXiEhTqtAs9wwRLfWHmetwhI4kmM5Rn0d6gtmK863Ki7qqbQnp9+Wwlqoe3B1LFWj7kMp5ctE4rQ=="], + "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], @@ -274,6 +281,8 @@ "postgres-interval": ["postgres-interval@1.2.0", "", { "dependencies": { "xtend": "^4.0.0" } }, "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ=="], + "prettier": ["prettier@3.9.9", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-Z/CJHIkdujO/OtN7nXUii0Rf3VT5SRuhjBA82Xvu2XhBUgX3nhP67T0LHceBdQLex7OOFGTox+Q5Yg8Jk2Qivg=="], + "prisma": ["prisma@7.10.0", "", { "dependencies": { "@prisma/config": "7.10.0", "@prisma/dev": "0.24.17", "@prisma/engines": "7.10.0", "@prisma/studio-core": "0.33.0", "mysql2": "3.15.3", "postgres": "3.4.7" }, "peerDependencies": { "better-sqlite3": ">=9.0.0", "typescript": ">=5.4.0" }, "optionalPeers": ["better-sqlite3", "typescript"], "bin": { "prisma": "build/index.js" } }, "sha512-o0ornyJOWgygVAzGCpr8PdXV8EJLHyVGDDUr/voBQt8Azzw8cYTByzzPGcA/m4tCkPcnJA8raEOv2CslsKhPEw=="], "proper-lockfile": ["proper-lockfile@4.1.2", "", { "dependencies": { "graceful-fs": "^4.2.4", "retry": "^0.12.0", "signal-exit": "^3.0.2" } }, "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA=="], @@ -328,9 +337,13 @@ "xtend": ["xtend@4.0.2", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="], + "yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="], + "zeptomatch": ["zeptomatch@2.1.0", "", { "dependencies": { "grammex": "^3.1.11", "graphmatch": "^1.1.0" } }, "sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA=="], - "zod": ["zod@4.6.5", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="], + "zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], + + "@lovat/api/zod": ["zod@4.6.5", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="], "@prisma/engines/@prisma/get-platform": ["@prisma/get-platform@7.10.0", "", { "dependencies": { "@prisma/debug": "7.10.0" } }, "sha512-0bra1LFYi8xNw0yqV62bHJNQk4BKleOngZiqPWIQc7a3+9q6rqsnqJ15BuepP8943PFMvtmgnP52juZsyYkA6w=="], diff --git a/apps/worker/index.ts b/apps/worker/index.ts index b3c3bf882..27bfe6cb4 100644 --- a/apps/worker/index.ts +++ b/apps/worker/index.ts @@ -1,20 +1,24 @@ +import { createOutboxDelivery, runOutbox } from "./src/outbox"; import { db } from "./src/db"; import { tba } from "./src/tba"; import { runBatch, runWorker } from "./src/worker"; import { runScheduledWindow } from "./src/scheduled-window"; import { createHealthApp, healthPort } from "./src/server"; -// Validate the provider configuration before starting any background work. +// Validate configuration before starting background work. void tba; - -const shutdown = new AbortController(); -const stop = () => shutdown.abort(); -let lastReconciledAt = 0; - const mode = process.env.WORKER_MODE ?? "continuous"; if (!["batch", "continuous", "scheduled"].includes(mode)) throw new Error("WORKER_MODE must be batch, scheduled or continuous"); +const effectsEnabled = process.env.API_EFFECTS_ENABLED === "true"; +if (effectsEnabled && mode !== "continuous") + throw new Error( + "API_EFFECTS_ENABLED requires WORKER_MODE=continuous; finite import windows cannot provide continuous effect delivery", + ); +const shutdown = new AbortController(); +const stop = () => shutdown.abort(); +let lastReconciledAt = 0; const port = healthPort(); const concurrency = Number(process.env.WORKER_CONCURRENCY ?? 2); const app = createHealthApp({ @@ -26,28 +30,39 @@ const app = createHealthApp({ await db.$queryRaw`SELECT 1`; }, }); - process.once("SIGINT", stop); process.once("SIGTERM", stop); - let server: ReturnType | undefined; +let effects: ReturnType | undefined; +let effectsLoop: Promise | undefined; try { - // Batch has no listener or readiness queries between windows. if (mode === "batch") { await runBatch(db, shutdown.signal, concurrency); } else if (mode === "scheduled") { await runScheduledWindow(db, shutdown.signal, concurrency); } else { - // Migrations are owned by the release/API service. await db.$queryRaw`SELECT 1 FROM "ImportJob", "FetchState", "TournamentGap" LIMIT 0`; server = Bun.serve({ hostname: "0.0.0.0", port, fetch: app.fetch }); + if (effectsEnabled) { + effects = createOutboxDelivery(db, { + redisUrl: process.env.REDIS_URL ?? "redis://127.0.0.1:6379", + prefix: process.env.REDIS_KEY_PREFIX ?? "lovat:rewrite:", + resendKey: process.env.RESEND_KEY, + emailFrom: process.env.EMAIL_FROM, + slackWebhook: process.env.SLACK_WEBHOOK, + }); + effectsLoop = runOutbox(db, effects, shutdown.signal); + } await runWorker(db, shutdown.signal, concurrency, () => { lastReconciledAt = Date.now(); }); } } finally { + shutdown.abort(); + await effectsLoop; process.removeListener("SIGINT", stop); process.removeListener("SIGTERM", stop); + effects?.close(); await server?.stop(true); await db.$disconnect(); } diff --git a/apps/worker/package.json b/apps/worker/package.json index 7fb70a736..531d4723c 100644 --- a/apps/worker/package.json +++ b/apps/worker/package.json @@ -8,7 +8,7 @@ "batch": "WORKER_MODE=batch bun run index.ts", "enqueue": "bun run src/enqueue.ts", "backfill": "bun run src/backfill.ts", - "postinstall": "npm --prefix ../../packages/db ci --include=dev && npm --prefix ../../packages/db run build", + "postinstall": "npm --prefix ../../packages/api ci --include=dev && npm --prefix ../../packages/api run build && npm --prefix ../../packages/db ci --include=dev && npm --prefix ../../packages/db run build", "test": "bun test", "typecheck": "tsc --noEmit" }, @@ -19,8 +19,9 @@ "typescript": "^5" }, "dependencies": { + "@lovat/api": "file:../../packages/api", "@lovat/db": "file:../../packages/db", "hono": "^4.13.13", - "zod": "4.6.5" + "zod": "4.6.7" } } diff --git a/apps/worker/src/jobs/report-reliability.ts b/apps/worker/src/jobs/report-reliability.ts index 406d53e36..b5b02318a 100644 --- a/apps/worker/src/jobs/report-reliability.ts +++ b/apps/worker/src/jobs/report-reliability.ts @@ -1,16 +1,15 @@ import type { Prisma } from "@lovat/db"; - +import { recordRevision } from "../outbox"; export async function flagReportsAboveAllianceScore( tx: Prisma.TransactionClient, eventKey: string, ) { - const flagged = await tx.$executeRaw` + const flagged = await tx.$queryRaw<{ teamNumber: number }[]>` UPDATE "ScoutReport" report SET "reliability" = 'FLAGGED_SYSTEM' FROM "TeamMatchData" slot JOIN "Match" match ON match."key" = slot."matchKey" - JOIN "MatchAlliance" alliance - ON alliance."matchKey" = slot."matchKey" AND alliance."color" = slot."alliance" + JOIN "MatchAlliance" alliance ON alliance."matchKey" = slot."matchKey" AND alliance."color" = slot."alliance" WHERE report."teamMatchKey" = slot."key" AND slot."tournamentKey" = ${eventKey} AND match."status" = 'COMPLETED' @@ -19,12 +18,14 @@ export async function flagReportsAboveAllianceScore( AND report."reliability" = 'UNVERIFIED' AND ( SELECT COALESCE(SUM(COALESCE(event."quantity", event."points")), 0) - FROM "Event" event - WHERE event."scoutReportUuid" = report."uuid" - AND event."action" = 'STOP_SCORING' + FROM "Event" event WHERE event."scoutReportUuid" = report."uuid" AND event."action" = 'STOP_SCORING' ) > alliance."score" + RETURNING slot."teamNumber" `; - - // Server cache reads check these registrations, so workers need no Redis access. - if (flagged > 0) await tx.cachedAnalysis.deleteMany(); + if (flagged.length) { + // Keep the old server coherent while replacement traffic is introduced. + await tx.cachedAnalysis.deleteMany(); + for (const number of new Set(flagged.map((row) => row.teamNumber))) + await recordRevision(tx, number); + } } diff --git a/apps/worker/src/jobs/tournaments.ts b/apps/worker/src/jobs/tournaments.ts index 2e3b74874..ccac8326c 100644 --- a/apps/worker/src/jobs/tournaments.ts +++ b/apps/worker/src/jobs/tournaments.ts @@ -1,3 +1,4 @@ +import { recordRevision } from "../outbox"; import type { PrismaClient } from "@lovat/db"; import type { createTbaClient } from "../providers/tba"; @@ -107,6 +108,7 @@ export const importTournaments = async ( }); } + await recordRevision(tx, 0); // All tournament parents must exist before linking divisions. for (const tournament of fetched.data) { await tx.tournament.update({ diff --git a/apps/worker/src/outbox.ts b/apps/worker/src/outbox.ts new file mode 100644 index 000000000..1bd28027c --- /dev/null +++ b/apps/worker/src/outbox.ts @@ -0,0 +1,422 @@ +import { randomUUID } from "node:crypto"; +import { RedisClient } from "bun"; +import type { ApiOutbox, PrismaClient } from "@lovat/db"; +import { effectSchema, type Effect } from "@lovat/api/effects"; + +const publishRevisionScript = + "local old=redis.call('GET',KEYS[1]); local v=ARGV[1]; if not old or #v>#old or (#v==#old and v>old) then redis.call('SET',KEYS[1],v) end; return 1"; +export interface OutboxDelivery { + deliver(effect: Effect, id: string): Promise; +} +export function createOutboxDelivery( + db: PrismaClient, + options: { + redisUrl: string; + prefix: string; + resendKey?: string; + emailFrom?: string; + slackWebhook?: string; + fetcher?: typeof fetch; + }, +): OutboxDelivery & { close(): void } { + if (!options.prefix || /[*?\[\]\\]/.test(options.prefix)) + throw new Error("Invalid Redis prefix"); + const redis = new RedisClient(options.redisUrl, { + connectionTimeout: 2000, + enableOfflineQueue: false, + maxRetries: 1, + }); + let connecting: Promise | undefined; + const connect = async () => { + if (!redis.connected) { + connecting ??= redis.connect().finally(() => { + connecting = undefined; + }); + await connecting; + } + }; + const fetcher = options.fetcher ?? fetch; + const slack = async (token: string, body: Record) => { + const response = await fetcher("https://slack.com/api/chat.postMessage", { + method: "POST", + headers: { + Authorization: "Bearer " + token, + "Content-Type": "application/json", + }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(10000), + }); + const data: unknown = await response.json(); + if ( + !response.ok || + !data || + typeof data !== "object" || + !("ok" in data) || + data.ok !== true + ) + throw new Error("Slack delivery failed"); + return data as { ok: true; ts?: string }; + }; + const escape = (text: string) => + text + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">"); + return { + close: () => redis.close(), + async deliver(effect, id) { + if (effect.kind === "cache.revision") { + await connect(); + await redis.send("EVAL", [ + publishRevisionScript, + "1", + options.prefix + "revision:" + effect.teamNumber, + effect.revision, + ]); + } else if (effect.kind === "email.send") { + if (!options.resendKey || !options.emailFrom) + throw new Error("Email delivery is not configured"); + const response = await fetcher("https://api.resend.com/emails", { + method: "POST", + headers: { + Authorization: "Bearer " + options.resendKey, + "Content-Type": "application/json", + "Idempotency-Key": id, + }, + body: JSON.stringify({ + from: options.emailFrom, + to: [effect.to], + subject: effect.subject, + text: effect.text, + }), + signal: AbortSignal.timeout(10000), + }); + if (!response.ok) throw new Error("Email delivery failed"); + } else if (effect.kind === "slack.registration") { + if (!options.slackWebhook) + throw new Error("Registration notification is not configured"); + const row = await db.registeredTeam.findUnique({ + where: { number: effect.teamNumber }, + }); + if (!row || row.teamApproved) return; + const response = await fetcher(options.slackWebhook, { + method: "POST", + headers: { "Content-Type": "application/json" }, + signal: AbortSignal.timeout(10000), + body: JSON.stringify({ + blocks: [ + { + type: "section", + text: { + type: "mrkdwn", + text: "Received a new team wanting to register", + }, + }, + { + type: "section", + text: { + type: "mrkdwn", + text: + "*Number*\n" + + row.number + + "\n*Website*\n" + + escape(row.website ?? "None") + + "\n*Team Email*\n" + + escape(row.email), + }, + }, + { + type: "actions", + elements: [ + { + type: "button", + text: { type: "plain_text", text: "Approve" }, + value: "approve_" + row.number, + action_id: "verify_action", + }, + { + type: "button", + text: { type: "plain_text", text: "Reject" }, + value: "reject_" + row.number, + action_id: "reject_action", + }, + ], + }, + ], + }), + }); + if (!response.ok) throw new Error("Registration notification failed"); + } else if (effect.kind === "slack.message") { + const workspace = await db.slackWorkspace.findUnique({ + where: { workspaceId: effect.workspaceId }, + select: { authToken: true }, + }); + if (!workspace) return; + await slack(workspace.authToken, { + channel: effect.channelId, + text: effect.text, + client_msg_id: id, + }); + } else { + const report = await db.scoutReport.findFirst({ + where: { + uuid: effect.reportUuid, + training: false, + scouter: { sourceTeamNumber: effect.sourceTeamNumber }, + }, + include: { scouter: true, teamMatchData: true }, + }); + if (!report?.robotBrokeDescription?.trim()) return; + const slot = report.teamMatchData; + const upcoming = await db.teamMatchData.findMany({ + where: { + tournamentKey: slot.tournamentKey, + teamNumber: slot.teamNumber, + matchType: "QUALIFICATION", + matchNumber: { gt: slot.matchNumber }, + }, + select: { matchNumber: true, alliance: true, key: true }, + take: 1000, + }); + if (!upcoming.length) return; + const partners = await db.teamMatchData.findMany({ + where: { + tournamentKey: slot.tournamentKey, + matchType: "QUALIFICATION", + teamNumber: { not: slot.teamNumber }, + matchNumber: { in: upcoming.map((row) => row.matchNumber) }, + }, + select: { + teamNumber: true, + matchNumber: true, + alliance: true, + key: true, + }, + take: 6000, + }); + const byMatch = new Map( + upcoming.map((row) => [ + row.matchNumber, + row.alliance ?? (Number(row.key.at(-1)) < 3 ? "RED" : "BLUE"), + ]), + ); + const partnerTeams = [ + ...new Set( + partners + .filter( + (row) => + (row.alliance ?? + (Number(row.key.at(-1)) < 3 ? "RED" : "BLUE")) === + byMatch.get(row.matchNumber), + ) + .map((row) => row.teamNumber), + ), + ]; + const channels = await db.slackSubscription.findMany({ + where: { + ...(effect.kind === "slack.warning.channel" + ? { subscriptionId: effect.subscriptionId } + : {}), + subscribedEvent: "BREAK", + workspace: { owner: { in: partnerTeams } }, + }, + include: { workspace: true }, + take: 1000, + }); + if (effect.kind === "slack.warning") { + await db.apiOutbox.createMany({ + skipDuplicates: true, + data: channels.map((channel) => { + const payload = effectSchema.parse({ + ...effect, + kind: "slack.warning.channel", + subscriptionId: channel.subscriptionId, + }); + return { + id: randomUUID(), + dedupeKey: + "break-channel:" + + effect.reportUuid + + ":" + + channel.subscriptionId, + kind: payload.kind, + payload, + }; + }), + }); + return; + } + for (const channel of channels) { + const author = + report.scouter.sourceTeamNumber === channel.workspace.owner + ? report.scouter.name?.trim() || + "A scouter from team " + report.scouter.sourceTeamNumber + : "A scouter from team " + report.scouter.sourceTeamNumber; + const thread = await db.slackNotificationThread.findFirst({ + where: { + teamNumber: slot.teamNumber, + channelId: channel.channelId, + tournamentKey: slot.tournamentKey, + }, + }); + const message = await slack(channel.workspace.authToken, { + channel: channel.channelId, + client_msg_id: id, + ...(thread ? { thread_ts: thread.messageId } : {}), + text: + escape(author) + + " reported team " + + slot.teamNumber + + " broke in Q" + + slot.matchNumber + + ".\n" + + escape(report.robotBrokeDescription), + }); + if (!thread && message.ts) + await db.slackNotificationThread.create({ + data: { + messageId: message.ts, + channelId: channel.channelId, + subscriptionId: channel.subscriptionId, + matchNumber: slot.matchNumber, + teamNumber: slot.teamNumber, + tournamentKey: slot.tournamentKey, + }, + }); + } + } + }, + }; +} +export async function runNextEffect( + db: PrismaClient, + delivery: OutboxDelivery, + now = new Date(), +): Promise { + const lease = randomUUID(); + const until = new Date(now.getTime() + 60000); + const rows = await db.$queryRaw` + UPDATE "ApiOutbox" SET "leaseToken" = ${lease}, "leaseUntil" = ${until}, "attempts" = "attempts" + 1 + WHERE "id" = ( + SELECT "id" FROM "ApiOutbox" WHERE "completedAt" IS NULL AND "attempts" < 10 AND "availableAt" <= ${now} + AND ("leaseUntil" IS NULL OR "leaseUntil" <= ${now}) + ORDER BY CASE WHEN "kind" = 'cache.revision' THEN 0 ELSE 1 END, "availableAt", "createdAt" + FOR UPDATE SKIP LOCKED LIMIT 1 + ) RETURNING *`; + const row = rows[0]; + if (!row) return false; + try { + const effect = effectSchema.parse(row.payload); + if (effect.kind !== row.kind) throw new Error("Effect kind mismatch"); + await delivery.deliver(effect, row.id); + await db.apiOutbox.updateMany({ + where: { id: row.id, leaseToken: lease }, + data: { + completedAt: new Date(), + leaseToken: null, + leaseUntil: null, + lastError: null, + }, + }); + } catch { + await db.apiOutbox.updateMany({ + where: { id: row.id, leaseToken: lease }, + data: { + leaseToken: null, + leaseUntil: null, + lastError: "DELIVERY_FAILED", + availableAt: new Date( + Date.now() + Math.min(600000, 1000 * 2 ** row.attempts), + ), + }, + }); + } + return true; +} +export async function maintainApiData(db: PrismaClient, now = new Date()) { + await db.scoutReportInProgress.updateMany({ + where: { + status: { in: ["LOADED", "STARTED", "ENDED"] }, + expiresAt: { lte: now }, + }, + data: { status: "ABANDONED" }, + }); + await db.scoutReportInProgress.updateMany({ + where: { + status: "ABANDONED", + expiresAt: { lte: new Date(now.getTime() - 23 * 86400000) }, + NOT: { payload: { equals: {} } }, + }, + data: { payload: {} }, + }); + const emails = await db.emailVerificationRequest.findMany({ + where: { expiresAt: { lte: now } }, + select: { verificationCode: true }, + take: 1000, + }); + if (emails.length) + await db.emailVerificationRequest.deleteMany({ + where: { + verificationCode: { in: emails.map((row) => row.verificationCode) }, + }, + }); + const delivered = await db.apiOutbox.findMany({ + where: { completedAt: { lt: new Date(now.getTime() - 30 * 86400000) } }, + select: { id: true }, + take: 1000, + }); + if (delivered.length) + await db.apiOutbox.deleteMany({ + where: { id: { in: delivered.map((row) => row.id) } }, + }); +} +export async function runOutbox( + db: PrismaClient, + delivery: OutboxDelivery, + signal: AbortSignal, +) { + let maintained = 0; + while (!signal.aborted) { + try { + if (Date.now() - maintained > 60000) { + await maintainApiData(db); + maintained = Date.now(); + } + if (await runNextEffect(db, delivery)) continue; + } catch { + console.error("API outbox unavailable; retrying"); + } + await new Promise((resolve) => { + const finish = () => { + clearTimeout(timer); + signal.removeEventListener("abort", finish); + resolve(); + }; + const timer = setTimeout(finish, 250); + signal.addEventListener("abort", finish, { once: true }); + if (signal.aborted) finish(); + }); + } +} + +export async function recordRevision( + tx: import("@lovat/db").Prisma.TransactionClient, + teamNumber: number, +) { + const revision = await tx.analysisRevision.upsert({ + where: { teamNumber }, + create: { teamNumber, revision: 1n }, + update: { revision: { increment: 1n } }, + }); + const payload = effectSchema.parse({ + kind: "cache.revision", + teamNumber, + revision: revision.revision.toString(), + }); + const dedupeKey = "analysis:" + teamNumber + ":" + revision.revision; + await tx.apiOutbox.upsert({ + where: { dedupeKey }, + update: {}, + create: { dedupeKey, kind: payload.kind, payload }, + }); +} diff --git a/apps/worker/test/modes.test.ts b/apps/worker/test/modes.test.ts new file mode 100644 index 000000000..eca686a1b --- /dev/null +++ b/apps/worker/test/modes.test.ts @@ -0,0 +1,28 @@ +import { expect, test } from "bun:test"; +import { fileURLToPath } from "node:url"; + +for (const mode of ["batch", "scheduled"]) { + test( + mode + " rejects continuous API effects before connecting to a database", + async () => { + const child = Bun.spawn([process.execPath, "index.ts"], { + cwd: fileURLToPath(new URL("..", import.meta.url)), + env: { + ...process.env, + WORKER_MODE: mode, + API_EFFECTS_ENABLED: "true", + DATABASE_URL: "postgresql://nobody@127.0.0.1:1/lovat_test", + TBA_KEY: "synthetic-mode-test", + }, + stdout: "pipe", + stderr: "pipe", + }); + const error = await new Response(child.stderr).text(); + expect(await child.exited).not.toBe(0); + expect(error).toContain( + "API_EFFECTS_ENABLED requires WORKER_MODE=continuous", + ); + expect(error).not.toContain("Can't reach database"); + }, + ); +} diff --git a/apps/worker/test/outbox.integration.test.ts b/apps/worker/test/outbox.integration.test.ts new file mode 100644 index 000000000..4e07f6759 --- /dev/null +++ b/apps/worker/test/outbox.integration.test.ts @@ -0,0 +1,173 @@ +import { afterAll, beforeAll, expect, test } from "bun:test"; +import type { PrismaClient } from "@lovat/db"; +import { runNextEffect } from "../src/outbox"; +const enabled = process.env.LOVAT_DB_TEST === "1"; +const prefix = "outbox-fixture-" + crypto.randomUUID(); +const now = new Date("2000-01-01T00:00:00Z"); +let db: PrismaClient; +beforeAll(async () => { + if (!enabled) return; + const url = new URL( + process.env.DATABASE_URL ?? "postgresql://localhost/missing", + ); + if ( + !["localhost", "127.0.0.1"].includes(url.hostname) || + url.pathname !== "/lovat_test" + ) + throw new Error("Use a disposable loopback lovat_test database"); + const { createDb } = await import("@lovat/db"); + db = createDb(url.href, { maxConnections: 4 }); +}); +afterAll(async () => { + if (db) { + await db.apiOutbox.deleteMany({ + where: { dedupeKey: { startsWith: prefix } }, + }); + await db.$disconnect(); + } +}); +const add = (suffix: string, extras = {}) => + db.apiOutbox.create({ + data: { + dedupeKey: prefix + suffix, + kind: "cache.revision", + payload: { kind: "cache.revision", teamNumber: 1, revision: "1" }, + availableAt: now, + ...extras, + }, + }); +test.skipIf(!enabled)( + "outbox claims once across concurrent workers", + async () => { + const row = await add("-claim"); + let deliveries = 0; + const delivery = { + deliver: async () => { + deliveries++; + await Bun.sleep(10); + }, + }; + await Promise.all([ + runNextEffect(db, delivery, now), + runNextEffect(db, delivery, now), + ]); + expect(deliveries).toBe(1); + const saved = await db.apiOutbox.findUniqueOrThrow({ + where: { id: row.id }, + }); + expect(saved.attempts).toBe(1); + expect(saved.completedAt).not.toBeNull(); + expect(saved.leaseToken).toBeNull(); + }, +); +test.skipIf(!enabled)( + "delivery failures retry without completing or exposing provider secrets", + async () => { + const row = await add("-failure"); + await runNextEffect( + db, + { + deliver: async () => { + throw Error("secret-provider-response"); + }, + }, + now, + ); + const saved = await db.apiOutbox.findUniqueOrThrow({ + where: { id: row.id }, + }); + expect(saved.completedAt).toBeNull(); + expect(saved.leaseToken).toBeNull(); + expect(saved.lastError).toBe("DELIVERY_FAILED"); + expect(saved.availableAt.getTime()).toBeGreaterThan(Date.now()); + }, +); +test.skipIf(!enabled)( + "expired leases are reclaimed while active leases remain untouched", + async () => { + const row = await add("-lease", { + leaseToken: "crashed", + leaseUntil: new Date(now.getTime() + 1000), + }); + let deliveries = 0; + expect( + await runNextEffect( + db, + { + deliver: async () => { + deliveries++; + }, + }, + now, + ), + ).toBe(false); + expect( + await runNextEffect( + db, + { + deliver: async () => { + deliveries++; + }, + }, + new Date(now.getTime() + 2000), + ), + ).toBe(true); + expect(deliveries).toBe(1); + expect( + (await db.apiOutbox.findUniqueOrThrow({ where: { id: row.id } })) + .completedAt, + ).not.toBeNull(); + }, +); +test.skipIf(!enabled)( + "malformed effects never reach external delivery", + async () => { + const row = await add("-invalid", { + payload: { kind: "cache.revision", teamNumber: 1, revision: "NaN" }, + }); + let deliveries = 0; + await runNextEffect( + db, + { + deliver: async () => { + deliveries++; + }, + }, + now, + ); + expect(deliveries).toBe(0); + expect( + (await db.apiOutbox.findUniqueOrThrow({ where: { id: row.id } })) + .lastError, + ).toBe("DELIVERY_FAILED"); + }, +); + +test.skipIf(!enabled || process.env.LOVAT_REDIS_TEST !== "1")( + "published Redis revisions remain monotonic beyond JavaScript integer precision", + async () => { + const url = new URL(process.env.REDIS_URL ?? "redis://127.0.0.1:6379"); + if (!["localhost", "127.0.0.1"].includes(url.hostname)) + throw Error("Use loopback Redis"); + const { createOutboxDelivery } = await import("../src/outbox"); + const { RedisClient } = await import("bun"); + const prefix = "lovat:outbox-test:" + crypto.randomUUID() + ":", + redis = new RedisClient(url.href); + const delivery = createOutboxDelivery(db, { redisUrl: url.href, prefix }); + try { + await delivery.deliver( + { kind: "cache.revision", teamNumber: 1, revision: "9007199254740993" }, + crypto.randomUUID(), + ); + await delivery.deliver( + { kind: "cache.revision", teamNumber: 1, revision: "9007199254740992" }, + crypto.randomUUID(), + ); + expect(await redis.get(prefix + "revision:1")).toBe("9007199254740993"); + } finally { + await redis.del(prefix + "revision:1"); + redis.close(); + delivery.close(); + } + }, +); diff --git a/apps/worker/test/provider-delivery.test.ts b/apps/worker/test/provider-delivery.test.ts new file mode 100644 index 000000000..039c5f729 --- /dev/null +++ b/apps/worker/test/provider-delivery.test.ts @@ -0,0 +1,98 @@ +import { expect, test } from "bun:test"; +import type { PrismaClient } from "@lovat/db"; +import { createOutboxDelivery } from "../src/outbox"; + +test("email transport preserves idempotency across retries and sanitizes provider errors", async () => { + const calls: { key: string | null; body: unknown }[] = []; + const delivery = createOutboxDelivery({} as PrismaClient, { + redisUrl: "redis://127.0.0.1:6379", + prefix: "lovat:provider-fixture:", + resendKey: "synthetic-key", + emailFrom: "fixture@example.invalid", + fetcher: (async (url, init) => { + expect(String(url)).toBe("https://api.resend.com/emails"); + expect(new Headers(init?.headers).get("authorization")).toBe( + "Bearer synthetic-key", + ); + calls.push({ + key: new Headers(init?.headers).get("idempotency-key"), + body: JSON.parse(String(init?.body)), + }); + return calls.length === 1 + ? new Response("private-provider-detail", { status: 503 }) + : Response.json({ id: "fixture" }); + }) as typeof fetch, + }); + const effect = { + kind: "email.send" as const, + to: "recipient@example.invalid", + subject: "Synthetic", + text: "Synthetic content", + }; + try { + await expect(delivery.deliver(effect, "stable-fixture-id")).rejects.toThrow( + "Email delivery failed", + ); + await delivery.deliver(effect, "stable-fixture-id"); + expect(calls.map((call) => call.key)).toEqual([ + "stable-fixture-id", + "stable-fixture-id", + ]); + expect(calls[1]?.body).toEqual({ + from: "fixture@example.invalid", + to: ["recipient@example.invalid"], + subject: "Synthetic", + text: "Synthetic content", + }); + } finally { + delivery.close(); + } +}); +test("Slack delivery validates success and rechecks workspace access on retry", async () => { + let calls = 0, + removed = false; + const db = { + slackWorkspace: { + findUnique: async () => + removed ? null : { authToken: "synthetic-token" }, + }, + } as unknown as PrismaClient; + const delivery = createOutboxDelivery(db, { + redisUrl: "redis://127.0.0.1:6379", + prefix: "lovat:provider-fixture:", + fetcher: (async (url, init) => { + expect(String(url)).toBe("https://slack.com/api/chat.postMessage"); + expect(new Headers(init?.headers).get("authorization")).toBe( + "Bearer synthetic-token", + ); + expect(JSON.parse(String(init?.body))).toEqual({ + channel: "fixture-channel", + text: "Synthetic", + client_msg_id: "stable-slack-id", + }); + calls++; + return Response.json( + calls === 1 + ? { ok: false, error: "private-provider-detail" } + : { ok: true, ts: "1.0" }, + ); + }) as typeof fetch, + }); + const effect = { + kind: "slack.message" as const, + workspaceId: "fixture-workspace", + channelId: "fixture-channel", + text: "Synthetic", + }; + try { + await expect(delivery.deliver(effect, "stable-slack-id")).rejects.toThrow( + "Slack delivery failed", + ); + await delivery.deliver(effect, "stable-slack-id"); + removed = true; + await delivery.deliver(effect, "stable-slack-id"); + expect(calls).toBe(2); + } finally { + delivery.close(); + } +}); diff --git a/docs/server-rewrite-qualification.md b/docs/server-rewrite-qualification.md new file mode 100644 index 000000000..3e7982b58 --- /dev/null +++ b/docs/server-rewrite-qualification.md @@ -0,0 +1,60 @@ +# Server rewrite qualification + +The replacement is independent of legacy Server handlers. All 137 legacy HTTP routes map to replacement modules and policies in `apps/api/legacy-routes.json`; native v3 endpoints and training WebSockets are additional surfaces. Registration checks prevent missing handlers but do not prove behavioral parity. + +## Current evidence + +Local PostgreSQL 18 and a Redis-compatible Memurai service were used only with synthetic fixtures and run-specific key namespaces. The new database suite covers report load/start/end/submit, repeated and conflicting submissions, atomic invalidation, cross-team denial, picklists, API keys, analysis, CSV/path views, signed email verification, joining, training pairing/readiness/control/submission/grading, and browser/attempt socket authentication. The worker suite covers durable claims, retry fencing and recovery. Shared schemas have no database/runtime side effects. + +The former Node deployment image limited V8 old-space to 256 MiB; the current Bun policy is documented below. Cold calculations, exports and path calculations share bounded work admission; HTTP and SQL concurrency are separately bounded. A maximum dataset is accepted explicitly; larger datasets fail with 413. + +## Bun/Hono runtime qualification + +The replacement now runs Hono on native Bun HTTP and WebSockets, pinned to Bun 1.4.4. HTTP integration tests use the same `startApi` path as production. Local packages use Bun path links, while each shared package retains its npm lockfile. A clean frozen Bun install was verified on Windows; the failed Bun 1.4.0 file-dependency install was resolved by the patch and linked-package design. + +Bun `--smol` replaces the former V8 old-space option. It encourages more frequent collection; it is not a hard heap/RSS cap. The old Node figures below are historical evidence from an earlier engine/runtime and must not be presented as the current memory profile or a controlled speed comparison. + +Bun 1.4.4 with `--smol`, local PostgreSQL 18 and Redis-compatible Memurai, all 31 metrics, synthetic identity, client/server/fixture setup in one process: + +| Reports / events | Sequential requests | Cold p95 | Warm Redis p95 | +| ---------------- | ------------------: | --------: | -------------: | +| 1,000 / 20,000 | 20 | 128.04 ms | 1.64 ms | +| 5,000 / 100,000 | 5 | 624.33 ms | 1.74 ms | + +At concurrency four, cold/warm p95 were 389.22/3.17 ms at 1,000 reports and 1,486.29/4.43 ms at 5,000. The maximum-size process peaked around 1.07 GiB RSS and ended around 484 MiB after the warm-cache run. Fixture creation and the client are included; an isolated server measurement is still needed. These results do **not** qualify the low-memory target. Streaming database reads or smaller admission limits, isolated RSS measurements, and a sustained soak test remain release work. Do not infer a production footprint from the cached latency. + +Reproduce with the documented disposable-service guards and `bun --smol apps/api/tools/benchmark-http.mjs`; set `BENCHMARK_REPORTS=1000 BENCHMARK_ITERATIONS=20` or `5000/5`. + +## Annual game qualification + +The pure `@lovat/games` package now owns report codecs, timing/scoring rules, metric calculations/output schemas/aggregation and prediction. Public game descriptors include JSON Schemas. Generic reports persist the game/report versions and JSON data; 2026 version 1 uses explicit compatibility adapters. A new game version cannot accidentally select that adapter. Legacy analysis remains pinned to its version 1 contract. + +A fictional 2099 game passes real Bun/Hono/PostgreSQL tests for different fields, timing, scoring, two-team alliances, structured metrics, prediction, old report upgrades, concurrent retries, conflicts, tenant denial and system plausibility flags. It is test-only. Clients and legacy training/schedule adapters are not automatically migrated; see [game development and remaining surfaces](../packages/games/README.md). + +## Historical Node latency measurements + +Node 22.20.0, local warm PostgreSQL, local Redis, all 31 metrics, synthetic authenticated scope. Client and API share a process. Identity database reads, JWKS verification/fetch, production networking and deployment overhead are excluded. + +| Reports / events | Requests, concurrency 1 | Uncached p95 | Warm Redis p95 | +| ---------------- | ----------------------: | -----------: | -------------: | +| 100 / 2,000 | 20 | 18.99 ms | 2.52 ms | +| 1,000 / 20,000 | 20 | 115.52 ms | 2.03 ms | +| 5,000 / 100,000 | 5 | 713.27 ms | 7.22 ms | + +At four concurrent requests, p95 was 369.92 ms uncached and 5.29 ms cached for 1,000 reports. At the maximum dataset it was 2,371.19 ms uncached and 11.51 ms cached; the small maximum-workload sample is diagnostic, not a release percentile estimate. Peak process RSS over the maximum run was about 407 MiB, including fixture setup and client work. The heap limit is not a total-memory limit. + +The first unconstrained 1,000-report run reached about 479 MiB peak RSS; the subsequent queue/heap-budget run reached about 302 MiB. Both configuration changes were applied together, so this does not isolate their individual effects. It also does not compare against the legacy server. + +Reproduce with `LOVAT_DB_TEST=1`, a loopback PostgreSQL URL ending in `/lovat_test`, a loopback `REDIS_URL`, and `node apps/api/tools/benchmark-http.mjs` after building. Set `BENCHMARK_REPORTS=5000 BENCHMARK_ITERATIONS=5` for the maximum-size diagnostic. Fixture records and cache keys are cleaned up by the tool. + +## Compatibility and release review + +- Shared API definitions are extracted and consumed by Server, the replacement and worker. The package includes TypeScript contracts/client and OpenAPI artifacts. Flutter bindings remain unchanged; generated Dart migration is tracked in LVT-377. +- v1 analysis adapters use the unified 2026 metric engine. Rate pooling, missing values, weighting and CSV headers can differ from legacy endpoint-specific calculations. Review fixtures and consumer output before rollout. +- Pit display now requires caller authentication and uses caller source scope. Scout renames and management writes enforce team/lead ownership. Public team-code recovery masks the returned contact address and queues at most one delivery per team per two-minute bucket. +- Catalog defaults are paginated. Large analysis/export selections return explicit limits. Review consumers that previously relied on unlimited responses. +- Official schedule, result and roster imports belong to the worker; requests do not run imports. Official ranking/webcast reads use a bounded, timed cache. Exercise provider failures and stale schedules in staging. +- Redis publication is monotonic and cache TTL bounds delayed invalidation. Delivery is at least once; email idempotency keys and Slack message IDs reduce duplicates but cannot guarantee exactly-once remote delivery after a timeout. +- The existing Server remains the deployment target. Apply additive migrations through the release owner, configure matching Redis prefixes and delivery credentials, qualify the replacement worker flag, then rehearse rollback before routing traffic. +- Public abuse budgets use the socket peer address. Validate reverse-proxy addressing and actual scout traffic before production rollout. +- An equivalent old/new workload, sustained soak test, container image build and real Auth0/Slack/Resend staging checks are still required for release. The local results above must not be presented as production guarantees. diff --git a/packages/README.md b/packages/README.md index 37963829b..1fec24d66 100644 --- a/packages/README.md +++ b/packages/README.md @@ -1,5 +1,7 @@ # Shared packages +- [`@lovat/api`](api): shared runtime API schemas, inferred TypeScript contracts, client helper and generated OpenAPI for the current and replacement APIs. +- [`@lovat/games`](games): pure, versioned rules, report codecs, metric definitions, aggregation and prediction. - [`@lovat/db`](db): canonical Prisma schema, migration history, generated types, and PostgreSQL client. Server consumes it today; the separate Support backend will consume it when implemented. -Each package owns its lockfile. Applications consume the built package through a local `file:` dependency, without cross-app source imports or a root workspace. +Each package owns its lockfile. Applications consume the built package through a local `file:` dependency (or Bun `link:` in the replacement API), without cross-app source imports or a root workspace. diff --git a/packages/api/.prettierignore b/packages/api/.prettierignore new file mode 100644 index 000000000..b77d2e6ad --- /dev/null +++ b/packages/api/.prettierignore @@ -0,0 +1,4 @@ +dist/ +node_modules/ +openapi.json +openapi.legacy.json diff --git a/packages/api/README.md b/packages/api/README.md new file mode 100644 index 000000000..35c669f1f --- /dev/null +++ b/packages/api/README.md @@ -0,0 +1,24 @@ +# @lovat/api + +Shared API definitions for Lovat. This package has its own npm lockfile and is consumed through local file dependencies. It does not import Prisma, read environment variables, start a server, or connect to external services. + +## Consumers + +- The existing Server consumes the extracted Collection report validator and legacy OpenAPI definitions. +- The replacement application in apps/api consumes the v3 contracts and typed client. +- Other TypeScript services can add a file dependency on this package and use createApiClient or inferred request/response types. +- Dashboard client generation and consumer migration are tracked by LVT-377. Existing Flutter bindings remain in use. + +The root export contains report/event schemas, Collection lifecycle and training schemas, error schemas, metric metadata/results, v3 routes and createApiClient. The optional @lovat/api/effects export defines the durable API-to-worker protocol. The optional @lovat/api/legacy export contains the existing model-shaped wire schemas and createLegacyOpenApiDocument. Those legacy schemas describe the existing API; they are not a database model API. Some existing endpoints still have broad or incomplete documentation. + +## Commands + +Run npm ci, npm test, npm run lint, npm run format:check and npm run generate:check. Run npm run generate after changing contracts. Generated OpenAPI artifacts are checked in; compiled dist and dependencies are not. + +OpenAPI 3.1 describes the replacement routes in openapi.json and the extracted documented legacy routes in openapi.legacy.json. Refinements such as required quantities on scoring-stop event tuples are enforced by runtime validation; not every cross-field refinement can be represented by JSON Schema. + +## Compatibility + +Event action/position indexes are a wire contract: never reorder them. Report extraction preserves existing validation, including permissive rating ranges. Tightening validation requires a coordinated producer/consumer change. + +Version incompatible public payload changes. Shared contracts must not expose database clients, secrets or private internal models. New routes must declare input, output and authentication requirements. Keep formulas in the replacement server's metric registry; this package owns the public shapes. diff --git a/packages/api/openapi.json b/packages/api/openapi.json new file mode 100644 index 000000000..8526199a3 --- /dev/null +++ b/packages/api/openapi.json @@ -0,0 +1,3032 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Lovat API", + "version": "0.1.0" + }, + "paths": { + "/v3/prediction": { + "post": { + "operationId": "predictGame", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "season": { + "type": "integer", + "minimum": 1992, + "maximum": 2200 + }, + "gameVersion": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "red": { + "minItems": 1, + "maxItems": 6, + "type": "array", + "items": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "blue": { + "minItems": 1, + "maxItems": 6, + "type": "array", + "items": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + } + }, + "required": [ + "season", + "red", + "blue" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "redWinning": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "blueWinning": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "winningAlliance": { + "type": "string", + "enum": [ + "red", + "blue", + "tie" + ] + }, + "redScore": { + "type": "number" + }, + "blueScore": { + "type": "number" + }, + "redRankingPoints": { + "type": "number", + "minimum": 0 + }, + "blueRankingPoints": { + "type": "number", + "minimum": 0 + } + }, + "required": [ + "redWinning", + "blueWinning", + "winningAlliance", + "redScore", + "blueScore" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "401": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "403": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "409": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "413": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "422": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "429": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "500": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "503": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + } + } + } + }, + "/v3/games": { + "get": { + "operationId": "games", + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9-]{0,99}$" + }, + "season": { + "type": "integer", + "minimum": 1992, + "maximum": 2200 + }, + "version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "label": { + "type": "string", + "minLength": 1 + }, + "reportVersion": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "reportSchemas": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/gamesResponse___schema0" + } + } + }, + "rules": { + "type": "object", + "properties": { + "allianceSize": { + "type": "integer", + "minimum": 1, + "maximum": 6 + }, + "periods": { + "minItems": 1, + "maxItems": 10, + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1 + }, + "label": { + "type": "string" + }, + "durationSeconds": { + "type": "number", + "exclusiveMinimum": 0 + } + }, + "required": [ + "id", + "label", + "durationSeconds" + ], + "additionalProperties": false + } + }, + "scoring": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/gamesResponse___schema1" + } + } + }, + "required": [ + "allianceSize", + "periods", + "scoring" + ], + "additionalProperties": false + }, + "metrics": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1 + }, + "aliases": { + "type": "array", + "items": { + "type": "string" + } + }, + "season": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "label": { + "type": "string" + }, + "unit": { + "type": "string" + }, + "kind": { + "type": "string", + "enum": [ + "number", + "distribution", + "structured" + ] + }, + "precision": { + "type": "integer", + "minimum": 0, + "maximum": 8 + }, + "missing": { + "type": "string", + "const": "exclude" + }, + "dependencies": { + "type": "array", + "items": { + "type": "string" + } + }, + "outputSchema": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/gamesResponse___schema2" + } + }, + "requires": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "id", + "aliases", + "season", + "version", + "label", + "unit", + "kind", + "precision", + "missing", + "dependencies", + "requires" + ], + "additionalProperties": false + } + }, + "features": { + "type": "object", + "properties": { + "predictions": { + "type": "boolean" + } + }, + "required": [ + "predictions" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "season", + "version", + "label", + "reportVersion", + "reportSchemas", + "rules", + "metrics", + "features" + ], + "additionalProperties": false + } + } + } + } + }, + "400": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "401": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "403": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "409": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "413": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "422": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "429": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "500": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "503": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + } + } + } + }, + "/v3/reports": { + "post": { + "operationId": "submitGameReport", + "security": [ + { + "collectionCode": [] + } + ], + "parameters": [ + { + "in": "header", + "name": "X-Scouter-Uuid", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "in": "header", + "name": "X-Device-Id", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "uuid": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "scouterUuid": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "teamNumber": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "tournamentKey": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "matchType": { + "type": "string", + "enum": [ + "QUALIFICATION", + "ELIMINATION", + "PRACTICE" + ] + }, + "matchNumber": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 32767 + }, + "season": { + "type": "integer", + "minimum": 1992, + "maximum": 2200 + }, + "gameId": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "gameVersion": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "reportVersion": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "startTime": { + "type": "integer", + "minimum": 0, + "maximum": 8640000000000000 + }, + "endTime": { + "type": "integer", + "minimum": 0, + "maximum": 8640000000000000 + }, + "data": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/submitGameReportRequest___schema0" + } + } + }, + "required": [ + "uuid", + "scouterUuid", + "teamNumber", + "tournamentKey", + "matchType", + "matchNumber", + "season", + "gameId", + "gameVersion", + "reportVersion", + "startTime", + "endTime", + "data" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "uuid": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "created": { + "type": "boolean" + }, + "gameId": { + "type": "string" + }, + "gameVersion": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "reportVersion": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "uuid", + "created", + "gameId", + "gameVersion", + "reportVersion" + ], + "additionalProperties": false + } + } + } + }, + "201": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "uuid": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "created": { + "type": "boolean" + }, + "gameId": { + "type": "string" + }, + "gameVersion": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "reportVersion": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + }, + "required": [ + "uuid", + "created", + "gameId", + "gameVersion", + "reportVersion" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "401": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "403": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "409": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "413": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "422": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "429": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "500": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "503": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + } + } + } + }, + "/v3/metrics": { + "get": { + "operationId": "metrics", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "in": "query", + "name": "season", + "required": false, + "schema": { + "type": "integer", + "minimum": 1992, + "maximum": 2200 + } + }, + { + "in": "query", + "name": "gameVersion", + "required": false, + "schema": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + } + ], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1 + }, + "aliases": { + "type": "array", + "items": { + "type": "string" + } + }, + "season": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "label": { + "type": "string" + }, + "unit": { + "type": "string" + }, + "kind": { + "type": "string", + "enum": [ + "number", + "distribution", + "structured" + ] + }, + "precision": { + "type": "integer", + "minimum": 0, + "maximum": 8 + }, + "missing": { + "type": "string", + "const": "exclude" + }, + "dependencies": { + "type": "array", + "items": { + "type": "string" + } + }, + "outputSchema": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/metricsResponse___schema0" + } + }, + "requires": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "id", + "aliases", + "season", + "version", + "label", + "unit", + "kind", + "precision", + "missing", + "dependencies", + "requires" + ], + "additionalProperties": false + } + } + } + } + }, + "400": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "401": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "403": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "409": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "413": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "422": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "429": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "500": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "503": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + } + } + } + }, + "/v3/analysis": { + "post": { + "operationId": "analyze", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "teams": { + "minItems": 1, + "maxItems": 100, + "type": "array", + "items": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "metrics": { + "minItems": 1, + "maxItems": 64, + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "maxLength": 100 + } + }, + "season": { + "default": 2026, + "type": "integer", + "minimum": 2000, + "maximum": 2100 + }, + "timeline": { + "default": false, + "type": "boolean" + }, + "gameVersion": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "teams", + "metrics", + "season", + "timeline" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "season": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "teams": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "metrics": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "value": { + "anyOf": [ + { + "$ref": "#/components/schemas/analyzeResponse___schema0" + }, + { + "type": "null" + } + ] + }, + "samples": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "value", + "samples", + "version" + ], + "additionalProperties": false + } + }, + "timeline": { + "type": "array", + "items": { + "type": "object", + "properties": { + "matchKey": { + "type": "string" + }, + "tournamentKey": { + "type": "string" + }, + "metrics": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "properties": { + "value": { + "anyOf": [ + { + "$ref": "#/components/schemas/analyzeResponse___schema0" + }, + { + "type": "null" + } + ] + }, + "samples": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "version": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "value", + "samples", + "version" + ], + "additionalProperties": false + } + } + }, + "required": [ + "matchKey", + "tournamentKey", + "metrics" + ], + "additionalProperties": false + } + } + }, + "required": [ + "metrics" + ], + "additionalProperties": false + } + } + }, + "required": [ + "season", + "teams" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "401": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "403": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "409": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "413": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "422": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "429": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "500": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + }, + "503": { + "description": "Request failed", + "content": { + "application/json": { + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "ApiError": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ], + "additionalProperties": false + }, + "ReportSubmission": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "uuid": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "scouterUuid": { + "type": "string", + "format": "uuid", + "pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$" + }, + "tournamentKey": { + "type": "string", + "minLength": 1 + }, + "matchType": { + "type": "string", + "enum": [ + "QUALIFICATION", + "ELIMINATION", + "PRACTICE" + ] + }, + "matchNumber": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "teamNumber": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "startTime": { + "type": "integer", + "minimum": 0, + "maximum": 8640000000000000 + }, + "notes": { + "type": "string" + }, + "robotRoles": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "CYCLING", + "SCORING", + "FEEDING", + "DEFENDING", + "IMMOBILE" + ] + } + }, + "mobility": { + "type": "string", + "enum": [ + "TRENCH", + "BUMP", + "BOTH", + "NONE" + ] + }, + "climbPosition": { + "type": "string", + "enum": [ + "SIDE", + "MIDDLE" + ] + }, + "climbSide": { + "type": "string", + "enum": [ + "FRONT", + "BACK" + ] + }, + "beached": { + "type": "string", + "enum": [ + "ON_FUEL", + "ON_BUMP", + "BOTH", + "NEITHER" + ] + }, + "feederTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "CONTINUOUS", + "STOP_TO_SHOOT", + "DUMP" + ] + } + }, + "intakeType": { + "type": "string", + "enum": [ + "GROUND", + "OUTPOST", + "BOTH", + "NEITHER" + ] + }, + "robotBrokeDescription": { + "type": [ + "string", + "null" + ] + }, + "driverAbility": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "accuracy": { + "anyOf": [ + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ] + }, + "disrupts": { + "type": "boolean" + }, + "defenseEffectiveness": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + "scoresWhileMoving": { + "type": "boolean" + }, + "autoClimb": { + "type": "string", + "enum": [ + "NOT_ATTEMPTED", + "FAILED", + "SUCCEEDED" + ] + }, + "endgameClimb": { + "type": "string", + "enum": [ + "NOT_ATTEMPTED", + "FAILED", + "L1", + "L2", + "L3" + ] + }, + "appVersion": { + "type": "string" + }, + "events": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "array", + "prefixItems": [ + { + "type": "number", + "minimum": 0 + }, + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + } + ], + "items": false, + "minItems": 3, + "maxItems": 3 + }, + { + "type": "array", + "prefixItems": [ + { + "type": "number", + "minimum": 0 + }, + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991 + }, + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + ], + "items": false, + "minItems": 4, + "maxItems": 4 + } + ] + } + } + }, + "required": [ + "uuid", + "scouterUuid", + "tournamentKey", + "matchType", + "matchNumber", + "teamNumber", + "startTime", + "notes", + "robotRoles", + "mobility", + "beached", + "feederTypes", + "intakeType", + "driverAbility", + "disrupts", + "defenseEffectiveness", + "scoresWhileMoving", + "autoClimb", + "endgameClimb", + "events" + ], + "additionalProperties": false + }, + "gamesResponse___schema0": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/gamesResponse___schema0" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/gamesResponse___schema0" + } + } + ] + }, + "gamesResponse___schema1": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/gamesResponse___schema1" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/gamesResponse___schema1" + } + } + ] + }, + "gamesResponse___schema2": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/gamesResponse___schema2" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/gamesResponse___schema2" + } + } + ] + }, + "submitGameReportRequest___schema0": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/submitGameReportRequest___schema0" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/submitGameReportRequest___schema0" + } + } + ] + }, + "metricsResponse___schema0": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/metricsResponse___schema0" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/metricsResponse___schema0" + } + } + ] + }, + "analyzeResponse___schema0": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/components/schemas/analyzeResponse___schema0" + } + }, + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "$ref": "#/components/schemas/analyzeResponse___schema0" + } + } + ] + } + }, + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer" + }, + "collectionCode": { + "type": "apiKey", + "in": "header", + "name": "X-Team-Code" + } + } + } +} diff --git a/packages/api/openapi.legacy.json b/packages/api/openapi.legacy.json new file mode 100644 index 000000000..7dbcbad1e --- /dev/null +++ b/packages/api/openapi.legacy.json @@ -0,0 +1,10351 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Lovat API", + "version": "26.0.0", + "description": "API Documentation for Lovat, a scouting system used to scout teams and matches in the First Robotics Competition. Clients request the shared format using X-Lovat-Error-Format: json-v1. Without that header, direct guard responses retain their legacy formats for installed clients; unexpected failures are still sanitized. Negotiated HTTP error responses (400–599) use application/json and the ApiError schema. message and displayError contain the same safe text. invalidFields and retryAfterSeconds appear only when applicable. Authentication, validation, missing resources, rate limits and unexpected failures share this format. Success responses, including legacy domain messages returned with status 200, retain their documented shapes. Internal exception details and submitted values are not part of the error response." + }, + "servers": [ + { + "url": "https://api.lovat.app" + } + ], + "components": { + "responses": { + "ApiErrorResponse": { + "description": "Request failed. The HTTP status describes the failure category; code identifies the error. Unexpected server failures use INTERNAL_SERVER_ERROR and a generic message.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + }, + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "description": "Accepts either a JWT token from Auth0 or an API key (prefixed with 'lvt-'). Use format: Authorization: Bearer " + }, + "slackToken": { + "type": "apiKey", + "in": "header", + "name": "x-slack-signature", + "description": "Slack signature header (requires accompanying x-slack-request-timestamp)" + }, + "lovatSignature": { + "type": "apiKey", + "in": "header", + "name": "x-signature", + "description": "HMAC signature header (requires accompanying x-timestamp)" + } + }, + "schemas": { + "ApiError": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "displayError": { + "type": "string" + }, + "invalidFields": { + "type": "array", + "items": { + "type": "string" + } + }, + "retryAfterSeconds": { + "type": "number" + } + }, + "required": [ + "code", + "message", + "displayError" + ] + }, + "Position": { + "type": "string", + "enum": [ + "LEFT_TRENCH", + "LEFT_BUMP", + "HUB", + "RIGHT_TRENCH", + "RIGHT_BUMP", + "NEUTRAL_ZONE", + "DEPOT", + "OUTPOST", + "NONE" + ] + }, + "EventAction": { + "type": "string", + "enum": [ + "START_SCORING", + "STOP_SCORING", + "START_MATCH", + "START_CAMPING", + "STOP_CAMPING", + "START_DEFENDING", + "STOP_DEFENDING", + "INTAKE", + "OUTTAKE", + "DISRUPT", + "CROSS", + "CLIMB", + "START_FEEDING", + "STOP_FEEDING" + ] + }, + "FieldTraversal": { + "type": "string", + "enum": [ + "TRENCH", + "BUMP", + "BOTH", + "NONE" + ] + }, + "Beached": { + "type": "string", + "enum": [ + "ON_FUEL", + "ON_BUMP", + "BOTH", + "NEITHER" + ] + }, + "EndgameClimb": { + "type": "string", + "enum": [ + "NOT_ATTEMPTED", + "FAILED", + "L1", + "L2", + "L3" + ] + }, + "ClimbPosition": { + "type": "string", + "enum": [ + "SIDE", + "MIDDLE" + ] + }, + "ClimbSide": { + "type": "string", + "enum": [ + "FRONT", + "BACK" + ] + }, + "AutoClimb": { + "type": "string", + "enum": [ + "NOT_ATTEMPTED", + "FAILED", + "SUCCEEDED" + ] + }, + "FeederType": { + "type": "string", + "enum": [ + "CONTINUOUS", + "STOP_TO_SHOOT", + "DUMP" + ] + }, + "IntakeType": { + "type": "string", + "enum": [ + "GROUND", + "OUTPOST", + "BOTH", + "NEITHER" + ] + }, + "RobotRole": { + "type": "string", + "enum": [ + "CYCLING", + "SCORING", + "FEEDING", + "DEFENDING", + "IMMOBILE" + ] + }, + "WarningType": { + "type": "string", + "enum": [ + "BREAK" + ] + }, + "UserRole": { + "type": "string", + "enum": [ + "ANALYST", + "SCOUTING_LEAD" + ] + }, + "MatchType": { + "type": "string", + "enum": [ + "QUALIFICATION", + "ELIMINATION", + "PRACTICE" + ] + }, + "Event": { + "type": "object", + "properties": { + "eventUuid": { + "type": "string", + "format": "uuid" + }, + "time": { + "type": "number" + }, + "action": { + "type": "string", + "enum": [ + "START_SCORING", + "STOP_SCORING", + "START_MATCH", + "START_CAMPING", + "STOP_CAMPING", + "START_DEFENDING", + "STOP_DEFENDING", + "INTAKE", + "OUTTAKE", + "DISRUPT", + "CROSS", + "CLIMB", + "START_FEEDING", + "STOP_FEEDING" + ] + }, + "position": { + "type": "string", + "enum": [ + "LEFT_TRENCH", + "LEFT_BUMP", + "HUB", + "RIGHT_TRENCH", + "RIGHT_BUMP", + "NEUTRAL_ZONE", + "DEPOT", + "OUTPOST", + "NONE" + ] + }, + "points": { + "type": "integer" + }, + "quantity": { + "type": [ + "integer", + "null" + ] + }, + "scoutReportUuid": { + "type": "string", + "format": "uuid" + } + }, + "required": [ + "eventUuid", + "time", + "action", + "position", + "points", + "scoutReportUuid" + ] + }, + "FeatureToggle": { + "type": "object", + "properties": { + "feature": { + "type": "string" + }, + "enabled": { + "type": "boolean" + } + }, + "required": [ + "feature", + "enabled" + ] + }, + "TeamMatchData": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "tournamentKey": { + "type": "string" + }, + "matchNumber": { + "type": "integer" + }, + "teamNumber": { + "type": "integer" + }, + "matchType": { + "type": "string", + "enum": [ + "QUALIFICATION", + "ELIMINATION", + "PRACTICE" + ] + } + }, + "required": [ + "key", + "tournamentKey", + "matchNumber", + "teamNumber", + "matchType" + ] + }, + "MutablePicklist": { + "type": "object", + "properties": { + "uuid": { + "type": "string", + "format": "uuid" + }, + "teams": { + "type": "array", + "items": { + "type": "integer" + } + }, + "authorId": { + "type": "string" + }, + "name": { + "type": "string" + }, + "tournamentKey": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "uuid", + "teams", + "authorId", + "name" + ] + }, + "ScoutReport": { + "type": "object", + "properties": { + "uuid": { + "type": "string", + "format": "uuid" + }, + "teamMatchKey": { + "type": "string" + }, + "startTime": { + "type": "string", + "format": "date-time" + }, + "notes": { + "type": "string" + }, + "robotRoles": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "CYCLING", + "SCORING", + "FEEDING", + "DEFENDING", + "IMMOBILE" + ] + } + }, + "driverAbility": { + "type": "integer" + }, + "scouterUuid": { + "type": "string", + "format": "uuid" + }, + "robotBrokeDescription": { + "type": [ + "string", + "null" + ] + }, + "reliability": { + "type": "string", + "enum": [ + "UNVERIFIED", + "VERIFIED", + "FLAGGED", + "BAD_REPORT" + ] + }, + "accuracy": { + "type": "integer" + }, + "beached": { + "type": "string", + "enum": [ + "ON_FUEL", + "ON_BUMP", + "BOTH", + "NEITHER" + ] + }, + "climbPosition": { + "type": [ + "string", + "null" + ], + "enum": [ + "SIDE", + "MIDDLE", + null + ] + }, + "climbSide": { + "type": [ + "string", + "null" + ], + "enum": [ + "FRONT", + "BACK", + null + ] + }, + "defenseEffectiveness": { + "type": "integer" + }, + "feederTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "CONTINUOUS", + "STOP_TO_SHOOT", + "DUMP" + ] + } + }, + "intakeType": { + "type": "string", + "enum": [ + "GROUND", + "OUTPOST", + "BOTH", + "NEITHER" + ] + }, + "fieldTraversal": { + "type": "string", + "enum": [ + "TRENCH", + "BUMP", + "BOTH", + "NONE" + ] + }, + "scoresWhileMoving": { + "type": "boolean" + }, + "disrupts": { + "type": "boolean" + }, + "endgameClimb": { + "type": "string", + "enum": [ + "NOT_ATTEMPTED", + "FAILED", + "L1", + "L2", + "L3" + ] + }, + "autoClimb": { + "type": "string", + "enum": [ + "NOT_ATTEMPTED", + "FAILED", + "SUCCEEDED" + ] + } + }, + "required": [ + "uuid", + "teamMatchKey", + "startTime", + "notes", + "robotRoles", + "driverAbility", + "scouterUuid", + "reliability", + "accuracy", + "beached", + "defenseEffectiveness", + "feederTypes", + "intakeType", + "fieldTraversal", + "scoresWhileMoving", + "disrupts", + "endgameClimb", + "autoClimb" + ] + }, + "ScouterScheduleShift": { + "type": "object", + "properties": { + "uuid": { + "type": "string", + "format": "uuid" + }, + "sourceTeamNumber": { + "type": "integer" + }, + "tournamentKey": { + "type": "string" + }, + "startMatchOrdinalNumber": { + "type": "integer" + }, + "endMatchOrdinalNumber": { + "type": "integer" + } + }, + "required": [ + "uuid", + "sourceTeamNumber", + "tournamentKey", + "startMatchOrdinalNumber", + "endMatchOrdinalNumber" + ] + }, + "Scouter": { + "type": "object", + "properties": { + "uuid": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": [ + "string", + "null" + ] + }, + "sourceTeamNumber": { + "type": "integer" + }, + "strikes": { + "type": "integer" + }, + "scouterReliability": { + "type": "integer" + }, + "archived": { + "type": "boolean" + } + }, + "required": [ + "uuid", + "sourceTeamNumber", + "strikes", + "scouterReliability", + "archived" + ] + }, + "SharedPicklist": { + "type": "object", + "properties": { + "uuid": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "totalPoints": { + "type": "number" + }, + "autoPoints": { + "type": "number" + }, + "teleopPoints": { + "type": "number" + }, + "authorId": { + "type": "string" + }, + "autoClimb": { + "type": "number" + }, + "campingDefenseTime": { + "type": "number" + }, + "climbResult": { + "type": "number" + }, + "contactDefenseTime": { + "type": "number" + }, + "driverAbility": { + "type": "number" + }, + "defenseEffectiveness": { + "type": "number" + }, + "estimatedSuccessfulFuelRate": { + "type": "number" + }, + "estimatedTotalFuelScored": { + "type": "number" + }, + "feedingRate": { + "type": "number" + }, + "scoringRate": { + "type": "number" + }, + "totalDefensiveTime": { + "type": "number" + }, + "totalFuelFed": { + "type": "number" + }, + "totalFuelThroughput": { + "type": "number" + } + }, + "required": [ + "uuid", + "name", + "totalPoints", + "autoPoints", + "teleopPoints", + "authorId", + "autoClimb", + "campingDefenseTime", + "climbResult", + "contactDefenseTime", + "driverAbility", + "defenseEffectiveness", + "estimatedSuccessfulFuelRate", + "estimatedTotalFuelScored", + "feedingRate", + "scoringRate", + "totalDefensiveTime", + "totalFuelFed", + "totalFuelThroughput" + ] + }, + "Team": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "name": { + "type": "string" + } + }, + "required": [ + "number", + "name" + ] + }, + "RegisteredTeam": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "code": { + "type": "string" + }, + "email": { + "type": "string" + }, + "emailVerified": { + "type": "boolean" + }, + "timeCreated": { + "type": "string", + "format": "date-time" + }, + "teamApproved": { + "type": "boolean" + }, + "website": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "number", + "code", + "email", + "emailVerified", + "teamApproved" + ] + }, + "EmailVerificationRequest": { + "type": "object", + "properties": { + "verificationCode": { + "type": "string" + }, + "email": { + "type": "string" + }, + "expiresAt": { + "type": "string", + "format": "date-time" + }, + "teamNumber": { + "type": "integer" + } + }, + "required": [ + "verificationCode", + "email", + "expiresAt", + "teamNumber" + ] + }, + "SlackWorkspace": { + "type": "object", + "properties": { + "workspaceId": { + "type": "string" + }, + "owner": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "botUserId": { + "type": "string" + }, + "authUserId": { + "type": "string" + } + }, + "required": [ + "workspaceId", + "owner", + "name", + "botUserId", + "authUserId" + ] + }, + "SlackSubscription": { + "type": "object", + "properties": { + "subscriptionId": { + "type": "string" + }, + "channelId": { + "type": "string" + }, + "workspaceId": { + "type": "string" + }, + "subscribedEvent": { + "type": "string", + "enum": [ + "BREAK" + ] + } + }, + "required": [ + "subscriptionId", + "channelId", + "workspaceId", + "subscribedEvent" + ] + }, + "SlackNotificationThread": { + "type": "object", + "properties": { + "messageId": { + "type": "string" + }, + "matchNumber": { + "type": "integer" + }, + "teamNumber": { + "type": "integer" + }, + "subscriptionId": { + "type": "string" + }, + "channelId": { + "type": "string" + } + }, + "required": [ + "messageId", + "matchNumber", + "teamNumber", + "subscriptionId", + "channelId" + ] + }, + "Tournament": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "name": { + "type": "string" + }, + "location": { + "type": [ + "string", + "null" + ] + }, + "date": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "key", + "name" + ] + }, + "User": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "teamNumber": { + "type": [ + "integer", + "null" + ] + }, + "email": { + "type": "string" + }, + "emailVerified": { + "type": "boolean" + }, + "username": { + "type": [ + "string", + "null" + ] + }, + "role": { + "type": "string", + "enum": [ + "ANALYST", + "SCOUTING_LEAD" + ] + }, + "teamSourceRule": { + "type": "object", + "properties": { + "mode": { + "type": "string", + "enum": [ + "INCLUDE", + "EXCLUDE" + ] + }, + "items": { + "type": "array", + "items": { + "type": "number" + } + } + }, + "required": [ + "mode", + "items" + ] + }, + "tournamentSourceRule": { + "type": "object", + "properties": { + "mode": { + "type": "string", + "enum": [ + "INCLUDE", + "EXCLUDE" + ] + }, + "items": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "mode", + "items" + ] + } + }, + "required": [ + "id", + "email", + "emailVerified", + "role", + "teamSourceRule", + "tournamentSourceRule" + ] + }, + "ApiKey": { + "type": "object", + "properties": { + "uuid": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "lastUsed": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "requests": { + "type": "integer" + } + }, + "required": [ + "uuid", + "name", + "createdAt", + "requests" + ] + }, + "CachedAnalysis": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "teamDependencies": { + "type": "array", + "items": { + "type": "integer" + }, + "default": [] + }, + "tournamentDependencies": { + "type": "array", + "items": { + "type": "string" + }, + "default": [] + } + }, + "required": [ + "key" + ] + } + }, + "parameters": {} + }, + "paths": { + "/status": { + "get": { + "summary": "Health check", + "description": "Returns a simple message indicating the server is running.", + "responses": { + "200": { + "description": "Server is running", + "content": { + "text/plain": { + "schema": { + "type": "string", + "example": "Server running" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/pitdisplay": { + "get": { + "tags": [ + "Analysis" + ], + "summary": "Public pit display data for a team/event", + "parameters": [ + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "team", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "tournamentKey", + "in": "query" + }, + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "topTeamCount", + "in": "query" + }, + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "teamsAboveCount", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Pit display payload", + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Error generating display", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/alliance": { + "get": { + "tags": [ + "Analysis" + ], + "summary": "Alliance analysis for three teams", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "teamOne", + "in": "query" + }, + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "teamTwo", + "in": "query" + }, + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "teamThree", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Alliance composition and metrics", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "totalPoints": { + "type": "number" + }, + "teams": { + "type": "array", + "items": { + "type": "object", + "properties": { + "team": { + "type": "number" + }, + "role": { + "type": "number" + }, + "averagePoints": { + "type": "number" + }, + "paths": { + "type": "array", + "items": { + "type": "object", + "properties": { + "positions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "location": { + "type": "number" + }, + "event": { + "type": "number" + }, + "time": { + "type": "number" + } + }, + "required": [ + "location", + "event" + ] + } + }, + "matches": { + "type": "array", + "items": { + "type": "object", + "properties": { + "matchKey": { + "type": "string" + }, + "tournamentName": { + "type": "string" + } + }, + "required": [ + "matchKey", + "tournamentName" + ] + } + }, + "score": { + "type": "array", + "items": { + "type": "number" + } + }, + "frequency": { + "type": "number" + }, + "maxScore": { + "type": "number" + } + }, + "required": [ + "positions", + "matches", + "score", + "frequency", + "maxScore" + ] + } + } + }, + "required": [ + "team", + "role", + "averagePoints", + "paths" + ] + } + }, + "l1StartTime": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + }, + "l2StartTime": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + }, + "l3StartTime": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + }, + "totalFuelOutputted": { + "type": "number" + }, + "totalBallThroughput": { + "type": "number" + } + }, + "required": [ + "totalPoints", + "teams", + "l1StartTime", + "l2StartTime", + "l3StartTime", + "totalFuelOutputted", + "totalBallThroughput" + ] + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/matchprediction": { + "get": { + "tags": [ + "Analysis" + ], + "summary": "Predict match outcome for two alliances", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "red1", + "in": "query" + }, + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "red2", + "in": "query" + }, + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "red3", + "in": "query" + }, + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "blue1", + "in": "query" + }, + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "blue2", + "in": "query" + }, + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "blue3", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Prediction and alliance details", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "red1": { + "type": "number" + }, + "red2": { + "type": "number" + }, + "red3": { + "type": "number" + }, + "blue1": { + "type": "number" + }, + "blue2": { + "type": "number" + }, + "blue3": { + "type": "number" + }, + "redWinning": { + "type": "number" + }, + "blueWinning": { + "type": "number" + }, + "winningAlliance": { + "type": "number" + }, + "redAlliance": { + "type": "object", + "properties": { + "totalPoints": { + "type": "number" + }, + "teams": { + "type": "array", + "items": { + "type": "object", + "properties": { + "team": { + "type": "number" + }, + "role": { + "type": "number" + }, + "averagePoints": { + "type": "number" + }, + "paths": { + "type": "array", + "items": { + "type": "object", + "properties": { + "positions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "location": { + "type": "number" + }, + "event": { + "type": "number" + }, + "time": { + "type": "number" + } + }, + "required": [ + "location", + "event" + ] + } + }, + "matches": { + "type": "array", + "items": { + "type": "object", + "properties": { + "matchKey": { + "type": "string" + }, + "tournamentName": { + "type": "string" + } + }, + "required": [ + "matchKey", + "tournamentName" + ] + } + }, + "score": { + "type": "array", + "items": { + "type": "number" + } + }, + "frequency": { + "type": "number" + }, + "maxScore": { + "type": "number" + } + }, + "required": [ + "positions", + "matches", + "score", + "frequency", + "maxScore" + ] + } + } + }, + "required": [ + "team", + "role", + "averagePoints", + "paths" + ] + } + }, + "l1StartTime": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + }, + "l2StartTime": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + }, + "l3StartTime": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + }, + "totalFuelOutputted": { + "type": "number" + }, + "totalBallThroughput": { + "type": "number" + } + }, + "required": [ + "totalPoints", + "teams", + "l1StartTime", + "l2StartTime", + "l3StartTime", + "totalFuelOutputted", + "totalBallThroughput" + ] + }, + "blueAlliance": { + "type": "object", + "properties": { + "totalPoints": { + "type": "number" + }, + "teams": { + "type": "array", + "items": { + "type": "object", + "properties": { + "team": { + "type": "number" + }, + "role": { + "type": "number" + }, + "averagePoints": { + "type": "number" + }, + "paths": { + "type": "array", + "items": { + "type": "object", + "properties": { + "positions": { + "type": "array", + "items": { + "type": "object", + "properties": { + "location": { + "type": "number" + }, + "event": { + "type": "number" + }, + "time": { + "type": "number" + } + }, + "required": [ + "location", + "event" + ] + } + }, + "matches": { + "type": "array", + "items": { + "type": "object", + "properties": { + "matchKey": { + "type": "string" + }, + "tournamentName": { + "type": "string" + } + }, + "required": [ + "matchKey", + "tournamentName" + ] + } + }, + "score": { + "type": "array", + "items": { + "type": "number" + } + }, + "frequency": { + "type": "number" + }, + "maxScore": { + "type": "number" + } + }, + "required": [ + "positions", + "matches", + "score", + "frequency", + "maxScore" + ] + } + } + }, + "required": [ + "team", + "role", + "averagePoints", + "paths" + ] + } + }, + "l1StartTime": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + }, + "l2StartTime": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + }, + "l3StartTime": { + "type": "array", + "items": { + "type": [ + "number", + "null" + ] + } + }, + "totalFuelOutputted": { + "type": "number" + }, + "totalBallThroughput": { + "type": "number" + } + }, + "required": [ + "totalPoints", + "teams", + "l1StartTime", + "l2StartTime", + "l3StartTime", + "totalFuelOutputted", + "totalBallThroughput" + ] + } + }, + "required": [ + "red1", + "red2", + "red3", + "blue1", + "blue2", + "blue3", + "redWinning", + "blueWinning", + "winningAlliance", + "redAlliance", + "blueAlliance" + ] + }, + { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "not enough data" + ] + } + }, + "required": [ + "error" + ] + } + ] + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/qualrankingprediction": { + "get": { + "tags": [ + "Analysis" + ], + "summary": "Predict qual ranking for a tournament", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "tournamentKey", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Qual ranking prediction", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": {} + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/picklist": { + "get": { + "tags": [ + "Analysis" + ], + "summary": "Compute picklist rankings for a tournament", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": false, + "name": "tournamentKey", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "flags", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "stage", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "totalPoints", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "autoPoints", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "teleopPoints", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "driverAbility", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "climbResult", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "autoClimb", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "defenseEffectiveness", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "contactDefenseTime", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "campingDefenseTime", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "totalDefensiveTime", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "totalFuelThroughput", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "totalFuelFed", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "feedingRate", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "scoringRate", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "estimatedSuccessfulFuelRate", + "in": "query" + }, + { + "schema": { + "type": [ + "number", + "null" + ] + }, + "required": false, + "name": "estimatedTotalFuelScored", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Picklist ranking results", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "teams": { + "type": "array", + "items": { + "type": "object", + "properties": { + "team": { + "type": "number" + }, + "result": { + "type": "number" + }, + "breakdown": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string" + }, + "result": { + "type": "number" + } + }, + "required": [ + "type", + "result" + ] + } + }, + "unweighted": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string" + }, + "result": { + "type": "number" + } + }, + "required": [ + "type", + "result" + ] + } + }, + "flags": { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string" + }, + "result": { + "type": "number" + } + }, + "required": [ + "type", + "result" + ] + } + } + }, + "required": [ + "team", + "result", + "breakdown", + "unweighted", + "flags" + ] + } + } + }, + "required": [ + "teams" + ] + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/csvplain": { + "get": { + "tags": [ + "Analysis - CSV" + ], + "summary": "Team CSV", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "team", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "tournamentKey", + "in": "query" + } + ], + "responses": { + "200": { + "description": "CSV", + "content": { + "text/csv": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid parameters or not enough scouting data", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/reportcsv": { + "get": { + "tags": [ + "Analysis - CSV" + ], + "summary": "Report CSV", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "tournamentKey", + "in": "query" + } + ], + "responses": { + "200": { + "description": "CSV", + "content": { + "text/csv": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid parameters or not enough scouting data", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/metrics/scoutreport/{uuid}": { + "get": { + "security": [ + { + "bearerAuth": [] + } + ], + "tags": [ + "Analysis - Scout Report" + ], + "summary": "Metrics for specific scout report", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Metrics", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": {} + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/scoutreports/match/{match}": { + "get": { + "security": [ + { + "bearerAuth": [] + } + ], + "tags": [ + "Analysis - Scout Report" + ], + "summary": "All scout reports for a match", + "parameters": [ + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "match", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Reports", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": {} + } + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error or not authorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/timeline/scoutreport/{uuid}": { + "get": { + "security": [ + { + "bearerAuth": [] + } + ], + "tags": [ + "Analysis - Scout Report" + ], + "summary": "Timeline data for scout report", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Timeline", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": {} + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/metric/{metric}/team/{team}": { + "get": { + "security": [ + { + "bearerAuth": [] + } + ], + "tags": [ + "Analysis - Team Lookup" + ], + "summary": "Metric details for team", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "metric", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "team", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Details", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": {} + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/category/team/{team}": { + "get": { + "security": [ + { + "bearerAuth": [] + } + ], + "tags": [ + "Analysis - Team Lookup" + ], + "summary": "Category metrics for team", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "team", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Categories", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": {} + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/breakdown/team/{team}": { + "get": { + "security": [ + { + "bearerAuth": [] + } + ], + "tags": [ + "Analysis - Team Lookup" + ], + "summary": "Breakdown metrics for team", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "team", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Breakdown", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": {} + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/breakdown/team/{team}/{breakdown}": { + "get": { + "security": [ + { + "bearerAuth": [] + } + ], + "tags": [ + "Analysis - Team Lookup" + ], + "summary": "Specific breakdown details", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "team", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "breakdown", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Details", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": {} + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/notes/team/{team}": { + "get": { + "security": [ + { + "bearerAuth": [] + } + ], + "tags": [ + "Analysis - Team Lookup" + ], + "summary": "Notes for team", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "team", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Notes", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object", + "properties": { + "note": { + "type": "string" + } + }, + "required": [ + "note" + ] + } + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/analysis/flag/team/{team}": { + "get": { + "security": [ + { + "bearerAuth": [] + } + ], + "tags": [ + "Analysis - Team Lookup" + ], + "summary": "Flags for team", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "team", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Flags", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object", + "properties": { + "flag": { + "type": "string" + } + }, + "required": [ + "flag" + ] + } + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Internal server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/apikey": { + "post": { + "tags": [ + "Manager - API Keys" + ], + "summary": "Create a new API key", + "description": "JWT required; API keys (lvt-...) are not permitted for this endpoint.", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "name", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "apiKey": { + "type": "string" + } + }, + "required": [ + "apiKey" + ] + } + } + } + }, + "400": { + "description": "Invalid request parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Forbidden for API key auth", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "delete": { + "tags": [ + "Manager - API Keys" + ], + "summary": "Revoke an API key", + "description": "JWT required; API keys (lvt-...) are not permitted for this endpoint.", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Revoked", + "content": { + "application/json": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Forbidden for API key auth", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "API key not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "patch": { + "tags": [ + "Manager - API Keys" + ], + "summary": "Rename an API key", + "description": "JWT required; API keys (lvt-...) are not permitted for this endpoint.", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "newName", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Renamed", + "content": { + "application/json": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Forbidden for API key auth", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "API key not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "get": { + "tags": [ + "Manager - API Keys" + ], + "summary": "List API keys", + "description": "Returns current user's API keys. Accepts JWT or API keys.", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Keys", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "apiKeys": { + "type": "array", + "items": { + "type": "object", + "properties": { + "uuid": { + "type": "string" + }, + "name": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "lastUsed": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "requests": { + "type": "integer" + }, + "user": { + "type": "object", + "properties": { + "username": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "username" + ] + } + }, + "required": [ + "uuid", + "name", + "createdAt", + "lastUsed", + "requests", + "user" + ] + } + } + }, + "required": [ + "apiKeys" + ] + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/upcoming-entered-tournaments": { + "get": { + "tags": [ + "Manager - Tournaments" + ], + "summary": "Next two future Blue Alliance events for the signed-in user's team", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Events in start-date order; week numbers start at one" + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "502": { + "description": "Blue Alliance event data unavailable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/teams": { + "get": { + "tags": [ + "Manager - Teams" + ], + "summary": "List teams with optional pagination and filter", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "take", + "in": "query" + }, + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "skip", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "filter", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Teams and total count", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "teams": { + "type": "array", + "items": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "name": { + "type": "string" + } + }, + "required": [ + "number", + "name" + ] + } + }, + "count": { + "type": "number" + } + }, + "required": [ + "teams", + "count" + ] + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/tournaments": { + "get": { + "tags": [ + "Manager - Tournaments" + ], + "summary": "List tournaments with optional pagination and filter", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "take", + "in": "query" + }, + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "skip", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "filter", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Tournaments and total count", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tournaments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "name": { + "type": "string" + }, + "location": { + "type": [ + "string", + "null" + ] + }, + "date": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "key", + "name" + ] + } + }, + "count": { + "type": "number" + } + }, + "required": [ + "tournaments", + "count" + ] + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/matches/{tournament}": { + "get": { + "tags": [ + "Manager - Matches" + ], + "summary": "List matches for a tournament", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "tournament", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "teams", + "in": "query" + }, + { + "schema": { + "type": "string", + "enum": [ + "true", + "false" + ], + "description": "Defaults to false. When true, append practice matches (matchType 2) with a teams array instead of team1–team6. Official scouting-shift numbering is unchanged." + }, + "required": false, + "description": "Defaults to false. When true, append practice matches (matchType 2) with a teams array instead of team1–team6. Official scouting-shift numbering is unchanged.", + "name": "includePractice", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Formatted match list", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "matchNumber": { + "type": "integer" + }, + "matchType": { + "type": "integer" + }, + "scouted": { + "type": "boolean" + }, + "finished": { + "type": "boolean" + }, + "team1": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "scouters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "scouted": { + "type": "boolean" + } + }, + "required": [ + "name", + "scouted" + ] + } + }, + "externalReports": { + "type": "integer" + } + }, + "required": [ + "number", + "scouters", + "externalReports" + ] + }, + "team2": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "scouters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "scouted": { + "type": "boolean" + } + }, + "required": [ + "name", + "scouted" + ] + } + }, + "externalReports": { + "type": "integer" + } + }, + "required": [ + "number", + "scouters", + "externalReports" + ] + }, + "team3": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "scouters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "scouted": { + "type": "boolean" + } + }, + "required": [ + "name", + "scouted" + ] + } + }, + "externalReports": { + "type": "integer" + } + }, + "required": [ + "number", + "scouters", + "externalReports" + ] + }, + "team4": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "scouters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "scouted": { + "type": "boolean" + } + }, + "required": [ + "name", + "scouted" + ] + } + }, + "externalReports": { + "type": "integer" + } + }, + "required": [ + "number", + "scouters", + "externalReports" + ] + }, + "team5": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "scouters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "scouted": { + "type": "boolean" + } + }, + "required": [ + "name", + "scouted" + ] + } + }, + "externalReports": { + "type": "integer" + } + }, + "required": [ + "number", + "scouters", + "externalReports" + ] + }, + "team6": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "scouters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "scouted": { + "type": "boolean" + } + }, + "required": [ + "name", + "scouted" + ] + } + }, + "externalReports": { + "type": "integer" + } + }, + "required": [ + "number", + "scouters", + "externalReports" + ] + } + }, + "required": [ + "matchNumber", + "matchType", + "scouted", + "finished", + "team1", + "team2", + "team3", + "team4", + "team5", + "team6" + ] + }, + { + "type": "object", + "properties": { + "matchNumber": { + "type": "integer" + }, + "matchType": { + "type": "number", + "enum": [ + 2 + ] + }, + "scouted": { + "type": "boolean" + }, + "finished": { + "type": "boolean", + "enum": [ + false + ] + }, + "teams": { + "type": "array", + "items": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "scouters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "scouted": { + "type": "boolean" + } + }, + "required": [ + "name", + "scouted" + ] + } + }, + "externalReports": { + "type": "integer" + } + }, + "required": [ + "number", + "scouters", + "externalReports" + ] + }, + "description": "Publicly scheduled or visibly reported practice teams, sorted by team number; no alliance slots" + } + }, + "required": [ + "matchNumber", + "matchType", + "scouted", + "finished", + "teams" + ] + } + ] + } + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/checkmatch": { + "get": { + "tags": [ + "Manager - Matches" + ], + "summary": "Check if a match exists and if a team is in the match", + "security": [], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "tournamentKey", + "in": "query" + }, + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "teamNumber", + "in": "query" + }, + { + "schema": { + "type": [ + "integer", + "null" + ] + }, + "required": false, + "name": "matchNumber", + "in": "query" + }, + { + "schema": { + "anyOf": [ + { + "type": "string", + "enum": [ + "true" + ] + }, + { + "type": "string", + "enum": [ + "false" + ] + }, + { + "type": "boolean" + } + ], + "description": "Legacy match selector; provide this or matchType." + }, + "required": false, + "description": "Legacy match selector; provide this or matchType.", + "name": "isElim", + "in": "query" + }, + { + "schema": { + "type": "string", + "enum": [ + "QUALIFICATION", + "ELIMINATION", + "PRACTICE" + ] + }, + "required": false, + "name": "matchType", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Match data row and alliance", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "match": { + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "tournamentKey": { + "type": "string" + }, + "matchNumber": { + "type": "integer" + }, + "teamNumber": { + "type": "integer" + }, + "matchType": { + "type": "string", + "enum": [ + "QUALIFICATION", + "ELIMINATION", + "PRACTICE" + ] + } + }, + "required": [ + "key", + "tournamentKey", + "matchNumber", + "teamNumber", + "matchType" + ] + }, + "alliance": { + "type": [ + "string", + "null" + ], + "enum": [ + "red", + "blue", + null + ] + } + }, + "required": [ + "match", + "alliance" + ] + } + } + } + }, + "400": { + "description": "Invalid parameters", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Match not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/matchschedule/{tournament}": { + "get": { + "tags": [ + "Manager - Matches" + ], + "summary": "Fetch public match assignments for Collection, including scheduled practice matches", + "security": [], + "parameters": [ + { + "schema": { + "type": "string", + "minLength": 1 + }, + "required": true, + "name": "tournament", + "in": "path" + }, + { + "schema": { + "type": "string", + "minLength": 1 + }, + "required": true, + "name": "x-team-code", + "in": "header" + } + ], + "responses": { + "200": { + "description": "Official and publicly scheduled practice assignments, without private scouting data", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tournamentKey": { + "type": "string" + }, + "matches": { + "type": "array", + "items": { + "type": "object", + "properties": { + "matchNumber": { + "type": "integer" + }, + "matchType": { + "anyOf": [ + { + "type": "number", + "enum": [ + 0 + ] + }, + { + "type": "number", + "enum": [ + 1 + ] + }, + { + "type": "number", + "enum": [ + 2 + ] + } + ] + }, + "teams": { + "type": "array", + "items": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "alliance": { + "type": [ + "string", + "null" + ], + "enum": [ + "red", + "blue", + null + ] + } + }, + "required": [ + "number", + "alliance" + ] + } + } + }, + "required": [ + "matchNumber", + "matchType", + "teams" + ] + } + } + }, + "required": [ + "tournamentKey", + "matches" + ] + } + } + } + }, + "400": { + "description": "Missing team code or tournament", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Invalid team code", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Unable to fetch schedule", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/profile": { + "get": { + "tags": [ + "Manager - Account" + ], + "summary": "Get current user profile", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Profile", + "content": { + "application/json": { + "schema": { + "type": [ + "object", + "null" + ], + "properties": { + "id": { + "type": "string" + }, + "username": { + "type": [ + "string", + "null" + ] + }, + "email": { + "type": "string", + "format": "email" + }, + "role": { + "type": "string" + }, + "team": { + "type": [ + "object", + "null" + ], + "properties": { + "team": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "name": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "number", + "name" + ] + } + }, + "required": [ + "team" + ] + } + }, + "required": [ + "id", + "username", + "email", + "role", + "team" + ] + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/users": { + "get": { + "tags": [ + "Manager - Users" + ], + "summary": "List users", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Users", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "email": { + "type": "string", + "format": "email" + }, + "username": { + "type": [ + "string", + "null" + ] + }, + "role": { + "type": "string" + } + }, + "required": [ + "id", + "email", + "username", + "role" + ] + } + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/user": { + "delete": { + "tags": [ + "Manager - Users" + ], + "summary": "Delete the current user", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Deleted" + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/upgradeuser": { + "post": { + "tags": [ + "Manager - Users" + ], + "summary": "Upgrade current user to Scouting Lead", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Upgraded" + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/analysts": { + "get": { + "tags": [ + "Manager - Users" + ], + "summary": "List analysts", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Analysts", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "username": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "username" + ] + } + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Not a scouting lead", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/code": { + "get": { + "tags": [ + "Manager - Teams" + ], + "summary": "Get team code for current user", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Team code", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "code": { + "type": "string" + } + }, + "required": [ + "code" + ] + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Not authorized to get the team code", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/dashboard/scoutreport": { + "post": { + "tags": [ + "Manager - Scout Reports" + ], + "summary": "Create scout report from dashboard", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "match": { + "type": "integer" + }, + "team": { + "type": "integer" + }, + "notes": { + "type": "string" + } + }, + "required": [ + "match", + "team" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "uuid": { + "type": "string" + } + }, + "required": [ + "uuid" + ] + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/team-tournament-status": { + "get": { + "tags": [ + "Manager - Tournaments" + ], + "summary": "Get status of current team in tournaments", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Status", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tournaments": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "code": { + "type": "string" + }, + "status": { + "type": "string" + } + }, + "required": [ + "id", + "code", + "status" + ] + } + } + }, + "required": [ + "tournaments" + ] + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/match-results-page": { + "get": { + "tags": [ + "Manager - Matches" + ], + "summary": "Get match results page data", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Results", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "matches": { + "type": "array", + "items": { + "type": "object", + "properties": { + "matchNumber": { + "type": "integer" + }, + "matchType": { + "type": "integer" + }, + "scouted": { + "type": "boolean" + }, + "finished": { + "type": "boolean" + }, + "team1": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "scouters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "scouted": { + "type": "boolean" + } + }, + "required": [ + "name", + "scouted" + ] + } + }, + "externalReports": { + "type": "integer" + } + }, + "required": [ + "number", + "scouters", + "externalReports" + ] + }, + "team2": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "scouters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "scouted": { + "type": "boolean" + } + }, + "required": [ + "name", + "scouted" + ] + } + }, + "externalReports": { + "type": "integer" + } + }, + "required": [ + "number", + "scouters", + "externalReports" + ] + }, + "team3": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "scouters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "scouted": { + "type": "boolean" + } + }, + "required": [ + "name", + "scouted" + ] + } + }, + "externalReports": { + "type": "integer" + } + }, + "required": [ + "number", + "scouters", + "externalReports" + ] + }, + "team4": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "scouters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "scouted": { + "type": "boolean" + } + }, + "required": [ + "name", + "scouted" + ] + } + }, + "externalReports": { + "type": "integer" + } + }, + "required": [ + "number", + "scouters", + "externalReports" + ] + }, + "team5": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "scouters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "scouted": { + "type": "boolean" + } + }, + "required": [ + "name", + "scouted" + ] + } + }, + "externalReports": { + "type": "integer" + } + }, + "required": [ + "number", + "scouters", + "externalReports" + ] + }, + "team6": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "scouters": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "scouted": { + "type": "boolean" + } + }, + "required": [ + "name", + "scouted" + ] + } + }, + "externalReports": { + "type": "integer" + } + }, + "required": [ + "number", + "scouters", + "externalReports" + ] + } + }, + "required": [ + "matchNumber", + "matchType", + "scouted", + "finished", + "team1", + "team2", + "team3", + "team4", + "team5", + "team6" + ] + } + } + }, + "required": [ + "matches" + ] + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/notes/{uuid}": { + "put": { + "tags": [ + "Manager - Notes" + ], + "summary": "Update scout report notes (SCOUTING_LEAD)", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "note": { + "type": "string" + } + }, + "required": [ + "note" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Note updated" + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Not authorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scoutershift/scouters": { + "get": { + "tags": [ + "Manager - Scouters" + ], + "summary": "List scouters for current team", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": false, + "name": "archived", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Scouters", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object", + "properties": { + "uuid": { + "type": "string" + }, + "name": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "uuid", + "name" + ] + } + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "User not affiliated with a team", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/noteam": { + "post": { + "tags": [ + "Manager - Users" + ], + "summary": "Set current user to ANALYST and remove team", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Updated", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "role": { + "type": "string" + }, + "teamNumber": { + "type": [ + "number", + "null" + ] + } + }, + "required": [ + "id", + "role", + "teamNumber" + ] + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/mutablepicklists": { + "post": { + "tags": [ + "Manager - Mutable Picklists" + ], + "summary": "Create mutable picklist", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "teams": { + "type": "array", + "items": { + "type": "integer" + } + }, + "tournamentKey": { + "type": "string" + } + }, + "required": [ + "name", + "teams" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Created", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key, or user is not on a team", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "get": { + "tags": [ + "Manager - Mutable Picklists" + ], + "summary": "List mutable picklists", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "List", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object", + "properties": { + "uuid": { + "type": "string" + }, + "name": { + "type": "string" + }, + "tournamentKey": { + "type": [ + "string", + "null" + ] + }, + "author": { + "type": "object", + "properties": { + "username": { + "type": [ + "string", + "null" + ] + } + } + } + }, + "required": [ + "uuid", + "name", + "author" + ] + } + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "User is not on a team", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/mutablepicklists/{uuid}": { + "get": { + "tags": [ + "Manager - Mutable Picklists" + ], + "summary": "Get mutable picklist", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Detail", + "content": { + "application/json": { + "schema": { + "type": [ + "object", + "null" + ], + "properties": { + "uuid": { + "type": "string", + "format": "uuid" + }, + "teams": { + "type": "array", + "items": { + "type": "integer" + } + }, + "authorId": { + "type": "string" + }, + "name": { + "type": "string" + }, + "tournamentKey": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "uuid", + "teams", + "authorId", + "name" + ] + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "put": { + "tags": [ + "Manager - Mutable Picklists" + ], + "summary": "Update mutable picklist", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "teams": { + "type": "array", + "items": { + "type": "integer" + } + } + }, + "required": [ + "name", + "teams" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Updated", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key, or not authorized to update", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Picklist not found or not on same team", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "delete": { + "tags": [ + "Manager - Mutable Picklists" + ], + "summary": "Delete mutable picklist", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Deleted", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key, or not authorized to delete", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/onboarding/verifyemail": { + "post": { + "tags": [ + "Manager - Onboarding" + ], + "summary": "Approve team email (signed)", + "security": [ + { + "lovatSignature": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string", + "description": "Unix timestamp (seconds) used in HMAC signature generation" + }, + "required": true, + "description": "Unix timestamp (seconds) used in HMAC signature generation", + "name": "x-timestamp", + "in": "header" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "code": { + "type": "string" + } + }, + "required": [ + "code" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Approved" + }, + "400": { + "description": "Invalid", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Invalid signature", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Code not recognized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/onboarding/username": { + "post": { + "tags": [ + "Manager - Onboarding" + ], + "summary": "Set username", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "username": { + "type": "string" + } + }, + "required": [ + "username" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Updated" + }, + "400": { + "description": "Invalid", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/onboarding/teamcode": { + "post": { + "tags": [ + "Manager - Onboarding" + ], + "summary": "Check team code", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "team", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "code", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Valid" + }, + "400": { + "description": "Invalid", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Team/code not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/onboarding/team": { + "post": { + "tags": [ + "Manager - Onboarding" + ], + "summary": "Add registered team", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "name": { + "type": "string" + } + }, + "required": [ + "number" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Added" + }, + "400": { + "description": "Invalid", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/onboarding/teamwebsite": { + "post": { + "tags": [ + "Manager - Onboarding" + ], + "summary": "Add team website", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "website": { + "type": "string" + } + }, + "required": [ + "website" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Added" + }, + "400": { + "description": "Invalid", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/onboarding/resendverificationemail": { + "post": { + "tags": [ + "Manager - Onboarding" + ], + "summary": "Resend verification email", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Sent" + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Team not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "429": { + "description": "Rate limited", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/picklists": { + "post": { + "tags": [ + "Manager - Picklists" + ], + "summary": "Create shared picklist", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "totalPoints": { + "type": "number", + "default": 0 + }, + "autoPoints": { + "type": "number", + "default": 0 + }, + "teleopPoints": { + "type": "number", + "default": 0 + }, + "climbResult": { + "type": "number", + "default": 0 + }, + "autoClimb": { + "type": "number", + "default": 0 + }, + "defenseEffectiveness": { + "type": "number", + "default": 0 + }, + "contactDefenseTime": { + "type": "number", + "default": 0 + }, + "campingDefenseTime": { + "type": "number", + "default": 0 + }, + "totalDefensiveTime": { + "type": "number", + "default": 0 + }, + "totalFuelThroughput": { + "type": "number", + "default": 0 + }, + "totalFuelFed": { + "type": "number", + "default": 0 + }, + "feedingRate": { + "type": "number", + "default": 0 + }, + "scoringRate": { + "type": "number", + "default": 0 + }, + "estimatedSuccessfulFuelRate": { + "type": "number", + "default": 0 + }, + "estimatedTotalFuelScored": { + "type": "number", + "default": 0 + }, + "driverAbility": { + "type": "number", + "default": 0 + } + }, + "required": [ + "name" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Picklist created", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid body", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key, or user is not on a team", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "get": { + "tags": [ + "Manager - Picklists" + ], + "summary": "List picklists by team", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "List of picklists", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "uuid": { + "type": "string" + }, + "author": { + "type": "object", + "properties": { + "username": { + "type": [ + "string", + "null" + ] + } + } + } + }, + "required": [ + "name", + "uuid", + "author" + ] + } + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "User is not on a team", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/picklists/{uuid}": { + "get": { + "tags": [ + "Manager - Picklists" + ], + "summary": "Get picklist by UUID", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Picklist detail", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "uuid": { + "type": "string" + }, + "name": { + "type": "string" + }, + "authorId": { + "type": "string" + }, + "driverAbility": { + "type": "number" + }, + "totalPoints": { + "type": "number" + }, + "autoPoints": { + "type": "number" + }, + "teleopPoints": { + "type": "number" + }, + "climbResult": { + "type": "number" + }, + "autoClimb": { + "type": "number" + }, + "defenseEffectiveness": { + "type": "number" + }, + "contactDefenseTime": { + "type": "number" + }, + "campingDefenseTime": { + "type": "number" + }, + "totalDefensiveTime": { + "type": "number" + }, + "totalFuelThroughput": { + "type": "number" + }, + "totalFuelFed": { + "type": "number" + }, + "feedingRate": { + "type": "number" + }, + "scoringRate": { + "type": "number" + }, + "estimatedSuccessfulFuelRate": { + "type": "number" + }, + "estimatedTotalFuelScored": { + "type": "number" + } + }, + "required": [ + "uuid", + "name", + "authorId", + "driverAbility", + "totalPoints", + "autoPoints", + "teleopPoints", + "climbResult", + "autoClimb", + "defenseEffectiveness", + "contactDefenseTime", + "campingDefenseTime", + "totalDefensiveTime", + "totalFuelThroughput", + "totalFuelFed", + "feedingRate", + "scoringRate", + "estimatedSuccessfulFuelRate", + "estimatedTotalFuelScored" + ] + } + } + } + }, + "400": { + "description": "Invalid UUID", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Picklist not found or not on same team", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "put": { + "tags": [ + "Manager - Picklists" + ], + "summary": "Update picklist", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "totalPoints": { + "type": "number", + "default": 0 + }, + "autoPoints": { + "type": "number", + "default": 0 + }, + "teleopPoints": { + "type": "number", + "default": 0 + }, + "climbResult": { + "type": "number", + "default": 0 + }, + "autoClimb": { + "type": "number", + "default": 0 + }, + "defenseEffectiveness": { + "type": "number", + "default": 0 + }, + "contactDefenseTime": { + "type": "number", + "default": 0 + }, + "campingDefenseTime": { + "type": "number", + "default": 0 + }, + "totalDefensiveTime": { + "type": "number", + "default": 0 + }, + "totalFuelThroughput": { + "type": "number", + "default": 0 + }, + "totalFuelFed": { + "type": "number", + "default": 0 + }, + "feedingRate": { + "type": "number", + "default": 0 + }, + "scoringRate": { + "type": "number", + "default": 0 + }, + "estimatedSuccessfulFuelRate": { + "type": "number", + "default": 0 + }, + "estimatedTotalFuelScored": { + "type": "number", + "default": 0 + }, + "driverAbility": { + "type": "number", + "default": 0 + } + }, + "required": [ + "name" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Picklist updated", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid input", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key, or not authorized to update", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Picklist not found or not on same team", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "delete": { + "tags": [ + "Manager - Picklists" + ], + "summary": "Delete picklist", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Deleted", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid UUID", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key, or unauthorized to delete this picklist", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/registeredteams/{team}/registrationstatus": { + "get": { + "tags": [ + "Manager - Registered Teams" + ], + "summary": "Check team registration status", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "team", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Registration status", + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "NOT_STARTED" + ] + } + }, + "required": [ + "status" + ] + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "PENDING_EMAIL_VERIFICATION" + ] + }, + "email": { + "type": "string" + } + }, + "required": [ + "status", + "email" + ] + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "PENDING_WEBSITE" + ] + } + }, + "required": [ + "status" + ] + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "PENDING_TEAM_VERIFICATION" + ] + }, + "teamEmail": { + "type": "string" + } + }, + "required": [ + "status", + "teamEmail" + ] + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "REGISTERED_ON_TEAM" + ] + } + }, + "required": [ + "status" + ] + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "REGISTERED_OFF_TEAM" + ] + } + }, + "required": [ + "status" + ] + }, + { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "PENDING" + ] + } + }, + "required": [ + "status" + ] + } + ] + } + } + } + }, + "400": { + "description": "Invalid team", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/registeredteams/{team}/approve": { + "post": { + "tags": [ + "Manager - Registered Teams" + ], + "summary": "Approve team", + "description": "Requires `x-signature` and `x-timestamp` headers. Signs request body, method, path.", + "security": [ + { + "lovatSignature": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "team", + "in": "path" + }, + { + "schema": { + "type": "string", + "description": "Unix timestamp (seconds) used in HMAC signature generation" + }, + "required": true, + "description": "Unix timestamp (seconds) used in HMAC signature generation", + "name": "x-timestamp", + "in": "header" + } + ], + "responses": { + "200": { + "description": "Approved registered team row", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "code": { + "type": "string" + }, + "email": { + "type": "string" + }, + "emailVerified": { + "type": "boolean" + }, + "timeCreated": { + "type": "string", + "format": "date-time" + }, + "teamApproved": { + "type": "boolean" + }, + "website": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "number", + "code", + "email", + "emailVerified", + "teamApproved" + ] + } + } + } + }, + "400": { + "description": "Invalid team", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized or signature expired", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Invalid signature", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/registeredteams/{team}/reject": { + "post": { + "tags": [ + "Manager - Registered Teams" + ], + "summary": "Reject team", + "description": "Requires `x-signature` and `x-timestamp` headers. Signs request body, method, path.", + "security": [ + { + "lovatSignature": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "team", + "in": "path" + }, + { + "schema": { + "type": "string", + "description": "Unix timestamp (seconds) used in HMAC signature generation" + }, + "required": true, + "description": "Unix timestamp (seconds) used in HMAC signature generation", + "name": "x-timestamp", + "in": "header" + } + ], + "responses": { + "200": { + "description": "Rejection message", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid team", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized or signature expired", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Invalid signature", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/emailTeamCode": { + "post": { + "tags": [ + "Manager - Scouters (Public)" + ], + "summary": "Email team code to registered address", + "parameters": [ + { + "schema": { + "type": "integer" + }, + "required": true, + "name": "teamNumber", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Email sent", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "email": { + "type": "string", + "format": "email" + } + }, + "required": [ + "email" + ] + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scouter/checkcode": { + "get": { + "tags": [ + "Manager - Scouters (Public)" + ], + "summary": "Check team code", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "code", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Valid or team row", + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/name/uuid/{uuid}": { + "post": { + "tags": [ + "Manager - Scouters (Public)" + ], + "summary": "Change scouter name by UUID", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string" + } + }, + "required": [ + "name" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Updated" + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scouters": { + "get": { + "tags": [ + "Manager - Scouters (Public)" + ], + "summary": "List active scouters for team code", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "x-team-code", + "in": "header" + } + ], + "responses": { + "200": { + "description": "Scouters", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object", + "properties": { + "uuid": { + "type": "string", + "format": "uuid" + }, + "name": { + "type": [ + "string", + "null" + ] + }, + "sourceTeamNumber": { + "type": "integer" + }, + "strikes": { + "type": "integer" + }, + "scouterReliability": { + "type": "integer" + }, + "archived": { + "type": "boolean" + } + }, + "required": [ + "uuid", + "sourceTeamNumber", + "strikes", + "scouterReliability", + "archived" + ] + } + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Team code not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scouter": { + "post": { + "tags": [ + "Manager - Scouters (Public)" + ], + "summary": "Create scouter", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "teamNumber": { + "type": "integer" + }, + "name": { + "type": "string" + } + }, + "required": [ + "teamNumber", + "name" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Created", + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scouters/{uuid}/tournaments": { + "get": { + "tags": [ + "Manager - Scouters (Public)" + ], + "summary": "List tournaments", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Tournaments", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": {} + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scouterschedules/{tournament}": { + "get": { + "tags": [ + "Manager - Scouters (Public)" + ], + "summary": "Get scouter schedule", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "tournament", + "in": "path" + }, + { + "schema": { + "type": "string" + }, + "required": true, + "name": "x-team-code", + "in": "header" + } + ], + "responses": { + "200": { + "description": "Schedule", + "content": { + "application/json": { + "schema": {} + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scouter/tournaments": { + "get": { + "tags": [ + "Manager - Scouters (Public)" + ], + "summary": "List scouter tournaments with schedule", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "x-team-code", + "in": "header" + } + ], + "responses": { + "200": { + "description": "Tournaments", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": {} + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/unarchive/uuid/{uuid}": { + "post": { + "tags": [ + "Manager - Scouters" + ], + "summary": "Unarchive scouter", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Unarchived" + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/archive/uuid/{uuid}": { + "post": { + "tags": [ + "Manager - Scouters" + ], + "summary": "Archive scouter", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Archived" + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scoutername": { + "put": { + "tags": [ + "Manager - Scouters" + ], + "summary": "Update scouter name", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "uuid": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "name" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Updated" + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scouterdashboard": { + "delete": { + "tags": [ + "Manager - Scouters" + ], + "summary": "Delete scouter from dashboard", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Deleted" + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "post": { + "tags": [ + "Manager - Scouters" + ], + "summary": "Add scouter on dashboard", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "scouterId": { + "type": "string" + }, + "tournament": { + "type": "string" + } + }, + "required": [ + "scouterId" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Created" + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scouterspage": { + "get": { + "tags": [ + "Manager - Scouters" + ], + "summary": "Scouting lead progress page", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Page data", + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scouterreports": { + "get": { + "tags": [ + "Manager - Scouters" + ], + "summary": "List scouter reports", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Reports", + "content": { + "application/json": { + "schema": {} + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scoutershifts/{uuid}": { + "post": { + "tags": [ + "Manager - Scouter Shifts" + ], + "summary": "Update scouter shift", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "startMatchOrdinalNumber": { + "type": "integer" + }, + "endMatchOrdinalNumber": { + "type": "integer" + }, + "team1": { + "type": "array", + "items": { + "type": "string" + } + }, + "team2": { + "type": "array", + "items": { + "type": "string" + } + }, + "team3": { + "type": "array", + "items": { + "type": "string" + } + }, + "team4": { + "type": "array", + "items": { + "type": "string" + } + }, + "team5": { + "type": "array", + "items": { + "type": "string" + } + }, + "team6": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "startMatchOrdinalNumber", + "endMatchOrdinalNumber", + "team1", + "team2", + "team3", + "team4", + "team5", + "team6" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Updated" + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key, or not a scouting lead", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Shift not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "delete": { + "tags": [ + "Manager - Scouter Shifts" + ], + "summary": "Delete scouter shift", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Deleted" + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scoutreports": { + "post": { + "tags": [ + "Manager - Scout Reports" + ], + "summary": "Create scout report", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "uuid": { + "type": "string" + }, + "tournamentKey": { + "type": "string" + }, + "matchType": { + "type": "string", + "enum": [ + "QUALIFICATION", + "ELIMINATION", + "PRACTICE" + ] + }, + "matchNumber": { + "type": "integer" + }, + "startTime": { + "type": "integer" + }, + "notes": { + "type": "string" + }, + "robotRoles": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "CYCLING", + "SCORING", + "FEEDING", + "DEFENDING", + "IMMOBILE" + ] + } + }, + "mobility": { + "type": "string", + "enum": [ + "TRENCH", + "BUMP", + "BOTH", + "NONE" + ] + }, + "climbPosition": { + "type": "string", + "enum": [ + "SIDE", + "MIDDLE" + ] + }, + "climbSide": { + "type": "string", + "enum": [ + "FRONT", + "BACK" + ] + }, + "beached": { + "type": "string", + "enum": [ + "ON_FUEL", + "ON_BUMP", + "BOTH", + "NEITHER" + ] + }, + "feederTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "CONTINUOUS", + "STOP_TO_SHOOT", + "DUMP" + ] + } + }, + "intakeType": { + "type": "string", + "enum": [ + "GROUND", + "OUTPOST", + "BOTH", + "NEITHER" + ] + }, + "robotBrokeDescription": { + "type": [ + "string", + "null" + ] + }, + "driverAbility": { + "type": "integer" + }, + "accuracy": { + "type": "integer" + }, + "disrupts": { + "type": "boolean" + }, + "defenseEffectiveness": { + "type": "integer" + }, + "scoresWhileMoving": { + "type": "boolean" + }, + "autoClimb": { + "type": "string", + "enum": [ + "NOT_ATTEMPTED", + "FAILED", + "SUCCEEDED" + ] + }, + "endgameClimb": { + "type": "string", + "enum": [ + "NOT_ATTEMPTED", + "FAILED", + "L1", + "L2", + "L3" + ] + }, + "scouterUuid": { + "type": "string" + }, + "teamNumber": { + "type": "integer" + }, + "events": { + "type": "array", + "items": { + "type": "array", + "prefixItems": [ + { + "type": "integer" + }, + { + "type": "integer" + }, + { + "type": "integer" + }, + { + "type": "integer" + } + ] + } + } + }, + "required": [ + "uuid", + "tournamentKey", + "matchType", + "matchNumber", + "startTime", + "notes", + "robotRoles", + "mobility", + "beached", + "feederTypes", + "intakeType", + "driverAbility", + "disrupts", + "defenseEffectiveness", + "scoresWhileMoving", + "autoClimb", + "endgameClimb", + "scouterUuid", + "teamNumber", + "events" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Created", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Match not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scoutreports/{uuid}": { + "get": { + "security": [ + { + "bearerAuth": [] + } + ], + "tags": [ + "Manager - Scout Reports" + ], + "summary": "Get scout report", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Scout report and events", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "scoutReport": { + "type": "object", + "properties": { + "uuid": { + "type": "string", + "format": "uuid" + }, + "teamMatchKey": { + "type": "string" + }, + "startTime": { + "type": "string", + "format": "date-time" + }, + "notes": { + "type": "string" + }, + "robotRoles": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "CYCLING", + "SCORING", + "FEEDING", + "DEFENDING", + "IMMOBILE" + ] + } + }, + "driverAbility": { + "type": "integer" + }, + "scouterUuid": { + "type": "string", + "format": "uuid" + }, + "robotBrokeDescription": { + "type": [ + "string", + "null" + ] + }, + "reliability": { + "type": "string", + "enum": [ + "UNVERIFIED", + "VERIFIED", + "FLAGGED", + "BAD_REPORT" + ] + }, + "accuracy": { + "type": "integer" + }, + "beached": { + "type": "string", + "enum": [ + "ON_FUEL", + "ON_BUMP", + "BOTH", + "NEITHER" + ] + }, + "climbPosition": { + "type": [ + "string", + "null" + ], + "enum": [ + "SIDE", + "MIDDLE", + null + ] + }, + "climbSide": { + "type": [ + "string", + "null" + ], + "enum": [ + "FRONT", + "BACK", + null + ] + }, + "defenseEffectiveness": { + "type": "integer" + }, + "feederTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "CONTINUOUS", + "STOP_TO_SHOOT", + "DUMP" + ] + } + }, + "intakeType": { + "type": "string", + "enum": [ + "GROUND", + "OUTPOST", + "BOTH", + "NEITHER" + ] + }, + "fieldTraversal": { + "type": "string", + "enum": [ + "TRENCH", + "BUMP", + "BOTH", + "NONE" + ] + }, + "scoresWhileMoving": { + "type": "boolean" + }, + "disrupts": { + "type": "boolean" + }, + "endgameClimb": { + "type": "string", + "enum": [ + "NOT_ATTEMPTED", + "FAILED", + "L1", + "L2", + "L3" + ] + }, + "autoClimb": { + "type": "string", + "enum": [ + "NOT_ATTEMPTED", + "FAILED", + "SUCCEEDED" + ] + } + }, + "required": [ + "uuid", + "teamMatchKey", + "startTime", + "notes", + "robotRoles", + "driverAbility", + "scouterUuid", + "reliability", + "accuracy", + "beached", + "defenseEffectiveness", + "feederTypes", + "intakeType", + "fieldTraversal", + "scoresWhileMoving", + "disrupts", + "endgameClimb", + "autoClimb" + ] + }, + "events": { + "type": "array", + "items": { + "type": "object", + "properties": { + "eventUuid": { + "type": "string", + "format": "uuid" + }, + "time": { + "type": "number" + }, + "action": { + "type": "string", + "enum": [ + "START_SCORING", + "STOP_SCORING", + "START_MATCH", + "START_CAMPING", + "STOP_CAMPING", + "START_DEFENDING", + "STOP_DEFENDING", + "INTAKE", + "OUTTAKE", + "DISRUPT", + "CROSS", + "CLIMB", + "START_FEEDING", + "STOP_FEEDING" + ] + }, + "position": { + "type": "string", + "enum": [ + "LEFT_TRENCH", + "LEFT_BUMP", + "HUB", + "RIGHT_TRENCH", + "RIGHT_BUMP", + "NEUTRAL_ZONE", + "DEPOT", + "OUTPOST", + "NONE" + ] + }, + "points": { + "type": "integer" + }, + "quantity": { + "type": [ + "integer", + "null" + ] + }, + "scoutReportUuid": { + "type": "string", + "format": "uuid" + } + }, + "required": [ + "eventUuid", + "time", + "action", + "position", + "points", + "scoutReportUuid" + ] + } + } + }, + "required": [ + "scoutReport", + "events" + ] + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "delete": { + "security": [ + { + "bearerAuth": [] + } + ], + "tags": [ + "Manager - Scout Reports" + ], + "summary": "Delete scout report", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "uuid", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Deleted", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/scoutreports/setflag/{report}": { + "post": { + "security": [ + { + "bearerAuth": [] + } + ], + "tags": [ + "Manager - Scout Reports" + ], + "summary": "Set or remove your flag on a scout report", + "parameters": [ + { + "schema": { + "type": "string", + "minLength": 1 + }, + "required": true, + "name": "report", + "in": "path" + }, + { + "schema": { + "type": "string", + "enum": [ + "true", + "false" + ] + }, + "required": true, + "name": "flag", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Flag updated", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "flagged": { + "type": "boolean" + }, + "flagCount": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "flagged", + "flagCount" + ] + } + } + } + }, + "400": { + "description": "Invalid report parameter or flag value", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Authentication required or no team assigned", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Team is not verified", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Report not found or outside allowed sources", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/settings": { + "put": { + "tags": [ + "Manager - Settings" + ], + "summary": "Update sources", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "teamSource": { + "type": "array", + "items": { + "type": "integer" + } + }, + "tournamentSource": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "teamSource", + "tournamentSource" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Updated", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Cannot be performed using an API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/settings/teamsource": { + "get": { + "tags": [ + "Manager - Settings" + ], + "summary": "Get team source", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Team source", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "type": "string", + "enum": [ + "THIS_TEAM" + ] + }, + { + "type": "string", + "enum": [ + "ALL_TEAMS" + ] + }, + { + "type": "array", + "items": { + "type": "integer" + } + } + ] + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "post": { + "tags": [ + "Manager - Settings" + ], + "summary": "Add team source", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "mode": { + "type": "string", + "enum": [ + "ALL_TEAMS" + ] + } + }, + "required": [ + "mode" + ] + }, + { + "type": "object", + "properties": { + "mode": { + "type": "string", + "enum": [ + "THIS_TEAM" + ] + } + }, + "required": [ + "mode" + ] + }, + { + "type": "object", + "properties": { + "teams": { + "type": "array", + "items": { + "type": "integer" + } + } + }, + "required": [ + "teams" + ] + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "Added", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Not affiliated with a team", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/settings/tournamentsource": { + "get": { + "tags": [ + "Manager - Settings" + ], + "summary": "Get tournament source", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Tournament source", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "post": { + "tags": [ + "Manager - Settings" + ], + "summary": "Add tournament source", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "tournaments": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "tournaments" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Added", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/settings/teamemail": { + "get": { + "tags": [ + "Manager - Settings" + ], + "summary": "Get team email", + "security": [ + { + "bearerAuth": [] + } + ], + "responses": { + "200": { + "description": "Team email", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Forbidden", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Team not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "429": { + "description": "Rate limited", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "put": { + "tags": [ + "Manager - Settings" + ], + "summary": "Update team email", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string", + "format": "email" + }, + "required": true, + "name": "email", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Verification sent", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Invalid request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Team not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "429": { + "description": "Rate limited", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/tournament/{tournament}/teams": { + "get": { + "tags": [ + "Manager - Tournaments" + ], + "summary": "List teams in tournament", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "tournament", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Teams", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "name": { + "type": "string" + } + }, + "required": [ + "number", + "name" + ] + } + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/tournament/{tournament}/rankedTeams": { + "get": { + "tags": [ + "Manager - Tournaments" + ], + "summary": "Ranked teams", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "tournament", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Rankings", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "object", + "properties": { + "number": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "rank": { + "type": [ + "integer", + "null" + ] + }, + "rankingPoints": { + "type": [ + "integer", + "null" + ] + }, + "matchesPlayed": { + "type": [ + "integer", + "null" + ] + }, + "avatar": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "number", + "name", + "rank", + "rankingPoints", + "matchesPlayed", + "avatar" + ] + } + } + } + } + }, + "404": { + "description": "Tournament or teams not found", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/manager/tournament/{tournament}/scoutershifts": { + "post": { + "tags": [ + "Manager - Tournaments" + ], + "summary": "Create scouter shift", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "tournament", + "in": "path" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "startMatchOrdinalNumber": { + "type": "integer" + }, + "endMatchOrdinalNumber": { + "type": "integer" + }, + "team1": { + "type": "array", + "items": { + "type": "string" + } + }, + "team2": { + "type": "array", + "items": { + "type": "string" + } + }, + "team3": { + "type": "array", + "items": { + "type": "string" + } + }, + "team4": { + "type": "array", + "items": { + "type": "string" + } + }, + "team5": { + "type": "array", + "items": { + "type": "string" + } + }, + "team6": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "startMatchOrdinalNumber", + "endMatchOrdinalNumber", + "team1", + "team2", + "team3", + "team4", + "team5", + "team6" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Created" + }, + "400": { + "description": "Invalid request, overlapping scouters, or overlapping shift matches", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "API key forbidden or user role not SCOUTING_LEAD", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + }, + "get": { + "tags": [ + "Manager - Tournaments" + ], + "summary": "List scouter shifts", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "tournament", + "in": "path" + } + ], + "responses": { + "200": { + "description": "Shifts", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "hash": { + "type": "string" + }, + "data": { + "type": "array", + "items": { + "type": "object", + "properties": { + "uuid": { + "type": "string", + "format": "uuid" + }, + "sourceTeamNumber": { + "type": "integer" + }, + "tournamentKey": { + "type": "string" + }, + "startMatchOrdinalNumber": { + "type": "integer" + }, + "endMatchOrdinalNumber": { + "type": "integer" + }, + "team1": { + "type": [ + "object", + "null" + ], + "properties": { + "name": { + "type": [ + "string", + "null" + ] + }, + "uuid": { + "type": "string" + } + }, + "required": [ + "name", + "uuid" + ] + }, + "team2": { + "type": [ + "object", + "null" + ], + "properties": { + "name": { + "type": [ + "string", + "null" + ] + }, + "uuid": { + "type": "string" + } + }, + "required": [ + "name", + "uuid" + ] + }, + "team3": { + "type": [ + "object", + "null" + ], + "properties": { + "name": { + "type": [ + "string", + "null" + ] + }, + "uuid": { + "type": "string" + } + }, + "required": [ + "name", + "uuid" + ] + }, + "team4": { + "type": [ + "object", + "null" + ], + "properties": { + "name": { + "type": [ + "string", + "null" + ] + }, + "uuid": { + "type": "string" + } + }, + "required": [ + "name", + "uuid" + ] + }, + "team5": { + "type": [ + "object", + "null" + ], + "properties": { + "name": { + "type": [ + "string", + "null" + ] + }, + "uuid": { + "type": "string" + } + }, + "required": [ + "name", + "uuid" + ] + }, + "team6": { + "type": [ + "object", + "null" + ], + "properties": { + "name": { + "type": [ + "string", + "null" + ] + }, + "uuid": { + "type": "string" + } + }, + "required": [ + "name", + "uuid" + ] + } + }, + "required": [ + "uuid", + "sourceTeamNumber", + "tournamentKey", + "startMatchOrdinalNumber", + "endMatchOrdinalNumber", + "team1", + "team2", + "team3", + "team4", + "team5", + "team6" + ] + } + } + }, + "required": [ + "hash", + "data" + ] + } + } + } + }, + "401": { + "description": "Unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "User not affiliated with a team", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "500": { + "description": "Server error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/slack/add-workspace": { + "get": { + "tags": [ + "Slack" + ], + "summary": "Add Slack workspace (OAuth flow)", + "security": [ + { + "slackToken": [] + } + ], + "responses": { + "200": { + "description": "Redirect or JSON" + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/slack/command": { + "post": { + "tags": [ + "Slack" + ], + "summary": "Slack slash command", + "security": [ + { + "slackToken": [] + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "command": { + "type": "string" + }, + "text": { + "type": "string" + } + }, + "required": [ + "command" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Processed" + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + }, + "/v1/slack/event": { + "post": { + "tags": [ + "Slack" + ], + "summary": "Slack event callback", + "security": [ + { + "slackToken": [] + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "type": { + "type": "string" + }, + "event": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "type", + "event" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Processed" + }, + "default": { + "$ref": "#/components/responses/ApiErrorResponse" + } + } + } + } + }, + "webhooks": {} +} diff --git a/packages/api/package-lock.json b/packages/api/package-lock.json new file mode 100644 index 000000000..0047ba319 --- /dev/null +++ b/packages/api/package-lock.json @@ -0,0 +1,98 @@ +{ + "name": "@lovat/api", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@lovat/api", + "version": "0.1.0", + "dependencies": { + "@asteasolutions/zod-to-openapi": "9.1.0", + "zod": "4.6.7" + }, + "devDependencies": { + "prettier": "3.9.9", + "typescript": "5.9.3" + }, + "engines": { + "node": ">=22.20.0 <23 || >=24" + } + }, + "node_modules/@asteasolutions/zod-to-openapi": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/@asteasolutions/zod-to-openapi/-/zod-to-openapi-9.1.0.tgz", + "integrity": "sha512-pLMeRgRYS7/vZIgAAkOe2P6+XGTifR1MT9pqDoxZ11EmcJJ+DPmdPqLN8ZZF4U8R9KHCCQCS9c2wtuE8wSrfkw==", + "license": "MIT", + "dependencies": { + "openapi3-ts": "^4.6.0" + }, + "peerDependencies": { + "zod": "^4.0.0" + } + }, + "node_modules/openapi3-ts": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/openapi3-ts/-/openapi3-ts-4.6.2.tgz", + "integrity": "sha512-gyyil3DweqhXiEhTqtAs9wwRLfWHmetwhI4kmM5Rn0d6gtmK863Ki7qqbQnp9+Wwlqoe3B1LFWj7kMp5ctE4rQ==", + "license": "MIT", + "dependencies": { + "yaml": "^2.9.1" + } + }, + "node_modules/prettier": { + "version": "3.9.9", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.9.tgz", + "integrity": "sha512-Z/CJHIkdujO/OtN7nXUii0Rf3VT5SRuhjBA82Xvu2XhBUgX3nhP67T0LHceBdQLex7OOFGTox+Q5Yg8Jk2Qivg==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/packages/api/package.json b/packages/api/package.json new file mode 100644 index 000000000..cc945c7bb --- /dev/null +++ b/packages/api/package.json @@ -0,0 +1,45 @@ +{ + "name": "@lovat/api", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + }, + "./legacy": { + "types": "./dist/legacy/index.d.ts", + "import": "./dist/legacy/index.js" + }, + "./effects": { + "import": "./dist/effects.js", + "types": "./dist/effects.d.ts" + } + }, + "files": [ + "dist", + "openapi.json", + "openapi.legacy.json" + ], + "scripts": { + "build": "tsc", + "typecheck": "tsc --noEmit", + "test": "npm run build && node --test test/*.test.mjs", + "generate": "npm run build && node tools/generate.mjs", + "generate:check": "npm run build && node tools/generate.mjs --check", + "lint": "tsc --noEmit --noUnusedLocals --noUnusedParameters", + "format:check": "prettier --check ." + }, + "engines": { + "node": ">=22.20.0 <23 || >=24" + }, + "dependencies": { + "@asteasolutions/zod-to-openapi": "9.1.0", + "zod": "4.6.7" + }, + "devDependencies": { + "prettier": "3.9.9", + "typescript": "5.9.3" + } +} diff --git a/packages/api/src/client.ts b/packages/api/src/client.ts new file mode 100644 index 000000000..c2e1c5fe7 --- /dev/null +++ b/packages/api/src/client.ts @@ -0,0 +1,70 @@ +import type { z } from "zod"; +import { apiErrorSchema, type ApiError } from "./errors.js"; +import { routes } from "./routes.js"; + +export class ApiClientError extends Error { + constructor( + readonly status: number, + readonly details: ApiError, + ) { + super(details.message); + } +} +export function createApiClient(options: { + baseUrl: string; + token?: () => string | Promise; + collection?: () => Record | Promise>; + fetch?: typeof fetch; +}) { + const fetcher = options.fetch ?? globalThis.fetch; + return { + async request( + operation: K, + input: z.input<(typeof routes)[K]["input"]>, + signal?: AbortSignal, + ): Promise> { + const definition = routes[operation]; + const body = definition.input.parse(input); + const url = new URL(definition.path, options.baseUrl); + if (definition.method === "GET") + for (const [key, value] of Object.entries(body)) + if (value !== undefined) url.searchParams.set(key, String(value)); + const headers: Record = { + "Content-Type": "application/json", + }; + if (definition.auth === "dashboard") { + if (!options.token) + throw new Error("A Dashboard token provider is required"); + headers.Authorization = "Bearer " + (await options.token()); + } + if (definition.auth === "collection") { + if (!options.collection) + throw new Error("A Collection identity provider is required"); + Object.assign(headers, await options.collection()); + } + const response = await fetcher(url, { + method: definition.method, + headers, + ...(definition.method === "POST" ? { body: JSON.stringify(body) } : {}), + signal: signal ?? AbortSignal.timeout(15_000), + }); + const data: unknown = await response.json(); + if (!response.ok) { + const parsed = apiErrorSchema.safeParse(data); + throw new ApiClientError( + response.status, + parsed.success + ? parsed.data + : { + code: "HTTP_ERROR", + message: "API request failed", + displayError: "API request failed", + }, + ); + } + return definition.output.parse(data) as z.output< + (typeof routes)[K]["output"] + >; + }, + }; +} diff --git a/packages/api/src/collection.ts b/packages/api/src/collection.ts new file mode 100644 index 000000000..b4590e7a3 --- /dev/null +++ b/packages/api/src/collection.ts @@ -0,0 +1,53 @@ +import { z } from "zod"; +import { timestampSchema } from "./common.js"; +export const collectionIdentityHeadersSchema = z.object({ + "x-team-code": z.string().min(1).max(256), + "x-scouter-uuid": z.uuid(), + "x-device-id": z.string().min(1).max(200), +}); +export const loadReportSchema = z.object({ + uuid: z.uuid(), + teamNumber: z.coerce.number().int().positive().optional(), + trainingAttemptUuid: z.uuid().optional(), + matchIdentity: z + .object({ + tournamentKey: z.string().min(1), + matchType: z.enum(["QUALIFICATION", "ELIMINATION", "PRACTICE"]), + matchNumber: z.number().int().positive(), + }) + .optional(), +}); +export const startReportSchema = z.object({ + uuid: z.uuid(), + startTime: timestampSchema, +}); +export const endReportSchema = z.object({ + uuid: z.uuid(), + endTime: timestampSchema, +}); +export const reportReceiptSchema = z.object({ uuid: z.uuid() }); +export const trainingSessionCreateSchema = z.object({ videoUuid: z.uuid() }); +export const trainingPairSchema = z.object({ + pairingToken: z.string().min(32).max(100), + deviceName: z.string().trim().min(1).max(80), +}); +export const trainingReadySchema = z.object({ + attemptUuid: z.uuid(), + stage: z.enum(["LOBBY", "ARMED"]).optional(), +}); +export const trainingControlSchema = z.object({ + action: z.enum(["arm", "play", "end", "interrupt"]), + playbackSeconds: z.number().finite().min(0).max(600).optional(), +}); +export const trainingSocketCredentialsSchema = z.object({ + sessionUuid: z.uuid(), + token: z.string().min(32).max(100), + attemptUuid: z.uuid().optional(), +}); +export type LoadReport = z.infer; +export type StartReport = z.infer; +export type EndReport = z.infer; +export type TrainingControl = z.infer; +export type TrainingSocketCredentials = z.infer< + typeof trainingSocketCredentialsSchema +>; diff --git a/packages/api/src/common.ts b/packages/api/src/common.ts new file mode 100644 index 000000000..94864451f --- /dev/null +++ b/packages/api/src/common.ts @@ -0,0 +1,6 @@ +import { z } from "zod"; +export const timestampSchema = z + .number() + .int() + .nonnegative() + .max(8_640_000_000_000_000); diff --git a/packages/api/src/effects.ts b/packages/api/src/effects.ts new file mode 100644 index 000000000..765bcfb8d --- /dev/null +++ b/packages/api/src/effects.ts @@ -0,0 +1,48 @@ +import { z } from "zod"; +export const effectSchema = z.discriminatedUnion("kind", [ + z + .object({ + kind: z.literal("slack.registration"), + teamNumber: z.number().int().positive(), + }) + .strict(), + z + .object({ + kind: z.literal("cache.revision"), + teamNumber: z.number().int(), + revision: z.string().regex(/^(0|[1-9]\d*)$/), + }) + .strict(), + z + .object({ + kind: z.literal("email.send"), + to: z.email(), + subject: z.string().max(500), + text: z.string().max(50000), + }) + .strict(), + z + .object({ + kind: z.literal("slack.warning"), + reportUuid: z.string().min(1), + sourceTeamNumber: z.number().int(), + }) + .strict(), + z + .object({ + kind: z.literal("slack.warning.channel"), + reportUuid: z.string().min(1), + sourceTeamNumber: z.number().int(), + subscriptionId: z.string().min(1), + }) + .strict(), + z + .object({ + kind: z.literal("slack.message"), + channelId: z.string(), + workspaceId: z.string(), + text: z.string().max(50000), + }) + .strict(), +]); +export type Effect = z.infer; diff --git a/packages/api/src/errors.ts b/packages/api/src/errors.ts new file mode 100644 index 000000000..525eb9273 --- /dev/null +++ b/packages/api/src/errors.ts @@ -0,0 +1,11 @@ +import { z } from "zod"; + +export const apiErrorSchema = z.object({ + code: z.string(), + message: z.string(), + displayError: z.string(), + invalidFields: z.array(z.string()).optional(), + retryAfterSeconds: z.number().optional(), +}); + +export type ApiError = z.infer; diff --git a/packages/api/src/games.ts b/packages/api/src/games.ts new file mode 100644 index 000000000..e6197a49c --- /dev/null +++ b/packages/api/src/games.ts @@ -0,0 +1,75 @@ +import { z } from "zod"; +import { metricMetadataSchema } from "./metrics.js"; +import { timestampSchema } from "./common.js"; +export const gameRulesSchema = z.object({ + allianceSize: z.number().int().min(1).max(6), + periods: z + .array( + z.object({ + id: z.string().min(1), + label: z.string(), + durationSeconds: z.number().positive(), + }), + ) + .min(1) + .max(10), + scoring: z.record(z.string(), z.json()), +}); +export const gameDescriptorSchema = z.object({ + id: z.string().regex(/^[a-z0-9][a-z0-9-]{0,99}$/), + season: z.number().int().min(1992).max(2200), + version: z.number().int().positive(), + label: z.string().min(1), + reportVersion: z.number().int().positive(), + reportSchemas: z.record(z.string(), z.record(z.string(), z.json())), + rules: gameRulesSchema, + metrics: z.array(metricMetadataSchema), + features: z.object({ predictions: z.boolean() }), +}); +export const gameReportEnvelopeSchema = z + .object({ + uuid: z.uuid(), + scouterUuid: z.uuid(), + teamNumber: z.number().int().positive(), + tournamentKey: z.string().min(1).max(100), + matchType: z.enum(["QUALIFICATION", "ELIMINATION", "PRACTICE"]), + matchNumber: z.number().int().positive().max(32767), + season: z.number().int().min(1992).max(2200), + gameId: z.string().min(1).max(100), + gameVersion: z.number().int().positive(), + reportVersion: z.number().int().positive(), + startTime: timestampSchema, + endTime: timestampSchema, + data: z.record(z.string(), z.json()), + }) + .strict() + .refine((report) => report.endTime >= report.startTime, { + message: "Report must end after it starts", + }); +export type GameDescriptor = z.infer; +export type GameRules = z.infer; +export type GameReportEnvelope = z.infer; + +export const gamePredictionRequestSchema = z + .object({ + season: z.number().int().min(1992).max(2200), + gameVersion: z.number().int().positive().optional(), + red: z.array(z.number().int().positive()).min(1).max(6), + blue: z.array(z.number().int().positive()).min(1).max(6), + }) + .strict(); +export const gamePredictionResultSchema = z + .object({ + redWinning: z.number().min(0).max(1), + blueWinning: z.number().min(0).max(1), + winningAlliance: z.enum(["red", "blue", "tie"]), + redScore: z.number(), + blueScore: z.number(), + redRankingPoints: z.number().nonnegative().optional(), + blueRankingPoints: z.number().nonnegative().optional(), + }) + .refine( + (value) => Math.abs(value.redWinning + value.blueWinning - 1) < 0.00001, + { message: "Win probabilities must sum to one" }, + ); +export type GamePredictionResult = z.infer; diff --git a/packages/api/src/games/2026/report.ts b/packages/api/src/games/2026/report.ts new file mode 100644 index 000000000..d3b92cf5d --- /dev/null +++ b/packages/api/src/games/2026/report.ts @@ -0,0 +1,111 @@ +import { z } from "zod"; + +// Tuple positions are a versioned Collection wire contract. Never reorder these. +export const eventActions = [ + "START_SCORING", + "STOP_SCORING", + "START_MATCH", + "START_CAMPING", + "STOP_CAMPING", + "START_DEFENDING", + "STOP_DEFENDING", + "INTAKE", + "OUTTAKE", + "DISRUPT", + "CROSS", + "CLIMB", + "START_FEEDING", + "STOP_FEEDING", +] as const; +export const eventPositions = [ + "LEFT_TRENCH", + "LEFT_BUMP", + "HUB", + "RIGHT_TRENCH", + "RIGHT_BUMP", + "NEUTRAL_ZONE", + "DEPOT", + "OUTPOST", + "NONE", +] as const; +import { timestampSchema } from "../../common.js"; +export { timestampSchema } from "../../common.js"; +export const eventTupleSchema = z + .union([ + z.tuple([z.number().nonnegative(), z.number().int(), z.number().int()]), + z.tuple([ + z.number().nonnegative(), + z.number().int(), + z.number().int(), + z.number().int().nonnegative(), + ]), + ]) + .superRefine((event, ctx) => { + const action = eventActions[event[1]]; + if (!action || !eventPositions[event[2]]) { + ctx.addIssue({ + code: "custom", + message: "Unknown event action or position.", + }); + } + if ( + (action === "STOP_SCORING" || action === "STOP_FEEDING") && + event[3] === undefined + ) { + ctx.addIssue({ + code: "custom", + message: "Scoring and feeding stop events require a quantity.", + }); + } + }); + +// Existing Collection report fields, independent of Prisma and server imports. +export const reportSchema = z.object({ + uuid: z.uuid(), + scouterUuid: z.uuid(), + tournamentKey: z.string().min(1), + matchType: z.enum(["QUALIFICATION", "ELIMINATION", "PRACTICE"]), + matchNumber: z.number().int().positive(), + teamNumber: z.number().int().positive(), + startTime: timestampSchema, + notes: z.string(), + robotRoles: z.array( + z.enum(["CYCLING", "SCORING", "FEEDING", "DEFENDING", "IMMOBILE"]), + ), + mobility: z.enum(["TRENCH", "BUMP", "BOTH", "NONE"]), + climbPosition: z.enum(["SIDE", "MIDDLE"]).optional(), + climbSide: z.enum(["FRONT", "BACK"]).optional(), + beached: z.enum(["ON_FUEL", "ON_BUMP", "BOTH", "NEITHER"]), + feederTypes: z.array(z.enum(["CONTINUOUS", "STOP_TO_SHOOT", "DUMP"])), + intakeType: z.enum(["GROUND", "OUTPOST", "BOTH", "NEITHER"]), + robotBrokeDescription: z.string().nullable().optional(), + driverAbility: z.number().int(), + accuracy: z.number().int().nullable().optional(), + disrupts: z.boolean(), + defenseEffectiveness: z.number().int(), + scoresWhileMoving: z.boolean(), + autoClimb: z.enum(["NOT_ATTEMPTED", "FAILED", "SUCCEEDED"]), + endgameClimb: z.enum(["NOT_ATTEMPTED", "FAILED", "L1", "L2", "L3"]), + appVersion: z.string().optional(), + events: z.array(eventTupleSchema), +}); + +export type ReportSubmission = z.infer; +export type EventTuple = z.infer; + +export const gameData2026Schema = reportSchema + .omit({ + uuid: true, + scouterUuid: true, + tournamentKey: true, + matchType: true, + matchNumber: true, + teamNumber: true, + startTime: true, + }) + .extend({ + notes: z.string().max(50000), + robotBrokeDescription: z.string().max(50000).nullable().optional(), + events: z.array(eventTupleSchema).max(10000), + }) + .strict(); diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts new file mode 100644 index 000000000..952f6da15 --- /dev/null +++ b/packages/api/src/index.ts @@ -0,0 +1,9 @@ +export * from "./errors.js"; +export * from "./reports.js"; +export * from "./metrics.js"; +export * from "./routes.js"; +export * from "./client.js"; + +export * from "./collection.js"; + +export * from "./games.js"; diff --git a/packages/api/src/legacy/analysis.ts b/packages/api/src/legacy/analysis.ts new file mode 100644 index 000000000..6c09a727c --- /dev/null +++ b/packages/api/src/legacy/analysis.ts @@ -0,0 +1,194 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; + +export function registerAnalysisPaths(registry: OpenAPIRegistry) { + const AlliancePathPosition = z.object({ + location: z.number(), + event: z.number(), + time: z.number().optional(), + }); + const AlliancePath = z.object({ + positions: z.array(AlliancePathPosition), + matches: z.array( + z.object({ matchKey: z.string(), tournamentName: z.string() }), + ), + score: z.array(z.number()), + frequency: z.number(), + maxScore: z.number(), + }); + const AllianceTeam = z.object({ + team: z.number(), + role: z.number(), + averagePoints: z.number(), + paths: z.array(AlliancePath), + }); + const AllianceResponseSchema = z.object({ + totalPoints: z.number(), + teams: z.array(AllianceTeam), + l1StartTime: z.array(z.number().nullable()).length(3), + l2StartTime: z.array(z.number().nullable()).length(3), + l3StartTime: z.array(z.number().nullable()).length(3), + totalFuelOutputted: z.number(), + totalBallThroughput: z.number(), + }); + const MatchPredictionResponseSchema = z.union([ + z.object({ + red1: z.number(), + red2: z.number(), + red3: z.number(), + blue1: z.number(), + blue2: z.number(), + blue3: z.number(), + redWinning: z.number(), + blueWinning: z.number(), + winningAlliance: z.number(), + redAlliance: AllianceResponseSchema, + blueAlliance: AllianceResponseSchema, + }), + z.object({ error: z.literal("not enough data") }), + ]); + const PicklistEntrySchema = z.object({ + team: z.number(), + result: z.number(), + breakdown: z.array(z.object({ type: z.string(), result: z.number() })), + unweighted: z.array(z.object({ type: z.string(), result: z.number() })), + flags: z.array(z.object({ type: z.string(), result: z.number() })), + }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/pitdisplay", + tags: ["Analysis"], + summary: "Public pit display data for a team/event", + request: { + query: z.object({ + team: z.coerce.number().int(), + tournamentKey: z.string(), + topTeamCount: z.coerce.number().int(), + teamsAboveCount: z.coerce.number().int(), + }), + }, + responses: { + 200: { + description: "Pit display payload", + content: { "application/json": { schema: z.any() } }, + }, + 400: { description: "Invalid parameters" }, + 500: { description: "Error generating display" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/alliance", + tags: ["Analysis"], + summary: "Alliance analysis for three teams", + request: { + query: z.object({ + teamOne: z.coerce.number().int(), + teamTwo: z.coerce.number().int(), + teamThree: z.coerce.number().int(), + }), + }, + responses: { + 200: { + description: "Alliance composition and metrics", + content: { "application/json": { schema: AllianceResponseSchema } }, + }, + 400: { description: "Invalid parameters" }, + 500: { description: "Internal server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/matchprediction", + tags: ["Analysis"], + summary: "Predict match outcome for two alliances", + request: { + query: z.object({ + red1: z.coerce.number().int(), + red2: z.coerce.number().int(), + red3: z.coerce.number().int(), + blue1: z.coerce.number().int(), + blue2: z.coerce.number().int(), + blue3: z.coerce.number().int(), + }), + }, + responses: { + 200: { + description: "Prediction and alliance details", + content: { + "application/json": { schema: MatchPredictionResponseSchema }, + }, + }, + 400: { description: "Invalid parameters" }, + 401: { description: "Unauthorized" }, + 500: { description: "Internal server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/qualrankingprediction", + tags: ["Analysis"], + summary: "Predict qual ranking for a tournament", + request: { + query: z.object({ + tournamentKey: z.string(), + }), + }, + responses: { + 200: { + description: "Qual ranking prediction", + content: { + "application/json": { schema: z.array(z.any()) }, + }, + }, + 400: { description: "Invalid parameters" }, + 401: { description: "Unauthorized" }, + 500: { description: "Internal server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/picklist", + tags: ["Analysis"], + summary: "Compute picklist rankings for a tournament", + request: { + query: z.object({ + tournamentKey: z.string().optional(), + flags: z.string().optional(), + stage: z.string().optional(), + totalPoints: z.coerce.number().optional(), + autoPoints: z.coerce.number().optional(), + teleopPoints: z.coerce.number().optional(), + driverAbility: z.coerce.number().optional(), + climbResult: z.coerce.number().optional(), + autoClimb: z.coerce.number().optional(), + defenseEffectiveness: z.coerce.number().optional(), + contactDefenseTime: z.coerce.number().optional(), + campingDefenseTime: z.coerce.number().optional(), + totalDefensiveTime: z.coerce.number().optional(), + totalFuelThroughput: z.coerce.number().optional(), + totalFuelFed: z.coerce.number().optional(), + feedingRate: z.coerce.number().optional(), + scoringRate: z.coerce.number().optional(), + estimatedSuccessfulFuelRate: z.coerce.number().optional(), + estimatedTotalFuelScored: z.coerce.number().optional(), + }), + }, + responses: { + 200: { + description: "Picklist ranking results", + content: { + "application/json": { + schema: z.object({ teams: z.array(PicklistEntrySchema) }), + }, + }, + }, + 400: { description: "Invalid parameters" }, + 500: { description: "Internal server error" }, + }, + security: [{ bearerAuth: [] }], + }); +} diff --git a/packages/api/src/legacy/apikey.ts b/packages/api/src/legacy/apikey.ts new file mode 100644 index 000000000..9e0e01efc --- /dev/null +++ b/packages/api/src/legacy/apikey.ts @@ -0,0 +1,100 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; + +export function registerApikeyPaths(registry: OpenAPIRegistry) { + registry.registerPath({ + method: "post", + path: "/v1/manager/apikey", + tags: ["Manager - API Keys"], + summary: "Create a new API key", + description: + "JWT required; API keys (lvt-...) are not permitted for this endpoint.", + request: { query: z.object({ name: z.string() }) }, + responses: { + 200: { + description: "Created", + content: { + "application/json": { schema: z.object({ apiKey: z.string() }) }, + }, + }, + 400: { description: "Invalid request parameters" }, + 401: { description: "Unauthorized" }, + 403: { description: "Forbidden for API key auth" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "delete", + path: "/v1/manager/apikey", + tags: ["Manager - API Keys"], + summary: "Revoke an API key", + description: + "JWT required; API keys (lvt-...) are not permitted for this endpoint.", + request: { query: z.object({ uuid: z.string() }) }, + responses: { + 404: { description: "API key not found" }, + 200: { + description: "Revoked", + content: { "application/json": { schema: z.string() } }, + }, + 400: { description: "Invalid request parameters" }, + 401: { description: "Unauthorized" }, + 403: { description: "Forbidden for API key auth" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "patch", + path: "/v1/manager/apikey", + tags: ["Manager - API Keys"], + summary: "Rename an API key", + description: + "JWT required; API keys (lvt-...) are not permitted for this endpoint.", + request: { query: z.object({ uuid: z.string(), newName: z.string() }) }, + responses: { + 404: { description: "API key not found" }, + 200: { + description: "Renamed", + content: { "application/json": { schema: z.string() } }, + }, + 400: { description: "Invalid request parameters" }, + 401: { description: "Unauthorized" }, + 403: { description: "Forbidden for API key auth" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/apikey", + tags: ["Manager - API Keys"], + summary: "List API keys", + description: "Returns current user's API keys. Accepts JWT or API keys.", + responses: { + 200: { + description: "Keys", + content: { + "application/json": { + schema: z.object({ + apiKeys: z.array( + z.object({ + uuid: z.string(), + name: z.string(), + createdAt: z.string().datetime(), + lastUsed: z.string().datetime().nullable(), + requests: z.number().int(), + user: z.object({ username: z.string().nullable() }), + }), + ), + }), + }, + }, + }, + 401: { description: "Unauthorized" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); +} diff --git a/packages/api/src/legacy/csv.ts b/packages/api/src/legacy/csv.ts new file mode 100644 index 000000000..d498fe684 --- /dev/null +++ b/packages/api/src/legacy/csv.ts @@ -0,0 +1,42 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; + +export function registerCsvPaths(registry: OpenAPIRegistry) { + registry.registerPath({ + method: "get", + path: "/v1/analysis/csvplain", + tags: ["Analysis - CSV"], + summary: "Team CSV", + request: { + query: z.object({ + team: z.coerce.number().int(), + tournamentKey: z.string().optional(), + }), + }, + responses: { + 200: { + description: "CSV", + content: { "text/csv": { schema: z.string() } }, + }, + 400: { description: "Invalid parameters or not enough scouting data" }, + 500: { description: "Internal server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/reportcsv", + tags: ["Analysis - CSV"], + summary: "Report CSV", + request: { query: z.object({ tournamentKey: z.string() }) }, + responses: { + 200: { + description: "CSV", + content: { "text/csv": { schema: z.string() } }, + }, + 400: { description: "Invalid parameters or not enough scouting data" }, + 500: { description: "Internal server error" }, + }, + security: [{ bearerAuth: [] }], + }); +} diff --git a/packages/api/src/legacy/index.ts b/packages/api/src/legacy/index.ts new file mode 100644 index 000000000..caa8ed4be --- /dev/null +++ b/packages/api/src/legacy/index.ts @@ -0,0 +1,5 @@ +export * from "./models.js"; +export { + createLegacyOpenApiDocument, + normalizeLegacyErrorResponses, +} from "./openapi.js"; diff --git a/packages/api/src/legacy/manager.ts b/packages/api/src/legacy/manager.ts new file mode 100644 index 000000000..c1ccbd24c --- /dev/null +++ b/packages/api/src/legacy/manager.ts @@ -0,0 +1,467 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; +import { TeamMatchDataSchema, TeamSchema, TournamentSchema } from "./models.js"; + +export function registerManagerPaths(registry: OpenAPIRegistry) { + const PaginationQuery = z.object({ + take: z.coerce.number().int().optional(), + skip: z.coerce.number().int().optional(), + }); + const MatchTeamSchema = z.object({ + number: z.number().int(), + scouters: z.array(z.object({ name: z.string(), scouted: z.boolean() })), + externalReports: z.number().int(), + }); + const MatchSchema = z.object({ + matchNumber: z.number().int(), + matchType: z.number().int(), + scouted: z.boolean(), + finished: z.boolean(), + team1: MatchTeamSchema, + team2: MatchTeamSchema, + team3: MatchTeamSchema, + team4: MatchTeamSchema, + team5: MatchTeamSchema, + team6: MatchTeamSchema, + }); + const PracticeMatchSchema = z.object({ + matchNumber: z.number().int(), + matchType: z.literal(2), + scouted: z.boolean(), + finished: z.literal(false), + teams: z + .array(MatchTeamSchema) + .describe( + "Publicly scheduled or visibly reported practice teams, sorted by team number; no alliance slots", + ), + }); + const ProfileSchema = z.object({ + id: z.string(), + username: z.string().nullable(), + email: z.string().email(), + role: z.string(), + team: z + .object({ + team: z.object({ + number: z.number().int(), + name: z.string().nullable(), + }), + }) + .nullable(), + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/upcoming-entered-tournaments", + tags: ["Manager - Tournaments"], + summary: + "Next two future Blue Alliance events for the signed-in user's team", + security: [{ bearerAuth: [] }], + responses: { + 200: { + description: "Events in start-date order; week numbers start at one", + }, + 401: { description: "Unauthorized" }, + 502: { description: "Blue Alliance event data unavailable" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/teams", + tags: ["Manager - Teams"], + summary: "List teams with optional pagination and filter", + request: { + query: PaginationQuery.extend({ filter: z.string().optional() }), + }, + responses: { + 200: { + description: "Teams and total count", + content: { + "application/json": { + schema: z.object({ teams: z.array(TeamSchema), count: z.number() }), + }, + }, + }, + 401: { description: "Unauthorized" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/tournaments", + tags: ["Manager - Tournaments"], + summary: "List tournaments with optional pagination and filter", + request: { + query: PaginationQuery.extend({ filter: z.string().optional() }), + }, + responses: { + 200: { + description: "Tournaments and total count", + content: { + "application/json": { + schema: z.object({ + tournaments: z.array(TournamentSchema), + count: z.number(), + }), + }, + }, + }, + 401: { description: "Unauthorized" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/matches/{tournament}", + tags: ["Manager - Matches"], + summary: "List matches for a tournament", + request: { + params: z.object({ tournament: z.string() }), + query: z.object({ + teams: z.string().optional(), + includePractice: z + .enum(["true", "false"]) + .optional() + .describe( + "Defaults to false. When true, append practice matches (matchType 2) with a teams array instead of team1–team6. Official scouting-shift numbering is unchanged.", + ), + }), + }, + responses: { + 200: { + description: "Formatted match list", + content: { + "application/json": { + schema: z.array(z.union([MatchSchema, PracticeMatchSchema])), + }, + }, + }, + 400: { description: "Invalid parameters" }, + 401: { description: "Unauthorized" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/checkmatch", + tags: ["Manager - Matches"], + summary: "Check if a match exists and if a team is in the match", + request: { + query: z.object({ + tournamentKey: z.string(), + teamNumber: z.coerce.number().int(), + matchNumber: z.coerce.number().int(), + isElim: z + .union([z.literal("true"), z.literal("false"), z.boolean()]) + .transform((value) => value === true || value === "true") + .optional() + .describe("Legacy match selector; provide this or matchType."), + matchType: z + .enum(["QUALIFICATION", "ELIMINATION", "PRACTICE"]) + .optional(), + }), + }, + responses: { + 200: { + description: "Match data row and alliance", + content: { + "application/json": { + schema: z.object({ + match: TeamMatchDataSchema, + alliance: z.enum(["red", "blue"]).nullable(), + }), + }, + }, + }, + 400: { description: "Invalid parameters" }, + 404: { description: "Match not found" }, + }, + security: [], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/matchschedule/{tournament}", + tags: ["Manager - Matches"], + summary: + "Fetch public match assignments for Collection, including scheduled practice matches", + request: { + params: z.object({ tournament: z.string().min(1) }), + headers: z.object({ "x-team-code": z.string().min(1) }), + }, + responses: { + 200: { + description: + "Official and publicly scheduled practice assignments, without private scouting data", + content: { + "application/json": { + schema: z.object({ + tournamentKey: z.string(), + matches: z.array( + z.object({ + matchNumber: z.number().int(), + matchType: z.union([ + z.literal(0), + z.literal(1), + z.literal(2), + ]), + teams: z.array( + z.object({ + number: z.number().int(), + alliance: z.enum(["red", "blue"]).nullable(), + }), + ), + }), + ), + }), + }, + }, + }, + 400: { description: "Missing team code or tournament" }, + 401: { description: "Invalid team code" }, + 500: { description: "Unable to fetch schedule" }, + }, + security: [], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/profile", + tags: ["Manager - Account"], + summary: "Get current user profile", + responses: { + 200: { + description: "Profile", + content: { "application/json": { schema: ProfileSchema.nullable() } }, + }, + 401: { description: "Unauthorized" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/users", + tags: ["Manager - Users"], + summary: "List users", + responses: { + 200: { + description: "Users", + content: { + "application/json": { + schema: z.array( + z.object({ + id: z.string(), + email: z.string().email(), + username: z.string().nullable(), + role: z.string(), + }), + ), + }, + }, + }, + 401: { description: "Unauthorized" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "delete", + path: "/v1/manager/user", + tags: ["Manager - Users"], + summary: "Delete the current user", + responses: { + 200: { description: "Deleted" }, + 401: { description: "Unauthorized" }, + 403: { description: "Cannot be performed using an API key" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/upgradeuser", + tags: ["Manager - Users"], + summary: "Upgrade current user to Scouting Lead", + responses: { + 200: { description: "Upgraded" }, + 401: { description: "Unauthorized" }, + 403: { description: "Forbidden" }, + 400: { description: "Invalid request" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/analysts", + tags: ["Manager - Users"], + summary: "List analysts", + responses: { + 200: { + description: "Analysts", + content: { + "application/json": { + schema: z.array( + z.object({ id: z.string(), username: z.string().nullable() }), + ), + }, + }, + }, + 401: { description: "Unauthorized" }, + 403: { description: "Not a scouting lead" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/code", + tags: ["Manager - Teams"], + summary: "Get team code for current user", + responses: { + 200: { + description: "Team code", + content: { + "application/json": { schema: z.object({ code: z.string() }) }, + }, + }, + 401: { description: "Unauthorized" }, + 403: { description: "Not authorized to get the team code" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/dashboard/scoutreport", + tags: ["Manager - Scout Reports"], + summary: "Create scout report from dashboard", + request: { + body: { + content: { + "application/json": { + schema: z.object({ + match: z.number().int(), + team: z.number().int(), + notes: z.string().optional(), + }), + }, + }, + }, + }, + responses: { + 200: { + description: "Created", + content: { + "application/json": { schema: z.object({ uuid: z.string() }) }, + }, + }, + 401: { description: "Unauthorized" }, + 403: { description: "Cannot be performed using an API key" }, + 400: { description: "Invalid request" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/team-tournament-status", + tags: ["Manager - Tournaments"], + summary: "Get status of current team in tournaments", + responses: { + 200: { + description: "Status", + content: { + "application/json": { + schema: z.object({ + tournaments: z.array( + z.object({ + id: z.string(), + code: z.string(), + status: z.string(), + }), + ), + }), + }, + }, + }, + 401: { description: "Unauthorized" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/match-results-page", + tags: ["Manager - Matches"], + summary: "Get match results page data", + responses: { + 200: { + description: "Results", + content: { + "application/json": { + schema: z.object({ matches: z.array(MatchSchema) }), + }, + }, + }, + 401: { description: "Unauthorized" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "put", + path: "/v1/manager/notes/{uuid}", + tags: ["Manager - Notes"], + summary: "Update scout report notes (SCOUTING_LEAD)", + request: { + params: z.object({ uuid: z.string() }), + body: { + content: { + "application/json": { schema: z.object({ note: z.string() }) }, + }, + }, + }, + responses: { + 200: { description: "Note updated" }, + 400: { description: "Invalid request" }, + 401: { description: "Unauthorized" }, + 403: { description: "Not authorized" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/scoutershift/scouters", + tags: ["Manager - Scouters"], + summary: "List scouters for current team", + request: { query: z.object({ archived: z.string().optional() }) }, + responses: { + 200: { + description: "Scouters", + content: { + "application/json": { + schema: z.array( + z.object({ uuid: z.string(), name: z.string().nullable() }), + ), + }, + }, + }, + 401: { description: "Unauthorized" }, + 403: { description: "User not affiliated with a team" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/noteam", + tags: ["Manager - Users"], + summary: "Set current user to ANALYST and remove team", + responses: { + 200: { + description: "Updated", + content: { + "application/json": { + schema: z.object({ + id: z.string(), + role: z.string(), + teamNumber: z.number().nullable(), + }), + }, + }, + }, + 401: { description: "Unauthorized" }, + 403: { description: "Cannot be performed using an API key" }, + }, + security: [{ bearerAuth: [] }], + }); +} diff --git a/apps/server/src/lib/prisma-zod.ts b/packages/api/src/legacy/models.ts similarity index 94% rename from apps/server/src/lib/prisma-zod.ts rename to packages/api/src/legacy/models.ts index f4050b973..3126e6e41 100644 --- a/apps/server/src/lib/prisma-zod.ts +++ b/packages/api/src/legacy/models.ts @@ -199,20 +199,14 @@ export const EmailVerificationRequestSchema = z.object({ teamNumber: z.number().int(), }); -export const SlackWorkspaceSchema = z.object({ +export const SlackWorkspacePublicSchema = z.object({ workspaceId: z.string(), owner: z.number().int(), name: z.string(), - authToken: z.string(), botUserId: z.string(), authUserId: z.string(), }); -// Public schema omitting authToken for API responses -export const SlackWorkspacePublicSchema = SlackWorkspaceSchema.omit({ - authToken: true, -}); - export const SlackSubscriptionSchema = z.object({ subscriptionId: z.string(), channelId: z.string(), @@ -246,16 +240,6 @@ export const UserSchema = z.object({ tournamentSourceRule: DataSourceRuleStringSchema, }); -export const ApiKeySchema = z.object({ - uuid: z.string().uuid(), - keyHash: z.string(), - name: z.string(), - userId: z.string(), - createdAt: z.string().datetime(), - lastUsed: z.string().datetime().optional().nullable(), - requests: z.number().int(), -}); - // Public response schema matching what API endpoints actually return export const ApiKeyResponseSchema = z.object({ uuid: z.string().uuid(), @@ -306,3 +290,9 @@ export function registerPrismaSchemas(registry: OpenAPIRegistry) { registry.register("ApiKey", ApiKeyResponseSchema); registry.register("CachedAnalysis", CachedAnalysisSchema); } + +export const LovatTimestampHeader = z.object({ + "x-timestamp": z.string().openapi({ + description: "Unix timestamp (seconds) used in HMAC signature generation", + }), +}); diff --git a/packages/api/src/legacy/mutablepicklists.ts b/packages/api/src/legacy/mutablepicklists.ts new file mode 100644 index 000000000..4ff333e98 --- /dev/null +++ b/packages/api/src/legacy/mutablepicklists.ts @@ -0,0 +1,139 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; +import { MutablePicklistSchema } from "./models.js"; + +export function registerMutablepicklistsPaths(registry: OpenAPIRegistry) { + const MutablePicklistCreateSchema = z.object({ + name: z.string(), + teams: z.array(z.number().int()), + tournamentKey: z.string().optional(), + }); + const MutablePicklistListItemSchema = z.object({ + uuid: z.string(), + name: z.string(), + tournamentKey: z.string().nullable().optional(), + author: z.object({ username: z.string().nullable().optional() }), + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/mutablepicklists", + tags: ["Manager - Mutable Picklists"], + summary: "Create mutable picklist", + request: { + body: { + content: { + "application/json": { schema: MutablePicklistCreateSchema }, + }, + }, + }, + responses: { + 200: { + description: "Created", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid request" }, + 401: { description: "Unauthorized" }, + 403: { + description: + "Cannot be performed using an API key, or user is not on a team", + }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/mutablepicklists", + tags: ["Manager - Mutable Picklists"], + summary: "List mutable picklists", + responses: { + 200: { + description: "List", + content: { + "application/json": { + schema: z.array(MutablePicklistListItemSchema), + }, + }, + }, + 401: { description: "Unauthorized" }, + 403: { description: "User is not on a team" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/mutablepicklists/{uuid}", + tags: ["Manager - Mutable Picklists"], + summary: "Get mutable picklist", + request: { params: z.object({ uuid: z.string() }) }, + responses: { + 200: { + description: "Detail", + content: { + "application/json": { schema: MutablePicklistSchema.nullable() }, + }, + }, + 400: { description: "Invalid request" }, + 404: { description: "Not found" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "put", + path: "/v1/manager/mutablepicklists/{uuid}", + tags: ["Manager - Mutable Picklists"], + summary: "Update mutable picklist", + request: { + params: z.object({ uuid: z.string() }), + body: { + content: { + "application/json": { + schema: z.object({ + name: z.string(), + teams: z.array(z.number().int()), + }), + }, + }, + }, + }, + responses: { + 200: { + description: "Updated", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid request" }, + 404: { description: "Picklist not found or not on same team" }, + 401: { description: "Unauthorized" }, + 403: { + description: + "Cannot be performed using an API key, or not authorized to update", + }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "delete", + path: "/v1/manager/mutablepicklists/{uuid}", + tags: ["Manager - Mutable Picklists"], + summary: "Delete mutable picklist", + request: { params: z.object({ uuid: z.string() }) }, + responses: { + 200: { + description: "Deleted", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid request" }, + 401: { description: "Unauthorized" }, + 403: { + description: + "Cannot be performed using an API key, or not authorized to delete", + }, + 404: { description: "Not found" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); +} diff --git a/packages/api/src/legacy/onboarding.ts b/packages/api/src/legacy/onboarding.ts new file mode 100644 index 000000000..c390399b8 --- /dev/null +++ b/packages/api/src/legacy/onboarding.ts @@ -0,0 +1,127 @@ +import { LovatTimestampHeader } from "./models.js"; +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; + +export function registerOnboardingPaths(registry: OpenAPIRegistry) { + registry.registerPath({ + method: "post", + path: "/v1/manager/onboarding/verifyemail", + tags: ["Manager - Onboarding"], + summary: "Approve team email (signed)", + request: { + headers: LovatTimestampHeader, + body: { + content: { + "application/json": { schema: z.object({ code: z.string() }) }, + }, + }, + }, + responses: { + 200: { description: "Approved" }, + 400: { description: "Invalid" }, + 403: { description: "Invalid signature" }, + 404: { description: "Code not recognized" }, + 500: { description: "Server error" }, + }, + security: [{ lovatSignature: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/onboarding/username", + tags: ["Manager - Onboarding"], + summary: "Set username", + request: { + body: { + content: { + "application/json": { schema: z.object({ username: z.string() }) }, + }, + }, + }, + responses: { + 200: { description: "Updated" }, + 400: { description: "Invalid" }, + 401: { description: "Unauthorized" }, + 403: { description: "Cannot be performed using an API key" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/onboarding/teamcode", + tags: ["Manager - Onboarding"], + summary: "Check team code", + request: { query: z.object({ team: z.string(), code: z.string() }) }, + responses: { + 200: { description: "Valid" }, + 400: { description: "Invalid" }, + 401: { description: "Unauthorized" }, + 403: { description: "Cannot be performed using an API key" }, + 404: { description: "Team/code not found" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/onboarding/team", + tags: ["Manager - Onboarding"], + summary: "Add registered team", + request: { + body: { + content: { + "application/json": { + schema: z.object({ + number: z.number().int(), + name: z.string().optional(), + }), + }, + }, + }, + }, + responses: { + 200: { description: "Added" }, + 400: { description: "Invalid" }, + 401: { description: "Unauthorized" }, + 403: { description: "Cannot be performed using an API key" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/onboarding/teamwebsite", + tags: ["Manager - Onboarding"], + summary: "Add team website", + request: { + body: { + content: { + "application/json": { schema: z.object({ website: z.string() }) }, + }, + }, + }, + responses: { + 200: { description: "Added" }, + 400: { description: "Invalid" }, + 401: { description: "Unauthorized" }, + 403: { description: "Cannot be performed using an API key" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/onboarding/resendverificationemail", + tags: ["Manager - Onboarding"], + summary: "Resend verification email", + responses: { + 200: { description: "Sent" }, + 401: { description: "Unauthorized" }, + 403: { description: "Cannot be performed using an API key" }, + 404: { description: "Team not found" }, + 429: { description: "Rate limited" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); +} diff --git a/packages/api/src/legacy/openapi.ts b/packages/api/src/legacy/openapi.ts new file mode 100644 index 000000000..3f00156a5 --- /dev/null +++ b/packages/api/src/legacy/openapi.ts @@ -0,0 +1,165 @@ +import { + OpenAPIRegistry, + OpenApiGeneratorV31, + extendZodWithOpenApi, +} from "@asteasolutions/zod-to-openapi"; +import { z } from "zod"; +import { apiErrorSchema } from "../errors.js"; + +// Enable .openapi() on Zod types +extendZodWithOpenApi(z); + +import { registerPrismaSchemas } from "./models.js"; +import { registerAnalysisPaths } from "./analysis.js"; +import { registerCsvPaths } from "./csv.js"; +import { registerScoutreportPaths } from "./scoutreport.js"; +import { registerTeamLookupPaths } from "./teamLookup.js"; +import { registerApikeyPaths } from "./apikey.js"; +import { registerManagerPaths } from "./manager.js"; +import { registerMutablepicklistsPaths } from "./mutablepicklists.js"; +import { registerOnboardingPaths } from "./onboarding.js"; +import { registerPicklistsPaths } from "./picklists.js"; +import { registerRegisteredteamsPaths } from "./registeredteams.js"; +import { registerScoutersPaths } from "./scouters.js"; +import { registerScoutershiftsPaths } from "./scoutershifts.js"; +import { registerScoutreportsPaths } from "./scoutreports.js"; +import { registerSettingsPaths } from "./settings.js"; +import { registerTournamentsPaths } from "./tournaments.js"; +import { registerSlackPaths } from "./slack.js"; + +export function createLegacyOpenApiDocument(options: { + version: string; + baseUrl: string; +}) { + const registry = new OpenAPIRegistry(); + + registry.register("ApiError", z.object(apiErrorSchema.shape)); + + const apiErrorContent = { + "application/json": { schema: { $ref: "#/components/schemas/ApiError" } }, + }; + + registry.registerComponent("responses", "ApiErrorResponse", { + description: + "Request failed. The HTTP status describes the failure category; code identifies the error. Unexpected server failures use INTERNAL_SERVER_ERROR and a generic message.", + content: apiErrorContent, + }); + + // Import and register Prisma-derived schemas + registerPrismaSchemas(registry); + + // Register security schemes + registry.registerComponent("securitySchemes", "bearerAuth", { + type: "http", + scheme: "bearer", + description: + "Accepts either a JWT token from Auth0 or an API key (prefixed with 'lvt-'). " + + "Use format: Authorization: Bearer ", + }); + registry.registerComponent("securitySchemes", "slackToken", { + type: "apiKey", + in: "header", + name: "x-slack-signature", + description: + "Slack signature header (requires accompanying x-slack-request-timestamp)", + }); + registry.registerComponent("securitySchemes", "lovatSignature", { + type: "apiKey", + in: "header", + name: "x-signature", + description: "HMAC signature header (requires accompanying x-timestamp)", + }); + + // Minimal example: document the /status health check route + registry.registerPath({ + method: "get", + path: "/status", + summary: "Health check", + description: "Returns a simple message indicating the server is running.", + responses: { + 200: { + description: "Server is running", + content: { + "text/plain": { + schema: z.string().openapi({ example: "Server running" }), + }, + }, + }, + }, + }); + + registerAnalysisPaths(registry); + registerCsvPaths(registry); + registerScoutreportPaths(registry); + registerTeamLookupPaths(registry); + registerApikeyPaths(registry); + registerManagerPaths(registry); + registerMutablepicklistsPaths(registry); + registerOnboardingPaths(registry); + registerPicklistsPaths(registry); + registerRegisteredteamsPaths(registry); + registerScoutersPaths(registry); + registerScoutershiftsPaths(registry); + registerScoutreportsPaths(registry); + registerSettingsPaths(registry); + registerTournamentsPaths(registry); + registerSlackPaths(registry); + + const generator = new OpenApiGeneratorV31(registry.definitions); + const document = generator.generateDocument({ + openapi: "3.1.0", + info: { + title: "Lovat API", + version: options.version, + description: + "API Documentation for Lovat, a scouting system used to scout teams and matches in the First Robotics Competition. Clients request the shared format using X-Lovat-Error-Format: json-v1. Without that header, direct guard responses retain their legacy formats for installed clients; unexpected failures are still sanitized. Negotiated HTTP error responses (400–599) use application/json and the ApiError schema. message and displayError contain the same safe text. invalidFields and retryAfterSeconds appear only when applicable. Authentication, validation, missing resources, rate limits and unexpected failures share this format. Success responses, including legacy domain messages returned with status 200, retain their documented shapes. Internal exception details and submitted values are not part of the error response.", + }, + servers: [{ url: options.baseUrl }], + }); + + return normalizeLegacyErrorResponses(document); +} + +export function normalizeLegacyErrorResponses( + document: ReturnType, +) { + const apiErrorContent = { + "application/json": { schema: { $ref: "#/components/schemas/ApiError" } }, + }; + // Keep each endpoint's status descriptions and headers while documenting the + // response contract enforced by errorResponses and errorHandler. + for (const path of Object.values(document.paths ?? {})) { + if (!path) { + continue; + } + for (const method of [ + "get", + "post", + "put", + "patch", + "delete", + "options", + "head", + "trace", + ] as const) { + const operation = path[method]; + if (!operation) { + continue; + } + operation.responses ??= {}; + for (const [status, response] of Object.entries(operation.responses)) { + if ( + /^[45](?:\d{2}|XX)$/.test(status) && + response && + !("$ref" in response) + ) { + response.content = apiErrorContent; + } + } + operation.responses.default ??= { + $ref: "#/components/responses/ApiErrorResponse", + }; + } + } + return document; +} diff --git a/packages/api/src/legacy/picklists.ts b/packages/api/src/legacy/picklists.ts new file mode 100644 index 000000000..f54831842 --- /dev/null +++ b/packages/api/src/legacy/picklists.ts @@ -0,0 +1,166 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; + +export function registerPicklistsPaths(registry: OpenAPIRegistry) { + const PicklistCreateBodySchema = z.object({ + name: z.string(), + totalPoints: z.number().default(0).optional(), + autoPoints: z.number().default(0).optional(), + teleopPoints: z.number().default(0).optional(), + climbResult: z.number().default(0).optional(), + autoClimb: z.number().default(0).optional(), + defenseEffectiveness: z.number().default(0).optional(), + contactDefenseTime: z.number().default(0).optional(), + campingDefenseTime: z.number().default(0).optional(), + totalDefensiveTime: z.number().default(0).optional(), + totalFuelThroughput: z.number().default(0).optional(), + totalFuelFed: z.number().default(0).optional(), + feedingRate: z.number().default(0).optional(), + scoringRate: z.number().default(0).optional(), + estimatedSuccessfulFuelRate: z.number().default(0).optional(), + estimatedTotalFuelScored: z.number().default(0).optional(), + driverAbility: z.number().default(0).optional(), + }); + const PicklistSummarySchema = z.object({ + name: z.string(), + uuid: z.string(), + author: z.object({ username: z.string().nullable().optional() }), + }); + const PicklistDetailSchema = z.object({ + uuid: z.string(), + name: z.string(), + authorId: z.string(), + driverAbility: z.number(), + totalPoints: z.number(), + autoPoints: z.number(), + teleopPoints: z.number(), + climbResult: z.number(), + autoClimb: z.number(), + defenseEffectiveness: z.number(), + contactDefenseTime: z.number(), + campingDefenseTime: z.number(), + totalDefensiveTime: z.number(), + totalFuelThroughput: z.number(), + totalFuelFed: z.number(), + feedingRate: z.number(), + scoringRate: z.number(), + estimatedSuccessfulFuelRate: z.number(), + estimatedTotalFuelScored: z.number(), + }); + const PicklistUpdateBodySchema = PicklistCreateBodySchema; + registry.registerPath({ + method: "post", + path: "/v1/manager/picklists", + tags: ["Manager - Picklists"], + summary: "Create shared picklist", + request: { + body: { + content: { + "application/json": { schema: PicklistCreateBodySchema }, + }, + required: true, + }, + }, + responses: { + 200: { + description: "Picklist created", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid body" }, + 401: { description: "Unauthorized" }, + 403: { + description: + "Cannot be performed using an API key, or user is not on a team", + }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/picklists", + tags: ["Manager - Picklists"], + summary: "List picklists by team", + responses: { + 200: { + description: "List of picklists", + content: { + "application/json": { schema: z.array(PicklistSummarySchema) }, + }, + }, + 401: { description: "Unauthorized" }, + 403: { description: "User is not on a team" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/picklists/{uuid}", + tags: ["Manager - Picklists"], + summary: "Get picklist by UUID", + request: { + params: z.object({ uuid: z.string() }), + }, + responses: { + 200: { + description: "Picklist detail", + content: { "application/json": { schema: PicklistDetailSchema } }, + }, + 400: { description: "Invalid UUID" }, + 401: { description: "Unauthorized" }, + 404: { description: "Picklist not found or not on same team" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "put", + path: "/v1/manager/picklists/{uuid}", + tags: ["Manager - Picklists"], + summary: "Update picklist", + request: { + params: z.object({ uuid: z.string() }), + body: { + content: { "application/json": { schema: PicklistUpdateBodySchema } }, + }, + }, + responses: { + 200: { + description: "Picklist updated", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid input" }, + 404: { description: "Picklist not found or not on same team" }, + 401: { description: "Unauthorized" }, + 403: { + description: + "Cannot be performed using an API key, or not authorized to update", + }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "delete", + path: "/v1/manager/picklists/{uuid}", + tags: ["Manager - Picklists"], + summary: "Delete picklist", + request: { params: z.object({ uuid: z.string() }) }, + responses: { + 200: { + description: "Deleted", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid UUID" }, + 401: { description: "Unauthorized" }, + 403: { + description: + "Cannot be performed using an API key, or unauthorized to delete this picklist", + }, + 404: { description: "Not found" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); +} diff --git a/packages/api/src/legacy/registeredteams.ts b/packages/api/src/legacy/registeredteams.ts new file mode 100644 index 000000000..2d41adc06 --- /dev/null +++ b/packages/api/src/legacy/registeredteams.ts @@ -0,0 +1,80 @@ +import { LovatTimestampHeader } from "./models.js"; +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; +import { RegisteredTeamSchema } from "./models.js"; + +export function registerRegisteredteamsPaths(registry: OpenAPIRegistry) { + const TeamParamSchema = z.object({ team: z.string() }); + const RegistrationStatusSchema = z.discriminatedUnion("status", [ + z.object({ status: z.literal("NOT_STARTED") }), + z.object({ + status: z.literal("PENDING_EMAIL_VERIFICATION"), + email: z.string(), + }), + z.object({ status: z.literal("PENDING_WEBSITE") }), + z.object({ + status: z.literal("PENDING_TEAM_VERIFICATION"), + teamEmail: z.string(), + }), + z.object({ status: z.literal("REGISTERED_ON_TEAM") }), + z.object({ status: z.literal("REGISTERED_OFF_TEAM") }), + z.object({ status: z.literal("PENDING") }), + ]); + registry.registerPath({ + method: "get", + path: "/v1/manager/registeredteams/{team}/registrationstatus", + tags: ["Manager - Registered Teams"], + summary: "Check team registration status", + request: { params: TeamParamSchema }, + responses: { + 200: { + description: "Registration status", + content: { "application/json": { schema: RegistrationStatusSchema } }, + }, + 400: { description: "Invalid team" }, + 401: { description: "Unauthorized" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/registeredteams/{team}/approve", + tags: ["Manager - Registered Teams"], + summary: "Approve team", + description: + "Requires `x-signature` and `x-timestamp` headers. Signs request body, method, path.", + request: { params: TeamParamSchema, headers: LovatTimestampHeader }, + responses: { + 200: { + description: "Approved registered team row", + content: { "application/json": { schema: RegisteredTeamSchema } }, + }, + 400: { description: "Invalid team" }, + 401: { description: "Unauthorized or signature expired" }, + 403: { description: "Invalid signature" }, + 500: { description: "Server error" }, + }, + security: [{ lovatSignature: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/registeredteams/{team}/reject", + tags: ["Manager - Registered Teams"], + summary: "Reject team", + description: + "Requires `x-signature` and `x-timestamp` headers. Signs request body, method, path.", + request: { params: TeamParamSchema, headers: LovatTimestampHeader }, + responses: { + 200: { + description: "Rejection message", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid team" }, + 401: { description: "Unauthorized or signature expired" }, + 403: { description: "Invalid signature" }, + 500: { description: "Server error" }, + }, + security: [{ lovatSignature: [] }], + }); +} diff --git a/packages/api/src/legacy/scouters.ts b/packages/api/src/legacy/scouters.ts new file mode 100644 index 000000000..8f0f69116 --- /dev/null +++ b/packages/api/src/legacy/scouters.ts @@ -0,0 +1,271 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; +import { ScouterSchema } from "./models.js"; + +export function registerScoutersPaths(registry: OpenAPIRegistry) { + registry.registerPath({ + method: "post", + path: "/v1/manager/emailTeamCode", + tags: ["Manager - Scouters (Public)"], + summary: "Email team code to registered address", + request: { query: z.object({ teamNumber: z.number().int() }) }, + responses: { + 200: { + description: "Email sent", + content: { + "application/json": { + schema: z.object({ email: z.string().email() }), + }, + }, + }, + 400: { description: "Invalid request" }, + 500: { description: "Server error" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/scouter/checkcode", + tags: ["Manager - Scouters (Public)"], + summary: "Check team code", + request: { query: z.object({ code: z.string() }) }, + responses: { + 200: { + description: "Valid or team row", + content: { "application/json": { schema: z.any() } }, + }, + 400: { description: "Invalid request" }, + 500: { description: "Server error" }, + }, + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/name/uuid/{uuid}", + tags: ["Manager - Scouters (Public)"], + summary: "Change scouter name by UUID", + request: { + params: z.object({ uuid: z.string() }), + body: { + content: { + "application/json": { schema: z.object({ name: z.string() }) }, + }, + }, + }, + responses: { + 200: { description: "Updated" }, + 400: { description: "Invalid request" }, + 500: { description: "Server error" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/scouters", + tags: ["Manager - Scouters (Public)"], + summary: "List active scouters for team code", + request: { headers: z.object({ "x-team-code": z.string() }) }, + responses: { + 200: { + description: "Scouters", + content: { "application/json": { schema: z.array(ScouterSchema) } }, + }, + 400: { description: "Invalid request" }, + 404: { description: "Team code not found" }, + 500: { description: "Server error" }, + }, + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/scouter", + tags: ["Manager - Scouters (Public)"], + summary: "Create scouter", + request: { + body: { + content: { + "application/json": { + schema: z.object({ + teamNumber: z.number().int(), + name: z.string(), + }), + }, + }, + }, + }, + responses: { + 200: { + description: "Created", + content: { "application/json": { schema: z.any() } }, + }, + 400: { description: "Invalid request" }, + 500: { description: "Server error" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/scouters/{uuid}/tournaments", + tags: ["Manager - Scouters (Public)"], + summary: "List tournaments", + request: { params: z.object({ uuid: z.string() }) }, + responses: { + 200: { + description: "Tournaments", + content: { "application/json": { schema: z.array(z.any()) } }, + }, + 500: { description: "Server error" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/scouterschedules/{tournament}", + tags: ["Manager - Scouters (Public)"], + summary: "Get scouter schedule", + request: { + params: z.object({ tournament: z.string() }), + headers: z.object({ "x-team-code": z.string() }), + }, + responses: { + 200: { + description: "Schedule", + content: { "application/json": { schema: z.any() } }, + }, + 400: { description: "Invalid request" }, + 500: { description: "Server error" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/scouter/tournaments", + tags: ["Manager - Scouters (Public)"], + summary: "List scouter tournaments with schedule", + request: { headers: z.object({ "x-team-code": z.string() }) }, + responses: { + 200: { + description: "Tournaments", + content: { "application/json": { schema: z.array(z.any()) } }, + }, + 400: { description: "Invalid request" }, + 500: { description: "Server error" }, + }, + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/unarchive/uuid/{uuid}", + tags: ["Manager - Scouters"], + summary: "Unarchive scouter", + request: { params: z.object({ uuid: z.string() }) }, + responses: { + 200: { description: "Unarchived" }, + 401: { description: "Unauthorized" }, + 403: { description: "Forbidden" }, + 404: { description: "Not found" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/archive/uuid/{uuid}", + tags: ["Manager - Scouters"], + summary: "Archive scouter", + request: { params: z.object({ uuid: z.string() }) }, + responses: { + 200: { description: "Archived" }, + 401: { description: "Unauthorized" }, + 403: { description: "Forbidden" }, + 404: { description: "Not found" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "put", + path: "/v1/manager/scoutername", + tags: ["Manager - Scouters"], + summary: "Update scouter name", + request: { + body: { + content: { + "application/json": { + schema: z.object({ uuid: z.string().optional(), name: z.string() }), + }, + }, + }, + }, + responses: { + 200: { description: "Updated" }, + 400: { description: "Invalid request" }, + 401: { description: "Unauthorized" }, + 403: { description: "Forbidden" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "delete", + path: "/v1/manager/scouterdashboard", + tags: ["Manager - Scouters"], + summary: "Delete scouter from dashboard", + responses: { + 200: { description: "Deleted" }, + 401: { description: "Unauthorized" }, + 403: { description: "Forbidden" }, + 404: { description: "Not found" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/scouterspage", + tags: ["Manager - Scouters"], + summary: "Scouting lead progress page", + responses: { + 200: { + description: "Page data", + content: { "application/json": { schema: z.any() } }, + }, + 401: { description: "Unauthorized" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/scouterdashboard", + tags: ["Manager - Scouters"], + summary: "Add scouter on dashboard", + request: { + body: { + content: { + "application/json": { + schema: z.object({ + scouterId: z.string(), + tournament: z.string().optional(), + }), + }, + }, + }, + }, + responses: { + 200: { description: "Created" }, + 400: { description: "Invalid request" }, + 401: { description: "Unauthorized" }, + 403: { description: "Forbidden" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/scouterreports", + tags: ["Manager - Scouters"], + summary: "List scouter reports", + responses: { + 200: { + description: "Reports", + content: { "application/json": { schema: z.any() } }, + }, + 401: { description: "Unauthorized" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); +} diff --git a/packages/api/src/legacy/scoutershifts.ts b/packages/api/src/legacy/scoutershifts.ts new file mode 100644 index 000000000..1f6af59da --- /dev/null +++ b/packages/api/src/legacy/scoutershifts.ts @@ -0,0 +1,54 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; + +export function registerScoutershiftsPaths(registry: OpenAPIRegistry) { + const ScouterShiftUpdateSchema = z.object({ + startMatchOrdinalNumber: z.number().int(), + endMatchOrdinalNumber: z.number().int(), + team1: z.array(z.string()), + team2: z.array(z.string()), + team3: z.array(z.string()), + team4: z.array(z.string()), + team5: z.array(z.string()), + team6: z.array(z.string()), + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/scoutershifts/{uuid}", + tags: ["Manager - Scouter Shifts"], + summary: "Update scouter shift", + request: { + params: z.object({ uuid: z.string() }), + body: { + content: { "application/json": { schema: ScouterShiftUpdateSchema } }, + }, + }, + responses: { + 200: { description: "Updated" }, + 400: { description: "Invalid request" }, + 401: { description: "Unauthorized" }, + 403: { + description: + "Cannot be performed using an API key, or not a scouting lead", + }, + 404: { description: "Shift not found" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "delete", + path: "/v1/manager/scoutershifts/{uuid}", + tags: ["Manager - Scouter Shifts"], + summary: "Delete scouter shift", + request: { params: z.object({ uuid: z.string() }) }, + responses: { + 200: { description: "Deleted" }, + 401: { description: "Unauthorized" }, + 403: { description: "Forbidden" }, + 404: { description: "Not found" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); +} diff --git a/packages/api/src/legacy/scoutreport.ts b/packages/api/src/legacy/scoutreport.ts new file mode 100644 index 000000000..9e2c67df7 --- /dev/null +++ b/packages/api/src/legacy/scoutreport.ts @@ -0,0 +1,61 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; + +export function registerScoutreportPaths(registry: OpenAPIRegistry) { + registry.registerPath({ + method: "get", + path: "/v1/analysis/metrics/scoutreport/{uuid}", + security: [{ bearerAuth: [] }], + tags: ["Analysis - Scout Report"], + summary: "Metrics for specific scout report", + request: { params: z.object({ uuid: z.string() }) }, + responses: { + 200: { + description: "Metrics", + content: { + "application/json": { schema: z.record(z.string(), z.any()) }, + }, + }, + 400: { description: "Invalid parameters" }, + 500: { description: "Internal server error" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/scoutreports/match/{match}", + security: [{ bearerAuth: [] }], + tags: ["Analysis - Scout Report"], + summary: "All scout reports for a match", + request: { params: z.object({ match: z.coerce.number().int() }) }, + responses: { + 200: { + description: "Reports", + content: { + "application/json": { + schema: z.array(z.record(z.string(), z.any())), + }, + }, + }, + 400: { description: "Invalid parameters" }, + 500: { description: "Internal server error or not authorized" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/timeline/scoutreport/{uuid}", + security: [{ bearerAuth: [] }], + tags: ["Analysis - Scout Report"], + summary: "Timeline data for scout report", + request: { params: z.object({ uuid: z.string() }) }, + responses: { + 200: { + description: "Timeline", + content: { + "application/json": { schema: z.record(z.string(), z.any()) }, + }, + }, + 400: { description: "Invalid parameters" }, + 500: { description: "Internal server error" }, + }, + }); +} diff --git a/packages/api/src/legacy/scoutreports.ts b/packages/api/src/legacy/scoutreports.ts new file mode 100644 index 000000000..4e9030722 --- /dev/null +++ b/packages/api/src/legacy/scoutreports.ts @@ -0,0 +1,139 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; +import { + EventSchema, + ScoutReportSchema as PrismaScoutReportSchema, +} from "./models.js"; + +export function registerScoutreportsPaths(registry: OpenAPIRegistry) { + const ScoutReportCreateSchema = z.object({ + uuid: z.string(), + tournamentKey: z.string(), + matchType: z.enum(["QUALIFICATION", "ELIMINATION", "PRACTICE"]), + matchNumber: z.number().int(), + startTime: z.number().int(), + notes: z.string(), + robotRoles: z.array( + z.enum(["CYCLING", "SCORING", "FEEDING", "DEFENDING", "IMMOBILE"]), + ), + mobility: z.enum(["TRENCH", "BUMP", "BOTH", "NONE"]), + climbPosition: z.enum(["SIDE", "MIDDLE"]).optional(), + climbSide: z.enum(["FRONT", "BACK"]).optional(), + beached: z.enum(["ON_FUEL", "ON_BUMP", "BOTH", "NEITHER"]), + feederTypes: z.array(z.enum(["CONTINUOUS", "STOP_TO_SHOOT", "DUMP"])), + intakeType: z.enum(["GROUND", "OUTPOST", "BOTH", "NEITHER"]), + robotBrokeDescription: z.string().nullable().optional(), + driverAbility: z.number().int(), + accuracy: z.number().int().optional(), + disrupts: z.boolean(), + defenseEffectiveness: z.number().int(), + scoresWhileMoving: z.boolean(), + autoClimb: z.enum(["NOT_ATTEMPTED", "FAILED", "SUCCEEDED"]), + endgameClimb: z.enum(["NOT_ATTEMPTED", "FAILED", "L1", "L2", "L3"]), + scouterUuid: z.string(), + teamNumber: z.number().int(), + events: z.array( + z.tuple([ + z.number().int(), // time + z.number().int(), // action index + z.number().int(), // position index + z.number().int().optional(), // points/quantity (optional) + ]), + ), + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/scoutreports", + tags: ["Manager - Scout Reports"], + summary: "Create scout report", + request: { + body: { + content: { "application/json": { schema: ScoutReportCreateSchema } }, + }, + }, + responses: { + 200: { + description: "Created", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid request" }, + 404: { description: "Match not found" }, + 500: { description: "Server error" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/scoutreports/{uuid}", + security: [{ bearerAuth: [] }], + tags: ["Manager - Scout Reports"], + summary: "Get scout report", + request: { params: z.object({ uuid: z.string() }) }, + responses: { + 200: { + description: "Scout report and events", + content: { + "application/json": { + schema: z.object({ + scoutReport: PrismaScoutReportSchema, + events: z.array(EventSchema), + }), + }, + }, + }, + 400: { description: "Invalid request" }, + 404: { description: "Not found" }, + 500: { description: "Server error" }, + }, + }); + registry.registerPath({ + method: "delete", + path: "/v1/manager/scoutreports/{uuid}", + security: [{ bearerAuth: [] }], + tags: ["Manager - Scout Reports"], + summary: "Delete scout report", + request: { params: z.object({ uuid: z.string() }) }, + responses: { + 200: { + description: "Deleted", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid request" }, + 403: { description: "Forbidden" }, + 404: { description: "Not found" }, + 500: { description: "Server error" }, + }, + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/scoutreports/setflag/{report}", + security: [{ bearerAuth: [] }], + tags: ["Manager - Scout Reports"], + summary: "Set or remove your flag on a scout report", + request: { + params: z.object({ + report: z.string().min(1), + }), + query: z.object({ + flag: z.enum(["true", "false"]), + }), + }, + responses: { + 200: { + description: "Flag updated", + content: { + "application/json": { + schema: z.object({ + flagged: z.boolean(), + flagCount: z.number().int().nonnegative(), + }), + }, + }, + }, + 400: { description: "Invalid report parameter or flag value" }, + 401: { description: "Authentication required or no team assigned" }, + 403: { description: "Team is not verified" }, + 404: { description: "Report not found or outside allowed sources" }, + 500: { description: "Server error" }, + }, + }); +} diff --git a/packages/api/src/legacy/settings.ts b/packages/api/src/legacy/settings.ts new file mode 100644 index 000000000..1d3ae17c9 --- /dev/null +++ b/packages/api/src/legacy/settings.ts @@ -0,0 +1,165 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; + +export function registerSettingsPaths(registry: OpenAPIRegistry) { + registry.registerPath({ + method: "put", + path: "/v1/manager/settings", + tags: ["Manager - Settings"], + summary: "Update sources", + request: { + body: { + content: { + "application/json": { + schema: z.object({ + teamSource: z.array(z.number().int()), + tournamentSource: z.array(z.string()), + }), + }, + }, + }, + }, + responses: { + 200: { + description: "Updated", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid request" }, + 401: { description: "Unauthorized" }, + 403: { description: "Cannot be performed using an API key" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/settings/teamsource", + tags: ["Manager - Settings"], + summary: "Get team source", + responses: { + 200: { + description: "Team source", + content: { + "application/json": { + schema: z.union([ + z.literal("THIS_TEAM"), + z.literal("ALL_TEAMS"), + z.array(z.number().int()), + ]), + }, + }, + }, + 401: { description: "Unauthorized" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/settings/teamsource", + tags: ["Manager - Settings"], + summary: "Add team source", + request: { + body: { + content: { + "application/json": { + schema: z.union([ + z.object({ mode: z.literal("ALL_TEAMS") }), + z.object({ mode: z.literal("THIS_TEAM") }), + z.object({ teams: z.array(z.number().int()) }), + ]), + }, + }, + }, + }, + responses: { + 200: { + description: "Added", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid request" }, + 401: { description: "Unauthorized" }, + 403: { description: "Not affiliated with a team" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/settings/tournamentsource", + tags: ["Manager - Settings"], + summary: "Get tournament source", + responses: { + 200: { + description: "Tournament source", + content: { "application/json": { schema: z.array(z.string()) } }, + }, + 401: { description: "Unauthorized" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/settings/tournamentsource", + tags: ["Manager - Settings"], + summary: "Add tournament source", + request: { + body: { + content: { + "application/json": { + schema: z.object({ tournaments: z.array(z.string()) }), + }, + }, + }, + }, + responses: { + 200: { + description: "Added", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid request" }, + 401: { description: "Unauthorized" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/settings/teamemail", + tags: ["Manager - Settings"], + summary: "Get team email", + responses: { + 200: { + description: "Team email", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid request" }, + 401: { description: "Unauthorized" }, + 403: { description: "Forbidden" }, + 404: { description: "Team not found" }, + 429: { description: "Rate limited" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "put", + path: "/v1/manager/settings/teamemail", + tags: ["Manager - Settings"], + summary: "Update team email", + request: { query: z.object({ email: z.string().email() }) }, + responses: { + 200: { + description: "Verification sent", + content: { "text/plain": { schema: z.string() } }, + }, + 400: { description: "Invalid request" }, + 401: { description: "Unauthorized" }, + 404: { description: "Team not found" }, + 429: { description: "Rate limited" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); +} diff --git a/packages/api/src/legacy/slack.ts b/packages/api/src/legacy/slack.ts new file mode 100644 index 000000000..b7bd46d26 --- /dev/null +++ b/packages/api/src/legacy/slack.ts @@ -0,0 +1,53 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; + +export function registerSlackPaths(registry: OpenAPIRegistry) { + registry.registerPath({ + method: "get", + path: "/v1/slack/add-workspace", + tags: ["Slack"], + summary: "Add Slack workspace (OAuth flow)", + responses: { 200: { description: "Redirect or JSON" } }, + security: [{ slackToken: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/slack/command", + tags: ["Slack"], + summary: "Slack slash command", + request: { + body: { + content: { + "application/x-www-form-urlencoded": { + schema: z.object({ + command: z.string(), + text: z.string().optional(), + }), + }, + }, + }, + }, + responses: { 200: { description: "Processed" } }, + security: [{ slackToken: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/slack/event", + tags: ["Slack"], + summary: "Slack event callback", + request: { + body: { + content: { + "application/json": { + schema: z.object({ + type: z.string(), + event: z.record(z.string(), z.any()), + }), + }, + }, + }, + }, + responses: { 200: { description: "Processed" } }, + security: [{ slackToken: [] }], + }); +} diff --git a/packages/api/src/legacy/teamLookup.ts b/packages/api/src/legacy/teamLookup.ts new file mode 100644 index 000000000..9c04996e0 --- /dev/null +++ b/packages/api/src/legacy/teamLookup.ts @@ -0,0 +1,120 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; + +export function registerTeamLookupPaths(registry: OpenAPIRegistry) { + const TeamParam = z.object({ team: z.string() }); + const MetricTeamParam = z.object({ metric: z.string(), team: z.string() }); + const BreakdownParam = z.object({ team: z.string(), breakdown: z.string() }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/metric/{metric}/team/{team}", + security: [{ bearerAuth: [] }], + tags: ["Analysis - Team Lookup"], + summary: "Metric details for team", + request: { params: MetricTeamParam }, + responses: { + 200: { + description: "Details", + content: { + "application/json": { schema: z.record(z.string(), z.any()) }, + }, + }, + 400: { description: "Invalid parameters" }, + 500: { description: "Internal server error" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/category/team/{team}", + security: [{ bearerAuth: [] }], + tags: ["Analysis - Team Lookup"], + summary: "Category metrics for team", + request: { params: TeamParam }, + responses: { + 200: { + description: "Categories", + content: { + "application/json": { schema: z.record(z.string(), z.any()) }, + }, + }, + 400: { description: "Invalid parameters" }, + 500: { description: "Internal server error" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/breakdown/team/{team}", + security: [{ bearerAuth: [] }], + tags: ["Analysis - Team Lookup"], + summary: "Breakdown metrics for team", + request: { params: TeamParam }, + responses: { + 200: { + description: "Breakdown", + content: { + "application/json": { schema: z.record(z.string(), z.any()) }, + }, + }, + 400: { description: "Invalid parameters" }, + 500: { description: "Internal server error" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/breakdown/team/{team}/{breakdown}", + security: [{ bearerAuth: [] }], + tags: ["Analysis - Team Lookup"], + summary: "Specific breakdown details", + request: { params: BreakdownParam }, + responses: { + 200: { + description: "Details", + content: { + "application/json": { schema: z.record(z.string(), z.any()) }, + }, + }, + 400: { description: "Invalid parameters" }, + 500: { description: "Internal server error" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/notes/team/{team}", + security: [{ bearerAuth: [] }], + tags: ["Analysis - Team Lookup"], + summary: "Notes for team", + request: { params: TeamParam }, + responses: { + 200: { + description: "Notes", + content: { + "application/json": { + schema: z.array(z.object({ note: z.string() })), + }, + }, + }, + 400: { description: "Invalid parameters" }, + 500: { description: "Internal server error" }, + }, + }); + registry.registerPath({ + method: "get", + path: "/v1/analysis/flag/team/{team}", + security: [{ bearerAuth: [] }], + tags: ["Analysis - Team Lookup"], + summary: "Flags for team", + request: { params: TeamParam }, + responses: { + 200: { + description: "Flags", + content: { + "application/json": { + schema: z.array(z.object({ flag: z.string() })), + }, + }, + }, + 400: { description: "Invalid parameters" }, + 500: { description: "Internal server error" }, + }, + }); +} diff --git a/packages/api/src/legacy/tournaments.ts b/packages/api/src/legacy/tournaments.ts new file mode 100644 index 000000000..0489c58b4 --- /dev/null +++ b/packages/api/src/legacy/tournaments.ts @@ -0,0 +1,125 @@ +import { z } from "zod"; +import type { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi"; +import { TeamSchema, ScouterScheduleShiftSchema } from "./models.js"; + +export function registerTournamentsPaths(registry: OpenAPIRegistry) { + const TournamentParamSchema = z.object({ tournament: z.string() }); + const ScouterTeamRelationSchema = z + .object({ name: z.string().nullable(), uuid: z.string() }) + .nullable(); + const ScouterScheduleShiftWithTeamsSchema = ScouterScheduleShiftSchema.extend( + { + team1: ScouterTeamRelationSchema, + team2: ScouterTeamRelationSchema, + team3: ScouterTeamRelationSchema, + team4: ScouterTeamRelationSchema, + team5: ScouterTeamRelationSchema, + team6: ScouterTeamRelationSchema, + }, + ); + registry.registerPath({ + method: "get", + path: "/v1/manager/tournament/{tournament}/teams", + tags: ["Manager - Tournaments"], + summary: "List teams in tournament", + request: { params: TournamentParamSchema }, + responses: { + 200: { + description: "Teams", + content: { "application/json": { schema: z.array(TeamSchema) } }, + }, + 401: { description: "Unauthorized" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/tournament/{tournament}/rankedTeams", + tags: ["Manager - Tournaments"], + summary: "Ranked teams", + request: { params: TournamentParamSchema }, + responses: { + 200: { + description: "Rankings", + content: { + "application/json": { + schema: z.array( + z.object({ + number: z.number().int(), + name: z.string(), + rank: z.number().int().nullable(), + rankingPoints: z.number().int().nullable(), + matchesPlayed: z.number().int().nullable(), + avatar: z.string().nullable(), + }), + ), + }, + }, + }, + 404: { description: "Tournament or teams not found" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "post", + path: "/v1/manager/tournament/{tournament}/scoutershifts", + tags: ["Manager - Tournaments"], + summary: "Create scouter shift", + request: { + params: TournamentParamSchema, + body: { + content: { + "application/json": { + schema: z.object({ + startMatchOrdinalNumber: z.number().int(), + endMatchOrdinalNumber: z.number().int(), + team1: z.array(z.string()), + team2: z.array(z.string()), + team3: z.array(z.string()), + team4: z.array(z.string()), + team5: z.array(z.string()), + team6: z.array(z.string()), + }), + }, + }, + }, + }, + responses: { + 200: { description: "Created" }, + 400: { + description: + "Invalid request, overlapping scouters, or overlapping shift matches", + }, + 401: { description: "Unauthorized" }, + 403: { description: "API key forbidden or user role not SCOUTING_LEAD" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); + registry.registerPath({ + method: "get", + path: "/v1/manager/tournament/{tournament}/scoutershifts", + tags: ["Manager - Tournaments"], + summary: "List scouter shifts", + request: { params: TournamentParamSchema }, + responses: { + 200: { + description: "Shifts", + content: { + "application/json": { + schema: z.object({ + hash: z.string(), + data: z.array(ScouterScheduleShiftWithTeamsSchema), + }), + }, + }, + }, + 401: { description: "Unauthorized" }, + 403: { description: "User not affiliated with a team" }, + 500: { description: "Server error" }, + }, + security: [{ bearerAuth: [] }], + }); +} diff --git a/packages/api/src/metrics.ts b/packages/api/src/metrics.ts new file mode 100644 index 000000000..c70dd1f6b --- /dev/null +++ b/packages/api/src/metrics.ts @@ -0,0 +1,53 @@ +import { z } from "zod"; + +export const metricMetadataSchema = z.object({ + id: z.string().min(1), + aliases: z.array(z.string()), + season: z.number().int(), + version: z.number().int().positive(), + label: z.string(), + unit: z.string(), + kind: z.enum(["number", "distribution", "structured"]), + precision: z.number().int().min(0).max(8), + missing: z.literal("exclude"), + dependencies: z.array(z.string()), + outputSchema: z.record(z.string(), z.json()).optional(), + requires: z.array(z.string()), +}); +export type MetricMetadata = z.infer; +export const metricValueSchema = z.json(); +export type MetricValue = z.infer; +export const metricResultSchema = z.object({ + value: metricValueSchema.nullable(), + samples: z.number().int().nonnegative(), + version: z.number().int().positive(), +}); +export const analysisRequestSchema = z + .object({ + teams: z.array(z.number().int().positive()).min(1).max(100), + metrics: z.array(z.string().min(1).max(100)).min(1).max(64), + season: z.number().int().min(2000).max(2100).default(2026), + timeline: z.boolean().default(false), + gameVersion: z.number().int().positive().optional(), + }) + .strict(); +export const analysisResponseSchema = z.object({ + season: z.number().int(), + teams: z.record( + z.string(), + z.object({ + metrics: z.record(z.string(), metricResultSchema), + timeline: z + .array( + z.object({ + matchKey: z.string(), + tournamentKey: z.string(), + metrics: z.record(z.string(), metricResultSchema), + }), + ) + .optional(), + }), + ), +}); +export type AnalysisRequest = z.infer; +export type AnalysisResponse = z.infer; diff --git a/packages/api/src/reports.ts b/packages/api/src/reports.ts new file mode 100644 index 000000000..46c2f0e28 --- /dev/null +++ b/packages/api/src/reports.ts @@ -0,0 +1,2 @@ +// Explicit compatibility exports for the 2026 Collection wire format. +export * from "./games/2026/report.js"; diff --git a/packages/api/src/routes.ts b/packages/api/src/routes.ts new file mode 100644 index 000000000..f9cfed65a --- /dev/null +++ b/packages/api/src/routes.ts @@ -0,0 +1,72 @@ +import { + gameDescriptorSchema, + gameReportEnvelopeSchema, + gamePredictionRequestSchema, + gamePredictionResultSchema, +} from "./games.js"; +import { z } from "zod"; +import { + analysisRequestSchema, + analysisResponseSchema, + metricMetadataSchema, +} from "./metrics.js"; + +export interface Route { + method: "GET" | "POST"; + path: string; + auth: "public" | "dashboard" | "collection"; + input: I; + output: O; +} +function route( + definition: Route, +): Route { + return definition; +} +export const routes = { + predictGame: route({ + method: "POST", + path: "/v3/prediction", + auth: "dashboard", + input: gamePredictionRequestSchema, + output: gamePredictionResultSchema, + }), + games: route({ + method: "GET", + path: "/v3/games", + auth: "public", + input: z.object({}), + output: z.array(gameDescriptorSchema), + }), + submitGameReport: route({ + method: "POST", + path: "/v3/reports", + auth: "collection", + input: gameReportEnvelopeSchema, + output: z.object({ + uuid: z.uuid(), + created: z.boolean(), + gameId: z.string(), + gameVersion: z.number().int(), + reportVersion: z.number().int(), + }), + }), + + metrics: route({ + method: "GET", + path: "/v3/metrics", + auth: "dashboard", + input: z.object({ + season: z.coerce.number().int().min(1992).max(2200).optional(), + gameVersion: z.coerce.number().int().positive().optional(), + }), + output: z.array(metricMetadataSchema), + }), + analyze: route({ + method: "POST", + path: "/v3/analysis", + auth: "dashboard", + input: analysisRequestSchema, + output: analysisResponseSchema, + }), +}; diff --git a/packages/api/test/contracts.test.mjs b/packages/api/test/contracts.test.mjs new file mode 100644 index 000000000..c209c47a2 --- /dev/null +++ b/packages/api/test/contracts.test.mjs @@ -0,0 +1,143 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + routes, + reportSchema, + eventTupleSchema, + createApiClient, + ApiClientError, +} from "../dist/index.js"; + +test("event wire numbering and quantity requirements stay compatible", () => { + assert.equal(eventTupleSchema.safeParse([10, 1, 2]).success, false); + assert.deepEqual(eventTupleSchema.parse([10, 1, 2, 0]), [10, 1, 2, 0]); + assert.equal(eventTupleSchema.safeParse([10, 99, 2]).success, false); + assert.equal(eventTupleSchema.safeParse([10, 0, 99]).success, false); + assert.equal(eventTupleSchema.safeParse([10, 13, 2]).success, false); + assert.equal(eventTupleSchema.safeParse([-1, 0, 2]).success, false); +}); +test("analysis limits reject oversized and unknown inputs", () => { + assert.equal( + routes.analyze.input.safeParse({ + teams: [8033], + metrics: ["totalPoints"], + sourceTeam: 1, + }).success, + false, + ); + assert.equal( + routes.analyze.input.safeParse({ + teams: Array(101).fill(1), + metrics: ["totalPoints"], + }).success, + false, + ); + assert.equal( + routes.analyze.input.parse({ teams: [8033], metrics: ["totalPoints"] }) + .timeline, + false, + ); +}); +test("client validates input before sending and parses structured failures", async () => { + let calls = 0; + const client = createApiClient({ + baseUrl: "https://api.example", + token: () => "secret", + fetch: async (url, init) => { + calls++; + assert.equal(String(url), "https://api.example/v3/analysis"); + assert.equal(init.headers.Authorization, "Bearer secret"); + return new Response( + JSON.stringify({ + code: "FORBIDDEN", + message: "Denied", + displayError: "Denied", + }), + { status: 403 }, + ); + }, + }); + await assert.rejects(client.request("analyze", { teams: [], metrics: [] })); + assert.equal(calls, 0); + await assert.rejects( + client.request("analyze", { teams: [8033], metrics: ["totalPoints"] }), + (error) => + error instanceof ApiClientError && + error.status === 403 && + error.details.code === "FORBIDDEN", + ); +}); +test("client validates successful responses", async () => { + const client = createApiClient({ + baseUrl: "https://api.example", + token: () => "secret", + fetch: async () => new Response(JSON.stringify({ unexpected: true })), + }); + await assert.rejects( + client.request("analyze", { teams: [8033], metrics: ["totalPoints"] }), + ); +}); +test("report definition has no database-owned scalar dependency", () => { + assert.equal( + reportSchema.shape.autoClimb.safeParse("SUCCEEDED").success, + true, + ); + assert.equal( + reportSchema.shape.matchType.safeParse("PRACTICE").success, + true, + ); +}); + +test("public discovery omits credentials and GET game selection uses query parameters", async () => { + let credentials = 0; + const client = createApiClient({ + baseUrl: "https://api.example", + token: () => { + credentials++; + return "token"; + }, + fetch: async (url, init) => { + if (url.pathname === "/v3/games") { + assert.equal(init.headers.Authorization, undefined); + return Response.json([]); + } + assert.equal(url.searchParams.get("season"), "2099"); + assert.equal(url.searchParams.get("gameVersion"), "2"); + assert.equal(init.body, undefined); + assert.equal(init.headers.Authorization, "Bearer token"); + return Response.json([]); + }, + }); + assert.deepEqual(await client.request("games", {}), []); + assert.equal(credentials, 0); + assert.deepEqual( + await client.request("metrics", { season: 2099, gameVersion: 2 }), + [], + ); + assert.equal(credentials, 1); +}); +test("generated OpenAPI references resolve and document Collection report authentication", async () => { + const { readFile } = await import("node:fs/promises"); + const document = JSON.parse( + await readFile(new URL("../openapi.json", import.meta.url), "utf8"), + ); + const walk = (node) => { + if (!node || typeof node !== "object") return; + if (node.$ref?.startsWith("#/")) { + let target = document; + for (const part of node.$ref.slice(2).split("/")) + target = target?.[part.replaceAll("~1", "/").replaceAll("~0", "~")]; + assert.ok(target, "Unresolved schema: " + node.$ref); + } + for (const child of Object.values(node)) walk(child); + }; + walk(document); + const report = document.paths["/v3/reports"].post; + assert.deepEqual(report.security, [{ collectionCode: [] }]); + assert.ok(report.responses["201"]); + assert.ok( + report.parameters.some( + (parameter) => parameter.name === "X-Scouter-Uuid" && parameter.required, + ), + ); +}); diff --git a/packages/api/test/legacy.test.mjs b/packages/api/test/legacy.test.mjs new file mode 100644 index 000000000..5c501b8ac --- /dev/null +++ b/packages/api/test/legacy.test.mjs @@ -0,0 +1,31 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createLegacyOpenApiDocument } from "../dist/legacy/index.js"; +test("legacy definitions build without database, server imports or environment configuration", () => { + const document = createLegacyOpenApiDocument({ + version: "test", + baseUrl: "https://api.example", + }); + assert.equal(Object.keys(document.paths).length, 77); + assert.equal(document.info.version, "test"); + assert(document.paths["/v1/manager/scoutreports/{uuid}"].get); + assert(document.paths["/v1/analysis/matchprediction"].get); + assert(document.components.schemas.ScoutReport); + assert.equal( + document.components.schemas.ApiKey.properties.keyHash, + undefined, + ); +}); +test("documents are isolated and errors keep their shared public contract", () => { + const options = { version: "test", baseUrl: "https://api.example" }; + const first = createLegacyOpenApiDocument(options); + delete first.paths["/v1/manager/profile"]; + const second = createLegacyOpenApiDocument(options); + assert(second.paths["/v1/manager/profile"]); + assert.equal( + second.paths["/v1/manager/profile"].get.responses[401].content[ + "application/json" + ].schema.$ref, + "#/components/schemas/ApiError", + ); +}); diff --git a/packages/api/tools/generate.mjs b/packages/api/tools/generate.mjs new file mode 100644 index 000000000..f164b5247 --- /dev/null +++ b/packages/api/tools/generate.mjs @@ -0,0 +1,129 @@ +import { readFile, writeFile } from "node:fs/promises"; +import { z } from "zod"; +import { apiErrorSchema, reportSchema, routes } from "../dist/index.js"; +const definitions = {}; +function schema(value, name) { + const raw = z.toJSONSchema(value, { target: "draft-2020-12" }); + const rewrite = (node) => { + if (Array.isArray(node)) return node.map(rewrite); + if (!node || typeof node !== "object") return node; + return Object.fromEntries( + Object.entries(node) + .filter(([key]) => key !== "$defs") + .map(([key, entry]) => [ + key, + key === "$ref" && + typeof entry === "string" && + entry.startsWith("#/$defs/") + ? "#/components/schemas/" + + name + + "_" + + entry.slice("#/$defs/".length) + : rewrite(entry), + ]), + ); + }; + for (const [key, entry] of Object.entries(raw.$defs ?? {})) + definitions[name + "_" + key] = rewrite(entry); + return rewrite(raw); +} +const paths = {}; +for (const [operationId, route] of Object.entries(routes)) { + const requestSchema = schema(route.input, operationId + "Request"); + const responseSchema = schema(route.output, operationId + "Response"); + const errorSchema = schema(apiErrorSchema, "ApiError"); + const parameters = + route.method === "GET" + ? Object.entries(requestSchema.properties ?? {}).map( + ([name, property]) => ({ + in: "query", + name, + required: (requestSchema.required ?? []).includes(name), + schema: property, + }), + ) + : []; + if (route.auth === "collection") + parameters.push( + ...["X-Scouter-Uuid", "X-Device-Id"].map((name) => ({ + in: "header", + name, + required: true, + schema: { type: "string", minLength: 1 }, + })), + ); + paths[route.path] ??= {}; + const success = operationId === "submitGameReport" ? [200, 201] : [200]; + paths[route.path][route.method.toLowerCase()] = { + operationId, + security: + route.auth === "public" + ? [] + : route.auth === "collection" + ? [{ collectionCode: [] }] + : [{ bearerAuth: [] }], + ...(parameters.length ? { parameters } : {}), + ...(route.method === "POST" + ? { + requestBody: { + required: true, + content: { "application/json": { schema: requestSchema } }, + }, + } + : {}), + responses: Object.fromEntries( + [...success, 400, 401, 403, 409, 413, 422, 429, 500, 503].map( + (status) => [ + status, + { + description: success.includes(status) + ? "Success" + : "Request failed", + content: { + "application/json": { + schema: success.includes(status) ? responseSchema : errorSchema, + }, + }, + }, + ], + ), + ), + }; +} +const components = { + ApiError: schema(apiErrorSchema, "ApiError"), + ReportSubmission: schema(reportSchema, "ReportSubmission"), +}; +const document = { + openapi: "3.1.0", + info: { title: "Lovat API", version: "0.1.0" }, + paths, + components: { + schemas: { ...components, ...definitions }, + securitySchemes: { + bearerAuth: { type: "http", scheme: "bearer" }, + collectionCode: { type: "apiKey", in: "header", name: "X-Team-Code" }, + }, + }, +}; +const content = JSON.stringify(document, null, 2) + "\n", + destination = new URL("../openapi.json", import.meta.url); +if (process.argv.includes("--check")) { + if ((await readFile(destination, "utf8")) !== content) + throw Error("Run npm run generate: API contract drift detected"); +} else await writeFile(destination, content); +const { createLegacyOpenApiDocument } = await import("../dist/legacy/index.js"); +const legacyContent = + JSON.stringify( + createLegacyOpenApiDocument({ + version: "26.0.0", + baseUrl: "https://api.lovat.app", + }), + null, + 2, + ) + "\n"; +const legacyDestination = new URL("../openapi.legacy.json", import.meta.url); +if (process.argv.includes("--check")) { + if ((await readFile(legacyDestination, "utf8")) !== legacyContent) + throw Error("Legacy contract drift: run npm run generate"); +} else await writeFile(legacyDestination, legacyContent); diff --git a/packages/api/tsconfig.json b/packages/api/tsconfig.json new file mode 100644 index 000000000..5c5d393b0 --- /dev/null +++ b/packages/api/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "declaration": true, + "outDir": "dist", + "rootDir": "src", + "skipLibCheck": true + }, + "include": ["src/**/*.ts"] +} diff --git a/packages/db/README.md b/packages/db/README.md index 9ef807c67..6cbe21b49 100644 --- a/packages/db/README.md +++ b/packages/db/README.md @@ -135,3 +135,7 @@ These fields contain public official data and preserve the season context. display it as Week 1, Week 2, and so on; championship grouping uses `eventType`. The worker uses a versioned events cache key to refresh existing season records after this field is introduced. + +## Per-service pool limits + +Services can pass an optional second argument to createDb: maxConnections, idleTimeoutMs, and statementTimeoutMs. Values must be positive integers. Existing callers retain the original ten-connection pool and five-minute idle timeout; SQL statement timeouts are opt-in. The replacement API uses four connections, a 30-second idle timeout, and an eight-second statement timeout to bound contention and long queries. diff --git a/packages/db/prisma/migrations/20261113010000_add_api_outbox_and_analysis_revision/migration.sql b/packages/db/prisma/migrations/20261113010000_add_api_outbox_and_analysis_revision/migration.sql new file mode 100644 index 000000000..bb0f1095a --- /dev/null +++ b/packages/db/prisma/migrations/20261113010000_add_api_outbox_and_analysis_revision/migration.sql @@ -0,0 +1,20 @@ +CREATE TABLE "AnalysisRevision" ( + "teamNumber" INTEGER NOT NULL PRIMARY KEY, + "revision" BIGINT NOT NULL DEFAULT 0, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE TABLE "ApiOutbox" ( + "id" TEXT NOT NULL PRIMARY KEY, + "dedupeKey" TEXT NOT NULL, + "kind" TEXT NOT NULL, + "payload" JSONB NOT NULL, + "availableAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "attempts" INTEGER NOT NULL DEFAULT 0, + "leaseToken" TEXT, + "leaseUntil" TIMESTAMP(3), + "completedAt" TIMESTAMP(3), + "lastError" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE UNIQUE INDEX "ApiOutbox_dedupeKey_key" ON "ApiOutbox"("dedupeKey"); +CREATE INDEX "ApiOutbox_completedAt_availableAt_idx" ON "ApiOutbox"("completedAt", "availableAt"); diff --git a/packages/db/prisma/migrations/20261113011000_scope_warning_threads_to_events/migration.sql b/packages/db/prisma/migrations/20261113011000_scope_warning_threads_to_events/migration.sql new file mode 100644 index 000000000..a48418be6 --- /dev/null +++ b/packages/db/prisma/migrations/20261113011000_scope_warning_threads_to_events/migration.sql @@ -0,0 +1 @@ +ALTER TABLE "SlackNotificationThread" ADD COLUMN "tournamentKey" TEXT; diff --git a/packages/db/prisma/migrations/20261115233000_add_versioned_game_reports/migration.sql b/packages/db/prisma/migrations/20261115233000_add_versioned_game_reports/migration.sql new file mode 100644 index 000000000..59c7f95d1 --- /dev/null +++ b/packages/db/prisma/migrations/20261115233000_add_versioned_game_reports/migration.sql @@ -0,0 +1,23 @@ +CREATE TABLE "GameReport" ( + "uuid" TEXT NOT NULL PRIMARY KEY, + "scouterUuid" TEXT NOT NULL, + "teamMatchKey" TEXT NOT NULL, + "seasonYear" INTEGER NOT NULL, + "gameId" TEXT NOT NULL, + "gameVersion" INTEGER NOT NULL, + "reportVersion" INTEGER NOT NULL, + "startTime" TIMESTAMP(3) NOT NULL, + "endTime" TIMESTAMP(3) NOT NULL, + "data" JSONB NOT NULL, + "training" BOOLEAN NOT NULL DEFAULT false, + "reliability" "ReportReliability" NOT NULL DEFAULT 'UNVERIFIED', + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "GameReport_scouterUuid_fkey" FOREIGN KEY ("scouterUuid") REFERENCES "Scouter"("uuid") ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT "GameReport_teamMatchKey_fkey" FOREIGN KEY ("teamMatchKey") REFERENCES "TeamMatchData"("key") ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT "GameReport_seasonYear_fkey" FOREIGN KEY ("seasonYear") REFERENCES "Season"("year") ON DELETE RESTRICT ON UPDATE CASCADE, + CONSTRAINT "GameReport_versions_check" CHECK ("gameVersion">0 AND "reportVersion">0), + CONSTRAINT "GameReport_time_check" CHECK ("endTime">="startTime") +); +CREATE INDEX "GameReport_scouterUuid_idx" ON "GameReport"("scouterUuid"); +CREATE INDEX "GameReport_teamMatchKey_idx" ON "GameReport"("teamMatchKey"); +CREATE INDEX "GameReport_seasonYear_gameId_gameVersion_idx" ON "GameReport"("seasonYear","gameId","gameVersion"); diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma index fe1531604..1114b3eec 100644 --- a/packages/db/prisma/schema.prisma +++ b/packages/db/prisma/schema.prisma @@ -52,8 +52,9 @@ model ImportJob { } model Season { - year Int @id - gameName String? + gameReports GameReport[] + year Int @id + gameName String? teamSeasons TeamSeason[] districtSeasons DistrictSeason[] @@ -236,13 +237,14 @@ enum TournamentGapTimingSource { } model TeamMatchData { - key String @id + gameReports GameReport[] + key String @id tournamentKey String - matchNumber Int @db.SmallInt + matchNumber Int @db.SmallInt teamNumber Int matchType MatchType /// True only when a public provider schedule includes this practice team. - practiceScheduled Boolean @default(false) + practiceScheduled Boolean @default(false) matchKey String? alliance AllianceColor? @@ -476,6 +478,7 @@ model ScouterScheduleShift { } model Scouter { + gameReports GameReport[] reportsInProgress ScoutReportInProgress[] trainingAttempts TrainingAttempt[] uuid String @id @default(uuid()) @@ -564,6 +567,7 @@ model SlackSubscription { } model SlackNotificationThread { + tournamentKey String? messageId String @id matchNumber Int teamNumber Int @@ -605,8 +609,6 @@ model CachedAnalysis { tournamentDependencies String[] @default([]) } - - enum Position { LEFT_TRENCH LEFT_BUMP @@ -718,3 +720,48 @@ enum ReportReliability { FLAGGED_SYSTEM BAD_REPORT } + +model AnalysisRevision { + teamNumber Int @id + revision BigInt @default(0) + updatedAt DateTime @default(now()) @updatedAt +} + +model ApiOutbox { + id String @id @default(uuid()) + dedupeKey String @unique + kind String + payload Json + availableAt DateTime @default(now()) + attempts Int @default(0) + leaseToken String? + leaseUntil DateTime? + completedAt DateTime? + lastError String? + createdAt DateTime @default(now()) + + @@index([completedAt, availableAt]) +} + +model GameReport { + uuid String @id + scouterUuid String + teamMatchKey String + seasonYear Int + gameId String + gameVersion Int + reportVersion Int + startTime DateTime + endTime DateTime + data Json + training Boolean @default(false) + reliability ReportReliability @default(UNVERIFIED) + createdAt DateTime @default(now()) + scouter Scouter @relation(fields: [scouterUuid], references: [uuid], onDelete: Cascade) + teamMatchData TeamMatchData @relation(fields: [teamMatchKey], references: [key], onDelete: Cascade) + season Season @relation(fields: [seasonYear], references: [year]) + + @@index([scouterUuid]) + @@index([teamMatchKey]) + @@index([seasonYear, gameId, gameVersion]) +} diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index f07f76a17..967ea0020 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -2,7 +2,20 @@ import "dotenv/config"; import { PrismaPg } from "@prisma/adapter-pg"; import { PrismaClient } from "./generated/prisma/client.js"; -export function createDb(connectionString = process.env.DATABASE_URL) { +export interface DbPoolOptions { + maxConnections?: number; + statementTimeoutMs?: number; + idleTimeoutMs?: number; +} + +export function createDb( + connectionString = process.env.DATABASE_URL, + options: DbPoolOptions = {}, +) { + for (const [name, value] of Object.entries(options)) { + if (!Number.isSafeInteger(value) || value <= 0) + throw new Error(name + " must be a positive integer"); + } if (!connectionString) throw new Error("DATABASE_URL is required"); const url = new URL(connectionString); if (!["postgres:", "postgresql:"].includes(url.protocol)) { @@ -11,9 +24,12 @@ export function createDb(connectionString = process.env.DATABASE_URL) { const adapter = new PrismaPg({ connectionString, - max: 10, + max: options.maxConnections ?? 10, connectionTimeoutMillis: 5_000, - idleTimeoutMillis: 300_000, + idleTimeoutMillis: options.idleTimeoutMs ?? 300_000, + ...(options.statementTimeoutMs + ? { statement_timeout: options.statementTimeoutMs } + : {}), }); return new PrismaClient({ adapter }); } diff --git a/packages/games/.prettierignore b/packages/games/.prettierignore new file mode 100644 index 000000000..1eae0cf67 --- /dev/null +++ b/packages/games/.prettierignore @@ -0,0 +1,2 @@ +dist/ +node_modules/ diff --git a/packages/games/README.md b/packages/games/README.md new file mode 100644 index 000000000..4b5aa1f75 --- /dev/null +++ b/packages/games/README.md @@ -0,0 +1,41 @@ +# Game rules and metrics + +`@lovat/games` contains pure, versioned game modules with no database connections, HTTP runtime, environment configuration, or provider calls. The Bun/Hono API consumes the package; other TypeScript services can use the same rules. Game descriptors and JSON Schemas are published through `@lovat/api` for other languages. + +## Adding a season + +1. Create a module with a stable ID, season and game version. Define its report schema and report version with Zod. +2. Put periods, scoring constants, ranking rules, timing validation and plausibility checks in the module. +3. Prepare shared facts once per report. Define metrics with `defineMetricFor()`: declare metadata/output schema, calculate compact report states, reduce states within a match, and aggregate matches/tournaments. Use `defineDerivedMetricFor()` for dependencies. +4. Add a predictor when supported. It selects required metrics and receives scoped team analyses; alliance size comes from game rules. +5. Register the module in `src/catalog.ts`. New games use the versioned JSON report table and generic HTTP/analysis code without season-specific database columns. +6. Add fixtures for scoring, timing, invalid input, aggregation, prediction and historical upgrades. Run package checks and the API database suite. + +The fictional 2099 fixture in `test/fixtures.mjs` demonstrates different fields, scoring, periods, alliance size, structured metrics and report-schema upgrades. It is never registered in production and makes no claims about a future official game. + +## Versions and storage + +Game versions select an immutable rules contract. Report versions select an input schema; explicit older codecs upgrade historical payloads. Preserve old game versions and codecs when rules change. Metric formula versions participate in cache keys and must change with calculations. + +The 2026 module retains current scoring and scouting-clock conventions. Its typed legacy adapter prepares facts directly from database columns, avoiding an extra wire-payload graph. Only trusted typed adapters use `fromFacts`; arbitrary client and stored JSON payloads pass through their report codec. The engine streams ordered team/tournament/match groups and releases completed report payloads. A metric can supply an optional `reducer` with `add(state)` and `finish()` to avoid storing one state per report; built-in means, rates and distributions do this. Both direct evaluation and streaming use the same reducer. Array-based `reports` reducers remain available for calculations such as medians. + +`analyze` sorts array inputs stably. `analyzeStream` requires groups ordered by `compareReportGroups` and rejects out-of-order input rather than silently giving matches the wrong weight. Storage adapters own the ordered, bounded stream; game modules remain independent of database and transport code. + +## Client and feature work + +`GET /v3/games` publishes rules, report/metric JSON Schemas and prediction capability. Collection submits a stable envelope to `POST /v3/reports`; the game owns its `data`. Analysis and predictions select season and game version. + +Adding a module does not automatically change Collection or Dashboard screens. Clients must consume descriptors or supply their game-specific UI. Existing v1/Collection lifecycle, training grading, six-station schedules and CSV adapters retain 2026 contracts. Generic report review/deletion/flags, worker reassessment of generic reports, and future-game training/schedule support remain follow-ups before a future-season rollout. + +## Checks + +Use Node 22.20.0 and this package's npm lockfile: + +```sh +npm ci +npm test +npm run lint +npm run format:check +``` + +The package depends on built `@lovat/api`. It introduces no root workspace or cross-application imports. diff --git a/packages/games/package-lock.json b/packages/games/package-lock.json new file mode 100644 index 000000000..a4c919e3a --- /dev/null +++ b/packages/games/package-lock.json @@ -0,0 +1,81 @@ +{ + "name": "@lovat/games", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@lovat/games", + "version": "0.1.0", + "dependencies": { + "@lovat/api": "file:../api", + "zod": "4.6.7" + }, + "devDependencies": { + "prettier": "3.9.9", + "typescript": "5.9.3" + }, + "engines": { + "node": ">=22.20.0 <23 || >=24" + } + }, + "../api": { + "name": "@lovat/api", + "version": "0.1.0", + "dependencies": { + "@asteasolutions/zod-to-openapi": "9.1.0", + "zod": "4.6.7" + }, + "devDependencies": { + "prettier": "3.9.9", + "typescript": "5.9.3" + }, + "engines": { + "node": ">=22.20.0 <23 || >=24" + } + }, + "node_modules/@lovat/api": { + "resolved": "../api", + "link": true + }, + "node_modules/prettier": { + "version": "3.9.9", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.9.tgz", + "integrity": "sha512-Z/CJHIkdujO/OtN7nXUii0Rf3VT5SRuhjBA82Xvu2XhBUgX3nhP67T0LHceBdQLex7OOFGTox+Q5Yg8Jk2Qivg==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/packages/games/package.json b/packages/games/package.json new file mode 100644 index 000000000..c3d495b37 --- /dev/null +++ b/packages/games/package.json @@ -0,0 +1,38 @@ +{ + "name": "@lovat/games", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + }, + "./2026": { + "types": "./dist/2026/index.d.ts", + "import": "./dist/2026/index.js" + } + }, + "files": [ + "dist" + ], + "scripts": { + "build": "tsc", + "test": "npm run build && node --test test/*.test.mjs", + "lint": "tsc --noEmit --noUnusedLocals --noUnusedParameters", + "format:check": "prettier --check .", + "prebuild": "npm --prefix ../api run build", + "postinstall": "npm --prefix ../api ci --include=dev && npm --prefix ../api run build" + }, + "dependencies": { + "@lovat/api": "file:../api", + "zod": "4.6.7" + }, + "devDependencies": { + "typescript": "5.9.3", + "prettier": "3.9.9" + }, + "engines": { + "node": ">=22.20.0 <23 || >=24" + } +} diff --git a/packages/games/src/2026/adapter.ts b/packages/games/src/2026/adapter.ts new file mode 100644 index 000000000..6b37af9f5 --- /dev/null +++ b/packages/games/src/2026/adapter.ts @@ -0,0 +1,8 @@ +import { game2026 } from "./index.js"; +import { prepareFacts, type ReportInput } from "./facts.js"; +import type { StoredGameReport } from "../pack.js"; + +/** Read typed legacy columns directly, without constructing a second wire payload. */ +export function legacyAnalysisInput(report: ReportInput): StoredGameReport { + return game2026.fromFacts(report, () => prepareFacts(report)); +} diff --git a/packages/games/src/2026/assess.ts b/packages/games/src/2026/assess.ts new file mode 100644 index 000000000..f5a804ba0 --- /dev/null +++ b/packages/games/src/2026/assess.ts @@ -0,0 +1,20 @@ +import { rules2026 } from "./rules.js"; +import { eventActions, type ReportSubmission } from "@lovat/api"; +export function plausible2026( + data: Pick, + officialScore?: number, +) { + const fuel = data.events.reduce( + (sum, event) => + sum + (eventActions[event[1]] === "STOP_SCORING" ? (event[3] ?? 0) : 0), + 0, + ); + const total = + fuel + + (data.autoClimb === "SUCCEEDED" ? rules2026.autoClimbPoints : 0) + + (rules2026.endgamePoints[data.endgameClimb] ?? 0); + return ( + total <= rules2026.reportFlagThreshold && + (officialScore === undefined || fuel <= officialScore) + ); +} diff --git a/packages/games/src/2026/facts.ts b/packages/games/src/2026/facts.ts new file mode 100644 index 000000000..191002c0c --- /dev/null +++ b/packages/games/src/2026/facts.ts @@ -0,0 +1,114 @@ +import { rules2026 } from "./rules.js"; +import type { eventActions, eventPositions } from "@lovat/api"; + +export interface AnalysisEvent { + action: (typeof eventActions)[number]; + position: (typeof eventPositions)[number]; + time: number; + quantity: number | null; + points: number; +} +export interface ReportInput { + uuid: string; + teamNumber: number; + matchKey: string; + tournamentKey: string; + tournamentDate: string; + events: readonly AnalysisEvent[]; + driverAbility: number; + defenseEffectiveness: number; + accuracy: number | null; + autoClimb: string; + endgameClimb: string; + robotRoles: readonly string[]; + feederTypes: readonly string[]; + fieldTraversal: string; + beached: string; + scoresWhileMoving: boolean; + disrupts: boolean; + intakeType: string; +} +export interface Facts { + report: ReportInput; + counts: Readonly>; + quantity: Readonly>; + durations: Readonly>; + firstClimbAuto: number | null; + firstClimbTeleop: number | null; + autoPoints: number; + teleopPoints: number; + outpostIntakes: number; +} + +/** Stable ordering; repeated starts do not manufacture intervals or double count time. */ +export function prepareFacts(report: ReportInput): Facts { + const counts: Record = {}; + const quantity: Record = {}; + const durations: Record = {}; + const active = new Map(); + const pairs: Record = { + STOP_SCORING: "START_SCORING", + STOP_FEEDING: "START_FEEDING", + STOP_DEFENDING: "START_DEFENDING", + STOP_CAMPING: "START_CAMPING", + }; + let firstClimbAuto: number | null = null; + let firstClimbTeleop: number | null = null; + let autoPoints = 0; + let teleopPoints = 0; + let outpostIntakes = 0; + for (const event of [...report.events].sort((a, b) => a.time - b.time)) { + if (!Number.isFinite(event.time) || event.time < 0) { + throw new Error("Invalid event time"); + } + counts[event.action] = (counts[event.action] ?? 0) + 1; + quantity[event.action] = + (quantity[event.action] ?? 0) + (event.quantity ?? 0); + if (event.action.startsWith("START_") && !active.has(event.action)) { + active.set(event.action, event.time); + } + const start = pairs[event.action]; + if (start) { + const startedAt = active.get(start); + if (startedAt !== undefined) { + const duration = event.time - startedAt; + const minimum = + start === "START_SCORING" || start === "START_FEEDING" + ? rules2026.minimumScoringInterval + : 0; + if (duration >= minimum) { + durations[start] = (durations[start] ?? 0) + duration; + } + active.delete(start); + } + } + if (event.action === "CLIMB") { + if (event.time <= rules2026.autoEnd) { + firstClimbAuto ??= event.time; + } else { + firstClimbTeleop ??= event.time; + } + } + if (event.action === "STOP_SCORING") { + if (event.time <= rules2026.autoEnd) { + autoPoints += event.points; + } else { + teleopPoints += event.points; + } + } + if (event.action === "INTAKE" && event.position === "OUTPOST") { + outpostIntakes++; + } + } + return { + report, + counts, + quantity, + durations, + firstClimbAuto, + firstClimbTeleop, + autoPoints, + teleopPoints, + outpostIntakes, + }; +} diff --git a/packages/games/src/2026/index.ts b/packages/games/src/2026/index.ts new file mode 100644 index 000000000..91c6a3713 --- /dev/null +++ b/packages/games/src/2026/index.ts @@ -0,0 +1,71 @@ +import { normalizeTimeline } from "./timeline.js"; +import { plausible2026 } from "./assess.js"; +import { prediction2026 } from "./prediction.js"; +import { gameData2026Schema, eventActions, eventPositions } from "@lovat/api"; +import { defineGame } from "../pack.js"; +import { season2026 } from "./metrics.js"; +import { prepareFacts } from "./facts.js"; +import { rules2026 } from "./rules.js"; +export const game2026 = defineGame({ + id: "frc-2026", + season: 2026, + version: 1, + label: "Lovat 2026", + report: { version: 1, schema: gameData2026Schema }, + rules: { + allianceSize: rules2026.allianceSize, + periods: [...rules2026.periods], + scoring: { + autoClimbPoints: rules2026.autoClimbPoints, + endgamePoints: rules2026.endgamePoints, + accuracyPercent: [...rules2026.accuracyPercent], + ranking: { + ...rules2026.ranking, + scoreBonusThresholds: [...rules2026.ranking.scoreBonusThresholds], + }, + reportFlagThreshold: rules2026.reportFlagThreshold, + }, + }, + metrics: season2026, + prediction: prediction2026, + assess: plausible2026, + check: (data, context) => { + normalizeTimeline( + data, + Math.min( + (context.endTime - context.startTime) / 1000, + rules2026.periods.reduce( + (sum, period) => sum + period.durationSeconds, + 0, + ), + ), + ); + }, + prepare(report) { + const { data, ...identity } = report; + return prepareFacts({ + ...identity, + ...data, + fieldTraversal: data.mobility, + accuracy: data.accuracy ?? null, + events: data.events.map(([time, action, position, quantity]) => ({ + time, + action: eventActions[action], + position: eventPositions[position], + quantity: quantity ?? 0, + points: eventActions[action] === "STOP_SCORING" ? (quantity ?? 0) : 0, + })), + }); + }, +}); + +export * from "./facts.js"; +export * from "./metrics.js"; +export * from "./rules.js"; + +export * from "./adapter.js"; + +export * from "./prediction.js"; + +export * from "./timeline.js"; +export * from "./assess.js"; diff --git a/packages/games/src/2026/metrics.ts b/packages/games/src/2026/metrics.ts new file mode 100644 index 000000000..42803a00e --- /dev/null +++ b/packages/games/src/2026/metrics.ts @@ -0,0 +1,297 @@ +import { rules2026 } from "./rules.js"; +import { z } from "zod"; +import type { MetricMetadata } from "@lovat/api"; +import type { Facts } from "./facts.js"; +import { + defineDerivedMetricFor, + defineMetricFor, + mean, + meanReducer, + MetricRegistry, + recencyWeightedMean, +} from "../registry.js"; +const defineMetric = defineMetricFor(); +const defineDerivedMetric = defineDerivedMetricFor(); + +function metadata( + id: string, + unit: string, + requires: string[], + aliases: string[] = [], +): MetricMetadata { + return { + id, + label: id, + unit, + season: rules2026.season, + version: 1, + aliases, + kind: "number", + precision: 2, + missing: "exclude", + dependencies: [], + requires, + }; +} +function numberMetric( + id: string, + unit: string, + requires: string[], + calculate: (facts: Facts) => number | null, + aliases: string[] = [], +) { + return defineMetric({ + metadata: metadata(id, unit, requires, aliases), + output: z.number(), + calculate, + reports: mean, + reducer: meanReducer, + aggregate: (values, level) => + level === "team" ? recencyWeightedMean(values) : mean(values), + }); +} +function rateMetric( + id: string, + action: string, + start: string, + aliases: string[] = [], +) { + return defineMetric({ + metadata: metadata(id, "balls/second", ["events"], aliases), + output: z.number(), + calculate: (f: Facts) => ({ + quantity: f.quantity[action] ?? 0, + seconds: f.durations[start] ?? 0, + }), + reducer() { + let quantity = 0, + seconds = 0; + return { + add(state) { + quantity += state.quantity; + seconds += state.seconds; + }, + finish: () => (seconds > 0 ? quantity / seconds : null), + }; + }, + reports: (states) => { + const seconds = states.reduce((sum, state) => sum + state.seconds, 0); + return seconds > 0 + ? states.reduce((sum, state) => sum + state.quantity, 0) / seconds + : null; + }, + aggregate: (values, level) => + level === "team" ? recencyWeightedMean(values) : mean(values), + }); +} +const accuracyPercent = (value: number | null): number | null => { + const percentages = rules2026.accuracyPercent; + return value !== null && Number.isInteger(value) + ? (percentages[value] ?? null) + : null; +}; +const autoPoints = (f: Facts) => + f.autoPoints * ((accuracyPercent(f.report.accuracy) ?? 100) / 100) + + (f.report.autoClimb === "SUCCEEDED" ? rules2026.autoClimbPoints : 0); +const teleopPoints = (f: Facts) => + f.teleopPoints * ((accuracyPercent(f.report.accuracy) ?? 100) / 100); +const endgamePoints = rules2026.endgamePoints; +const eventCount = (id: string, action: string) => + numberMetric(id, "count", ["events"], (f) => f.counts[action] ?? 0); +const duration = (id: string, action: string) => + numberMetric(id, "seconds", ["events"], (f) => f.durations[action] ?? 0); +const fuelOutput = (f: Facts) => + (f.quantity.STOP_SCORING ?? 0) + (f.quantity.STOP_FEEDING ?? 0); + +function distribution( + id: string, + options: readonly string[], + calculate: (f: Facts) => readonly string[], + requires: string[], +) { + const aggregate = ( + values: readonly Record[], + level: "tournament" | "team", + ) => + Object.fromEntries( + options.map((option) => [ + option, + (level === "team" ? recencyWeightedMean : mean)( + values.map((value) => value[option] ?? 0), + ) ?? 0, + ]), + ); + return defineMetric({ + metadata: { ...metadata(id, "proportion", requires), kind: "distribution" }, + output: z.record(z.string(), z.number()), + calculate: (f: Facts) => + Object.fromEntries( + options.map((option) => [ + option, + calculate(f).includes(option) ? 1 : 0, + ]), + ), + reducer() { + const totals = Object.fromEntries(options.map((option) => [option, 0])); + let count = 0; + return { + add(state) { + count++; + for (const option of options) totals[option] += state[option] ?? 0; + }, + finish: () => + count + ? Object.fromEntries( + options.map((option) => [option, totals[option] / count]), + ) + : null, + }; + }, + reports: (values) => aggregate(values, "tournament"), + aggregate, + }); +} +export const season2026 = new MetricRegistry([ + numberMetric( + "autoPoints", + "points", + ["events", "accuracy", "autoClimb"], + autoPoints, + ), + numberMetric("teleopPoints", "points", ["events", "accuracy"], teleopPoints), + numberMetric( + "totalPoints", + "points", + ["events", "accuracy", "autoClimb", "endgameClimb"], + (f) => + autoPoints(f) + + teleopPoints(f) + + (endgamePoints[f.report.endgameClimb] ?? 0), + ), + rateMetric("fuelPerSecond", "STOP_SCORING", "START_SCORING", ["scoringRate"]), + rateMetric("feedingRate", "STOP_FEEDING", "START_FEEDING"), + numberMetric("accuracy", "percent", ["accuracy"], (f) => + accuracyPercent(f.report.accuracy), + ), + numberMetric( + "driverAbility", + "rating", + ["driverAbility"], + (f) => f.report.driverAbility, + ), + numberMetric( + "defenseEffectiveness", + "rating", + ["defenseEffectiveness"], + (f) => f.report.defenseEffectiveness, + ), + eventCount("volleysPerMatch", "START_SCORING"), + eventCount("feedsPerMatch", "STOP_FEEDING"), + duration("contactDefenseTime", "START_DEFENDING"), + duration("campingDefenseTime", "START_CAMPING"), + duration("timeFeeding", "START_FEEDING"), + defineDerivedMetric({ + metadata: { + ...metadata("totalDefenseTime", "seconds", []), + dependencies: ["contactDefenseTime", "campingDefenseTime"], + }, + output: z.number(), + calculate: (dependencies) => { + const a = dependencies.get("contactDefenseTime"); + const b = dependencies.get("campingDefenseTime"); + return typeof a === "number" && typeof b === "number" ? a + b : null; + }, + aggregate: (values, level) => + level === "team" ? recencyWeightedMean(values) : mean(values), + }), + numberMetric("totalFuelOutputted", "balls", ["events"], fuelOutput, [ + "totalFuelThroughput", + ]), + numberMetric("totalBallThroughput", "balls", ["events"], fuelOutput, [ + "totalBallThroughPut", + ]), + numberMetric( + "totalBallsFed", + "balls", + ["events"], + (f) => f.quantity.STOP_FEEDING ?? 0, + ["totalFuelFed"], + ), + numberMetric("outpostIntakes", "count", ["events"], (f) => f.outpostIntakes), + numberMetric( + "autoClimbStartTime", + "secondsRemaining", + ["events", "autoClimb"], + (f) => + f.report.autoClimb === "SUCCEEDED" && f.firstClimbAuto !== null + ? rules2026.autoEnd - f.firstClimbAuto + : null, + ), + ...["L1", "L2", "L3"].map((level) => + numberMetric( + level.toLowerCase() + "StartTime", + "secondsRemaining", + ["events", "endgameClimb"], + (f) => + f.report.endgameClimb === level && + f.firstClimbTeleop !== null && + f.firstClimbTeleop <= rules2026.climbClockEnd + ? rules2026.climbClockEnd - f.firstClimbTeleop + : null, + ), + ), + distribution( + "robotRole", + ["CYCLING", "SCORING", "FEEDING", "DEFENDING", "IMMOBILE"], + (f) => f.report.robotRoles, + ["robotRoles"], + ), + distribution( + "feederType", + ["CONTINUOUS", "STOP_TO_SHOOT", "DUMP"], + (f) => f.report.feederTypes, + ["feederTypes"], + ), + distribution( + "fieldTraversal", + ["TRENCH", "BUMP", "BOTH", "NONE"], + (f) => [f.report.fieldTraversal], + ["fieldTraversal"], + ), + distribution( + "climbResult", + Object.keys(endgamePoints), + (f) => [f.report.endgameClimb], + ["endgameClimb"], + ), + distribution( + "beached", + ["ON_FUEL", "ON_BUMP", "BOTH", "NEITHER"], + (f) => [f.report.beached], + ["beached"], + ), + distribution( + "scoresWhileMoving", + ["TRUE", "FALSE"], + (f) => [String(f.report.scoresWhileMoving).toUpperCase()], + ["scoresWhileMoving"], + ), + distribution( + "disrupts", + ["TRUE", "FALSE"], + (f) => [String(f.report.disrupts).toUpperCase()], + ["disrupts"], + ), + distribution( + "autoClimb", + ["NOT_ATTEMPTED", "FAILED", "SUCCEEDED"], + (f) => [f.report.autoClimb], + ["autoClimb"], + ), + distribution( + "intakeType", + ["GROUND", "OUTPOST", "BOTH", "NEITHER"], + (f) => [f.report.intakeType], + ["intakeType"], + ), +]); diff --git a/packages/games/src/2026/prediction.ts b/packages/games/src/2026/prediction.ts new file mode 100644 index 000000000..208f0156a --- /dev/null +++ b/packages/games/src/2026/prediction.ts @@ -0,0 +1,62 @@ +import type { AnalysisResponse } from "@lovat/api"; +import { normalPrediction } from "../prediction.js"; +import { rules2026 } from "./rules.js"; +type Team = AnalysisResponse["teams"][string]; +const series = (team: Team) => + (team.timeline ?? []).flatMap((point) => + typeof point.metrics.totalPoints?.value === "number" + ? [point.metrics.totalPoints.value] + : [], + ); +const average = (teams: readonly Team[]) => + teams.reduce( + (sum, team) => + sum + + (typeof team.metrics.totalPoints?.value === "number" + ? team.metrics.totalPoints.value + : 0), + 0, + ); +export const rankingPoints2026 = ( + score: number, + outcome: "win" | "loss" | "tie", +) => + (outcome === "win" + ? rules2026.ranking.win + : outcome === "tie" + ? rules2026.ranking.tie + : 0) + + rules2026.ranking.scoreBonusThresholds.filter( + (threshold) => score >= threshold, + ).length; +export const prediction2026 = { + metrics: ["totalPoints"], + calculate({ red, blue }: { red: readonly Team[]; blue: readonly Team[] }) { + const odds = normalPrediction( + [...red, ...blue].map(series), + rules2026.allianceSize, + ); + const redScore = average(red), + blueScore = average(blue); + const winner = + odds.redWinning === odds.blueWinning + ? "tie" + : odds.winningAlliance === 0 + ? "red" + : "blue"; + return { + ...odds, + winningAlliance: winner as "red" | "blue" | "tie", + redScore, + blueScore, + redRankingPoints: rankingPoints2026( + redScore, + winner === "tie" ? "tie" : winner === "red" ? "win" : "loss", + ), + blueRankingPoints: rankingPoints2026( + blueScore, + winner === "tie" ? "tie" : winner === "blue" ? "win" : "loss", + ), + }; + }, +}; diff --git a/packages/games/src/2026/rules.ts b/packages/games/src/2026/rules.ts new file mode 100644 index 000000000..33df4989a --- /dev/null +++ b/packages/games/src/2026/rules.ts @@ -0,0 +1,35 @@ +export const rules2026 = { + season: 2026, + version: 1, + id: "frc-2026", + label: "Lovat 2026", + minimumScoringInterval: 0.5, + allianceSize: 3, + periods: [ + { id: "auto", label: "Autonomous scouting clock", durationSeconds: 23 }, + { + id: "teleop", + label: "Teleoperated scouting clock", + durationSeconds: 135, + }, + { id: "buffer", label: "Post-match scouting buffer", durationSeconds: 5 }, + ], + autoEnd: 23, + climbClockEnd: 158, + autoClimbPoints: 15, + endgamePoints: { + NOT_ATTEMPTED: 0, + FAILED: 0, + L1: 10, + L2: 20, + L3: 30, + } as Record, + accuracyPercent: [25, 55, 65, 75, 85, 95], + reportFlagThreshold: 800, + ranking: { + win: 3, + tie: 1, + scoreBonusThresholds: [240, 400], + forecastScale: 0.9, + }, +} as const; diff --git a/packages/games/src/2026/timeline.ts b/packages/games/src/2026/timeline.ts new file mode 100644 index 000000000..6dfe6983e --- /dev/null +++ b/packages/games/src/2026/timeline.ts @@ -0,0 +1,50 @@ +import { eventActions, type ReportSubmission } from "@lovat/api"; +import { GameError } from "../errors.js"; +export function normalizeTimeline< + T extends Pick, +>(report: T, duration = Infinity): T { + let events = report.events; + if (["26.0.3", "26.0.4"].includes(report.appVersion ?? "")) { + events = events.filter((event, index) => { + const action = eventActions[event[1]]; + return ( + !action.startsWith("START_") || + action === "START_MATCH" || + eventActions[events[index + 1]?.[1]] === + action.replace("START_", "STOP_") + ); + }); + } + let active: string | null = null; + let previous = -1; + for (const event of events) { + const action = eventActions[event[1]]; + if (event[0] < previous || event[0] > duration) + throw new GameError( + 400, + "INVALID_TIMELINE", + "Events must be ordered and within the match duration", + ); + previous = event[0]; + if (action.startsWith("START_") && action !== "START_MATCH") { + if (active) + throw new GameError(400, "INVALID_TIMELINE", "Actions cannot overlap"); + active = action.slice(6); + } else if (action.startsWith("STOP_")) { + if (active !== action.slice(5)) + throw new GameError( + 400, + "INVALID_TIMELINE", + "Stop events must match an active action", + ); + active = null; + } + } + if (active) + throw new GameError( + 400, + "INVALID_TIMELINE", + "Action is missing its stop event", + ); + return { ...report, events }; +} diff --git a/packages/games/src/catalog.ts b/packages/games/src/catalog.ts new file mode 100644 index 000000000..2e4805ec8 --- /dev/null +++ b/packages/games/src/catalog.ts @@ -0,0 +1,3 @@ +import { GameCatalog } from "./pack.js"; +import { game2026 } from "./2026/index.js"; +export const games = new GameCatalog([game2026]); diff --git a/packages/games/src/engine.ts b/packages/games/src/engine.ts new file mode 100644 index 000000000..b71de7ec3 --- /dev/null +++ b/packages/games/src/engine.ts @@ -0,0 +1,225 @@ +import type { + AnalysisRequest, + AnalysisResponse, + MetricValue, +} from "@lovat/api"; +import type { MetricAccumulator, MetricRegistry } from "./registry.js"; + +export interface ReportIdentity { + uuid: string; + teamNumber: number; + matchKey: string; + tournamentKey: string; + tournamentDate: string; +} +/** Matching reports stay contiguous; stable sorting preserves their input order. */ +export function compareReportGroups( + a: ReportIdentity, + b: ReportIdentity, +): number { + return ( + a.teamNumber - b.teamNumber || + a.tournamentDate.localeCompare(b.tournamentDate) || + a.tournamentKey.localeCompare(b.tournamentKey) || + a.matchKey.localeCompare(b.matchKey) + ); +} + +/** Holds one match's compact report states and one tournament's reduced values. */ +export function createGameAnalysis( + request: AnalysisRequest, + registry: MetricRegistry, + prepare: (report: R) => F, +) { + const requested = [ + ...new Set(request.metrics.map((id) => registry.get(id).metadata.id)), + ]; + const definitions = registry.resolve(requested); + if ( + definitions.some( + (definition) => definition.metadata.season !== request.season, + ) + ) + throw new RangeError("Unsupported metric season"); + const indexes = new Map( + definitions.map((definition, index) => [definition.metadata.id, index]), + ); + const teamSet = new Set(request.teams); + const response: AnalysisResponse = { season: request.season, teams: {} }; + let closed = false; + let previous: ReportIdentity | undefined; + let team: + | { + number: number; + values: MetricValue[][]; + samples: number[]; + timeline: NonNullable; + } + | undefined; + let tournament: + { key: string; date: string; values: MetricValue[][] } | undefined; + let match: { key: string; collectors: MetricAccumulator[] } | undefined; + const emptyValues = () => definitions.map(() => [] as MetricValue[]); + function finishMatch() { + if (!match || !tournament || !team) return; + const dependencies = new Map(); + for (const [index, definition] of definitions.entries()) { + const value = match.collectors[index].finish(dependencies); + dependencies.set(definition.metadata.id, value); + if (value !== null) { + tournament.values[index].push(value); + team.samples[index]++; + } + } + if (request.timeline) + team.timeline.push({ + matchKey: match.key, + tournamentKey: tournament.key, + metrics: Object.fromEntries( + requested.map((id) => [ + id, + { + value: dependencies.get(id) ?? null, + samples: dependencies.get(id) == null ? 0 : 1, + version: registry.get(id).metadata.version, + }, + ]), + ), + }); + match = undefined; + } + function finishTournament() { + finishMatch(); + if (!tournament || !team) return; + for (const [index, definition] of definitions.entries()) { + const value = definition.combine(tournament.values[index], "tournament"); + if (value !== null) team.values[index].push(value); + } + tournament = undefined; + } + function finishTeam() { + finishTournament(); + if (!team) return; + const current = team; + response.teams[String(current.number)] = { + metrics: Object.fromEntries( + requested.map((id) => { + const index = indexes.get(id)!; + return [ + id, + { + value: definitions[index].combine(current.values[index], "team"), + samples: current.samples[index], + version: registry.get(id).metadata.version, + }, + ]; + }), + ), + ...(request.timeline ? { timeline: current.timeline } : {}), + }; + team = undefined; + } + return { + add(report: R) { + if (closed) throw new Error("Analysis is already complete"); + if (!teamSet.has(report.teamNumber)) return; + if (previous && compareReportGroups(previous, report) > 0) + throw new RangeError( + "Analysis report stream must be ordered by team, tournament and match", + ); + previous = { + uuid: report.uuid, + teamNumber: report.teamNumber, + matchKey: report.matchKey, + tournamentKey: report.tournamentKey, + tournamentDate: report.tournamentDate, + }; + if (team?.number !== report.teamNumber) { + finishTeam(); + team = { + number: report.teamNumber, + values: emptyValues(), + samples: definitions.map(() => 0), + timeline: [], + }; + } + if ( + tournament && + tournament.key === report.tournamentKey && + tournament.date !== report.tournamentDate + ) + throw new RangeError("Inconsistent tournament dates"); + if (tournament?.key !== report.tournamentKey) { + finishTournament(); + tournament = { + key: report.tournamentKey, + date: report.tournamentDate, + values: emptyValues(), + }; + } + if (match?.key !== report.matchKey) { + finishMatch(); + match = { + key: report.matchKey, + collectors: definitions.map((definition) => { + if (definition.start) return definition.start(); + const facts: F[] = []; + return { + add: (value: F) => { + facts.push(value); + }, + finish: (dependencies) => + definition.evaluate(facts, dependencies), + }; + }), + }; + } + const facts = prepare(report); + for (const collector of match.collectors) collector.add(facts); + }, + finish(): AnalysisResponse { + if (closed) throw new Error("Analysis is already complete"); + finishTeam(); + for (const number of teamSet) { + response.teams[String(number)] ??= { + metrics: Object.fromEntries( + requested.map((id) => [ + id, + { + value: registry.get(id).combine([], "team"), + samples: 0, + version: registry.get(id).metadata.version, + }, + ]), + ), + ...(request.timeline ? { timeline: [] } : {}), + }; + } + closed = true; + previous = undefined; + return response; + }, + }; +} +export function analyzeGameReports( + reports: readonly R[], + request: AnalysisRequest, + registry: MetricRegistry, + prepare: (report: R) => F, +): AnalysisResponse { + const analysis = createGameAnalysis(request, registry, prepare); + for (const report of [...reports].sort(compareReportGroups)) + analysis.add(report); + return analysis.finish(); +} +/** Sources must order match groups, so completed event payloads can be released. */ +export async function analyzeGameReportStream( + reports: AsyncIterable, + request: AnalysisRequest, + registry: MetricRegistry, + prepare: (report: R) => F, +): Promise { + const analysis = createGameAnalysis(request, registry, prepare); + for await (const report of reports) analysis.add(report); + return analysis.finish(); +} diff --git a/packages/games/src/errors.ts b/packages/games/src/errors.ts new file mode 100644 index 000000000..9066b857b --- /dev/null +++ b/packages/games/src/errors.ts @@ -0,0 +1,9 @@ +export class GameError extends Error { + constructor( + readonly status: number, + readonly code: string, + message: string, + ) { + super(message); + } +} diff --git a/packages/games/src/index.ts b/packages/games/src/index.ts new file mode 100644 index 000000000..ea27d09e1 --- /dev/null +++ b/packages/games/src/index.ts @@ -0,0 +1,7 @@ +export * from "./pack.js"; +export * from "./registry.js"; +export * from "./engine.js"; +export * from "./catalog.js"; +export * from "./errors.js"; + +export * from "./prediction.js"; diff --git a/packages/games/src/pack.ts b/packages/games/src/pack.ts new file mode 100644 index 000000000..70190cf7b --- /dev/null +++ b/packages/games/src/pack.ts @@ -0,0 +1,274 @@ +import { z } from "zod"; +import { + gamePredictionResultSchema, + gameDescriptorSchema, + type GameDescriptor, + type GameRules, + type AnalysisRequest, + type AnalysisResponse, + type GamePredictionResult, +} from "@lovat/api"; +import { + analyzeGameReports, + analyzeGameReportStream, + type ReportIdentity, +} from "./engine.js"; +import type { MetricRegistry } from "./registry.js"; +import { GameError } from "./errors.js"; +export interface StoredGameReport extends ReportIdentity { + gameId: string; + gameVersion: number; + reportVersion: number; + data: unknown; +} +type TeamAnalysis = AnalysisResponse["teams"][string]; +export interface GamePrediction { + metrics: readonly string[]; + calculate: (input: { + red: readonly TeamAnalysis[]; + blue: readonly TeamAnalysis[]; + }) => GamePredictionResult; +} +export interface GamePack { + analyzeStream( + reports: AsyncIterable, + request: AnalysisRequest, + ): Promise; + prediction?: GamePrediction; + readonly descriptor: GameDescriptor; + readonly metrics: { + resolve: ( + ids: readonly string[], + ) => { metadata: GameDescriptor["metrics"][number] }[]; + get: (id: string) => { metadata: GameDescriptor["metrics"][number] }; + metadata: () => GameDescriptor["metrics"]; + }; + validate( + data: unknown, + reportVersion: number, + context?: { startTime: number; endTime: number }, + ): Record; + plausible( + data: unknown, + reportVersion: number, + officialScore?: number, + ): boolean; + analyze( + reports: readonly StoredGameReport[], + request: AnalysisRequest, + ): AnalysisResponse; +} +export interface TypedGamePack extends GamePack { + /** For a trusted, typed storage adapter; never for client payloads. */ + fromFacts(identity: ReportIdentity, prepare: () => F): StoredGameReport; +} +export function defineGame< + S extends z.ZodType>, + F, +>(options: { + id: string; + season: number; + version: number; + label: string; + rules: GameRules; + report: { version: number; schema: S }; + olderReports?: readonly { + version: number; + schema: z.ZodType; + upgrade: (data: unknown) => z.input; + }[]; + metrics: MetricRegistry; + prepare: (report: ReportIdentity & { data: z.output }) => F; + prediction?: GamePrediction; + check?: ( + data: z.output, + context: { startTime: number; endTime: number }, + ) => void; + assess?: (data: z.output, officialScore?: number) => boolean; +}): TypedGamePack { + const prepared = new WeakMap F>(); + const codecs = new Map< + number, + { schema: z.ZodType; upgrade?: (data: unknown) => z.input } + >(); + codecs.set(options.report.version, { schema: options.report.schema }); + for (const old of options.olderReports ?? []) { + if (codecs.has(old.version)) throw Error("Duplicate report schema version"); + codecs.set(old.version, old); + } + const metadata = options.metrics.metadata(); + if (metadata.some((metric) => metric.season !== options.season)) + throw Error("Metric season does not match its game"); + const descriptor = gameDescriptorSchema.parse({ + id: options.id, + season: options.season, + version: options.version, + label: options.label, + reportVersion: options.report.version, + reportSchemas: Object.fromEntries( + [...codecs].map(([version, codec]) => [ + String(version), + z.toJSONSchema(codec.schema), + ]), + ), + rules: options.rules, + metrics: metadata, + features: { predictions: Boolean(options.prediction) }, + }); + const decode = (data: unknown, version: number): z.output => { + const codec = codecs.get(version); + if (!codec) + throw new GameError( + 409, + "REPORT_VERSION_UNSUPPORTED", + "Update Collection to a supported report version", + ); + const parsed = codec.schema.safeParse(data); + if (!parsed.success) + throw new GameError( + 400, + "INVALID_GAME_REPORT", + "Report does not match the selected game's schema", + ); + if (!codec.upgrade) return parsed.data as z.output; + const normalized = options.report.schema.safeParse( + codec.upgrade ? codec.upgrade(parsed.data) : parsed.data, + ); + if (!normalized.success) + throw new GameError( + 400, + "INVALID_GAME_REPORT", + "Report cannot be read by the selected game", + ); + return normalized.data; + }; + function checkRequest(request: AnalysisRequest) { + if (request.season !== descriptor.season) + throw new GameError( + 400, + "GAME_SEASON_MISMATCH", + "Report season does not match the selected game", + ); + } + function checkReport(report: StoredGameReport) { + if ( + report.gameId !== descriptor.id || + report.gameVersion !== descriptor.version + ) + throw new GameError( + 409, + "GAME_VERSION_MISMATCH", + "Reports from different game contracts cannot be mixed", + ); + } + function prepareReport(report: StoredGameReport): F { + const trusted = prepared.get(report); + if (trusted) return trusted(); + let data: z.output; + try { + data = decode(report.data, report.reportVersion); + } catch (error) { + if (error instanceof GameError && error.code === "INVALID_GAME_REPORT") + throw new Error("Stored game report is invalid"); + throw error; + } + return options.prepare({ + uuid: report.uuid, + teamNumber: report.teamNumber, + matchKey: report.matchKey, + tournamentKey: report.tournamentKey, + tournamentDate: report.tournamentDate, + data, + }); + } + return { + fromFacts(identity, prepare) { + const report = { + ...identity, + gameId: descriptor.id, + gameVersion: descriptor.version, + reportVersion: descriptor.reportVersion, + data: undefined, + }; + prepared.set(report, prepare); + return report; + }, + descriptor, + metrics: options.metrics, + validate: (data, version, context) => { + const parsed = decode(data, version); + if (context) options.check?.(parsed, context); + return parsed; + }, + plausible: (data, version, officialScore) => + options.assess?.(decode(data, version), officialScore) ?? true, + prediction: options.prediction + ? { + metrics: options.prediction.metrics, + calculate: (input) => + gamePredictionResultSchema.parse( + options.prediction!.calculate(input), + ), + } + : undefined, + analyze(reports, request) { + checkRequest(request); + for (const report of reports) checkReport(report); + return analyzeGameReports( + reports, + request, + options.metrics, + prepareReport, + ); + }, + async analyzeStream(reports, request) { + checkRequest(request); + async function* checked() { + for await (const report of reports) { + checkReport(report); + yield report; + } + } + return analyzeGameReportStream( + checked(), + request, + options.metrics, + prepareReport, + ); + }, + }; +} +export class GameCatalog { + private readonly bySeason = new Map>(); + constructor(games: readonly GamePack[]) { + for (const game of games) { + const { season, version } = game.descriptor; + let versions = this.bySeason.get(season); + if (!versions) { + versions = new Map(); + this.bySeason.set(season, versions); + } + if (versions.has(version)) throw Error("Duplicate game season/version"); + versions.set(version, game); + } + } + get(season: number, version?: number): GamePack { + const versions = this.bySeason.get(season); + const selected = version ?? Math.max(...(versions?.keys() ?? [])); + const game = versions?.get(selected); + if (!game) + throw new GameError( + 400, + "UNSUPPORTED_GAME", + "This game season/version is not installed", + ); + return game; + } + list() { + return [...this.bySeason.values()] + .flatMap((versions) => + [...versions.values()].map((game) => structuredClone(game.descriptor)), + ) + .sort((a, b) => a.season - b.season || a.version - b.version); + } +} diff --git a/packages/games/src/prediction.ts b/packages/games/src/prediction.ts new file mode 100644 index 000000000..8d5876e84 --- /dev/null +++ b/packages/games/src/prediction.ts @@ -0,0 +1,46 @@ +import { GameError } from "./errors.js"; +export function normalPrediction( + series: readonly (readonly number[])[], + allianceSize = 3, +) { + if (series.length !== allianceSize * 2 || series.some((a) => a.length < 2)) + throw new GameError( + 422, + "INSUFFICIENT_DATA", + "At least two matches are needed for each team", + ); + const means = series.map((a) => a.reduce((sum, n) => sum + n, 0) / a.length); + const variance = series.map( + (a, i) => a.reduce((sum, n) => sum + (n - means[i]) ** 2, 0) / a.length, + ); + const difference = + means.slice(0, allianceSize).reduce((s, n) => s + n, 0) - + means.slice(allianceSize).reduce((s, n) => s + n, 0); + const deviation = Math.sqrt(variance.reduce((s, n) => s + n, 0)); + const redWinning = + deviation === 0 + ? difference === 0 + ? 0.5 + : difference > 0 + ? 1 + : 0 + : normalCdf(difference / deviation); + return { + redWinning, + blueWinning: 1 - redWinning, + winningAlliance: redWinning >= 0.5 ? 0 : 1, + }; +} +export function normalCdf(value: number) { + const x = Math.abs(value), + t = 1 / (1 + 0.2316419 * x); + const density = Math.exp((-x * x) / 2) / Math.sqrt(2 * Math.PI); + const tail = + density * + t * + (0.31938153 + + t * + (-0.356563782 + + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429)))); + return value >= 0 ? 1 - tail : tail; +} diff --git a/packages/games/src/registry.ts b/packages/games/src/registry.ts new file mode 100644 index 000000000..6c446aae8 --- /dev/null +++ b/packages/games/src/registry.ts @@ -0,0 +1,202 @@ +import { z } from "zod"; +import { + metricMetadataSchema, + type MetricMetadata, + type MetricValue, +} from "@lovat/api"; + +export interface ReportReducer { + add(state: S): void; + finish(): V | null; +} +export function meanReducer(): ReportReducer { + let count = 0, + total = 0; + return { + add(value) { + total += value; + count++; + }, + finish: () => (count ? total / count : null), + }; +} +export interface MetricAccumulator { + add: (facts: F) => void; + finish: ( + dependencies: ReadonlyMap, + ) => MetricValue | null; +} +export interface MetricDefinition { + start?: () => MetricAccumulator; + metadata: MetricMetadata; + evaluate( + facts: readonly F[], + dependencies: ReadonlyMap, + ): MetricValue | null; + combine( + values: readonly MetricValue[], + level: "tournament" | "team", + ): MetricValue | null; +} +export function defineMetric(definition: { + metadata: MetricMetadata; + output: z.ZodType; + calculate: (facts: F) => S | null; + reports: (states: readonly S[]) => V | null; + reducer?: () => ReportReducer; + aggregate: (values: readonly V[], level: "tournament" | "team") => V | null; +}): MetricDefinition { + const metadata = metricMetadataSchema.parse({ + ...definition.metadata, + outputSchema: z.toJSONSchema(definition.output), + }); + const start = (): MetricAccumulator => { + const states: S[] = []; + const reducer = definition.reducer?.(); + let samples = 0; + return { + add(facts: F) { + const value = definition.calculate(facts); + if (value !== null) { + samples++; + if (reducer) reducer.add(value); + else states.push(value); + } + }, + finish() { + const value = samples + ? reducer + ? reducer.finish() + : definition.reports(states) + : null; + states.length = 0; + return value === null ? null : definition.output.parse(value); + }, + }; + }; + return { + metadata, + start, + evaluate(facts) { + const accumulator = start(); + for (const fact of facts) accumulator.add(fact); + return accumulator.finish(new Map()); + }, + combine(values, level) { + const typed = values.map((value) => definition.output.parse(value)); + const value = typed.length ? definition.aggregate(typed, level) : null; + return value === null ? null : definition.output.parse(value); + }, + }; +} +export function defineDerivedMetric(definition: { + metadata: MetricMetadata; + output: z.ZodType; + calculate: ( + dependencies: ReadonlyMap, + ) => V | null; + aggregate: (values: readonly V[], level: "tournament" | "team") => V | null; +}): MetricDefinition { + return { + metadata: metricMetadataSchema.parse({ + ...definition.metadata, + outputSchema: z.toJSONSchema(definition.output), + }), + start() { + return { + add(_facts: F) {}, + finish(dependencies: ReadonlyMap) { + const value = definition.calculate(dependencies); + return value === null ? null : definition.output.parse(value); + }, + }; + }, + evaluate(_facts, dependencies) { + const value = definition.calculate(dependencies); + return value === null ? null : definition.output.parse(value); + }, + combine(values, level) { + const value = definition.aggregate( + values.map((v) => definition.output.parse(v)), + level, + ); + return value === null ? null : definition.output.parse(value); + }, + }; +} +export class MetricRegistry { + private readonly definitions = new Map>(); + private readonly aliases = new Map(); + constructor(definitions: readonly MetricDefinition[]) { + for (const definition of definitions) { + const { id, aliases } = definition.metadata; + for (const key of [id, ...aliases]) { + if (this.aliases.has(key)) { + throw new Error("Duplicate metric ID or alias: " + key); + } + this.aliases.set(key, id); + } + this.definitions.set(id, definition); + } + this.resolve([...this.definitions.keys()]); + } + get(id: string): MetricDefinition { + const canonical = this.aliases.get(id); + const definition = canonical ? this.definitions.get(canonical) : undefined; + if (!definition) { + throw new RangeError("Unknown metric: " + id); + } + return definition; + } + resolve(ids: readonly string[]): MetricDefinition[] { + const visiting = new Set(); + const visited = new Set(); + const ordered: MetricDefinition[] = []; + const visit = (id: string) => { + const metric = this.get(id); + const canonical = metric.metadata.id; + if (visiting.has(canonical)) { + throw new Error("Metric dependency cycle: " + canonical); + } + if (visited.has(canonical)) { + return; + } + visiting.add(canonical); + for (const dependency of metric.metadata.dependencies) { + visit(dependency); + } + visiting.delete(canonical); + visited.add(canonical); + ordered.push(metric); + }; + ids.forEach(visit); + return ordered; + } + metadata(): MetricMetadata[] { + return [...this.definitions.values()].map((d) => + structuredClone(d.metadata), + ); + } +} +export const mean = (values: readonly number[]): number | null => + values.length + ? values.reduce((sum, value) => sum + value, 0) / values.length + : null; +export function recencyWeightedMean(values: readonly number[]): number | null { + return values.length + ? values + .slice(1) + .reduce((value, next) => value * 0.2 + next * 0.8, values[0]) + : null; +} + +export function defineMetricFor() { + return ( + definition: Parameters>[0], + ) => defineMetric(definition); +} +export function defineDerivedMetricFor() { + return ( + definition: Parameters>[0], + ) => defineDerivedMetric(definition); +} diff --git a/packages/games/test/fixtures.mjs b/packages/games/test/fixtures.mjs new file mode 100644 index 000000000..af4fbda5b --- /dev/null +++ b/packages/games/test/fixtures.mjs @@ -0,0 +1,158 @@ +import { z } from "zod"; +import { + defineGame, + MetricRegistry, + defineMetricFor, + mean, + GameError, +} from "../dist/index.js"; +const glyphRules = { + high: 7, + low: 2, + balance: 13, + winRP: 2, + bonusThreshold: 20, + maxPlausibleScore: 1000, +}; +const glyphPeriods = [ + { id: "setup", label: "Setup", durationSeconds: 15 }, + { id: "play", label: "Play", durationSeconds: 60 }, +]; +const glyphScore = (data) => + data.throws.reduce( + (n, entry) => + n + + entry.count * (entry.zone === "high" ? glyphRules.high : glyphRules.low), + 0, + ) + (data.balanced ? glyphRules.balance : 0); +const metric = defineMetricFor(); +const metadata = (id, kind = "number") => ({ + id, + aliases: id === "glyphScore" ? ["points"] : [], + season: 2099, + version: 1, + label: id, + unit: "points", + kind, + precision: 2, + missing: "exclude", + dependencies: [], + requires: ["throws", "balanced"], +}); +const schema = z + .object({ + throws: z + .array( + z.object({ + zone: z.enum(["high", "low"]), + count: z.number().int().nonnegative(), + }), + ) + .max(50), + balanced: z.boolean(), + }) + .strict(); +const old = z + .object({ + high: z.number().int().nonnegative(), + low: z.number().int().nonnegative(), + balanced: z.boolean(), + }) + .strict(); +export const fictionalGame = defineGame({ + id: "fixture-glyphs", + season: 2099, + version: 1, + label: "Fictional test game", + report: { version: 2, schema }, + olderReports: [ + { + version: 1, + schema: old, + upgrade: (value) => ({ + throws: [ + { zone: "high", count: value.high }, + { zone: "low", count: value.low }, + ], + balanced: value.balanced, + }), + }, + ], + rules: { allianceSize: 2, periods: glyphPeriods, scoring: glyphRules }, + check: (_data, context) => { + if ( + context.endTime - context.startTime > + (glyphPeriods.reduce((n, p) => n + p.durationSeconds, 0) + 1) * 1000 + ) + throw new GameError( + 400, + "INVALID_GAME_TIMING", + "Report exceeds this game's clock", + ); + }, + assess: (data, officialScore) => + glyphScore(data) <= + Math.min(glyphRules.maxPlausibleScore, officialScore ?? Infinity), + prediction: { + metrics: ["glyphScore", "capability"], + calculate({ red, blue }) { + const score = (teams) => + teams.reduce( + (sum, team) => + sum + + (typeof team.metrics.glyphScore?.value === "number" + ? team.metrics.glyphScore.value + : 0), + 0, + ); + const redScore = score(red), + blueScore = score(blue), + redWinning = + redScore === blueScore ? 0.5 : redScore > blueScore ? 1 : 0; + return { + redScore, + blueScore, + redWinning, + blueWinning: 1 - redWinning, + winningAlliance: + redWinning === 0.5 ? "tie" : redWinning === 1 ? "red" : "blue", + redRankingPoints: + (redWinning === 1 ? glyphRules.winRP : redWinning === 0.5 ? 1 : 0) + + (redScore >= glyphRules.bonusThreshold ? 1 : 0), + blueRankingPoints: + (redWinning === 0 ? glyphRules.winRP : redWinning === 0.5 ? 1 : 0) + + (blueScore >= glyphRules.bonusThreshold ? 1 : 0), + }; + }, + }, + prepare: ({ data }) => ({ + score: glyphScore(data), + balanced: data.balanced, + attempts: data.throws.reduce((n, entry) => n + entry.count, 0), + }), + metrics: new MetricRegistry([ + metric({ + metadata: metadata("glyphScore"), + output: z.number(), + calculate: (facts) => facts.score, + reports: mean, + aggregate: mean, + }), + metric({ + metadata: metadata("capability", "structured"), + output: z.object({ canBalance: z.boolean(), capacity: z.number() }), + calculate: (facts) => ({ + canBalance: facts.balanced, + capacity: facts.attempts, + }), + reports: (values) => ({ + canBalance: values.some((v) => v.canBalance), + capacity: Math.max(...values.map((v) => v.capacity)), + }), + aggregate: (values) => ({ + canBalance: values.some((v) => v.canBalance), + capacity: Math.max(...values.map((v) => v.capacity)), + }), + }), + ]), +}); diff --git a/packages/games/test/games.test.mjs b/packages/games/test/games.test.mjs new file mode 100644 index 000000000..31152e395 --- /dev/null +++ b/packages/games/test/games.test.mjs @@ -0,0 +1,141 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { z } from "zod"; +import { + defineGame, + GameCatalog, + MetricRegistry, + defineMetricFor, + mean, +} from "../dist/index.js"; +import { game2026 } from "../dist/2026/index.js"; +import { fictionalGame } from "./fixtures.mjs"; +const report = (data, overrides = {}) => ({ + uuid: "fixture", + teamNumber: 8033, + matchKey: "qm1", + tournamentKey: "2099fixture", + tournamentDate: "2099-03-01", + gameId: "fixture-glyphs", + gameVersion: 1, + reportVersion: 2, + data, + ...overrides, +}); +const request = { + teams: [8033], + metrics: ["points", "capability"], + season: 2099, + timeline: true, +}; +test("different game fields, scoring and structured metrics use the unchanged generic engine", () => { + const response = fictionalGame.analyze( + [ + report({ + throws: [ + { zone: "high", count: 2 }, + { zone: "low", count: 3 }, + ], + balanced: true, + }), + report( + { + throws: [ + { zone: "high", count: 1 }, + { zone: "low", count: 1 }, + ], + balanced: false, + }, + { uuid: "second" }, + ), + report( + { + throws: [ + { zone: "high", count: 2 }, + { zone: "low", count: 3 }, + ], + balanced: true, + }, + { uuid: "third", matchKey: "qm2" }, + ), + ], + request, + ); + assert.equal(response.teams["8033"].metrics.glyphScore.value, 27); + assert.equal(response.teams["8033"].metrics.glyphScore.samples, 2); + assert.deepEqual(response.teams["8033"].metrics.capability.value, { + canBalance: true, + capacity: 5, + }); + assert.equal(response.teams["8033"].timeline.length, 2); +}); +test("historical report schemas upgrade through their owning game module", () => { + const response = fictionalGame.analyze( + [report({ high: 2, low: 3, balanced: true }, { reportVersion: 1 })], + request, + ); + assert.equal(response.teams["8033"].metrics.glyphScore.value, 33); + assert.deepEqual(Object.keys(fictionalGame.descriptor.reportSchemas), [ + "1", + "2", + ]); + assert.equal( + fictionalGame.descriptor.rules.periods.reduce( + (n, p) => n + p.durationSeconds, + 0, + ), + 75, + ); +}); +test("game selection and report versions fail closed without changing another season", () => { + const catalog = new GameCatalog([game2026, fictionalGame]); + assert.equal(catalog.get(2026).descriptor.id, "frc-2026"); + assert.equal(catalog.get(2099).descriptor.id, "fixture-glyphs"); + assert.throws( + () => catalog.get(2027), + (e) => e.code === "UNSUPPORTED_GAME", + ); + assert.throws( + () => + fictionalGame.analyze( + [report({ high: 1 }, { reportVersion: 7 })], + request, + ), + (e) => e.code === "REPORT_VERSION_UNSUPPORTED", + ); + assert.throws( + () => + fictionalGame.analyze( + [report({ throws: [], balanced: false }, { gameId: "another-game" })], + request, + ), + (e) => e.code === "GAME_VERSION_MISMATCH", + ); + assert.throws( + () => fictionalGame.validate({ throws: [], balanced: "yes" }, 2), + (e) => e.code === "INVALID_GAME_REPORT", + ); + assert.throws(() => new GameCatalog([fictionalGame, fictionalGame])); +}); + +test("incremental report reducers preserve missing values and validate their output", async () => { + const { meanReducer } = await import("../dist/index.js"); + const metric = defineMetricFor()({ + metadata: fictionalGame.descriptor.metrics[0], + output: z.number(), + calculate: (value) => value, + reports: () => { + throw Error("The incremental reducer must be used"); + }, + reducer: meanReducer, + aggregate: mean, + }); + const accumulator = metric.start(); + for (const value of [0, null, 4]) accumulator.add(value); + assert.equal(accumulator.finish(new Map()), 2); + assert.equal(metric.evaluate([0, null, 4], new Map()), 2); + assert.equal(metric.start().finish(new Map()), null); + const invalid = metric.start(); + invalid.add(Infinity); + assert.throws(() => invalid.finish(new Map())); +}); diff --git a/packages/games/tsconfig.json b/packages/games/tsconfig.json new file mode 100644 index 000000000..4fc5b0c9c --- /dev/null +++ b/packages/games/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2023", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "declaration": true, + "outDir": "dist", + "rootDir": "src", + "skipLibCheck": true + }, + "include": ["src/**/*.ts"] +} diff --git a/scripts/ci-selection.test.mjs b/scripts/ci-selection.test.mjs index 1cc804a6a..a58d1427c 100644 --- a/scripts/ci-selection.test.mjs +++ b/scripts/ci-selection.test.mjs @@ -17,6 +17,7 @@ test("Server and database changes run consumer contracts while isolated web edit for (const path of [ "apps/server/src/handler/collection/reportSchema.ts", "packages/db/prisma/schema.prisma", + "packages/api/src/games.ts", ]) { const jobs = selectJobs([path]); assert.equal(jobs.server, true);