# Deploy Same model as the other BitReport projects (see `app.photoreport.pt/DEPLOY.md`, BIT-23722): push to `main` on Gitea -> webhook -> the container pulls and redeploys itself. No manual `scp`/`rsync` of code. ## Flow per container 1. Gitea sends a push webhook to `https:///_deploy/gitea` (one webhook per container). 2. The receiver (small Node service, `infra/deploy-receiver`) verifies `X-Gitea-Signature` (HMAC-SHA256 with the webhook secret from `.env`), checks `ref == refs/heads/main`, and that the push touched a path this container owns (table below). Otherwise it answers 202 and does nothing. 3. It runs `infra/deploy/.sh ` under a lock (one deploy at a time per container): - `git fetch` + `git reset --hard ` in `/srv/photoreport` - `pnpm install --frozen-lockfile` / `cargo build --release -p ` as needed - build only the affected package (`pnpm --filter build`) - API only: `prisma migrate deploy` - reload the process (PM2 for Node, systemd for Rust/Python workers) - health check (`/health` must report the new `version`); on failure, reset to the previous sha and reload 4. Result (sha, duration, status) is posted to the deploy log and, on failure, to the notifications channel. ## What a deploy never touches (norm BIT-25005) - `.env` is never created from `.env.example` over an existing file and never overwritten; a backup `.env.bak.deploy` is written before each deploy. New variables are appended, never replaced. - Data directories, Garage buckets, database contents (only versioned migrations run). ## Path ownership | Container | Redeploys when these paths change | | --- | --- | | pr-api | `apps/api/**`, `packages/contracts/**`, `packages/metadata/**`, `prisma/**` | | pr-app | `apps/app/**`, `packages/ui/**`, `packages/sdk/**`, `engine/**` (WASM build) | | pr-site | `apps/site/**`, `packages/ui/**` | | pr-workers | `workers/media/**`, `workers/render/**`, `engine/**`, `packages/metadata/**` | | pr-ml | `workers/ml/**` | ## Files | File | Purpose | | --- | --- | | `infra/deploy-receiver/` | Webhook receiver (Node, no dependencies). Tests cover signature, path rules and the queue. | | `infra/deploy/deploy.sh` | Per-service deploy with rollback. Tested end to end (success, failed build -> rollback, `.env` kept). | | `infra/systemd/photoreport-deploy-receiver.service` | Runs the receiver on each container. | | `infra/nginx/deploy-receiver.conf` | Exposes `/_deploy/gitea` to Gitea; `/_deploy/status` only locally. | | `infra/pm2/api.config.cjs` | API processes (2 instances, cluster mode) and `photoreport-worker` (one, fork mode). | ## Runtime upgrades on an already-provisioned container Bumping the Node version pinned in this repo (`.nvmrc`, `package.json#engines`, CI) does not touch the Node binary already installed on a running container — that binary is provisioned once in "First-time setup" below and only a human with host access can change it (agents never SSH into containers). `pr-api` (CT 264, `10.10.50.61`) currently has Node 22 installed; before (or right after) the first deploy that lands with this repo pinned to Node 24.22.1, a human needs to run, on that container: ```sh curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash - sudo apt-get install -y nodejs=24.22.1-1nodesource1 node -v # expect v24.22.1 pm2 reload all ``` (Adjust the exact `nodejs=` package version string to whatever NodeSource publishes for 24.22.1 at run time; `apt list -a nodejs` after adding the repo shows the available build string.) Until that runs, `pr-api` keeps serving on Node 22 even though the deployed code and lockfile target Node 24 — PM2 processes don't re-exec against a different Node binary on their own. ## First-time setup of a container 1. Clone the repo to `/srv/photoreport` (read-only deploy key from Gitea). 2. Install Node 24.22.1, pnpm, PM2 (and Rust for `workers`); create the service `.env` from its `.env.example`. 3. `/etc/photoreport/deploy-receiver.env` from `infra/deploy-receiver/.env.example` (0600), with a new secret. 4. `pnpm install && pnpm --filter @photoreport/deploy-receiver build`, then enable `photoreport-deploy-receiver.service` and include `infra/nginx/deploy-receiver.conf` in the site. Then, for a service that comes back by itself after any reboot (container or Proxmox host): `cp infra/systemd/photoreport-boot.service /etc/systemd/system/ && systemctl enable photoreport-boot.service`, `cp infra/systemd/photoreport-tmp.conf /etc/tmpfiles.d/photoreport.conf`, and `pm2 startup systemd`. `photoreport-boot.service` runs `infra/deploy/boot.sh`, which starts the PM2 processes (api, site) from the code the last deploy left built, without relying on PM2's saved list; deploys also `pm2 save`. PM2 retries crashed processes with a growing pause, so the API waits for a database that starts later. Check after setting it up: `reboot` the container, then `/health` (api) or the home page (site) must answer without anyone doing anything. 5. In Gitea: Settings -> Webhooks -> add `https:///_deploy/gitea`, content type JSON, the same secret, push events only, branch filter `main`. 6. API container only, once: `create-owner` (see README) for the first organization. 7. API and ingest containers: mount the shared data folder at `/srv/photoreport-data` (Proxmox bind mount), set `STORAGE_ROOT`, `INGEST_ROOT` and `DELIVERY_SECRET_KEY` (`openssl rand -base64 32`, the same value wherever the worker or API runs). The worker needs `perl` (ExifTool) and `ffmpeg` for the archive's videos (`apt install ffmpeg`; without it each API deploy puts a static build in `~/.local/ffmpeg`, which the worker finds; with neither, videos wait as FAILED "ffprobe_missing" and "Analisar agora" retries them). Faces in videos run in the face worker (`FACES_*` set), `ARCHIVE_VIDEO_FACE_FPS` frames a second (default 5). On the ingest container, SFTPGo users get `/` as home folder; register each login under the member it belongs to (`POST /v1/orgs/:orgId/ftp-accounts`). 8. Faces (worker host): install Rust, `infra/faces/download-models.sh /srv/photoreport-data/models`, and set the `FACES_*` variables in `apps/api/.env`. Deploys build `photoreport-faces` whenever `cargo` is present. Shirt numbers are optional. Once a model has been trained (`workers/ml/jersey/README.md`), copy its folder to the worker host and set `JERSEY_MODEL_DIR` to it. 9. Develop (Revelar): on the worker host set `RENDER_BIN=/srv/photoreport/target/release/photoreport-render` (built by the API deploy when Rust is installed). On the app host install the browser engine toolchain once: `rustup target add wasm32-unknown-unknown` and `cargo install wasm-bindgen-cli --version 0.2.129 --locked`; every app deploy then rebuilds `apps/app/public/engine/` (`infra/engine/build-wasm.sh`). Serve `.wasm` as `application/wasm`. 10. Sites (pr-site): `API_URL` for `infra/pm2/site.config.cjs` (default http://127.0.0.1:3000), reverse proxy every brand domain to port 3100. In the app (Vendas -> Sites e pagamentos) add each domain, then the Stripe secret key and webhook secret; in Stripe add the shown endpoint for `checkout.session.completed`, `checkout.session.async_payment_succeeded`, `checkout.session.async_payment_failed` and `checkout.session.expired`. Set `SMTP_URL` on the worker for order emails. An archive's own address (app -> Arquivo -> "Endereço próprio", e.g. `ligaportugal.photoreport.pt`) is one more host on the same port 3100: in Nginx Proxy Manager a Proxy Host for it, forwarded like `events.next.photoreport.pt` (Host passed as is), with its Let's Encrypt certificate. With a wildcard certificate (DNS challenge) one Proxy Host for `*.photoreport.pt` covers every archive under that domain. 11. SFTPGo (pr-ingest): no users in SFTPGo itself. Set `data_provider.external_auth_hook` to `http:///v1/sftpgo/auth?key=` and `external_auth_scope` to 1 (passwords), with the same `SFTPGO_HOOK_KEY` (24+ characters) in `apps/api/.env`. FTP logins and their passwords are created in the app (Metadados -> Logins FTP); each lands in `/` with upload-only permissions. 12. Desktop app (pr-api): `CORS_ORIGINS` must include `tauri://localhost,http://tauri.localhost` (the bundled copy the desktop app opens without network). For its self-updates set `API_PUBLIC_URL=https://api.next.photoreport.pt`, `DESKTOP_RELEASES_API=https://git.bitreport.pt/api/v1/repos/BitReport.pt/photoreport` and a read-only Gitea token in `DESKTOP_RELEASES_TOKEN`; release signing is in `apps/desktop/README.md` (Updates). ## Desktop and print agent Not deployed by webhook. A tag `desktop-v*` / `agent-v*` triggers Gitea Actions to build installers per OS and publish a Gitea release; the Tauri updater and the agent's updater read from it. The desktop app keeps the interface on disk and never needs the server to open. Each web deploy writes `ui-manifest.json` (every file of the build with its SHA-256); the app checks it 20 s after start and every 30 minutes, downloads only the files that changed, checks each hash and uses the new version from the next start (or when the photographer reloads). The installer's own copy is the fallback, and wins when it is newer. macOS builds on a Mac registered once as a runner (`bash infra/desktop/macos-runner.sh`, with a registration token from Gitea → Actions → Runners; label `macos`, a launchd service of that user). Its builds carry the updater key, so apps installed from a release update themselves; an app compiled by hand without the key never does. A release made while the Mac is off waits for it. ## Importing the old app.photoreport.pt `apps/api/scripts/import-legacy.ts` reads the old MySQL database, read-only. It brings over accounts, squads, events, the photos in each event's folder and the storefront (galleries, paid orders, affiliates). Photos are copied: the old folders are never changed. - **Accounts:** people keep their old password. It is checked once and then stored the new way. Admins come in as ADMIN and everyone else as PHOTOGRAPHER. FTP passwords are not carried over: each photographer creates a new one in the app. - **Squads:** every player becomes a person with their club and shirt number, which shirt-number suggestions use. - **Shop:** every public gallery link becomes a gallery with the same address (a suffix if it is taken), title and password or PIN (the old hash still works), listed if it was in the portal, unpublished if it had expired, and with its folder's photos. Paid carts become orders numbered `OLD-…`, marked delivered: they are history (no new payment, no new downloads, no earnings). Affiliates keep their codes and rates, and orders keep their affiliate. Photographers keep their Stripe Connect account for payouts (Stripe confirms it the first time they open Ganhos). - **Not imported:** face clusters (they are recalculated), proofing favourites and comments, download counts and print history. Run it on the API host, after `create-owner`: ```sh cd /srv/photoreport/apps/api export LEGACY_MYSQL_URL='mysql://readonly-user:...@old-host:3306/photoreport' # environment only, never argv pnpm import-legacy -- --org-slug photoreport --owner-email peter@photoreport.pt \ --photos-root /path/to/old/sftpgo/data --photos-layout "{username}/{folder}" --dry-run ``` 1. **Dry run.** It prints what would come over and lists the event folders it can't find. If many are missing, fix `--photos-layout`; `{username}`, `{userId}` and `{folder}` are available. 2. **Real run.** Run it without `--dry-run`. `--only users,squads,events,photos,shop` limits it to some parts. 3. **Again later.** Running it again adds only what is new: imports are recorded in `legacy_imports`, and photos are deduplicated by content.