timeline.go176 lines, 5.4 KB
| 1 | // Package timeline keeps a ready-made home feed for every reader in Redis: |
| 2 | // a sorted set of post ids, written when somebody they follow posts. |
| 3 | package timeline |
| 4 | |
| 5 | import ( |
| 6 | "cmp" |
| 7 | "context" |
| 8 | "encoding/json" |
| 9 | "fmt" |
| 10 | "math" |
| 11 | "slices" |
| 12 | "strconv" |
| 13 | "time" |
| 14 | |
| 15 | "github.com/fiston-user/murmur/internal/live" |
| 16 | "github.com/jackc/pgx/v5" |
| 17 | "github.com/jackc/pgx/v5/pgxpool" |
| 18 | "github.com/redis/go-redis/v9" |
| 19 | ) |
| 20 | |
| 21 | // Max is how many posts one timeline keeps. |
| 22 | const Max = 800 |
| 23 | |
| 24 | // ttl is how long a timeline lives. After that, the next read builds a fresh one. |
| 25 | const ttl = 7 * 24 * time.Hour |
| 26 | |
| 27 | type Store struct { |
| 28 | db *pgxpool.Pool |
| 29 | rdb *redis.Client |
| 30 | big int // followers that make an account big: its posts are pulled, not pushed |
| 31 | } |
| 32 | |
| 33 | func New(db *pgxpool.Pool, rdb *redis.Client, big int) *Store { |
| 34 | return &Store{db: db, rdb: rdb, big: big} |
| 35 | } |
| 36 | |
| 37 | // key is where a reader's timeline lives in Redis. |
| 38 | func key(user int64) string { |
| 39 | return "timeline:" + strconv.FormatInt(user, 10) |
| 40 | } |
| 41 | |
| 42 | // add puts a post into a timeline that exists. A reader without one gets none. |
| 43 | var add = redis.NewScript(` |
| 44 | if redis.call('EXISTS', KEYS[1]) == 0 then |
| 45 | return 0 |
| 46 | end |
| 47 | redis.call('ZADD', KEYS[1], ARGV[1], ARGV[1]) |
| 48 | return redis.call('ZREMRANGEBYRANK', KEYS[1], 1, -ARGV[2] - 1)`) |
| 49 | |
| 50 | // Push adds a post to the timelines of the people who follow its author. |
| 51 | func (s *Store) Push(ctx context.Context, author, post int64) error { |
| 52 | // A big account gets no rows here: its posts are pulled when a feed is read. |
| 53 | rows, _ := s.db.Query(ctx, ` |
| 54 | select follower_id |
| 55 | from follows |
| 56 | where followee_id = $1 |
| 57 | and (select followers_count from users where id = $1) < $2`, author, s.big) |
| 58 | followers, err := pgx.CollectRows(rows, pgx.RowTo[int64]) |
| 59 | if err != nil || len(followers) == 0 { |
| 60 | return err |
| 61 | } |
| 62 | // Redis gets the script once. After that, the pipeline calls it by its hash. |
| 63 | if err := add.Load(ctx, s.rdb).Err(); err != nil { |
| 64 | return err |
| 65 | } |
| 66 | news := live.Event{Kind: "post", Data: fmt.Appendf(nil, `{"post_id":%d}`, post)} |
| 67 | pipe := s.rdb.Pipeline() |
| 68 | for _, id := range followers { |
| 69 | add.EvalSha(ctx, pipe, []string{key(id)}, post, Max) |
| 70 | live.Publish(ctx, pipe, id, news) |
| 71 | } |
| 72 | _, err = pipe.Exec(ctx) |
| 73 | return err |
| 74 | } |
| 75 | |
| 76 | // FanOut is the kind of job that pushes one post to its author's followers. |
| 77 | const FanOut = "fanout" |
| 78 | |
| 79 | // FanOutArgs is that job's payload. |
| 80 | type FanOutArgs struct { |
| 81 | Author int64 `json:"author"` |
| 82 | Post int64 `json:"post"` |
| 83 | } |
| 84 | |
| 85 | // RunFanOut handles a FanOut job: it pushes the post in the payload. |
| 86 | func (s *Store) RunFanOut(ctx context.Context, payload []byte) error { |
| 87 | var a FanOutArgs |
| 88 | if err := json.Unmarshal(payload, &a); err != nil { |
| 89 | return err |
| 90 | } |
| 91 | return s.Push(ctx, a.Author, a.Post) |
| 92 | } |
| 93 | |
| 94 | // Page returns up to n post ids below cursor from a reader's feed, newest first. |
| 95 | // What Redis doesn't hold is read from db. A missing timeline is built on the primary. |
| 96 | func (s *Store) Page(ctx context.Context, db *pgxpool.Pool, user, cursor int64, n int) ([]int64, error) { |
| 97 | below := redis.ZRangeArgs{ |
| 98 | Key: key(user), Start: "(" + strconv.FormatInt(cursor, 10), Stop: 0, |
| 99 | ByScore: true, Rev: true, Count: int64(n), |
| 100 | } |
| 101 | var ids []int64 |
| 102 | err := s.rdb.ZRangeArgs(ctx, below).ScanSlice(&ids) |
| 103 | if err == nil && len(ids) == 0 { // not even the marker: there's no timeline |
| 104 | if err = s.build(ctx, user); err == nil { |
| 105 | err = s.rdb.ZRangeArgs(ctx, below).ScanSlice(&ids) |
| 106 | } |
| 107 | } |
| 108 | if err != nil { |
| 109 | return nil, err |
| 110 | } |
| 111 | if len(ids) < n || ids[n-1] == 0 { // the timeline ends here: Postgres has the rest |
| 112 | return s.fromFollows(ctx, db, user, cursor, n, 0) |
| 113 | } |
| 114 | pulled, err := s.fromFollows(ctx, db, user, cursor, n, s.big) |
| 115 | if err != nil { |
| 116 | return nil, err |
| 117 | } |
| 118 | return merge(ids, pulled, n), nil |
| 119 | } |
| 120 | |
| 121 | // merge joins two lists of post ids into one, newest first, n at most. |
| 122 | // A post that is in both lists comes out once. |
| 123 | func merge(a, b []int64, n int) []int64 { |
| 124 | ids := slices.Concat(a, b) |
| 125 | slices.SortFunc(ids, func(x, y int64) int { return cmp.Compare(y, x) }) |
| 126 | ids = slices.Compact(ids) |
| 127 | return ids[:min(n, len(ids))] |
| 128 | } |
| 129 | |
| 130 | // fromFollows is the slow way to a feed, straight from Postgres: the newest posts |
| 131 | // of every followed account with at least atLeast followers, sorted together. |
| 132 | func (s *Store) fromFollows( |
| 133 | ctx context.Context, db *pgxpool.Pool, user, cursor int64, n, atLeast int, |
| 134 | ) ([]int64, error) { |
| 135 | rows, _ := db.Query(ctx, ` |
| 136 | select p.id |
| 137 | from follows f |
| 138 | join users u on u.id = f.followee_id and u.followers_count >= $4 |
| 139 | cross join lateral ( |
| 140 | select id |
| 141 | from posts |
| 142 | where user_id = f.followee_id and id < $2 |
| 143 | order by id desc |
| 144 | limit $3 |
| 145 | ) p |
| 146 | where f.follower_id = $1 |
| 147 | order by p.id desc |
| 148 | limit $3`, user, cursor, n, atLeast) |
| 149 | return pgx.CollectRows(rows, pgx.RowTo[int64]) |
| 150 | } |
| 151 | |
| 152 | // build fills a reader's timeline from Postgres. |
| 153 | func (s *Store) build(ctx context.Context, user int64) error { |
| 154 | // The marker goes in first. From here on the timeline exists, so new posts reach it. |
| 155 | zs := []redis.Z{{Score: 0, Member: 0}} |
| 156 | if err := s.rdb.ZAdd(ctx, key(user), zs...).Err(); err != nil { |
| 157 | return err |
| 158 | } |
| 159 | ids, err := s.fromFollows(ctx, s.db, user, math.MaxInt64, Max, 0) |
| 160 | if err != nil { |
| 161 | return err |
| 162 | } |
| 163 | for _, id := range ids { |
| 164 | zs = append(zs, redis.Z{Score: float64(id), Member: id}) |
| 165 | } |
| 166 | pipe := s.rdb.Pipeline() |
| 167 | pipe.ZAdd(ctx, key(user), zs...) |
| 168 | pipe.Expire(ctx, key(user), ttl) |
| 169 | _, err = pipe.Exec(ctx) |
| 170 | return err |
| 171 | } |
| 172 | |
| 173 | // Drop forgets a reader's timeline. Their next read builds it again. |
| 174 | func (s *Store) Drop(ctx context.Context, user int64) error { |
| 175 | return s.rdb.Del(ctx, key(user)).Err() |
| 176 | } |