Pub-Sub Message Broker
Topics, subscribers, per-consumer queues, FIFO polling — a miniature Kafka that doubles as the Observer pattern's stress test.
Requirements
- Delivery model: fan-out on publish — publishing copies the message reference into each subscriber's personal FIFO queue.
- A subscriber's queue merges all their topics in arrival order.
- Unsubscribing stops future deliveries only; queued messages survive.
- No subscribers → the message is dropped (return 0), not stored.
API to implement
Implement the class Broker. The I/O driver is already written in the starter code — it parses the command script below and calls your methods. You only implement the class.
| Command | Returns | Behavior |
|---|---|---|
| subscribe <topic> <subscriberId> | — | Subscribe subscriberId to topic. Subscribing twice is a no-op. Subscribers only receive messages published after they subscribe. |
| unsubscribe <topic> <subscriberId> | — | Remove the subscription (no-op if absent). Messages already queued for the subscriber remain pollable. |
| publish <topic> <message> | int | Deliver message to the queue of every current subscriber of topic; return how many subscribers received it (0 for unknown topics). |
| poll <subscriberId> | string | Pop and return the oldest undelivered message across all of the subscriber's topics (FIFO by arrival), or - if their queue is empty or the id is unknown. |
Input format
The first line contains Q, the number of operations. Each of the next Q lines is one command as listed above. String arguments contain no spaces.
Output format
For each command with a non-void return, print its result on its own line, in order. The driver does this for you — your methods just return values.
This is a design problem: the hidden tests exercise edge cases and interaction sequences, not performance tricks. Model the state cleanly and the tests will pass.
Sample cases
14
subscribe news s1
subscribe news s2
publish news m1
subscribe news s3
publish news m2
poll s1
poll s1
poll s3
poll s3
unsubscribe news s2
publish news m3
poll s2
poll s2
poll s22
3
m1
m2
m2
-
2
m1
m2
-6
publish ghost m
subscribe t a
subscribe t a
publish t x
poll a
poll a0
1
x
-