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) collections with /locations, /area and /radius, and grid collections with /position and /cube, in CoverageJSON, CSV and GeoJSON; and the envlib catalogue at /catalogue. 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
cataloguecollection. - A removed entry is retired: its
datasetsdocument 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
appliedornochange, and "error" otherwise. A missed check-in alerts too.
MongoDB collections:
- from
ebooklet.mongo:datasets,entriesandchunks(ebooklet'sdocs/ops.md, "The MongoDB read path"); - from this repo:
catalogue(one document per dataset version) andstate(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.
Routes (EDR 1.2):
| Route | Answers |
|---|---|
/, /conformance, /api |
The landing page, the conformance classes, and FastAPI's generated OpenAPI 3.1 document. That document lists the routes but not their query parameters, so the conformance list does not claim oas31 (plan 6). |
/collections, /collections/{id} |
One collection per dataset_id, serving its latest version: the greatest user_meta.created_at, with a tie going to the greater dataset_version_id. The full catalogue entry rides in its envlib object. ts_ortho (station) and grid collections are listed; a grid's native CRS, axes and spacing ride in envlib:grid. |
/collections/{id}/position?coords=POINT(...) |
Grids: the series of the cell nearest the point (see "Grids" below): a CoverageJSON PointSeries (a CoverageCollection of them, one per level, when several depths are selected), or CSV. |
/collections/{id}/cube?bbox=w,s,e,n |
Grids: the smallest grid rectangle holding every cell whose centre is in the bbox, as one CoverageJSON Grid (CoverageJSON only). |
/collections/{id}/locations |
The stations as an EDR GeoJSON FeatureCollection. The id is the station_id. |
/collections/{id}/locations/{station_id} |
One station's series: a CoverageJSON PointSeries, or CSV. |
/collections/{id}/area?coords=POLYGON(...) |
The stations a WKT POLYGON or MULTIPOLYGON covers, boundary included: a CoverageCollection of PointSeries, or CSV. |
/collections/{id}/radius?coords=POINT(...)&within=…&within-units=km|m |
The stations within a great-circle distance (WGS84). |
/catalogue |
The envlib catalogue: Catalogue.query() over HTTP, every version on request (see "The catalogue" below). |
/catalogue/distinct/{field} |
The distinct stored values of one queryable field: Catalogue.distinct(). |
Query rules:
datetimeis an instant or an interval, with..for an open end. Times are UTC: a naive time is read as UTC, and an offset is converted. A time step is selected when its label t hasstart <= t <= end, so05:30/10:30starts at the 06:00 step. An instant must equal a step. A list of datetimes answers 400, a gap against EDR 1.2.- Other parameters:
parameter-name(a comma-separated list),f(CoverageJSON,CSV, orGeoJSONfor/locations),crs(CRS84 only, except a projected grid's cube: see "Grids") and, on grids,z. - Queries by type: station collections offer
/locations,/areaand/radius; grid collections offer/positionand/cube. Asking a collection for a query it does not offer answers 404, naming the queries it does offer. - Strictness: an unknown, repeated or missing parameter answers 400. A valid query that selects no station or no time step answers 204.
/areaand the antimeridian: each station is tested at lon, lon − 360 and lon + 360, so a polygon drawn across the antimeridian (the Chatham Islands) works in either longitude convention./radiusis great-circle, so it needs no such rule.- Values are printed at the variable's stored precision. NaN prints as
nullin JSON and as an empty cell in CSV. Times print asYYYY-MM-DDTHH:MM:SSZ.- What is printed equals a direct envlib read, rounded to that precision.
- It is not always the producer's decimal. A float32 variable cannot hold p decimals once
|value| × 10^p passes about 2²⁴: streamflow at precision 4 above about 1,677 m³/s. The
producer's float32 step already lost that digit, so there the last printed decimal is not
significant (code review
edr-api-code-3).
- Errors are JSON in the OGC exception shape (
code,description), including unknown routes (404), other methods (405) and anything unexpected (500). - Compression follows
Accept-Encoding(q-values honoured): zstd level 1, else gzip level 1, else none. - CORS. Every answer carries
Access-Control-Allow-Origin: *and exposesRetry-After, whatever the request, so a web page on any site can read the API from the browser (Mike, 2026-11-25). That includes errors, FastAPI's/apiand Starlette's trailing-slash redirects, because one ASGI middleware (Corsinenvlib_api/api/app.py) adds the headers to every answer as it starts. The unexpected 500 is sent outside every middleware, so its handler sets them itself (code reviewedr-api-code-5). The API is public, read-only and cookie-free, so this gives a page nothing it could not fetch from a server. Because*does not depend on the request, noVary: Originis sent, and a copy cached without anOriginstill serves a browser. AnOPTIONSpreflight answers 204 and allowsGETonly, with no extra request headers. ExposingETagand allowingIf-None-Matchwait for plan 6's conditional requests, andHEADis 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
Rules for /position and /cube (envlib_api/api/grid.py; plan 4, its review edr-api-plan-4
and code review edr-api-code-4):
- No reprojection. The API never reprojects or regrids values: every value is a stored cell's, and
coordinates are transformed only to find cells and to say where they are. Regridding is the
caller's choice of method and far heavier per request; it belongs to envlib with
geointerp, or cfdb's.interp()(Mike, 2026-11-25). - Axes. x and y are the coordinates cfdb records as the x and y axes. They need not be regular:
the live SST centres are float32 values whose spacing varies by about 3e-4. They are increasing,
because cfdb sorts a coordinate when it is created. A vertical axis is the coordinate whose CF attrs
say
axis: Z. - The CRS. A projected grid is served through pyproj. A geographic grid is served only on WGS 84;
any other geographic CRS (a rotated pole, or another datum such as NZGD49, 187 m away) is left out of
/collectionsand answers 404NotServed, because reading it as CRS84 would serve the wrong cells (Mike, 2026-11-25). - The cell. A projected grid (the WRF grids' Lambert CRS) is reached by projecting the CRS84
point. A geographic grid's longitude is wrapped onto the window centred on its axis, so −179 and
181 reach the same SST cell. On each axis the cell is the nearest stored centre (
searchsortedon the midpoints). A point up to half a cell beyond an outer centre is in, with a tolerance of 0.1% of the edge spacing; further is out (204). The tolerance is for SST, whose float32 centres put the outer cell edges 4.5e-6° inside the round numbers 120°E and 60°S (Mike, 2026-11-25). On a midpoint the lower index wins. SST's inner cell edges fall on round numbers too (multiples of 0.05°), so a round-number point sits on a corner, and float32 noise in the centres decides its cell.envlib:cellreports the indices and native coordinates of the cell served, and thePointSeriesx and y are its centre in CRS84, with lon in [−180, 180). - The cube. A cell's centre is in the bbox when s ≤ lat ≤ n and it lies within the bbox's width
east of w, taken mod 360. So a bbox across the antimeridian works as west > east (
178,…,-178,…) or in the 0–360 convention (178,…,182,…). The answer is the smallest grid rectangle holding every such cell, unmasked (Mike, 2026-11-25). The WRF grid is rotated about 37° against north, so a lon/lat square returns about twice its own cells, and a thin strip many times more (28–70× measured on live WRF; there is no bound); the caps count the rectangle. A bbox between centres (smaller than a cell) answers 204. Malformed bboxes answer 400, numbers included (1_0is refused), and so does a bbox whose west lies more than 360° east of its east (190,…,-190,…), which no reading makes a box.- On a global lon/lat grid (none is served today), a bbox across the axis's seam (±180 on a −180..180 axis) returns the whole longitude axis, because the rectangle is one index range.
- The cost before the caps: the 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.
- The cube's CRS. A cube comes back on the grid's own axes. On SST that is CRS84, with
longitudes past 180 kept so the axis stays monotonic. On the WRF grids it is the Lambert CRS in
metres, as a
ProjectedCRSwhose WKT is in the custom memberenvlib:wkt. The collection listscrs: ["CRS84", "native"]; each query'scrs_detailslists the one it returns (nativefor a WRF cube, CRS84 for a position and for an SST cube). This is a documented deviation from EDR's/req/edr/REQ_rc-crs-responseA (data in the extent's CRS whencrsis absent): a rotated grid cannot be a CRS84Grid.crs=nativeand nocrsgive the same answer;crs=CRS84on a WRF cube answers 400. Input coordinates are always CRS84. zis a level or an interval (a/b, with..for an open end), matched after rounding both sides to the coordinate's stored precision: the live soil level 1.0 m is stored as 0.9999999999999999. A list or a recurring interval answers 400 (EDR's MAY). On a grid without levelszis ignored, as EDR requires.- CoverageJSON. A
Gridrange is anNdArrayin row-major (t, z, y, x) order; itsaxisNamesleave out the axes with a single value.zis referenced by aVerticalCRS.resolution-x/y/zanswer 400 (cubes are at native resolution). Grid/areaand netCDF output come later (the item "EDR grid/areaand netCDF output" in envlib'sOPEN_WORK.md). - CSV is offered for
/positiononly: one row per time step (and level), with the cell's native coordinates and its centre in CRS84. A cube is CoverageJSON only (Mike, 2026-11-25). Long-form CSV of a cube repeats every coordinate on every cell's row, and grid users want arrays: CoverageJSON now, netCDF later.f=CSVon a cube answers 400, naming the formats offered. - The pyproj transformers are cached per CRS (an
lru_cachekeyed 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 afrom_crstransformer repeats PROJ's operation search in every new thread. So the cache holds afrom_pipelinetransformer 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), thefrom_crstransformer is cached instead: it is correct, but it pays about 30 ms in each new thread. POINT Zanswers 400 (usezfor a level). In position CSV, a native coordinate column namedlonorlatgets the suffix_native.
The catalogue
/catalogue and /catalogue/distinct/{field} serve the envlib catalogue as the mirror holds it
(envlib_api/api/catalogue.py; plan 5 and its review edr-api-plan-5). The matching rules are
envlib's: each request reads every mirrored catalogue document and calls envlib.match_entries,
envlib.latest_per_dataset or envlib.distinct_values, the functions Catalogue.query() and
Catalogue.distinct() call. So an HTTP query and a Python query of the same catalogue give the same
entries.
/catalogue parameters (anything else answers 400):
| Parameter | Meaning |
|---|---|
any queryable field (envlib.QUERYABLE_FIELDS: the identity fields, license, dataset_type, dataset_id, dataset_version_id) |
Comma-separated values, any of which matches, case-insensitive. An empty value (product_code=) asks for null |
bbox=w,s,e,n |
Intersects the stored bbox. Longitudes as on /cube (−360..360, west > east crossing 180, or 0–360). The 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 |
coords=POLYGON(...) or MULTIPOLYGON(...) |
Intersects the stored bbox. A polygon is also tried 360° east and west, so 0–360 longitudes work. Non-finite coordinates answer 400 |
coords=POINT(lon lat)&within=…&within-units=km|m |
A stored bbox within that great-circle distance |
datetime |
Overlaps the stored time range: an instant, or an interval with .. for an open end |
all-versions=true |
Every matching version. Otherwise the latest matching version of each dataset |
limit, after |
Paging (below) |
bbox and coords are alternatives. The spatial filters test each dataset's stored bbox, a coarse
filter that is never too small, as in envlib.
Each entry carries dataset_version_id, dataset_id, latest, db_url, the full catalogue
metadata, links, and an envlib snippet that opens that version.
latestsays whether this is the version the collection serves, over the whole catalogue and whatever the filters. A time filter can return an older version, because envlib picks the latest of the matching versions; that entry haslatest: false.- Links:
- on the latest entry of a served type,
alternatepoints to its EDR collection. That collection can still answer 404NotServed(a dataset that breaks a convention) or 503 (its remote is missing), because checking needs the dataset opened; - on an older entry,
latest-version(RFC 5829) points to the latest one in/catalogue; - on every entry,
version-historypoints to all its dataset's versions.
- on the latest entry of a served type,
- Each collection links to the same
version-history, and the landing page links to/cataloguewith the relationhttps://envlib.xyz/rel/catalogue.
Order and paging. Entries are sorted by dataset_id, then by envlib.version_key descending,
the order latest_per_dataset itself uses (created_at, then dataset_version_id), so each
dataset's served version comes first whatever its stamp looks like. limit is a whole number of
ASCII digits; it defaults to catalogue_limit (100, in [api]), and a larger value is clamped to it.
The next link carries every filter plus after: the page's last entry's dataset_id,
created_at text and dataset_version_id, each percent-encoded and joined by |. The next page
starts strictly after that key. So a change between pages never repeats an entry and never skips one
that was already there; an entry added before the cursor is not seen. The body carries
numberMatched and numberReturned.
/catalogue/distinct/{field} (counts=true for counts) answers {"field", "values"} or
{"field", "counts": [{"value", "count"}]}, in envlib's order, with null as null. It counts every
version, so a facet's counts can exceed /catalogue's numberMatched. An unknown field answers 404.
Limits:
- a value containing a comma cannot be matched;
- a hand-typed
+must be sent as%2B(utc_offset=%2B00:00): a bare+decodes as a space; - a date-only
datetimeis the instant at 00:00, not the whole day; - the mirror never lists an entry it refuses (one with no http(s)
db_urlor nodataset_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'sdistinct()raises on it. Only a hand-damaged entry holds one, sinceMetadatawould not publish it (code reviewedr-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.jscreates the user when the secretenvlib_api_mongo_api_passwordis mounted. - On the existing production volume, create it by hand as root in the
mongocontainer, with the privileges frommongo/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 binds0.0.0.0:8000unlessENVLIB_API_HOSTandENVLIB_API_PORTsay otherwise. - Secrets: compose's
mongoservice now mounts the API's password secret, somongo-api-passwordmust exist in the local secrets directory, even for the refresher alone.
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 nodocker 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$$NOWwith 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.
- If two refreshers are ever seen, build the lease the plan review designed (
- 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
urllibUser-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:
- Pick MongoDB's node and label it. The volume is node-local, and the refresher follows it.
Label exactly one node: with two,
mongoandrefreshercould be placed apart, and a restartedmongocould start on an empty volume.docker node ls docker node update --label-add envlib_mongo=true <node>
- Create the three secrets. Generate the two passwords first, for example with
python -c "import secrets; print(secrets.token_hex(24))".- Hex needs no escaping. A password containing
@ : / %must be percent-encoded in the URI, or the refresher fails at start withInvalidURI. - The refresher password goes in the TOML's URI, and it must match its secret.
- Pass each secret on stdin (
-) or from a file you delete afterwards, so nothing stays on disk.
docker secret create envlib_api_mongo_root_password - # paste, then Ctrl-D docker secret create envlib_api_mongo_refresher_password - docker secret create envlib_api_toml - <<'EOF' [mongo] uri = "mongodb://refresher:<refresher password>@mongo:27017/envlib_api?authSource=envlib_api" [sentry] dsn = "https://<key>@<org>.ingest.sentry.io/<project>" # without it nothing alerts (the log says so at start) monitor_slug = "envlib-api-refresher" EOF
envlib_api/config.pyhas every TOML key.- The
dsnmust be a fullhttps://URL. Anything else (a placeholder left in, for instance) makes the refresher crash-loop at start with sentry-sdk'sBadDsn: Unsupported scheme '', which is what happened on the first deploy. - The Sentry cron monitor is created by the first check-in (
monitor_config), so it needs no setup.
- Hex needs no escaping. A password containing
- Build and push the image from a checkout whose lock comes from PyPI (the Dockerfile's header
explains why):
docker build -t mullenkamp/envlib-api:0.1.0 . && docker push mullenkamp/envlib-api:0.1.0
Then, from the checkout on the manager:
git pull
docker stack deploy -c docker-swarm.yml envlib-api
Bump the image tag with every code change, and bump a config's name: with every change of its
file, because configs are immutable.
Replacing a secret (they are immutable too). A service holds the secrets it uses, so detach first:
docker service update --detach --secret-rm envlib_api_toml envlib-api_refresher
docker secret rm envlib_api_toml
docker secret create envlib_api_toml - # the corrected TOML on stdin
docker stack deploy -c docker-swarm.yml envlib-api # re-attaches it and restarts the refresher
Operations
-
Status:
docker exec -it $(docker ps -qf name=envlib-api_refresher) envlib-api status. It shows one row per dataset and exits 1 if any is stale (checked_atolder than 3 polls), missing, unapplied, or stuck applying. Retired datasets are listed but not flagged. -
A blocked retire (logged and alerted once): check the catalogue. If the removal is intended, run
envlib-api allow-retiresin the refresher container.- It acknowledges the current catalogue uuid.
- It allows one retire pass that ignores the cap and the empty-catalogue guard.
- That pass must come within an hour, and it is consumed when used.
- It refuses while the catalogue mirror is not applied.
-
Never mirrored:
statusalso lists catalogue entries that have no dataset document. A new entry shows that way for up to one cycle; one that stays is failing, and Sentry has its error. -
Changing the refresher password: Swarm secrets are immutable, and
init-users.jsruns only on an empty volume.- As root in the
mongocontainer, rundb.getSiblingDB("envlib_api").changeUserPassword("refresher", "<new>"). - Create new secrets under new names (e.g.
envlib_api_toml_v2), both the password and the TOML. - Point
docker-swarm.ymlat the new names, and redeploy.
- As root in the
-
If
mongo's first start fails (for example,init-users.jscould not read a secret), the volume is already initialised and the script will not run again. Remove the stack and the volume (docker volume rm envlib_api_mongoon its node), fix the cause, and deploy again. -
Stopping the refresher:
docker service scale envlib-api_refresher=0, and=1to restart it. While it is stopped,checked_atages,statusflags every dataset, and Sentry alerts on the missed check-ins. -
Rebuilding MongoDB, for example after a lost volume or a suspected divergence:
- scale the refresher to 0 (and the API);
- drop the database:
docker exec -it <mongo container> mongosh -u root -p --authenticationDatabase admin --eval 'db.getSiblingDB("envlib_api").dropDatabase()'; - scale the refresher back to 1.
Its start re-creates the schema, and the first cycle re-mirrors everything: about 220 MB of indexes from B2, in about 75 s. Never drop collections under a running refresher, because it would recreate them without validators, compressors or the TTL index. The refresher's role and user survive
dropDatabase(checked on 9.0.8). On a new, empty volume,mongo/init-users.jscreates them; it runs by itself only then. -
Upgrading MongoDB: follow the binary-then-feature-compatibility-version pattern in
dshg/mvp/web_app/MONGO_DEPLOY.md. Or, since the data is derived, rebuild on the new version. -
autoheal is not running on the cluster (checked 2026-11-24: no service, and no container on uswest11), although
tethys-docker-swarm/autoheal/defines one withAUTOHEAL_CONTAINER_LABEL=all. Swarm replaces an unhealthy task itself, and waits for the old container to exit first. If autoheal is ever deployed, its in-place restart of the old container beside Swarm's replacement could make a second refresher. The refresher therefore carries the container labelautoheal=False, which is autoheal's opt-out according to the code review's reading of its source. The label is on the running container, checked withdocker inspect. Whether a deployed autoheal honours it is untested. -
Seeing how a task stopped: scaling a service down deletes its tasks, together with their logs, so
docker service psanddocker service logsno longer show them. Docker's event log still does:docker events --since 30m --until 0s --filter label=com.docker.swarm.service.name=envlib-api_refreshershows eachkill(with its signal) anddie(with its exit code). -
The role is
readWritepluscollModonenvlib_api(mongo/refresher-role.json). It includesdropCollection, which the refresher never uses. It is kept that broad because a hand-written action list would break silently the first time ebooklet's schema code needs another action. -
Local runs (
docker-compose.yml) take their secrets from~/.envlib/envlib-api-local, never production's directory. Give the local TOML its own Sentry environment, or no DSN.
Development
uv sync
docker run -d --rm --name envlib-api-test-mongo -p 127.0.0.1:27092:27017 --tmpfs /data/db \
-e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=testpw mongo:9.0.8
ENVLIB_API_TEST_MONGO_URI='mongodb://root:testpw@127.0.0.1:27092/?authSource=admin' uv run pytest
- The tests use real ebooklet remotes on a moto S3 server and a real MongoDB with auth, connecting
as the production roles (
mongo/refresher-role.json,mongo/api-role.json). - The API tests build their station datasets with envlib-ingest-base's
build_and_publish, the real producer, and compare every answer with a direct cfdb read and with the producer's input (envlib_api/tests/api_support.py). The schema tests validate against the CoverageJSON and EDR 1.2 schemas vendored inenvlib_api/tests/schemas/. planning/mutate.pyruns the mutants inplanning/mutants.json(the refresher) andplanning/mutants_api.json(the API). Every one must be KILLED except the documented equivalent (planning/mutants_result.txt,planning/mutants_api_result.txt).- The catalogue's mutants are
planning/mutants_catalogue.json(the API side) andplanning/mutants_envlib.json(envlib's matching, run byplanning/mutate_envlib.pyon a copy of envlib).mutate.pykeeps an existingPYTHONPATHafter the copy, so a mutant run can import an unreleased envlib (PYTHONPATH=../envlib MUTATE_ENVLIB_VERSION=0.1.9). planning/close_check_api.pycompares a running API with direct envlib reads of the live datasets.benchmarks/times the API's hot paths, and an A/B of the previous release against the candidate is a release step (benchmarks/README.md).
Metadata
Release files for envlib-api 0.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| envlib_api-0.4.0.tar.gz | 650.8 kB | Without provenance | Details for envlib_api-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| envlib_api-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for envlib_api-0.4.0-py3-none-any.whl |
Total release size: 839.3 kB
Release files / envlib_api-0.4.0.tar.gz
| Download URL | envlib_api-0.4.0.tar.gz |
|---|---|
| Size | 650.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d2da2ca3231cea32f7a4a1452d59b5aa354cbce0bba5ff01427c50d96fb9c0cf
|
|
BLAKE2b-256 checksum How to use checksums |
caa1cfe3e65d506338de1bbfb44105fe5faa935fa226e4b6d9d92189c9c88b3e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.8.7
|
Release files / envlib_api-0.4.0-py3-none-any.whl
| Download URL | envlib_api-0.4.0-py3-none-any.whl |
|---|---|
| Size | 188.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d2003f2418d8d0e9fe176cf3ae69fb838e5e362421d29087e1f69fb1fbf7cf59
|
|
BLAKE2b-256 checksum How to use checksums |
b5b2f37f66c45ad817a1f3cf8a156da723a9154981bc51e9d29bb3f0b225d083
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.8.7
|
Security for envlib-api 0.4.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.