Skip to content

Commit 00b9c1c

Browse files
committed
feat(deploy): unify Compose startup and standalone installation
1 parent 9229e08 commit 00b9c1c

11 files changed

Lines changed: 471 additions & 204 deletions

File tree

‎.env.example‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@
77
# =============================================================================
88
# 镜像来源
99
# =============================================================================
10-
# 发布的镜像;配合 docker-compose.ghcr.yml 使用,例如
11-
# ghcr.io/webmonitor/webmonitor:1.0.0。留空则从源码构建。
12-
WEBMONITOR_IMAGE=
10+
# 公开应用镜像;docker compose up -d --wait 默认匿名拉取。
11+
# :latest 跟随稳定发布;需要固定版本时改为 :1.0.0。
12+
# 源码开发使用 compose.build.yaml 与独立本地镜像标签。
13+
WEBMONITOR_IMAGE=ghcr.io/webmonitor/webmonitor:latest
1314

1415
# =============================================================================
1516
# 应用安全配置

‎.github/workflows/docker-image.yml‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,8 @@
1414
# pull request -> build only, never push (paths filter below)
1515
# workflow_dispatch -> build and push :main (no :latest)
1616
#
17-
# Packages are published private. Making them public is a one-time manual step in
18-
# the package settings UI: GitHub exposes no API for container visibility. Once a
19-
# package is public it cannot be made private again.
17+
# This package is public and supports anonymous pulls. Visibility is managed in
18+
# the package settings UI, separately from this publishing workflow.
2019
name: docker-image
2120

2221
on:
@@ -29,7 +28,7 @@ on:
2928
- "backend/**"
3029
- "deploy/**"
3130
- "frontend/**"
32-
- "docker-compose.yml"
31+
- "compose*.yaml"
3332
- "pyproject.toml"
3433
- "requirements.txt"
3534
workflow_dispatch:
@@ -199,20 +198,26 @@ jobs:
199198
set -eu
200199
version="${TAG#v}"
201200
notes=$(cat <<'EOF'
202-
Container image (linux/amd64 + linux/arm64):
201+
Public container image (linux/amd64 + linux/arm64):
203202
204-
```
203+
```sh
205204
docker pull ghcr.io/REPO:VERSION
206205
```
207206
208-
Run it instead of building from source:
207+
No registry login or repository clone is required. Follow the README to
208+
download `compose.yaml` and create your own `.env`. Set its image:
209209
210+
```dotenv
211+
WEBMONITOR_IMAGE=ghcr.io/REPO:VERSION
210212
```
211-
echo "WEBMONITOR_IMAGE=ghcr.io/REPO:VERSION" >> .env
212-
docker compose -f docker-compose.yml -f docker-compose.ghcr.yml up -d --wait
213+
214+
Start from the deployment directory:
215+
216+
```sh
217+
docker compose up -d --wait
213218
```
214219
215-
See the README for the required .env values.
220+
Setup, configuration and data-retention limits: https://github.com/REPO#readme
216221
EOF
217222
)
218223
repo_lower=$(printf '%s' "$REPO" | tr '[:upper:]' '[:lower:]')

‎AGENTS.md‎

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Repository Guidelines
22

3-
Legacy v1 of a web content change-monitoring platform with email alerts. Two independent subprojects in one repo: `backend/` (FastAPI + SQLAlchemy + APScheduler + Selenium) and `frontend/` (React CRA SPA). Python 3.12, Node 18, plain JavaScript on the frontend, no migrations, no CI. Backend/API tests are stdlib `unittest` in `tests/`.
3+
Legacy v1 of a web content change-monitoring platform with email alerts. Two independent subprojects in one repo: `backend/` (FastAPI + SQLAlchemy + APScheduler + Selenium) and `frontend/` (React CRA SPA). Python 3.12, Node 18, plain JavaScript on the frontend, no migrations. Backend/API tests are stdlib `unittest` in `tests/`. GitHub Actions builds and publishes the single container image; it does not run the tests.
44

55
> Note: active development happens in the sibling `WebMonitor-Agent/` project; this repo receives maintenance/legacy fixes only.
66
@@ -34,7 +34,7 @@ APScheduler (BackgroundScheduler, per-task interval jobs)
3434
- **Selenium**: one new headless Chrome per scrape (`monitor_service.get_content_with_selenium`): flags `--headless --disable-gpu --no-sandbox --disable-dev-shm-usage`, 30s page load, `WebDriverWait(…, 20)` for `By.XPATH`, extracts `element.text` + `driver.title`, `quit()` in `finally`. Driver resolved by Selenium Manager (apt `chromium-driver` in image).
3535
- **Auth**: JWT bearer (`OAuth2PasswordBearer`, `tokenUrl="/api/auth/login"`), payload `{sub: str(user.id), username}` — **the token's `is_admin` is never trusted**; authorization always re-reads the DB row. `sub` must be a positive-integer string, otherwise 401 with `WWW-Authenticate: Bearer`. Inactive accounts get 403 on an existing token and the same 401 as a bad password at login. bcrypt hashing refuses >72-byte passwords instead of truncating (`core/passwords.py`). No server-side session or token blacklist; logout is client-side only (`POST /api/auth/logout` was removed). Admin gate via `get_current_admin_user`. Public registration accepts `UserRegister` (no role/quota fields); admin creation is `POST /api/auth/users` with `UserCreate`.
3636
- **Email**: per-user `EmailConfig` rows in DB, and nothing else. Resolution is strictly owner-scoped: an explicit `email_config_id` must exist **and belong to that user** (otherwise the send fails with a warning — never a silent fallback to someone else's config) → that user's lowest-id config → **no send at all**. There is no "first config in the table" path and no deployment-level SMTP fallback: `SMTP_*`/`RECEIVER_EMAIL` were removed from `Settings`, compose and the env templates, so a notification can only reach an address the user configured. A task's `email_config_id` is optional (`MonitorTaskCreate`), and a task without one still collects/logs — `MonitorService` skips the owner notification entirely. SMTP_SSL or starttls; failures are logged without credentials and skipped, never raised. `EmailConfigResponse` never contains the password; `PUT` without `smtp_password` keeps the stored one, and an explicit `""`/`null` is a 422. Deleting a config referenced by any task or subscription (including inactive subscriptions) is a 409.
37-
- **DB**: sync SQLAlchemy 2.0, `SessionLocal` + `get_db()` dependency (`db/database.py`); SQLite default, PostgreSQL by changing `DATABASE_URL` only. Schema via `create_all` inside the `main.py` lifespan — **no Alembic**; model changes have no migration path.
37+
- **DB**: sync SQLAlchemy 2.0, `SessionLocal` + `get_db()` dependency (`db/database.py`); SQLite is the supported database. `database.py` always passes `check_same_thread=False`, and no PostgreSQL driver is pinned, so another database would need both a driver and engine changes. `compose.yaml` hardcodes `DATABASE_URL` (no `${...}` interpolation): editing `.env` only affects local runs, and a container deployment needs an explicit Compose override. Schema via `create_all` inside the `main.py` lifespan — **no Alembic**; model changes have no migration path. The SQLite file is the unit to back up.
3838
- **Startup**: `lifespan` → `configure_logging()` (stdout + `LOG_LEVEL`, the only `basicConfig` in the tree) → `bootstrap()` (create tables, then seed an admin only if none exists) → `monitor_scheduler.start()`; shutdown stops the scheduler in a `finally`. If no admin exists and `ADMIN_PASSWORD` is missing/short, or the configured username/email collides with an existing user, startup **fails** with a value-free log line. An existing admin is never reset.
3939
- **Scoping rules**: every private endpoint resolves the task through `task_service.require_owned_task` (404/403, admins included — these endpoints are owner-only); `/monitor-logs/latest` joins on `owner_id`; task logs return `{logs, total}` with `page`/`limit` query params; public task list/detail only return `is_public=True, is_active=True` (anything else is 404) and count only active subscriptions in the `outerjoin` ON clause.
4040
- **Subscriptions**: `subscription_service` owns every create/reactivate/toggle/update path. The DB unique constraint on `(user_id, task_id)` means re-subscribing must reuse the existing row. Activation (new or reactivated) checks publicity and the quota; deactivation and cancellation do not require the task to still be public. A module-level `RLock` serializes the read→check→commit window (single Uvicorn process).
@@ -62,28 +62,39 @@ frontend/
6262
src/utils/ # i18n.js helpers, date.js
6363
deploy/
6464
Dockerfile # multi-stage: CRA build → FastAPI+Chromium runtime that serves both (context: repo root)
65+
.github/workflows/
66+
docker-image.yml # multi-arch build, tag verification, GHCR publish, GitHub Release
67+
compose.yaml # normal deployment: public image (default latest), pull_policy always, healthcheck
68+
compose.build.yaml # development-only override: webmonitor:local, pull_policy build, adds build
6569
image/ # README screenshot asset
6670
```
6771

6872
## Development Commands
6973

7074
```sh
71-
# Docker (full stack)
72-
docker-compose up -d # single container: UI + API on :8000, docs at /docs
75+
# Docker (normal install: no checkout required; compose.yaml + user-created .env)
76+
docker compose up -d --wait # public image, default tag latest
7377
curl -f http://localhost:8000/health # compose healthcheck target
7478

79+
# Docker (build from source; development only, from a clone)
80+
docker compose -f compose.yaml -f compose.build.yaml up --build -d --wait
81+
# single container: UI + API on :8000, docs at /docs
82+
7583
# Backend local (dependency manifest lives at the repo root)
7684
pip install -r requirements.txt
77-
cp .env.example .env # repo root; SECRET_KEY + ADMIN_PASSWORD are required
78-
cd backend && python main.py # uvicorn main:app --host 0.0.0.0 --port 8000
85+
# create .env from the template in README.md; SECRET_KEY + ADMIN_PASSWORD are required
86+
cd backend && mkdir -p data && python main.py # SQLite does not create the parent directory
7987

8088
# Frontend local
8189
cd frontend && pnpm install && pnpm start # CRA dev server :3000, proxies /api to :8000 (package.json "proxy")
8290
pnpm run build # production build → build/, copied into the single Docker image
91+
92+
# Backend tests (stdlib unittest; no extra dependencies)
93+
python -m unittest discover -s tests -p 'test_*.py'
8394
```
8495

85-
- No lint/format commands exist (backend has no linter config; frontend eslint is CRA defaults via `package.json` eslintConfig).
86-
- No test commands that do anything: see Testing & QA.
96+
- Ruff is configured in the repo-root `pyproject.toml` (`target-version = "py312"`, `line-length = 120`) but the tree is not clean; do not run repo-wide `--fix` as a side effect. There is no formatter command; frontend linting is CRA's bundled eslint defaults.
97+
- The release image is public at `ghcr.io/webmonitor/webmonitor` (anonymous pulls work) for `linux/amd64` + `linux/arm64`; `compose.yaml` defaults to `:latest` and uses `pull_policy: always`. Pin `:1.0.0` in `WEBMONITOR_IMAGE` when a deployment needs a fixed release. `latest` moves only for stable release tags; `main` follows the development branch. A normal install downloads only `compose.yaml` and creates `.env`; only source development clones the repository and uses `compose.build.yaml`.
8798

8899
## Code Conventions & Common Patterns
89100

@@ -113,20 +124,21 @@ pnpm run build # production build → build/, copied
113124
| `backend/app/services/auth_service.py` | JWT/bcrypt, `get_current_user`, `get_current_admin_user` |
114125
| `frontend/src/App.js` | Routes + MUI theme |
115126
| `frontend/src/contexts/AuthContext.js` | Auth state, token storage, axios base config |
116-
| `docker-compose.yml` | One `webmonitor` service on :8000, env defaults, healthcheck |
127+
| `compose.yaml` | Normal deployment: one `webmonitor` service on :8000, image default `latest`, `pull_policy: always`, healthcheck |
128+
| `compose.build.yaml` | Development-only source-build override: builds `webmonitor:local` with `pull_policy: build` |
117129
| `deploy/Dockerfile` | Single multi-stage build definition (context: repo root); backend serves the SPA, no reverse proxy, no CORS |
118130
| `backend/app/services/bootstrap.py` | Table creation + first-admin seeding rules |
119131
| `backend/app/services/subscription_service.py` | Only implementation of subscribe/reactivate/toggle/update |
120-
| `.env.example` | Env template; `SECRET_KEY` and `ADMIN_PASSWORD` are intentionally blank (no usable weak default) |
132+
| `.env.example` | Environment template for a source checkout; a normal install creates `.env` from the README template |
121133

122134
## Runtime/Tooling Preferences
123135

124136
- Python 3.12 (`python:3.12-slim` image). Dependency pins live in the repo-root `pyproject.toml`; `requirements.txt` next to it is generated by `uv pip compile --generate-hashes --python-version 3.12 --universal`. No lock file.
125137
- Node 18 (`node:18-alpine`); pnpm 10 with committed `pnpm-lock.yaml` (`packageManager` pinned; images run `pnpm install --frozen-lockfile`); react-scripts 5.0.1 (CRA, pinned).
126138
- Frontend stack after the dependency upgrade: React 19.3, MUI 9.5 (`@mui/material` + `@mui/icons-material`), TanStack Query 5, react-router-dom 6.30 (v7 needs Node ≥20, so it stays on 6), i18next 26 + react-i18next 17, framer-motion 14, axios 1.20. `devDependencies` are limited to what CRA's bundled eslint/fork-ts-checker actually need (`eslint-plugin-jest` 25.7, `typescript` 4.9.5); raising either breaks `react-scripts` peer resolution. `@mui/x-data-grid`, `@mui/x-date-pickers` and `web-vitals` were unused and removed.
127139
- Chromium comes from apt (`chromium` + `chromium-driver`) inside the backend image; Selenium Manager resolves the driver from `PATH` (no `CHROME_BIN`/`CHROME_DRIVER` env).
128-
- Docker: backend container runs as non-root `appuser`; SQLite DB lives at `/app/data/webmonitor.db` with **no volume** — data does not survive container rebuilds.
129-
- Env vars are read only via pydantic-settings `.env` (backend) and `REACT_APP_*` (frontend). The real `.env` lives at the repo root and is gitignored; `backend/.env` is a symlink to it so `cd backend && python main.py` finds the same values. Both are excluded from the Docker build context by `.dockerignore` (`**/.env*`, with `.env.example` re-included).
140+
- Docker: backend container runs as non-root `appuser`; SQLite DB lives at `/app/data/webmonitor.db` with **no volume** — data is lost when the container is recreated (image tag change, `docker compose down`, `--force-recreate`, or a `latest` update under `pull_policy: always`), and must be backed up before upgrades or rollbacks. The published multi-arch image is public; `compose.yaml` defaults to `latest`, while a fixed deployment pins `WEBMONITOR_IMAGE` to `:1.0.0`.
141+
- Env vars are read only via pydantic-settings `.env` (backend) and `REACT_APP_*` (frontend). In a source checkout the real `.env` lives at the repo root and is gitignored; `backend/.env` is a symlink to it so `cd backend && python main.py` finds the same values. A normal install creates `.env` next to the downloaded `compose.yaml`. Both are excluded from the Docker build context by `.dockerignore` (`**/.env*`, with `.env.example` re-included).
130142
- **Single image, single origin.** `deploy/Dockerfile` is multi-stage: it builds the CRA bundle and copies it next to the backend, and `backend/main.py` serves it (`FRONTEND_DIST`, default `web/`) on the same port as `/api`. Consequences:
131143
- Only one container and one port (`8000`); `docker compose up -d` starts `webmonitor` alone.
132144
- No CORS middleware and no `BACKEND_CORS_ORIGINS`; none is needed because browser and API share an origin.
@@ -135,8 +147,8 @@ pnpm run build # production build → build/, copied
135147

136148
## Testing & QA
137149

138-
- **No automated tests and no CI** (no pytest, no `*.test.js`, no `.github/workflows`). `pnpm test` finds no tests; backend has no test runner installed.
139-
- **`tests/` (stdlib `unittest`, no extra dependencies)** — `support.py` builds an isolated temp SQLite + real uvicorn thread (empty `ProxyHandler`); run everything with `python -m unittest discover -s tests -p 'test_*.py'`. Coverage: scheduler job binding/reschedule/removal (`test_scheduler.py`), auth + ownership + log pagination + public tasks + email config protocol (`test_api.py`), subscription state machine (`test_subscriptions.py`), settings/password/bootstrap (`test_bootstrap.py`).
150+
- **CI publishes the image only.** `.github/workflows/docker-image.yml` builds `linux/amd64` and `linux/arm64` on native runners, merges the manifest, and pushes to GHCR. A `v*` tag is verified against `pyproject.toml` and `backend/app/core/config.py`, then published as `X.Y.Z`, `X.Y`, `latest`, and `sha-<short>` with a GitHub Release; `main` publishes `:main`; pull requests build without pushing. `latest` never moves for a development build or prerelease. No test job runs in CI; frontend `pnpm test` finds no tests.
151+
- **`tests/` (stdlib `unittest`, no extra dependencies)** — `support.py` builds an isolated temp SQLite + real uvicorn thread (empty `ProxyHandler`); run everything with `python -m unittest discover -s tests -p 'test_*.py'`. There are 86 test methods: scheduler job binding/reschedule/removal (10 in `test_scheduler.py`), auth + ownership + log pagination + public tasks + email config protocol (30 in `test_api.py`), subscription state machine (15 in `test_subscriptions.py`), settings/password/bootstrap (20 in `test_bootstrap.py`), and email resolution/failures (11 in `test_email.py`).
140152
- **`tests/smoke_runtime.py`** is the behavioral acceptance run: local HTTP fixture + loopback SMTP sink + real Selenium + real scheduler. `--serve` keeps the stack up for browser checks. It prints pass/fail lines and exits non-zero on failure.
141153
- Ad-hoc runtime checks: `GET /health`, and the authorized test endpoints — `POST /api/monitor-tasks/{id}/test`, `POST /api/email-configs/{id}/test`, `POST /api/blacklist-domains/test` (`/api/test-email` was removed).
142-
- When changing behavior, exercise the real path: run the stack, hit the affected endpoint (or `pnpm start` + browser for UI), and report observed results. If adding tests, keep them self-contained (no test infra exists to extend).
154+
- When changing behavior, exercise the real path: run the stack, hit the affected endpoint (or `pnpm start` + browser for UI), and report observed results. If adding tests, extend the existing `tests/support.py` helpers and keep each test self-contained.

0 commit comments

Comments
 (0)