Renewing the Lease

Step 4: Renewing the Lease

A short TTL is safer (a crash frees the lock fast) but a real job might outlive it. The answer isn't a longer lease, it's a heartbeat: while the holder is alive and working, it periodically extends its own lease.

  • renew(name, client_id, ttl): if client_id still holds a live lease, push the expiry out to now + ttl and return True.
  • You may not renew a lease that has already expired, nor one you don't own. Return False.
Hints
Starter code
import time


class LockManager:
    def __init__(self, clock=time.time):
        self.clock = clock
        self._locks = {}   # name -> {"client", "expiry"}

    def acquire(self, name, client_id, ttl):
        now = self.clock()
        cur = self._locks.get(name)
        if cur is None or cur["expiry"] <= now:
            self._locks[name] = {"client": client_id, "expiry": now + ttl}
            return True
        return False

    def renew(self, name, client_id, ttl):
        """Extend a live lease you own. Return True on success."""
        now = self.clock()
        cur = self._locks.get(name)
        # TODO: renewal is allowed only when cur exists, its stored client
        #   matches client_id, and its expiry is still strictly later than now.
        #   In that case push the entry's expiry out to ttl seconds past now and
        #   answer True. Every other case answers False and changes nothing.
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.