A Tmall / Taobao review-scraping + analysis system built on FastAPI, Celery, Playwright, PostgreSQL, and Redis.
Rolling fixes on master closed the original code-review findings and more:
- Authentication. Admin / task-management / download / analysis /
WebSocket /
/metricsall acceptX-API-Keyor HTTP Basic Auth. Non-localAPP_ENVrefuses to start with empty keys (override withALLOW_INSECURE_AUTH=1). Dashboard JS stores the key insessionStorageand usesdownloadWithApiKeyfor artifact links. - Product uniqueness.
UNIQUE(platform, external_product_id)plus a savepoint-basedget_or_create_productshared by API + collector. - Task lifecycle.
start_taskCAS is queued-only; late-ack redelivery of done/failed is a no-op. SoftTimeLimit marks the row failed and balances the active gauge. Queued + running stale reapers run at startup and every 5 minutes. - Path / injection sandbox. Export filenames, report paths, and delete
unlinks are all
ensure_within-gated; CSV/XLSX cells are formula-safe. - Analysis. Review cap (10k), dialect-native upsert, Redis cache,
asyncio.to_threadfor jieba, and a 20/min rate limit. - Concurrency. Process-local semaphore + Redis Lua global scrape slot; thread fallback refused outside local/test.
- Ops.
/healthreports db/redis/workers/stale counts; docker-compose binds to loopback and requires secrets via${VAR:?}. - Alerting (r11).
alert()delivers SMTP email viasmtp_*/notify_to(STARTTLS or implicit SSL on 465) in addition to the Feishu webhook;deliver=Falsestill logs only. Parser pure helpers now have JSONP/mtop fixture coverage (no network). - Failure artifacts (r12). On scrape failure the collector dumps
live page HTML + screenshot into the task dir;
write_failure_artifactspreserves those instead of overwriting with a traceback wrapper. - Retry lineage (r13).
task_to_info/TaskInfoexposeretry_count+parent_task_id; HTTP/retrykeeps the fullnew_taskpayload (was silently dropped by the response model). - Create-task cache bust (r14). Successful
create_tmall_scrape_tasknow callsinvalidate_task_cacheso the 30stasks:list:*andfrontend:overviewcaches cannot hide a just-created task (retry/delete already did this; create did not). - Task-list cache policy (r15). List reads and invalidation now share
TASK_LIST_CACHE_LIMITS(10/20/50/100). Noncanonical limits bypass cache, while the dashboard's 50/100-item requests are cached and reliably invalidated.
See the recent git log for the full trail.
Open a terminal in this directory and run:
:: One-off setup (creates .venv, installs deps, installs Playwright)
run.bat
:: Start everything detached (no window)
start.vbs
:: Tail the live log
start_hidden.cmd
:: Stop everything
shutdown.batThere is no start.bat / stop.bat / service_install.bat in
this repo — those were renamed in an earlier audit round to avoid clashing
with the Windows start builtin and because we no longer register a
Scheduled Task. Please update any local docs you have that still reference
those names.
cp .env.example .env
# Edit .env to set POSTGRES_PASSWORD, ADMIN_API_KEY, ADMIN_METRICS_BASIC_AUTH,
# GRAFANA_ADMIN_PASSWORD.
docker compose up -dThe compose file binds every service to 127.0.0.1 so nothing is exposed
on the LAN by default.
| Endpoint | Auth required |
|---|---|
GET /, /reviews, /tasks ... |
none (HTML shell only) |
GET/POST /api/reviews/tmall/... |
X-API-Key (when ADMIN_API_KEY set) |
GET /api/products |
X-API-Key |
WS /api/reviews/tmall/tasks/{id}/ws |
?api_key= or X-API-Key |
GET /api/analysis/tasks/... |
X-API-Key (20/min) |
GET /api/admin/worker-health |
X-API-Key |
POST /api/admin/reap-stale |
X-API-Key |
GET /metrics |
HTTP Basic (ADMIN_METRICS_BASIC_AUTH) |
The dashboard JS reads the key from sessionStorage (key
review_scraper_api_key), attaches it to every same-origin fetch(),
and uses window.downloadWithApiKey for artifact / report downloads
(plain <a href> cannot send the header).
| Env var | Default | Notes |
|---|---|---|
DATABASE_URL |
sqlite:///./data/app.db |
Postgres recommended for production |
REDIS_URL |
memory:// |
Set to redis://... for any real use |
REDIS_PASSWORD |
unset | Required by docker-compose (:? fail-closed) |
APP_ENV |
local |
local/test allow empty auth keys |
ADMIN_API_KEY |
"" (disabled) |
When set, X-API-Key on admin / mutate / analysis / WS |
ADMIN_METRICS_BASIC_AUTH |
"" (disabled) |
When set, Basic Auth on /metrics |
ALLOW_INSECURE_AUTH |
0 |
Non-local escape hatch for empty keys |
TRUSTED_HOSTS |
localhost,127.0.0.1 |
Host header allow-list outside local/test |
SCRAPE_MAX_CONCURRENT |
3 |
Process + Redis-shared in-flight cap |
SCRAPE_TASK_TIMEOUT |
1800 seconds (30 min) | Must exceed realistic task duration |
TMALL_LOGIN_TIMEOUT |
300 seconds | Headed login-wall wait budget |
BROWSER_POOL_ENABLED |
unset (pool disabled) | Opt-in long-lived Playwright contexts |
Exports always produce CSV and JSON. XLSX is best-effort (requires pandas/openpyxl); when it is missing the UI hides the XLSX download button instead of linking to a 404.
python -m pytest -qThe project also keeps python -m unittest discover -s tests -v working
for non-pytest-aware callers; the two runs cover the same set of assertions
today.
| Endpoint | Use as | Behaviour |
|---|---|---|
GET /healthz |
liveness | Always 200 if the process accepts HTTP. Body includes version. No DB/Redis I/O. |
GET /health |
readiness | Aggregates DB ping, Redis ping, worker heartbeats, and stale task counts. Status is healthy / degraded / unhealthy. |
Example readiness payload:
{
"status": "healthy",
"components": {
"api": "up",
"database": "up",
"redis": "up",
"workers": {"any_alive": true, "alive_count": 1},
"stale_tasks": {"running": 0, "queued": 0}
}
}Point orchestrator liveness at /healthz and readiness at /health so a
brief Redis blip does not get the API process killed.
Internal project, no public license declared.