s3func 0.9.3__tar.gz → 0.9.4__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: s3func
3
- Version: 0.9.3
3
+ Version: 0.9.4
4
4
  Summary: Simple functions for working with S3
5
5
  Project-URL: Documentation, https://mullenkamp.github.io/s3func/
6
6
  Project-URL: Source, https://github.com/mullenkamp/s3func
@@ -33,6 +33,7 @@ Description-Content-Type: text/markdown
33
33
  - **Distributed Locking**: Verified shared/exclusive locking on plain object storage - no CAS required (see [docs/locking.md](docs/locking.md)).
34
34
  - **Streaming Support**: Efficiently stream large objects.
35
35
  - **Automatic Retries**: urllib3 retries with exponential backoff for connection errors and transient HTTP statuses (429/5xx); `Retry-After` honored; non-idempotent POSTs are never status-retried.
36
+ - **Slow-link-safe transfers** (0.9.4): timeouts are true *idle* bounds, never total-request deadlines — large uploads are streamed in chunks (bytes bodies over 1 MiB are wrapped automatically), so a slow-but-progressing multi-minute transfer never times out while a genuinely stalled socket still dies within `read_timeout`/`connect_timeout`.
36
37
 
37
38
  ## Installation
38
39
 
@@ -141,7 +142,12 @@ compare-and-swap needed):
141
142
  worker's own ticket; if another client deleted it (e.g. `break_other_locks`),
142
143
  acquisition raises instead of "winning" without a ticket. Recovering a ticket
143
144
  via `lock_id=` restores the ticket only - `acquire()` re-runs the election.
144
- 6. **Auto-Cleanup**: `weakref.finalize` deletes ticket objects even if the process
145
+ 6. **Holder re-verification (0.9.3)**: `lock.verify()` re-checks that a holder
146
+ still holds the lock (a fresh listing must show both of its ticket objects) -
147
+ call it at critical boundaries so a broken holder aborts instead of writing
148
+ without mutual exclusion. `break_other_locks()` is age-gated by default
149
+ (only tickets older than 2 hours are broken; the caller's own never are).
150
+ 7. **Auto-Cleanup**: `weakref.finalize` deletes ticket objects even if the process
145
151
  exits unexpectedly (best effort).
146
152
 
147
153
  **Guarantee and residual window**: on storage with strongly consistent listings the
@@ -19,6 +19,7 @@
19
19
  - **Distributed Locking**: Verified shared/exclusive locking on plain object storage - no CAS required (see [docs/locking.md](docs/locking.md)).
20
20
  - **Streaming Support**: Efficiently stream large objects.
21
21
  - **Automatic Retries**: urllib3 retries with exponential backoff for connection errors and transient HTTP statuses (429/5xx); `Retry-After` honored; non-idempotent POSTs are never status-retried.
22
+ - **Slow-link-safe transfers** (0.9.4): timeouts are true *idle* bounds, never total-request deadlines — large uploads are streamed in chunks (bytes bodies over 1 MiB are wrapped automatically), so a slow-but-progressing multi-minute transfer never times out while a genuinely stalled socket still dies within `read_timeout`/`connect_timeout`.
22
23
 
23
24
  ## Installation
24
25
 
@@ -127,7 +128,12 @@ compare-and-swap needed):
127
128
  worker's own ticket; if another client deleted it (e.g. `break_other_locks`),
128
129
  acquisition raises instead of "winning" without a ticket. Recovering a ticket
129
130
  via `lock_id=` restores the ticket only - `acquire()` re-runs the election.
130
- 6. **Auto-Cleanup**: `weakref.finalize` deletes ticket objects even if the process
131
+ 6. **Holder re-verification (0.9.3)**: `lock.verify()` re-checks that a holder
132
+ still holds the lock (a fresh listing must show both of its ticket objects) -
133
+ call it at critical boundaries so a broken holder aborts instead of writing
134
+ without mutual exclusion. `break_other_locks()` is age-gated by default
135
+ (only tickets older than 2 hours are broken; the caller's own never are).
136
+ 7. **Auto-Cleanup**: `weakref.finalize` deletes ticket objects even if the process
131
137
  exits unexpectedly (best effort).
132
138
 
133
139
  **Guarantee and residual window**: on storage with strongly consistent listings the
@@ -130,3 +130,12 @@ exclude_lines = [
130
130
  "if __name__ == .__main__.:",
131
131
  "if TYPE_CHECKING:",
132
132
  ]
133
+
134
+ [tool.pytest.ini_options]
135
+ ## The scale tier (real-network, large-body, release-cadence) is deselected
136
+ ## by default and NEVER runs in CI: opt in with `uv run pytest -m scale`.
137
+ addopts = "-m 'not scale'"
138
+ markers = [
139
+ "scale: real-network large-body tests; run at release cadence with `pytest -m scale` (never CI)",
140
+ ]
141
+ testpaths = ["s3func/tests"]
@@ -6,4 +6,4 @@ from s3func.locking import S3Lock, B2Lock
6
6
  from s3func.http_url import HttpSession
7
7
  from s3func import s3, http_url, utils, b2
8
8
 
9
- __version__ = '0.9.3'
9
+ __version__ = '0.9.4'
@@ -424,9 +424,14 @@ class B2Session:
424
424
 
425
425
  headers = {'Authorization': upload_url_data['auth_token'], 'X-Bz-File-Name': key}
426
426
 
427
- if isinstance(obj, bytes):
427
+ if isinstance(obj, (bytes, bytearray)):
428
428
  headers['Content-Length'] = len(obj)
429
429
  headers['X-Bz-Content-Sha1'] = hashlib.sha1(obj).hexdigest()
430
+ ## Stream large bodies (see s3.py put_object): a monolithic bytes
431
+ ## body is one sendall() with a whole-body deadline. The sha1 above
432
+ ## is computed from the bytes, so integrity verification is kept.
433
+ if len(obj) > utils.stream_body_threshold:
434
+ obj = io.BytesIO(obj)
430
435
  else:
431
436
  if obj.seekable():
432
437
  obj.seek(0, 2)
@@ -471,6 +476,12 @@ class B2Session:
471
476
 
472
477
  counter = 0
473
478
  while True:
479
+ ## Each attempt re-POSTs the body: a file-like obj consumed by the
480
+ ## previous attempt MUST be rewound or the retry sends an empty
481
+ ## stream against a non-zero Content-Length (reachable since the
482
+ ## large-bytes BytesIO wrap above; harmless on the first attempt).
483
+ if hasattr(obj, 'seek'):
484
+ obj.seek(0)
474
485
  resp = self._session.request('post', upload_url, body=obj, headers=headers)
475
486
  if resp.status == 200:
476
487
  break
@@ -24,7 +24,7 @@ from . import utils, response
24
24
  ### Functions
25
25
 
26
26
 
27
- def session(max_connections: int = 10, max_attempts: int = 3, timeout: int = 120):
27
+ def session(max_connections: int = 10, max_attempts: int = 3, timeout: int = 120, connect_timeout: int = 30):
28
28
  """
29
29
  Function to setup a urllib3 pool manager for url downloads.
30
30
 
@@ -36,13 +36,31 @@ def session(max_connections: int = 10, max_attempts: int = 3, timeout: int = 120
36
36
  The number of retries for connection errors and transient HTTP
37
37
  statuses (429, 500, 502, 503, 504). N retries = N+1 attempts.
38
38
  timeout: int
39
- The timeout in seconds.
39
+ The READ timeout in seconds: the maximum time a single read of the
40
+ response may sit without data (an idle timeout), NOT a cap on total
41
+ request duration.
42
+ connect_timeout: int
43
+ Seconds allowed for connection establishment. NOTE: urllib3 leaves
44
+ the socket on this timeout during the request-SEND phase, so it also
45
+ caps each body-send operation - which is why large bytes bodies are
46
+ streamed (see utils.stream_body_threshold): streamed bodies send in
47
+ 16KiB chunks, making this a per-chunk idle bound during upload.
40
48
 
41
49
  Returns
42
50
  -------
43
51
  Pool Manager object
44
52
  """
45
- timeout = urllib3.util.Timeout(timeout)
53
+ ## Timeout semantics, hard-won (2026-07-15 transport review):
54
+ ## - A bare Timeout(x) sets total=x - a hard wall on WHOLE requests.
55
+ ## Never do that: multi-minute uploads/downloads are legitimate.
56
+ ## - read= applies per response-read: slow-but-progressing GETs never
57
+ ## spuriously die; a stalled socket dies within `timeout`.
58
+ ## - connect= ALSO governs each socket send op during the request body
59
+ ## phase. A monolithic bytes body = ONE send op spanning the whole
60
+ ## body, so it must be streamed (put_object wraps large bytes in
61
+ ## BytesIO); then a progressing upload never times out and a genuinely
62
+ ## stalled one dies within `connect_timeout`.
63
+ timeout = urllib3.util.Timeout(connect=connect_timeout, read=timeout)
46
64
  retries = Retry(
47
65
  total=max_attempts,
48
66
  backoff_factor=1,
@@ -68,6 +68,7 @@ class S3Session:
68
68
  retry_mode: str = 'adaptive',
69
69
  read_timeout: int = 120,
70
70
  stream=True,
71
+ connect_timeout: int = 30,
71
72
  ):
72
73
  """
73
74
  Establishes an S3 client connection with an S3 account.
@@ -96,11 +97,15 @@ class S3Session:
96
97
  (it is forwarded through the lock machinery); will be removed
97
98
  at 1.0.
98
99
  read_timeout: int
99
- The read timeout in seconds.
100
+ The read timeout in seconds (per response read - an idle timeout,
101
+ not a total-request cap).
100
102
  stream : bool
101
103
  Should the connection stay open for streaming or should all the data/content be loaded during the initial request.
104
+ connect_timeout : int
105
+ Seconds allowed for connection establishment (also bounds each
106
+ body-send chunk during uploads - see http_url.session).
102
107
  """
103
- self._session = http_url.session(max_pool_connections, max_attempts, read_timeout)
108
+ self._session = http_url.session(max_pool_connections, max_attempts, read_timeout, connect_timeout)
104
109
 
105
110
  from .signer import SigV4Auth
106
111
 
@@ -275,6 +280,19 @@ class S3Session:
275
280
  headers['Content-Length'] = str(obj.tell() - curr)
276
281
  obj.seek(curr)
277
282
 
283
+ # Large bytes bodies MUST be streamed, never sent monolithically:
284
+ # urllib3 transmits a bytes body as ONE sendall() whose socket
285
+ # deadline (the CONNECT timeout during the send phase) covers the
286
+ # WHOLE body and is never extended by progress - any upload slower
287
+ # than len(obj)/connect_timeout dies spuriously mid-transfer and is
288
+ # retried from byte 0. A BytesIO body streams in 16KiB chunks (the
289
+ # timeout becomes per-chunk idle) and stays seekable, so connection-
290
+ # error retries rewind it. Hash while it's still bytes (one C-speed
291
+ # pass) so the signer doesn't re-read the stream to hash it.
292
+ if isinstance(obj, (bytes, bytearray)) and len(obj) > utils.stream_body_threshold:
293
+ headers['x-amz-content-sha256'] = hashlib.sha256(obj).hexdigest()
294
+ obj = io.BytesIO(obj)
295
+
278
296
  # PutObject response is always small, safe to preload
279
297
  resp = self.request('PUT', url, headers=headers, fields=query_params, body=obj, preload_content=True)
280
298
 
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Scale-tier live transport regression (deselected by default; run with
5
+ `uv run pytest -m scale` at release cadence — NEVER in CI).
6
+
7
+ T2 from the 2026-07-15 transport review: the deterministic live reproduction
8
+ of the send-wall defect, link-speed independent — instead of needing a slow
9
+ link and a huge body, it shrinks the wall (connect_timeout=5) and sizes the
10
+ body from a calibration PUT so transmission MUST outlive the wall. On any
11
+ pre-0.9.4 stack this dies at ~5s with TimeoutError('The write operation
12
+ timed out'); on the streamed-body stack it succeeds.
13
+
14
+ Transfer budget: <= ~250 MB per run. All objects deleted in finally.
15
+ """
16
+ import io
17
+ import os
18
+ import pathlib
19
+ import time
20
+
21
+ import pytest
22
+
23
+ try:
24
+ import tomllib as toml
25
+ except ImportError:
26
+ import tomli as toml
27
+
28
+ from s3func import S3Session
29
+
30
+ pytestmark = pytest.mark.scale
31
+
32
+ script_path = pathlib.Path(os.path.realpath(os.path.dirname(__file__)))
33
+
34
+ try:
35
+ with io.open(script_path.joinpath('s3_config.toml'), 'rb') as f:
36
+ _cc = toml.load(f)['connection_config']
37
+ endpoint_url = _cc['endpoint_url']
38
+ access_key_id = _cc['aws_access_key_id']
39
+ access_key = _cc['aws_secret_access_key']
40
+ _HAVE_CREDS = True
41
+ except Exception:
42
+ _HAVE_CREDS = os.environ.get('aws_secret_access_key') is not None
43
+ if _HAVE_CREDS:
44
+ endpoint_url = os.environ['endpoint_url']
45
+ access_key_id = os.environ['aws_access_key_id']
46
+ access_key = os.environ['aws_secret_access_key']
47
+
48
+ bucket = 'achelous'
49
+ _PREFIX = 'scale-transport-'
50
+
51
+
52
+ @pytest.mark.skipif(not _HAVE_CREDS, reason='no s3 credentials available')
53
+ def test_send_wall_live():
54
+ """A single PUT sized to legitimately outlive a 5s send wall must succeed
55
+ (and the elapsed-time assert proves the test really was in the failing
56
+ regime, not on a link so fast the wall was never at risk)."""
57
+ session = S3Session(access_key_id, access_key, bucket, endpoint_url,
58
+ max_attempts=0, read_timeout=60, connect_timeout=5)
59
+ keys = []
60
+ try:
61
+ ## Calibrate: single-stream throughput varies hour to hour - never
62
+ ## hardcode a rate (transport review, NOTE-6).
63
+ cal = os.urandom(16 * 2**20)
64
+ t0 = time.monotonic()
65
+ resp = session.put_object(_PREFIX + 'cal', cal)
66
+ keys.append(_PREFIX + 'cal')
67
+ assert resp.status == 200
68
+ rate = len(cal) / (time.monotonic() - t0)
69
+
70
+ ## Size the body for ~15x the wall at the calibrated rate, bounded.
71
+ size = int(min(max(15 * 5 * rate, 48 * 2**20), 200 * 2**20))
72
+ body = os.urandom(size)
73
+ t0 = time.monotonic()
74
+ resp = session.put_object(_PREFIX + 'wall', body)
75
+ keys.append(_PREFIX + 'wall')
76
+ elapsed = time.monotonic() - t0
77
+
78
+ assert resp.status == 200, f'PUT failed: {resp.status}'
79
+ assert elapsed > 5.0, (
80
+ f'{size / 2**20:.0f}MiB completed in {elapsed:.1f}s - the link is too fast '
81
+ 'for this wall; the regime proof failed (raise the size bound)'
82
+ )
83
+ finally:
84
+ for key in keys:
85
+ session.delete_object(key)
86
+ leftover = [o['key'] for o in session.list_objects(prefix=_PREFIX).iter_objects()]
87
+ assert not leftover, f'test objects not cleaned up: {leftover}'
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Tripwire for the 0.9.4 large-upload streaming fix: a slow-but-PROGRESSING
5
+ upload whose transmission time exceeds the socket timeout must succeed.
6
+
7
+ Pre-0.9.4, put_object handed urllib3 a monolithic `bytes` body, which is
8
+ transmitted as ONE sendall() whose deadline is fixed at entry and never
9
+ extended by progress - the upload died at exactly the timeout with
10
+ TimeoutError('The write operation timed out') on a healthy connection.
11
+ Streaming the body (BytesIO -> 16KiB chunks) makes the timeout per-chunk.
12
+
13
+ Runs against a local throttled sink - no credentials, no network, no TLS
14
+ (the deadline mechanism is not TLS-specific).
15
+ """
16
+ import io
17
+ import socket
18
+ import threading
19
+ import time
20
+
21
+ from s3func import S3Session, utils
22
+
23
+ ##############################################
24
+ ### Throttled sink
25
+
26
+ _DRAIN_CHUNK = 65536
27
+ _DRAIN_SLEEP = 0.01 # ~6.4 MB/s drain rate
28
+
29
+
30
+ class _ThrottledSink:
31
+ """Accepts ONE HTTP request, drains its body at a throttled rate through a
32
+ small receive buffer, then replies 200. The small RCVBUF caps the TCP
33
+ window, so the client cannot dump the whole body into kernel buffers -
34
+ its send path genuinely has to wait on the drain, which is what pushes a
35
+ monolithic-bytes sendall past the send wall."""
36
+
37
+ def __init__(self):
38
+ self._srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
39
+ self._srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
40
+ self._srv.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 65536)
41
+ self._srv.bind(('127.0.0.1', 0))
42
+ self._srv.listen(1)
43
+ self.port = self._srv.getsockname()[1]
44
+ self.bytes_received = 0
45
+ self._thread = threading.Thread(target=self._serve, daemon=True)
46
+ self._thread.start()
47
+
48
+ def _serve(self):
49
+ conn, _ = self._srv.accept()
50
+ conn.settimeout(60)
51
+ try:
52
+ buf = b''
53
+ while b'\r\n\r\n' not in buf:
54
+ data = conn.recv(4096)
55
+ if not data:
56
+ return
57
+ buf += data
58
+ head, _, rest = buf.partition(b'\r\n\r\n')
59
+ content_length = 0
60
+ for line in head.split(b'\r\n'):
61
+ if line.lower().startswith(b'content-length:'):
62
+ content_length = int(line.split(b':', 1)[1])
63
+ self.bytes_received = len(rest)
64
+ remaining = content_length - len(rest)
65
+ while remaining > 0:
66
+ chunk = conn.recv(min(_DRAIN_CHUNK, remaining))
67
+ if not chunk:
68
+ return
69
+ remaining -= len(chunk)
70
+ self.bytes_received += len(chunk)
71
+ time.sleep(_DRAIN_SLEEP)
72
+ conn.sendall(b'HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n')
73
+ finally:
74
+ conn.close()
75
+ self._srv.close()
76
+
77
+
78
+ ##############################################
79
+ ### Tests
80
+
81
+
82
+ def test_large_upload_survives_send_wall():
83
+ """The core invariant: send progress must extend the upload's life.
84
+ The body is sized past what the kernel can locally queue (tcp_wmem max),
85
+ so the sender must genuinely outlive the 2s connect/send wall - the
86
+ pre-0.9.4 monolithic path dies at ~2.0s here."""
87
+ wmem_max = 4 * 2**20
88
+ try:
89
+ with open('/proc/sys/net/ipv4/tcp_wmem') as f:
90
+ wmem_max = int(f.read().split()[2])
91
+ except OSError:
92
+ pass
93
+ body = b'x' * (wmem_max + 24 * 2**20)
94
+
95
+ sink = _ThrottledSink()
96
+ session = S3Session('test-key-id', 'test-secret', 'testbucket',
97
+ endpoint_url=f'http://127.0.0.1:{sink.port}',
98
+ max_attempts=0, read_timeout=60, connect_timeout=2)
99
+ t0 = time.monotonic()
100
+ resp = session.put_object('tripwire-key', body)
101
+ elapsed = time.monotonic() - t0
102
+
103
+ assert resp.status == 200
104
+ assert sink.bytes_received == len(body), 'the sink did not receive the full body'
105
+ ## Regime proof: the send outlived the wall, i.e. this test really was in
106
+ ## the territory where the monolithic path times out.
107
+ assert elapsed > 2.0
108
+
109
+
110
+ def test_bytes_wrap_threshold():
111
+ """Bodies over utils.stream_body_threshold reach the transport as a
112
+ seekable stream with the SigV4 payload hash precomputed from the bytes;
113
+ small bodies stay bytes (byte-identical legacy path)."""
114
+ captured = {}
115
+
116
+ class _CaptureSession(S3Session):
117
+ def request(self, method, url, headers=None, fields=None, body=None, preload_content=None):
118
+ captured['body'] = body
119
+ captured['headers'] = dict(headers or {})
120
+
121
+ class _Resp:
122
+ status = 200
123
+ headers = {}
124
+ data = b''
125
+
126
+ return _Resp()
127
+
128
+ s = _CaptureSession('k', 's', 'b', endpoint_url='http://127.0.0.1:1/')
129
+
130
+ s.put_object('small', b'tiny')
131
+ assert isinstance(captured['body'], bytes)
132
+ assert 'x-amz-content-sha256' not in captured['headers']
133
+
134
+ big = b'y' * (utils.stream_body_threshold + 1)
135
+ s.put_object('big', big)
136
+ assert isinstance(captured['body'], io.BytesIO)
137
+ assert captured['body'].read() == big
138
+ assert 'x-amz-content-sha256' in captured['headers']
139
+ assert captured['headers']['Content-Length'] == str(len(big))
@@ -23,6 +23,13 @@ from urllib.parse import urlparse
23
23
  #######################################################
24
24
  ### Parameters
25
25
 
26
+ ## Bytes bodies larger than this are wrapped in io.BytesIO before upload so
27
+ ## urllib3 streams them in 16KiB chunks. A monolithic bytes body is sent as
28
+ ## ONE socket sendall() whose deadline covers the WHOLE body (progress does
29
+ ## not extend it) - any upload slower than body/timeout dies spuriously
30
+ ## mid-transfer. Streaming makes the timeout per-chunk: a true idle timeout.
31
+ stream_body_threshold = 2**20
32
+
26
33
  # key_patterns = {
27
34
  # 'b2': '{base_url}/{bucket}/{obj_key}',
28
35
  # 'contabo': '{base_url}:{bucket}/{obj_key}',
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes