forcingkit-client 0.1.0__tar.gz → 0.2.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: forcingkit-client
3
- Version: 0.1.0
3
+ Version: 0.2.1
4
4
  Summary: Lightweight Python client for a forcingkit service: ocean, atmosphere and station forcing as xarray, and forcing interpolated along a trajectory.
5
5
  Project-URL: Documentation, https://forcingkit.docs.lhzn.io/client.html
6
6
  Project-URL: Issues, https://github.com/lhzn-io/forcingkit/issues
@@ -35,7 +35,7 @@ from forcingkit_client import Client
35
35
 
36
36
  fk = Client("http://localhost:9598")
37
37
  box = (-70.9, 41.3, -70.6, 41.6) # west, south, east, north
38
- ocean = fk.ocean(box, "2025-07-01", 24) # u, v, temp, salt, zeta
38
+ ocean = fk.ocean(box, "2025-07-01", 24) # u, v, temp, salt, zeta; w from NECOFS
39
39
  air = fk.atmosphere(box, "2025-07-01", 24) # HRRR u10, v10, t2m, ...
40
40
 
41
41
  # lon, lat, time, z: one value per point; z in metres, positive up
@@ -11,7 +11,7 @@ from forcingkit_client import Client
11
11
 
12
12
  fk = Client("http://localhost:9598")
13
13
  box = (-70.9, 41.3, -70.6, 41.6) # west, south, east, north
14
- ocean = fk.ocean(box, "2025-07-01", 24) # u, v, temp, salt, zeta
14
+ ocean = fk.ocean(box, "2025-07-01", 24) # u, v, temp, salt, zeta; w from NECOFS
15
15
  air = fk.atmosphere(box, "2025-07-01", 24) # HRRR u10, v10, t2m, ...
16
16
 
17
17
  # lon, lat, time, z: one value per point; z in metres, positive up
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "forcingkit-client"
7
- version = "0.1.0"
7
+ version = "0.2.1"
8
8
  description = "Lightweight Python client for a forcingkit service: ocean, atmosphere and station forcing as xarray, and forcing interpolated along a trajectory."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -15,4 +15,4 @@ __all__ = [
15
15
  "trajectory_window",
16
16
  ]
17
17
 
18
- __version__ = "0.1.0"
18
+ __version__ = "0.2.1"
@@ -56,9 +56,16 @@ def _bbox(bbox: BBox) -> Dict[str, float]:
56
56
 
57
57
 
58
58
  def _ocean_request(
59
- bbox, start, hours, vertical_spacing_m, pad_cells, sponge_cells, **options
59
+ bbox,
60
+ start,
61
+ hours,
62
+ vertical_spacing_m,
63
+ pad_cells,
64
+ sponge_cells,
65
+ donor: Optional[str] = None,
66
+ **options,
60
67
  ):
61
- return {
68
+ request = {
62
69
  "bbox": _bbox(bbox),
63
70
  "start_date": iso_utc(start),
64
71
  "duration_hours": int(hours),
@@ -69,6 +76,22 @@ def _ocean_request(
69
76
  "sponge_cells": int(sponge_cells),
70
77
  **options,
71
78
  }
79
+ if donor:
80
+ request["donor"] = str(donor)
81
+ return request
82
+
83
+
84
+ def _check_donor(item: Dict[str, Any], donor: Optional[str]) -> Dict[str, Any]:
85
+ """`item`, unless a named `donor` is not the one that delivered it: a service older than the
86
+ `donor` option ignores it and ranks the donors, and its store must not pass for the named one."""
87
+ delivered = item["properties"].get("forcingkit:donor")
88
+ if donor and delivered != donor:
89
+ raise ForcingkitError(
90
+ f"asked for donor {donor!r} but store {item['id']} is from {delivered!r}; "
91
+ "the service may predate the donor option",
92
+ detail={"requested": donor, "delivered": delivered},
93
+ )
94
+ return item
72
95
 
73
96
 
74
97
  def _atmosphere_request(bbox, start, hours, resolution_deg, margin_deg, cache_bust):
@@ -238,6 +261,10 @@ class _Base:
238
261
  "forcingkit_schema": props.get("forcingkit:schema") or "",
239
262
  }
240
263
  )
264
+ # Ocean stores say where their vertical velocity comes from ("model", "continuity" or
265
+ # "none"); a service older than the property, and other kinds of store, leave it out.
266
+ if props.get("forcingkit:w_source"):
267
+ ds.attrs["forcingkit_w_source"] = props["forcingkit:w_source"]
241
268
  return ds
242
269
 
243
270
 
@@ -287,15 +314,31 @@ class Client(_Base):
287
314
  vertical_spacing_m: float = 2.0,
288
315
  pad_cells: int = 1,
289
316
  sponge_cells: int = 0,
317
+ donor: Optional[str] = None,
290
318
  **options: Any,
291
319
  ) -> xr.Dataset:
292
320
  """The parent ocean over `bbox` for `hours` from `start`: `u, v` (m/s), `temp` (deg C),
293
- `salt`, `zeta` (m) on `(time, z, lat, lon)`, z in metres positive up. Further `options`
294
- (`include_tides`, `allow_donor_fallback`, `cache_bust`, ...) pass through to the service."""
321
+ `salt`, `zeta` (m) on `(time, z, lat, lon)`, z in meters positive up, plus `w` (m/s,
322
+ upward; its origin in the `forcingkit_w_source` attribute).
323
+
324
+ `donor` names one parent model to use alone ("necofs", "hycom", "doppio", ...): the
325
+ service neither ranks nor falls back, and refuses an unknown id or a box outside that
326
+ model's domain. A store from any other donor (a service too old to know the option) is
327
+ refused here with ForcingkitError. Without it the service picks the donor. Further
328
+ `options` (`include_tides`, `allow_donor_fallback`, `cache_bust`, ...) pass through to
329
+ the service."""
295
330
  payload = _ocean_request(
296
- bbox, start, hours, vertical_spacing_m, pad_cells, sponge_cells, **options
331
+ bbox,
332
+ start,
333
+ hours,
334
+ vertical_spacing_m,
335
+ pad_cells,
336
+ sponge_cells,
337
+ donor=donor,
338
+ **options,
297
339
  )
298
- return self.open_item(self._wait("/api/v1/jobs/obc", payload))
340
+ item = _check_donor(self._wait("/api/v1/jobs/obc", payload), donor)
341
+ return self.open_item(item)
299
342
 
300
343
  def atmosphere(
301
344
  self,
@@ -428,12 +471,21 @@ class AsyncClient(_Base):
428
471
  vertical_spacing_m: float = 2.0,
429
472
  pad_cells: int = 1,
430
473
  sponge_cells: int = 0,
474
+ donor: Optional[str] = None,
431
475
  **options: Any,
432
476
  ) -> xr.Dataset:
477
+ """`Client.ocean` (including the `donor` option) for an asynchronous client."""
433
478
  payload = _ocean_request(
434
- bbox, start, hours, vertical_spacing_m, pad_cells, sponge_cells, **options
479
+ bbox,
480
+ start,
481
+ hours,
482
+ vertical_spacing_m,
483
+ pad_cells,
484
+ sponge_cells,
485
+ donor=donor,
486
+ **options,
435
487
  )
436
- item = await self._wait("/api/v1/jobs/obc", payload)
488
+ item = _check_donor(await self._wait("/api/v1/jobs/obc", payload), donor)
437
489
  return await asyncio.to_thread(self.open_item, item)
438
490
 
439
491
  async def atmosphere(
@@ -2,9 +2,9 @@
2
2
 
3
3
  The service writes two parent-ocean layouts. Schema `z-v3` (streamed donors) is already what the
4
4
  client returns: `u, v, temp, salt` on `(time, z, lat, lon)` with `z` in metres, positive up, and
5
- longitudes in -180..180. Older one-shot donors write `legacy` stores in the donor's own
6
- conventions: `depth` positive down, `latitude`/`longitude` names, and for HYCOM longitudes in
7
- 0..360. `normalise` brings those to the z-v3 conventions and refuses any schema it does not know,
5
+ longitudes in -180..180; NECOFS stores add `w`, the upward velocity, on the same axes. Older
6
+ one-shot donors write `legacy` stores in the donor's own conventions: `depth` positive down,
7
+ `latitude`/`longitude` names, and for HYCOM longitudes in 0..360. `normalise` brings those to the z-v3 conventions and refuses any schema it does not know,
8
8
  so a layout change fails here with a clear message instead of later on a variable name.
9
9
  The atmosphere (`hrrr-atm-v1`) and waves (`nwps-waves-v1`) stores are written in that convention
10
10
  too and pass through unchanged.
@@ -5,11 +5,18 @@ directory store that, on a miss, fetches the key from the server and keeps it, s
5
5
  read remotely the first time and from disk afterwards, and only the chunks actually read are ever
6
6
  transferred. The cache directory is keyed by store id and store version, so a store the server
7
7
  rebuilt under the same id is fetched afresh.
8
+
9
+ Each chunk read opens its own connection. A connection kept open between reads can go stale while
10
+ the caller waits on the next job (the service closes idle connections after a few seconds); a
11
+ request written to it may then get no answer at all, and the read hangs until its timeout. A read
12
+ that fails in transport (a timeout, a reset, a refused connection) is retried on a new connection.
8
13
  """
9
14
 
10
15
  import asyncio
16
+ import logging
11
17
  import os
12
18
  import threading
19
+ import time
13
20
  from pathlib import Path
14
21
  from typing import Any, Optional
15
22
 
@@ -17,26 +24,60 @@ import httpx
17
24
  import xarray as xr
18
25
  from zarr.storage import LocalStore
19
26
 
27
+ log = logging.getLogger(__name__)
28
+
20
29
 
21
30
  class CachingHTTPStore(LocalStore):
22
- def __init__(self, root: str | Path, url: str, timeout_s: float = 120.0):
31
+ def __init__(
32
+ self,
33
+ root: str | Path,
34
+ url: str,
35
+ timeout_s: float = 60.0,
36
+ attempts: int = 4,
37
+ retry_wait_s: float = 2.0,
38
+ ):
23
39
  os.makedirs(root, exist_ok=True)
24
40
  super().__init__(root, read_only=True)
25
41
  self.url = url.rstrip("/")
26
42
  self._timeout_s = timeout_s
43
+ self._attempts = max(1, attempts)
44
+ self._retry_wait_s = retry_wait_s
27
45
  self._http: Optional[httpx.Client] = None
28
46
  self._lock = threading.Lock()
29
47
 
30
48
  def _client(self) -> httpx.Client:
31
49
  with self._lock:
32
50
  if self._http is None:
33
- self._http = httpx.Client(timeout=self._timeout_s)
51
+ self._http = httpx.Client(
52
+ timeout=httpx.Timeout(self._timeout_s, connect=10.0),
53
+ limits=httpx.Limits(max_keepalive_connections=0),
54
+ )
34
55
  return self._http
35
56
 
57
+ def _get(self, key: str) -> httpx.Response:
58
+ """GET `key`, retrying a transport failure on a new connection."""
59
+ for attempt in range(1, self._attempts + 1):
60
+ try:
61
+ return self._client().get(f"{self.url}/{key}")
62
+ except httpx.TransportError as e:
63
+ if attempt == self._attempts:
64
+ raise
65
+ log.warning(
66
+ "store read %s/%s failed (%s: %s); retry %d of %d",
67
+ self.url,
68
+ key,
69
+ type(e).__name__,
70
+ e,
71
+ attempt,
72
+ self._attempts - 1,
73
+ )
74
+ time.sleep(self._retry_wait_s * attempt)
75
+ raise AssertionError("unreachable")
76
+
36
77
  def _fetch(self, key: str) -> bool:
37
78
  """Copy `key` from the server into the cache; False when the server has no such key
38
79
  (an unwritten chunk, which reads as the fill value)."""
39
- response = self._client().get(f"{self.url}/{key}")
80
+ response = self._get(key)
40
81
  if response.status_code == 404:
41
82
  return False
42
83
  response.raise_for_status()
@@ -136,9 +136,14 @@ def interpolate_points(
136
136
 
137
137
 
138
138
  def _provenance(prefix: str, ds: xr.Dataset) -> Dict[str, Any]:
139
+ """The store's identity as trajectory attributes; an ocean store also names where its w
140
+ comes from (`forcingkit_ocean_w_source`: "model", "continuity" or "none")."""
141
+ keys = ["store_id", "store_version", "donor", "schema"]
142
+ if "forcingkit_w_source" in ds.attrs:
143
+ keys.append("w_source")
139
144
  return {
140
145
  f"forcingkit_{prefix}_{key}": ds.attrs.get(f"forcingkit_{key}", "")
141
- for key in ("store_id", "store_version", "donor", "schema")
146
+ for key in keys
142
147
  }
143
148
 
144
149
 
@@ -17,15 +17,24 @@ STORE_ID = "obc_0123456789ab"
17
17
  BBOX = (-70.9, 41.3, -70.6, 41.6)
18
18
 
19
19
 
20
- def _item(base: str, store_id: str = STORE_ID, schema: str = "z-v3") -> dict:
20
+ def _item(
21
+ base: str,
22
+ store_id: str = STORE_ID,
23
+ schema: str = "z-v3",
24
+ w_source: str | None = None,
25
+ donor: str = "necofs",
26
+ ) -> dict:
27
+ props = {
28
+ "forcingkit:schema": schema,
29
+ "forcingkit:donor": donor,
30
+ "forcingkit:store_version": "1",
31
+ }
32
+ if w_source is not None:
33
+ props["forcingkit:w_source"] = w_source
21
34
  return {
22
35
  "type": "Feature",
23
36
  "id": store_id,
24
- "properties": {
25
- "forcingkit:schema": schema,
26
- "forcingkit:donor": "necofs",
27
- "forcingkit:store_version": "1",
28
- },
37
+ "properties": props,
29
38
  # The service names itself as it saw the request; the client re-roots on its own URL.
30
39
  "assets": {
31
40
  "zarr": {"href": f"http://elsewhere:9598/api/v1/stores/{store_id}.zarr"}
@@ -36,8 +45,16 @@ def _item(base: str, store_id: str = STORE_ID, schema: str = "z-v3") -> dict:
36
45
  class FakeService:
37
46
  """/api/v1/jobs: queued, then running, then `final` ('succeeded' or 'failed')."""
38
47
 
39
- def __init__(self, base: str, final: str = "succeeded", schema: str = "z-v3"):
48
+ def __init__(
49
+ self,
50
+ base: str,
51
+ final: str = "succeeded",
52
+ schema: str = "z-v3",
53
+ w_source: str | None = None,
54
+ donor: str = "necofs",
55
+ ):
40
56
  self.base, self.final, self.schema = base, final, schema
57
+ self.w_source, self.donor = w_source, donor
41
58
  self.posts: list[dict] = []
42
59
  self.polls = 0
43
60
 
@@ -48,7 +65,9 @@ class FakeService:
48
65
  "status": status,
49
66
  "error": "All OBC donors failed" if status == "failed" else None,
50
67
  "status_url": f"http://elsewhere:9598/api/v1/jobs/{STORE_ID}",
51
- "result": _item(self.base, schema=self.schema)
68
+ "result": _item(
69
+ self.base, schema=self.schema, w_source=self.w_source, donor=self.donor
70
+ )
52
71
  if status == "succeeded"
53
72
  else None,
54
73
  }
@@ -219,6 +238,21 @@ def test_interpolate_trajectory_through_client(store_server, tmp_path):
219
238
  )
220
239
  assert ds.attrs["forcingkit_ocean_store_id"] == STORE_ID
221
240
  assert ds.attrs["featureType"] == "trajectory"
241
+ # A service older than `forcingkit:w_source` leaves the attribute out.
242
+ assert "forcingkit_ocean_w_source" not in ds.attrs
243
+
244
+
245
+ @pytest.mark.parametrize("w_source", ["model", "continuity"])
246
+ def test_trajectory_names_where_w_comes_from(store_server, tmp_path, w_source):
247
+ root, base, _ = store_server
248
+ _publish(root, z_v3_store())
249
+ fk = _client(base, FakeService(base, w_source=w_source), tmp_path)
250
+ ocean = fk.ocean(BBOX, "2026-06-01T00:00:00Z", 6)
251
+ assert ocean.attrs["forcingkit_w_source"] == w_source
252
+ ds = fk.interpolate_trajectory(
253
+ np.array([-70.85]), np.array([41.35]), T0 + pd.to_timedelta([1.5], unit="h")
254
+ )
255
+ assert ds.attrs["forcingkit_ocean_w_source"] == w_source
222
256
 
223
257
 
224
258
  def _waves_store() -> xr.Dataset:
@@ -291,3 +325,48 @@ async def test_async_waves(store_server, tmp_path):
291
325
  ds = await fk.waves(BBOX, T0, 2)
292
326
  assert service.posts[0]["wfo"] == "okx" and service.posts[0]["grid"] == "CG1"
293
327
  assert float(ds["dir"].values[0, 1, 1]) == 90.0
328
+
329
+
330
+ def test_ocean_names_a_donor_only_when_asked(store_server, tmp_path):
331
+ root, base, _ = store_server
332
+ _publish(root, z_v3_store())
333
+ service = FakeService(base, donor="doppio")
334
+ fk = _client(base, service, tmp_path)
335
+ ds = fk.ocean(BBOX, "2026-06-01T00:00:00Z", 6, donor="doppio")
336
+ assert service.posts[0]["donor"] == "doppio"
337
+ assert ds.attrs["forcingkit_donor"] == "doppio"
338
+ fk.ocean(BBOX, "2026-06-01T00:00:00Z", 6)
339
+ assert "donor" not in service.posts[1]
340
+
341
+
342
+ def test_ocean_refuses_a_store_from_another_donor(store_server, tmp_path):
343
+ """A service older than the donor option ignores it and ranks the donors."""
344
+ root, base, _ = store_server
345
+ _publish(root, z_v3_store())
346
+ fk = _client(base, FakeService(base, donor="necofs"), tmp_path)
347
+ with pytest.raises(ForcingkitError, match="asked for donor 'doppio'") as err:
348
+ fk.ocean(BBOX, "2026-06-01T00:00:00Z", 6, donor="doppio")
349
+ assert err.value.detail == {"requested": "doppio", "delivered": "necofs"}
350
+
351
+
352
+ def test_async_ocean_passes_the_donor(store_server, tmp_path):
353
+ import asyncio
354
+
355
+ root, base, _ = store_server
356
+ _publish(root, z_v3_store())
357
+ service = FakeService(base, donor="doppio")
358
+
359
+ async def run():
360
+ fk = AsyncClient(
361
+ base,
362
+ cache_dir=tmp_path / "cache",
363
+ poll_s=0,
364
+ http=httpx.AsyncClient(transport=httpx.MockTransport(service)),
365
+ )
366
+ return await fk.ocean(BBOX, "2026-06-01T00:00:00Z", 6, donor="doppio")
367
+
368
+ ds = asyncio.run(run())
369
+ assert (
370
+ service.posts[0]["donor"] == "doppio"
371
+ and ds.attrs["forcingkit_donor"] == "doppio"
372
+ )
@@ -0,0 +1,64 @@
1
+ """CachingHTTPStore: chunk reads that fail in transport are retried on a new connection."""
2
+
3
+ import httpx
4
+ import pytest
5
+
6
+ from forcingkit_client.store import CachingHTTPStore
7
+
8
+
9
+ def _store(tmp_path, handler, attempts=3):
10
+ store = CachingHTTPStore(
11
+ tmp_path / "cache",
12
+ "http://svc/api/v1/stores/s.zarr",
13
+ attempts=attempts,
14
+ retry_wait_s=0.0,
15
+ )
16
+ store._http = httpx.Client(transport=httpx.MockTransport(handler))
17
+ return store
18
+
19
+
20
+ def test_read_that_times_out_is_retried(tmp_path):
21
+ calls = []
22
+
23
+ def handler(request):
24
+ calls.append(request.url.path)
25
+ if len(calls) == 1:
26
+ raise httpx.ReadTimeout("no answer", request=request)
27
+ return httpx.Response(200, content=b"chunk")
28
+
29
+ store = _store(tmp_path, handler)
30
+ assert store._fetch("u/0.0.0.0")
31
+ assert (tmp_path / "cache" / "u" / "0.0.0.0").read_bytes() == b"chunk"
32
+ assert calls == ["/api/v1/stores/s.zarr/u/0.0.0.0"] * 2
33
+
34
+
35
+ def test_read_gives_up_after_its_attempts(tmp_path):
36
+ calls = []
37
+
38
+ def handler(request):
39
+ calls.append(1)
40
+ raise httpx.ConnectError("refused", request=request)
41
+
42
+ store = _store(tmp_path, handler, attempts=3)
43
+ with pytest.raises(httpx.ConnectError):
44
+ store._fetch("u/0.0.0.0")
45
+ assert len(calls) == 3
46
+ assert not (tmp_path / "cache" / "u" / "0.0.0.0").exists()
47
+
48
+
49
+ def test_missing_chunk_is_not_retried(tmp_path):
50
+ calls = []
51
+
52
+ def handler(request):
53
+ calls.append(1)
54
+ return httpx.Response(404)
55
+
56
+ store = _store(tmp_path, handler)
57
+ assert not store._fetch("u/0.0.0.0")
58
+ assert len(calls) == 1
59
+
60
+
61
+ def test_connections_are_not_kept_between_reads(tmp_path):
62
+ store = CachingHTTPStore(tmp_path / "cache", "http://svc/s.zarr")
63
+ pool = store._client()._transport._pool
64
+ assert pool._max_keepalive_connections == 0
@@ -58,7 +58,7 @@ wheels = [
58
58
 
59
59
  [[package]]
60
60
  name = "forcingkit-client"
61
- version = "0.1.0"
61
+ version = "0.2.1"
62
62
  source = { editable = "." }
63
63
  dependencies = [
64
64
  { name = "httpx" },