From dedb9adf4d1782683a8bf43830a4ebe4bd054e20 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Sun, 8 Nov 2026 17:33:17 -0800 Subject: [PATCH 1/5] docs(developers): move the API reference and the wiki's developer pages onto the site The API reference is brought up to date with volumes kept on the unit, unit mode, the description search and the bootstrap token, with citations by function name and tables of the routes it did not describe. Developer setup, Git workflow and camera libraries come from the wiki, corrected against the repositories. --- content/en/docs/developers/api-reference.md | 1317 +++++++++++++++++ .../en/docs/developers/camera-libraries.md | 44 + content/en/docs/developers/developer-setup.md | 182 +++ content/en/docs/developers/git-workflow.md | 148 ++ migration/sources.json | 31 + 5 files changed, 1722 insertions(+) create mode 100644 content/en/docs/developers/api-reference.md create mode 100644 content/en/docs/developers/camera-libraries.md create mode 100644 content/en/docs/developers/developer-setup.md create mode 100644 content/en/docs/developers/git-workflow.md diff --git a/content/en/docs/developers/api-reference.md b/content/en/docs/developers/api-reference.md new file mode 100644 index 0000000..51b52b5 --- /dev/null +++ b/content/en/docs/developers/api-reference.md @@ -0,0 +1,1317 @@ +--- +title: "Captua — API reference" +linkTitle: "API reference" +url: /docs/developers/api-reference/ +translationKey: docs-developers-api-reference +docs_section: developers +source: docs/developers/API_REFERENCE.md +--- + +This page is for developers who work on the Captua backend or write clients for it. It covers how to run the stack, the rules the generated API schema does not state, how storage is laid out, worked examples, authentication and configuration. + +Environment variables are written here with their `CAPTUA_` names. The backend also reads the older `DTK_` name of each, and the env files on units keep the `DTK_` names (see [`CAPTUA_` and `DTK_` names](#captua-and-dtk-names)). + +## 1. Quick start {#quick-start} + +### Backend setup {#backend-setup} + +The backend runs **in Docker for development** and **natively through pixi on the Raspberry Pi**. A legacy virtualenv + `pip install -r requirements.txt` still works on Linux, but pixi is preferred for new development (`.github/copilot-instructions.md`). + +It does **not** work on Windows or macOS: `backend/requirements.txt` pins `picamera2` and `gphoto2`, which are Linux/Pi camera libraries, and `backend/pixi.toml` declares only `linux-aarch64` and `linux-64`. Use Docker on those platforms. + +**Development — any machine, no cameras attached:** + +```bash +./scripts/start-dev.sh +``` + +This brings the whole stack up in Docker — PostgreSQL, the FastAPI backend and the SvelteKit dev server — and applies Alembic migrations on startup. It is shorthand for: + +```bash +docker compose -f docker-compose.yml -f docker-compose.dev.yml --profile with-backend up --build +``` + +**Production — on the Pi:** `./scripts/start.sh` runs the database and frontend in Docker and the backend natively via pixi, because camera access needs Pi-specific libraries (libcamera, picamera2) that cannot run in a container. + +See `backend/DEVELOPMENT.md` for the dependency-manifest rules that follow from this split. + +### Verify that it works {#verify-it-works} + +After `start-dev.sh` (development): + +- **Frontend**: `http://localhost:5173` (Vite dev server) +- **Interactive API Docs**: `http://localhost:8000/docs` (Swagger UI) +- **Health Check**: `http://localhost:8000/health` +- **ReDoc**: `http://localhost:8000/redoc` + +After `start.sh` (production on the Pi), there is no Vite server: Nginx serves the UI and proxies the API on **port 80** — `http://.local`. Port 8000 is not open to the LAN (see [the firewall note](#environment-variables)). + +### Run the tests {#run-the-tests} + +Tests run inside the backend container: + +```bash +# Run all tests +docker compose exec backend python -m pytest + +# Or run specific test suites: +docker compose exec backend python -m pytest tests/unit/ +docker compose exec backend python -m pytest tests/integration/ +docker compose exec backend python tests/validate_system.py +``` + +--- + +## 2. Key resources {#key-resources} + +| Resource | Location | Purpose | +|----------|----------|---------| +| **Endpoint reference** | `http://localhost:8000/docs` | Generated from the code; always current | +| **Backend setup** | [`backend/README.md`](https://github.com/UCSB-AMPLab/digitization-toolkit-backend/blob/dev/README.md) | Quick start and environment setup | +| **Configuration example** | [Code examples](#configuration-page-example) | How to build the configuration page | +| **Live scan example** | [Code examples](#live-scan-page-example) | How to build the live scan page | +| **Gallery example** | [Code examples](#gallery-page-example) | How to build the gallery page | +| **Device setup** | [Pi 5 with IMX519 cameras](/docs/deployment/pi5-imx519/) | Raspberry Pi configuration | + +--- + +## 3. API reference {#api-reference} + +The endpoint list, path and query parameters, and request/response schemas are **generated from the code** and served by the running backend: + +| | | +|---|---| +| **Swagger UI** | `http://localhost:8000/docs` — interactive; send real requests, including authenticated ones | +| **ReDoc** | `http://localhost:8000/redoc` — readable single-page reference | +| **OpenAPI schema** | `http://localhost:8000/openapi.json` — machine-readable, for client generation | + +FastAPI derives these from the routers themselves, so they cannot fall out of step with the implementation. The endpoints this page does not discuss are listed, with their roles, in [Endpoints not described above](#undocumented-endpoints). + +Two limits: the schema is only as complete as the routes declare it. Endpoints without a `response_model` — `POST /auth/login` and `GET /auth/setup/status` among them — appear with no response schema. On errors, the schema is partial: no route in `backend/app/api/` declares `responses=`, so the only error FastAPI advertises is the `422` with an `HTTPValidationError` body it adds automatically wherever a route validates input. **Every other code the application raises is absent from the schema: 400, 401, 403, 404, 409, 410, 413, 429, 500, 501, 502, 503 and 504** — and so is the application's own `422`, which is a different thing from the automatic one. Two more can reach a client from the framework beneath the application, and the grep below does not see them: `405` from Starlette's router when the path exists and the method does not, and `416` from `FileResponse` when a `Range` header cannot be satisfied — the image download routes in `records.py` return one. + +Three of those need more detail, because a client that assumes a shorter list mishandles them. + +- **`422` has two meanings.** FastAPI's is a validation failure whose body is an object with a `detail` array. Thirty-one places in `backend/app/api/` raise their own, carrying a `detail` string or, on the handover and export refusals in `collections.py`, a dict — `{message, blocking_record_ids}`. Two of the thirty-one are the unit mode's `stem_required`, with `{code, message}` (`update_collection`, `collections.py`); a thirty-second, `unknown_reference_code`, carries `{code, message, referenceCode}` and is raised with a status taken from a variable, so the grep below does not count it (`_check_codes_with_fisqua`, `collections.py`). Both are described under The unit's mode, below. The move refusals that name records the same way are `409`s, not `422`s: records handed over for review, and records with files in the offsite bucket (`move_collection_records`, `collections.py`). And a refusal from the background export job never arrives as an error status at all: the job records it, and `GET .../export/status/{job_id}` returns it at `200` with the message in a top-level `error` field (`export_status`, `collections.py`). A client that reads every 422 as a malformed request misreports a volume refused for unapproved records. +- **`401` comes from one file, and `403` mostly does.** All fourteen 401s are in `app/api/auth.py`. Three are in `get_current_user`, the dependency of every route except `/health` and six auth routes (setup status, register, login, logout, refresh and password-reset), so a client can meet them anywhere. The other eleven are raised by the auth routes themselves — login, register, refresh and password-reset — for that route's own reason: a wrong password, a wrong bootstrap token at first-user registration (`_authorize_bootstrap` in `auth.py`, called only from `register`), and at register, refresh and password-reset an invalid or expired token as well (`register`, `refresh_token`, `reset_password`). The status code does not say whether the session has ended; the route and its message do. Four of the nine 403s that the grep below counts are in `auth.py` too. One is `RoleChecker.__call__`, the role gate routes declare as a dependency, with `"Operation not permitted"`. Another is the CSRF check, `"Missing X-Requested-With header"` (`_require_csrf_header`, `auth.py`): a request that carries the session cookie and no `Authorization: Bearer` header, with a method other than `GET`, `HEAD` or `OPTIONS`, is refused when it lacks the `X-Requested-With` header (`_session_token`, `auth.py`). The check runs before the token is checked (`_session_token`), so an expired or invalid cookie gets this 403, not a 401. `POST /auth/logout` refuses any request without the header, Bearer or not (`logout`). `get_current_user` reads the session through `_session_token`, so a client that sends the cookie without the header meets this 403 on any state-changing route; apart from logout, a request with an `Authorization: Bearer` header is never checked. The other two in `auth.py` are `"Only admins can register new users"`, when users already exist and the caller is not an admin (`register`), and `"User is inactive"`, at login with the right password for a deactivated account (`login`). Two are domain rules: an annotation with a recorded creator may only be deleted by that creator or an admin, and one with none by anyone who can reach the route (`delete_record_annotation`, `records.py`); and `_apply_status_change` checks the caller's role (`_apply_status_change`, `records.py`). `_apply_status_change` is also called from `promote_collection`, so a role refusal can arrive from the handover — but the bulk status route calls it too and catches the refusal and returns `200` with the records it accepted — including a record already in the requested status, which is a no-op (`bulk_update_status`, `records.py`); a refused record is logged on the server and not reported to the client. The seventh 403 is the list import's: while projects are shown, an operator's list whose project does not exist yet is refused (`import_digitisation_list`, `imports.py`; `import_list`, `list_import.py`). The eighth and ninth are the unit mode's `volumes_from_fisqua`, with `{code, message}`: in fisqua mode an operator may not create a volume, change its stem or reference code, or import a list (`_volumes_from_fisqua`, `collections.py`; `import_digitisation_list`, `imports.py`; The unit's mode, below). A tenth comes from an exception with its own status, which the grep does not count: `kept_on_unit_admin_only`, `403` with `{code, message}`, when someone other than an admin asks for `kept_on_unit` on `POST /collections/` or `POST /imports/digitisation-list` outside offline mode (`kept_on_create`, `app/core/kept_volumes.py`; Volumes kept on the unit, below). +- **`500` is a documented outcome, not only a crash.** Eighteen routes raise it deliberately, fifteen of them in `backend/app/api/` and three through `relocate_images_and_commit` (`app/core/storage_ops.py`): `PATCH /collections/{id}`, `POST /collections/{id}/move-records` and `POST /projects/{id}/move-collections`. The causes are a camera control that failed, a storage command (`lsblk`, mount, unmount) that failed, a file operation that failed, or a database commit that failed after files had already changed. `POST /collections/{id}/images/renumber` writes no file, so its 500, `"The database update failed, so no record was renumbered. Please retry"`, leaves every sequence as it was (`renumber_images`, `collections.py`). When the commit of `POST /records/{id}/images` fails, the route unlinks the saved file and thumbnail before raising, and the line already appended to the volume's capture manifest stays (`add_image_to_record`, `records.py`). A failure after the commit, in the `db.refresh` that follows it, is also a 500 and cleans nothing up, so the two cannot be told apart from the status alone. + +To re-derive this rather than trust it, which is what let the previous list go stale: + +```bash +grep -rhoE 'HTTPException\(\s*(status_code\s*=\s*)?(status\.HTTP_)?[0-9]{3}|status_code\s*=\s*(status\.HTTP_)?[0-9]{3}' backend/app/ \ + | grep -oE '[0-9]{3}' | sort -u +``` + +Then drop the success codes the decorators declare — 200, 201, 202, 204. The grep does not see a status taken from an exception: `HTTPException(status_code=exc.status, …)` passes on the status of `KeepRefused` (`app/core/kept_volumes.py`, raised from `POST /collections/`, `PATCH /collections/{id}`, `POST /collections/{id}/move-records`, `PATCH /records/{id}`, `POST /projects/{id}/add_record/{rec_id}`, `POST /imports/digitisation-list`, `POST /collections/{id}/keep-on-unit` and `POST /collections/{id}/release-from-unit`), of `FreeRefused` (`app/core/offsite_free.py`), of `CodeRefused` (`_check_codes_with_fisqua`), and of `SearchRefused` on `GET /fisqua/descriptions` (`search_descriptions`, `app/core/unit_mode.py`: `400` `query_too_short`, `409` `off_in_this_mode` or `fisqua_not_configured`, `429` `rate_limited` with `Retry-After` when Fisqua gives one, `503` `fisqua_unreachable`). One raiser sits outside `backend/app/api/`: `app/core/db_errors.py`, which turns any `IntegrityError` — not only a unique-constraint one — into a 409 carrying a message and, when one could be recovered, the constraint name. For any single route, read it: the `HTTPException` calls are explicit, and twenty callables in `backend/app/api/` raise on a route's behalf — `_require_csrf_header` (reached through `_session_token`, and from `POST /auth/logout`), `_authorize_bootstrap`, `get_current_user` and `RoleChecker.__call__` in `auth.py`; `_zone` in `activity.py`; `_check_codes_with_fisqua` in `collections.py`, which raises the lookup's `422` or `409` with the status the refusal carries; `_refuse_capture_without_volume_or_stem`, `_refuse_retake_out_of_the_operators_hands`, `_refuse_a_new_volume_out_of_turn`, `_refuse_resolution_in_filename`, `_resolve_capture_target` and `_take_filename_index` in `cameras.py`; `_read_capped` in `imports.py`; `_refuse_a_name_that_is_a_stem` and `_update_project_held` in `projects.py`; `_stored_master`, `_image_row`, `assert_movable`, `_assert_promotable` and `_apply_status_change` in `records.py` — so a route can return a code its own body never names. + +Capture endpoints report a failed capture as `{success: false, error: ...}` at HTTP 200, so a client must read the body as well as the status. `POST /cameras/calibrate` does the same with its own `501` for a backend without autofocus calibration: the route raises it inside its `try` block, and the `except Exception` there returns it as `{success: false, error: "501: …"}` at 200 (`calibrate_camera`, `cameras.py`). + +**A volume's identity — on `/collections` requests and responses.** A volume (a row in `collections`) carries the identity defined by exchange contract 1.1: a file name stem and the catalogue item's reference code. Records have no catalogue identifier: `records.external_id` was removed in migration `a7c1e9d2b4f6`. The schema gives the pattern and the lengths; the rules below are the ones it cannot state. + +- **`filename_stem`.** The slug that, under exchange contract 1.1, the volume's image file names are built from (`-img__c`), and which the contract requires to equal the volume's reference code. New captures and uploads are named from it (see Filename Format below). A lowercase slug (`^[a-z0-9]+(-[a-z0-9]+)*$`) of at most 27 characters, so that `-img_0000` fits the 36-character pair id; a stem that does not match, or is longer, is refused with FastAPI's validation `422`. Required on `POST /collections/`: `CollectionCreate` declares it without a default (`filename_stem`, `app/schemas/collection.py`), so a request without one is refused with FastAPI's validation `422`. Optional on `PATCH /collections/{id}`, and the column is nullable, so that a volume created before stems existed can be given one. Unique on the unit; a duplicate is refused with `409`, naming the constraint `collections_filename_stem_key`. Before the volume has captured, a `PATCH` can set, change or clear the stem; a volume whose stem is cleared cannot be captured into until it is given another. A `NULL` stem can be set at any time, including on a volume that already has images. Once a volume has a stem and has captured (`capture_counter` above 0, or any image on its own records, superseded ones included), a request to change or clear the stem is refused with `409`. +- **The stem names a directory.** A volume with a stem keeps its files in `//`, beside the project directories (section 5). So a stem is refused with `409` when it equals a project's directory name, or when `//` exists, holds a file, and the volume has no image there (`stem_directory_conflict`, `app/models/collection.py`). `POST /collections/` and `PATCH /collections/{id}` check this before the flush and answer with `{message}` in `detail` (`stem_directory_collision`, called from `create_collection` and `update_collection` in `app/api/collections.py`). On `POST /collections/` this check comes after the kept-on-unit, project and Fisqua checks. `POST /projects/` and `PUT /projects/{id}` refuse a project name whose directory would be a volume's stem with `409` and a plain-string `detail` (`_refuse_a_name_that_is_a_stem`, `app/api/projects.py`). A `before_flush` listener refuses the same collisions from any other writer (`_refuse_a_stem_that_is_a_project_directory`, `app/models/collection.py`), and `app/main.py` answers it with `409` and `{message}` in `detail`. No file is moved when a stem is set. New captures and uploads into the volume are written to `/captures/` at once; the backend moves the volume's existing files at its next start (section 5). +- **A capture needs a volume with a stem.** `POST /cameras/capture` and `POST /cameras/capture/dual`, retakes included, refuse a request before any camera is touched (`trigger_capture`, `app/api/cameras.py`; `trigger_dual_capture`; with `_refuse_capture_without_volume_or_stem`, and `_refuse_retake_out_of_the_operators_hands`). After FastAPI's own validation of the body, the checks run in this order, and the first that fails gives the answer: `include_resolution_in_filename` set to `true`, `422` with `"A capture's file name cannot carry its resolution: the exchange contract fixes the name."` (`_refuse_resolution_in_filename`); a `record_id` that matches no record, `404` with `"Record N not found"`; no `collection_id`, or `0`, `409` with `"Captures must go into a volume."`; a `collection_id` that matches no volume, `404`; for a retake (a request with a `record_id`), a record that belongs to no volume, the same `409`, and a record in a volume other than the one named, `409` with `"A retake must go into the record's own volume."`; then a volume without a stem, `409` with `"This volume has no file name stem. Give it one before capturing into it."`; then a retake of a record in review or approved, `409` with `"Only a captured or rejected record can be retaken."`; then, on `POST /cameras/capture` only, a retake of a placeholder (`missing_side` `both`), `409` with `detail` `{code: "placeholder_needs_dual", message: "This record is a placeholder for a whole opening; capture it with both cameras."}` (`PLACEHOLDER_NEEDS_DUAL_DETAIL`, `cameras.py`); then a retake in the other capture mode, `422`; then, for an operator whose capture would start a new volume while the unit is in its recaptures turn, `409` (`_refuse_a_new_volume_out_of_turn`; described under Recaptures and the recapture turn, below). `POST /cameras/capture/dual` with `afterRecordId` adds its own checks (Openings and pages never captured, below). A retake that names another volume without a stem therefore gets the retake message. After the camera connection check, and before the shot, the capture's file name is taken (`_take_filename_index`). It is refused with `409` and `"This volume has reached the limit of 9999 captures. A new volume is needed. Nothing was captured."` when the volume's next capture number would be above 9999, including while numbers already taken are passed over, and with `"The next capture numbers of this volume are already taken by files on disk. Nothing was captured."` when more than 100 numbers in a row are taken (`app/core/capture_naming.py`). A refused name is rolled back and uses no number. A retake supersedes the record's current images; a rejected record returns to `captured`, and a captured one stays `captured` (`trigger_capture`, `trigger_dual_capture`). `POST /records/{id}/images` refuses an upload on the same terms: a record attached straight to a project with the first message and a volume without a stem with the second, before anything is written (`add_image_to_record`, `app/api/records.py`), and a name that cannot be taken with the same two `409`s as a capture, the 9999 limit included, before it writes any file. By then `ensure_volume_dirs` has created the volume's directories. The details are plain strings, defined in `app/core/volume_stem.py` and `app/core/capture_naming.py`. The stem is read under `SELECT … FOR UPDATE` on the volume row (`locked_volume_query`), and `PATCH /collections/{id}` takes the same row lock through `_locked_collection_query` (`update_collection`, `app/api/collections.py`), or, when the request names a new parent, through `lock_for_reparent`, which takes the volume `FOR UPDATE` and the new parent `FOR SHARE`, in ascending id order (`app/core/kept_volumes.py`). So on PostgreSQL a `PATCH` that sets or clears the stem waits until the capture's transaction commits. On SQLite neither query adds a lock clause. `POST /cameras/test-capture/{camera_index}` stores nothing and is not refused. +- **`external_id`.** The item's `referenceCode` under the exchange contract. Stripped of surrounding whitespace in requests; a blank value is refused with FastAPI's validation `422` (a `detail` array). Unique; a duplicate is refused with `409`, naming `ix_collections_external_id`. Written once: a request to change or clear a stored value is refused with `409`. +- **A volume's reference code is its stem.** When a volume has both `external_id` and `filename_stem`, the two are the same value. A write that would leave a volume with both set and different is refused with `409` and `detail` `{message, reason, external_id, filename_stem}`. `reason` is `reference_code_differs_from_stem`, and `message` reads `The reference code '' is not the file name stem ''; a volume's reference code is its file name stem.` (`ReferenceCodeDiffersFromStemError`, `app/models/collection.py`; its handler, `app/main.py`). The rule is a `before_flush` listener, so it applies to `POST /collections/`, to `PATCH /collections/{id}` and to every other writer through the ORM (`_refuse_a_reference_code_that_is_not_the_stem`, `app/models/collection.py`). It judges the pair as the flush writes it, so a request that sets both at once is accepted when they are equal, whatever the order of the fields. It checks a new volume, or a volume whose stem or reference code changed in the flush; a stored volume whose two values already differ is not refused for an unrelated edit. A volume with no `external_id`, or with no stem, is not checked: a volume with no `external_id` has its stem as its reference code, in the capture manifest and in the Fisqua link (below). A blank `external_id` is refused earlier, with the validation `422` above. `query().update()` and raw SQL go around the listener. The digitisation-list import refuses an item whose `filenameStem` differs from its `referenceCode` before the database, with the reason `filename_stem_differs_from_reference_code`, and a pair that reaches the flush is reported under the same reason (`list_import.py`). +- **`capture_counter`.** Read-only. It is raised for each capture event (a dual capture is one event) and for each upload into a volume, by `take_filename_index` (`take_filename_index`, `app/core/capture_naming.py`), which calls `next_capture_number` in `app/core/capture_counter.py`, a single atomic `UPDATE … RETURNING`, once more for each number it passes over. It is never lowered. An operator can raise it to a given number with `raise-capture-counter` (section 5, Offsite copies). +- **`stem_reserved`.** Read-only: the volume has a stem and has captured. A `DELETE /collections/{id}` on such a volume is refused with `409`, even when the volume is empty, so its stem cannot be issued again. A volume counts as having captured when its `capture_counter` is above 0, when it has any image, or when any `offsite_objects` key is of the form `//` for its stem, under any tenant and whether or not the key's image still exists (`has_captured`, `app/models/collection.py`; `offsite_keys_under_stem`). +- **A stem with offsite objects under it is held.** A new volume, or a change of stem, is refused with `409` and `{message}` in `detail` when any `offsite_objects` key is of the form `//` for that stem, under any tenant, unless the key's image belongs to a record of the same volume. The message is `"Images are stored offsite under the file name stem , so it cannot be given to this volume."` The check is a `before_flush` listener, so it applies to every write made through an ORM session, and raw SQL goes around it; `app/main.py` answers it (`_refuse_a_stem_held_offsite`, `app/models/collection.py`; `app/main.py`). The list import rejects such an item as `filename_stem_held_offsite` (`app/core/list_import.py`). +- **`kept_on_unit`.** Whether Captua keeps the volume on the unit (Volumes kept on the unit, below). `CollectionCreate` takes it as an optional boolean, and `CollectionRead` returns it, `false` by default (`app/schemas/collection.py`). In offline mode every new volume is kept, whatever is sent. In backup mode an admin may ask for it, and anyone else who sends `true` is refused with `403` and `detail` `{code: "kept_on_unit_admin_only", message: "Only an admin can keep a new volume on the unit."}` (`kept_on_create`, `app/core/kept_volumes.py`). In fisqua mode only an admin can create a volume at all: anyone else is refused first with `403` `volumes_from_fisqua` (`create_collection`, `app/api/collections.py`), and an admin may ask for `kept_on_unit`. A volume created under a kept parent is kept. The mode, and the parent's flag, are read again in the insert's transaction; when either changed, the request is refused with `409` and `{code: "mode_changed", message}` (`create_collection`; `mode_for_insert`, `app/core/unit_mode.py`). `PATCH /collections/{id}` does not change it: `POST /collections/{id}/keep-on-unit` and `POST /collections/{id}/release-from-unit` do. +- `date`, `date_start`, `date_end`, `sequence` and `custom_attributes` describe the volume. An end date before its start is refused with `422` when both are in the request, and with `409` when the end is checked against a stored start. + +Refused identity changes and the delete refusal return `409` with `{message}`; constraint violations return `{message, constraint}`. Both rules are in `app/models/collection.py`. The write rules are attribute validators, so they apply to every ORM assignment. The delete refusal is a `before_flush` listener, so it also applies to `session.delete()`, to the delete cascades from `Project.collections` and `Collection.child_collections`, and to delete-orphan. A bulk `query().update()`, raw SQL or a database-level `ON DELETE CASCADE` goes around both. + +**A volume's record order — `records.sequence`.** The records of a volume are ordered by their `sequence`. Under exchange contract 1.1, section 3, renumbering rewrites records' `sequence` and never renames a file: a file's name carries its capture number, and order is the records' `sequence` (`app/core/record_sequence.py`). Every path that puts a record into a volume or rewrites the order in one keeps the volume's sequences distinct. + +- **A record added to a volume takes the next sequence.** A record created by `POST /cameras/capture` or `POST /cameras/capture/dual` (not a retake), a record created by `POST /records/` with a `collection_id`, and a record moved to another volume by `PATCH /records/{id}` take the sequence after the highest in that volume; in a volume with no sequenced record the first is `1` (`next_sequences`, `record_sequence.py`; `app/api/cameras.py`; `app/api/records.py`). `POST /records/` does not use a `sequence` in the body, and gives no sequence to a record outside a volume or to one naming a volume that does not exist. `PATCH /records/{id}` takes no `sequence` in its body; a `sequence` sent there is ignored (`RecordUpdate`, `app/schemas/record.py`). A retake keeps its record's sequence. `POST /collections/{id}/move-records` gives the moved records the sequences after the target's highest, in their listing order in the source (`move_collection_records`, `collections.py`). In each case the volume's row is locked before the highest sequence is read and stays locked until the commit. +- **A record inserted after another is given the sequence right after it.** Under contract 1.9, section 10.2, two paths put new records right after a given record of the volume instead of after the highest: `POST /cameras/capture/dual` with `afterRecordId` (one record) and the placeholders of `POST /collections/{id}/records/missing-opening` or of a Fisqua request (`count` records). Each adds the count to the sequence of every record of the volume whose sequence is after the given record's, and gives the new records the freed values (`insert_after`, `record_sequence.py`). The given record may have any status, `excluded` included. A record without a sequence keeps none. When the given record has no sequence, or shares it with another record, the volume is first numbered 1..N in listing order, as a renumber does. No file is renamed, read or written. The volume's records and then its row are locked as for a renumber. On the two routes, the same `409` with `"The volume changed while it was being renumbered. Try again."` is returned after five attempts; on a Fisqua request, the decisions set is rolled back and `apply_decisions` returns the status `error` (`apply_decisions`, `fisqua_decisions.py`). +- **`POST /collections/{id}/images/renumber`.** Admins and operators may renumber. The route sets the `sequence` of every record of the volume to 1..N in listing order: by `sequence`, records without one last, records that share one by id (`listing_order`, `record_sequence.py`; `renumber_volume_records`). No file is renamed, moved or written, no manifest line is written, and records of other volumes are not touched. The response is `200` with `{renumbered: N}`, N being the number of records in the volume (`collections.py`). A volume that does not exist is refused with `404`. A failed commit is the `500` described above. The renumber is recorded in the activity log as `images_renumbered`. +- **`PATCH /collections/{id}/records/reorder`.** Admins and operators may reorder. The body is `{ordered_ids: [...]}`, and the list must name every record of the volume exactly once. Each record's `sequence` is set to its position in the list, counted from 1. An empty list is refused with FastAPI's validation `422` (`ReorderRecords`, `app/schemas/record.py`). A list that leaves a record out, repeats one or names a record of another volume is refused with the application's `422` and the plain-string detail `"ordered_ids must name every record of the volume exactly once."`, and nothing is written (`reorder_volume_records`, `record_sequence.py`; `collections.py`). The response is `200` with `{reordered: N}`. A volume that does not exist is refused with `404`. +- **Both answer `409` when the volume keeps changing.** Renumber and reorder lock the volume's records and then the volume's row. If a record was added to the volume between the two, the transaction is rolled back and the locking starts again. After five attempts that each found the volume's records changed, the request is refused with `409` and the plain-string detail `"The volume changed while it was being renumbered. Try again."` (`lock_volume_records`, `record_sequence.py`; `LOCK_ATTEMPTS` and the message; `collections.py`). Nothing is written. On SQLite no lock clause is emitted (`record_sequence.py`). +- **A renumber or reorder during an export fails the export.** Neither route is refused while an export of the volume is queued or running. When the export job has planned its payload, and before it writes anything, it compares each record's status, `sequence` and current images with what they were when the job passed its gate. If any differ, the job fails: `GET /collections/{id}/export/status/{job_id}` returns `state: "failed"`, the `error` `"Cannot export: the collection changed while the archive was being assembled (N record(s) affected). Try again."` and `detail: {blocking_record_ids}` (`app/core/export_service.py`; `app/core/export_jobs.py`). + +**Renaming, moving and deleting a volume — `PATCH /collections/{id}`, `POST /projects/{id}/move-collections` and `DELETE /collections/{id}`.** A volume belongs to a project or to a parent volume, never to both and never to neither (`check_collection_parent`, `app/models/collection.py`). + +- **A null parent makes the volume top-level in its root's project.** `PATCH /collections/{id}` with `parent_collection_id: null` on a nested volume follows the volume's chain of parents to the top-level volume it hangs from and gives the volume that volume's `project_id`, so the volume becomes a top-level volume of the project its former root belongs to. The chain is read under the volume's row lock, before anything is changed. On a volume that is already top-level, the null is dropped and nothing changes (`update_collection`, `app/api/collections.py`). +- **A volume that is not kept cannot move under a kept one.** A `PATCH` that names a new parent which Captua keeps on the unit, for a volume it does not keep, is refused with `409` and `{code: "kept_on_unit_move", message}` (`refuse_kept_reparent`, `app/core/kept_volumes.py`). A kept volume may move under a parent that is not kept, or to the top level. `CollectionUpdate` has no `project_id` field, so a `PATCH` cannot name the project (`CollectionUpdate`, `app/schemas/collection.py`). +- **Each change is recorded in the activity log after its commit.** A refused or failed request records nothing (`update_collection`, `collections.py`). Each value in a detail is written as Python writes it: a string quoted, an absent value `None`. + - `collection_renamed`, at `INFO`, when a `PATCH` changes the volume's name or its stem, a stem set for the first time included. The subject is the new name, and the detail is `id=; stem -> ; name -> `, with both pairs whichever changed (`collections.py`; `_volume_change_detail`). + - `collection_moved`, at `INFO`, when a `PATCH` changes the volume's project or its parent, with the detail `id=; project -> ; parent -> ` (`update_collection`, `collections.py`). `POST /projects/{id}/move-collections` records one `collection_moved` for each top-level volume of the source project, read before the move, with `parent None -> None`, and then its own `collections_moved` entry. The sub-volumes, which follow their parents, get no entry of their own (`app/api/projects.py`). + - `collection_deleted`, at `WARN`, when `DELETE /collections/{id}` has committed. The subject is the volume's name, and the detail is `id=; stem ; project ; parent ; records=; images=; sub-collections=`. The route refuses a volume that still has records or sub-volumes, so the three counts are always `0` (`delete_collection`, `collections.py`). + +**A volume's offsite copy — `GET /collections/{id}/offsite`, `GET /system/catalogue-backup` and the refusals.** The backend uploads every image of each volume with a stem that Captua does not keep on the unit to the offsite bucket, records each object in `offsite_objects`, and uploads an encrypted dump of the catalogue to the same tenant prefix (section 5, Offsite copies). This is what reaches a client. + +- **`GET /collections/{id}/offsite`, the received indicator.** Admins, operators and reviewers may read it (`allow_read_only`, `app/api/collections.py`). A volume that does not exist is refused with `404`. The response carries `collection_id`, `filename_stem`, `uploadable` (the volume has a stem), the counts `total`, `verified`, `pending` and `refused`, `last_verified_at` (the latest verification among the volume's objects, or `null`), `received`, `refusals`, `freed_files` and `freed_bytes` (below, Freeing a volume), `held` and `hold_file` (the upload hold, below), `kept_on_unit`, and `fisqua` (`null` when Fisqua is not configured; otherwise the object described under Delivery to Fisqua, below) (`get_collection_offsite_state`, `app/api/collections.py`; `volume_upload_state`, `app/core/image_upload.py`; `_object_counts`). `total` counts one capture object for each image of the volume's records, superseded images included, and one preview object for each RAW master whose preview has a row or is on disk. `pending` is `total` less `verified` and `refused`, so it includes objects not yet tried. For a volume Captua keeps on the unit, `pending` is `0` and `total` is the number of files Captua would copy. `received` is `true` only when `total` is above `0` and every object is verified; a volume with nothing to upload has received nothing. Each entry of `refusals` carries `image_id`, `kind` (`capture` or `preview`), `reason`, `key`, `local_sha1`, `remote_sha1` and `refused_at`. A volume without a stem is answered with `uploadable: false`, zero counts, `received: false` and no refusals, and still carries `held` and `hold_file`. +- **The `refusal` values.** There are two, and a check constraint admits no other (`REFUSALS`, `app/models/offsite_object.py`). `remote_differs`: before the upload, the listing showed an object at the key with another SHA1, which is stored as `remote_sha1`. `fixity`: the file's sha256 is not the one its capture record holds; `remote_sha1` is then `null`. An image with no capture-time sha256 is not refused on that ground (`offsite_object.py`; `image_upload.py`). Nothing is uploaded for a refused object, and the uploader does not retry it. Each refusal is also written to the system log as `image_upload_refused` at `ERR`, with the key as subject (`_refuse`, `image_upload.py`). +- **`GET /system/catalogue-backup`.** Admins, operators and reviewers may read it (`get_catalogue_backup_state`, `app/api/system.py`). `enabled` is `true` when `CAPTUA_OFFSITE_REMOTE` is set and `CAPTUA_OFFSITE_TENANT` holds a valid tenant prefix (`is_configured`, `app/core/catalogue_backup.py`). `mode_allows` is the unit mode's answer: `false` in offline mode, where no dump is taken, so the age of the last verified dump says nothing then about whether the copy has stopped (`offsite_on`, `app/core/unit_mode.py`). `last_verified_at`, `object` and `detail` come from the most recent `catalogue_backup_verified` entry in the system log, and are `null` on a unit that has never verified a dump (`last_verified_backup`, `catalogue_backup.py`). `object` is the dump's name, `catalogue--<6 hex digits>.sql.gz.age`, and `detail` reads `verified at //: bytes encrypted, raw, sha1 ` (`_object_name`; `run_catalogue_backup`, which adds `AGE_SUFFIX` and writes the detail; `remote_dir`). `held` and `hold_file` report the upload hold (below); `held` is `true` while the file exists, and `hold_file` is its path whether or not it exists (`hold_state`, `app/core/offsite_hold.py`; `app/api/system.py`). `images` is the image upload's summary for the unit (`unit_upload_summary`, `image_upload.py`): `enabled`, `mode_allows` (`true` in backup and fisqua mode), `tenant`, `misconfigured`, `volumes` (the volumes with a stem that Captua does not keep on the unit), `volumes_received`, the counts `total`, `verified`, `pending`, `refused`, `freed_files` and `freed_bytes` summed over those volumes, `last_verified_at`, `kept_volumes` (the number of volumes Captua keeps on the unit, with or without a stem) and `kept_files` (the files it would copy of them), `held` and `hold_file` (the same two values as at the top level), and `last_run`, the result of the upload's most recent run in this backend process. `last_run` is `null` until the first run after a start; a run's result has `status` (`done`, `stopped`, `held`, `aborted` or `failed`; a run that finds no remote or no tenant returns only `{status: "disabled"}`, and one with an invalid tenant `{status: "misconfigured", error}`), the counts `uploaded`, `already_present` and `unverified`, the lists `refused`, `conflicts` and `skipped`, `error` and `finished_at` (`RunResult.as_dict`; the statuses). A run in offline mode returns `{status: "off_in_this_mode", mode}` and nothing else, and a run already draining when the unit is switched to offline stops before its next object with the full result and status `off_in_this_mode` (`image_upload.py`; The unit's mode, below). `fisqua` is the unit's Fisqua summary, described under Delivery to Fisqua, below (`unit_fisqua_summary`, `app/core/fisqua_outbox.py`; `app/api/system.py`). +- **The upload hold.** While the file named by `CAPTUA_OFFSITE_HOLD_FILE` exists, nothing is sent offsite. The default is `offsite-hold` in `CAPTUA_DATA_DIR`, `/var/lib/dtk/offsite-hold` on a unit, and only the file's existence counts (`hold_file`, `is_held`, `app/core/offsite_hold.py`; `offsite_hold_file`, `app/core/config.py`). The backend only reads the file; no script creates or removes it. An operator creates it by hand during an upgrade, before the tenant is written to `offsite.env`, and removes it after the one-time commands (`adopt`, `mark-freed` and the others) have run. It is read at the start of every run and not when a schedule starts, so a hold that is created or removed applies from the next tick, with no restart. The routes show it as `held` and `hold_file` on `GET /collections/{id}/offsite` and `GET /system/catalogue-backup` (above). While it exists: + - the image upload lists and uploads nothing and returns status `held` with `hold_file`, after its check of the mode (in offline mode it returns `{status: "off_in_this_mode", mode}` first); a run held at its start returns `{status: "held", hold_file}` and nothing else, and that is what `last_run` holds (`run_image_upload`, `image_upload.py`; the scheduler keeps the result as it is in `last_result`). A run already draining checks the file between objects and stops after the object in progress; its result is the full run result with status `held` and no `hold_file`. When a run did work, the uploader logs `image_upload_run` at `INFO` if its status is `held` and nothing was refused; + - the Fisqua send pass and the Fisqua status poll each return `{status: "held", hold_file}` at their start, after their check of the mode (outside fisqua mode each returns `{status: "off_in_this_mode", mode}` first), make no call to Fisqua and promote nothing (`run_fisqua_outbox`, `app/core/fisqua_outbox.py`; `poll_fisqua_status`); + - the catalogue dump is not taken and the run returns status `held` with `hold_file`, after its check of the mode; the sweep of stale dumps still runs (`run_catalogue_backup`, `catalogue_backup.py`); + - `POST /collections/{id}/offsite/free` is refused with `409` (below). The dry run, `GET /collections/{id}/offsite/free`, and `POST /collections/{id}/offsite/restore` are not refused. The free is held because the upgrade's one-time commands may still be completing the volume's offsite rows and freed state; the dry run changes nothing, and restore is the way back for a freed file (`_prepare_free`, `offsite_free.py`; `app/core/offsite_hold.py`). A free already running when the file is created is not stopped. +- **The `misconfigured` state.** When `CAPTUA_OFFSITE_TENANT` is set to a value that is not a tenant prefix, after surrounding whitespace and slashes are stripped (`configured_tenant`, `image_upload.py`), `images.misconfigured` carries one of three messages, `images.tenant` is `null`, and both `enabled` fields are `false`; otherwise `misconfigured` is `null`. A tenant prefix is Fisqua's tenant slug: 1 to 63 lowercase letters, digits and single hyphens, starting with a letter, with no hyphen at the end and no double hyphen, and none of `platform`, `www`, `api`, `admin` and `app`. The checks run in this order, each with its message: not matching the pattern, `CAPTUA_OFFSITE_TENANT='' is not a tenant prefix (lowercase letters, digits and single hyphens, starting with a letter)`; a reserved name, `CAPTUA_OFFSITE_TENANT='' is reserved by Fisqua and cannot be a tenant prefix`; and more than 63 characters, `CAPTUA_OFFSITE_TENANT is characters long; a tenant prefix is at most 63`. `scripts/provision-rclone.sh` checks a tenant by the same rule (`valid_tenant`, `scripts/provision-rclone.sh`). (`TENANT_PATTERN`, `image_upload.py`; `configured_tenant`). The backend starts neither schedule at boot in that state, so no image and no dump is uploaded and nothing is written to the system log, and `last_verified_at` keeps the date of the last dump verified before (`start`, `catalogue_backup.py`; `start`, `image_upload.py`). A missing or invalid `CAPTUA_OFFSITE_DUMP_RECIPIENT` is not shown by the route: `enabled` stays `true`, each run that the mode and the hold allow, on a day with no verified dump, records `catalogue_backup_failed` at `ERR` with the detail `not run: ` and writes no dump, and `last_verified_at` stops advancing (`run_catalogue_backup`, `catalogue_backup.py`). +- **A record with a file in the bucket stays in its volume.** Any `offsite_objects` row for one of a record's images, verified, pending or refused, holds the record in its volume, because the object's key is under the volume's stem and never changes (`records_stored_offsite`, `image_upload.py`). The row is committed before the upload starts, so the record is held from the moment its first key is reserved. Three routes change a record's volume, and each checks this under the record's row lock, after its handover refusal (`assert_movable`). Each also refuses a move between a volume Captua keeps on the unit and one it does not, and a move into or out of a kept volume from outside every volume, with `409` and `{code: "kept_on_unit_move", message}` (`refuse_kept_move`, `app/core/kept_volumes.py`). `PATCH /records/{id}` makes the kept check before the offsite check; the other two make it after: + - `PATCH /records/{id}` that changes the record's volume is refused with `409` and the plain-string detail `"This record's files are already stored offsite under this volume, so it cannot be moved to another volume."` when the record is in a volume, or when the request leaves it in none (`STORED_OFFSITE_MESSAGE`, `image_upload.py`; `app/api/records.py`). A `project_id` in the body clears `collection_id`, so it counts as a change of volume (`update_record`, `records.py`). + - `POST /projects/{id}/add_record/{rec_id}`, which detaches the record from any volume, is refused with `409` and the same detail when the record is in a volume and any of its images has an offsite row, after the handover refusal (`assert_movable`). A record outside every volume is not checked, so only its project changes (`add_record_to_project`, `app/api/projects.py`). + - `POST /collections/{id}/move-records` to another volume is refused whole with `409` when any record of the volume has such a row, before anything is moved. The `detail` is `{message, blocking_record_ids}`, with the message `"Cannot move: N record(s) have files already stored offsite under this volume: [ids]."` (`move_collection_records`, `collections.py`). +- **The way back for a record outside every volume.** A record with offsite rows and no volume (one taken out before `add_record` checked for them) can be put back into a volume only by `PATCH /records/{id}`, and only into the volume whose stem all its keys are under, `//...`, with `` the configured `CAPTUA_OFFSITE_TENANT` (`offsite_keys_under_volume` and `_key_stem`, `image_upload.py`). The target volume's row is locked after the record's before the keys are compared (`update_record`, `records.py`). A `PATCH` that keeps such a record outside every volume and changes only its `project_id` is not checked (`update_record`, `records.py`), and neither is `POST /projects/{id}/add_record/{rec_id}` for it (`add_record_to_project`, `projects.py`). Any other target, a volume that does not exist included, is refused with `409` and a plain-string detail from `stranded_offsite_message` (`stranded_offsite_message`, `image_upload.py`): + - all keys under one stem: `"This record's files are stored offsite under the volume stem , so it can be put only into the volume with that stem."`; + - keys under more than one stem: `"This record's files are stored offsite under more than one volume stem (), so it can be put into no volume."`; + - a key that is not of the form `//`, such as an adopted key or one under an earlier tenant: `"This record's files are stored offsite under keys that name no volume of this unit, so it can be put into no volume."`; + - no valid `CAPTUA_OFFSITE_TENANT`: `"This record's files are stored offsite, and no valid CAPTUA_OFFSITE_TENANT is set, so their keys cannot be matched to any volume of this unit. It can be put into a volume only once CAPTUA_OFFSITE_TENANT is set, and then only into the volume its keys are under."` +- **The files-being-read hold.** To read an image, the uploader holds the image's volume for a short span, in which it re-reads the image's row and makes a hard link to its file (`hold_for_reading`, `app/core/export_jobs.py`; `_read_object`, `image_upload.py`). A request that takes the hold for file changes on that volume during the span is refused with `409` and the plain-string detail `"Captua is preparing a file of this volume for the offsite copy. Try again in a moment."` (`FILES_BEING_READ_MESSAGE`, `export_jobs.py`). The routes that take that hold are `DELETE /records/{id}`, `DELETE /records/images/{img_id}` for a current image, `POST /collections/{id}/move-records` for the source volume, and the free, its dry run and the restore below (`records.py`; `collections.py`; `app/core/offsite_free.py`), and, only for volumes with files still in the name-based layout, `PATCH /collections/{id}` with a rename or a re-parent, `PUT /projects/{id}` with a rename and `POST /projects/{id}/move-collections` (`collections.py`; `projects.py`). `PATCH /records/{id}`, `POST /projects/{id}/add_record/{rec_id}` and the renumber do not take it; they rewrite rows and move no file (`_read_object`, `image_upload.py`). In the other direction, the uploader skips an image whose volume a request holds for file changes, and tries it again on its next run (`_read_object`, `image_upload.py`). + +**Freeing a volume from the card, and restoring it — `/collections/{id}/offsite/free`, `/offsite/restore` and `/offsite/jobs/{job_id}`.** Freeing removes a received volume's masters and the previews of its RAW masters from the card; thumbnails stay. The image rows keep their paths, and `record_images.master_freed_at` and `preview_freed_at`, each with its size in `master_freed_bytes` or `preview_freed_bytes`, record that the file is stored offsite (`app/core/offsite_free.py`; `app/models/record.py`, added by migration `c4e8f1a3b5d7`). `GET /records/images/{img_id}` returns both timestamps (`RecordImageRead`, `app/schemas/record.py`). All four routes are admin-only (`allow_admin`, `app/api/collections.py`). + +- **The routes.** `GET /collections/{id}/offsite/free` is a dry run: it lists the bucket and changes nothing (`collections.py`). `POST /collections/{id}/offsite/free` and `POST /collections/{id}/offsite/restore` answer `202` with `{job_id, state, action, status_url}`, the URL being `/collections/{id}/offsite/jobs/{job_id}`, and do the work in a background job. `GET /collections/{id}/offsite/jobs/{job_id}` returns `{job_id, collection_id, action, state, result, error}`, with `action` `free` or `restore` and `state` `queued`, `running`, `done` or `failed`; a job id that is unknown, or belongs to another volume, is `404` with `"Job not found"` (`offsite_job_status`, `collections.py`; `OffsiteJob.to_dict`, `offsite_free.py`). A finished job is dropped a day (`FINISHED_JOB_TTL`, 24 hours) after it ends, when the next job is reserved, and then answers `404` (`offsite_free.py`). A queued or running job is not dropped by age. The registry lives in the backend process and each job runs in a daemon thread, so a restart loses every job, a running one included, and its id then answers `404` (`run`, `offsite_free.py`). +- **Refusals before a job starts.** Each is a `409` whose `detail` is `{message, ...}` unless noted (`FreeRefused.as_detail`, `offsite_free.py`; `collections.py`). In order (`start_free` and `start_restore`, `offsite_free.py`; `_prepare_free`; `_prepare_restore`): + - a free or restore of the volume already queued or running: `"Files of this volume are already being freed or restored. Wait for that to finish."`, with `job_id` (`offsite_free.py`; not on the dry run); + - for a free, the unit in offline mode (The unit's mode, below): `"The unit is in offline mode, so the bucket copy is not kept up and no file on the unit is freed or marked freed. Switch to a mode with the offsite copy to free space."`, with `code` `off_in_this_mode` and `mode`. It is checked before the hold and before the volume is looked up. Neither the dry run nor a restore is refused for it (`OFFLINE_MESSAGE`, `_refuse_offline`, `offsite_free.py`; `_prepare_free`; `plan_free`); + - for a free, the upload hold file exists (above): `"Offsite uploads are on hold on this unit while it is being upgraded, so no files can be freed from the card. Try again once the upgrade has finished."`, with `hold_file`. It is checked before the volume is looked up, so it is also the answer for a volume that does not exist. Neither the dry run nor a restore is refused for it (`HOLD_MESSAGE`, `offsite_free.py`; `_prepare_free`); + - a volume that does not exist: `404`, `{message: "Collection N not found"}` (`_volume`, `offsite_free.py`); + - no stem: `"This volume has no file name stem, so none of its files are stored offsite and none can be freed or restored."` (`NO_STEM_MESSAGE`, `offsite_free.py`); + - any image of the volume still in the name-based layout: the `NOT_IN_OWN_FOLDER_MESSAGE` text, which begins `"Some of this volume's files have not yet been moved into the volume's own folder"`, with `folder` (`/`) and `images_outside_own_folder` (`offsite_free.py`); + - for a free and its dry run, a volume Captua keeps on the unit: `"Captua keeps this volume on the unit and copies none of its files offsite, so none of them can be freed from the card."`, with `code` `kept_on_unit` (`_require_received`, `offsite_free.py`); + - for a free and its dry run, a volume not received (section above): `"Not every file of this volume is verified in the offsite bucket yet, so its files cannot be freed from the card. Wait for the upload to finish."`, with `total`, `verified`, `pending` and `refused` (`offsite_free.py`); + - for a restore, no `CAPTUA_OFFSITE_READ_REMOTE`: `"Restore is not set up on this unit: it needs read access to the offsite bucket (CAPTUA_OFFSITE_READ_REMOTE), and none is configured."` (`offsite_free.py`); and a volume directory under a storage root that cannot take writes, `503` with a string `detail` (`app/main.py`); + - the hold for file changes refused: `"An export of this volume is queued or running. Wait for it to finish, then try again."`, or the files-being-read message (`_Hold`, `offsite_free.py`); + - for a free and its dry run, a bucket listing that does not answer: `"The offsite bucket could not be listed, so nothing could be checked against it and nothing was freed. Try again later."`, with `error` (`offsite_free.py`). +- **What a free checks, file by file.** The work list is the volume's objects with a verified offsite row that are not yet freed (`_objects`, `offsite_free.py`). The job checks the stem and the folder again, then refuses, as entries of `result.refused` with a `reason`: an object whose image is in the name-based layout, `outside_own_folder`; a RAW preview whose capture manifests hold no sha256 for it, `no_preview_digest` (its master may still be freed); a file not on disk, `local_file_missing`; one that changed or could not be read while it was hashed, `local_file_unreadable`; and one whose recomputed SHA1 is not its row's `local_sha1`, `local_sha1_differs`, with `local_sha1` and `expected_sha1` (`_free_work`; `_layout_refusal`; `_digest_refusal`). It then lists the bucket again and refuses a key that is not listed, `not_in_bucket`, one listed with no SHA1, `listed_without_sha1`, and one listed with another SHA1, `bucket_sha1_differs`, with `listed_sha1` and `expected_sha1` (`_listing_refusal`). A file that passes has its freed state committed under its record's row lock, only while the row still names the same path, and is unlinked after that commit. A row that is gone or changed is refused as `changed`, and a failed unlink clears the state again and is refused as `could_not_remove`, with `error` (`_set_freed`). A listing that does not answer during the job fails the job with the listing message, followed by the listing's error in parentheses (`run`, `offsite_free.py`). +- **What a restore does.** For each freed object, the job copies the object from `CAPTUA_OFFSITE_READ_REMOTE` with `rclone copyto --inplace`, one at a time under the upload's transfer lock and `CAPTUA_OFFSITE_BWLIMIT`, to `...part` beside the file's path. It checks the copy's SHA1 against the row's `local_sha1`, fsyncs it, and moves it into place with `os.replace` under the record's row lock, clearing the freed state (`_restore_one`, `offsite_free.py`; `_copy_from_bucket`; `_place`). A file already at the path is never overwritten: when its SHA1 is the object's, the state is cleared and the entry carries `already_present: true`; otherwise it is refused as `local_file_differs`. An object whose image is in the name-based layout when the work list is read stays freed and is refused as `outside_own_folder`, as in a free (`_restore_work`, `offsite_free.py`). The other refusals are `outside_storage`, `copy_failed` (with `error`), `sha1_differs` (with `copied_sha1` and `expected_sha1`), `could_not_write` (with `error`) and `changed`. A storage root that becomes unusable stops the job, which fails with that message. +- **Results.** A free's `result` is `{collection_id, filename_stem, freed: {files, bytes}, files, refused, manifest}`, each freed file with `image_id`, `kind`, `path`, `key`, `bytes`, `sha1` and `freed_at` (`_free_work`, `offsite_free.py`). A restore's is the same with `restored` for `freed` and `restored_at` on each file. The dry run returns `{collection_id, filename_stem, would_free: {files, bytes}, files, refused, local_sha1_checked: false}`. For each object it applies, in this order, the layout, preview-digest, listing and missing-file refusals. It hashes nothing, so it never reports `local_file_unreadable` or `local_sha1_differs` (`plan_free`, `offsite_free.py`). A free writes one line for each file it freed, and a restore one for each file it restored, to `/metadata/offsite-freed-.jsonl` or `offsite-restored-.jsonl`; the file is created with its first line, so a run that freed or restored nothing leaves none (`_RunManifest`, `offsite_free.py`). A free logs `volume_freed` in the system log only when it freed or refused something, and a restore logs `volume_restored` when it restored or refused something or was stopped. The entry is at `WARN` when anything was refused, and for a restore also when it was stopped, and at `INFO` otherwise. +- **A freed file is not missing.** The image routes answer `410` for a freed file, with `detail` `{message, stored_offsite: true, image_id, kind, key, freed_at}` and the message `"This file is stored offsite and has been freed from the card to make room. An admin can restore the volume to bring it back."` (`freed_detail`, `offsite_free.py`; `_freed`, `app/api/records.py`). `GET /records/images/{img_id}/file` answers it for a freed master (`_stored_master`). `GET /records/images/{img_id}/preview` answers it for a RAW master's freed preview, and for any other image whose master was freed; a RAW master's preview is still served when only the master was freed (`get_image_preview`, `records.py`). `GET /records/images/{img_id}/thumbnail` serves a stored thumbnail as before, and answers `410` only when the thumbnail has to be made again from a freed source. `POST /collections/{id}/export` is refused with `409` and `{message, freed_image_ids}` while any current image's master is freed, with the message `"N file(s) of this volume are stored offsite and freed from the card. Restore the volume before exporting it."`; the export job checks again and fails with `reason: "freed_files"` (`export_collection_bagit`, `collections.py`; `_do_export`, `app/core/export_service.py`; `FREED_EXPORT_MESSAGE`, `offsite_free.py`). The integrity check lists a freed master under `freed_files`, not `missing_files`, and does not hash it (`app/core/integrity.py`). `GET /collections/{id}/offsite` and the `images` summary count freed files in `freed_files` and `freed_bytes` (`image_upload.py`). + +**The capture manifest for Fisqua — `GET /collections/{id}/capture-manifest`.** The route returns the volume's capture manifest, artefact 2 of the exchange contract (section 4, as in 1.1, with the additions of 1.5, 1.6 and 1.9), as a JSON download. Admins and operators may export it (`allow_contributor`); a volume that does not exist is `404` (`app/api/collections.py`). The manifest is built from the catalogue, the capture manifests and `offsite_objects` only, so no image file is read and the manifest of a freed volume is the same as that of one still on the card (`app/core/capture_manifest.py`). + +- **The response.** `200` with `{contract: "fisqua-captua-exchange", version: "1.9", kind: "capture-manifest", id, generatedAt, generatedBy: {system: "captua", instance: , systemVersion}, inReplyTo: null, project: {captuaProjectId, name}, transfer: {channel: "upload", root: "/"}, volumes: [...]}`, with a new `id` on every export (`build_capture_manifest`, `capture_manifest.py`). `version` is always `"1.9"`, whatever the records and whatever `CAPTUA_FISQUA_ROTATE_DEG` (`VERSION`, `capture_manifest.py`). With `CAPTUA_FISQUA_ROTATE_DEG` set, each image whose `rotate_deg` is `0`, `90`, `180` or `270` also carries `rotateDeg`, that value, counted clockwise from the stored pixels with the EXIF tag ignored; an image with no recorded rotation carries none, and with the setting off no image carries it (`capture_manifest.py`). `systemVersion` is the release the unit runs, with the backend's commit appended when the code is not the tagged release (Version reporting, below). The one volume carries `externalId`, `captuaCollectionId`, `stem`, `title` and `records`; each record `captuaRecordId`, `sequence`, `status`, `rejectionNote` (a rejected record's latest comment, or its reason) and `images`, and, where they apply, `missingSide`, `closedReason`, `closedNote` and `requestId` (below; `_record_entry`, `capture_manifest.py`); each image `captureId`, `pairId`, `filename`, `role`, `objectKey` and `sha256`, and for a RAW image `previewObjectKey` and `previewSha256`. `externalId` is the volume's recorded `external_id`, stripped, or its stem when none is recorded (`reference_code`, `capture_manifest.py`). An image is RAW when its file on disk has a suffix in `RAW_SUFFIXES`, or when the name in its capture key has one, so an adopted object whose key names a RAW is counted as RAW and needs a preview. Every record of the volume is listed with its status, in the order of its `sequence`, and only current images. A record still `captured` refuses the export (`records_captured`), except an open missing record (below). The keys are the frozen keys of the verified objects with the tenant prefix taken off, and `filename` is the last segment of the capture key. The `sha256` values come from the capture manifests and are never computed here (`_digest`). The download name is `capture-manifest__.json`, by the UTC date, in `Content-Disposition` (`download_name`; `collections.py`). Each export is logged in the activity log as `capture_manifest_exported`, at `INFO`, with the stem as subject and the detail `volume id= records= images= previews=` (`export_capture_manifest`, `collections.py`). +- **Missing and excluded records (contract 1.9, section 10.1).** A record with a `missing_side` (Openings and pages never captured, below) is listed with `status` `"missing"`, whatever its status on the unit other than `excluded`, and `missingSide` `left`, `right` or `both`, with its current images: the other page's for a side, none for a placeholder. Once it has been closed it also carries `closedReason` and, when a note was written, `closedNote`. A record `excluded` by a Fisqua decision (contract 1.6) keeps `status` `"excluded"`, and still carries `missingSide` and the closing fields when it has them. A record made from a Fisqua request carries its `requestId`, whatever its status, and still carries it after it has been captured into. A placeholder that has been captured into is an ordinary record and carries no `missingSide` (`_record_entry`, `capture_manifest.py`; `_request_id`). An open missing record, one not closed, does not refuse the export as a captured record does, but its images are listed and must pass every image check. Pages are the images of records in review or approved, except an open missing record's: its image is not a page, and a missing record with no image is not refused as `roles_invalid`. A closed missing record in review or approved has its images counted as pages. An excluded record is listed with its current images, is not a page, and its roles are not checked. Before 1.9, a record that missed a side was left out of the manifest; it is now listed as `missing`. +- **`409` with problems.** When Fisqua would refuse the file, the route answers `409` with `detail: {message, problems}`. `message` is `"The capture manifest cannot be exported, because Fisqua would refuse it: "` followed by each problem's message, and each problem is `{rule, message, record_ids, image_ids}` (`collections.py`; `ManifestRefused`, `capture_manifest.py`; `Problem.as_dict`). The rules, in the order they are reported, are `tenant_missing`, `tenant_invalid`, `no_stem`, `no_project`, `records_captured`, `sequence_missing`, `sequence_repeated`, `roles_invalid`, `missing_side_contradicted`, `capture_id_missing`, `not_uploaded`, `preview_not_uploaded`, `raw_without_preview`, `upload_refused`, `key_outside`, `filename_form`, `page_key_repeated`, `sha256_missing`, `preview_sha256_missing` and `no_pages` (`RULES`). The messages of the record-level rules name the records concerned, at most twenty ids, and the fix (`_problems`; `_ids`). `tenant_missing`, `tenant_invalid`, `no_stem`, `no_project` and `no_pages` name the fix only. `no_pages` is reported when no record in review or approved, other than an open missing record, has an image, and no open missing record that is not excluded remains: Fisqua accepts a delivery whose only records are missing as long as one of them is open (contract 1.9 §10.3, amended). `missing_side_contradicted` refuses a missing record, other than an excluded one, that has an image on its missing side, or any image when it misses `both`: exactly the two clauses of Fisqua's `missing-side` rule (§9.2), so the unit refuses nothing Fisqua would accept (`_contradicts_its_side`, `capture_manifest.py`). + +**Delivery to Fisqua — the `fisqua` object of `GET /collections/{id}/offsite` and `GET /system/catalogue-backup`, and what a handover does.** A unit queues the capture manifest of each handed-over volume and, when Fisqua is configured and the unit is in fisqua mode, sends it over HTTPS once every object of the volume is verified in the bucket and the volume is not kept on the unit, polls Fisqua for the volume's status, and applies Fisqua's QC decisions to the volume's records (`app/core/fisqua_outbox.py`, `app/core/fisqua_decisions.py`, `app/core/fisqua_http.py`). The names on Fisqua's side are in `app/core/fisqua_contract.py`, which names contract version `1.2` (`CONTRACT_VERSION`). The manifest document itself declares `version: "1.9"`, whatever its records and settings; `CONTRACT_VERSION` is not sent (`VERSION`, `capture_manifest.py`). `GET /collections/{id}/capture-manifest` is not tied to the configuration. The tables are `fisqua_outbox` and `fisqua_status`, created by migration `9b7087bd0bc5` and extended by `a5f0306a8f8c` and `6df85ec6309b` (`app/models/fisqua.py`). + +- **When Fisqua is configured.** The environment is `production` or `staging`, the token is 64 lowercase hexadecimal characters, and the offsite tenant is valid (`fisqua_configured`, `fisqua_outbox.py`; `TOKEN_PATTERN`, `fisqua_contract.py`). Otherwise `fisqua` is `null` on the volume route, a handover still queues its `waiting_for_upload` row, which waits, the worker returns `{status: "disabled"}`, and the poll thread is not started (`fisqua_outbox.py`; `FisquaStatusScheduler.start`, `fisqua_outbox.py`). A handover still supersedes, and a take-back still withdraws, the volume's unsent rows. The host is `https://.fisqua.org` in `production` and `https://.staging.fisqua.org` in `staging`. `CAPTUA_FISQUA_BASE_URL` replaces it only when it is `https://`, or `http://` to `127.0.0.1`, `localhost` or `[::1]`; any other value is ignored with one warning in the journal for each value (`base_url`, `_usable_override`, `fisqua_outbox.py`; `ENVIRONMENTS`, `fisqua_contract.py`). The token goes in the `Authorization: Bearer` header only. The transport follows no redirect, verifies TLS, and times out after `CAPTUA_FISQUA_TIMEOUT` seconds to read and write, with 10 seconds to connect; the description search has its own 5-second timeout for every phase (`HttpFisquaTransport`, `fisqua_http.py`; `SEARCH_TIMEOUT_SECONDS`, `fisqua_contract.py`). `redact` replaces the token with `[token]` in everything the transport returns before a row, a log line or an error text is written, and the settings hold it as a `SecretStr` (`scrub`, `fisqua_outbox.py`; `FISQUA_TOKEN`, `config.py`). `token_invalid` on the unit summary is `true` when a token is set and is not of that shape; its value is never shown. +- **What a handover does.** `POST /collections/{id}/promote` (`allow_contributor`) that promotes at least one record calls `enqueue_handover` in the same transaction as the status changes: every unsent row of the volume (`waiting_for_upload`, `ready`, `failed`) becomes `superseded`, a row being sent is marked to become `superseded` unless the send delivers or is refused, and a `waiting_for_upload` row is added with a new UUID as `manifest_id`, whatever the configuration and the mode; it waits until the unit is in fisqua mode with Fisqua configured (`app/api/collections.py`; `enqueue_handover`, `fisqua_outbox.py`; `_cancel_sending`). A promote that finds no captured record to promote, open missing records aside, returns `promoted: 0` and queues nothing. A change to a volume's missing records also queues a handover, when the volume was handed over before (Openings and pages never captured, below). After the commit, `promote` calls `image_upload_scheduler.wake()`, which starts an upload run at once, or one more run after a run in progress, however many wakes arrive; it does nothing when the offsite schedule is not running (`collections.py`; `ImageUploadScheduler.wake`, `image_upload.py`; `_wait`). Each scheduled run uploads first and then runs the Fisqua send pass in the same thread, so a volume received in that run is sent in that run (`tick`). `POST /collections/{id}/take-back` that returns at least one record to `captured` makes the volume's unsent rows `withdrawn`, whatever the configuration, and marks a row being sent the same way (`collections.py`; `withdraw_unsent`, `fisqua_outbox.py`). A delivered or refused row is left as it is, and nothing is sent to Fisqua on a take-back. +- **The states of an outbox row.** `waiting_for_upload`: handed over, manifest not built, `manifest_id` reserved. `ready`: the manifest is built and stored on the row, so a retry sends the same document. `sending`: claimed by the worker. `delivered`: Fisqua accepted it, with `delivered_at` and, in `external_id`, the `volumeId` Fisqua gave. `refused`: final, with `refusal` `not_exportable` (the unit could not build the manifest; `problems` lists the problems as the capture-manifest route gives them) or `fisqua` (Fisqua refused it; its answer is in `response` and the problems it named in `problems`). `failed`: the last attempt ended in a transient error, in `last_error`, to be tried at `next_attempt_at`. `superseded`: a later handover queued a newer manifest before this one was sent. `withdrawn`: the handover was taken back before this one was sent (`STATES`, `REFUSALS`, `app/models/fisqua.py`; the descriptions). The database refuses a `refusal` on a row that is not `refused`, a `delivered_at` on a row that is not `delivered`, and a negative `attempts`. +- **The reference code at handover.** A volume's reference code is its recorded `external_id` or else its stem. When the recorded `external_id` is not the stem, the row is `refused` at once with refusal `not_exportable` and one problem, `{rule: "reference_code_differs", message, record_ids: [], image_ids: []}`; the model refuses such a pair for every ORM writer, so only a row written before that rule or by raw SQL can reach this (`_reference_problem`, `fisqua_outbox.py`; `reference_code_differs_problem`). The worker checks again when it builds the manifest. A volume with no stem is built at once, with no wait for the bucket, and refused by the builder with the problem `no_stem` (`capture_manifest.py`). +- **A pass of the worker.** `run_fisqua_outbox` runs after each upload run, in this order (`run_fisqua_outbox`, `fisqua_outbox.py`). A row found `sending` was left by a run that did not finish, and becomes `failed`, due at once, with `last_error` `interrupted while sending`, unless a handover or take-back marked it while it was being sent, in which case it becomes `superseded` or `withdrawn`. Under a unit stop with reason `version`, the pass sends the stop's retest manifest when one is due (The configuration stop, below) and, unless that retest removed the stop, returns `config_error`, or `stopped` or `off_in_this_mode` when the retest ended that way (`run_fisqua_outbox`, `fisqua_outbox.py`). Each `waiting_for_upload` row is promoted when the volume is received, that is, uploadable and every object verified in the bucket, and the volume is not kept on the unit (`_promote`). A row of a kept volume stays `waiting_for_upload`, and counts in `waiting`, until an admin releases the volume; the flag is read again with the volume's row `FOR SHARE` before each move out of `waiting_for_upload`, so a keep committed while the manifest is being built leaves the row waiting (`_kept_now`). When a row is promoted: the manifest is built under the volume's read hold with the row's `manifest_id`, stored, and the row becomes `ready` with `reference_code` set to the manifest's `externalId`; a manifest the builder refuses makes the row `refused`, `not_exportable`; a volume with files being changed is left waiting. With no transport the pass returns `no_transport`, and with a recorded configuration stop it returns `config_error`. Then each `ready` row, and each `failed` row whose `next_attempt_at` has come, is sent, at most 60 in a pass, each taking one call from a budget of 60 calls a minute shared by every request to Fisqua; when the budget is spent the pass returns `rate_limited` (`MAX_SENDS_PER_PASS`, `CALLS_PER_MINUTE`, `fisqua_contract.py`; `CallBudget`, `fisqua_outbox.py`). The pass statuses are `disabled`, `held`, `no_transport`, `config_error`, `rate_limited`, `stopped`, `error`, `off_in_this_mode` and `done`, and the result carries the counts `promoted`, `not_exportable`, `delivered`, `refused`, `failed` and `waiting` (`_Run`); the `disabled` and `held` results carry only `status`, and `hold_file` when held. `off_in_this_mode` means the unit's mode is not `fisqua`: at the start of the pass the result is `{status, mode}` and nothing else, and no call is made; after a switch out of fisqua mode between two sends, or a send the transport refused for the mode, the pass stops with the full result, and the row of the refused send is put back to `ready` with no attempt counted (`_send`). +- **How an answer to the POST is read.** A `2xx` that carries a `volumeId` and names the manifest id sent makes the row `delivered`; any other `2xx` is an error and is retried. `401` and `403` are a configuration stop with reason `token`, `404` with reason `not_found`, and every `3xx` with reason `redirect`; the worker puts the row back to `ready`, not counting the attempt, unless a handover or take-back marked it while it was being sent, in which case it becomes `superseded` or `withdrawn`. `400`, `413` and `422` refuse the manifest for good; a `400` or `413` with no `problems` array is given the local problem `bad-request` or `payload-too-large`. A `409` with a non-empty `problems` array refuses it for good, and a `409` without one is retried. `429`, any `5xx`, any other code, a timeout and a connection error are retried (`read_send_answer`, `fisqua_http.py`; `REFUSED_ALWAYS`, `REFUSED_WITH_PROBLEMS`, `CONFIG_ERROR`, `fisqua_contract.py`; `_send`, `fisqua_outbox.py`). A failed send is tried again after `CAPTUA_FISQUA_RETRY_BASE` seconds (300), doubled for each further failure up to `CAPTUA_FISQUA_RETRY_MAX` (21,600), and a longer `Retry-After` from Fisqua replaces that wait; retries never stop (`retry_delay`). A refusal with `object-missing` problems is logged at `ERR` as `fisqua_object_missing` in the system log, with the stem as subject and each missing key and kind in the detail (`_log_object_missing`). +- **The configuration stop.** When Fisqua refuses the unit's configuration, the unit stops sending and polling. The stop is the file `fisqua-config-error.json` in `CAPTUA_DATA_DIR`, holding `{at, status_code, reason, config_fingerprint}`, so a restart does not clear it (`record_config_error`, `config_error`, `fisqua_outbox.py`). It can also hold `retest_at` and `retest_row`, the time of a version stop's last retest and the row that retest sent (`_note_retest`, `fisqua_outbox.py`), and `rebuild_retest_row` and `rebuild_unsent`, which mark manifests built under a version stop that has been cleared or replaced as still to be built again. The reasons are `token`, `not_found`, `redirect` and `version`. `version` is a `400` whose problems include a rule `version`, `envelope` or `shape`: Fisqua cannot read what this software writes. That manifest is refused for good (`_version_refusal`, `fisqua_outbox.py`; `VERSION_RULES`, `VERSION_REASON`, `fisqua_contract.py`; `fisqua_outbox.py`). While the stop stands, the pass builds and sends one manifest, a retest, at most once every `_retest_interval`, which is `CAPTUA_FISQUA_RETRY_MAX` seconds (six hours by default), counted from when the stop was recorded or last retested (`_retest_version_stop`, `fisqua_outbox.py`). The retest sends again, under its id, the row the last retest sent, when that row is `ready` or `failed`; otherwise it takes the first, lowest id first, that is or can now be built: a `ready` row never attempted, a `waiting_for_upload` row, which is built first, or a volume whose newest manifest was refused for `version`, which is handed over again under a new id. That volume is chosen again under its row lock, and skipped when a handover or a capture was committed in the meantime (`_lock_version_refused`). A `failed` row of an ordinary send is left out (`_retest_candidates`). No retest is sent, and `retest_at` is left as it was, when the row of the last retest failed and its `next_attempt_at` is still to come, when there is nothing to send, when the call budget is spent, or when a shutdown or a switch out of fisqua mode is under way. When Fisqua reads the retest manifest, that is, accepts it or refuses it for a rule other than `version`, `envelope` or `shape`, the stop is removed and the pass goes on as after an update; when Fisqua refuses it for one of those three rules, the stop is recorded again and the next retest is an interval later (`_retest_version_stop`, `fisqua_outbox.py`; `_retest_interval`). The stop is removed when the fingerprint changes: the first 8 hexadecimal digits of a SHA-256 of the environment, the base URL in use, the token, the installed code, which is the backend's commit and the release, or the time the process started when no commit can be read, and the `CAPTUA_FISQUA_ROTATE_DEG` setting, so an update clears any stop (`version`, `token`, `not_found` or `redirect`), and where no commit can be read a restart does; sending then resumes, and a stop whose cause remains is recorded again on the next call (`config_fingerprint`, `fisqua_outbox.py`; `code_identity`, `app/core/version.py`). After a `version` refusal, a `ready` row with no attempt is put back to `waiting_for_upload` under a new `manifest_id`, and once the stop has cleared, each volume whose newest outbox row is a refusal for `version`, and which has no captured record other than open missing ones, is handed over again under a new id, under the same lock and checks as the retest (`_rebuild_unsent`, `_resend_version_refusals`, `_version_refused_volumes`, `_lock_version_refused`, `fisqua_outbox.py`). While any other stop stands, rows are still promoted to `ready` and nothing is sent (`run_fisqua_outbox`, `fisqua_outbox.py`). +- **The status poll.** `FisquaStatusScheduler` polls on its own thread, first after `CAPTUA_OFFSITE_BACKUP_DELAY` seconds and then every `CAPTUA_FISQUA_POLL_INTERVAL` seconds (600). A tick's status poll with nothing to ask makes no call. Every tick then runs `sync_fisqua_queue`, which asks Fisqua for the digitisation queue and, before that, sends the operators PUT when it is due: after a send that failed, after a user is created, changed or deleted through the users routes, and at least once a day (`sync_fisqua_queue`, `app/core/fisqua_queue.py`). The thread also sends the operators PUT when it starts, before its first wait (`FisquaStatusScheduler`, `fisqua_outbox.py`; `_loop`; `tick`). `main.py` starts it with the other schedules and stops it first (`lifespan`, `app/main.py`). Each volume whose newest sent manifest (`delivered`, or `failed` after at least one attempt) is not final is asked for by the reference code the manifest was sent under, `fisqua_outbox.reference_code`, in batches of at most 100 references to `GET /api/capture/v1/volumes/status?refs=,` (`volumes_to_poll`, `fisqua_outbox.py`; `STATUS_PATH`, `MAX_REFS_PER_CALL`, `fisqua_contract.py`; `get_status`, `fisqua_http.py`). Status batches leave 10 calls of the minute's budget for decisions reads, and each tick starts after the last reference asked for, so no batch is starved (`DECISIONS_RESERVED_CALLS`, `fisqua_contract.py`; `fisqua_outbox.py`). Fisqua's states are `received`, `registered`, `preparing_review`, `in_capture_qc`, `retakes_requested`, `approved`, `queued`, `running`, `review_pending`, `published`, `refused`, `superseded`, `failed` and `unknown`. A volume is final, and no longer asked for, when its status for its newest sent manifest is `published`, `refused` or `superseded` and no decisions set it offered is unread; `unknown` is not final (`STATES`, `FINAL_STATES`, `fisqua_contract.py`). An answer is kept in `fisqua_status`. An answer that names the manifest id of a `failed` row, with a state other than `refused`, makes that row `delivered`, so a lost answer to the POST is recovered; a refused one is left to be sent again with the same id (`poll_fisqua_status`, `fisqua_outbox.py`). A `Retry-After` on a status or decisions answer stops polling until it has passed, with status `cooling_down` (`poll_fisqua_status`, `fisqua_outbox.py`). The poll statuses are `disabled`, `held`, `no_transport`, `config_error`, `cooling_down`, `rate_limited`, `error`, `off_in_this_mode` and `done`, and the result carries `asked`, `calls`, `answered`, `changed`, `recovered`, `decisions_fetched`, `decisions_applied` and `decisions_stale` (the `disabled`, `held` and `no_transport` results carry only `status`, and `hold_file` when held) (`poll_fisqua_status`, `fisqua_outbox.py`). `off_in_this_mode` means the unit's mode is not `fisqua`: at the start of the poll the result is `{status, mode}` and nothing else, and no call is made; after a switch out of fisqua mode before a status batch or a decisions read, or a call the transport refused for the mode, the poll stops with the full result (`_fetch_decisions`). +- **The `fisqua` object of `GET /collections/{id}/offsite`.** Its keys are `environment`; `config_error`, `null` or `{at, status_code, reason, config_fingerprint, retest_at}`, with `retest_at` `null` before a version stop's first retest (`config_error`, `fisqua_outbox.py`); `held` and `hold_file`; `outbox`; `status`; and `decisions` (`volume_fisqua_state`, `fisqua_outbox.py`). `outbox` lists the volume's rows newest first, at most 20, each with `manifest_id`, `stem`, `state`, `created_at`, `attempts`, `next_attempt_at`, `last_attempt_at`, `last_error`, `refusal`, `problems`, `response`, `external_id` and `delivered_at`, and without the manifest (`OUTBOX_LISTED`, `_OUTBOX_FIELDS`). `status` is `null` or `{status, status_at, status_checked_at, problems, manifest_id}`, Fisqua's latest word on the volume, with the state as Fisqua gave it. `decisions` is `null` until a set has been seen, and then `{decisions_id, decided_at, applied_at, manifest_id, counts, skipped, rotation_skips, request_skips, reopened, stale}`; `stale` is `true` when the last set offered was for another manifest and was not applied (`decisions_state`, `fisqua_decisions.py`). +- **The `fisqua` object of `GET /system/catalogue-backup`.** `{configured, mode_allows, token_invalid, environment, config_error, held, hold_file, last_send, last_poll}`. `configured` is the configuration's answer and `mode_allows` the unit mode's, `true` only in fisqua mode, so a configured unit in offline or backup mode answers `configured: true, mode_allows: false` and calls Fisqua for nothing (`link_on`, `unit_mode.py`). `environment` and `config_error` are `null` while Fisqua is not configured. `last_send` is the result of the last send pass in this backend process and `last_poll` the result of the last poll, each `null` until the first run (`unit_fisqua_summary`, `fisqua_outbox.py`; `ImageUploadScheduler.last_fisqua_result`, `image_upload.py`). +- **Applying Fisqua's QC decisions.** When a status entry carries a `decisionsId` that is neither the set last applied nor one already seen to be stale, the poll reads `GET /api/capture/v1/volumes//decisions`, with the reference quoted into the path, taking one call from the budget, and applies the set (`_fetch_decisions`, `fisqua_outbox.py`; `DECISIONS_PATH`, `fisqua_contract.py`; `get_decisions`, `fisqua_http.py`). A volume stays polled while an offered set is unread, even in a final state (`volumes_to_poll`, `fisqua_outbox.py`). `apply_decisions` returns a status: `invalid` (no `decisionsId` or no `records` list), `already_applied`, `pending_handover`, `stale`, `applied` or `error`, which is rolled back (`apply_decisions`, `fisqua_decisions.py`). + - A set is applied only when its `manifestId` is the volume's current handover, the newest `delivered` row. A set for another manifest is stale: it is noted, not applied, and logged in the activity log as `fisqua_decisions_stale`. A set is held back as `pending_handover`, unapplied and not stale, while a later row of the volume is `waiting_for_upload`, `ready`, `sending` or `failed`, checked again after the records are locked (`fisqua_decisions.py`; `PENDING`). + - Records are locked in id order and each is handled in the one transaction. When the set carries `requests`, every record of the volume is locked in id order and then the volume's row, and a decided record outside the volume is skipped without being locked. A set without `requests` that carries a `missing_page` decision takes the volume's row `FOR UPDATE` after the records and before any status change (`apply_decisions`, `fisqua_decisions.py`). A record is skipped, with nothing changed, and listed in `skipped` as `{captua_record_id, reason}`, for one of these reasons: `not_in_volume`; `invalid_decision` (not `approved`, `rejected`, `excluded` or `missing_page`, or an exclusion that carries rotations); `invalid_side` (a `missing_page` whose `side` is not `left` or `right`); `invalid_reason` (a rejection whose reason is not one of the nine, or an exclusion with any reason); `note_too_long` (a note over 2,000 characters on a rejection, an exclusion or a `missing_page`); `other_without_note`; `captured` (an open missing record stays captured on the unit when its volume is promoted, so a decision for it is skipped here); `images_changed` (the record's current images are not exactly the images the delivered manifest listed for it, compared as capture id, role and object key, so a record retaken since, or one whose pair lost, gained or swapped an image, is not touched); `missing_page_single_record` (a `missing_page` for a record captured in single mode); and `transition_refused` (`_why_not`, `apply_decisions`, `fisqua_decisions.py`; `missing_page_refusal`, `app/api/records.py`). + - `approved` moves a record from `in_review` to `approved`, from `rejected` through `in_review`, and leaves an `approved` record as it is. `rejected` moves a record from `in_review` to `rejected` with a rejection row, the reason, the note stripped as the comment and `rejected_by` `Fisqua: ` (`Fisqua` alone when none is given), written by the same function as `POST /records/{id}/reject`; a record already `approved` or `rejected` goes through `in_review` first, and a record already rejected with the same reason, note and reviewer is left as it is. The moves to `approved` and `in_review` go through `_apply_status_change` as a reviewer named `Fisqua: `, and the rejection through `reject_locked_record`, so every history row names Fisqua (`_apply_one`, `_actor`, `fisqua_decisions.py`; `reject_locked_record`, `app/api/records.py`). + - `missing_page` (contract 1.9, section 10.4), with `side` `left` or `right`, is applied by the same function as `POST /records/{id}/missing-page` (Openings and pages never captured, below), and that page is marked missing on the record: a current image of that side is superseded, a record in review or approved is returned to `captured` under the reviewer `Fisqua: `, and the decision's note, stripped, is kept as `missing_note`. A record already missing that side, or both, is counted as `unchanged`. A closed record that the decision reopens is listed in the report's `reopened` as `{recordId, reason, note}`, the closing it had, and written to the activity log as `missing_record_reopened` under that reviewer (`fisqua_decisions.py`; `_record_reopened`). + - `requests` (contract 1.9, section 10.4), a list beside `records`, is applied after the decisions in the same transaction. For each request of kind `missing_opening`, placeholders are made after its `afterRecordId`, whatever that record's status, `excluded` included: `count` of them, or one when `count` is null, each carrying the request's `expected` and `note`, stripped, and its `requestId`, with `created_by` `Fisqua: `. The sequences of the records after them are raised, as for `POST /collections/{id}/records/missing-opening`. Each applied request is written to the activity log as `missing_openings_marked`, with `requestedBy` and `requestedAt` in the detail (`_apply_request`). A request is skipped, and listed in `request_skips` as `{request_id, reason}`, for one of these reasons: `invalid_request` (not an object); `invalid_request_id` (missing, blank, or over 64 characters); `invalid_kind` (not `missing_opening`); `not_in_volume` (`afterRecordId` is not a record of the volume); `invalid_count` (not an integer from 1 to 50); `text_too_long` (`expected` or `note` over 2,000 characters); and `already_applied` (a record on the unit already carries the `requestId`) (`_request_why_not`). + - When the set marked a page missing or made a placeholder, the volume is handed over again in the same transaction under the rule given under Openings and pages never captured, below. + - Rotations: each current image of a record decided `approved` or `rejected` takes `rotation_correction_quarter_turns` from the set's `rotations`, matched by `captureId` and `role` (`single`, `left` or `right`), with `quarterTurns` 1, 2 or 3; an image the set lists none for is set to `null`. A rotation that cannot be used is skipped alone and listed in `rotation_skips` as `{captua_record_id, reason}` with `invalid_quarter_turns`, `invalid_role` or `no_such_image`. No file is changed. A `missing_page` or `excluded` decision changes no rotation (`_apply_rotations`, `fisqua_decisions.py`; `ROTATION_ROLES`, `QUARTER_TURNS`, `fisqua_contract.py`). + - The report is kept on `fisqua_status`: `counts` has `approved`, `rejected`, `excluded`, `unchanged`, `skipped`, `rotations`, `rotations_skipped`, `missing_pages`, `placeholders`, `requests_skipped` and `reopened`, beside the lists `skipped`, `rotation_skips`, `request_skips` and `reopened` (`_empty_report`, `fisqua_decisions.py`; `decisions_state`). It is recorded in the activity log as `fisqua_decisions_applied`, at `INFO`, with the stem as subject and the detail `volume decisions= approved= rejected= excluded= unchanged= skipped= rotations= rotations_skipped= missing_pages= placeholders= requests_skipped= reopened=`. +- **Version reporting.** The release is `APP_VERSION` when set, else the first line of the superproject's `VERSION` file, found at `../VERSION` from the backend's working directory, else `unknown` (`release_version`, `app/core/version.py`). `systemVersion`, in the capture manifest's `generatedBy`, is the release alone when the superproject's HEAD is the commit the tag named for the release points to, annotated tags peeled; otherwise it is `+g`; and the release alone when no commit can be read. A tag known only from inside a pack file counts as absent (`system_version`; the reading of git files). The same value is `software.version` in a project's capture manifest (`generate_manifest_project`, `capture/manifestHandler.py`). The setting `app_version` (`APP_VERSION`) now defaults to unset; it used to default to `0.0.0-dev` (`Settings`, `config.py`). +- **Lines in the journal.** The backend's workers write one line to stderr for each run that did something, at `INFO` or `WARNING` as each worker's rule below says (the handler is the one in Logging, section 8). The image upload: `Image upload run : uploaded= already_present= unverified= refused= conflicts= skipped=`, at `INFO` only when the status is `done`, `stopped` or `held` and nothing was refused, and at `WARNING` otherwise (`image_upload.py`). The send pass, when it promoted, built an unexportable manifest, delivered, was refused or failed anything: `Fisqua outbox pass : promoted= not_exportable= delivered= refused= failed= waiting=`, at `INFO` only when the status is `done`, `stopped` or `rate_limited` and nothing was refused or failed (`_log_pass`, `fisqua_outbox.py`). The poll, when it made a call: `Fisqua status poll : asked= calls= answered= changed= recovered= decisions_fetched= decisions_applied= decisions_stale=`, at `INFO` for `done` and `rate_limited`, and at `WARNING` for any other status. A decisions set applied: `Fisqua decisions applied to volume : approved= rejected= excluded= unchanged= skipped= rotations= rotations_skipped= missing_pages= placeholders= requests_skipped= reopened=`, at `INFO` (`apply_decisions`, `fisqua_decisions.py`). No line carries the token. + +**The unit's mode — `GET /system/unit` and `PUT /system/unit`.** A unit runs in one of three modes, which an admin sets, and keeps a projects setting beside it (NEH-311, NEH-313). Both are stored in `unit_settings`, a table of one row (`id` 1, `check_unit_settings_single_row`) added by migration `d7f9a1c3e5b2`, which only `app/core/unit_mode.py` reads and writes (`app/models/unit_settings.py`; `upgrade`, `alembic/versions/d7f9a1c3e5b2_add_unit_settings.py`). Changing the mode changes no stored data. + +- **The three modes** (`MODES`, `unit_mode.py`; `check_unit_settings_mode`, `app/models/unit_settings.py`). + - `offline`, shown in the interface as Scanner only: nothing leaves the unit, and every volume created in it is kept on the unit (Volumes kept on the unit, below). The image upload and the catalogue dump each return `{status: "off_in_this_mode", mode}` and list, upload and dump nothing; the dump's sweep of stale local dumps still runs first (`image_upload.py`; `catalogue_backup.py`). A free is refused (Freeing a volume, above), and so is the `mark-freed` command, with a `ValueError` (`mark_freed`, `offsite_free.py`). The free dry run, restore and the adopt commands, which only read from the bucket, have no mode check (`plan_free`, `offsite_free.py`; `_prepare_restore`). In `image_upload.py` the mode is checked in `run_image_upload`, and reported by `unit_upload_summary` as `mode_allows`. + - `backup`: the image upload and the dump run as configured. No call is made to Fisqua. + - `fisqua`: the same, and the link to Fisqua: the send pass, the status poll with its QC decisions, the queue sync, the operators PUT and the description search, `GET /fisqua/descriptions` (`link_on`, `unit_mode.py`; `search_descriptions`). Outside fisqua mode each of these returns `{status: "off_in_this_mode", mode}` and makes no call (`run_fisqua_outbox`, `fisqua_outbox.py`; `poll_fisqua_status`; `_gate`, `fisqua_queue.py`). In fisqua mode volumes come from Fisqua's queue, and operators are restricted (Fisqua mode and volumes, below). +- **When the mode is read.** Each run reads it at its start, after its own configuration checks (`disabled`, `misconfigured`) and before the upload hold, so an offline unit with the hold file in place reports `off_in_this_mode`, not `held`. A run reads it again between objects (image upload), between sends (send pass), and before each batch and each decisions read (status poll), and stops with status `off_in_this_mode` after a switch (`image_upload.py`; `fisqua_outbox.py`). `HttpFisquaTransport` also checks every request to Fisqua against the stored mode: it reads the mode just before sending and, unless the mode is `fisqua`, sends nothing and returns the outcome `off_in_this_mode`. A mode that cannot be read counts as not `fisqua` (`_mode_refusal`, `app/core/fisqua_http.py`; `stored_mode_now`, `unit_mode.py`). The operators PUTs that a change of mode sends are the only requests that skip this check (`get_transport`, `unit_mode.py`; `fisqua_queue.py`). The reference-code lookup and the description search do not skip it (`get_lookup_transport`, `unit_mode.py`; `search_descriptions`, `fisqua_http.py`). +- **What a switch leaves unchanged.** Outbox rows, statuses and records stay as they are. The backend queues the manifest of every handover, whatever the mode and the configuration, because `enqueue_handover` reads neither, and sends the row once the unit is in fisqua mode with Fisqua configured (`fisqua_outbox.py`; `tests/unit/test_unit_mode.py`). Volumes kept on the unit stay kept across a switch unless the admin includes them (below). The upload hold applies in every mode. +- **The starting mode.** At start-up, before the schedules, the backend writes the row when there is none: `fisqua` when Fisqua is configured (environment, token and a valid tenant), else `backup` when the offsite upload is configured (remote and a valid tenant), else `offline`, with projects off. It logs `unit_mode_initialised` in the system log, with the mode and the reason in the detail (`initialise`, `unit_mode.py`; `inferred`; `_new_row`; `app/main.py`). The catalogue dump plays no part in this choice. A stored row is not rewritten at later starts, whatever the configuration says then (`initialise`, `unit_mode.py`). Until the row exists, the backend answers with the inferred mode and projects off, and writes nothing (`current`, `unit_mode.py`). +- **Projects.** `projectsEnabled` is the admin's setting, stored in any mode. Projects are shown only when the mode is `offline` and the setting is on (`projects_shown`, `unit_mode.py`). While they are hidden, the backend puts every new top-level volume into the unit's default project: + - `POST /collections/` ignores any `project_id` given and puts a volume without `parent_collection_id` into the default project; a volume with a parent is created under its parent, as before. While projects are shown, a request with neither is refused with `400`, as before (`create_collection`, `collections.py`). + - on `POST /imports/digitisation-list`, the import puts the list's volumes into the default project (Importing a digitisation list, below). + - the Fisqua queue sync, which runs only in fisqua mode, creates its new volumes there (`fisqua_queue.py`). +- **The default project.** The stored `defaultProjectId` when that project still exists; else the unit's only project, when there is exactly one; else the project whose name matches `default` as `_name_key` compares names (stripped, NFC, case-folded), the oldest when several match, and a project named `default` is created when none matches, with no admin needed (`list_import.py`). The choice is stored and logged `default_project_set` in the system log, with the detail `project ()` and the project's name as subject (`default_project`, `unit_mode.py`). On `POST /collections/`, choosing it can be refused: `503` when the project lock cannot be taken, and `409` with `{message}` when `default` would be the directory of a volume's stem (`create_collection`, `collections.py`). Nothing moves an existing volume (`tests/unit/test_unit_mode.py`). When the default project is deleted its id is set to null (`ON DELETE SET NULL`, migration `d7f9a1c3e5b2`), and a project is chosen again by the rule above at the next need. +- **`GET /system/unit`.** Admins, operators and reviewers may read it (`allow_read_only`, `app/api/system.py`). The response is `{mode, projectsEnabled, projectsShown, defaultProjectId, prerequisites, keptVolumes}` (`as_api`, `unit_mode.py`). `defaultProjectId` is `null` until a default project is first chosen. `keptVolumes` lists every volume Captua keeps on the unit as `{id, name, files}`, in id order, `files` being the number of files Captua would copy offsite (`kept_volumes`, `app/core/kept_volumes.py`). `prerequisites` is `{backup: [...], fisqua: [...]}`, the codes of what the configuration lacks for each mode, read from the configuration alone, with no call to Fisqua (`prerequisites`, `unit_mode.py`): + - `offsite_not_configured`: no offsite remote, or no valid tenant (`is_enabled`, `image_upload.py`); + - `catalogue_dump_not_configured`: the catalogue dump is not configured, or `CAPTUA_OFFSITE_DUMP_RECIPIENT` is missing or invalid (`unit_mode.py`); + - `fisqua_not_configured`, under `fisqua` only: the link to Fisqua is not configured (environment, token and tenant). + + `fisqua` lists `backup`'s codes as well. An empty list means a switch to that mode can be tried. A switch to `fisqua` also needs the upload hold file to be absent (`change`, `unit_mode.py`) and Fisqua to accept the operators PUT. +- **`PUT /system/unit`.** Admin only (`allow_admin`, `system.py`). The body is `{mode, projectsEnabled, keptVolumes}`; all three are optional, and a missing or `null` `mode` leaves the mode as it is (`UnitUpdate`, `system.py`; `unit_mode.py`). `mode` is `offline`, `backup` or `fisqua`, `projectsEnabled` a boolean, and `keptVolumes` `include` or `keep`: the admin's decision for the kept volumes when the unit leaves offline mode. `keptVolumes` is used only on a switch out of offline mode while a volume is kept; on any other request it is ignored. Any other key, or any other mode, is refused with FastAPI's validation `422` (`extra="forbid"`, `system.py`; `tests/unit/test_unit_mode.py`). The response is the `GET /system/unit` body. A change of mode is checked in this order (`change`, `unit_mode.py`): + - a switch to `backup` or `fisqua` with missing prerequisites is refused, with one problem for each missing one. A switch to `offline` needs nothing. A switch out of `offline` while any volume is kept on the unit, without `keptVolumes`, adds the problem `kept_volumes_decision` to the same refusal, before any call to Fisqua; + - a switch to `fisqua` while the upload hold file exists is refused with `offsite_held`, and nothing is sent; + - a switch to `fisqua` sends Fisqua the operators PUT with `mode: "fisqua"`, and is refused with `fisqua_unreachable` when Fisqua does not accept it; + - a switch down from `fisqua` sends the operators PUT once, with the new mode, best effort: a failure does not stop the switch, and `unit_mode_changed` is then logged at `WARN` with `; Fisqua not told: ` in its detail. A change between `offline` and `backup` sends nothing (`tests/unit/test_unit_mode.py`); + - when another change was committed after this request first read the row, the request is refused with `mode_changed` and stores nothing. The check compares both the mode and `projects_enabled`, so a request that changes only `projectsEnabled` can be refused this way too (`change`, `unit_mode.py`). The check for kept volumes is made again here, under the row lock, and refused with `kept_volumes_decision` when a kept volume was created in the meantime. Then `include` releases every kept volume in the same transaction, logged `kept_volumes_released` with their count and ids, and `keep` leaves them kept, logged `kept_volumes_kept` with their count (`_decide_kept`, `unit_mode.py`). When this request told Fisqua a mode, on a switch to `fisqua` or on a down-switch whose PUT succeeded, and the stored mode differs from it, the backend sends the stored mode at once and logs `unit_mode_resent` (`_resend_stored`). The backend does the same when the commit fails, and the error is then raised. + + A refusal is `409` with `detail` `{message, problems}`, and nothing is stored, `projectsEnabled` included (`ModeRefused.detail`, `unit_mode.py`; `system.py`; `tests/unit/test_unit_mode.py`). `message` is `"The unit cannot switch to mode."`. Each problem is `{code, message}`, the messages fixed in `PREREQUISITE_MESSAGES` (`PREREQUISITE_MESSAGES`, `unit_mode.py`), and a `fisqua_unreachable` problem also carries `error`, which begins with the outcome (`not_configured`, `held`, `config_error`, `rate_limited`, `unsupported`, `refused` or `error`) and never holds the token (`send_operators_with_mode`, `fisqua_queue.py`; `tests/unit/test_unit_mode.py`). The codes are `offsite_not_configured`, `catalogue_dump_not_configured`, `fisqua_not_configured`, `offsite_held`, `fisqua_unreachable`, `mode_changed` and `kept_volumes_decision`. The message of `kept_volumes_decision` is `"Captua keeps volumes made in Scanner only mode on this unit. Say whether the switch includes them (keptVolumes: include) or Captua keeps them on the unit (keptVolumes: keep)."` (`KEPT_VOLUMES_DECISION_MESSAGE`, `kept_volumes.py`). Each change is logged in the system log, category `system`: `unit_mode_changed` with the detail ` -> `, and `unit_projects_changed` with `projects_enabled -> ` (`change`, `unit_mode.py`). +- **Fisqua mode and volumes.** In fisqua mode volumes come from Fisqua's queue. + - An operator is refused with `403` and `detail` `{code: "volumes_from_fisqua", message}`, the message `"In Fisqua mode, volumes come from Fisqua's queue. Only an admin can create a volume, change its file name stem or reference code, or import a list."` (`VOLUMES_FROM_FISQUA_MESSAGE`, `unit_mode.py`). The refusal is made on `POST /collections/` after FastAPI's validation of the body and the role check, and before any other check in the route body (`collections.py`); on `PATCH /collections/{id}` that sets `filename_stem` or `external_id` to a value other than the stored one, clearing included; and on `POST /imports/digitisation-list`, before the file is read (`import_digitisation_list`, `imports.py`). A `PATCH` of other fields, or one that repeats the stored stem, is accepted (`tests/unit/test_unit_mode.py`). + - An admin's new volume, top-level or nested, and an admin's change of stem or `external_id`, are saved only after Fisqua has confirmed each new code, with one `GET /api/capture/v1/descriptions/{code}` (contract 1.8) for each distinct value: the stem and any `external_id` of a new volume, the changed values of a `PATCH` (`create_collection`, `update_collection`, `collections.py`; `check_reference_codes`, `unit_mode.py`; `DESCRIPTIONS_PATH`, `app/core/fisqua_contract.py`). A volume kept on the unit is not checked; its codes are checked when an admin releases it (`POST /collections/{id}/release-from-unit`). They are logged `volume_created_override` and `volume_code_override`, at `INFO` in category `activity`, with the stem and `external_id` in the detail; for a kept volume the detail ends `; kept on the unit, not checked with Fisqua` (`collections.py`; `tests/unit/test_unit_mode.py`). + - An admin's `PATCH` that clears the stem is refused with `422` and `{code: "stem_required", message}`, the message `"In Fisqua mode a volume's file name stem is its Fisqua reference code, so it cannot be empty."` (`collections.py`; `STEM_REQUIRED_MESSAGE`, `unit_mode.py`). Outside fisqua mode the rules under A volume's identity, above, apply. + - An admin may import a list, with no lookup; the import is logged `list_import_override` with the list id and the reference code and id of each volume created, and the detail ends `; kept on the unit` when the list's volumes were kept (`import_digitisation_list`, `imports.py`; `tests/unit/test_unit_mode.py`). + - **The lookup's refusals.** Each `detail` is `{code, message, referenceCode}`, with `error` on the `409`s, and nothing is saved (`CodeRefused.detail`, `unit_mode.py`; `check_reference_code`): + - `422` `unknown_reference_code`, `"Fisqua has no description with the reference code in this workspace."`: Fisqua answered `404` with the rule `unknown-reference-code`, or a `2xx` whose `referenceCode` is not exactly the code asked for (`read_description_answer`, `fisqua_http.py`; `unit_mode.py`); + - `409` `fisqua_no_lookup`, `"This Fisqua cannot check reference codes (contract 1.8). A list file exported from Fisqua can be imported instead."`: any other `404`, or a `405`, with `error` `unsupported: HTTP ` (`read_description_answer`, `fisqua_http.py`; `check_reference_code`, `unit_mode.py`); + - `409` `fisqua_unreachable`, `"Fisqua could not be reached to check the reference code . A list file exported from Fisqua can be imported instead."`: the request was not sent, or Fisqua's answer could not be used. `error` names the cause (`unit_mode.py`): `not_configured`, Fisqua is not configured; `held`, the upload hold file exists; `config_error: ...`, the link's configuration stop is in place; `cooling_down`, the link is waiting out a `Retry-After`; `rate_limited`, the call budget is spent; `off_in_this_mode: ...`, the unit was switched out of fisqua mode before the request was sent, so the transport sent nothing (`_mode_refusal`, `fisqua_http.py`); `unreadable: ...`, a `2xx` object with no string `referenceCode` (a `2xx` that is not an object gives `error: ...`, `fisqua_http.py`); `error: ...`, a network error or timeout, or an answer such as `429`, which gives `error: Fisqua answered HTTP 429` (`_transient`, `fisqua_http.py`); `config_error: ...` also follows a `401`, `403` or redirect, which the backend records as the link's configuration stop. A `Retry-After` on the answer puts the link into its cooldown, as on the link's other calls. + +**Volumes kept on the unit — `collections.kept_on_unit`, `POST /collections/{id}/keep-on-unit` and `POST /collections/{id}/release-from-unit`.** Captua can keep a volume on the unit: none of its images is copied offsite and none of its capture manifests is sent to Fisqua until an admin releases it (`app/core/kept_volumes.py`). Offline mode is a mode in its own right, for an institution whose material stays on the unit, so every volume created in it is kept. + +- **How a volume comes to be kept.** A volume created in offline mode, by `POST /collections/` or by the list import, is kept whatever the request sends. In backup and fisqua mode an admin may ask for it with `kept_on_unit: true` on either path; anyone else is refused with `403` `kept_on_unit_admin_only` (`kept_on_create`). A volume created under a kept parent is kept. An admin keeps an existing volume, and every volume inside it, with `POST /collections/{id}/keep-on-unit` (`keep`). +- **The rule for nesting.** A volume inside a kept volume is kept. A kept volume inside one that is not kept is allowed, so an admin can keep one sub-volume as a test. A re-parent that would put a volume that is not kept under a kept one is refused with `409` `kept_on_unit_move` (`refuse_kept_reparent`). +- **While a volume is kept.** The image upload leaves it out, and a run reads the flag again for each object, so a keep committed during a run is caught (`pending_work`, `_read_object`, `image_upload.py`). A handover still queues its `waiting_for_upload` row, and the row waits, neither superseded nor refused (`_promote`, `fisqua_outbox.py`). The volume counts as pending nowhere: on `GET /collections/{id}/offsite` its `pending` is `0`, and the unit summary counts it only in `kept_volumes` and `kept_files` (`volume_upload_state`, `unit_upload_summary`). A free and its dry run are refused with `409` `kept_on_unit`, and so is the `mark-freed` command (`_require_received`, `mark_freed`, `offsite_free.py`). Records cannot be moved between a kept volume and one that is not kept (A record with a file in the bucket stays in its volume, above). The catalogue dump is a `pg_dumpall` of the whole database and cannot leave one volume out, so in backup and fisqua mode a kept volume's records go offsite with the dump; its images stay on the unit. +- **`POST /collections/{id}/keep-on-unit`.** Admin only (`allow_admin`). The response is the volume's offsite state, as `GET /collections/{id}/offsite` gives it. Logged as one `volume_kept_on_unit` entry for the volume, naming how many volumes were kept with it. Refused as a whole, with nothing changed, with `409` and `{code, message}`: `already_kept_on_unit`, when the volume is already kept; `already_left_unit`, when a file of the volume, or of a volume inside it, has been uploaded or verified offsite, or a manifest has been sent or is being sent (`"Part of this volume, or of a volume inside it, has already left the unit: a file was copied offsite, or a manifest was sent or is being sent to Fisqua. Captua can no longer keep it on the unit."`); and `kept_volumes_changed`, when the volumes inside it changed while Captua read them, after three attempts. A volume that does not exist is `404` (`keep_collection_on_unit`, `collections.py`; `keep`, `kept_volumes.py`). +- **`POST /collections/{id}/release-from-unit`.** Admin only, in any mode. It releases the volume and every kept volume inside it; from then on their images are copied offsite and, in fisqua mode, their manifests are sent. The response is the volume's offsite state. Logged as one `volume_released_from_unit` entry, naming how many were released with it. Refused with `409` and `{code, message}`: `not_kept_on_unit`, when the volume is not kept; `kept_parent`, when the volume that holds it is kept; `kept_volumes_changed`, as above; and `mode_changed`, when the mode kept changing while Captua read it. In fisqua mode the stem and `external_id` of each volume it releases are first checked with Fisqua, as on `POST /collections/`, and a refusal from that check is returned with Fisqua's status and detail, every volume still kept. Offline and backup mode make no call. A volume that does not exist is `404` (`release_collection_from_unit`, `collections.py`; `release`, `kept_volumes.py`). +- **Leaving offline mode.** A switch out of offline mode while any volume is kept needs the admin's decision, `keptVolumes: include` or `keep`, on `PUT /system/unit` (The unit's mode, above). `include` releases every kept volume with the switch; `keep` leaves them kept. Released volumes are not checked with Fisqua on this path. + +**Importing a digitisation list — `POST /imports/digitisation-list`.** The route reads artefact 1 of exchange contract 1.1 and creates one volume per item; the route is in `app/api/imports.py` and the import in `app/core/list_import.py`. The request is a multipart upload with the field `file`, carrying the list file unchanged, and an optional boolean field `kept_on_unit`, which asks Captua to keep the list's volumes on the unit (`import_digitisation_list`, `imports.py`). In offline mode every volume is kept, whatever is sent. In backup and fisqua mode an admin may ask for it; in backup mode an operator who sends `true` is refused with `403` and `detail` `{code: "kept_on_unit_admin_only", message}` before the list's lock is taken, with nothing written (`kept_on_create`, `app/core/kept_volumes.py`). Admins and operators may import; in fisqua mode only admins may (The unit's mode, above). Creating a project is admin-only, as on `POST /projects/`, so while projects are shown a list whose project does not exist yet is refused to an operator with `403` before anything is written. While projects are hidden the import puts the volumes into the unit's default project, and this refusal is not made (`import_list`, `list_import.py`). + +- **Refused whole, with no volume or report written.** A file over 10 MiB (10,485,760 bytes) is refused with `413` (`_read_capped`, `imports.py`). A file that is not strict UTF-8 JSON (not UTF-8, not JSON, `NaN` or `Infinity`, a key repeated within one object, nesting too deep, a number too large to read) is refused with `400` (`parse_list_file`, `list_import.py`). So is a file in which any key or string holds an escaped lone surrogate, such as `\ud800`; an escaped surrogate pair is one character and is accepted (`_holds_lone_surrogate`). An envelope this unit does not read is refused with the application's `422`: a top-level value that is not a JSON object (`check_envelope`, `list_import.py`), a `contract` other than `fisqua-captua-exchange`, a `kind` other than `digitisation-list`, a `version` whose major is not `1`, an `id` that is not a UUID, a missing or blank `list.name`, one containing NUL, or one longer than 255 characters once stripped and in NFC, or `items` that are not a list (`check_envelope`, `list_import.py`). Unknown fields are ignored. A list id imported before from a file with a different SHA-256, or whose earlier hash cannot be read, is refused with `409`; a first import whose hash cannot be recorded, with `503` (`_check_hash`, `list_import.py`). A list that would create a project is also refused with `503` when the lock an import takes to look for and create its project when none exists, `/imports/.project-create.lock`, cannot be taken; the detail is `"Captua could not take the lock that keeps two imports from creating the same project, so it did not import the list. Try again."`, and no project or volume is written. A list whose project exists is imported without that lock (`_project_for`, `list_import.py`). Each body of the refusals in this bullet is `{detail}` with a string. +- **The project refusals and the list's hash.** While projects are shown, an operator's list whose name matches no project is refused with `403` before the list's lock is taken, so no lock file is made (`import_list`, `list_import.py`). Inside the list lock's block, whether or not the lock file could be made, and before the list's hash is written, `_refuse_list_before_hash` makes the same check again, for an import that raced with a project's deletion or rename, and refuses an admin's list with `422` when the project it would create would have a volume's stem as its directory name (`list_import.py`). A refused file therefore leaves no hash, and a corrected file can be imported under the same list id. If `_project_for` fails after the hash was written, for any reason (a refusal, the project deleted between the check and its use, the project lock not taken, or a database error), the hash is removed when this run wrote it and holds the lock (`import_list`, `list_import.py`). Without the lock the hash is kept and a WARNING names its path; a corrected file under that id is then refused with `409` until the hash file is removed by hand. A hash that an earlier import recorded is never removed (`import_list`, `_check_hash`; `_remove_hash_file` logs a removal that fails). +- **The project.** While projects are hidden, the volumes are created in the unit's default project, whoever imports; `list.notes` is not stored on it, `projectNotesSkipped` is `"default_project"`, and `projectCreated` says whether this import created the default project (`list_import.py`; The unit's mode, above). The operator's `403` and `_refuse_list_before_hash` are then skipped, but choosing the default project can still refuse the list after its hash is written: with the application's `422` when `default` would be the directory of a volume's stem (`ListRefused`, `list_import.py`; `imports.py`), and with `503` when the project lock cannot be taken (`ProjectLockUnavailable`, `list_import.py`; `imports.py`). The hash is then removed as the bullet above describes (`import_list`, `list_import.py`). While projects are shown, the volumes are created directly under the project whose name matches `list.name`, compared stripped, in NFC and case-folded, with accents kept (`_name_key`, `list_import.py`; `_find_project`); if several match, the oldest. If none matches, a project is created, and `list.notes` becomes its description when it is a non-blank string of at most 10,000 characters with no NUL (`notes_skip_reason`, `list_import.py`). An existing project's description is never changed (`_project_for`, `list_import.py`). +- **The mapping.** `referenceCode` to `external_id`, `filenameStem` to `filename_stem`, `title` to `name`, `dates.display` to `date`, `dates.start` to `date_start`, `dates.end` to `date_end`, `sequence` to `sequence`. Every other item field, `containerPath` included, is stored in `custom_attributes` as a JSON string under a `fisqua` key, and `dates` subfields other than those three under `fisqua.dates` (`_check_item`, `list_import.py`). No records are created. +- **Items are skip-and-report.** Each item is checked, then created and committed on its own, so no item is rolled back because another was rejected. The first failing check gives the reason, in this order: the item is not an object; the reference code is missing, not a string of at most 255 characters with no NUL, padded with whitespace, or repeated earlier in the list; the stem is missing, not a slug, longer than 27 characters, not equal to the reference code, or repeated earlier in the list; the title is missing or invalid; the dates are invalid or end before they start; the sequence is not a 32-bit integer; a volume on the unit already has the reference code, or the stem (`_check_item`, `list_import.py`; the last two in `create_volume`). At the insert, before the two duplicate lookups, an item is rejected as `mode_changed` when the unit's mode, read again in the insert's transaction, is no longer the one the import started under (`create_volume`, `list_import.py`). The volumes are created with `kept_on_unit` as the import decided it. A constraint violation at the insert or the commit is mapped by constraint name to the same reasons, or else to `refused_by_database`. The stem directory check at the insert gives two more: `filename_stem_is_project_directory` when the stem is a project's directory name, and `filename_stem_directory_occupied` when `//` already holds files (`list_import.py`), and the stem check against offsite keys a third, `filename_stem_held_offsite`. Any other database failure on an item, in the two duplicate lookups, the insert or the commit, rejects that item as `refused_by_database`, and the import and its report go on. The reason codes and their messages are `REASONS`, and the constraint names are mapped to codes in `_CONSTRAINT_REASONS` (`list_import.py`). The reference code is never stripped. The import refuses a mismatched item before the database, as `filename_stem_differs_from_reference_code`; `POST /collections/` and `PATCH /collections/{id}` refuse the same pair at the flush with `409` (above, A volume's reference code is its stem). +- **The report.** The response is `200` with the report: `listId`, `listName`, `projectId`, `projectName`, `projectCreated`, `projectNotesStored`, `projectNotesSkipped`, `importedAt`, `importedBy`, the counts `created` and `skipped`, `volumes` (each created volume's `position`, `referenceCode`, `filenameStem` and `captuaCollectionId`), `rejects` (each rejected item's `position`, `referenceCode` cut to 120 characters, `referenceCodeTruncated`, `reason` and `message`), `fileSha256`, `listStored`, `reportStored` and `keptOnUnit`, whether the list's volumes were kept on the unit (`import_list`, `list_import.py`). The report is also written, without `reportStored`, to `/imports//import-report__run.json`, one numbered file per run, none overwritten (`store_report`, `list_import.py`). If that write fails, `reportStored` is `false` and the volumes stay created. `listStored` is `true` when the uploaded file was kept, byte for byte, as `/imports//list.json`, and `false` when it could not be written; the volumes stay created either way, and `listStored` is stored with the report (`import_list`, `list_import.py`; `store_list_file`). `GET /imports/digitisation-lists` reads a list's items from that file (below). The client's `ImportReport` declares the field, and the queue page shows a warning when it is `false` (`frontend/src/lib/api.ts`; `frontend/src/routes/(dashboard)/dashboard/queue/+page.svelte`). The list's hash is kept beside the runs in a file named `sha256`. `GET /imports/digitisation-list/{list_id}/report` (admin, operator or reviewer) returns the highest-numbered run that parses as the list's report, as an attachment named `import-report_.json`; an id that is not a UUID is refused with `422`, and a list with no readable report with `404` (`imports.py`). Each completed import is recorded in the activity log as `digitisation_list_imported`, at `WARN` when the report could not be stored; a refused import is not logged (`import_digitisation_list`, `imports.py`). +- **Re-importing.** The same file can be imported again. Every item already on the unit is rejected as `reference_code_on_unit` (or `filename_stem_on_unit`), any other item is checked and created as on the first run, and the report is stored as the next run. A different file under the same list id is refused with `409`. Imports of one list id are serialised by an exclusive lock on `/imports//.lock` (`import_list`, `list_import.py`; `_list_lock`); if the lock file cannot be created, the import runs unlocked and the failure is logged. A re-import finds its project by name (`_find_project`), so while projects are shown, after the project has been renamed an operator's re-import is refused with `403`, and an admin's creates a new project. While projects are hidden, a re-import goes into the default project whoever imports. +- **Imported lists — `GET /imports/digitisation-lists`.** Admins, operators and reviewers may read the lists (`allow_read_only`, `imports.py`). The route takes no query parameters and writes nothing. The response is `200` with an array of every list imported on the unit, newest `importedAt` first, followed, in order of id, by the lists with no readable report (`list_digitisation_lists`, `imports.py`; `stored_lists`, `list_import.py`). A list is a directory under `/imports/` named by a UUID that holds a readable report, a `list.json` readable as that list, or both; a directory with neither is left out, and when the `imports/` directory cannot be read the response is `[]`. The digitisation queue synced with Fisqua is one of the lists. + - Each list has `listId`; `source`, `queue` for the digitisation queue and `file` for an imported file; `listName`, `projectId` and `importedAt`, from the latest report, or, without one, `listName` from the file and the other two `null`; `listFileMissing`, `true` when `list.json` is missing, cannot be read, or is another list's file; and `items`, which is `[]` when `listFileMissing` is `true`. + - The items are in list order: by `sequence`, items without an integer `sequence` after those with one, then by position in the file. An item that is not a JSON object is left out. Each item has `position`, counted from 1 in the file; `sequence`; `referenceCode`, `filenameStem`, `title`, `notes`, `action`, `assignee` and `itemId`, each the file's string or `null`; `withdrawn`, `true` only when the item holds `true`; and `retakes`, the item's list or `[]` (`_list_items`, `list_import.py`). + - The route adds to each item `collectionId`, the id of the volume on the unit whose `filename_stem` is the item's `filenameStem`, and `projectId`, that volume's own `project_id`, which is `null` for a nested volume; `status`, that volume's record counts by status (`captured`, `in_review`, `rejected`, `approved` and `excluded`), as `GET /activity/collections` gives them; `doneMark`, `{by, at}` when the item was marked done with `PUT /imports/digitisation-lists/{list_id}/items/{position}/done`, otherwise `null`; and `queueHidden`, `true` when that volume's `queue_hidden_at` is set. A stem is looked up only when it is a slug of at most 27 characters, the first of the import's stem checks (`stem_is_well_formed`, `list_import.py`; `imports.py`); an item whose stem passes that check can be given a volume even when the import would refuse the item for another reason. A stem's volume is given to one item of the list: the first, by position, that is not withdrawn, or the first withdrawn one when no live item names the stem. Every other item has `collectionId`, `projectId` and `status` `null`, as does an item whose stem no volume has (`imports.py`; `StatusCounts`, `app/schemas/activity.py`). The done marks are read from `done.json` in the list's directory, by position for a file's list and by `itemId` for the queue; a missing or damaged file is read as no marks (`read_done_marks`, `list_import.py`). + - The route raises no error of its own. A request without a valid session, a Bearer token or the session cookie, is refused with `401`, and one from a role outside the three with `403`, by the role check. + - The client calls it as `importsApi.lists()` (`frontend/src/lib/api.ts`). +- **Marking an item done — `PUT /imports/digitisation-lists/{list_id}/items/{position}/done`.** Admins and reviewers may mark an item; operators are refused with `403` (`allow_reviewer`, `imports.py`). Record counts cannot show whether a spot recapture, a rescan or a completion is finished, so a person marks the item done. The body is `{done: true|false, itemId?: string}`. `done: true` records the mark as `{by, at}`, with the user's name and the UTC time. A mark already there is replaced. `done: false` removes the mark, and removing a mark that isn't there is not an error. `position` is the item's `position` as `GET /imports/digitisation-lists` gives it (`mark_list_item_done`, `imports.py`). + - On the digitisation queue a mark is kept by the item's `itemId`, so it stays with the entry when Fisqua issues a revision that gives the entry another position. The body must name that `itemId`; a request without it is refused with `422`. When the item now at `position` carries another `itemId`, the request is refused with `409` (`"The item at this position is another queue entry now. Reload the queue and try again."`), and nothing is written. On a file's list a mark is kept by position, and the body needs no `itemId`. One sent anyway is compared with the file item's own `itemId` field, which file items normally lack, so such a request is refused with the same `409` (`_list_items`, `list_import.py`; `set_done_mark`, `list_import.py`; `done_key`). + - The marks are written to `done.json` in the list's directory, under the list's lock. The whole file is rewritten through a temporary file and a rename, so a failed write leaves it as it was. The response is `200` with `listId`, `position`, `itemId` (the item's `itemId` field, `null` when it has none, as a file's item normally does) and `doneMark` (`{by, at}`, or `null` once removed). Each mark and removal is recorded in the activity log as `digitisation_list_item_marked_done` or `digitisation_list_item_unmarked`. The subject is the list's name from its latest report, or `null` when there is no readable report, and the detail is `list : item ()`. + - It is refused with `422` when the list id is not a UUID, when `position` is not an integer, or when the body is not of that form. It is refused with `404` when no stored list of that id has an item at that position. It is refused with `503` when the lock cannot be taken or `done.json` cannot be written, and then nothing has changed. + - The client calls it as `importsApi.setDone(listId, position, done, itemId?)` (`frontend/src/lib/api.ts`). The queue page has the buttons for admins and reviewers only (`frontend/src/routes/(dashboard)/dashboard/queue/+page.svelte`). + +**A record's rejection — `POST /records/{id}/reject`.** A reviewer or admin rejects a record that is `in_review` (`allow_reviewer`, `app/api/records.py`). The body is `{predefined_reason, comment}`. The response is `200` with the record, now `rejected`. Every current image is linked to the rejection, and `GET /records/{id}/rejections` lists the rejections, newest first, each with the images it flagged (`records.py`). + +- **The reasons.** `predefined_reason` is one of nine values: `blur`, `glare`, `shadow`, `focus`, `exposure`, `dirt`, `framing`, `obstruction` and `other`. `framing` is a page cut off or badly framed, and `obstruction` is a finger, weight or object in the shot (`PredefinedRejectionReason`, `PREDEFINED_REJECTION_REASONS`, `app/schemas/record.py`). Any other value is refused with FastAPI's validation `422`. The `record_rejections` table admits the same nine in the check constraint `check_record_rejection_reason`, widened from the first six by migration `a8c2e4f6b1d3` (`RecordRejection`, `app/models/record.py`). On `GET /records/{id}/rejections`, `predefined_reason` is a plain string, so rows written before the migration are returned unchanged. +- **The comment.** `comment` is at most 2,000 characters for every reason, counted as sent: a longer one is refused with the validation `422` and the message `"Value error, A rejection comment can be at most 2,000 characters long."` inside the `detail` array, and nothing is written (`REJECTION_COMMENT_MAX_LENGTH`, `app/schemas/record.py`; `_comment_fits_fisqua`). Within that, `comment` is optional for the first eight reasons. For `other` it must hold text other than whitespace: a request without one, or with `null`, an empty string or whitespace only, is refused with `422` and nothing is written (`RecordRejectRequest._other_needs_a_comment`, `schemas/record.py`). This is the validation `422`, a `detail` array whose message reads `"Value error, A rejection with reason 'other' needs a comment saying what is wrong."`, not one of the application's own. The table does not check the comment, because rows written before the migration carry none (`alembic/versions/a8c2e4f6b1d3_rejection_reasons_framing_obstruction_other.py`). +- **Other refusals.** A record that does not exist is `404` with `"Record not found"`. A record whose status is not `in_review` is `422` with a string `detail` naming the status (`reject_record`, `records.py`). +- **Downgrade.** `downgrade()` in `alembic/versions/a8c2e4f6b1d3_rejection_reasons_framing_obstruction_other.py` is refused while any rejection uses `framing`, `obstruction` or `other`, and no reason is rewritten; those rows are removed by hand first. + +**Recaptures and the recapture turn — `GET /records/to-retake/summary`.** While records are pending anywhere on the unit, starting a new volume alternates with finishing recaptures (`app/core/recapture_turn.py`). A record is pending while its status is `rejected`, or while it is `captured` and a current image still carries a `rejection_id`, the state `PATCH /records/{id}/status` leaves a record prepared for retake in until a capture replaces the image; or while it misses a page or a whole opening (`missing_side` set), has not been closed (`closed_reason` null) and is not `excluded`, until a dual capture into it writes both pages or it is closed with `POST /records/{id}/close-missing` (Openings and pages never captured, below) (`retake_clause`, `open_missing_clause`, `missing_side_clause`, `pending_clause`, `recapture_turn.py`; `pending_reason`, `record_is_pending`). That one definition is used by the summary, the list, the count, the turn and the completion test. The promotion refusal counts only the first two states (below). + +- **The summary.** Any signed-in role (`allow_read_only`, `app/api/records.py`). The response is `200` with `{pendingRecords, volumes, turn}`. `pendingRecords` counts the unit's pending records. Each volume with at least one pending record is listed as `{collectionId, projectId, name, filenameStem, pending, total, excluded, firstPendingRecordId, pendingRecordIds, missingSideRecordIds}`, most pending first, then by name: `pending` is its pending records, `total` its records with at least one rejection whatever their state now, except excluded ones, `excluded` its records excluded by a Fisqua decision (contract 1.6), which are never pending, `pendingRecordIds` its pending records by sequence (a record with none last) and then id, `firstPendingRecordId` the first of them, and `missingSideRecordIds` those of them whose pending reason is `missing_side`, in the same order, so a rejected record that also misses a side is not among them (`summarise_records_to_retake`, `records.py`). A record pending only because it is missing, such as a placeholder, has no rejection, so it counts in `pending` and not in `total`; a record rejected earlier and later marked missing counts in both. `projectId` is the project that owns the volume, through its parents for a nested one. `GET /records/to-retake/count` returns `{count}`, the number of pending records on the unit, the same set the list returns (`records.py`). +- **The list.** `GET /records/to-retake`, any signed-in role, returns every pending record on the unit (`_to_retake_query`, `records.py`). Records are ordered by volume, by its stem (volumes without one after every volume with one), then its name and id, so records in no volume come last; within a volume, by `sequence` (records without one last) and then id. Each row is `{recordId, title, sequence, collectionId, projectId, name, filenameStem, reason, comment, rejectedBy, rejectedAt, pendingReason, missingSide, missingExpected, missingNote, requestId}` (`RecordToRetake`, `app/schemas/record.py`). `reason`, `comment`, `rejectedBy` and `rejectedAt` come from the record's latest rejection and are `null` when it has none, as a placeholder has none. `pendingReason` is `rejected`, `prepared` or `missing_side`, checked in that order, so a rejected record that also misses a side is `rejected` (`pending_reason_clause`, `recapture_turn.py`). `missingSide`, `missingExpected`, `missingNote` and `requestId` are the record's `missing_side`, `missing_expected`, `missing_note` and `missing_request_id`. A closed missing record is not pending and is not listed. +- **The turn.** `turn` is `{state, unlockedBy}` (`turn`, `recapture_turn.py`). `state` is `free` when no record is pending; otherwise `new` when the newest `recapture_volume_completed` or `rescan_volume_completed` event in the system log is newer than the newest `new_volume_started` (`_COMPLETION_ACTIONS`, `recapture_turn.py`), and `recaptures` when it is not or there is none. Newer means a higher `system_logs.id`. `unlockedBy`, for `new` only, is `{collectionId, name}` of the volume whose completion opened the turn, by its current name, or the name the event recorded when the volume has been deleted; otherwise `null`. Turns do not accumulate: two completions in a row open one turn. +- **The two events.** Both are system-log rows with category `capture`, the volume's name as subject and the detail `collection_id= filename_stem=`, added to the capture's own transaction, so each stands or falls with its capture (`record_event`, `recapture_turn.py`; `_record_turn_events`, `app/api/cameras.py`). `new_volume_started` is written for a capture that creates the first record of a volume with none, except the first capture of a full rescan, which writes none (`cameras.py`). `recapture_volume_completed` is written for a retake of a pending record that leaves its volume with no pending record, once each time the volume reaches zero, and never for a status change alone. A retake in a full rescan whose volume has no `rescan_volume_completed` event yet writes none (`_record_turn_events`, `cameras.py`). `POST /records/{id}/close-missing` writes it in the same way, in its own transaction, when the record it closes was pending and the volume is left with none (`close_missing_record`, `records.py`). +- **The capture refusal.** `POST /cameras/capture` and `POST /cameras/capture/dual` refuse a capture that is not a retake, into a volume with no record, while the turn is `recaptures`, unless the user is an admin: `409` with `detail` `{code: "recapture_turn", message: "The volume could not be started: it is the retake turn. Finish the retakes of one volume and try again."}` (`_refuse_a_new_volume_out_of_turn`, `cameras.py`; `RECAPTURE_TURN_DETAIL`, `recapture_turn.py`). It runs after the refusals listed under A capture needs a volume with a stem, before any capture number is taken or camera touched (`cameras.py`). Retakes, captures into a volume that already has records, and the first capture of a full rescan are never refused by it (`_refuse_a_new_volume_out_of_turn`, `cameras.py`). +- **Locking.** A capture that starts a volume, and a retake of a pending record, take the unit's turn lock, a PostgreSQL transaction-level advisory lock (`pg_advisory_xact_lock`, key `0x43415054`), after the record and volume row locks they already hold, and keep it until the capture commits, so two operators cannot both start a new volume on one completion. The first takes it before reading the turn, the second before the completion count; any other capture takes none (`cameras.py`; `lock_turn`, `recapture_turn.py`). `POST /records/{id}/close-missing`, when the record it closes was pending, takes the record's row, then the volume's row, then the turn lock, before the completion count (`close_missing_record`, `records.py`). On SQLite, used only by the test suite, no lock is taken. +- **The promotion refusal.** `POST /collections/{id}/promote`, which admins and operators may call (`allow_contributor`), refuses a volume with any record waiting for a retake whoever calls it, that is, a record `rejected`, or `captured` with a current image that carries a `rejection_id`: `409` with `detail` `{code: "recaptures_pending", pending: , message: "The volume could not be sent to review: retakes left."}`. The count is taken after the record locks and before the idempotent return, so a volume whose only records left are rejected is refused too (`volume_retakes_pending`, `recapture_turn.py`; `app/api/collections.py`). An open missing record is pending but does not refuse the promotion: it is not promoted, stays `captured`, and is listed as `missing` in the manifest; a closed one is promoted like any captured record (`promote_collection`, `collections.py`). `PATCH /records/{id}/status` refuses to move an open missing record from `captured` to `in_review`, with `422` and `"Record N misses both pages. Capture the opening, or close it as not to be captured, before handing it over."` (or `its left page`, `its right page`), and `POST /records/bulk-status` skips it (`_assert_promotable`, `records.py`). After the record locks and before any status change, every promotion takes the volume's row `FOR UPDATE` once, so a promotion locks the records, then the volume's row, and then writes the history rows and the outbox row (`promote_collection`, `collections.py`). + +**Openings and pages never captured — `POST /collections/{id}/records/missing-opening`, `POST /records/{id}/missing-page` and `POST /records/{id}/close-missing`.** Under exchange contract 1.9, section 10, a record can stand for an opening, or one page of an opening, that was never captured. Such a record is pending (Recaptures and the recapture turn, above) until a dual capture into it writes both pages, or until an operator closes it as not to be captured. All three routes are for admins and operators (`allow_contributor`). + +- **The record fields.** `RecordRead` carries six fields for this (`RecordRead`, `app/schemas/record.py`). `missing_side` is `left` or `right` for a dual record that misses that page, whose one current image, if it has one, is the other page; `both` for a record with no image, a placeholder; otherwise `null`. `missing_expected` is what a placeholder should hold, and `missing_note` a note on the missing record. `missing_request_id` is the Fisqua request a placeholder was made from, kept after the placeholder has been captured into. `closed_reason` is why the record was closed without being captured, one of `foliation_skip`, `leaf_missing_from_volume`, `captured_elsewhere` and `other`, and `closed_note` the note given with it. Check constraints admit no other `missing_side` or `closed_reason` value, and no `closed_reason` on a record with no `missing_side` (`app/models/record.py`; migration `c4e6a8b0d2f4`). +- **`POST /collections/{id}/records/missing-opening`.** The body is `{afterRecordId, count, expected, note, requestId}`, and only `afterRecordId` is required. `count` is 1 to 50, and one when null or absent; `expected` and `note` are at most 2,000 characters, and `requestId` at most 64. A value outside these limits is FastAPI's validation `422` (`MissingOpeningsCreate`, `app/schemas/record.py`). The route inserts `count` placeholders right after the record named, whatever its status, `excluded` included. Each placeholder is a dual record of the volume, `captured`, with no image, `missing_side` `both`, and the body's `expected`, `note` and `requestId` (`insert_placeholders`, `app/core/record_sequence.py`). The placeholders are given the sequences right after that record, and the sequences of the later records are raised by `count` (A record inserted after another, above). The response is `200` with the placeholders, in order, as `RecordRead`. A volume or a record that does not exist is `404`, with `"Collection N not found"` or `"Record N not found"`. A record of another volume is `422` with `"Record N is not in volume M, so no opening can be marked after it there."`. A volume whose records keep changing gives the renumber's `409` (`app/api/collections.py`). The insertion is recorded in the activity log as `missing_openings_marked`, with the detail `volume after count= requestId= records=[]`. +- **`POST /records/{id}/missing-page`.** The body is `{side, note}`: `side` is `left` or `right`, and `note` is optional and at most 2,000 characters (`MissingPageRequest`, `app/schemas/record.py`). A record captured in single mode is refused with `409` and `detail` `{code: "missing_page_single_record", message}`, and nothing changes (`missing_page_refusal`, `app/api/records.py`). On a dual record that does not already miss that side or both, the current image of that side, if it has one, is superseded as a retake supersedes it: the file stays on the unit and in the bucket, and the image is no longer listed in the manifest. The record then misses that side, or `both` when no current image is left. A closed record is reopened: its `closed_reason` and `closed_note` are cleared, and it is pending again. A note, stripped, is kept as `missing_note`. A record in review or approved is returned to `captured`, and the change is written to its status history, so that an operator can capture into it; a rejected record stays `rejected` (`mark_missing_page`, `records.py`). A record that already misses that side, or both, keeps its side and its images. The record's row and then the volume's row are locked before any status change. The response is `200` with the record; a record that does not exist is `404`. When something changed, the change is recorded in the activity log as `missing_page_marked`, with `reopened=` in the detail when a closing was cleared, and the volume may be handed over again (below) (`records.py`). +- **`POST /records/{id}/close-missing`.** The body is `{reason, note}`. `reason` is `foliation_skip`, `leaf_missing_from_volume`, `captured_elsewhere` or `other`. `note` is optional and at most 2,000 characters, and `other` needs one: `other` with no note, or a blank one, is refused with FastAPI's validation `422` (`CloseMissingRequest`, `app/schemas/record.py`). A record that does not exist is `404`. A record with no `missing_side` is refused with `409` and `detail` `{code: "not_missing", message}`, and a record already closed with `409` and `{code: "already_closed", message}` (`close_missing_record`, `records.py`). The route sets `closed_reason`, and `closed_note` to the note stripped, or `null`. The record keeps its `missing_side`, stays in its volume and is no longer pending. When its volume has been handed over before, a `captured` record with no current image carrying a `rejection_id` is moved to `in_review`, as promotion would move it. A record waiting for a retake keeps its status and stays pending. In a volume never handed over, the status is left as it is, and the next promotion sends the record (`close_missing_record`, `records.py`). No route reopens a closed record; marking its other page missing, by `POST /records/{id}/missing-page` or a Fisqua decision, reopens it, and a dual capture into it clears the closing; such a capture is accepted only while the record is `captured` or `rejected`. The response is `200` with the record. The closing is recorded in the activity log as `missing_record_closed`, with the detail `record volume missing_side= reason=` (`records.py`). +- **Capturing into a missing record.** A missing record is captured into by `POST /cameras/capture/dual` with its `record_id`, as a retake. The capture supersedes any current image, writes both pages, and clears `missing_side`, `missing_expected`, `missing_note`, `closed_reason` and `closed_note`; `missing_request_id` is kept. The record keeps its sequence, and a rejected record is returned to `captured` (`trigger_dual_capture`, `app/api/cameras.py`). A missing record in review, approved or `excluded` is refused, like any retake of such a record, with `409` and `"Only a captured or rejected record can be retaken."` (`_refuse_retake_out_of_the_operators_hands`, `cameras.py`). `POST /cameras/capture` refuses a placeholder with `409` `placeholder_needs_dual` (A capture needs a volume with a stem, above). +- **`afterRecordId` on `POST /cameras/capture/dual`.** A dual capture that creates a record can put it right after a record of the volume: the body's `afterRecordId`, also accepted as `after_record_id` (`DualCaptureRequest`, `cameras.py`). With `record_id` as well, the request is refused with `422` and `"afterRecordId inserts a new record; it cannot be combined with record_id, which recaptures one."`, right after the resolution check. With a `collection_id`, the volume's records and then its row are locked before the volume checks, and a volume whose records keep changing gives the renumber's `409`. After the volume and stem checks, an `afterRecordId` that matches no record is `404` with `"Record N not found"`, and a record of another volume is `422` with `"Record N is not in volume M."`. The new record is given the sequence right after that record, and the sequences of the later records are raised by one. +- **Promotion.** `POST /collections/{id}/promote` sends a closed missing record to review like any captured record, a closed placeholder with no image included, and leaves an open one `captured` on the unit, where the manifest lists it as `missing` (The promotion refusal, above; `_assert_promotable`, `records.py`). +- **Handing over again.** `POST /collections/{id}/records/missing-opening` and `POST /records/{id}/close-missing` call `hand_over_again_after_missing_change` in their own transaction every time; `POST /records/{id}/missing-page` calls it only when something changed (`mark_record_missing_page`, `records.py`). A Fisqua decisions set calls it when the set marked a page missing or made a placeholder. The function takes the volume's row, and queues a handover as promotion does (What a handover does, above) when the volume has been handed over before, that is, has an outbox row in any state, and now holds no `captured` record other than open missing ones and no record waiting for a retake. Otherwise nothing is queued. The row is queued whatever the configuration and the mode: the volume's unsent rows become `superseded`, and the new row, unless the volume's recorded `external_id` differs from its stem (then it is queued `refused`, `not_exportable`; `enqueue_handover`, `fisqua_outbox.py`), waits until the unit is in fisqua mode with Fisqua configured, and, for a volume kept on the unit, until an admin releases the volume (`hand_over_again_after_missing_change`, `app/core/fisqua_outbox.py`; `handed_over_before`; `enqueue_handover`). After the commit, a route that queued a handover wakes the upload scheduler. +- **In an export.** A missing record closed without being captured that has no current image is left out of the BagIt export: it does not enter the bag, and it blocks neither the handover check nor the approval check. A closed missing record with an image is bagged once approved, like any record. An open missing record refuses the export as any other record that is not approved does: as not handed over while it is `captured`, and as not approved when it is `rejected`. A volume left with no record that holds a current image has nothing to export: `POST /collections/{id}/export` is refused with `422` and `detail` `{message: "Collection has nothing to export: no record has a current image.", blocking_record_ids: []}`, after the handover and approval checks, and the export job's own check fails the job with the same message (`_closed_without_image`, `exported_records`, `workflow_blockers`, `app/core/export_service.py`; `app/api/collections.py`). + +**An image's rotation — `rotate_deg`.** `RecordImageRead` carries `rotate_deg`, the clockwise rotation in degrees (`0`, `90`, `180` or `270`) that displays the image upright, as the capturing body was set. It is `null` for an upload and for every image captured before the column existed; nothing was backfilled, because a body's orientation can have changed since (`app/schemas/record.py`; `RecordImage.rotate_deg` and the check constraint `check_record_image_rotate_deg`, `app/models/record.py`, added by migration `d7a1c3e5f9b2`). It is returned wherever the schema is: the images of a record, `GET /records/{id}/images`, `POST /records/{id}/images`, `GET /records/images/{img_id}`, `PATCH /records/images/{img_id}` and the images of a rejection (`app/api/records.py`). + +- **Where it is set.** `POST /cameras/capture` and `POST /cameras/capture/dual` write it from the capturing body's saved orientation, one value for each image of a pair (`recorded_rotation`, `capture/camera.py`; `app/api/cameras.py`). A body with no saved orientation records `0`. Any other value that is not an integer is recorded as `null`; an integer is taken modulo 360, and one that is then not `0`, `90`, `180` or `270` is recorded as `null` (`recorded_rotation`, `capture/camera.py`). The capture request can override the saved orientation, `0` included: `rotate_deg` on `POST /cameras/capture`, and `rotate_deg_cam0` and `rotate_deg_cam1` on `POST /cameras/capture/dual` (`CaptureRequest` and `DualCaptureRequest`, `app/api/cameras.py`; applied in `trigger_capture` and `trigger_dual_capture`). A request value outside `0`, `90`, `180` and `270` is refused with the validation `422`. Once recorded, no route changes it: `RecordImageUpdate` holds only `sequence` and `role`. +- **A RAW master is not rewritten.** The orientation is written into the EXIF Orientation tag only for a `.jpg` or `.jpeg` file, which is a JPEG master or a RAW master's `_preview.jpg`, and no tag is written for `0`. A RAW master (`RAW_SUFFIXES`, `app/core/paths.py`: `.3fr`, `.arw`, `.cr2`, `.cr3`, `.crw`, `.dcr`, `.dng`, `.erf`, `.iiq`, `.kdc`, `.mef`, `.mos`, `.mrw`, `.nef`, `.nrw`, `.orf`, `.pef`, `.raf`, `.raw`, `.rw2`, `.rwl`, `.sr2`, `.srf`, `.srw`, `.x3f`) stays as the camera wrote it, so `rotate_deg` and the `rotate_deg` of the capture record's `files` entry are where its rotation is kept (`_apply_rotation`, `capture/service.py`; `CaptureFile.rotate_deg`, `capture/manifestHandler.py`). A capture record written before the key existed lacks it. +- **Fisqua's correction.** `RecordImageRead` also carries `rotation_correction_quarter_turns`: `1`, `2` or `3` quarter-turns clockwise, or `null` when Fisqua has made none. It is set only by applying Fisqua's decisions (above, Applying Fisqua's QC decisions), is for display, and changes no file (`app/schemas/record.py`; `RecordImage.rotation_correction_quarter_turns` and the check constraint `check_record_image_rotation_correction`, `app/models/record.py`, added by migration `a5f0306a8f8c`). +- **In an export.** The `metadata.json` of a BagIt export lists `rotate_deg` for each current image, and its `schema_version` is `2`, where earlier bags carry `1` or none (`METADATA_SCHEMA_VERSION`, `app/core/export_service.py`; `_metadata_payload`). Bags already exported are not rewritten. + +**Reaching the schema on a deployed appliance.** Explore the API on a development stack. On a provisioned unit, `scripts/setup-firewall.sh` allows port 8000 from the appliance's own compose network (`172.30.0.0/24`) and over `tailscale0`, but not from the venue LAN — so it is reachable for remote support, not from a laptop in the room. The proxied `/api/docs` path does not render Swagger UI, because the page requests `/openapi.json` at the site root and Nginx routes `/` to the frontend; `/api/openapi.json` does proxy correctly, so the raw schema is retrievable that way. + +--- + + +## 4. Testing the API {#testing-the-api} + +### 4.1 Option 1: interactive docs in Swagger UI {#swagger-ui} + +The fastest way to test endpoints is using the interactive documentation. + +#### Getting started with Swagger UI {#swagger-getting-started} + +1. **Open in Browser** + ``` + http://localhost:8000/docs + ``` + +2. **You'll see:** + - All API endpoints grouped by tag (records, cameras, projects, collections, auth, users, system, activity, imports, fisqua), and `GET /health`, which has no tag, under **default** (`app/main.py`) + - Green `POST`, blue `GET`, teal `PATCH`, orange `PUT`, red `DELETE` method badges + +#### Swagger UI navigation {#swagger-navigation} + +**Example:** To test the login endpoint: +1. Look for the **auth** section and expand it +2. Click `POST /auth/login` +3. Click **"Try it out"**, fill in credentials, click **"Execute"** +4. Copy the `access_token` from the response + +**Using Bearer Tokens for Protected Endpoints** + +1. Test `POST /auth/login`, copy the `access_token` +2. Click the green **"Authorize"** button (top-right) +3. Paste the token without the `Bearer ` prefix and click **"Authorize"**. Swagger UI adds the prefix itself; a pasted `Bearer ` is sent as `Bearer Bearer ` and refused with `401` +4. All subsequent requests automatically include your token + +Swagger UI sends no `X-Requested-With` header, so the backend answers the login with the token in the body, as it does for any API client. The same response also sets the `dtk_session` cookie in your browser for the host, whatever the port (`auth.py`; the cookie names no `Domain`, and browsers do not scope cookies by port). A Swagger login therefore replaces a session the dev frontend holds in the same browser, and a session the frontend set already authenticates Swagger. While the cookie is present and you have not authorized, the backend accepts Swagger's `GET` requests on it and refuses with `403` and `"Missing X-Requested-With header"` the other requests to routes that read the session; login, first-user registration and setup status do not read it. Once you authorize, every request carries `Authorization: Bearer`, and the backend uses the header and ignores the cookie (`_session_token`, `auth.py`), except at `POST /auth/logout`, which refuses any request without `X-Requested-With` (`auth.py`). + +**Testing a Protected Endpoint Example: Create Record** + +1. After authorization, find `POST /records/` under **records** section +2. Click "Try it out", fill in the request body: + ```json + { + "title": "Ancient Manuscript", + "capture_mode": "single", + "author": "Unknown", + "date": "1500-01-01" + } + ``` +3. Click "Execute": view the 200 OK response with the record ID (this endpoint does not set 201; `POST /collections/` does) + +##### Swagger UI status colours {#swagger-status-colours} + +- **2xx (Green):** Success +- **4xx (Red):** Client error - check your request or role permissions +- **5xx (Red):** Server error - backend issue + +--- + +### 4.2 Option 2: a complete testing workflow in Swagger UI {#swagger-workflow} + +Recommended order to test the entire API: + +1. **Health Check** → `GET /health` (no auth needed) +2. **Check setup state** → `GET /auth/setup/status` (no auth needed) +3. **Bootstrap, only if `needs_setup` is true** → `POST /auth/register`. This first user becomes admin. Outside a development `APP_ENV` (`dev`, `development`, `test`, `testing` or `local`), the request must carry the unit's bootstrap token in the `X-Bootstrap-Token` header: without it, or with a wrong one, the answer is `401` `"Invalid or missing bootstrap token"`, and on a unit with no `BOOTSTRAP_TOKEN` configured it is `503` (`_authorize_bootstrap`, `auth.py`). In development with `BOOTSTRAP_TOKEN` empty, no header is needed. If an account already exists, skip this step: registration then requires an admin token and returns 401 without one, or 403 `"Missing X-Requested-With header"` when the browser holds a session cookie from an earlier login and you have not authorized. +4. **Login** → `POST /auth/login` (save token) +5. **Authorize** → Click Authorize button, paste token +6. **Get Current User** → `GET /users/me` (check your role) +7. **Create Project** → `POST /projects/` (admin only) +8. **Create Volume** → `POST /collections/` with a `filename_stem`, which is required (`201`). While projects are hidden, as they are on a new unit, the volume goes into the unit's default project and a `project_id` in the body is ignored (`create_collection`, `collections.py`) +9. **Create Record** → `POST /records/` with the volume's `collection_id`. An image can be added only to a record in a volume with a stem; a record outside every volume is refused with `409` `"Captures must go into a volume."` (`add_image_to_record`, `records.py`) +10. **Upload Image** → `POST /records/{id}/images` +11. **Add to Project** → `POST /projects/{id}/add_record/{rec_id}`. It takes the record out of its volume, so on a unit in offline mode, where every new volume is kept on the unit, it is refused with `409` and `kept_on_unit_move` (`add_record_to_project`, `projects.py`; `refuse_kept_move`, `app/core/kept_volumes.py`). A development stack with neither Fisqua nor the offsite upload configured starts in offline mode (`app/core/unit_mode.py`) +12. **Get Record** → `GET /records/{id}` +13. **Delete Record** → `DELETE /records/{id}` + +--- + +### 4.3 Option 3: run the test suite {#test-suite} + +```bash +# Run all tests with pytest +docker compose exec backend python -m pytest + +# Run specific test categories +docker compose exec backend python -m pytest tests/unit/ # API, models, schemas +docker compose exec backend python -m pytest tests/integration/ # capture workflow +# Camera tests need real hardware AND the native pixi environment on the Pi; +# the dev container has no camera devices and no libcamera (Dockerfile.dev +# installs none) — see backend/DEPENDENCIES.md. On the Pi, in backend/: +# pixi run -e dev pytest tests/test_cameras.py -m camera +# Note: the `test-cameras` pixi task is currently broken — it points at +# test/test_cameras.py, and the file is tests/test_cameras.py (NEH-195). + +# Run with verbose output +docker compose exec backend python -m pytest -v + +``` + +`pytest-cov` is not in either dependency manifest, so `--cov` is unavailable. + +**Test Organization:** +- `tests/unit/test_api.py` — API endpoint validation, imports, models, schemas +- `tests/integration/test_capture_integration.py` — Full capture workflow with database +- `tests/test_cameras.py` — Camera hardware tests (requires connected cameras) +- `tests/validate_system.py` — Complete system validation script +- `tests/conftest.py` — Shared pytest fixtures + +### 4.4 Option 4: manual testing with cURL {#manual-testing-curl} + +```bash +# Health check +curl http://localhost:8000/health + +# Register the first user (in development with BOOTSTRAP_TOKEN empty; +# otherwise add -H "X-Bootstrap-Token: ") +curl -X POST http://localhost:8000/auth/register \ + -H "Content-Type: application/json" \ + -d '{"username":"test","email":"test@example.com","password":"pass123"}' + +# Login +curl -X POST http://localhost:8000/auth/login \ + -H "Content-Type: application/json" \ + -d '{"username":"test","password":"pass123"}' + +# Get current user's role +curl http://localhost:8000/users/me \ + -H "Authorization: Bearer " +``` + +The backend answers a login made without the `X-Requested-With` header with `{access_token, token_type: "bearer"}`, and the client puts the token in `Authorization: Bearer` on every later request. It answers a login made with the header with `{access_token: null, token_type: "cookie"}`, and the session is then only in the `dtk_session` cookie; that is the browser app's login (`auth.py`). cURL keeps no cookie unless it is given a cookie jar, so these examples authenticate by the header alone. `POST /auth/logout` answers `204` with or without a session, and `403` without the header (`auth.py`). + +--- + +### Other views of the generated docs {#alternative-views} + +**ReDoc** (Read-only documentation): +``` +http://localhost:8000/redoc +``` + +**OpenAPI JSON** (Raw specification): +``` +http://localhost:8000/openapi.json +``` + +--- + +## 5. File storage {#file-storage} + +### Storage structure {#storage-structure} + +Images are stored under the active projects root, `/var/lib/dtk/projects/` by default. A volume with a file name stem keeps its files in a directory named by the stem, directly under the root and outside any project. A volume without a stem keeps the name-based layout inside its project's tree: + +``` +/ +├── example-vol-003/ ← a volume with a stem: / +│ ├── captures/ ← masters (JPEG, TIFF or CR2) and uploads +│ │ ├── example-vol-003-img_0001_c0.jpg +│ │ ├── example-vol-003-img_0001_c1.jpg +│ │ └── ... +│ ├── previews/ ← the _preview.jpg of each RAW master +│ ├── thumbnails/ +│ └── metadata/ +│ └── manifest.jsonl ← the volume's own capture records, appended +├── project_1/ ← a project's tree, named by project_dir_name() +│ ├── volume_b/ ← a volume without a stem +│ │ └── images/ +│ │ ├── main/ ← masters, each RAW master's _preview.jpg beside it +│ │ └── thumbnails/ +│ ├── images/ +│ │ ├── main/ ← images of records attached straight to the project +│ │ └── thumbnails/ +│ ├── metadata/ +│ │ ├── project_manifest.jsonl ← written at project init +│ │ └── manifest.jsonl ← capture records made in the name-based layout +│ └── packages/ ← created at init, currently unused +├── .retired-manifests/ ← capture manifests of deleted projects +├── .captua-offsite-staging/ ← links the offsite upload reads from; removed at each start +└── ... +``` + +- **The stem decides the layout.** `image_output_dir()` (`backend/capture/project_manager.py`) returns `//captures/` for a volume with a stem, `//images/main/` for a volume without one, and `/images/main/` for neither. `volume_root()` refuses a value that is not a stem, so a stored stem cannot name a path outside the root. Before a capture into a volume with a stem, all four directories are created (`ensure_volume_dirs`; `backend/capture/service.py`). In the name-based layout two volumes of one name share a directory, and a nested volume's directory sits beside its parent's (`collection_capture_root`, `project_manager.py`). A volume without a stem takes no capture or upload (section 3), but a move of records into it, or a rename of it or of its project, still writes files there. An upload goes to `/captures/`, named as a single capture is (see Filename Format), and its thumbnail to `/thumbnails/` (`add_image_to_record`, `backend/app/api/records.py`). +- **A RAW master's preview is placed by the layout.** `preview_sidecar_of()` (`backend/app/core/paths.py`) names the `_preview.jpg` of a master in `captures/` in the sibling `previews/`, and that of any other master beside it. +- **Each volume with a stem has its own manifest.** `append_manifest_record()` (`backend/capture/manifestHandler.py`) writes `project_manifest.jsonl` at project init, in the project's `metadata/`, and one `manifest.jsonl` line per capture event, carrying each file's capture-time sha256. The capture line goes to the manifest under `capture_manifest_root()` (`project_manager.py`): `/metadata/manifest.jsonl` for a volume with a stem, the project's otherwise. Its paths are relative to the directory that holds `metadata/`. Each line is appended in one `O_APPEND` write and fsynced, after a newline when the last line was torn (`_append_line`, `manifestHandler.py`). An upload into a volume writes an upload record to `/metadata/manifest.jsonl` by the same append, before its row is committed: `{record_type: "upload", capture_id, timestamp_utc, files: [{role: "single", relative_path, bytes, mimetype, sha256}]}`, with the stored file's path, size, content type and sha256 (`append_upload_record`, `manifestHandler.py`; `backend/app/api/records.py`). Its `capture_id` is the one the client sent with the upload, or a uuid4 the route gives an upload sent without one, and the image row carries the same id (`add_image_to_record`, `records.py`). If the commit fails, the file and thumbnail are removed and the line stays, so the number it names is not given again. When a move, or the startup migration (see Moving volumes into the stem layout at startup), renames a master with a capture id, a relocation record, `{record_type: "relocation", capture_id, image_id, sha256, from, to, relocated_at}`, is appended to the manifest of the top directory the master was moved into (`append_relocation_record`, `manifestHandler.py`; `relocation_of`, `backend/app/core/storage_ops.py`; `_record_relocation`, `backend/app/core/volume_layout.py`). A renumber renames no file and writes no relocation record. With no capture-time checksum to carry, no record is written and a WARNING is logged. A project's manifest is not deleted with the project: `DELETE /projects/{id}` moves it to `.retired-manifests/--manifest.jsonl` first, and refuses with `409` a tree that holds any other capture manifest (`backend/app/api/projects.py`, `retire_project_manifest`, `storage_ops.py`). +- **Old and new manifests are read together.** `build_fixity_index()` (`backend/app/core/integrity.py`) reads every `metadata/manifest.jsonl` under the projects root, each project's and each volume's, and the retired ones (`_manifests`). Paths in a manifest are resolved against the directory that holds its `metadata/`, or, for a retired one, against the project directory its file name carries (`manifest_base`). A capture record gives each file's sha256 by path and by file name, and an upload record is read as a capture record; a relocation record that names its image gives that image's sha256 directly. A line that is not JSON is skipped, and the count is logged. The export fixity gate (`_fixity_gate`, `backend/app/core/export_service.py`) refuses the bag with `checksum_mismatch` when a file's bytes differ from its sha256, and with `checksum_unresolved` when an image's capture id has a capture record in some manifest but no sha256 resolves for the image; an image whose capture id has no capture record anywhere, such as an upload made before uploads were written to the manifest, passes unchecked, and a later upload is checked against its upload record. A master freed from the card is not hashed again, since its bytes were checked against its SHA1 when it was freed, and a file that is missing is skipped by this check (`verify_images_against_manifest`, `integrity.py`). The bag's `data/metadata/manifest.jsonl` holds the capture records of the volume's current images from every manifest, without relocation or `preview_digest` records; where both a capture-time record and a migration copy exist, the capture-time record is used. The upload records of the volume's current images are included as capture records are (`capture_record_lines`, `integrity.py`; `backend/app/core/export_service.py`; `backend/app/core/bag_export.py`). +- **Renames and moves no longer touch migrated files.** No file in `/` is moved when the volume is renamed, re-parented or moved to another project, and when its project is renamed. Files still in the name-based layout, which are every file of a volume without a stem and those of a volume given a stem since the last start, are moved as before, and the operation is refused with `409` while an export of a volume with such files is queued or running (`collections_in_old_layout`, `storage_ops.py`; `backend/app/api/collections.py`; `projects.py`). `POST /collections/{id}/move-records` still moves the records' files, to the target's `/captures/` or to its name-based directory (`collection_image_dir`, `storage_ops.py`; `collections.py`). A record with an image in the offsite bucket is not moved out of its volume at all, by this route, by `PATCH /records/{id}` or by `POST /projects/{id}/add_record/{rec_id}` (section 3). The same three routes refuse a move between a volume Captua keeps on the unit and one it does not (`refuse_kept_move`, `app/core/kept_volumes.py`; section 3, Volumes kept on the unit). `DELETE /collections/{id}` removes only the volume's empty directories; a file found there that no row references stays where it is and is logged (`remove_empty_dirs`, `storage_ops.py`; `collections.py`). +- **`packages/` is not where exports go.** It is created at project init and nothing writes into it. BagIt exports are written to `settings.exports_dir`, `/var/lib/dtk/exports` by default (`backend/app/core/config.py`, `backend/app/core/export_service.py`). +- **There is no `temp/` or `trash/` directory under the projects root, and deletion is permanent.** Deleting a record unlinks its files, as does deleting a single image (`delete_record` and the image delete handler in `backend/app/api/records.py`); each takes the master, the thumbnail and the `_preview.jpg` sidecar where `preview_sidecar_of()` places it, except that the image delete keeps a sidecar another image of the record still names (`_image_files_to_unlink`, `backend/app/api/records.py`). There is no recovery directory, and on a backup-less appliance a delete is final. An object already uploaded stays in the offsite bucket: its `offsite_objects` row is kept. On PostgreSQL the foreign key sets its `record_image_id` to null; on SQLite, where the backend does not turn foreign keys on, the id is left pointing at no image (`backend/app/models/offsite_object.py`; `sqlite_foreign_keys_off`, `backend/app/core/db.py`, which only restores the pragma). +- **The root is not fixed.** Activating an external storage device changes `settings.projects_dir` at runtime, so captures may live somewhere other than the default microSD path. + +### Moving volumes into the stem layout at startup {#stem-layout-migration} + +Volumes captured before stems existed, and volumes given a stem later, have files in the name-based layout. At every start, after the project rename reconciliation, the backend runs `migrate_volume_layout_at_startup()` (`backend/app/main.py`; `backend/app/core/volume_layout.py`), and the migration moves the existing files of each volume with a stem into `/`. New captures and uploads into a volume with a stem are written to `/captures/` at once. + +- **The rows decide what is moved.** An image row of a volume with a stem is out of place when its stored path is under the active projects root and not in the volume's `captures/` (`_expected_dirs` and `_out_of_place`, `volume_layout.py`). Nothing else is looked at: finding the rows takes one query for the stems, one over the image rows and a string comparison per row, with no filesystem access per row. The files of a volume without a stem are left where they are. Files are attributed by their rows, never by the directory they are in, so the migration separates two volumes of one name that share a directory. +- **What is moved, and where.** The migration moves a master to `captures/`, a RAW master's sidecar to `previews/` and a thumbnail to `thumbnails/`, and keeps their names. No file is moved onto an existing one. A master's name counts as taken when a file in `captures/`, a move planned there or a freed file's reserved name has it (compared case-folded), when, for a RAW master, its sidecar's name is taken in `previews/`, or when a file in `captures/` that is not the same record's has the same stem (`_Dir.master_taken`). A master whose name is taken is renamed by inserting `_img` before its suffix, then `_img_2`, `_3` and on, so `20260109_143652_123_c0.jpg` of image 42 becomes `20260109_143652_123_c0_img42.jpg` (`_suffixed_stems`; `_free_name`). A renamed master with a capture id gets a relocation record in the volume's manifest before it is moved (`_record_relocation`). The migration moves only files under the active projects root, so uploads made before this layout, under `/uploads/`, stay there and are not looked at (`_out_of_place`, `backend/app/core/volume_layout.py`). +- **A row whose file is already in place.** When a row's old path is gone, a file in the volume's `captures/` under the row's own name or one of the clash names, and that no row references, is adopted: the row is pointed at it, but only when its sha256 matches the capture-time checksum held for the image. Adopted rows are listed under `adopted`. With no matching checksum the image is skipped as `missing` (`_adoptable`, `_plan`, `volume_layout.py`). A row whose master was freed from the card is never `missing`: no file moves for it, its row is pointed at the name the master would have been moved to, and it is listed under `freed_paths_moved`; that name, and a freed preview's, stays taken for later moves (`volume_layout.py`). +- **Thumbnails.** A thumbnail whose name is taken in `thumbnails/`, or whose file is missing, has its row cleared, and the image is listed under `thumbnails_cleared` with the reason `name_taken` or `missing`; the thumbnail route regenerates it. A thumbnail that cannot be moved keeps its row and is listed under `thumbnails_not_moved`. +- **The volume's records are copied first.** Before the migration moves a volume's files, it copies the volume's capture records and their relocation records from every other manifest into `/metadata/manifest.jsonl`, marked `copied_from` and with their paths rebased onto `/`. The manifests they are copied from are not changed. When the copy cannot be written, the failure is logged at ERROR and reported under `manifest_copy_failed`, and the move goes on (`_copy_volume_records`). +- **The journal.** The work is done one volume at a time. The migration writes the volume's planned moves to `/volume-layout.journal` before it moves any file; after the moves it fsyncs the directories, commits the rows and removes the journal (`_commit_batch`). At startup the migration completes a journal it finds before anything else. +- **When the backend does not serve.** Any `VolumeLayoutError` is re-raised and the backend does not serve: a pending journal that names another projects root, a journal or sidecar list that cannot be read (`_read_json`), or a volume manifest that cannot be read while records are copied. Another failure that leaves a journal is re-raised too. Any other failure is logged and the backend serves, as it does when the projects root cannot take writes. +- **What is skipped or fails.** Each image the plan does not move is listed under `skipped` with a `reason`. A volume whose `/` already holds entries that are not the volume's is not moved; each of its images has the reason `stem_dir_occupied` and the list `foreign` (`_foreign_entries`). A volume whose `/` is a live project tree has the reason `stem_dir_is_project_tree`. A volume whose `/`, or one of its directories, resolves outside the projects root, for example through a symbolic link, has the reason `stem_dir_outside_projects_root` (`_plan`, `volume_layout.py`). A stored stem that is not a valid stem gives `no_stem`. Single images can also be skipped as `outside_storage`, `outside_projects_root`, `missing`, `row_changed` or `freed_but_present`, a freed master whose path holds a file again (`_execute`). An image whose move fails is listed under `failed` with `image_id`, `path` and `error`; its file and row are left as they were, and the migration goes on with the next image. A sidecar that cannot be moved with its master is listed under `sidecars_not_moved`, recorded in `/volume-layout.sidecars`, retried at every start, and listed under `sidecars_pending` until it has been moved (`_retry_sidecars`). +- **What else is reported.** A writer's temporary file in `/` is not counted as foreign; it is left where it is and listed under `temp_files_left`. A generated thumbnail (`_thumb.jpg`) that no row owns is treated the same way and listed under `orphan_thumbnails_left`. On a run that finds out-of-place rows, the files no row references in the name-based volume directories, and in the directories files are moved out of, are listed under `left_unreferenced` and stay where they are (`_unreferenced_in_collection_dirs`). So is a file that no row references and that took a name a master was denied, forcing the clash rename, in `captures/` or, for a RAW master, `previews/` (`_clashing_files`), and a file that took a master's planned name after planning. Such a file makes the volume's `/` hold what is not the volume's, so a later run that has more of the volume's files to move skips it as `stem_dir_occupied` until the file is removed. At every start each volume's leftover `metadata/manifest.jsonl.part`, written by an earlier version of the manifest copy, is removed and counted in `stale_parts_removed`; one that cannot be removed is counted too, and logged at ERROR (`_remove_stale_parts`). After the moves, each migrated volume's own manifest is checked for a capture record per capture id of its images. The missing ones are copied in from the other manifests with their relocation records, and the lines copied are counted per volume in `manifests_repaired`, and capture ids that no manifest holds are listed per volume in `captures_without_record` (`_repair_volume_manifests`). The capture ids found in no manifest are kept in `/volume-layout.missing-records` with each manifest's path, size and modification time, and the search of every manifest is skipped while both the missing ids and the manifests are unchanged. The report's keys are set in `_new_report`, except `pending_journal_entries`, which a dry run adds (`migrate_volume_layout`). At startup the findings are logged. `python -m app.core.volume_layout [--dry-run]`, run with the backend stopped, prints the report as JSON and exits with 1 when `failed` is not empty; a dry run writes nothing and lists a pending journal's entries under `pending_journal_entries` without completing it (`main`). + +### Offsite copies {#offsite-copies} + +The backend puts two kinds of object in the offsite destination, `CAPTUA_OFFSITE_REMOTE`, both under the tenant prefix `CAPTUA_OFFSITE_TENANT`: each image of a volume with a stem, and an encrypted dump of the catalogue database. At boot, and only when the remote and a valid tenant are set, the backend starts an in-process schedule for each, which first runs `CAPTUA_OFFSITE_BACKUP_DELAY` seconds after the start and then `CAPTUA_OFFSITE_BACKUP_INTERVAL` seconds after each run ends; a handover wakes the image schedule, which then runs at once, or right after a run in progress, and each image tick runs the Fisqua send pass after the upload (`backend/app/main.py`; `ImageUploadScheduler`, `backend/app/core/image_upload.py`; the dump's scheduler in `backend/app/core/catalogue_backup.py`). Each run reads the unit's mode before it reads the hold or lists, uploads or dumps anything: in offline mode it returns `off_in_this_mode` and nothing is listed, uploaded or dumped, and a change of mode applies from the next tick. While the hold file exists, runs return `held` (section 3, The upload hold). Both copy with rclone under one lock, so one object is in transit at a time within the one `CAPTUA_OFFSITE_BWLIMIT` cap, and both pass `--no-check-dest`, because the appliance's key can write and list but not read (`upload_file`, `image_upload.py`; `transfer_lock`, `backend/app/core/catalogue_backup.py`). + +``` +/ +└── / ← CAPTUA_OFFSITE_TENANT + ├── / ← one per volume with a stem + │ ├── captures/ ← each image as shot, current and superseded + │ └── previews/ ← each RAW master's _preview.jpg + └── db-backups/ ← CAPTUA_OFFSITE_DB_PREFIX + └── catalogue--.sql.gz.age +``` + +- **What is uploaded.** Every image of a volume with a stem that Captua does not keep on the unit, current and superseded alike, and the preview of each RAW master whose preview file exists. Thumbnails are never uploaded, and the images of a volume without a stem, or of a kept volume, are not uploaded (`image_upload.py`). Finding work does not scan the disk: one query selects the images of volumes with a stem, not kept, that have no verified or refused row for their capture or, for a RAW master, for their preview (`pending_work`). A keep committed during a run is caught when the object is read, and the object is skipped (`_read_object`). A capture is not held up by the upload: the worker holds no database lock and no transaction while rclone runs, and a file whose size or modification time changes while it is hashed is skipped for that run (`stable_digests`). +- **Keys are frozen at first upload.** `` is the file's name on disk when the unit first uploads the object (`capture_key` and `preview_key`, `image_upload.py`). The key is stored in `offsite_objects.object_key` and never changed: every later run uses the stored key, and a `before_update` guard raises `ImmutableFieldError` on any change to it (`backend/app/models/offsite_object.py`). The guard is an ORM listener, so it applies to changes made through the ORM and not to raw SQL or a bulk `query().update()`. A downgrade below migration `b8d2f4a6c1e3` drops the table, and with it every recorded key (`downgrade`, `backend/alembic/versions/b8d2f4a6c1e3_add_offsite_objects.py`). A move on disk or a project rename leaves the bucket as it is (`image_upload.py`). When a new object's key is already another image's key, the object is keyed beside it with `_img` before the suffix (`disambiguated_key`, `image_upload.py`). A key that another row holds even then is reported under `conflicts` and nothing is uploaded (`_process_read`, `image_upload.py`). +- **Keys are reserved before the transfer.** The object's row is committed with its key, as a pending row, before rclone starts. A record move requested during the copy is then refused (section 3), and a crash after the copy leaves the key frozen for the next run to verify (`image_upload.py`; `_claim`). A pending row is never deleted. On a later run the uploader lists the key and verifies the object there, copies it again to the same key, or refuses or skips it on the checks above and below (`offsite_object.py`; `_process_read`, `image_upload.py`). A pending row whose image was deleted, so that its `record_image_id` is null, is never selected again: the work list is built from the image rows (`pending_work`, `image_upload.py`). +- **Nothing is overwritten.** Before each upload the key's directory is listed. An object already at the key with the local SHA1 is recorded as verified without an upload; one with another SHA1 is refused as `remote_differs` and not retried; an entry with no SHA1 is skipped (`_process_read`, `image_upload.py`). The copy itself is `rclone copyto`, and the listing before it is what keeps it from overwriting (`upload_file`, `image_upload.py`). The listing and the copy are two steps, so this holds against what the listing showed. A capture is also checked against its capture-time sha256 before it is uploaded, and refused as `fixity` on a mismatch that persists when the manifests are read again (`_process_read`, `image_upload.py`). +- **Objects are verified by listing.** An object counts as verified only when a listing shows its key with the local SHA1: the listing before an upload, for an object already there; the listing after it; or the adoption listing (`image_upload.py`). A copy command that succeeded sets `uploaded_at`, and the object stays pending until a listing confirms it (`_process_read`, `image_upload.py`). rclone's B2 backend uploads a file above `--b2-upload-cutoff` (200 MiB by default) in parts, and the listing's SHA1 for such a file comes from its `large_file_sha1` metadata. rclone sets that from a local source, but a part-uploaded object without it lists no SHA1, and without a SHA1 nothing is verified (`_process_read`, `image_upload.py`). When a listing does not answer, the uploader stops the run with the status `aborted`, and when a copy fails, with `failed`. rclone's "directory not found" is read as absence only when the parent directory's listing answers and does not show the directory, or for the tenant prefix itself, and nothing above `//` is listed (`_entries`, `image_upload.py`; `run_image_upload`). +- **The bytes come from a staged link.** The file is read through a hard link in `/.captua-offsite-staging/`, made under the files-being-read hold (section 3), so a move that renames the file during the upload cannot change the bytes that are sent. Where the file system cannot make a hard link, a copy is made there instead and removed after the upload. The directory is removed at each start, and the integrity check does not count its files (`_stage`, `image_upload.py`; `sweep_staging`; `OFFSITE_STAGING_DIR`, `backend/app/core/paths.py`; `backend/app/core/integrity.py`). +- **`offsite_objects`.** Created by migration `b8d2f4a6c1e3` (`backend/alembic/versions/b8d2f4a6c1e3_add_offsite_objects.py`). One row per object: `id`, `record_image_id` (a foreign key to `record_images.id`, `ON DELETE SET NULL`), `kind` (`capture` or `preview`), `object_key` (unique across all rows, relative to `CAPTUA_OFFSITE_REMOTE`), `local_sha1`, `remote_sha1`, `uploaded_at`, `verified_at`, `refused_at`, `refusal` and `created_at`; an image has at most one row of each kind (`OffsiteObject`, `offsite_object.py`). The states are derived from the columns, and a check constraint keeps `verified_at` and `refused_at` from both being set: **verified**, `verified_at` set; **refused**, `refused_at` and `refusal` set; **pending**, neither, with no `uploaded_at` while the key is only reserved, and with it once the copy command has succeeded. An adopted object has `verified_at` and no `uploaded_at`. When an image row is deleted, its rows stay as the unit's record of what it put in the bucket. On PostgreSQL `record_image_id` is set to null; on SQLite, without foreign keys, it is left pointing at no image (`backend/app/models/collection.py`). +- **The system log.** After each run that did any work, the uploader writes `image_upload_run` to the system log, in the `system` category, at `INFO` when its status is `done`, `stopped` or `held` and nothing was refused, and at `WARN` otherwise, a run stopped by a switch to offline mode included. Its subject is the status and its detail the counts `uploaded`, `already_present`, `unverified`, `refused`, `conflicts` and `skipped`, with the error when there was one (`image_upload.py`). Each refusal is logged as `image_upload_refused` (section 3). +- **Adopting objects already in a bucket.** `python -m app.core.image_upload adopt [--apply]` lists ``, relative to `CAPTUA_OFFSITE_REMOTE`, recursively. It hashes each object of a volume with a stem, not kept on the unit, that has no row yet, and when exactly one listed object carries the same SHA1, records that object's key as the image's frozen key, verified, with no upload. Two or more listed objects with the SHA1 (`ambiguous_remote`), two local objects matching one listed object (`ambiguous_local`) and a key another row already holds (`key_already_held`) are reported, and nothing is recorded for them. With `--apply`, an image whose record moved or whose row changed after it was hashed is reported under `changed` and not adopted; `changed` is filled only then. A file or image row that changes around the hash itself is reported under `unreadable`. Without `--apply` nothing is written. The command neither requires nor applies `CAPTUA_OFFSITE_TENANT`: `` is any prefix under the remote. The command prints the report as JSON, with the keys `prefix`, `listed`, `listed_without_sha1`, `adopted`, `ambiguous_remote`, `ambiguous_local`, `key_already_held`, `changed`, `unmatched` (a count), `unreadable` and `applied`, and exits with `0`; with an empty prefix, no remote configured or a listing that does not answer, it prints `error: ` and exits with `2`. With `--apply` it writes `image_upload_adopted` to the system log with the counts (`adopt_objects`, `image_upload.py`; `main`). It runs in a process of its own, outside the backend's read hold, so it checks instead that the file's inode and the image's row are the same before and after the hash. An adopted key is whatever was found under the operator's prefix: its name may differ from the file's name on disk, and it may sit under another stem than the volume's. +- **Adopting from a rename map.** `python -m app.core.image_upload adopt-map [--apply]` reads a contract 1.1 rename map, which lists for one volume the key each capture and preview was copied to in the destination bucket, and records each listed object as the frozen key of its image, verified, with no upload (`adopt_rename_map`, `image_upload.py`; `load_rename_map`; the command). Unlike `adopt`, it records keys for images whose files are absent from the card, so `mark-freed` can then mark those files as freed. + - **Whole-map refusals.** The command prints `error: `, lists nothing, writes nothing and exits with `2` when the file cannot be read or is not JSON; when the map is not a JSON object, or its `contract`, `version` or `kind` is not `fisqua-captua-exchange`, `1.1` and `rename-map`; when it has no `volume` or `destination` object, or `entries` is not a list; when no volume on the unit has both the map's `volume.captuaCollectionId` and `volume.stem`; when `CAPTUA_OFFSITE_REMOTE` is unset or is not of the form `:`, or its bucket is not the map's `destination.bucket`; when `destination.root` is not a key prefix; when `CAPTUA_OFFSITE_TENANT` is unset or invalid; and when the root's first segment is not that tenant (`_read_rename_map_header`, `image_upload.py`; `_remote_bucket`). A listing that does not answer also ends the command with `2`. + - **Per-entry checks.** Each entry is recorded at `/`, the root stripped of surrounding whitespace and slashes (`_read_rename_map_header`, `image_upload.py`), only when every check passes. Otherwise it is listed under `refused` with its `index`, `image_id`, `kind`, `key` and `reason`, and, for most reasons, the values that differed. The reasons are: `malformed_entry` (an entry that is not an object; a missing or mistyped `imageId`, `recordId`, `originalFilename` or `sha1`; a `kind` other than `capture` or `preview`; a `sha1` that is not 40 hexadecimal digits; an empty `originalFilename`; or a mistyped `bytes` or `captureId`); `key_outside_volume` (the key is not `//captures/` for a capture or `//previews/` for a preview, or `destinationKey` is not a plain relative path); `duplicate_entry` (among the entries that passed the shape and key checks, more than one names the same image and kind, or the same key; every such entry is refused); `image_not_found`; `record_differs`; `not_in_volume`; `capture_differs` (when the entry gives a `captureId`); `filename_differs` (`originalFilename` is not the master's name for a capture, or its preview's for a preview); `key_differs` (the image already has a row of that kind at another key); `key_already_held` (another row holds the key); `not_in_bucket`, `listed_without_sha1` and `bucket_sha1_differs` (from a fresh listing of the key's directory); `bucket_size_differs` (when the listing and the entry both give a size); `unreadable` and `local_sha1_differs` (when the file is on the card, it is hashed and must carry the entry's `sha1`); and, with `--apply`, `changed` (the image moved or its row changed after it was checked) and `recorded_meanwhile` (`_map_entry_fields`, `image_upload.py`; `_map_key`). An image that already has a row at the same key is listed under `already_recorded`, with `verified`, and not counted as refused. + - **The report.** `{map_id, filename_stem, collection_id, key_prefix, entries, applied, adopted, adopted_present, adopted_absent, already_recorded, refused, refused_counts}`. Each adopted entry carries `index`, `image_id`, `kind`, `key`, `sha1`, `bytes`, `local` (`present` or `absent`) and `local_path`; `refused` is sorted by `index`, and `refused_counts` counts the reasons (`image_upload.py`). Rows are written through `_claim`, as `adopt` writes them. Without `--apply` nothing is written; with it, `image_upload_adopted` is logged in the system log with the volume's stem as subject, at `WARN` when any entry was refused and at `INFO` otherwise, with the detail `rename-map : adopted= absent= present= already_recorded= refused=` followed, when any entry was refused, by the reason counts in parentheses, sorted by reason, as `(= ...)`; the detail is cut at 500 characters (`_log`). +- **Raising a volume's capture counter.** `python -m app.core.image_upload raise-capture-counter [--apply]` raises the `capture_counter` of the volume with that stem to `n`, so the next number a capture tries is `n + 1`. It is for numbers given outside this unit, such as the `counterAfter` of a rename map whose copies exist only in the bucket (`raise_capture_counter`, `backend/app/core/capture_counter.py`; the command, `image_upload.py`). The volume's row is taken under the same lock a capture takes before it raises the counter, and the value is read again under it (`raise_capture_counter`, `capture_counter.py`). It refuses, with `error: ` and exit code `2`, an `n` outside 0 to 9999, a stem no volume has, and an `n` below the current counter, which never decreases (`image_upload.py`). The report is `{stem, collection_id, counter_before, counter_after, raised, applied}`. Without `--apply`, nothing is written. With `--apply` and an `n` equal to the counter, nothing is written and the report's `applied` is `true`. With `--apply` and a higher `n`, the raise is committed and logged in the system log as `capture_counter_raised`, with the stem as subject and the detail `collection_id= from= to=` (`raise_capture_counter`, `capture_counter.py`). +- **Preview digests.** A capture record lists a RAW master's `_preview.jpg` beside the master, as an entry with the role `_preview` (`single_preview`, `left_preview`, `right_preview`, or `cam_preview` with three or more cameras), its `relative_path`, `bytes`, `mimetype: "image/jpeg"`, `sha256` and `rotate_deg`, when the sidecar exists at the time the record is written (`_preview_file`, `backend/capture/manifestHandler.py`). For previews captured before that, `python -m app.core.image_upload backfill-preview-digests [--apply]` computes each one's sha256 from the file on disk and appends a `preview_digest` record to the volume's `metadata/manifest.jsonl`: `{record_type: "preview_digest", capture_id, image_id, files: [{role: "_preview", relative_path, bytes, mimetype, sha256}], computed_at, backfilled: true}`. Existing lines are never rewritten (`backend/app/core/preview_digests.py`). Where the preview has an offsite row, its file is backfilled only while its SHA1 is still the row's `local_sha1`; otherwise it is reported under `sha1_differs`. The report also lists `already_recorded` (a count), `no_capture_id`, `freed`, `missing`, `outside_volume`, `unreadable` and `changed`, and every image of the volume with a RAW master is considered, current or superseded. Without `--apply` nothing is written; with it, `preview_digests_backfilled` is logged in the system log. A stem no volume has prints `error: ...` and exits with `2` (`image_upload.py`). The fixity index reads both kinds of entry, so freeing, the backfill and the capture manifest export find a preview's digest in either (`build_fixity_index`, `backend/app/core/integrity.py`). A `preview_digest` record is not a capture record, and the export bag leaves it out with the relocation records (`integrity.py`; `is_capture_record`, `manifestHandler.py`). +- **Files removed by hand.** `python -m app.core.image_upload mark-freed [--apply]` records as freed each file of the volume that is absent from the card when its verified object is listed, in a fresh listing, with the row's SHA1. It deletes nothing, and records the size the listing gives. An absent file the bucket does not account for is reported under `unaccounted`, with the reason `no_verified_object`, `not_in_bucket`, `listed_without_sha1` or `bucket_sha1_differs`; with `--apply`, a file that came back is reported as `file_reappeared` and a changed row as `changed`. The report is `{filename_stem, collection_id, applied, marked, unaccounted, marked_bytes, manifest}`. With `--apply` it writes an `offsite-freed-.jsonl` run manifest only when it marked something, and logs `volume_freed` with a detail that begins `mark-freed:` only when it marked or left unaccounted anything (`mark_freed`, `backend/app/core/offsite_free.py`; `_RunManifest`; `image_upload.py`). It refuses, with `error: ` and exit code `2`, a stem no volume has, a volume Captua keeps on the unit, and any run while the unit is in offline mode (`mark_freed`). +- **The catalogue dump.** The scheduler runs a dump at each tick until one has been verified on the appliance's local day, and then none until the next day (`needs_run_today`, `catalogue_backup.py`). In each run the backend dumps the catalogue through gzip to a temporary file under `/tmp/`, encrypts it with age to the X25519 public key in `CAPTUA_OFFSITE_DUMP_RECIPIENT`, removes the plaintext, uploads the ciphertext to `///`, checks its SHA1 against the listing, and records `catalogue_backup_verified` in the system log (`remote_dir`; `run_catalogue_backup`). No plaintext dump is uploaded. With no recipient, or a value that is not an `age1...` public key (a private key, `AGE-SECRET-KEY-...`, included), no dump is written (`dump_recipient`), and `upload` refuses any file whose name does not end in `.age` or whose first bytes are not the age header. The unit is given only the public key; a private key in the setting is refused. Each dump's name carries the UTC time to the second and a 24-bit random token, so a retry adds an object rather than writing over one (`_object_name`). An empty tenant disables the dump, as an empty remote does. What `GET /system/catalogue-backup` reports is in section 3. + +### Filename format {#filename-format} + +New captures and uploads are named under exchange contract 1.1, section 3: + +`-img__c.` + +- `` — the volume's `filename_stem` +- `` — the volume's capture number, zero-padded to four digits, from `0001` to `9999`. `take_filename_index` refuses a number above 9999 (`backend/app/core/capture_naming.py`; `MAX_CAPTURE_NUMBER`), and `capture_filename_index` formats the number it is given +- `c` — the camera index (`c0`, `c1`); an upload is always `c0` +- `.` — the file's suffix + +**Example**: `example-vol-003-img_0001_c0.jpg` and `example-vol-003-img_0001_c1.jpg`, the two images of one dual capture. + +`-img_` is the capture event's filename index. Both images of a dual capture carry it, and it is their pair id; a single capture has no pair id (`backend/capture/service.py`). A stem holds at most 27 characters and the number at most four digits, so the index always fits the 36-character `pair_id` column (`RecordImage`, `backend/app/models/record.py`; `backend/app/models/collection.py`). A RAW master's preview is `-img__c_preview.jpg`, in the volume's `previews/` (`preview_sidecar_of`, `backend/app/core/paths.py`). An upload is named `-img__c0` with the client's suffix, lowercased, when it is `.jpg`, `.jpeg`, `.png`, `.tif`, `.tiff` or `.webp`, and otherwise the suffix of its content type; the name the client sent is logged at INFO with the name the file is stored under, and not kept (`_upload_suffix`, `backend/app/api/records.py`). + +`take_filename_index` (`take_filename_index`, `capture_naming.py`) takes one number per capture event or upload, in the transaction that writes the event's images. It passes over a number that a file in the volume's `captures/` or `previews/` already carries, under any suffix and compared case-folded (`capture_name_taken` and `files_carrying`), or whose `-img__c` the volume's `metadata/manifest.jsonl` holds on a complete line, where it does not follow a letter, digit or hyphen, in capture, upload and relocation records alike (`manifest_capture_numbers`), or that an `offsite_objects` key under the volume's stem carries. A key carries a number when its second path segment is exactly the stem and its file name starts with `-img__`, compared without regard to case (`offsite_capture_numbers`), whatever its first segment: the configured tenant, an earlier tenant, or a prefix recorded by `adopt`. `adopt-map` records keys only under the configured tenant (`image_upload.py`). Numbers carried by offsite keys count towards the 100 passed over before the capture is refused, and the refusal's text is the same (`capture_naming.py`). Numbers can be skipped; none is given twice. The refusals are listed in section 3. `capture_image` also refuses a name that a file took after the number was chosen (`capture_image`, `service.py`); that `FileExistsError` reaches the client as `200` with `{success: false, error}`, and the transaction is rolled back (`backend/app/api/cameras.py`). + +Files written before this naming keep their names. Earlier captures are named `YYYYMMDD_HHMMSS_mmm_cX.jpg` (UTC date, time, milliseconds and camera index, for example `20260109_143652_123_c0.jpg`), and earlier uploads ``. The startup migration keeps every name except on a clash, when it inserts `_img` before the suffix (`20260109_143652_123_c0_img42.jpg`), then `_2`, `_3` and so on if that name is taken too (`_suffixed_stems`, `backend/app/core/volume_layout.py`). + +### Data flow {#data-flow} + +``` +┌─────────────────┐ +│ API Client │ (Frontend / cURL / Python) +└────────┬────────┘ + │ POST /cameras/capture + ▼ +┌──────────────────────┐ +│ FastAPI Endpoint │ cameras.py +│ - Validates request │ +│ - Checks auth/role │ +│ - Runs the refusals │ +│ - Takes the name │ +│ -img_ │ +└────────┬─────────────┘ + ▼ +┌──────────────────────────────────┐ +│ Capture Service │ capture/service.py +│ - Takes the endpoint's config, │ - Uses CAMERA_BACKEND: +│ calibration from the registry │ picamera2, subprocess, +│ │ gphoto2 or chdk +│ │ - Applies camera settings +│ - Captures image to: │ +│ /var/lib/dtk/projects// │ +│ captures/ │ +│ - Appends the capture record to │ +│ /metadata/manifest.jsonl│ +└────────┬─────────────────────────┘ + ▼ +┌──────────────────────────────────┐ +│ Metadata Extraction │ PIL / EXIF +│ - Image dimensions │ +│ - EXIF tags, as one string │ +│ - White balance of the config │ +└────────┬─────────────────────────┘ + ▼ +┌──────────────────────────────────┐ +│ Create Database Records │ SQLAlchemy ORM +│ - Record (unless a retake) │ +│ - RecordImage (one per file) │ +│ - CameraSettings (capture cfg) │ +│ - ExifData (image metadata) │ +└────────┬─────────────────────────┘ + ▼ +┌──────────────────────────────────┐ +│ PostgreSQL Database │ +│ - Image metadata stored │ +│ - Linked to record + volume │ +└──────────────────────────────────┘ +``` + +A dual capture takes the same path through `POST /cameras/capture/dual`, with one capture number for both images (`trigger_dual_capture`, `cameras.py`; `dual_capture_image`, `capture/service.py`). + +### Database relationships {#database-relationships} + +``` +Record (title, capture_mode, project_id, collection_id) + └─> RecordImage[] (file_path, filename, format, role) + ├─> CameraSettings (camera_model, white_balance, lens_model) + ├─> ExifData (raw_exif, datetime_original, GPS) + └─< OffsiteObject[] (object_key, kind; record_image_id ON DELETE SET NULL) + +Project (name, description) + └─> Record[] + └─> Collection[] + ├─> Record[] + └─> Collection[] (nested sub-collections) +``` + +Deleting a record deletes its images (`Record.images`, `cascade="all, delete-orphan"`, and `record_images.record_id` `ON DELETE CASCADE`), and an image's `CameraSettings` and `ExifData` go with it. `Project.collections` and `Collection.child_collections` are delete-orphan. `records.project_id` and `records.collection_id` are `ON DELETE SET NULL` (`backend/app/models/record.py`; `project.py`; `collection.py`). An `offsite_objects` row outlives its image (Offsite copies, above). + +### Performance {#performance} + +Measured on the bench, July 2026, on a Pi 5. The picamera2 figures are at the medium preset; the presets do not apply to gphoto2, which shot at the settings of the camera bodies (see the storage note below). The `chdk` backend has not been measured. + +**Dual capture, seconds per pair:** + +| Backend | Measured on the bench, July 2026 | Note | +|---|---|---| +| gphoto2 (Canon EOS 1500D ×2) | ~4 s | | +| picamera2 (IMX519 ×2) | 7–8 s | too slow for production; NEH-173 tracks the fix | + +Both fire the two cameras in parallel (a thread pool with a 20 ms stagger, `dual_capture_image`, `capture/service.py`). The picamera2 and gphoto2 backends lock per camera index rather than globally, so the cost is per-capture work and not serialisation. The `chdk` backend locks per camera body, not per index (`capture/backends/chdk_backend.py`). + +**Throughput** follows from the above: roughly 900 pages an hour on picamera2 and 1,800 on gphoto2, at two pages per capture. These are ceilings: they leave out page turning, which takes most of the time in practice. + +**Storage, picamera2 only:** at the medium preset, paired JPEGs measured on the bench, July 2026, at **560–780 KB each**, so 100 pages take roughly 56–78 MB. + +This figure does not apply to gphoto2. No file sizes were measured on the DSLR path, and the resolution presets do not apply to it. The gphoto2 backend ignores the picamera2 fields of `CameraConfig` and the presets; before each capture it applies ISO, shutter speed, aperture and image format when the configuration sets them, always turns the flash off, and otherwise shoots at the body's own settings (`apply_dslr_config` and `capture_image()`, `capture/backends/gphoto2_backend.py`). Storage for a DSLR unit cannot be sized from the number above. The low and high picamera2 presets have not been measured. + +--- + +## 6. Code examples {#code-examples} + +### Complete workflow: registration to gallery {#complete-workflow} + +```python +import requests + +BASE_URL = "http://localhost:8000" + +# 1. Register first user (becomes admin). This works as written in development +# with BOOTSTRAP_TOKEN empty; elsewhere pass +# headers={"X-Bootstrap-Token": ""}. +print("1. Registering user...") +user_resp = requests.post( + f"{BASE_URL}/auth/register", + json={ + "username": "john_doe", + "email": "john@example.com", + "password": "secure_password_123" + } +) +user = user_resp.json() +print(f" Registered: {user['username']} (role: {user['role']})") + +# 2. Login +print("\n2. Logging in...") +login_resp = requests.post( + f"{BASE_URL}/auth/login", + json={"username": "john_doe", "password": "secure_password_123"} +) +token = login_resp.json()["access_token"] +headers = {"Authorization": f"Bearer {token}"} + +# 3. Get current user role (frontend uses this for dashboard routing) +me_resp = requests.get(f"{BASE_URL}/users/me", headers=headers) +me = me_resp.json() +print(f" Role: {me['role']}") + +# 4. Create project (admin only) +print("\n4. Creating project...") +project_resp = requests.post( + f"{BASE_URL}/projects/", + headers=headers, + json={ + "name": "Book Digitization", + "description": "Scanning historical books" + } +) +project = project_resp.json() +print(f" Project: {project['name']} (ID: {project['id']})") + +# A capture must go into a volume with a file name stem (409 otherwise). +volume_resp = requests.post( + f"{BASE_URL}/collections/", + headers=headers, + json={ + "name": "Volume 1", + "project_id": project['id'], + "filename_stem": "book-digitization-001" + } +) +volume = volume_resp.json() +print(f" Volume: {volume['name']} (ID: {volume['id']})") + +# 5. List devices +print("\n5. Listing cameras...") +devices_resp = requests.get(f"{BASE_URL}/cameras/devices", headers=headers) +devices = devices_resp.json() +if devices: + for dev in devices: + status = "calibrated" if dev['calibrated'] else "needs calibration" + print(f" [{dev['index']}] {dev['model']} - {status}") +else: + print(" No cameras detected (run on Raspberry Pi)") + +# 6. Capture image (creates RecordImage automatically) +print("\n6. Capturing image...") +capture_resp = requests.post( + f"{BASE_URL}/cameras/capture", + headers=headers, + json={ + "project_name": "Book Digitization", + "collection_id": volume['id'], + "camera_index": 0, + "resolution": "medium" + } +) +capture_result = capture_resp.json() +if capture_resp.status_code != 200: + # Refused before any camera is triggered: 409 for no volume or no stem, 404 or 422 otherwise. + print(f" Capture refused ({capture_resp.status_code}): {capture_result['detail']}") +elif capture_result['success']: + print(f" Captured: {capture_result['file_path']}") +else: + print(f" Capture failed: {capture_result.get('error')}") + + # Fallback: create record manually + rec_resp = requests.post( + f"{BASE_URL}/records/", + headers=headers, + json={ + "title": "Ancient Manuscript", + "capture_mode": "single", + "author": "Unknown Scribe", + "date": "1500-01-01", + "collection_id": volume['id'] + } + ) + rec = rec_resp.json() + print(f" Created record: {rec['title']} (ID: {rec['id']})") + +# 7. List records (gallery) +print("\n7. Fetching gallery...") +list_resp = requests.get( + f"{BASE_URL}/records/", + headers=headers, + params={"limit": 50} +) +records = list_resp.json() +print(f" Total records: {len(records)}") +for r in records[:3]: + print(f" - {r['title']}: {r['capture_mode']}") + +print("\nWorkflow complete!") +``` + +--- + +### Configuration page example {#configuration-page-example} + +```python +def configuration_page_flow(token): + """Flow for the configuration/setup page: cameras and calibration.""" + headers = {"Authorization": f"Bearer {token}"} + + # Step 1: Get available cameras + devices = requests.get(f"{BASE_URL}/cameras/devices", headers=headers).json() + print(f"Devices: {len(devices)} found") + + # Step 2: Run calibration if needed + if devices and not devices[0]['calibrated']: + cal_resp = requests.post( + f"{BASE_URL}/cameras/calibrate", + headers=headers, + json={"camera_index": 0, "resolution": "high"} + ) + result = cal_resp.json() + if result['success']: + print(f"Calibrated: lens_position={result['lens_position']}") +``` + +--- + +### Live scan page example {#live-scan-page-example} + +```python +def live_scan_workflow(token, project_name, collection_id): + """Workflow for the live scan page: capture → auto-save → optional metadata update. + + collection_id must name a volume that has a filename_stem: a capture + without one, or into a volume without a stem, is refused with 409 before + any camera is triggered (_refuse_capture_without_volume_or_stem, cameras.py). + _resolve_capture_target then resolves the path from the volume and never + reads project_name (cameras.py). + """ + headers = {"Authorization": f"Bearer {token}"} + + # 1. Get cameras + devices = requests.get(f"{BASE_URL}/cameras/devices", headers=headers).json() + if not devices: + print("No cameras detected") + return + selected = devices[0] + print(f"Selected: [{selected['index']}] {selected['model']}") + + # 2. Capture (automatically creates RecordImage, CameraSettings, ExifData) + capture_resp = requests.post( + f"{BASE_URL}/cameras/capture", + headers=headers, + json={ + "project_name": project_name, + "collection_id": collection_id, + "camera_index": selected['index'], + "resolution": "medium" + } + ) + result = capture_resp.json() + if capture_resp.status_code != 200: + print(f"Capture refused ({capture_resp.status_code}): {result['detail']}") + return + if not result['success']: + print(f"Capture failed: {result['error']}") + return + print(f"Captured: {result['file_path']}") + + # 3. Update the metadata of the record this capture created. + # Use record_id from the capture response — do NOT list records and + # take the first. An unfiltered GET /records/ orders by id ASCENDING + # (see list_records in records.py), so `limit=1` returns the OLDEST + # record in the database and patching it overwrites an unrelated page. + # With ?collection_id=N the order is sequence-then-id in the same + # function, so you get whatever the operator ranked first — also not + # your capture. + rec_id = result.get('record_id') + if rec_id: + update_resp = requests.patch( + f"{BASE_URL}/records/{rec_id}", + headers=headers, + json={ + "title": "Page 1 of Ancient Manuscript", + "author": "Unknown Scribe" + } + ) + print(f"Updated: {update_resp.json()['title']}") +``` + +--- + +### Gallery page example {#gallery-page-example} + +```python +def gallery_view(token): + """Display all captured records grouped by capture mode.""" + headers = {"Authorization": f"Bearer {token}"} + + records = requests.get( + f"{BASE_URL}/records/", + headers=headers, + params={"limit": 100} + ).json() + + print(f"Total Records: {len(records)}\n") + + # Group by capture mode ("single" or "dual") + by_mode = {} + for rec in records: + by_mode.setdefault(rec['capture_mode'], []).append(rec) + + for mode, recs in sorted(by_mode.items()): + print(f"\n{mode.upper()} ({len(recs)} items)") + print("-" * 60) + for rec in recs[:5]: + print(f" - {rec['title']}") + print(f" Author: {rec.get('author', 'N/A')}") + print(f" Images: {len(rec.get('images', []))}") +``` + +--- + +## 7. Frontend integration {#frontend-integration} + +### Authentication flow {#authentication-flow} + +The browser app keeps its session in an httpOnly cookie, `dtk_session`, that +the backend sets at login (`set_session_cookie`, `auth.py`): `HttpOnly`, +`SameSite=Strict`, `Path=/`, a `Max-Age` equal to `ACCESS_TOKEN_EXPIRE_SECONDS`, +and `Secure` only when the browser's request was HTTPS: nginx's +`X-Forwarded-Proto` says `https`, or, without that header, the request's own +scheme is `https` (`_request_is_https`, `auth.py`). nginx listens on +port 80 only, so on the appliance the cookie has no `Secure` flag. No script +on the page can read the cookie, and no URL carries the token. Every authenticated route reads the +`Authorization: Bearer` header first and the cookie second; the backend reads no +token from the query string (`_session_token`, `auth.py`). The steps below +are the browser app's flow. + +API clients and scripts do not use the cookie. They log in without the +`X-Requested-With` header, receive the token in the body, and send it as +`Authorization: Bearer` on every request: the Swagger UI steps and the cURL and +Python examples in sections 4 and 6 work this way. + +``` +1. GET /auth/setup/status (no auth) + Response: { needs_setup: boolean } + → true = no user exists yet; route to first-run setup + false = route to login + The frontend calls this on the unauthenticated path, from the welcome + and setup routes. When a user is saved in localStorage (auth_user), the + root route redirects to /dashboard without calling it + (routes/+page.svelte), + and the dashboard layout then checks the session (step 5). + +2. POST /auth/register + Request: { username, email, password } + Response: { id, username, email, role, is_active, created_at } + Note: first user becomes admin, all others become reviewer. + Note: outside a development APP_ENV, and in development too when + BOOTSTRAP_TOKEN is set, the first registration needs the + X-Bootstrap-Token header (401 without it, 503 when the unit has + no BOOTSTRAP_TOKEN configured; _authorize_bootstrap, auth.py). + Note: PUBLIC ONLY FOR THE FIRST USER. Once one account exists this + endpoint requires an authenticated admin — 401 without a token, + 403 for a non-admin. Account creation is admin-controlled: an + admin submits the new user's credentials directly. There is no + invitation or token flow. Role is ignored if sent; elevate + afterwards with PATCH /auth/users/{id}/role. + +3. POST /auth/login + Request: { username, password } + Headers: { X-Requested-With: XMLHttpRequest } + Response: { access_token: null, token_type: "cookie" } + and Set-Cookie: dtk_session= + The body carries a token only when the request lacks X-Requested-With, + as an API client's does: { access_token, token_type: "bearer" }. The + cookie is set either way (auth.py). The frontend sends every + fetch with credentials: 'include' and X-Requested-With, and with no + Authorization header (sessionRequestInit, api.ts); authApi.login() + keeps nothing from the body (api.ts). + +4. Nothing is stored but the user. After step 5 the login page keeps the + user in localStorage under auth_user (authStore.setSession, + stores/auth.ts; routes/(auth)/login/+page.svelte). That + copy only lets the routes decide without waiting for the backend; the + cookie is what authenticates. + +5. GET /users/me + Sent with the cookie (credentials: 'include') + Response: { id, username, role, ... } + The login page calls it right after step 3. The dashboard layout calls + it each time the layout mounts to check that the backend still accepts the cookie, + and there a 401 or 403 clears the saved user and sends the browser to + /login (routes/(dashboard)/+layout.svelte). + → Use role to determine which UI sections to show: + - admin: full dashboard + user management panel + - operator: full dashboard, no user management + - reviewer: cannot create or edit records, projects or collections, + BUT is not passive — reviewers drive the QA workflow, annotating + records and moving them in_review -> approved / rejected + (approval: STATUS_TRANSITIONS, schemas/record.py; + rejection is its own route, POST /records/{id}/reject, reject_record in records.py), and may trigger a BagIt export + (export_collection_bagit, collections.py). They cannot send a + record back to captured: rejected -> captured is operator/admin, and + there is no approved -> captured for anyone -- an approved record goes + back to in_review first (reviewer/admin). + Note each router defines its own allow_read_only — the one in + records.py governs records; the one in auth.py governs only auth + endpoints. + +6. Every later request carries the cookie, which the browser attaches + to fetch calls made with credentials: 'include', and by itself to + requests and download links, so thumbnail, file, preview and + export URLs carry no token. A cookie-authenticated request whose method + is not GET, HEAD or OPTIONS must also carry X-Requested-With, or the + backend refuses it with 403 "Missing X-Requested-With header" + (auth.py). A cross-site page can add that header only + through a CORS preflight, which the backend answers only for the origins + in CORS_ORIGINS; with SameSite=Strict the browser also leaves the cookie + off any request a cross-site page starts. While a user is saved, a 401 + on any route but /auth/login and /auth/password-reset clears the saved + user and sends the browser to /login (isDeadSession, api.ts). + +7. Before expiry (8 hours by default — ACCESS_TOKEN_EXPIRE_SECONDS), refresh: + POST /auth/refresh + Sent with the cookie and X-Requested-With + Response: { access_token: null, token_type: "cookie" } + and a new dtk_session cookie + A request with a Bearer header gets { access_token, token_type: + "bearer" } instead, and the backend sets no cookie (auth.py). + The frontend defines authApi.refreshSession() (api.ts), but no + page calls it, so a browser session ends at most + ACCESS_TOKEN_EXPIRE_SECONDS after login. + +8. On logout: + POST /auth/logout + Headers: { X-Requested-With: XMLHttpRequest } + Response: 204, with a Set-Cookie that clears dtk_session + Only the backend can remove an httpOnly cookie. The route needs no + session, so an expired session can still log out, and refuses a request + without X-Requested-With with 403 (auth.py). authApi.logout() + calls it, waits at most 5 seconds (LOGOUT_TIMEOUT_MS, api.ts), then clears + auth_user whatever the answer (api.ts); when the backend cannot + be reached, the cookie stays in the browser until its Max-Age runs out. + Logout clears only the cookie: the backend keeps no revocation list, so + a token copied out of the cookie is accepted until its exp. + The frontend removes an access_token key left in localStorage by a + build before NEH-61, and auth_user with it, at the next load, and the + browser starts logged out (stores/legacy-token.ts; + readInitialUser, stores/auth.ts). +``` + +--- + +The three capture-side pages — system configuration at `/dashboard/config`, capture at `/live-preview`, and the collection view at `/dashboard/projects/{projectId}/collections/{collectionId}` — used to be described here with the API calls each makes. The lists were wrong in substance when they were checked, as the endpoint table above was. The frontend source under `frontend/src/routes/` is the reference for what a page calls; the sections below cover only what the backend enforces regardless of which page is calling. + +--- + +### Projects and volumes page {#projects-volumes-page} + +**API Calls:** +1. `GET /projects/` — List projects (reviewer+) +2. `POST /projects/` — Create project (admin only) +3. `POST /projects/{id}/initialize` — Init filesystem (operator+) +4. `GET /collections/?project_id={id}` — List top-level collections (reviewer+) +5. `GET /collections/{id}/hierarchy` — Full collection tree (reviewer+) +6. `POST /collections/` — Create a volume (operator+, admin only in fisqua mode; `filename_stem` required; `project_id` ignored while projects are hidden — section 3, The unit's mode) +7. `GET /projects/{id}/records` — List project records (reviewer+) +8. `POST /imports/digitisation-list` — Import a digitisation list (operator+, admin only in fisqua mode; while projects are shown, a list whose project does not exist, admin only) +9. `GET /imports/digitisation-list/{list_id}/report` — Latest stored import report (reviewer+) +10. `GET /imports/digitisation-lists` — Imported lists, with their items and the volume each item names (reviewer+) +11. `PUT /imports/digitisation-lists/{list_id}/items/{position}/done` — Mark an imported list's item done, or remove the mark (admin or reviewer; not operator) + +--- + +### User management page (admin only) {#user-management-page} + +**API Calls:** +1. `GET /auth/users` — List all users +2. `PATCH /auth/users/{id}/role` — Promote/demote user +3. `PATCH /auth/users/{id}/active` — Activate/deactivate user +4. `DELETE /auth/users/{id}` — Delete user + +--- + +## 8. Configuration {#configuration} + +### Environment variables (`.env`) {#environment-variables} + +```env +# Database — the backend builds its connection URL from these +DATABASE_USER=user +DATABASE_PASSWORD=password +DATABASE_HOST=db +DATABASE_PORT=5432 +DATABASE_NAME=digitization_toolkit + +# Optional, Alembic only: if set, migrations use this verbatim instead of +# building the URL from the DATABASE_* values above (alembic/env.py). +# The application itself never reads it. Note the +psycopg driver — a bare +# postgresql:// URL selects psycopg2, which is not installed. +DATABASE_URL=postgresql+psycopg://user:password@localhost:5432/digitization_toolkit + +# Security +# Anything other than dev, development, test, testing or local requires a real +# SECRET_KEY and DATABASE_PASSWORD, and the bootstrap token for the first user. +APP_ENV=development +SECRET_KEY=change-this-to-a-random-string +# Protects first-user registration (X-Bootstrap-Token); generated per unit. +BOOTSTRAP_TOKEN= +ACCESS_TOKEN_EXPIRE_SECONDS=28800 +``` + +The settings the backend reads are declared in `Settings`, `backend/app/core/config.py`, which is the authoritative list. The repository root `.env.example` lists most of them; it leaves out `CAPTUA_LOG_LEVEL`, `CAPTUA_OFFSITE_HOLD_FILE`, `CAPTUA_FISQUA_BASE_URL`, `CAPTUA_FISQUA_RETRY_BASE`, `CAPTUA_FISQUA_RETRY_MAX`, `CAPTUA_FISQUA_POLL_INTERVAL` and `CAPTUA_FISQUA_TIMEOUT`, which keep their defaults unless set. The block above shows only the settings relevant to the API. + +The server host and port are not configurable by environment: the pixi `start` and `dev` tasks hardcode `--host 0.0.0.0 --port 8000`, so the native backend listens on every interface. + +What keeps port 8000 off the venue LAN is the host firewall installed by `scripts/setup-firewall.sh`: ufw defaults to deny-inbound and allows 8000/tcp only from the appliance's own compose network (`172.30.0.0/24`), so Nginx can reach the backend and nothing else on the LAN can. Nginx itself is a reverse proxy, not a filter — it restricts nothing on its own. Container ports are handled separately, because Docker's iptables chains sit ahead of ufw's — but only some are loopback-bound. `docker-compose.yml` binds the database to `127.0.0.1:5432` and the production frontend to `127.0.0.1:3000`, while the backend service publishes `8000:8000` and the dev overlay publishes `5173:5173`, both on all interfaces. On a development machine on an untrusted network, those two are exposed. + +Changing the address the backend actually binds to, as opposed to filtering access to it, means editing the uvicorn invocation in `backend/pixi.toml`. + +### `CAPTUA_` and `DTK_` names {#captua-and-dtk-names} + +Every backend setting read under a `DTK_` name is also read under the `CAPTUA_` name with the same suffix: `CAPTUA_OFFSITE_TENANT` for `DTK_OFFSITE_TENANT`, and so on. Each such field of `Settings` declares both names through `_names` (`_names`, `app/core/config.py`). There are twenty-five suffixes: `DATA_DIR`, `LOG_DIR`, `LOG_LEVEL`, `EXPORTS_DIR`, `MAX_UPLOAD_BYTES`, `OFFSITE_REMOTE`, `OFFSITE_DB_PREFIX`, `OFFSITE_TENANT`, `OFFSITE_READ_REMOTE`, `OFFSITE_DUMP_RECIPIENT`, `OFFSITE_BWLIMIT`, `RCLONE_BIN`, `RCLONE_CONFIG`, `PG_DUMP_COMMAND`, `OFFSITE_BACKUP_DELAY`, `OFFSITE_BACKUP_INTERVAL`, `OFFSITE_HOLD_FILE`, `FISQUA_ENV`, `FISQUA_BASE_URL`, `FISQUA_TOKEN`, `FISQUA_RETRY_BASE`, `FISQUA_RETRY_MAX`, `FISQUA_POLL_INTERVAL`, `FISQUA_TIMEOUT` and `FISQUA_ROTATE_DEG` (`DATA_DIR`, `app/core/config.py`). The suffix is the variable's, not always the setting's: `CAPTUA_EXPORTS_DIR` sets `EXPORTS_ROOT` (`EXPORTS_ROOT`, `app/core/config.py`), and the table below gives the setting of each offsite and Fisqua name, such as `OFFSITE_BACKUP_DELAY_SECONDS` for `DTK_OFFSITE_BACKUP_DELAY`. Settings without a prefix (`APP_ENV`, `DATABASE_*`, `PROJECTS_ROOT`, `CAMERA_BACKEND`, `SECRET_KEY`, `BOOTSTRAP_TOKEN`, `ACCESS_TOKEN_EXPIRE_SECONDS`, `CORS_ORIGINS` and `APP_VERSION`) have one name only. + +When both names of a setting are set, the `CAPTUA_` value is used, wherever each is set: a `CAPTUA_` name in `.env` or `offsite.env` wins over a `DTK_` name in the process environment. Within each family the process environment wins over the files, and `offsite.env` over `.env` (`settings_customise_sources`, `app/core/config.py`). So a `CAPTUA_OFFSITE_TENANT` in `.env` overrides the `DTK_OFFSITE_TENANT` that `scripts/provision-rclone.sh` writes to `offsite.env`. The script writes `DTK_` names only, because a rollback restores code that reads only those (`app/core/config.py`). A `CAPTUA_` name set to an empty value, or written in an env file as a bare name with no `=`, counts as unset, as it does for `scripts/captua-env.sh`: the `DTK_` value is read instead, or the default when neither name has a value. The rule is applied to each file before the files are merged, so an empty `CAPTUA_` line in `offsite.env` does not replace a `CAPTUA_` value in `.env` (`_is_unset_new_name`, `app/core/config.py`; `_NewNamesDotEnv`). A value of spaces is a value when it is set in the process environment or quoted in a file; python-dotenv strips an unquoted value, so `CAPTUA_OFFSITE_TENANT= ` in a file counts as empty. An empty `DTK_` value is read as it is. For a text setting the empty value is used. The backend cannot read an empty value into a number or boolean setting: for `MAX_UPLOAD_BYTES`, `OFFSITE_BACKUP_DELAY`, `OFFSITE_BACKUP_INTERVAL`, `FISQUA_RETRY_BASE`, `FISQUA_RETRY_MAX`, `FISQUA_POLL_INTERVAL` and `FISQUA_TIMEOUT` (numbers) and `FISQUA_ROTATE_DEG` (a boolean), an empty `DTK_` value with no `CAPTUA_` value makes `Settings()` raise a validation error when `app.core.config` is imported, and the backend cannot be started (`app/core/config.py`). + +At startup the backend logs at `INFO` which `CAPTUA_` and `DTK_` names are set, by the same rule, so an empty `CAPTUA_` name is not listed, and logs a `WARNING` for each setting whose two names are set to different values, naming the `CAPTUA_` one as the one used. It logs names, never values (`log_environment_names`, `app/core/config.py`, called in `app/main.py`). + +`CAPTUA_SKIP_SCHEMA_CHECK` is read apart from `Settings`, from the process environment only. When it is set to a value that is not empty, it is used, and `DTK_SKIP_SCHEMA_CHECK` is read only when it is unset or empty (`_skip_requested`, `app/core/schema.py`). + +--- + +### Offsite copy variables {#offsite-variables} + +The offsite image upload, the catalogue dump, and restore (section 3 and section 5, Offsite copies) are configured by these variables. The backend reads them from `.env` and from `/var/lib/dtk/offsite.env`; a key in `offsite.env` wins over the same key in `.env`, and a variable in the backend's process environment wins over both (`Settings`, `app/core/config.py`). `scripts/provision-rclone.sh` writes `offsite.env` whole, with up to eight keys: `DTK_RCLONE_BIN` always, and `DTK_RCLONE_CONFIG`, `DTK_OFFSITE_REMOTE`, `DTK_OFFSITE_READ_REMOTE`, `DTK_OFFSITE_TENANT`, `DTK_OFFSITE_DUMP_RECIPIENT`, `DTK_FISQUA_TOKEN` and `DTK_FISQUA_ENV` each only when the run was given it or found it already recorded there. A key it leaves out overrides nothing in `.env` (`write_offsite_env`, `scripts/provision-rclone.sh`). The tenant is given with `--tenant`, and replacing a recorded tenant also needs `--change-tenant`; the recipient is given with `--dump-recipient`, and the Fisqua environment with `--fisqua-env production` or `--fisqua-env staging` (`scripts/provision-rclone.sh`). The script takes the token only from a `FISQUA_TOKEN=` line in the key file named by `DTK_OFFSITE_KEY_FILE`; it is never printed, and it is refused unless it is exactly 64 lowercase hexadecimal characters (`valid_fisqua_token`). It is not taken under `--advisory`, the mode in which the update script calls this one, and it is refused when no tenant or no Fisqua environment is given or recorded (`scripts/provision-rclone.sh`). The read remote is written when a read key, `READ_KEY_ID` and `READ_APP_KEY`, is supplied in the key file named by `DTK_OFFSITE_KEY_FILE`, as a second section of the same rclone config, named `b2read`. A read remote already recorded is carried forward. It is refused when it names the upload remote, and, when the upload remote is kept, when it is on another bucket; it is dropped when it is on another bucket than an upload remote this run writes, or names a section the config this run wrote does not hold (`reconcile_recorded_read_remote`). The script checks the tenant and the dump recipient by the rules the backend applies to them, checks every value against its own character classes, and refuses to write a value shaped like an age private key. `.env.example` lists all of them. The script and `.env.example` use the `DTK_` names, so that a rollback to code that reads only those still works; the table below gives the `CAPTUA_` name of each, which the backend reads first and which wins when both are set. + +| Variable | Setting | Default | Meaning | +|---|---|---|---| +| `CAPTUA_OFFSITE_REMOTE` | `OFFSITE_REMOTE` | empty | The rclone destination, a remote and a bucket (`b2unit:`). Empty disables the image upload and the dump. | +| `CAPTUA_OFFSITE_TENANT` | `OFFSITE_TENANT` | empty | The tenant prefix every object is keyed under, and Fisqua's tenant slug: 1 to 63 lowercase letters, digits and single hyphens, starting with a letter, and none of `platform`, `www`, `api`, `admin` or `app`. Empty disables the image upload and the dump; any other value that is not a prefix is the `misconfigured` state (section 3). | +| `CAPTUA_OFFSITE_READ_REMOTE` | `OFFSITE_READ_REMOTE` | empty | A second rclone remote and bucket whose key may read objects under the tenant prefix. Only restore reads through it; empty, the restore route answers `409`. | +| `CAPTUA_OFFSITE_DUMP_RECIPIENT` | `OFFSITE_DUMP_RECIPIENT` | empty | The age X25519 public key (`age1...`) every catalogue dump is encrypted to. Empty or invalid, no dump is written. | +| `CAPTUA_OFFSITE_DB_PREFIX` | `OFFSITE_DB_PREFIX` | `db-backups` | The dump's directory under the tenant prefix. | +| `CAPTUA_OFFSITE_BWLIMIT` | `OFFSITE_BWLIMIT` | `750k` | rclone's `--bwlimit` for every offsite transfer. | +| `CAPTUA_OFFSITE_BACKUP_DELAY` | `OFFSITE_BACKUP_DELAY_SECONDS` | `300` | Seconds from the start to each schedule's first run. | +| `CAPTUA_OFFSITE_BACKUP_INTERVAL` | `OFFSITE_BACKUP_INTERVAL_SECONDS` | `1800` | Seconds between runs. | +| `CAPTUA_OFFSITE_HOLD_FILE` | `OFFSITE_HOLD_FILE` | empty, meaning `offsite-hold` in `CAPTUA_DATA_DIR` | While this file exists, no image or dump is uploaded and a free is refused (section 3, The upload hold). | +| `CAPTUA_FISQUA_ENV` | `FISQUA_ENV` | empty | `production` or `staging`, which picks the host `.fisqua.org` or `.staging.fisqua.org`. Empty, Fisqua is not configured (section 3, Delivery to Fisqua). | +| `CAPTUA_FISQUA_BASE_URL` | `FISQUA_BASE_URL` | empty | Replaces the host, for tests and development; used only when `https://`, or `http://` to a loopback host. | +| `CAPTUA_FISQUA_TOKEN` | `FISQUA_TOKEN` | empty | This unit's token, 64 lowercase hexadecimal characters. Held as a secret; never logged or returned. | +| `CAPTUA_FISQUA_RETRY_BASE` | `FISQUA_RETRY_BASE_SECONDS` | `300` | Seconds before a failed send is tried again; doubled after each further failure. | +| `CAPTUA_FISQUA_RETRY_MAX` | `FISQUA_RETRY_MAX_SECONDS` | `21600` | The longest backoff between attempts; a longer `Retry-After` from Fisqua wins. | +| `CAPTUA_FISQUA_POLL_INTERVAL` | `FISQUA_POLL_INTERVAL_SECONDS` | `600` | Seconds between status polls. | +| `CAPTUA_FISQUA_TIMEOUT` | `FISQUA_TIMEOUT_SECONDS` | `60` | Read and write timeout of each call to Fisqua, in seconds; connecting has 10. | +| `CAPTUA_FISQUA_ROTATE_DEG` | `FISQUA_ROTATE_DEG` | `false` | When `true`, each image of the capture manifest with a recorded `rotate_deg` carries it as `rotateDeg`; when `false`, no image carries `rotateDeg`. The manifest declares contract `1.9` either way (section 3). Part of the configuration fingerprint (`config_fingerprint`, `app/core/fisqua_outbox.py`). | +| `APP_VERSION` | `app_version` | unset | Overrides the release read from `VERSION` (section 3, Version reporting). | +| `CAPTUA_RCLONE_BIN` | `RCLONE_BIN` | `rclone` | The rclone executable. | +| `CAPTUA_RCLONE_CONFIG` | `RCLONE_CONFIG` | empty | When set, passed to rclone as `--config`. | +| `CAPTUA_PG_DUMP_COMMAND` | `PG_DUMP_COMMAND` | empty | Replaces the default `docker compose exec -T db pg_dumpall` command of the catalogue dump, where the appliance's compose overlay is not one directory up: a development machine, a container, or a host with a PostgreSQL client on `PATH`. | + +The offsite settings are declared in `app/core/config.py` and the Fisqua ones in `CAPTUA_OFFSITE_TENANT` is checked in `configured_tenant` (`configured_tenant`, `app/core/image_upload.py`), `CAPTUA_OFFSITE_DUMP_RECIPIENT` in `dump_recipient` (`dump_recipient`, `app/core/catalogue_backup.py`), and `CAPTUA_RCLONE_CONFIG` in `_rclone_argv` (`_rclone_argv`, `catalogue_backup.py`). + +--- + +### Logging {#logging} + +The backend's own loggers, `app.*` and `capture.*`, write to stderr, which the journal records on the appliance. `CAPTUA_LOG_LEVEL` (setting `LOG_LEVEL`) sets their level and defaults to `INFO`; a value that is not a logging level falls back to `INFO` with a warning (`app/core/config.py`; `configure_logging`, `app/core/logging_setup.py`, called at import in `app/main.py`). Before this, the INFO lines of those loggers, such as the startup `Volume layout:` report, reached no handler. `CAPTUA_LOG_DIR` is a different setting: the folder of the rotating capture logs, which the `capture_service` and `project_manager` loggers keep writing to. + +### CORS configuration {#cors-configuration} + +Allowed origins come from the `CORS_ORIGINS` environment variable, bound in `app/core/config.py` and applied in `app/main.py` (`allow_origins=settings.CORS_ORIGINS`). Set it in `.env` as a JSON array; it defaults to `http://localhost:5173` (Vite dev server) and `http://localhost:3000` (production Node server). + +```env +CORS_ORIGINS=["http://localhost","http://localhost:5173","http://localhost:3000","http://captua.local"] +``` + +Do **not** edit `allow_origins` in `app/main.py` — it reads `settings.CORS_ORIGINS`, so a source edit is overridden by configuration. + +Every origin must be named. The backend refuses to start when `CORS_ORIGINS` contains `*`, in every environment, with a `RuntimeError` (`_guard_cors_origins`, `app/core/config.py`, called when the module is imported). The browser session is a cookie and `app/main.py` allows credentials (`allow_credentials=True`, `app/main.py`); with `*` in the list and credentials allowed, Starlette's `CORSMiddleware` answers each request with that request's own `Origin`, so a page on any site could make credentialed calls to the API. `X-Requested-With`, the header a cookie-authenticated state change must carry (section 7, Authentication Flow), is in `allow_headers`. + +The session cookie is `SameSite=Strict`, so in development the page and the API must be on the same site: open the page on `localhost` when the API is on `localhost`, and on `127.0.0.1` when it is on `127.0.0.1`. The port does not count, so `http://localhost:5173` calling `http://localhost:8000` works. A page on `http://127.0.0.1:5173` calling `http://localhost:8000`, even with that origin in `CORS_ORIGINS`, gets a `200` from the login, but the browser does not store the cookie that the cross-site response sets, or does not send it back, so the next request is refused with `401`. The browser calls the API at `PUBLIC_API_BASE`, or `http://localhost:8000` when it is unset (`frontend/src/lib/api-base.ts`), so a page opened on `127.0.0.1` needs `PUBLIC_API_BASE=http://127.0.0.1:8000`, and `CORS_ORIGINS` must list the page's origin as the browser writes it, `http://127.0.0.1:5173`. + +On the appliance the frontend calls the API at the relative `/api` (`PUBLIC_API_BASE=/api` in `docker-compose.pi.yml`), and nginx on port 80 serves both, so every call is same-origin, whatever name or address the page was opened by, the kiosk's `http://localhost` included. CORS does not come into play there. It matters for the development stack, where the Vite page on calls the backend on and for the code a rollback can restore: before 0.1.0 the frontend called `http://${HOST_IP}/api` and the kiosk opened `http://localhost:3000`, so those origins and the unit's names must stay listed. `setup.sh` and `update.sh` add `http://captua.local` (and keep `http://digitool.local` on a unit renamed from it) through `scripts/provision-hostname.sh`. + +--- + +### Token expiration {#token-expiration} + +Default: 8 hours (28800 seconds), per `ACCESS_TOKEN_EXPIRE_SECONDS` in `app/core/config.py`. Change via `ACCESS_TOKEN_EXPIRE_SECONDS` in `.env`. + +Deactivation does not wait for this: `get_current_user` checks `is_active` on every request (`get_current_user`, `app/api/auth.py`), so a deactivated user is refused on the next call to any route that depends on it. `POST /auth/refresh` and `POST /auth/password-reset` check it too, and refuse a deactivated user with `401` and `"User not found or inactive"` (`auth.py`). + +The session cookie's `Max-Age` is the same number of seconds, so the browser drops the cookie when the token it holds would be refused anyway (`set_session_cookie`, `auth.py`). `POST /auth/logout` clears only the cookie. Tokens are stateless and the backend keeps no revocation list, so a token copied out of the cookie, or one an API client received in a login body, is accepted until its `exp`. What the expiry bounds is how long a token that has left its owner keeps working, so shorten it on units in shared spaces. + +--- + +## 9. Endpoints not described above {#undocumented-endpoints} + +The routes below are in the code and are not discussed elsewhere on this page. The role is the `RoleChecker` each route declares. Request and response schemas are in Swagger UI. + +### auth (`/auth`) {#undocumented-auth} + +| Method | Path | Role | Purpose | +|---|---|---|---| +| `GET` | `/auth/users/{user_id}` | admin | One user by id. | + +### activity (`/activity`) {#undocumented-activity} + +| Method | Path | Role | Purpose | +|---|---|---|---| +| `GET` | `/activity/daily` | admin, operator, reviewer | Images captured and records reviewed on each of the last `days` local days, oldest first, with a zero for a day with no work. | + +### cameras (`/cameras`) {#undocumented-cameras} + +| Method | Path | Role | Purpose | +|---|---|---|---| +| `GET` | `/cameras/devices` | admin, operator, reviewer | The cameras the active backend detects, with hardware id, model and calibration status; an empty list where no camera library is available. | +| `POST` | `/cameras/rescan` | admin, operator | Detects the attached cameras again and closes device sessions that no longer match a port. | +| `POST` | `/cameras/side/{camera_index}` | admin | Writes onto the body's own card which pages it shoots, odd or even. | +| `GET` | `/cameras/capabilities` | admin, operator, reviewer | The capability flags of the active camera backend, which the interface uses to show or hide controls. | +| `GET` | `/cameras/preview/{camera_index}` | admin, operator, reviewer | One live preview frame as JPEG. | +| `DELETE` | `/cameras/preview/tmp` | admin, operator | Deletes preview temporary files left in `/tmp`. | +| `GET` | `/cameras/focus/{camera_index}` | admin, operator, reviewer | The camera's current lens position, in dioptres. | +| `POST` | `/cameras/focus/{camera_index}` | admin, operator | Sets a manual lens position, in dioptres. | +| `POST` | `/cameras/settings/{camera_index}` | admin, operator | Applies live camera controls without a capture. | +| `POST` | `/cameras/calibrate/white-balance` | admin, operator | Runs auto white balance until it converges and saves the gains. | +| `POST` | `/cameras/calibrate/white-balance/manual` | admin, operator | Saves white balance gains sampled from the live preview, with no capture. | +| `GET` | `/cameras/dslr/{camera_index}/settings` | admin, operator, reviewer | The DSLR's ISO, shutter speed, aperture and image format; `501` on a backend without DSLR settings. | +| `PUT` | `/cameras/dslr/{camera_index}/settings` | admin, operator | Applies the DSLR settings given in the body; `501` on a backend without DSLR settings. | +| `PUT` | `/cameras/{camera_index}/orientation` | admin, operator | Saves the clockwise rotation for the body at this index, keyed by its hardware id. | +| `POST` | `/cameras/` | admin, operator | Creates a camera settings row for an image. | +| `GET` | `/cameras/` | admin, operator, reviewer | Lists camera settings rows. | +| `GET` | `/cameras/{id}` | admin, operator, reviewer | One camera settings row. | +| `PUT` | `/cameras/settings/{id}` | admin, operator | Updates a camera settings row. | +| `DELETE` | `/cameras/settings/{id}` | admin, operator | Deletes a camera settings row. | + +### collections (`/collections`) {#undocumented-collections} + +| Method | Path | Role | Purpose | +|---|---|---|---| +| `GET` | `/collections/count` | admin, operator, reviewer | The number of volumes that match the filters. | +| `GET` | `/collections/{collection_id}` | admin, operator, reviewer | One volume. | +| `GET` | `/collections/{collection_id}/status-changes` | admin, operator, reviewer | The status history of the volume's records, newest first, one row per change. | +| `GET` | `/collections/{collection_id}/export/download` | admin, operator, reviewer | The volume's most recent BagIt export, as a zip. | + +### projects (`/projects`) {#undocumented-projects} + +| Method | Path | Role | Purpose | +|---|---|---|---| +| `GET` | `/projects/{project_id}` | admin, operator, reviewer | One project. | +| `POST` | `/projects/{project_id}/remove_record/{rec_id}` | admin, operator | Detaches a record from the project, leaving it with no parent. | +| `GET` | `/projects/{project_id}/members` | admin, operator, reviewer | The project's collaborators: every active admin, and the users added as members. | +| `POST` | `/projects/{project_id}/members` | admin | Adds a user to the project as operator or reviewer. | +| `DELETE` | `/projects/{project_id}/members/{user_id}` | admin | Removes a user from the project. | + +### records (`/records`) {#undocumented-records} + +| Method | Path | Role | Purpose | +|---|---|---|---| +| `GET` | `/records/count` | admin, operator, reviewer | The number of records that match the filters. | +| `GET` | `/records/{rec_id}/annotations` | admin, operator, reviewer | The record's annotations, newest first. | +| `POST` | `/records/{rec_id}/annotations` | admin, operator, reviewer | Adds an annotation, a flagged error or a note, to the record. | +| `DELETE` | `/records/annotations/{annotation_id}` | admin, operator, reviewer | Deletes an annotation; only its creator or an admin may, unless no creator is recorded (section 3). | + +### system (`/system`) {#undocumented-system} + +| Method | Path | Role | Purpose | +|---|---|---|---| +| `GET` | `/system/logs` | admin | Recent system log entries, newest first. | +| `GET` | `/system/integrity` | admin | Checks the database against the image files and the capture manifests, read-only. | +| `GET` | `/system/temperature` | admin, operator, reviewer | The Raspberry Pi's CPU temperature, or `available: false` without `vcgencmd`. | +| `GET` | `/system/storage` | admin, operator, reviewer | The projects path in use and its disk usage. | +| `GET` | `/system/storage/devices` | admin | Removable and non-system partitions that can hold the projects. | +| `POST` | `/system/storage/mount` | admin | Mounts a partition through the system helper. | +| `DELETE` | `/system/storage/mount` | admin | Unmounts a partition Captua mounted, clearing the storage override when it pointed there. | +| `POST` | `/system/storage/activate` | admin | Makes a mounted path the projects root. | +| `DELETE` | `/system/storage/activate` | admin | Returns to the default projects root under the data directory. | +| `POST` | `/system/power` | any signed-in user (`get_current_user`, no role check) | Powers off or reboots the unit; `501` where the helper is not installed. | + +--- + +## 10. Architecture overview {#architecture-overview} + +### Security {#security} +- **Password Hashing**: PBKDF2-HMAC-SHA256 with 600,000 iterations (`PBKDF2_ITERATIONS`, `backend/app/core/security.py`). 100,000 is the *legacy* count, kept only to verify hashes stored before the format carried its own iteration count; login re-hashes those at the current count on the next successful sign-in. +- **Tokens**: HMAC-SHA256 signed, time-based expiration +- **Authentication**: an `Authorization: Bearer` header or, for the browser app, the httpOnly `dtk_session` cookie (`SameSite=Strict`) that login sets; the header wins when a request carries both, and no query parameter is read (`_session_token`, `app/api/auth.py`). A request that carries the cookie and no Bearer header, with a method other than `GET`, `HEAD` or `OPTIONS`, must carry `X-Requested-With`, or it is refused with `403` before its token is checked (CSRF check, `auth.py`) +- **Authorization**: Role-based via `RoleChecker` dependency (`admin`, `operator`, `reviewer`) +- **Bootstrap**: First registered user becomes admin; all others start as reviewer. Outside a development `APP_ENV`, and in development too when `BOOTSTRAP_TOKEN` is set, the first registration needs the unit's `BOOTSTRAP_TOKEN` in the `X-Bootstrap-Token` header, and is refused with `503` while none is configured (`_authorize_bootstrap`, `app/api/auth.py`) +- **User Status**: Inactive users cannot log in: the right password for a deactivated account gets `403` `"User is inactive"` (`login`, `app/api/auth.py`) + +### Database {#database} +- **ORM**: SQLAlchemy 2.0 +- **Engine**: PostgreSQL +- **Relationships**: Proper foreign keys with cascading deletes +- **Timestamps**: not uniform. Most models carry `created_at`, but `ProjectMember` uses `added_at` instead (`ProjectMember`, `models/project_member.py`). For modification times, `Record` has `modified_at` (`models/record.py`), `Collection` has `updated_at` (`Collection`, `models/collection.py`), and `UnitSettings` has `updated_at` and `updated_by` (`models/unit_settings.py`); no other model tracks one +- **Migrations**: Alembic. Automatic only in the dev container, whose command is `alembic upgrade head && uvicorn …`. Production runs `pixi run start`, a bare uvicorn; the Pi is migrated by `scripts/update.sh`, and `assert_schema_at_head()` fails startup if that has not happened + +### Validation {#validation} +- **Schemas**: Pydantic v2 for all inputs/outputs +- **Type Safety**: Full type hints throughout +- **Email Validation**: A basic format regex, deliberately — `pydantic[email]` is excluded to keep the appliance offline-capable (`UserCreate`, `schemas/user.py`) + +### Extensibility {#extensibility} +- **Custom Attributes**: JSON string for free-form record metadata +- **Camera Integration**: libcamera/picamera2 with hardware detection +- **Camera Registry**: Persistent calibration storage across system reboots +- **Dual Camera Support**: Synchronized captures for book scanning +- **Resolution Profiles**: Three DPI-optimized presets (low/medium/high) + +## 11. Support and resources {#support-resources} + +- **FastAPI Documentation**: https://fastapi.tiangolo.com/ +- **SQLAlchemy Documentation**: https://docs.sqlalchemy.org/ +- **Pydantic Documentation**: https://docs.pydantic.dev/ +- **Libcamera Documentation**: https://libcamera.org/ +- **Picamera2 Documentation**: https://datasheets.raspberrypi.com/camera/picamera2-manual.pdf +- **Interactive API Docs**: `http://localhost:8000/docs` (when running) + +--- diff --git a/content/en/docs/developers/camera-libraries.md b/content/en/docs/developers/camera-libraries.md new file mode 100644 index 0000000..6a9f01e --- /dev/null +++ b/content/en/docs/developers/camera-libraries.md @@ -0,0 +1,44 @@ +--- +title: "Captua — Camera libraries" +linkTitle: "Camera libraries" +url: /docs/developers/camera-libraries/ +translationKey: docs-developers-camera-libraries +docs_section: developers +--- + +Captua drives cameras through one of four backends. The `CAMERA_BACKEND` setting in `.env` chooses the backend. This page names the library behind each backend and the reference documentation for it. To run the native backend on a Raspberry Pi, see [Developer setup](/docs/developers/developer-setup/#option-2-raspberry-pi-mode-with-cameras). + +## Choosing a backend {#choosing-a-backend} + +| `CAMERA_BACKEND` | Cameras | Library | Code | +|---|---|---|---| +| `picamera2` (default) | Raspberry Pi camera modules, such as the IMX519 | picamera2, on libcamera | `backend/capture/backends/picamera2_backend.py` | +| `subprocess` | Raspberry Pi camera modules | the `rpicam-still` command from rpicam-apps, on libcamera | `backend/capture/backends/subprocess_backend.py` | +| `gphoto2` | DSLRs supported by libgphoto2, such as the Canon EOS Rebel T7 | python-gphoto2, on libgphoto2 | `backend/capture/backends/gphoto2_backend.py` | +| `chdk` | Canon compacts running the CHDK firmware add-on | pychdk, over pyusb | `backend/capture/backends/chdk_backend.py` | + +The backend reads the value without surrounding spaces and without regard to case. If the value names none of these four, the backend refuses to start and names the valid values (`assert_camera_backend_configured` in `backend/capture/service.py`). It does not fall back to another backend, because a fallback would look like a dead camera. + +Setting up the hardware for each backend is described in the camera guides: [Raspberry Pi 5 with IMX519 cameras](/docs/deployment/pi5-imx519/), [gPhoto2 cameras](/docs/cameras/gphoto2/) and [CHDK cameras](/docs/cameras/chdk/). + +## picamera2 and rpicam-apps (libcamera) {#libcamera} + +The `picamera2` and `subprocess` backends both reach the Raspberry Pi camera modules through libcamera. `picamera2` uses the picamera2 Python library directly, with streaming, live preview and settings that change while the camera runs. `subprocess` runs the `rpicam-still` command for each capture. + +picamera2 and libcamera come from the Raspberry Pi OS packages `python3-picamera2` and `python3-libcamera`, not from pixi. `scripts/setup.sh` installs them, and `pixi run setup-camera-link` puts them on the pixi environment's path. numpy stays below 2 in `backend/pixi.toml` and `backend/requirements.txt`, because numpy 2 breaks the system-built picamera2 dependencies. + +- [Raspberry Pi camera software](https://www.raspberrypi.com/documentation/computers/camera_software.html): the rpicam-apps commands, libcamera and picamera2 + +## gPhoto2 {#gphoto2} + +The `gphoto2` backend uses [python-gphoto2](https://github.com/jim-easterbrook/python-gphoto2), the Python binding to libgphoto2 (`gphoto2>=2.6.3,<3` in `backend/pixi.toml`). On a unit, `scripts/setup.sh` installs the `gphoto2` command and builds python-gphoto2 from source against the system libgphoto2 (`gphoto2==2.6.4`). The binary wheel from PyPI bundles its own libgphoto2 and libusb, and on Raspberry Pi OS Bookworm its autodetection finds no cameras even when the system's `gphoto2` command lists them. + +- [libgphoto2 API documentation](http://www.gphoto.org/doc/api/index.html): the most complete description of the library +- [gphoto2 command reference](http://www.gphoto.org/doc/manual/ref-gphoto2-cli.html): the command-line tool, useful for checking a camera by hand +- [python-gphoto2](https://github.com/jim-easterbrook/python-gphoto2): the binding Captua uses + +## CHDK {#chdk} + +The `chdk` backend talks to Canon compacts running CHDK over PTP and USB through pychdk, a library maintained in the UCSB-AMPLab organisation and pinned to a tag (`v0.1.3` in `backend/pixi.toml`). pychdk uses pyusb (`pyusb>=1.2,<2`), with no Lua or C on the host. `scripts/provision-chdk-usb.sh` installs libusb, a udev rule and the group membership that let the backend open the cameras. Both `scripts/setup.sh` and `scripts/update.sh` run it. + +- [pychdk](https://github.com/UCSB-AMPLab/pychdk): the library and its documentation diff --git a/content/en/docs/developers/developer-setup.md b/content/en/docs/developers/developer-setup.md new file mode 100644 index 0000000..b289f12 --- /dev/null +++ b/content/en/docs/developers/developer-setup.md @@ -0,0 +1,182 @@ +--- +title: "Captua — Developer setup" +linkTitle: "Developer setup" +url: /docs/developers/developer-setup/ +translationKey: docs-developers-developer-setup +docs_section: developers +--- + +This page sets up a development environment for Captua, so that every contributor works against the same stack. For branches, pull requests and releases, see [Git workflow](/docs/developers/git-workflow/). For the camera libraries behind each backend, see [Camera libraries](/docs/developers/camera-libraries/). The backend's endpoints are described in the [API reference](/docs/developers/api-reference/). + +## Required software {#required-software} + +You need these tools on any operating system: + +- **Git** + - Check whether Git is installed with `git --version`. + - If it is not installed: + - macOS: `brew install git` (or the Xcode command line tools) + - Windows: download it from the [official Git website](https://git-scm.com/download/win) + - Linux (Debian and derivatives): `sudo apt install git` +- **Docker Desktop** + - macOS: download it from [Docker's official site](https://docs.docker.com/desktop/install/mac-install/) + - Windows: download it from [Docker's official site](https://docs.docker.com/desktop/install/windows-install/) + - Linux: install Docker Engine (`curl -fsSL https://get.docker.com | sh`) and the `docker compose` plugin. + - After installing, run `docker --version` and `docker compose version` to check the installation. + +The development stack runs in Docker images that contain Node and Python, so a development machine needs nothing else. The native backend on a Raspberry Pi is the exception: it runs under [pixi](https://pixi.sh) (see [Option 2](#option-2-raspberry-pi-mode-with-cameras)). + +## Cloning the repository {#cloning-the-repository} + +Clone the repository with its submodules: + +```bash +git clone --recurse-submodules git@github.com:UCSB-AMPLab/digitization-toolkit-software.git +cd digitization-toolkit-software +``` + +The submodules are addressed over SSH, so the clone needs an SSH key registered with GitHub. + +The checkout has this structure: + +```text +. +├── backend # FastAPI backend (submodule) +├── frontend # SvelteKit frontend (submodule) +├── wiki # project wiki (submodule) +├── docs +├── scripts # start, setup, update and provisioning scripts +├── docker-compose.yml # base stack: database, production frontend, optional backend +├── docker-compose.dev.yml # development overlay: Vite dev server +├── docker-compose.pi.yml # appliance overlay: appliance paths and Nginx +├── .env.example +├── nginx.conf +├── CHANGELOG.md +├── CITATION.cff +├── VERSION +├── LICENSE +├── README.md +└── README-SETUP.md +``` + +## Create the environment file {#create-the-environment-file} + +The backend service reads `.env` (`env_file: ./.env` in `docker-compose.yml`). The file is not in the repository and `scripts/start-dev.sh` does not create it, so Docker Compose stops if it is missing. Create it from the example before the first start: + +```bash +cp .env.example .env +``` + +`.env.example` sets `APP_ENV=dev`. In a development environment with no `BOOTSTRAP_TOKEN` set, the first administrator account can be created without a token (`_authorize_bootstrap` in `backend/app/api/auth.py`). Outside development, Captua asks for the token. + +## Start the services {#start-the-services} + +Captua runs in two arrangements: + +- **Database and frontend** run in Docker containers. +- **Backend** runs natively on a Raspberry Pi, for camera access, or in Docker, for development. + +### Option 1: Development mode (no cameras) {#option-1-development-mode-no-cameras} + +From the root of the repository, run: + +```bash +./scripts/start-dev.sh +``` + +On Windows, use `scripts\start-dev.bat` or `scripts\start-dev.ps1`. + +The script runs this Docker Compose command, which you can also run directly: + +```bash +docker compose -f docker-compose.yml -f docker-compose.dev.yml --profile with-backend up --build +``` + +The `docker-compose.dev.yml` overlay is required for the Vite dev server. Without it, the base `docker-compose.yml` builds and serves the **production** frontend image on port 3000 instead. + +This command: + +- starts the **database** (PostgreSQL 16, from a pinned image, on port 5432, bound to 127.0.0.1) +- builds and starts the **backend** (FastAPI and Uvicorn, port 8000), which applies the database migrations (`alembic upgrade head`) before it starts +- builds and starts the **frontend** (SvelteKit and Vite, port 5173) +- mounts your local `backend/` and `frontend/` directories in the containers, so changes reload live + +### Option 2: Raspberry Pi mode (with cameras) {#option-2-raspberry-pi-mode-with-cameras} + +On a unit provisioned with `scripts/setup.sh`, the systemd service `dtk.service` runs the stack through `scripts/start.sh`. Do not start a second copy by hand. Stop the service first (`sudo systemctl stop dtk`) if you need to run the backend yourself. + +`scripts/setup.sh` prepares a unit: it creates `.env` if it is missing, installs pixi v0.73.0 if no pixi is installed (the committed `pixi.lock` needs a pixi that reads lock-file format v7), installs the backend environment, links the system camera libraries, builds python-gphoto2 against the system libgphoto2, and applies the database migrations. On an unprovisioned Pi, run `scripts/setup.sh`, or do the backend steps by hand: + +```bash +cd backend +pixi install --locked # first time only +pixi run setup-camera-link # puts the system picamera2 and libcamera packages on the environment's path +pixi run db-upgrade # applies the migrations; the backend refuses to start against an un-migrated database +``` + +`setup-camera-link` needs the Raspberry Pi OS packages `python3-picamera2` and `python3-libcamera`, which `scripts/setup.sh` installs. pixi supports only `linux-aarch64` and `linux-64` (`platforms` in `backend/pixi.toml`), so the native backend cannot run on macOS or Windows. Use the Docker backend there. + +Start the database, the production frontend and Nginx, as `scripts/start.sh` does: + +```bash +docker compose -f docker-compose.yml -f docker-compose.pi.yml up -d --pull never --wait --remove-orphans +``` + +In a separate terminal, start the native backend: + +```bash +cd backend +pixi run dev # Uvicorn with --reload, for development on the Pi +``` + +`pixi run dev` starts the FastAPI backend with `--reload`, listening on `0.0.0.0:8000`. The appliance itself runs `pixi run start`, which is the same server without `--reload`. + +Captua detects cameras when they are first used, not at startup. At startup, the backend checks the `CAMERA_BACKEND` value and refuses to start if it names no backend this build has (`assert_camera_backend_configured` in `backend/capture/service.py`). + +**Why native?** Camera access needs Raspberry Pi system libraries (libcamera and picamera2, libgphoto2, and USB access for CHDK bodies) that are difficult to reproduce in Docker. There is no `run_backend_native.sh` script and no Python virtualenv to activate. pixi manages the backend's dependencies. + +## Verify the backend {#verify-backend} + +Open `http://localhost:8000/health` in your browser. The response is: + +```json +{"status": "ok"} +``` + +## Verify the frontend {#verify-frontend} + +In development mode, open `http://localhost:5173`. On a Pi, open `http://localhost` or `http://captua.local`. Nginx serves Captua on port 80 there, and nothing listens on 5173. + +The root address redirects to the welcome page, or to the dashboard if a user is already signed in. On the welcome page, choose **Get started in English**. On a new database, Captua then opens the setup page, where you create the administrator account. Otherwise it opens the login page. + +## Common issues {#common-issues} + +- **Port already in use**: if ports 5432, 8000 or 5173 are occupied, stop the conflicting services or change the ports. Ports 5432 and 8000, and the production frontend's 3000, are set in `docker-compose.yml`. The development frontend's 5173 is set in `docker-compose.dev.yml`. +- **The frontend cannot reach the backend**: + - Check that the backend is running: `curl http://localhost:8000/health`. + - For the native backend, check that `.env` has `DATABASE_HOST=localhost`. The Docker backend uses `db`, which `docker-compose.yml` sets itself. +- **Camera not detected**: camera access needs the native backend on a Raspberry Pi. The Docker backend cannot reach cameras. +- **Backend stops at startup**: an invalid `CAMERA_BACKEND` value, or a database that has not been migrated, stops the backend before it serves requests. Correct the value in `.env`, or run `pixi run db-upgrade`. +- **Live reloading does not work**: restart the containers: + +```bash +docker compose -f docker-compose.yml -f docker-compose.dev.yml --profile with-backend down +docker compose -f docker-compose.yml -f docker-compose.dev.yml --profile with-backend up --build +``` + +For the native backend: + +```bash +# Stop it with Ctrl+C, then restart +cd backend && pixi run dev +``` + +## Shut everything down {#shut-everything-down} + +When you finish, stop the containers: + +```bash +docker compose -f docker-compose.yml -f docker-compose.dev.yml --profile with-backend down +``` + +You can also stop and start the containers from Docker Desktop. diff --git a/content/en/docs/developers/git-workflow.md b/content/en/docs/developers/git-workflow.md new file mode 100644 index 0000000..1779814 --- /dev/null +++ b/content/en/docs/developers/git-workflow.md @@ -0,0 +1,148 @@ +--- +title: "Captua — Git workflow" +linkTitle: "Git workflow" +url: /docs/developers/git-workflow/ +translationKey: docs-developers-git-workflow +docs_section: developers +--- + +This page describes how Captua's repositories use Git: branches, pull requests, submodule pointers and releases, across the superproject and its submodules. To set up the development stack, see [Developer setup](/docs/developers/developer-setup/). + +## Repository structure {#repository-structure} + +- **Superproject** (`UCSB-AMPLab/digitization-toolkit-software`): holds the orchestration (`docker-compose.yml`, `docker-compose.dev.yml`, `docker-compose.pi.yml`, `nginx.conf`), the environment example (`.env.example`), the setup, update, rollback and provisioning scripts and systemd units in `scripts/`, the documentation, `CHANGELOG.md`, `VERSION`, and the submodule pointers. +- **Submodules**: + - `frontend/`: the SvelteKit application (`UCSB-AMPLab/digitization-toolkit-frontend`) + - `backend/`: the FastAPI application (`UCSB-AMPLab/digitization-toolkit-backend`) + - `wiki/`: the project wiki (`UCSB-AMPLab/digitization-toolkit-software.wiki`) + +Most code changes are made in the submodule repositories. The superproject records which commit of each submodule belongs together. + +## Team branching model {#team-branching-model} + +What the three repositories actually do (checked against their branches, merged pull requests and protection settings on 2026-11-08): + +- **Branches.** Work branches from `dev` and is named after the repository area: `frontend/` and `backend/` in the submodules; `chore/bump-`, `docs/` or `scripts/` in the superproject. +- **Into dev.** Every change reaches `dev` through a pull request; `dev` and `main` refuse direct pushes, force-pushes and deletions. No approving review is required. Before merging: CI passes where the repository has it (backend: `pytest -m "not camera"` and the migration drift check; frontend: `npm run check` and Vitest; the superproject has none), and `codex review --base origin/dev` reports nothing open. Pull requests are merged with a merge commit (`gh pr merge --merge`), never squashed or rebased. +- **Submodule pointers.** After a submodule pull request merges, a superproject branch `chore/bump-` moves the pointer to the merged commit, and its own pull request goes into `dev`. +- **Releases.** A release is a `dev`→`main` pull request in each submodule and then in the superproject, merged by an administrator with a merge commit. The protection rule asks for one approving review on `main`; administrators are exempt (`enforce_admins` is off), and release merges have used that exemption. Only the superproject is tagged, without a `v` prefix (`0.2.0`), with a CHANGELOG pull request, a `release: Captua ` commit and a GitHub Release. Docker images are built on each unit by `scripts/update.sh`, not by CI. +- **Urgent fixes.** A few fixes have gone straight to `main` as `fix/` pull requests. + +```text +frontend/, backend/ ──PR──► dev ──release PR──► main +chore/bump- (superproject) ──PR──► dev +``` + +## Continuous integration {#continuous-integration} + +No status check is required by the branch protection on any of the three repositories, so a pull request can be merged with CI failing. Check the result before merging. + +| Repository | Workflow | When it runs | What it runs | +|---|---|---|---| +| backend | `.github/workflows/ci.yml` | pull requests into `dev`, pushes to `dev` | `pixi run -e dev pytest tests/ -m "not camera"`, then `pixi run -e dev db-check-drift` | +| frontend | `.github/workflows/ci.yml` | every pull request, pushes to `dev` and `main` | `npm ci`, `npm run check`, `npx vitest run` (in Chromium, through Playwright) | + +The superproject has no workflow. + +## Workflow for submodules {#workflow-for-submodules} + +### 1. Prepare the checkout {#prepare-checkout} + +```bash +git fetch --all +git switch dev +git pull origin dev +git submodule update --init --recursive # takes the exact pins the superproject records (no --remote) +``` + +### 2. Create a feature branch in a submodule {#create-a-feature-branch} + +```bash +cd frontend +git checkout dev +git pull origin dev +git checkout -b frontend/capture-panel +``` + +Commit as you work, then push: + +```bash +git push -u origin frontend/capture-panel +``` + +### 3. Open a pull request in the submodule repository {#open-a-pr-in-the-submodule} + +Open the pull request against `dev`. Merge it with a merge commit once CI passes (see [Team branching model](#team-branching-model)). + +### 4. Update the superproject pointer {#update-the-superproject-pointer} + +A code change lands in two steps: + +1. **Land the change in the submodule first.** Branch inside the submodule (`frontend/` or `backend/`), open a PR against that submodule's repo, merge it. +2. **Bump the superproject pointer.** On a superproject branch `chore/bump-` from `dev`, advance the submodule to the merged commit, commit the new gitlink, and open a PR into `dev`. + +After the submodule pull request merges: + +```bash +cd .. +git switch dev +git pull origin dev +git switch -c chore/bump- +git -C frontend fetch origin # or backend +git -C frontend checkout # the exact commit merged in the submodule PR + # (read it with: git -C frontend rev-parse --short HEAD) +git add frontend +git commit -m "chore(submodule): bump frontend to " +git push -u origin chore/bump- +``` + +Open a pull request from `chore/bump-` into `dev` in the superproject. Do not push the commit to `dev` directly: `dev` refuses direct pushes. + +## Commit guidelines {#commit-guidelines} + +Commits follow [Conventional Commits](https://www.conventionalcommits.org/), with a scope. Keep each commit to one change: + +- `feat(api): add /upload endpoint` +- `fix(ui): handle 404 from /health` +- `chore(submodule): bump frontend to ` + +## Pull request checklist {#pull-request-checklist} + +- [ ] The stack builds and runs in Docker (`./scripts/start-dev.sh`) +- [ ] Backend CI and frontend CI pass on the pull request +- [ ] `codex review --base origin/dev` reports nothing open +- [ ] Commit messages are meaningful +- [ ] No unresolved merge conflicts +- [ ] Documentation updated if needed + +## Working with Docker {#working-with-docker} + +On a development machine, the stack runs in Docker, and you do not need Node.js or Python installed locally. On a Raspberry Pi the backend runs natively under pixi, and the backend's CI runs its tests under pixi as well (see [Developer setup](/docs/developers/developer-setup/#option-2-raspberry-pi-mode-with-cameras)). + +- Start the stack: + + ```bash + ./scripts/start-dev.sh + ``` + + This runs `docker compose -f docker-compose.yml -f docker-compose.dev.yml --profile with-backend up --build`. A plain `docker compose up --build` builds the production frontend on port 3000 and does not start the backend, which is in the `with-backend` profile. +- Frontend: `http://localhost:5173` +- Backend: `http://localhost:8000/health` + +### Switching branches {#switching-branches} + +- If only source files changed, `git checkout ` is enough. +- If the frontend's dependencies changed (`package.json` or `package-lock.json`), restart the stack. The development frontend runs `npm install` each time it starts (`command` in `docker-compose.dev.yml`), which brings the `frontend_node_modules` volume in line with `package-lock.json`. If the packages still look wrong after a restart, stop the stack, remove that volume, and start again: + + ```bash + docker compose -f docker-compose.yml -f docker-compose.dev.yml --profile with-backend down + docker volume rm dtk_frontend_node_modules + ./scripts/start-dev.sh + ``` + + The volume name has the Compose project name `dtk` (`name:` in `docker-compose.yml`) as its prefix. +- If the backend's dependencies changed (`requirements.txt`, which moves together with `pixi.toml` and `pixi.lock`), `./scripts/start-dev.sh` rebuilds the backend image with `--build`. + +{{< callout type="warning" appearance="simple" >}} +Do not use `docker compose down -v` to refresh dependencies. `-v` removes the `postgres_data` volume, which deletes the development database. Without the development overlay, the same command also leaves `frontend_node_modules` in place, because only `docker-compose.dev.yml` declares that volume. +{{< /callout >}} diff --git a/migration/sources.json b/migration/sources.json index 2d169ec..f1261e5 100644 --- a/migration/sources.json +++ b/migration/sources.json @@ -51,5 +51,36 @@ "source": "docs/developers/device_setup_CM4.qmd", "reason": "Captua units use standard Raspberry Pi 5 boards; the CM4 build is not used." } + ], + "later_moves": [ + { + "source": "UCSB-AMPLab/digitization-toolkit-software docs/developers/API_REFERENCE.md", + "source_commit": "cf70bbe", + "url": "/docs/developers/api-reference/", + "translationKey": "docs-developers-api-reference", + "section": "developers", + "note": "Brought up to date with the code on 2026-11-08; English only." + }, + { + "source": "UCSB-AMPLab/digitization-toolkit-software.wiki Developer-Setup-Guide.md", + "source_commit": "29bb223", + "url": "/docs/developers/developer-setup/", + "translationKey": "docs-developers-developer-setup", + "section": "developers" + }, + { + "source": "UCSB-AMPLab/digitization-toolkit-software.wiki Git-workflow.md", + "source_commit": "29bb223", + "url": "/docs/developers/git-workflow/", + "translationKey": "docs-developers-git-workflow", + "section": "developers" + }, + { + "source": "UCSB-AMPLab/digitization-toolkit-software.wiki Dependencies-Documentation.md", + "source_commit": "29bb223", + "url": "/docs/developers/camera-libraries/", + "translationKey": "docs-developers-camera-libraries", + "section": "developers" + } ] } From 164cebe766c9e76c842087f629c857e176368533 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Sun, 8 Nov 2026 17:33:17 -0800 Subject: [PATCH 2/5] feat(site): add an English-only Developers section The Developers section lists the developer setup, Git workflow, camera libraries and API reference pages in English only. The section order is set per language, translations_pending.json gains an english_only list that the site test accepts, and the API reference links point to the site's own page. --- content/en/docs/developers/_index.md | 7 ++++ data/docs_navigation.json | 51 ++++++++++++++++++++++------ data/translations_pending.json | 10 +++++- hugo.json | 2 +- layouts/_partials/docs-shell.html | 2 +- layouts/_partials/header.html | 2 +- layouts/_partials/home.html | 2 +- layouts/_partials/hub.html | 4 +-- scripts/verify.py | 9 +++-- 9 files changed, 70 insertions(+), 19 deletions(-) create mode 100644 content/en/docs/developers/_index.md diff --git a/content/en/docs/developers/_index.md b/content/en/docs/developers/_index.md new file mode 100644 index 0000000..9970a9d --- /dev/null +++ b/content/en/docs/developers/_index.md @@ -0,0 +1,7 @@ +--- +title: Developers +description: "Setting up a development environment, the branching and release practice, the camera libraries, and the API reference." +url: /docs/developers/ +translationKey: docs-developers +docs_section: developers +--- diff --git a/data/docs_navigation.json b/data/docs_navigation.json index 13e8c9f..e29b9cf 100644 --- a/data/docs_navigation.json +++ b/data/docs_navigation.json @@ -89,11 +89,19 @@ "footer": "El Archives, Memory, and Preservation Lab (AMPL) de la Universidad de California en Santa Bárbara y la Universidad de Texas en Austin desarrollan Captua con financiación del National Endowment for the Humanities." } }, - "order": [ - "operators", - "cameras", - "deployment" - ], + "order": { + "en": [ + "operators", + "cameras", + "deployment", + "developers" + ], + "es": [ + "operators", + "cameras", + "deployment" + ] + }, "sections": { "en": { "operators": { @@ -167,14 +175,37 @@ "title": "Reference", "items": [ { - "title": "API reference", - "url": "https://github.com/UCSB-AMPLab/digitization-toolkit-software/blob/dev/docs/developers/API_REFERENCE.md", - "external": true + "page": "/docs/developers/api-reference" } ] } ], "page": "/docs/deployment" + }, + "developers": { + "title": "Developers", + "url": "/docs/developers/", + "groups": [ + { + "id": "main", + "title": "Developers", + "items": [ + { + "page": "/docs/developers/developer-setup" + }, + { + "page": "/docs/developers/git-workflow" + }, + { + "page": "/docs/developers/camera-libraries" + }, + { + "page": "/docs/developers/api-reference" + } + ] + } + ], + "page": "/docs/developers" } }, "es": { @@ -249,8 +280,8 @@ "title": "Referencia", "items": [ { - "title": "Referencia de la API", - "url": "https://github.com/UCSB-AMPLab/digitization-toolkit-software/blob/dev/docs/developers/API_REFERENCE.md", + "title": "Referencia de la API (en inglés)", + "url": "/docs/developers/api-reference/", "external": true } ] diff --git a/data/translations_pending.json b/data/translations_pending.json index 9105578..38bb4d0 100644 --- a/data/translations_pending.json +++ b/data/translations_pending.json @@ -1,4 +1,12 @@ { "_comment": "English translationKeys whose Spanish page under content/es/ does not exist yet. npm test fails if an English page has neither a Spanish counterpart nor an entry here, or if an entry here already has a Spanish page. The Spanish step removes each key as it adds the page.", - "pending": [] + "pending": [], + "_comment_english_only": "English translationKeys published in English only, by decision: the developer guides. npm test fails if one of them gains a Spanish page while still listed here.", + "english_only": [ + "docs-developers", + "docs-developers-developer-setup", + "docs-developers-git-workflow", + "docs-developers-camera-libraries", + "docs-developers-api-reference" + ] } diff --git a/hugo.json b/hugo.json index 5191514..fa22da3 100644 --- a/hugo.json +++ b/hugo.json @@ -41,7 +41,7 @@ }, "params": { "docs_preview": false, - "api_reference": "https://github.com/UCSB-AMPLab/digitization-toolkit-software/blob/dev/docs/developers/API_REFERENCE.md", + "api_reference": "/docs/developers/api-reference/", "repository": "https://github.com/UCSB-AMPLab/captua-docs" }, "enableRobotsTXT": true, diff --git a/layouts/_partials/docs-shell.html b/layouts/_partials/docs-shell.html index 9e130ce..59e4331 100644 --- a/layouts/_partials/docs-shell.html +++ b/layouts/_partials/docs-shell.html @@ -5,7 +5,7 @@ {{ partial "header.html" (dict "page" . "labels" $labels "routes" $r "current" "guides") }} -{{ if not $hub }}
{{ end }} +{{ if not $hub }}
{{ end }}
{{ if site.Params.docs_preview }}
{{ $labels.preview }}
{{ end }} {{ if $hub }}
{{ partial "hub.html" (dict "page" . "level" 1) }}{{ .Content }}
{{ else }}
diff --git a/layouts/_partials/header.html b/layouts/_partials/header.html index 2b39130..5490ac9 100644 --- a/layouts/_partials/header.html +++ b/layouts/_partials/header.html @@ -1,4 +1,4 @@ {{ $p := .page }}{{ $labels := .labels }}{{ $r := .routes }}{{ $lang := $p.Language.Lang }}{{ $copy := index hugo.Data.site_copy $lang }}
{{ partial "brand.html" "mark" }}{{ $copy.header_tagline }}
- +
diff --git a/layouts/_partials/home.html b/layouts/_partials/home.html index d467380..385ab72 100644 --- a/layouts/_partials/home.html +++ b/layouts/_partials/home.html @@ -10,7 +10,7 @@

{{ partial "brand.html" (cond (eq $lang "es") "esp" "eng") }}

{{ if gt (len .AllTranslations) 1 }}{{ end }}

{{ $copy.tagline }}

- +

{{ $copy.about_heading }}

diff --git a/layouts/_partials/hub.html b/layouts/_partials/hub.html index d08d42c..7fab6d7 100644 --- a/layouts/_partials/hub.html +++ b/layouts/_partials/hub.html @@ -5,6 +5,6 @@

{{ $copy.documentation }}

{{ printf "<%s>" $h | safeHTML }}{{ $title }}{{ printf "" $h | safeHTML }}

{{ $copy.hub_lede }}

{{ with site.GetPage "docs/operators/card" }}{{ end }}

{{ $copy.beta }}

{{ printf "<%s id=\"release-heading\">" $hc | safeHTML }}{{ $copy.current_release }}{{ printf "" $hc | safeHTML }}

{{ $copy.release_tested }}

{{ $copy.releases }} ↗
-
{{ range $i, $key := $nav.order }}{{ $a := index $sections $key }}{{ $sp := site.GetPage $a.page }}
{{ printf "<%s>" $hc | safeHTML }}{{ $a.title }}{{ printf "" $hc | safeHTML }}

{{ with $sp }}{{ .Description }}{{ end }}

    {{ range $a.groups }}{{ range .items }}
  • {{ partial "nav-item.html" (dict "item" . "current" "") }}
  • {{ end }}{{ end }}
{{ $labels.index }} →
{{ end }}
-

{{ $copy.reference }}

{{ printf "<%s>" $hc | safeHTML }}{{ $labels.api_reference }}{{ printf "" $hc | safeHTML }}

{{ $copy.api_text }}

+
{{ range $i, $key := index $nav.order $lang }}{{ $a := index $sections $key }}{{ $sp := site.GetPage $a.page }}
{{ printf "<%s>" $hc | safeHTML }}{{ $a.title }}{{ printf "" $hc | safeHTML }}

{{ with $sp }}{{ .Description }}{{ end }}

    {{ range $a.groups }}{{ range .items }}
  • {{ partial "nav-item.html" (dict "item" . "current" "") }}
  • {{ end }}{{ end }}
{{ $labels.index }} →
{{ end }}
+

{{ $copy.reference }}

{{ printf "<%s>" $hc | safeHTML }}{{ $labels.api_reference }}{{ printf "" $hc | safeHTML }}

{{ $copy.api_text }}

{{ $copy.open_source }}

{{ printf "<%s>" $hc | safeHTML }}{{ $copy.source_code }}{{ printf "" $hc | safeHTML }}

{{ $copy.source_text }}

diff --git a/scripts/verify.py b/scripts/verify.py index 59c69c2..5dc8a44 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -189,7 +189,9 @@ def route_of(file): m = SECRET.search(f.read_text()) check(not m, f'Possible credential in {f.relative_to(ROOT)}: {m.group(0) if m else ""}') -pending = json.loads((ROOT / 'data/translations_pending.json').read_text())['pending'] +_translations = json.loads((ROOT / 'data/translations_pending.json').read_text()) +pending = _translations['pending'] +english_only = _translations.get('english_only', []) en_keys = {}; es_keys = {} for lang, store in (('en', en_keys), ('es', es_keys)): for f in (ROOT / 'content' / lang).rglob('*.md'): @@ -198,11 +200,14 @@ def route_of(file): check(key not in store, f'translationKey {key} used twice in content/{lang}') store[key] = f.relative_to(ROOT) for key, f in en_keys.items(): - check(key in es_keys or key in pending, f'No Spanish counterpart and not listed as pending: {key} ({f})') + check(key in es_keys or key in pending or key in english_only, f'No Spanish counterpart and not listed as pending or English-only: {key} ({f})') for key in pending: check(key in en_keys, f'Pending translationKey {key} has no English page') check(key not in es_keys, f'Pending translationKey {key} already has a Spanish page; remove it from data/translations_pending.json') check(len(set(pending)) == len(pending), 'Duplicate entries in data/translations_pending.json') +for key in english_only: + check(key in en_keys, f'English-only translationKey {key} has no English page') + check(key not in es_keys, f'English-only translationKey {key} has a Spanish page; remove it from english_only in data/translations_pending.json') check((PUBLIC / '404.html').exists(), '404 page missing') check((PUBLIC / 'pagefind/pagefind.js').exists(), 'Search index missing') From b71538a622bb1afc504ed493f063d039b050139e Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Sun, 8 Nov 2026 17:33:17 -0800 Subject: [PATCH 3/5] docs(guides): correct the operator, camera and deployment guides against the code Each statement was checked against the code at superproject cf70bbe (backend 190ad27, frontend ab71033). Rionegro's tenant, bucket and key names are replaced by placeholders, and the Spanish pages quote the interface's own labels. --- content/en/docs/cameras/chdk.md | 28 +- content/en/docs/cameras/gphoto2.md | 20 +- content/en/docs/deployment/pi5-imx519.md | 2 +- .../docs/deployment/sd-card-distribution.md | 63 +++- content/en/docs/deployment/updating-a-unit.md | 177 ++++++----- content/en/docs/operators/card.md | 10 +- content/en/docs/operators/external-storage.md | 79 +++-- content/es/docs/cameras/chdk.md | 28 +- content/es/docs/cameras/gphoto2.md | 18 +- content/es/docs/deployment/pi5-imx519.md | 2 +- .../docs/deployment/sd-card-distribution.md | 63 +++- content/es/docs/deployment/updating-a-unit.md | 286 ++++++++++-------- content/es/docs/operators/card.md | 12 +- content/es/docs/operators/external-storage.md | 32 +- data/site_copy.json | 4 +- 15 files changed, 517 insertions(+), 307 deletions(-) diff --git a/content/en/docs/cameras/chdk.md b/content/en/docs/cameras/chdk.md index ef876f8..da2366b 100644 --- a/content/en/docs/cameras/chdk.md +++ b/content/en/docs/cameras/chdk.md @@ -16,19 +16,19 @@ CHDK is not installed onto the camera's own firmware. It boots from a specially - **Two Canon A2500 cameras.** The card-preparation tool (`tools/flash_chdk.py`) downloads and installs CHDK 1.6.1-6315 for the A2500 running firmware 1.00A specifically; it is not a general CHDK installer for other Canon models. - **Two SD cards**, one per camera, each prepared as described below. -- **A Mac**, with its own clone of the `pychdk` repository (`https://github.com/UCSB-AMPLab/pychdk`, at tag `v0.1.2` — the version this appliance's backend is pinned to, in `backend/requirements.txt` and `backend/pixi.toml`) to prepare the cards from. `pychdk` is not part of this toolkit checkout, and installing it as a Python package — which is all the backend itself does — does not bring the card-preparation tool along either: it lives only under `tools/` in the repository, which packaging leaves out. `tools/flash_chdk.py` only runs on macOS — it drives the Mac's own `diskutil` to format and write the card. +- **A Mac**, with its own clone of the `pychdk` repository (`https://github.com/UCSB-AMPLab/pychdk`, at tag `v0.1.3` — the version this appliance's backend is pinned to, in `backend/requirements.txt` and `backend/pixi.toml`) to prepare the cards from. `pychdk` is not part of the Captua checkout, and installing it as a Python package — which is all the backend itself does — does not bring the card-preparation tool along either: it lives only under `tools/` in the repository, which packaging leaves out. `tools/flash_chdk.py` only runs on macOS — it drives the Mac's own `diskutil` to format and write the card. - **A USB cable** per camera, to connect it to the appliance. {{< callout type="important" title="Capture over USB is not proven on this hardware yet" >}} -The appliance takes the picture over the USB cable: the image is sent straight down the wire and is never written to the camera's own SD card. The A2500's CHDK port is alpha-level, and `pychdk` records that this streamed capture can fail on the A2500 with PTP error `0x2002`. Neither `pychdk` v0.1.2 nor this backend falls back to shooting onto the card, so wherever that failure occurs the capture fails outright rather than quietly producing a file somewhere else. A capture that fails this way also drops the camera: the backend closes its session and takes it out of the device list, and the next scan has to open it again. Whether it comes back cleanly, and whether preview still works when it does, is not established either — the same test would settle all of it. The backend's log names the error. +The appliance takes the picture over the USB cable: the image is sent straight down the wire and is never written to the camera's own SD card. This streamed capture has never been run against an A2500. If it fails, neither `pychdk` v0.1.3 nor this backend falls back to shooting onto the card, so the capture fails outright rather than quietly producing a file somewhere else, and the state the camera is left in is not known. A capture that fails this way also drops the camera: the backend closes its session and takes it out of the device list, and the next scan has to open it again. Whether it comes back cleanly, and whether preview still works when it does, is not established either — the same test would settle all of it. The backend's log names the error. -Whether it happens on these particular bodies is not yet known — it has never been run against the cameras themselves. That test is on the bench-test list. Until it has been done, treat capture on the A2500 as unproven, and do not plan a digitization session around it. +Whether streamed capture works on these bodies is not yet known. That test is on the bench-test list. Until it has been done, treat capture on the A2500 as unproven, and do not plan a digitization session around it. {{< /callout >}} ## Selecting the CHDK backend {#selecting-the-chdk-backend} -This page applies from the release that bumps the superproject's backend pointer past NEH-231 onward; an appliance still on an earlier backend has neither the CHDK backend code nor its `pychdk` dependency, so `CAMERA_BACKEND=chdk` cannot work there yet. +This page applies from Captua 0.1.0-beta onward; an appliance still on an earlier release has neither the CHDK backend code nor its `pychdk` dependency, so `CAMERA_BACKEND=chdk` cannot work there yet. {{< callout type="warning" appearance="simple" >}} The appliance only talks to these cameras as CHDK bodies if it is told to. The backend defaults to a different camera system entirely, and nothing in the appliance's setup changes that on its own — you can prepare both cards perfectly and connect two working cameras and still see nothing, because the appliance is listening for a different kind of camera altogether. @@ -50,17 +50,17 @@ If you did not provision this appliance yourself, check with whoever did — it ## Preparing an SD card {#preparing-an-sd-card} -Cards are prepared with `tools/flash_chdk.py`, on a Mac, from a clone of the `pychdk` repository itself — not from anything in this toolkit checkout, and not from wherever the backend's own Python dependency installed it: +Cards are prepared with `tools/flash_chdk.py`, on a Mac, from a clone of the `pychdk` repository itself — not from anything in the Captua checkout, and not from wherever the backend's own Python dependency installed it: ```bash git clone https://github.com/UCSB-AMPLab/pychdk.git cd pychdk -git checkout v0.1.2 +git checkout v0.1.3 python3 tools/flash_chdk.py ``` {{< callout type="warning" appearance="simple" >}} -Preparing a card **erases it**. The confirmation prompt — "This will ERASE the disk. Continue?" — only fires when the Mac detects **exactly one** removable disk in total, not one SD card. If any other removable storage is also attached (a USB drive, a second card reader, and so on), the tool skips the prompt entirely and erases whichever disk you pick by number. Disconnect every other piece of removable storage first, so that the card you intend to prepare is the only one connected. +Preparing a card **erases it**. Before it erases anything, the tool asks for confirmation and names the disk it is about to erase: "This will ERASE /dev/diskN (name, sizeGB) and everything on it. Continue? [y/N]". Check that name before you answer `y`. The tool lists every physical removable disk, not only SD cards, so an external USB drive can appear in the list. Disconnecting other removable storage first leaves the card as the only choice. {{< /callout >}} The tool downloads (and caches) the CHDK build, formats the card, extracts CHDK's boot files onto it, and patches the card's boot sector so it is bootable. It then asks which pages this camera will shoot — odd, even, or skip — and records that choice on the card. When it finishes, **lock the card** with the write-protect switch on its edge before inserting it into the camera. @@ -75,7 +75,7 @@ The card records which **pages** that camera photographs — ODD or EVEN — not So a card belongs to "the camera that shoots even pages" or "the camera that shoots odd pages" — not to "the left camera" or "the right camera." -A camera with a parity on its card keeps that parity's index, provided no other connected camera claims the same parity — if one does, neither of them is where you would expect, and neither may capture until you have fixed it. A camera that has not been given one yet holds no index of its own — it takes the lowest index no parity has claimed, so it can be pushed along to another index when a further camera appears, even though nothing is wrong with it. That is one more reason to assign both parities before you start rather than after. What a shared parity does move is the cameras sharing it: both are refused, the first of them on the bus keeps that parity's index, and the other is parked on the lowest index no parity is using — which can be an index that does not match its own card. It cannot capture from there, so nothing is filed under it; it is placed only so that you can still address it to repair it, as described further down. (A shared identity with no shared parity moves nothing at all — it only blocks capture.) Read a camera's actual parity and identity from the device list rather than assuming either from its index. +A camera with a parity on its card keeps that parity's index, provided no other connected camera claims the same parity — if one does, only the first of the two on the bus keeps that index, and neither may capture until you have fixed it. A camera that has not been given one yet holds no index of its own — it takes the lowest index no parity has claimed, so it can be pushed along to another index when a further camera appears, even though nothing is wrong with it. That is one more reason to assign both parities before you start rather than after. What a shared parity does move is the cameras sharing it: both are refused, the first of them on the bus keeps that parity's index, and the other is parked on the lowest index no parity is using — which can be an index that does not match its own card. It cannot capture from there, so nothing is filed under it; it is placed only so that you can still address it to repair it, as described further down. (A shared identity with no shared parity moves nothing at all — it only blocks capture.) Read a camera's actual parity and identity from the device list rather than assuming either from its index. ## The camera's identity {#the-cameras-identity} @@ -93,29 +93,29 @@ The appliance's ordinary web interface only shows a camera's model and its index Read the authenticated device list instead — `GET /cameras/devices`, the same call documented under "Assigning a camera's parity" below. There, each connected body should appear with its model, its page parity (odd or even), and no error. A body that has neither a USB serial nor an identity of its own yet — which happens with these compacts before a parity has ever been assigned to them — shows an error there saying it needs a parity assigned before it can capture; assigning one, as described below, is also what gives it that identity. -If you have just re-flashed a card, or changed a parity by hand, ask the appliance to rescan (`POST /cameras/rescan`) rather than trusting what an earlier check found — a rescan re-reads every connected camera's card. +If you have just re-flashed a card, or changed a parity by hand, ask the appliance to rescan (`POST /cameras/rescan`) rather than trusting what an earlier check found — a rescan re-reads every connected camera's card. A rescan needs an administrator or operator login; reading the device list needs any login. ## Assigning a camera's parity {#assigning-a-cameras-parity} There is no dashboard control for this yet — a future release is expected to add one. Today, assigning a page parity is an administrator action taken directly against the appliance's API. {{< callout type="warning" appearance="simple" >}} -Logging into the appliance's ordinary web interface does not authorise this. In a browser signed in to the web interface at the same address — the appliance's own browser, which opens `http://localhost`, for instance — the appliance accepts the read-only calls of the API's interactive explorer on that session, but refuses every change it sends, the parity assignment included, with 403 and `"Missing X-Requested-With header"`, until you log in inside the explorer as below. The explorer is not reachable from a laptop on the venue network at all — port 8000 is open only from the appliance itself and over Tailscale, never from the venue LAN. +Logging into the appliance's ordinary web interface does not authorise this. In a browser signed in to the web interface at the same address — the appliance's own browser, which opens `http://localhost`, for instance — the appliance accepts the read-only calls of the API's interactive explorer on that session, but refuses every change it sends, the parity assignment included, with 403 and `"Missing X-Requested-With header"`, until you log in inside the explorer as below. The explorer cannot be used from a laptop on the venue network: port 8000 is open only from the appliance itself and over Tailscale, never from the venue LAN. The API itself is still reachable from the venue LAN through the interface's `/api/` path, and the parity route there, as everywhere, accepts a request only from an administrator. {{< /callout >}} 1. **Open the API explorer** — a different address from the one the ordinary interface runs on: - On the appliance itself: `http://localhost:8000/docs`. - From elsewhere over Tailscale: the appliance's own Tailscale address (not `localhost`, which on a remote machine means that machine, not the appliance), port 8000, `/docs` — e.g. `http://:8000/docs`. -2. **Log in as an administrator, inside that explorer.** This is several steps. If you skip any of them, the appliance refuses the assignment in step 4: with 401 and `"Not authenticated"` when the browser holds no session, or with 403 and `"Missing X-Requested-With header"` when it holds one, from the web interface or from the login in this step. Logging in here also replaces the web interface's session in this browser, so the web interface is then signed in as the administrator; sign out with **Salir** when you have finished. +2. **Log in as an administrator, inside that explorer.** This is several steps. If you skip any of them, the appliance refuses the assignment in step 4: with 401 and `"Not authenticated"` when the browser holds no session, or with 403 and `"Missing X-Requested-With header"` when it holds one, from the web interface or from the login in this step. Logging in here also replaces the web interface's session in this browser, so the web interface is then signed in as the administrator; sign out with **Log out** when you have finished. - Expand `POST /auth/login`, click **Try it out**, fill in the administrator's credentials, and click **Execute**. - Copy the `access_token` value out of the response body. - Click the green **Authorize** button near the top of the page — this opens a dialog. - Paste the token into that dialog's field, then click the **Authorize** button *inside the dialog* to submit it (pasting the token alone does nothing; that second click is what actually applies it). Close the dialog once it confirms. -3. **Read the current device list** (`GET /cameras/devices`) and find the camera you mean to change by its `index`, `hardware_id`, and `location`/port. +3. **Read the current device list** (`GET /cameras/devices`) and find the camera you mean to change by its `index`, `hardware_id`, and `location` (which carries the USB port, for example `USB usb:001,004`). 4. **Send the assignment**: `POST /cameras/side/`, with a JSON body of `{"side": "odd"}` or `{"side": "even"}`. 5. **Re-read the response**, which is a freshly rescanned device list rather than a single updated row. The camera you just changed usually moves to the other index. Identify every camera again from this refreshed list before sending another assignment — do not assume a camera kept the index it had a moment ago. -This rewrites the parity — and the camera's existing identity, or a freshly minted one if it had none — onto the camera's own card. +This rewrites the parity — and the camera's existing identity, or a freshly minted one if it had none, or if it has no USB serial and its card identity is shared with another connected camera — onto the camera's own card. The appliance will not give a camera a parity that another **currently connected** camera already holds. That means two connected cameras cannot trade parities with each other directly: whichever parity you try to assign to either one, the other camera is already holding it, so the request is refused either way — there is no order of requests that works. Swapping two cameras' parities takes the documented sequence instead: @@ -138,7 +138,7 @@ Work through these in order — later causes look identical to earlier ones from - **It could not be opened, and the message says the device is busy or already claimed** — something else on the appliance already has that camera open; see below. - **It could not be opened, and the message says something else** — a timeout is common here. The log only shows that opening failed, not why; nothing confirms this is a camera still finishing its boot, so treat that as a guess, not a diagnosis. It's still worth giving the camera a moment and rescanning — a fresh timeout can clear on its own — but do not force the message into "permissions" or "busy" if it does not actually say either, and if it keeps failing after a retry, do not keep assuming it will resolve itself: record the exact message and treat it as undiagnosed rather than as an explained, expected delay. - **It opened fine, but a later step failed** (reading the card, most often) — this points at the card or the connection itself, not at permissions: reseat the card, check it is genuinely locked and not corrupted, or try a different card or cable. -- **The log names a permissions problem opening the camera, and the card and the backend selection both check out:** this is the udev rule. Confirm with `lsusb` — you should see one "Canon, Inc." line per camera, the same as for the gPhoto2 cameras; if `lsusb` sees it, the camera is physically fine and this is a permissions problem. Do not re-run the full setup script for this — on an appliance with no usable network it tears the running stack down and then does network-dependent pulls and builds, over a fault that only stops the cameras working. Instead run `sudo ./scripts/provision-chdk-usb.sh` (installs the rule and the group membership on their own, idempotently, touching nothing else), then restart the backend service (`sudo systemctl restart dtk`) — the service picks up the appliance user's updated group membership on restart, without needing a reboot. +- **The log names a permissions problem opening the camera, and the card and the backend selection both check out:** this is the udev rule. Confirm with `lsusb` — you should see one "Canon, Inc." line per camera, the same as for the gPhoto2 cameras; if `lsusb` sees it, the camera is physically fine and this is a permissions problem. Do not re-run the full setup script for this — on an appliance with no usable network it tears the running stack down and then does network-dependent pulls and builds, over a fault that only stops the cameras working. Instead, from the checkout root (`/home/pi/dtk`), run `sudo ./scripts/provision-chdk-usb.sh`. It installs libusb (already present on a provisioned appliance), the udev rule and the group membership, and nothing else, and it is safe to run again. Then restart the backend service (`sudo systemctl restart dtk`) — the service picks up the appliance user's updated group membership on restart, without needing a reboot. - **The log says the camera is busy or already claimed:** restarting the backend service only helps if the stale claim is the *backend's own*, left over from a previous run of it that did not release the camera cleanly — restarting `dtk` then releases it. It does nothing for a claim held by anything else running on the appliance, and that claim survives the restart and can simply grab the camera again the next time it is plugged in. Find whatever process actually holds it (for example, check what else is running on the appliance, or which process has the device node open) and stop that process specifically. - **A camera does not appear at all, and `lsusb` does not see it either:** this is the USB cable, not the software — check the connection and the camera's power. - **Two cameras refuse to capture, one or both reporting a conflict:** read both the parity and the identity of each camera from the device list yourself — do not assume the error text names the only thing wrong. The device list reports an identity clash first whenever one is present, even on a camera that also shares its parity with the other; but the parity is what an assignment request itself checks first, and it will refuse for a shared parity before it ever gets to identity, regardless of which one the list's error text was talking about. So resolve a shared parity first, whether or not the error mentions it: diff --git a/content/en/docs/cameras/gphoto2.md b/content/en/docs/cameras/gphoto2.md index 80ac47f..51cdcc6 100644 --- a/content/en/docs/cameras/gphoto2.md +++ b/content/en/docs/cameras/gphoto2.md @@ -10,7 +10,7 @@ source: docs/users/setting-up-gphoto2-cams.qmd For a comprehensive list of gPhoto2-supported cameras, visit the [official support page](http://gphoto.org/proj/libgphoto2/support.php). -To be fully compatible with the Digitization Toolkit software, cameras should support all of the following capabilities: Image Capture, Trigger Capture, Live View, and Configuration. +To be fully compatible with Captua, cameras should support all of the following capabilities: Image Capture, Trigger Capture, Live View, and Configuration. {{< /callout >}} ## Connect the cameras to the Raspberry Pi {#connect-the-cameras-to-the-raspberry-pi} @@ -41,6 +41,20 @@ gphoto2 --auto-detect # expect both cameras listed If a camera is missing: reseat both cable ends, power-cycle the camera body, and check `dmesg | tail` — repeated `error -71` messages point to a bad cable or a poorly seated plug; total silence with a powered-on camera points to a charge-only cable. +## Select the gPhoto2 backend {#select-the-gphoto2-backend} + +The backend defaults to `CAMERA_BACKEND=picamera2`, which looks only for the Pi's own ribbon-cable sensors, and the appliance's setup does not change that. With the default, the interface shows no DSLR cameras even when `gphoto2 --auto-detect` lists both. Confirm that the appliance's `.env` file (at the project root) has: + +``` +CAMERA_BACKEND=gphoto2 +``` + +and then restart the backend service so it takes effect: + +```bash +sudo systemctl restart dtk +``` + ## Canon EOS Rebel T7 {#canon-eos-rebel-t7} - Set the focus mode to "Manual Focus": On the lens switch, set the focus mode to MF (Manual Focus). @@ -60,9 +74,9 @@ If a camera is missing: reseat both cable ends, power-cycle the camera body, and {{< media id="cannon-eos-rebelt7-config-menu" >}} {{< callout type="caution" appearance="simple" >}} -When the software opens a session on a body, which happens on the first preview, capture, or settings read after the body is switched on, it attempts to switch the body's Auto power off setting off so the camera cannot sleep mid-session; it never powers the camera off itself. Until a session has been opened, the body's own setting applies, so a body that sat idle before the first preview of the day may already have left the USB bus. If the Raspberry Pi crashes or is powered off while a session is open, the camera can stay on until you switch it off by hand. +When the software opens a session on a body, which happens on the first preview, capture, or settings read after the body is switched on, it attempts to switch the body's Auto power off setting off so the camera cannot sleep mid-session; it never powers the camera off itself. Until a session has been opened, the body's own setting applies, so a body that sat idle before the first preview of the day may already have left the USB bus. The software does not restore Auto power off when it closes a session, so after any shutdown of the service or the Raspberry Pi, not only a crash, the camera can stay on until you switch it off by hand. If the camera menu then shows Auto power off as disabled, set it back to 15 minutes. {{< /callout >}} {{< callout type="important" appearance="simple" >}} -When Auto power off fires, the camera does not just sleep — it **drops off the USB bus entirely** (`lsusb` no longer lists it), and the software cannot wake it: a slept body looks exactly like a disconnected one, and the interface will show the camera as not connected. To bring it back, **half-press the shutter button** on the camera, wait a few seconds for it to re-enumerate, then press **Reconnect cameras** in the interface (on the dashboard camera panel or in the live preview controls). The same action recovers a body whose USB cable was reseated. Keep this in mind before unplugging anything or restarting services. +When Auto power off fires, the camera does not just sleep — it **drops off the USB bus entirely** (`lsusb` no longer lists it), and the software cannot wake it: a slept body looks exactly like a disconnected one, and the interface will show the camera as not connected. To bring it back, **half-press the shutter button** on the camera, wait a few seconds for it to re-enumerate, then press **Reconnect cameras** in the interface (on the camera panel of **Overview** or in the live preview controls). The same action recovers a body whose USB cable was reseated. Keep this in mind before unplugging anything or restarting services. {{< /callout >}} diff --git a/content/en/docs/deployment/pi5-imx519.md b/content/en/docs/deployment/pi5-imx519.md index a6fdca7..3642f78 100644 --- a/content/en/docs/deployment/pi5-imx519.md +++ b/content/en/docs/deployment/pi5-imx519.md @@ -17,7 +17,7 @@ This guide explains how to connect and configure the **Arducam IMX519** camera o * Arducam IMX519 Camera Module, SKU: B0371 x 2 * CSI **22-to-22-pin Ribbon Cable** (15 cm or 20 cm recommended) x 2 * Raspberry Pi Official Power Supply (5V/3A or higher, 27 W PSU recommended) -* microSD Card 16 GB with Raspberry Pi OS Lite (64-bit) installed +* microSD Card 16 GB with Raspberry Pi OS (Legacy, 64-bit) Lite, Debian 12 "Bookworm", installed. Raspberry Pi Imager's plain "Raspberry Pi OS Lite (64-bit)" entry now installs Debian 13 "Trixie", which Captua has not been validated against. Initial setup steps for Raspberry Pi OS can be found in the [Raspberry Pi Documentation](https://www.raspberrypi.com/documentation/computers/getting-started.html). diff --git a/content/en/docs/deployment/sd-card-distribution.md b/content/en/docs/deployment/sd-card-distribution.md index 6d2a3ed..98dd71a 100644 --- a/content/en/docs/deployment/sd-card-distribution.md +++ b/content/en/docs/deployment/sd-card-distribution.md @@ -8,7 +8,7 @@ source: docs/developers/sd_card_distribution.qmd *** -This guide explains how to prepare and ship a Raspberry Pi SD card image with the Digitization Toolkit pre-installed, so the recipient can plug it in and access the application from any device on the same network — without any manual IP configuration. +This guide explains how to prepare and ship a Raspberry Pi SD card image with Captua pre-installed, so the recipient can plug it in and access the application from any device on the same network — without any manual IP configuration. --- @@ -22,6 +22,40 @@ The browser calls the API at `/api` on the page's own origin, and Nginx on port ## Preparing the Master Image {#preparing-the-master-image} +### 0. Install Captua on the master card {#install-captua-on-the-master-card} + +Flash **Raspberry Pi OS (Legacy, 64-bit) Lite**, Debian 12 "Bookworm": it is the system Captua is tested on. Raspberry Pi Imager's plain "Raspberry Pi OS Lite (64-bit)" entry now installs Debian 13 "Trixie", which Captua has not been validated against. In Imager's customisation options, set the username to `pi`: `scripts/dtk.service` runs the service as `pi` from `/home/pi/dtk`, and the kiosk installer expects the same user. Set up the network and SSH there as well (see [What the Recipient Needs to Do](#what-the-recipient-needs-to-do)). + +Then, on the Pi, as `pi`, with an internet connection: + +```bash +sudo apt update && sudo apt install -y git +curl -fsSL https://get.docker.com | sudo sh +sudo usermod -aG docker $USER +``` + +Log out and back in, so that the `pi` account is in the `docker` group, then continue: + +```bash +curl -fsSL https://pixi.sh/install.sh | PIXI_VERSION=v0.73.0 bash +git config --global url."https://github.com/".insteadOf "git@github.com:" +git clone --recurse-submodules https://github.com/UCSB-AMPLab/digitization-toolkit-software.git ~/dtk +cd ~/dtk +sudo ./scripts/setup.sh +sudo ./scripts/install-service.sh +sudo systemctl start dtk +curl http://localhost:8000/health # {"status":"ok"} +curl -I http://localhost # HTTP 200, the interface through nginx +sudo ./scripts/installkb.sh +sudo ./scripts/install-kiosk-service.sh +``` + +- The `git config` line comes before the clone because `.gitmodules` registers the submodules over SSH (`git@github.com:`), and the Pi has no GitHub key: the line makes git fetch them over HTTPS. The repositories are public, so the clone needs no token. +- pixi is pinned to the version in `PIXI_VERSION` in `scripts/setup.sh`: older versions cannot read the committed `pixi.lock`. +- `setup.sh` creates `.env` from `.env.example`, builds the frontend image, installs the backend environment, names the unit (step 1), and applies the database migrations. It needs the internet; the card does not need it afterwards. +- `install-service.sh` installs and enables `dtk.service` and `dtk-secrets.service`, but does not start `dtk`; `systemctl start` does, and the two `curl` lines check that the backend and the interface answer. +- `installkb.sh` and `install-kiosk-service.sh` set up the kiosk: the full-screen browser on the display attached to the Pi. + ### 1. Name the unit {#name-the-unit} `setup.sh` names the unit `captua` (step 6f, `scripts/provision-hostname.sh`): it sets the hostname and the `127.0.1.1` line of `/etc/hosts`, and sets `HOST_IP=captua.local` and adds `http://captua.local` to `CORS_ORIGINS` in `.env`. Nothing needs editing by hand. @@ -29,9 +63,11 @@ The browser calls the API at `/api` on the page's own origin, and Nginx on port Two units on one network cannot share a name. For the second unit at such a site, give it its own name when running setup: ```bash -sudo DTK_HOSTNAME=captua-2 ./scripts/setup.sh +sudo CAPTUA_HOSTNAME=captua-2 ./scripts/setup.sh ``` +`setup.sh` still accepts the older name `DTK_HOSTNAME`. + Verify: ```bash @@ -109,13 +145,13 @@ gzip dtk-master.img The result is `dtk-master.img.gz`. On Windows, you can use a compression tool that supports gzip. {{< callout type="note" title="Secrets are per-unit — imaging is safe at any point" >}} -`SECRET_KEY` and `DATABASE_PASSWORD` are regenerated automatically on each physical unit by `dtk-secrets.service` (installed by `install-service.sh`). It records the Pi's hardware serial in `/var/lib/dtk/secrets-provenance`; when a flashed clone boots on a different Pi, the serial mismatch triggers fresh secrets before the backend starts — including rotating the Postgres password inside the cloned data directory. You do **not** need to scrub secrets from the master image, and test-booting the master before imaging is fine. +`SECRET_KEY`, `DATABASE_PASSWORD`, and `BOOTSTRAP_TOKEN` (the token for creating the first account) are regenerated automatically on each physical unit by `dtk-secrets.service` (installed by `install-service.sh`). It records the Pi's hardware serial in `/var/lib/dtk/secrets-provenance`; when a flashed clone boots on a different Pi, the serial mismatch triggers fresh secrets before the backend starts — including rotating the Postgres password inside the cloned data directory. You do **not** need to scrub secrets from the master image, and test-booting the master before imaging is fine. {{< /callout >}} {{< callout type="warning" title="Never add a credential to `.env` by hand" >}} -The per-unit generation above covers `SECRET_KEY` and `DATABASE_PASSWORD`. It does not cover anything you add yourself while preparing a card — and whatever sits in `.env` at imaging time is copied into every clone of that image. The Rionegro card shipped with a live GitHub personal access token in plaintext in `~/dtk/.env`. It was unused and has been revoked, but nothing in the software put it there. +The per-unit generation above covers `SECRET_KEY`, `DATABASE_PASSWORD`, and `BOOTSTRAP_TOKEN`. It does not cover anything you add yourself while preparing a card — and whatever sits in `.env` at imaging time is copied into every clone of that image. A card has been found with a live GitHub personal access token in plaintext in `~/dtk/.env`; nothing in the software put it there. -Provisioning never needs a token: the repositories are public and `setup.sh` clones them anonymously. If a private fetch is ever required, read the token from a prompt so it never appears on the command line, then clear it: +Provisioning never needs a token: the repositories are public, so you clone them over HTTPS with no token, and `setup.sh` makes later submodule fetches use HTTPS as well. If a private fetch is ever required, read the token from a prompt so it never appears on the command line, then clear it: ```bash read -rs -p "Token: " GH_TOKEN && export GH_TOKEN @@ -128,6 +164,15 @@ Do **not** pass it inline as `GH_TOKEN=… gh …`: that writes the token verbat Before imaging a master card, diff `.env` against `.env.example`: it should carry no keys the template does not have. {{< /callout >}} +{{< callout type="warning" title="Provision the offsite copy and accounts on each unit, not on the master" >}} +Everything else on the card is copied into every clone as well, and the per-unit generation does not change it: + +- `/var/lib/dtk/offsite.env` and `/var/lib/dtk/rclone.conf`, which `provision-rclone.sh` writes when it is given a unit's offsite key or Fisqua token. `setup.sh` already runs it without key material; give it none on the master, and provision each unit's offsite copy after flashing, as in [Updating a Unit, step 4](/docs/deployment/updating-a-unit/#provision-the-offsite-copy-without-restarting). +- The database, with every account created during a test boot. Create no accounts on the master. + +From the release after 0.2.0, a card that has been started before its offsite copy is provisioned is in "Scanner only" mode, and so is every clone of it. Set the mode on each unit once its offsite copy is provisioned ([Updating a Unit, 6.2a](/docs/deployment/updating-a-unit/#set-the-units-mode)). +{{< /callout >}} + --- ## Flashing and Delivering the Image {#flashing-and-delivering-the-image} @@ -172,17 +217,17 @@ Do not assume Imager can apply the same customisation options to a cloned local - Try pinging: `ping captua.local` - As a fallback, find the IP via the router's DHCP client list and open it directly: the app works by IP. -**A unit in service before 0.1.0 answers as `digitool.local`** +**A unit in service before 0.1.0-beta answers as `digitool.local`** -Units set up before 0.1.0 were called `digitool`. `update.sh` renames them to `captua` and keeps `digitool.local` answering through 0.1.x (see [Updating a unit](/docs/deployment/updating-a-unit/#the-unit-name-digitool-becomes-captua)). +Units set up before 0.1.0-beta were called `digitool`. `update.sh` renames them to `captua` and keeps `digitool.local` answering; 0.2.0 still does (see [Updating a unit](/docs/deployment/updating-a-unit/#the-unit-name-digitool-becomes-captua)). **CORS errors in the browser** -The browser calls the API on the page's own origin, so the production stack has no cross-origin calls and this error should not occur there. On the development stack (Vite on `:5173` calling the backend on `:8000`), the page's origin must be in `CORS_ORIGINS` in `.env`; update that list and restart the backend. The page and the API must also be on the same site, because the session cookie is `SameSite=Strict`: open the page on `localhost` when `PUBLIC_API_BASE` names `localhost`, and on `127.0.0.1` when it names `127.0.0.1`. With a mismatch the browser shows no CORS error: the backend answers the login with 200 and refuses the next request with 401. [`docs/developers/API_REFERENCE.md`](https://github.com/UCSB-AMPLab/digitization-toolkit-software/blob/dev/docs/developers/API_REFERENCE.md), section 8, CORS Configuration, has the details. +The browser calls the API on the page's own origin, so the production stack has no cross-origin calls and this error should not occur there. On the development stack (Vite on `:5173` calling the backend on `:8000`), the page's origin must be in `CORS_ORIGINS` in `.env`; update that list and restart the backend. The page and the API must also be on the same site, because the session cookie is `SameSite=Strict`: open the page on `localhost` when `PUBLIC_API_BASE` names `localhost`, and on `127.0.0.1` when it names `127.0.0.1`. With a mismatch the browser shows no CORS error: the backend answers the login with 200 and refuses the next request with 401. The [API reference, CORS Configuration](/docs/developers/api-reference/#cors-configuration), has the details. **Two Pis on the same network** -mDNS hostnames must be unique per network. Name the second unit at setup with `DTK_HOSTNAME=captua-2` (step 1). On a unit already set up, run the same script by hand: +mDNS hostnames must be unique per network. Name the second unit at setup with `CAPTUA_HOSTNAME=captua-2` (step 1). On a unit already set up, run the same script by hand: ```bash sudo /home/pi/dtk/scripts/provision-hostname.sh --name captua-2 diff --git a/content/en/docs/deployment/updating-a-unit.md b/content/en/docs/deployment/updating-a-unit.md index 98da742..81dd292 100644 --- a/content/en/docs/deployment/updating-a-unit.md +++ b/content/en/docs/deployment/updating-a-unit.md @@ -1,5 +1,5 @@ --- -title: "Updating a Unit to 0.1.0" +title: "Updating a Unit" url: /docs/deployment/updating-a-unit/ translationKey: docs-deployment-updating-a-unit docs_section: deployment @@ -8,10 +8,12 @@ source: docs/developers/updating_a_unit.qmd *** -This guide is for whoever manages a unit: it takes a unit already in use to 0.1.0, through the one-time steps that follow, in the order they must be done. A short version for a new unit is at the end. +This guide is for whoever manages a unit. It takes a unit that runs a version before 0.1.0-beta to the current release, through the one-time steps that follow, in the order they must be done. The steps were written for the move to 0.1.0-beta, and this guide calls that update "the 0.1.0-beta install"; they apply to every unit that runs a version before 0.1.0-beta, whichever release `main` now carries. A short version for a new unit is at the end. The commands assume a unit installed as `scripts/dtk.service` ships: the checkout at `/home/pi/dtk`, the service running as `pi`. Run them over SSH as `pi`. +Settings are named `CAPTUA_` in this guide. The older `DTK_` names are still read, and the files on a unit (`.env` and `/var/lib/dtk/offsite.env`) keep the `DTK_` names, because a rollback restores code that reads only those. When both names are set, the `CAPTUA_` name wins. + --- ## 1. Before the update {#before-the-update} @@ -24,7 +26,7 @@ git -C /home/pi/dtk submodule status sudo cat /var/lib/dtk/backups/last-deployed-SHA ``` -`update.sh` returns to the commit in `last-deployed-SHA` if it fails, and records it as the rollback target. With `--no-pull`, which the 0.1.0 install uses (2.1), it refuses to start, with nothing changed, when that file is absent, empty, or names a commit not in the checkout: the checkout is already the new code and cannot stand in for it. In that case, before 2.1, write the commit the first command printed: +`update.sh` returns to the commit in `last-deployed-SHA` if it fails, and records it as the rollback target. With `--no-pull`, which the 0.1.0-beta install uses (2.1), it refuses to start, with nothing changed, when that file is absent, empty, or names a commit not in the checkout: the checkout is already the new code and cannot stand in for it. In that case, before 2.1, write the commit the first command printed: ```bash echo | sudo tee /var/lib/dtk/backups/last-deployed-SHA @@ -50,11 +52,11 @@ sudo ls -lt /var/lib/dtk/backups/ ### 1.4 Stop any interim upload timer {#stop-any-interim-upload-timer} -Some units were given an upload timer by hand before the backend could upload. These timers are unit-specific and are not part of the software. On the Rionegro unit the timer is `b2push-interim`, and it runs the script `/home/pi/b2push.sh`, which pushes the images and also takes the daily `pg_dumpall` of the catalogue to the bucket. Find the timer and stop it, so that after the update only the backend writes to the bucket: +Some units were given an upload timer by hand before the backend could upload. These timers are unit-specific and are not part of the software. Such a timer runs a script of its own that pushes the images to the bucket, and it may also push a daily `pg_dumpall` of the catalogue. Find the timer and stop it, so that after the update only the backend writes to the bucket: ```bash systemctl list-timers --all -sudo systemctl disable --now b2push-interim.timer +sudo systemctl disable --now .timer ``` Use the name `list-timers` shows on your unit. The name of the service the timer starts is not recorded; `systemctl list-timers` shows it in its `ACTIVATES` column. If a run of it is in progress, wait for it to end before step 2. @@ -62,12 +64,12 @@ Use the name `list-timers` shows on your unit. The name of the service the timer If you abandon the update before step 3, enable the timer again, so the unit goes on uploading as it did before: ```bash -sudo systemctl enable --now b2push-interim.timer +sudo systemctl enable --now .timer ``` ### 1.5 Pin the unit's Tailscale name {#pin-the-units-tailscale-name} -The update renames the unit from `digitool` to `captua` (2.6) when apt can reach its sources: the alias that keeps `digitool.local` answering needs `avahi-utils`, which the update installs. A unit that cannot reach apt keeps its name until an update that can. Tailscale takes the machine's name from its hostname unless the name is set, so a unit reached as `ssh pi-dtk` or by its Tailscale name would change name in the tailnet with it. Set the Tailscale name explicitly first, to the name the unit has in the tailnet now: +The update renames the unit from `digitool` to `captua` (2.6) when apt can reach its sources: the alias that keeps `digitool.local` answering needs `avahi-utils`, which the update installs. A unit that cannot reach apt keeps its name until an update that can. Tailscale takes the machine's name from its hostname unless the name is set, so a unit reached over SSH by its Tailscale name would change name in the tailnet with it. Set the Tailscale name explicitly first, to the name the unit has in the tailnet now: ```bash tailscale status --self @@ -80,11 +82,11 @@ The software does not touch Tailscale. Skip this on a unit without Tailscale. ## 2. Run the update {#run-the-update} -### 2.1 Put the 0.1.0 code on disk first {#put-the-0.1.0-code-on-disk-first} +### 2.1 Put the 0.1.0-beta code on disk first {#put-the-0.1.0-code-on-disk-first} -For the 0.1.0 install, fetch and check out the new code by hand, and only then run `update.sh` with `--no-pull`. This is the only path for this install, on every unit. Bash reads a script from disk as it runs, so an `update.sh` that fetches its own update runs the old copy's failure handling, and none of the protections of the new script apply to that run. +For the 0.1.0-beta install, fetch and check out the new code by hand, and only then run `update.sh` with `--no-pull`. This is the only path for this install, on every unit. Bash reads a script from disk as it runs, so an `update.sh` that fetches its own update runs the old copy's failure handling, and none of the protections of the new script apply to that run. -Units run `main`, which moves only at releases. A unit on `dev` (the bench unit and the Rionegro unit, at the time of writing) is moved to `main` here, once. As `pi`: +Units run `main`, which moves only at releases. A unit on `dev` is moved to `main` here, once. As `pi`: ```bash git -C /home/pi/dtk fetch origin @@ -138,7 +140,7 @@ git -C /home/pi/dtk submodule foreach --quiet --recursive 'git ls-files -v | gre `checkout` refuses when local changes would be overwritten; set them aside by hand first, since `update.sh` does that only when it fetches. -**After a rollback to a version before 0.1.0.** The rollback puts back that version's `update.sh`, which is not the 0.1.0 one. The next update must again take this path: fetch and check out the code by hand, then run the new `update.sh` with `--no-pull` (8.4). The ordinary path in "Later updates" below would run the old script. +**After a rollback to a version before 0.1.0-beta.** The rollback puts back that version's `update.sh`, which is not the 0.1.0-beta one. The next update must again take this path: fetch and check out the code by hand, then run the new `update.sh` with `--no-pull` (8.4). The ordinary path in "Later updates" below would run the old script. ### 2.2 Run `update.sh` outside the SSH session {#run-update.sh-outside-the-ssh-session} @@ -167,7 +169,7 @@ With `--no-pull`, `update.sh` installs whatever is checked out, so it checks the Each refusal says `Nothing has been changed.` The script prints its git commands with `sudo -u pi`; as `pi`, leave that prefix out. The fourth prints `sudo /home/pi/dtk/scripts/rollback-update.sh`. -**Later updates (0.1.x onward).** The script on disk is then already the 0.1.0 one, so the ordinary path applies: `sudo systemd-run --unit=dtk-deploy --collect /home/pi/dtk/scripts/update.sh --yes`, which fetches and fast-forwards `main` itself. This holds only while the checkout is on 0.1.0 or later. After any rollback to a version before 0.1.0, the script on disk is the old one again, and the next update takes the 2.1 path: fetch and check out by hand, then the new `update.sh` with `--no-pull` (8.4). +**Later updates (0.1.x onward).** The script on disk is then already the 0.1.0-beta one, so the ordinary path applies: `sudo systemd-run --unit=dtk-deploy --collect /home/pi/dtk/scripts/update.sh --yes`, which fetches and fast-forwards `main` itself. This holds only while the checkout is on 0.1.0-beta or later. After any rollback to a version before 0.1.0-beta, the script on disk is the old one again, and the next update takes the 2.1 path: fetch and check out by hand, then the new `update.sh` with `--no-pull` (8.4). ### 2.3 What `update.sh` does {#what-update.sh-does} @@ -205,7 +207,7 @@ journalctl -u dtk --since "15 min ago" | grep -E "Volume layout:|Cannot start|Tr ### 2.5 Check that nothing uploads yet {#check-that-nothing-uploads-yet} -The backend starts its upload schedules at boot only when `DTK_OFFSITE_REMOTE` and a valid `DTK_OFFSITE_TENANT` are both set. A unit not yet provisioned for 0.1.0 has no tenant, so nothing is uploaded. Confirm it before step 3 with the request in 6.3: `images.enabled` must be `false`. If it is `true`, the uploader keys each object by the file's name on disk, so an image copied into the bucket under a contract name would be uploaded again at a second key, and `adopt-map` would then refuse its entry as `key_differs`. On a unit whose `offsite.env` already records a remote and a tenant, create the upload hold (4.0) before step 2, so the backend holds uploads from the update's restart on: +The backend starts its upload schedules at boot only when `CAPTUA_OFFSITE_REMOTE` and a valid `CAPTUA_OFFSITE_TENANT` are both set. A unit not yet provisioned for 0.1.0-beta has no tenant, so nothing is uploaded. Confirm it before step 3 with the request in 6.3: `images.enabled` must be `false`. If it is `true`, the uploader keys each object by the file's name on disk, so an image copied into the bucket under a contract name would be uploaded again at a second key, and `adopt-map` would then refuse its entry as `key_differs`. On a unit whose `offsite.env` already records a remote and a tenant, create the upload hold (4.0) before step 2, so the backend holds uploads from the update's restart on. The file records the two keys under their `DTK_` names: ```bash sudo grep -E '^DTK_OFFSITE_(REMOTE|TENANT)=' /var/lib/dtk/offsite.env @@ -213,20 +215,20 @@ sudo grep -E '^DTK_OFFSITE_(REMOTE|TENANT)=' /var/lib/dtk/offsite.env ### 2.6 The unit name: digitool becomes captua {#the-unit-name-digitool-becomes-captua} -From 0.1.0 every unit is called `captua` and answers at `http://captua.local`. The browser calls the API at `/api` on the page's own origin, through nginx, so the unit also works when opened by its IP address or by any other name that reaches it, and the kiosk opens `http://localhost` instead of `http://localhost:3000`. +From 0.1.0-beta every unit is called `captua` and answers at `http://captua.local`. The browser calls the API at `/api` on the page's own origin, through nginx, so the unit also works when opened by its IP address or by any other name that reaches it, and the kiosk opens `http://localhost` instead of `http://localhost:3000`. `update.sh` renames a unit only when its hostname is exactly `digitool` and `.env` has `HOST_IP=digitool.local`. A unit named otherwise by hand is left alone. The work is done by `scripts/provision-hostname.sh`, in two calls: -- Before the stop (`--prepare`): it installs `avahi-utils` from apt if it is missing, the alias script `/usr/local/sbin/dtk-mdns-alias`, its unit `dtk-mdns-alias.service`, the NetworkManager hook `/etc/NetworkManager/dispatcher.d/90-dtk-mdns-alias`, and the drop-in `/etc/systemd/system/dtk.service.d/hostname-repair.conf`. It tries apt under `--no-pull` too, so the 0.1.0 install (2.1) renames a unit that can reach apt. Only `update.sh --no-pull --offline` skips apt. When `avahi-utils` cannot be installed, the log says `The rename to captua waits for avahi-utils`, the unit keeps the name `digitool` until an update that can reach apt, and the update goes on. -- With `dtk` stopped (`--switch`): it writes `127.0.1.1 captua digitool` to `/etc/hosts`, runs `hostnamectl set-hostname captua`, restarts `avahi-daemon`, and starts `dtk-mdns-alias`, which keeps `digitool.local` answering through 0.1.x. It then checks that `captua.local` and `digitool.local` both resolve, to one of the unit's own addresses. If either does not, or resolves to another device, it puts the name, `/etc/hosts`, avahi, and the alias back and leaves `.env` as it was. If both do, it sets `HOST_IP=captua.local` in `.env` and adds `http://captua.local` to `CORS_ORIGINS`, keeping `http://digitool.local`. +- Before the stop (`--prepare`): it installs `avahi-utils` from apt if it is missing, the alias script `/usr/local/sbin/dtk-mdns-alias`, its unit `dtk-mdns-alias.service`, the NetworkManager hook `/etc/NetworkManager/dispatcher.d/90-dtk-mdns-alias`, and the drop-in `/etc/systemd/system/dtk.service.d/hostname-repair.conf`. It tries apt under `--no-pull` too, so the 0.1.0-beta install (2.1) renames a unit that can reach apt. Only `update.sh --no-pull --offline` skips apt. When `avahi-utils` cannot be installed, the log says `The rename to captua waits for avahi-utils`, the unit keeps the name `digitool` until an update that can reach apt, and the update goes on. +- With `dtk` stopped (`--switch`): it writes `127.0.1.1 captua digitool` to `/etc/hosts`, runs `hostnamectl set-hostname captua`, restarts `avahi-daemon`, and starts `dtk-mdns-alias`, which keeps `digitool.local` answering. The alias is still installed in 0.2.0; no release has removed it yet. It then checks that `captua.local` and `digitool.local` both resolve, to one of the unit's own addresses. If either does not, or resolves to another device, it puts the name, `/etc/hosts`, avahi, and the alias back and leaves `.env` as it was. If both do, it sets `HOST_IP=captua.local` in `.env` and adds `http://captua.local` to `CORS_ORIGINS`, keeping `http://digitool.local`. Neither call can make the update fail. A rename that does not happen prints `⚠ The rename to captua did not finish`, and the unit keeps working as `digitool`. A power cut in the middle of the rename is handled at the next start of `dtk`: the drop-in runs `provision-hostname.sh --repair`. If the hostname had already changed, it writes the `127.0.1.1 captua digitool` line again, starts the alias, and checks both names as the rename does. When both resolve to the unit it finishes `.env` and records the rename as done; when `captua.local` answers from another device it undoes the rename; when the names do not answer yet (no network at boot) it finishes `.env` and leaves the record pending for the next start. If the hostname is still `digitool`, it undoes the rename; if it has since been set by hand to another name (`--name`), it keeps that name and removes the record. An undo puts `/etc/hosts` back only once the hostname is `digitool` again; if `hostnamectl` fails, everything stays as it is for the next start to try. A unit called `captua` whose `.env` still has `HOST_IP=digitool.local` is finished the same way, whatever the record says. The repair also removes the temporary files a power cut can leave next to `.env`, `/etc/hosts`, and the record. -A failed update, and a rollback, restore the code but not the name. The code before 0.1.0 works under it: its frontend calls `http://${HOST_IP}/api`, now `http://captua.local/api`, which resolves, and `CORS_ORIGINS` lists both names, so a page opened as `digitool.local` can call it. +A failed update, and a rollback, restore the code but not the name. The code before 0.1.0-beta works under it: its frontend calls `http://${HOST_IP}/api`, now `http://captua.local/api`, which resolves, and `CORS_ORIGINS` lists both names, so a page opened as `digitool.local` can call it. -Once the new version answers `/health`, `update.sh` ends the kiosk's `cage` (only `pi`'s), and the tty1 autologin relaunches it from the new `start-kiosk.sh`, on `http://localhost`. That is a new origin for the browser, so the kiosk asks for a login once. `update.sh --resolve-forward` (7.4) relaunches it the same way once it has started `dtk`, and a rollback relaunches it on the restored version's address. Chromium's profile lock, `~/.config/chromium/SingletonLock`, names the hostname it was taken under, and Chromium refuses a profile locked under another name. The rename points the running kiosk's lock at `captua` (and an undo back at `digitool`), so that the next Chromium, started by whichever `start-kiosk.sh` is on disk after an update, a restore or a rollback, can take it over. The kiosk user is read from the tty1 autologin that `install-kiosk-service.sh` sets up. Before it starts Chromium, the 0.1.0 `start-kiosk.sh` also removes `SingletonLock`, `SingletonCookie`, and `SingletonSocket`, unless a Chromium of `pi`'s is still running. +Once the new version answers `/health`, `update.sh` ends the kiosk's `cage` (only `pi`'s), and the tty1 autologin relaunches it from the new `start-kiosk.sh`, on `http://localhost`. That is a new origin for the browser, so the kiosk asks for a login once. `update.sh --resolve-forward` (7.4) relaunches it the same way once it has started `dtk`, and a rollback relaunches it on the restored version's address. Chromium's profile lock, `~/.config/chromium/SingletonLock`, names the hostname it was taken under, and Chromium refuses a profile locked under another name. The rename points the running kiosk's lock at `captua` (and an undo back at `digitool`), so that the next Chromium, started by whichever `start-kiosk.sh` is on disk after an update, a restore or a rollback, can take it over. The kiosk user is read from the tty1 autologin that `install-kiosk-service.sh` sets up. Before it starts Chromium, the 0.1.0-beta `start-kiosk.sh` also removes `SingletonLock`, `SingletonCookie`, and `SingletonSocket`, unless a Chromium of `pi`'s is still running. Two units on one network that are both called `digitool` cannot both become `captua`: the second one's check finds `captua.local` answering from the first and undoes its rename. Give it its own name by hand, as in [SD Card Distribution](/docs/deployment/sd-card-distribution/), troubleshooting; its update then leaves it alone. @@ -250,7 +252,7 @@ Setting a stem moves no file. The backend writes new captures into the volume to ### 3.2 Preview the move (optional) {#preview-the-move-optional} -`python -m app.core.volume_layout --dry-run` prints, as JSON, what the next start would move, and writes nothing. It needs the database up and the backend stopped, so stop `dtk`, start the database alone, run it, and stop the database again (verify on the bench): +`python -m app.core.volume_layout --dry-run` prints, as JSON, what the next start would move, and writes nothing. It needs the database up and the backend stopped, so stop `dtk`, start the database alone, run it, and stop the database again (verify on a test unit): ```bash sudo systemctl stop dtk @@ -314,7 +316,7 @@ The skip reasons: | `missing` | The row's file is gone and no file in `captures/` matches its capture-time sha256. | | `row_changed` | The row changed while the move was being planned. | -The journal also holds lines logged at INFO, such as the one for freed files pointed at their new names: since backend `aa0a10a` (#134), the backend sends the INFO lines of its own `app.*` and `capture.*` loggers to stderr, which the journal records, as ` : ` (`app/core/logging_setup.py`). The level is set by `DTK_LOG_LEVEL`, `INFO` by default. +The journal also holds lines logged at INFO, such as the one for freed files pointed at their new names: since backend `aa0a10a` (#134), the backend sends the INFO lines of its own `app.*` and `capture.*` loggers to stderr, which the journal records, as ` : ` (`app/core/logging_setup.py`). The level is set by `CAPTUA_LOG_LEVEL`, `INFO` by default. --- @@ -328,7 +330,7 @@ While `/var/lib/dtk/offsite-hold` exists, nothing is sent offsite: - the backend takes no catalogue dump; - freeing a volume from the card is refused. The free's dry run and restore are not held. -The backend checks for the file at the start of each run, so creating or removing it takes effect at the next run, with no restart. It also holds through a restart caused by a crash, a reboot, or a power cut. The commands in step 5 do not read it. Only the file's existence counts. Its path can be changed with `DTK_OFFSITE_HOLD_FILE`. `GET /system/catalogue-backup` reports it as `held` and `hold_file`. The send to Fisqua and the Fisqua status poll are held too: each answers "held" at its start, with no call to Fisqua and no manifest built (9.3). +The backend checks for the file at the start of each run, so creating or removing it takes effect at the next run, with no restart. It also holds through a restart caused by a crash, a reboot, or a power cut. The commands in step 5 do not read it. Only the file's existence counts. Its path can be changed with `CAPTUA_OFFSITE_HOLD_FILE`. `GET /system/catalogue-backup` reports it as `held` and `hold_file`. The send to Fisqua and the Fisqua status poll are held too: each answers "held" at its start, with no call to Fisqua and no manifest built (9.3). Create it before provisioning, or before step 2 on a unit whose `offsite.env` already records a remote and a tenant (2.5): @@ -361,22 +363,21 @@ READ_APP_KEY=... | Key | What it is | |---|---| -| `KEY_ID`, `APP_KEY` | The unit's write key, `captua--write`: `listBuckets`, `listFiles`, and `writeFiles`. No `readFiles` and no `deleteFiles`, so a stolen unit can neither download nor erase the archive. | +| `KEY_ID`, `APP_KEY` | The unit's write key, `captua--write`: `listBuckets`, `listFiles`, and `writeFiles`. No `readFiles` and no `deleteFiles`, so a stolen unit can neither download nor erase the archive. | | `BUCKET` | The unit's bucket (table below). | -| `READ_KEY_ID`, `READ_APP_KEY` | Optional. The unit's read key, `captua--read`: `listBuckets`, `listFiles`, and `readFiles`. It must differ from the write key. Without it, restoring a freed volume is unavailable. | +| `READ_KEY_ID`, `READ_APP_KEY` | Optional. The unit's read key, `captua--read`: `listBuckets`, `listFiles`, and `readFiles`. It must differ from the write key. Without it, restoring a freed volume is unavailable. | -Both keys are scoped to the unit's bucket and its tenant prefix. `provision-rclone.sh` asks only for `writeFiles` and `listFiles` on the write key and `listFiles` and `readFiles` on the read key; the keys issued for 0.1.0 also carry `listBuckets`, as the interim Rionegro key did. Each 0.1.0 key was tested from a workstation with the `b2` command-line tool: it authorised, listed its tenant prefix, and was refused outside it. rclone on a unit has not used them yet, and no key without `listBuckets` has been tried, so whether rclone needs `listBuckets` is untested (verify). The file's mode is 0600 and its owner root. +Both keys are scoped to the unit's bucket and its tenant prefix. `provision-rclone.sh` asks only for `writeFiles` and `listFiles` on the write key and `listFiles` and `readFiles` on the read key; the keys issued for 0.1.0-beta also carry `listBuckets`, as the earlier interim keys did. Each 0.1.0-beta key was tested from a workstation with the `b2` command-line tool: it authorised, listed its tenant prefix, and was refused outside it. rclone on a unit has not used them yet, and no key without `listBuckets` has been tried, so whether rclone needs `listBuckets` is untested (verify). The file's mode is 0600 and its owner root. For the link to Fisqua, the same file holds `FISQUA_TOKEN=`, the token Fisqua issued for this unit: exactly 64 lowercase hexadecimal characters (9.2). #### Units and tenants {#units-and-tenants} +Each unit has its own tenant and its own pair of keys. Several units can share a bucket. Whoever manages the offsite storage records, for each unit: + | Unit | Tenant (`--tenant`) | Bucket (`BUCKET`) | Keys | |---|---|---|---| -| rionegro | `ahr` | `neogranadina-masters` | `captua-rionegro-write`, `captua-rionegro-read` | -| lab | `ampl` | `ampl-masters` | `captua-lab-write`, `captua-lab-read` | -| sbmal | `sbmal` | `ampl-masters` | `captua-sbmal-write`, `captua-sbmal-read` | -| cobos (staging only) | `cobos` | `ampl-masters` | `captua-cobos-write`, `captua-cobos-read` | +| `captua-` | `` | `` | `captua--write`, `captua--read` | Never print a key id or an application key in a log, a ticket, or this guide. @@ -385,14 +386,14 @@ Never pass a key as an assignment in front of `sudo`: it becomes part of sudo's ### 4.2 Run the provisioning script {#run-the-provisioning-script} ```bash -sudo DTK_OFFSITE_KEY_FILE=/root/dtk-offsite-key \ +sudo CAPTUA_OFFSITE_KEY_FILE=/root/dtk-offsite-key \ /home/pi/dtk/scripts/provision-rclone.sh \ --tenant \ - --dump-recipient age172wkzadqepd565chppztfw8jefpcga8s7t6eqrfhnxnv2nlfkdrqygrl3m + --dump-recipient ``` - `--tenant` is the prefix every object of the unit is keyed under, and the unit's slug in Fisqua. The script refuses a value that is not 1 to 63 lowercase letters, digits, and single hyphens, starting with a letter and not ending with a hyphen, or that is one of `platform`, `www`, `api`, `admin`, or `app`. Replacing a tenant already recorded also needs `--change-tenant`. -- `--dump-recipient` is the age public key the catalogue dumps are encrypted to; the one above is the recipient for every unit. The script refuses a private key. The private key never goes on the unit. +- `--dump-recipient` is the age public key the catalogue dumps are encrypted to, `age1` followed by 58 characters. Every unit uses the same recipient; whoever holds its private key gives it to you. The script refuses a private key. The private key never goes on the unit. - `--fisqua-env production` or `--fisqua-env staging` turns on the link to Fisqua, with `FISQUA_TOKEN` in the key file (9.2). - The tenant, the dump recipient, the Fisqua environment, and the Fisqua token are kept on later runs that do not give them, including the run inside every update. @@ -414,7 +415,7 @@ sudo rm /root/dtk-offsite-key sudo sed 's/^DTK_FISQUA_TOKEN=.*/DTK_FISQUA_TOKEN=(not shown)/' /var/lib/dtk/offsite.env ``` -The `sed` prints the file with the Fisqua token replaced, so the token does not reach the screen. The file holds `DTK_RCLONE_BIN`, `DTK_OFFSITE_REMOTE`, `DTK_OFFSITE_TENANT`, and `DTK_OFFSITE_DUMP_RECIPIENT`; `DTK_OFFSITE_READ_REMOTE` when a read key was given; `DTK_RCLONE_CONFIG` when the run established the rclone config's path; and `DTK_FISQUA_TOKEN` and `DTK_FISQUA_ENV` on a unit with the link to Fisqua (9.2). +The `sed` prints the file with the Fisqua token replaced, so the token does not reach the screen. The file records its keys under their `DTK_` names. It holds `DTK_RCLONE_BIN`, `DTK_OFFSITE_REMOTE`, `DTK_OFFSITE_TENANT`, and `DTK_OFFSITE_DUMP_RECIPIENT`; `DTK_OFFSITE_READ_REMOTE` when a read key was given; `DTK_RCLONE_CONFIG` when the run established the rclone config's path; and `DTK_FISQUA_TOKEN` and `DTK_FISQUA_ENV` on a unit with the link to Fisqua (9.2). ### 4.4 Why nothing uploads yet {#why-nothing-uploads-yet} @@ -426,9 +427,9 @@ A backend restarted before step 6, by a crash, a reboot, or a power cut, reads t ### 4.5 Offsite bandwidth {#offsite-bandwidth} -The backend runs the image uploads, the catalogue dump uploads, and the restores of freed files under one bandwidth cap, `DTK_OFFSITE_BWLIMIT`, passed to rclone as `--bwlimit`. Bucket listings and calls to Fisqua are not capped. The default is `750k`, about 750 KB/s (verify the unit rclone reads), the setting the Rionegro unit has used over its ~12 Mbit/s link. For another site, measure the uplink in Mbit/s, divide by 8 for MB/s, and take about half. The bench unit ran with the default until the `cobos-bench-005` run (9.3), and was set to `1.5M` after it, from a home uplink of ~25 Mbit/s measured on 2026-10-25. +The backend runs the image uploads, the catalogue dump uploads, and the restores of freed files under one bandwidth cap, `CAPTUA_OFFSITE_BWLIMIT`, passed to rclone as `--bwlimit`. Bucket listings and calls to Fisqua are not capped. The default is `750k`, about 750 KB/s (verify the unit rclone reads), a setting in use over a link of about 12 Mbit/s. For another site, measure the uplink in Mbit/s, divide by 8 for MB/s, and take about half: an uplink of about 25 Mbit/s gives about 3 MB/s, and half of that is `1.5M`. -Set it in `/home/pi/dtk/.env`; `provision-rclone.sh` does not write it: +Set it in `/home/pi/dtk/.env`, under the `DTK_` name the unit's files keep; `provision-rclone.sh` does not write it: ```bash DTK_OFFSITE_BWLIMIT=1.5M @@ -455,7 +456,7 @@ The reports can be long. Send each to a file and read it there: pixi run python -m app.core.image_upload adopt-map /path/to/map.json > ~/adopt-map--dry.json ``` -`adopt`, `adopt-map`, and `backfill-preview-digests` hash the files on the card in the dry run as well as with `--apply`, so both runs take time on a large volume, and an SSH disconnect stops them. Under `systemd-run` they survive a disconnect. Send the report to a file, truncated at each run, and errors to the journal (verify the form on the bench): +`adopt`, `adopt-map`, and `backfill-preview-digests` hash the files on the card in the dry run as well as with `--apply`, so both runs take time on a large volume, and an SSH disconnect stops them. Under `systemd-run` they survive a disconnect. Send the report to a file, truncated at each run, and errors to the journal (verify the form on a test unit): ```bash sudo systemd-run --unit=dtk-adopt --collect --uid=pi \ @@ -483,9 +484,9 @@ The whole map is refused, with `error: ` and nothing written, when: - its `contract`, `version`, or `kind` is not `fisqua-captua-exchange`, `1.1`, and `rename-map`; - it has no `volume` or `destination` object, or `entries` is not a list; - no volume on the unit has both its `volume.captuaCollectionId` and its `volume.stem`; -- `DTK_OFFSITE_REMOTE` is unset or not `:`, or its bucket is not `destination.bucket`; +- `CAPTUA_OFFSITE_REMOTE` is unset or not `:`, or its bucket is not `destination.bucket`; - `destination.root` is not a key prefix; -- `DTK_OFFSITE_TENANT` is unset or invalid, or is not the first segment of `destination.root`; +- `CAPTUA_OFFSITE_TENANT` is unset or invalid, or is not the first segment of `destination.root`; - a bucket listing does not answer. Read `refused` and `refused_counts` in the dry run. Resolve every refused entry whose image is still on the card before the backend starts uploading in step 6: the uploader would otherwise upload that file at a second key, its name on disk. Apply every map before 5.2, so that `adopt` does not record a key a map names differently. @@ -497,7 +498,7 @@ pixi run python -m app.core.image_upload adopt pixi run python -m app.core.image_upload adopt --apply ``` -`` is relative to `DTK_OFFSITE_REMOTE`. The command lists it, hashes each image of a volume with a stem that has no key yet, and records a listed object as the image's key when exactly one object carries the same SHA1. Ambiguous matches and keys already held are reported, not recorded. It only matches files still on the card. +`` is relative to `CAPTUA_OFFSITE_REMOTE`. The command lists it, hashes each image of a volume with a stem that has no key yet, and records a listed object as the image's key when exactly one object carries the same SHA1. Ambiguous matches and keys already held are reported, not recorded. It only matches files still on the card. The command does not check the tenant, but give it a prefix under the tenant (`/...`). A free lists each key's directory and lists nothing outside the tenant prefix, so a volume with a key adopted outside it can never be freed. @@ -546,7 +547,7 @@ It records the sha256 of each RAW preview captured before previews were listed i sudo systemctl restart dtk ``` -The backend now reads the tenant and starts both schedules. The backend runs each one first `DTK_OFFSITE_BACKUP_DELAY` seconds after the start (300 by default), and again `DTK_OFFSITE_BACKUP_INTERVAL` seconds after each run ends (1800 by default). +The backend now reads the tenant and starts both schedules; from the release after 0.2.0 they send nothing until the mode allows it (6.2a). The backend runs each one first `CAPTUA_OFFSITE_BACKUP_DELAY` seconds after the start (300 by default), and again `CAPTUA_OFFSITE_BACKUP_INTERVAL` seconds after each run ends (1800 by default). ### 6.2 Remove the hold {#remove-the-hold} @@ -558,10 +559,22 @@ sudo rm /var/lib/dtk/offsite-hold The backend starts uploading at its next scheduled run, with no restart. +### 6.2a Set the unit's mode (from the release after 0.2.0) {#set-the-units-mode} + +This step applies from the release after 0.2.0. 0.2.0 has no unit mode. + +From that release, a unit runs in one of three modes: "Scanner only", in which nothing leaves the unit; "Offsite copy only", in which the images and the catalogue are copied to the bucket; and "Fisqua", which adds the link to Fisqua. The backend sets the mode once, at the first start of that release, from what is configured at that start: "Fisqua" when the link to Fisqua is configured, "Offsite copy only" when the offsite copy is, and "Scanner only" otherwise. In this guide the update's start (2.2) comes before the offsite copy is provisioned (step 4), so on most units the backend sets "Scanner only", and the unit stays in that mode after the restart in 6.1: the backend uploads nothing and sends nothing to Fisqua. On a unit whose `offsite.env` already records a remote and a tenant (2.5), that start sets "Offsite copy only", or "Fisqua" when the link to Fisqua is configured; the hold (4.0) is then the only thing that stops uploads. The backend also sets "Scanner only" on a new unit, or a card, started before its offsite copy was provisioned. + +After 6.2, open **Settings** with an administrator account and, under **Unit mode**, choose "Offsite copy only" or "Fisqua". Captua refuses the switch, and names each missing item, while the offsite copy or the catalogue's offsite copy (with its age recipient) is not configured. For "Fisqua", Captua also refuses it while the link to Fisqua is not configured, while the offsite hold exists, and when Fisqua cannot be reached or does not accept the switch: Captua tells Fisqua of the switch before it makes it. + +Captua keeps on the unit every volume created in "Scanner only" mode: it copies none of their images offsite and sends none of their manifests to Fisqua. When you switch the unit from "Scanner only" to another mode while it keeps such volumes, choose, under **Volumes Captua keeps on this unit**, **Include them** or **Keep them here**. Captua does not change the mode until you choose. + +Once the mode is set, the check in 6.3 also requires `mode_allows` and `images.mode_allows` to be `true`, and, on a unit with the link to Fisqua, `fisqua.mode_allows`. + ### 6.3 Check {#check} - **Each volume's received indicator.** On the volume's page, the offsite line is `Uploading: N of M files verified, P pending` while the upload is under way, and `Stored offsite: N of N files verified` once every object is verified. `N files need attention` means objects were refused: the bucket holds a different file at the key (`remote_differs`), or the file's sha256 is not the one its capture record holds (`fixity`). A refused object is not retried. `GET /collections/{id}/offsite` returns the same counts. -- **The unit's offsite state.** The Configuration page's **Offsite copy** section and the indicator in the dashboard read `GET /system/catalogue-backup`. From the unit: +- **The unit's offsite state.** The **Settings** page's **Offsite copy** section and the indicator in the dashboard read `GET /system/catalogue-backup`. From the unit: ```bash read -rs -p "Password: " PW; echo @@ -574,7 +587,7 @@ The backend starts uploading at its next scheduled run, with no restart. `read -rs` keeps the password off the screen and out of the shell history, and the request body goes through a pipe, so the password is never on a command line. - `held` is `false`; `enabled` and `images.enabled` are `true`; `images.misconfigured` is `null`; `last_verified_at` fills in once the first dump is verified. A missing or invalid dump recipient is not shown here: `enabled` stays `true` and `last_verified_at` does not advance, and each run writes `catalogue_backup_failed` to the system log. + `held` is `false`; `enabled` and `images.enabled` are `true`; from the release after 0.2.0, `mode_allows` and `images.mode_allows` are `true` as well (6.2a); `images.misconfigured` is `null`; `last_verified_at` fills in once the first dump is verified. A missing or invalid dump recipient is not shown here: `enabled` stays `true` and `last_verified_at` does not advance, and each run writes `catalogue_backup_failed` to the system log. ### 6.4 Free one volume first {#free-one-volume-first} @@ -594,7 +607,7 @@ Before it removes any file, the backend recomputes the SHA1 of every file, then Reinstalling the previous pixi environment needs the conda registry when `pixi.lock` changed in the update, unless every package is still in pixi's cache. The script says so when it cannot. -After a restore, the local branch names the previous commit and the submodules are on its pins. For the 0.1.0 install, that is `main` pointing at the commit the unit ran before. Before trying again, point it back at `origin/main` and put the submodules on its pins, since `update.sh --no-pull` does not sync them: +After a restore, the local branch names the previous commit and the submodules are on its pins. For the 0.1.0-beta install, that is `main` pointing at the commit the unit ran before. Before trying again, point it back at `origin/main` and put the submodules on its pins, since `update.sh --no-pull` does not sync them: ```bash git -C /home/pi/dtk checkout -B main origin/main @@ -604,9 +617,9 @@ git -C /home/pi/dtk submodule status Every line of `submodule status` must begin with a space. Then check the tree as in 2.1 before running 2.2 again. -### 7.2 A failed 0.1.0 install {#a-failed-0.1.0-install} +### 7.2 A failed 0.1.0-beta install {#a-failed-0.1.0-install} -`update.sh` can leave an unresolved record (7.3) with the previous code already back on disk: when it could not restore the database, refused to, or moved the code back only part-way. If the `update.sh` on disk then predates the record, as the pre-0.1.0 one does, it would not refuse to run. In that case, and only then, the script prints `DO NOT RUN scripts/update.sh ON THIS UNIT UNTIL THE ROLLBACK HAS SUCCEEDED`. Run only the recorded rollback command, under `systemd-run` as in 7.3. +`update.sh` can leave an unresolved record (7.3) with the previous code already back on disk: when it could not restore the database, refused to, or moved the code back only part-way. If the `update.sh` on disk then predates the record, as the pre-0.1.0-beta one does, it would not refuse to run. In that case, and only then, the script prints `DO NOT RUN scripts/update.sh ON THIS UNIT UNTIL THE ROLLBACK HAS SUCCEEDED`. Run only the recorded rollback command, under `systemd-run` as in 7.3. ### 7.3 The unresolved record {#the-unresolved-record} @@ -622,7 +635,7 @@ sudo cat /var/lib/dtk/backups/unresolved-deployment | `kind` | What happened | What to do | |---|---|---| -| `started-failed` | `update.sh` started the new version and then failed. The code is the new version's and the database is migrated for it. | Either run the recorded rollback command, which returns code and database to the previous version and discards everything written since the dump, or, once the cause is fixed, `update.sh --resolve-forward` (7.4). On the first 0.1.0 install, once files have moved into `/captures/`, the stem guard refuses the rollback (8.0a); use `--resolve-forward`. | +| `started-failed` | `update.sh` started the new version and then failed. The code is the new version's and the database is migrated for it. | Either run the recorded rollback command, which returns code and database to the previous version and discards everything written since the dump, or, once the cause is fixed, `update.sh --resolve-forward` (7.4). On the first 0.1.0-beta install, once files have moved into `/captures/`, the stem guard refuses the rollback (8.0a); use `--resolve-forward`. | | `migrated-not-restored` | `update.sh` failed after the migration began, and the code was not moved back, or only part-way. The database may be migrated or partly migrated. | The recorded rollback command, once whatever stopped the code from moving is cleared; or `--resolve-forward` if the code is exactly the failed commit and the database is at its head. | | `restore-failed` | The database was dropped for a restore, and loading the dump failed or was cut off. The database may be empty or partly restored. Also written by a rollback cut off after its drop. | Only the recorded rollback command. `--resolve-forward` refuses this kind. | | `restore-refused` | `update.sh` failed after the migration, and refused the restore before anything was dropped (a backend was running, or the start guard could not be put in place). The code is back on the previous commit; the database is as the migration left it. | Only the recorded rollback command. `--resolve-forward` refuses this kind. | @@ -695,7 +708,7 @@ At the first start after a rollback, `start.sh` runs `pixi run start`, which may Before the script changes anything, it checks whether the restored catalogue would point at files that are not there: - It reads every image path in the backup and looks for the file on disk, resolving a relative path as the backend does, against `/home/pi/dtk/backend`. A master freed to offsite storage is not counted. A volume with any image missing is at risk. -- It asks the current database for volumes with a stem, and counts only those whose stem directory exists. It looks under the projects root named in `/var/lib/dtk/storage-override.json` and under the default root (`PROJECTS_ROOT`, or `/projects`); a relative root is resolved under `/home/pi/dtk/backend`, as the backend resolves it. A volume with a stem directory that the backup does not have is at risk: it would be gone from the catalogue, its files left in the directory. +- It asks the current database for volumes with a stem, and counts only those whose stem directory exists. It looks under the projects root named in `/var/lib/dtk/storage-override.json` and under the default root (`PROJECTS_ROOT`, or `/projects`); a relative root is resolved under `/home/pi/dtk/backend`, as the backend resolves it. A volume with a stem directory that the backup does not have is at risk: it would be gone from the catalogue, its files left in the directory. - If the backup's image or record rows cannot be read, every volume with a stem directory is listed, and the message says some of them may be safe. If any volume is at risk, the script refuses with nothing changed and writes the list to `/var/lib/dtk/backups/rollback-stems-at-risk`, root's and mode 0600. The file begins with `#` header lines (the dump, whether the loss was accepted, how the dump was checked), then a tab-separated table with the columns `id`, `name`, `filename_stem`, `images_missing`, `images_total`, and `example`. The message begins: @@ -715,9 +728,9 @@ With `--accept-lost-stems`, the script goes on, records `accepted: yes` in the l The script starts the database container itself if it is not running. It refuses when that fails or a query fails: `✗ Could not check the current database for volumes with a stem directory`. Make the database reachable and run it again: start `dtk`, or, if the unresolved flag keeps `dtk` from starting, start the database container alone (`sudo docker compose -f /home/pi/dtk/docker-compose.yml -f /home/pi/dtk/docker-compose.pi.yml up -d db`). Three states are not refusals: a database that does not exist, which an interrupted restore leaves, holds no volume; a database with no volumes table holds none either; and a schema from before stems has no stem directories. In each, the backup's own images are still checked. -**The first 0.1.0 install.** Once 0.1.0 has started and moved files into `/captures/` (3.3, and for volumes that already had a stem, the start at the end of `update.sh`), the pre-update backup names those files at their old paths. A rollback to it would cut those volumes off, so the guard refuses it. After a failed update with an unresolved record of kind `started-failed`, use `update.sh --resolve-forward` (7.4), not a rollback. A record of kind `migrated-not-restored` means the new version never started, so no file moved for it. After a successful update, install a fixed version with an ordinary update. +**The first 0.1.0-beta install.** Once 0.1.0-beta has started and moved files into `/captures/` (3.3, and for volumes that already had a stem, the start at the end of `update.sh`), the pre-update backup names those files at their old paths. A rollback to it would cut those volumes off, so the guard refuses it. After a failed update with an unresolved record of kind `started-failed`, use `update.sh --resolve-forward` (7.4), not a rollback. A record of kind `migrated-not-restored` means the new version never started, so no file moved for it. After a successful update, install a fixed version with an ordinary update. -No command recovers a volume after an accepted loss yet. A `restore-stem` command is planned after 0.1.0. +No command recovers a volume after an accepted loss yet. A `restore-stem` command is planned after 0.1.0-beta. ### 8.1 What it restores {#what-it-restores} @@ -750,7 +763,7 @@ Do not roll back after the restart in 3.3. From then on the files of each volume ### 8.4 The next update {#the-next-update} -The rollback writes the restored commit to `last-deployed-SHA` and moves the local branch to it. The `update.sh` on disk is then the restored version's, not the 0.1.0 one, so the next update repeats the 0.1.0 install: +The rollback writes the restored commit to `last-deployed-SHA` and moves the local branch to it. The `update.sh` on disk is then the restored version's, not the 0.1.0-beta one, so the next update repeats the 0.1.0-beta install: 1. 2.1: bring `main` back to `origin/main` (`git -C /home/pi/dtk checkout -B main origin/main`), sync the submodules, and check the tree. 2. If `offsite.env` was moved aside (8.1), create the hold and put `offsite.env` back: @@ -764,10 +777,10 @@ The rollback writes the restored commit to `last-deployed-SHA` and moves the loc 3. 2.2, with `--no-pull`. 4. Steps 3 to 6 again: the rollback discarded everything written after the dump (8.2). -When the unit is updated to 0.1.0 again, the backend moves files at its start: +When the unit is updated to 0.1.0-beta again, the backend moves files at its start: - For a volume whose stem is in the restored database, a row whose old path is gone is pointed at the file of the same name in `/captures/` when the file's sha256 matches the capture-time checksum. A file with no such checksum is reported as `missing`. -- The stem guard (8.0a) refuses a rollback that would cut a volume off from its files. After a rollback accepted with `--accept-lost-stems`, giving a lost stem again is refused while `/` holds files that none of the volume's rows name. No command recovers a volume after an accepted loss yet; `restore-stem` is planned after 0.1.0. +- The stem guard (8.0a) refuses a rollback that would cut a volume off from its files. After a rollback accepted with `--accept-lost-stems`, giving a lost stem again is refused while `/` holds files that none of the volume's rows name. No command recovers a volume after an accepted loss yet; `restore-stem` is planned after 0.1.0-beta. --- @@ -777,17 +790,19 @@ When the unit is updated to 0.1.0 again, the backend moves files at its start: The backend sends each handed-over volume's capture manifest to Fisqua, and asks Fisqua for the volume's status, when all three are set: -- `DTK_FISQUA_ENV` is `production` or `staging`. Production calls `https://.fisqua.org`; staging calls `https://.staging.fisqua.org`. -- `DTK_FISQUA_TOKEN` is 64 lowercase hexadecimal characters. -- `DTK_OFFSITE_TENANT` holds a valid tenant. +- `CAPTUA_FISQUA_ENV` is `production` or `staging`. Production calls `https://.fisqua.org`; staging calls `https://.staging.fisqua.org`. +- `CAPTUA_FISQUA_TOKEN` is 64 lowercase hexadecimal characters. +- `CAPTUA_OFFSITE_TENANT` holds a valid tenant. Otherwise nothing is queued or sent, and at start the journal has `INFO app.core.fisqua_outbox: Fisqua is not configured; no status poll started`. -The backend sends manifests only when `DTK_OFFSITE_REMOTE` is also set: the send pass runs inside the image upload schedule, which the backend starts only with a remote and a valid tenant. With a tenant and no remote, the backend queues manifests and never sends them. +The backend sends manifests only when `CAPTUA_OFFSITE_REMOTE` is also set: the send pass runs inside the image upload schedule, which the backend starts only with a remote and a valid tenant. With a tenant and no remote, the backend queues manifests and never sends them. + +From the release after 0.2.0, the link works only while the unit is in "Fisqua" mode (6.2a); in any other mode the backend sends nothing to Fisqua and does not poll it. The backend reads these settings at start. During an update, set them before step 6, and the restart in 6.1 applies them; outside an update, apply a change with `sudo systemctl restart dtk`. Every call goes over HTTPS with the unit's token. The backend never logs, stores, or returns the token; on the unit it is in `offsite.env`, and in the key file until you remove it. -The release number is in the file `VERSION` at the root of the checkout (`0.1.0`). The backend sends it in each manifest as `systemVersion`: `0.1.0` when the checkout is on the commit tagged `0.1.0`, otherwise `0.1.0+g`. The backend reads the tag from the superproject's git files without running git: a tag it can find only inside a pack file, or in `packed-refs` without the fully-peeled line, counts as no tag, and the version is `+g…` even on the tagged commit (verify on the bench once the tag exists). +The release number is in the file `VERSION` at the root of the checkout (`0.2.0` in the current release). The backend sends it in each manifest as `systemVersion`: `` when the checkout is on the commit tagged ``, otherwise `+g`. The backend reads the tag from the superproject's git files without running git: a tag it can find only inside a pack file, or in `packed-refs` without the fully-peeled line, counts as no tag, and the version is `+g…` even on the tagged commit (verify on a test unit). ### 9.2 Provisioning {#provisioning} @@ -798,10 +813,10 @@ FISQUA_TOKEN=<64 lowercase hexadecimal characters> ``` ```bash -sudo DTK_OFFSITE_KEY_FILE=/root/dtk-offsite-key \ +sudo CAPTUA_OFFSITE_KEY_FILE=/root/dtk-offsite-key \ /home/pi/dtk/scripts/provision-rclone.sh \ --tenant \ - --dump-recipient age172wkzadqepd565chppztfw8jefpcga8s7t6eqrfhnxnv2nlfkdrqygrl3m \ + --dump-recipient \ --fisqua-env production ``` @@ -829,13 +844,13 @@ When an operator sends a volume for review, the backend queues a capture manifes 1. The backend holds a queued manifest until the volume is received: every object of the volume verified in the bucket. 2. The backend then builds the manifest, under a fixed manifest id, and sends it in the same pass. -3. From Fisqua's answer, the backend marks the manifest delivered or refused. After a transient failure the manifest becomes due again after `DTK_FISQUA_RETRY_BASE` seconds (300), twice as long after each further failure, at most `DTK_FISQUA_RETRY_MAX` (6 hours), and never before the time Fisqua's `Retry-After` gives. The backend sends it at the first send pass after that. The backend runs a send pass after each image upload run, and runs those every `DTK_OFFSITE_BACKUP_INTERVAL` (30 minutes by default), or at once when a handover wakes the schedule. The backend does not stop retrying. +3. From Fisqua's answer, the backend marks the manifest delivered or refused. After a transient failure the manifest becomes due again after `CAPTUA_FISQUA_RETRY_BASE` seconds (300), twice as long after each further failure, at most `CAPTUA_FISQUA_RETRY_MAX` (6 hours), and never before the time Fisqua's `Retry-After` gives. The backend sends it at the first send pass after that. The backend runs a send pass after each image upload run, and runs those every `CAPTUA_OFFSITE_BACKUP_INTERVAL` (30 minutes by default), or at once when a handover wakes the schedule. The backend does not stop retrying. A volume whose recorded reference code is not its stem is refused at once, not sent, with the problem `reference_code_differs`. A volume the manifest builder refuses is refused with the builder's problems. Taking a volume back from review withdraws its unsent manifests; nothing is sent to Fisqua. A new handover replaces the volume's unsent manifests. While the hold exists (4.0), no manifest is built or sent. -On the bench unit on 2026-10-25, volume `cobos-bench-005`, with the default cap of `750k` (4.5): the backend started the upload 2 seconds after the handover, verified its 12 objects in 5 minutes 43 seconds, and sent the manifest 0.08 seconds after the last verification. After a take-back and a new handover, Fisqua registered the new manifest within 3 seconds. +In one test, on a test unit with the default cap of `750k` (4.5), the backend started the upload 2 seconds after the handover, verified its 12 objects in 5 minutes 43 seconds, and sent the manifest 0.08 seconds after the last verification. After a take-back and a new handover, Fisqua registered the new manifest within 3 seconds. -The backend first asks Fisqua for the status of its volumes `DTK_OFFSITE_BACKUP_DELAY` seconds (300) after start, and then every ten minutes (`DTK_FISQUA_POLL_INTERVAL`, 600). It asks about a volume while Fisqua has not given a final state for the volume's newest sent manifest, and while Fisqua offers a decisions set for the volume that the backend has not yet read (9.5). The final states are `published`, `refused`, and `superseded`. +The backend first asks Fisqua for the status of its volumes `CAPTUA_OFFSITE_BACKUP_DELAY` seconds (300) after start, and then every ten minutes (`CAPTUA_FISQUA_POLL_INTERVAL`, 600). It asks about a volume while Fisqua has not given a final state for the volume's newest sent manifest, and while Fisqua offers a decisions set for the volume that the backend has not yet read (9.5). The final states are `published`, `refused`, and `superseded`. ### 9.4 The volume page {#the-volume-page} @@ -858,22 +873,22 @@ Once Fisqua answers, the line shows its status, from `Fisqua received the volume **Configuration stops.** The backend stops sending and polling for the whole unit when Fisqua answers `401` or `403` (reason `token`), `404` (`not_found`) or any redirect (`redirect`). A `404` with rule `no-decisions` on a decisions read is not a stop (9.5). The backend also stops on a `400` whose problems say Fisqua cannot read the manifests this software writes (rules `version`, `envelope`, or `shape`, reason `version`); that manifest is refused for good. The journal has: ```text -ERROR app.core.fisqua_outbox: Fisqua answered HTTP () for this unit's configuration (fingerprint <8 hex>); sending and polling stop until DTK_FISQUA_ENV, DTK_FISQUA_BASE_URL or DTK_FISQUA_TOKEN is changed +ERROR app.core.fisqua_outbox: Fisqua answered HTTP () for this unit's configuration (fingerprint <8 hex>); sending and polling stop until CAPTUA_FISQUA_ENV, CAPTUA_FISQUA_BASE_URL or CAPTUA_FISQUA_TOKEN is changed ``` -For reason `version` the backend writes this line instead; `` is `DTK_FISQUA_RETRY_MAX` (21600 by default): +For reason `version` the backend writes this line instead; `` is `CAPTUA_FISQUA_RETRY_MAX` (21600 by default): ```text ERROR app.core.fisqua_outbox: Fisqua answered HTTP 400 (version) for this unit's manifests (fingerprint <8 hex>); sending and polling stop until the software is updated, or until a retest every s finds that Fisqua reads its manifests ``` -The volume page and the Configuration page say why. For a token stop they read `Fisqua does not accept the token configured on this scanner, so Captua has stopped sending volumes to Fisqua and checking their status. Ask whoever manages the scanner to correct DTK_FISQUA_TOKEN and restart Captua.` For reason `version` they read `Fisqua does not read the capture manifests this version of Captua writes, so Captua has stopped sending volumes to Fisqua and checking their status. Ask whoever manages the scanner to update Captua or Fisqua.` +The volume page and the **Settings** page say why. For a token stop they read `Fisqua does not accept the token configured on this scanner, so Captua has stopped sending volumes to Fisqua and checking their status. Ask whoever manages the scanner to correct CAPTUA_FISQUA_TOKEN and restart Captua.` For reason `version` they read `Fisqua does not read the capture manifests this version of Captua writes, so Captua has stopped sending volumes to Fisqua and checking their status. Ask whoever manages the scanner to update Captua or Fisqua.` -The stop is kept in `/var/lib/dtk/fisqua-config-error.json` and survives restarts. The backend clears the stop when the environment, the tenant (through the base URL built from it, unless `DTK_FISQUA_BASE_URL` is set), `DTK_FISQUA_BASE_URL`, the token, or the installed code changes; the journal then has `INFO app.core.fisqua_outbox: The Fisqua configuration was changed since Fisqua refused it; sending resumes`. The backend reads `offsite.env` at start: during an update, the restart in 6.1 applies a change to it; outside an update, apply it with `sudo systemctl restart dtk`. An update that changes the backend commit or the release also clears a token stop; if the token is still wrong, the backend's next call stops the unit again. The backend also removes a version stop after a retest that Fisqua reads (below). +The stop is kept in `/var/lib/dtk/fisqua-config-error.json` and survives restarts. The backend clears the stop when the environment, the tenant (through the base URL built from it, unless `CAPTUA_FISQUA_BASE_URL` is set), `CAPTUA_FISQUA_BASE_URL`, the token, or the installed code changes; the journal then has `INFO app.core.fisqua_outbox: The Fisqua configuration was changed since Fisqua refused it; sending resumes`. The backend reads `offsite.env` at start: during an update, the restart in 6.1 applies a change to it; outside an update, apply it with `sudo systemctl restart dtk`. An update that changes the backend commit or the release also clears a token stop; if the token is still wrong, the backend's next call stops the unit again. The backend also removes a version stop after a retest that Fisqua reads (below). **The version stop.** While it holds, the backend builds no manifest except the one a retest sends (below). Manifests already built but never sent when the refusal came are put back to be built again under new ids, so their line reads `Waiting for the complete offsite copy before sending to Fisqua`. The installed code, for this stop, is the backend commit and the release in `VERSION`: an update that changes either clears it, and an update that changes neither does not. When it cannot read its commit, the backend removes the stop at every restart. A change of environment, tenant, base URL, or token clears it too, and so does a retest that Fisqua reads (below). Once the stop is removed, the backend hands each volume whose newest manifest was refused for version over again under a new manifest id, as long as none of its records is captured, and logs `INFO app.core.fisqua_outbox: Volume handed to Fisqua again under a new manifest id after a version refusal`. -**The retest.** While a version stop holds, the backend sends one manifest every `DTK_FISQUA_RETRY_MAX` seconds (21600, six hours), counted from the time it recorded the stop or from the last retest, whichever is later. The backend sends the first retest six hours after it records the stop. The backend sends the retest at the first send pass after that time, and runs a send pass after each image upload run (9.3). A retest needs a volume handed over and received offsite: the backend takes, oldest first, a manifest waiting to be built or built and never sent, or a volume whose newest manifest was refused for version and none of whose records is captured, which it hands over again under a new manifest id. With no such volume, or no call left in the per-minute budget, the backend sends nothing and tries again at the next send pass. What the backend does next depends on Fisqua's answer: +**The retest.** While a version stop holds, the backend sends one manifest every `CAPTUA_FISQUA_RETRY_MAX` seconds (21600, six hours), counted from the time it recorded the stop or from the last retest, whichever is later. The backend sends the first retest six hours after it records the stop. The backend sends the retest at the first send pass after that time, and runs a send pass after each image upload run (9.3). A retest needs a volume handed over and received offsite: the backend takes, oldest first, a manifest waiting to be built or built and never sent, or a volume whose newest manifest was refused for version and none of whose records is captured, which it hands over again under a new manifest id. With no such volume, or no call left in the per-minute budget, the backend sends nothing and tries again at the next send pass. What the backend does next depends on Fisqua's answer: - Fisqua accepts the manifest, or refuses it for its content rather than its version: the backend removes the stop. In the same pass it hands over again each volume whose newest manifest was refused for version, then builds and sends what is due, within the per-pass limit. - Fisqua refuses it again for version: the backend records the stop again with the time of this refusal, so the next retest is one interval later. @@ -882,7 +897,7 @@ The stop is kept in `/var/lib/dtk/fisqua-config-error.json` and survives restart When Fisqua is changed to read the manifests this software writes, the backend resumes sending within six hours plus the time to the next send pass, with nothing done on the unit, provided some volume is handed over and received offsite and none of its records is captured. Otherwise the stop holds until such a volume exists, or until an update or a configuration change removes it. The backend retests nothing while the offsite upload hold (4.0) exists. Removing `/var/lib/dtk/fisqua-config-error.json` by hand is not needed. When an update or a configuration change removes the stop instead, the backend builds again, under the new code and new manifest ids, the manifests the retests built and never sent, and the last retest's manifest when its answer was lost or its send failed. -The Configuration page's **Offsite copy** card has a **Fisqua** section with the environment, the last send, and the last status check. `GET /system/catalogue-backup` returns the same under `fisqua`: `configured`, `token_invalid`, `environment`, `config_error`, `held`, `last_send`, and `last_poll`. +The **Settings** page's **Offsite copy** card has a **Fisqua** section with the environment, the last send, and the last status check. `GET /system/catalogue-backup` returns the same under `fisqua`: `configured`, `token_invalid`, `environment`, `config_error`, `held`, `last_send`, and `last_poll`. ### 9.5 Fisqua's decisions {#fisquas-decisions} @@ -890,10 +905,18 @@ When Fisqua has decided a volume's records, the status poll reads the decisions - An approved record becomes `approved`; a rejected record becomes `rejected`, with Fisqua's reason and note. The reviewer recorded for either is `Fisqua: `, or `Fisqua` when Fisqua names no one. Fisqua's decision replaces a local one. - Fisqua's set replaces the rotation correction of each current image of a record it is applied to: an image the set gives no correction loses any local one. No file is touched. -- Skipped and reported, with nothing changed for that record: a record not in the volume, a record that is `captured` (the volume was taken back, or the record retaken), a record whose current images are not the ones the decided manifest listed (`images_changed`), a decision that is neither approved nor rejected, and a rejection the local reject route would refuse (`note_too_long`, a reason not in the list, `other` with no note). +- Skipped and reported, with nothing changed for that record: a record not in the volume, a record that is `captured` (the volume was taken back, or the record retaken), a record whose current images are not the ones the decided manifest listed (`images_changed`), a decision that is neither approved nor rejected (`invalid_decision`), and a rejection the local reject route would refuse (`note_too_long`, a reason not in the list, `other` with no note). - A set for an earlier manifest is not applied. A set waits while a newer handover of the volume is not yet delivered. - When Fisqua's status offers a set and Fisqua answers the read with `404` and rule `no-decisions`, the backend applies nothing, writes `INFO app.core.fisqua_outbox: Fisqua has no decisions to give for volume yet; read again at the next poll`, and reads the set again at the next poll. The link is not stopped. Any other `404` is a configuration stop (9.4). +From the release after 0.2.0, the backend also applies these decisions: + +- An excluded record, one Fisqua says is not a page of the volume, becomes `excluded`, with the same reviewer; no rejection is written and no image changes. An exclusion with a reason or with rotations is skipped. +- A decision `missing_page`, with `side` `left` or `right`, marks a record captured with two cameras as missing that page; the current image of that side, if any, is superseded. A record in review or approved returns to captured, and the backend reopens a closed record. A record captured with one camera is skipped (`missing_page_single_record`). +- A set can also carry requests of kind `missing_opening`: for each, the backend adds placeholder records after the record the request names (one, or the request's `count`, from 1 to 50). A request already applied is skipped. +- When applying the set marked a page missing or added a placeholder, and the volume was handed over before and holds no captured record other than those still missing a page, and no record waiting for a retake, the backend hands the volume over again. +- Rotation corrections apply only to approved and rejected records, and `invalid_decision` covers a decision that is not approved, rejected, excluded or missing_page. + ### 9.6 The journal lines {#the-journal-lines} The backend writes one line per run that did something, as ` : `: @@ -907,7 +930,13 @@ INFO app.core.fisqua_decisions: Fisqua decisions applied to volume : ap INFO app.core.fisqua_outbox: Fisqua has no decisions to give for volume yet; read again at the next poll ``` -During a version stop (9.4), the backend writes a line when it sends each retest, and one for its outcome; `` is `DTK_FISQUA_RETRY_MAX`: +From the release after 0.2.0, the decisions line carries more counts: + +```text +INFO app.core.fisqua_decisions: Fisqua decisions applied to volume : approved= rejected= excluded= unchanged= skipped= rotations= rotations_skipped= missing_pages= placeholders= requests_skipped= reopened= +``` + +During a version stop (9.4), the backend writes a line when it sends each retest, and one for its outcome; `` is `CAPTUA_FISQUA_RETRY_MAX`: ```text INFO app.core.fisqua_outbox: Fisqua version stop retest: sending manifest of volume @@ -933,14 +962,14 @@ Failures have their own lines: `Sending manifest of volume to Fisqua f ### 9.7 When nothing arrives in Fisqua {#when-nothing-arrives-in-fisqua} -1. `GET /system/catalogue-backup` (6.3): `fisqua.configured` must be `true`. If `token_invalid` is `true`, the token is not 64 lowercase hexadecimal characters. If `configured` is `false` and `token_invalid` is `false`, check that `DTK_FISQUA_TOKEN` is present (the command in 4.3 shows it as `(not shown)`), and check `DTK_FISQUA_ENV` and `DTK_OFFSITE_TENANT`. During an update, set any change before step 6, and the restart in 6.1 applies it; outside an update, restart dtk with `sudo systemctl restart dtk`. If `config_error` is set, see the configuration stops in 9.4. For reason `version`, the backend retests every six hours with nothing done on the unit, provided some volume is handed over and received offsite and none of its records is captured; otherwise the stop holds until such a volume exists, or until an update or a configuration change removes it, and the backend retests nothing while the hold exists. `config_error.at` is the time the backend last recorded the stop, which a retest refused for version renews, and `config_error.retest_at` is the time of the last retest whose send failed (`null` otherwise). Both are UTC, written without an offset. The next retest is due six hours after the later of the two. If `held` is `true` and step 5 is complete, remove the hold (6.2); during an update, leave it. +1. `GET /system/catalogue-backup` (6.3): `fisqua.configured` must be `true`, and from the release after 0.2.0 `fisqua.mode_allows` as well (6.2a). If `token_invalid` is `true`, the token is not 64 lowercase hexadecimal characters. If `configured` is `false` and `token_invalid` is `false`, check that `offsite.env` holds `DTK_FISQUA_TOKEN` (the command in 4.3 shows it as `(not shown)`), and check `DTK_FISQUA_ENV` and `DTK_OFFSITE_TENANT` there. During an update, set any change before step 6, and the restart in 6.1 applies it; outside an update, restart dtk with `sudo systemctl restart dtk`. If `config_error` is set, see the configuration stops in 9.4. For reason `version`, the backend retests every six hours with nothing done on the unit, provided some volume is handed over and received offsite and none of its records is captured; otherwise the stop holds until such a volume exists, or until an update or a configuration change removes it, and the backend retests nothing while the hold exists. `config_error.at` is the time the backend last recorded the stop, which a retest refused for version renews, and `config_error.retest_at` is the time of the last retest whose send failed (`null` otherwise). Both are UTC, written without an offset. The next retest is due six hours after the later of the two. If `held` is `true` and step 5 is complete, remove the hold (6.2); during an update, leave it. 2. The volume's line in 9.4. `Waiting for the complete offsite copy…` (the start of the text) means the upload has not verified every object: read the volume's offsite line and the `Image upload run` lines. 3. The journal: `journalctl -u dtk --since "1 hour ago" | grep -E "Fisqua|Image upload run"`. 4. The backend asks again every ten minutes about a delivered volume that Fisqua reports as `Fisqua does not know this volume yet`, and resends nothing on its own. To send it again, take the volume back from review and send it for review again: the backend queues a new manifest under a new id and sends it once the volume is received. The backend queues a new manifest only while some of the volume's records are in review; taking the volume back returns only those records to captured, and the backend queues nothing for a handover with no captured record. ## 10. Checks after an update {#checks-after-an-update} -Run these on the bench unit after every update, and on a unit in service after its update: +Run these on a test unit after every update, and on a unit in service after its update: ```bash curl -s http://localhost:8000/health @@ -965,7 +994,7 @@ sudo cat /etc/dtk/hostname-switch - The drop-in's `ConditionPathExists=!/etc/dtk/unresolved-deployment` is listed. - `check-stack-health.sh` reports the database healthy and port 5432 listening on the host, on any address, the frontend running, and nginx running. - The journal has no `Cannot start` and no `Traceback`; any `Volume layout:` lines are read as in 3.4. `offsite uploads are on hold` appears at each run while the hold exists. -- `GET /system/catalogue-backup` (6.3) reports `held` as expected for the point of the procedure, and, on a unit with the link, `fisqua.configured` `true` with no `config_error`. +- `GET /system/catalogue-backup` (6.3) reports `held` as expected for the point of the procedure, and, on a unit with the link, `fisqua.configured` `true` with no `config_error`. From the release after 0.2.0, `mode_allows`, `images.mode_allows` and, on a unit with the link, `fisqua.mode_allows` are `true` once the mode is set (6.2a). - The journal, on a unit with the link, has no `Fisqua answered HTTP` line since the restart. The `Fisqua accepted manifest` line (9.6) appears only after a handed-over volume is received offsite; a `Fisqua outbox pass` line can also report a volume refused as not exportable. Neither appears while the hold exists. - On a volume handed over since the update, the Fisqua line under the offsite copy line reads `Sent to Fisqua; waiting for its status` or a status from Fisqua (9.4). - On a unit renamed from `digitool`: `hostname` prints `captua`; `getent` prints an address for both names; `HOST_IP=captua.local` and `CORS_ORIGINS` lists `http://captua.local` and `http://digitool.local`; `dtk-mdns-alias` is `enabled` and `active`; `/etc/dtk/hostname-switch` reads `state=done`. From another machine on the same network, `http://captua.local`, `http://digitool.local`, and the unit's IP each load the app and log in. On a unit that kept its name, the update's journal says why (2.6). @@ -974,8 +1003,8 @@ sudo cat /etc/dtk/hostname-switch ## A new unit {#a-new-unit} -1. Provision the card with `sudo ./scripts/setup.sh`, which names it `captua` (`sudo DTK_HOSTNAME=captua-2 ./scripts/setup.sh` for a second unit at a site), then `sudo ./scripts/install-service.sh`, which also installs the unresolved-update drop-in (see [SD Card Distribution](/docs/deployment/sd-card-distribution/)). +1. Provision the card with `sudo ./scripts/setup.sh`, which names it `captua` (`sudo CAPTUA_HOSTNAME=captua-2 ./scripts/setup.sh` for a second unit at a site), then `sudo ./scripts/install-service.sh`, which also installs the unresolved-update drop-in (see [SD Card Distribution](/docs/deployment/sd-card-distribution/)). 2. Write the key file and run `provision-rclone.sh` with `--tenant` and `--dump-recipient`, as in step 4. For a unit with the link to Fisqua, add `--fisqua-env` and a `FISQUA_TOKEN` line in the key file (9.2). -3. Start or restart `dtk` and check as in 6.3. +3. Start or restart `dtk` and check as in 6.3. From the release after 0.2.0, set the unit's mode first (6.2a) if the unit was started before step 2. A new volume must be given its stem when it is created, so step 3 does not apply, and with nothing in the bucket before the unit, step 5 does not apply either. diff --git a/content/en/docs/operators/card.md b/content/en/docs/operators/card.md index 46ccbfc..90bd936 100644 --- a/content/en/docs/operators/card.md +++ b/content/en/docs/operators/card.md @@ -12,7 +12,7 @@ A one-page guide for the people who operate the scanner. Print it and keep it ne ## Shutting down and restarting the scanner {#shutting-down-and-restarting-the-scanner} 1. If a capture is in progress, wait for it to finish. -2. Open the user menu. In **Overview** and **Projects**, click your user name at the bottom of the sidebar; if the sidebar is collapsed, click the box with the first two letters of your name. On the capture screen and the volume screen, click the circle with those letters at the top right. +2. Open the user menu. On any screen with the sidebar, such as **Overview** or **Projects**, click your user name at the bottom of the sidebar; if the sidebar is collapsed, click the box with the first two letters of your name. On the capture screen and the volume screen, click the circle with those letters at the top right. 3. Click "Shut down the scanner", then "Yes, shut down" to confirm. 4. "Shutting down the scanner…" appears. Unplug the power only when the screen goes dark. @@ -44,8 +44,8 @@ If you leave the switch on AF, each capture takes about 12 seconds longer and ca ## Sending a finished volume for review {#sending-a-finished-volume-for-review} -1. Open the volume: **Projects →** your project **→** the volume. -2. Click "Send for review" in the top bar. If you already sent part of the volume, the button shows how many new records you are about to send (for example, "Send 3 new records"). +1. Open the volume: **Projects →** your project **→** the volume. If your unit does not use projects, open **Volumes →** the volume. +2. Click "Send for review" in the top bar. If you already sent part of the volume, the button shows how many new records you are about to send (for example, "Send 3 new records"). If the button says how many retakes are left (for example, "2 retakes left"), you can't send yet: finish the retakes first, and then you can send the volume. 3. Click "Send" to confirm. From then on the records are under review and you can't move them to another volume. If you made a mistake, click "Withdraw from review", then "Withdraw" to confirm. This withdraws only the records not yet reviewed; approved and rejected records stay as they are. @@ -64,6 +64,6 @@ From then on the records are under review and you can't move them to another vol ## If the application freezes {#if-the-application-freezes} -Press **Ctrl+Alt+F2**, type `sudo systemctl restart dtk`, and press Enter. **No message appears after you press Enter; this is normal.** Wait about 30 seconds, then go back to the application with **Ctrl+Alt+F1**. +Press **Ctrl+Alt+F2**, type `sudo systemctl restart dtk`, and press Enter. **No message appears while Captua is being restarted; this is normal.** Wait until the prompt appears again, which can take a minute or more, then go back to the application with **Ctrl+Alt+F1**. -If the application still doesn't respond, shut the scanner down with the power button (see above) and switch it on again. +If a message appears saying that `dtk.service` failed, or if the application still doesn't respond, shut the scanner down with the power button (see above) and switch it on again. diff --git a/content/en/docs/operators/external-storage.md b/content/en/docs/operators/external-storage.md index 8d17a8a..6ade9de 100644 --- a/content/en/docs/operators/external-storage.md +++ b/content/en/docs/operators/external-storage.md @@ -6,8 +6,8 @@ docs_section: operators source: docs/users/external-storage.qmd --- -The Digitization Toolkit can save captured images to an external USB drive or SD card instead of -the device's internal storage. This is useful when digitizing large collections that would exceed +Captua can save captured images to an external USB drive or SD card instead of +the unit's internal storage. This is useful when digitizing large collections that would exceed the capacity of the built-in microSD card. {{< callout type="warning" title="Experimental feature" >}} @@ -20,9 +20,19 @@ external drive as your **only** copy of digitized material — always keep a bac ## How it works {#how-it-works} -When an external drive is **activated**, new projects are saved to a `dtk-projects/` folder on -that drive. Existing projects already stored on the internal card are unaffected and remain -accessible. Only one external location can be active at a time. +While an external drive is **active**, Captua saves every new capture to a `dtk-projects/` folder +on that drive. This includes new captures for volumes you started on the internal card, so the +images of such a volume end up on two disks. Images captured earlier stay where they are and +remain readable. To keep each volume on one disk, activate the drive or restore internal storage +between volumes, not while a volume is in progress. Only one external location can be active at a +time. + +The note under **Storage drive** in **Settings**, "Only new projects will be saved to the selected +drive", is out of date and will be corrected (NEH-325). This page describes what Captua does. + +If the active drive is disconnected or not mounted, Captua does not switch to the internal card. +It refuses to save new captures until an administrator connects and activates the drive again, or +restores internal storage. --- @@ -30,7 +40,7 @@ accessible. Only one external location can be active at a time. ### Recommended format: exFAT {#recommended-format-exfat} -**exFAT** is the recommended format for external drives used with the toolkit. It is: +**exFAT** is the recommended format for external drives used with Captua. It is: - Compatible with Linux, Windows, and macOS (no drivers needed on any platform) - Supports files larger than 4 GB (important for high-resolution image sets) @@ -72,7 +82,7 @@ will permanently erase its contents. ### Format compatibility summary {#format-compatibility-summary} -| Format | Works with DTK | Notes | +| Format | Works with Captua | Notes | |--------|:--------------:|-------| | **exFAT** | ✅ Recommended | Best cross-platform choice | | **ext4** | ✅ Supported | Linux-only; slightly faster | @@ -85,8 +95,12 @@ will permanently erase its contents. ## Using external storage in the UI {#using-external-storage-in-the-ui} -Navigate to **Configuración** (the gear icon in the sidebar) and expand the -**Unidad de almacenamiento** section. +{{< callout type="note" >}} +Only an administrator can do this. **Settings** does not appear in the sidebar for operators and reviewers. +{{< /callout >}} + +Go to **Settings** (the gear icon in the sidebar). In the **Storage** section, click +**Storage drive** (marked experimental) to expand it. ### Step 1 — Connect the drive {#step-1-connect-the-drive} @@ -95,26 +109,26 @@ mounted beforehand. ### Step 2 — Mount the drive {#step-2-mount-the-drive} -The device list shows all detected partitions. Unmounted partitions have a **Montar** -(Mount) button. +The device list shows the partitions Captua can use. Unmounted partitions have a **Mount** +button. 1. Find the partition you want to use in the list -2. Click **Montar** -3. The toolkit mounts the drive and the button changes to **Activar** +2. Click **Mount** +3. Captua mounts the drive, and the row then shows **Activate** and **Unmount** ### Step 3 — Activate the drive {#step-3-activate-the-drive} -Click **Activar** next to the mounted partition. The toolkit: +Click **Activate** next to the mounted partition. Captua: 1. Creates a `dtk-projects/` directory on the drive (if it does not exist) 2. Sets that directory as the active projects location -3. Shows a green **activo** badge on the device row and a banner confirming the active path +3. Shows a green **active** badge on the device row, **✓ In use** in place of the **Activate** button, and a banner confirming the active path -New projects created after this point are stored on the external drive. +From this point, every new capture is stored on the external drive. ### Deactivating / reverting to internal storage {#deactivating-reverting-to-internal-storage} -Click **Restaurar predeterminado** in the override banner to switch back to the +Click **Restore default** in the banner to switch back to the internal storage. The external drive is **not** unmounted — existing projects on it remain intact and accessible. @@ -122,13 +136,15 @@ intact and accessible. Before physically unplugging the drive: -1. If it is the active storage location, click **Restaurar predeterminado** first -2. Click **Desmontar** next to the partition +1. If it is the active storage location, you can click **Restore default** first. Clicking **Unmount** on the active drive also switches back to internal storage. +2. Click **Unmount** next to the partition 3. Wait for the success message 4. Unplug the drive +Captua can unmount only drives it mounted itself with **Mount**. + {{< callout type="important" >}} -Always click **Desmontar** before unplugging. Removing a drive while it is mounted can +Always click **Unmount** before unplugging. Removing a drive while it is mounted can corrupt the filesystem and cause data loss. {{< /callout >}} @@ -137,17 +153,20 @@ corrupt the filesystem and cause data loss. ## Troubleshooting {#troubleshooting} **Drive not appearing in the list** -: The toolkit only shows partitions on removable devices that are not part of the -operating system. Try clicking **Actualizar lista**. If the drive still does not appear, -check that it is properly connected and recognised by the OS (`lsblk` in a terminal). - -**"Montar" returns an error** -: The drive may use an unsupported format (APFS, HFS+) or require additional kernel modules -(NTFS). Reformat the drive as exFAT and try again. - -**"Activar" fails with a permission error** +: Captua lists the partitions it can use. It leaves out the operating system's own partitions and +partitions whose filesystem it cannot use, such as APFS and HFS+. A drive formatted without a +partition table does not appear either: create a partition on it with Disk Utility or another +partitioning tool, then format that partition (for example `/dev/sdX1`) as exFAT. If the drive uses +APFS or HFS+, reformat it as exFAT as well. Then click **Refresh list**. If the drive still does not +appear, check that it is properly connected and recognised by the OS (`lsblk` in a terminal). + +**"Mount" returns an error** +: The filesystem may have errors, or the drive may need additional kernel modules (NTFS). +Reformat the drive as exFAT and try again. + +**"Activate" fails with a permission error** : This can happen on freshly formatted ext4 drives where the filesystem root is owned by -`root`. The toolkit attempts a fallback using elevated privileges. If it still fails, +`root`. Captua attempts a fallback using elevated privileges. If it still fails, reformat the drive as exFAT. **Drive mounted but read-only** diff --git a/content/es/docs/cameras/chdk.md b/content/es/docs/cameras/chdk.md index a0c6d29..962b708 100644 --- a/content/es/docs/cameras/chdk.md +++ b/content/es/docs/cameras/chdk.md @@ -16,18 +16,18 @@ CHDK no sustituye el firmware de la cámara. La cámara lo carga desde una tarje - **Dos cámaras Canon A2500.** La herramienta de preparación de tarjetas (`tools/flash_chdk.py`) descarga e instala CHDK 1.6.1-6315 específicamente para la A2500 con firmware 1.00A. No es un instalador general de CHDK para otros modelos Canon. - **Dos tarjetas SD**, una por cámara, preparadas según las instrucciones de esta guía. -- **Un Mac** con una copia del repositorio [`pychdk`](https://github.com/UCSB-AMPLab/pychdk) en la etiqueta `v0.1.2`, para preparar las tarjetas. Esa es la versión que usa el backend, fijada en `backend/requirements.txt` y `backend/pixi.toml`. El repositorio de Digitization Toolkit no incluye `pychdk`. Instalarlo como paquete de Python, como hace el backend, tampoco incluye la herramienta de preparación: esta solo está en `tools/` dentro del repositorio y no forma parte del paquete. `tools/flash_chdk.py` solo funciona en macOS; usa `diskutil` del Mac para formatear y escribir la tarjeta. +- **Un Mac** con una copia del repositorio [`pychdk`](https://github.com/UCSB-AMPLab/pychdk) en la etiqueta `v0.1.3`, para preparar las tarjetas. Esa es la versión que usa el backend, fijada en `backend/requirements.txt` y `backend/pixi.toml`. El repositorio de Captua no incluye `pychdk`. Instalarlo como paquete de Python, como hace el backend, tampoco incluye la herramienta de preparación: esta solo está en `tools/` dentro del repositorio y no forma parte del paquete. `tools/flash_chdk.py` solo funciona en macOS; usa `diskutil` del Mac para formatear y escribir la tarjeta. - **Un cable USB** por cámara para conectarla al equipo. {{< callout type="important" title="Todavía no hemos comprobado la captura por USB en estas cámaras" >}} -El equipo captura la fotografía por el cable USB: la cámara envía la imagen directamente por el cable y nunca la escribe en su propia tarjeta SD. La adaptación de CHDK para la A2500 está en fase alfa, y la documentación de `pychdk` señala que esta transmisión puede fallar en la A2500 con el error PTP `0x2002`. Ni `pychdk` v0.1.2 ni este backend intentan guardar la imagen en la tarjeta como alternativa. Si aparece ese error, la captura falla por completo, sin crear un archivo en otro lugar. El backend también cierra la sesión de esa cámara y la retira de la lista de dispositivos; en la siguiente búsqueda tiene que abrirla de nuevo. Tampoco hemos comprobado si esa reconexión funciona sin problemas ni si la vista previa sigue funcionando después. Una misma prueba permitiría resolver esas dudas. El registro del backend indica el error. +El equipo captura la fotografía por el cable USB: la cámara envía la imagen directamente por el cable y nunca la escribe en su propia tarjeta SD. Todavía nadie ha probado esta transmisión con una A2500. Si la transmisión falla, ni `pychdk` v0.1.3 ni este backend intentan guardar la imagen en la tarjeta como alternativa: la captura falla por completo, sin crear un archivo en otro lugar, y no sabemos en qué estado queda la cámara. El backend también cierra la sesión de esa cámara y la retira de la lista de dispositivos; en la siguiente búsqueda tiene que abrirla de nuevo. Tampoco hemos comprobado si esa reconexión funciona sin problemas ni si la vista previa sigue funcionando después. Una misma prueba permitiría resolver esas dudas. El registro del backend muestra el error. -No sabemos todavía si estas cámaras concretas presentan ese problema: aún no hemos ejecutado la prueba con ellas. Todavía tenemos pendiente esa prueba con las cámaras. Hasta completarla, considera que la captura en la A2500 está sin comprobar y no organices una jornada de digitalización que dependa de ella. +Todavía no sabemos si la captura por transmisión funciona con estas cámaras; esa prueba está en la lista de pruebas pendientes en el banco de trabajo. Mientras no la hagamos, considera que la captura en la A2500 no está comprobada y no organices una jornada de digitalización que dependa de ella. {{< /callout >}} ## Seleccionar el backend CHDK {#selecting-the-chdk-backend} -Esta página corresponde a la versión que actualiza la referencia del backend en el superproyecto a una revisión posterior a NEH-231, y a las versiones siguientes. Un equipo con un backend anterior no tiene ni el código del backend CHDK ni la dependencia `pychdk`, por lo que `CAMERA_BACKEND=chdk` todavía no puede funcionar allí. +Esta página corresponde a Captua 0.1.0-beta y a las versiones siguientes. Un equipo con una versión anterior no tiene ni el código del backend CHDK ni la dependencia `pychdk`, por lo que `CAMERA_BACKEND=chdk` no puede funcionar allí. {{< callout type="warning" appearance="simple" >}} Debes indicar al equipo que use el backend CHDK para estas cámaras. La configuración predeterminada del backend usa otro sistema de cámaras, y la instalación del equipo no cambia esa elección automáticamente. Aunque prepares bien las dos tarjetas y conectes dos cámaras que funcionen, el equipo puede no mostrar nada porque está buscando otro tipo de cámara. @@ -49,17 +49,17 @@ Si no preparaste tú el equipo, consulta con quien lo hizo: quizá ya tenga esta ## Preparar una tarjeta SD {#preparing-an-sd-card} -Prepara las tarjetas en un Mac con `tools/flash_chdk.py`, desde una copia del propio repositorio `pychdk`. La herramienta no está en el repositorio de Digitization Toolkit ni en la instalación de la dependencia de Python que usa el backend: +Prepara las tarjetas en un Mac con `tools/flash_chdk.py`, desde una copia del propio repositorio `pychdk`. La herramienta no está en el repositorio de Captua ni en la instalación de la dependencia de Python que usa el backend: ```bash git clone https://github.com/UCSB-AMPLab/pychdk.git cd pychdk -git checkout v0.1.2 +git checkout v0.1.3 python3 tools/flash_chdk.py ``` {{< callout type="warning" appearance="simple" >}} -Preparar una tarjeta **borra su contenido**. La herramienta solo muestra la confirmación "This will ERASE the disk. Continue?" cuando el Mac detecta **exactamente un disco extraíble en total**, no una sola tarjeta SD. Si hay otro almacenamiento extraíble conectado, como una unidad USB u otro lector de tarjetas, la herramienta omite la confirmación y borra el disco que elijas por número. Desconecta primero todos los demás dispositivos de almacenamiento extraíble y deja conectada únicamente la tarjeta que quieras preparar. +Preparar una tarjeta **borra su contenido**. Antes de borrar nada, la herramienta pide confirmación y nombra el disco: "This will ERASE /dev/diskN (name, sizeGB) and everything on it. Continue? [y/N]". Revisa ese nombre antes de responder `y`. La herramienta muestra todos los discos extraíbles físicos, no solo las tarjetas SD, así que en la lista puede aparecer una unidad USB externa. Si desconectas antes los demás dispositivos de almacenamiento extraíble, la tarjeta queda como única opción. {{< /callout >}} La herramienta descarga la versión de CHDK y conserva una copia en caché, formatea la tarjeta, extrae en ella los archivos de arranque de CHDK y modifica el sector de arranque para que la cámara pueda arrancar desde la tarjeta. Después pregunta qué páginas fotografiará esa cámara: impares, pares, o si prefieres omitir la elección. Guarda la respuesta en la tarjeta. Al terminar, **bloquea la tarjeta** con el interruptor de protección contra escritura del borde antes de insertarla en la cámara. @@ -74,7 +74,7 @@ La tarjeta indica qué **páginas** fotografía la cámara, ODD (impares) o EVEN Por tanto, una tarjeta corresponde a "la cámara que fotografía páginas pares" o a "la cámara que fotografía páginas impares", y no a "la cámara izquierda" o "la cámara derecha". -Una cámara con paridad en su tarjeta conserva el índice de esa paridad mientras ninguna otra cámara conectada declare la misma. Si dos cámaras comparten paridad, no puedes dar por hecho que sus índices sean los esperados y el backend bloquea la captura de ambas hasta que resuelvas el conflicto. +Una cámara con paridad en su tarjeta conserva el índice de esa paridad mientras ninguna otra cámara conectada declare la misma. Si dos cámaras comparten paridad, solo la primera que el backend encuentra en el bus conserva ese índice, y el backend bloquea la captura de ambas hasta que resuelvas el conflicto. Una cámara sin paridad no tiene un índice propio: recibe el menor índice que ninguna paridad haya reservado. Cuando conectas otra cámara, el backend puede asignarle un índice distinto a la primera aunque funcione bien. Por eso conviene asignar las dos paridades antes de empezar. @@ -82,7 +82,7 @@ Cuando dos cámaras comparten paridad, el backend bloquea ambas para captura. La ## El identificador de la cámara {#the-cameras-identity} -Algunas de estas cámaras no proporcionan un número de serie USB, así que el equipo no siempre puede distinguir dos cámaras conectadas solo por la conexión USB. Para resolverlo, el archivo de la tarjeta que guarda la paridad también puede guardar un identificador corto: una cadena hexadecimal de 12 caracteres. La herramienta crea ese identificador la primera vez que asignas una paridad, ya sea en el banco de trabajo con `tools/flash_chdk.py` o desde el equipo, como explicamos más abajo. El equipo usa este identificador para reconocer cada cámara después de desconectarla y volver a conectarla, y para recordar su configuración. +Algunas de estas cámaras no proporcionan un número de serie USB, así que el equipo no siempre puede distinguir dos cámaras conectadas solo por la conexión USB. Para resolverlo, el archivo de la tarjeta que guarda la paridad también puede guardar un identificador corto: una cadena hexadecimal de 12 caracteres. La primera vez que asignas una paridad, se crea ese identificador: si la asignas en el banco de trabajo, lo crea `tools/flash_chdk.py`; si la asignas desde el equipo, lo crea Captua, como explicamos más abajo. El equipo usa este identificador para reconocer cada cámara después de desconectarla y volver a conectarla, y para recordar su configuración. Cuando vuelves a preparar una tarjeta, la herramienta conserva el identificador en lugar de reemplazarlo. Por eso el equipo conserva la configuración registrada de la cámara después de volver a grabar la tarjeta. @@ -96,14 +96,14 @@ La interfaz web habitual solo muestra el modelo y el índice de cada cámara, y Consulta la lista de dispositivos con autenticación: `GET /cameras/devices`, la misma llamada que explicamos en "Asignar la paridad de una cámara". Cada cámara conectada debe aparecer con su modelo, su paridad (`odd` o `even`) y sin errores. Una cámara sin número de serie USB ni identificador propio muestra un error que indica que debes asignarle una paridad antes de capturar. Esto ocurre con estas cámaras compactas antes de la primera asignación. Asignar la paridad también crea su identificador. -Si acabas de volver a grabar una tarjeta o de cambiar una paridad manualmente, solicita otra búsqueda con `POST /cameras/rescan`, en lugar de usar el resultado de una consulta anterior. Esa búsqueda vuelve a leer la tarjeta de cada cámara conectada. +Si acabas de volver a grabar una tarjeta o de cambiar una paridad manualmente, solicita otra búsqueda con `POST /cameras/rescan`, en lugar de usar el resultado de una consulta anterior. Esa búsqueda vuelve a leer la tarjeta de cada cámara conectada. Para solicitarla necesitas una sesión con el rol **Administrador** u **Operario**; para consultar la lista de dispositivos basta con cualquier sesión. ## Asignar la paridad de una cámara {#assigning-a-cameras-parity} La interfaz todavía no tiene un control para esta tarea; esperamos incorporarlo en una versión futura. Por ahora, un administrador debe asignar la paridad directamente mediante la API del equipo. {{< callout type="warning" appearance="simple" >}} -Iniciar sesión en la interfaz web habitual no autoriza esta operación. Si el navegador ya tiene una sesión en la interfaz web con la misma dirección, por ejemplo el navegador del equipo en `http://localhost`, el explorador interactivo de la API admite consultas de lectura con esa sesión, pero rechaza todos los cambios, incluida la asignación de paridad, con un error 403 y `"Missing X-Requested-With header"`, hasta que inicies sesión dentro del explorador como explicamos a continuación. Tampoco puedes acceder al explorador desde un portátil conectado únicamente a la red local del lugar: el puerto 8000 solo admite conexiones desde el propio equipo o mediante Tailscale. +Iniciar sesión en la interfaz web habitual no autoriza esta operación. Si el navegador ya tiene una sesión en la interfaz web con la misma dirección, por ejemplo el navegador del equipo en `http://localhost`, el explorador interactivo de la API admite consultas de lectura con esa sesión, pero rechaza todos los cambios, incluida la asignación de paridad, con un error 403 y `"Missing X-Requested-With header"`, hasta que inicies sesión dentro del explorador como explicamos a continuación. Tampoco puedes acceder al explorador desde un portátil conectado únicamente a la red local del lugar: el puerto 8000 solo admite conexiones desde el propio equipo o mediante Tailscale. La API sí está disponible desde la red local a través de la ruta `/api/` de la interfaz, pero allí, igual que en el puerto 8000, la ruta de paridad solo acepta solicitudes de un administrador. {{< /callout >}} 1. **Abre el explorador de la API**, en una dirección distinta de la interfaz habitual: @@ -114,11 +114,11 @@ Iniciar sesión en la interfaz web habitual no autoriza esta operación. Si el n - Copia el valor `access_token` del cuerpo de la respuesta. - Presiona el botón verde **Authorize**, cerca de la parte superior de la página, para abrir el cuadro de diálogo. - Pega el token en el campo y presiona **Authorize dentro del cuadro de diálogo** para enviarlo. Pegar el token no basta: debes presionar ese segundo botón para aplicarlo. Cierra el cuadro cuando confirme la autorización. -3. **Consulta la lista actual de dispositivos** con `GET /cameras/devices` e identifica la cámara que quieres cambiar mediante `index`, `hardware_id` y `location`/puerto. +3. **Consulta la lista actual de dispositivos** con `GET /cameras/devices` e identifica la cámara que quieres cambiar mediante `index`, `hardware_id` y `location`, que incluye el puerto USB (por ejemplo, `USB usb:001,004`). 4. **Envía la asignación** a `POST /cameras/side/`, con un cuerpo JSON de `{"side": "odd"}` o `{"side": "even"}`. Reemplaza `` por el índice actual de la cámara. 5. **Vuelve a leer la respuesta:** contiene una lista completa de dispositivos tras una nueva búsqueda, no una sola fila actualizada. La cámara que acabas de cambiar suele pasar al otro índice. Identifica de nuevo todas las cámaras en esa lista antes de enviar otra asignación. No supongas que una cámara conserva el índice de hace un momento. -Esta operación vuelve a escribir la paridad y el identificador en la tarjeta de la cámara. Conserva el identificador existente, o crea uno si la cámara no tenía ninguno. +Esta operación vuelve a escribir la paridad y el identificador en la tarjeta de la cámara. El backend conserva el identificador que ya tenía la cámara. Crea uno nuevo en dos casos: si la cámara no tenía ninguno, o si no tiene número de serie USB y su tarjeta tiene el mismo identificador que otra cámara conectada. El equipo no asigna a una cámara una paridad que otra cámara **conectada en ese momento** ya tenga. Por eso dos cámaras conectadas no pueden intercambiar paridades directamente: cualquier paridad que intentes asignar a una ya pertenece a la otra, y el equipo rechaza la solicitud. Ningún orden de esas solicitudes resuelve el problema. Para intercambiar las paridades: @@ -154,7 +154,7 @@ Consulta el registro del backend en `/var/log/dtk/capture_service.log`. El backe **El registro indica un problema de permisos al abrir la cámara y ya comprobaste la tarjeta y el backend** -Revisa la regla udev. Ejecuta `lsusb`: debe mostrar una línea `"Canon, Inc."` por cámara, igual que con gPhoto2. Si `lsusb` la detecta, la conexión física funciona y el problema es de permisos. No vuelvas a ejecutar todo el script de instalación: en un equipo sin conexión útil a la red, ese script detiene los servicios y luego intenta descargar y compilar componentes que necesitan red, aunque el problema solo afecte a las cámaras. Ejecuta `sudo ./scripts/provision-chdk-usb.sh` para instalar únicamente la regla y la pertenencia al grupo. Puedes repetirlo sin alterar otros componentes. Luego reinicia el backend con `sudo systemctl restart dtk`. Al reiniciar el servicio, el backend usa la pertenencia actualizada del usuario del equipo a los grupos; no necesitas reiniciar todo el equipo. +Revisa la regla udev. Ejecuta `lsusb`: debe mostrar una línea `"Canon, Inc."` por cámara, igual que con gPhoto2. Si `lsusb` la detecta, la conexión física funciona y el problema es de permisos. No vuelvas a ejecutar todo el script de instalación: en un equipo sin conexión útil a la red, ese script detiene los servicios y luego intenta descargar y compilar componentes que necesitan red, aunque el problema solo afecte a las cámaras. Desde la raíz de la copia del proyecto (`/home/pi/dtk`), ejecuta `sudo ./scripts/provision-chdk-usb.sh`. El script instala libusb (un equipo ya instalado ya la tiene) y la regla udev, añade el usuario del equipo al grupo y no toca nada más. Puedes ejecutarlo varias veces sin riesgo. Luego reinicia el backend con `sudo systemctl restart dtk`. Al reiniciar el servicio, el backend usa la pertenencia actualizada del usuario del equipo a los grupos; no necesitas reiniciar todo el equipo. **El registro indica que la cámara está ocupada o reservada** diff --git a/content/es/docs/cameras/gphoto2.md b/content/es/docs/cameras/gphoto2.md index 78974de..1a7ffc6 100644 --- a/content/es/docs/cameras/gphoto2.md +++ b/content/es/docs/cameras/gphoto2.md @@ -9,7 +9,7 @@ source: "docs/users/setting-up-gphoto2-cams.qmd" {{< callout type="note" title="Lista de cámaras compatibles con gphoto2" appearance="simple" collapse="true" >}} Consulta la lista completa de cámaras compatibles con gphoto2 en la [página oficial de compatibilidad](http://gphoto.org/proj/libgphoto2/support.php). -Para funcionar plenamente con Digitization Toolkit, las cámaras deben ofrecer todas estas funciones: captura de imágenes (Image Capture), disparo remoto (Trigger Capture), vista en vivo (Live View) y configuración (Configuration). +Para funcionar plenamente con Captua, las cámaras deben ofrecer todas estas funciones: captura de imágenes (Image Capture), disparo remoto (Trigger Capture), vista en vivo (Live View) y configuración (Configuration). {{< /callout >}} ## Conectar las cámaras a la Raspberry Pi {#connect-the-cameras-to-the-raspberry-pi} @@ -40,6 +40,20 @@ gphoto2 --auto-detect # Deben aparecer ambas cámaras Si falta una cámara, vuelve a conectar ambos extremos del cable, apaga la cámara y vuelve a encenderla. Revisa `dmesg | tail`: un `error -71` repetido indica un cable defectuoso o un conector mal ajustado; si una cámara encendida no produce ninguna señal, el cable podría servir solo para cargar. +## Seleccionar el backend gPhoto2 {#select-the-gphoto2-backend} + +La configuración predeterminada del backend es `CAMERA_BACKEND=picamera2`, que solo busca los sensores conectados a la Pi por cable plano, y la instalación del equipo no cambia esa elección. Con esa configuración, la interfaz no muestra ninguna cámara réflex aunque `gphoto2 --auto-detect` detecte las dos. Comprueba que el archivo `.env` del equipo, en la raíz del proyecto, incluya: + +``` +CAMERA_BACKEND=gphoto2 +``` + +Luego reinicia el servicio del backend para aplicar el cambio: + +```bash +sudo systemctl restart dtk +``` + ## Canon EOS Rebel T7 {#canon-eos-rebel-t7} - Selecciona el enfoque manual: pon el interruptor del lente en **MF** (Manual Focus). @@ -59,7 +73,7 @@ Si falta una cámara, vuelve a conectar ambos extremos del cable, apaga la cáma {{< media id="cannon-eos-rebelt7-config-menu" >}} {{< callout type="caution" appearance="simple" >}} -El software abre una sesión con la cámara al solicitar la primera vista previa, captura o lectura de configuración después de encenderla. En ese momento intenta desactivar **Auto power off** para impedir que la cámara entre en reposo durante la sesión; el software nunca apaga la cámara. Antes de abrir esa sesión, la cámara aplica su propia configuración: si estuvo inactiva antes de la primera vista previa del día, podría haber abandonado ya el bus USB. Si la Raspberry Pi falla o la apagas durante una sesión, la cámara puede seguir encendida hasta que la apagues manualmente. +El software abre una sesión con la cámara al solicitar la primera vista previa, captura o lectura de configuración después de encenderla. En ese momento intenta desactivar **Auto power off** para impedir que la cámara entre en reposo durante la sesión; el software nunca apaga la cámara. Antes de abrir esa sesión, la cámara aplica su propia configuración: si estuvo inactiva antes de la primera vista previa del día, podría haber abandonado ya el bus USB. El software no restablece **Auto power off** al cerrar la sesión. Por eso, cada vez que se detiene el servicio o la Raspberry Pi, y no solo después de una falla, la cámara puede seguir encendida hasta que la apagues manualmente. Si el menú de la cámara muestra luego **Auto power off** desactivado, vuelve a seleccionar **15 minutos**. {{< /callout >}} {{< callout type="important" appearance="simple" >}} diff --git a/content/es/docs/deployment/pi5-imx519.md b/content/es/docs/deployment/pi5-imx519.md index 4b1bc28..b968263 100644 --- a/content/es/docs/deployment/pi5-imx519.md +++ b/content/es/docs/deployment/pi5-imx519.md @@ -17,7 +17,7 @@ Esta guía explica cómo conectar y configurar la cámara **Arducam IMX519** en - Dos módulos de cámara Arducam IMX519, SKU B0371. - Dos cables planos CSI de **22 a 22 pines** (recomendamos 15 o 20 cm). - Fuente de alimentación oficial de Raspberry Pi, de 5 V/3 A o superior (recomendamos la fuente de 27 W). -- Tarjeta microSD de 16 GB con Raspberry Pi OS Lite de 64 bits instalado. +- Tarjeta microSD de 16 GB con Raspberry Pi OS (Legacy, 64-bit) Lite, basado en Debian 12 "Bookworm". La opción "Raspberry Pi OS Lite (64-bit)" de Raspberry Pi Imager instala ahora Debian 13 "Trixie", un sistema con el que todavía no hemos validado Captua. Consulta los pasos iniciales de instalación de Raspberry Pi OS en la [documentación de Raspberry Pi](https://www.raspberrypi.com/documentation/computers/getting-started.html). diff --git a/content/es/docs/deployment/sd-card-distribution.md b/content/es/docs/deployment/sd-card-distribution.md index 1d6791c..97ed01e 100644 --- a/content/es/docs/deployment/sd-card-distribution.md +++ b/content/es/docs/deployment/sd-card-distribution.md @@ -8,7 +8,7 @@ source: docs/developers/sd_card_distribution.qmd *** -Esta guía explica cómo preparar y distribuir una imagen de tarjeta SD para Raspberry Pi con Digitization Toolkit preinstalado. Quien reciba la tarjeta podrá insertarla y acceder a la aplicación desde cualquier dispositivo de la misma red, sin configurar direcciones IP manualmente. +Esta guía explica cómo preparar y distribuir una imagen de tarjeta SD para Raspberry Pi con Captua preinstalado. Quien reciba la tarjeta podrá insertarla y acceder a la aplicación desde cualquier dispositivo de la misma red, sin configurar direcciones IP manualmente. --- @@ -22,6 +22,40 @@ El navegador llama a la API en `/api`, en el mismo origen que la página, y Ngin ## Preparar la imagen maestra {#preparing-the-master-image} +### 0. Instalar Captua en la tarjeta maestra {#install-captua-on-the-master-card} + +Graba en la tarjeta **Raspberry Pi OS (Legacy, 64-bit) Lite**, basado en Debian 12 "Bookworm": es el sistema con el que probamos Captua. La opción "Raspberry Pi OS Lite (64-bit)" de Raspberry Pi Imager instala ahora Debian 13 "Trixie", un sistema con el que todavía no hemos validado Captua. En las opciones de personalización de Imager, usa `pi` como nombre de usuario: `scripts/dtk.service` ejecuta el servicio como `pi` desde `/home/pi/dtk`, y el instalador del quiosco espera ese mismo usuario. Configura allí también la red y SSH (consulta [Qué debe hacer quien recibe la tarjeta](#what-the-recipient-needs-to-do)). + +Después, en la Pi, con la cuenta `pi` y conexión a internet, ejecuta: + +```bash +sudo apt update && sudo apt install -y git +curl -fsSL https://get.docker.com | sudo sh +sudo usermod -aG docker $USER +``` + +Cierra la sesión y vuelve a iniciarla, para que la cuenta `pi` tenga los permisos del grupo `docker`. Después, ejecuta: + +```bash +curl -fsSL https://pixi.sh/install.sh | PIXI_VERSION=v0.73.0 bash +git config --global url."https://github.com/".insteadOf "git@github.com:" +git clone --recurse-submodules https://github.com/UCSB-AMPLab/digitization-toolkit-software.git ~/dtk +cd ~/dtk +sudo ./scripts/setup.sh +sudo ./scripts/install-service.sh +sudo systemctl start dtk +curl http://localhost:8000/health # {"status":"ok"} +curl -I http://localhost # HTTP 200: la interfaz, a través de nginx +sudo ./scripts/installkb.sh +sudo ./scripts/install-kiosk-service.sh +``` + +- La línea `git config` va antes de clonar porque `.gitmodules` registra los submódulos con direcciones SSH (`git@github.com:`) y la Pi no tiene una clave SSH para GitHub: con esa línea, git los descarga por HTTPS. Los repositorios son públicos, así que no necesitas ningún token para clonarlos. +- La versión de pixi está fijada en `PIXI_VERSION`, en `scripts/setup.sh`: las versiones anteriores no pueden leer el `pixi.lock` del repositorio. +- `setup.sh` crea `.env` a partir de `.env.example`, construye la imagen del frontend, instala el entorno del backend, asigna el nombre del equipo (paso 1) y aplica las migraciones de la base de datos. Necesita conexión a internet; después, el equipo funciona sin ella. +- `install-service.sh` instala y habilita `dtk.service` y `dtk-secrets.service`, pero no inicia `dtk`; para eso está la línea `systemctl start`. Las dos líneas `curl` comprueban que el backend y la interfaz responden. +- `installkb.sh` e `install-kiosk-service.sh` configuran el quiosco, es decir, el navegador a pantalla completa en el monitor conectado a la Pi. + ### 1. Asignar un nombre al equipo {#name-the-unit} `setup.sh` asigna el nombre `captua` al equipo en el paso 6f, mediante `scripts/provision-hostname.sh`. Configura el nombre del equipo y la línea `127.0.1.1` de `/etc/hosts`, establece `HOST_IP=captua.local` y añade `http://captua.local` a `CORS_ORIGINS` en `.env`. No necesitas editar nada manualmente. @@ -29,9 +63,11 @@ El navegador llama a la API en `/api`, en el mismo origen que la página, y Ngin Dos equipos en una misma red no pueden compartir nombre. Si vas a instalar un segundo equipo en el mismo lugar, asígnale otro nombre al ejecutar la instalación: ```bash -sudo DTK_HOSTNAME=captua-2 ./scripts/setup.sh +sudo CAPTUA_HOSTNAME=captua-2 ./scripts/setup.sh ``` +`setup.sh` todavía acepta el nombre anterior, `DTK_HOSTNAME`. + Comprueba el resultado: ```bash @@ -109,13 +145,13 @@ gzip dtk-master.img El resultado será `dtk-master.img.gz`. En Windows puedes usar una herramienta de compresión compatible con gzip. {{< callout type="note" title="Cada equipo genera sus propias claves y contraseñas" >}} -`dtk-secrets.service`, que instala `install-service.sh`, genera de nuevo `SECRET_KEY` y `DATABASE_PASSWORD` en cada equipo físico. El servicio registra el número de serie de la Pi en `/var/lib/dtk/secrets-provenance`. Si grabas una copia de la imagen y la arrancas en otra Pi, el servicio detecta el número de serie distinto y genera claves y contraseñas nuevas antes de iniciar el backend. También cambia la contraseña de Postgres dentro del directorio de datos clonado. No necesitas borrar estas claves y contraseñas de la imagen maestra, y puedes arrancar la tarjeta maestra para probarla antes de crear la imagen. +`dtk-secrets.service`, que instala `install-service.sh`, genera de nuevo `SECRET_KEY`, `DATABASE_PASSWORD` y `BOOTSTRAP_TOKEN` (el token para crear la primera cuenta) en cada equipo físico. El servicio registra el número de serie de la Pi en `/var/lib/dtk/secrets-provenance`. Si grabas una copia de la imagen y la arrancas en otra Pi, el servicio detecta el número de serie distinto y genera claves y contraseñas nuevas antes de iniciar el backend. También cambia la contraseña de Postgres dentro del directorio de datos clonado. No necesitas borrar estas claves y contraseñas de la imagen maestra, y puedes arrancar la tarjeta maestra para probarla antes de crear la imagen. {{< /callout >}} {{< callout type="warning" title="Nunca añadas credenciales a `.env` manualmente" >}} -La generación por equipo descrita arriba solo cubre `SECRET_KEY` y `DATABASE_PASSWORD`. No cubre lo que añadas tú al preparar una tarjeta: la imagen y todas sus copias incluirán todo lo que contenga `.env` en ese momento. La tarjeta de Rionegro salió con un token personal de acceso a GitHub vigente y en texto plano en `~/dtk/.env`. Nadie lo había usado y ya lo hemos revocado, pero el software no lo había añadido. +La generación por equipo descrita arriba solo cubre `SECRET_KEY`, `DATABASE_PASSWORD` y `BOOTSTRAP_TOKEN`. No cubre lo que añadas tú al preparar una tarjeta: la imagen y todas sus copias incluirán todo lo que contenga `.env` en ese momento. Ya encontramos una tarjeta que tenía en `~/dtk/.env`, en texto plano, un token personal de acceso a GitHub vigente; no lo había añadido el software. -La preparación del equipo no necesita ningún token: los repositorios son públicos y `setup.sh` los clona de forma anónima. Si alguna vez necesitas descargar un repositorio privado, introduce el token en una solicitud interactiva para que nunca aparezca en la línea de comandos y elimina la variable al terminar: +La preparación del equipo no necesita ningún token: los repositorios son públicos, así que los clonas por HTTPS sin token, y `setup.sh` hace que las descargas posteriores de los submódulos también usen HTTPS. Si alguna vez necesitas descargar un repositorio privado, introduce el token en una solicitud interactiva para que nunca aparezca en la línea de comandos y elimina la variable al terminar: ```bash read -rs -p "Token: " GH_TOKEN && export GH_TOKEN @@ -128,6 +164,15 @@ unset GH_TOKEN Antes de crear la imagen maestra, compara `.env` con `.env.example`: no debe contener claves que no figuren en la plantilla. {{< /callout >}} +{{< callout type="warning" title="Prepara la copia externa y las cuentas en cada equipo, no en la tarjeta maestra" >}} +Todo lo demás que contiene la tarjeta maestra queda también en cada tarjeta grabada a partir de ella, y la generación por equipo no lo cambia: + +- `/var/lib/dtk/offsite.env` y `/var/lib/dtk/rclone.conf`, que `provision-rclone.sh` escribe cuando recibe la clave de la copia externa o el token de Fisqua de un equipo. `setup.sh` ya ejecuta `provision-rclone.sh` sin claves. En la tarjeta maestra no le pases ninguna clave a `provision-rclone.sh`; prepara la copia externa de cada equipo después de grabar su tarjeta, como indica el [paso 4 de Actualizar un equipo](/guia/instalacion/actualizar-un-equipo/#provision-the-offsite-copy-without-restarting). +- La base de datos, con todas las cuentas que crees al probar la tarjeta. No crees cuentas en la tarjeta maestra. + +Desde la versión siguiente a 0.2.0, si arrancaste la tarjeta antes de preparar su copia externa, el backend pone el equipo en el modo "Solo en el escáner", y cada tarjeta grabada a partir de ella arranca en ese mismo modo. Fija el modo en cada equipo cuando su copia externa esté lista ([Actualizar un equipo, 6.2a](/guia/instalacion/actualizar-un-equipo/#set-the-units-mode)). +{{< /callout >}} + --- ## Grabar y entregar la imagen {#flashing-and-delivering-the-image} @@ -172,19 +217,19 @@ No supongas que Imager puede aplicar las mismas opciones de personalización a u - Prueba `ping captua.local`. - Si no funciona, busca la dirección IP en la lista de clientes DHCP del router y abre esa dirección: la aplicación también funciona por IP. -**Un equipo instalado antes de 0.1.0 responde como `digitool.local`** +**Un equipo instalado antes de 0.1.0-beta responde como `digitool.local`** -Los equipos instalados antes de 0.1.0 tenían el nombre `digitool`. `update.sh` cambia su nombre a `captua` y conserva la respuesta de `digitool.local` durante la serie 0.1.x. Consulta **[Actualizar un equipo](/guia/instalacion/actualizar-un-equipo/#the-unit-name-digitool-becomes-captua)**. +Los equipos instalados antes de 0.1.0-beta tenían el nombre `digitool`. `update.sh` cambia su nombre a `captua` y conserva la respuesta de `digitool.local`; la versión 0.2.0 también la conserva. Consulta **[Actualizar un equipo](/guia/instalacion/actualizar-un-equipo/#the-unit-name-digitool-becomes-captua)**. **Errores CORS en el navegador** El navegador llama a la API en el mismo origen que la página. La instalación de producción no hace llamadas entre orígenes distintos, así que no debería presentar este error. En el entorno de desarrollo, Vite en `:5173` llama al backend en `:8000`: el origen de la página debe figurar en `CORS_ORIGINS`, en `.env`. Actualiza la lista y reinicia el backend. -La página y la API también deben pertenecer al mismo sitio, porque la cookie de sesión usa `SameSite=Strict`: abre la página en `localhost` si `PUBLIC_API_BASE` usa `localhost`, y en `127.0.0.1` si usa `127.0.0.1`. Si no coinciden, el navegador no muestra un error CORS: el backend responde al inicio de sesión con 200 y rechaza la siguiente solicitud con 401. Consulta la sección 8, **CORS Configuration**, de [`docs/developers/API_REFERENCE.md`](https://github.com/UCSB-AMPLab/digitization-toolkit-software/blob/dev/docs/developers/API_REFERENCE.md) para más detalles. +La página y la API también deben pertenecer al mismo sitio, porque la cookie de sesión usa `SameSite=Strict`: abre la página en `localhost` si `PUBLIC_API_BASE` usa `localhost`, y en `127.0.0.1` si usa `127.0.0.1`. Si no coinciden, el navegador no muestra un error CORS: el backend responde al inicio de sesión con 200 y rechaza la siguiente solicitud con 401. Consulta la sección **CORS Configuration** de la [referencia de la API (en inglés)](/docs/developers/api-reference/#cors-configuration) para más detalles. **Dos Raspberry Pi en la misma red** -Cada nombre de equipo mDNS debe ser único en su red. Asigna el nombre de la segunda unidad durante la instalación con `DTK_HOSTNAME=captua-2`, como en el paso 1. En un equipo ya instalado, ejecuta el mismo script manualmente: +Cada nombre de equipo mDNS debe ser único en su red. Asigna el nombre de la segunda unidad durante la instalación con `CAPTUA_HOSTNAME=captua-2`, como en el paso 1. En un equipo ya instalado, ejecuta el mismo script manualmente: ```bash sudo /home/pi/dtk/scripts/provision-hostname.sh --name captua-2 diff --git a/content/es/docs/deployment/updating-a-unit.md b/content/es/docs/deployment/updating-a-unit.md index 29efc3b..22f2f1a 100644 --- a/content/es/docs/deployment/updating-a-unit.md +++ b/content/es/docs/deployment/updating-a-unit.md @@ -1,5 +1,5 @@ --- -title: "Actualizar un equipo a 0.1.0" +title: "Actualizar un equipo" url: /guia/instalacion/actualizar-un-equipo/ translationKey: docs-deployment-updating-a-unit docs_section: deployment @@ -8,10 +8,12 @@ source: docs/developers/updating_a_unit.qmd *** -Esta guía está dirigida a quien administra un equipo. Explica cómo actualizar un equipo que ya está en uso a la versión 0.1.0 y recoge los pasos que debes realizar una sola vez, en el orden necesario. Al final encontrarás una versión breve para un equipo nuevo. +Esta guía está dirigida a quien administra un equipo. Explica cómo actualizar a la versión actual un equipo que tiene una versión anterior a 0.1.0-beta, con los pasos que solo debes hacer una vez, en el orden necesario. Escribimos estos pasos para la actualización a 0.1.0-beta; por eso la guía la llama "la instalación de 0.1.0-beta". Sirven para cualquier equipo con una versión anterior a 0.1.0-beta, sea cual sea la versión que tenga `main`. Al final encontrarás una versión breve para un equipo nuevo. Los comandos suponen una instalación con la configuración que incluye `scripts/dtk.service`: el repositorio está en `/home/pi/dtk` y el servicio usa la cuenta `pi`. Ejecútalos por SSH como `pi`. +En esta guía, las variables de configuración se llaman `CAPTUA_`. Captua también lee los nombres anteriores, `DTK_`. En los archivos del equipo (`.env` y `/var/lib/dtk/offsite.env`), las variables mantienen los nombres `DTK_`, porque una reversión puede devolver el equipo a un código que solo lee esos nombres. Si una variable está definida con los dos nombres, Captua usa la de `CAPTUA_`. + --- ## 1. Antes de actualizar {#before-the-update} @@ -24,7 +26,7 @@ git -C /home/pi/dtk submodule status sudo cat /var/lib/dtk/backups/last-deployed-SHA ``` -`update.sh` registra como destino para la reversión el commit indicado en `last-deployed-SHA` y vuelve a él si la actualización falla. Con `--no-pull`, que usa la instalación de 0.1.0 (2.1), el script no inicia ni modifica nada si ese archivo no existe, está vacío o indica un commit que no está en el repositorio local. El repositorio ya contiene el código nuevo y no puede sustituir ese registro. En ese caso, antes del paso 2.1, escribe el commit que imprimió el primer comando: +`update.sh` registra como destino para la reversión el commit indicado en `last-deployed-SHA` y vuelve a él si la actualización falla. Con `--no-pull`, que usa la instalación de 0.1.0-beta (2.1), el script no inicia ni modifica nada si ese archivo no existe, está vacío o indica un commit que no está en el repositorio local. El repositorio ya contiene el código nuevo y no puede sustituir ese registro. En ese caso, antes del paso 2.1, escribe el commit que imprimió el primer comando: ```bash echo | sudo tee /var/lib/dtk/backups/last-deployed-SHA @@ -56,11 +58,11 @@ sudo ls -lt /var/lib/dtk/backups/ Algunos equipos tienen un temporizador de carga que alguien instaló manualmente antes de que el backend pudiera subir archivos. Estos temporizadores dependen de cada equipo y no forman parte del software. -En el equipo de Rionegro, el temporizador `b2push-interim` ejecuta `/home/pi/b2push.sh`. Ese script sube al bucket las imágenes y la copia diaria del catálogo que genera con `pg_dumpall`. Busca el temporizador y detenlo para que, después de actualizar, solo el backend escriba en el bucket: +Un temporizador de este tipo ejecuta un script hecho para ese equipo, que sube las imágenes al bucket y, a veces, también una copia diaria del catálogo que el propio script genera con `pg_dumpall`. Busca el temporizador y detenlo para que, después de actualizar, solo el backend escriba en el bucket: ```bash systemctl list-timers --all -sudo systemctl disable --now b2push-interim.timer +sudo systemctl disable --now .timer ``` Usa el nombre que muestre `list-timers` en tu equipo. No tenemos registrado el nombre del servicio que inicia el temporizador; `systemctl list-timers` lo muestra en la columna `ACTIVATES`. Si el servicio está en ejecución, espera a que termine antes del paso 2. @@ -68,14 +70,14 @@ Usa el nombre que muestre `list-timers` en tu equipo. No tenemos registrado el n Si abandonas la actualización antes del paso 3, habilita de nuevo el temporizador para que el equipo siga subiendo archivos como antes: ```bash -sudo systemctl enable --now b2push-interim.timer +sudo systemctl enable --now .timer ``` ### 1.5 Fijar el nombre de Tailscale del equipo {#pin-the-units-tailscale-name} La actualización cambia el nombre del equipo de `digitool` a `captua` (2.6) cuando apt puede acceder a sus repositorios. El alias que permite seguir usando `digitool.local` necesita `avahi-utils`, que instala la actualización. Si el equipo no tiene acceso a apt, conserva su nombre hasta una actualización que sí tenga acceso. -Tailscale toma el nombre del equipo del hostname, salvo que hayas fijado otro nombre. Si accedes al equipo con `ssh pi-dtk` o con su nombre de Tailscale, el cambio de hostname también cambiaría su nombre en la red de Tailscale. Antes de actualizar, fija explícitamente el nombre que tiene ahora en esa red: +Tailscale toma el nombre del equipo del hostname, salvo que hayas fijado otro nombre. Si accedes al equipo por SSH con su nombre de Tailscale, el cambio de hostname también cambiaría su nombre en la red de Tailscale. Antes de actualizar, fija explícitamente el nombre que tiene ahora en esa red: ```bash tailscale status --self @@ -88,11 +90,11 @@ El software no modifica Tailscale. Omite este paso si el equipo no usa Tailscale ## 2. Ejecutar la actualización {#run-the-update} -### 2.1 Descargar primero el código de 0.1.0 {#put-the-0.1.0-code-on-disk-first} +### 2.1 Descargar primero el código de 0.1.0-beta {#put-the-0.1.0-code-on-disk-first} -Para instalar 0.1.0, descarga el código nuevo y selecciona su revisión manualmente. Solo después ejecuta `update.sh` con `--no-pull`. Todos los equipos deben seguir este procedimiento para esta instalación. Bash lee el script del disco mientras lo ejecuta. Si `update.sh` descarga su propia actualización, esa ejecución conserva el manejo de errores de la copia anterior y no cuenta con ninguna de las protecciones del script nuevo. +Para instalar 0.1.0-beta, descarga el código nuevo y selecciona su revisión manualmente. Solo después ejecuta `update.sh` con `--no-pull`. Todos los equipos deben seguir este procedimiento para esta instalación. Bash lee el script del disco mientras lo ejecuta. Si `update.sh` descarga su propia actualización, esa ejecución conserva el manejo de errores de la copia anterior y no cuenta con ninguna de las protecciones del script nuevo. -Los equipos usan `main`, que solo cambia con las publicaciones de nuevas versiones. Si un equipo usa `dev`, cámbialo a `main` aquí, una sola vez. En el momento de redactar la guía, ese era el caso del equipo de pruebas y del equipo de Rionegro. Como `pi`, ejecuta: +Los equipos usan `main`, que solo cambia con las publicaciones de nuevas versiones. Si un equipo usa `dev`, cámbialo a `main` aquí, una sola vez. Como `pi`, ejecuta: ```bash git -C /home/pi/dtk fetch origin @@ -146,7 +148,7 @@ git -C /home/pi/dtk submodule foreach --quiet --recursive 'git ls-files -v | gre `checkout` rechaza una operación que sobrescribiría cambios locales. Guarda esos cambios aparte manualmente antes de continuar: `update.sh` solo lo hace cuando descarga código. -**Después de volver a una versión anterior a 0.1.0:** la reversión restaura el `update.sh` de esa versión anterior. La próxima actualización debe seguir de nuevo este procedimiento: descarga el código, selecciona la revisión manualmente y ejecuta el nuevo `update.sh` con `--no-pull` (8.4). El procedimiento de "Actualizaciones posteriores" que aparece más abajo ejecutaría el script antiguo. +**Después de volver a una versión anterior a 0.1.0-beta:** la reversión restaura el `update.sh` de esa versión anterior. La próxima actualización debe seguir de nuevo este procedimiento: descarga el código, selecciona la revisión manualmente y ejecuta el nuevo `update.sh` con `--no-pull` (8.4). El procedimiento de "Actualizaciones posteriores" que aparece más abajo ejecutaría el script antiguo. ### 2.2 Ejecutar `update.sh` fuera de la sesión SSH {#run-update.sh-outside-the-ssh-session} @@ -177,9 +179,9 @@ Todos los rechazos incluyen `Nothing has been changed.` El script muestra sus co **Actualizaciones posteriores, desde 0.1.x** -Una vez instalado 0.1.0, el disco ya contiene el script nuevo. Entonces puedes usar el procedimiento habitual: `sudo systemd-run --unit=dtk-deploy --collect /home/pi/dtk/scripts/update.sh --yes`. +Una vez instalado 0.1.0-beta, el disco ya contiene el script nuevo. Entonces puedes usar el procedimiento habitual: `sudo systemd-run --unit=dtk-deploy --collect /home/pi/dtk/scripts/update.sh --yes`. -El script descarga `main` y la actualiza mediante un avance directo (fast-forward). Esto solo vale mientras el repositorio tenga 0.1.0 o una versión posterior. Si vuelves a una versión anterior a 0.1.0, el disco vuelve a contener el script antiguo y la siguiente actualización debe seguir el paso 2.1: descarga y selecciona el código manualmente, y después ejecuta el nuevo `update.sh` con `--no-pull` (8.4). +El script descarga `main` y la actualiza mediante un avance directo (fast-forward). Esto solo vale mientras el repositorio tenga 0.1.0-beta o una versión posterior. Si vuelves a una versión anterior a 0.1.0-beta, el disco vuelve a contener el script antiguo y la siguiente actualización debe seguir el paso 2.1: descarga y selecciona el código manualmente, y después ejecuta el nuevo `update.sh` con `--no-pull` (8.4). ### 2.3 Qué hace `update.sh` {#what-update.sh-does} @@ -217,9 +219,9 @@ journalctl -u dtk --since "15 min ago" | grep -E "Volume layout:|Cannot start|Tr ### 2.5 Comprobar que todavía no haya cargas {#check-that-nothing-uploads-yet} -Al arrancar, el backend solo activa sus tareas programadas de carga cuando tiene tanto `DTK_OFFSITE_REMOTE` como un `DTK_OFFSITE_TENANT` válido. Un equipo que aún no has preparado para 0.1.0 no tiene tenant y, por tanto, no sube nada. Compruébalo antes del paso 3 con la solicitud de 6.3: `images.enabled` debe ser `false`. +Al arrancar, el backend solo activa sus tareas programadas de carga cuando tiene tanto `CAPTUA_OFFSITE_REMOTE` como un `CAPTUA_OFFSITE_TENANT` válido. Un equipo que aún no has preparado para 0.1.0-beta no tiene tenant y, por tanto, no sube nada. Compruébalo antes del paso 3 con la solicitud de 6.3: `images.enabled` debe ser `false`. -Si es `true`, el proceso de carga usa el nombre del archivo en el disco como clave de cada objeto. Una imagen que ya copiaste al bucket con un nombre del contrato tendría otra carga bajo una segunda clave; después, `adopt-map` rechazaría su entrada con `key_differs`. Si `offsite.env` ya registra un destino remoto y un tenant, crea el archivo de suspensión de cargas (4.0) antes del paso 2. Así, el backend mantendrá suspendidas las cargas desde el reinicio de la actualización: +Si es `true`, el proceso de carga usa el nombre del archivo en el disco como clave de cada objeto. Una imagen que ya copiaste al bucket con un nombre del contrato tendría otra carga bajo una segunda clave; después, `adopt-map` rechazaría su entrada con `key_differs`. Si `offsite.env` ya registra un destino remoto y un tenant, crea el archivo de suspensión de cargas (4.0) antes del paso 2. Así, el backend mantendrá suspendidas las cargas desde el reinicio de la actualización. En `offsite.env`, las dos claves aparecen con sus nombres `DTK_`: ```bash sudo grep -E '^DTK_OFFSITE_(REMOTE|TENANT)=' /var/lib/dtk/offsite.env @@ -227,12 +229,12 @@ sudo grep -E '^DTK_OFFSITE_(REMOTE|TENANT)=' /var/lib/dtk/offsite.env ### 2.6 El nombre del equipo: de digitool a captua {#the-unit-name-digitool-becomes-captua} -Desde 0.1.0, todos los equipos tienen el nombre `captua` y responden en `http://captua.local`. El navegador llama a la API en `/api`, en el mismo origen que la página, a través de nginx. Por eso también puedes abrir el equipo por su dirección IP o por cualquier otro nombre que apunte a él. El quiosco abre `http://localhost` en lugar de `http://localhost:3000`. +Desde 0.1.0-beta, todos los equipos tienen el nombre `captua` y responden en `http://captua.local`. El navegador llama a la API en `/api`, en el mismo origen que la página, a través de nginx. Por eso también puedes abrir el equipo por su dirección IP o por cualquier otro nombre que apunte a él. El quiosco abre `http://localhost` en lugar de `http://localhost:3000`. `update.sh` solo cambia el nombre si el hostname es exactamente `digitool` y `.env` contiene `HOST_IP=digitool.local`. Si alguien asignó otro nombre manualmente, el script lo conserva. `scripts/provision-hostname.sh` realiza el trabajo en dos llamadas: -- Antes de detener el servicio, con `--prepare`: instala `avahi-utils` mediante apt si falta, el script de alias `/usr/local/sbin/dtk-mdns-alias`, su unidad `dtk-mdns-alias.service`, el script de respuesta a eventos de NetworkManager `/etc/NetworkManager/dispatcher.d/90-dtk-mdns-alias` y el archivo adicional de configuración `/etc/systemd/system/dtk.service.d/hostname-repair.conf`. También intenta usar apt con `--no-pull`, así que la instalación de 0.1.0 (2.1) cambia el nombre si el equipo tiene acceso a apt. Solo `update.sh --no-pull --offline` omite apt. Si no puede instalar `avahi-utils`, el registro indica `The rename to captua waits for avahi-utils`: el equipo conserva `digitool` hasta una actualización con acceso a apt y la actualización continúa. -- Con `dtk` detenido, con `--switch`: escribe `127.0.1.1 captua digitool` en `/etc/hosts`, ejecuta `hostnamectl set-hostname captua`, reinicia `avahi-daemon` e inicia `dtk-mdns-alias`, que mantiene la respuesta de `digitool.local` durante la serie 0.1.x. Después comprueba que `captua.local` y `digitool.local` resuelvan a una dirección del propio equipo. Si alguno no responde o apunta a otro dispositivo, restaura el nombre, `/etc/hosts`, avahi y el alias, y conserva `.env` sin cambios. Si ambos apuntan al equipo, establece `HOST_IP=captua.local` en `.env` y añade `http://captua.local` a `CORS_ORIGINS`, conservando `http://digitool.local`. +- Antes de detener el servicio, con `--prepare`: instala `avahi-utils` mediante apt si falta, el script de alias `/usr/local/sbin/dtk-mdns-alias`, su unidad `dtk-mdns-alias.service`, el script de respuesta a eventos de NetworkManager `/etc/NetworkManager/dispatcher.d/90-dtk-mdns-alias` y el archivo adicional de configuración `/etc/systemd/system/dtk.service.d/hostname-repair.conf`. También intenta usar apt con `--no-pull`, así que la instalación de 0.1.0-beta (2.1) cambia el nombre si el equipo tiene acceso a apt. Solo `update.sh --no-pull --offline` omite apt. Si no puede instalar `avahi-utils`, el registro indica `The rename to captua waits for avahi-utils`: el equipo conserva `digitool` hasta una actualización con acceso a apt y la actualización continúa. +- Con `dtk` detenido, con `--switch`: escribe `127.0.1.1 captua digitool` en `/etc/hosts`, ejecuta `hostnamectl set-hostname captua`, reinicia `avahi-daemon` e inicia `dtk-mdns-alias`, que mantiene la respuesta de `digitool.local`. La versión 0.2.0 todavía instala el alias; ninguna versión lo ha retirado. Después comprueba que `captua.local` y `digitool.local` resuelvan a una dirección del propio equipo. Si alguno no responde o apunta a otro dispositivo, restaura el nombre, `/etc/hosts`, avahi y el alias, y conserva `.env` sin cambios. Si ambos apuntan al equipo, establece `HOST_IP=captua.local` en `.env` y añade `http://captua.local` a `CORS_ORIGINS`, conservando `http://digitool.local`. Ninguna de las dos llamadas puede hacer fallar la actualización. Si el cambio de nombre no termina, el script imprime `⚠ The rename to captua did not finish` y el equipo sigue funcionando como `digitool`. @@ -240,31 +242,31 @@ Si un corte de corriente interrumpe el cambio de nombre, el siguiente arranque d Si el hostname sigue siendo `digitool`, el script deshace el cambio. Si alguien asignó otro nombre manualmente con `--name`, conserva ese nombre y elimina el registro. Al deshacer el cambio, solo restaura `/etc/hosts` cuando el hostname vuelve a ser `digitool`; si `hostnamectl` falla, conserva el estado para que el siguiente arranque vuelva a intentarlo. El script también termina de reparar un equipo llamado `captua` cuyo `.env` aún contiene `HOST_IP=digitool.local`, independientemente del estado del registro. La reparación elimina además los archivos temporales que un corte de corriente puede dejar junto a `.env`, `/etc/hosts` y el registro. -Una actualización fallida y una reversión restauran el código, pero conservan el nombre. El código anterior a 0.1.0 funciona con él: su frontend llama a `http://${HOST_IP}/api`, ahora `http://captua.local/api`, y `CORS_ORIGINS` incluye ambos nombres. Así, una página abierta en `digitool.local` puede llamar a la API. +Una actualización fallida y una reversión restauran el código, pero conservan el nombre. El código anterior a 0.1.0-beta funciona con él: su frontend llama a `http://${HOST_IP}/api`, ahora `http://captua.local/api`, y `CORS_ORIGINS` incluye ambos nombres. Así, una página abierta en `digitool.local` puede llamar a la API. Cuando la versión nueva responde a `/health`, `update.sh` termina el proceso `cage` del quiosco, únicamente el de `pi`, y el inicio automático de sesión de tty1 vuelve a lanzarlo con el `start-kiosk.sh` nuevo en `http://localhost`. Ese es un origen nuevo para el navegador, así que el quiosco pide iniciar sesión una vez. `update.sh --resolve-forward` (7.4) vuelve a lanzar el quiosco del mismo modo después de iniciar `dtk`; una reversión lo abre en la dirección de la versión restaurada. -El bloqueo del perfil de Chromium, `~/.config/chromium/SingletonLock`, registra el hostname con el que Chromium lo creó, y Chromium rechaza un perfil bloqueado con otro nombre. El cambio de nombre actualiza el bloqueo del quiosco en ejecución a `captua`; si deshace el cambio, lo devuelve a `digitool`. Así, el siguiente Chromium puede usar el perfil con el `start-kiosk.sh` que haya en el disco después de una actualización, restauración o reversión. El script obtiene el usuario del quiosco del inicio automático de sesión de tty1 que configura `install-kiosk-service.sh`. Antes de iniciar Chromium, el `start-kiosk.sh` de 0.1.0 también elimina `SingletonLock`, `SingletonCookie` y `SingletonSocket`, salvo que siga activo un Chromium de `pi`. +El bloqueo del perfil de Chromium, `~/.config/chromium/SingletonLock`, registra el hostname con el que Chromium lo creó, y Chromium rechaza un perfil bloqueado con otro nombre. El cambio de nombre actualiza el bloqueo del quiosco en ejecución a `captua`; si deshace el cambio, lo devuelve a `digitool`. Así, el siguiente Chromium puede usar el perfil con el `start-kiosk.sh` que haya en el disco después de una actualización, restauración o reversión. El script obtiene el usuario del quiosco del inicio automático de sesión de tty1 que configura `install-kiosk-service.sh`. Antes de iniciar Chromium, el `start-kiosk.sh` de 0.1.0-beta también elimina `SingletonLock`, `SingletonCookie` y `SingletonSocket`, salvo que siga activo un Chromium de `pi`. Dos equipos de la misma red llamados `digitool` no pueden adoptar ambos el nombre `captua`: la comprobación del segundo detecta que el primero responde como `captua.local` y deshace el cambio. Asigna al segundo un nombre propio manualmente, como explica la solución de problemas de [Preparación y distribución de tarjetas SD](/guia/instalacion/tarjetas-sd/). La actualización conservará ese nombre. --- -## 3. Asignar a cada volumen su prefijo de nombre de archivo y reiniciar {#give-each-volume-its-stem-then-restart} +## 3. Asignar a cada volumen su raíz y reiniciar {#give-each-volume-its-stem-then-restart} -### 3.1 Asignar los prefijos {#set-the-stems} +### 3.1 Asignar las raíces {#set-the-stems} -En la interfaz, abre el proyecto, edita cada volumen con **Edit Volume** y completa **FILE NAME STEM**. Estas son las reglas: +En la interfaz, abre el proyecto, edita cada volumen con **Editar volumen** y completa el campo **RAÍZ**. Estas son las reglas: - Letras minúsculas y dígitos unidos por guiones simples, con un máximo de 27 caracteres. -- El prefijo debe coincidir con el código de referencia del volumen en Fisqua. El backend rechaza un prefijo distinto del código registrado. En **Edit Volume**, el mensaje es `The stem has to be the volume's Fisqua reference code, ""; "" is different. Use "" as the stem.` Una solicitud `PATCH` al volumen recibe `409` con `The reference code '' is not the file name stem ''; a volume's reference code is its file name stem.` Una importación rechaza ese elemento con `filename_stem_differs_from_reference_code` ("The filenameStem is not the same as the referenceCode.") y continúa con el resto. -- Debe ser único en el equipo y no coincidir con el nombre del directorio de un proyecto. -- El backend lo rechaza mientras `//` contenga archivos ajenos al volumen. -- Puedes asignar un prefijo a un volumen sin prefijo en cualquier momento, incluso después de capturar imágenes. Una vez que el volumen tiene prefijo y capturas, no puedes cambiarlo ni borrarlo. +- La raíz debe coincidir con el código de referencia del volumen en Fisqua. El backend rechaza una raíz distinta del código registrado. En **Editar volumen**, el mensaje es `La raíz tiene que coincidir con el código de referencia del volumen en Fisqua: usa "" en lugar de "".` Una solicitud `PATCH` al volumen recibe `409` con `The reference code '' is not the file name stem ''; a volume's reference code is its file name stem.` Una importación rechaza ese elemento con `filename_stem_differs_from_reference_code` ("The filenameStem is not the same as the referenceCode.") y continúa con el resto. +- Debe ser única en el equipo y no coincidir con el nombre del directorio de un proyecto. +- El backend la rechaza mientras `//` contenga archivos ajenos al volumen. +- Puedes asignar en cualquier momento una raíz a un volumen que no la tiene, incluso después de capturar imágenes. Una vez que el volumen tiene raíz y capturas, no puedes cambiarla ni borrarla. -En un volumen que ya tiene imágenes, el prefijo queda fijo en cuanto lo guardas. Antes de guardar, compara cada prefijo con el código de referencia del volumen en Fisqua. +En un volumen que ya tiene imágenes, la raíz queda fija en cuanto la guardas. Antes de guardar, compara cada raíz con el código de referencia del volumen en Fisqua. -Asignar un prefijo no mueve ningún archivo. El backend escribe inmediatamente las capturas nuevas de ese volumen en `/captures/`. No captures en un volumen con mapa de nombres hasta completar sus operaciones `adopt-map` y `raise-capture-counter` (5.1, 5.3): antes de ellas, el backend podría asignar a una captura un número que ya existe en el bucket. +Asignar una raíz no mueve ningún archivo. El backend escribe inmediatamente las capturas nuevas de ese volumen en `/captures/`. No captures en un volumen con mapa de nombres hasta completar sus operaciones `adopt-map` y `raise-capture-counter` (5.1, 5.3): antes de ellas, el backend podría asignar a una captura un número que ya existe en el bucket. ### 3.2 Previsualizar el traslado, opcional {#preview-the-move-optional} @@ -287,11 +289,11 @@ Repite `pg_isready` hasta que indique que el servidor acepta conexiones. El coma sudo systemctl restart dtk ``` -No reinicies hasta comprobar todos los prefijos. A partir de este arranque, los archivos de cada volumen con prefijo estarán en `/`, y una reversión ya no devolverá el equipo a un estado utilizable (8.3). +No reinicies hasta comprobar todas las raíces. A partir de este arranque, los archivos de cada volumen con raíz estarán en `/`, y una reversión ya no devolverá el equipo a un estado utilizable (8.3). -En cada arranque, antes de prestar servicio, el backend mueve los archivos existentes de cada volumen con prefijo desde la estructura basada en nombres a `/captures/`, `/previews/` y `/thumbnails/`. Trabaja un volumen a la vez, mediante un diario de operaciones en `/var/lib/dtk/volume-layout.journal`, y completa cualquier lote interrumpido en el siguiente arranque. Una vez que todos los volúmenes con prefijo están en su lugar, no mueve nada. +En cada arranque, antes de prestar servicio, el backend mueve los archivos existentes de cada volumen con raíz desde la estructura basada en nombres a `/captures/`, `/previews/` y `/thumbnails/`. Trabaja un volumen a la vez, mediante un diario de operaciones en `/var/lib/dtk/volume-layout.journal`, y completa cualquier lote interrumpido en el siguiente arranque. Una vez que todos los volúmenes con raíz están en su lugar, no mueve nada. -Si un volumen ya tenía prefijo antes de la actualización, el backend ya movió sus archivos cuando `update.sh` lo inició. +Si un volumen ya tenía raíz antes de la actualización, el backend ya movió sus archivos cuando `update.sh` lo inició. ### 3.4 Leer las líneas `Volume layout:` {#read-the-volume-layout-lines} @@ -299,7 +301,7 @@ Si un volumen ya tenía prefijo antes de la actualización, el backend ya movió journalctl -u dtk --since "15 min ago" | grep "Volume layout:" ``` -El backend solo escribe la línea de resumen cuando movió o adoptó archivos, o completó una operación pendiente. Si reinicias después de asignar prefijos a volúmenes con archivos y no aparece esa línea, revisa el resultado. +El backend solo escribe la línea de resumen cuando movió o adoptó archivos, o completó una operación pendiente. Si reinicias después de asignar raíces a volúmenes con archivos y no aparece esa línea, revisa el resultado. | Línea | Significado | |---|---| @@ -327,28 +329,28 @@ Motivos para omitir una imagen: | `stem_dir_occupied` | `/` contiene archivos ajenos al volumen; consulta la tabla anterior. | | `stem_dir_is_project_tree` | `/` es un directorio de proyecto activo. | | `stem_dir_outside_projects_root` | `/` apunta fuera del directorio raíz de proyectos. | -| `no_stem` | El prefijo guardado no es válido. | +| `no_stem` | La raíz guardada no es válida. | | `outside_storage`, `outside_projects_root` | La ruta de la fila está fuera del directorio raíz de proyectos activo. Los archivos cargados antes de esta estructura en `/var/lib/dtk/uploads/` permanecen allí y reciben estos motivos. | | `missing` | El archivo de la fila no existe y ningún archivo de `captures/` coincide con el sha256 registrado al capturar. | | `row_changed` | La fila cambió mientras el backend preparaba el traslado. | -El registro de systemd también contiene mensajes de nivel INFO, como el de archivos liberados cuyas referencias ahora apuntan a sus nombres nuevos. Desde el backend `aa0a10a` (#134), el backend envía a stderr los mensajes INFO de sus registradores `app.*` y `capture.*`; systemd los registra con el formato ` : ` (`app/core/logging_setup.py`). `DTK_LOG_LEVEL` establece el nivel, con `INFO` como valor predeterminado. +El registro de systemd también contiene mensajes de nivel INFO, como el de archivos liberados cuyas referencias ahora apuntan a sus nombres nuevos. Desde el backend `aa0a10a` (#134), el backend envía a stderr los mensajes INFO de sus registradores `app.*` y `capture.*`; systemd los registra con el formato ` : ` (`app/core/logging_setup.py`). `CAPTUA_LOG_LEVEL` establece el nivel, con `INFO` como valor predeterminado. --- -## 4. Preparar la copia remota sin reiniciar {#provision-the-offsite-copy-without-restarting} +## 4. Preparar la copia externa sin reiniciar {#provision-the-offsite-copy-without-restarting} ### 4.0 Crear el archivo de suspensión de cargas {#create-the-upload-hold} -Mientras exista `/var/lib/dtk/offsite-hold`, el equipo no envía nada a la copia remota: +Mientras exista `/var/lib/dtk/offsite-hold`, el equipo no envía nada a la copia externa: - El backend no sube ni enumera imágenes. Si ya hay una carga en curso, la detiene después del objeto que está procesando. - El backend no genera copias del catálogo. - El backend rechaza la liberación de un volumen de la tarjeta. La simulación de liberación y la restauración siguen disponibles. -El backend comprueba la existencia del archivo al empezar cada ejecución. Crearlo o eliminarlo afecta a la siguiente ejecución sin necesidad de reiniciar. La suspensión también continúa después de reinicios por fallos, reinicios del equipo o cortes de corriente. Los comandos del paso 5 no consultan ese archivo. Solo importa que exista. Puedes cambiar su ruta con `DTK_OFFSITE_HOLD_FILE`. `GET /system/catalogue-backup` informa de él mediante `held` y `hold_file`. La suspensión también afecta al envío a Fisqua y a la consulta de su estado: ambos responden "held" al empezar, sin llamar a Fisqua ni crear un manifiesto (9.3). +El backend comprueba la existencia del archivo al empezar cada ejecución. Crearlo o eliminarlo afecta a la siguiente ejecución sin necesidad de reiniciar. La suspensión también continúa después de reinicios por fallos, reinicios del equipo o cortes de corriente. Los comandos del paso 5 no consultan ese archivo. Solo importa que exista. Puedes cambiar su ruta con `CAPTUA_OFFSITE_HOLD_FILE`. `GET /system/catalogue-backup` informa de él mediante `held` y `hold_file`. La suspensión también afecta al envío a Fisqua y a la consulta de su estado: ambos responden "held" al empezar, sin llamar a Fisqua ni crear un manifiesto (9.3). -Crea el archivo antes de preparar la copia remota, o antes del paso 2 si `offsite.env` ya registra un destino remoto y un tenant (2.5): +Crea el archivo antes de preparar la copia externa, o antes del paso 2 si `offsite.env` ya registra un destino remoto y un tenant (2.5): ```bash sudo touch /var/lib/dtk/offsite-hold @@ -379,22 +381,21 @@ READ_APP_KEY=... | Clave | Qué contiene | |---|---| -| `KEY_ID`, `APP_KEY` | La clave de escritura del equipo, `captua--write`, con `listBuckets`, `listFiles` y `writeFiles`. No tiene `readFiles` ni `deleteFiles`, así que alguien que robe el equipo no puede descargar ni borrar el archivo remoto. | +| `KEY_ID`, `APP_KEY` | La clave de escritura del equipo, `captua--write`, con `listBuckets`, `listFiles` y `writeFiles`. No tiene `readFiles` ni `deleteFiles`, así que alguien que robe el equipo no puede descargar ni borrar el archivo remoto. | | `BUCKET` | El bucket del equipo; consulta la tabla siguiente. | -| `READ_KEY_ID`, `READ_APP_KEY` | Opcionales. La clave de lectura del equipo, `captua--read`, con `listBuckets`, `listFiles` y `readFiles`. Debe ser distinta de la clave de escritura. Sin ella, no puedes restaurar un volumen liberado. | +| `READ_KEY_ID`, `READ_APP_KEY` | Opcionales. La clave de lectura del equipo, `captua--read`, con `listBuckets`, `listFiles` y `readFiles`. Debe ser distinta de la clave de escritura. Sin ella, no puedes restaurar un volumen liberado. | -Ambas claves limitan el acceso al bucket del equipo y al prefijo de su tenant. `provision-rclone.sh` solo exige `writeFiles` y `listFiles` para la clave de escritura, y `listFiles` y `readFiles` para la de lectura. Las claves emitidas para 0.1.0 también incluyen `listBuckets`, como la clave provisional de Rionegro. Probamos cada clave de 0.1.0 desde una estación de trabajo con la herramienta `b2`: permitió la autenticación y la consulta de su prefijo de tenant, y rechazó el acceso fuera de él. Todavía no hemos usado esas claves con rclone en un equipo ni probado una clave sin `listBuckets`. Falta comprobar si rclone necesita ese permiso. El archivo tiene permisos 0600 y pertenece a `root`. +Ambas claves limitan el acceso al bucket del equipo y al prefijo de su tenant. `provision-rclone.sh` solo exige `writeFiles` y `listFiles` para la clave de escritura, y `listFiles` y `readFiles` para la de lectura. Las claves emitidas para 0.1.0-beta también incluyen `listBuckets`, como las claves provisionales anteriores. Probamos cada clave de 0.1.0-beta desde una estación de trabajo con la herramienta `b2`: permitió la autenticación y la consulta de su prefijo de tenant, y rechazó el acceso fuera de él. Todavía no hemos usado esas claves con rclone en un equipo ni probado una clave sin `listBuckets`. Falta comprobar si rclone necesita ese permiso. El archivo tiene permisos 0600 y pertenece a `root`. Para la conexión con Fisqua, el mismo archivo contiene `FISQUA_TOKEN=`, el token que Fisqua emitió para este equipo: exactamente 64 caracteres hexadecimales en minúsculas (9.2). #### Equipos y tenants {#units-and-tenants} +Cada equipo tiene su propio tenant y su propio par de claves, y varios equipos pueden compartir un bucket. Quien administra el almacenamiento de la copia externa registra estos datos para cada equipo: + | Equipo | Tenant (`--tenant`) | Bucket (`BUCKET`) | Claves | |---|---|---|---| -| rionegro | `ahr` | `neogranadina-masters` | `captua-rionegro-write`, `captua-rionegro-read` | -| lab | `ampl` | `ampl-masters` | `captua-lab-write`, `captua-lab-read` | -| sbmal | `sbmal` | `ampl-masters` | `captua-sbmal-write`, `captua-sbmal-read` | -| cobos (solo staging) | `cobos` | `ampl-masters` | `captua-cobos-write`, `captua-cobos-read` | +| `captua-` | `` | `` | `captua--write`, `captua--read` | Nunca incluyas un identificador de clave ni una clave de aplicación en un registro, una incidencia o esta guía. @@ -403,14 +404,14 @@ Nunca pases una clave como asignación delante de `sudo`: formará parte de la l ### 4.2 Ejecutar el script de preparación {#run-the-provisioning-script} ```bash -sudo DTK_OFFSITE_KEY_FILE=/root/dtk-offsite-key \ +sudo CAPTUA_OFFSITE_KEY_FILE=/root/dtk-offsite-key \ /home/pi/dtk/scripts/provision-rclone.sh \ --tenant \ - --dump-recipient age172wkzadqepd565chppztfw8jefpcga8s7t6eqrfhnxnv2nlfkdrqygrl3m + --dump-recipient ``` - `--tenant` es el prefijo de las claves de todos los objetos del equipo y su identificador en la URL de Fisqua. El script exige entre 1 y 63 caracteres: letras minúsculas, dígitos y guiones simples. Debe empezar por una letra y no terminar con un guion. Rechaza `platform`, `www`, `api`, `admin` y `app`. Para reemplazar un tenant ya registrado, también necesitas `--change-tenant`. -- `--dump-recipient` es la clave pública de age para cifrar las copias del catálogo. La del ejemplo es el destinatario de todos los equipos. El script rechaza una clave privada. Nunca guardes la clave privada en el equipo. +- `--dump-recipient` es la clave pública de age con la que Captua cifra las copias del catálogo: `age1` seguido de 58 caracteres. Todos los equipos usan el mismo destinatario; te lo da quien guarda la clave privada correspondiente. El script rechaza una clave privada. Nunca guardes la clave privada en el equipo. - `--fisqua-env production` o `--fisqua-env staging` activa la conexión con Fisqua, con `FISQUA_TOKEN` en el archivo de claves (9.2). - En ejecuciones posteriores que no indiquen esos valores, el script conserva el tenant, el destinatario de las copias, el entorno de Fisqua y su token. Esto incluye la ejecución de cada actualización. @@ -432,7 +433,7 @@ sudo rm /root/dtk-offsite-key sudo sed 's/^DTK_FISQUA_TOKEN=.*/DTK_FISQUA_TOKEN=(not shown)/' /var/lib/dtk/offsite.env ``` -`sed` imprime el archivo con el token de Fisqua reemplazado para que no aparezca en pantalla. El archivo contiene `DTK_RCLONE_BIN`, `DTK_OFFSITE_REMOTE`, `DTK_OFFSITE_TENANT` y `DTK_OFFSITE_DUMP_RECIPIENT`; `DTK_OFFSITE_READ_REMOTE` si proporcionaste una clave de lectura; `DTK_RCLONE_CONFIG` si la ejecución estableció la ruta de configuración de rclone; y `DTK_FISQUA_TOKEN` y `DTK_FISQUA_ENV` si el equipo tiene conexión con Fisqua (9.2). +`sed` imprime el archivo con el token de Fisqua reemplazado para que no aparezca en pantalla. En el archivo, las claves llevan los nombres `DTK_`. Contiene `DTK_RCLONE_BIN`, `DTK_OFFSITE_REMOTE`, `DTK_OFFSITE_TENANT` y `DTK_OFFSITE_DUMP_RECIPIENT`; `DTK_OFFSITE_READ_REMOTE` si proporcionaste una clave de lectura; `DTK_RCLONE_CONFIG` si la ejecución estableció la ruta de configuración de rclone; y `DTK_FISQUA_TOKEN` y `DTK_FISQUA_ENV` si el equipo tiene conexión con Fisqua (9.2). ### 4.4 Por qué todavía no hay cargas {#why-nothing-uploads-yet} @@ -442,11 +443,11 @@ Cada comando del paso 5 es un proceso nuevo que crea su configuración al empeza Si un fallo, un reinicio o un corte de corriente reinicia el backend antes del paso 6, el proceso nuevo lee el tenant. El archivo de suspensión (4.0) impide que suba archivos en ese caso. -### 4.5 Ancho de banda para la copia remota {#offsite-bandwidth} +### 4.5 Ancho de banda para la copia externa {#offsite-bandwidth} -El backend aplica un único límite de ancho de banda a las cargas de imágenes, las cargas de copias del catálogo y la restauración de archivos liberados: `DTK_OFFSITE_BWLIMIT`, que pasa a rclone como `--bwlimit`. No limita las consultas del bucket ni las llamadas a Fisqua. El valor predeterminado es `750k`, aproximadamente 750 KB/s; falta comprobar la unidad que interpreta rclone. Ese es el valor que ha usado el equipo de Rionegro con su conexión de unos 12 Mbit/s. Para otro lugar, mide la velocidad de subida en Mbit/s, divide entre 8 para obtener MB/s y usa aproximadamente la mitad. El equipo de pruebas usó el valor predeterminado hasta la ejecución `cobos-bench-005` (9.3). Después lo configuramos en `1.5M`, a partir de una conexión doméstica de unos 25 Mbit/s medida el 25 de octubre de 2026. +El backend aplica un único límite de ancho de banda a las cargas de imágenes, las cargas de copias del catálogo y la restauración de archivos liberados: `CAPTUA_OFFSITE_BWLIMIT`, que pasa a rclone como `--bwlimit`. No limita las consultas del bucket ni las llamadas a Fisqua. El valor predeterminado es `750k`, aproximadamente 750 KB/s; falta comprobar la unidad que interpreta rclone. Ese valor ya funciona en un equipo con una conexión de unos 12 Mbit/s. Para otro lugar, mide la velocidad de subida en Mbit/s, divide entre 8 para obtener MB/s y usa aproximadamente la mitad: una conexión de unos 25 Mbit/s da unos 3 MB/s, y la mitad es `1.5M`. -Configúralo en `/home/pi/dtk/.env`; `provision-rclone.sh` no escribe ese valor: +Configúralo en `/home/pi/dtk/.env`, con el nombre `DTK_`, como las demás variables de los archivos del equipo; `provision-rclone.sh` no escribe ese valor: ```bash DTK_OFFSITE_BWLIMIT=1.5M @@ -501,9 +502,9 @@ El comando rechaza todo el mapa, muestra `error: ` y no escribe nada cua - los valores de `contract`, `version` o `kind` no son, respectivamente, `fisqua-captua-exchange`, `1.1` y `rename-map`; - falta el objeto `volume` o `destination`, o `entries` no es una lista; - ningún volumen del equipo coincide tanto con `volume.captuaCollectionId` como con `volume.stem` del mapa; -- `DTK_OFFSITE_REMOTE` no tiene un valor definido, no tiene el formato `:` o su bucket no coincide con `destination.bucket`; +- `CAPTUA_OFFSITE_REMOTE` no tiene un valor definido, no tiene el formato `:` o su bucket no coincide con `destination.bucket`; - `destination.root` no es un prefijo de clave; -- `DTK_OFFSITE_TENANT` no tiene un valor definido, tiene un valor inválido o no coincide con el primer segmento de `destination.root`; +- `CAPTUA_OFFSITE_TENANT` no tiene un valor definido, tiene un valor inválido o no coincide con el primer segmento de `destination.root`; - la solicitud para listar el bucket no obtiene respuesta. Lee `refused` y `refused_counts` en la simulación. Resuelve cada entrada rechazada cuya imagen todavía esté en la tarjeta antes de que el backend empiece a subir archivos en el paso 6: de lo contrario, el componente de carga subiría ese archivo con una segunda clave, su nombre en el disco. Aplica todos los mapas antes del paso 5.2 para que `adopt` no registre una clave a la que un mapa da otro nombre. @@ -515,7 +516,7 @@ pixi run python -m app.core.image_upload adopt pixi run python -m app.core.image_upload adopt --apply ``` -`` es relativo a `DTK_OFFSITE_REMOTE`. El comando lista ese prefijo, calcula el hash de cada imagen que aún no tiene clave y pertenece a un volumen con prefijo de nombre de archivo, y registra un objeto de la lista como clave de la imagen cuando exactamente un objeto tiene el mismo SHA1. El comando informa de las coincidencias ambiguas y las claves que ya tienen asignación, sin registrarlas. Solo busca coincidencias para archivos que todavía están en la tarjeta. +`` es relativo a `CAPTUA_OFFSITE_REMOTE`. El comando lista ese prefijo, calcula el hash de cada imagen que aún no tiene clave y pertenece a un volumen con raíz, y registra un objeto de la lista como clave de la imagen cuando exactamente un objeto tiene el mismo SHA1. El comando informa de las coincidencias ambiguas y las claves que ya tienen asignación, sin registrarlas. Solo busca coincidencias para archivos que todavía están en la tarjeta. El comando no comprueba el tenant, pero debes darle un prefijo dentro del tenant (`/...`). Al liberar espacio, el backend lista el directorio de cada clave y no lista nada fuera del prefijo del tenant. Por eso nunca puedes liberar un volumen con una clave adoptada fuera de ese prefijo. @@ -564,7 +565,7 @@ El comando registra el sha256 de cada vista previa RAW capturada antes de que el sudo systemctl restart dtk ``` -El backend ahora lee el tenant e inicia las dos tareas programadas. Ejecuta cada una por primera vez `DTK_OFFSITE_BACKUP_DELAY` segundos después del inicio (300 de forma predeterminada), y de nuevo `DTK_OFFSITE_BACKUP_INTERVAL` segundos después de que termine cada ejecución (1800 de forma predeterminada). +El backend ahora lee el tenant e inicia las dos tareas programadas. Desde la versión siguiente a 0.2.0, estas tareas no envían nada hasta que el modo del equipo lo permita (6.2a). El backend ejecuta cada una por primera vez `CAPTUA_OFFSITE_BACKUP_DELAY` segundos después del inicio (300 de forma predeterminada), y de nuevo `CAPTUA_OFFSITE_BACKUP_INTERVAL` segundos después de que termine cada ejecución (1800 de forma predeterminada). ### 6.2 Retirar la suspensión {#remove-the-hold} @@ -576,10 +577,27 @@ sudo rm /var/lib/dtk/offsite-hold El backend empieza a subir archivos en la siguiente ejecución programada, sin necesidad de reiniciarlo. +### 6.2a Fijar el modo del equipo (desde la versión siguiente a 0.2.0) {#set-the-units-mode} + +Este paso corresponde a la versión siguiente a 0.2.0 y a las posteriores. La versión 0.2.0 no tiene modo del equipo. + +Desde esa versión, cada equipo funciona en uno de tres modos: "Solo en el escáner", en el que nada sale del equipo; "Solo copia externa", en el que Captua copia las imágenes y el catálogo al bucket; y "Fisqua", que añade la conexión con Fisqua. El backend fija el modo una sola vez, en el primer arranque de esa versión, según lo que esté configurado en ese momento: "Fisqua" si la conexión con Fisqua está configurada, "Solo copia externa" si lo está la copia externa, y "Solo en el escáner" en cualquier otro caso. En esta guía, el arranque de la actualización (2.2) ocurre antes de que prepares la copia externa (paso 4). Por eso, en la mayoría de los equipos, el backend fija "Solo en el escáner", y el equipo sigue en ese modo después del reinicio de 6.1: el backend no sube nada ni envía nada a Fisqua. Si el `offsite.env` del equipo ya registra un destino remoto y un tenant (2.5), en ese arranque el backend fija "Solo copia externa", o "Fisqua" si la conexión con Fisqua está configurada; en ese caso, solo el archivo de suspensión (4.0) impide las cargas. El backend también fija "Solo en el escáner" en un equipo nuevo o en una tarjeta que arrancaste antes de preparar su copia externa. + +Después de 6.2, abre **Configuración** con una cuenta de administrador y, en **Modo del equipo**, elige "Solo copia externa" o "Fisqua". Captua rechaza el cambio, e indica qué falta, en cualquiera de estos casos: + +- no está configurada la copia externa de las imágenes o la del catálogo (con su destinatario de age) +- solo para pasar a "Fisqua": no está configurada la conexión con Fisqua, existe el archivo de suspensión de cargas, Captua no logra comunicarse con Fisqua, o Fisqua no acepta el cambio + +Antes de pasar a "Fisqua", Captua le comunica el cambio a Fisqua. + +Captua guarda solo en el equipo todos los volúmenes creados en el modo "Solo en el escáner": no sube sus imágenes a la copia externa ni envía sus manifiestos a Fisqua. Cuando cambias el equipo de "Solo en el escáner" a otro modo y hay volúmenes de ese tipo, elige en **Volúmenes que Captua guarda solo en este equipo** entre **Incluirlos** y **Seguir guardándolos aquí**. Captua no cambia el modo hasta que elijas. + +Con el modo ya fijado, la comprobación de 6.3 también exige que `mode_allows` e `images.mode_allows` tengan el valor `true` y, en un equipo con conexión con Fisqua, `fisqua.mode_allows` también. + ### 6.3 Comprobar {#check} -- **El indicador de recepción de cada volumen.** En la página del volumen, la línea de copia remota muestra `Uploading: N of M files verified, P pending` durante la carga, y `Stored offsite: N of N files verified` cuando el backend ha verificado todos los objetos. `N files need attention` indica que el backend rechazó objetos: el bucket contiene un archivo diferente en esa clave (`remote_differs`), o el sha256 del archivo no coincide con el de su registro de captura (`fixity`). El backend no vuelve a intentar la carga de un objeto rechazado. `GET /collections/{id}/offsite` devuelve los mismos recuentos. -- **El estado de la copia remota del equipo.** La sección **Offsite copy** de la página de configuración y el indicador de la página de resumen consultan `GET /system/catalogue-backup`. Desde el equipo: +- **El indicador de recepción de cada volumen.** En la página del volumen, la línea de copia externa muestra `Copia externa en curso: N de M archivos verificados, P pendientes` durante la carga, y `Copia externa completa: N de N archivos verificados` cuando el backend ha verificado todos los objetos. `N archivos requieren atención` indica que el backend rechazó objetos: el bucket contiene un archivo diferente en esa clave (`remote_differs`), o el sha256 del archivo no coincide con el de su registro de captura (`fixity`). El backend no vuelve a intentar la carga de un objeto rechazado. `GET /collections/{id}/offsite` devuelve los mismos recuentos. +- **El estado de la copia externa del equipo.** La sección **Copia externa** de la página **Configuración** y el indicador de la página **Resumen** consultan `GET /system/catalogue-backup`. Desde el equipo: ```bash read -rs -p "Password: " PW; echo @@ -592,13 +610,13 @@ El backend empieza a subir archivos en la siguiente ejecución programada, sin n `read -rs` evita que la contraseña aparezca en la pantalla y en el historial del shell. El cuerpo de la solicitud pasa por una tubería, así que la contraseña nunca aparece en una línea de comandos. - `held` tiene el valor `false`; `enabled` e `images.enabled` tienen el valor `true`; `images.misconfigured` tiene el valor `null`; el backend completa `last_verified_at` después de verificar la primera copia de la base de datos. Esta respuesta no indica si falta el destinatario de cifrado de esa copia o si es inválido: `enabled` conserva el valor `true` y `last_verified_at` no avanza, y cada ejecución escribe `catalogue_backup_failed` en el registro del sistema. + `held` tiene el valor `false`; `enabled` e `images.enabled` tienen el valor `true`; desde la versión siguiente a 0.2.0, también `mode_allows` e `images.mode_allows` (6.2a); `images.misconfigured` tiene el valor `null`; el backend completa `last_verified_at` después de verificar la primera copia de la base de datos. Esta respuesta no indica si falta el destinatario de cifrado de esa copia o si es inválido: `enabled` conserva el valor `true` y `last_verified_at` no avanza, y cada ejecución escribe `catalogue_backup_failed` en el registro del sistema. ### 6.4 Liberar primero un solo volumen {#free-one-volume-first} -No liberes nada hasta que el backend haya verificado una copia del catálogo: `last_verified_at` en 6.3 debe tener un valor distinto de `null`. Después elige un volumen cuya línea de copia remota muestre `Stored offsite`. Con una cuenta de administrador, ábrelo, elige **Space on the SD card** y luego **Free space on the SD card**. Captua primero solicita al backend la simulación (`GET /collections/{id}/offsite/free`) y enumera en el cuadro de diálogo lo que liberaría y cada archivo que dejaría en la tarjeta, con el motivo. La simulación no modifica nada. Confirma con **Free space** solo cuando esa lista corresponda a lo que esperas. +No liberes nada hasta que el backend haya verificado una copia del catálogo: `last_verified_at` en 6.3 debe tener un valor distinto de `null`. Después elige un volumen cuya línea de copia externa muestre `Copia externa completa`. Con una cuenta de administrador, ábrelo, elige **Espacio en la tarjeta** y luego **Liberar espacio en la tarjeta**. Captua primero solicita al backend la simulación (`GET /collections/{id}/offsite/free`) y enumera en el cuadro de diálogo lo que liberaría y cada archivo que dejaría en la tarjeta, con el motivo. La simulación no modifica nada. Confirma con **Liberar espacio** solo cuando esa lista corresponda a lo que esperas. -Antes de retirar cualquier archivo, el backend vuelve a calcular el SHA1 de cada uno y después vuelve a listar el bucket, una vez por cada directorio de clave. El backend deja en la tarjeta cualquier archivo que falle una de las dos comprobaciones y lo incluye en la lista con un motivo. Las miniaturas permanecen, así que puedes seguir explorando el volumen. Un administrador puede recuperar un archivo liberado con **Restore to the SD card**; para ello necesita la clave de lectura de 4.1. +Antes de retirar cualquier archivo, el backend vuelve a calcular el SHA1 de cada uno y después vuelve a listar el bucket, una vez por cada directorio de clave. El backend deja en la tarjeta cualquier archivo que falle una de las dos comprobaciones y lo incluye en la lista con un motivo. Las miniaturas permanecen, así que puedes seguir explorando el volumen. Un administrador puede recuperar un archivo liberado con **Restaurar en la tarjeta**; para ello necesita la clave de lectura de 4.1. --- @@ -613,7 +631,7 @@ Antes de retirar cualquier archivo, el backend vuelve a calcular el SHA1 de cada Para reinstalar el entorno anterior de pixi, el equipo necesita acceso al registro de conda si la actualización cambió `pixi.lock`, salvo que la caché de pixi todavía contenga todos los paquetes. El script avisa cuando no puede reinstalarlo. -Después de una restauración, la rama local apunta al commit anterior y los submódulos tienen las revisiones fijadas por ese commit. En la instalación de 0.1.0, esto deja `main` apuntando al commit que el equipo usaba antes. Antes de volver a intentarlo, haz que apunte otra vez a `origin/main` y selecciona las revisiones de los submódulos que fija ese commit, porque `update.sh --no-pull` no las sincroniza: +Después de una restauración, la rama local apunta al commit anterior y los submódulos tienen las revisiones fijadas por ese commit. En la instalación de 0.1.0-beta, esto deja `main` apuntando al commit que el equipo usaba antes. Antes de volver a intentarlo, haz que apunte otra vez a `origin/main` y selecciona las revisiones de los submódulos que fija ese commit, porque `update.sh --no-pull` no las sincroniza: ```bash git -C /home/pi/dtk checkout -B main origin/main @@ -623,9 +641,9 @@ git -C /home/pi/dtk submodule status Cada línea de `submodule status` debe empezar con un espacio. Después comprueba el árbol de trabajo como indica 2.1 antes de ejecutar otra vez el paso 2.2. -### 7.2 Una instalación fallida de 0.1.0 {#a-failed-0.1.0-install} +### 7.2 Una instalación fallida de 0.1.0-beta {#a-failed-0.1.0-install} -`update.sh` puede dejar un registro sin resolver (7.3) aunque el disco ya tenga el código anterior: cuando no pudo restaurar la base de datos, rechazó la restauración o solo restauró parte del código. Si el `update.sh` del disco es anterior al mecanismo de ese registro, como ocurre con la versión anterior a 0.1.0, no rechazaría la ejecución. En ese caso, y solo en ese caso, el script muestra `DO NOT RUN scripts/update.sh ON THIS UNIT UNTIL THE ROLLBACK HAS SUCCEEDED`. Ejecuta únicamente el comando de reversión registrado, mediante `systemd-run` como indica 7.3. +`update.sh` puede dejar un registro sin resolver (7.3) aunque el disco ya tenga el código anterior: cuando no pudo restaurar la base de datos, rechazó la restauración o solo restauró parte del código. Si el `update.sh` del disco es anterior al mecanismo de ese registro, como ocurre con la versión anterior a 0.1.0-beta, no rechazaría la ejecución. En ese caso, y solo en ese caso, el script muestra `DO NOT RUN scripts/update.sh ON THIS UNIT UNTIL THE ROLLBACK HAS SUCCEEDED`. Ejecuta únicamente el comando de reversión registrado, mediante `systemd-run` como indica 7.3. ### 7.3 El registro sin resolver {#the-unresolved-record} @@ -641,7 +659,7 @@ sudo cat /var/lib/dtk/backups/unresolved-deployment | `kind` | Qué ocurrió | Qué debes hacer | |---|---|---| -| `started-failed` | `update.sh` inició la versión nueva y después falló. El código corresponde a la versión nueva y la base de datos tiene las migraciones para ella. | Ejecuta el comando de reversión registrado, que devuelve el código y la base de datos a la versión anterior y descarta todo lo escrito después de la copia, o, cuando hayas corregido la causa, ejecuta `update.sh --resolve-forward` (7.4). En la primera instalación de 0.1.0, una vez que el backend ha movido archivos a `/captures/`, la comprobación de prefijos de nombre de archivo rechaza la reversión (8.0a); usa `--resolve-forward`. | +| `started-failed` | `update.sh` inició la versión nueva y después falló. El código corresponde a la versión nueva y la base de datos tiene las migraciones para ella. | Ejecuta el comando de reversión registrado, que devuelve el código y la base de datos a la versión anterior y descarta todo lo escrito después de la copia, o, cuando hayas corregido la causa, ejecuta `update.sh --resolve-forward` (7.4). En la primera instalación de 0.1.0-beta, una vez que el backend ha movido archivos a `/captures/`, la comprobación de raíces rechaza la reversión (8.0a); usa `--resolve-forward`. | | `migrated-not-restored` | `update.sh` falló después del inicio de la migración y no restauró el código anterior, o solo restauró una parte. La base de datos puede tener una migración completa o parcial. | Ejecuta el comando de reversión registrado después de resolver lo que impidió restaurar el código; o usa `--resolve-forward` si el código corresponde exactamente al commit fallido y la base de datos está en la última revisión de migraciones de ese código. | | `restore-failed` | El script eliminó la base de datos para restaurarla, y la carga de la copia falló o sufrió una interrupción. La base de datos puede estar vacía o parcialmente restaurada. Una reversión interrumpida después de eliminar la base de datos también escribe este tipo de registro. | Ejecuta únicamente el comando de reversión registrado. `--resolve-forward` rechaza este tipo. | | `restore-refused` | `update.sh` falló después de la migración y rechazó la restauración antes de eliminar nada (había un backend en ejecución o el script no pudo instalar la protección de inicio). El código ya corresponde al commit anterior; la base de datos conserva el estado que dejó la migración. | Ejecuta únicamente el comando de reversión registrado. `--resolve-forward` rechaza este tipo. | @@ -709,13 +727,13 @@ sudo systemd-run --unit=dtk-rollback --collect \ En el primer inicio después de una reversión, `start.sh` ejecuta `pixi run start`, que puede reinstalar el entorno de pixi para el archivo de bloqueo restaurado; esto necesita conexión a la red. -### 8.0a La comprobación de prefijos de nombre de archivo {#a-the-stem-guard} +### 8.0a La comprobación de raíces {#a-the-stem-guard} Antes de cambiar nada, el script comprueba si el catálogo restaurado apuntaría a archivos ausentes: -- Lee todas las rutas de imágenes de la copia y busca cada archivo en el disco. Resuelve una ruta relativa a partir de `/home/pi/dtk/backend`, igual que el backend. No cuenta un archivo maestro cuyo espacio ya liberaste gracias a la copia remota. Cualquier volumen con una imagen ausente está en riesgo. -- Consulta en la base de datos actual los volúmenes con prefijo de nombre de archivo y solo cuenta aquellos cuyo directorio con ese prefijo existe. Busca bajo la raíz de proyectos que indica `/var/lib/dtk/storage-override.json` y bajo la raíz predeterminada (`PROJECTS_ROOT`, o `/projects`); resuelve una raíz relativa a partir de `/home/pi/dtk/backend`, igual que el backend. Un volumen con un directorio de prefijo que no figura en la copia está en riesgo: desaparecería del catálogo y sus archivos quedarían en el directorio. -- Si el script no puede leer las filas de imágenes o registros de la copia, incluye en la lista todos los volúmenes con un directorio de prefijo, y el mensaje aclara que algunos pueden estar a salvo. +- Lee todas las rutas de imágenes de la copia y busca cada archivo en el disco. Resuelve una ruta relativa a partir de `/home/pi/dtk/backend`, igual que el backend. No cuenta un archivo maestro cuyo espacio ya liberaste gracias a la copia externa. Cualquier volumen con una imagen ausente está en riesgo. +- Consulta en la base de datos actual los volúmenes con raíz y solo cuenta aquellos cuyo directorio de raíz existe. Busca bajo el directorio raíz de proyectos que indica `/var/lib/dtk/storage-override.json` y bajo el predeterminado (`PROJECTS_ROOT`, o `/projects`); resuelve un directorio relativo a partir de `/home/pi/dtk/backend`, igual que el backend. Un volumen con un directorio de raíz que no figura en la copia está en riesgo: desaparecería del catálogo y sus archivos quedarían en el directorio. +- Si el script no puede leer las filas de imágenes o registros de la copia, incluye en la lista todos los volúmenes con un directorio de raíz, y el mensaje aclara que algunos pueden estar a salvo. Si algún volumen está en riesgo, el script rechaza la ejecución sin cambiar nada y escribe la lista en `/var/lib/dtk/backups/rollback-stems-at-risk`, que pertenece a root y tiene permisos 0600. El archivo empieza con líneas de encabezado `#` (la copia, si aceptaste la pérdida y cómo comprobó el script la copia), seguidas de una tabla separada por tabulaciones con las columnas `id`, `name`, `filename_stem`, `images_missing`, `images_total` y `example`. El mensaje empieza así: @@ -732,11 +750,11 @@ Y termina así: Con `--accept-lost-stems`, el script continúa, registra `accepted: yes` en la lista y añade `lost-stems-accepted:` con la ruta de la lista al registro que escribe antes de eliminar la base de datos. -El propio script inicia el contenedor de la base de datos si no está en funcionamiento. Rechaza la ejecución si ese inicio falla o si falla una consulta: `✗ Could not check the current database for volumes with a stem directory`. Restablece el acceso a la base de datos y vuelve a ejecutarlo: inicia `dtk` o, si el indicador de actualización sin resolver impide iniciar `dtk`, inicia solo el contenedor de la base de datos (`sudo docker compose -f /home/pi/dtk/docker-compose.yml -f /home/pi/dtk/docker-compose.pi.yml up -d db`). Hay tres estados que no causan rechazo: una base de datos inexistente, como la que deja una restauración interrumpida, no contiene ningún volumen; una base de datos sin tabla de volúmenes tampoco contiene ninguno; y un esquema anterior a los prefijos de nombre de archivo no tiene directorios de prefijo. En los tres casos, el script sigue comprobando las imágenes de la propia copia. +El propio script inicia el contenedor de la base de datos si no está en funcionamiento. Rechaza la ejecución si ese inicio falla o si falla una consulta: `✗ Could not check the current database for volumes with a stem directory`. Restablece el acceso a la base de datos y vuelve a ejecutarlo: inicia `dtk` o, si el indicador de actualización sin resolver impide iniciar `dtk`, inicia solo el contenedor de la base de datos (`sudo docker compose -f /home/pi/dtk/docker-compose.yml -f /home/pi/dtk/docker-compose.pi.yml up -d db`). Hay tres estados que no causan rechazo: una base de datos inexistente, como la que deja una restauración interrumpida, no contiene ningún volumen; una base de datos sin tabla de volúmenes tampoco contiene ninguno; y un esquema anterior a las raíces no tiene directorios de raíz. En los tres casos, el script sigue comprobando las imágenes de la propia copia. -**La primera instalación de 0.1.0.** Cuando 0.1.0 ya ha arrancado y ha movido archivos a `/captures/` (3.3 y, para volúmenes que ya tenían prefijo, el inicio al final de `update.sh`), la copia anterior a la actualización indica las rutas antiguas de esos archivos. Una reversión a esa copia dejaría los volúmenes sin acceso a sus archivos, así que la comprobación rechaza la ejecución. Después de una actualización fallida con un registro de tipo `started-failed`, usa `update.sh --resolve-forward` (7.4) en lugar de una reversión. Un registro de tipo `migrated-not-restored` significa que la versión nueva nunca arrancó, así que no movió ningún archivo. Después de una actualización exitosa, instala una versión corregida mediante una actualización habitual. +**La primera instalación de 0.1.0-beta.** Cuando 0.1.0-beta ya ha arrancado y ha movido archivos a `/captures/` (3.3 y, para volúmenes que ya tenían raíz, el inicio al final de `update.sh`), la copia anterior a la actualización indica las rutas antiguas de esos archivos. Una reversión a esa copia dejaría los volúmenes sin acceso a sus archivos, así que la comprobación rechaza la ejecución. Después de una actualización fallida con un registro de tipo `started-failed`, usa `update.sh --resolve-forward` (7.4) en lugar de una reversión. Un registro de tipo `migrated-not-restored` significa que la versión nueva nunca arrancó, así que no movió ningún archivo. Después de una actualización exitosa, instala una versión corregida mediante una actualización habitual. -Todavía no existe ningún comando para recuperar un volumen después de aceptar su pérdida. Tenemos previsto un comando `restore-stem` para después de 0.1.0. +Todavía no existe ningún comando para recuperar un volumen después de aceptar su pérdida. Tenemos previsto un comando `restore-stem` para después de 0.1.0-beta. ### 8.1 Qué restaura {#what-it-restores} @@ -757,19 +775,19 @@ sudo mv /var/lib/dtk/offsite.env /var/lib/dtk/offsite.env.aside ### 8.2 Qué pierde {#what-it-loses} -Todo lo escrito en la base de datos después de la copia: capturas (sus archivos permanecen en la tarjeta, pero ninguna fila los referencia), prefijos de nombre de archivo asignados en el paso 3, claves registradas por `adopt-map` y `adopt` en el paso 5, aumentos del contador, cargas registradas en el paso 6 y el estado de los archivos liberados. +Todo lo escrito en la base de datos después de la copia: capturas (sus archivos permanecen en la tarjeta, pero ninguna fila los referencia), raíces asignadas en el paso 3, claves registradas por `adopt-map` y `adopt` en el paso 5, aumentos del contador, cargas registradas en el paso 6 y el estado de los archivos liberados. Nunca vuelvas a una versión anterior después de liberar un volumen. Los archivos liberados ya no están en la tarjeta, la base de datos restaurada los indica como presentes y ya no contiene los registros que permitirían a un administrador recuperarlos desde el bucket. ### 8.3 Cuándo es seguro {#when-it-is-safe} -El momento más sencillo es antes del paso 3. Hasta entonces, el backend solo ha movido archivos de volúmenes que tenían prefijo de nombre de archivo antes de la actualización; en un equipo donde ningún volumen tenía prefijo, no ha movido nada. +El momento más sencillo es antes del paso 3. Hasta entonces, el backend solo ha movido archivos de volúmenes que tenían raíz antes de la actualización; en un equipo donde ningún volumen tenía raíz, no ha movido nada. -No vuelvas a una versión anterior después del reinicio de 3.3. A partir de ese momento, los archivos de cada volumen al que asignaste un prefijo están en `/` y las filas restauradas indican sus rutas antiguas. La versión anterior no puede encontrar los archivos trasladados y ningún proceso los devuelve a su lugar. La comprobación de prefijos de nombre de archivo (8.0a) rechaza una reversión de ese tipo. +No vuelvas a una versión anterior después del reinicio de 3.3. A partir de ese momento, los archivos de cada volumen al que asignaste una raíz están en `/` y las filas restauradas indican sus rutas antiguas. La versión anterior no puede encontrar los archivos trasladados y ningún proceso los devuelve a su lugar. La comprobación de raíces (8.0a) rechaza una reversión de ese tipo. ### 8.4 La próxima actualización {#the-next-update} -La reversión escribe el commit restaurado en `last-deployed-SHA` y mueve la rama local a ese commit. El `update.sh` del disco corresponde entonces a la versión restaurada, no a 0.1.0, así que la próxima actualización repite la instalación de 0.1.0: +La reversión escribe el commit restaurado en `last-deployed-SHA` y mueve la rama local a ese commit. El `update.sh` del disco corresponde entonces a la versión restaurada, no a 0.1.0-beta, así que la próxima actualización repite la instalación de 0.1.0-beta: 1. 2.1: devuelve `main` a `origin/main` (`git -C /home/pi/dtk checkout -B main origin/main`), sincroniza los submódulos y comprueba el árbol de trabajo. 2. Si apartaste `offsite.env` (8.1), crea la suspensión y devuelve `offsite.env` a su lugar: @@ -783,10 +801,10 @@ La reversión escribe el commit restaurado en `last-deployed-SHA` y mueve la ram 3. 2.2, con `--no-pull`. 4. Repite los pasos 3 a 6: la reversión descartó todo lo escrito después de la copia (8.2). -Cuando vuelves a actualizar el equipo a 0.1.0, el backend mueve archivos al arrancar: +Cuando vuelves a actualizar el equipo a 0.1.0-beta, el backend mueve archivos al arrancar: -- Para un volumen cuyo prefijo de nombre de archivo figura en la base de datos restaurada, el backend hace que una fila cuya ruta antigua ya no existe apunte al archivo del mismo nombre en `/captures/` si el sha256 del archivo coincide con la suma de comprobación registrada durante la captura. Informa de un archivo sin esa suma de comprobación como `missing`. -- La comprobación de prefijos de nombre de archivo (8.0a) rechaza una reversión que dejaría un volumen sin acceso a sus archivos. Después de aceptar una reversión con `--accept-lost-stems`, el backend rechaza una nueva asignación de un prefijo perdido mientras `/` contenga archivos que ninguna fila del volumen referencia. Todavía no existe ningún comando para recuperar un volumen después de aceptar su pérdida; tenemos previsto `restore-stem` para después de 0.1.0. +- Para un volumen cuya raíz figura en la base de datos restaurada, el backend hace que una fila cuya ruta antigua ya no existe apunte al archivo del mismo nombre en `/captures/` si el sha256 del archivo coincide con la suma de comprobación registrada durante la captura. Informa de un archivo sin esa suma de comprobación como `missing`. +- La comprobación de raíces (8.0a) rechaza una reversión que dejaría un volumen sin acceso a sus archivos. Después de aceptar una reversión con `--accept-lost-stems`, el backend rechaza una nueva asignación de una raíz perdida mientras `/` contenga archivos que ninguna fila del volumen referencia. Todavía no existe ningún comando para recuperar un volumen después de aceptar su pérdida; tenemos previsto `restore-stem` para después de 0.1.0-beta. --- @@ -797,17 +815,19 @@ Cuando vuelves a actualizar el equipo a 0.1.0, el backend mueve archivos al arra El backend envía a Fisqua el manifiesto de captura de cada volumen enviado a revisión y consulta a Fisqua el estado del volumen cuando la configuración cumple las tres condiciones siguientes: -- `DTK_FISQUA_ENV` tiene el valor `production` o `staging`. Producción llama a `https://.fisqua.org`; staging llama a `https://.staging.fisqua.org`. -- `DTK_FISQUA_TOKEN` contiene 64 caracteres hexadecimales en minúsculas. -- `DTK_OFFSITE_TENANT` contiene un tenant válido. +- `CAPTUA_FISQUA_ENV` tiene el valor `production` o `staging`. Producción llama a `https://.fisqua.org`; staging llama a `https://.staging.fisqua.org`. +- `CAPTUA_FISQUA_TOKEN` contiene 64 caracteres hexadecimales en minúsculas. +- `CAPTUA_OFFSITE_TENANT` contiene un tenant válido. De lo contrario, el backend no pone nada en cola ni envía nada, y al arrancar escribe en el registro `INFO app.core.fisqua_outbox: Fisqua is not configured; no status poll started`. -El backend solo envía manifiestos cuando `DTK_OFFSITE_REMOTE` también tiene un valor definido: el ciclo de envío forma parte de la tarea programada de carga de imágenes, que el backend solo inicia si tiene un destino remoto y un tenant válido. Con tenant pero sin destino remoto, el backend pone manifiestos en cola y nunca los envía. +El backend solo envía manifiestos cuando `CAPTUA_OFFSITE_REMOTE` también tiene un valor definido: el ciclo de envío forma parte de la tarea programada de carga de imágenes, que el backend solo inicia si tiene un destino remoto y un tenant válido. Con tenant pero sin destino remoto, el backend pone manifiestos en cola y nunca los envía. + +Desde la versión siguiente a 0.2.0, el enlace solo funciona mientras el equipo está en modo "Fisqua" (6.2a). En cualquier otro modo, el backend no envía nada a Fisqua ni le consulta el estado de los volúmenes. El backend lee esta configuración al arrancar. Durante una actualización, define los valores antes del paso 6 y el reinicio de 6.1 los aplica; fuera de una actualización, aplica cualquier cambio con `sudo systemctl restart dtk`. Todas las llamadas usan HTTPS y el token del equipo. El backend nunca escribe el token en los registros, lo almacena ni lo devuelve; en el equipo, `offsite.env` lo contiene, y el archivo de claves también lo contiene hasta que lo elimines. -El número de versión está en el archivo `VERSION` de la raíz del repositorio (`0.1.0`). El backend lo envía en cada manifiesto como `systemVersion`: `0.1.0` cuando el repositorio tiene seleccionado el commit con la etiqueta `0.1.0`; en cualquier otro caso, `0.1.0+g`. El backend lee la etiqueta de los archivos de Git del superproyecto sin ejecutar git: si solo puede encontrar una etiqueta dentro de un archivo pack, o en `packed-refs` sin la línea que resuelve por completo el destino de la etiqueta, considera que no hay etiqueta y la versión incluye `+g…` incluso en el commit etiquetado (compruébalo en el equipo de pruebas cuando exista la etiqueta). +El número de versión está en el archivo `VERSION` de la raíz del repositorio (`0.2.0` en la versión actual). El backend lo envía en cada manifiesto como `systemVersion`: `` cuando el repositorio tiene seleccionado el commit con la etiqueta ``; en cualquier otro caso, `+g`. El backend lee la etiqueta de los archivos de Git del superproyecto sin ejecutar git: si solo puede encontrar una etiqueta dentro de un archivo pack, o en `packed-refs` sin la línea que resuelve por completo el destino de la etiqueta, considera que no hay etiqueta y la versión incluye `+g…` incluso en el commit etiquetado (compruébalo en un equipo de pruebas). ### 9.2 Preparar la configuración {#provisioning} @@ -818,10 +838,10 @@ FISQUA_TOKEN=<64 lowercase hexadecimal characters> ``` ```bash -sudo DTK_OFFSITE_KEY_FILE=/root/dtk-offsite-key \ +sudo CAPTUA_OFFSITE_KEY_FILE=/root/dtk-offsite-key \ /home/pi/dtk/scripts/provision-rclone.sh \ --tenant \ - --dump-recipient age172wkzadqepd565chppztfw8jefpcga8s7t6eqrfhnxnv2nlfkdrqygrl3m \ + --dump-recipient \ --fisqua-env production ``` @@ -829,7 +849,7 @@ sudo DTK_OFFSITE_KEY_FILE=/root/dtk-offsite-key \ - El script lee el token exclusivamente del archivo de claves, rechaza cualquier token que no tenga 64 caracteres hexadecimales en minúsculas sin mostrarlo y lo rechaza cuando no indicas un tenant o un entorno y tampoco hay uno registrado. - Escribe `DTK_FISQUA_TOKEN` y `DTK_FISQUA_ENV` en `offsite.env`. Conserva ambos valores en las ejecuciones posteriores en las que no los indiques. Si cambias cualquiera de los dos, aplica el cambio y muestra una nota. - Con `--advisory`, como lo ejecuta `update.sh`, el script no toma el token. -- El script no hace ninguna llamada a Fisqua. El backend detecta un token incorrecto en la primera llamada: Fisqua responde `401` y el backend detiene los envíos y las consultas de estado (9.4). El backend solo hace su primera llamada a Fisqua cuando ha verificado por completo la copia remota del primer volumen enviado a revisión. Por eso un token incorrecto puede pasar inadvertido durante horas o días después de preparar la configuración. +- El script no hace ninguna llamada a Fisqua. El backend detecta un token incorrecto en la primera llamada: Fisqua responde `401` y el backend detiene los envíos y las consultas de estado (9.4). El backend solo hace su primera llamada a Fisqua cuando ha verificado por completo la copia externa del primer volumen enviado a revisión. Por eso un token incorrecto puede pasar inadvertido durante horas o días después de preparar la configuración. El backend lee `offsite.env` al arrancar. Durante una actualización, ejecuta el script antes del paso 6 y el reinicio de 6.1 aplica los cambios. Fuera de una actualización, reinicia dtk. Elimina el archivo de claves después de ejecutar el script: @@ -849,71 +869,79 @@ Cuando una persona operadora envía un volumen a revisión, el backend pone en c 1. El backend mantiene en cola el manifiesto hasta completar la recepción del volumen: todos los objetos del volumen deben estar verificados en el bucket. 2. Después construye el manifiesto con un identificador fijo y lo envía en ese mismo ciclo. -3. A partir de la respuesta de Fisqua, marca el manifiesto como entregado o rechazado. Tras un fallo transitorio, el siguiente intento queda programado para después de `DTK_FISQUA_RETRY_BASE` segundos (300). La espera duplica su duración con cada fallo posterior, hasta un máximo de `DTK_FISQUA_RETRY_MAX` (6 horas), y nunca termina antes del momento que indique `Retry-After` de Fisqua. El backend envía el manifiesto en el primer ciclo de envío posterior a ese momento. Ejecuta un ciclo de envío después de cada ejecución de carga de imágenes, y ejecuta estas cargas cada `DTK_OFFSITE_BACKUP_INTERVAL` (30 minutos de forma predeterminada), o de inmediato cuando un envío a revisión activa la tarea programada. El backend sigue reintentando sin límite de intentos. +3. A partir de la respuesta de Fisqua, marca el manifiesto como entregado o rechazado. Tras un fallo transitorio, el siguiente intento queda programado para después de `CAPTUA_FISQUA_RETRY_BASE` segundos (300). La espera duplica su duración con cada fallo posterior, hasta un máximo de `CAPTUA_FISQUA_RETRY_MAX` (6 horas), y nunca termina antes del momento que indique `Retry-After` de Fisqua. El backend envía el manifiesto en el primer ciclo de envío posterior a ese momento. Ejecuta un ciclo de envío después de cada ejecución de carga de imágenes, y ejecuta estas cargas cada `CAPTUA_OFFSITE_BACKUP_INTERVAL` (30 minutos de forma predeterminada), o de inmediato cuando un envío a revisión activa la tarea programada. El backend sigue reintentando sin límite de intentos. -El backend rechaza de inmediato, sin enviarlo, un volumen cuyo código de referencia registrado no coincida con su prefijo de nombre de archivo, con el problema `reference_code_differs`. Si el componente que construye el manifiesto rechaza un volumen, el backend lo rechaza con los problemas que indica ese componente. Al retirar un volumen de revisión, el backend retira sus manifiestos aún no enviados y no envía nada a Fisqua. Un nuevo envío a revisión reemplaza los manifiestos del volumen que aún no ha enviado. Mientras exista la suspensión (4.0), el backend no construye ni envía ningún manifiesto. +El backend rechaza de inmediato, sin enviarlo, un volumen cuyo código de referencia registrado no coincida con su raíz, con el problema `reference_code_differs`. Si el componente que construye el manifiesto rechaza un volumen, el backend lo rechaza con los problemas que indica ese componente. Al retirar un volumen de revisión, el backend retira sus manifiestos aún no enviados y no envía nada a Fisqua. Un nuevo envío a revisión reemplaza los manifiestos del volumen que aún no ha enviado. Mientras exista la suspensión (4.0), el backend no construye ni envía ningún manifiesto. -En el equipo de pruebas, el 25 de octubre de 2026, con el volumen `cobos-bench-005` y el límite predeterminado de `750k` (4.5): el backend empezó la carga 2 segundos después del envío a revisión, verificó sus 12 objetos en 5 minutos y 43 segundos, y envió el manifiesto 0,08 segundos después de la última verificación. Después de retirar el volumen de revisión y enviarlo de nuevo, Fisqua registró el manifiesto nuevo en menos de 3 segundos. +En una prueba, con el límite predeterminado de `750k` (4.5), el backend empezó la carga 2 segundos después del envío a revisión, verificó los 12 objetos del volumen en 5 minutos y 43 segundos, y envió el manifiesto 0,08 segundos después de la última verificación. Después de retirar el volumen de revisión y enviarlo de nuevo, Fisqua registró el manifiesto nuevo en menos de 3 segundos. -El backend consulta por primera vez a Fisqua el estado de sus volúmenes `DTK_OFFSITE_BACKUP_DELAY` segundos (300) después del inicio y después cada diez minutos (`DTK_FISQUA_POLL_INTERVAL`, 600). Consulta un volumen mientras Fisqua no haya indicado un estado final para su manifiesto enviado más reciente y mientras Fisqua ofrezca un conjunto de decisiones del volumen que el backend aún no haya leído (9.5). Los estados finales son `published`, `refused` y `superseded`. +El backend consulta por primera vez a Fisqua el estado de sus volúmenes `CAPTUA_OFFSITE_BACKUP_DELAY` segundos (300) después del inicio y después cada diez minutos (`CAPTUA_FISQUA_POLL_INTERVAL`, 600). Consulta un volumen mientras Fisqua no haya indicado un estado final para su manifiesto enviado más reciente y mientras Fisqua ofrezca un conjunto de decisiones del volumen que el backend aún no haya leído (9.5). Los estados finales son `published`, `refused` y `superseded`. ### 9.4 La página del volumen {#the-volume-page} -En la barra superior de la vista del volumen, debajo de la línea de copia remota, una línea muestra la entrega a Fisqua del manifiesto más reciente del volumen que no tenga un reemplazo posterior ni haya sido retirado. Cuando hay más información (una detención por configuración, un incidente, problemas, notas o envíos anteriores), puedes seleccionar la línea para abrir un panel. Los textos de la línea son los siguientes: +En la barra superior de la vista del volumen, debajo de la línea de copia externa, una línea muestra la entrega a Fisqua del manifiesto más reciente del volumen que no tenga un reemplazo posterior ni haya sido retirado. Cuando hay más información (una detención por configuración, un incidente, problemas, notas o envíos anteriores), puedes seleccionar la línea para abrir un panel. Los textos de la línea son los siguientes: | Texto | Significado | |---|---| -| `Not sent to Fisqua yet` | El backend no tiene ningún manifiesto en cola para el volumen, o todos tienen reemplazos posteriores o han sido retirados. | -| `Waiting for the complete offsite copy before sending to Fisqua` | El manifiesto está en cola; el volumen todavía no tiene recepción completa. | -| `Captua is sending the capture manifest to Fisqua` | El manifiesto está construido y espera el siguiente ciclo de envío (`ready`), o el backend lo está enviando (`sending`). Durante una detención por configuración debida a `token`, `not_found` o `redirect`, la línea conserva este texto y el panel muestra la advertencia. | -| `Captua could not send the capture manifest to Fisqua; it will try again ` | Ocurrió un fallo transitorio; el backend vuelve a intentar el envío. | -| `Not sent to Fisqua: Captua cannot build the capture manifest` | El equipo rechazó el manifiesto; la lista indica los problemas. | -| `Fisqua refused the capture manifest` | Fisqua rechazó el manifiesto e indicó sus problemas. | -| `Sent to Fisqua; waiting for its status` | El manifiesto está entregado; todavía no hay un estado. | +| `Todavía no se ha enviado a Fisqua` | El backend no tiene ningún manifiesto en cola para el volumen, o todos tienen reemplazos posteriores o han sido retirados. | +| `Captua lo enviará a Fisqua cuando la copia externa esté completa` | El manifiesto está en cola; el volumen todavía no tiene recepción completa. | +| `Captua está enviando el manifiesto de captura a Fisqua` | El manifiesto está construido y espera el siguiente ciclo de envío (`ready`), o el backend lo está enviando (`sending`). Durante una detención por configuración debida a `token`, `not_found` o `redirect`, la línea conserva este texto y el panel muestra la advertencia. | +| `Captua no pudo enviar el manifiesto de captura a Fisqua; lo intentará de nuevo ` | Ocurrió un fallo transitorio; el backend vuelve a intentar el envío. | +| `No se envió a Fisqua: Captua no puede generar el manifiesto de captura` | El equipo rechazó el manifiesto; la lista indica los problemas. | +| `Fisqua rechazó el manifiesto de captura` | Fisqua rechazó el manifiesto e indicó sus problemas. | +| `Enviado a Fisqua; a la espera de que Fisqua informe el estado` | El manifiesto está entregado; todavía no hay un estado. | -La lista `Earlier sends ()` del panel muestra los otros manifiestos del volumen con los mismos textos. Dos textos solo aparecen allí: `Not sent: a later send for review replaced it` para un manifiesto con un reemplazo posterior y `Not sent: the volume was withdrawn from review` para uno retirado. +La lista `Envíos anteriores ()` del panel muestra los otros manifiestos del volumen con los mismos textos. Dos textos solo aparecen allí: `No se envió: el volumen se volvió a enviar a revisión y el nuevo envío lo reemplazó` para un manifiesto con un reemplazo posterior y `No se envió: el volumen se retiró de revisión` para uno retirado. -Cuando Fisqua responde, la línea muestra su estado, desde `Fisqua received the volume` hasta `Published in Fisqua`, o `Fisqua does not know this volume yet` (normalmente el manifiesto no llegó; el backend sigue consultando). El panel enumera los problemas y las notas de Fisqua, y antepone `From Fisqua: ` al texto de Fisqua. Captua redacta por su cuenta los textos de cuatro reglas: `unlisted-object` y `missing-object` (cuando Fisqua identifica el objeto), `bad-request` y `payload-too-large`. `Fisqua could not find some files in the offsite copy that Captua had already verified there. This needs investigating: ask whoever manages the scanner to check the offsite copy. The missing files are listed below.` indica un incidente: comprueba en el bucket las claves enumeradas. +Cuando Fisqua responde, la línea muestra su estado, desde `Fisqua recibió el volumen` hasta `Publicado en Fisqua`, o `Fisqua todavía no tiene registro de este volumen` (normalmente el manifiesto no llegó; el backend sigue consultando). El panel enumera los problemas y las notas de Fisqua, y antepone `Mensaje de Fisqua: ` al texto de Fisqua. Captua redacta por su cuenta los textos de cuatro reglas: `unlisted-object` y `missing-object` (cuando Fisqua identifica el objeto), `bad-request` y `payload-too-large`. `Fisqua no encontró en la copia externa algunos archivos que Captua ya había verificado allí. Avisa al administrador: tiene que revisar la copia externa y averiguar qué pasó con ellos. Abajo aparece la lista de los archivos que faltan.` indica un incidente: comprueba en el bucket las claves enumeradas. **Detenciones por configuración.** El backend detiene los envíos y las consultas de estado de todo el equipo cuando Fisqua responde `401` o `403` (motivo `token`), `404` (`not_found`) o cualquier redirección (`redirect`). Un `404` con la regla `no-decisions` al leer decisiones no causa una detención (9.5). El backend también detiene estas operaciones ante un `400` cuyos problemas indiquen que Fisqua no puede leer los manifiestos que escribe este software (reglas `version`, `envelope` o `shape`, motivo `version`); el rechazo de ese manifiesto es definitivo. El registro muestra: ```text -ERROR app.core.fisqua_outbox: Fisqua answered HTTP () for this unit's configuration (fingerprint <8 hex>); sending and polling stop until DTK_FISQUA_ENV, DTK_FISQUA_BASE_URL or DTK_FISQUA_TOKEN is changed +ERROR app.core.fisqua_outbox: Fisqua answered HTTP () for this unit's configuration (fingerprint <8 hex>); sending and polling stop until CAPTUA_FISQUA_ENV, CAPTUA_FISQUA_BASE_URL or CAPTUA_FISQUA_TOKEN is changed ``` -Para el motivo `version`, el backend escribe en cambio esta línea; `` es `DTK_FISQUA_RETRY_MAX` (21600 de forma predeterminada): +Para el motivo `version`, el backend escribe en cambio esta línea; `` es `CAPTUA_FISQUA_RETRY_MAX` (21600 de forma predeterminada): ```text ERROR app.core.fisqua_outbox: Fisqua answered HTTP 400 (version) for this unit's manifests (fingerprint <8 hex>); sending and polling stop until the software is updated, or until a retest every s finds that Fisqua reads its manifests ``` -La página del volumen y la página de configuración indican el motivo. Para una detención por token muestran `Fisqua does not accept the token configured on this scanner, so Captua has stopped sending volumes to Fisqua and checking their status. Ask whoever manages the scanner to correct DTK_FISQUA_TOKEN and restart Captua.` Para el motivo `version` muestran `Fisqua does not read the capture manifests this version of Captua writes, so Captua has stopped sending volumes to Fisqua and checking their status. Ask whoever manages the scanner to update Captua or Fisqua.` +La página del volumen y la página **Configuración** indican el motivo. Para una detención por token muestran `Fisqua no acepta el token configurado en este equipo, así que Captua dejó de enviarle volúmenes y de consultar en qué estado están. Avisa al administrador: tiene que corregir CAPTUA_FISQUA_TOKEN y reiniciar Captua.` Para el motivo `version` muestran `Fisqua no puede leer los manifiestos de captura de esta versión de Captua, así que Captua dejó de enviarle volúmenes y de consultar en qué estado están. Avisa al administrador: tiene que actualizar Captua, o pedir que actualicen Fisqua.` -El backend conserva la detención en `/var/lib/dtk/fisqua-config-error.json`, incluso después de reiniciar. La elimina cuando cambia el entorno, el tenant (a través de la URL base que construye a partir de él, salvo que `DTK_FISQUA_BASE_URL` tenga un valor definido), `DTK_FISQUA_BASE_URL`, el token o el código instalado; entonces el registro muestra `INFO app.core.fisqua_outbox: The Fisqua configuration was changed since Fisqua refused it; sending resumes`. El backend lee `offsite.env` al arrancar: durante una actualización, el reinicio de 6.1 aplica cualquier cambio de ese archivo; fuera de una actualización, aplícalo con `sudo systemctl restart dtk`. Una actualización que cambie el commit del backend o la versión publicada también elimina una detención por token; si el token sigue siendo incorrecto, la siguiente llamada del backend vuelve a detener estas operaciones en el equipo. El backend también elimina una detención por versión después de una prueba de compatibilidad cuyo manifiesto Fisqua pueda leer (más abajo). +El backend conserva la detención en `/var/lib/dtk/fisqua-config-error.json`, incluso después de reiniciar. La elimina cuando cambia el entorno, el tenant (a través de la URL base que construye a partir de él, salvo que `CAPTUA_FISQUA_BASE_URL` tenga un valor definido), `CAPTUA_FISQUA_BASE_URL`, el token o el código instalado; entonces el registro muestra `INFO app.core.fisqua_outbox: The Fisqua configuration was changed since Fisqua refused it; sending resumes`. El backend lee `offsite.env` al arrancar: durante una actualización, el reinicio de 6.1 aplica cualquier cambio de ese archivo; fuera de una actualización, aplícalo con `sudo systemctl restart dtk`. Una actualización que cambie el commit del backend o la versión publicada también elimina una detención por token; si el token sigue siendo incorrecto, la siguiente llamada del backend vuelve a detener estas operaciones en el equipo. El backend también elimina una detención por versión después de una prueba de compatibilidad cuyo manifiesto Fisqua pueda leer (más abajo). -**La detención por versión.** Mientras dure, el backend no construye ningún manifiesto salvo el que envía una prueba de compatibilidad (más abajo). El backend vuelve a poner en espera de construcción los manifiestos que ya había construido, pero no había enviado cuando llegó el rechazo, para construirlos de nuevo con identificadores nuevos. Por eso su línea muestra `Waiting for the complete offsite copy before sending to Fisqua`. Para esta detención, el código instalado consiste en el commit del backend y la versión que indica `VERSION`: una actualización que cambie cualquiera de los dos elimina la detención, y una que no cambie ninguno la conserva. Cuando el backend no puede leer su commit, elimina la detención en cada reinicio. Un cambio de entorno, tenant, URL base o token también la elimina, al igual que una prueba de compatibilidad cuyo manifiesto Fisqua pueda leer (más abajo). Cuando desaparece la detención, el backend vuelve a enviar a revisión cada volumen cuyo manifiesto más reciente tenga un rechazo por versión, con un identificador de manifiesto nuevo, siempre que ninguno de sus registros esté en estado `captured`, y escribe `INFO app.core.fisqua_outbox: Volume handed to Fisqua again under a new manifest id after a version refusal`. +**La detención por versión.** Mientras dure, el backend no construye ningún manifiesto salvo el que envía una prueba de compatibilidad (más abajo). El backend vuelve a poner en espera de construcción los manifiestos que ya había construido, pero no había enviado cuando llegó el rechazo, para construirlos de nuevo con identificadores nuevos. Por eso su línea muestra `Captua lo enviará a Fisqua cuando la copia externa esté completa`. Para esta detención, el código instalado consiste en el commit del backend y la versión que indica `VERSION`: una actualización que cambie cualquiera de los dos elimina la detención, y una que no cambie ninguno la conserva. Cuando el backend no puede leer su commit, elimina la detención en cada reinicio. Un cambio de entorno, tenant, URL base o token también la elimina, al igual que una prueba de compatibilidad cuyo manifiesto Fisqua pueda leer (más abajo). Cuando desaparece la detención, el backend vuelve a enviar a revisión cada volumen cuyo manifiesto más reciente tenga un rechazo por versión, con un identificador de manifiesto nuevo, siempre que ninguno de sus registros esté en estado `captured`, y escribe `INFO app.core.fisqua_outbox: Volume handed to Fisqua again under a new manifest id after a version refusal`. -**La prueba de compatibilidad.** Mientras dure una detención por versión, el backend envía un manifiesto cada `DTK_FISQUA_RETRY_MAX` segundos (21600, seis horas), contados desde el momento en que registró la detención o desde la última prueba, el que sea posterior. Envía la primera prueba seis horas después de registrar la detención. Envía la prueba en el primer ciclo de envío posterior a ese momento y ejecuta un ciclo de envío después de cada ejecución de carga de imágenes (9.3). La prueba necesita un volumen enviado a revisión y con recepción completa de la copia remota: el backend toma, del más antiguo al más reciente, un manifiesto pendiente de construcción o construido pero nunca enviado, o un volumen cuyo manifiesto más reciente tenga un rechazo por versión y ninguno de cuyos registros esté en estado `captured`; en este último caso, vuelve a enviarlo a revisión con un identificador de manifiesto nuevo. Si no hay un volumen así o no quedan llamadas en el límite por minuto, el backend no envía nada y vuelve a intentarlo en el siguiente ciclo de envío. La acción posterior del backend depende de la respuesta de Fisqua: +**La prueba de compatibilidad.** Mientras dure una detención por versión, el backend envía un manifiesto cada `CAPTUA_FISQUA_RETRY_MAX` segundos (21600, seis horas), contados desde el momento en que registró la detención o desde la última prueba, el que sea posterior. Envía la primera prueba seis horas después de registrar la detención. Envía la prueba en el primer ciclo de envío posterior a ese momento y ejecuta un ciclo de envío después de cada ejecución de carga de imágenes (9.3). La prueba necesita un volumen enviado a revisión y con recepción completa de la copia externa: el backend toma, del más antiguo al más reciente, un manifiesto pendiente de construcción o construido pero nunca enviado, o un volumen cuyo manifiesto más reciente tenga un rechazo por versión y ninguno de cuyos registros esté en estado `captured`; en este último caso, vuelve a enviarlo a revisión con un identificador de manifiesto nuevo. Si no hay un volumen así o no quedan llamadas en el límite por minuto, el backend no envía nada y vuelve a intentarlo en el siguiente ciclo de envío. La acción posterior del backend depende de la respuesta de Fisqua: - Fisqua acepta el manifiesto o lo rechaza por su contenido en lugar de su versión: el backend elimina la detención. En el mismo ciclo vuelve a enviar a revisión cada volumen cuyo manifiesto más reciente tenga un rechazo por versión, y después construye y envía los manifiestos pendientes, dentro del límite por ciclo. - Fisqua vuelve a rechazarlo por versión: el backend registra de nuevo la detención con la hora de este rechazo, así que la próxima prueba corresponde a un intervalo después. - El envío tiene un fallo transitorio: la detención continúa. El backend envía el mismo manifiesto con el mismo identificador en la siguiente prueba, nunca antes del momento que indique `Retry-After` de Fisqua. - Fisqua responde con un error de configuración (`token`, `not_found` o `redirect`): esa detención reemplaza la detención por versión. El backend no hace pruebas para ella; la conserva hasta que cambie la configuración o el código instalado (más arriba). -Cuando Fisqua admita los manifiestos que escribe este software, el backend reanuda los envíos en un plazo de seis horas más la espera hasta el siguiente ciclo de envío, sin que tengas que intervenir en el equipo, siempre que exista algún volumen enviado a revisión y con recepción completa de la copia remota y ninguno de sus registros esté en estado `captured`. De lo contrario, conserva la detención hasta que exista un volumen así, o hasta que una actualización o un cambio de configuración la elimine. El backend no hace ninguna prueba mientras exista la suspensión de cargas remotas (4.0). No necesitas eliminar `/var/lib/dtk/fisqua-config-error.json` manualmente. Cuando una actualización o un cambio de configuración elimina la detención, el backend vuelve a construir, con el código nuevo y con identificadores de manifiesto nuevos, los manifiestos que construyeron las pruebas y que nunca llegaron a enviar, y el manifiesto de la última prueba cuando el backend perdió su respuesta o su envío falló. +Cuando Fisqua admita los manifiestos que escribe este software, el backend reanuda los envíos en un plazo de seis horas más la espera hasta el siguiente ciclo de envío, sin que tengas que intervenir en el equipo, siempre que exista algún volumen enviado a revisión y con recepción completa de la copia externa y ninguno de sus registros esté en estado `captured`. De lo contrario, conserva la detención hasta que exista un volumen así, o hasta que una actualización o un cambio de configuración la elimine. El backend no hace ninguna prueba mientras exista la suspensión de cargas remotas (4.0). No necesitas eliminar `/var/lib/dtk/fisqua-config-error.json` manualmente. Cuando una actualización o un cambio de configuración elimina la detención, el backend vuelve a construir, con el código nuevo y con identificadores de manifiesto nuevos, los manifiestos que construyeron las pruebas y que nunca llegaron a enviar, y el manifiesto de la última prueba cuando el backend perdió su respuesta o su envío falló. -La tarjeta **Offsite copy** de la página de configuración tiene una sección **Fisqua** con el entorno, el último envío y la última consulta de estado. `GET /system/catalogue-backup` devuelve lo mismo dentro de `fisqua`: `configured`, `token_invalid`, `environment`, `config_error`, `held`, `last_send` y `last_poll`. +La tarjeta **Copia externa** de la página **Configuración** tiene una sección **Fisqua** con el entorno, el último envío y la última consulta de estado. `GET /system/catalogue-backup` devuelve lo mismo dentro de `fisqua`: `configured`, `token_invalid`, `environment`, `config_error`, `held`, `last_send` y `last_poll`. ### 9.5 Las decisiones de Fisqua {#fisquas-decisions} Cuando Fisqua ha decidido sobre los registros de un volumen, la consulta de estado lee y aplica las decisiones, exclusivamente para el envío a revisión actual del volumen: -- Un registro aprobado pasa a `approved`; un registro rechazado pasa a `rejected`, con el motivo y la nota de Fisqua. El backend registra como revisor en ambos casos `Fisqua: `, o `Fisqua` cuando Fisqua no identifica a nadie. La decisión de Fisqua reemplaza una decisión local. -- El conjunto de decisiones de Fisqua reemplaza la corrección de rotación de cada imagen actual de un registro al que aplica: si el conjunto no indica una corrección para una imagen, esa imagen pierde cualquier corrección local. El backend no modifica ningún archivo. -- El backend omite los siguientes casos e informa de ellos sin cambiar nada en ese registro: un registro que no pertenece al volumen, un registro en estado `captured` (alguien retiró el volumen de revisión o repitió la captura del registro), un registro cuyas imágenes actuales no coinciden con las que enumeraba el manifiesto objeto de la decisión (`images_changed`), una decisión que no sea de aprobación ni de rechazo, y un rechazo que la ruta local de rechazo no admitiría (`note_too_long`, un motivo que no figure en la lista, `other` sin nota). -- El backend no aplica un conjunto de decisiones de un manifiesto anterior. Deja pendiente un conjunto mientras un envío a revisión más reciente del volumen aún no haya llegado a Fisqua. -- Cuando el estado de Fisqua ofrece un conjunto de decisiones y Fisqua responde a su lectura con `404` y la regla `no-decisions`, el backend no aplica nada, escribe `INFO app.core.fisqua_outbox: Fisqua has no decisions to give for volume yet; read again at the next poll` y vuelve a leer el conjunto en la siguiente consulta de estado. El enlace sigue activo. Cualquier otro `404` causa una detención por configuración (9.4). +- Un registro aprobado pasa a `approved`; un registro rechazado pasa a `rejected`, con el motivo y la nota de Fisqua. En ambos casos, el backend registra como revisor `Fisqua: `, o `Fisqua` cuando Fisqua no identifica a nadie. La decisión de Fisqua reemplaza cualquier decisión local. +- El conjunto de decisiones de Fisqua reemplaza la corrección de rotación de cada imagen actual de los registros a los que se aplica: si el conjunto no indica una corrección para una imagen, esa imagen pierde cualquier corrección local. El backend no modifica ningún archivo. +- El backend omite los casos siguientes y los informa, sin cambiar nada en el registro afectado: un registro que no pertenece al volumen, un registro en estado `captured` (alguien retiró el volumen de revisión o repitió la captura del registro), un registro cuyas imágenes actuales no coinciden con las que enumeraba el manifiesto objeto de la decisión (`images_changed`), una decisión que no sea de aprobación ni de rechazo (`invalid_decision`), y un rechazo que Captua no admitiría si se hiciera en el equipo (`note_too_long`, un motivo que no figure en la lista, `other` sin nota). +- El backend no aplica los conjuntos de decisiones de manifiestos anteriores, y deja pendiente un conjunto mientras Fisqua no haya recibido un envío a revisión más reciente del volumen. +- Cuando el estado de Fisqua indica que hay un conjunto de decisiones, pero Fisqua responde con `404` y la regla `no-decisions` cuando el backend lo lee, el backend no aplica nada, escribe `INFO app.core.fisqua_outbox: Fisqua has no decisions to give for volume yet; read again at the next poll` y vuelve a leer el conjunto en la siguiente consulta de estado. El enlace sigue activo. Cualquier otro `404` causa una detención por configuración (9.4). + +Desde la versión siguiente a 0.2.0, el backend también aplica estas decisiones: + +- Un registro excluido, es decir, uno que según Fisqua no es una página del volumen, pasa a `excluded`, y el backend registra el revisor de la misma forma: el backend no registra ningún rechazo y no cambia ninguna imagen. El backend omite una exclusión que traiga un motivo o rotaciones. +- Una decisión `missing_page`, con `side` igual a `left` o `right`, marca que a un registro capturado con dos cámaras le falta esa página; si el registro tiene una imagen actual de ese lado, esa imagen deja de ser la actual. Un registro en revisión o aprobado vuelve a `captured`, y el backend vuelve a abrir un registro cerrado. El backend omite un registro capturado con una sola cámara (`missing_page_single_record`). +- Un conjunto también puede traer solicitudes de tipo `missing_opening`: por cada una, el backend añade pares de páginas vacíos después del registro que indica la solicitud (uno, o el número que indica `count`, de 1 a 50). El backend omite una solicitud que ya aplicó. +- El backend vuelve a enviar el volumen a revisión cuando se cumplen estas condiciones: al aplicar el conjunto, marcó una página faltante o añadió un par de páginas vacío; el volumen ya se había enviado a revisión; y ningún registro está pendiente de recaptura ni en estado `captured`, salvo los que todavía tienen una página faltante sin resolver. +- Las correcciones de rotación solo se aplican a registros aprobados o rechazados, y `invalid_decision` cubre cualquier decisión distinta de `approved`, `rejected`, `excluded` o `missing_page`. ### 9.6 Las líneas del registro {#the-journal-lines} @@ -928,7 +956,13 @@ INFO app.core.fisqua_decisions: Fisqua decisions applied to volume : ap INFO app.core.fisqua_outbox: Fisqua has no decisions to give for volume yet; read again at the next poll ``` -Durante una detención por versión (9.4), el backend escribe una línea cuando envía cada prueba de compatibilidad y otra para su resultado; `` es `DTK_FISQUA_RETRY_MAX`: +Desde la versión siguiente a 0.2.0, la línea de las decisiones incluye más recuentos: + +```text +INFO app.core.fisqua_decisions: Fisqua decisions applied to volume : approved= rejected= excluded= unchanged= skipped= rotations= rotations_skipped= missing_pages= placeholders= requests_skipped= reopened= +``` + +Durante una detención por versión (9.4), el backend escribe una línea cuando envía cada prueba de compatibilidad y otra para su resultado; `` es `CAPTUA_FISQUA_RETRY_MAX`: ```text INFO app.core.fisqua_outbox: Fisqua version stop retest: sending manifest of volume @@ -954,14 +988,14 @@ Los fallos tienen sus propias líneas: `Sending manifest of volume to ### 9.7 Cuando no llega nada a Fisqua {#when-nothing-arrives-in-fisqua} -1. `GET /system/catalogue-backup` (6.3): `fisqua.configured` debe tener el valor `true`. Si `token_invalid` tiene el valor `true`, el token no contiene 64 caracteres hexadecimales en minúsculas. Si `configured` tiene el valor `false` y `token_invalid` tiene el valor `false`, comprueba que `DTK_FISQUA_TOKEN` tenga un valor (el comando de 4.3 lo muestra como `(not shown)`), y comprueba `DTK_FISQUA_ENV` y `DTK_OFFSITE_TENANT`. Durante una actualización, introduce cualquier cambio antes del paso 6 y el reinicio de 6.1 lo aplica; fuera de una actualización, reinicia dtk con `sudo systemctl restart dtk`. Si `config_error` tiene un valor, consulta las detenciones por configuración de 9.4. Para el motivo `version`, el backend hace una prueba de compatibilidad cada seis horas sin que tengas que intervenir en el equipo, siempre que exista algún volumen enviado a revisión y con recepción completa de la copia remota y ninguno de sus registros esté en estado `captured`; de lo contrario, conserva la detención hasta que exista un volumen así, o hasta que una actualización o un cambio de configuración la elimine. El backend no hace ninguna prueba mientras exista la suspensión. `config_error.at` es la hora en que el backend registró la detención por última vez; una prueba que Fisqua rechaza por versión renueva esa hora. `config_error.retest_at` es la hora de la última prueba cuyo envío falló (`null` en cualquier otro caso). Ambas horas corresponden a UTC y aparecen sin desplazamiento horario. La siguiente prueba corresponde a seis horas después de la más reciente de las dos. Si `held` tiene el valor `true` y ya terminaste el paso 5, retira la suspensión (6.2); durante una actualización, déjala. -2. La línea del volumen en 9.4. `Waiting for the complete offsite copy…` (el inicio del texto) indica que la carga aún no ha verificado todos los objetos: lee la línea de copia remota del volumen y las líneas `Image upload run`. +1. `GET /system/catalogue-backup` (6.3): `fisqua.configured` debe tener el valor `true` y, desde la versión siguiente a 0.2.0, también `fisqua.mode_allows` (6.2a). Si `token_invalid` tiene el valor `true`, el token no contiene 64 caracteres hexadecimales en minúsculas. Si `configured` tiene el valor `false` y `token_invalid` tiene el valor `false`, comprueba que `offsite.env` contenga `DTK_FISQUA_TOKEN` (el comando de 4.3 lo muestra como `(not shown)`), y comprueba allí `DTK_FISQUA_ENV` y `DTK_OFFSITE_TENANT`. Durante una actualización, introduce cualquier cambio antes del paso 6 y el reinicio de 6.1 lo aplica; fuera de una actualización, reinicia dtk con `sudo systemctl restart dtk`. Si `config_error` tiene un valor, consulta las detenciones por configuración de 9.4. Para el motivo `version`, el backend hace una prueba de compatibilidad cada seis horas sin que tengas que intervenir en el equipo, siempre que exista algún volumen enviado a revisión y con recepción completa de la copia externa y ninguno de sus registros esté en estado `captured`; de lo contrario, conserva la detención hasta que exista un volumen así, o hasta que una actualización o un cambio de configuración la elimine. El backend no hace ninguna prueba mientras exista la suspensión. `config_error.at` es la hora en que el backend registró la detención por última vez; una prueba que Fisqua rechaza por versión renueva esa hora. `config_error.retest_at` es la hora de la última prueba cuyo envío falló (`null` en cualquier otro caso). Ambas horas corresponden a UTC y aparecen sin desplazamiento horario. La siguiente prueba corresponde a seis horas después de la más reciente de las dos. Si `held` tiene el valor `true` y ya terminaste el paso 5, retira la suspensión (6.2); durante una actualización, déjala. +2. La línea del volumen en 9.4. `Captua lo enviará a Fisqua cuando la copia externa esté completa` indica que la carga aún no ha verificado todos los objetos: lee la línea de copia externa del volumen y las líneas `Image upload run`. 3. El registro: `journalctl -u dtk --since "1 hour ago" | grep -E "Fisqua|Image upload run"`. -4. El backend vuelve a consultar cada diez minutos un volumen entregado para el que Fisqua responde `Fisqua does not know this volume yet`, y no reenvía nada por su cuenta. Para enviarlo de nuevo, retira el volumen de revisión y vuelve a enviarlo a revisión: el backend pone en cola un manifiesto nuevo con un identificador nuevo y lo envía cuando el volumen tiene recepción completa. El backend solo pone en cola un manifiesto nuevo mientras algunos registros del volumen estén en revisión; al retirar el volumen de revisión, devuelve únicamente esos registros al estado `captured`, y no pone nada en cola para un envío a revisión que no tenga ningún registro en estado `captured`. +4. El backend vuelve a consultar cada diez minutos un volumen entregado para el que la línea muestra `Fisqua todavía no tiene registro de este volumen`, y no reenvía nada por su cuenta. Para enviarlo de nuevo, retira el volumen de revisión y vuelve a enviarlo a revisión: el backend pone en cola un manifiesto nuevo con un identificador nuevo y lo envía cuando el volumen tiene recepción completa. El backend solo pone en cola un manifiesto nuevo mientras algunos registros del volumen estén en revisión; al retirar el volumen de revisión, devuelve únicamente esos registros al estado `captured`, y no pone nada en cola para un envío a revisión que no tenga ningún registro en estado `captured`. ## 10. Comprobaciones después de una actualización {#checks-after-an-update} -Ejecuta estas comprobaciones en el equipo de pruebas después de cada actualización y en un equipo en uso después de actualizarlo: +Ejecuta estas comprobaciones en un equipo de pruebas después de cada actualización y en un equipo en uso después de actualizarlo: ```bash curl -s http://localhost:8000/health @@ -986,17 +1020,17 @@ sudo cat /etc/dtk/hostname-switch - La salida incluye `ConditionPathExists=!/etc/dtk/unresolved-deployment` de la configuración complementaria. - `check-stack-health.sh` informa de que la base de datos funciona correctamente y el puerto 5432 escucha en el equipo, en cualquier dirección, y de que el frontend y nginx están en ejecución. - El registro no contiene `Cannot start` ni `Traceback`; interpreta cualquier línea `Volume layout:` como indica 3.4. `offsite uploads are on hold` aparece en cada ejecución mientras exista la suspensión. -- `GET /system/catalogue-backup` (6.3) indica para `held` el valor esperado según el punto del procedimiento y, en un equipo con el enlace, `fisqua.configured` tiene el valor `true` y no hay `config_error`. -- En un equipo con el enlace, el registro no contiene ninguna línea `Fisqua answered HTTP` desde el reinicio. La línea `Fisqua accepted manifest` (9.6) solo aparece después de que un volumen enviado a revisión tenga recepción completa de su copia remota; una línea `Fisqua outbox pass` también puede informar de un volumen rechazado por no ser exportable. Ninguna de las dos aparece mientras exista la suspensión. -- En un volumen enviado a revisión después de la actualización, la línea de Fisqua debajo de la línea de copia remota muestra `Sent to Fisqua; waiting for its status` o un estado de Fisqua (9.4). +- `GET /system/catalogue-backup` (6.3) indica para `held` el valor esperado según el punto del procedimiento y, en un equipo con el enlace, `fisqua.configured` tiene el valor `true` y no hay `config_error`. Desde la versión siguiente a 0.2.0, una vez fijado el modo (6.2a), `mode_allows`, `images.mode_allows` y, en un equipo con el enlace, `fisqua.mode_allows` tienen el valor `true`. +- En un equipo con el enlace, el registro no contiene ninguna línea `Fisqua answered HTTP` desde el reinicio. La línea `Fisqua accepted manifest` (9.6) solo aparece después de que un volumen enviado a revisión tenga recepción completa de su copia externa; una línea `Fisqua outbox pass` también puede informar de un volumen rechazado por no ser exportable. Ninguna de las dos aparece mientras exista la suspensión. +- En un volumen enviado a revisión después de la actualización, la línea de Fisqua debajo de la línea de copia externa muestra `Enviado a Fisqua; a la espera de que Fisqua informe el estado` o un estado de Fisqua (9.4). - En un equipo cuyo nombre cambió desde `digitool`: `hostname` imprime `captua`; `getent` imprime una dirección para ambos nombres; `HOST_IP=captua.local` y `CORS_ORIGINS` incluye `http://captua.local` y `http://digitool.local`; `dtk-mdns-alias` tiene los estados `enabled` y `active`; `/etc/dtk/hostname-switch` contiene `state=done`. Desde otra computadora de la misma red, `http://captua.local`, `http://digitool.local` y la dirección IP del equipo permiten abrir la aplicación e iniciar sesión. En un equipo que conservó su nombre, el registro de la actualización indica el motivo (2.6). --- ## Un equipo nuevo {#a-new-unit} -1. Prepara la tarjeta con `sudo ./scripts/setup.sh`, que asigna el nombre `captua` (`sudo DTK_HOSTNAME=captua-2 ./scripts/setup.sh` para un segundo equipo en un mismo lugar), y después con `sudo ./scripts/install-service.sh`, que también instala la configuración complementaria para las actualizaciones sin resolver (consulta [Preparación y distribución de tarjetas SD](/guia/instalacion/tarjetas-sd/)). +1. Prepara la tarjeta con `sudo ./scripts/setup.sh`, que asigna el nombre `captua` (`sudo CAPTUA_HOSTNAME=captua-2 ./scripts/setup.sh` para un segundo equipo en un mismo lugar), y después con `sudo ./scripts/install-service.sh`, que también instala la configuración complementaria para las actualizaciones sin resolver (consulta [Preparación y distribución de tarjetas SD](/guia/instalacion/tarjetas-sd/)). 2. Escribe el archivo de claves y ejecuta `provision-rclone.sh` con `--tenant` y `--dump-recipient` como indica el paso 4. Para un equipo con el enlace a Fisqua, añade `--fisqua-env` y una línea `FISQUA_TOKEN` en el archivo de claves (9.2). -3. Inicia o reinicia `dtk` y comprueba el resultado como indica 6.3. +3. Inicia o reinicia `dtk` y comprueba el resultado como indica 6.3. Desde la versión siguiente a 0.2.0, si encendiste el equipo antes del paso 2, fija primero su modo (6.2a). -Debes asignar el prefijo de nombre de archivo a un volumen nuevo al crearlo, así que el paso 3 no corresponde. Como el bucket no contiene nada anterior al equipo, el paso 5 tampoco corresponde. +Debes asignar la raíz a un volumen nuevo al crearlo, así que el paso 3 no corresponde. Como el bucket no contiene nada anterior al equipo, el paso 5 tampoco corresponde. diff --git a/content/es/docs/operators/card.md b/content/es/docs/operators/card.md index bb15e8f..895121d 100644 --- a/content/es/docs/operators/card.md +++ b/content/es/docs/operators/card.md @@ -12,7 +12,7 @@ Guía de una página para quienes operan el equipo de digitalización. Imprímel ## Apagar y reiniciar el equipo {#shutting-down-and-restarting-the-scanner} 1. Si hay una captura en curso, espera a que termine. -2. Abre el menú de usuario. En **Resumen** y **Proyectos**, presiona tu nombre de usuario, abajo en la barra lateral; si la barra está contraída, presiona el cuadro con las dos primeras letras de tu nombre. En la pantalla de captura y en la del volumen, presiona el círculo con esas letras, arriba a la derecha. +2. Abre el menú de usuario. En cualquier pantalla con barra lateral, como **Resumen** o **Proyectos**, presiona tu nombre de usuario, abajo en la barra lateral; si la barra está contraída, presiona el cuadro con las dos primeras letras de tu nombre. En la pantalla de captura y en la del volumen, presiona el círculo con esas letras, arriba a la derecha. 3. Presiona "Apagar el equipo" y, en la confirmación, "Sí, apagar". 4. Aparece "Apagando el equipo…". Desconecta la corriente solo cuando la pantalla quede negra. @@ -44,15 +44,15 @@ Si dejas el interruptor en AF, cada captura tarda unos 12 segundos más y puede ## Enviar un volumen terminado a revisión {#sending-a-finished-volume-for-review} -1. Abre el volumen: **Proyectos →** tu proyecto **→** el volumen. -2. Presiona "Enviar a revisión", en la barra superior. Si ya habías enviado parte del volumen, el botón indica cuántos registros nuevos vas a enviar (por ejemplo, "Enviar 3 registros nuevos"). +1. Abre el volumen: **Proyectos →** tu proyecto **→** el volumen. Si el equipo no usa proyectos, abre **Volúmenes →** el volumen. +2. Presiona "Enviar a revisión", en la barra superior. Si ya habías enviado parte del volumen, el botón indica cuántos registros nuevos vas a enviar (por ejemplo, "Enviar 3 registros nuevos"). Si el botón indica cuántas recapturas faltan (por ejemplo, "Faltan 2 recapturas"), todavía no puedes enviar el volumen: termina primero las recapturas. 3. En la confirmación, presiona "Enviar". Desde ese momento los registros quedan en revisión y no puedes moverlos a otro volumen. Si te equivocaste, presiona "Retirar de revisión" y, en la confirmación, "Retirar". Así retiras solo los registros que todavía están pendientes de revisión: los aprobados y los rechazados quedan como están. ## Si las cámaras no aparecen {#if-the-cameras-dont-appear} -1. Si una cámara está apagada, presiona el disparador hasta la mitad para activarla, o vuelve a conectar el cable USB. +1. Si una cámara se apagó sola, presiona el disparador hasta la mitad para activarla, o vuelve a conectar el cable USB. 2. Presiona "Reconectar cámaras". Está en **Resumen**, en la sección "Probar cámaras", y en la pantalla de captura, en el panel "Controles de cámara" (ábrelo con el ícono del engranaje). 3. Si siguen sin aparecer, presiona "Salir" en el menú de usuario (ver arriba) y vuelve a iniciar sesión. @@ -64,6 +64,6 @@ Desde ese momento los registros quedan en revisión y no puedes moverlos a otro ## Si la aplicación deja de responder {#if-the-application-freezes} -Presiona **Ctrl+Alt+F2**, escribe `sudo systemctl restart dtk` y presiona Enter. **Después de presionar Enter no aparece ningún mensaje: es normal.** Espera unos 30 segundos y vuelve a la aplicación con **Ctrl+Alt+F1**. +Presiona **Ctrl+Alt+F2**, escribe `sudo systemctl restart dtk` y presiona Enter. **Durante el reinicio no aparece ningún mensaje: es normal.** Espera hasta que puedas volver a escribir en la terminal (puede tardar un minuto o más) y vuelve a la aplicación con **Ctrl+Alt+F1**. -Si la aplicación sigue sin responder, apaga el equipo con el botón de encendido (ver arriba) y vuelve a encenderlo. +Si aparece un mensaje que dice que `dtk.service` falló, o si la aplicación sigue sin responder, apaga el equipo con el botón de encendido (ver arriba) y vuelve a encenderlo. diff --git a/content/es/docs/operators/external-storage.md b/content/es/docs/operators/external-storage.md index 359e243..38d5778 100644 --- a/content/es/docs/operators/external-storage.md +++ b/content/es/docs/operators/external-storage.md @@ -6,7 +6,7 @@ docs_section: "operators" source: "docs/users/external-storage.qmd" --- -Digitization Toolkit puede guardar las imágenes capturadas en una unidad USB externa o en una tarjeta SD, en lugar de usar el almacenamiento interno del equipo. Esta opción resulta útil al digitalizar fondos grandes que superan la capacidad de la tarjeta microSD interna. +Captua puede guardar las imágenes capturadas en una unidad USB externa o en una tarjeta SD, en lugar de usar el almacenamiento interno del equipo. Esta opción resulta útil al digitalizar fondos grandes que superan la capacidad de la tarjeta microSD interna. {{< callout type="warning" title="Función experimental" >}} Esta función depende de las operaciones que realiza el sistema operativo sobre los discos. La compatibilidad varía según el formato de la unidad y el hardware. Consulta **[Formatos compatibles](#supported-formats)** más abajo. No uses una unidad externa como **única** copia del material digitalizado: conserva siempre una copia de respaldo. @@ -16,7 +16,11 @@ Esta función depende de las operaciones que realiza el sistema operativo sobre ## Cómo funciona {#how-it-works} -Cuando activas una unidad externa, Captua guarda los proyectos nuevos en una carpeta `dtk-projects/` de esa unidad. Los proyectos que ya guardaste en la tarjeta interna no cambian y siguen disponibles. Solo puedes tener una ubicación externa activa a la vez. +Mientras una unidad externa esté activa, Captua guarda todas las capturas nuevas en una carpeta `dtk-projects/` de esa unidad. Eso incluye las capturas nuevas de los volúmenes que empezaste en la tarjeta interna, así que las imágenes de esos volúmenes quedan repartidas en dos discos. Las imágenes que ya capturaste se quedan donde están y puedes seguir consultándolas. Para que cada volumen quede en un solo disco, activa la unidad o vuelve al almacenamiento interno entre un volumen y otro, nunca con un volumen a medias. Solo puedes tener una ubicación externa activa a la vez. + +En **Configuración**, la sección **Unidad de almacenamiento** muestra esta nota: "Solo los proyectos nuevos se guardarán en la unidad seleccionada". La nota está desactualizada y la vamos a corregir (NEH-325); esta página describe lo que Captua hace en realidad. + +Si alguien desconecta la unidad activa, o si no está montada, Captua no pasa a guardar en la tarjeta interna: no guarda ninguna captura nueva hasta que un administrador vuelva a conectar y activar la unidad, o hasta que restaure el almacenamiento interno. --- @@ -63,7 +67,7 @@ Verifica dos veces la ruta del dispositivo con `lsblk` antes de ejecutar `mkfs`. ### Resumen de compatibilidad de formatos {#format-compatibility-summary} -| Formato | Funciona con DTK | Notas | +| Formato | Funciona con Captua | Notas | |---|---|---| | **exFAT** | ✅ Recomendado | La mejor opción para usar en varios sistemas operativos | | **ext4** | ✅ Compatible | Solo Linux; algo más rápido | @@ -76,7 +80,11 @@ Verifica dos veces la ruta del dispositivo con `lsblk` antes de ejecutar `mkfs`. ## Usar almacenamiento externo desde la interfaz {#using-external-storage-in-the-ui} -Ve a **Configuración** (el ícono del engranaje en la barra lateral) y despliega la sección **Unidad de almacenamiento**. +{{< callout type="note" >}} +Solo un administrador puede seguir estos pasos. Quienes tienen el rol **Operario** o **Revisor** no ven **Configuración** en la barra lateral. +{{< /callout >}} + +Ve a **Configuración** (el ícono del engranaje en la barra lateral). En la sección **Almacenamiento**, presiona **Unidad de almacenamiento** (marcada como experimental) para desplegarla. ### Paso 1: conectar la unidad {#step-1-connect-the-drive} @@ -84,11 +92,11 @@ Conecta la unidad USB o la tarjeta SD a la Raspberry Pi. No necesitas montar la ### Paso 2: montar la unidad {#step-2-mount-the-drive} -La lista de dispositivos muestra todas las particiones detectadas. Las particiones sin montar tienen un botón **Montar**. +La lista de dispositivos muestra las particiones que Captua puede usar. Las particiones sin montar tienen un botón **Montar**. 1. Busca en la lista la partición que quieras usar. 2. Presiona **Montar**. -3. Captua monta la unidad y el botón cambia a **Activar**. +3. Captua monta la unidad y, desde ese momento, la fila muestra los botones **Activar** y **Desmontar**. ### Paso 3: activar la unidad {#step-3-activate-the-drive} @@ -96,9 +104,9 @@ Presiona **Activar** junto a la partición montada. Captua: 1. Crea un directorio `dtk-projects/` en la unidad, si aún no existe. 2. Usa ese directorio como ubicación activa de los proyectos. -3. Muestra una etiqueta verde con la palabra **activo** en la fila del dispositivo y un aviso que confirma la ruta activa. +3. Muestra en la fila del dispositivo una etiqueta verde con la palabra **activo** y el texto **✓ En uso** donde estaba el botón **Activar**, además de un aviso que confirma la ruta activa. -Captua guarda en la unidad externa los proyectos que crees a partir de este momento. +A partir de este momento, Captua guarda en la unidad externa todas las capturas nuevas. ### Desactivar la unidad y volver al almacenamiento interno {#deactivating-reverting-to-internal-storage} @@ -108,11 +116,13 @@ Presiona **Restaurar predeterminado** en el aviso que indica la ubicación activ Antes de desconectar la unidad: -1. Si es la ubicación de almacenamiento activa, presiona primero **Restaurar predeterminado**. +1. Si es la ubicación de almacenamiento activa, puedes presionar primero **Restaurar predeterminado**. Si en lugar de eso presionas **Desmontar** en la unidad activa, Captua vuelve igualmente al almacenamiento interno. 2. Presiona **Desmontar** junto a la partición. 3. Espera el mensaje de confirmación. 4. Desconecta la unidad. +Captua solo puede desmontar las unidades que montó con **Montar**. + {{< callout type="important" >}} Presiona siempre **Desmontar** antes de desconectar la unidad. Si retiras una unidad montada, puedes dañar el sistema de archivos y perder datos. {{< /callout >}} @@ -122,10 +132,10 @@ Presiona siempre **Desmontar** antes de desconectar la unidad. Si retiras una un ## Solución de problemas {#troubleshooting} **La unidad no aparece en la lista** -: Captua solo muestra las particiones de dispositivos extraíbles que no forman parte del sistema operativo. Prueba a presionar **Actualizar lista**. Si la unidad sigue sin aparecer, comprueba la conexión y verifica que el sistema operativo la reconozca (ejecuta `lsblk` en una terminal). +: Captua muestra las particiones que puede usar. Deja por fuera las particiones del sistema operativo y las que tienen un sistema de archivos que Captua no puede usar, como APFS y HFS+. Una unidad formateada sin tabla de particiones tampoco aparece: crea una partición en ella con Utilidad de Discos u otra herramienta de particiones y formatea esa partición (por ejemplo, `/dev/sdX1`) como exFAT. Si la unidad usa APFS o HFS+, formátala también como exFAT. Después presiona **Actualizar lista**. Si la unidad sigue sin aparecer, comprueba la conexión y verifica que el sistema operativo la reconozca (ejecuta `lsblk` en una terminal). **"Montar" devuelve un error** -: Puede que la unidad use un formato incompatible (APFS, HFS+) o que necesite módulos adicionales del kernel (NTFS). Formatea la unidad como exFAT y vuelve a intentarlo. +: Puede que el sistema de archivos tenga errores o que la unidad necesite módulos adicionales del kernel (NTFS). Formatea la unidad como exFAT y vuelve a intentarlo. **"Activar" falla por un error de permisos** : Esto puede ocurrir en unidades ext4 recién formateadas, cuando `root` es el propietario del directorio raíz del sistema de archivos. Captua intenta completar la operación con permisos elevados. Si vuelve a fallar, formatea la unidad como exFAT. diff --git a/data/site_copy.json b/data/site_copy.json index 174fcb9..465a7cb 100644 --- a/data/site_copy.json +++ b/data/site_copy.json @@ -24,7 +24,7 @@ "current_release": "Current release: 0.2.0", "shortcut_title": "Operating a unit?", "documentation": "Documentation", - "beta": "Beta release", + "beta": "In active development", "open_source": "Open source", "reference": "Reference", "header_tagline": "Digitization Toolkit", @@ -60,7 +60,7 @@ "current_release": "Versión actual: 0.2.0", "shortcut_title": "¿Vas a usar Captua?", "documentation": "Documentación", - "beta": "Versión beta", + "beta": "En desarrollo activo", "open_source": "Código abierto", "reference": "Referencia", "header_tagline": "Herramientas de digitalización", From 292a1e729a7bb41be4e987660bebb0540891d8fd Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Sun, 8 Nov 2026 17:38:47 -0800 Subject: [PATCH 4/5] docs(developers): start PostgreSQL before the manual migrations, and run Compose from the repository root --- content/en/docs/developers/developer-setup.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/content/en/docs/developers/developer-setup.md b/content/en/docs/developers/developer-setup.md index b289f12..d13b599 100644 --- a/content/en/docs/developers/developer-setup.md +++ b/content/en/docs/developers/developer-setup.md @@ -108,15 +108,18 @@ On a unit provisioned with `scripts/setup.sh`, the systemd service `dtk.service` `scripts/setup.sh` prepares a unit: it creates `.env` if it is missing, installs pixi v0.73.0 if no pixi is installed (the committed `pixi.lock` needs a pixi that reads lock-file format v7), installs the backend environment, links the system camera libraries, builds python-gphoto2 against the system libgphoto2, and applies the database migrations. On an unprovisioned Pi, run `scripts/setup.sh`, or do the backend steps by hand: ```bash +# from the repository root: start PostgreSQL and wait until it is healthy +docker compose -f docker-compose.yml -f docker-compose.pi.yml up -d --pull never --wait db cd backend pixi install --locked # first time only pixi run setup-camera-link # puts the system picamera2 and libcamera packages on the environment's path pixi run db-upgrade # applies the migrations; the backend refuses to start against an un-migrated database +cd .. ``` `setup-camera-link` needs the Raspberry Pi OS packages `python3-picamera2` and `python3-libcamera`, which `scripts/setup.sh` installs. pixi supports only `linux-aarch64` and `linux-64` (`platforms` in `backend/pixi.toml`), so the native backend cannot run on macOS or Windows. Use the Docker backend there. -Start the database, the production frontend and Nginx, as `scripts/start.sh` does: +From the repository root, start the database, the production frontend and Nginx, as `scripts/start.sh` does: ```bash docker compose -f docker-compose.yml -f docker-compose.pi.yml up -d --pull never --wait --remove-orphans From 25c913cf67c6782920c3ea9f0e9ed69fd60ca44d Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Sun, 8 Nov 2026 17:43:14 -0800 Subject: [PATCH 5/5] docs(developers): let the first database start pull its image, and comment out the localhost DATABASE_URL example --- content/en/docs/developers/api-reference.md | 2 +- content/en/docs/developers/developer-setup.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/content/en/docs/developers/api-reference.md b/content/en/docs/developers/api-reference.md index 51b52b5..a01d00c 100644 --- a/content/en/docs/developers/api-reference.md +++ b/content/en/docs/developers/api-reference.md @@ -1095,7 +1095,7 @@ DATABASE_NAME=digitization_toolkit # building the URL from the DATABASE_* values above (alembic/env.py). # The application itself never reads it. Note the +psycopg driver — a bare # postgresql:// URL selects psycopg2, which is not installed. -DATABASE_URL=postgresql+psycopg://user:password@localhost:5432/digitization_toolkit +# DATABASE_URL=postgresql+psycopg://user:password@localhost:5432/digitization_toolkit # Security # Anything other than dev, development, test, testing or local requires a real diff --git a/content/en/docs/developers/developer-setup.md b/content/en/docs/developers/developer-setup.md index d13b599..53f7995 100644 --- a/content/en/docs/developers/developer-setup.md +++ b/content/en/docs/developers/developer-setup.md @@ -109,7 +109,8 @@ On a unit provisioned with `scripts/setup.sh`, the systemd service `dtk.service` ```bash # from the repository root: start PostgreSQL and wait until it is healthy -docker compose -f docker-compose.yml -f docker-compose.pi.yml up -d --pull never --wait db +# (the first run downloads the pinned PostgreSQL image, so it needs internet) +docker compose -f docker-compose.yml -f docker-compose.pi.yml up -d --wait db cd backend pixi install --locked # first time only pixi run setup-camera-link # puts the system picamera2 and libcamera packages on the environment's path