rida-format 0.2.0__tar.gz → 0.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. {rida_format-0.2.0 → rida_format-0.2.1}/CHANGELOG.md +31 -0
  2. {rida_format-0.2.0/src/rida_format.egg-info → rida_format-0.2.1}/PKG-INFO +19 -3
  3. {rida_format-0.2.0 → rida_format-0.2.1}/RIDA-FORMAT.md +4 -0
  4. {rida_format-0.2.0 → rida_format-0.2.1}/RIDA-README.md +18 -2
  5. {rida_format-0.2.0 → rida_format-0.2.1}/pyproject.toml +1 -1
  6. {rida_format-0.2.0 → rida_format-0.2.1}/src/rida/__init__.py +156 -7
  7. {rida_format-0.2.0 → rida_format-0.2.1/src/rida_format.egg-info}/PKG-INFO +19 -3
  8. {rida_format-0.2.0 → rida_format-0.2.1}/tests/test_rida.py +115 -11
  9. {rida_format-0.2.0 → rida_format-0.2.1}/LICENSE +0 -0
  10. {rida_format-0.2.0 → rida_format-0.2.1}/MANIFEST.in +0 -0
  11. {rida_format-0.2.0 → rida_format-0.2.1}/docs/rida-metadata.html +0 -0
  12. {rida_format-0.2.0 → rida_format-0.2.1}/setup.cfg +0 -0
  13. {rida_format-0.2.0 → rida_format-0.2.1}/src/rida/__main__.py +0 -0
  14. {rida_format-0.2.0 → rida_format-0.2.1}/src/rida_format.egg-info/SOURCES.txt +0 -0
  15. {rida_format-0.2.0 → rida_format-0.2.1}/src/rida_format.egg-info/dependency_links.txt +0 -0
  16. {rida_format-0.2.0 → rida_format-0.2.1}/src/rida_format.egg-info/entry_points.txt +0 -0
  17. {rida_format-0.2.0 → rida_format-0.2.1}/src/rida_format.egg-info/top_level.txt +0 -0
  18. {rida_format-0.2.0 → rida_format-0.2.1}/tests/fixture_spec.py +0 -0
  19. {rida_format-0.2.0 → rida_format-0.2.1}/tests/fixtures/golden-source-dictionary.json +0 -0
  20. {rida_format-0.2.0 → rida_format-0.2.1}/tests/fixtures/golden-source-sequential.json +0 -0
  21. {rida_format-0.2.0 → rida_format-0.2.1}/tests/fixtures/golden-v1-dictionary-dense.rida +0 -0
  22. {rida_format-0.2.0 → rida_format-0.2.1}/tests/fixtures/golden-v1-dictionary-sparse.rida +0 -0
  23. {rida_format-0.2.0 → rida_format-0.2.1}/tests/fixtures/golden-v1-sequential-dense.rida +0 -0
  24. {rida_format-0.2.0 → rida_format-0.2.1}/tests/fixtures/golden-v1-sequential-sparse.rida +0 -0
  25. {rida_format-0.2.0 → rida_format-0.2.1}/tests/make_fixtures.py +0 -0
@@ -2,6 +2,37 @@
2
2
 
3
3
  All notable changes to the RIDA library and container format.
4
4
 
5
+ ## 0.2.1
6
+
7
+ No file-format change: 0.2.1 reads and writes exactly what 0.2.0 did, and files
8
+ from 0.1.1 onwards stay readable.
9
+
10
+ ### Fixed
11
+
12
+ * **Remote reads no longer open a fresh connection for every range request.**
13
+ `RemoteRidaFile` now keeps one HTTP(S) connection per calling thread and
14
+ reuses it, which removes a full TLS handshake from every lookup. Measured
15
+ against Bunny CDN on the 27,647-record Musnad Ahmed file, average lookup time
16
+ fell from **89.0 ms to 25.9 ms** (median 76.9 ms to 20.9 ms). The 0.2.0
17
+ behaviour is still available with `keepalive=False` or `--no-keepalive`.
18
+
19
+ ### Added
20
+
21
+ * `RemoteRidaFile` is now a context manager and has `close()`. Closing only drops
22
+ the sockets; a later read opens a new one.
23
+ * `RemoteRidaFile(keepalive=False)` and `rida remote-get --no-keepalive`.
24
+ * Seven new tests, and the test range server now speaks HTTP/1.1 so connection
25
+ reuse is covered: reuse, reconnect after a dropped socket, redirect fallback,
26
+ thread sharing, context-manager use, `keepalive=False`, and non-HTTP URLs.
27
+
28
+ ### Changed
29
+
30
+ * Before reusing an idle connection, RIDA checks the socket and reconnects when
31
+ the server has already closed it, so a dead keep-alive socket cannot waste a
32
+ round trip.
33
+ * A server that answers with a redirect hands that request back to `urllib`, so
34
+ redirecting URLs keep working instead of failing on the raw connection path.
35
+
5
36
  ## 0.2.0
6
37
 
7
38
  ### Format
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rida-format
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Range Indexed Data Access (RIDA) static data format and library
5
5
  Author: Syed Ali Hamza Chishty
6
6
  Maintainer-email: Qasra Foundation <admin@qasra.org>
@@ -21,7 +21,7 @@ Description-Content-Type: text/markdown
21
21
  License-File: LICENSE
22
22
  Dynamic: license-file
23
23
 
24
- # RIDA Python library — 0.2.0
24
+ # RIDA Python library — 0.2.1
25
25
 
26
26
  RIDA means **Range Indexed Data Access**. It is an installable Python library
27
27
  and terminal tool that builds one `.rida` file from a collection of JSON
@@ -334,6 +334,22 @@ own cache entry automatically, because the header no longer matches.
334
334
 
335
335
  Network reads fail after `--timeout` seconds (default 30) instead of hanging.
336
336
 
337
+ ### Connection reuse
338
+
339
+ A range request sent over a fresh TLS connection pays a full handshake, which on
340
+ a CDN costs several times more than the lookup itself. The remote reader
341
+ therefore keeps one HTTP(S) connection open per reading thread and reuses it, so
342
+ a warm lookup spends its time on the value, not on the handshake.
343
+
344
+ Measured against Bunny CDN on the 27,647-record Musnad Ahmed file:
345
+
346
+ | | average | median |
347
+ | --- | ---: | ---: |
348
+ | 0.2.1 with connection reuse (default) | **25.9 ms** | 20.9 ms |
349
+ | 0.2.0, fresh connection per lookup | 89.0 ms | 76.9 ms |
350
+
351
+ Use `--no-keepalive`, or `keepalive=False` in Python, to get the old behaviour.
352
+
337
353
  ## Use from Python
338
354
 
339
355
  ```python
@@ -380,7 +396,7 @@ Useful names:
380
396
  | --- | --- |
381
397
  | `rida.build`, `rida.scan` | Build or analyse input; `value_codec=` and `memory_mode=` select behaviour |
382
398
  | `rida.RidaFile` | Local reader: `get(record_id, field)`, `verify_data()` |
383
- | `rida.RemoteRidaFile` | HTTP byte-range reader: `cache_hit`, `timeout=`, `cache_dir=` |
399
+ | `rida.RemoteRidaFile` | HTTP byte-range reader: `cache_hit`, `timeout=`, `cache_dir=`, `keepalive=`, `close()` |
384
400
  | `rida.verify` | Full integrity report for a local file |
385
401
  | `rida.inspect_metadata` | Header and metadata as a dictionary |
386
402
  | `rida.VALUE_CODECS` | `("gzip-per-field", "plain")` |
@@ -193,6 +193,10 @@ A reader needs at most three requests for a cold lookup:
193
193
  2. `bytes=128-(128 + metadata_length + catalog_length - 1)` — metadata and catalog.
194
194
  3. the requested value range.
195
195
 
196
+ These requests travel over one reused connection per reading thread, because a
197
+ fresh TLS handshake per lookup costs several times more than the lookup itself.
198
+ A redirecting URL falls back to a plain follow-redirect request path.
199
+
196
200
  With a warm local catalog cache (see below) step 2 disappears.
197
201
 
198
202
  ## 8. Local catalog cache (optional, not part of the format)
@@ -1,4 +1,4 @@
1
- # RIDA Python library — 0.2.0
1
+ # RIDA Python library — 0.2.1
2
2
 
3
3
  RIDA means **Range Indexed Data Access**. It is an installable Python library
4
4
  and terminal tool that builds one `.rida` file from a collection of JSON
@@ -311,6 +311,22 @@ own cache entry automatically, because the header no longer matches.
311
311
 
312
312
  Network reads fail after `--timeout` seconds (default 30) instead of hanging.
313
313
 
314
+ ### Connection reuse
315
+
316
+ A range request sent over a fresh TLS connection pays a full handshake, which on
317
+ a CDN costs several times more than the lookup itself. The remote reader
318
+ therefore keeps one HTTP(S) connection open per reading thread and reuses it, so
319
+ a warm lookup spends its time on the value, not on the handshake.
320
+
321
+ Measured against Bunny CDN on the 27,647-record Musnad Ahmed file:
322
+
323
+ | | average | median |
324
+ | --- | ---: | ---: |
325
+ | 0.2.1 with connection reuse (default) | **25.9 ms** | 20.9 ms |
326
+ | 0.2.0, fresh connection per lookup | 89.0 ms | 76.9 ms |
327
+
328
+ Use `--no-keepalive`, or `keepalive=False` in Python, to get the old behaviour.
329
+
314
330
  ## Use from Python
315
331
 
316
332
  ```python
@@ -357,7 +373,7 @@ Useful names:
357
373
  | --- | --- |
358
374
  | `rida.build`, `rida.scan` | Build or analyse input; `value_codec=` and `memory_mode=` select behaviour |
359
375
  | `rida.RidaFile` | Local reader: `get(record_id, field)`, `verify_data()` |
360
- | `rida.RemoteRidaFile` | HTTP byte-range reader: `cache_hit`, `timeout=`, `cache_dir=` |
376
+ | `rida.RemoteRidaFile` | HTTP byte-range reader: `cache_hit`, `timeout=`, `cache_dir=`, `keepalive=`, `close()` |
361
377
  | `rida.verify` | Full integrity report for a local file |
362
378
  | `rida.inspect_metadata` | Header and metadata as a dictionary |
363
379
  | `rida.VALUE_CODECS` | `("gzip-per-field", "plain")` |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "rida-format"
7
- version = "0.2.0"
7
+ version = "0.2.1"
8
8
  description = "Range Indexed Data Access (RIDA) static data format and library"
9
9
  readme = "RIDA-README.md"
10
10
  requires-python = ">=3.10"
@@ -21,14 +21,18 @@ import argparse
21
21
  import array
22
22
  import gzip
23
23
  import hashlib
24
+ import http.client
24
25
  import json
25
26
  import lzma
26
27
  import os
28
+ import select
27
29
  import struct
28
30
  import subprocess
29
31
  import sys
30
32
  import tempfile
33
+ import threading
31
34
  import urllib.error
35
+ import urllib.parse
32
36
  import urllib.request
33
37
  from dataclasses import dataclass
34
38
  from pathlib import Path
@@ -65,7 +69,7 @@ _LAYOUTS = {
65
69
  (RIDA_MAGIC_V1, RIDA_VERSION_V1): VALUE_CODEC_PLAIN,
66
70
  (RIDA_MAGIC_V2, RIDA_VERSION_V2): VALUE_CODEC_GZIP,
67
71
  }
68
- __version__ = "0.2.0"
72
+ __version__ = "0.2.1"
69
73
  ProgressCallback = Callable[[str, int, int], None]
70
74
 
71
75
 
@@ -1879,6 +1883,133 @@ def _http_range(
1879
1883
  return data
1880
1884
 
1881
1885
 
1886
+ class _RangeReader:
1887
+ """Fetch RIDA byte ranges while reusing one HTTP(S) connection per thread.
1888
+
1889
+ A range request over a fresh TLS connection pays a full handshake, which on a
1890
+ CDN costs several times more than the lookup itself. One connection is kept
1891
+ open per calling thread, so a reader shared by a thread pool still gets one
1892
+ connection per worker, while a single-threaded reader reuses one socket.
1893
+
1894
+ A dropped connection is retried once on a fresh socket, and a server that
1895
+ answers with a redirect hands the request back to urllib, which follows it.
1896
+ """
1897
+
1898
+ _REDIRECTS = (301, 302, 303, 307, 308)
1899
+
1900
+ def __init__(self, url: str, timeout: float, keepalive: bool = True):
1901
+ parsed = urllib.parse.urlsplit(url)
1902
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
1903
+ raise RidaError(f"RIDA remote URL must be http or https: {url!r}")
1904
+ self.url = url
1905
+ self.timeout = timeout
1906
+ self.keepalive = keepalive
1907
+ self._scheme = parsed.scheme
1908
+ self._host = parsed.hostname
1909
+ self._port = parsed.port
1910
+ self._path = parsed.path or "/"
1911
+ if parsed.query:
1912
+ self._path += "?" + parsed.query
1913
+ self._local = threading.local()
1914
+ self._connections: list[Any] = []
1915
+ self._lock = threading.Lock()
1916
+ #: Set once a redirect is seen, so every later request uses urllib.
1917
+ self._follow_redirects = False
1918
+
1919
+ def _new_connection(self) -> Any:
1920
+ if self._scheme == "https":
1921
+ connection = http.client.HTTPSConnection(self._host, self._port, timeout=self.timeout)
1922
+ else:
1923
+ connection = http.client.HTTPConnection(self._host, self._port, timeout=self.timeout)
1924
+ with self._lock:
1925
+ self._connections.append(connection)
1926
+ return connection
1927
+
1928
+ def _connection_is_usable(self, connection: Any) -> bool:
1929
+ """False when the server already closed, or dirtied, the idle socket.
1930
+
1931
+ Without this check a request sent on a socket the server has closed would
1932
+ only fail once the response was expected, wasting a whole round trip.
1933
+ """
1934
+ sock = getattr(connection, "sock", None)
1935
+ if sock is None:
1936
+ return False
1937
+ try:
1938
+ readable, _, _ = select.select([sock], [], [], 0)
1939
+ except (OSError, ValueError):
1940
+ return False
1941
+ return not readable
1942
+
1943
+ def _current_connection(self) -> Any:
1944
+ connection = getattr(self._local, "connection", None)
1945
+ if connection is not None and not self._connection_is_usable(connection):
1946
+ self._drop_current_connection()
1947
+ connection = None
1948
+ if connection is None:
1949
+ connection = self._new_connection()
1950
+ self._local.connection = connection
1951
+ return connection
1952
+
1953
+ def _drop_current_connection(self) -> None:
1954
+ connection = getattr(self._local, "connection", None)
1955
+ self._local.connection = None
1956
+ if connection is not None:
1957
+ try:
1958
+ connection.close()
1959
+ except Exception: # pragma: no cover - never mask the original error
1960
+ pass
1961
+
1962
+ def fetch(self, offset: int, length: int) -> bytes:
1963
+ if length <= 0:
1964
+ raise RidaError("RIDA byte-range length must be positive")
1965
+ if not self.keepalive or self._follow_redirects:
1966
+ return _http_range(self.url, offset, length, self.timeout)
1967
+ last = offset + length - 1
1968
+ headers = {
1969
+ "Range": f"bytes={offset}-{last}",
1970
+ "Accept-Encoding": "identity",
1971
+ "User-Agent": f"rida/{__version__}",
1972
+ }
1973
+ for attempt in (1, 2):
1974
+ connection = self._current_connection()
1975
+ try:
1976
+ connection.request("GET", self._path, headers=headers)
1977
+ response = connection.getresponse()
1978
+ status = response.status
1979
+ content_range = response.getheader("Content-Range") or ""
1980
+ data = response.read()
1981
+ except (http.client.HTTPException, OSError) as exc:
1982
+ self._drop_current_connection()
1983
+ if attempt == 2:
1984
+ raise RidaError(f"RIDA range request failed: {exc}") from exc
1985
+ continue
1986
+ if status in self._REDIRECTS:
1987
+ self._drop_current_connection()
1988
+ self._follow_redirects = True
1989
+ return _http_range(self.url, offset, length, self.timeout)
1990
+ if status != 206 or not content_range.casefold().startswith(f"bytes {offset}-{last}/"):
1991
+ self._drop_current_connection()
1992
+ raise RidaError("Server did not honor the requested byte range")
1993
+ if len(data) != length:
1994
+ self._drop_current_connection()
1995
+ raise RidaError(
1996
+ f"Server returned {len(data)} bytes; expected {length}. "
1997
+ "Range support is required."
1998
+ )
1999
+ return data
2000
+ raise AssertionError("unreachable")
2001
+
2002
+ def close(self) -> None:
2003
+ with self._lock:
2004
+ connections, self._connections = self._connections, []
2005
+ for connection in connections:
2006
+ try:
2007
+ connection.close()
2008
+ except Exception: # pragma: no cover
2009
+ pass
2010
+ self._local = threading.local()
2011
+
2012
+
1882
2013
  def remote_cache_directory() -> Path:
1883
2014
  """Return the folder used for cached remote catalogs."""
1884
2015
  configured = os.environ.get("RIDA_CACHE_DIR")
@@ -1992,7 +2123,8 @@ class RemoteRidaFile:
1992
2123
 
1993
2124
  The header is always re-fetched, because its catalog digest and lengths are
1994
2125
  what validate a locally cached catalog. With a warm cache a lookup needs two
1995
- requests: the 128-byte header and the requested value range.
2126
+ requests, the 128-byte header and the requested value range, and both travel
2127
+ over the same reused connection.
1996
2128
  """
1997
2129
 
1998
2130
  def __init__(
@@ -2002,11 +2134,14 @@ class RemoteRidaFile:
2002
2134
  timeout: float = DEFAULT_REMOTE_TIMEOUT,
2003
2135
  cache_dir: str | Path | None = None,
2004
2136
  use_cache: bool = True,
2137
+ keepalive: bool = True,
2005
2138
  ):
2006
2139
  if timeout <= 0:
2007
2140
  raise RidaError("RIDA remote timeout must be positive")
2008
2141
  self.url = url
2009
2142
  self.timeout = timeout
2143
+ self.keepalive = keepalive
2144
+ self._reader = _RangeReader(url, timeout, keepalive)
2010
2145
  if not use_cache:
2011
2146
  self.cache_dir: Path | None = None
2012
2147
  elif cache_dir is not None:
@@ -2015,18 +2150,16 @@ class RemoteRidaFile:
2015
2150
  self.cache_dir = remote_cache_directory()
2016
2151
  self.cache_hit = False
2017
2152
 
2018
- header_bytes = _http_range(url, 0, HEADER.size, timeout)
2153
+ header_bytes = self._reader.fetch(0, HEADER.size)
2019
2154
  self.header = _parse_header(header_bytes)
2020
2155
  cached = _read_cached_prefix(self.cache_dir, url, header_bytes)
2021
2156
  if cached is not None:
2022
2157
  metadata_bytes, catalog = cached
2023
2158
  self.cache_hit = True
2024
2159
  else:
2025
- prefix = _http_range(
2026
- url,
2160
+ prefix = self._reader.fetch(
2027
2161
  HEADER.size,
2028
2162
  self.header.metadata_length + self.header.catalog_length,
2029
- timeout,
2030
2163
  )
2031
2164
  metadata_bytes = prefix[:self.header.metadata_length]
2032
2165
  catalog = prefix[self.header.metadata_length:]
@@ -2040,9 +2173,19 @@ class RemoteRidaFile:
2040
2173
 
2041
2174
  def get(self, record_id: str | int, field: str) -> Any:
2042
2175
  relative_offset, length = self.catalog.pointer(record_id, field)
2043
- raw = _http_range(self.url, self.header.data_offset + relative_offset, length, self.timeout)
2176
+ raw = self._reader.fetch(self.header.data_offset + relative_offset, length)
2044
2177
  return _decode_value(raw, self.header.value_codec)
2045
2178
 
2179
+ def close(self) -> None:
2180
+ """Close the connections this reader opened. Later reads reopen them."""
2181
+ self._reader.close()
2182
+
2183
+ def __enter__(self) -> "RemoteRidaFile":
2184
+ return self
2185
+
2186
+ def __exit__(self, *_: object) -> None:
2187
+ self.close()
2188
+
2046
2189
 
2047
2190
  def inspect_metadata(path: Path) -> dict[str, Any]:
2048
2191
  with path.open("rb") as file:
@@ -2228,6 +2371,11 @@ def _main() -> int:
2228
2371
  remote_get_parser.add_argument(
2229
2372
  "--cache-dir", type=Path, help="Catalog cache folder (default: the user cache folder for RIDA)"
2230
2373
  )
2374
+ remote_get_parser.add_argument(
2375
+ "--no-keepalive",
2376
+ action="store_true",
2377
+ help="Open a fresh connection for every range request instead of reusing one",
2378
+ )
2231
2379
 
2232
2380
  cache_parser = commands.add_parser("cache", help="Show or clear the remote catalog cache")
2233
2381
  cache_parser.add_argument("--clear", action="store_true", help="Delete cached catalog entries")
@@ -2353,6 +2501,7 @@ def _main() -> int:
2353
2501
  timeout=args.timeout,
2354
2502
  cache_dir=args.cache_dir,
2355
2503
  use_cache=not args.no_cache,
2504
+ keepalive=not args.no_keepalive,
2356
2505
  )
2357
2506
  _print_value(data.get(args.record_id, args.field))
2358
2507
  sys.stdout.flush()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rida-format
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Range Indexed Data Access (RIDA) static data format and library
5
5
  Author: Syed Ali Hamza Chishty
6
6
  Maintainer-email: Qasra Foundation <admin@qasra.org>
@@ -21,7 +21,7 @@ Description-Content-Type: text/markdown
21
21
  License-File: LICENSE
22
22
  Dynamic: license-file
23
23
 
24
- # RIDA Python library — 0.2.0
24
+ # RIDA Python library — 0.2.1
25
25
 
26
26
  RIDA means **Range Indexed Data Access**. It is an installable Python library
27
27
  and terminal tool that builds one `.rida` file from a collection of JSON
@@ -334,6 +334,22 @@ own cache entry automatically, because the header no longer matches.
334
334
 
335
335
  Network reads fail after `--timeout` seconds (default 30) instead of hanging.
336
336
 
337
+ ### Connection reuse
338
+
339
+ A range request sent over a fresh TLS connection pays a full handshake, which on
340
+ a CDN costs several times more than the lookup itself. The remote reader
341
+ therefore keeps one HTTP(S) connection open per reading thread and reuses it, so
342
+ a warm lookup spends its time on the value, not on the handshake.
343
+
344
+ Measured against Bunny CDN on the 27,647-record Musnad Ahmed file:
345
+
346
+ | | average | median |
347
+ | --- | ---: | ---: |
348
+ | 0.2.1 with connection reuse (default) | **25.9 ms** | 20.9 ms |
349
+ | 0.2.0, fresh connection per lookup | 89.0 ms | 76.9 ms |
350
+
351
+ Use `--no-keepalive`, or `keepalive=False` in Python, to get the old behaviour.
352
+
337
353
  ## Use from Python
338
354
 
339
355
  ```python
@@ -380,7 +396,7 @@ Useful names:
380
396
  | --- | --- |
381
397
  | `rida.build`, `rida.scan` | Build or analyse input; `value_codec=` and `memory_mode=` select behaviour |
382
398
  | `rida.RidaFile` | Local reader: `get(record_id, field)`, `verify_data()` |
383
- | `rida.RemoteRidaFile` | HTTP byte-range reader: `cache_hit`, `timeout=`, `cache_dir=` |
399
+ | `rida.RemoteRidaFile` | HTTP byte-range reader: `cache_hit`, `timeout=`, `cache_dir=`, `keepalive=`, `close()` |
384
400
  | `rida.verify` | Full integrity report for a local file |
385
401
  | `rida.inspect_metadata` | Header and metadata as a dictionary |
386
402
  | `rida.VALUE_CODECS` | `("gzip-per-field", "plain")` |
@@ -25,7 +25,9 @@ import sys
25
25
  import tempfile
26
26
  import threading
27
27
  import unittest
28
+ from concurrent.futures import ThreadPoolExecutor
28
29
  from pathlib import Path
30
+ from unittest import mock
29
31
 
30
32
  SOURCE_ROOT = Path(__file__).resolve().parents[1]
31
33
  TESTS_DIR = Path(__file__).resolve().parent
@@ -365,16 +367,30 @@ class InputValidationTests(TempDirTestCase):
365
367
  class _RangeRequestHandler(http.server.BaseHTTPRequestHandler):
366
368
  directory = Path(".")
367
369
  supports_range = True
370
+ close_after_response = False
371
+ redirect_first = False
372
+ redirected = False
368
373
  log: list = []
369
374
 
375
+ #: HTTP/1.1 so the connection can be kept alive between range requests.
376
+ protocol_version = "HTTP/1.1"
377
+
370
378
  def log_message(self, *args: object) -> None: # keep the test output quiet
371
379
  return
372
380
 
373
381
  def do_GET(self) -> None: # noqa: N802 - required by BaseHTTPRequestHandler
374
382
  self.log.append(self.headers.get("Range"))
383
+ if self.redirect_first and not type(self).redirected:
384
+ type(self).redirected = True
385
+ self.send_response(302)
386
+ self.send_header("Location", self.path)
387
+ self.send_header("Content-Length", "0")
388
+ self.end_headers()
389
+ return
375
390
  target = self.directory / self.path.lstrip("/")
376
391
  if not target.is_file():
377
392
  self.send_error(404)
393
+ self.close_connection = True
378
394
  return
379
395
  payload = target.read_bytes()
380
396
  size = len(payload)
@@ -395,15 +411,36 @@ class _RangeRequestHandler(http.server.BaseHTTPRequestHandler):
395
411
  self.send_header("Accept-Ranges", "bytes")
396
412
  self.end_headers()
397
413
  self.wfile.write(body)
414
+ if self.close_after_response:
415
+ self.close_connection = True
398
416
 
399
417
 
400
418
  class RemoteTests(TempDirTestCase):
401
- def _serve(self, directory: Path, supports_range: bool = True) -> tuple[str, list]:
419
+ def _reader(self, url: str, **kwargs: object) -> rida.RemoteRidaFile:
420
+ """Create a remote reader and always close its sockets afterwards."""
421
+ reader = rida.RemoteRidaFile(url, **kwargs)
422
+ self.addCleanup(reader.close)
423
+ return reader
424
+
425
+ def _serve(
426
+ self,
427
+ directory: Path,
428
+ supports_range: bool = True,
429
+ close_after_response: bool = False,
430
+ redirect_first: bool = False,
431
+ ) -> tuple[str, list]:
402
432
  log: list = []
403
433
  handler = type(
404
434
  "Handler",
405
435
  (_RangeRequestHandler,),
406
- {"directory": directory, "supports_range": supports_range, "log": log},
436
+ {
437
+ "directory": directory,
438
+ "supports_range": supports_range,
439
+ "close_after_response": close_after_response,
440
+ "redirect_first": redirect_first,
441
+ "redirected": False,
442
+ "log": log,
443
+ },
407
444
  )
408
445
  server = socketserver.ThreadingTCPServer(("127.0.0.1", 0), handler)
409
446
  server.daemon_threads = True
@@ -424,7 +461,7 @@ class RemoteTests(TempDirTestCase):
424
461
  def test_reads_only_the_requested_ranges(self) -> None:
425
462
  target = self._remote_file()
426
463
  base, log = self._serve(self.tmp)
427
- remote = rida.RemoteRidaFile(f"{base}/{target.name}", use_cache=False)
464
+ remote = self._reader(f"{base}/{target.name}", use_cache=False)
428
465
  self.assertEqual(remote.get("2", "langs"), ["ur", "en"])
429
466
  self.assertEqual(remote.get("3", "note"), "اردو متن")
430
467
  self.assertGreaterEqual(len(log), 4)
@@ -434,7 +471,7 @@ class RemoteTests(TempDirTestCase):
434
471
  target = self._remote_file()
435
472
  base, _ = self._serve(self.tmp, supports_range=False)
436
473
  with self.assertRaises(rida.RidaError):
437
- rida.RemoteRidaFile(f"{base}/{target.name}", use_cache=False)
474
+ self._reader(f"{base}/{target.name}", use_cache=False)
438
475
 
439
476
  def test_catalog_cache_turns_a_cold_open_into_a_warm_one(self) -> None:
440
477
  target = self._remote_file()
@@ -443,11 +480,11 @@ class RemoteTests(TempDirTestCase):
443
480
  cache = self.tmp / "cache"
444
481
 
445
482
  log.clear()
446
- cold = rida.RemoteRidaFile(url, cache_dir=cache)
483
+ cold = self._reader(url, cache_dir=cache)
447
484
  self.assertFalse(cold.cache_hit)
448
485
 
449
486
  log.clear()
450
- warm = rida.RemoteRidaFile(url, cache_dir=cache)
487
+ warm = self._reader(url, cache_dir=cache)
451
488
  self.assertTrue(warm.cache_hit)
452
489
  self.assertEqual(log, ["bytes=0-127"], "a warm open must skip the catalog download")
453
490
  self.assertEqual(warm.get("1", "city"), "Mumbai")
@@ -457,24 +494,24 @@ class RemoteTests(TempDirTestCase):
457
494
  base, _ = self._serve(self.tmp)
458
495
  url = f"{base}/{target.name}"
459
496
  cache = self.tmp / "cache"
460
- self.assertFalse(rida.RemoteRidaFile(url, cache_dir=cache).cache_hit)
497
+ self.assertFalse(self._reader(url, cache_dir=cache).cache_hit)
461
498
 
462
499
  changed = self.build(
463
500
  "changed.json", {"1": {"name": "Ali", "city": "Karachi"}}, value_codec="plain"
464
501
  )
465
502
  target.write_bytes(changed.read_bytes())
466
- replacement = rida.RemoteRidaFile(url, cache_dir=cache)
503
+ replacement = self._reader(url, cache_dir=cache)
467
504
  self.assertFalse(replacement.cache_hit, "a different header must invalidate the cache")
468
505
  self.assertEqual(replacement.get("1", "city"), "Karachi")
469
506
  # The cache now describes the new object.
470
- self.assertTrue(rida.RemoteRidaFile(url, cache_dir=cache).cache_hit)
507
+ self.assertTrue(self._reader(url, cache_dir=cache).cache_hit)
471
508
 
472
509
  def test_clear_remote_cache(self) -> None:
473
510
  target = self._remote_file()
474
511
  base, _ = self._serve(self.tmp)
475
512
  cache = self.tmp / "cache"
476
513
  url = f"{base}/{target.name}"
477
- rida.RemoteRidaFile(url, cache_dir=cache)
514
+ self._reader(url, cache_dir=cache)
478
515
  self.assertEqual(len(list(cache.glob("*.rdacat"))), 1)
479
516
  self.assertEqual(rida.clear_remote_cache(cache_dir=cache), 1)
480
517
  self.assertEqual(list(cache.glob("*.rdacat")), [])
@@ -482,11 +519,78 @@ class RemoteTests(TempDirTestCase):
482
519
 
483
520
  def test_remote_timeout_must_be_positive(self) -> None:
484
521
  with self.assertRaises(rida.RidaError):
485
- rida.RemoteRidaFile("http://127.0.0.1:1/x.rida", timeout=0, use_cache=False)
522
+ self._reader("http://127.0.0.1:1/x.rida", timeout=0, use_cache=False)
486
523
 
487
524
  def test_remote_defaults_to_the_user_cache_directory(self) -> None:
488
525
  self.assertTrue(str(rida.remote_cache_directory()).endswith("rida"))
489
526
 
527
+ def test_one_connection_serves_many_lookups(self) -> None:
528
+ target = self._remote_file()
529
+ base, _ = self._serve(self.tmp)
530
+ url = f"{base}/{target.name}"
531
+ created: list = []
532
+ real = rida.http.client.HTTPConnection
533
+
534
+ def counting(*args: object, **kwargs: object):
535
+ connection = real(*args, **kwargs)
536
+ created.append(connection)
537
+ return connection
538
+
539
+ with mock.patch.object(rida.http.client, "HTTPConnection", counting):
540
+ reader = self._reader(url, cache_dir=self.tmp / "cache")
541
+ for _ in range(10):
542
+ self.assertEqual(reader.get("1", "name"), "Ali")
543
+ self.assertEqual(len(created), 1, f"expected one reused connection, got {len(created)}")
544
+
545
+ def test_reconnects_when_the_server_closes_the_connection(self) -> None:
546
+ target = self._remote_file()
547
+ base, _ = self._serve(self.tmp, close_after_response=True)
548
+ reader = self._reader(f"{base}/{target.name}", cache_dir=self.tmp / "cache")
549
+ for _ in range(5):
550
+ self.assertEqual(reader.get("2", "name"), "Fatima")
551
+
552
+ def test_redirect_hands_the_request_back_to_urllib(self) -> None:
553
+ target = self._remote_file()
554
+ base, _ = self._serve(self.tmp, redirect_first=True)
555
+ reader = self._reader(f"{base}/{target.name}", cache_dir=self.tmp / "cache")
556
+ self.assertEqual(reader.get("1", "city"), "Mumbai")
557
+ self.assertEqual(reader.get("3", "note"), "اردو متن")
558
+
559
+ def test_threads_share_one_reader(self) -> None:
560
+ target = self._remote_file()
561
+ base, _ = self._serve(self.tmp)
562
+ reader = self._reader(f"{base}/{target.name}", cache_dir=self.tmp / "cache")
563
+
564
+ def work(seed: int) -> list:
565
+ return [reader.get(str(seed % 3 + 1), "name") for _ in range(10)]
566
+
567
+ with ThreadPoolExecutor(max_workers=4) as pool:
568
+ results = list(pool.map(work, range(4)))
569
+ self.assertEqual(sum(len(row) for row in results), 40)
570
+ self.assertTrue(all(value for row in results for value in row))
571
+
572
+ def test_reader_is_a_context_manager(self) -> None:
573
+ target = self._remote_file()
574
+ base, _ = self._serve(self.tmp)
575
+ url = f"{base}/{target.name}"
576
+ with self._reader(url, cache_dir=self.tmp / "cache") as reader:
577
+ self.assertEqual(reader.get("1", "city"), "Mumbai")
578
+ # close() only drops the sockets; a later read may open a new one.
579
+ self.assertEqual(reader.get("2", "name"), "Fatima")
580
+
581
+ def test_keepalive_can_be_disabled(self) -> None:
582
+ target = self._remote_file()
583
+ base, _ = self._serve(self.tmp)
584
+ reader = self._reader(
585
+ f"{base}/{target.name}", cache_dir=self.tmp / "cache", keepalive=False
586
+ )
587
+ self.assertFalse(reader.keepalive)
588
+ self.assertEqual(reader.get("1", "name"), "Ali")
589
+
590
+ def test_non_http_url_is_rejected(self) -> None:
591
+ with self.assertRaises(rida.RidaError):
592
+ self._reader("ftp://example.com/data.rida", use_cache=False)
593
+
490
594
 
491
595
  class CliTests(TempDirTestCase):
492
596
  def _run(self, *args: str) -> subprocess.CompletedProcess:
File without changes
File without changes
File without changes