reference.py 48 KB

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