Spaces:
Running on T4
Running on T4
File size: 8,338 Bytes
2756f0f 4b1e064 7a3215f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | # Cognivision Baseball backend
This is the FastAPI backend for the Cognivision Baseball app. It covers accounts, teams, media, sessions and drills, the coach loop, billing, and the AI coach swing report.
- **Design:** [DESIGN.md](DESIGN.md)
- **Rules for contributors:** [CONTRIBUTING.md](CONTRIBUTING.md)
- **Swing report output:** [../AI-coach-agent/docs/SWING_REPORT_API.md](../AI-coach-agent/docs/SWING_REPORT_API.md)
## Setup
Requirements: Python 3.11, and Docker for the local test Postgres.
```bash
cd backend
python3.11 -m venv .venv
.venv/bin/pip install -e ".[dev]" -e ../AI-coach-agent
cp .env.example .env # then fill in DATABASE_URL, JWT_SECRET, STORAGE_*, GOOGLE_API_KEY
```
## Run
```bash
.venv/bin/alembic upgrade head # create or upgrade the schema
.venv/bin/uvicorn app.main:app --reload # API on http://localhost:8000, docs at /docs (not in prod)
.venv/bin/python -m app.jobs.cleanup # schedule this hourly (uploads, abandoned sessions, media)
```
## Test
```bash
docker run -d --name cognivision-backend-pg -e POSTGRES_USER=app -e POSTGRES_PASSWORD=app \
-e POSTGRES_DB=app_test -p 55440:5432 postgres:16-alpine
TEST_DATABASE_NAME=app_test .venv/bin/python -m pytest
.venv/bin/ruff check app tests
```
- Each run creates a fresh database named by `TEST_DATABASE_NAME` and migrates it with Alembic.
- S3 is simulated in-process with moto.
- Gemini is not called: the AI coach falls back to its rule-based text.
## Environment
| Variable | Purpose |
|---|---|
| `ENV` | `dev`, `test` or `prod`. `prod` hides `/docs`. |
| `DATABASE_URL` | `postgresql+asyncpg://user:password@host/db` (Neon or Supabase) |
| `JWT_SECRET` | Long random secret for access tokens |
| `STORAGE_ENDPOINT`, `STORAGE_REGION`, `STORAGE_BUCKET`, `STORAGE_KEY`, `STORAGE_SECRET` | DigitalOcean Spaces bucket and access keys |
| `GOOGLE_API_KEY` | Gemini key for the coach text. Without it, rule-based text is used. |
| `RESEND_API_KEY`, `EMAIL_FROM`, `PASSWORD_RESET_URL` | Password reset email (milestone 4) |
| `FCM_PROJECT_ID`, `FCM_SERVICE_ACCOUNT_FILE` | Push notifications (milestone 3) |
| `APPLE_CLIENT_IDS`, `GOOGLE_CLIENT_IDS` | Social sign-in audiences (JSON lists) |
| `APPLE_BUNDLE_ID`, `APPLE_ENVIRONMENT`, `GOOGLE_PACKAGE_NAME`, `GOOGLE_SERVICE_ACCOUNT_FILE`, `GOOGLE_PUBSUB_AUDIENCE`, `PRO_PRODUCT_IDS` | Billing (milestone 4) |
## Docker
```bash
docker build -f backend/Dockerfile -t cognivision-backend . # from the repository root
docker run --env-file backend/.env cognivision-backend alembic upgrade head
docker run --env-file backend/.env -p 8000:8000 cognivision-backend
```
For Firebase on a Hugging Face Docker Space running this backend, set `FCM_PROJECT_ID` to your Firebase project ID
and `FCM_SERVICE_ACCOUNT_FILE` to `/tmp/firebase-service-account.json` in the Space's variables. Add the entire
service account JSON as a secret named `FCM_SERVICE_ACCOUNT_JSON`. At startup, the container writes that secret
to the configured path with owner-only permissions before starting the API. Keep the JSON out of Git and Docker
build arguments. Without the JSON secret, startup still supports an existing credentials file or disabled push.
The repository's root Dockerfile and existing Hugging Face deployment run the separate GPU analysis API;
this setup requires deploying `backend/Dockerfile` with Space `app_port: 8000`.
## API request/response diagnostics
Apply `alembic upgrade head` before deploying this version. The `api_request_logs`
table records every HTTP call handled by this backend, including failed validation,
authentication failures, unknown routes, health checks, and repeated requests.
The separate GPU API and standalone coach API do not write to this backend table;
the ML payload forwarded to the swing-report endpoint is captured here in full
within the configured JSON size limit.
Each row includes the request ID (also returned as `X-Request-Id`), timestamp,
method, route/path, authenticated account ID when available, session/analysis ID
and revision, HTTP status, duration, error code/type, service build version,
selected headers, query parameters, and sanitized request/response JSON. For a
swing report this includes event times, measurement values and quality reasons,
benchmarks, scores, chosen focus/drill, provider/fallback metadata, and generated
coaching text. The logger does not change measurement or scoring logic.
`request_payload` and `response_payload` contain `capture_status`,
`observed_bytes`, and `body`. JSON bodies up to `API_AUDIT_MAX_BODY_BYTES` (default
1 MiB per direction) are captured. Larger bodies are marked `truncated` and their
body is omitted, never stored as an invalid partial JSON document. Malformed JSON,
binary/media bodies, and unread/incomplete streams are explicitly marked. Video
bytes are never buffered for logging. Passwords, tokens, authorization, cookies,
receipts, webhook encoded data, emails, phone numbers, and URLs are redacted;
athlete measurements and report text remain diagnostic data. Restrict database
access to these records; audit browsing is restricted to explicitly allowlisted accounts.
Writes use their own transaction after handling the request, so application
rollbacks do not erase diagnostics. They are best-effort with a bounded timeout
(default two seconds): a database outage or full audit table does not replace the
API response. Such failures emit `api_audit_write_failed` with request ID and
exception class only. No database logger can guarantee a row during a database
outage or process termination. The hourly cleanup command removes records older
than `API_AUDIT_RETENTION_DAYS` (default 30). Set `SERVICE_VERSION` to the deployed
commit/build ID. `API_AUDIT_ENABLED=false` disables collection.
Find a reported analysis:
```sql
SELECT created_at, request_id, session_id, analysis_id, analysis_revision,
status_code, duration_ms, service_version,
request_payload->'body' AS input,
response_payload->'body' AS output
FROM api_request_logs
WHERE analysis_id = 'analysis_001'
ORDER BY created_at DESC;
```
Trace a request or recent failures:
```sql
SELECT * FROM api_request_logs WHERE request_id = 'request-id-from-response';
SELECT created_at, request_id, route, status_code, error_code, response_payload
FROM api_request_logs
WHERE status_code >= 400
ORDER BY created_at DESC LIMIT 100;
```
A repeated analysis revision can legitimately return an older stored report; the
request log retains each submitted payload and the actual returned response so
that difference can be investigated.
### Read logs through the API
Set `API_AUDIT_READER_ACCOUNT_IDS` to a JSON array of trusted operator account UUIDs
and restart the backend. The default empty list denies access to everyone. Player
or coach status alone does not grant access. Use the operator's normal access JWT:
```dotenv
API_AUDIT_READER_ACCOUNT_IDS=["YOUR-OPERATOR-ACCOUNT-UUID"]
```
- `GET /v1/admin/api-logs`: newest-first metadata, with `items` and `next_cursor`.
Filters: `request_id`, `session_id`, `analysis_id`, `account_id`, `status_code`,
`method` (uppercase), `route` (exact route template), `since`, and `until`.
Date filters apply to `created_at`, are timezone-aware, and use an inclusive
`since` and exclusive `until`. `limit` defaults to 50, maximum 200. Pass
`next_cursor` as `cursor` with the same filters to fetch another page.
- `GET /v1/admin/api-logs/{log_id}`: metadata plus saved sanitized request/response
bodies, selected headers, and query parameters. Use the log row's `id`, not its
`request_id`, for this URL.
```bash
curl "$API_BASE_URL/v1/admin/api-logs?analysis_id=analysis_001&limit=20" \
-H "Authorization: Bearer $ACCESS_TOKEN"
curl "$API_BASE_URL/v1/admin/api-logs/$LOG_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN"
```
Returns 401 without valid authentication, 403 without allowlist access, 400 for
invalid filters, and 404 for a missing/expired log ID. Successful responses use
`Cache-Control: no-store`. Lists omit payload columns; fetch individual records to
inspect bodies. Log reads are themselves audited, but their response bodies are
marked `omitted_audit_read` to avoid recursively duplicating saved payloads.
No additional database migration is needed beyond the original audit-log table.
|