ws-availability 1.1.0__tar.gz → 1.1.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. {ws_availability-1.1.0 → ws_availability-1.1.2}/PKG-INFO +74 -13
  2. {ws_availability-1.1.0 → ws_availability-1.1.2}/README.md +73 -12
  3. ws_availability-1.1.2/apps/cli.py +163 -0
  4. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/globals.py +1 -1
  5. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/settings.py +19 -2
  6. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/updater.py +65 -18
  7. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/wfcatalog_client.py +64 -11
  8. {ws_availability-1.1.0 → ws_availability-1.1.2}/docker-compose.yml +11 -0
  9. {ws_availability-1.1.0 → ws_availability-1.1.2}/pyproject.toml +7 -1
  10. ws_availability-1.1.2/tests/test_cli.py +71 -0
  11. {ws_availability-1.1.0 → ws_availability-1.1.2}/tests/test_data_access.py +3 -1
  12. {ws_availability-1.1.0 → ws_availability-1.1.2}/tests/test_docker_compose.py +2 -0
  13. {ws_availability-1.1.0 → ws_availability-1.1.2}/tests/test_query_no_endtime.py +7 -5
  14. {ws_availability-1.1.0 → ws_availability-1.1.2}/tests/test_settings.py +62 -1
  15. {ws_availability-1.1.0 → ws_availability-1.1.2}/tests/test_updater.py +46 -0
  16. {ws_availability-1.1.0 → ws_availability-1.1.2}/tests/test_wfcatalog_query.py +116 -1
  17. {ws_availability-1.1.0 → ws_availability-1.1.2}/ws_availability.egg-info/PKG-INFO +74 -13
  18. {ws_availability-1.1.0 → ws_availability-1.1.2}/ws_availability.egg-info/SOURCES.txt +3 -0
  19. ws_availability-1.1.2/ws_availability.egg-info/entry_points.txt +2 -0
  20. {ws_availability-1.1.0 → ws_availability-1.1.2}/Dockerfile.api +0 -0
  21. {ws_availability-1.1.0 → ws_availability-1.1.2}/Dockerfile.cacher +0 -0
  22. {ws_availability-1.1.0 → ws_availability-1.1.2}/LICENSE +0 -0
  23. {ws_availability-1.1.0 → ws_availability-1.1.2}/MANIFEST.in +0 -0
  24. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/__init__.py +0 -0
  25. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/data_access_layer.py +0 -0
  26. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/models.py +0 -0
  27. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/parameters.py +0 -0
  28. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/redis_client.py +0 -0
  29. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/restriction.py +0 -0
  30. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/root.py +0 -0
  31. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/scheduler.py +0 -0
  32. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/sentry.py +0 -0
  33. {ws_availability-1.1.0 → ws_availability-1.1.2}/apps/utils.py +0 -0
  34. {ws_availability-1.1.0 → ws_availability-1.1.2}/setup.cfg +0 -0
  35. {ws_availability-1.1.0 → ws_availability-1.1.2}/templates/doc.html +0 -0
  36. {ws_availability-1.1.0 → ws_availability-1.1.2}/templates/wadl.xml +0 -0
  37. {ws_availability-1.1.0 → ws_availability-1.1.2}/tests/test.py +0 -0
  38. {ws_availability-1.1.0 → ws_availability-1.1.2}/tests/test_gunicorn_conf.py +0 -0
  39. {ws_availability-1.1.0 → ws_availability-1.1.2}/tests/test_issue60_protection.py +0 -0
  40. {ws_availability-1.1.0 → ws_availability-1.1.2}/tests/test_merge_parameter.py +0 -0
  41. {ws_availability-1.1.0 → ws_availability-1.1.2}/tests/test_orderby.py +0 -0
  42. {ws_availability-1.1.0 → ws_availability-1.1.2}/tests/test_restriction.py +0 -0
  43. {ws_availability-1.1.0 → ws_availability-1.1.2}/tests/test_wfcatalog_filtering.py +0 -0
  44. {ws_availability-1.1.0 → ws_availability-1.1.2}/views/main.js +0 -0
  45. {ws_availability-1.1.0 → ws_availability-1.1.2}/ws_availability.egg-info/dependency_links.txt +0 -0
  46. {ws_availability-1.1.0 → ws_availability-1.1.2}/ws_availability.egg-info/requires.txt +0 -0
  47. {ws_availability-1.1.0 → ws_availability-1.1.2}/ws_availability.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ws-availability
3
- Version: 1.1.0
3
+ Version: 1.1.2
4
4
  Summary: Add your description here
5
5
  Requires-Python: >=3.13
6
6
  Description-Content-Type: text/markdown
@@ -23,7 +23,7 @@ A Flask implementation of the [FDSN Availability web service 1.0](http://www.fds
23
23
 
24
24
  It runs as three Docker containers: the **API** (Flask + gunicorn, port 9001), a **Redis** cache, and a **cacher** that keeps the restriction inventory and the `availability` view up to date on a built-in daily schedule.
25
25
 
26
- > **Upgrading from v1.0.x?** Follow [`BETA.md`](BETA.md) for the exact upgrade steps (config.py changes, the in-app scheduler replacing host cron).
26
+ > **Upgrading from v1.0.x?** See [Upgrading from v1.0.x](#upgrading-from-v10x) for the exact `config.py` changes — it's a quick, self-contained checklist.
27
27
 
28
28
  ## Deployment
29
29
 
@@ -74,6 +74,50 @@ curl "127.0.0.1:9001/extent?net=NA&start=2023-02-01"
74
74
 
75
75
  For a node that already has a populated WFCatalog, that's the whole install. A brand-new database also needs the one-time [database setup](#first-time-database-setup). Requires MongoDB ≥ 4.2.
76
76
 
77
+ ## Upgrading from v1.0.x
78
+
79
+ Upgrading reuses the same containers and the same `config.py`. The only manual step is making sure `config.py` has the keys the new version expects, then rebuilding.
80
+
81
+ > **What changed for operators:** `config.py` is now the **only** place to set MongoDB, FDSNWS-Station and Sentry settings. `docker-compose.yml` no longer passes them to the container, so your edits in `config.py` actually take effect.
82
+
83
+ 1. **Get the new code.** Your `config.py` is gitignored, so this won't touch it:
84
+
85
+ ```bash
86
+ git fetch && git checkout v1.1.0
87
+ ```
88
+
89
+ 2. **Add any missing `config.py` keys.** `MONGODB_*`, `CACHE_*` and `FDSNWS_STATION_URL` are unchanged — keep your values. What to add depends on the version you're coming from (add the lines inside the `try:` block, next to the other `os.environ.get(...)` lines):
90
+
91
+ - **From v1.0.5 or v1.0.4** — add one line:
92
+
93
+ ```python
94
+ SENTRY_ENVIRONMENT = "yournode_production"
95
+ ```
96
+
97
+ - **From v1.0.3 or earlier** (predates Sentry) — add all three:
98
+
99
+ ```python
100
+ SENTRY_DSN = os.environ.get("SENTRY_DSN", "") # your Sentry DSN, or "" to disable
101
+ SENTRY_TRACES_SAMPLE_RATE = float(os.environ.get("SENTRY_TRACES_SAMPLE_RATE", "1.0"))
102
+ SENTRY_ENVIRONMENT = "yournode_production"
103
+ ```
104
+
105
+ **`SENTRY_ENVIRONMENT` is required and must be unique per node** (e.g. `noa_production`, `resif_production`) so your events are distinguishable in Sentry. Not sure what's missing? Diff against the sample — see [Troubleshooting](#troubleshooting).
106
+
107
+ 3. **Rebuild and restart:**
108
+
109
+ ```bash
110
+ docker-compose up -d --build # or: docker-compose pull && docker-compose up -d
111
+ ```
112
+
113
+ 4. **Remove the old host cron**, if you had one triggering `views/main.js` — it's now redundant, replaced by the [built-in scheduler](#what-runs-daily):
114
+
115
+ ```bash
116
+ crontab -l | grep -v "ws-availability.*views.*main.js" | crontab -
117
+ ```
118
+
119
+ Then re-run the `curl` checks above; `/version` should report `1.1.0`.
120
+
77
121
  ## Endpoints
78
122
 
79
123
  API on port `9001`. `/query` (time spans per channel) and `/extent` (one row per channel) accept GET and POST. Also `/version`, `/application.wadl`, and `/` (landing page).
@@ -90,11 +134,13 @@ Everything lives in `config.py` (copied from `config.py.sample`, gitignored so u
90
134
 
91
135
  | Key | Default | Description |
92
136
  |-----|---------|-------------|
137
+ | `MONGODB_ENGINE` | `mongodb` | Database engine: `mongodb`, or `docdb` for Amazon DocumentDB. |
93
138
  | `MONGODB_HOST` | `host.docker.internal` | WFCatalog MongoDB host. |
94
139
  | `MONGODB_PORT` | `27017` | MongoDB port. |
95
140
  | `MONGODB_USR` / `MONGODB_PWD` | empty | MongoDB credentials (leave empty if no auth). |
96
141
  | `MONGODB_NAME` | `wfrepo` | Database name; also used as `authSource` unless `MONGODB_AUTH_SOURCE` is set. |
97
142
  | `MONGODB_AUTH_SOURCE` | `None` | Optional. Mongo auth database when it differs from `MONGODB_NAME` (e.g. `admin`). Falls back to `MONGODB_NAME` when unset. |
143
+ | `DOCDB_CA_PATH` | `None` | Path to the Amazon CA bundle. Required when `MONGODB_ENGINE = "docdb"`, ignored otherwise. |
98
144
  | `FDSNWS_STATION_URL` | `https://orfeus-eu.org/fdsnws/station/1/query` | FDSNWS-Station endpoint to harvest restriction info from. |
99
145
  | `CACHE_HOST` | `cache` | Redis host. |
100
146
  | `CACHE_PORT` | `6379` | Redis port. |
@@ -112,7 +158,9 @@ The cacher runs a built-in scheduler — no host cron needed:
112
158
 
113
159
  - **03:00 UTC** — refresh the restriction inventory from FDSNWS-Station into Redis.
114
160
  - **06:00 UTC** — update the `availability` view from the last 4 days of WFCatalog data.
115
- - **On startup** — both run once, so a restart leaves data fresh.
161
+ - **On startup** — both run once, so a restart leaves recent data fresh.
162
+
163
+ This covers only the recent window. To repair an older date (e.g. after a backfill), see [Back-processing](#back-processing-historical--scoped-rebuild).
116
164
 
117
165
  ## Tuning (optional)
118
166
 
@@ -165,16 +213,33 @@ The compound index `{ net: 1, sta: 1, loc: 1, cha: 1, ts: 1, te: 1 }` is created
165
213
 
166
214
  After the initial build, the cacher keeps the view current automatically (see [What runs daily](#what-runs-daily)) — **no host cron is needed** (earlier versions required one; it has been replaced by the built-in scheduler).
167
215
 
168
- ### Back-processing
216
+ ### Back-processing (historical / scoped rebuild)
217
+
218
+ The daily scheduler only refreshes a **rolling recent window** (the last 4 days). It therefore *cannot* repair a historical gap: if WFCatalog is (re)populated for an old date — e.g. after a backfill, or a data correction surfaced by an [EIDA consistency report](https://github.com/EIDA) — restarting the cacher does **not** rebuild that date, so `/query` and `/extent` keep reporting "no data" even though dataselect / the SDS archive serve it. You must reprocess that range explicitly.
169
219
 
170
- The daily scheduler only refreshes a rolling recent window. To reprocess a specific historical range or a subset of streams — e.g. after a data correction or a backfill — run `views/main.js` manually with parameters (`networks`/`stations` accept regex):
220
+ > **Prerequisite:** back-processing only re-derives the view *from* WFCatalog (`daily_streams`/`c_segments`). It does **not** scan the SDS archive. If WFCatalog itself is missing the range, refresh WFCatalog for those dates **first**, otherwise the rebuild completes cleanly but writes nothing.
221
+
222
+ **Preferred — the `avail-rebuild` CLI** (runs inside the cacher, so it uses the container's own MongoDB credentials; supports full NSLC):
171
223
 
172
224
  ```bash
173
- # A specific month
174
- mongosh -u USER -p PASSWORD --authenticationDatabase wfrepo \
175
- --eval "start='2023-01-01'; end='2023-01-31'" views/main.js
225
+ # A network/station over a range (all of 2008 -> end is the day boundary, 2009-01-01)
226
+ docker exec fdsnws-availability-cacher \
227
+ avail-rebuild --net IV --sta ABC --start 2008-01-01 --end 2009-01-01
176
228
 
177
- # One network/station over a range
229
+ # Channel-precise (e.g. just HHZ; --loc=-- means the empty location.
230
+ # Use the attached '=' form: a bare '--' is read by the shell/argparse as end-of-options.)
231
+ docker exec fdsnws-availability-cacher \
232
+ avail-rebuild --net IV --sta ABC --loc=-- --cha HHZ --start 2008-01-01 --end 2009-01-01
233
+
234
+ # Whole range, all streams
235
+ docker exec fdsnws-availability-cacher avail-rebuild --start 2023-01-01 --end 2023-02-01
236
+ ```
237
+
238
+ `--net/--sta/--loc/--cha` are comma-separated exact-match lists; omit any to leave it unconstrained. The rebuild is idempotent (`$merge whenMatched:"replace"`) — safe to re-run. After it finishes, flush Redis or wait out `CACHE_RESP_PERIOD` before re-checking, in case an empty response for that query is still cached. (If the console script isn't on `PATH` for some reason, `docker exec fdsnws-availability-cacher python -m apps.cli …` is equivalent.)
239
+
240
+ **Fallback — `views/main.js` via `mongosh`** (host-side; net+sta+date only, no loc/cha; needs a repo checkout and DB creds on the host):
241
+
242
+ ```bash
178
243
  mongosh -u USER -p PASSWORD --authenticationDatabase wfrepo \
179
244
  --eval "networks='NL'; stations='HGN'; start='2022-12-01'; end='2023-01-31'" views/main.js
180
245
  ```
@@ -200,7 +265,3 @@ If the service isn't working — often right after an upgrade — it's usually a
200
265
  Lines prefixed `>` are keys present in the sample but missing from your `config.py` — add them.
201
266
 
202
267
  3. **Check database access** — confirm the MongoDB and Redis connection parameters in `config.py` are correct and that both services are reachable from the containers.
203
-
204
- ## References
205
-
206
- Forked from [gitlab.com/resif/ws-availability](https://gitlab.com/resif/ws-availability) — thanks to our colleagues at RESIF for sharing their FDSNWS-Availability implementation. 💐
@@ -4,7 +4,7 @@ A Flask implementation of the [FDSN Availability web service 1.0](http://www.fds
4
4
 
5
5
  It runs as three Docker containers: the **API** (Flask + gunicorn, port 9001), a **Redis** cache, and a **cacher** that keeps the restriction inventory and the `availability` view up to date on a built-in daily schedule.
6
6
 
7
- > **Upgrading from v1.0.x?** Follow [`BETA.md`](BETA.md) for the exact upgrade steps (config.py changes, the in-app scheduler replacing host cron).
7
+ > **Upgrading from v1.0.x?** See [Upgrading from v1.0.x](#upgrading-from-v10x) for the exact `config.py` changes — it's a quick, self-contained checklist.
8
8
 
9
9
  ## Deployment
10
10
 
@@ -55,6 +55,50 @@ curl "127.0.0.1:9001/extent?net=NA&start=2023-02-01"
55
55
 
56
56
  For a node that already has a populated WFCatalog, that's the whole install. A brand-new database also needs the one-time [database setup](#first-time-database-setup). Requires MongoDB ≥ 4.2.
57
57
 
58
+ ## Upgrading from v1.0.x
59
+
60
+ Upgrading reuses the same containers and the same `config.py`. The only manual step is making sure `config.py` has the keys the new version expects, then rebuilding.
61
+
62
+ > **What changed for operators:** `config.py` is now the **only** place to set MongoDB, FDSNWS-Station and Sentry settings. `docker-compose.yml` no longer passes them to the container, so your edits in `config.py` actually take effect.
63
+
64
+ 1. **Get the new code.** Your `config.py` is gitignored, so this won't touch it:
65
+
66
+ ```bash
67
+ git fetch && git checkout v1.1.0
68
+ ```
69
+
70
+ 2. **Add any missing `config.py` keys.** `MONGODB_*`, `CACHE_*` and `FDSNWS_STATION_URL` are unchanged — keep your values. What to add depends on the version you're coming from (add the lines inside the `try:` block, next to the other `os.environ.get(...)` lines):
71
+
72
+ - **From v1.0.5 or v1.0.4** — add one line:
73
+
74
+ ```python
75
+ SENTRY_ENVIRONMENT = "yournode_production"
76
+ ```
77
+
78
+ - **From v1.0.3 or earlier** (predates Sentry) — add all three:
79
+
80
+ ```python
81
+ SENTRY_DSN = os.environ.get("SENTRY_DSN", "") # your Sentry DSN, or "" to disable
82
+ SENTRY_TRACES_SAMPLE_RATE = float(os.environ.get("SENTRY_TRACES_SAMPLE_RATE", "1.0"))
83
+ SENTRY_ENVIRONMENT = "yournode_production"
84
+ ```
85
+
86
+ **`SENTRY_ENVIRONMENT` is required and must be unique per node** (e.g. `noa_production`, `resif_production`) so your events are distinguishable in Sentry. Not sure what's missing? Diff against the sample — see [Troubleshooting](#troubleshooting).
87
+
88
+ 3. **Rebuild and restart:**
89
+
90
+ ```bash
91
+ docker-compose up -d --build # or: docker-compose pull && docker-compose up -d
92
+ ```
93
+
94
+ 4. **Remove the old host cron**, if you had one triggering `views/main.js` — it's now redundant, replaced by the [built-in scheduler](#what-runs-daily):
95
+
96
+ ```bash
97
+ crontab -l | grep -v "ws-availability.*views.*main.js" | crontab -
98
+ ```
99
+
100
+ Then re-run the `curl` checks above; `/version` should report `1.1.0`.
101
+
58
102
  ## Endpoints
59
103
 
60
104
  API on port `9001`. `/query` (time spans per channel) and `/extent` (one row per channel) accept GET and POST. Also `/version`, `/application.wadl`, and `/` (landing page).
@@ -71,11 +115,13 @@ Everything lives in `config.py` (copied from `config.py.sample`, gitignored so u
71
115
 
72
116
  | Key | Default | Description |
73
117
  |-----|---------|-------------|
118
+ | `MONGODB_ENGINE` | `mongodb` | Database engine: `mongodb`, or `docdb` for Amazon DocumentDB. |
74
119
  | `MONGODB_HOST` | `host.docker.internal` | WFCatalog MongoDB host. |
75
120
  | `MONGODB_PORT` | `27017` | MongoDB port. |
76
121
  | `MONGODB_USR` / `MONGODB_PWD` | empty | MongoDB credentials (leave empty if no auth). |
77
122
  | `MONGODB_NAME` | `wfrepo` | Database name; also used as `authSource` unless `MONGODB_AUTH_SOURCE` is set. |
78
123
  | `MONGODB_AUTH_SOURCE` | `None` | Optional. Mongo auth database when it differs from `MONGODB_NAME` (e.g. `admin`). Falls back to `MONGODB_NAME` when unset. |
124
+ | `DOCDB_CA_PATH` | `None` | Path to the Amazon CA bundle. Required when `MONGODB_ENGINE = "docdb"`, ignored otherwise. |
79
125
  | `FDSNWS_STATION_URL` | `https://orfeus-eu.org/fdsnws/station/1/query` | FDSNWS-Station endpoint to harvest restriction info from. |
80
126
  | `CACHE_HOST` | `cache` | Redis host. |
81
127
  | `CACHE_PORT` | `6379` | Redis port. |
@@ -93,7 +139,9 @@ The cacher runs a built-in scheduler — no host cron needed:
93
139
 
94
140
  - **03:00 UTC** — refresh the restriction inventory from FDSNWS-Station into Redis.
95
141
  - **06:00 UTC** — update the `availability` view from the last 4 days of WFCatalog data.
96
- - **On startup** — both run once, so a restart leaves data fresh.
142
+ - **On startup** — both run once, so a restart leaves recent data fresh.
143
+
144
+ This covers only the recent window. To repair an older date (e.g. after a backfill), see [Back-processing](#back-processing-historical--scoped-rebuild).
97
145
 
98
146
  ## Tuning (optional)
99
147
 
@@ -146,16 +194,33 @@ The compound index `{ net: 1, sta: 1, loc: 1, cha: 1, ts: 1, te: 1 }` is created
146
194
 
147
195
  After the initial build, the cacher keeps the view current automatically (see [What runs daily](#what-runs-daily)) — **no host cron is needed** (earlier versions required one; it has been replaced by the built-in scheduler).
148
196
 
149
- ### Back-processing
197
+ ### Back-processing (historical / scoped rebuild)
198
+
199
+ The daily scheduler only refreshes a **rolling recent window** (the last 4 days). It therefore *cannot* repair a historical gap: if WFCatalog is (re)populated for an old date — e.g. after a backfill, or a data correction surfaced by an [EIDA consistency report](https://github.com/EIDA) — restarting the cacher does **not** rebuild that date, so `/query` and `/extent` keep reporting "no data" even though dataselect / the SDS archive serve it. You must reprocess that range explicitly.
150
200
 
151
- The daily scheduler only refreshes a rolling recent window. To reprocess a specific historical range or a subset of streams — e.g. after a data correction or a backfill — run `views/main.js` manually with parameters (`networks`/`stations` accept regex):
201
+ > **Prerequisite:** back-processing only re-derives the view *from* WFCatalog (`daily_streams`/`c_segments`). It does **not** scan the SDS archive. If WFCatalog itself is missing the range, refresh WFCatalog for those dates **first**, otherwise the rebuild completes cleanly but writes nothing.
202
+
203
+ **Preferred — the `avail-rebuild` CLI** (runs inside the cacher, so it uses the container's own MongoDB credentials; supports full NSLC):
152
204
 
153
205
  ```bash
154
- # A specific month
155
- mongosh -u USER -p PASSWORD --authenticationDatabase wfrepo \
156
- --eval "start='2023-01-01'; end='2023-01-31'" views/main.js
206
+ # A network/station over a range (all of 2008 -> end is the day boundary, 2009-01-01)
207
+ docker exec fdsnws-availability-cacher \
208
+ avail-rebuild --net IV --sta ABC --start 2008-01-01 --end 2009-01-01
157
209
 
158
- # One network/station over a range
210
+ # Channel-precise (e.g. just HHZ; --loc=-- means the empty location.
211
+ # Use the attached '=' form: a bare '--' is read by the shell/argparse as end-of-options.)
212
+ docker exec fdsnws-availability-cacher \
213
+ avail-rebuild --net IV --sta ABC --loc=-- --cha HHZ --start 2008-01-01 --end 2009-01-01
214
+
215
+ # Whole range, all streams
216
+ docker exec fdsnws-availability-cacher avail-rebuild --start 2023-01-01 --end 2023-02-01
217
+ ```
218
+
219
+ `--net/--sta/--loc/--cha` are comma-separated exact-match lists; omit any to leave it unconstrained. The rebuild is idempotent (`$merge whenMatched:"replace"`) — safe to re-run. After it finishes, flush Redis or wait out `CACHE_RESP_PERIOD` before re-checking, in case an empty response for that query is still cached. (If the console script isn't on `PATH` for some reason, `docker exec fdsnws-availability-cacher python -m apps.cli …` is equivalent.)
220
+
221
+ **Fallback — `views/main.js` via `mongosh`** (host-side; net+sta+date only, no loc/cha; needs a repo checkout and DB creds on the host):
222
+
223
+ ```bash
159
224
  mongosh -u USER -p PASSWORD --authenticationDatabase wfrepo \
160
225
  --eval "networks='NL'; stations='HGN'; start='2022-12-01'; end='2023-01-31'" views/main.js
161
226
  ```
@@ -181,7 +246,3 @@ If the service isn't working — often right after an upgrade — it's usually a
181
246
  Lines prefixed `>` are keys present in the sample but missing from your `config.py` — add them.
182
247
 
183
248
  3. **Check database access** — confirm the MongoDB and Redis connection parameters in `config.py` are correct and that both services are reachable from the containers.
184
-
185
- ## References
186
-
187
- Forked from [gitlab.com/resif/ws-availability](https://gitlab.com/resif/ws-availability) — thanks to our colleagues at RESIF for sharing their FDSNWS-Availability implementation. 💐
@@ -0,0 +1,163 @@
1
+ """
2
+ avail-rebuild — on-demand rebuild of the `availability` materialized view for a
3
+ specific date range and (optionally) a specific NSLC subset.
4
+
5
+ Why this exists
6
+ ---------------
7
+ The cacher's daily scheduler only refreshes a rolling recent window
8
+ (`run_updates(days_back=4)` in apps/scheduler.py). It cannot repair *historical*
9
+ gaps: if WFCatalog is (re)populated for an old date — e.g. after a backfill or a
10
+ data correction surfaced by an EIDA consistency report — the availability view
11
+ for that date is never rebuilt, so `/availability` keeps reporting "no data"
12
+ even though dataselect / the SDS archive serve it.
13
+
14
+ The underlying engine (`AvailabilityUpdater.run_updates`) already accepts an
15
+ arbitrary start/end and is idempotent (`$merge whenMatched:"replace"`). Until
16
+ now the only ways to drive it for an old range were the host-side
17
+ `mongosh ... views/main.js` invocation (needs a repo checkout + DB creds on the
18
+ host, and is net+sta+date only) or editing the scheduler. This CLI exposes the
19
+ engine as a stable, versioned, in-container interface so an orchestrator (dmtri)
20
+ can trigger a scoped rebuild without reaching into MongoDB:
21
+
22
+ docker exec fdsnws-availability-cacher \
23
+ avail-rebuild --net IV --sta ABC --start 2008-01-01 --end 2009-01-01
24
+
25
+ Running inside the cacher means MongoDB credentials come from the container's
26
+ own config.py/settings — the caller never handles DB secrets. Unlike main.js it
27
+ also accepts full NSLC (--loc/--cha) for channel-precise rebuilds.
28
+
29
+ Prerequisite
30
+ ------------
31
+ WFCatalog (`daily_streams`/`c_segments`) must already contain the range. This
32
+ tool only re-derives the view *from* WFCatalog; it does not scan the SDS
33
+ archive. Run the WFCatalog refresh for the range first — otherwise the rebuild
34
+ completes cleanly but writes nothing.
35
+ """
36
+ import argparse
37
+ import logging
38
+ import sys
39
+ from datetime import datetime
40
+ from typing import Optional
41
+
42
+ from apps.settings import settings
43
+ from apps.updater import AvailabilityUpdater
44
+ from apps.wfcatalog_client import get_db_client
45
+
46
+ logging.basicConfig(
47
+ handlers=[logging.StreamHandler()],
48
+ level=logging.INFO,
49
+ format="[%(asctime)s] [AVAIL-REBUILD] [%(levelname)s] %(message)s",
50
+ datefmt="%Y-%m-%d %H:%M:%S +0000",
51
+ )
52
+ logger = logging.getLogger(__name__)
53
+
54
+
55
+ def _anchor_regex(csv: Optional[str]) -> str:
56
+ """Turn "IV,GE" into the anchored regex ``^(IV|GE)$`` (exact match per code).
57
+
58
+ None/empty -> ``^.*$`` (match all), mirroring ``run_updates``' default and
59
+ main.js's ``^${networks}$`` convention.
60
+ """
61
+ if not csv:
62
+ return "^.*$"
63
+ codes = [c.strip() for c in csv.split(",") if c.strip()]
64
+ if not codes:
65
+ return "^.*$"
66
+ return "^(" + "|".join(codes) + ")$"
67
+
68
+
69
+ def _code_list(csv: Optional[str]) -> Optional[list[str]]:
70
+ """Turn "00,--" into ``["00", ""]``; ``--`` denotes the empty location.
71
+
72
+ None -> None (dimension left unconstrained in the aggregation).
73
+ """
74
+ if csv is None:
75
+ return None
76
+ return ["" if c.strip() == "--" else c.strip() for c in csv.split(",")]
77
+
78
+
79
+ def _parse_day(value: str) -> datetime:
80
+ try:
81
+ return datetime.strptime(value, "%Y-%m-%d")
82
+ except ValueError:
83
+ raise argparse.ArgumentTypeError(
84
+ f"invalid date '{value}', expected YYYY-MM-DD"
85
+ )
86
+
87
+
88
+ def build_parser() -> argparse.ArgumentParser:
89
+ p = argparse.ArgumentParser(
90
+ prog="avail-rebuild",
91
+ description=(
92
+ "Rebuild the availability materialized view for a date range (and "
93
+ "optional NSLC subset) from WFCatalog. Idempotent — safe to re-run."
94
+ ),
95
+ )
96
+ p.add_argument("--net", help="Comma-separated network codes (exact). Default: all.")
97
+ p.add_argument("--sta", help="Comma-separated station codes (exact). Default: all.")
98
+ p.add_argument(
99
+ "--loc",
100
+ help="Comma-separated location codes (exact). For the empty location pass "
101
+ "--loc=-- (attached form) or --loc '' . Default: all.",
102
+ )
103
+ p.add_argument("--cha", help="Comma-separated channel codes (exact). Default: all.")
104
+ p.add_argument(
105
+ "--start", required=True, type=_parse_day,
106
+ help="Range start, YYYY-MM-DD (inclusive).",
107
+ )
108
+ p.add_argument(
109
+ "--end", required=True, type=_parse_day,
110
+ help="Range end, YYYY-MM-DD. Day boundary: matches segments with te <= end "
111
+ "(e.g. for all of 2008 use --end 2009-01-01).",
112
+ )
113
+ return p
114
+
115
+
116
+ def main(argv: Optional[list[str]] = None) -> int:
117
+ args = build_parser().parse_args(argv)
118
+
119
+ if args.end < args.start:
120
+ logger.error(
121
+ "END (%s) is before START (%s) — nothing to do.",
122
+ args.end.date(), args.start.date(),
123
+ )
124
+ return 2
125
+
126
+ # Sentry is optional; never let its wiring (or a missing config.py) block a
127
+ # rebuild.
128
+ try:
129
+ from apps.sentry import init_sentry
130
+ init_sentry()
131
+ except Exception as e: # pragma: no cover - defensive, env-dependent
132
+ logger.warning("Sentry init skipped: %s", e)
133
+
134
+ networks = _anchor_regex(args.net)
135
+ stations = _anchor_regex(args.sta)
136
+ locations = _code_list(args.loc)
137
+ channels = _code_list(args.cha)
138
+
139
+ db = get_db_client().get_database(settings.mongodb_name)
140
+ updater = AvailabilityUpdater(db)
141
+
142
+ logger.info(
143
+ "Rebuild start: net=%s sta=%s loc=%s cha=%s range=%s..%s db=%s",
144
+ networks, stations, locations, channels,
145
+ args.start.date(), args.end.date(), settings.mongodb_name,
146
+ )
147
+ updater.run_updates(
148
+ networks=networks,
149
+ stations=stations,
150
+ start_date=args.start,
151
+ end_date=args.end,
152
+ locations=locations,
153
+ channels=channels,
154
+ )
155
+ logger.info(
156
+ "Rebuild complete. If a previous query was cached, flush Redis or wait "
157
+ "out CACHE_RESP_PERIOD before re-checking /availability."
158
+ )
159
+ return 0
160
+
161
+
162
+ if __name__ == "__main__":
163
+ sys.exit(main())
@@ -38,7 +38,7 @@ ORDERBY = (
38
38
  # error message constants
39
39
  DOCUMENTATION_URI = "http://www.fdsn.org/webservices/fdsnws-availability-1.0.pdf"
40
40
  SERVICE = "fdsnws-availability"
41
- VERSION = "1.1.0"
41
+ VERSION = "1.1.2"
42
42
 
43
43
 
44
44
  class Error:
@@ -13,12 +13,14 @@ class Settings(BaseSettings):
13
13
  runmode: Literal["test", "production"] = Field("test", alias="RUNMODE")
14
14
 
15
15
  # WFCatalog MongoDB
16
+ mongodb_engine: Literal["mongodb", "docdb"] = Field("mongodb", alias="MONGODB_ENGINE")
16
17
  mongodb_host: str = Field("localhost", alias="MONGODB_HOST")
17
18
  mongodb_port: int = Field(27017, alias="MONGODB_PORT")
18
19
  mongodb_usr: str = Field("", alias="MONGODB_USR")
19
20
  mongodb_pwd: str = Field("", alias="MONGODB_PWD")
20
21
  mongodb_name: str = Field("wfrepo", alias="MONGODB_NAME")
21
22
  mongodb_auth_source: str | None = Field(None, alias="MONGODB_AUTH_SOURCE")
23
+ docdb_ca_path: str | None = Field(None, alias="DOCDB_CA_PATH")
22
24
 
23
25
  # FDSNWS-Station cache source
24
26
  fdsnws_station_url: str = Field("https://orfeus-eu.org/fdsnws/station/1/query", alias="FDSNWS_STATION_URL")
@@ -33,6 +35,9 @@ class Settings(BaseSettings):
33
35
  # Resource Limits
34
36
  max_data_rows: int = Field(2_500_000, alias="MAX_DATA_ROWS")
35
37
  max_streams: int = Field(2000, alias="MAX_STREAMS")
38
+ # Longest stored segment, in days. Bounds the index scan on `ts`;
39
+ # 0 disables the bound (slow: scans each channel's whole history).
40
+ max_segment_days: int = Field(2, ge=0, alias="MAX_SEGMENT_DAYS")
36
41
 
37
42
  # Parallel time-window fan-out for MongoDB queries.
38
43
  # When enabled, mongo_request splits ranges >= fanout_min_days into shards
@@ -42,7 +47,15 @@ class Settings(BaseSettings):
42
47
  fanout_min_days: int = Field(7, alias="FANOUT_MIN_DAYS")
43
48
  fanout_window_days: int = Field(30, alias="FANOUT_WINDOW_DAYS")
44
49
 
45
- model_config = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8', extra='ignore')
50
+ # env_ignore_empty: an env var set to "" (e.g. MONGODB_ENGINE=) means "unset", not an invalid value
51
+ model_config = SettingsConfigDict(env_file='.env', env_file_encoding='utf-8', extra='ignore', env_ignore_empty=True)
52
+
53
+ @model_validator(mode='after')
54
+ def require_docdb_ca_path(self):
55
+ """DocumentDB requires TLS with the Amazon CA bundle; fail at startup, not at first query."""
56
+ if self.mongodb_engine == "docdb" and not self.docdb_ca_path:
57
+ raise ValueError('DOCDB_CA_PATH must be set when MONGODB_ENGINE = "docdb"')
58
+ return self
46
59
 
47
60
  @model_validator(mode='after')
48
61
  def set_production_defaults(self):
@@ -71,18 +84,21 @@ def load_legacy_config():
71
84
  from config import Config
72
85
  return {
73
86
  "RUNMODE": getattr(Config, "RUNMODE", "test"),
87
+ "MONGODB_ENGINE": getattr(Config, "MONGODB_ENGINE", None),
74
88
  "MONGODB_HOST": getattr(Config, "MONGODB_HOST", None),
75
89
  "MONGODB_PORT": getattr(Config, "MONGODB_PORT", None),
76
90
  "MONGODB_USR": getattr(Config, "MONGODB_USR", None),
77
91
  "MONGODB_PWD": getattr(Config, "MONGODB_PWD", None),
78
92
  "MONGODB_NAME": getattr(Config, "MONGODB_NAME", None),
79
93
  "MONGODB_AUTH_SOURCE": getattr(Config, "MONGODB_AUTH_SOURCE", None),
94
+ "DOCDB_CA_PATH": getattr(Config, "DOCDB_CA_PATH", None),
80
95
  "FDSNWS_STATION_URL": getattr(Config, "FDSNWS_STATION_URL", None),
81
96
  "CACHE_HOST": getattr(Config, "CACHE_HOST", None),
82
97
  "CACHE_PORT": getattr(Config, "CACHE_PORT", None),
83
98
  "CACHE_INVENTORY_KEY": getattr(Config, "CACHE_INVENTORY_KEY", None),
84
99
  "CACHE_INVENTORY_PERIOD": getattr(Config, "CACHE_INVENTORY_PERIOD", None),
85
100
  "CACHE_RESP_PERIOD": getattr(Config, "CACHE_RESP_PERIOD", None),
101
+ "MAX_SEGMENT_DAYS": getattr(Config, "MAX_SEGMENT_DAYS", None),
86
102
  }
87
103
  except ImportError:
88
104
  return {}
@@ -100,7 +116,8 @@ def build_settings(legacy: dict, env: dict | None = None) -> "Settings":
100
116
  env = os.environ if env is None else env
101
117
  overrides: dict = {}
102
118
  for k, v in legacy.items():
103
- if v is None:
119
+ # None = key absent from config.py; "" = config.py copied an empty env var
120
+ if v is None or v == "":
104
121
  continue
105
122
  if env.get(k): # truthy: present AND non-empty
106
123
  continue
@@ -8,6 +8,35 @@ from pymongo.database import Database
8
8
  logger = logging.getLogger(__name__)
9
9
 
10
10
 
11
+ def _nslc_match(
12
+ networks: str,
13
+ stations: str,
14
+ start_date: datetime,
15
+ end_date: datetime,
16
+ avail: dict,
17
+ locations: Optional[list[str]] = None,
18
+ channels: Optional[list[str]] = None,
19
+ ) -> dict:
20
+ """Build the stage-0 ``$match`` shared by the daily and continuous pipelines.
21
+
22
+ net/sta stay ``$regex`` (the scheduler/legacy default is ``^.*$``). loc/cha
23
+ are optional exact-match ``$in`` lists, added only when provided — so with
24
+ both None the match is byte-identical to the original net+sta+date filter.
25
+ """
26
+ match: dict = {
27
+ "net": {"$regex": networks},
28
+ "sta": {"$regex": stations},
29
+ "ts": {"$gte": start_date},
30
+ "te": {"$lte": end_date},
31
+ "avail": avail,
32
+ }
33
+ if locations is not None:
34
+ match["loc"] = {"$in": locations}
35
+ if channels is not None:
36
+ match["cha"] = {"$in": channels}
37
+ return match
38
+
39
+
11
40
  class AvailabilityUpdater:
12
41
  def __init__(self, db: Database):
13
42
  self.db = db
@@ -18,19 +47,23 @@ class AvailabilityUpdater:
18
47
  stations: str,
19
48
  start_date: datetime,
20
49
  end_date: datetime,
50
+ locations: Optional[list[str]] = None,
51
+ channels: Optional[list[str]] = None,
21
52
  ):
22
53
  """
23
- Equivalent to `updateAvailabilityDaily` in views/main.js
54
+ Equivalent to `updateAvailabilityDaily` in views/main.js.
55
+
56
+ ``locations``/``channels`` are optional exact-match filters (lists of
57
+ codes). When None the dimension is unconstrained — preserving the
58
+ original net+sta+date behavior the daily scheduler relies on. An empty
59
+ location is the empty string "" (callers normalize "--" -> "").
24
60
  """
25
61
  pipeline = [
26
62
  {
27
- "$match": {
28
- "net": {"$regex": networks},
29
- "sta": {"$regex": stations},
30
- "ts": {"$gte": start_date},
31
- "te": {"$lte": end_date},
32
- "avail": {"$gte": 100},
33
- }
63
+ "$match": _nslc_match(
64
+ networks, stations, start_date, end_date,
65
+ avail={"$gte": 100}, locations=locations, channels=channels,
66
+ )
34
67
  },
35
68
  {
36
69
  "$group": {
@@ -60,19 +93,23 @@ class AvailabilityUpdater:
60
93
  stations: str,
61
94
  start_date: datetime,
62
95
  end_date: datetime,
96
+ locations: Optional[list[str]] = None,
97
+ channels: Optional[list[str]] = None,
63
98
  ):
64
99
  """
65
- Equivalent to `updateAvailabilityContinuous` in views/main.js
100
+ Equivalent to `updateAvailabilityContinuous` in views/main.js.
101
+
102
+ The optional ``locations``/``channels`` filters are applied at the
103
+ stage-0 ``$match`` against ``daily_streams`` (where net/sta/loc/cha
104
+ live), restricting which streams' continuous segments get rebuilt.
105
+ See ``update_availability_daily`` for the filter semantics.
66
106
  """
67
107
  pipeline = [
68
108
  {
69
- "$match": {
70
- "net": {"$regex": networks},
71
- "sta": {"$regex": stations},
72
- "ts": {"$gte": start_date},
73
- "te": {"$lte": end_date},
74
- "avail": {"$lt": 100},
75
- }
109
+ "$match": _nslc_match(
110
+ networks, stations, start_date, end_date,
111
+ avail={"$lt": 100}, locations=locations, channels=channels,
112
+ )
76
113
  },
77
114
  {
78
115
  "$lookup": {
@@ -112,9 +149,15 @@ class AvailabilityUpdater:
112
149
  start_date: Optional[datetime] = None,
113
150
  end_date: Optional[datetime] = None,
114
151
  days_back: Optional[int] = None,
152
+ locations: Optional[list[str]] = None,
153
+ channels: Optional[list[str]] = None,
115
154
  ):
116
155
  """
117
156
  Main runner function replicating the logic at the bottom of main.js.
157
+
158
+ ``locations``/``channels`` are optional exact-match NSLC filters passed
159
+ through to both pipelines; None (the default, used by the scheduler)
160
+ leaves that dimension unconstrained.
118
161
  """
119
162
  now = datetime.utcnow()
120
163
  if days_back is not None:
@@ -135,8 +178,12 @@ class AvailabilityUpdater:
135
178
  f"Processing WFCatalog entries using networks: '{networks}', stations: '{stations}', start: '{start_date.isoformat()}', end: '{end_date.isoformat()}' started!"
136
179
  )
137
180
 
138
- self.update_availability_daily(networks, stations, start_date, end_date)
139
- self.update_availability_continuous(networks, stations, start_date, end_date)
181
+ self.update_availability_daily(
182
+ networks, stations, start_date, end_date, locations, channels
183
+ )
184
+ self.update_availability_continuous(
185
+ networks, stations, start_date, end_date, locations, channels
186
+ )
140
187
 
141
188
  logger.info(
142
189
  f"Processing WFCatalog entries using networks: '{networks}', stations: '{stations}', start: '{start_date.isoformat()}', end: '{end_date.isoformat()}' completed!"