s3func 0.9.0__tar.gz → 0.9.2__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.
- {s3func-0.9.0 → s3func-0.9.2}/PKG-INFO +5 -3
- {s3func-0.9.0 → s3func-0.9.2}/README.md +4 -2
- {s3func-0.9.0 → s3func-0.9.2}/s3func/__init__.py +1 -1
- {s3func-0.9.0 → s3func-0.9.2}/s3func/b2.py +5 -1
- {s3func-0.9.0 → s3func-0.9.2}/s3func/http_url.py +19 -2
- {s3func-0.9.0 → s3func-0.9.2}/s3func/response.py +40 -0
- {s3func-0.9.0 → s3func-0.9.2}/s3func/s3.py +49 -5
- s3func-0.9.2/s3func/tests/test_delete_objects.py +136 -0
- s3func-0.9.2/s3func/tests/test_retry.py +189 -0
- {s3func-0.9.0 → s3func-0.9.2}/.gitignore +0 -0
- {s3func-0.9.0 → s3func-0.9.2}/LICENSE +0 -0
- {s3func-0.9.0 → s3func-0.9.2}/pyproject.toml +0 -0
- {s3func-0.9.0 → s3func-0.9.2}/s3func/locking.py +0 -0
- {s3func-0.9.0 → s3func-0.9.2}/s3func/signer.py +0 -0
- {s3func-0.9.0 → s3func-0.9.2}/s3func/tests/__init__.py +0 -0
- {s3func-0.9.0 → s3func-0.9.2}/s3func/tests/conftest.py +0 -0
- {s3func-0.9.0 → s3func-0.9.2}/s3func/tests/test_lock_model.py +0 -0
- {s3func-0.9.0 → s3func-0.9.2}/s3func/tests/test_locks.py +0 -0
- {s3func-0.9.0 → s3func-0.9.2}/s3func/tests/test_mock_s3.py +0 -0
- {s3func-0.9.0 → s3func-0.9.2}/s3func/tests/test_s3func.py +0 -0
- {s3func-0.9.0 → s3func-0.9.2}/s3func/utils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: s3func
|
|
3
|
-
Version: 0.9.
|
|
3
|
+
Version: 0.9.2
|
|
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
|
|
@@ -32,7 +32,7 @@ Description-Content-Type: text/markdown
|
|
|
32
32
|
- **Provider-Agnostic**: One `S3Session` for AWS S3 and any S3-compatible provider (Backblaze B2, MEGA S4, ...), with provider quirks handled portably (strict RFC3986 signing of paths and queries).
|
|
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
|
-
- **Automatic Retries**:
|
|
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
36
|
|
|
37
37
|
## Installation
|
|
38
38
|
|
|
@@ -116,7 +116,9 @@ if lock.acquire(blocking=True, timeout=10):
|
|
|
116
116
|
## Performance Tips
|
|
117
117
|
|
|
118
118
|
- **Streaming**: Set `stream=True` in the session (default) or individual requests to handle large files without loading them entirely into memory.
|
|
119
|
-
- **
|
|
119
|
+
- **Retries**: All sessions share one `urllib3` Retry policy (`max_attempts` retries, exponential backoff): connection errors and transient statuses (429, 500, 502, 503, 504) are retried on idempotent methods; when retries exhaust, the final response is returned (never an exception) so callers can inspect `resp.status`/`resp.error`. POST requests (S3 multi-object-delete, B2-native uploads) are never status-retried.
|
|
120
|
+
|
|
121
|
+
Changes between releases are tracked in [CHANGELOG.md](CHANGELOG.md).
|
|
120
122
|
|
|
121
123
|
## How Distributed Locking Works
|
|
122
124
|
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
- **Provider-Agnostic**: One `S3Session` for AWS S3 and any S3-compatible provider (Backblaze B2, MEGA S4, ...), with provider quirks handled portably (strict RFC3986 signing of paths and queries).
|
|
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
|
-
- **Automatic Retries**:
|
|
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
22
|
|
|
23
23
|
## Installation
|
|
24
24
|
|
|
@@ -102,7 +102,9 @@ if lock.acquire(blocking=True, timeout=10):
|
|
|
102
102
|
## Performance Tips
|
|
103
103
|
|
|
104
104
|
- **Streaming**: Set `stream=True` in the session (default) or individual requests to handle large files without loading them entirely into memory.
|
|
105
|
-
- **
|
|
105
|
+
- **Retries**: All sessions share one `urllib3` Retry policy (`max_attempts` retries, exponential backoff): connection errors and transient statuses (429, 500, 502, 503, 504) are retried on idempotent methods; when retries exhaust, the final response is returned (never an exception) so callers can inspect `resp.status`/`resp.error`. POST requests (S3 multi-object-delete, B2-native uploads) are never status-retried.
|
|
106
|
+
|
|
107
|
+
Changes between releases are tracked in [CHANGELOG.md](CHANGELOG.md).
|
|
106
108
|
|
|
107
109
|
## How Distributed Locking Works
|
|
108
110
|
|
|
@@ -164,7 +164,11 @@ class B2Session:
|
|
|
164
164
|
max_connections : int
|
|
165
165
|
The number of simultaneous connections for the B2 connection.
|
|
166
166
|
max_attempts: int
|
|
167
|
-
The number of retries
|
|
167
|
+
The number of retries for connection errors and transient HTTP
|
|
168
|
+
statuses (429, 500, 502, 503, 504) on non-POST requests.
|
|
169
|
+
N retries = N+1 attempts. (The B2-native upload/copy/delete calls
|
|
170
|
+
are POSTs and are never status-retried; put_object keeps its own
|
|
171
|
+
manual retry loop.)
|
|
168
172
|
read_timeout: int
|
|
169
173
|
The read timeout in seconds.
|
|
170
174
|
download_url : str or None
|
|
@@ -33,7 +33,8 @@ def session(max_connections: int = 10, max_attempts: int = 3, timeout: int = 120
|
|
|
33
33
|
max_connections : int
|
|
34
34
|
The number of simultaneous connections for the S3 connection.
|
|
35
35
|
max_attempts: int
|
|
36
|
-
The number of retries
|
|
36
|
+
The number of retries for connection errors and transient HTTP
|
|
37
|
+
statuses (429, 500, 502, 503, 504). N retries = N+1 attempts.
|
|
37
38
|
timeout: int
|
|
38
39
|
The timeout in seconds.
|
|
39
40
|
|
|
@@ -45,6 +46,21 @@ def session(max_connections: int = 10, max_attempts: int = 3, timeout: int = 120
|
|
|
45
46
|
retries = Retry(
|
|
46
47
|
total=max_attempts,
|
|
47
48
|
backoff_factor=1,
|
|
49
|
+
# Transient statuses are retried with exponential backoff (Retry-After
|
|
50
|
+
# honored when present - note urllib3 obeys it uncapped, so a
|
|
51
|
+
# misconfigured endpoint sending a huge Retry-After can block up to
|
|
52
|
+
# max_attempts * that value). POST is deliberately NOT in the retried
|
|
53
|
+
# methods (urllib3 default): the S3 multi-object-delete and the
|
|
54
|
+
# B2-native upload paths are POSTs, and b2.put_object has its own
|
|
55
|
+
# manual retry loop that must not compound with this one.
|
|
56
|
+
status_forcelist=(429, 500, 502, 503, 504),
|
|
57
|
+
# Callers dispatch on resp.status (locking lock-PUT check, delete_objects
|
|
58
|
+
# per-chunk failure handling, list iterators) and never expect a raise:
|
|
59
|
+
# when retries exhaust, the LAST response must be returned, not
|
|
60
|
+
# MaxRetryError. A status-retried PUT body is fine here because all
|
|
61
|
+
# internal PUT bodies are bytes (non-seekable file bodies would not be
|
|
62
|
+
# rewound - pre-existing hazard shared with connection-error retries).
|
|
63
|
+
raise_on_status=False,
|
|
48
64
|
)
|
|
49
65
|
http = urllib3.PoolManager(maxsize=max_connections, timeout=timeout, retries=retries, block=True)
|
|
50
66
|
|
|
@@ -76,7 +92,8 @@ class HttpSession:
|
|
|
76
92
|
max_connections : int
|
|
77
93
|
The number of simultaneous connections for the S3 connection.
|
|
78
94
|
max_attempts: int
|
|
79
|
-
The number of retries
|
|
95
|
+
The number of retries for connection errors and transient HTTP
|
|
96
|
+
statuses (429, 500, 502, 503, 504). N retries = N+1 attempts.
|
|
80
97
|
read_timeout: int
|
|
81
98
|
The read timeout in seconds.
|
|
82
99
|
stream : bool
|
|
@@ -227,6 +227,46 @@ class S3ListResponse:
|
|
|
227
227
|
return f'status: {self.status}'
|
|
228
228
|
|
|
229
229
|
|
|
230
|
+
def parse_delete_errors(data):
|
|
231
|
+
"""
|
|
232
|
+
Parse a multi-object-delete DeleteResult body and return the per-key failures
|
|
233
|
+
as a list of {'key', 'code', 'message'} dicts (empty list = full success).
|
|
234
|
+
Quiet mode suppresses only <Deleted> entries - <Error> elements still arrive
|
|
235
|
+
in a 200 response, so a caller that skips this parse mistakes partial failure
|
|
236
|
+
for success. An empty body is full success (some providers send none when all
|
|
237
|
+
deletes succeed in quiet mode); an unparseable non-empty body raises.
|
|
238
|
+
"""
|
|
239
|
+
if not data or not data.strip():
|
|
240
|
+
return []
|
|
241
|
+
|
|
242
|
+
try:
|
|
243
|
+
root = ET.fromstring(data)
|
|
244
|
+
except ET.ParseError:
|
|
245
|
+
raise urllib3.exceptions.HTTPError('Failed to parse S3 multi-delete XML response')
|
|
246
|
+
|
|
247
|
+
# Determine namespace from root tag
|
|
248
|
+
if '}' in root.tag:
|
|
249
|
+
ns_url = root.tag.split('}')[0][1:]
|
|
250
|
+
ns = {'s3': ns_url}
|
|
251
|
+
error_path, key_path, code_path, msg_path = 's3:Error', 's3:Key', 's3:Code', 's3:Message'
|
|
252
|
+
else:
|
|
253
|
+
ns = {}
|
|
254
|
+
error_path, key_path, code_path, msg_path = 'Error', 'Key', 'Code', 'Message'
|
|
255
|
+
|
|
256
|
+
errors = []
|
|
257
|
+
for err in root.findall(error_path, ns):
|
|
258
|
+
key_el = err.find(key_path, ns)
|
|
259
|
+
code_el = err.find(code_path, ns)
|
|
260
|
+
msg_el = err.find(msg_path, ns)
|
|
261
|
+
errors.append({
|
|
262
|
+
'key': key_el.text if key_el is not None else None,
|
|
263
|
+
'code': code_el.text if code_el is not None else None,
|
|
264
|
+
'message': msg_el.text if msg_el is not None else None,
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
return errors
|
|
268
|
+
|
|
269
|
+
|
|
230
270
|
def iter_b2_list(session, url, headers, params):
|
|
231
271
|
""" """
|
|
232
272
|
while True:
|
|
@@ -87,11 +87,16 @@ class S3Session:
|
|
|
87
87
|
max_pool_connections : int
|
|
88
88
|
The number of simultaneous connections for the S3 connection.
|
|
89
89
|
max_attempts: int
|
|
90
|
-
The number of
|
|
90
|
+
The number of retries for connection errors and transient HTTP
|
|
91
|
+
statuses (429, 500, 502, 503, 504). N retries = N+1 attempts.
|
|
91
92
|
retry_mode: str
|
|
92
|
-
|
|
93
|
+
.. deprecated:: 0.9.2
|
|
94
|
+
Unused. Retry behavior is the fixed urllib3 Retry policy
|
|
95
|
+
configured via max_attempts. Kept for signature compatibility
|
|
96
|
+
(it is forwarded through the lock machinery); will be removed
|
|
97
|
+
at 1.0.
|
|
93
98
|
read_timeout: int
|
|
94
|
-
The read timeout in seconds
|
|
99
|
+
The read timeout in seconds.
|
|
95
100
|
stream : bool
|
|
96
101
|
Should the connection stay open for streaming or should all the data/content be loaded during the initial request.
|
|
97
102
|
"""
|
|
@@ -385,7 +390,14 @@ class S3Session:
|
|
|
385
390
|
|
|
386
391
|
Returns
|
|
387
392
|
-------
|
|
388
|
-
None
|
|
393
|
+
None on full success.
|
|
394
|
+
|
|
395
|
+
Raises
|
|
396
|
+
------
|
|
397
|
+
urllib3.exceptions.HTTPError
|
|
398
|
+
If any object fails to delete (whole-batch HTTP failure or per-key
|
|
399
|
+
errors in the DeleteResult). All chunks are attempted before raising,
|
|
400
|
+
so everything deletable is deleted; the error lists the failed keys.
|
|
389
401
|
"""
|
|
390
402
|
if keys is not None and prefix is not None:
|
|
391
403
|
raise ValueError('keys and prefix are mutually exclusive.')
|
|
@@ -451,6 +463,7 @@ class S3Session:
|
|
|
451
463
|
# <Delete><Object><Key>...</Key><VersionId>...</VersionId></Object>...</Delete>
|
|
452
464
|
url = urllib.parse.urljoin(self._endpoint_url, f"{self.bucket}")
|
|
453
465
|
|
|
466
|
+
failures = []
|
|
454
467
|
for keys_chunk in utils.chunks(keys, 1000):
|
|
455
468
|
# Build XML
|
|
456
469
|
root = ET.Element('Delete', xmlns="http://s3.amazonaws.com/doc/2006-03-01/")
|
|
@@ -478,7 +491,38 @@ class S3Session:
|
|
|
478
491
|
md5 = base64.b64encode(hashlib.md5(body).digest()).decode('utf-8')
|
|
479
492
|
headers = {'Content-MD5': md5, 'Content-Type': 'application/xml'}
|
|
480
493
|
|
|
481
|
-
|
|
494
|
+
## The POST response must be checked: urllib3 does not raise on HTTP
|
|
495
|
+
## status, and Quiet=true still returns per-key <Error> elements -
|
|
496
|
+
## ignoring either silently no-ops the deletes. All chunks are still
|
|
497
|
+
## attempted (best effort) before any raise.
|
|
498
|
+
resp = self.request('POST', url, headers=headers, fields=query_params, body=body, preload_content=True)
|
|
499
|
+
if (resp.status // 100) != 2:
|
|
500
|
+
reason = resp.data[:200] if resp.data else b''
|
|
501
|
+
for k in keys_chunk:
|
|
502
|
+
failures.append({
|
|
503
|
+
'key': k.get('key') or k.get('Key'),
|
|
504
|
+
'code': str(resp.status),
|
|
505
|
+
'message': reason.decode('utf-8', errors='replace'),
|
|
506
|
+
})
|
|
507
|
+
else:
|
|
508
|
+
try:
|
|
509
|
+
failures.extend(response.parse_delete_errors(resp.data))
|
|
510
|
+
except urllib3.exceptions.HTTPError:
|
|
511
|
+
# Unparseable 200 body: the chunk's outcome is unknown - record
|
|
512
|
+
# it as failed rather than aborting the remaining chunks.
|
|
513
|
+
for k in keys_chunk:
|
|
514
|
+
failures.append({
|
|
515
|
+
'key': k.get('key') or k.get('Key'),
|
|
516
|
+
'code': 'unparseable-response',
|
|
517
|
+
'message': (resp.data[:200] if resp.data else b'').decode('utf-8', errors='replace'),
|
|
518
|
+
})
|
|
519
|
+
|
|
520
|
+
if failures:
|
|
521
|
+
shown = ', '.join(f"{f['key']} ({f['code']}: {f['message']})" for f in failures[:5])
|
|
522
|
+
more = f' (+{len(failures) - 5} more)' if len(failures) > 5 else ''
|
|
523
|
+
raise urllib3.exceptions.HTTPError(
|
|
524
|
+
f'S3 multi-delete failed for {len(failures)} key(s): {shown}{more}'
|
|
525
|
+
)
|
|
482
526
|
|
|
483
527
|
def copy_object(
|
|
484
528
|
self,
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Unit tests (no network) for the multi-object-delete response checking (0.9.1).
|
|
3
|
+
|
|
4
|
+
Regression context: delete_objects used to fire the batched POST and discard the
|
|
5
|
+
response entirely - urllib3 does not raise on HTTP status, and Quiet=true mode
|
|
6
|
+
still returns per-key <Error> elements, so failed deletes reported success.
|
|
7
|
+
"""
|
|
8
|
+
from types import SimpleNamespace
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
import urllib3
|
|
12
|
+
|
|
13
|
+
from s3func import S3Session
|
|
14
|
+
from s3func.response import parse_delete_errors
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
#################################################
|
|
18
|
+
### parse_delete_errors (pure)
|
|
19
|
+
|
|
20
|
+
NS = 'http://s3.amazonaws.com/doc/2006-03-01/'
|
|
21
|
+
|
|
22
|
+
BODY_NAMESPACED_TWO_ERRORS = f'''<?xml version="1.0" encoding="UTF-8"?>
|
|
23
|
+
<DeleteResult xmlns="{NS}">
|
|
24
|
+
<Error><Key>k1</Key><Code>AccessDenied</Code><Message>denied</Message></Error>
|
|
25
|
+
<Error><Key>k2</Key><Code>InternalError</Code><Message>oops</Message></Error>
|
|
26
|
+
</DeleteResult>'''.encode()
|
|
27
|
+
|
|
28
|
+
BODY_PLAIN_ONE_ERROR = b'''<DeleteResult>
|
|
29
|
+
<Deleted><Key>k0</Key></Deleted>
|
|
30
|
+
<Error><Key>k1</Key><Code>NoSuchVersion</Code><Message>gone</Message></Error>
|
|
31
|
+
</DeleteResult>'''
|
|
32
|
+
|
|
33
|
+
BODY_ALL_SUCCESS = f'<DeleteResult xmlns="{NS}"></DeleteResult>'.encode()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_parse_namespaced_errors():
|
|
37
|
+
errors = parse_delete_errors(BODY_NAMESPACED_TWO_ERRORS)
|
|
38
|
+
assert errors == [
|
|
39
|
+
{'key': 'k1', 'code': 'AccessDenied', 'message': 'denied'},
|
|
40
|
+
{'key': 'k2', 'code': 'InternalError', 'message': 'oops'},
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_parse_plain_error_ignores_deleted_entries():
|
|
45
|
+
errors = parse_delete_errors(BODY_PLAIN_ONE_ERROR)
|
|
46
|
+
assert errors == [{'key': 'k1', 'code': 'NoSuchVersion', 'message': 'gone'}]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_parse_success_bodies():
|
|
50
|
+
assert parse_delete_errors(BODY_ALL_SUCCESS) == []
|
|
51
|
+
assert parse_delete_errors(b'') == [] # some providers send no body in quiet mode
|
|
52
|
+
assert parse_delete_errors(None) == []
|
|
53
|
+
assert parse_delete_errors(b' \n') == []
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_parse_malformed_raises():
|
|
57
|
+
with pytest.raises(urllib3.exceptions.HTTPError):
|
|
58
|
+
parse_delete_errors(b'<DeleteResult><unclosed')
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
#################################################
|
|
62
|
+
### delete_objects failure paths (stubbed request)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def make_session():
|
|
66
|
+
return S3Session('fake-id', 'fake-key', 'fake-bucket', endpoint_url='https://s3.example.com')
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_delete_objects_all_success(monkeypatch):
|
|
70
|
+
session = make_session()
|
|
71
|
+
calls = []
|
|
72
|
+
|
|
73
|
+
def fake_request(method, url, headers=None, fields=None, body=None, preload_content=None):
|
|
74
|
+
calls.append(body)
|
|
75
|
+
return SimpleNamespace(status=200, data=BODY_ALL_SUCCESS)
|
|
76
|
+
|
|
77
|
+
monkeypatch.setattr(session, 'request', fake_request)
|
|
78
|
+
|
|
79
|
+
assert session.delete_objects(['a', 'b'], purge=False) is None
|
|
80
|
+
assert len(calls) == 1
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_delete_objects_per_key_errors_raise(monkeypatch):
|
|
84
|
+
session = make_session()
|
|
85
|
+
|
|
86
|
+
def fake_request(method, url, headers=None, fields=None, body=None, preload_content=None):
|
|
87
|
+
return SimpleNamespace(status=200, data=BODY_NAMESPACED_TWO_ERRORS)
|
|
88
|
+
|
|
89
|
+
monkeypatch.setattr(session, 'request', fake_request)
|
|
90
|
+
|
|
91
|
+
with pytest.raises(urllib3.exceptions.HTTPError, match=r'2 key\(s\).*k1.*AccessDenied.*k2') as exc_info:
|
|
92
|
+
session.delete_objects(['k0', 'k1', 'k2'], purge=False)
|
|
93
|
+
assert 'k0' not in str(exc_info.value) # only FAILED keys are listed
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def test_delete_objects_http_failure_attempts_all_chunks(monkeypatch):
|
|
97
|
+
"""A failed chunk must not stop later chunks (best-effort), but must raise at the end."""
|
|
98
|
+
session = make_session()
|
|
99
|
+
keys = [f'key{i:04d}' for i in range(1001)] # 2 chunks: 1000 + 1
|
|
100
|
+
responses = iter([
|
|
101
|
+
SimpleNamespace(status=500, data=b'throttled'),
|
|
102
|
+
SimpleNamespace(status=200, data=BODY_ALL_SUCCESS),
|
|
103
|
+
])
|
|
104
|
+
calls = []
|
|
105
|
+
|
|
106
|
+
def fake_request(method, url, headers=None, fields=None, body=None, preload_content=None):
|
|
107
|
+
calls.append(body)
|
|
108
|
+
return next(responses)
|
|
109
|
+
|
|
110
|
+
monkeypatch.setattr(session, 'request', fake_request)
|
|
111
|
+
|
|
112
|
+
with pytest.raises(urllib3.exceptions.HTTPError, match=r'1000 key\(s\)'):
|
|
113
|
+
session.delete_objects(keys, purge=False)
|
|
114
|
+
assert len(calls) == 2 # the second chunk was still attempted
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def test_delete_objects_unparseable_200_marks_chunk_failed_and_continues(monkeypatch):
|
|
118
|
+
"""A 200 with an unparseable body means the chunk's outcome is unknown - it must
|
|
119
|
+
be recorded as failed WITHOUT aborting the remaining chunks."""
|
|
120
|
+
session = make_session()
|
|
121
|
+
keys = [f'key{i:04d}' for i in range(1001)]
|
|
122
|
+
responses = iter([
|
|
123
|
+
SimpleNamespace(status=200, data=b'not xml at all'),
|
|
124
|
+
SimpleNamespace(status=200, data=BODY_ALL_SUCCESS),
|
|
125
|
+
])
|
|
126
|
+
calls = []
|
|
127
|
+
|
|
128
|
+
def fake_request(method, url, headers=None, fields=None, body=None, preload_content=None):
|
|
129
|
+
calls.append(body)
|
|
130
|
+
return next(responses)
|
|
131
|
+
|
|
132
|
+
monkeypatch.setattr(session, 'request', fake_request)
|
|
133
|
+
|
|
134
|
+
with pytest.raises(urllib3.exceptions.HTTPError, match=r'1000 key\(s\).*unparseable-response'):
|
|
135
|
+
session.delete_objects(keys, purge=False)
|
|
136
|
+
assert len(calls) == 2
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
Regression tests for the 0.9.2 retry policy: transient HTTP statuses
|
|
5
|
+
(429/500/502/503/504) are retried with backoff on idempotent methods, exhausted
|
|
6
|
+
retries RETURN the final response (never raise), and POSTs are never
|
|
7
|
+
status-retried.
|
|
8
|
+
|
|
9
|
+
Runs against a local scripted HTTP server - no credentials, no network.
|
|
10
|
+
"""
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
14
|
+
|
|
15
|
+
import pytest
|
|
16
|
+
from urllib3.util import Retry
|
|
17
|
+
|
|
18
|
+
from s3func import s3, http_url
|
|
19
|
+
|
|
20
|
+
##############################################
|
|
21
|
+
### Local flaky server
|
|
22
|
+
|
|
23
|
+
_ERROR_BODY = (
|
|
24
|
+
b'<?xml version="1.0" encoding="UTF-8"?>'
|
|
25
|
+
b'<Error><Code>InternalError</Code><Message>scripted test error</Message></Error>'
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _ScriptedHandler(BaseHTTPRequestHandler):
|
|
30
|
+
"""Responds with a scripted sequence of statuses; the last entry repeats."""
|
|
31
|
+
|
|
32
|
+
protocol_version = 'HTTP/1.1'
|
|
33
|
+
script = [(200, {})] # [(status, extra_headers), ...] - class-level, set per test
|
|
34
|
+
requests_log = [] # [(method, path), ...] - class-level, reset per test
|
|
35
|
+
|
|
36
|
+
def _respond(self):
|
|
37
|
+
length = int(self.headers.get('Content-Length', 0))
|
|
38
|
+
if length:
|
|
39
|
+
self.rfile.read(length)
|
|
40
|
+
|
|
41
|
+
idx = len(type(self).requests_log)
|
|
42
|
+
type(self).requests_log.append((self.command, self.path))
|
|
43
|
+
status, extra_headers = self.script[min(idx, len(self.script) - 1)]
|
|
44
|
+
|
|
45
|
+
body = _ERROR_BODY if status >= 400 else b'ok'
|
|
46
|
+
self.send_response(status)
|
|
47
|
+
for name, value in extra_headers.items():
|
|
48
|
+
self.send_header(name, value)
|
|
49
|
+
self.send_header('Content-Length', str(len(body)))
|
|
50
|
+
self.send_header('Content-Type', 'application/xml' if status >= 400 else 'application/octet-stream')
|
|
51
|
+
self.end_headers()
|
|
52
|
+
if self.command != 'HEAD':
|
|
53
|
+
self.wfile.write(body)
|
|
54
|
+
|
|
55
|
+
do_GET = do_PUT = do_POST = do_HEAD = do_DELETE = _respond
|
|
56
|
+
|
|
57
|
+
def log_message(self, format, *args):
|
|
58
|
+
pass
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _QuietServer(ThreadingHTTPServer):
|
|
62
|
+
def handle_error(self, request, client_address):
|
|
63
|
+
# urllib3 drops connections between retry attempts - the resulting
|
|
64
|
+
# broken-pipe tracebacks in the server thread are expected noise.
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _ServerHandle:
|
|
69
|
+
def __init__(self, server):
|
|
70
|
+
self._server = server
|
|
71
|
+
host, port = server.server_address
|
|
72
|
+
self.url = f'http://{host}:{port}'
|
|
73
|
+
|
|
74
|
+
def set_script(self, script):
|
|
75
|
+
_ScriptedHandler.script = script
|
|
76
|
+
_ScriptedHandler.requests_log = []
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def requests(self):
|
|
80
|
+
return list(_ScriptedHandler.requests_log)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@pytest.fixture()
|
|
84
|
+
def flaky_server():
|
|
85
|
+
server = _QuietServer(('127.0.0.1', 0), _ScriptedHandler)
|
|
86
|
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
87
|
+
thread.start()
|
|
88
|
+
handle = _ServerHandle(server)
|
|
89
|
+
try:
|
|
90
|
+
yield handle
|
|
91
|
+
finally:
|
|
92
|
+
server.shutdown()
|
|
93
|
+
server.server_close()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@pytest.fixture()
|
|
97
|
+
def zero_backoff(monkeypatch):
|
|
98
|
+
"""
|
|
99
|
+
Disable backoff sleeps. MUST patch at CLASS level: urllib3 rebuilds the
|
|
100
|
+
Retry via .new() on every increment, so an instance-level patch is lost
|
|
101
|
+
after the first retry (and the tests would silently sleep 0+2+4s).
|
|
102
|
+
"""
|
|
103
|
+
monkeypatch.setattr(Retry, 'get_backoff_time', lambda self: 0.0)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _make_session(url, max_attempts=3):
|
|
107
|
+
return s3.S3Session('test-id', 'test-key', 'test-bucket', endpoint_url=url, max_attempts=max_attempts)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
##############################################
|
|
111
|
+
### Tests
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def test_retry_config():
|
|
115
|
+
http = http_url.session(max_attempts=3)
|
|
116
|
+
retries = http.connection_pool_kw['retries']
|
|
117
|
+
assert retries.total == 3
|
|
118
|
+
assert set(retries.status_forcelist) == {429, 500, 502, 503, 504}
|
|
119
|
+
assert retries.raise_on_status is False
|
|
120
|
+
assert retries.allowed_methods == Retry.DEFAULT_ALLOWED_METHODS
|
|
121
|
+
assert 'POST' not in retries.allowed_methods
|
|
122
|
+
assert retries.respect_retry_after_header is True
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_get_5xx_retried_until_success(flaky_server, zero_backoff):
|
|
126
|
+
flaky_server.set_script([(500, {}), (503, {}), (200, {})])
|
|
127
|
+
session = _make_session(flaky_server.url)
|
|
128
|
+
|
|
129
|
+
resp = session.get_object('some_key')
|
|
130
|
+
|
|
131
|
+
assert resp.status == 200
|
|
132
|
+
assert len(flaky_server.requests) == 3
|
|
133
|
+
assert all(method == 'GET' for method, _path in flaky_server.requests)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_put_5xx_retried_until_success(flaky_server, zero_backoff):
|
|
137
|
+
flaky_server.set_script([(500, {}), (200, {})])
|
|
138
|
+
session = _make_session(flaky_server.url)
|
|
139
|
+
|
|
140
|
+
resp = session.put_object('some_key', b'data')
|
|
141
|
+
|
|
142
|
+
assert resp.status == 200
|
|
143
|
+
assert len(flaky_server.requests) == 2
|
|
144
|
+
assert all(method == 'PUT' for method, _path in flaky_server.requests)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def test_persistent_5xx_returns_response_not_exception(flaky_server, zero_backoff):
|
|
148
|
+
# The raise_on_status=False contract: exhausted retries hand back the final
|
|
149
|
+
# response so callers (lock PUT check, delete_objects, list iterators) can
|
|
150
|
+
# dispatch on resp.status - a raise here would bypass their error handling.
|
|
151
|
+
flaky_server.set_script([(500, {})])
|
|
152
|
+
session = _make_session(flaky_server.url, max_attempts=2)
|
|
153
|
+
|
|
154
|
+
resp = session.get_object('some_key')
|
|
155
|
+
|
|
156
|
+
assert resp.status == 500
|
|
157
|
+
assert resp.error
|
|
158
|
+
# total=N means N retries = N+1 requests (documented off-by-one)
|
|
159
|
+
assert len(flaky_server.requests) == 3
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def test_post_not_status_retried(flaky_server, zero_backoff):
|
|
163
|
+
# Multi-object-delete is a POST; POST must never be status-retried (B2's
|
|
164
|
+
# native POSTs are non-idempotent, and b2.put_object has its own manual
|
|
165
|
+
# retry loop that must not compound).
|
|
166
|
+
flaky_server.set_script([(500, {})])
|
|
167
|
+
session = _make_session(flaky_server.url)
|
|
168
|
+
|
|
169
|
+
with pytest.raises(Exception):
|
|
170
|
+
# delete_objects raises its own HTTPError on a failed chunk - that's
|
|
171
|
+
# its documented contract; what matters here is the request count.
|
|
172
|
+
session.delete_objects(['a', 'b'], purge=False)
|
|
173
|
+
|
|
174
|
+
post_requests = [m for m, _p in flaky_server.requests if m == 'POST']
|
|
175
|
+
assert len(post_requests) == 1
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def test_429_retry_after_honored(flaky_server):
|
|
179
|
+
# No zero_backoff: Retry-After bypasses get_backoff_time entirely.
|
|
180
|
+
flaky_server.set_script([(429, {'Retry-After': '1'}), (200, {})])
|
|
181
|
+
session = _make_session(flaky_server.url)
|
|
182
|
+
|
|
183
|
+
start = time.perf_counter()
|
|
184
|
+
resp = session.get_object('some_key')
|
|
185
|
+
elapsed = time.perf_counter() - start
|
|
186
|
+
|
|
187
|
+
assert resp.status == 200
|
|
188
|
+
assert len(flaky_server.requests) == 2
|
|
189
|
+
assert elapsed >= 1.0
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|