s3func 0.9.2__tar.gz → 0.9.3__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.3
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
@@ -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.3'
@@ -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
@@ -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))
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