Design an inventory management system
medium 80 minCount goods in several places, promise them to orders without ever promising too much, ship or let go, and explain every count.
Watch lesson4:28
Expiry
Promises that end by themselves
The point: expiry is decided by the clock when somebody asks, and cleaned up by a sweeper. The sweeper is housekeeping; correctness does not depend on it.
Two moments
Overdue, and swept
| Who looks | At 899 | At 900 | At 903, sweeper was late |
|---|---|---|---|
ship | Works | Refused, gives back | Refused |
release | Works | Refused, gives back | Refused |
available | Counts as held | Still counts as held | Free after the sweep |
Structure
A heap, with lazy removal
Walking all promises each second is wasteful: most are not due. A heap keeps the next one on top. Shipped promises are not searched for in the heap. They are thrown away when they reach the top.
Python
import heapqclass Promises: def __init__(self): self.open = {} # id -> end self.heap = [] # (end, id), may hold ids that are closed already def add(self, rid, end): self.open[rid] = end heapq.heappush(self.heap, (end, rid)) def extend(self, rid, end): if rid not in self.open: raise KeyError("closed already") self.add(rid, end) # the older entry stays in the heap and is ignored def close(self, rid): return self.open.pop(rid, None) is not None def due(self, now, limit=100): out = [] while self.heap and self.heap[0][0] <= now and len(out) < limit: end, rid = heapq.heappop(self.heap) if self.open.get(rid) == end: # not shipped, and not extended del self.open[rid] out.append(rid) return outp = Promises()p.add(1, 900); p.add(2, 300); p.add(3, 600)p.close(3) # shippedp.extend(2, 1200) # the customer asked for more timeassert p.due(900) == [1]assert p.due(1199) == [] and p.due(1200) == [2]print("ok")limit keeps each visit short, so that a thousand overdue promises do not hold the lock in one go.Race
Payment arrives in the last second
How do you avoid taking money for a jar that is gone?
BreaksIgnore the end if the card was accepted
- How
shipskips the check when paid.- Limit
- The jar may be promised to somebody else. Held would go below zero or a second customer loses.
- Choose when
- Never.
WorksReserve again, or refund
- How
- Try a new reserve. If sold out, give the money back.
- Limit
- Sometimes a customer pays and gets an apology.
- Choose when
- Always as the last net.
StrongConfirm before the charge
- How
- A step
start_payment(id)extends the promise while the card is asked, with a hard limit, for example five minutes. - Limit
- One more state, and a card that hangs holds jars a little longer.
- Choose when
- When paying takes seconds. With the last net behind it.