notify.go194 lines, 5.8 KB
| 1 | // Package notify tells people what happened to their posts. |
| 2 | package notify |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "log/slog" |
| 9 | "math" |
| 10 | "net/http" |
| 11 | "strconv" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/fiston-user/murmur/internal/live" |
| 15 | "github.com/fiston-user/murmur/internal/platform/httpx" |
| 16 | "github.com/fiston-user/murmur/internal/users" |
| 17 | "github.com/jackc/pgx/v5" |
| 18 | "github.com/jackc/pgx/v5/pgxpool" |
| 19 | "github.com/redis/go-redis/v9" |
| 20 | ) |
| 21 | |
| 22 | // Like is the kind of job that tells a post's author about a like. |
| 23 | const Like = "like" |
| 24 | |
| 25 | // LikeArgs is that job's payload. |
| 26 | type LikeArgs struct { |
| 27 | Liker int64 `json:"liker"` |
| 28 | Post int64 `json:"post"` |
| 29 | } |
| 30 | |
| 31 | type Handler struct { |
| 32 | db *pgxpool.Pool |
| 33 | rdb *redis.Client |
| 34 | } |
| 35 | |
| 36 | func New(db *pgxpool.Pool, rdb *redis.Client) *Handler { |
| 37 | return &Handler{db: db, rdb: rdb} |
| 38 | } |
| 39 | |
| 40 | // RunLike handles a Like job: it writes a notification for the post's author. |
| 41 | // Running it twice writes one, and liking your own post writes none. |
| 42 | func (h *Handler) RunLike(ctx context.Context, payload []byte) error { |
| 43 | var a LikeArgs |
| 44 | if err := json.Unmarshal(payload, &a); err != nil { |
| 45 | return err |
| 46 | } |
| 47 | var id, author int64 |
| 48 | var actor string |
| 49 | err := h.db.QueryRow(ctx, ` |
| 50 | with told as ( |
| 51 | insert into notifications (user_id, kind, actor_id, post_id) |
| 52 | select p.user_id, 'like', $1, p.id |
| 53 | from posts p |
| 54 | where p.id = $2 and p.user_id <> $1 |
| 55 | on conflict do nothing |
| 56 | returning id, user_id |
| 57 | ) |
| 58 | select told.id, told.user_id, a.handle from told join users a on a.id = $1`, |
| 59 | a.Liker, a.Post).Scan(&id, &author, &actor) |
| 60 | if errors.Is(err, pgx.ErrNoRows) { |
| 61 | return nil // nobody to tell: it's their own post, or they have been told already |
| 62 | } |
| 63 | if err != nil { |
| 64 | return err |
| 65 | } |
| 66 | ctx, cancel := context.WithTimeout(ctx, 250*time.Millisecond) |
| 67 | defer cancel() |
| 68 | if err := live.Publish(ctx, h.rdb, author, event(id, Like, actor, a.Post)); err != nil { |
| 69 | slog.Warn("a notification was not announced", "id", id, "error", err) |
| 70 | } |
| 71 | return nil |
| 72 | } |
| 73 | |
| 74 | // event is a notification, the way a stream sends it. |
| 75 | func event(id int64, kind, actor string, post int64) live.Event { |
| 76 | data, _ := json.Marshal(map[string]any{"actor": actor, "post_id": post}) |
| 77 | return live.Event{ID: id, Kind: kind, Data: data} |
| 78 | } |
| 79 | |
| 80 | // Since returns a user's notifications above an id as events, oldest first. |
| 81 | // It's what a stream sends to a client that was away. |
| 82 | func (h *Handler) Since(ctx context.Context, user, after int64) ([]live.Event, error) { |
| 83 | rows, _ := h.db.Query(ctx, ` |
| 84 | select n.id, n.kind, a.handle, n.post_id |
| 85 | from notifications n |
| 86 | join users a on a.id = n.actor_id |
| 87 | where n.user_id = $1 and n.id > $2 |
| 88 | order by n.id`, user, after) |
| 89 | return pgx.CollectRows(rows, func(row pgx.CollectableRow) (live.Event, error) { |
| 90 | var id, post int64 |
| 91 | var kind, actor string |
| 92 | err := row.Scan(&id, &kind, &actor, &post) |
| 93 | return event(id, kind, actor, post), err |
| 94 | }) |
| 95 | } |
| 96 | |
| 97 | // Notification is one line of a user's list. |
| 98 | type Notification struct { |
| 99 | ID int64 `json:"id"` |
| 100 | Kind string `json:"kind"` |
| 101 | Actor string `json:"actor"` |
| 102 | PostID int64 `json:"post_id"` |
| 103 | CreatedAt time.Time `json:"created_at"` |
| 104 | Unread bool `json:"unread"` |
| 105 | Body string `json:"body"` // of the post |
| 106 | } |
| 107 | |
| 108 | // Page is one page of notifications. NextCursor is null on the last page. |
| 109 | type Page struct { |
| 110 | NextCursor *int64 `json:"next_cursor"` |
| 111 | Notifications []Notification `json:"notifications"` |
| 112 | } |
| 113 | |
| 114 | // List returns a page of the caller's notifications, newest first. |
| 115 | func (h *Handler) List(w http.ResponseWriter, r *http.Request) { |
| 116 | q := r.URL.Query() |
| 117 | limit, _ := strconv.Atoi(q.Get("limit")) |
| 118 | if limit < 1 { |
| 119 | limit = 20 |
| 120 | } |
| 121 | limit = min(limit, 100) |
| 122 | cursor := int64(math.MaxInt64) |
| 123 | if s := q.Get("cursor"); s != "" { |
| 124 | id, err := strconv.ParseInt(s, 10, 64) |
| 125 | if err != nil || id < 1 { |
| 126 | httpx.Error(w, http.StatusBadRequest, "cursor must be a notification id") |
| 127 | return |
| 128 | } |
| 129 | cursor = id |
| 130 | } |
| 131 | rows, _ := h.db.Query(r.Context(), ` |
| 132 | select n.id, n.kind, a.handle, n.post_id, n.created_at, n.id > u.seen_notification, |
| 133 | p.body |
| 134 | from notifications n |
| 135 | join users a on a.id = n.actor_id |
| 136 | join users u on u.id = n.user_id |
| 137 | join posts p on p.id = n.post_id |
| 138 | where n.user_id = $1 and n.id < $2 |
| 139 | order by n.id desc |
| 140 | limit $3`, users.ID(r.Context()), cursor, limit+1) |
| 141 | list, err := pgx.CollectRows(rows, pgx.RowToStructByPos[Notification]) |
| 142 | if err != nil { |
| 143 | httpx.ServerError(w, r, err) |
| 144 | return |
| 145 | } |
| 146 | page := Page{Notifications: list} |
| 147 | if len(list) > limit { |
| 148 | page.Notifications = list[:limit] |
| 149 | page.NextCursor = &list[limit-1].ID |
| 150 | } |
| 151 | httpx.JSON(w, http.StatusOK, page) |
| 152 | } |
| 153 | |
| 154 | // MaxUnread is where the unread count stops counting. A client shows it as "99+". |
| 155 | const MaxUnread = 100 |
| 156 | |
| 157 | // Unread returns how many notifications the caller hasn't seen, up to MaxUnread. |
| 158 | func (h *Handler) Unread(w http.ResponseWriter, r *http.Request) { |
| 159 | var n int |
| 160 | err := h.db.QueryRow(r.Context(), ` |
| 161 | select count(*) from ( |
| 162 | select 1 |
| 163 | from notifications |
| 164 | where user_id = $1 and id > (select seen_notification from users where id = $1) |
| 165 | limit $2 |
| 166 | ) unseen`, users.ID(r.Context()), MaxUnread).Scan(&n) |
| 167 | if err != nil { |
| 168 | httpx.ServerError(w, r, err) |
| 169 | return |
| 170 | } |
| 171 | httpx.JSON(w, http.StatusOK, map[string]int{"unread": n}) |
| 172 | } |
| 173 | |
| 174 | // Read marks the caller's notifications as seen, up to the id in the body. |
| 175 | func (h *Handler) Read(w http.ResponseWriter, r *http.Request) { |
| 176 | var in struct { |
| 177 | UpTo int64 `json:"up_to"` |
| 178 | } |
| 179 | if err := httpx.Decode(w, r, &in); err != nil || in.UpTo < 1 { |
| 180 | httpx.Error(w, http.StatusBadRequest, "up_to must be a notification id") |
| 181 | return |
| 182 | } |
| 183 | // The marker lands on a notification of their own, and it never moves back. |
| 184 | _, err := h.db.Exec(r.Context(), ` |
| 185 | update users |
| 186 | set seen_notification = greatest(seen_notification, ( |
| 187 | select coalesce(max(id), 0) from notifications where user_id = $1 and id <= $2)) |
| 188 | where id = $1`, users.ID(r.Context()), in.UpTo) |
| 189 | if err != nil { |
| 190 | httpx.ServerError(w, r, err) |
| 191 | return |
| 192 | } |
| 193 | w.WriteHeader(http.StatusNoContent) |
| 194 | } |