reference.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. import base64
  2. import collections
  3. import io
  4. import itertools
  5. import logging
  6. import math
  7. import os
  8. from functools import lru_cache
  9. from itertools import chain
  10. from typing import TYPE_CHECKING, Literal
  11. import fsspec.core
  12. from fsspec.spec import AbstractBufferedFile
  13. try:
  14. import ujson as json
  15. except ImportError:
  16. if not TYPE_CHECKING:
  17. import json
  18. from fsspec.asyn import AsyncFileSystem
  19. from fsspec.callbacks import DEFAULT_CALLBACK
  20. from fsspec.core import filesystem, open, split_protocol
  21. from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
  22. from fsspec.utils import (
  23. isfilelike,
  24. merge_offset_ranges,
  25. other_paths,
  26. )
  27. logger = logging.getLogger("fsspec.reference")
  28. class ReferenceNotReachable(RuntimeError):
  29. def __init__(self, reference, target, *args):
  30. super().__init__(*args)
  31. self.reference = reference
  32. self.target = target
  33. def __str__(self):
  34. return f'Reference "{self.reference}" failed to fetch target {self.target}'
  35. def _first(d):
  36. return next(iter(d.values()))
  37. def _prot_in_references(path, references):
  38. ref = references.get(path)
  39. if isinstance(ref, (list, tuple)) and isinstance(ref[0], str):
  40. return split_protocol(ref[0])[0] if ref[0] else ref[0]
  41. def _protocol_groups(paths, references):
  42. if isinstance(paths, str):
  43. return {_prot_in_references(paths, references): [paths]}
  44. out = {}
  45. for path in paths:
  46. protocol = _prot_in_references(path, references)
  47. out.setdefault(protocol, []).append(path)
  48. return out
  49. class RefsValuesView(collections.abc.ValuesView):
  50. def __iter__(self):
  51. for val in self._mapping.zmetadata.values():
  52. yield json.dumps(val).encode()
  53. yield from self._mapping._items.values()
  54. for field in self._mapping.listdir():
  55. chunk_sizes = self._mapping._get_chunk_sizes(field)
  56. if len(chunk_sizes) == 0:
  57. yield self._mapping[field + "/0"]
  58. continue
  59. yield from self._mapping._generate_all_records(field)
  60. class RefsItemsView(collections.abc.ItemsView):
  61. def __iter__(self):
  62. return zip(self._mapping.keys(), self._mapping.values())
  63. def ravel_multi_index(idx, sizes):
  64. val = 0
  65. mult = 1
  66. for i, s in zip(idx[::-1], sizes[::-1]):
  67. val += i * mult
  68. mult *= s
  69. return val
  70. class LazyReferenceMapper(collections.abc.MutableMapping):
  71. """This interface can be used to read/write references from Parquet stores.
  72. It is not intended for other types of references.
  73. It can be used with Kerchunk's MultiZarrToZarr method to combine
  74. references into a parquet store.
  75. Examples of this use-case can be found here:
  76. https://fsspec.github.io/kerchunk/advanced.html?highlight=parquet#parquet-storage"""
  77. # import is class level to prevent numpy dep requirement for fsspec
  78. @property
  79. def np(self):
  80. import numpy as np
  81. return np
  82. @property
  83. def pd(self):
  84. import pandas as pd
  85. return pd
  86. def __init__(
  87. self,
  88. root,
  89. fs=None,
  90. out_root=None,
  91. cache_size=128,
  92. categorical_threshold=10,
  93. engine: Literal["fastparquet", "pyarrow"] = "fastparquet",
  94. ):
  95. """
  96. This instance will be writable, storing changes in memory until full partitions
  97. are accumulated or .flush() is called.
  98. To create an empty lazy store, use .create()
  99. Parameters
  100. ----------
  101. root : str
  102. Root of parquet store
  103. fs : fsspec.AbstractFileSystem
  104. fsspec filesystem object, default is local filesystem.
  105. cache_size : int, default=128
  106. Maximum size of LRU cache, where cache_size*record_size denotes
  107. the total number of references that can be loaded in memory at once.
  108. categorical_threshold : int
  109. Encode urls as pandas.Categorical to reduce memory footprint if the ratio
  110. of the number of unique urls to total number of refs for each variable
  111. is greater than or equal to this number. (default 10)
  112. engine: Literal["fastparquet","pyarrow"]
  113. Engine choice for reading parquet files. (default is "fastparquet")
  114. """
  115. self.root = root
  116. self.chunk_sizes = {}
  117. self.cat_thresh = categorical_threshold
  118. self.engine = engine
  119. self.cache_size = cache_size
  120. self.url = self.root + "/{field}/refs.{record}.parq"
  121. # TODO: derive fs from `root`
  122. self.fs = fsspec.filesystem("file") if fs is None else fs
  123. self.out_root = self.fs.unstrip_protocol(out_root or self.root)
  124. from importlib.util import find_spec
  125. if self.engine == "pyarrow" and find_spec("pyarrow") is None:
  126. raise ImportError("engine choice `pyarrow` is not installed.")
  127. def __getattr__(self, item):
  128. if item in ("_items", "record_size", "zmetadata"):
  129. self.setup()
  130. # avoid possible recursion if setup fails somehow
  131. return self.__dict__[item]
  132. raise AttributeError(item)
  133. def setup(self):
  134. self._items = {}
  135. self._items[".zmetadata"] = self.fs.cat_file(
  136. "/".join([self.root, ".zmetadata"])
  137. )
  138. met = json.loads(self._items[".zmetadata"])
  139. self.record_size = met["record_size"]
  140. self.zmetadata = met["metadata"]
  141. # Define function to open and decompress refs
  142. @lru_cache(maxsize=self.cache_size)
  143. def open_refs(field, record):
  144. """cached parquet file loader"""
  145. path = self.url.format(field=field, record=record)
  146. data = io.BytesIO(self.fs.cat_file(path))
  147. try:
  148. df = self.pd.read_parquet(data, engine=self.engine)
  149. refs = {c: df[c].to_numpy() for c in df.columns}
  150. except OSError:
  151. refs = None
  152. return refs
  153. self.open_refs = open_refs
  154. @staticmethod
  155. def create(root, storage_options=None, fs=None, record_size=10000, **kwargs):
  156. """Make empty parquet reference set
  157. First deletes the contents of the given directory, if it exists.
  158. Parameters
  159. ----------
  160. root: str
  161. Directory to contain the output; will be created
  162. storage_options: dict | None
  163. For making the filesystem to use for writing is fs is None
  164. fs: FileSystem | None
  165. Filesystem for writing
  166. record_size: int
  167. Number of references per parquet file
  168. kwargs: passed to __init__
  169. Returns
  170. -------
  171. LazyReferenceMapper instance
  172. """
  173. met = {"metadata": {}, "record_size": record_size}
  174. if fs is None:
  175. fs, root = fsspec.core.url_to_fs(root, **(storage_options or {}))
  176. if fs.exists(root):
  177. fs.rm(root, recursive=True)
  178. fs.makedirs(root, exist_ok=True)
  179. fs.pipe("/".join([root, ".zmetadata"]), json.dumps(met).encode())
  180. return LazyReferenceMapper(root, fs, **kwargs)
  181. @lru_cache
  182. def listdir(self):
  183. """List top-level directories"""
  184. dirs = (p.rsplit("/", 1)[0] for p in self.zmetadata if not p.startswith(".z"))
  185. return set(dirs)
  186. def ls(self, path="", detail=True):
  187. """Shortcut file listings"""
  188. path = path.rstrip("/")
  189. pathdash = path + "/" if path else ""
  190. dirnames = self.listdir()
  191. dirs = [
  192. d
  193. for d in dirnames
  194. if d.startswith(pathdash) and "/" not in d.lstrip(pathdash)
  195. ]
  196. if dirs:
  197. others = {
  198. f
  199. for f in chain(
  200. [".zmetadata"],
  201. (name for name in self.zmetadata),
  202. (name for name in self._items),
  203. )
  204. if f.startswith(pathdash) and "/" not in f.lstrip(pathdash)
  205. }
  206. if detail is False:
  207. others.update(dirs)
  208. return sorted(others)
  209. dirinfo = [{"name": name, "type": "directory", "size": 0} for name in dirs]
  210. fileinfo = [
  211. {
  212. "name": name,
  213. "type": "file",
  214. "size": len(
  215. json.dumps(self.zmetadata[name])
  216. if name in self.zmetadata
  217. else self._items[name]
  218. ),
  219. }
  220. for name in others
  221. ]
  222. return sorted(dirinfo + fileinfo, key=lambda s: s["name"])
  223. field = path
  224. others = set(
  225. [name for name in self.zmetadata if name.startswith(f"{path}/")]
  226. + [name for name in self._items if name.startswith(f"{path}/")]
  227. )
  228. fileinfo = [
  229. {
  230. "name": name,
  231. "type": "file",
  232. "size": len(
  233. json.dumps(self.zmetadata[name])
  234. if name in self.zmetadata
  235. else self._items[name]
  236. ),
  237. }
  238. for name in others
  239. ]
  240. keys = self._keys_in_field(field)
  241. if detail is False:
  242. return list(others) + list(keys)
  243. recs = self._generate_all_records(field)
  244. recinfo = [
  245. {"name": name, "type": "file", "size": rec[-1]}
  246. for name, rec in zip(keys, recs)
  247. if rec[0] # filters out path==None, deleted/missing
  248. ]
  249. return fileinfo + recinfo
  250. def _load_one_key(self, key):
  251. """Get the reference for one key
  252. Returns bytes, one-element list or three-element list.
  253. """
  254. if key in self._items:
  255. return self._items[key]
  256. elif key in self.zmetadata:
  257. return json.dumps(self.zmetadata[key]).encode()
  258. elif "/" not in key or self._is_meta(key):
  259. raise KeyError(key)
  260. field, _ = key.rsplit("/", 1)
  261. record, ri, chunk_size = self._key_to_record(key)
  262. maybe = self._items.get((field, record), {}).get(ri, False)
  263. if maybe is None:
  264. # explicitly deleted
  265. raise KeyError
  266. elif maybe:
  267. return maybe
  268. elif chunk_size == 0:
  269. return b""
  270. # Chunk keys can be loaded from row group and cached in LRU cache
  271. try:
  272. refs = self.open_refs(field, record)
  273. except (ValueError, TypeError, FileNotFoundError) as exc:
  274. raise KeyError(key) from exc
  275. columns = ["path", "offset", "size", "raw"]
  276. selection = [refs[c][ri] if c in refs else None for c in columns]
  277. raw = selection[-1]
  278. if raw is not None:
  279. return raw
  280. if selection[0] is None:
  281. raise KeyError("This reference does not exist or has been deleted")
  282. if selection[1:3] == [0, 0]:
  283. # URL only
  284. return selection[:1]
  285. # URL, offset, size
  286. return selection[:3]
  287. @lru_cache(4096)
  288. def _key_to_record(self, key):
  289. """Details needed to construct a reference for one key"""
  290. field, chunk = key.rsplit("/", 1)
  291. chunk_sizes = self._get_chunk_sizes(field)
  292. if len(chunk_sizes) == 0:
  293. return 0, 0, 0
  294. chunk_idx = [int(c) for c in chunk.split(".")]
  295. chunk_number = ravel_multi_index(chunk_idx, chunk_sizes)
  296. record = chunk_number // self.record_size
  297. ri = chunk_number % self.record_size
  298. return record, ri, len(chunk_sizes)
  299. def _get_chunk_sizes(self, field):
  300. """The number of chunks along each axis for a given field"""
  301. if field not in self.chunk_sizes:
  302. zarray = self.zmetadata[f"{field}/.zarray"]
  303. size_ratio = [
  304. math.ceil(s / c) for s, c in zip(zarray["shape"], zarray["chunks"])
  305. ]
  306. self.chunk_sizes[field] = size_ratio or [1]
  307. return self.chunk_sizes[field]
  308. def _generate_record(self, field, record):
  309. """The references for a given parquet file of a given field"""
  310. refs = self.open_refs(field, record)
  311. it = iter(zip(*refs.values()))
  312. if len(refs) == 3:
  313. # All urls
  314. return (list(t) for t in it)
  315. elif len(refs) == 1:
  316. # All raws
  317. return refs["raw"]
  318. else:
  319. # Mix of urls and raws
  320. return (list(t[:3]) if not t[3] else t[3] for t in it)
  321. def _generate_all_records(self, field):
  322. """Load all the references within a field by iterating over the parquet files"""
  323. nrec = 1
  324. for ch in self._get_chunk_sizes(field):
  325. nrec *= ch
  326. nrec = math.ceil(nrec / self.record_size)
  327. for record in range(nrec):
  328. yield from self._generate_record(field, record)
  329. def values(self):
  330. return RefsValuesView(self)
  331. def items(self):
  332. return RefsItemsView(self)
  333. def __hash__(self):
  334. return id(self)
  335. def __getitem__(self, key):
  336. return self._load_one_key(key)
  337. def __setitem__(self, key, value):
  338. if "/" in key and not self._is_meta(key):
  339. field, chunk = key.rsplit("/", 1)
  340. record, i, _ = self._key_to_record(key)
  341. subdict = self._items.setdefault((field, record), {})
  342. subdict[i] = value
  343. if len(subdict) == self.record_size:
  344. self.write(field, record)
  345. else:
  346. # metadata or top-level
  347. if hasattr(value, "to_bytes"):
  348. val = value.to_bytes().decode()
  349. elif isinstance(value, bytes):
  350. val = value.decode()
  351. else:
  352. val = value
  353. self._items[key] = val
  354. new_value = json.loads(val)
  355. self.zmetadata[key] = {**self.zmetadata.get(key, {}), **new_value}
  356. @staticmethod
  357. def _is_meta(key):
  358. return key.startswith(".z") or "/.z" in key
  359. def __delitem__(self, key):
  360. if key in self._items:
  361. del self._items[key]
  362. elif key in self.zmetadata:
  363. del self.zmetadata[key]
  364. else:
  365. if "/" in key and not self._is_meta(key):
  366. field, _ = key.rsplit("/", 1)
  367. record, i, _ = self._key_to_record(key)
  368. subdict = self._items.setdefault((field, record), {})
  369. subdict[i] = None
  370. if len(subdict) == self.record_size:
  371. self.write(field, record)
  372. else:
  373. # metadata or top-level
  374. self._items[key] = None
  375. def write(self, field, record, base_url=None, storage_options=None):
  376. # extra requirements if writing
  377. import kerchunk.df
  378. import numpy as np
  379. import pandas as pd
  380. partition = self._items[(field, record)]
  381. original = False
  382. if len(partition) < self.record_size:
  383. try:
  384. original = self.open_refs(field, record)
  385. except OSError:
  386. pass
  387. if original:
  388. paths = original["path"]
  389. offsets = original["offset"]
  390. sizes = original["size"]
  391. raws = original["raw"]
  392. else:
  393. paths = np.full(self.record_size, np.nan, dtype="O")
  394. offsets = np.zeros(self.record_size, dtype="int64")
  395. sizes = np.zeros(self.record_size, dtype="int64")
  396. raws = np.full(self.record_size, np.nan, dtype="O")
  397. for j, data in partition.items():
  398. if isinstance(data, list):
  399. if (
  400. str(paths.dtype) == "category"
  401. and data[0] not in paths.dtype.categories
  402. ):
  403. paths = paths.add_categories(data[0])
  404. paths[j] = data[0]
  405. if len(data) > 1:
  406. offsets[j] = data[1]
  407. sizes[j] = data[2]
  408. elif data is None:
  409. # delete
  410. paths[j] = None
  411. offsets[j] = 0
  412. sizes[j] = 0
  413. raws[j] = None
  414. else:
  415. # this is the only call into kerchunk, could remove
  416. raws[j] = kerchunk.df._proc_raw(data)
  417. # TODO: only save needed columns
  418. df = pd.DataFrame(
  419. {
  420. "path": paths,
  421. "offset": offsets,
  422. "size": sizes,
  423. "raw": raws,
  424. },
  425. copy=False,
  426. )
  427. if df.path.count() / (df.path.nunique() or 1) > self.cat_thresh:
  428. df["path"] = df["path"].astype("category")
  429. object_encoding = {"raw": "bytes", "path": "utf8"}
  430. has_nulls = ["path", "raw"]
  431. fn = f"{base_url or self.out_root}/{field}/refs.{record}.parq"
  432. self.fs.mkdirs(f"{base_url or self.out_root}/{field}", exist_ok=True)
  433. if self.engine == "pyarrow":
  434. df_backend_kwargs = {"write_statistics": False}
  435. elif self.engine == "fastparquet":
  436. df_backend_kwargs = {
  437. "stats": False,
  438. "object_encoding": object_encoding,
  439. "has_nulls": has_nulls,
  440. }
  441. else:
  442. raise NotImplementedError(f"{self.engine} not supported")
  443. df.to_parquet(
  444. fn,
  445. engine=self.engine,
  446. storage_options=storage_options
  447. or getattr(self.fs, "storage_options", None),
  448. compression="zstd",
  449. index=False,
  450. **df_backend_kwargs,
  451. )
  452. partition.clear()
  453. self._items.pop((field, record))
  454. def flush(self, base_url=None, storage_options=None):
  455. """Output any modified or deleted keys
  456. Parameters
  457. ----------
  458. base_url: str
  459. Location of the output
  460. """
  461. # write what we have so far and clear sub chunks
  462. for thing in list(self._items):
  463. if isinstance(thing, tuple):
  464. field, record = thing
  465. self.write(
  466. field,
  467. record,
  468. base_url=base_url,
  469. storage_options=storage_options,
  470. )
  471. # gather .zmetadata from self._items and write that too
  472. for k in list(self._items):
  473. if k != ".zmetadata" and ".z" in k:
  474. self.zmetadata[k] = json.loads(self._items.pop(k))
  475. met = {"metadata": self.zmetadata, "record_size": self.record_size}
  476. self._items.clear()
  477. self._items[".zmetadata"] = json.dumps(met).encode()
  478. self.fs.pipe(
  479. "/".join([base_url or self.out_root, ".zmetadata"]),
  480. self._items[".zmetadata"],
  481. )
  482. # TODO: only clear those that we wrote to?
  483. self.open_refs.cache_clear()
  484. def __len__(self):
  485. # Caveat: This counts expected references, not actual - but is fast
  486. count = 0
  487. for field in self.listdir():
  488. if field.startswith("."):
  489. count += 1
  490. else:
  491. count += math.prod(self._get_chunk_sizes(field))
  492. count += len(self.zmetadata) # all metadata keys
  493. # any other files not in reference partitions
  494. count += sum(1 for _ in self._items if not isinstance(_, tuple))
  495. return count
  496. def __iter__(self):
  497. # Caveat: returns only existing keys, so the number of these does not
  498. # match len(self)
  499. metas = set(self.zmetadata)
  500. metas.update(self._items)
  501. for bit in metas:
  502. if isinstance(bit, str):
  503. yield bit
  504. for field in self.listdir():
  505. for k in self._keys_in_field(field):
  506. if k in self:
  507. yield k
  508. def __contains__(self, item):
  509. try:
  510. self._load_one_key(item)
  511. return True
  512. except KeyError:
  513. return False
  514. def _keys_in_field(self, field):
  515. """List key names in given field
  516. Produces strings like "field/x.y" appropriate from the chunking of the array
  517. """
  518. chunk_sizes = self._get_chunk_sizes(field)
  519. if len(chunk_sizes) == 0:
  520. yield field + "/0"
  521. return
  522. inds = itertools.product(*(range(i) for i in chunk_sizes))
  523. for ind in inds:
  524. yield field + "/" + ".".join([str(c) for c in ind])
  525. class ReferenceFileSystem(AsyncFileSystem):
  526. """View byte ranges of some other file as a file system
  527. Initial version: single file system target, which must support
  528. async, and must allow start and end args in _cat_file. Later versions
  529. may allow multiple arbitrary URLs for the targets.
  530. This FileSystem is read-only. It is designed to be used with async
  531. targets (for now). We do not get original file details from the target FS.
  532. Configuration is by passing a dict of references at init, or a URL to
  533. a JSON file containing the same; this dict
  534. can also contain concrete data for some set of paths.
  535. Reference dict format:
  536. {path0: bytes_data, path1: (target_url, offset, size)}
  537. https://github.com/fsspec/kerchunk/blob/main/README.md
  538. """
  539. protocol = "reference"
  540. cachable = False
  541. def __init__(
  542. self,
  543. fo,
  544. target=None,
  545. ref_storage_args=None,
  546. target_protocol=None,
  547. target_options=None,
  548. remote_protocol=None,
  549. remote_options=None,
  550. fs=None,
  551. template_overrides=None,
  552. simple_templates=True,
  553. max_gap=64_000,
  554. max_block=256_000_000,
  555. cache_size=128,
  556. **kwargs,
  557. ):
  558. """
  559. Parameters
  560. ----------
  561. fo : dict or str
  562. The set of references to use for this instance, with a structure as above.
  563. If str referencing a JSON file, will use fsspec.open, in conjunction
  564. with target_options and target_protocol to open and parse JSON at this
  565. location. If a directory, then assume references are a set of parquet
  566. files to be loaded lazily.
  567. target : str
  568. For any references having target_url as None, this is the default file
  569. target to use
  570. ref_storage_args : dict
  571. If references is a str, use these kwargs for loading the JSON file.
  572. Deprecated: use target_options instead.
  573. target_protocol : str
  574. Used for loading the reference file, if it is a path. If None, protocol
  575. will be derived from the given path
  576. target_options : dict
  577. Extra FS options for loading the reference file ``fo``, if given as a path
  578. remote_protocol : str
  579. The protocol of the filesystem on which the references will be evaluated
  580. (unless fs is provided). If not given, will be derived from the first
  581. URL that has a protocol in the templates or in the references, in that
  582. order.
  583. remote_options : dict
  584. kwargs to go with remote_protocol
  585. fs : AbstractFileSystem | dict(str, (AbstractFileSystem | dict))
  586. Directly provide a file system(s):
  587. - a single filesystem instance
  588. - a dict of protocol:filesystem, where each value is either a filesystem
  589. instance, or a dict of kwargs that can be used to create in
  590. instance for the given protocol
  591. If this is given, remote_options and remote_protocol are ignored.
  592. template_overrides : dict
  593. Swap out any templates in the references file with these - useful for
  594. testing.
  595. simple_templates: bool
  596. Whether templates can be processed with simple replace (True) or if
  597. jinja is needed (False, much slower). All reference sets produced by
  598. ``kerchunk`` are simple in this sense, but the spec allows for complex.
  599. max_gap, max_block: int
  600. For merging multiple concurrent requests to the same remote file.
  601. Neighboring byte ranges will only be merged when their
  602. inter-range gap is <= ``max_gap``. Default is 64KB. Set to 0
  603. to only merge when it requires no extra bytes. Pass a negative
  604. number to disable merging, appropriate for local target files.
  605. Neighboring byte ranges will only be merged when the size of
  606. the aggregated range is <= ``max_block``. Default is 256MB.
  607. cache_size : int
  608. Maximum size of LRU cache, where cache_size*record_size denotes
  609. the total number of references that can be loaded in memory at once.
  610. Only used for lazily loaded references.
  611. kwargs : passed to parent class
  612. """
  613. super().__init__(**kwargs)
  614. self.target = target
  615. self.template_overrides = template_overrides
  616. self.simple_templates = simple_templates
  617. self.templates = {}
  618. self.fss = {}
  619. self._dircache = {}
  620. self.max_gap = max_gap
  621. self.max_block = max_block
  622. if isinstance(fo, str):
  623. dic = dict(
  624. **(ref_storage_args or target_options or {}), protocol=target_protocol
  625. )
  626. ref_fs, fo2 = fsspec.core.url_to_fs(fo, **dic)
  627. if ".json" not in fo2 and (
  628. fo.endswith(("parq", "parquet", "/")) or ref_fs.isdir(fo2)
  629. ):
  630. # Lazy parquet refs
  631. logger.info("Open lazy reference dict from URL %s", fo)
  632. self.references = LazyReferenceMapper(
  633. fo2,
  634. fs=ref_fs,
  635. cache_size=cache_size,
  636. )
  637. else:
  638. # text JSON
  639. with fsspec.open(fo, "rb", **dic) as f:
  640. logger.info("Read reference from URL %s", fo)
  641. text = json.load(f)
  642. self._process_references(text, template_overrides)
  643. else:
  644. # dictionaries
  645. self._process_references(fo, template_overrides)
  646. if isinstance(fs, dict):
  647. self.fss = {
  648. k: (
  649. fsspec.filesystem(k.split(":", 1)[0], **opts)
  650. if isinstance(opts, dict)
  651. else opts
  652. )
  653. for k, opts in fs.items()
  654. }
  655. if None not in self.fss:
  656. self.fss[None] = filesystem("file")
  657. return
  658. if fs is not None:
  659. # single remote FS
  660. remote_protocol = (
  661. fs.protocol[0] if isinstance(fs.protocol, tuple) else fs.protocol
  662. )
  663. self.fss[remote_protocol] = fs
  664. if remote_protocol is None:
  665. # get single protocol from any templates
  666. for ref in self.templates.values():
  667. if callable(ref):
  668. ref = ref()
  669. protocol, _ = fsspec.core.split_protocol(ref)
  670. if protocol and protocol not in self.fss:
  671. fs = filesystem(protocol, **(remote_options or {}))
  672. self.fss[protocol] = fs
  673. if remote_protocol is None:
  674. # get single protocol from references
  675. # TODO: warning here, since this can be very expensive?
  676. for ref in self.references.values():
  677. if callable(ref):
  678. ref = ref()
  679. if isinstance(ref, list) and ref[0]:
  680. protocol, _ = fsspec.core.split_protocol(ref[0])
  681. if protocol not in self.fss:
  682. fs = filesystem(protocol, **(remote_options or {}))
  683. self.fss[protocol] = fs
  684. # only use first remote URL
  685. break
  686. if remote_protocol and remote_protocol not in self.fss:
  687. fs = filesystem(remote_protocol, **(remote_options or {}))
  688. self.fss[remote_protocol] = fs
  689. self.fss[None] = fs or filesystem("file") # default one
  690. # Wrap any non-async filesystems to ensure async methods are available below
  691. for k, f in self.fss.items():
  692. if not f.async_impl:
  693. self.fss[k] = AsyncFileSystemWrapper(f, asynchronous=self.asynchronous)
  694. elif self.asynchronous ^ f.asynchronous:
  695. raise ValueError(
  696. "Reference-FS's target filesystem must have same value "
  697. "of asynchronous"
  698. )
  699. def _cat_common(self, path, start=None, end=None):
  700. path = self._strip_protocol(path)
  701. logger.debug(f"cat: {path}")
  702. try:
  703. part = self.references[path]
  704. except KeyError as exc:
  705. raise FileNotFoundError(path) from exc
  706. if isinstance(part, str):
  707. part = part.encode()
  708. if hasattr(part, "to_bytes"):
  709. part = part.to_bytes()
  710. if isinstance(part, bytes):
  711. logger.debug(f"Reference: {path}, type bytes")
  712. if part.startswith(b"base64:"):
  713. part = base64.b64decode(part[7:])
  714. return part, None, None
  715. if len(part) == 1:
  716. logger.debug(f"Reference: {path}, whole file => {part}")
  717. url = part[0]
  718. start1, end1 = start, end
  719. else:
  720. url, start0, size = part
  721. logger.debug(f"Reference: {path} => {url}, offset {start0}, size {size}")
  722. end0 = start0 + size
  723. if start is not None:
  724. if start >= 0:
  725. start1 = start0 + start
  726. else:
  727. start1 = end0 + start
  728. else:
  729. start1 = start0
  730. if end is not None:
  731. if end >= 0:
  732. end1 = start0 + end
  733. else:
  734. end1 = end0 + end
  735. else:
  736. end1 = end0
  737. if url is None:
  738. url = self.target
  739. return url, start1, end1
  740. async def _cat_file(self, path, start=None, end=None, **kwargs):
  741. part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
  742. if isinstance(part_or_url, bytes):
  743. return part_or_url[start:end]
  744. protocol, _ = split_protocol(part_or_url)
  745. try:
  746. return await self.fss[protocol]._cat_file(
  747. part_or_url, start=start0, end=end0
  748. )
  749. except Exception as e:
  750. raise ReferenceNotReachable(path, part_or_url) from e
  751. def cat_file(self, path, start=None, end=None, **kwargs):
  752. part_or_url, start0, end0 = self._cat_common(path, start=start, end=end)
  753. if isinstance(part_or_url, bytes):
  754. return part_or_url[start:end]
  755. protocol, _ = split_protocol(part_or_url)
  756. try:
  757. return self.fss[protocol].cat_file(part_or_url, start=start0, end=end0)
  758. except Exception as e:
  759. raise ReferenceNotReachable(path, part_or_url) from e
  760. def pipe_file(self, path, value, **_):
  761. """Temporarily add binary data or reference as a file"""
  762. self.references[path] = value
  763. async def _get_file(self, rpath, lpath, **kwargs):
  764. if self.isdir(rpath):
  765. return os.makedirs(lpath, exist_ok=True)
  766. data = await self._cat_file(rpath)
  767. with open(lpath, "wb") as f:
  768. f.write(data)
  769. def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, **kwargs):
  770. if self.isdir(rpath):
  771. return os.makedirs(lpath, exist_ok=True)
  772. data = self.cat_file(rpath, **kwargs)
  773. callback.set_size(len(data))
  774. if isfilelike(lpath):
  775. lpath.write(data)
  776. else:
  777. with open(lpath, "wb") as f:
  778. f.write(data)
  779. callback.absolute_update(len(data))
  780. def get(self, rpath, lpath, recursive=False, **kwargs):
  781. if recursive:
  782. # trigger directory build
  783. self.ls("")
  784. rpath = self.expand_path(rpath, recursive=recursive)
  785. fs = fsspec.filesystem("file", auto_mkdir=True)
  786. targets = other_paths(rpath, lpath)
  787. if recursive:
  788. data = self.cat([r for r in rpath if not self.isdir(r)])
  789. else:
  790. data = self.cat(rpath)
  791. for remote, local in zip(rpath, targets):
  792. if remote in data:
  793. fs.pipe_file(local, data[remote])
  794. def cat(self, path, recursive=False, on_error="raise", **kwargs):
  795. if isinstance(path, str) and recursive:
  796. raise NotImplementedError
  797. if isinstance(path, list) and (recursive or any("*" in p for p in path)):
  798. raise NotImplementedError
  799. # TODO: if references is lazy, pre-fetch all paths in batch before access
  800. proto_dict = _protocol_groups(path, self.references)
  801. out = {}
  802. for proto, paths in proto_dict.items():
  803. fs = self.fss[proto]
  804. urls, starts, ends, valid_paths = [], [], [], []
  805. for p in paths:
  806. # find references or label not-found. Early exit if any not
  807. # found and on_error is "raise"
  808. try:
  809. u, s, e = self._cat_common(p)
  810. if not isinstance(u, (bytes, str)):
  811. # nan/None from parquet
  812. continue
  813. except FileNotFoundError as err:
  814. if on_error == "raise":
  815. raise
  816. if on_error != "omit":
  817. out[p] = err
  818. else:
  819. urls.append(u)
  820. starts.append(s)
  821. ends.append(e)
  822. valid_paths.append(p)
  823. # process references into form for merging
  824. urls2 = []
  825. starts2 = []
  826. ends2 = []
  827. paths2 = []
  828. whole_files = set()
  829. for u, s, e, p in zip(urls, starts, ends, valid_paths):
  830. if isinstance(u, bytes):
  831. # data
  832. out[p] = u
  833. elif s is None:
  834. # whole file - limits are None, None, but no further
  835. # entries take for this file
  836. whole_files.add(u)
  837. urls2.append(u)
  838. starts2.append(s)
  839. ends2.append(e)
  840. paths2.append(p)
  841. for u, s, e, p in zip(urls, starts, ends, valid_paths):
  842. # second run to account for files that are to be loaded whole
  843. if s is not None and u not in whole_files:
  844. urls2.append(u)
  845. starts2.append(s)
  846. ends2.append(e)
  847. paths2.append(p)
  848. # merge and fetch consolidated ranges
  849. new_paths, new_starts, new_ends = merge_offset_ranges(
  850. list(urls2),
  851. list(starts2),
  852. list(ends2),
  853. sort=True,
  854. max_gap=self.max_gap,
  855. max_block=self.max_block,
  856. )
  857. bytes_out = fs.cat_ranges(new_paths, new_starts, new_ends)
  858. # unbundle from merged bytes - simple approach
  859. for u, s, e, p in zip(urls, starts, ends, valid_paths):
  860. if p in out:
  861. continue # was bytes, already handled
  862. for np, ns, ne, b in zip(new_paths, new_starts, new_ends, bytes_out):
  863. if np == u and (ns is None or ne is None):
  864. if isinstance(b, Exception):
  865. out[p] = b
  866. else:
  867. out[p] = b[s:e]
  868. elif np == u and s >= ns and e <= ne:
  869. if isinstance(b, Exception):
  870. out[p] = b
  871. else:
  872. out[p] = b[s - ns : (e - ne) or None]
  873. for k, v in out.copy().items():
  874. # these were valid references, but fetch failed, so transform exc
  875. if isinstance(v, Exception) and k in self.references:
  876. ex = out[k]
  877. new_ex = ReferenceNotReachable(k, self.references[k])
  878. new_ex.__cause__ = ex
  879. if on_error == "raise":
  880. raise new_ex
  881. elif on_error != "omit":
  882. out[k] = new_ex
  883. if len(out) == 1 and isinstance(path, str) and "*" not in path:
  884. return _first(out)
  885. return out
  886. def _process_references(self, references, template_overrides=None):
  887. vers = references.get("version", None)
  888. if vers is None:
  889. self._process_references0(references)
  890. elif vers == 1:
  891. self._process_references1(references, template_overrides=template_overrides)
  892. else:
  893. raise ValueError(f"Unknown reference spec version: {vers}")
  894. # TODO: we make dircache by iterating over all entries, but for Spec >= 1,
  895. # can replace with programmatic. Is it even needed for mapper interface?
  896. def _process_references0(self, references):
  897. """Make reference dict for Spec Version 0"""
  898. if isinstance(references, dict):
  899. # do not do this for lazy/parquet backend, which will not make dicts,
  900. # but must remain writable in the original object
  901. references = {
  902. key: json.dumps(val) if isinstance(val, dict) else val
  903. for key, val in references.items()
  904. }
  905. self.references = references
  906. def _process_references1(self, references, template_overrides=None):
  907. if not self.simple_templates or self.templates:
  908. import jinja2
  909. self.references = {}
  910. self._process_templates(references.get("templates", {}))
  911. @lru_cache(1000)
  912. def _render_jinja(u):
  913. return jinja2.Template(u).render(**self.templates)
  914. for k, v in references.get("refs", {}).items():
  915. if isinstance(v, str):
  916. if v.startswith("base64:"):
  917. self.references[k] = base64.b64decode(v[7:])
  918. self.references[k] = v
  919. elif isinstance(v, dict):
  920. self.references[k] = json.dumps(v)
  921. elif self.templates:
  922. u = v[0]
  923. if "{{" in u:
  924. if self.simple_templates:
  925. u = (
  926. u.replace("{{", "{")
  927. .replace("}}", "}")
  928. .format(**self.templates)
  929. )
  930. else:
  931. u = _render_jinja(u)
  932. self.references[k] = [u] if len(v) == 1 else [u, v[1], v[2]]
  933. else:
  934. self.references[k] = v
  935. self.references.update(self._process_gen(references.get("gen", [])))
  936. def _process_templates(self, tmp):
  937. self.templates = {}
  938. if self.template_overrides is not None:
  939. tmp.update(self.template_overrides)
  940. for k, v in tmp.items():
  941. if "{{" in v:
  942. import jinja2
  943. self.templates[k] = lambda temp=v, **kwargs: jinja2.Template(
  944. temp
  945. ).render(**kwargs)
  946. else:
  947. self.templates[k] = v
  948. def _process_gen(self, gens):
  949. out = {}
  950. for gen in gens:
  951. dimension = {
  952. k: (
  953. v
  954. if isinstance(v, list)
  955. else range(v.get("start", 0), v["stop"], v.get("step", 1))
  956. )
  957. for k, v in gen["dimensions"].items()
  958. }
  959. products = (
  960. dict(zip(dimension.keys(), values))
  961. for values in itertools.product(*dimension.values())
  962. )
  963. for pr in products:
  964. import jinja2
  965. key = jinja2.Template(gen["key"]).render(**pr, **self.templates)
  966. url = jinja2.Template(gen["url"]).render(**pr, **self.templates)
  967. if ("offset" in gen) and ("length" in gen):
  968. offset = int(
  969. jinja2.Template(gen["offset"]).render(**pr, **self.templates)
  970. )
  971. length = int(
  972. jinja2.Template(gen["length"]).render(**pr, **self.templates)
  973. )
  974. out[key] = [url, offset, length]
  975. elif ("offset" in gen) ^ ("length" in gen):
  976. raise ValueError(
  977. "Both 'offset' and 'length' are required for a "
  978. "reference generator entry if either is provided."
  979. )
  980. else:
  981. out[key] = [url]
  982. return out
  983. def _dircache_from_items(self):
  984. self.dircache = {"": []}
  985. it = self.references.items()
  986. for path, part in it:
  987. if isinstance(part, (bytes, str)) or hasattr(part, "to_bytes"):
  988. size = len(part)
  989. elif len(part) == 1:
  990. size = None
  991. else:
  992. _, _, size = part
  993. par = path.rsplit("/", 1)[0] if "/" in path else ""
  994. par0 = par
  995. subdirs = [par0]
  996. while par0 and par0 not in self.dircache:
  997. # collect parent directories
  998. par0 = self._parent(par0)
  999. subdirs.append(par0)
  1000. subdirs.reverse()
  1001. for parent, child in zip(subdirs, subdirs[1:]):
  1002. # register newly discovered directories
  1003. assert child not in self.dircache
  1004. assert parent in self.dircache
  1005. self.dircache[parent].append(
  1006. {"name": child, "type": "directory", "size": 0}
  1007. )
  1008. self.dircache[child] = []
  1009. self.dircache[par].append({"name": path, "type": "file", "size": size})
  1010. def _open(self, path, mode="rb", block_size=None, cache_options=None, **kwargs):
  1011. part_or_url, start0, end0 = self._cat_common(path)
  1012. # This logic is kept outside `ReferenceFile` to avoid unnecessary redirection.
  1013. # That does mean `_cat_common` gets called twice if it eventually reaches `ReferenceFile`.
  1014. if isinstance(part_or_url, bytes):
  1015. return io.BytesIO(part_or_url[start0:end0])
  1016. protocol, _ = split_protocol(part_or_url)
  1017. if start0 is None and end0 is None:
  1018. return self.fss[protocol]._open(
  1019. part_or_url,
  1020. mode,
  1021. block_size=block_size,
  1022. cache_options=cache_options,
  1023. **kwargs,
  1024. )
  1025. return ReferenceFile(
  1026. self,
  1027. path,
  1028. mode,
  1029. block_size=block_size,
  1030. cache_options=cache_options,
  1031. **kwargs,
  1032. )
  1033. def ls(self, path, detail=True, **kwargs):
  1034. logger.debug("list %s", path)
  1035. path = self._strip_protocol(path)
  1036. if isinstance(self.references, LazyReferenceMapper):
  1037. try:
  1038. return self.references.ls(path, detail)
  1039. except KeyError:
  1040. pass
  1041. raise FileNotFoundError(f"'{path}' is not a known key")
  1042. if not self.dircache:
  1043. self._dircache_from_items()
  1044. out = self._ls_from_cache(path)
  1045. if out is None:
  1046. raise FileNotFoundError(path)
  1047. if detail:
  1048. return out
  1049. return [o["name"] for o in out]
  1050. def exists(self, path, **kwargs): # overwrite auto-sync version
  1051. return self.isdir(path) or self.isfile(path)
  1052. def isdir(self, path): # overwrite auto-sync version
  1053. if self.dircache:
  1054. return path in self.dircache
  1055. elif isinstance(self.references, LazyReferenceMapper):
  1056. return path in self.references.listdir()
  1057. else:
  1058. # this may be faster than building dircache for single calls, but
  1059. # by looping will be slow for many calls; could cache it?
  1060. return any(_.startswith(f"{path}/") for _ in self.references)
  1061. def isfile(self, path): # overwrite auto-sync version
  1062. return path in self.references
  1063. async def _ls(self, path, detail=True, **kwargs): # calls fast sync code
  1064. return self.ls(path, detail, **kwargs)
  1065. def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
  1066. if withdirs:
  1067. return super().find(
  1068. path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, **kwargs
  1069. )
  1070. if path:
  1071. path = self._strip_protocol(path)
  1072. r = sorted(k for k in self.references if k.startswith(path))
  1073. else:
  1074. r = sorted(self.references)
  1075. if detail:
  1076. if not self.dircache:
  1077. self._dircache_from_items()
  1078. return {k: self._ls_from_cache(k)[0] for k in r}
  1079. else:
  1080. return r
  1081. def info(self, path, **kwargs):
  1082. out = self.references.get(path)
  1083. if out is not None:
  1084. if isinstance(out, (str, bytes)):
  1085. # decode base64 here
  1086. return {"name": path, "type": "file", "size": len(out)}
  1087. elif len(out) > 1:
  1088. return {"name": path, "type": "file", "size": out[2]}
  1089. else:
  1090. out0 = [{"name": path, "type": "file", "size": None}]
  1091. else:
  1092. out = self.ls(path, True)
  1093. out0 = [o for o in out if o["name"] == path]
  1094. if not out0:
  1095. return {"name": path, "type": "directory", "size": 0}
  1096. if out0[0]["size"] is None:
  1097. # if this is a whole remote file, update size using remote FS
  1098. prot, _ = split_protocol(self.references[path][0])
  1099. out0[0]["size"] = self.fss[prot].size(self.references[path][0])
  1100. return out0[0]
  1101. async def _info(self, path, **kwargs): # calls fast sync code
  1102. return self.info(path)
  1103. async def _rm_file(self, path, **kwargs):
  1104. self.references.pop(
  1105. path, None
  1106. ) # ignores FileNotFound, just as well for directories
  1107. self.dircache.clear() # this is a bit heavy handed
  1108. async def _pipe_file(self, path, data, mode="overwrite", **kwargs):
  1109. if mode == "create" and self.exists(path):
  1110. raise FileExistsError
  1111. # can be str or bytes
  1112. self.references[path] = data
  1113. self.dircache.clear() # this is a bit heavy handed
  1114. async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs):
  1115. # puts binary
  1116. if mode == "create" and self.exists(rpath):
  1117. raise FileExistsError
  1118. with open(lpath, "rb") as f:
  1119. self.references[rpath] = f.read()
  1120. self.dircache.clear() # this is a bit heavy handed
  1121. def save_json(self, url, **storage_options):
  1122. """Write modified references into new location"""
  1123. out = {}
  1124. for k, v in self.references.items():
  1125. if isinstance(v, bytes):
  1126. try:
  1127. out[k] = v.decode("ascii")
  1128. except UnicodeDecodeError:
  1129. out[k] = (b"base64:" + base64.b64encode(v)).decode()
  1130. else:
  1131. out[k] = v
  1132. with fsspec.open(url, "wb", **storage_options) as f:
  1133. f.write(json.dumps({"version": 1, "refs": out}).encode())
  1134. class ReferenceFile(AbstractBufferedFile):
  1135. def __init__(
  1136. self,
  1137. fs,
  1138. path,
  1139. mode="rb",
  1140. block_size="default",
  1141. autocommit=True,
  1142. cache_type="readahead",
  1143. cache_options=None,
  1144. size=None,
  1145. **kwargs,
  1146. ):
  1147. super().__init__(
  1148. fs,
  1149. path,
  1150. mode=mode,
  1151. block_size=block_size,
  1152. autocommit=autocommit,
  1153. size=size,
  1154. cache_type=cache_type,
  1155. cache_options=cache_options,
  1156. **kwargs,
  1157. )
  1158. part_or_url, self.start, self.end = self.fs._cat_common(self.path)
  1159. protocol, _ = split_protocol(part_or_url)
  1160. self.src_fs = self.fs.fss[protocol]
  1161. self.src_path = part_or_url
  1162. self._f = None
  1163. @property
  1164. def f(self):
  1165. if self._f is None or self._f.closed:
  1166. self._f = self.src_fs._open(
  1167. self.src_path,
  1168. mode=self.mode,
  1169. block_size=self.blocksize,
  1170. autocommit=self.autocommit,
  1171. cache_type="none",
  1172. **self.kwargs,
  1173. )
  1174. return self._f
  1175. def close(self):
  1176. if self._f is not None:
  1177. self._f.close()
  1178. return super().close()
  1179. def _fetch_range(self, start, end):
  1180. start = start + self.start
  1181. end = min(end + self.start, self.end)
  1182. self.f.seek(start)
  1183. return self.f.read(end - start)