Skip to content

About

This is the server of the cardQuery app in Linux

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

54 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CardQuery - Campus Fee Query Backend

Flask / Celery / Redis / SQLAlchemy backend for campus electricity and water balance queries, with email login, room binding, history and asynchronous tasks with replayable SSE progress.

Architecture

flowchart LR
    Client[iOS / CLI] --> API[Flask + Gunicorn]
    API --> Redis[Redis sessions / task state]
    API --> Broker[Redis Celery broker]
    Broker --> Worker[Celery Worker]
    Worker --> Campus[Campus query API]
    Worker --> DB[SQLite]
    API --> DB
    Worker --> Events[Redis Streams]
    Events --> API
    API -->|SSE| Client
    Scheduler[APScheduler] --> Broker
Loading
  • Codes: secrets generation, five-minute expiry, atomic single use, five failed attempts before invalidation. Sending limits: once/minute and five/hour per email, thirty/hour per client IP.
  • Sessions: revocable Redis Bearer sessions, SHA-256 token digests as keys, ownership checks and explicit admin allowlist.
  • Storage: user profiles and history in SQLite, WAL, transactions, atomic counters, unique (email, query_date) and upsert.
  • Tasks: HTTP 202 + task ID, Celery Worker, submission idempotency, saved per-user progress and accurate outcome counts.
  • SSE: named events, Redis event IDs, replay/resume, heartbeat, revocation checks and proxy buffering controls.
  • Operations: Gunicorn, separate Worker/Scheduler, Docker Compose, request IDs, integration tests and GitHub Actions.

Setup

Use Python 3.12 and Redis 7.x:

python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-dev.txt
cp doNotUpload.env.example doNotUpload.env

Edit the environment file; real credentials and campus identifiers are intentionally absent.

Configuration Meaning
DATABASE_PATH SQLite path; use the existing history database when upgrading.
REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_PASS Codes, sessions, task state and events.
CELERY_BROKER_URL Broker URL; include its password if Redis requires one.
ADMIN_EMAILS Comma-separated school emails; empty means no admins.
SESSION_TTL_SECONDS Default seven days.
SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS Real email delivery settings.
ROOM_USER_ID, DEVICE_ID, AREA_ID_ELEC, AREA_ID_WATER Existing campus configuration. Missing settings fail queries explicitly.
TRUST_PROXY Enable only behind one trusted proxy that overwrites forwarded headers.
LOG_DIR Logs from the Linux launcher.

Legacy private config.py remains supported on the original Linux path. Start Redis, then use separate terminals:

gunicorn --config gunicorn.conf.py app:app
celery -A verification_service.celery worker --loglevel=info --concurrency=2
python scheduler_service.py

The Scheduler submits the daily batch at 09:00 Asia/Shanghai. On Linux, python start_server.py daemon manages these together; stop, restart and status remain available. Do not also start a separate Scheduler with this launcher.

Use HTTPS remotely. deploy/nginx.conf.example supplies SSE proxy settings for an existing TLS server block; python app.py is for local development.

Optional APNs

APNS_ENABLED=false by default. The original adapter can be enabled with its Apple configuration and requirements-apns.txt in a compatible environment. Initialization happens inside the push task, so missing Apple dependencies/certificates do not stop ordinary queries. Real delivery and legacy SDK compatibility are not covered by core tests.

Existing data migration

Stop the old server and back up its SQLite database and users_data.json first. Set DATABASE_PATH to the database to retain:

python migrate_users.py /path/to/users_data.json --dry-run
python migrate_users.py /path/to/users_data.json

The migration validates all input, imports in one transaction, leaves JSON unchanged and skips existing emails. Times/counts are preserved; old records without a login count use the legacy initial value of one. Missing required room/time fields or conflicting emails abort import.

API, Scheduler and the user viewer now read SQLite only. If old history has duplicate (email, query_date) rows, unique-index creation fails without deleting records; back up and review those duplicates. Import does not automatically copy an old database into a Docker volume.

Authentication and client upgrade

Public endpoints: POST /api/send_code, POST /api/verify_code, POST /api/verify_code_with_room and GET /api/health (process liveness).

Verification returns access_token, token_type: Bearer and expires_in. Other calls need Authorization: Bearer <token>.

  1. One-step login: email + code + room information to /api/verify_code_with_room.
  2. Two-step login: /api/verify_code consumes the code; call /api/verify_code_with_room with the returned Bearer session, email and room information, without reusing the code.

Room fields: building_code, building_name, floor_code, floor_name, room_code and room_name. Supply actual campus values. First registration binds the room; later logins preserve it. POST /api/logout revokes the session, including connected SSE access.

Old clients require changes: protected requests need Bearer authentication; manual query returns HTTP 202 + task ID instead of waiting for completion.

Task API

curl -i -X POST http://127.0.0.1:5000/api/tasks \
  -H "Authorization: Bearer ${CARDQUERY_TOKEN}" \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: query-request-001' \
  -d '{}'

An empty object queries the caller's room. Normal users cannot select another email. Admins may send {"email":"[email protected]"} for one registered user, or explicitly {"all_users":true} for a batch. An omitted email never implicitly grants a batch.

HTTP 202 example (IDs vary); the response also includes Location:

{
  "task_id": "<uuid>",
  "status": "queued",
  "total": 1,
  "completed": 0,
  "succeeded": 0,
  "failed": 0,
  "status_url": "/api/tasks/<uuid>",
  "events_url": "/api/tasks/<uuid>/events"
}
  • POST /api/scheduler/manual_query aliases submission.
  • GET /api/tasks/<task_id> returns state; GET /api/tasks/<task_id>/events streams progress.
  • Only owner/admin may access a task; others receive 404.
  • Same caller + Idempotency-Key + scope returns the previous task; conflicting scope returns 409.
  • Ten new tasks per caller/minute; idempotent retries do not consume this limit.
  • Failed publication returns 503 and saves a failed task; retry it with a new idempotency key.
  • A Worker may start before the submission response reaches the client.

SSE replay and resume

curl -N http://127.0.0.1:5000/api/tasks/${CARDQUERY_TASK_ID}/events \
  -H "Authorization: Bearer ${CARDQUERY_TOKEN}"

Example frame:

id: 1760000000200-0
event: completed
data: {"task_id":"<uuid>","status":"succeeded","total":1,"completed":1,"succeeded":1,"failed":0}

Events: queued, started, progress, completed or failed. Reconnect using the last received ID as Last-Event-ID; only newer events are returned. No header replays from the beginning; invalid/future IDs return 400. Idle streams send comment heartbeats every fifteen seconds, and terminal streams close after draining history.

For browsers use streaming fetch with Authorization; native EventSource cannot set that custom header. Tokens are never accepted through URL query parameters.

Task states: queued, running, succeeded, partial and failed. A user counts as successful only when both balances and the history write succeed; partial results are still stored.

Delivery boundaries

  • State/event updates are atomic in Redis, retained for 24 hours of inactivity and refreshed by new events. Compose enables AOF.
  • Query tasks use late acknowledgement and worker-loss rejection. Per-task leases prevent duplicate concurrent execution; redelivery skips checkpointed users. The in-flight user's read-only query can repeat; daily upsert prevents duplicate rows.
  • Notifications follow checkpoints; external push delivery is not exactly-once.
  • State creation and Celery publication are separate: a producer crash between them may leave a queued record. There is no transactional outbox.
  • SQLite targets a single host. Each active SSE occupies a Gunicorn thread; production capacity requires load testing.

Other endpoints

Endpoint Access
GET /api/user_info/<email> Self/admin
GET /api/query_history/<email> Self/admin; last 30 daily records
POST /api/device_token Self/admin; registered user, 64-character hex token
GET /api/device_token/<email> Self/admin
GET /api/users_stats Admin
GET /api/scheduler/status Admin; shared Redis heartbeat

Responses include X-Request-ID. Application request logs contain route, status and response setup latency, without Authorization headers or codes.

Docker Compose

Copy/edit doNotUpload.env and set REDIS_PASS to a nonempty URL-safe hex secret. Compose configures Redis and the broker password; supply actual SMTP/campus settings separately.

docker compose --env-file doNotUpload.env up --build -d
docker compose --env-file doNotUpload.env logs -f api worker scheduler

API binds host loopback port 5000 for a TLS proxy; Redis has no host port. SQLite and Redis AOF have named volumes. API/Worker/Scheduler share one data volume and run as an unprivileged user.

Migrate/copy existing data into that volume before switching traffic. This single-host configuration does not establish Kubernetes operation.

Testing

Install requirements-dev.txt; put redis-server on PATH or specify its binary:

python -m pytest -q
REDIS_SERVER_BINARY=/path/to/redis-server python -m pytest -q

Tests create/stop a dedicated Redis process on a random loopback port and temporary SQLite files. They never contact real campus, SMTP or Apple services. Coverage includes concurrent code consumption, authorization, SQL concurrency, migration, queue failure, checkpoint resumption, SSE replay/heartbeat/revocation, a real Redis + Celery Worker, and a two-worker Gunicorn HTTP/SSE smoke test.

python test_scheduler.py invokes the new database/task tests. Older debug guides describe the legacy system; this README defines the current API contract.

.github/workflows/tests.yml runs tests on Python 3.12 with Redis. A saved workflow does not imply remote CI has passed.

Backend experience

The project demonstrates API design, session/role authorization, Redis Lua atomicity, task queues, SQL transactions/concurrency, idempotency, SSE replay, process separation, testing and deployment configuration. Production user counts, uptime, throughput and availability still require actual operational measurements.

About

This is the server of the cardQuery app in Linux

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages