forcingkit-client 0.2.1__tar.gz → 0.3.0__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.2.1
3
+ Version: 0.3.0
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
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "forcingkit-client"
7
- version = "0.2.1"
7
+ version = "0.3.0"
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.2.1"
18
+ __version__ = "0.3.0"
@@ -8,6 +8,7 @@ chunk cache. A second request for the same store is answered from the cache.
8
8
  import asyncio
9
9
  import hashlib
10
10
  import io
11
+ import logging
11
12
  import os
12
13
  import time
13
14
  import zipfile
@@ -24,6 +25,8 @@ import xarray as xr
24
25
  from .schema import normalise
25
26
  from .store import open_remote
26
27
 
28
+ log = logging.getLogger(__name__)
29
+
27
30
  BBox: TypeAlias = Sequence[float] # (west, south, east, north), degrees
28
31
  TimeLike: TypeAlias = str | datetime | pd.Timestamp | np.datetime64
29
32
 
@@ -117,6 +120,18 @@ def _waves_request(bbox, start, hours, wfo, grid, cache_bust):
117
120
  }
118
121
 
119
122
 
123
+ def _volume_request(bbox, start, hours, variables, layers, cache_bust):
124
+ return {
125
+ "bbox": _bbox(bbox),
126
+ "start_time": iso_utc(start),
127
+ "hours": int(hours),
128
+ "source": "necofs",
129
+ "variables": list(variables) if variables is not None else None,
130
+ "layers": [int(k) for k in layers] if layers is not None else None,
131
+ "cache_bust": bool(cache_bust),
132
+ }
133
+
134
+
120
135
  def _ndbc_dataset(data: Dict[str, Any]) -> xr.Dataset:
121
136
  """The /api/v1/ndbc payload as one Dataset on a shared time axis (outer join)."""
122
137
  parts = []
@@ -200,12 +215,35 @@ class _Base:
200
215
  poll_s: float = 5.0,
201
216
  timeout_s: float = 3 * 3600.0,
202
217
  on_progress: Optional[ProgressCallback] = None,
218
+ attempts: int = 4,
219
+ retry_wait_s: float = 2.0,
203
220
  ):
204
221
  self.base_url = base_url.rstrip("/")
205
222
  self.cache_dir = Path(cache_dir).expanduser()
206
223
  self.poll_s = poll_s
207
224
  self.timeout_s = timeout_s
208
225
  self.on_progress = on_progress
226
+ self.attempts = max(1, attempts)
227
+ self.retry_wait_s = retry_wait_s
228
+
229
+ def _retry_wait(
230
+ self, method: str, url: str, error: Exception, attempt: int
231
+ ) -> Optional[float]:
232
+ """Seconds to wait before retrying a job request that failed in transport (a failed name
233
+ lookup, a refused or reset connection, a timeout), or None when its attempts are spent.
234
+ Submitting a job again is safe: the service keys a job by its request."""
235
+ if attempt >= self.attempts:
236
+ return None
237
+ log.warning(
238
+ "%s %s failed (%s: %s); retry %d of %d",
239
+ method,
240
+ url,
241
+ type(error).__name__,
242
+ error,
243
+ attempt,
244
+ self.attempts - 1,
245
+ )
246
+ return self.retry_wait_s * attempt
209
247
 
210
248
  def _url(self, path: str) -> str:
211
249
  return f"{self.base_url}{path}"
@@ -294,8 +332,20 @@ class Client(_Base):
294
332
  def __exit__(self, *exc: Any) -> None:
295
333
  self.close()
296
334
 
335
+ def _send(self, method: str, url: str, **kwargs: Any) -> httpx.Response:
336
+ attempt = 1
337
+ while True:
338
+ try:
339
+ return self._http.request(method, url, **kwargs)
340
+ except httpx.TransportError as e:
341
+ wait = self._retry_wait(method, url, e, attempt)
342
+ if wait is None:
343
+ raise
344
+ time.sleep(wait)
345
+ attempt += 1
346
+
297
347
  def _wait(self, path: str, payload: Dict[str, Any]) -> Dict[str, Any]:
298
- job = self._check(self._http.post(self._url(path), json=payload))
348
+ job = self._check(self._send("POST", self._url(path), json=payload))
299
349
  deadline = time.monotonic() + self.timeout_s
300
350
  while (item := self._settled(job)) is None:
301
351
  if time.monotonic() > deadline:
@@ -303,7 +353,7 @@ class Client(_Base):
303
353
  f"job {job['job_id']} still {job['status']} after {self.timeout_s:.0f} s"
304
354
  )
305
355
  time.sleep(self.poll_s)
306
- job = self._check(self._http.get(self._local(job["status_url"])))
356
+ job = self._check(self._send("GET", self._local(job["status_url"])))
307
357
  return item
308
358
 
309
359
  def ocean(
@@ -371,6 +421,23 @@ class Client(_Base):
371
421
  payload = _waves_request(bbox, start, hours, wfo, grid, cache_bust)
372
422
  return self.open_item(self._wait("/api/v1/jobs/waves", payload))
373
423
 
424
+ def volume(
425
+ self,
426
+ bbox: BBox,
427
+ start: TimeLike,
428
+ hours: int,
429
+ variables: Optional[Sequence[str]] = None,
430
+ layers: Optional[Sequence[int]] = None,
431
+ cache_bust: bool = False,
432
+ ) -> xr.Dataset:
433
+ """NECOFS FVCOM GOM7 on its own mesh with every sigma layer (or `layers`, zero-based,
434
+ surface first), hourly from `start` (on the hour): element `u`, `v`, node `zeta` by
435
+ default (`variables` among u, v, ww, temp, salinity, zeta), with `h`, `siglay`,
436
+ `siglev`, `triangles` and node and element coordinates. Schema volume-v1; a cold
437
+ build can take minutes."""
438
+ payload = _volume_request(bbox, start, hours, variables, layers, cache_bust)
439
+ return self.open_item(self._wait("/api/v1/jobs/volume", payload))
440
+
374
441
  def ndbc(
375
442
  self,
376
443
  station_id: str,
@@ -451,8 +518,20 @@ class AsyncClient(_Base):
451
518
  async def __aexit__(self, *exc: Any) -> None:
452
519
  await self.aclose()
453
520
 
521
+ async def _send(self, method: str, url: str, **kwargs: Any) -> httpx.Response:
522
+ attempt = 1
523
+ while True:
524
+ try:
525
+ return await self._http.request(method, url, **kwargs)
526
+ except httpx.TransportError as e:
527
+ wait = self._retry_wait(method, url, e, attempt)
528
+ if wait is None:
529
+ raise
530
+ await asyncio.sleep(wait)
531
+ attempt += 1
532
+
454
533
  async def _wait(self, path: str, payload: Dict[str, Any]) -> Dict[str, Any]:
455
- job = self._check(await self._http.post(self._url(path), json=payload))
534
+ job = self._check(await self._send("POST", self._url(path), json=payload))
456
535
  deadline = time.monotonic() + self.timeout_s
457
536
  while (item := self._settled(job)) is None:
458
537
  if time.monotonic() > deadline:
@@ -460,7 +539,7 @@ class AsyncClient(_Base):
460
539
  f"job {job['job_id']} still {job['status']} after {self.timeout_s:.0f} s"
461
540
  )
462
541
  await asyncio.sleep(self.poll_s)
463
- job = self._check(await self._http.get(self._local(job["status_url"])))
542
+ job = self._check(await self._send("GET", self._local(job["status_url"])))
464
543
  return item
465
544
 
466
545
  async def ocean(
@@ -516,6 +595,19 @@ class AsyncClient(_Base):
516
595
  item = await self._wait("/api/v1/jobs/waves", payload)
517
596
  return await asyncio.to_thread(self.open_item, item)
518
597
 
598
+ async def volume(
599
+ self,
600
+ bbox: BBox,
601
+ start: TimeLike,
602
+ hours: int,
603
+ variables: Optional[Sequence[str]] = None,
604
+ layers: Optional[Sequence[int]] = None,
605
+ cache_bust: bool = False,
606
+ ) -> xr.Dataset:
607
+ payload = _volume_request(bbox, start, hours, variables, layers, cache_bust)
608
+ item = await self._wait("/api/v1/jobs/volume", payload)
609
+ return await asyncio.to_thread(self.open_item, item)
610
+
519
611
  async def ndbc(
520
612
  self,
521
613
  station_id: str,
@@ -7,13 +7,14 @@ one-shot donors write `legacy` stores in the donor's own conventions: `depth` po
7
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
- too and pass through unchanged.
10
+ too and pass through unchanged, as does a model's own mesh (`volume-v1`: an unstructured mesh with
11
+ sigma layers, which has no z axis to convert).
11
12
  """
12
13
 
13
14
  import numpy as np
14
15
  import xarray as xr
15
16
 
16
- KNOWN_SCHEMAS = ("z-v3", "legacy", "hrrr-atm-v1", "nwps-waves-v1")
17
+ KNOWN_SCHEMAS = ("z-v3", "legacy", "hrrr-atm-v1", "nwps-waves-v1", "volume-v1")
17
18
 
18
19
 
19
20
  class SchemaError(ValueError):
@@ -1,5 +1,6 @@
1
1
  """Client job flow against a mocked job API, with stores read from a real local HTTP server."""
2
2
 
3
+ import asyncio
3
4
  import io
4
5
  import json
5
6
  import zipfile
@@ -370,3 +371,127 @@ def test_async_ocean_passes_the_donor(store_server, tmp_path):
370
371
  service.posts[0]["donor"] == "doppio"
371
372
  and ds.attrs["forcingkit_donor"] == "doppio"
372
373
  )
374
+
375
+
376
+ def _flaky_jobs(fail: int, error=httpx.ConnectError):
377
+ """A job API whose first `fail` requests fail in transport; then a job that succeeds at once."""
378
+ calls = []
379
+
380
+ def service(request):
381
+ calls.append(request.method)
382
+ if len(calls) <= fail:
383
+ raise error(
384
+ "[Errno -3] Temporary failure in name resolution", request=request
385
+ )
386
+ return httpx.Response(
387
+ 200,
388
+ json={
389
+ "job_id": "obc_x",
390
+ "kind": "ocean",
391
+ "status": "failed",
392
+ "error": "stop",
393
+ },
394
+ )
395
+
396
+ return service, calls
397
+
398
+
399
+ def test_job_request_that_fails_in_transport_is_retried(tmp_path):
400
+ service, calls = _flaky_jobs(fail=2)
401
+ fk = Client(
402
+ "http://svc:9598",
403
+ cache_dir=tmp_path,
404
+ http=httpx.Client(transport=httpx.MockTransport(service)),
405
+ retry_wait_s=0.0,
406
+ )
407
+ with pytest.raises(ForcingkitError, match="stop"):
408
+ fk.ocean((-71.0, 41.2, -70.5, 41.7), T0, 3)
409
+ assert calls == ["POST", "POST", "POST"]
410
+
411
+
412
+ def test_job_request_gives_up_after_its_attempts(tmp_path):
413
+ service, calls = _flaky_jobs(fail=10)
414
+ fk = Client(
415
+ "http://svc:9598",
416
+ cache_dir=tmp_path,
417
+ http=httpx.Client(transport=httpx.MockTransport(service)),
418
+ attempts=3,
419
+ retry_wait_s=0.0,
420
+ )
421
+ with pytest.raises(httpx.ConnectError):
422
+ fk.ocean((-71.0, 41.2, -70.5, 41.7), T0, 3)
423
+ assert len(calls) == 3
424
+
425
+
426
+ def test_async_job_request_that_fails_in_transport_is_retried(tmp_path):
427
+ service, calls = _flaky_jobs(fail=1, error=httpx.ReadTimeout)
428
+
429
+ async def run():
430
+ fk = AsyncClient(
431
+ "http://svc:9598",
432
+ cache_dir=tmp_path,
433
+ http=httpx.AsyncClient(transport=httpx.MockTransport(service)),
434
+ retry_wait_s=0.0,
435
+ )
436
+ with pytest.raises(ForcingkitError, match="stop"):
437
+ await fk.ocean((-71.0, 41.2, -70.5, 41.7), T0, 3)
438
+
439
+ asyncio.run(run())
440
+ assert calls == ["POST", "POST"]
441
+
442
+
443
+ def _volume_store() -> xr.Dataset:
444
+ """A small store in the volume-v1 layout: one element, three nodes, two sigma layers."""
445
+ time = pd.date_range(T0, periods=2, freq="1h")
446
+ return xr.Dataset(
447
+ {
448
+ "u": (("time", "siglay", "element"), np.full((2, 2, 1), 0.25, np.float32)),
449
+ "v": (("time", "siglay", "element"), np.zeros((2, 2, 1), np.float32)),
450
+ "h": (("node",), np.array([10.0, 11.0, 12.0], np.float32)),
451
+ "siglay": (
452
+ ("siglay", "node"),
453
+ np.array([[-0.25] * 3, [-0.75] * 3], np.float32),
454
+ ),
455
+ "node_lon": (("node",), np.array([-72.5, -72.4, -72.45], np.float32)),
456
+ "node_lat": (("node",), np.array([41.0, 41.0, 41.1], np.float32)),
457
+ "triangles": (("element", "vertex"), np.array([[0, 1, 2]], np.int32)),
458
+ },
459
+ coords={"time": time},
460
+ attrs={"schema": "volume-v1", "complete": True},
461
+ )
462
+
463
+
464
+ def test_volume_job_flow(store_server, tmp_path):
465
+ root, base, _ = store_server
466
+ _publish(root, _volume_store())
467
+ service = FakeService(base, schema="volume-v1")
468
+ ds = _client(base, service, tmp_path).volume(BBOX, T0, 2, layers=[0, 1])
469
+ post = service.posts[0]
470
+ assert (post["source"], post["hours"], post["variables"], post["layers"]) == (
471
+ "necofs",
472
+ 2,
473
+ None,
474
+ [0, 1],
475
+ )
476
+ assert post["start_time"] == "2026-06-01T00:00:00"
477
+ assert ds.attrs["forcingkit_schema"] == "volume-v1"
478
+ assert (
479
+ ds["u"].dims == ("time", "siglay", "element")
480
+ and float(ds["u"].values[0, 1, 0]) == 0.25
481
+ )
482
+
483
+
484
+ async def test_async_volume(store_server, tmp_path):
485
+ root, base, _ = store_server
486
+ _publish(root, _volume_store())
487
+ service = FakeService(base, schema="volume-v1")
488
+ async with AsyncClient(
489
+ base,
490
+ cache_dir=tmp_path / "cache",
491
+ poll_s=0,
492
+ http=httpx.AsyncClient(transport=httpx.MockTransport(service)),
493
+ ) as fk:
494
+ ds = await fk.volume(BBOX, T0, 2, variables=["u", "v"], cache_bust=True)
495
+ post = service.posts[0]
496
+ assert post["variables"] == ["u", "v"] and post["cache_bust"] is True
497
+ assert ds["siglay"].shape == (2, 3)
@@ -42,3 +42,11 @@ def test_legacy_curvilinear_is_refused():
42
42
  def test_unknown_schema_is_refused():
43
43
  with pytest.raises(SchemaError, match="z-v9"):
44
44
  normalise(xr.Dataset(attrs={"schema": "z-v9"}))
45
+
46
+
47
+ def test_volume_stores_pass_through():
48
+ ds = xr.Dataset(
49
+ {"u": (("time", "siglay", "element"), np.zeros((1, 2, 1)))},
50
+ attrs={"schema": "volume-v1"},
51
+ )
52
+ assert normalise(ds) is ds
@@ -58,7 +58,7 @@ wheels = [
58
58
 
59
59
  [[package]]
60
60
  name = "forcingkit-client"
61
- version = "0.2.1"
61
+ version = "0.3.0"
62
62
  source = { editable = "." }
63
63
  dependencies = [
64
64
  { name = "httpx" },