Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 19 additions & 11 deletions kerchunk/combine.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import asyncio
import collections.abc
import io
import logging
import re
from typing import List
import warnings

import fsspec
import fsspec.compression
import fsspec.utils
import numpy as np
import numcodecs
Expand All @@ -18,6 +20,14 @@
logger = logging.getLogger("kerchunk.combine")


def _load_json(data, compression=None):
"""Decode JSON references from raw bytes, decompressing them first if needed"""
if compression:
with fsspec.compression.compr[compression](io.BytesIO(data), mode="rb") as f:
data = f.read()
return ujson.loads(data)


def drop(fields):
"""Generate example preprocessor removing given fields"""

Expand Down Expand Up @@ -271,24 +281,22 @@ def fss(self):
for path in self.path:
self._paths.append(path.get("templates", {}).get("u", None))
else:
self._paths = []
for of in fsspec.open_files(self.path, **self.target_options):
self._paths.append(of.full_name)
fs = fsspec.core.url_to_fs(
self.path[0], asynchronous=True, **self.target_options
)[0]
ofs = fsspec.open_files(self.path, **self.target_options)
self._paths = [of.full_name for of in ofs]
try:
# JSON path
fo_list = fs.cat(self.path)
fo_list = [ujson.loads(v) for v in fo_list.values()]
except (IOError, TypeError, ValueError):
# JSON path: fetch all reference files in one batch and
# decode them in the same order as the inputs
raw = ofs.fs.cat([of.path for of in ofs])
fo_list = [_load_json(raw[of.path], of.compression) for of in ofs]
except (IOError, KeyError, TypeError, ValueError):
# tries again sequentially in comprehension below
fo_list = self.path
fo_list = self._paths

self._fss = [
fsspec.filesystem(
"reference",
fo=fo,
target_options=self.target_options if isinstance(fo, str) else None,
remote_protocol=self.remote_protocol,
remote_options=self.remote_options,
)
Expand Down
73 changes: 73 additions & 0 deletions tests/test_combine.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import numpy as np
import dask.array as da
import pytest
import ujson
import xarray as xr
import zarr.storage

Expand Down Expand Up @@ -862,3 +863,75 @@ def test_chunk_error(refs):
with pytest.raises(ValueError) as e:
mzz.translate()
assert "chunk size mismatch" in str(e.value)


def _write_refs(path, refs, compression=None):
with fsspec.open(str(path), "wt", compression=compression) as f:
f.write(ujson.dumps(refs))


@pytest.mark.parametrize("compression", [None, "gzip"])
def test_paths_target_options(refs, tmp_path, compression):
paths = []
for name in ["single1", "single2"]:
path = tmp_path / f"{name}.json"
_write_refs(path, refs[name], compression=compression)
paths.append(str(path))
mzz = MultiZarrToZarr(
paths,
target_options={"compression": compression},
remote_protocol="memory",
concat_dims=["time"],
)
out = mzz.translate()
assert out["refs"]["data/0.0.0"] == ["memory:///single1.zarr/data/0.0.0"]
assert out["refs"]["data/1.0.0"] == ["memory:///single2.zarr/data/0.0.0"]


def test_paths_keep_input_order(refs, tmp_path):
# the file names sort the other way round from the order of the inputs
_write_refs(tmp_path / "b.json", refs["single1"])
_write_refs(tmp_path / "a.json", refs["single2"])
mzz = MultiZarrToZarr(
[str(tmp_path / "b.json"), str(tmp_path / "a.json")],
remote_protocol="memory",
concat_dims=["time"],
coo_map={"time": "INDEX"},
)
out = mzz.translate()
assert out["refs"]["data/0.0.0"] == ["memory:///single1.zarr/data/0.0.0"]
assert out["refs"]["data/1.0.0"] == ["memory:///single2.zarr/data/0.0.0"]


@pytest.fixture
def http_dir(tmp_path):
pytest.importorskip("aiohttp")
import functools
import http.server
import threading

class Handler(http.server.SimpleHTTPRequestHandler):
def log_message(self, *args):
pass

handler = functools.partial(Handler, directory=str(tmp_path))
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
yield tmp_path, f"http://127.0.0.1:{server.server_address[1]}"
server.shutdown()
server.server_close()


def test_paths_async_filesystem(refs, http_dir):
root, url = http_dir
for name in ["single1", "single2"]:
_write_refs(root / f"{name}.json", refs[name])
mzz = MultiZarrToZarr(
[f"{url}/single1.json", f"{url}/single2.json"],
remote_protocol="memory",
concat_dims=["time"],
)
out = mzz.translate()
assert out["refs"]["data/0.0.0"] == ["memory:///single1.zarr/data/0.0.0"]
assert out["refs"]["data/1.0.0"] == ["memory:///single2.zarr/data/0.0.0"]