envlib-api
The envlib data API service, in two processes:
- the refresher keeps a MongoDB copy of the public envlib catalogue and of every catalogued
dataset's index, using
ebooklet.mongo.refresh();
- the API (
envlib-api-server) is a read-only OGC API – EDR server that answers every request
from that MongoDB, and fetches a chunk from B2 only on a cache miss.
Its design record is plans/edr_api_assessment.md §11 in the envlib repo, and the work is tracked
under "EDR API (new service)" in envlib's OPEN_WORK.md. The API runs locally so far. Deploying it on
the swarm is "EDR plan 6: going public".
What runs
| Service |
What it does |
mongo |
MongoDB 9.0, on one node with a named volume, with auth and no published port. It holds only data derived from B2, so it has no backups. |
refresher |
Every 60 s it refreshes the catalogue, syncs the set of mirrored datasets with it, then refreshes every dataset. It is pinned to MongoDB's node. |
api (local only so far) |
The EDR API: station (ts_ortho) and grid collections, and the envlib catalogue at /catalogue, with its docs site at /docs/. See "The API" below. |
Each cycle, in order:
- Refresh the catalogue. It is an ebooklet RemoteConnGroup, mirrored like any dataset under the
id
catalogue.
- Sync (
envlib_api/mirror.py):
- Membership is the catalogue index's keys.
- A new or changed entry is refreshed first and listed afterwards, in the
catalogue collection.
- A removed entry is retired: its
datasets document is tombstoned, never deleted, and its
entries are deleted. A retire happens only when every guard passes, so a broken, empty or
recreated catalogue, or one dropping more than 2 datasets at once, retires nothing and alerts.
Every retire alerts, whether or not a guard was involved.
- A changed
db_url (a re-point) is followed only when the new remote answers and the
catalogue's uuid is acknowledged. Until then the old remote keeps being served and polled.
- Refresh every listed dataset, oldest check first. Each one is isolated: a failure is logged
and reported to Sentry once until it clears. The same goes for every other alert, except retires
and catalogue adoptions, which alert every time.
- Send a Sentry cron check-in. It is "ok" when the catalogue refresh and the sync succeeded and
at least one dataset refreshed to
applied or nochange, and "error" otherwise. A missed check-in
alerts too.
MongoDB collections:
- from
ebooklet.mongo: datasets, entries and chunks (ebooklet's docs/ops.md, "The MongoDB
read path");
- from this repo:
catalogue (one document per dataset version) and state (the acknowledged
catalogue uuid).
The API
envlib-api-server runs uvicorn with one worker; scale it with replicas. Each request builds its own
MongoStore and cfdb dataset. The process shares only the MongoDB client and the B2 HTTP session, so
nothing is cached in the process. Its code is in envlib_api/api/, and the refresher's CLI never
imports it.
The user documentation is the docs site (docs/, mkdocs.yml; plan EDR plan 7). The API serves
it at /docs/, built into the image, so the docs always describe the API they are deployed with. It
holds the routes, the query rules, stations, grids, the catalogue, the formats, CORS, the limits and
every answer. Every example on it runs as a test in the default uv run pytest, against a local API
over a docs world that carries the live dataset ids (envlib_api/tests/docs_support.py). This README
keeps what an operator or a developer needs. Build the site with uv run mkdocs build; a server finds
it at [api] docs_dir, and without one it serves no /docs, links to no docs and claims no oas31.
The route specs (envlib_api/api/routes.py). Each route has one spec: its query parameters, the
required ones, its f and crs values, and its statuses. The handlers validate every request through
it, and /api (envlib_api/api/openapi.py) and the docs' Reference page are built from it, so the
three cannot disagree. A test probes every route with every parameter name, and another makes each
documented status happen; a recorder at the outermost layer fails the suite on any answer /api does
not document (envlib_api/tests/recorder.py).
CORS is one ASGI middleware (Cors in envlib_api/api/app.py), which adds the headers to every
answer as it starts: errors, /api, /docs and Starlette's trailing-slash redirects included (Mike,
2026-11-25). The unexpected 500 is sent outside every middleware, so its handler sets them itself (code
review edr-api-code-5). Exposing ETag and allowing If-None-Match wait for plan 6's conditional
requests, and HEAD is plan 6's too.
The caps ([api] in the API's TOML; envlib_api/config.py has the defaults):
max_values: the values returned (stations or cells × levels × time steps × parameters);
max_decoded_bytes: the data chunks a request touches × their decoded size;
max_csv_rows: CSV rows.
They are counted from each dimension's chunk spans after the coordinates are read, before any key is
built or data chunk read. A request over one answers 413, naming the limit, the dataset's db_url
and an envlib snippet for reading it directly. The key list is then built from the same spans and
feeds the one batched fetch (store.load_items), so the estimate is exactly what is fetched. On the
live WRF grids the bytes cap (100 MB) is about 51 chunks: one cell over about 4.9 years, or a cube of
about 300 km square at one hour. A full WRF map at one hour touches 322 chunks (623 MB) and answers
413, deliberately: bulk reads belong to envlib (Mike, 2026-11-25).
Grids
The rules for /position and /cube are the docs' Grids page (docs/grids.md). Their code is
envlib_api/api/grid.py (plan 4, its review edr-api-plan-4 and code review edr-api-code-4).
- Decided by Mike, 2026-11-25: no reprojection; geographic grids served only on WGS 84; the edge
tolerance of 0.1% of the edge spacing; the cube unmasked; a cube in CoverageJSON only; the cached
transformers (below).
- On each axis the cell is the nearest stored centre, found by
searchsorted on the midpoints.
- The cost before the caps: the cube's rectangle is found by projecting every cell centre to CRS84,
before the caps are checked. That is 15 ms on WRF's 168,210 cells, but about 2 s and 784 MB on a
16-million-cell grid. Bounding it first is the backlog item "[new service] Bound the cube hull's
projection on large grids", triggered by the first projected grid over about 1 million cells.
- Grid
/area and netCDF output are the item "EDR grid /area and netCDF output" in envlib's
OPEN_WORK.md.
- The pyproj transformers are cached per CRS (an
lru_cache keyed by the WKT; Mike, 2026-11-25):
building them cost about 25 ms per request. pyproj builds its PROJ object per thread, so sharing
one is safe, but a from_crs transformer repeats PROJ's operation search in every new thread. So
the cache holds a from_pipeline transformer of the operation PROJ chose, which a new thread
rebuilds in 0.2 ms. That works when PROJ resolves one operation, as on the WRF CRS. For a CRS where
PROJ keeps several (EPSG:27200 or 27700, for example), the from_crs transformer is cached instead:
it is correct, but it pays about 30 ms in each new thread.
The catalogue
The rules for /catalogue and /catalogue/distinct/{field} are the docs' catalogue page
(docs/catalogue.md). They serve the envlib catalogue as the mirror holds it
(envlib_api/api/catalogue.py; plan 5 and its review edr-api-plan-5): each request reads every
mirrored catalogue document and calls envlib's own matching functions.
- A
bbox's numbers are parsed strictly here and passed to envlib as given, and envlib reads 0–360
boxes itself, so Catalogue.query(bbox=...) gives the same entries.
- The
limit default and clamp is catalogue_limit in [api].
Operator limits:
- the mirror never lists an entry it refuses (one with no http(s)
db_url or no dataset_id, or an
integer of 2⁶³ or more), and a changed entry whose member refresh keeps failing keeps its old
metadata until it succeeds;
- a new entry appears within one poll of its first successful mirror;
- every request reads the whole mirrored catalogue: 41 KB for today's 18 entries, and about 48 ms at
5,000 entries on loopback (plan review
edr-api-plan-5);
/catalogue/distinct/{field} answers 500 if a stored value of that field is a list or an object,
as envlib's distinct() raises on it. Only a hand-damaged entry holds one, since Metadata would
not publish it (code review edr-api-code-5).
Consistency (envlib_api/api/resolve.py). Every attr is read first, then the selection and the
cap, then the batched fetch and the reads, then store.verify(). verify() runs before every answer
computed from the store, a 413, 204 or 404 included.
| Raised |
Answer |
A refresh overlapped the request (a refused store build, or a failed verify()) |
A new store after retry_wait_ms, up to retry_attempts times; then 503 with Retry-After |
| The remote is ahead of the mirror (a chunk fetch found a newer commit, and nothing was applied since) |
503 with Retry-After at once: only the refresher's next poll helps |
RemoteMissingError |
No version of the dataset_id left: 404. Another version is now the latest: retry. Otherwise 503 |
RemoteIntegrityError, or chunk bytes that do not decode |
500, logged at ERROR |
| Another B2 failure |
502 |
| MongoDB unavailable (selection times out after 5 s) |
503 with Retry-After |
| The request deadline passed |
503 with Retry-After |
The deadline (request_deadline_seconds) is checked between attempts and after the batched fetch.
It cannot interrupt a fetch in progress, so a request can overrun it by one B2 read: read_timeout ×
(retries + 1), plus s3func's backoff.
A collection whose store cannot be built is left out of /collections and logged. It never fails
the listing. A catalogue entry whose created_at does not parse counts as the oldest version, with a
warning; the rule is envlib's (envlib.latest_per_dataset, since envlib 0.1.9), and the API has no
copy of its own. The warning is envlib's warnings.warn, routed to the log by
logging.captureWarnings, so it is logged once per process for each damaged entry, not on every
request. A latest version whose remote is missing hides an older working one, as envlib's
query() would.
The API's MongoDB user is api, with the role envlib_api_reader (mongo/api-role.json): find
on datasets, entries, catalogue and chunks, and insert on chunks. It never calls
ensure_schema. ebooklet only logs a WARNING when a chunk insert is refused, so a cache that refuses
inserts would serve correct data, always cold. Two checks make that loud (at ERROR, so Sentry reports
it):
- at start, the API reads its own privileges (
connectionStatus) and reports any that are missing;
- at run time, the first refused insert of the process (a missing privilege, a validator, anything
else) is re-reported at ERROR.
- On a new volume,
init-users.js creates the user when the secret
envlib_api_mongo_api_password is mounted.
- On the existing production volume, create it by hand as root in the
mongo container, with the
privileges from mongo/api-role.json (<password> is the API TOML's):db.getSiblingDB("envlib_api").createRole({role: "envlib_api_reader", roles: [], privileges: [
{resource: {db: "envlib_api", collection: "datasets"}, actions: ["find"]},
{resource: {db: "envlib_api", collection: "entries"}, actions: ["find"]},
{resource: {db: "envlib_api", collection: "catalogue"}, actions: ["find"]},
{resource: {db: "envlib_api", collection: "chunks"}, actions: ["find", "insert"]}]})
db.getSiblingDB("envlib_api").createUser({user: "api", pwd: "<password>", roles: [{role: "envlib_api_reader", db: "envlib_api"}]})
- The API's credential can write bytes under a chunk id that is not cached yet. That is inherent in a
cache the API fills itself, and plan 6 should weigh it.
Running it locally: docker compose up -d mongo, a refresher (docker compose up refresher, or
uv run envlib-api refresher), then docker compose up api, or
ENVLIB_API_TOML=<the API's TOML> uv run envlib-api-server.
- Ports: compose publishes the API on
127.0.0.1:8000. The venv server binds 0.0.0.0:8000
unless ENVLIB_API_HOST and ENVLIB_API_PORT say otherwise.
- Secrets: compose's
mongo service now mounts the API's password secret, so
mongo-api-password must exist in the local secrets directory, even for the refresher alone.
- The docs: the image serves them at
/docs/. The venv server needs uv run mkdocs build and
[api] docs_dir set to the built site/.
Rules that must not be broken
- Exactly one refresher, ever. Two overlapping refreshers can leave MongoDB permanently
inconsistent with B2 while every check says it is current (ebooklet
docs/ops.md). There is no
lock. The stack prevents Swarm from running two: replicas: 1, stop-first updates, an exit within
seconds of SIGTERM, and pinning to MongoDB's node. Never run a second refresher by hand. That
means no docker run … refresher, and no development machine pointed at the production MongoDB.
There is deliberately no one-shot refresh command.
- If two refreshers are ever seen, build the lease the plan review designed (
planning/): a
server-clock expiry via $$NOW with a bootstrap insert and a non-upsert update, a uuid4 owner, a
conditional release, and a 5-minute TTL renewed before each refresh. It is not built, because
nothing above can start a second one.
- *Never add Cloudflare cache rules on the `b2.
hosts.** The refresher and the API rely on db-object HEADs and GETs, and on 404s, never being cached. On 2026-11-23, every catalogued db object and 404s on both hosts answeredcf-cache-status: DYNAMIC. A refresh status ofstale_get` (HEAD and GET
disagree) means a cache has appeared, and it alerts.
- Cloudflare refuses Python's default
urllib User-Agent with a 403, though ebooklet's sessions pass.
A new bot rule could block the refresher, which would show as error check-ins and an unhealthy
task.
Deploy (Docker Swarm, on the manager)
Where it runs (since 2026-11-24): both services are on uswest11.tethys-ts.xyz, the manager, which
carries the envlib_mongo label. The checkout the stack is deployed from is
~/git/envlib-repos/envlib-api on that host. The live close-checks are
planning/close-checks-live-2026-11-24.md.
One time, on the manager: