s3func 0.9.4__tar.gz → 0.9.6__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.4 → s3func-0.9.6}/PKG-INFO +1 -1
- {s3func-0.9.4 → s3func-0.9.6}/s3func/__init__.py +3 -2
- {s3func-0.9.4 → s3func-0.9.6}/s3func/http_url.py +6 -1
- {s3func-0.9.4 → s3func-0.9.6}/s3func/locking.py +9 -14
- {s3func-0.9.4 → s3func-0.9.6}/s3func/response.py +149 -32
- {s3func-0.9.4 → s3func-0.9.6}/s3func/s3.py +151 -36
- s3func-0.9.6/s3func/tests/test_delete_objects.py +493 -0
- {s3func-0.9.4 → s3func-0.9.6}/s3func/tests/test_mock_s3.py +94 -0
- {s3func-0.9.4 → s3func-0.9.6}/s3func/tests/test_retry.py +13 -1
- {s3func-0.9.4 → s3func-0.9.6}/s3func/tests/test_s3func.py +69 -0
- s3func-0.9.4/s3func/tests/test_delete_objects.py +0 -136
- {s3func-0.9.4 → s3func-0.9.6}/.gitignore +0 -0
- {s3func-0.9.4 → s3func-0.9.6}/LICENSE +0 -0
- {s3func-0.9.4 → s3func-0.9.6}/README.md +0 -0
- {s3func-0.9.4 → s3func-0.9.6}/pyproject.toml +0 -0
- {s3func-0.9.4 → s3func-0.9.6}/s3func/b2.py +0 -0
- {s3func-0.9.4 → s3func-0.9.6}/s3func/signer.py +0 -0
- {s3func-0.9.4 → s3func-0.9.6}/s3func/tests/__init__.py +0 -0
- {s3func-0.9.4 → s3func-0.9.6}/s3func/tests/conftest.py +0 -0
- {s3func-0.9.4 → s3func-0.9.6}/s3func/tests/test_lock_model.py +0 -0
- {s3func-0.9.4 → s3func-0.9.6}/s3func/tests/test_locks.py +0 -0
- {s3func-0.9.4 → s3func-0.9.6}/s3func/tests/test_scale_transport.py +0 -0
- {s3func-0.9.4 → s3func-0.9.6}/s3func/tests/test_streaming_upload.py +0 -0
- {s3func-0.9.4 → s3func-0.9.6}/s3func/utils.py +0 -0
|
@@ -4,6 +4,7 @@ from s3func.s3 import S3Session
|
|
|
4
4
|
from s3func.b2 import B2Session
|
|
5
5
|
from s3func.locking import S3Lock, B2Lock
|
|
6
6
|
from s3func.http_url import HttpSession
|
|
7
|
-
from s3func import
|
|
7
|
+
from s3func.response import S3ListError
|
|
8
|
+
from s3func import s3, http_url, utils, b2, response
|
|
8
9
|
|
|
9
|
-
__version__ = '0.9.
|
|
10
|
+
__version__ = '0.9.6'
|
|
@@ -71,7 +71,12 @@ def session(max_connections: int = 10, max_attempts: int = 3, timeout: int = 120
|
|
|
71
71
|
# methods (urllib3 default): the S3 multi-object-delete and the
|
|
72
72
|
# B2-native upload paths are POSTs, and b2.put_object has its own
|
|
73
73
|
# manual retry loop that must not compound with this one.
|
|
74
|
-
|
|
74
|
+
# 520-524 are the Cloudflare-style edge errors ("web server returned
|
|
75
|
+
# an unknown error"/timeouts) that B2's fronting infrastructure emits
|
|
76
|
+
# transiently - a bare 522 failed an ebooklet CI run un-retried
|
|
77
|
+
# (2026-07-15); all are server-side transient conditions, safe to
|
|
78
|
+
# retry on idempotent methods.
|
|
79
|
+
status_forcelist=(429, 500, 502, 503, 504, 520, 521, 522, 523, 524),
|
|
75
80
|
# Callers dispatch on resp.status (locking lock-PUT check, delete_objects
|
|
76
81
|
# per-chunk failure handling, list iterators) and never expect a raise:
|
|
77
82
|
# when retries exhaust, the LAST response must be returned, not
|
|
@@ -27,7 +27,7 @@ from time import sleep
|
|
|
27
27
|
import urllib3
|
|
28
28
|
import datetime
|
|
29
29
|
|
|
30
|
-
from . import b2, s3
|
|
30
|
+
from . import b2, s3, response
|
|
31
31
|
|
|
32
32
|
|
|
33
33
|
#######################################################
|
|
@@ -224,19 +224,14 @@ class DistributedLock:
|
|
|
224
224
|
def _list_objects(session, obj_lock_key, lock_id=None):
|
|
225
225
|
key = obj_lock_key + (lock_id if lock_id else "")
|
|
226
226
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
items = list(objs.iter_objects())
|
|
236
|
-
elif '401' in str(e) or '403' in str(e):
|
|
237
|
-
raise
|
|
238
|
-
else:
|
|
239
|
-
raise
|
|
227
|
+
## Versioned listing, falling back to the unversioned one for providers
|
|
228
|
+
## without versioning (e.g. Mega S3). Shared with the delete paths: the
|
|
229
|
+
## fallback used to be gated on `'501' in str(e)`, which false-positives
|
|
230
|
+
## on any transport error whose embedded URL contains '501' - and a lock
|
|
231
|
+
## id is uuid hex, so it can. list_records gates on the numeric status.
|
|
232
|
+
## No size cap is imposed here: an election needs the WHOLE snapshot
|
|
233
|
+
## (the own-ticket invariant), so a truncated listing is never safe.
|
|
234
|
+
items = list(response.list_records(session, key))
|
|
240
235
|
|
|
241
236
|
res = []
|
|
242
237
|
for l in items:
|
|
@@ -15,6 +15,109 @@ import urllib.parse
|
|
|
15
15
|
from s3func import utils
|
|
16
16
|
|
|
17
17
|
|
|
18
|
+
#############################################################
|
|
19
|
+
### Listing errors
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class S3ListError(urllib3.exceptions.HTTPError):
|
|
23
|
+
"""
|
|
24
|
+
A listing request failed, or returned something unparsable.
|
|
25
|
+
|
|
26
|
+
Carries the numeric HTTP status (None when the failure was in parsing) so
|
|
27
|
+
callers can branch STRUCTURALLY. The previous `'501' in str(e)` idiom could
|
|
28
|
+
not: urllib3's transport exceptions are themselves HTTPError subclasses and
|
|
29
|
+
MaxRetryError embeds the request URL in its str(), so any key or prefix
|
|
30
|
+
containing '501' - `db/501.<generation>` is a routine ebooklet group key -
|
|
31
|
+
turned a transport blip into a false "provider does not support versioning"
|
|
32
|
+
signal and silently downgraded a purge to a versionless delete.
|
|
33
|
+
|
|
34
|
+
Every failure escaping a listing must be an HTTPError subclass. ebooklet's
|
|
35
|
+
post-commit GC catches HTTPError and nothing else, and it runs after the
|
|
36
|
+
journal has been cleared: anything else crashes a push that already
|
|
37
|
+
succeeded.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, status, message=None):
|
|
41
|
+
self.status = status
|
|
42
|
+
super().__init__(message or f'S3 List Error {status}')
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
## Providers disagree on the LastModified shape (fractional seconds, 'Z' vs a
|
|
46
|
+
## numeric offset). Parse leniently rather than failing a whole listing over a
|
|
47
|
+
## timestamp nothing in the delete path reads - but if none of these match,
|
|
48
|
+
## raise S3ListError rather than letting a bare ValueError escape.
|
|
49
|
+
_TIMESTAMP_FORMATS = (
|
|
50
|
+
'%Y-%m-%dT%H:%M:%S.%fZ',
|
|
51
|
+
'%Y-%m-%dT%H:%M:%SZ',
|
|
52
|
+
'%Y-%m-%dT%H:%M:%S.%f%z',
|
|
53
|
+
'%Y-%m-%dT%H:%M:%S%z',
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _list_timestamp(text):
|
|
58
|
+
"""Parse a listing timestamp, or raise S3ListError."""
|
|
59
|
+
if not text:
|
|
60
|
+
return None
|
|
61
|
+
for fmt in _TIMESTAMP_FORMATS:
|
|
62
|
+
try:
|
|
63
|
+
parsed = datetime.datetime.strptime(text, fmt)
|
|
64
|
+
except ValueError:
|
|
65
|
+
continue
|
|
66
|
+
if parsed.tzinfo is None:
|
|
67
|
+
return parsed.replace(tzinfo=datetime.timezone.utc)
|
|
68
|
+
return parsed
|
|
69
|
+
raise S3ListError(None, f'unparsable LastModified in a listing response: {text!r}')
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _list_int(text):
|
|
73
|
+
"""Parse a listing integer field, or raise S3ListError."""
|
|
74
|
+
if not text:
|
|
75
|
+
return 0
|
|
76
|
+
try:
|
|
77
|
+
return int(text)
|
|
78
|
+
except (TypeError, ValueError):
|
|
79
|
+
raise S3ListError(None, f'unparsable numeric field in a listing response: {text!r}')
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def list_records(session, prefix, on_page=None):
|
|
83
|
+
"""
|
|
84
|
+
Stream every version record under `prefix`, preferring the versioned listing.
|
|
85
|
+
|
|
86
|
+
Falls back to the unversioned (v2) listing ONLY on a genuine 501 seen on the
|
|
87
|
+
FIRST page - a provider without versioning support refuses immediately, so a
|
|
88
|
+
501 arriving mid-stream is a real failure and is not recoverable by
|
|
89
|
+
restarting with a different listing.
|
|
90
|
+
|
|
91
|
+
This is the single implementation of that fallback; s3.py's two delete paths
|
|
92
|
+
and locking.py's election listing all route through it.
|
|
93
|
+
|
|
94
|
+
NOTE: this generator deliberately carries no size cap. The delete resolver's
|
|
95
|
+
over-listing guard lives in S3Session._resolve_versions, because a cap here
|
|
96
|
+
would silently truncate a LOCK election listing, whose own-ticket invariant
|
|
97
|
+
tolerates no partial snapshot.
|
|
98
|
+
"""
|
|
99
|
+
## `on_page` is passed ONLY when a caller asked for it. Session/list-response
|
|
100
|
+
## objects are duck-typed - s3func's own tests, ebooklet's fake_s3, and any
|
|
101
|
+
## external implementer define iter_objects(self) with no keyword - so
|
|
102
|
+
## passing it unconditionally would break every one of them.
|
|
103
|
+
def _iter(listing):
|
|
104
|
+
return listing.iter_objects(on_page=on_page) if on_page is not None else listing.iter_objects()
|
|
105
|
+
|
|
106
|
+
records = _iter(session.list_object_versions(prefix=prefix))
|
|
107
|
+
try:
|
|
108
|
+
first = next(records)
|
|
109
|
+
except StopIteration:
|
|
110
|
+
return
|
|
111
|
+
except S3ListError as err:
|
|
112
|
+
if err.status != 501:
|
|
113
|
+
raise
|
|
114
|
+
yield from _iter(session.list_objects(prefix=prefix))
|
|
115
|
+
return
|
|
116
|
+
|
|
117
|
+
yield first
|
|
118
|
+
yield from records
|
|
119
|
+
|
|
120
|
+
|
|
18
121
|
#############################################################
|
|
19
122
|
### Response classes
|
|
20
123
|
|
|
@@ -80,9 +183,16 @@ B2Response = lambda r, s: Response(r, s, 'b2')
|
|
|
80
183
|
HttpResponse = lambda r, s: Response(r, s, 'http')
|
|
81
184
|
|
|
82
185
|
|
|
83
|
-
def iter_s3_list(session, url, method, headers, params):
|
|
186
|
+
def iter_s3_list(session, url, method, headers, params, on_page=None):
|
|
84
187
|
"""
|
|
85
188
|
Iterates over S3 list results (Versions or Objects).
|
|
189
|
+
|
|
190
|
+
`on_page`, if given, is called once per successfully fetched page. Pages are
|
|
191
|
+
the unit a caller is actually billed for, and they are invisible from the
|
|
192
|
+
outside of this generator, so a caller that needs to bound its own cost
|
|
193
|
+
(the delete resolver) cannot count them any other way. It must NOT infer
|
|
194
|
+
them from a record count: s3func never sends max-keys, so the page size is
|
|
195
|
+
whatever the provider defaults to.
|
|
86
196
|
"""
|
|
87
197
|
# ns = {'s3': 'http://s3.amazonaws.com/doc/2006-03-01/'}
|
|
88
198
|
|
|
@@ -99,12 +209,15 @@ def iter_s3_list(session, url, method, headers, params):
|
|
|
99
209
|
resp = session.request('GET', url, headers=headers, fields=params)
|
|
100
210
|
|
|
101
211
|
if (resp.status // 100) != 2:
|
|
102
|
-
raise
|
|
212
|
+
raise S3ListError(resp.status)
|
|
103
213
|
|
|
104
214
|
try:
|
|
105
215
|
root = ET.fromstring(resp.data)
|
|
106
216
|
except ET.ParseError:
|
|
107
|
-
raise
|
|
217
|
+
raise S3ListError(resp.status, "Failed to parse S3 XML response")
|
|
218
|
+
|
|
219
|
+
if on_page is not None:
|
|
220
|
+
on_page()
|
|
108
221
|
|
|
109
222
|
# Determine namespace from root tag
|
|
110
223
|
if '}' in root.tag:
|
|
@@ -132,17 +245,11 @@ def iter_s3_list(session, url, method, headers, params):
|
|
|
132
245
|
yield {
|
|
133
246
|
# 'etag': version.find('s3:ETag', ns).text.strip('"') if version.find('s3:ETag', ns) is not None else None,
|
|
134
247
|
'content_md5': find_text(version, 'ETag').strip('"') if find_text(version, 'ETag') else None,
|
|
135
|
-
'content_length':
|
|
248
|
+
'content_length': _list_int(find_text(version, 'Size')),
|
|
136
249
|
'key': find_text(version, 'Key'),
|
|
137
250
|
'version_id': find_text(version, 'VersionId'),
|
|
138
251
|
'is_latest': find_text(version, 'IsLatest') == 'true',
|
|
139
|
-
'upload_timestamp': (
|
|
140
|
-
datetime.datetime.strptime(find_text(version, 'LastModified'), '%Y-%m-%dT%H:%M:%S.%fZ').replace(
|
|
141
|
-
tzinfo=datetime.timezone.utc
|
|
142
|
-
)
|
|
143
|
-
if find_text(version, 'LastModified')
|
|
144
|
-
else None
|
|
145
|
-
),
|
|
252
|
+
'upload_timestamp': _list_timestamp(find_text(version, 'LastModified')),
|
|
146
253
|
# 'owner': ... (Owner might be present)
|
|
147
254
|
}
|
|
148
255
|
# Delete markers are yielded explicitly with a flag so consumers can
|
|
@@ -156,23 +263,31 @@ def iter_s3_list(session, url, method, headers, params):
|
|
|
156
263
|
'key': find_text(marker, 'Key'),
|
|
157
264
|
'version_id': find_text(marker, 'VersionId'),
|
|
158
265
|
'is_latest': find_text(marker, 'IsLatest') == 'true',
|
|
159
|
-
'upload_timestamp': (
|
|
160
|
-
datetime.datetime.strptime(find_text(marker, 'LastModified'), '%Y-%m-%dT%H:%M:%S.%fZ').replace(
|
|
161
|
-
tzinfo=datetime.timezone.utc
|
|
162
|
-
)
|
|
163
|
-
if find_text(marker, 'LastModified')
|
|
164
|
-
else None
|
|
165
|
-
),
|
|
266
|
+
'upload_timestamp': _list_timestamp(find_text(marker, 'LastModified')),
|
|
166
267
|
}
|
|
167
268
|
|
|
168
269
|
is_truncated = find_text(root, 'IsTruncated') == 'true'
|
|
169
270
|
if is_truncated:
|
|
170
271
|
next_key_marker = find_text(root, 'NextKeyMarker')
|
|
171
272
|
next_version_id_marker = find_text(root, 'NextVersionIdMarker')
|
|
172
|
-
|
|
173
|
-
|
|
273
|
+
## Truncated with no continuation marker: the request params are
|
|
274
|
+
## unchanged, so continuing would re-fetch this same page for
|
|
275
|
+
## ever. Raise instead - a listing we cannot finish is INCOMPLETE
|
|
276
|
+
## data, and the delete resolver turns missing records into
|
|
277
|
+
## silently retained versions.
|
|
278
|
+
if not next_key_marker:
|
|
279
|
+
raise S3ListError(
|
|
280
|
+
resp.status,
|
|
281
|
+
'listing reported IsTruncated with no NextKeyMarker - cannot page further',
|
|
282
|
+
)
|
|
283
|
+
params['key-marker'] = next_key_marker
|
|
284
|
+
## set-or-CLEAR: a stale version-id-marker paired with a NEW
|
|
285
|
+
## key-marker asks the provider to resume from a version id that
|
|
286
|
+
## belongs to a different key, which can skip records.
|
|
174
287
|
if next_version_id_marker:
|
|
175
288
|
params['version-id-marker'] = next_version_id_marker
|
|
289
|
+
else:
|
|
290
|
+
params.pop('version-id-marker', None)
|
|
176
291
|
else:
|
|
177
292
|
break
|
|
178
293
|
|
|
@@ -181,22 +296,22 @@ def iter_s3_list(session, url, method, headers, params):
|
|
|
181
296
|
yield {
|
|
182
297
|
# 'etag': contents.find('s3:ETag', ns).text.strip('"'),
|
|
183
298
|
'content_md5': find_text(contents, 'ETag').strip('"') if find_text(contents, 'ETag') else None,
|
|
184
|
-
'content_length':
|
|
299
|
+
'content_length': _list_int(find_text(contents, 'Size')),
|
|
185
300
|
'key': find_text(contents, 'Key'),
|
|
186
|
-
'upload_timestamp': (
|
|
187
|
-
datetime.datetime.strptime(
|
|
188
|
-
find_text(contents, 'LastModified'), '%Y-%m-%dT%H:%M:%S.%fZ'
|
|
189
|
-
).replace(tzinfo=datetime.timezone.utc)
|
|
190
|
-
if find_text(contents, 'LastModified')
|
|
191
|
-
else None
|
|
192
|
-
),
|
|
301
|
+
'upload_timestamp': _list_timestamp(find_text(contents, 'LastModified')),
|
|
193
302
|
}
|
|
194
303
|
|
|
195
304
|
is_truncated = find_text(root, 'IsTruncated') == 'true'
|
|
196
305
|
if is_truncated:
|
|
197
306
|
token = find_text(root, 'NextContinuationToken')
|
|
198
|
-
|
|
199
|
-
|
|
307
|
+
## Same reasoning as the versioned branch: no token means we
|
|
308
|
+
## cannot page, and silently stopping under-reports.
|
|
309
|
+
if not token:
|
|
310
|
+
raise S3ListError(
|
|
311
|
+
resp.status,
|
|
312
|
+
'listing reported IsTruncated with no NextContinuationToken - cannot page further',
|
|
313
|
+
)
|
|
314
|
+
params['continuation-token'] = token
|
|
200
315
|
else:
|
|
201
316
|
break
|
|
202
317
|
else:
|
|
@@ -218,10 +333,12 @@ class S3ListResponse:
|
|
|
218
333
|
self.status = 200 # Assumed valid until iteration fails
|
|
219
334
|
self.error = None
|
|
220
335
|
|
|
221
|
-
def iter_objects(self):
|
|
336
|
+
def iter_objects(self, on_page=None):
|
|
222
337
|
if self.error:
|
|
223
338
|
raise urllib3.exceptions.HTTPError(self.error)
|
|
224
|
-
return iter_s3_list(
|
|
339
|
+
return iter_s3_list(
|
|
340
|
+
self._session, self._url, self._method, self._headers, copy.deepcopy(self._params), on_page=on_page
|
|
341
|
+
)
|
|
225
342
|
|
|
226
343
|
def __repr__(self):
|
|
227
344
|
return f'status: {self.status}'
|
|
@@ -6,6 +6,8 @@ Created on May 13 08:04:38 2024
|
|
|
6
6
|
@author: mike
|
|
7
7
|
"""
|
|
8
8
|
import io
|
|
9
|
+
import itertools
|
|
10
|
+
import os.path
|
|
9
11
|
from typing import List, Union
|
|
10
12
|
|
|
11
13
|
# import boto3
|
|
@@ -34,6 +36,13 @@ from . import http_url, utils, response, locking
|
|
|
34
36
|
md5_locks = {'shared': 'cfcd208495d565ef66e7dff9f98764da', 'exclusive': 'c4ca4238a0b923820dcc509a6f75849b'}
|
|
35
37
|
|
|
36
38
|
|
|
39
|
+
class _ListingBudgetExceeded(Exception):
|
|
40
|
+
"""
|
|
41
|
+
Internal: a bulk version listing outgrew its page budget and the caller
|
|
42
|
+
should fall back to per-key resolution. Never escapes _resolve_versions.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
|
|
37
46
|
#######################################################
|
|
38
47
|
### Functions
|
|
39
48
|
|
|
@@ -389,6 +398,83 @@ class S3Session:
|
|
|
389
398
|
|
|
390
399
|
return s3resp
|
|
391
400
|
|
|
401
|
+
def _resolve_versions(self, unresolved):
|
|
402
|
+
"""
|
|
403
|
+
Map each key to its version ids, for a purging delete.
|
|
404
|
+
|
|
405
|
+
Returns {key: [version_id, ...]}. Three states, and the caller must keep
|
|
406
|
+
them apart:
|
|
407
|
+
- key ABSENT -> no such object; emit no delete entry at all
|
|
408
|
+
- key -> [] -> exists but the provider gave no version id
|
|
409
|
+
(the unversioned-listing fallback); emit one
|
|
410
|
+
versionless delete
|
|
411
|
+
- key -> [v1, ...] -> emit one delete entry per version
|
|
412
|
+
|
|
413
|
+
Cost. Resolving each key with its own listing is one round trip per key,
|
|
414
|
+
which on a real 3,789-object delete was ~3,793 sequential requests and
|
|
415
|
+
~17.6 minutes at 0.279 s/call - pure latency, ~0.2% CPU. One bulk listing
|
|
416
|
+
under the keys' common prefix returned the same 7,937 version records in
|
|
417
|
+
3.62 s. So: derive the prefix, list once, filter to the exact requested
|
|
418
|
+
set in memory.
|
|
419
|
+
|
|
420
|
+
The filter is EXACT key equality, never a prefix match. Callers rely on
|
|
421
|
+
that: ebooklet group ids are non-zero-padded decimals, so deleting group
|
|
422
|
+
'1' by prefix would also destroy '10', '11', ...
|
|
423
|
+
"""
|
|
424
|
+
wanted = set(unresolved)
|
|
425
|
+
resolved = {}
|
|
426
|
+
|
|
427
|
+
## Route by count and by prefix. Attempting bulk and then aborting would
|
|
428
|
+
## pay for both, so the cases where bulk cannot win are excluded up front
|
|
429
|
+
## rather than left to the guard:
|
|
430
|
+
## - one key: commonprefix IS that key, so bulk == per-key already;
|
|
431
|
+
## - no common prefix: build_s3_params DROPS a falsy prefix, so the
|
|
432
|
+
## listing would enumerate the whole bucket from the root.
|
|
433
|
+
common = os.path.commonprefix(sorted(wanted)) if len(wanted) > 1 else ''
|
|
434
|
+
|
|
435
|
+
if common:
|
|
436
|
+
## A short common prefix can over-list badly. Bulk costs one request
|
|
437
|
+
## per PAGE, per-key costs one per key, so bulk only loses once it
|
|
438
|
+
## has fetched more pages than there are keys - at which point it has
|
|
439
|
+
## already spent what per-key would have, bounding the worst case at
|
|
440
|
+
## ~2x optimal with no page-size assumption anywhere.
|
|
441
|
+
budget = len(wanted)
|
|
442
|
+
pages = itertools.count(1)
|
|
443
|
+
bulk = {}
|
|
444
|
+
|
|
445
|
+
def charge_page():
|
|
446
|
+
## Charged when a page is FETCHED, not when its records are
|
|
447
|
+
## consumed, so a run of pages carrying nothing we asked for
|
|
448
|
+
## still counts against the budget.
|
|
449
|
+
if next(pages) > budget:
|
|
450
|
+
raise _ListingBudgetExceeded
|
|
451
|
+
|
|
452
|
+
try:
|
|
453
|
+
for record in response.list_records(self, common, on_page=charge_page):
|
|
454
|
+
key = record['key']
|
|
455
|
+
if key in wanted:
|
|
456
|
+
## Delete markers carry a version_id too, and a purge that
|
|
457
|
+
## leaves them behind is not a purge.
|
|
458
|
+
bulk.setdefault(key, [])
|
|
459
|
+
if record.get('version_id'):
|
|
460
|
+
bulk[key].append(record['version_id'])
|
|
461
|
+
except _ListingBudgetExceeded:
|
|
462
|
+
## Partial results are DISCARDED, never reused: a page yields all
|
|
463
|
+
## its Versions before all its DeleteMarkers, so a key seen early
|
|
464
|
+
## can still have marker records further down the listing.
|
|
465
|
+
pass
|
|
466
|
+
else:
|
|
467
|
+
return bulk
|
|
468
|
+
|
|
469
|
+
for key in unresolved:
|
|
470
|
+
for record in response.list_records(self, key):
|
|
471
|
+
if record['key'] == key:
|
|
472
|
+
resolved.setdefault(key, [])
|
|
473
|
+
if record.get('version_id'):
|
|
474
|
+
resolved[key].append(record['version_id'])
|
|
475
|
+
|
|
476
|
+
return resolved
|
|
477
|
+
|
|
392
478
|
def delete_objects(self, keys: Union[List[str], List[dict]] = None, prefix: str = None, purge: bool = True):
|
|
393
479
|
"""
|
|
394
480
|
Delete multiple objects from an S3 bucket.
|
|
@@ -416,6 +502,27 @@ class S3Session:
|
|
|
416
502
|
If any object fails to delete (whole-batch HTTP failure or per-key
|
|
417
503
|
errors in the DeleteResult). All chunks are attempted before raising,
|
|
418
504
|
so everything deletable is deleted; the error lists the failed keys.
|
|
505
|
+
ALSO if version resolution fails: a purge that cannot read the
|
|
506
|
+
versions it is meant to remove must not quietly fall back to a
|
|
507
|
+
versionless delete, which on a versioned bucket retains (and bills
|
|
508
|
+
for) every version while reporting success.
|
|
509
|
+
ValueError
|
|
510
|
+
If a key entry is not a string or a dict carrying a non-empty 'key'.
|
|
511
|
+
Validated before any request is made.
|
|
512
|
+
|
|
513
|
+
Notes
|
|
514
|
+
-----
|
|
515
|
+
With `keys` and `purge=True`, version ids are resolved with ONE bulk
|
|
516
|
+
listing under the keys' common prefix, filtered to the exact requested
|
|
517
|
+
set in memory - not one listing per key, which cost ~17.6 minutes for a
|
|
518
|
+
3,789-object delete against a remote endpoint. If that prefix turns out
|
|
519
|
+
to be unselective, resolution falls back to per-key listings once the
|
|
520
|
+
bulk attempt has fetched more pages than there are keys, bounding the
|
|
521
|
+
worst case at roughly twice the per-key cost.
|
|
522
|
+
|
|
523
|
+
A requested key with no listed versions is SKIPPED rather than deleted
|
|
524
|
+
without a version id, so a delete of something that does not exist no
|
|
525
|
+
longer leaves a delete marker behind.
|
|
419
526
|
"""
|
|
420
527
|
if keys is not None and prefix is not None:
|
|
421
528
|
raise ValueError('keys and prefix are mutually exclusive.')
|
|
@@ -425,56 +532,64 @@ class S3Session:
|
|
|
425
532
|
if prefix is not None:
|
|
426
533
|
# List all objects under the prefix and collect for deletion
|
|
427
534
|
if purge:
|
|
428
|
-
|
|
429
|
-
resp = self.list_object_versions(prefix=prefix)
|
|
430
|
-
items = list(resp.iter_objects())
|
|
431
|
-
except urllib3.exceptions.HTTPError as e:
|
|
432
|
-
if '501' in str(e):
|
|
433
|
-
resp = self.list_objects(prefix=prefix)
|
|
434
|
-
items = list(resp.iter_objects())
|
|
435
|
-
else:
|
|
436
|
-
raise
|
|
535
|
+
items = list(response.list_records(self, prefix))
|
|
437
536
|
else:
|
|
438
537
|
resp = self.list_objects(prefix=prefix)
|
|
439
538
|
items = list(resp.iter_objects())
|
|
440
539
|
keys = [{'key': obj['key'], 'version_id': obj.get('version_id')} for obj in items]
|
|
441
540
|
else:
|
|
442
|
-
# Normalize input: strings -> dicts
|
|
443
|
-
|
|
444
|
-
|
|
541
|
+
# Normalize input: strings -> dicts, and reject anything unusable
|
|
542
|
+
# BEFORE it reaches the network. A None or missing key used to cost a
|
|
543
|
+
# whole listing per bad entry and only then fail at the XML build.
|
|
544
|
+
normalized = []
|
|
545
|
+
for k in keys:
|
|
546
|
+
if isinstance(k, str):
|
|
547
|
+
k = {'key': k}
|
|
548
|
+
elif not isinstance(k, dict):
|
|
549
|
+
raise ValueError(f'keys must be strings or dicts, got {type(k).__name__}')
|
|
550
|
+
key_name = k.get('key') or k.get('Key')
|
|
551
|
+
if not isinstance(key_name, str) or not key_name:
|
|
552
|
+
raise ValueError(f'every key entry needs a non-empty "key" string, got {k!r}')
|
|
553
|
+
normalized.append(k)
|
|
554
|
+
keys = normalized
|
|
445
555
|
|
|
446
556
|
# If purge, resolve version IDs for keys that don't have them
|
|
447
557
|
if purge:
|
|
558
|
+
unresolved = []
|
|
559
|
+
for k in keys:
|
|
560
|
+
if not (k.get('version_id') or k.get('VersionId')):
|
|
561
|
+
key_name = k.get('key') or k.get('Key')
|
|
562
|
+
if key_name not in unresolved:
|
|
563
|
+
unresolved.append(key_name)
|
|
564
|
+
|
|
565
|
+
versions = self._resolve_versions(unresolved) if unresolved else {}
|
|
566
|
+
|
|
448
567
|
resolved = []
|
|
568
|
+
seen = set()
|
|
449
569
|
for k in keys:
|
|
450
570
|
key_name = k.get('key') or k.get('Key')
|
|
451
571
|
version_id = k.get('version_id') or k.get('VersionId')
|
|
452
572
|
if version_id:
|
|
453
|
-
|
|
573
|
+
entries = [{'key': key_name, 'version_id': version_id}]
|
|
574
|
+
elif key_name in versions:
|
|
575
|
+
entries = [{'key': key_name, 'version_id': v} for v in versions[key_name]] or [
|
|
576
|
+
{'key': key_name}
|
|
577
|
+
]
|
|
454
578
|
else:
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
if obj['key'] == key_name:
|
|
470
|
-
resolved.append({'key': obj['key']})
|
|
471
|
-
found = True
|
|
472
|
-
if not found:
|
|
473
|
-
resolved.append(k)
|
|
474
|
-
else:
|
|
475
|
-
resolved.append(k)
|
|
476
|
-
except Exception:
|
|
477
|
-
resolved.append(k)
|
|
579
|
+
## Not in the listing => no such object. Emitting the key
|
|
580
|
+
## bare would ask for a versionless delete, which on a
|
|
581
|
+
## versioned bucket creates a delete marker for an object
|
|
582
|
+
## that never existed.
|
|
583
|
+
continue
|
|
584
|
+
for entry in entries:
|
|
585
|
+
## Dedup the FINAL entries, not just the input keys: a
|
|
586
|
+
## bare 'k' alongside {'key': 'k', 'version_id': v} would
|
|
587
|
+
## otherwise delete v twice, and the second delete of a
|
|
588
|
+
## version can come back NoSuchVersion.
|
|
589
|
+
marker = (entry['key'], entry.get('version_id'))
|
|
590
|
+
if marker not in seen:
|
|
591
|
+
seen.add(marker)
|
|
592
|
+
resolved.append(entry)
|
|
478
593
|
keys = resolved
|
|
479
594
|
|
|
480
595
|
# S3 Delete Objects requires a specific XML payload
|