s3func 0.9.2__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.2
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.2'
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,
@@ -41,6 +41,12 @@ ACQUIRED = 'acquired'
41
41
  WAIT = 'wait'
42
42
  TICKET_LOST = 'ticket_lost'
43
43
 
44
+ ## Default age gate for break_other_locks: tickets younger than this are
45
+ ## presumed to belong to a LIVE writer (ticket timestamps reflect session
46
+ ## START, not activity - long bulk sessions are normal) and are not broken
47
+ ## by a default-argument call. Override with an explicit timestamp.
48
+ default_break_age = 7200 # seconds (2 hours)
49
+
44
50
  ## Session registry: maps a service name to a session class. A callable may also
45
51
  ## be passed directly as the service (e.g. a fake session factory in tests, or a
46
52
  ## future CAS-capable provider session - see benchmarks/conditional_write_probe.py
@@ -389,15 +395,36 @@ class DistributedLock:
389
395
  return other_locks
390
396
 
391
397
  def break_other_locks(self, timestamp: str | datetime.datetime = None):
398
+ """
399
+ Delete OTHER contenders' lock tickets uploaded at or before a cutoff.
400
+
401
+ By default the cutoff is ``default_break_age`` seconds (2 hours) ago:
402
+ younger tickets are presumed to belong to a LIVE writer - ticket
403
+ timestamps reflect session start, not activity, and long-running
404
+ write sessions are normal. Breaking a live holder's ticket does not
405
+ corrupt anything by itself, but the holder's next ``verify()`` will
406
+ return False and it must abort its protected operation (losing that
407
+ work). Pass an explicit ``timestamp`` to override the gate (e.g. now,
408
+ to break everything regardless of age).
409
+
410
+ The caller's OWN tickets are never deleted (before 0.9.3 the default
411
+ cutoff was "now" and included them, killing the caller's own
412
+ in-flight election).
413
+
414
+ Returns the list of deleted ticket objects.
415
+ """
392
416
  if timestamp is None:
393
- timestamp = datetime.datetime.now(datetime.timezone.utc)
417
+ timestamp = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(seconds=default_break_age)
394
418
  elif isinstance(timestamp, str):
395
419
  timestamp = datetime.datetime.fromisoformat(timestamp).astimezone(datetime.timezone.utc)
396
420
 
397
421
  session = init_session(self._service, self._session_kwargs)
398
422
  objs = self._list_objects(session, self._obj_lock_key)
399
423
  keys = []
424
+ own_prefix = self._obj_lock_key + self.lock_id + '-'
400
425
  for l in objs:
426
+ if l['key'].startswith(own_prefix):
427
+ continue
401
428
  if l['upload_timestamp'] <= timestamp:
402
429
  d = {'key': l['key']}
403
430
  if l.get('version_id'):
@@ -408,6 +435,34 @@ class DistributedLock:
408
435
 
409
436
  return keys
410
437
 
438
+ def verify(self):
439
+ """
440
+ Re-verify that THIS instance still holds the lock.
441
+
442
+ Returns True only if the election was won (``acquire()`` returned True
443
+ and ``release()`` has not been called) AND a fresh listing still shows
444
+ both of this instance's ticket objects. A False from a previous holder
445
+ means the ticket was broken (another client's ``break_other_locks``) -
446
+ mutual exclusion is gone and the protected operation must not proceed.
447
+
448
+ Under listing staleness the failure direction is a spurious False
449
+ (safe abort): the self-visibility gate already established that the
450
+ listing showed this ticket once, so a listing that stops showing a
451
+ long-since-written object is treated as a deletion signal.
452
+ """
453
+ if not self._acquired:
454
+ return False
455
+
456
+ session = init_session(self._service, self._session_kwargs)
457
+ objs = self._list_objects(session, self._obj_lock_key, lock_id=self.lock_id)
458
+ seqs = set()
459
+ for l in objs:
460
+ parts = l['key'][self._obj_lock_key_len:].split('-')
461
+ if len(parts) == 2 and parts[0] == self.lock_id:
462
+ seqs.add(parts[1])
463
+
464
+ return '0' in seqs and '1' in seqs
465
+
411
466
  def locked(self):
412
467
  session = init_session(self._service, self._session_kwargs)
413
468
  return len(self._list_objects(session, self._obj_lock_key)) > 0
@@ -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
 
@@ -425,3 +425,105 @@ def test_election_all_tied_single_winner():
425
425
  results = [evaluate_election(i, True, tickets) for i in ids]
426
426
  assert results.count(ACQUIRED) == 1 and results.count(WAIT) == 3
427
427
  assert results[0] == ACQUIRED # lexicographically smallest id wins
428
+
429
+ #################################################
430
+ ### 0.9.3: age-gated break_other_locks + holder verify()
431
+
432
+
433
+ def _age_tickets(store, lock_id, when):
434
+ """Stamp both ticket objects of lock_id with an absolute upload time."""
435
+ for k, e in store.objects.items():
436
+ if lock_id in k:
437
+ e['upload_timestamp'] = when
438
+
439
+
440
+ def test_break_other_locks_age_gate_default():
441
+ ## Default call must break only tickets older than default_break_age;
442
+ ## a fresh (live-writer) ticket survives.
443
+ store = FakeStore()
444
+ now = datetime.datetime.now(datetime.timezone.utc)
445
+
446
+ old = FakeLock(store, 'k')
447
+ old._put_lock_objects(True)
448
+ _age_tickets(store, old.lock_id, now - datetime.timedelta(hours=3))
449
+
450
+ live = FakeLock(store, 'k')
451
+ assert live.acquire() is True
452
+ _age_tickets(store, live.lock_id, now)
453
+
454
+ breaker = FakeLock(store, 'k')
455
+ deleted = breaker.break_other_locks()
456
+
457
+ deleted_keys = {d['key'] for d in deleted}
458
+ assert any(old.lock_id in k for k in deleted_keys), 'aged-out ticket not broken'
459
+ assert not any(live.lock_id in k for k in deleted_keys), 'default break killed a live ticket'
460
+ assert any(live.lock_id in k for k in store.objects), 'live ticket removed from the store'
461
+ live.release()
462
+ old._finalizer.detach()
463
+
464
+
465
+ def test_break_other_locks_explicit_now_breaks_all_others():
466
+ store = FakeStore()
467
+ now = datetime.datetime.now(datetime.timezone.utc)
468
+
469
+ live = FakeLock(store, 'k')
470
+ assert live.acquire() is True
471
+ _age_tickets(store, live.lock_id, now)
472
+
473
+ breaker = FakeLock(store, 'k')
474
+ deleted = breaker.break_other_locks(timestamp=now + datetime.timedelta(seconds=1))
475
+ assert any(live.lock_id in k for d in deleted for k in [d['key']])
476
+ assert not any(live.lock_id in k for k in store.objects)
477
+
478
+
479
+ def test_break_other_locks_never_breaks_own():
480
+ ## Even with an explicit force-everything timestamp, the caller's own
481
+ ## tickets must survive (pre-0.9.3 the default deleted them too).
482
+ store = FakeStore()
483
+ now = datetime.datetime.now(datetime.timezone.utc)
484
+
485
+ breaker = FakeLock(store, 'k')
486
+ breaker._put_lock_objects(True)
487
+ _age_tickets(store, breaker.lock_id, now - datetime.timedelta(days=1))
488
+
489
+ deleted = breaker.break_other_locks(timestamp=now)
490
+ assert deleted == []
491
+ own = [k for k in store.objects if breaker.lock_id in k]
492
+ assert len(own) == 2, 'break_other_locks deleted the caller\'s own tickets'
493
+ breaker._finalizer.detach()
494
+
495
+
496
+ def test_verify_holder_and_broken_ticket():
497
+ store = FakeStore()
498
+ a = FakeLock(store, 'k')
499
+
500
+ ## Not acquired -> False, even before any tickets exist.
501
+ assert a.verify() is False
502
+
503
+ assert a.acquire() is True
504
+ assert a.verify() is True
505
+
506
+ ## A ticket-holding NON-winner must verify False (ticket != lock).
507
+ b = FakeLock(store, 'k')
508
+ b._put_lock_objects(True)
509
+ assert b.verify() is False
510
+ b.release()
511
+
512
+ ## Break the holder's ticket behind its back -> verify() goes False.
513
+ for k in [k for k in store.objects if a.lock_id in k]:
514
+ del store.objects[k]
515
+ assert a.verify() is False
516
+
517
+ a.release()
518
+ assert a.verify() is False
519
+
520
+
521
+ def test_verify_partial_ticket_is_false():
522
+ ## Only one of the two seq objects left -> not held.
523
+ store = FakeStore()
524
+ a = FakeLock(store, 'k')
525
+ assert a.acquire() is True
526
+ seq0 = [k for k in store.objects if a.lock_id in k and k.endswith('-0')]
527
+ del store.objects[seq0[0]]
528
+ assert a.verify() is False
529
+ a.release()
@@ -1,6 +1,7 @@
1
1
  import pytest
2
2
  import os, pathlib
3
3
  import uuid
4
+ import datetime
4
5
  from time import sleep
5
6
  import concurrent.futures
6
7
 
@@ -165,3 +166,30 @@ def test_s3_lock_shared(s3_session):
165
166
  r2.release()
166
167
  w.release()
167
168
  assert w.locked() is False
169
+
170
+ def test_s3_lock_age_gate_and_verify(s3_session):
171
+ """0.9.3 live: a default break_other_locks spares a fresh (live) holder's
172
+ tickets; an explicit now-cutoff breaks them; the holder's verify() tracks
173
+ it (True while held, False after the break)."""
174
+ obj_key = uuid.uuid4().hex
175
+
176
+ holder = s3_session.lock(obj_key)
177
+ assert holder.acquire() is True
178
+ try:
179
+ assert holder.verify() is True
180
+
181
+ breaker = s3_session.lock(obj_key)
182
+
183
+ ## Age-gated default: the holder's minutes-old ticket must survive.
184
+ deleted = breaker.break_other_locks()
185
+ assert deleted == [], 'default break_other_locks deleted a fresh ticket'
186
+ assert holder.verify() is True
187
+
188
+ ## Explicit now-cutoff: the holder's ticket goes; its verify() fails safe.
189
+ deleted = breaker.break_other_locks(datetime.datetime.now(datetime.timezone.utc))
190
+ assert len(deleted) == 2
191
+ assert holder.verify() is False
192
+ finally:
193
+ holder.release()
194
+ ## Sweep any leftovers so the bucket stays clean.
195
+ s3_session.lock(obj_key).break_other_locks(datetime.datetime.now(datetime.timezone.utc))
@@ -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