# Architecture
## Components
```mermaid
flowchart LR
browser([Admin browser]) -->|HTTPS| proxy[proxy
Caddy]
proxy --> api[api
FastAPI + web UI]
api --> db[(postgres
metadata, index,
job queue)]
worker1[worker 1..N
module jobs] --> db
worker1 -->|Graph API| m365[(Microsoft 365)]
worker1 --> repo[(Backup repository
local / NFS / S3)]
api --> repo
```
| Container | Role |
|-------------|-------------------------------------------------------------------------|
| `proxy` | Caddy: TLS (automatic or supplied certificate), reverse proxy |
| `api` | FastAPI REST API; serves the built web UI; browse/restore requests |
| `worker` | Runs backup, restore, export and retention jobs, and the per-minute scheduler tick (there is no separate scheduler process; a database lock makes each tick run once). Scale with `--scale` |
| `migrate` | One-shot: applies database migrations, then exits; `api` and `worker` wait for it |
| `exo-runner` | Runs Exchange Online PowerShell tasks for the setup wizard (create the alerts mailbox, scope permissions). Separate image with PowerShell 7; idle otherwise, and can be removed after setup |
| `postgres` | Configuration, catalog/index of backed-up items, job queue |
| `minio` | *Optional* S3-compatible storage if you have no external object store |
All Python containers use **one image** with different commands, which keeps
builds and upgrades simple.
## Technology choices
| Concern | Choice | Why (details in ADRs) |
|------------------|-------------------------------------------------|--------------------------------------------------------|
| Backend language | Python 3.13 | Strong Graph/HTTP/async ecosystem, easy contributions |
| Web API | FastAPI + Pydantic v2 | Typed, async, OpenAPI generated from code |
| Database | PostgreSQL 17, SQLAlchemy 2, Alembic | Reliable, one store for metadata, search and queue |
| Job queue | Procrastinate (PostgreSQL-backed) | No Redis/RabbitMQ to operate; transactional enqueue |
| Graph access | Own thin async client on `httpx` + `msal` | Full control of throttling, batching, delta, streaming |
| Backup storage | Own content-addressed repository | Dedup, compression, encryption, S3 immutability |
| Frontend | React + TypeScript + Vite; platform features (dialog, popover, `:user-invalid`) over UI libraries | Small, accessible, strict CSP; served by the API image |
| Docs | Sphinx + MyST Markdown + Furo + sphinx-autoapi | See {doc}`documentation` |
## Repository layout (planned)
```text
mailsafehouse/
├── backend/
│ ├── src/s365b/
│ │ ├── core/ # config, db, auth, audit, jobs, scheduling
│ │ ├── graph/ # Graph client: auth, retry/throttle, batching, delta
│ │ ├── storage/ # repository format, backends (fs, s3), crypto
│ │ ├── modules/
│ │ │ ├── sdk.py # BackupModule interface (the module contract)
│ │ │ ├── exchange/
│ │ │ ├── onedrive/
│ │ │ ├── sharepoint/
│ │ │ ├── teams/ # later (not in v1)
│ │ │ └── entra/
│ │ └── api/ # FastAPI routers
│ ├── migrations/ # Alembic
│ └── tests/
├── frontend/ # React app (built into the image, served by the API)
├── deploy/
│ ├── compose.yaml
│ └── compose.minio.yaml # optional overlay
├── docs/ # this site
└── .github/workflows/ # CI: lint, test, build images, build docs
```
## Core flows
### Backup job
1. Every minute a worker runs the scheduler tick, which queues `run_backup_job(job_id)` for each job whose cron schedule is due.
2. A worker loads the job and asks each **enabled** module in the job to
`discover()` objects matching the job's include/exclude rules.
3. One sub-task is queued per protected object (a mailbox, a site, …) so work
spreads across workers and one failure does not stop the rest.
4. Each sub-task calls the module's `backup()` with the object's saved
**sync state** (delta tokens). The module yields items; the core writes
content to the repository and the item version to the catalog. State
saved for another repository starts a full copy (see storage.md,
"Changing a job's repository").
5. The new sync state is committed only after the items are durably stored,
so a crash resumes from the last good point.
### Restore / export
1. User browses the catalog at a point in time and selects items.
2. API creates a restore job (audited) and a worker calls the owning module's
`restore()` or `export()`.
3. Exports are written as a time-limited download (ZIP of EML/ICS/VCF/files/JSON).
### Run logs
Every process logs JSON lines to stdout (`docker compose logs`). In the
worker, each backup, restore and retention run also keeps its own log: a
run binds its ID to its task, so every line logged while it works,
including the Graph client's and the modules', is copied into the
`job_run_log` table, written every few seconds and when the run ends. A
run keeps at most 20,000 lines (a note at the end counts the rest).
**Jobs → Details → Download log** gives it as text. Housekeeping deletes
run logs older than its "Keep job run logs for" setting (90 days by
default); the runs themselves are kept. Lines carry no tokens or
pre-authenticated URLs, as for stdout.
## Graph client
Shared by all modules, so throttling and auth are solved once:
- App-only auth with **certificate** credentials via MSAL; token caching.
- Honors `Retry-After` on 429/503, exponential backoff with jitter, and a
per-tenant concurrency limiter.
- JSON batching (`$batch`, 20 requests) for metadata-heavy work.
- Delta-query helpers that persist `@odata.deltaLink` and handle `410 Gone`
(token expired) by triggering a resync.
- Streaming download/upload for large content (no full file in memory).