s3func 0.8.2__tar.gz → 0.8.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.
- {s3func-0.8.2 → s3func-0.8.4}/.gitignore +1 -0
- {s3func-0.8.2 → s3func-0.8.4}/PKG-INFO +1 -1
- {s3func-0.8.2 → s3func-0.8.4}/s3func/__init__.py +1 -1
- {s3func-0.8.2 → s3func-0.8.4}/s3func/b2.py +23 -122
- {s3func-0.8.2 → s3func-0.8.4}/s3func/locking.py +18 -5
- {s3func-0.8.2 → s3func-0.8.4}/s3func/s3.py +40 -10
- {s3func-0.8.2 → s3func-0.8.4}/s3func/signer.py +1 -1
- s3func-0.8.4/s3func/tests/conftest.py +85 -0
- s3func-0.8.4/s3func/tests/test_locks.py +147 -0
- {s3func-0.8.2 → s3func-0.8.4}/s3func/tests/test_mock_s3.py +13 -0
- s3func-0.8.4/s3func/tests/test_s3func.py +264 -0
- {s3func-0.8.2 → s3func-0.8.4}/s3func/utils.py +1 -2
- s3func-0.8.2/s3func/tests/test_locks.py +0 -194
- s3func-0.8.2/s3func/tests/test_s3func.py +0 -391
- {s3func-0.8.2 → s3func-0.8.4}/LICENSE +0 -0
- {s3func-0.8.2 → s3func-0.8.4}/README.md +0 -0
- {s3func-0.8.2 → s3func-0.8.4}/pyproject.toml +0 -0
- {s3func-0.8.2 → s3func-0.8.4}/s3func/http_url.py +0 -0
- {s3func-0.8.2 → s3func-0.8.4}/s3func/response.py +0 -0
- {s3func-0.8.2 → s3func-0.8.4}/s3func/tests/__init__.py +0 -0
|
@@ -131,125 +131,6 @@ def release_b2_lock(obj_lock_key, lock_id, version_ids, b2_session_kwargs):
|
|
|
131
131
|
#######################################################
|
|
132
132
|
### Other classes
|
|
133
133
|
|
|
134
|
-
|
|
135
|
-
# class B2Lock(locking.DistributedLock):
|
|
136
|
-
# """
|
|
137
|
-
# B2 implementation of DistributedLock.
|
|
138
|
-
# """
|
|
139
|
-
# def __init__(self, access_key_id: str, access_key: str, bucket: str, key: str, lock_id: str=None, **b2_session_kwargs):
|
|
140
|
-
# super().__init__(key, lock_id)
|
|
141
|
-
# self._b2_session_kwargs = dict(access_key_id=access_key_id, access_key=access_key, bucket=bucket)
|
|
142
|
-
# self._b2_session_kwargs.update(b2_session_kwargs)
|
|
143
|
-
|
|
144
|
-
# self._obj_lock_key = key + '.lock.'
|
|
145
|
-
# self._obj_lock_key_len = len(self._obj_lock_key)
|
|
146
|
-
|
|
147
|
-
# # If lock_id was provided, check if it already exists to recover state
|
|
148
|
-
# if lock_id:
|
|
149
|
-
# session = B2Session(**self._b2_session_kwargs)
|
|
150
|
-
# objs = self._list_objects(session, self._obj_lock_key, lock_id)
|
|
151
|
-
# for obj in objs:
|
|
152
|
-
# obj_key_name = obj['key']
|
|
153
|
-
# if lock_id in obj_key_name:
|
|
154
|
-
# seq = int(obj_key_name[-1])
|
|
155
|
-
# self._version_ids[seq] = obj['version_id']
|
|
156
|
-
# if seq == 1:
|
|
157
|
-
# self._timestamp = obj.get('last_modified', obj['upload_timestamp'])
|
|
158
|
-
# if self._timestamp:
|
|
159
|
-
# self._finalizer = weakref.finalize(self, release_b2_lock, self._obj_lock_key, self.lock_id, self._version_ids, self._b2_session_kwargs)
|
|
160
|
-
|
|
161
|
-
# @staticmethod
|
|
162
|
-
# def _list_objects(session, obj_lock_key, lock_id=None):
|
|
163
|
-
# key = obj_lock_key + (lock_id if lock_id else "")
|
|
164
|
-
# objs = session.list_objects(prefix=key)
|
|
165
|
-
# if objs.status in (401, 403):
|
|
166
|
-
# raise urllib3.exceptions.HTTPError(str(objs.error))
|
|
167
|
-
|
|
168
|
-
# res = []
|
|
169
|
-
# for l in objs.iter_objects():
|
|
170
|
-
# if l['content_md5'] == md5_locks['exclusive']:
|
|
171
|
-
# l['lock_type'] = 'exclusive'
|
|
172
|
-
# elif l['content_md5'] == md5_locks['shared']:
|
|
173
|
-
# l['lock_type'] = 'shared'
|
|
174
|
-
# else:
|
|
175
|
-
# continue
|
|
176
|
-
# res.append(l)
|
|
177
|
-
# return res
|
|
178
|
-
|
|
179
|
-
# def _do_put_lock_objects(self, exclusive):
|
|
180
|
-
# session = B2Session(**self._b2_session_kwargs)
|
|
181
|
-
# body = b'1' if exclusive else b'0'
|
|
182
|
-
|
|
183
|
-
# # Consistent local timestamp for B2 last_modified metadata
|
|
184
|
-
# local_ts = datetime.datetime.now(datetime.timezone.utc)
|
|
185
|
-
|
|
186
|
-
# for seq in (0, 1):
|
|
187
|
-
# obj_name = self._obj_lock_key + f'{self.lock_id}-{seq}'
|
|
188
|
-
# resp = session.put_object(obj_name, body, last_modified=local_ts)
|
|
189
|
-
# if resp.status == 200:
|
|
190
|
-
# self._version_ids[seq] = resp.metadata.get('version_id')
|
|
191
|
-
# # Use server-side upload_timestamp for ordering to avoid clock skew issues
|
|
192
|
-
# if seq == 0:
|
|
193
|
-
# self._timestamp = resp.metadata['upload_timestamp']
|
|
194
|
-
# else:
|
|
195
|
-
# release_b2_lock(self._obj_lock_key, self.lock_id, self._version_ids, self._b2_session_kwargs)
|
|
196
|
-
# raise urllib3.exceptions.HTTPError(f"Failed to put lock object: {resp.error}")
|
|
197
|
-
|
|
198
|
-
# self._finalizer = weakref.finalize(self, release_b2_lock, self._obj_lock_key, self.lock_id, self._version_ids, self._b2_session_kwargs)
|
|
199
|
-
|
|
200
|
-
# def _do_list_other_locks(self):
|
|
201
|
-
# session = B2Session(**self._b2_session_kwargs)
|
|
202
|
-
# objs = self._list_objects(session, self._obj_lock_key)
|
|
203
|
-
# other_locks = {}
|
|
204
|
-
# for l in objs:
|
|
205
|
-
# parts = l['key'][self._obj_lock_key_len:].split('-')
|
|
206
|
-
# if len(parts) != 2: continue
|
|
207
|
-
# lock_id, seq = parts
|
|
208
|
-
# if lock_id != self.lock_id:
|
|
209
|
-
# timestamp = l.get('last_modified', l['upload_timestamp'])
|
|
210
|
-
# if lock_id not in other_locks:
|
|
211
|
-
# other_locks[lock_id] = {'lock_type': l['lock_type']}
|
|
212
|
-
# other_locks[lock_id][int(seq)] = timestamp
|
|
213
|
-
# return other_locks
|
|
214
|
-
|
|
215
|
-
# def other_locks(self):
|
|
216
|
-
# session = B2Session(**self._b2_session_kwargs)
|
|
217
|
-
# objs = self._list_objects(session, self._obj_lock_key)
|
|
218
|
-
# other_locks = {}
|
|
219
|
-
# for l in objs:
|
|
220
|
-
# parts = l['key'][self._obj_lock_key_len:].split('-')
|
|
221
|
-
# if len(parts) != 2: continue
|
|
222
|
-
# lock_id, seq = parts
|
|
223
|
-
# if lock_id != self.lock_id:
|
|
224
|
-
# timestamp = l.get('last_modified', l['upload_timestamp'])
|
|
225
|
-
# other_locks[lock_id] = {
|
|
226
|
-
# 'last_modified': timestamp,
|
|
227
|
-
# 'lock_type': l['lock_type'],
|
|
228
|
-
# 'owner': l.get('owner'),
|
|
229
|
-
# }
|
|
230
|
-
# return other_locks
|
|
231
|
-
|
|
232
|
-
# def break_other_locks(self, timestamp: str | datetime.datetime=None):
|
|
233
|
-
# if timestamp is None:
|
|
234
|
-
# timestamp = datetime.datetime.now(datetime.timezone.utc)
|
|
235
|
-
# elif isinstance(timestamp, str):
|
|
236
|
-
# timestamp = datetime.datetime.fromisoformat(timestamp).astimezone(datetime.timezone.utc)
|
|
237
|
-
|
|
238
|
-
# session = B2Session(**self._b2_session_kwargs)
|
|
239
|
-
# objs = self._list_objects(session, self._obj_lock_key)
|
|
240
|
-
# keys = []
|
|
241
|
-
# for l in objs:
|
|
242
|
-
# timestamp_obj = l.get('last_modified', l['upload_timestamp'])
|
|
243
|
-
# if timestamp_obj <= timestamp:
|
|
244
|
-
# _ = session.delete_object(l['key'], l['version_id'])
|
|
245
|
-
# keys.append(l)
|
|
246
|
-
# return keys
|
|
247
|
-
|
|
248
|
-
# def locked(self):
|
|
249
|
-
# session = B2Session(**self._b2_session_kwargs)
|
|
250
|
-
# return len(self._list_objects(session, self._obj_lock_key)) > 0
|
|
251
|
-
|
|
252
|
-
|
|
253
134
|
#######################################################
|
|
254
135
|
### Main class
|
|
255
136
|
|
|
@@ -714,18 +595,38 @@ class B2Session:
|
|
|
714
595
|
|
|
715
596
|
return b2resp
|
|
716
597
|
|
|
717
|
-
def delete_objects(self, keys: List[dict]):
|
|
598
|
+
def delete_objects(self, keys: Union[List[str], List[dict]], purge: bool = True):
|
|
718
599
|
"""
|
|
719
|
-
|
|
600
|
+
Delete multiple objects from a B2 bucket.
|
|
601
|
+
|
|
602
|
+
Parameters
|
|
603
|
+
----------
|
|
604
|
+
keys : list of str or list of dict
|
|
605
|
+
Either a list of key strings (e.g. ['foo.bin', 'bar.bin']) or a list of
|
|
606
|
+
dicts with 'key' and optionally 'version_id' fields.
|
|
607
|
+
purge : bool
|
|
608
|
+
If True (default), all versions of each object are deleted. If False,
|
|
609
|
+
version_id is required in each dict and only those specific versions
|
|
610
|
+
are deleted.
|
|
720
611
|
|
|
721
612
|
Returns
|
|
722
613
|
-------
|
|
723
614
|
None
|
|
724
615
|
"""
|
|
616
|
+
# Normalize input: strings -> dicts
|
|
617
|
+
if keys and isinstance(keys[0], str):
|
|
618
|
+
keys = [{'key': k} for k in keys]
|
|
619
|
+
|
|
725
620
|
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
|
726
621
|
futures = []
|
|
727
622
|
for key_dict in keys:
|
|
728
|
-
|
|
623
|
+
key_name = key_dict.get('key') or key_dict.get('Key')
|
|
624
|
+
version_id = key_dict.get('version_id') or key_dict.get('VersionId')
|
|
625
|
+
if purge and not version_id:
|
|
626
|
+
# delete_object with version_id=None lists and deletes all versions
|
|
627
|
+
future = executor.submit(self.delete_object, key_name, None)
|
|
628
|
+
else:
|
|
629
|
+
future = executor.submit(self.delete_object, key_name, version_id)
|
|
729
630
|
futures.append(future)
|
|
730
631
|
concurrent.futures.wait(futures)
|
|
731
632
|
|
|
@@ -138,13 +138,23 @@ class DistributedLock:
|
|
|
138
138
|
@staticmethod
|
|
139
139
|
def _list_objects(session, obj_lock_key, lock_id=None):
|
|
140
140
|
key = obj_lock_key + (lock_id if lock_id else "")
|
|
141
|
-
objs = session.list_object_versions(prefix=key)
|
|
142
141
|
|
|
143
|
-
|
|
144
|
-
|
|
142
|
+
# Try list_object_versions first; fall back to list_objects
|
|
143
|
+
# for providers that don't support versioning (e.g. Mega S3)
|
|
144
|
+
objs = session.list_object_versions(prefix=key)
|
|
145
|
+
try:
|
|
146
|
+
items = list(objs.iter_objects())
|
|
147
|
+
except urllib3.exceptions.HTTPError as e:
|
|
148
|
+
if '501' in str(e):
|
|
149
|
+
objs = session.list_objects(prefix=key)
|
|
150
|
+
items = list(objs.iter_objects())
|
|
151
|
+
elif '401' in str(e) or '403' in str(e):
|
|
152
|
+
raise
|
|
153
|
+
else:
|
|
154
|
+
raise
|
|
145
155
|
|
|
146
156
|
res = []
|
|
147
|
-
for l in
|
|
157
|
+
for l in items:
|
|
148
158
|
if not l.get('is_latest', True):
|
|
149
159
|
continue
|
|
150
160
|
if l.get('content_md5') == md5_locks['exclusive']:
|
|
@@ -278,7 +288,10 @@ class DistributedLock:
|
|
|
278
288
|
keys = []
|
|
279
289
|
for l in objs:
|
|
280
290
|
if l['upload_timestamp'] <= timestamp:
|
|
281
|
-
|
|
291
|
+
d = {'key': l['key']}
|
|
292
|
+
if l.get('version_id'):
|
|
293
|
+
d['version_id'] = l['version_id']
|
|
294
|
+
keys.append(d)
|
|
282
295
|
if keys:
|
|
283
296
|
session.delete_objects(keys)
|
|
284
297
|
|
|
@@ -352,14 +352,50 @@ class S3Session:
|
|
|
352
352
|
|
|
353
353
|
return s3resp
|
|
354
354
|
|
|
355
|
-
def delete_objects(self, keys: List[dict]):
|
|
355
|
+
def delete_objects(self, keys: Union[List[str], List[dict]], purge: bool = True):
|
|
356
356
|
"""
|
|
357
|
-
|
|
357
|
+
Delete multiple objects from an S3 bucket.
|
|
358
|
+
|
|
359
|
+
Parameters
|
|
360
|
+
----------
|
|
361
|
+
keys : list of str or list of dict
|
|
362
|
+
Either a list of key strings (e.g. ['foo.bin', 'bar.bin']) or a list of
|
|
363
|
+
dicts with 'key' and optionally 'version_id' fields.
|
|
364
|
+
purge : bool
|
|
365
|
+
If True (default), all versions of each object are deleted by listing
|
|
366
|
+
versions first. If False, objects are deleted without version IDs
|
|
367
|
+
(which only adds a delete marker on versioned buckets).
|
|
358
368
|
|
|
359
369
|
Returns
|
|
360
370
|
-------
|
|
361
371
|
None
|
|
362
372
|
"""
|
|
373
|
+
# Normalize input: strings -> dicts
|
|
374
|
+
if keys and isinstance(keys[0], str):
|
|
375
|
+
keys = [{'key': k} for k in keys]
|
|
376
|
+
|
|
377
|
+
# If purge, resolve version IDs for keys that don't have them
|
|
378
|
+
if purge:
|
|
379
|
+
resolved = []
|
|
380
|
+
for k in keys:
|
|
381
|
+
key_name = k.get('key') or k.get('Key')
|
|
382
|
+
version_id = k.get('version_id') or k.get('VersionId')
|
|
383
|
+
if version_id:
|
|
384
|
+
resolved.append(k)
|
|
385
|
+
else:
|
|
386
|
+
try:
|
|
387
|
+
resp = self.list_object_versions(prefix=key_name)
|
|
388
|
+
found = False
|
|
389
|
+
for obj in resp.iter_objects():
|
|
390
|
+
if obj['key'] == key_name:
|
|
391
|
+
resolved.append({'key': obj['key'], 'version_id': obj['version_id']})
|
|
392
|
+
found = True
|
|
393
|
+
if not found:
|
|
394
|
+
resolved.append(k)
|
|
395
|
+
except Exception:
|
|
396
|
+
resolved.append(k)
|
|
397
|
+
keys = resolved
|
|
398
|
+
|
|
363
399
|
# S3 Delete Objects requires a specific XML payload
|
|
364
400
|
# <Delete><Object><Key>...</Key><VersionId>...</VersionId></Object>...</Delete>
|
|
365
401
|
url = urllib.parse.urljoin(self._endpoint_url, f"{self.bucket}")
|
|
@@ -367,7 +403,6 @@ class S3Session:
|
|
|
367
403
|
for keys_chunk in utils.chunks(keys, 1000):
|
|
368
404
|
# Build XML
|
|
369
405
|
root = ET.Element('Delete', xmlns="http://s3.amazonaws.com/doc/2006-03-01/")
|
|
370
|
-
# Quiet mode? Original used Quiet=True
|
|
371
406
|
quiet = ET.SubElement(root, 'Quiet')
|
|
372
407
|
quiet.text = 'true'
|
|
373
408
|
|
|
@@ -380,23 +415,18 @@ class S3Session:
|
|
|
380
415
|
else:
|
|
381
416
|
raise ValueError('"key" must be passed in the list of dict.')
|
|
382
417
|
|
|
383
|
-
if 'version_id'
|
|
418
|
+
if k.get('version_id'):
|
|
384
419
|
ET.SubElement(obj, 'VersionId').text = k['version_id']
|
|
385
|
-
elif 'VersionId'
|
|
420
|
+
elif k.get('VersionId'):
|
|
386
421
|
ET.SubElement(obj, 'VersionId').text = k['VersionId']
|
|
387
422
|
|
|
388
423
|
body = ET.tostring(root, encoding='utf-8')
|
|
389
424
|
|
|
390
|
-
# Subresource ?delete
|
|
391
425
|
query_params = {'delete': ''}
|
|
392
426
|
|
|
393
|
-
# Content-MD5 is often required for DeleteObjects for integrity, but let's try without first or add if needed.
|
|
394
|
-
# SigV4 protects integrity too.
|
|
395
|
-
|
|
396
427
|
md5 = base64.b64encode(hashlib.md5(body).digest()).decode('utf-8')
|
|
397
428
|
headers = {'Content-MD5': md5, 'Content-Type': 'application/xml'}
|
|
398
429
|
|
|
399
|
-
# Delete objects response is small, preload it
|
|
400
430
|
self.request('POST', url, headers=headers, fields=query_params, body=body, preload_content=True)
|
|
401
431
|
|
|
402
432
|
def copy_object(
|
|
@@ -94,7 +94,7 @@ class SigV4Auth:
|
|
|
94
94
|
if k_lower == 'authorization':
|
|
95
95
|
continue
|
|
96
96
|
# Sign x-amz-*, host, and content-length/type
|
|
97
|
-
if k_lower == 'host' or k_lower.startswith('x-amz-') or k_lower in ('content-length', 'content-type'):
|
|
97
|
+
if k_lower == 'host' or k_lower.startswith('x-amz-') or k_lower in ('content-length', 'content-type', 'content-md5'):
|
|
98
98
|
v_trimmed = ' '.join(v.split()) # Remove extra whitespace
|
|
99
99
|
canonical_headers_list.append(f"{k_lower}:{v_trimmed}")
|
|
100
100
|
signed_headers_list.append(k_lower)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Shared fixtures for s3func tests.
|
|
3
|
+
|
|
4
|
+
Provider configs are loaded from s3_config.toml (local dev) and/or
|
|
5
|
+
prefixed environment variables (CI). Each S3-compatible provider gets
|
|
6
|
+
its own parameterized test run.
|
|
7
|
+
|
|
8
|
+
To add a new provider:
|
|
9
|
+
1. Add a [providers.<name>] section to s3_config.toml, OR
|
|
10
|
+
2. Set env vars: <name>_endpoint_url, <name>_access_key_id, <name>_access_key, <name>_bucket
|
|
11
|
+
"""
|
|
12
|
+
import os
|
|
13
|
+
import pathlib
|
|
14
|
+
import uuid
|
|
15
|
+
|
|
16
|
+
import pytest
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
import tomllib as toml
|
|
20
|
+
except ImportError:
|
|
21
|
+
import tomli as toml
|
|
22
|
+
|
|
23
|
+
from s3func import s3
|
|
24
|
+
|
|
25
|
+
script_path = pathlib.Path(os.path.realpath(os.path.dirname(__file__)))
|
|
26
|
+
|
|
27
|
+
# Known provider prefixes to check in environment variables
|
|
28
|
+
_ENV_PREFIXES = ['b2', 'mega']
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _load_providers():
|
|
32
|
+
"""Load S3-compatible provider configs from toml and/or environment variables."""
|
|
33
|
+
providers = {}
|
|
34
|
+
|
|
35
|
+
# Load from toml
|
|
36
|
+
toml_path = script_path / 's3_config.toml'
|
|
37
|
+
if toml_path.exists():
|
|
38
|
+
with open(toml_path, 'rb') as f:
|
|
39
|
+
config = toml.load(f)
|
|
40
|
+
for name, conf in config.get('providers', {}).items():
|
|
41
|
+
providers[name] = conf
|
|
42
|
+
|
|
43
|
+
# Load from environment variables (may override toml)
|
|
44
|
+
for prefix in _ENV_PREFIXES:
|
|
45
|
+
key_id = os.environ.get(f'{prefix}_access_key_id')
|
|
46
|
+
key = os.environ.get(f'{prefix}_access_key')
|
|
47
|
+
bucket = os.environ.get(f'{prefix}_bucket')
|
|
48
|
+
if key_id and key and bucket:
|
|
49
|
+
providers[prefix] = {
|
|
50
|
+
'endpoint_url': os.environ.get(f'{prefix}_endpoint_url'),
|
|
51
|
+
'access_key_id': key_id,
|
|
52
|
+
'access_key': key,
|
|
53
|
+
'bucket': bucket,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return providers
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
provider_configs = _load_providers()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@pytest.fixture(params=list(provider_configs.keys()) or ['no_providers'], scope='module')
|
|
63
|
+
def s3_provider(request):
|
|
64
|
+
"""Yield (name, config_dict) for each available S3-compatible provider."""
|
|
65
|
+
if request.param == 'no_providers':
|
|
66
|
+
pytest.skip('No S3 provider credentials available')
|
|
67
|
+
return request.param, provider_configs[request.param]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@pytest.fixture(scope='module')
|
|
71
|
+
def s3_session(s3_provider):
|
|
72
|
+
"""Create an S3Session for the current provider."""
|
|
73
|
+
name, config = s3_provider
|
|
74
|
+
return s3.S3Session(
|
|
75
|
+
config['access_key_id'],
|
|
76
|
+
config['access_key'],
|
|
77
|
+
config['bucket'],
|
|
78
|
+
endpoint_url=config.get('endpoint_url'),
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@pytest.fixture(scope='module')
|
|
83
|
+
def s3_test_key():
|
|
84
|
+
"""Unique object key for this test run."""
|
|
85
|
+
return uuid.uuid4().hex
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import os, pathlib
|
|
3
|
+
import uuid
|
|
4
|
+
from time import sleep
|
|
5
|
+
import concurrent.futures
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
import tomllib as toml
|
|
9
|
+
except ImportError:
|
|
10
|
+
import tomli as toml
|
|
11
|
+
from s3func import s3, b2
|
|
12
|
+
|
|
13
|
+
#################################################
|
|
14
|
+
### Parameters
|
|
15
|
+
|
|
16
|
+
script_path = pathlib.Path(os.path.realpath(os.path.dirname(__file__)))
|
|
17
|
+
|
|
18
|
+
# Legacy credentials for B2-native lock tests
|
|
19
|
+
try:
|
|
20
|
+
with open(script_path.joinpath('s3_config.toml'), "rb") as f:
|
|
21
|
+
conn_config = toml.load(f)['connection_config']
|
|
22
|
+
legacy_endpoint_url = conn_config['endpoint_url']
|
|
23
|
+
legacy_access_key_id = conn_config['aws_access_key_id']
|
|
24
|
+
legacy_access_key = conn_config['aws_secret_access_key']
|
|
25
|
+
except:
|
|
26
|
+
legacy_endpoint_url = os.environ.get('endpoint_url')
|
|
27
|
+
legacy_access_key_id = os.environ.get('aws_access_key_id')
|
|
28
|
+
legacy_access_key = os.environ.get('aws_secret_access_key')
|
|
29
|
+
|
|
30
|
+
legacy_bucket = 'achelous'
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
################################################
|
|
34
|
+
### Helper functions
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def worker_lock(session, key, results, timeout=120):
|
|
38
|
+
"""Worker function for concurrency test."""
|
|
39
|
+
lock = session.lock(key)
|
|
40
|
+
acquired = lock.acquire(blocking=True, timeout=timeout)
|
|
41
|
+
if acquired:
|
|
42
|
+
results.append(True)
|
|
43
|
+
sleep(0.1)
|
|
44
|
+
lock.release()
|
|
45
|
+
else:
|
|
46
|
+
results.append(False)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
################################################
|
|
50
|
+
### S3-compatible lock tests (parameterized)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_s3_lock(s3_session):
|
|
54
|
+
"""Test lock acquire, release, and context manager."""
|
|
55
|
+
obj_key = uuid.uuid4().hex
|
|
56
|
+
|
|
57
|
+
lock = s3_session.lock(obj_key)
|
|
58
|
+
|
|
59
|
+
other_locks = lock.other_locks()
|
|
60
|
+
assert isinstance(other_locks, dict)
|
|
61
|
+
|
|
62
|
+
if other_locks:
|
|
63
|
+
lock.break_other_locks()
|
|
64
|
+
|
|
65
|
+
assert not lock.locked()
|
|
66
|
+
assert lock.acquire()
|
|
67
|
+
assert lock.locked()
|
|
68
|
+
|
|
69
|
+
lock.release()
|
|
70
|
+
assert not lock.locked()
|
|
71
|
+
|
|
72
|
+
with lock:
|
|
73
|
+
assert lock.locked()
|
|
74
|
+
|
|
75
|
+
assert not lock.locked()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_s3_lock_concurrency(s3_session):
|
|
79
|
+
"""Verify multiple threads can acquire the lock sequentially."""
|
|
80
|
+
concurrency_key = uuid.uuid4().hex + '.concurrent'
|
|
81
|
+
results = []
|
|
82
|
+
|
|
83
|
+
initial_lock = s3_session.lock(concurrency_key)
|
|
84
|
+
if initial_lock.other_locks():
|
|
85
|
+
initial_lock.break_other_locks()
|
|
86
|
+
|
|
87
|
+
num_workers = 2
|
|
88
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
|
|
89
|
+
futures = [executor.submit(worker_lock, s3_session, concurrency_key, results) for _ in range(num_workers)]
|
|
90
|
+
concurrent.futures.wait(futures)
|
|
91
|
+
|
|
92
|
+
assert sum(results) == num_workers
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
################################################
|
|
96
|
+
### B2-native lock tests (not parameterized)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_B2Lock():
|
|
100
|
+
"""Test B2 native lock."""
|
|
101
|
+
if not legacy_access_key_id:
|
|
102
|
+
pytest.skip('Legacy B2 credentials not available')
|
|
103
|
+
|
|
104
|
+
b2_session = b2.B2Session(legacy_access_key_id, legacy_access_key)
|
|
105
|
+
obj_key = uuid.uuid4().hex
|
|
106
|
+
|
|
107
|
+
lock = b2_session.lock(obj_key)
|
|
108
|
+
|
|
109
|
+
other_locks = lock.other_locks()
|
|
110
|
+
assert isinstance(other_locks, dict)
|
|
111
|
+
|
|
112
|
+
if other_locks:
|
|
113
|
+
lock.break_other_locks()
|
|
114
|
+
|
|
115
|
+
assert not lock.locked()
|
|
116
|
+
assert lock.acquire()
|
|
117
|
+
assert lock.locked()
|
|
118
|
+
|
|
119
|
+
lock.release()
|
|
120
|
+
assert not lock.locked()
|
|
121
|
+
|
|
122
|
+
with lock:
|
|
123
|
+
assert lock.locked()
|
|
124
|
+
|
|
125
|
+
assert not lock.locked()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def test_B2Lock_concurrency():
|
|
129
|
+
"""Verify B2 lock concurrency."""
|
|
130
|
+
if not legacy_access_key_id:
|
|
131
|
+
pytest.skip('Legacy B2 credentials not available')
|
|
132
|
+
|
|
133
|
+
concurrency_key = uuid.uuid4().hex + '.concurrent'
|
|
134
|
+
results = []
|
|
135
|
+
|
|
136
|
+
b2_session = b2.B2Session(legacy_access_key_id, legacy_access_key)
|
|
137
|
+
|
|
138
|
+
initial_lock = b2_session.lock(concurrency_key)
|
|
139
|
+
if initial_lock.other_locks():
|
|
140
|
+
initial_lock.break_other_locks()
|
|
141
|
+
|
|
142
|
+
num_workers = 4
|
|
143
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
|
|
144
|
+
futures = [executor.submit(worker_lock, b2_session, concurrency_key, results) for _ in range(num_workers)]
|
|
145
|
+
concurrent.futures.wait(futures)
|
|
146
|
+
|
|
147
|
+
assert sum(results) == num_workers
|
|
@@ -100,6 +100,19 @@ def test_mock_s3_delete_objects(s3_session):
|
|
|
100
100
|
assert not found
|
|
101
101
|
|
|
102
102
|
|
|
103
|
+
def test_mock_s3_delete_objects_string_keys(s3_session):
|
|
104
|
+
"""delete_objects accepts a list of key strings."""
|
|
105
|
+
keys = [f"delete-str-{uuid.uuid4().hex}-{i}" for i in range(3)]
|
|
106
|
+
for key in keys:
|
|
107
|
+
s3_session.put_object(key, b"data")
|
|
108
|
+
|
|
109
|
+
s3_session.delete_objects(keys)
|
|
110
|
+
|
|
111
|
+
listed = {obj['key'] for obj in s3_session.list_objects().iter_objects()}
|
|
112
|
+
for key in keys:
|
|
113
|
+
assert key not in listed
|
|
114
|
+
|
|
115
|
+
|
|
103
116
|
def test_mock_s3_copy_object(s3_session):
|
|
104
117
|
src_key = "src-key"
|
|
105
118
|
dest_key = "dest-key"
|