Coverage for python/lsst/resources/_resourceHandles/_httpResourceHandle.py: 18%
116 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-10 09:42 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-10 09:42 +0000
1# This file is part of lsst-resources.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# Use of this source code is governed by a 3-clause BSD-style
10# license that can be found in the LICENSE file.
12from __future__ import annotations
14__all__ = ("HttpReadResourceHandle",)
16import io
17from collections.abc import Callable, Iterable
18from logging import Logger
19from typing import AnyStr
21import requests
22from lsst.utils.timer import time_this
24from ._baseResourceHandle import BaseResourceHandle, CloseStatus
27class HttpReadResourceHandle(BaseResourceHandle[bytes]):
28 """HTTP-based specialization of `.BaseResourceHandle`."""
30 def __init__(
31 self,
32 mode: str,
33 log: Logger,
34 *,
35 session: requests.Session | None = None,
36 url: str | None = None,
37 timeout: tuple[float, float] | None = None,
38 newline: AnyStr | None = None,
39 ) -> None:
40 super().__init__(mode, log, newline=newline)
41 if url is None:
42 raise ValueError("Url must be specified when constructing this object")
43 self._url = url
44 if session is None:
45 raise ValueError("Session must be specified when constructing this object")
46 self._session = session
48 if timeout is None:
49 raise ValueError("timeout must be specified when constructing this object")
50 self._timeout = timeout
52 self._completeBuffer: io.BytesIO | None = None
54 self._closed = CloseStatus.OPEN
55 self._current_position = 0
56 self._eof = False
58 def close(self) -> None:
59 self._closed = CloseStatus.CLOSED
60 self._completeBuffer = None
61 self._eof = True
63 @property
64 def closed(self) -> bool:
65 return self._closed == CloseStatus.CLOSED
67 def fileno(self) -> int:
68 raise io.UnsupportedOperation("HttpReadResourceHandle does not have a file number")
70 def flush(self) -> None:
71 modes = set(self._mode)
72 if {"w", "x", "a", "+"} & modes:
73 raise io.UnsupportedOperation("HttpReadResourceHandles are read only")
75 @property
76 def isatty(self) -> bool | Callable[[], bool]:
77 return False
79 def readable(self) -> bool:
80 return True
82 def readline(self, size: int = -1) -> AnyStr:
83 raise io.UnsupportedOperation("HttpReadResourceHandles Do not support line by line reading")
85 def readlines(self, size: int = -1) -> Iterable[bytes]:
86 raise io.UnsupportedOperation("HttpReadResourceHandles Do not support line by line reading")
88 def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
89 self._eof = False
90 if whence == io.SEEK_CUR and (self._current_position + offset) >= 0:
91 self._current_position += offset
92 elif whence == io.SEEK_SET and offset >= 0:
93 self._current_position = offset
94 else:
95 raise io.UnsupportedOperation("Seek value is incorrect, or whence mode is unsupported")
97 # handle if the complete file has be read already
98 if self._completeBuffer is not None:
99 self._completeBuffer.seek(self._current_position, whence)
100 return self._current_position
102 def seekable(self) -> bool:
103 return True
105 def tell(self) -> int:
106 return self._current_position
108 def truncate(self, size: int | None = None) -> int:
109 raise io.UnsupportedOperation("HttpReadResourceHandles Do not support truncation")
111 def writable(self) -> bool:
112 return False
114 def write(self, b: bytes, /) -> int:
115 raise io.UnsupportedOperation("HttpReadResourceHandles are read only")
117 def writelines(self, b: Iterable[bytes], /) -> None:
118 raise io.UnsupportedOperation("HttpReadResourceHandles are read only")
120 def read(self, size: int = -1) -> bytes:
121 if self._eof:
122 # At EOF so always return an empty byte string.
123 return b""
125 # branch for if the complete file has been read before
126 if self._completeBuffer is not None:
127 result = self._completeBuffer.read(size)
128 self._current_position += len(result)
129 return result
131 if self._completeBuffer is None and size == -1 and self._current_position == 0:
132 # The whole file has been requested, read it into a buffer and
133 # return the result
134 self._completeBuffer = io.BytesIO()
135 with time_this(self._log, msg="Read from remote resource %s", args=(self._url,)):
136 resp = self._session.get(self._url, stream=False, timeout=self._timeout)
137 if (code := resp.status_code) not in (requests.codes.ok, requests.codes.partial):
138 raise FileNotFoundError(f"Unable to read resource {self._url}; status code: {code}")
139 self._completeBuffer.write(resp.content)
140 self._current_position = self._completeBuffer.tell()
142 return self._completeBuffer.getbuffer().tobytes()
144 # A partial read is required, either because a size has been specified,
145 # or a read has previously been done. Any time we specify a byte range
146 # we must disable the gzip compression on the server since we want
147 # to address ranges in the uncompressed file. If we send ranges that
148 # are interpreted by the server as offsets into the compressed file
149 # then that is at least confusing and also there is no guarantee that
150 # the bytes can be uncompressed.
152 end_pos = self._current_position + (size - 1) if size >= 0 else ""
153 headers = {"Range": f"bytes={self._current_position}-{end_pos}", "Accept-Encoding": "identity"}
155 with time_this(
156 self._log, msg="Read from remote resource %s using headers %s", args=(self._url, headers)
157 ):
158 resp = self._session.get(self._url, stream=False, timeout=self._timeout, headers=headers)
160 if resp.status_code == requests.codes.range_not_satisfiable:
161 # Must have run off the end of the file. A standard file handle
162 # will treat this as EOF so be consistent with that. Do not change
163 # the current position.
164 self._eof = True
165 return b""
167 if (code := resp.status_code) not in (requests.codes.ok, requests.codes.partial):
168 raise FileNotFoundError(
169 f"Unable to read resource {self._url}, or bytes are out of range; status code: {code}"
170 )
172 len_content = len(resp.content)
174 # verify this is not actually the whole file and the server did not lie
175 # about supporting ranges
176 if len_content > size or code != requests.codes.partial:
177 self._completeBuffer = io.BytesIO()
178 self._completeBuffer.write(resp.content)
179 self._completeBuffer.seek(0)
180 return self.read(size=size)
182 # The response header should tell us the total number of bytes
183 # in the file and also the current position we have got to in the
184 # server.
185 if "Content-Range" in resp.headers:
186 content_range = resp.headers["Content-Range"]
187 units, range_string = content_range.split(" ")
188 if units == "bytes":
189 range, total = range_string.split("/")
190 if "-" in range:
191 _, end = range.split("-")
192 end_pos = int(end)
193 if total != "*":
194 if end_pos >= int(total) - 1:
195 self._eof = True
196 else:
197 self._log.warning("Requested byte range from server but instead got: %s", content_range)
199 # Try to guess that we overran the end. This will not help if we
200 # read exactly the number of bytes to get us to the end and so we
201 # will need to do one more read and get a 416.
202 if len_content < size:
203 self._eof = True
205 self._current_position += len_content
206 return resp.content