Coverage for python/lsst/resources/_resourceHandles/_httpResourceHandle.py: 20%

115 statements  

« prev     ^ index     » next       coverage.py v7.3.1, created at 2023-09-13 09:44 +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. 

11 

12from __future__ import annotations 

13 

14__all__ = ("HttpReadResourceHandle",) 

15 

16import io 

17from collections.abc import Callable, Iterable 

18from logging import Logger 

19from typing import AnyStr 

20 

21import requests 

22from lsst.utils.timer import time_this 

23 

24from ._baseResourceHandle import BaseResourceHandle, CloseStatus 

25 

26 

27class HttpReadResourceHandle(BaseResourceHandle[bytes]): 

28 """HTTP-based specialization of `.BaseResourceHandle`.""" 

29 

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 

47 

48 if timeout is None: 

49 raise ValueError("timeout must be specified when constructing this object") 

50 self._timeout = timeout 

51 

52 self._completeBuffer: io.BytesIO | None = None 

53 

54 self._closed = CloseStatus.OPEN 

55 self._current_position = 0 

56 self._eof = False 

57 

58 def close(self) -> None: 

59 self._closed = CloseStatus.CLOSED 

60 self._completeBuffer = None 

61 self._eof = True 

62 

63 @property 

64 def closed(self) -> bool: 

65 return self._closed == CloseStatus.CLOSED 

66 

67 def fileno(self) -> int: 

68 raise io.UnsupportedOperation("HttpReadResourceHandle does not have a file number") 

69 

70 def flush(self) -> None: 

71 modes = set(self._mode) 

72 if {"w", "x", "a", "+"} & modes: 

73 raise io.UnsupportedOperation("HttpReadResourceHandles are read only") 

74 

75 @property 

76 def isatty(self) -> bool | Callable[[], bool]: 

77 return False 

78 

79 def readable(self) -> bool: 

80 return True 

81 

82 def readline(self, size: int = -1) -> AnyStr: 

83 raise io.UnsupportedOperation("HttpReadResourceHandles Do not support line by line reading") 

84 

85 def readlines(self, size: int = -1) -> Iterable[bytes]: 

86 raise io.UnsupportedOperation("HttpReadResourceHandles Do not support line by line reading") 

87 

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") 

96 

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 

101 

102 def seekable(self) -> bool: 

103 return True 

104 

105 def tell(self) -> int: 

106 return self._current_position 

107 

108 def truncate(self, size: int | None = None) -> int: 

109 raise io.UnsupportedOperation("HttpReadResourceHandles Do not support truncation") 

110 

111 def writable(self) -> bool: 

112 return False 

113 

114 def write(self, b: bytes, /) -> int: 

115 raise io.UnsupportedOperation("HttpReadResourceHandles are read only") 

116 

117 def writelines(self, b: Iterable[bytes], /) -> None: 

118 raise io.UnsupportedOperation("HttpReadResourceHandles are read only") 

119 

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"" 

124 

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 

130 

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() 

141 

142 return self._completeBuffer.getbuffer().tobytes() 

143 

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. 

151 

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"} 

154 

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) 

159 

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"" 

166 

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 ) 

171 

172 len_content = len(resp.content) 

173 

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) 

181 

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 != "*" and end_pos >= int(total) - 1: 

194 self._eof = True 

195 else: 

196 self._log.warning("Requested byte range from server but instead got: %s", content_range) 

197 

198 # Try to guess that we overran the end. This will not help if we 

199 # read exactly the number of bytes to get us to the end and so we 

200 # will need to do one more read and get a 416. 

201 if len_content < size: 

202 self._eof = True 

203 

204 self._current_position += len_content 

205 return resp.content