ws-availability 1.1.1__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.1 → ws_availability-1.1.2}/PKG-INFO +3 -5
  2. {ws_availability-1.1.1 → ws_availability-1.1.2}/README.md +2 -4
  3. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/globals.py +1 -1
  4. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/settings.py +19 -2
  5. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/wfcatalog_client.py +64 -11
  6. {ws_availability-1.1.1 → ws_availability-1.1.2}/docker-compose.yml +4 -0
  7. {ws_availability-1.1.1 → ws_availability-1.1.2}/pyproject.toml +1 -1
  8. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test_data_access.py +3 -1
  9. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test_docker_compose.py +2 -0
  10. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test_query_no_endtime.py +7 -5
  11. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test_settings.py +62 -1
  12. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test_wfcatalog_query.py +116 -1
  13. {ws_availability-1.1.1 → ws_availability-1.1.2}/ws_availability.egg-info/PKG-INFO +3 -5
  14. {ws_availability-1.1.1 → ws_availability-1.1.2}/Dockerfile.api +0 -0
  15. {ws_availability-1.1.1 → ws_availability-1.1.2}/Dockerfile.cacher +0 -0
  16. {ws_availability-1.1.1 → ws_availability-1.1.2}/LICENSE +0 -0
  17. {ws_availability-1.1.1 → ws_availability-1.1.2}/MANIFEST.in +0 -0
  18. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/__init__.py +0 -0
  19. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/cli.py +0 -0
  20. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/data_access_layer.py +0 -0
  21. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/models.py +0 -0
  22. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/parameters.py +0 -0
  23. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/redis_client.py +0 -0
  24. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/restriction.py +0 -0
  25. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/root.py +0 -0
  26. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/scheduler.py +0 -0
  27. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/sentry.py +0 -0
  28. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/updater.py +0 -0
  29. {ws_availability-1.1.1 → ws_availability-1.1.2}/apps/utils.py +0 -0
  30. {ws_availability-1.1.1 → ws_availability-1.1.2}/setup.cfg +0 -0
  31. {ws_availability-1.1.1 → ws_availability-1.1.2}/templates/doc.html +0 -0
  32. {ws_availability-1.1.1 → ws_availability-1.1.2}/templates/wadl.xml +0 -0
  33. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test.py +0 -0
  34. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test_cli.py +0 -0
  35. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test_gunicorn_conf.py +0 -0
  36. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test_issue60_protection.py +0 -0
  37. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test_merge_parameter.py +0 -0
  38. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test_orderby.py +0 -0
  39. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test_restriction.py +0 -0
  40. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test_updater.py +0 -0
  41. {ws_availability-1.1.1 → ws_availability-1.1.2}/tests/test_wfcatalog_filtering.py +0 -0
  42. {ws_availability-1.1.1 → ws_availability-1.1.2}/views/main.js +0 -0
  43. {ws_availability-1.1.1 → ws_availability-1.1.2}/ws_availability.egg-info/SOURCES.txt +0 -0
  44. {ws_availability-1.1.1 → ws_availability-1.1.2}/ws_availability.egg-info/dependency_links.txt +0 -0
  45. {ws_availability-1.1.1 → ws_availability-1.1.2}/ws_availability.egg-info/entry_points.txt +0 -0
  46. {ws_availability-1.1.1 → ws_availability-1.1.2}/ws_availability.egg-info/requires.txt +0 -0
  47. {ws_availability-1.1.1 → 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.1
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
@@ -134,11 +134,13 @@ Everything lives in `config.py` (copied from `config.py.sample`, gitignored so u
134
134
 
135
135
  | Key | Default | Description |
136
136
  |-----|---------|-------------|
137
+ | `MONGODB_ENGINE` | `mongodb` | Database engine: `mongodb`, or `docdb` for Amazon DocumentDB. |
137
138
  | `MONGODB_HOST` | `host.docker.internal` | WFCatalog MongoDB host. |
138
139
  | `MONGODB_PORT` | `27017` | MongoDB port. |
139
140
  | `MONGODB_USR` / `MONGODB_PWD` | empty | MongoDB credentials (leave empty if no auth). |
140
141
  | `MONGODB_NAME` | `wfrepo` | Database name; also used as `authSource` unless `MONGODB_AUTH_SOURCE` is set. |
141
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. |
142
144
  | `FDSNWS_STATION_URL` | `https://orfeus-eu.org/fdsnws/station/1/query` | FDSNWS-Station endpoint to harvest restriction info from. |
143
145
  | `CACHE_HOST` | `cache` | Redis host. |
144
146
  | `CACHE_PORT` | `6379` | Redis port. |
@@ -263,7 +265,3 @@ If the service isn't working — often right after an upgrade — it's usually a
263
265
  Lines prefixed `>` are keys present in the sample but missing from your `config.py` — add them.
264
266
 
265
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.
266
-
267
- ## References
268
-
269
- 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. 💐
@@ -115,11 +115,13 @@ Everything lives in `config.py` (copied from `config.py.sample`, gitignored so u
115
115
 
116
116
  | Key | Default | Description |
117
117
  |-----|---------|-------------|
118
+ | `MONGODB_ENGINE` | `mongodb` | Database engine: `mongodb`, or `docdb` for Amazon DocumentDB. |
118
119
  | `MONGODB_HOST` | `host.docker.internal` | WFCatalog MongoDB host. |
119
120
  | `MONGODB_PORT` | `27017` | MongoDB port. |
120
121
  | `MONGODB_USR` / `MONGODB_PWD` | empty | MongoDB credentials (leave empty if no auth). |
121
122
  | `MONGODB_NAME` | `wfrepo` | Database name; also used as `authSource` unless `MONGODB_AUTH_SOURCE` is set. |
122
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. |
123
125
  | `FDSNWS_STATION_URL` | `https://orfeus-eu.org/fdsnws/station/1/query` | FDSNWS-Station endpoint to harvest restriction info from. |
124
126
  | `CACHE_HOST` | `cache` | Redis host. |
125
127
  | `CACHE_PORT` | `6379` | Redis port. |
@@ -244,7 +246,3 @@ If the service isn't working — often right after an upgrade — it's usually a
244
246
  Lines prefixed `>` are keys present in the sample but missing from your `config.py` — add them.
245
247
 
246
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.
247
-
248
- ## References
249
-
250
- 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. 💐
@@ -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.1"
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
@@ -17,7 +17,7 @@ from datetime import datetime, timedelta
17
17
  from typing import Any
18
18
 
19
19
  from .restriction import RestrictionInventory
20
- from .globals import Error
20
+ from .globals import Error, START, END
21
21
 
22
22
  try:
23
23
  import sentry_sdk
@@ -63,6 +63,23 @@ from apps.settings import settings
63
63
  # Global DB Client to prevent thread exhaustion
64
64
  DB_CLIENT = None
65
65
 
66
+ def _db_client_kwargs() -> dict:
67
+ """Engine-specific MongoClient arguments."""
68
+ if settings.mongodb_engine == "docdb":
69
+ return {
70
+ "authSource": settings.mongodb_auth_source or "admin",
71
+ "tls": True,
72
+ "tlsCAFile": settings.docdb_ca_path,
73
+ "replicaSet": "rs0",
74
+ "readPreference": "secondaryPreferred",
75
+ "directConnection": False,
76
+ }
77
+ return {
78
+ "authSource": settings.mongodb_auth_source or settings.mongodb_name,
79
+ "directConnection": True,
80
+ }
81
+
82
+
66
83
  def get_db_client():
67
84
  global DB_CLIENT
68
85
  if DB_CLIENT is None:
@@ -76,12 +93,11 @@ def get_db_client():
76
93
  settings.mongodb_port,
77
94
  username=settings.mongodb_usr,
78
95
  password=settings.mongodb_pwd,
79
- authSource=settings.mongodb_auth_source or settings.mongodb_name,
80
96
  maxPoolSize=pool_size,
81
97
  connect=False,
82
- directConnection=True,
83
98
  retryReads=False,
84
- retryWrites=False
99
+ retryWrites=False,
100
+ **_db_client_kwargs(),
85
101
  )
86
102
  try:
87
103
  db = DB_CLIENT.get_database(settings.mongodb_name)
@@ -134,7 +150,7 @@ def mongo_request(paramslist: list[dict]) -> tuple[list[dict], list[list[Any]]]:
134
150
  if _should_fanout(start, end):
135
151
  shard_results = _run_fanout(db, qry, start, end, include_restricted)
136
152
  for shard in shard_results:
137
- result += shard
153
+ result += _drop_outside_window(shard, params["start"], params["end"])
138
154
  if len(result) > settings.max_data_rows:
139
155
  # Stop early: the row cap is enforced in get_output().
140
156
  break
@@ -143,7 +159,8 @@ def mongo_request(paramslist: list[dict]) -> tuple[list[dict], list[list[Any]]]:
143
159
  cursor = db.availability.find(
144
160
  qry, projection=PROJ
145
161
  ).limit(settings.max_data_rows + 1)
146
- result += _apply_restricted_bit(cursor, include_restricted)
162
+ rows = _apply_restricted_bit(cursor, include_restricted)
163
+ result += _drop_outside_window(rows, params["start"], params["end"])
147
164
 
148
165
  # Result needs to be sorted, this seems to be required by the fusion step
149
166
  result.sort(key=lambda x: (x[0], x[1], x[2], x[3], x[4]))
@@ -167,12 +184,32 @@ def _build_query(params: dict, start: datetime | None, end: datetime | None) ->
167
184
  qry["loc"] = {"$in": params["location"].split(",")}
168
185
  if params["channel"] != "*":
169
186
  qry["cha"] = {"$in": params["channel"].split(",")}
187
+ qry.update(_time_filter(start, end))
188
+ if params["quality"] != "*":
189
+ qry["qlt"] = {"$in": params["quality"].split(",")}
190
+ return qry
191
+
192
+
193
+ def _time_filter(start: datetime | None, end: datetime | None) -> dict:
194
+ """Overlap filter on [start, end): ts < end AND te > start.
195
+
196
+ `te > start` alone gives the index no lower bound on `ts`, so MongoDB
197
+ would scan every record of each matching channel from the start of the
198
+ archive (Sentry: one-day request killed by the 600 s Gunicorn timeout).
199
+ The availability view stores segments cut per day, so a segment that
200
+ overlaps the window cannot start more than max_segment_days before it.
201
+ max_segment_days = 0 turns the bound off.
202
+ """
203
+ qry: dict = {}
204
+ ts: dict = {}
205
+ if start is not None and settings.max_segment_days > 0:
206
+ ts["$gte"] = start - timedelta(days=settings.max_segment_days)
170
207
  if end is not None:
171
- qry["ts"] = {"$lt": end}
208
+ ts["$lt"] = end
209
+ if ts:
210
+ qry["ts"] = ts
172
211
  if start is not None:
173
212
  qry["te"] = {"$gt": start}
174
- if params["quality"] != "*":
175
- qry["qlt"] = {"$in": params["quality"].split(",")}
176
213
  return qry
177
214
 
178
215
 
@@ -212,8 +249,7 @@ def _run_shard(
212
249
  ) -> list[list[Any]]:
213
250
  """Execute a single time-window shard and return restricted-filtered rows."""
214
251
  shard_qry = dict(qry_base)
215
- shard_qry["te"] = {"$gt": w_start}
216
- shard_qry["ts"] = {"$lt": w_end}
252
+ shard_qry.update(_time_filter(w_start, w_end))
217
253
 
218
254
  with _sentry_span(
219
255
  "db.mongo.shard",
@@ -251,6 +287,23 @@ def _run_fanout(
251
287
  )
252
288
 
253
289
 
290
+ def _drop_outside_window(
291
+ rows: list[list[Any]], start: datetime | None, end: datetime | None
292
+ ) -> list[list[Any]]:
293
+ """Keep only the rows that overlap the requested [start, end).
294
+
295
+ crop_datetimes() widens the query to whole days (and always adds a day
296
+ to `end`), so MongoDB also returns segments outside the requested
297
+ window. select_columns() only trims the edges of each row, so such a
298
+ segment came out with its end before its start, e.g. a request ending
299
+ 2016-11-07 showed "2016-11-07T05:36:34 2016-11-07T00:00:00".
300
+ """
301
+ return [
302
+ row for row in rows
303
+ if (end is None or row[START] < end) and (start is None or row[END] > start)
304
+ ]
305
+
306
+
254
307
  def crop_datetimes(params: dict) -> tuple[datetime | None, datetime | None]:
255
308
  """
256
309
  Extracts and normalizes start/end datetimes for querying.
@@ -32,6 +32,8 @@ services:
32
32
  # it being baked into the image) is what makes the pre-built GHCR images
33
33
  # usable: pull, set config.py, run — no rebuild. Read-only by design.
34
34
  - ./config.py:/appli/config.py:ro
35
+ # Uncomment if (MONGODB_ENGINE = "docdb")
36
+ # - ./global-bundle.pem:/appli/global-bundle.pem:ro
35
37
  api:
36
38
  build:
37
39
  context: ./
@@ -66,6 +68,8 @@ services:
66
68
  - seccomp:unconfined
67
69
  volumes:
68
70
  - ./config.py:/appli/config.py:ro
71
+ # Uncomment if (MONGODB_ENGINE = "docdb")
72
+ # - ./global-bundle.pem:/appli/global-bundle.pem:ro
69
73
  mem_limit: 2g
70
74
  memswap_limit: 2g
71
75
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ws-availability"
7
- version = "1.1.1"
7
+ version = "1.1.2"
8
8
  description = "Add your description here"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.13"
@@ -73,7 +73,9 @@ class TestDataAccess(unittest.TestCase):
73
73
  cursor = MagicMock()
74
74
  cursor.limit.return_value = iter(["fake_cursor"])
75
75
  self.mock_collection.find.return_value = cursor
76
- self.mock_apply_restricted.return_value = ["fake_result"]
76
+ self.mock_apply_restricted.return_value = [
77
+ ["NL", "HGN", "--", "BHZ", "D", 100.0, datetime(2023, 1, 1), datetime(2023, 1, 2), None, "OPEN"]
78
+ ]
77
79
 
78
80
  # Act
79
81
  queries, results = wfcatalog_client.mongo_request(params)
@@ -23,12 +23,14 @@ COMPOSE_PATH = Path(__file__).resolve().parents[1] / "docker-compose.yml"
23
23
  # api/cacher service env block, the operator's config.py will be silently
24
24
  # overridden — the LMU/Tobias bug.
25
25
  CONFIG_PY_ONLY_KEYS = {
26
+ "MONGODB_ENGINE",
26
27
  "MONGODB_HOST",
27
28
  "MONGODB_PORT",
28
29
  "MONGODB_USR",
29
30
  "MONGODB_PWD",
30
31
  "MONGODB_NAME",
31
32
  "MONGODB_AUTH_SOURCE",
33
+ "DOCDB_CA_PATH",
32
34
  "FDSNWS_STATION_URL",
33
35
  "SENTRY_DSN",
34
36
  "SENTRY_TRACES_SAMPLE_RATE",
@@ -10,7 +10,7 @@ import unittest
10
10
  import sys
11
11
  from pathlib import Path
12
12
  from unittest.mock import patch, MagicMock
13
- from datetime import datetime
13
+ from datetime import datetime, timedelta
14
14
 
15
15
  # Add parent directory to path to import apps
16
16
  sys.path.insert(0, str(Path(__file__).parent.parent))
@@ -70,16 +70,18 @@ class TestQueryNoEndtime(unittest.TestCase):
70
70
  self.assertIn("te", query)
71
71
  self.assertEqual(query["te"], {"$gt": datetime(2025, 12, 1, 0, 0, 0)})
72
72
 
73
- # Should NOT have ts constraint (because end is None)
74
- self.assertNotIn("ts", query)
73
+ # No end: ts gets only the lower bound (start - MAX_SEGMENT_DAYS), no $lt
74
+ self.assertEqual(
75
+ query["ts"],
76
+ {"$gte": datetime(2025, 12, 1) - timedelta(days=wfcatalog_client.settings.max_segment_days)},
77
+ )
75
78
 
76
79
  # Verify find was called with the correct query
77
80
  mock_collection.find.assert_called_once()
78
81
  actual_query = mock_collection.find.call_args[0][0]
79
82
 
80
83
  # The actual query should NOT contain {"ts": {"$lt": None}}
81
- if "ts" in actual_query:
82
- self.assertIsNotNone(actual_query["ts"].get("$lt"))
84
+ self.assertNotIn("$lt", actual_query["ts"])
83
85
 
84
86
 
85
87
  if __name__ == "__main__":
@@ -68,6 +68,51 @@ class TestSettings:
68
68
  del os.environ["MONGODB_AUTH_SOURCE"]
69
69
  del os.environ["MONGODB_NAME"]
70
70
 
71
+ def test_engine_defaults_to_mongodb(self):
72
+ """Existing config.py files have no MONGODB_ENGINE — must keep working as before"""
73
+ os.environ.pop("MONGODB_ENGINE", None)
74
+ settings = build_settings({"MONGODB_HOST": "db"})
75
+ assert settings.mongodb_engine == "mongodb"
76
+ assert settings.docdb_ca_path is None
77
+
78
+ def test_docdb_requires_ca_path(self):
79
+ """MONGODB_ENGINE=docdb without DOCDB_CA_PATH must fail at startup"""
80
+ with pytest.raises(ValueError, match="DOCDB_CA_PATH"):
81
+ Settings(MONGODB_ENGINE="docdb")
82
+
83
+ def test_docdb_with_ca_path(self):
84
+ settings = Settings(MONGODB_ENGINE="docdb", DOCDB_CA_PATH="/appli/global-bundle.pem")
85
+ assert settings.mongodb_engine == "docdb"
86
+
87
+
88
+ class TestDbClientKwargs:
89
+ """Engine-specific MongoClient arguments in wfcatalog_client."""
90
+
91
+ def test_mongodb_engine_keeps_previous_behaviour(self):
92
+ from unittest.mock import patch
93
+ from apps import wfcatalog_client
94
+
95
+ with patch.object(wfcatalog_client.settings, "mongodb_engine", "mongodb"), \
96
+ patch.object(wfcatalog_client.settings, "mongodb_auth_source", None), \
97
+ patch.object(wfcatalog_client.settings, "mongodb_name", "wfrepo"):
98
+ assert wfcatalog_client._db_client_kwargs() == {
99
+ "authSource": "wfrepo",
100
+ "directConnection": True,
101
+ }
102
+
103
+ def test_docdb_engine(self):
104
+ from unittest.mock import patch
105
+ from apps import wfcatalog_client
106
+
107
+ with patch.object(wfcatalog_client.settings, "mongodb_engine", "docdb"), \
108
+ patch.object(wfcatalog_client.settings, "mongodb_auth_source", None), \
109
+ patch.object(wfcatalog_client.settings, "docdb_ca_path", "/appli/global-bundle.pem"):
110
+ kwargs = wfcatalog_client._db_client_kwargs()
111
+ assert kwargs["authSource"] == "admin"
112
+ assert kwargs["tls"] is True
113
+ assert kwargs["tlsCAFile"] == "/appli/global-bundle.pem"
114
+ assert kwargs["directConnection"] is False
115
+
71
116
 
72
117
  class TestConfigPyVsEnvPrecedence:
73
118
  """Guard rails for the docker-compose ↔ config.py precedence bug.
@@ -86,7 +131,7 @@ class TestConfigPyVsEnvPrecedence:
86
131
 
87
132
  @staticmethod
88
133
  def _clear():
89
- for k in ("MONGODB_HOST", "MONGODB_NAME"):
134
+ for k in ("MONGODB_HOST", "MONGODB_NAME", "MONGODB_ENGINE", "MONGODB_PORT"):
90
135
  os.environ.pop(k, None)
91
136
 
92
137
  def setup_method(self, method):
@@ -121,6 +166,22 @@ class TestConfigPyVsEnvPrecedence:
121
166
  s = build_settings({"MONGODB_HOST": None})
122
167
  assert s.mongodb_host == "localhost" # Pydantic Field default
123
168
 
169
+ def test_empty_env_var_without_config_value_uses_default(self):
170
+ """MONGODB_ENGINE= / MONGODB_PORT= in the env (and absent from
171
+ config.py) must fall back to the default, not fail validation."""
172
+ os.environ["MONGODB_ENGINE"] = ""
173
+ os.environ["MONGODB_PORT"] = ""
174
+ s = build_settings({"MONGODB_HOST": "db"})
175
+ assert s.mongodb_engine == "mongodb"
176
+ assert s.mongodb_port == 27017
177
+
178
+ def test_empty_legacy_value_uses_default(self):
179
+ """config.py.sample does os.environ.get("MONGODB_ENGINE", "mongodb"),
180
+ which yields "" when the env var is set but empty."""
181
+ s = build_settings({"MONGODB_ENGINE": "", "MONGODB_PORT": ""})
182
+ assert s.mongodb_engine == "mongodb"
183
+ assert s.mongodb_port == 27017
184
+
124
185
 
125
186
  class TestConfigSampleHasSaferGetters:
126
187
  """Lock in Tobias Megies's PR #62: config.py.sample must use
@@ -108,7 +108,8 @@ class TestWFCatalogQuery(unittest.TestCase):
108
108
  # So if end input is 2023-01-20, cropped end is 2023-01-21 00:00:00
109
109
  expected_end = params[0]["end"].replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
110
110
 
111
- self.assertEqual(qry["ts"], {"$lt": expected_end})
111
+ margin = timedelta(days=wfcatalog_client.settings.max_segment_days)
112
+ self.assertEqual(qry["ts"], {"$gte": params[0]["start"] - margin, "$lt": expected_end})
112
113
  self.assertEqual(qry["te"], {"$gt": params[0]["start"]})
113
114
 
114
115
  def test_fanout_disabled_runs_single_query(self):
@@ -238,6 +239,70 @@ class TestWFCatalogQuery(unittest.TestCase):
238
239
  self.assertEqual(len(results), 1)
239
240
  self.assertEqual(results[0][6], valid_segment["ts"]) # Index 6 is start time
240
241
 
242
+ def _seg(self, ts, te):
243
+ return {
244
+ "net": "NL", "sta": "HGN", "loc": "--", "cha": "BHZ", "qlt": "D", "srate": 100.0,
245
+ "ts": ts, "te": te, "created": datetime(2024, 1, 1), "count": 1, "restr": "OPEN",
246
+ }
247
+
248
+ def _request(self, start, end, docs):
249
+ params = [{
250
+ "network": "NL", "station": "HGN", "location": "--", "channel": "BHZ", "quality": "D",
251
+ "start": start, "end": end,
252
+ }]
253
+ with patch('apps.wfcatalog_client._expand_wildcards', side_effect=lambda x: x):
254
+ self._set_find_results(docs)
255
+ _, rows = wfcatalog_client.mongo_request(params)
256
+ return [(r[6], r[7]) for r in rows]
257
+
258
+ def test_drops_segments_of_the_day_after_a_midnight_endtime(self):
259
+ """endtime=2016-11-07 must not return segments from 7 Nov (they came
260
+ out as "2016-11-07T05:36:34 2016-11-07T00:00:00")."""
261
+ d = datetime
262
+ docs = [
263
+ self._seg(d(2016, 11, 6, 21, 10, 51), d(2016, 11, 7)),
264
+ self._seg(d(2016, 11, 7, 5, 36, 34), d(2016, 11, 7, 8, 24, 29)),
265
+ self._seg(d(2016, 11, 7, 9, 0, 36), d(2016, 11, 7, 10, 20, 40)),
266
+ ]
267
+ rows = self._request(d(2016, 11, 6), d(2016, 11, 7), docs)
268
+ self.assertEqual(rows, [(d(2016, 11, 6, 21, 10, 51), d(2016, 11, 7))])
269
+
270
+ def test_sub_day_window_keeps_only_overlapping_segments(self):
271
+ d = datetime
272
+ docs = [
273
+ self._seg(d(2016, 11, 6, 0, 0), d(2016, 11, 6, 5, 0)), # before 06:00
274
+ self._seg(d(2016, 11, 6, 5, 30), d(2016, 11, 6, 7, 0)), # crosses 06:00
275
+ self._seg(d(2016, 11, 6, 8, 0), d(2016, 11, 6, 13, 0)), # crosses 12:00
276
+ self._seg(d(2016, 11, 6, 14, 0), d(2016, 11, 7, 0, 0)), # after 12:00
277
+ ]
278
+ rows = self._request(d(2016, 11, 6, 6), d(2016, 11, 6, 12), docs)
279
+ self.assertEqual([r[0] for r in rows], [d(2016, 11, 6, 5, 30), d(2016, 11, 6, 8, 0)])
280
+
281
+ def test_segments_touching_the_window_edges_are_dropped(self):
282
+ d = datetime
283
+ docs = [
284
+ self._seg(d(2016, 11, 5), d(2016, 11, 6)), # ends exactly at start
285
+ self._seg(d(2016, 11, 6), d(2016, 11, 7)), # the requested day
286
+ self._seg(d(2016, 11, 7), d(2016, 11, 8)), # starts exactly at end
287
+ ]
288
+ rows = self._request(d(2016, 11, 6), d(2016, 11, 7), docs)
289
+ self.assertEqual(rows, [(d(2016, 11, 6), d(2016, 11, 7))])
290
+
291
+
292
+ class TestDropOutsideWindow(unittest.TestCase):
293
+
294
+ @staticmethod
295
+ def row(ts, te):
296
+ return ["NL", "HGN", "--", "BHZ", "D", 100.0, ts, te, None, "OPEN"]
297
+
298
+ def test_open_ended_window(self):
299
+ d = datetime
300
+ rows = [self.row(d(2020, 1, 1), d(2020, 1, 2)), self.row(d(2020, 1, 3), d(2020, 1, 4))]
301
+ f = wfcatalog_client._drop_outside_window
302
+ self.assertEqual(f(rows, None, None), rows)
303
+ self.assertEqual(f(rows, d(2020, 1, 2), None), rows[1:])
304
+ self.assertEqual(f(rows, None, d(2020, 1, 3)), rows[:1])
305
+
241
306
 
242
307
  class TestBuildQueryFieldOrder(unittest.TestCase):
243
308
  """Lock in the #51 fix: query field order must match the compound index
@@ -276,5 +341,55 @@ class TestBuildQueryFieldOrder(unittest.TestCase):
276
341
  self.assertEqual(list(qry.keys()), ["net", "loc", "ts", "te"])
277
342
 
278
343
 
344
+
345
+ class TestTimeFilterLowerBound(unittest.TestCase):
346
+ """The overlap filter must give the index a lower bound on ts (Sentry:
347
+ a one-day request scanned each channel's whole history and was killed
348
+ by the 600 s Gunicorn timeout)."""
349
+
350
+ PARAMS = {"network": "HL", "station": "*", "location": "*", "channel": "HHZ", "quality": "*"}
351
+
352
+ def test_ts_has_lower_bound_of_max_segment_days(self):
353
+ with patch.object(wfcatalog_client.settings, "max_segment_days", 2):
354
+ qry = wfcatalog_client._build_query(
355
+ self.PARAMS, datetime(2016, 11, 6), datetime(2016, 11, 7))
356
+ self.assertEqual(qry["ts"], {"$gte": datetime(2016, 11, 4), "$lt": datetime(2016, 11, 7)})
357
+ self.assertEqual(qry["te"], {"$gt": datetime(2016, 11, 6)})
358
+
359
+ def test_zero_disables_lower_bound(self):
360
+ with patch.object(wfcatalog_client.settings, "max_segment_days", 0):
361
+ qry = wfcatalog_client._build_query(
362
+ self.PARAMS, datetime(2016, 11, 6), datetime(2016, 11, 7))
363
+ self.assertEqual(qry["ts"], {"$lt": datetime(2016, 11, 7)})
364
+
365
+ def test_no_start_means_no_lower_bound(self):
366
+ qry = wfcatalog_client._build_query(self.PARAMS, None, datetime(2016, 11, 7))
367
+ self.assertEqual(qry["ts"], {"$lt": datetime(2016, 11, 7)})
368
+ self.assertNotIn("te", qry)
369
+
370
+ def test_segment_crossing_midnight_still_matches(self):
371
+ """A segment that starts the evening before the window must be kept."""
372
+ with patch.object(wfcatalog_client.settings, "max_segment_days", 2):
373
+ qry = wfcatalog_client._build_query(
374
+ self.PARAMS, datetime(2016, 11, 6), datetime(2016, 11, 7))
375
+ ts, te = datetime(2016, 11, 5, 22), datetime(2016, 11, 6, 3)
376
+ self.assertTrue(qry["ts"]["$gte"] <= ts < qry["ts"]["$lt"] and te > qry["te"]["$gt"])
377
+
378
+ def test_fanout_shards_carry_lower_bound(self):
379
+ db = MagicMock()
380
+ db.availability.find.return_value.limit.return_value = []
381
+ with patch.object(wfcatalog_client.settings, "max_segment_days", 2):
382
+ wfcatalog_client._run_shard(
383
+ db, {"net": {"$in": ["HL"]}}, datetime(2024, 2, 1), datetime(2024, 3, 1), False)
384
+ qry = db.availability.find.call_args[0][0]
385
+ self.assertEqual(qry["ts"], {"$gte": datetime(2024, 1, 30), "$lt": datetime(2024, 3, 1)})
386
+ self.assertEqual(qry["te"], {"$gt": datetime(2024, 2, 1)})
387
+
388
+ def test_negative_margin_rejected(self):
389
+ from apps.settings import Settings
390
+ with self.assertRaises(Exception):
391
+ Settings(MAX_SEGMENT_DAYS=-1)
392
+
393
+
279
394
  if __name__ == '__main__':
280
395
  unittest.main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ws-availability
3
- Version: 1.1.1
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
@@ -134,11 +134,13 @@ Everything lives in `config.py` (copied from `config.py.sample`, gitignored so u
134
134
 
135
135
  | Key | Default | Description |
136
136
  |-----|---------|-------------|
137
+ | `MONGODB_ENGINE` | `mongodb` | Database engine: `mongodb`, or `docdb` for Amazon DocumentDB. |
137
138
  | `MONGODB_HOST` | `host.docker.internal` | WFCatalog MongoDB host. |
138
139
  | `MONGODB_PORT` | `27017` | MongoDB port. |
139
140
  | `MONGODB_USR` / `MONGODB_PWD` | empty | MongoDB credentials (leave empty if no auth). |
140
141
  | `MONGODB_NAME` | `wfrepo` | Database name; also used as `authSource` unless `MONGODB_AUTH_SOURCE` is set. |
141
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. |
142
144
  | `FDSNWS_STATION_URL` | `https://orfeus-eu.org/fdsnws/station/1/query` | FDSNWS-Station endpoint to harvest restriction info from. |
143
145
  | `CACHE_HOST` | `cache` | Redis host. |
144
146
  | `CACHE_PORT` | `6379` | Redis port. |
@@ -263,7 +265,3 @@ If the service isn't working — often right after an upgrade — it's usually a
263
265
  Lines prefixed `>` are keys present in the sample but missing from your `config.py` — add them.
264
266
 
265
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.
266
-
267
- ## References
268
-
269
- 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. 💐
File without changes