release / web (push) Failing after 1m29s
release / go (push) Successful in 1m55s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m22s
release / android (push) Successful in 4m57s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 4m23s
Request notifications (approved, declined, completed, pending) are removed
along with the request flow that produced them. A new_music kind takes the
"new music arrived" slot: when a scan or a watcher batch finishes, the
scanner claims every album not yet announced (albums.announced_at) and tells
every user about the ones that are new: an album with a track on disk and
no track older than itself. The first import into an empty library, and an
album formed only by retagging tracks already held, announce nothing. One
notice per scan, carrying up to 50 albums and the total; it is never
coalesced, so a notice already emailed can't quietly absorb later arrivals.
It feeds the daily summary email, grouped by artist. Defaults: inbox and
email on, phone off.
Migration 0103 deletes request-kind notification rows and prefs, swaps the
kind CHECKs to new_music, and adds albums.announced_at with every album
held marked announced, so the first scan after it announces nothing old.
Web and Android: labels, the Android "Requests" settings section becomes
"New music", the shade channel your_requests becomes new_music (the old one
is deleted at startup), and "/" opens Home in the app. TrackLabel moves to
the notifications package. docs/smart-music-{server,client}-spec.md are
deleted per the operator; an Android comment loses the word "exchanges".
Grimoire #7666, #7671.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
215 lines
6.6 KiB
Go
215 lines
6.6 KiB
Go
package notifications
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log/slog"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
|
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
|
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
|
|
)
|
|
|
|
// EventCreated is the bus event a recipient's open clients receive when a
|
|
// row lands for them. It is a nudge with no content: the client fetches the
|
|
// inbox. A frame that carried the notification could not be told apart from
|
|
// a repeat after a reconnect, and a frame nobody received is then one nobody
|
|
// needed, because the client pulls on reconnect anyway.
|
|
const EventCreated = "notification.created"
|
|
|
|
// Recipients names who an event is for.
|
|
type Recipients struct {
|
|
Users []pgtype.UUID
|
|
// Admins adds every admin.
|
|
Admins bool
|
|
// Everyone adds every user.
|
|
Everyone bool
|
|
// Except is never notified, even when it is in Users or is an admin: the
|
|
// person who caused an event needs no notice of it.
|
|
Except pgtype.UUID
|
|
}
|
|
|
|
// ToUser addresses one user.
|
|
func ToUser(id pgtype.UUID) Recipients { return Recipients{Users: []pgtype.UUID{id}} }
|
|
|
|
// ToEveryone addresses every user.
|
|
func ToEveryone() Recipients { return Recipients{Everyone: true} }
|
|
|
|
// ToAdmins addresses every admin except one (pass the zero UUID for none).
|
|
func ToAdmins(except pgtype.UUID) Recipients { return Recipients{Admins: true, Except: except} }
|
|
|
|
// Notifier writes notifications and nudges recipients' clients. A nil
|
|
// *Notifier is valid and does nothing, so producers built without one (most
|
|
// tests) need no special case.
|
|
type Notifier struct {
|
|
db dbq.DBTX
|
|
bus *eventbus.Bus
|
|
logger *slog.Logger
|
|
}
|
|
|
|
// New returns a Notifier writing through db. bus may be nil.
|
|
func New(db dbq.DBTX, bus *eventbus.Bus, logger *slog.Logger) *Notifier {
|
|
if logger == nil {
|
|
logger = slog.Default()
|
|
}
|
|
return &Notifier{db: db, bus: bus, logger: logger}
|
|
}
|
|
|
|
// Notify records kind for each recipient whose inbox preference allows it,
|
|
// then nudges their open clients.
|
|
//
|
|
// For a coalescing kind, an unread row of that kind is updated in place
|
|
// rather than a new one added: payload["count"] adds to the row's count and
|
|
// payload["items"] joins its names. The row keeps the time it arrived, so an
|
|
// update is not announced again.
|
|
//
|
|
// The error is for logging. A notification must never fail the action that
|
|
// caused it, so producers log and carry on; NotifyLogged does exactly that.
|
|
func (n *Notifier) Notify(ctx context.Context, kind Kind, to Recipients, payload map[string]any) error {
|
|
if n == nil {
|
|
return nil
|
|
}
|
|
if !kind.Valid() {
|
|
return fmt.Errorf("notifications: unknown kind %q", kind)
|
|
}
|
|
q := dbq.New(n.db)
|
|
|
|
ids, err := n.resolve(ctx, q, kind, to)
|
|
if err != nil || len(ids) == 0 {
|
|
return err
|
|
}
|
|
channels, err := channelsFor(ctx, q, kind, ids)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if payload == nil {
|
|
payload = map[string]any{}
|
|
}
|
|
body, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return fmt.Errorf("notifications: encode %s payload: %w", kind, err)
|
|
}
|
|
|
|
var delivered []pgtype.UUID
|
|
for _, id := range ids {
|
|
if !channels[id].Inbox {
|
|
continue
|
|
}
|
|
if err := write(ctx, q, kind, id, body, channels[id].Email); err != nil {
|
|
return fmt.Errorf("notifications: write %s: %w", kind, err)
|
|
}
|
|
delivered = append(delivered, id)
|
|
}
|
|
n.nudge(delivered)
|
|
return nil
|
|
}
|
|
|
|
// NotifyLogged is Notify for producers: a failure is logged at WARN and
|
|
// otherwise ignored.
|
|
func (n *Notifier) NotifyLogged(ctx context.Context, kind Kind, to Recipients, payload map[string]any) {
|
|
if err := n.Notify(ctx, kind, to, payload); err != nil {
|
|
n.logger.Warn("notifications: notify failed", "kind", string(kind), "err", err)
|
|
}
|
|
}
|
|
|
|
// resolve turns Recipients into a deduplicated list of user ids. Admin kinds
|
|
// are delivered only to admins, whatever Users says, so a producer that
|
|
// addresses a non-admin by mistake stores nothing for them.
|
|
func (n *Notifier) resolve(ctx context.Context, q *dbq.Queries, kind Kind, to Recipients) ([]pgtype.UUID, error) {
|
|
var admins []pgtype.UUID
|
|
if to.Admins || kind.AdminOnly() {
|
|
var err error
|
|
if admins, err = q.ListAdminUserIDs(ctx); err != nil {
|
|
return nil, fmt.Errorf("notifications: list admins: %w", err)
|
|
}
|
|
}
|
|
isAdmin := make(map[pgtype.UUID]bool, len(admins))
|
|
for _, a := range admins {
|
|
isAdmin[a] = true
|
|
}
|
|
|
|
var candidates []pgtype.UUID
|
|
candidates = append(candidates, to.Users...)
|
|
if to.Admins {
|
|
candidates = append(candidates, admins...)
|
|
}
|
|
if to.Everyone {
|
|
all, err := q.ListUserIDs(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("notifications: list users: %w", err)
|
|
}
|
|
candidates = append(candidates, all...)
|
|
}
|
|
|
|
seen := make(map[pgtype.UUID]bool, len(candidates))
|
|
out := make([]pgtype.UUID, 0, len(candidates))
|
|
for _, id := range candidates {
|
|
if !id.Valid || seen[id] || (to.Except.Valid && id == to.Except) {
|
|
continue
|
|
}
|
|
if kind.AdminOnly() && !isAdmin[id] {
|
|
continue
|
|
}
|
|
seen[id] = true
|
|
out = append(out, id)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// channelsFor returns each recipient's effective channels for kind: their
|
|
// stored preference, or the kind's defaults when they have none.
|
|
func channelsFor(ctx context.Context, q *dbq.Queries, kind Kind, ids []pgtype.UUID) (map[pgtype.UUID]Channels, error) {
|
|
rows, err := q.ListNotificationPrefsForKind(ctx, dbq.ListNotificationPrefsForKindParams{
|
|
Kind: string(kind),
|
|
UserIds: ids,
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("notifications: read prefs: %w", err)
|
|
}
|
|
out := make(map[pgtype.UUID]Channels, len(ids))
|
|
for _, id := range ids {
|
|
out[id] = kind.Defaults().Effective()
|
|
}
|
|
for _, r := range rows {
|
|
out[r.UserID] = Channels{Inbox: r.Inbox, Phone: r.Phone, Email: r.Email}.Effective()
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// write stores one row. emailWanted is the recipient's email channel for the
|
|
// kind: a row nobody wants emailed is stamped emailed_at at once, so the
|
|
// digest never sends it, even if email is switched on later.
|
|
func write(ctx context.Context, q *dbq.Queries, kind Kind, userID pgtype.UUID, body []byte, emailWanted bool) error {
|
|
key := kind.coalesceKey()
|
|
if key == "" {
|
|
_, err := q.InsertNotification(ctx, dbq.InsertNotificationParams{
|
|
UserID: userID, Kind: string(kind), Payload: body, EmailWanted: emailWanted,
|
|
})
|
|
return err
|
|
}
|
|
_, err := q.UpsertCoalescedNotification(ctx, dbq.UpsertCoalescedNotificationParams{
|
|
UserID: userID,
|
|
Kind: string(kind),
|
|
Payload: body,
|
|
CoalesceKey: &key,
|
|
EmailWanted: emailWanted,
|
|
})
|
|
return err
|
|
}
|
|
|
|
func (n *Notifier) nudge(ids []pgtype.UUID) {
|
|
if n.bus == nil {
|
|
return
|
|
}
|
|
for _, id := range ids {
|
|
n.bus.Publish(eventbus.Event{
|
|
Kind: EventCreated,
|
|
UserID: uuid.UUID(id.Bytes).String(),
|
|
Data: map[string]any{},
|
|
})
|
|
}
|
|
}
|