Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 10
Module 5 · Design problems II: lockers, vending and blackjack · Chapter 10 of 28
Parcel Locker Service: Slots, Pickup Codes and Expiry
Builds on Solving a Design Problem: Requirements to Tested Code in Six Steps, Design Patterns in TypeScript: Creational, Structural and Behavioural and Parking Lot: Floors, Spots, Tickets and Fees. Next up: Vending Machine: States, Payments and Making Change.
Part 1 · Requirements
What the lockers must do
At a Bengaluru metro station a wall of lockers lets a courier leave a parcel for someone who passes by later. This chapter builds the software behind that wall as small classes you can run and test.
As in the parking lot chapter, the functional requirements come first. Here is the list for a station with one bank of lockers.
- A site has slots of three sizes: small, medium and large. A parcel is small, medium or large.
- A parcel goes into the smallest free slot it fits. A small parcel may use a medium or large slot when no small one is free.
- The courier is told which slot to use. The customer does not choose.
- Once the parcel is inside, the customer gets a six-digit pickup code by text message.
- The code opens the slot once. After that it is dead.
- A parcel left for three days or more is expired. Station staff empty the slot and send the parcel back.
- A customer can also leave a parcel, a return, for a courier to collect. The same slots and codes serve it.
- If no slot fits, the courier is refused with a reason.
Nothing above says how a door opens, how the text message travels or how a courier proves who they are. Requirements state behaviour. The design decides the rest.
A prompt as short as "design a parcel locker" leaves rules open, so the list comes from questions. Ask the ones whose answers change a class or a method.
| Question | If the answer is yes | Our answer |
|---|---|---|
| May a parcel use a bigger slot? | Allocation needs an order of sizes | Yes, smallest first |
Quality, numbers and scope
Non-functional requirements say how well the system behaves. Three matter here. A slot must never hold two parcels. A code must never open a slot that is not its own. And the same sequence of events must give the same result every time, so tests can rely on it.
The numbers below are our model, not any real operator's rules.
| Rule | Value in our model |
|---|---|
| Slot sizes | small, medium, large |
| Pickup code | six digits, such as 004821 |
| Pickup window | 3 days from the moment the parcel is inside |
| Codes | one use each, unique among live codes at a site |
Six digits give 10,00,000 (10 lakh) possible codes. If a site holds 100 parcels, a random guess hits a live code about once in 10,000 tries. That is why the extensions lesson limits wrong guesses.
We also rejected two designs. The first lets the customer type the slot number instead of a code. It needs no random numbers, but anyone who sees the number can open the slot. The second gives each parcel a long random identifier. It is hard to guess, but nobody wants to type 36 characters on a station keypad. A short code with a limit on wrong guesses fits a keypad and still keeps strangers out.
| Must | Should | Out of scope |
|---|---|---|
| Smallest fit, codes, expiry, returns, text message | Lock the keypad after wrong codes, nearest site | Payments, door hardware, courier identity checks |
Check yourself
A site has one free medium slot and one free large slot. Where does a small parcel go?
- Into the medium slot, because the smallest free slot that fits wins.
- The large slot stays free for a parcel that needs it.
Why is the code not simply the slot number?
- Anyone standing nearby could read it and open the slot.
- A random code is not guessable from what is visible on the wall.
The answer to "can a parcel stay forever" becomes yes. What goes away?
- The expired state, the sweep and the return trip.
- Slots could fill up with forgotten parcels, so some other limit would be needed.
Part 2 · Use cases
Actors and use cases
An actor is someone outside the system who uses it. A use case is one goal an actor wants to reach. The lockers have three actors: the courier who leaves parcels, the customer who collects them or leaves a return, and station staff who empty expired slots.
A use case diagram shows actors, the use cases each one starts and how use cases relate. Include means a use case always runs another as part of itself. Extend means an exceptional case that adds steps to a base case under a condition. Delivering a parcel always includes notifying the customer, and the refusal when no slot fits extends delivery.
The blue boxes are actors and the pills are use cases, with the exceptional ones in red. An arrow from an actor means the actor starts that use case. Every other arrow runs from a base case to the case it includes or the case that extends it, labelled "includes" or "extended by". The UML chapter explains why the extend arrow is drawn from the base case here.
The refusal is drawn once, under delivery, but it applies to drop-offs too, because a customer's return needs a slot as well. Read the diagram as a checklist of goals. Each pill becomes one or two methods and a few tests.
Flows and alternatives
Each use case gets a short written flow: a trigger, the main steps and the alternatives. Writing alternatives now is cheap. Finding them after the code exists is not.
| Use case | Main flow | Alternatives |
|---|---|---|
| Deliver a parcel | Courier scans the parcel; service picks a slot; courier fills it; service issues a code | No slot fits: refuse. Courier changes their mind: free the slot |
| Notify the customer | The code goes to the customer's phone | None in our model |
| Pick up a parcel | Customer types the code; the slot opens and is free again | Wrong code, used code, window over: refuse |
| Drop off a return | Customer is given a slot and fills it; the courier who collects gets the code | No slot fits: refuse |
| Expire and return | A timed sweep marks late parcels; staff empty the slot; parcel goes back | Slot not expired: refuse |
Alternatives are where requirements get argued, so each one becomes a named refusal. A refusal must change nothing. A wrong code must not touch a slot, and a refused parcel must not leave a half-reserved slot behind. We will test that.
One detail deserves a decision now. A slot is reserved when the courier is told which one to use, and the code is created only when the parcel is confirmed inside. A courier who walks away has not left a parcel, so no customer should be given a code for an empty slot.
Use cases as test names
As in the parking lot chapter, each use case becomes a test.todo name that is reported but not run, and each turns into a real test as the code lands.
test.todo('a courier delivers a parcel into a free slot'); test.todo('the customer is told the code'); test.todo('the customer picks up with the code'); test.todo('a parcel is refused when no slot fits'); test.todo('an unclaimed parcel expires and is returned'); test.todo('a customer drops off a return for the courier');
✔ a courier delivers a parcel into a free slot (0.6437ms) # TODO ✔ the customer is told the code (0.0885ms) # TODO ✔ the customer picks up with the code (0.1118ms) # TODO ✔ a parcel is refused when no slot fits (0.0783ms) # TODO ✔ an unclaimed parcel expires and is returned (0.0883ms) # TODO ✔ a customer drops off a return for the courier (0.0711ms) # TODO ℹ tests 6 ℹ todo 6
Output (durations vary)
All six names are reported as todo, and none counts as passed. Later lessons replace them with tests that pass. If a name never gets a test, the requirement behind it was probably missed.
What is the difference between include and extend?
- Include: the base case always runs the included case, as delivery always notifies.
- Extend: an exceptional case adds steps under a condition, as the no-slot refusal does.
Which is an actor: the keypad, station staff, or the pickup code?
- Station staff. An actor is outside the system and has a goal.
- The keypad and the code are parts of the system.
Part 3 · Class diagram
From nouns to classes
Read the requirements again and underline the nouns: site, locker, slot, parcel, code, courier, customer, text message. Not every noun becomes a class. A useful test is whether the thing has its own rules to protect.
| Noun | Decision | Why |
|---|---|---|
| Site, locker bank | Class Site | Owns its slots and finds a free one |
| Slot | Class Slot | Has a lifecycle with legal and illegal moves |
| Parcel | Record inside the service | Holds data, with no rules of its own |
| Pickup code | String, held by the service | A six-digit value has no behaviour |
| Allocation rule | The FITS table | A lookup from parcel size to usable slot sizes |
| Text message | Interface Notifier | Delivery is not our problem, so we inject it |
| Courier, customer | Not classes | They call the system, so they stay outside |
Two choices are worth defending. The code is a plain string because a class with only a string inside would add a name and no rule. The allocation rule is a table, not an AllocationPolicy class. A table says it in five lines, and a new size is a new row. If sites later prefer the slot nearest the door, that is the moment to turn it into a strategy, an interface for one swappable rule.
The class diagram
A class diagram shows classes, what they hold and how they relate. Multiplicity is the number on each link end: 1..* means one or more, * zero or more, 0..1 at most one.
reserve(id, size, kind, phone): slotIdconfirmDrop(id): codepickup(code): idsweep(): idsclear(slotId): idid: stringpeek(size): slotId?apply(slotId, event)counts()id: stringsize: small | medium | largestate: free | reserved | occupied | expiredid, size, kind, phoneslotIdcode?, expiresAt?now(): numberint(min, max): numbersend(to, text)- LockerService 1 → 1 Site
- Site 1 → 1..* Slot
- LockerService 1 → 0..* Parcel (record)
- Parcel (record) 0..1 → 1 Slot
- LockerService 1 → 1 Clock (interface)
- LockerService 1 → 1 Random (interface)
- LockerService 1 → 1 Notifier (interface)
Read the links like sentences. A service uses one site. A site has one or more slots. The service tracks zero or more parcels, and a parcel sits in exactly one slot while it is in the system. The service depends on three interfaces and knows nothing about real clocks, random sources or phones.
The skeleton in TypeScript
As in the parking lot chapter, a compiler checks the diagram before anything else. We start with the shared types. They are plain unions and tables, because enum is not erasable syntax and Node's type stripping rejects it.
export const SIZES = ['small', 'medium', 'large'] as const; export type Size = (typeof SIZES)[number]; export type Kind = 'delivery' | 'return'; // Slot sizes a parcel may use, smallest first. export const FITS: Record<Size, readonly Size[]> = { small: ['small', 'medium', 'large'], medium: ['medium', 'large'], large: ['large'], }; export const DAY_MIN = 24 * 60; export const WINDOW_MIN = 3 * DAY_MIN; export const WINDOW_MS = WINDOW_MIN * 60_000;
Each parcel size lists the slot sizes it may use, smallest first. That one table drives allocation. The error type comes next.
export type LockerCode = | 'NO_SLOT' | 'UNKNOWN_PARCEL' | 'UNKNOWN_SLOT' | 'BAD_STATE' | 'CODE_INVALID' | 'CODE_USED' | 'CODE_EXPIRED' | 'LOCKED_OUT'; export class LockerError extends Error { readonly code: LockerCode; constructor(code: LockerCode, message: string) { super(message); this.name = 'LockerError'; this.code = code; } }
Every refusal is a LockerError with a code from a closed set. Callers and tests branch on the code, never on the message text. The random source is an interface with one method.
export interface Random { // a whole number from min up to, but not including, max int(min: number, max: number): number; } export class SystemRandom implements Random { int(min: number, max: number): number { return randomInt(min, max); } } // Plays back fixed numbers, for tests and demos. export class ScriptedRandom implements Random { #values: number[]; #next = 0; constructor(values: number[]) { this.#values = values; } int(): number { const v = this.#values[this.#next % this.#values.length]; this.#next += 1; return v; } }
SystemRandom calls crypto.randomInt. ScriptedRandom plays back numbers chosen by the test. Type-check the project:
npx tsc -p .
(no output, exit code 0)Output
Why is the pickup code a string and not a class?
Part 4 · Slot lifecycle and delivery
The slot lifecycle
A slot moves through a small set of states, and only some moves are legal. A state machine lists the states, the events that cause moves and the events a state refuses. Drawing it first turns many if statements into one table.
Our slot starts free. Reserving it for a courier makes it reserved. The courier either cancels, which frees it, or deposits the parcel, which makes it occupied. An occupied slot is freed by a pickup, or expired when the window ends. Only staff move an expired slot back to free.
Watch for the locker refusing a pickup once the slot has expired
Read it as steps
A slot is reserved, filled, then either emptied by the customer or expired after three days.
The scene ends on the refusal. After the window the code no longer opens the door. Two layers say no. The service checks the time first and answers CODE_EXPIRED. Even without that check, the table has no pickup entry for expired, so the slot itself would refuse with BAD_STATE. We test both.
One parcel, from courier to customer
Now follow one parcel through the system. The courier scans it, and the service asks the site for the smallest free slot that fits. It reserves that slot and tells the courier. When the courier confirms the parcel is inside, the service draws a code and sends it.
Watch for the service reserving a slot before the courier opens the door
Read it as steps
The slot is reserved before the door opens, and the code exists only after the parcel is inside.
Two orderings matter. The slot is reserved before the door opens, so two couriers never get the same slot. And the code appears only after the deposit is confirmed, so a customer is never told a code for an empty slot.
The courier can still change their mind between the two calls. cancelDrop moves the slot from reserved back to free and forgets the parcel, and no code was ever made, so there is nothing to clean up.
A check that can fail comes before a change. reserve looks for a slot first and throws NO_SLOT before it touches any state, so a refused parcel leaves the site as it was. The same holds in pickup, which checks the code and the time before it frees anything.
Run the driver
The driver is the demo.ts script from the approach chapter, which runs the core flow once and prints what happened. This driver delivers one medium parcel with a scripted random number, tries a wrong code, picks up and then tries the same code again.
const clock = new FakeClock(); const notifier = new FakeNotifier(); const site = new Site('ST1', { small: 2, medium: 2, large: 1 }); const lockers = new LockerService({ site, clock, notifier, random: new ScriptedRandom([4821]), }); const slot = lockers.reserve('P-1', 'medium', 'delivery', '0100000001'); console.log('courier gets slot', slot, site.counts()); const code = lockers.confirmDrop('P-1'); console.log('customer is told:', notifier.sent[0].text); try { lockers.pickup('000000'); } catch (e) { if (e instanceof LockerError) console.log('wrong code:', e.code); } console.log('opened for', lockers.pickup(code), site.counts()); try { lockers.pickup(code); } catch (e) { if (e instanceof LockerError) console.log('second try:', e.code); }
courier gets slot ST1-M1 { small: 2, medium: 1, large: 1 }
customer is told: Parcel P-1: code 004821
wrong code: CODE_INVALID
opened for P-1 { small: 2, medium: 2, large: 1 }
second try: CODE_USEDOutput
The courier got ST1-M1, the smallest medium slot, and the free counts went from two medium slots to one. The text said code 004821, which is the scripted number 4821 padded to six digits. The wrong code gave CODE_INVALID. The right code opened the slot, and the counts show two medium slots again. The same code a second time gave CODE_USED.
To explore, change the scripted number to 7 and the text will say 000007, or ask for two large parcels on this site: the first gets ST1-L1 and the second is refused with NO_SLOT. Both runs use only the driver, with no real clock or phone. The next lesson writes the classes behind this output.
Why is the slot reserved before the courier opens the door?
- The slot is claimed first, so two couriers cannot be sent to the same slot.
Why is the code created at confirmDrop and not at reserve?
- A courier may walk away without leaving the parcel.
Part 5 · Code: slots, codes and pickup
The smallest free slot
The simplest allocator scans every slot and takes the first that fits. Its cost grows with the site and is paid again on every parcel. We keep an index instead: for each size, a set of the slot ids that are free right now.
constructor(id: string, layout: Layout) {
this.id = id;
for (const size of SIZES) {
for (let n = 1; n <= layout[size]; n++) {
const tag = size[0].toUpperCase();
const slot = new Slot(`${id}-${tag}${n}`, size);
this.#slots.set(slot.id, slot);
this.#free[size].add(slot.id);
}
}
}The constructor builds ids such as ST1-M1 and fills the index. A Set iterates in insertion order, so values().next() returns the free slot that was added earliest. The language defines that order. If ST1-M1 is taken and later freed, it goes behind ST1-M2, and the next parcel gets the slot that has been free longest.
// The smallest free slot a parcel of this size fits, or undefined. peek(size: Size): string | undefined { for (const fit of FITS[size]) { const first = this.#free[fit].values().next(); if (!first.done) return first.value; } return undefined; }
The cost of a lookup is now the number of sizes, which is three, and not the number of slots. peek walks the sizes the parcel may use, smallest first, and returns the first free slot. It only looks. It never changes anything.
// The only way a slot changes state, so the index never drifts. apply(slotId: string, event: SlotEvent): void { const slot = this.#slots.get(slotId); if (!slot) throw new LockerError('UNKNOWN_SLOT', slotId); slot.apply(event); const free = this.#free[slot.size]; if (slot.state === 'free') free.add(slotId); else free.delete(slotId); }
apply is the only way a slot changes state, so the index cannot drift from the truth. If the slot refuses the event, it throws before the index is touched.
Allocation tests
Allocation is where edge cases live, so it gets many small tests. Each builds a tiny site, because three slots are easier to reason about than three hundred. The helper setup makes a site from one count per size, a fake clock, a fake notifier and a scripted random source.
test('a small parcel takes the smallest slot first', () => { const { lockers } = setup({ small: 1, medium: 1, large: 1 }); const slot = lockers.reserve('P-1', 'small', 'delivery', '0100'); assert.equal(slot, 'ST1-S1'); }); test('a small parcel spills upward when small is full', () => { const { lockers } = setup({ small: 1, medium: 1, large: 1 }); lockers.reserve('P-1', 'small', 'delivery', '0100'); const slot = lockers.reserve('P-2', 'small', 'delivery', '0100'); assert.equal(slot, 'ST1-M1'); });
Two more show a refused parcel and a reserved slot that is not offered twice.
test('a large parcel is refused when only small slots are free', () => { const { lockers, site } = setup({ small: 2, medium: 0, large: 0 }); const fn = () => lockers.reserve('P-1', 'large', 'delivery', '0100'); assert.throws(fn, { code: 'NO_SLOT' }); assert.deepEqual(site.counts(), { small: 2, medium: 0, large: 0 }); }); test('a reserved slot is not offered twice', () => { const { lockers } = setup({ small: 0, medium: 1, large: 0 }); lockers.reserve('P-1', 'medium', 'delivery', '0100'); assert.equal(lockers.peek('medium'), undefined); });
The remaining tests cover a cancelled drop, a deposit without a reservation and the queue order of a freed slot.
✔ a small parcel takes the smallest slot first (0.9932ms) ✔ a small parcel spills upward when small is full (0.146ms) ✔ a large parcel is refused when only small slots are free (0.9851ms) ✔ a reserved slot is not offered twice (0.1439ms) ✔ cancelling a drop frees the slot again (0.1898ms) ✔ a slot cannot be deposited into before it is reserved (0.1327ms) ✔ a freed slot goes to the back of the line (0.1243ms) ℹ tests 7 ℹ pass 7 ℹ fail 0
Output (durations vary)
Seven pass. The refusal test also checks that the counts are the same afterwards. A refused parcel must change nothing, and the test says so out loud.
Codes: random, padded and unique
A code needs to be six digits, not already in use, and drawn from a source the test can control. The service asks the injected Random for a number from 0 up to, but not including, 10,00,000. The Node 24 documentation for crypto.randomInt(min, max) says min is included and defaults to 0, max is excluded, both must be safe integers and the range must be below 2 to the power 48. It also says the function avoids modulo bias, so every code is equally likely, and that without a callback it returns synchronously. We confirmed the range rules with a run.
const seen = new Set<number>(); for (let i = 0; i < 3000; i++) seen.add(randomInt(0, 3)); console.log('randomInt(0, 3) gave', [...seen].sort()); console.log('randomInt(5, 6) gave', randomInt(5, 6)); try { randomInt(5, 5); } catch (e) { console.log('randomInt(5, 5):', (e as { code: string }).code); } try { randomInt(0, 1.5); } catch (e) { console.log('randomInt(0, 1.5):', (e as { code: string }).code); } console.log(String(4821).padStart(6, '0'), String(0).padStart(6, '0'));
randomInt(0, 3) gave [ 0, 1, 2 ] randomInt(5, 6) gave 5 randomInt(5, 5): ERR_OUT_OF_RANGE randomInt(0, 1.5): ERR_INVALID_ARG_TYPE 004821 000000
Output (one real run)
Over 3,000 draws of randomInt(0, 3), only 0, 1 and 2 ever appeared, so the upper bound is exclusive. randomInt(5, 6) can only return 5. A range with no room throws ERR_OUT_OF_RANGE, and a fractional bound throws ERR_INVALID_ARG_TYPE. Codes under 1,00,000 need leading zeros, which padStart adds.
confirmDrop(id: string): string {
const p = this.#parcel(id);
const { site, clock, notifier } = this.#d;
site.apply(p.slotId, 'deposit');
p.code = this.#newCode();
p.expiresAt = clock.now() + (this.#d.windowMs ?? WINDOW_MS);
this.#byCode.set(p.code, id);
notifier.send(p.phone, `Parcel ${id}: code ${p.code}`);
return p.code;
}
#newCode(): string {
for (let tries = 0; tries < 100; tries++) {
const n = this.#d.random.int(0, 1_000_000);
const code = String(n).padStart(6, '0');
const taken = this.#byCode.has(code) || this.#spent.has(code);
if (!taken) return code;
}
throw new Error('could not find an unused code');
}The chance that a fresh draw clashes with a code in use is the number of such codes divided by 10,00,000, so with 100 live codes it is about one in 10,000. A retry loop handles it cheaply, and the test forces a clash with the numbers 7, 7, 8 to prove it.
Picking up, once
A pickup has three checks, and the order matters.
pickup(code: string): string {
if (this.#spent.has(code)) {
throw new LockerError('CODE_USED', 'that code was already used');
}
const id = this.#byCode.get(code);
if (id === undefined) {
throw new LockerError('CODE_INVALID', 'no parcel for that code');
}
const p = this.#parcel(id);
if (this.#d.clock.now() >= (p.expiresAt as number)) {
throw new LockerError('CODE_EXPIRED', 'the window is over');
}
this.#d.site.apply(p.slotId, 'pickup');
this.#byCode.delete(code);
this.#spent.add(code);
this.#parcels.delete(id);
return id;
}A spent code gives CODE_USED, which tells the customer something useful. An unknown code gives CODE_INVALID. A known code past its window gives CODE_EXPIRED. Only after all three pass does the slot move to free, and the code moves from the live map to the spent set.
One cost is worth naming. The spent set only grows. A long-running service would trim it, for example by forgetting codes spent more than a few windows ago, and accept that a forgotten code can be issued again to a later parcel. Someone who retypes a code that old could then open a stranger's slot, so the period before forgetting should be long. The order of the checks is also a choice. Checking spent codes first lets us say "already used" instead of "unknown", which helps a customer who typed the right code twice.
The time test is >=, so a parcel is collectable until expiresAt and not at it. The tests sit on that boundary: a code works one minute before the window ends and fails exactly when it ends.
✔ codes are padded to six digits (0.9879ms) ✔ a clash with a live code draws again (0.1552ms) ✔ a wrong code opens nothing and changes nothing (0.6107ms) ✔ a code works once (0.2226ms) ✔ a code still works one minute before the window ends (0.1452ms) ✔ a late code is refused and the slot stays occupied (0.1638ms) ℹ tests 6 ℹ pass 6 ℹ fail 0
Output (durations vary)
The last test shows what a refusal means: after a late code is refused, the slot is still occupied.
Why is a code a string and not a number?
Part 6 · Extensions and trade-offs
Expiry and return
Some parcels are never collected. The service does not watch the clock by itself. A sweep is a method that something else calls now and then, such as a timer, and that moves every late parcel to expired.
// Marks every parcel past its window as expired; returns their ids. sweep(): string[] { const now = this.#d.clock.now(); const late: string[] = []; for (const p of this.#parcels.values()) { const over = p.expiresAt !== undefined && now >= p.expiresAt; if (over && this.#d.site.state(p.slotId) === 'occupied') { this.#d.site.apply(p.slotId, 'expire'); late.push(p.id); } } return late; }
Why a sweep and not one timer per parcel? A timer lives in memory and is lost on a restart, and thousands of them are hard to inspect. A sweep reads the stored deadlines, so it can be called every few minutes and still be right after a crash. Choose the interval by how long a late parcel may stay marked occupied, because it can wait up to one interval past its deadline. Pickups are still refused on time, since pickup checks the clock itself.
sweep marks each occupied parcel whose window has ended and returns their ids. Running it twice does nothing the second time, because only occupied slots are touched. Staff then call clear, which empties the slot and removes the dead code.
// Staff empty an expired slot and send the parcel back. clear(slotId: string): string { const all = [...this.#parcels.values()]; const p = all.find((x) => x.slotId === slotId); if (!p) throw new LockerError('UNKNOWN_SLOT', slotId); this.#d.site.apply(slotId, 'clear'); this.#byCode.delete(p.code as string); this.#parcels.delete(p.id); return p.id; }
The fake clock makes three days instant. The tests move it by exact amounts.
test('a sweep expires only the parcels past their window', () => { const { lockers, clock } = setup({ ...ONE, small: 2 }, [1, 2]); lockers.reserve('P-1', 'small', 'delivery', '0100'); lockers.confirmDrop('P-1'); clock.advanceMinutes(2 * DAY_MIN); lockers.reserve('P-2', 'small', 'delivery', '0100'); lockers.confirmDrop('P-2'); clock.advanceMinutes(DAY_MIN); assert.deepEqual(lockers.sweep(), ['P-1']); assert.deepEqual(lockers.sweep(), []); }); test('staff clear an expired slot and the parcel goes back', () => { const { lockers, clock, site } = setup(ONE, [1]); lockers.reserve('P-1', 'small', 'return', '0100'); const code = lockers.confirmDrop('P-1'); clock.advanceMinutes(WINDOW_MIN); lockers.sweep(); assert.equal(site.state('ST1-S1'), 'expired'); assert.equal(lockers.peek('small'), undefined); assert.equal(lockers.clear('ST1-S1'), 'P-1'); assert.equal(lockers.peek('small'), 'ST1-S1'); assert.throws(() => lockers.pickup(code), { code: 'CODE_INVALID' }); });
Every use case, tested
The use case lesson left six test.todo names. With the service in place, each becomes a real test that drives the whole system the way its actor would. These are acceptance tests: they check a goal from the outside, while the earlier tests check single rules inside.
const L = { small: 1, medium: 1, large: 0 }; test('a courier delivers a parcel into a free slot', () => { const { lockers, site } = setup(L, [4821]); const slot = lockers.reserve('P-1', 'medium', 'delivery', '0100'); assert.equal(slot, 'ST1-M1'); lockers.confirmDrop('P-1'); assert.equal(site.state('ST1-M1'), 'occupied'); }); test('the customer is told the code', () => { const { lockers, notifier } = setup(L, [4821]); lockers.reserve('P-1', 'medium', 'delivery', '0100'); lockers.confirmDrop('P-1'); assert.deepEqual(notifier.sent, [{ to: '0100', text: 'Parcel P-1: code 004821' }]); }); test('the customer picks up with the code', () => { const { lockers, site } = setup(L, [4821]); lockers.reserve('P-1', 'medium', 'delivery', '0100'); lockers.confirmDrop('P-1'); assert.equal(lockers.pickup('004821'), 'P-1'); assert.equal(site.state('ST1-M1'), 'free'); });
The other three tests cover the no-slot refusal, expiry and return, and a customer's drop-off.
✔ a courier delivers a parcel into a free slot (0.7819ms) ✔ the customer is told the code (0.5226ms) ✔ the customer picks up with the code (0.1362ms) ✔ a parcel is refused when no slot fits (0.333ms) ✔ an unclaimed parcel expires and is returned (0.1915ms) ✔ a customer drops off a return for the courier (0.1017ms) ℹ tests 6 ℹ pass 6 ℹ fail 0 ℹ todo 0
Output (durations vary)
Six pass and no todo is left. Each name is the sentence the use case lesson wrote, so goals and tests can be read side by side.
A lockout and the nearest site
Six digits and a patient thief are a bad mix, so we add the limit promised earlier. Three wrong codes within five minutes lock the keypad until the oldest wrong code is five minutes old. Kiosk wraps the service and offers the same pickup method, so the keypad calls the kiosk in place of the service and the service stays untouched. A wrapper with the same method that adds a behaviour is the decorator pattern. Because what this one adds is a refusal of access, some books call it a protection proxy.
// Wraps pickup: three wrong codes in five minutes lock the keypad. export class Kiosk { readonly #lockers: LockerService; readonly #clock: Clock; #misses: number[] = []; constructor(lockers: LockerService, clock: Clock) { this.#lockers = lockers; this.#clock = clock; } pickup(code: string): string { const now = this.#clock.now(); this.#misses = this.#misses.filter((t) => now - t < 5 * 60_000); if (this.#misses.length >= 3) { throw new LockerError('LOCKED_OUT', 'too many wrong codes'); } try { return this.#lockers.pickup(code); } catch (e) { const wrong = e instanceof LockerError && (e.code === 'CODE_INVALID' || e.code === 'CODE_USED'); if (wrong) this.#misses.push(now); throw e; } } }
✔ three wrong codes lock the keypad for a while (1.6811ms) ✔ the nearest site with a slot that fits is chosen (0.33ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
Output (durations vary)
The first test walks through it: three wrong codes at minutes 0, 1 and 2, a refusal even for the right code at minute 3, then success at minute 5, when the first wrong code is five minutes old and no longer counts. The second test covers the nearest-site helper. With several sites, nearestWithSpace sorts them by distance and takes the first with a slot that fits. In our tests a site with no slots is skipped, even when it is the closest.
// Sites in order of distance; the first one with a slot that fits. export function nearestWithSpace( sites: { km: number; lockers: LockerService }[], size: Size, ): LockerService | undefined { const byKm = [...sites].sort((a, b) => a.km - b.km); return byKm.find((s) => s.lockers.peek(size) !== undefined)?.lockers; }
The lockout has one limit. Each Kiosk keeps its own count, so a site with two keypads gives a thief two counters. One shared counter per site would close that gap, at the price of state that every keypad at the site must reach. Another way to guard codes would be a per-code limit, but a wrong guess has no owner, so the limit belongs to the keypad.
Where this design is weak
Every design has costs. Parcels live in a Map, so a restart loses them and a real service stores them through a repository. The sweep needs something to call it. Parcel ids come from the courier's scanner, and a repeated id would overwrite the record, which a real system would reject. Reservation is synchronous, so two couriers cannot race for one slot. If a check were split from the claim by an await, the parking lot chapter shows the race and the keyed mutex that fixes it.
| Term | Meaning |
|---|---|
| Invariant | A condition that must always hold, such as one parcel per slot |
| State machine | States, events and the moves a state refuses |
| Sweep | A method called now and then to expire what is overdue |
| Decorator | A wrapper with the same interface that adds a behaviour |
| Acceptance test | A test of a goal from the outside, through the service |
Why does Kiosk wrap the service instead of editing pickup?
- The service keeps one job, and the lockout becomes one class that can be added or removed.
After a sweep, why can a new small parcel not use the expired small slot?
- The old parcel is still inside. The slot is free only after staff clear it.
A teammate adds a second sweep call right after the first. What does it return?
- An empty list. Only occupied slots are expired, so already expired ones are skipped.
All chapters · Previous: Library Management: Catalogue, Copies, Loans, Holds and Fines