# Architecture ## Overview ```mermaid flowchart TB subgraph callers[" Callers "] direction LR App[RewakeApp] ~~~ Info[RewakeInfo] ~~~ Ext[Chrome extension] ~~~ Auto[Airtable automations] ~~~ N8N[n8n workflows] ~~~ Partners[HelloPro · Machinio] end subgraph server[" Rewake server "] direction LR API["**API**
FastAPI"] -->|queues jobs| Redis[("Redis
queue · history")] Beat["**Beat**
scheduler"] -->|scheduled jobs| Redis Redis --> Worker["**Worker**
Celery"] Worker --> OCR["OCR service"] end subgraph external[" External services "] direction LR Airtable[("Airtable
source of truth")] ~~~ Shopify[("Shopify
shop")] ~~~ Google["Gmail · Sheets"] ~~~ AI["Claude · OpenRouter"] ~~~ N8NS["n8n
e-mails"] end callers ==>|HTTPS| server server ==>|API and worker| external %% Translucent fills and no text colour: readable in the light and dark themes classDef main fill:#19534f,stroke:#19534f,color:#ffffff classDef store fill:#19534f33,stroke:#19534f classDef node fill:#94a3b81a,stroke:#94a3b8 class API,Worker,Beat main class Redis,Airtable,Shopify store class App,Info,Ext,Auto,N8N,Partners,OCR,Google,AI,N8NS node style callers fill:#94a3b80d,stroke:#94a3b8 style server fill:#19534f1a,stroke:#19534f style external fill:#94a3b80d,stroke:#94a3b8 ``` - **The API** answers HTTP requests. Anything longer than a few seconds is queued for the worker and the caller polls for the result (`job_id` / `task_id`). - **The worker** runs those jobs and the **scripts**. The **beat** process queues the scheduled ones. - **Redis** holds the queue, the scripts' history, locks, and a few caches. - **n8n** (the automation platform on the same server) sends some e-mails for the API: the worker calls its webhooks for UltiMate 3000 offers. n8n workflows may also call the API. Other services on the server, such as Gotenberg (document conversion used by n8n), are not used by the API. See [n8n automations](n8n/index.md). - **Airtable** is the source of truth. The API keeps no business data of its own, except a few files in `DATA_DIR` (PDF counters, the discount grid, AI usage). ## Code layout ``` api/ main.py the FastAPI app: middleware and routers config.py every setting (see configuration.md) auth.py who may call which route log.py structured logs routes/ HTTP: one package per caller family (internal/, hellopro/, ...) services/ business logic integrations/ clients of external systems: airtable/ (client + generated schema), shopify/ domain/ pure business rules, no I/O scripts/ long jobs run by the worker, listed in scripts/registry.py worker/ the Celery app and its schedule, the script runner, other jobs templates/ HTML templates of the PDF documents scripts/ command-line tools for developers and operators (not the worker's scripts) tests/ docs/ ocr/ the OCR service (its own image) ``` ### Layers ```mermaid flowchart TD routes --> services routes --> domain services --> integrations services --> domain scripts --> services scripts --> integrations worker --> scripts worker --> services ``` | Layer | Does | Never | |---|---|---| | `routes/` | checks the input, calls a service, turns errors into HTTP answers | business rules, direct Airtable calls | | `services/` | business logic | imports FastAPI | | `integrations/` | talks to one external system | knows business rules | | `domain/` | pure rules and data types | any I/O | ## Access Every route is guarded by one rule from `api/auth.py`; `ADMIN_TOKEN` passes all of them. | Routes | Rule | Who | |---|---|---| | `/internal/scripts/*` | `require_app_or_automation` | the app, or Airtable automations (`AIRTABLE_AUTOMATION_TOKEN`) | | other `/internal/*` | `require_app` | `APP_TOKEN` from one of `config.APP_ORIGINS` (exact site) | | `/hellopro/*`, `/machinio/*` | `require_token(...)` | the partner's own token | | `/webhooks/u3000-price-grid` | `require_token("U3000_SHEET_WEBHOOK_TOKEN")` | the price sheet's script | | `/health`, `/metrics`, `/pdf/*`, `/invoice/*`, `/formulaire/photos/*` | none | public | The site check (`Origin` / `Referer`) only keeps browsers on other sites out; the token is what protects the API. ## Scripts and background jobs ```mermaid sequenceDiagram participant C as Caller (app, Airtable) participant A as API participant R as Redis participant W as Worker C->>A: POST /internal/scripts/{name}/run A->>R: queue run_script(name) A-->>C: task_id W->>R: take the job, lock the record W->>W: script.run() (reports its stages) W->>R: result in the history, new snapshot C->>A: GET /internal/scripts/{name}/runs ``` A **script** (`api/scripts/`) is a class with a `name`, an optional `schedule`, `is_configured()` and `run()`. Listing it in `scripts/registry.py` is enough: the worker runs it, beat schedules it, and `/internal/scripts/*` exposes it. `api/worker/scripts.py` runs every script the same way: - one run at a time per `record_id` (a script may ask to wait instead of being skipped); - the current stage, so the app can show progress, kept when the run fails; - the result in the history (last 1000 runs per script); - for scheduled scripts, a snapshot handed to the next run to compare against. Other jobs (`api/worker/tasks.py`) don't need a history: label OCR, AI product research and document search, the auctions sync, UltiMate 3000 offers, the payroll reminder. ## Airtable `api/integrations/airtable/` is the only way the code talks to Airtable, through [pyAirtable](https://pyairtable.readthedocs.io). pyAirtable retries a request refused for the rate limit (429) and never resends one that failed otherwise, so a creation cannot be duplicated. - `__init__.py`: the main base's records as dictionaries: `get_record`, `get_records(ids)`, `list_records(formula, fields=, view=)`, `create_record(s)`, `update_record(s)`, `delete_record`, `upload_attachment(table, record, field, ...)`, and cached look-ups: `ids_by_name(table)`, `names_by_id(table)`, `select_choices(table, field)`, `base_schema()` (`clear_caches()` forgets them). `api(token)` gives a pyAirtable client for another base (the auctions base). - `schema.py`: **generated**. Each table is a pyAirtable ORM model with typed fields, which also carries its names (`TABLE` and one constant per field) for the code that still uses dictionaries. ```python from api.integrations import airtable from api.integrations.airtable import schema # Dictionaries units = airtable.list_records( schema.ToutesLesUnites.TABLE, "{Statut commercial} = 'A vendre'", fields=[schema.ToutesLesUnites.NAME, schema.ToutesLesUnites.PRIX_DE_VENTE_HT], ) # Typed objects (mypy knows unit.prix_de_vente_ht is a float) for unit in schema.ToutesLesUnites.all(formula="{Statut commercial} = 'A vendre'"): print(unit.name, unit.prix_de_vente_ht, unit.etat_esthetique) ``` New code uses the ORM models; the dictionaries remain until each part of the code has moved. After a change in Airtable, regenerate the schema **from the production base**: `make airtable-schema` (the token needs `schema.bases:read`). The git diff shows what changed, and `mypy` reports code that uses a field that no longer exists. Formula and rollup fields that give a date are kept as Airtable sends them (a date or a date-time). ## Shopify `api/integrations/shopify/` talks to the store set by `SHOPIFY_SHOP_DOMAIN`. | Module | Does | |---|---| | `auth.py` | exchanges the app's client id and secret for a ~24 h token, shared by every process through Redis and renewed before it expires | | `graphql.py` | GraphQL calls: one retry with a fresh token after a 401, retries after a 429 (Retry-After), raises `ShopifyError` otherwise | | `catalog.py` | `ShopifyCatalog.fetch_products()`: every product and variant, page by page | | `files.py` | `ShopifyFiles`: uploads a PDF to the store's Files and sets a product's metafields | | `queries/` | the GraphQL operations the API sends | | `generated/` | typed client generated from `queries/` by ariadne-codegen: `ShopifyClient` (do not edit) | | `base_client.py` | base of the generated client: sends through `graphql.py` | The typed client checks every operation against the store's schema when it is generated. After changing a query in `queries/`, or `SHOPIFY_API_VERSION`, run `make shopify-client`: it downloads the schema of that version (with the token from `.env`) and regenerates `generated/`. A GraphQL mutation that fails on a network error or a 5xx is never sent again: Shopify may have applied it, and a second one could create a duplicate. A 429 is retried: Shopify applied nothing. ### Products `api/services/shopify_products.py` writes a product from the state Airtable wants it in. The scripts `create_product_shopify` and `update_product` build that state from the Model (`_desired_product` in `api/scripts/_shopify_links.py`) and hand it over: ```{mermaid} flowchart LR M[Airtable Model,
variations, units] -->|_desired_product| D[DesiredProduct] S[(Shopify)] -->|fetch_product| L[live product] D --> C{compare} L --> C C -->|product, options, variants,
prices, weights, image| P[productSet] C -->|stock of kept variants| I[inventorySetQuantities] C -->|metafields| F[metafieldsSet] P --> S I --> S F --> S ``` Only what differs is sent, so a product already in sync costs one read. `productSet` replaces the lists it receives: the variants sent are the ones the product keeps (a variant sent with its id keeps it and its stock). The image is sent only when the Airtable attachment changed (recorded in the `images_airtable_ids` metafield). Stock of existing variants is set with a compare-and-set (`changeFromQuantity`): a sale on Shopify between the read and the write makes the update fail instead of overwriting it, and the next run corrects it. | | `create_product_shopify` | `update_product` | |---|---|---| | Missing description, weight, type or photo | fails, nothing created | photo: reported after the rest synced | | Nothing to sell | fails (unless `restore`) | variants kept at 0 stock | | Product gone from Shopify | created (a stale "Annonces Shopify" record is reused) | fails, never recreated | | Failure after creating | product deleted, Model skipped for 15 min | — | ## Conventions - **Language**: code, comments, docstrings and docs in English. Messages shown to staff (the API's error `detail`s) are in French. Airtable names stay as they are in Airtable. - **Comments** explain why, never what the code says or its history. Each module starts with a short docstring saying what it is for. - **Settings**: only `api/config.py` reads the environment; use `config.NAME`. - **Airtable names**: from the generated schema, `schema.ToutesLesUnites.PRIX_DE_VENTE_HT`, never typed in the code (see [Airtable](#airtable)). - **Logs**: `logger = structlog.get_logger(__name__)`, an event in a few words, values as key-value pairs: `logger.info("product updated", model_id=model_id)`. - **Routes**: plural nouns in kebab-case; no verbs in paths; actions as `POST /resources/{id}/action`. - **Tests**: never reach the network; a test that needs the real development base is marked `@pytest.mark.live`. See [Contributing](contributing.md).