Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 22
Module 9 · Design problems VI: social, trading and puzzles · Chapter 22 of 28
Social Network: Friends, Posts, Privacy and the News Feed
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: Online Stock Brokerage: Orders, Order Book, Matching and Portfolio.
Part 1 · Requirements
What the network must do
A social network is one question asked millions of times: may this member see this? This chapter builds a small one with friends, follows, posts with audiences, a news feed and notifications.
A requirement is a sentence about the system that someone can check. Functional requirements say what the system does, and we write them before any class exists. Our members are invented: Asha, Bala, Chitra and Dev.
- A member joins with a name and gets an id.
- A friendship needs agreement. One member sends a friend request, the other accepts or declines it, and the sender can cancel while it waits.
- A follow needs no agreement and runs one way. A follower sees the followed member's public posts.
- A member can block another. A block ends the friendship and the follows in both directions, cancels a waiting request and hides each member's posts from the other.
- A post has text and an audience: public, friends or only me.
- A member can like a post once and comment on it, but only when the member may see it.
- The feed lists posts from friends and followed members, newest first, and only the ones the reader may see.
- Members get a notification for a request, an acceptance, a like and a comment.
Everything here is our model, not a description of any real service. A short prompt such as "design a social network" leaves many rules open, so we ask questions. Ask the ones whose answers change a class or a method.
| Question | If the answer is yes | Our answer |
|---|---|---|
| Is a follow the same as a friendship? | One relation with two kinds |
Quality, numbers and scope
Non-functional requirements say how well the system behaves. Three matter here. A post must never reach a member its audience excludes, and the rule lives in one function that every read goes through. A refused action must change nothing: not a request, not a like and not an inbox. And opening the feed must stay cheap. Its cost should grow with the number of authors you follow and the size of the page, not with every post anyone has ever written.
We rejected two designs. The first stores a list of allowed viewers inside each post when it is written. It looks fast, but friendships and blocks change later, so the list goes stale and a post can reach someone who was blocked since. We store only the audience and work out the answer at read time. The second keeps all posts in one list, filters it for each feed and sorts the result. It is simple, and it gets slower with every post on the network. We keep each author's posts in their own time-ordered list and merge the few we need.
Time is injected, as in the other cases: a small Clock interface lets a test choose when a post was written. Ids come from counters, so the output is the same on every run.
| Must | Should | Out of scope |
|---|---|---|
| Requests, follows, blocks, posts with audiences, feed, likes, comments, notifications | Fan-out on write, muting | Editing, deleting, ranking, photos, search |
Check yourself
Asha follows Bala, and Bala has never heard of Asha. Are they friends?
- No. A follow is one-way and needs no agreement. A friendship needs a request that the other member accepts.
- Asha sees Bala's public posts in her feed, but not his friends-only posts.
Why is the audience checked when a post is read and not when it is written?
- Friendships and blocks change after a post is written, so a list of viewers made at write time goes stale.
- Storing only the audience keeps one source of truth, and the answer is always current.
A member blocks another. Name two things that change.
- The friendship and the follows between them end, in both directions.
- A waiting request between them is cancelled, and each member's posts are hidden from the other.
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. Our network has one kind of person, the member, seen in two roles. As a member you act for yourself: you send a request, post, follow someone, read your feed and block someone. As a responding member you answer what another member did: you accept their request, or like and comment on their post.
A use case diagram shows actors, the use cases they start and how those relate. Include means a use case always runs another one as part of itself. Extend means an exceptional case adds steps to a base case under a condition. Viewing the feed always includes checking the audience of each post. A refused request extends sending, and a refused reaction extends liking and commenting.
The blue boxes are actors and the pills are use cases, with the refusals 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". Formal UML draws the extend arrow the other way, from the extension to the base; here the label carries the meaning.
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 |
|---|---|---|
| Send a request | Check the pair, record a pending request, notify the recipient | Self, blocked, already friends, one already pending: refuse |
| Accept a request | The recipient confirms, both become friends, the sender is notified | Not pending or wrong member: refuse |
| Post | Trim the text, store it with its audience and time | Empty text: refuse |
| View the feed | Gather friends and follows, merge newest first, keep visible posts | None |
| Like or comment | Check the reader may see the post, record, notify the author | Cannot see, empty comment: refuse |
| Follow | Record the one-way follow | Yourself or a blocked member: refuse |
| Block | End friendship and follows both ways, cancel waiting requests | Blocking yourself: refuse |
Every alternative is a named refusal, and each one must change nothing. A refused like leaves the like count and the author's inbox as they were, and we assert that.
Three details need a decision now, in our model. A member who was declined or cancelled may send a new request, because the old one is finished and a new request is a new fact. A request sent in one direction while the other is waiting is refused, so a pair never has two open requests. And a block cancels waiting requests, because a request between two members who cannot see each other would be a request nobody can answer.
Use cases as test names
As in the parking lot chapter, each use case becomes a test.todo name, a map of the work that is reported but not run, and each one becomes a real test by the end.
test.todo('a member sends a friend request'); test.todo('a member accepts a friend request'); test.todo('a member posts for an audience'); test.todo('a member views the feed'); test.todo('a member likes and comments on a post'); test.todo('a member blocks another member'); test.todo('a member follows another member');
✔ a member sends a friend request (0.5674ms) # TODO ✔ a member accepts a friend request (0.0794ms) # TODO ✔ a member posts for an audience (0.0558ms) # TODO ✔ a member views the feed (0.0452ms) # TODO ✔ a member likes and comments on a post (0.1039ms) # TODO ✔ a member blocks another member (0.0984ms) # TODO ✔ a member follows another member (0.0659ms) # TODO ℹ tests 7 ℹ todo 7
Output (durations vary)
All seven names are reported as todo, and none counts as passed. 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 viewing the feed always checks each post's audience.
- Extend: an exceptional case adds steps under a condition, as the refusal does when a reader cannot see a post.
A member sends a request to someone who already sent one to them. Which use case runs, and what is left afterwards?
- Send a request runs and is refused as already pending.
- The first request is still pending, and no second request exists.
Which of these is not an actor: the member, the notifier, the feed?
- The feed. It is part of the system, not someone outside it.
- The notifier is a secondary actor, because the system calls it.
Part 3 · Class diagram
From nouns to classes
Read the requirements again and underline the nouns: member, friend request, friendship, follow, block, post, audience, comment, like, feed, notification. Not every noun becomes a class. A useful test is whether the thing has rules to protect or behaviour that varies.
| Noun | Decision | Why |
|---|---|---|
| Member | Interface Member | An id and a name, nothing to protect |
| Friend request | Class FriendRequest | Owns a status that may only move from pending |
| Friendship, follow, block | Sets inside Relations | Facts about pairs of members, with no behaviour of their own |
| Post | Interface Post | A record the network creates and the store holds |
| Audience | String union Audience | Three fixed values |
| Like | A Set of member ids in the post | A set cannot hold a member twice |
| Comment | Plain value | Written once, never changed |
| Feed | The function mergeFeed | Computed on every read, never stored |
| Notification | Interface Notifier | Delivery varies, so the network asks an object |
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 exactly one, 0..* means any number, including none.
join(name): MembersendRequest(from, to)accept/decline/cancel(id, by)follow(a, b), block(by, target)post(author, text, audience)like(viewer, postId), comment(...)feed(viewer, limit): Post[]id, nameid, from, tostatus: RequestStatusapply(event)areFriends(a, b)isBlocked(a, b)friendsOf(a), followingOf(a)befriend, follow, blockid, seq, author, textaudience: Audienceat: numberlikes: Set, comments[]add(post), get(id)of(author): oldest firstnotify(to, text)notify(to, text)for(member)now(): number- SocialNetwork 1 → 0..* Member
- SocialNetwork 1 → 0..* FriendRequest
- SocialNetwork 1 → 1 Relations
The skeleton in TypeScript
A diagram is only a claim until a compiler reads it. We start with the shared types: the audience, the request status and the records.
export type Audience = 'public' | 'friends' | 'only-me'; export type RequestStatus = | 'pending' | 'accepted' | 'declined' | 'cancelled'; export interface Member { readonly id: string; readonly name: string; } export interface Comment { readonly author: string; readonly text: string; readonly at: number; } export interface Post { readonly id: string; readonly seq: number; readonly author: string; readonly text: string; readonly audience: Audience; readonly at: number; readonly likes: Set<string>; readonly comments: Comment[]; }
The Notifier interface follows in the same file, and Clock has a file of its own. Every refusal will be a SocialError with a code, so callers and tests branch on the code and never on the message.
export type SocialCode = | 'UNKNOWN_MEMBER' | 'UNKNOWN_POST' | 'UNKNOWN_REQUEST' | 'SELF_ACTION' | 'ALREADY_FRIENDS' | 'ALREADY_PENDING' | 'BLOCKED' | 'NOT_PENDING' | 'NOT_YOURS' | 'CANNOT_SEE' | 'EMPTY_TEXT'; export class SocialError extends Error { readonly code: SocialCode; constructor(code: SocialCode, message: string) { super(message); this.name = 'SocialError'; this.code = code; } }
Type-check the project:
npx tsc -p .
(no output, exit code 0)Output
The skeleton compiles. Notice the types that are missing: there is no Friendship and no Feed, because the table above chose to build them from sets and a function.
Why is the feed a function and not a class that holds posts?
- A feed is computed from posts and relations, so it is always current.
- A stored feed is a copy that must change whenever a friendship or a block changes.
Why are friendship, follow and block sets inside Relations and not classes?
- Each is a fact about a pair of members and has no behaviour or state of its own.
Part 4 · Request lifecycle and the post sequence
Four request states
A state machine lists the states, the events that cause moves and the events a state refuses. A friend request has four states. pending is the only one that can move. accepted, declined and cancelled are final: nothing leaves them.
Watch for a cancelled request refusing a late accept
Read it as steps
Only a pending request can move. Once it is cancelled, a late accept is refused.
The scene shows a request that Asha cancels just before Bala taps accept. The accept arrives late and is refused with NOT_PENDING, and no friendship is made. Writing the whole picture as a table shows the gaps early.
| Status | accept | decline | cancel |
|---|---|---|---|
| pending | to accepted | to declined | to cancelled |
From post to feed
Now follow two posts, the same posts the driver in the next lesson writes. Asha has already posted P1 for everyone. She now posts P2 for friends and P3 for only herself. Later Bala opens his feed and likes P2. Notice when the audience is asked, because a post is stored without anyone checking who may see it.
Watch for the audience being checked only when Bala reads
Read it as steps
The audience is checked when Bala reads, and the like reaches Asha as a notification.
The network stores both posts and asks nothing, because nobody is reading yet. The question comes when Bala reads: the network asks Relations whether Bala may see each post. The answer is no for the only-me post and yes for the other two: one is public, and Bala is a friend of Asha. A like asks the same question first, through one private method, #view.
// Every read and every reaction goes through here. #view(viewer: string, postId: string): Post { this.#member(viewer); const p = this.#posts.get(postId); if (!p) throw new SocialError('UNKNOWN_POST', postId); if (!canSee(this.#rel, viewer, p)) { const why = `${viewer} cannot see ${postId}`; throw new SocialError('CANNOT_SEE', why); } return p; }
The method refuses before it returns the post, so a caller cannot like or comment on something it cannot see, and the refusal happens before any change. The like and comment methods call it first and mutate only afterwards.
Run the driver
The driver is the demo.ts script from the approach chapter, which runs the core flow once and prints what happened. It adds Asha, Bala, Chitra and Dev, makes Asha and Bala friends and lets Chitra follow Asha. Asha writes one post for each audience, and the driver asks who can see each.
const { net, clock, inbox, asha, bala, chitra, dev } = rig(); const names: Record<string, string> = { [asha]: 'Asha', [bala]: 'Bala', [chitra]: 'Chitra', [dev]: 'Dev', }; const req = net.sendRequest(asha, bala); console.log(`request ${req.id}: ${req.status}`); net.accept(req.id, bala); console.log(`request ${req.id}: ${req.status}`); net.follow(chitra, asha); clock.advance(1_000); const hello = net.post(asha, 'Hello everyone', 'public'); clock.advance(1_000); const trip = net.post(asha, 'Trip photos', 'friends'); clock.advance(1_000); const diary = net.post(asha, 'My diary', 'only-me'); for (const p of [hello, trip, diary]) { const seen = [bala, chitra, dev].filter((m) => net.canSee(m, p.id)); const who = seen.map((m) => names[m]).join(', ') || 'nobody else'; console.log(`${p.id} ${p.audience.padEnd(7)} seen by ${who}`); }
const readers = [['Bala', bala], ['Chitra', chitra]] as const; for (const [label, member] of readers) { const texts = net.feed(member).map((p) => `${p.id} "${p.text}"`); console.log(`${label}'s feed: ${texts.join(', ')}`); } net.like(bala, trip.id); net.comment(bala, trip.id, 'Lovely'); console.log("Asha's inbox:"); for (const text of inbox.for(asha)) console.log(` ${text}`);
request R1: pending request R1: accepted P1 public seen by Bala, Chitra, Dev P2 friends seen by Bala P3 only-me seen by nobody else Bala's feed: P2 "Trip photos", P1 "Hello everyone" Chitra's feed: P1 "Hello everyone" Asha's inbox: Bala accepted your request Bala liked your post P2 Bala commented on P2
Output
Read the output top to bottom. The request moves from pending to accepted. The public post is seen by all three, because the audience is public and nobody is blocked. The friends post is seen only by Bala. The only-me post is seen by nobody else. Bala's feed shows the friends post first and the public one second, newest first. Chitra's feed shows only the public one, because she follows Asha and is not her friend. Asha's inbox holds the three notifications the flow produced.
Which request states accept an accept event?
- Only pending. Accepted, declined and cancelled all refuse with
NOT_PENDING.
Part 5 · Code: the audience check and the feed
One question for every read
Everything that reads a post asks one function: canSee. It takes the relations, the viewer and the post, and returns a yes or no. There is no second place that decides.
// The one question every read goes through. export function canSee( rel: Relations, viewer: string, post: Post, ): boolean { if (viewer === post.author) return true; if (rel.isBlocked(viewer, post.author)) return false; switch (post.audience) { case 'public': return true; case 'friends': return rel.areFriends(viewer, post.author); case 'only-me': return false; } }
The author always sees their own post. A block in either direction comes next, before the audience is looked at, so a blocked member sees nothing, not even a public post. Then each audience has its own rule. The switch has no default, and the return type is boolean, so if a fourth audience is added later and no case handles it, the compiler refuses to build. We will use that in the last lesson.
The relations behind it are two small sets of ids. A block counts in both directions, and the code says so.
areFriends(a: string, b: string): boolean {
return this.#friends.get(a)?.has(b) ?? false;
}
// Either direction counts: a block hides both from each other.
isBlocked(a: string, b: string): boolean {
const one = this.#blocked.get(a)?.has(b) ?? false;
return one || (this.#blocked.get(b)?.has(a) ?? false);
}test('each audience shows the post to the right members', () => { const { net, asha, bala, dev } = rig(); befriend(net, asha, bala); const pub = net.post(asha, 'public', 'public'); const fr = net.post(asha, 'friends', 'friends'); const me = net.post(asha, 'private', 'only-me'); const seen = (m: string) => [pub, fr, me] .filter((p) => net.canSee(m, p.id)) .map((p) => p.audience); assert.deepEqual(seen(asha), ['public', 'friends', 'only-me']); assert.deepEqual(seen(bala), ['public', 'friends']); assert.deepEqual(seen(dev), ['public']); });
test('reactions on a post you cannot see are refused', () => { const { net, asha, dev, inbox } = rig(); const p = net.post(asha, 'friends only', 'friends'); assert.throws(() => net.like(dev, p.id), { code: 'CANNOT_SEE' }); const talk = () => net.comment(dev, p.id, 'hi'); assert.throws(talk, { code: 'CANNOT_SEE' }); assert.equal(p.likes.size, 0); assert.equal(p.comments.length, 0); assert.deepEqual(inbox.for(asha), []); });
A refusal that changes nothing
Merging with a heap
A feed combines the posts of every friend and followed member, newest first, and stops after a page. Each author's posts are already in time order, because they are added as they happen. Merging several sorted lists is called a k-way merge. It needs only the newest unread post of each list, so we keep one cursor per author and a heap over the cursors. A heap is a tree stored in an array that always has the next item to come out at its first position, and a push or a pop takes time proportional to the logarithm of its size.
export class Heap<T> { readonly #items: T[] = []; readonly #first: (a: T, b: T) => boolean; // first(a, b) is true when a must come out before b. constructor(first: (a: T, b: T) => boolean) { this.#first = first; } get size(): number { return this.#items.length; } push(x: T): void { const h = this.#items; h.push(x); let i = h.length - 1; while (i > 0) { const p = (i - 1) >> 1; if (!this.#first(h[i]!, h[p]!)) break; [h[i], h[p]] = [h[p]!, h[i]!]; i = p; } }
pop(): T | undefined { const h = this.#items; const top = h[0]; const last = h.pop(); if (h.length > 0 && last !== undefined) { h[0] = last; this.#siftDown(); } return top; }
Pop: the last item moves to the top and sinks
The private #siftDown mirrors the loop in push: it moves the new top item down, swapping it with the first of its two children until neither comes before it. Walk through the merge once with real data. Bala has posts at 1010 and 1040, Chitra one at 1030 and Dev two, at 1020 and 1050. Asha is a friend of Bala and Chitra and follows Dev, and asks for a page of four.
Watch for the heap holding one cursor for each author
Read it as steps
Tests for the feed
The merge itself is a few lines. It pushes one cursor for each author, pops the newest, keeps the post when visible says yes and pushes the author's next older post.
// Each list is oldest first. Walk all of them from the end. export function mergeFeed( lists: readonly (readonly Post[])[], visible: (p: Post) => boolean, limit: number, stats = new FeedStats(), ): Post[] { const heap = new Heap<Cursor>(newer); for (const list of lists) { if (list.length === 0) continue; heap.push({ list, index: list.length - 1 }); stats.pushes++; } const out: Post[] = []; while (out.length < limit && heap.size > 0) { const c = heap.pop()!; stats.pops++; if (visible(at(c))) out.push(at(c)); if (c.index > 0) { heap.push({ list: c.list, index: c.index - 1 }); stats.pushes++; } } return out; }
The run for the example above prints the page and the counters. With three authors and five posts in play, four posts came out after five pushes and four pops.
const page = net.feed(asha, 4, stats); console.log(page.map((p) => `${p.text}@${p.at}`).join(' ')); console.log(`heap pushes ${stats.pushes}, pops ${stats.pops}`);
d2@1050 b2@1040 c1@1030 d1@1020 heap pushes 5, pops 4
Output
Posts written at the same instant need a tie-breaker, or two runs could order them differently. Each post carries seq, a counter, and the comparison uses it when the times are equal. The tests check the order, the audience filter, a block and the early stop.
test('posts at the same instant keep their posting order', () => { const { net, asha, bala } = rig(); net.accept(net.sendRequest(asha, bala).id, bala); net.post(bala, 'first', 'public'); net.post(bala, 'second', 'public'); const texts = net.feed(asha).map((p) => p.text); assert.deepEqual(texts, ['second', 'first']); });
test('the limit stops the merge early', () => { const { net, clock, asha, bala } = rig(); net.accept(net.sendRequest(asha, bala).id, bala); for (let i = 0; i < 50; i++) { clock.advance(1); net.post(bala, `p${i}`, 'public'); } const stats = new FeedStats(); const page = net.feed(asha, 3, stats); assert.deepEqual(page.map((p) => p.text), ['p49', 'p48', 'p47']); assert.equal(stats.pops, 3); });
The limit stops the merge early
✔ the heap hands out the largest first (1.3607ms) ✔ the feed merges friends and follows, newest first (0.6777ms) ✔ posts at the same instant keep their posting order (0.154ms) ✔ the feed skips what the viewer may not see (0.2223ms) ✔ a blocked member leaves the feed at once (0.2659ms) ✔ the limit stops the merge early (0.2062ms) ℹ tests 6 ℹ pass 6 ℹ fail 0
Output (durations vary)
Part 6 · Extensions and trade-offs
Every use case, tested
The use case lesson left seven test.todo names. With the network in place, each becomes a real test that drives the use case the way its actor would. These are acceptance tests: they check a goal from the outside, while the earlier tests check single rules.
test('a member sends a friend request', () => { const { net, inbox, asha, bala } = rig(); const r = net.sendRequest(asha, bala); assert.equal(r.status, 'pending'); assert.deepEqual(inbox.for(bala), ['Asha sent you a friend request']); }); test('a member accepts a friend request', () => { const { net, inbox, asha, bala } = rig(); net.accept(net.sendRequest(asha, bala).id, bala); assert.equal(net.relations.areFriends(asha, bala), true); assert.deepEqual(inbox.for(asha), ['Bala accepted your request']); });
test('a member likes and comments on a post', () => { const { net, inbox, asha, bala } = rig(); net.accept(net.sendRequest(asha, bala).id, bala); const p = net.post(asha, 'Trip', 'friends'); net.like(bala, p.id); net.comment(bala, p.id, 'Lovely'); assert.equal(p.likes.size, 1); assert.equal(p.comments[0]!.text, 'Lovely'); assert.equal(inbox.for(asha).length, 3); }); test('a member blocks another member', () => { const { net, asha, bala } = rig(); const r = net.sendRequest(asha, bala); net.block(bala, asha); assert.equal(r.status, 'cancelled'); assert.throws(() => net.sendRequest(asha, bala), { code: 'BLOCKED' }); }); test('a member follows another member', () => { const { net, asha, dev } = rig(); net.follow(dev, asha); assert.deepEqual(net.relations.followingOf(dev), [asha]); assert.equal(net.relations.areFriends(dev, asha), false); assert.throws(() => net.follow(dev, dev), { code: 'SELF_ACTION' }); });
Three of the seven
✔ a member sends a friend request (1.0227ms) ✔ a member accepts a friend request (0.1636ms) ✔ a member posts for an audience (0.4487ms) ✔ a member views the feed (0.295ms) ✔ a member likes and comments on a post (0.1723ms) ✔ a member blocks another member (0.1841ms) ✔ a member follows another member (0.1317ms) ℹ tests 7 ℹ pass 7 ℹ fail 0 ℹ todo 0
Output (durations vary)
Seven pass and no todo is left. The whole suite, including every earlier test, also passes.
ℹ tests 24 ℹ pass 24 ℹ fail 0 ℹ todo 0
Output: whole suite
Fan-out on write and on read
Our feed merges at read time. This is called fan-out on read: nothing is copied when a post is written, and each read does the work. The opposite is fan-out on write: when a post is written, a copy goes into the inbox of each reader, and a read just takes the newest entries. The rest of this lesson lives in a copy of the project with new files added. The only change to an old file is a reverse index in Relations, so a post can find its followers.
publish(author: string, text: string, audience: Audience): Post {
const p = this.#net.post(author, text, audience);
for (const r of this.#readers(author, audience)) {
const list = this.#inbox.get(r) ?? [];
list.push(p);
this.#inbox.set(r, list);
this.writes++;
}
return p;
}
#readers(author: string, audience: Audience): string[] {
const rel = this.#net.relations;
if (audience === 'only-me') return [];
const friends = rel.friendsOf(author);
if (audience === 'friends') return friends;
return [...new Set([...friends, ...rel.followersOf(author)])];
}// The copy is only a hint: privacy is asked again at read time. feed(viewer: string, limit = 10): Post[] { const rel = this.#net.relations; const list = this.#inbox.get(viewer) ?? []; const out: Post[] = []; for (let i = list.length - 1; i >= 0 && out.length < limit; i--) { this.reads++; const p = list[i]!; if (!this.#recheck || canSee(rel, viewer, p)) out.push(p); } return out; }
The publish method asks the base network to store the post, then copies it to each reader: friends for a friends-only post, friends and followers for a public one, and nobody for an only-me post. The stored copy is only a hint. The feed method asks canSee again before it shows an entry, because a copy made at post time can be stale. The tests show why: a post copied to a friend and then a block, and the copy would still be shown if the second check were off.
test('a copied post is checked again, so a block takes effect', () => { const { net, a, b } = make(); const wf = new WriteFeed(net); wf.publish(a, 'for friends', 'friends'); net.block(a, b); assert.equal(wf.feed(b).length, 0); }); test('without the second check a copy would leak', () => { const { net, a, b } = make(); const leaky = new WriteFeed(net, false); leaky.publish(a, 'for friends', 'friends'); net.block(a, b); assert.equal(leaky.feed(b).length, 1); });
Now count. We measure operations on lists, not seconds: one unit for each push or pop in the merge and for each entry read from an inbox, and one for each inbox write. The counts come from running the code, and are the same on every run.
Muting
A mute hides a member from your feed and keeps the friendship. It touches only the feed, so it is a subclass that filters the authors before the merge.
// A mute hides a member from your feed but keeps the friendship. export class MutingNetwork extends SocialNetwork { readonly #muted = new Map<string, Set<string>>(); mute(viewer: string, target: string): void { const set = this.#muted.get(viewer) ?? new Set<string>(); set.add(target); this.#muted.set(viewer, set); } override feed(viewer: string, limit = 10, stats = new FeedStats()) { const muted = this.#muted.get(viewer) ?? new Set<string>(); const rel = this.relations; const authors = new Set([ ...rel.friendsOf(viewer), ...rel.followingOf(viewer), ]); const lists = [...authors] .filter((a) => !muted.has(a)) .map((a) => this.store.of(a)); const visible = (p: Post) => canSee(rel, viewer, p); return mergeFeed(lists, visible, limit, stats); } }
The test mutes a friend, sees the feed empty and checks that they are still friends.
test('a muted friend leaves the feed but stays a friend', () => { const net = new MutingNetwork(new FakeClock(0), new Inbox()); const a = net.join('Asha').id; const b = net.join('Bala').id; net.accept(net.sendRequest(a, b).id, b); net.post(b, 'noise', 'friends'); assert.equal(net.feed(a).length, 1); net.mute(a, b); assert.equal(net.feed(a).length, 0); assert.equal(net.relations.areFriends(a, b), true); });
Groups and weak spots
A new audience, group, would touch more. Here is the compiler's checklist. In a copy of the base project, add the word 'group' to the Audience union and type-check it.
npx tsc -p .
audience.ts(10,4): error TS2366: Function lacks ending return statement and return type does not include 'undefined'.
Output: after adding 'group' (wrapped for the page)
The error points to canSee, the one function that every read uses. It no longer covers every audience, so the build fails until a rule for groups exists. That is the benefit of the single check: the compiler names the one place to change. The rule itself needs a table of group members, which is a new set in Relations.
Every design has costs. A post cannot be edited or deleted, so no copy ever goes stale about its text. The feed returns only a first page, so a real one would need a cursor to ask for the next. Everything is in memory in one process, so a restart loses it all. Two requests that arrive at the same moment on one thread cannot interleave inside the synchronous methods here, but a version with an await in the middle would need the lock that the parking lot chapter teaches.
| Term | Meaning |
|---|---|
| Audience | Who a post is meant for: public, friends or only me |
| Fan-out on read | Merging the authors' posts when a feed is opened |
| Fan-out on write | Copying each post into readers' inboxes when it is written |
| Heap | An array-backed tree that always has the next item first |
| k-way merge | Combining k sorted lists by keeping one cursor on each |
| Acceptance test | A test that checks a whole goal from the outside |
All chapters · Previous: Restaurant Management: Tables, Orders, Kitchen Tickets and Bills