http.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. import asyncio
  2. import io
  3. import logging
  4. import re
  5. import weakref
  6. from copy import copy
  7. from urllib.parse import urlparse
  8. import aiohttp
  9. import yarl
  10. from fsspec.asyn import AbstractAsyncStreamedFile, AsyncFileSystem, sync, sync_wrapper
  11. from fsspec.callbacks import DEFAULT_CALLBACK
  12. from fsspec.exceptions import FSTimeoutError
  13. from fsspec.spec import AbstractBufferedFile
  14. from fsspec.utils import (
  15. DEFAULT_BLOCK_SIZE,
  16. glob_translate,
  17. isfilelike,
  18. nullcontext,
  19. tokenize,
  20. )
  21. from ..caching import AllBytes
  22. # https://stackoverflow.com/a/15926317/3821154
  23. ex = re.compile(r"""<(a|A)\s+(?:[^>]*?\s+)?(href|HREF)=["'](?P<url>[^"']+)""")
  24. ex2 = re.compile(r"""(?P<url>http[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""")
  25. logger = logging.getLogger("fsspec.http")
  26. async def get_client(**kwargs):
  27. return aiohttp.ClientSession(**kwargs)
  28. class HTTPFileSystem(AsyncFileSystem):
  29. """
  30. Simple File-System for fetching data via HTTP(S)
  31. ``ls()`` is implemented by loading the parent page and doing a regex
  32. match on the result. If simple_link=True, anything of the form
  33. "http(s)://server.com/stuff?thing=other"; otherwise only links within
  34. HTML href tags will be used.
  35. """
  36. sep = "/"
  37. def __init__(
  38. self,
  39. simple_links=True,
  40. block_size=None,
  41. same_scheme=True,
  42. size_policy=None,
  43. cache_type="bytes",
  44. cache_options=None,
  45. asynchronous=False,
  46. loop=None,
  47. client_kwargs=None,
  48. get_client=get_client,
  49. encoded=False,
  50. **storage_options,
  51. ):
  52. """
  53. NB: if this is called async, you must await set_client
  54. Parameters
  55. ----------
  56. block_size: int
  57. Blocks to read bytes; if 0, will default to raw requests file-like
  58. objects instead of HTTPFile instances
  59. simple_links: bool
  60. If True, will consider both HTML <a> tags and anything that looks
  61. like a URL; if False, will consider only the former.
  62. same_scheme: True
  63. When doing ls/glob, if this is True, only consider paths that have
  64. http/https matching the input URLs.
  65. size_policy: this argument is deprecated
  66. client_kwargs: dict
  67. Passed to aiohttp.ClientSession, see
  68. https://docs.aiohttp.org/en/stable/client_reference.html
  69. For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}``
  70. get_client: Callable[..., aiohttp.ClientSession]
  71. A callable which takes keyword arguments and constructs
  72. an aiohttp.ClientSession. It's state will be managed by
  73. the HTTPFileSystem class.
  74. storage_options: key-value
  75. Any other parameters passed on to requests
  76. cache_type, cache_options: defaults used in open
  77. """
  78. super().__init__(self, asynchronous=asynchronous, loop=loop, **storage_options)
  79. self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE
  80. self.simple_links = simple_links
  81. self.same_schema = same_scheme
  82. self.cache_type = cache_type
  83. self.cache_options = cache_options
  84. self.client_kwargs = client_kwargs or {}
  85. self.get_client = get_client
  86. self.encoded = encoded
  87. self.kwargs = storage_options
  88. self._session = None
  89. # Clean caching-related parameters from `storage_options`
  90. # before propagating them as `request_options` through `self.kwargs`.
  91. # TODO: Maybe rename `self.kwargs` to `self.request_options` to make
  92. # it clearer.
  93. request_options = copy(storage_options)
  94. self.use_listings_cache = request_options.pop("use_listings_cache", False)
  95. request_options.pop("listings_expiry_time", None)
  96. request_options.pop("max_paths", None)
  97. request_options.pop("skip_instance_cache", None)
  98. self.kwargs = request_options
  99. @property
  100. def fsid(self):
  101. return "http"
  102. def encode_url(self, url):
  103. return yarl.URL(url, encoded=self.encoded)
  104. @staticmethod
  105. def close_session(loop, session):
  106. if loop is not None and loop.is_running():
  107. try:
  108. sync(loop, session.close, timeout=0.1)
  109. return
  110. except (TimeoutError, FSTimeoutError, NotImplementedError):
  111. pass
  112. connector = getattr(session, "_connector", None)
  113. if connector is not None:
  114. # close after loop is dead
  115. connector._close()
  116. async def set_session(self):
  117. if self._session is None:
  118. self._session = await self.get_client(loop=self.loop, **self.client_kwargs)
  119. if not self.asynchronous:
  120. weakref.finalize(self, self.close_session, self.loop, self._session)
  121. return self._session
  122. @classmethod
  123. def _strip_protocol(cls, path):
  124. """For HTTP, we always want to keep the full URL"""
  125. return path
  126. @classmethod
  127. def _parent(cls, path):
  128. # override, since _strip_protocol is different for URLs
  129. par = super()._parent(path)
  130. if len(par) > 7: # "http://..."
  131. return par
  132. return ""
  133. async def _ls_real(self, url, detail=True, **kwargs):
  134. # ignoring URL-encoded arguments
  135. kw = self.kwargs.copy()
  136. kw.update(kwargs)
  137. logger.debug(url)
  138. session = await self.set_session()
  139. async with session.get(self.encode_url(url), **self.kwargs) as r:
  140. self._raise_not_found_for_status(r, url)
  141. try:
  142. text = await r.text()
  143. if self.simple_links:
  144. links = ex2.findall(text) + [u[2] for u in ex.findall(text)]
  145. else:
  146. links = [u[2] for u in ex.findall(text)]
  147. except UnicodeDecodeError:
  148. links = [] # binary, not HTML
  149. out = set()
  150. parts = urlparse(url)
  151. for l in links:
  152. if isinstance(l, tuple):
  153. l = l[1]
  154. if l.startswith("/") and len(l) > 1:
  155. # absolute URL on this server
  156. l = f"{parts.scheme}://{parts.netloc}{l}"
  157. if l.startswith("http"):
  158. if self.same_schema and l.startswith(url.rstrip("/") + "/"):
  159. out.add(l)
  160. elif l.replace("https", "http").startswith(
  161. url.replace("https", "http").rstrip("/") + "/"
  162. ):
  163. # allowed to cross http <-> https
  164. out.add(l)
  165. else:
  166. if l not in ["..", "../"]:
  167. # Ignore FTP-like "parent"
  168. out.add("/".join([url.rstrip("/"), l.lstrip("/")]))
  169. if not out and url.endswith("/"):
  170. out = await self._ls_real(url.rstrip("/"), detail=False)
  171. if detail:
  172. return [
  173. {
  174. "name": u,
  175. "size": None,
  176. "type": "directory" if u.endswith("/") else "file",
  177. }
  178. for u in out
  179. ]
  180. else:
  181. return sorted(out)
  182. async def _ls(self, url, detail=True, **kwargs):
  183. if self.use_listings_cache and url in self.dircache:
  184. out = self.dircache[url]
  185. else:
  186. out = await self._ls_real(url, detail=detail, **kwargs)
  187. self.dircache[url] = out
  188. return out
  189. ls = sync_wrapper(_ls)
  190. def _raise_not_found_for_status(self, response, url):
  191. """
  192. Raises FileNotFoundError for 404s, otherwise uses raise_for_status.
  193. """
  194. if response.status == 404:
  195. raise FileNotFoundError(url)
  196. response.raise_for_status()
  197. async def _cat_file(self, url, start=None, end=None, **kwargs):
  198. kw = self.kwargs.copy()
  199. kw.update(kwargs)
  200. logger.debug(url)
  201. if start is not None or end is not None:
  202. if start == end:
  203. return b""
  204. headers = kw.pop("headers", {}).copy()
  205. headers["Range"] = await self._process_limits(url, start, end)
  206. kw["headers"] = headers
  207. session = await self.set_session()
  208. async with session.get(self.encode_url(url), **kw) as r:
  209. out = await r.read()
  210. self._raise_not_found_for_status(r, url)
  211. return out
  212. async def _get_file(
  213. self, rpath, lpath, chunk_size=5 * 2**20, callback=DEFAULT_CALLBACK, **kwargs
  214. ):
  215. kw = self.kwargs.copy()
  216. kw.update(kwargs)
  217. logger.debug(rpath)
  218. session = await self.set_session()
  219. async with session.get(self.encode_url(rpath), **kw) as r:
  220. try:
  221. size = int(r.headers["content-length"])
  222. except (ValueError, KeyError):
  223. size = None
  224. callback.set_size(size)
  225. self._raise_not_found_for_status(r, rpath)
  226. if isfilelike(lpath):
  227. outfile = lpath
  228. else:
  229. outfile = open(lpath, "wb") # noqa: ASYNC101, ASYNC230
  230. try:
  231. chunk = True
  232. while chunk:
  233. chunk = await r.content.read(chunk_size)
  234. outfile.write(chunk)
  235. callback.relative_update(len(chunk))
  236. finally:
  237. if not isfilelike(lpath):
  238. outfile.close()
  239. async def _put_file(
  240. self,
  241. lpath,
  242. rpath,
  243. chunk_size=5 * 2**20,
  244. callback=DEFAULT_CALLBACK,
  245. method="post",
  246. mode="overwrite",
  247. **kwargs,
  248. ):
  249. if mode != "overwrite":
  250. raise NotImplementedError("Exclusive write")
  251. async def gen_chunks():
  252. # Support passing arbitrary file-like objects
  253. # and use them instead of streams.
  254. if isinstance(lpath, io.IOBase):
  255. context = nullcontext(lpath)
  256. use_seek = False # might not support seeking
  257. else:
  258. context = open(lpath, "rb") # noqa: ASYNC101, ASYNC230
  259. use_seek = True
  260. with context as f:
  261. if use_seek:
  262. callback.set_size(f.seek(0, 2))
  263. f.seek(0)
  264. else:
  265. callback.set_size(getattr(f, "size", None))
  266. chunk = f.read(chunk_size)
  267. while chunk:
  268. yield chunk
  269. callback.relative_update(len(chunk))
  270. chunk = f.read(chunk_size)
  271. kw = self.kwargs.copy()
  272. kw.update(kwargs)
  273. session = await self.set_session()
  274. method = method.lower()
  275. if method not in ("post", "put"):
  276. raise ValueError(
  277. f"method has to be either 'post' or 'put', not: {method!r}"
  278. )
  279. meth = getattr(session, method)
  280. async with meth(self.encode_url(rpath), data=gen_chunks(), **kw) as resp:
  281. self._raise_not_found_for_status(resp, rpath)
  282. async def _exists(self, path, **kwargs):
  283. kw = self.kwargs.copy()
  284. kw.update(kwargs)
  285. try:
  286. logger.debug(path)
  287. session = await self.set_session()
  288. r = await session.get(self.encode_url(path), **kw)
  289. async with r:
  290. return r.status < 400
  291. except aiohttp.ClientError:
  292. return False
  293. async def _isfile(self, path, **kwargs):
  294. return await self._exists(path, **kwargs)
  295. def _open(
  296. self,
  297. path,
  298. mode="rb",
  299. block_size=None,
  300. autocommit=None, # XXX: This differs from the base class.
  301. cache_type=None,
  302. cache_options=None,
  303. size=None,
  304. **kwargs,
  305. ):
  306. """Make a file-like object
  307. Parameters
  308. ----------
  309. path: str
  310. Full URL with protocol
  311. mode: string
  312. must be "rb"
  313. block_size: int or None
  314. Bytes to download in one request; use instance value if None. If
  315. zero, will return a streaming Requests file-like instance.
  316. kwargs: key-value
  317. Any other parameters, passed to requests calls
  318. """
  319. if mode != "rb":
  320. raise NotImplementedError
  321. block_size = block_size if block_size is not None else self.block_size
  322. kw = self.kwargs.copy()
  323. kw["asynchronous"] = self.asynchronous
  324. kw.update(kwargs)
  325. info = {}
  326. size = size or info.update(self.info(path, **kwargs)) or info["size"]
  327. session = sync(self.loop, self.set_session)
  328. if block_size and size and info.get("partial", True):
  329. return HTTPFile(
  330. self,
  331. path,
  332. session=session,
  333. block_size=block_size,
  334. mode=mode,
  335. size=size,
  336. cache_type=cache_type or self.cache_type,
  337. cache_options=cache_options or self.cache_options,
  338. loop=self.loop,
  339. **kw,
  340. )
  341. else:
  342. return HTTPStreamFile(
  343. self,
  344. path,
  345. mode=mode,
  346. loop=self.loop,
  347. session=session,
  348. **kw,
  349. )
  350. async def open_async(self, path, mode="rb", size=None, **kwargs):
  351. session = await self.set_session()
  352. if size is None:
  353. try:
  354. size = (await self._info(path, **kwargs))["size"]
  355. except FileNotFoundError:
  356. pass
  357. return AsyncStreamFile(
  358. self,
  359. path,
  360. loop=self.loop,
  361. session=session,
  362. size=size,
  363. **kwargs,
  364. )
  365. def ukey(self, url):
  366. """Unique identifier; assume HTTP files are static, unchanging"""
  367. return tokenize(url, self.kwargs, self.protocol)
  368. async def _info(self, url, **kwargs):
  369. """Get info of URL
  370. Tries to access location via HEAD, and then GET methods, but does
  371. not fetch the data.
  372. It is possible that the server does not supply any size information, in
  373. which case size will be given as None (and certain operations on the
  374. corresponding file will not work).
  375. """
  376. info = {}
  377. session = await self.set_session()
  378. for policy in ["head", "get"]:
  379. try:
  380. info.update(
  381. await _file_info(
  382. self.encode_url(url),
  383. size_policy=policy,
  384. session=session,
  385. **self.kwargs,
  386. **kwargs,
  387. )
  388. )
  389. if info.get("size") is not None:
  390. break
  391. except Exception as exc:
  392. if policy == "get":
  393. # If get failed, then raise a FileNotFoundError
  394. raise FileNotFoundError(url) from exc
  395. logger.debug("", exc_info=exc)
  396. return {"name": url, "size": None, **info, "type": "file"}
  397. async def _glob(self, path, maxdepth=None, **kwargs):
  398. """
  399. Find files by glob-matching.
  400. This implementation is idntical to the one in AbstractFileSystem,
  401. but "?" is not considered as a character for globbing, because it is
  402. so common in URLs, often identifying the "query" part.
  403. """
  404. if maxdepth is not None and maxdepth < 1:
  405. raise ValueError("maxdepth must be at least 1")
  406. import re
  407. ends_with_slash = path.endswith("/") # _strip_protocol strips trailing slash
  408. path = self._strip_protocol(path)
  409. append_slash_to_dirname = ends_with_slash or path.endswith(("/**", "/*"))
  410. idx_star = path.find("*") if path.find("*") >= 0 else len(path)
  411. idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
  412. min_idx = min(idx_star, idx_brace)
  413. detail = kwargs.pop("detail", False)
  414. if not has_magic(path):
  415. if await self._exists(path, **kwargs):
  416. if not detail:
  417. return [path]
  418. else:
  419. return {path: await self._info(path, **kwargs)}
  420. else:
  421. if not detail:
  422. return [] # glob of non-existent returns empty
  423. else:
  424. return {}
  425. elif "/" in path[:min_idx]:
  426. min_idx = path[:min_idx].rindex("/")
  427. root = path[: min_idx + 1]
  428. depth = path[min_idx + 1 :].count("/") + 1
  429. else:
  430. root = ""
  431. depth = path[min_idx + 1 :].count("/") + 1
  432. if "**" in path:
  433. if maxdepth is not None:
  434. idx_double_stars = path.find("**")
  435. depth_double_stars = path[idx_double_stars:].count("/") + 1
  436. depth = depth - depth_double_stars + maxdepth
  437. else:
  438. depth = None
  439. allpaths = await self._find(
  440. root, maxdepth=depth, withdirs=True, detail=True, **kwargs
  441. )
  442. pattern = glob_translate(path + ("/" if ends_with_slash else ""))
  443. pattern = re.compile(pattern)
  444. out = {
  445. (
  446. p.rstrip("/")
  447. if not append_slash_to_dirname
  448. and info["type"] == "directory"
  449. and p.endswith("/")
  450. else p
  451. ): info
  452. for p, info in sorted(allpaths.items())
  453. if pattern.match(p.rstrip("/"))
  454. }
  455. if detail:
  456. return out
  457. else:
  458. return list(out)
  459. async def _isdir(self, path):
  460. # override, since all URLs are (also) files
  461. try:
  462. return bool(await self._ls(path))
  463. except (FileNotFoundError, ValueError):
  464. return False
  465. async def _pipe_file(self, path, value, mode="overwrite", **kwargs):
  466. """
  467. Write bytes to a remote file over HTTP.
  468. Parameters
  469. ----------
  470. path : str
  471. Target URL where the data should be written
  472. value : bytes
  473. Data to be written
  474. mode : str
  475. How to write to the file - 'overwrite' or 'append'
  476. **kwargs : dict
  477. Additional parameters to pass to the HTTP request
  478. """
  479. url = self._strip_protocol(path)
  480. headers = kwargs.pop("headers", {})
  481. headers["Content-Length"] = str(len(value))
  482. session = await self.set_session()
  483. async with session.put(url, data=value, headers=headers, **kwargs) as r:
  484. r.raise_for_status()
  485. class HTTPFile(AbstractBufferedFile):
  486. """
  487. A file-like object pointing to a remote HTTP(S) resource
  488. Supports only reading, with read-ahead of a predetermined block-size.
  489. In the case that the server does not supply the filesize, only reading of
  490. the complete file in one go is supported.
  491. Parameters
  492. ----------
  493. url: str
  494. Full URL of the remote resource, including the protocol
  495. session: aiohttp.ClientSession or None
  496. All calls will be made within this session, to avoid restarting
  497. connections where the server allows this
  498. block_size: int or None
  499. The amount of read-ahead to do, in bytes. Default is 5MB, or the value
  500. configured for the FileSystem creating this file
  501. size: None or int
  502. If given, this is the size of the file in bytes, and we don't attempt
  503. to call the server to find the value.
  504. kwargs: all other key-values are passed to requests calls.
  505. """
  506. def __init__(
  507. self,
  508. fs,
  509. url,
  510. session=None,
  511. block_size=None,
  512. mode="rb",
  513. cache_type="bytes",
  514. cache_options=None,
  515. size=None,
  516. loop=None,
  517. asynchronous=False,
  518. **kwargs,
  519. ):
  520. if mode != "rb":
  521. raise NotImplementedError("File mode not supported")
  522. self.asynchronous = asynchronous
  523. self.loop = loop
  524. self.url = url
  525. self.session = session
  526. self.details = {"name": url, "size": size, "type": "file"}
  527. super().__init__(
  528. fs=fs,
  529. path=url,
  530. mode=mode,
  531. block_size=block_size,
  532. cache_type=cache_type,
  533. cache_options=cache_options,
  534. **kwargs,
  535. )
  536. def read(self, length=-1):
  537. """Read bytes from file
  538. Parameters
  539. ----------
  540. length: int
  541. Read up to this many bytes. If negative, read all content to end of
  542. file. If the server has not supplied the filesize, attempting to
  543. read only part of the data will raise a ValueError.
  544. """
  545. if (
  546. (length < 0 and self.loc == 0) # explicit read all
  547. # but not when the size is known and fits into a block anyways
  548. and not (self.size is not None and self.size <= self.blocksize)
  549. ):
  550. self._fetch_all()
  551. if self.size is None:
  552. if length < 0:
  553. self._fetch_all()
  554. else:
  555. length = min(self.size - self.loc, length)
  556. return super().read(length)
  557. async def async_fetch_all(self):
  558. """Read whole file in one shot, without caching
  559. This is only called when position is still at zero,
  560. and read() is called without a byte-count.
  561. """
  562. logger.debug(f"Fetch all for {self}")
  563. if not isinstance(self.cache, AllBytes):
  564. r = await self.session.get(self.fs.encode_url(self.url), **self.kwargs)
  565. async with r:
  566. r.raise_for_status()
  567. out = await r.read()
  568. self.cache = AllBytes(
  569. size=len(out), fetcher=None, blocksize=None, data=out
  570. )
  571. self.size = len(out)
  572. _fetch_all = sync_wrapper(async_fetch_all)
  573. def _parse_content_range(self, headers):
  574. """Parse the Content-Range header"""
  575. s = headers.get("Content-Range", "")
  576. m = re.match(r"bytes (\d+-\d+|\*)/(\d+|\*)", s)
  577. if not m:
  578. return None, None, None
  579. if m[1] == "*":
  580. start = end = None
  581. else:
  582. start, end = [int(x) for x in m[1].split("-")]
  583. total = None if m[2] == "*" else int(m[2])
  584. return start, end, total
  585. async def async_fetch_range(self, start, end):
  586. """Download a block of data
  587. The expectation is that the server returns only the requested bytes,
  588. with HTTP code 206. If this is not the case, we first check the headers,
  589. and then stream the output - if the data size is bigger than we
  590. requested, an exception is raised.
  591. """
  592. logger.debug(f"Fetch range for {self}: {start}-{end}")
  593. kwargs = self.kwargs.copy()
  594. headers = kwargs.pop("headers", {}).copy()
  595. headers["Range"] = f"bytes={start}-{end - 1}"
  596. logger.debug(f"{self.url} : {headers['Range']}")
  597. r = await self.session.get(
  598. self.fs.encode_url(self.url), headers=headers, **kwargs
  599. )
  600. async with r:
  601. if r.status == 416:
  602. # range request outside file
  603. return b""
  604. r.raise_for_status()
  605. # If the server has handled the range request, it should reply
  606. # with status 206 (partial content). But we'll guess that a suitable
  607. # Content-Range header or a Content-Length no more than the
  608. # requested range also mean we have got the desired range.
  609. response_is_range = (
  610. r.status == 206
  611. or self._parse_content_range(r.headers)[0] == start
  612. or int(r.headers.get("Content-Length", end + 1)) <= end - start
  613. )
  614. if response_is_range:
  615. # partial content, as expected
  616. out = await r.read()
  617. elif start > 0:
  618. raise ValueError(
  619. "The HTTP server doesn't appear to support range requests. "
  620. "Only reading this file from the beginning is supported. "
  621. "Open with block_size=0 for a streaming file interface."
  622. )
  623. else:
  624. # Response is not a range, but we want the start of the file,
  625. # so we can read the required amount anyway.
  626. cl = 0
  627. out = []
  628. while True:
  629. chunk = await r.content.read(2**20)
  630. # data size unknown, let's read until we have enough
  631. if chunk:
  632. out.append(chunk)
  633. cl += len(chunk)
  634. if cl > end - start:
  635. break
  636. else:
  637. break
  638. out = b"".join(out)[: end - start]
  639. return out
  640. _fetch_range = sync_wrapper(async_fetch_range)
  641. magic_check = re.compile("([*[])")
  642. def has_magic(s):
  643. match = magic_check.search(s)
  644. return match is not None
  645. class HTTPStreamFile(AbstractBufferedFile):
  646. def __init__(self, fs, url, mode="rb", loop=None, session=None, **kwargs):
  647. self.asynchronous = kwargs.pop("asynchronous", False)
  648. self.url = url
  649. self.loop = loop
  650. self.session = session
  651. if mode != "rb":
  652. raise ValueError
  653. self.details = {"name": url, "size": None}
  654. super().__init__(fs=fs, path=url, mode=mode, cache_type="none", **kwargs)
  655. async def cor():
  656. r = await self.session.get(self.fs.encode_url(url), **kwargs).__aenter__()
  657. self.fs._raise_not_found_for_status(r, url)
  658. return r
  659. self.r = sync(self.loop, cor)
  660. self.loop = fs.loop
  661. def seek(self, loc, whence=0):
  662. if loc == 0 and whence == 1:
  663. return
  664. if loc == self.loc and whence == 0:
  665. return
  666. raise ValueError("Cannot seek streaming HTTP file")
  667. async def _read(self, num=-1):
  668. out = await self.r.content.read(num)
  669. self.loc += len(out)
  670. return out
  671. read = sync_wrapper(_read)
  672. async def _close(self):
  673. self.r.close()
  674. def close(self):
  675. asyncio.run_coroutine_threadsafe(self._close(), self.loop)
  676. super().close()
  677. class AsyncStreamFile(AbstractAsyncStreamedFile):
  678. def __init__(
  679. self, fs, url, mode="rb", loop=None, session=None, size=None, **kwargs
  680. ):
  681. self.url = url
  682. self.session = session
  683. self.r = None
  684. if mode != "rb":
  685. raise ValueError
  686. self.details = {"name": url, "size": None}
  687. self.kwargs = kwargs
  688. super().__init__(fs=fs, path=url, mode=mode, cache_type="none")
  689. self.size = size
  690. async def read(self, num=-1):
  691. if self.r is None:
  692. r = await self.session.get(
  693. self.fs.encode_url(self.url), **self.kwargs
  694. ).__aenter__()
  695. self.fs._raise_not_found_for_status(r, self.url)
  696. self.r = r
  697. out = await self.r.content.read(num)
  698. self.loc += len(out)
  699. return out
  700. async def close(self):
  701. if self.r is not None:
  702. self.r.close()
  703. self.r = None
  704. await super().close()
  705. async def get_range(session, url, start, end, file=None, **kwargs):
  706. # explicit get a range when we know it must be safe
  707. kwargs = kwargs.copy()
  708. headers = kwargs.pop("headers", {}).copy()
  709. headers["Range"] = f"bytes={start}-{end - 1}"
  710. r = await session.get(url, headers=headers, **kwargs)
  711. r.raise_for_status()
  712. async with r:
  713. out = await r.read()
  714. if file:
  715. with open(file, "r+b") as f: # noqa: ASYNC101, ASYNC230
  716. f.seek(start)
  717. f.write(out)
  718. else:
  719. return out
  720. async def _file_info(url, session, size_policy="head", **kwargs):
  721. """Call HEAD on the server to get details about the file (size/checksum etc.)
  722. Default operation is to explicitly allow redirects and use encoding
  723. 'identity' (no compression) to get the true size of the target.
  724. """
  725. logger.debug("Retrieve file size for %s", url)
  726. kwargs = kwargs.copy()
  727. ar = kwargs.pop("allow_redirects", True)
  728. head = kwargs.get("headers", {}).copy()
  729. head["Accept-Encoding"] = "identity"
  730. kwargs["headers"] = head
  731. info = {}
  732. if size_policy == "head":
  733. r = await session.head(url, allow_redirects=ar, **kwargs)
  734. elif size_policy == "get":
  735. r = await session.get(url, allow_redirects=ar, **kwargs)
  736. else:
  737. raise TypeError(f'size_policy must be "head" or "get", got {size_policy}')
  738. async with r:
  739. r.raise_for_status()
  740. if "Content-Length" in r.headers:
  741. # Some servers may choose to ignore Accept-Encoding and return
  742. # compressed content, in which case the returned size is unreliable.
  743. if "Content-Encoding" not in r.headers or r.headers["Content-Encoding"] in [
  744. "identity",
  745. "",
  746. ]:
  747. info["size"] = int(r.headers["Content-Length"])
  748. elif "Content-Range" in r.headers:
  749. info["size"] = int(r.headers["Content-Range"].split("/")[1])
  750. if "Content-Type" in r.headers:
  751. info["mimetype"] = r.headers["Content-Type"].partition(";")[0]
  752. if r.headers.get("Accept-Ranges") == "none":
  753. # Some servers may explicitly discourage partial content requests, but
  754. # the lack of "Accept-Ranges" does not always indicate they would fail
  755. info["partial"] = False
  756. info["url"] = str(r.url)
  757. for checksum_field in ["ETag", "Content-MD5", "Digest"]:
  758. if r.headers.get(checksum_field):
  759. info[checksum_field] = r.headers[checksum_field]
  760. return info
  761. async def _file_size(url, session=None, *args, **kwargs):
  762. if session is None:
  763. session = await get_client()
  764. info = await _file_info(url, session=session, *args, **kwargs)
  765. return info.get("size")
  766. file_size = sync_wrapper(_file_size)