Skip to content
quarry Artifact [624c8bd03c]
Login

Artifact [624c8bd03c]

Artifact 624c8bd03c5428a7e53984d978c15c41bfc8609241ca76cb4dbd6405241ca844:


package api

import (
	"context"
	"net/url"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"craftdesign.group/quarry/internal/index"
)

// An inbox row is "settled" when the thing it asked of the reader has
// already happened: the landing it proposed is no longer open, the arm
// it said lapsed has been set again, the request has been decided, the
// ticket it mentioned is closed. A reply is never settled by state: it
// waits until it is read. Settled is computed at read time, for unread
// rows only, from the row's subject; nothing is marked read.

// kindDisarmed is the attention kind of the event that says an arm
// lapsed.
const kindDisarmed = "landing.disarmed"

// settleTTL is how long one reader's settled answers are shared: every
// open tab redraws its badge on every event, and a burst of events must
// cost one pass.
var settleTTL = 5 * time.Second

var settleNow = time.Now

// settlePasses counts the passes that read subjects, for the test that
// shows a burst makes one.
var settlePasses atomic.Int64

type settleKey struct {
	repos *Repos
	who   string
}

type settleEntry struct {
	at      time.Time
	settled bool
}

type settleCache struct {
	mu sync.Mutex
	m  map[string]settleEntry
}

var settleCaches sync.Map // settleKey -> *settleCache

// settleSubject names what a row is about and whether state can settle
// it. ok is false for a row that is never settled by state.
func settleSubject(row inboxRow) (key string, ok bool) {
	if row.Link == "" || row.Read || repliesLike(row.Reason) || repliesLike(row.kind) {
		return "", false
	}
	u, err := url.Parse(row.Link)
	if err != nil {
		return "", false
	}
	p := u.Path
	if opsRow(row.Reason, p) {
		return "ops|" + row.ID + "|" + row.At, true
	}
	switch {
	case strings.HasPrefix(p, "/me/requests/"), strings.Contains(p, "/landing/"), strings.Contains(p, "/ticket/"):
		return row.Repo + "|" + p + "|" + row.kind, true
	}
	return "", false
}

// opsSettleAfter is how long an operations alert counts as waiting on
// someone when nothing says it cleared: by then it is history, which the
// operations page keeps.
const opsSettleAfter = 24 * time.Hour

// opsRow says a row is an operations alert: a slow render, a forge error,
// a failed service or a memory condition, all of which link into /fleet.
func opsRow(reason, path string) bool {
	switch reason {
	case "slow", "error", "ops":
		return true
	}
	return path == "/fleet" || strings.HasPrefix(path, "/fleet/")
}

// opsSettled says an operations alert no longer waits on who: it is a
// day old, or it is a memory alert and no memory condition who was told
// of is still open (the alerter clears that mark when it sends the
// clear). A row whose time cannot be read is not settled by age.
func (d Deps) opsSettled(who string, row inboxRow, fragment string) bool {
	if at, err := time.Parse(time.RFC3339, row.At); err == nil && settleNow().Sub(at) >= opsSettleAfter {
		return true
	}
	if fragment != "memory" || d.Prefs == nil {
		return false
	}
	for kind := range opsAlertKinds {
		if d.Prefs.AccountPref(who, openKey(kind)) != "" {
			return false
		}
	}
	return true
}

// unsettledTTL is how long one reader's walked count is shared while
// the raw unread total stays the same: every tab recounts its badge on
// every event. A new item or a mark-read changes the raw total and walks
// again at once; only a row becoming settled can wait this long to leave
// the badge.
var unsettledTTL = 30 * time.Second

// unsettledPages bounds the walk at the depth unreadVisible counts.
const unsettledPages = inboxMaxNotifyPages * inboxLocalScan / 200

type unsettledEntry struct {
	at   time.Time
	base int
	n    int
}

var unsettledCache sync.Map // settleKey -> unsettledEntry

// unsettledUnread is the badge: who's unread rows that are not settled,
// counted off the same list inbox.list renders, so the two agree. base is
// the raw unread total; it keys the shared answer and is the answer when
// the first page cannot be read. Counting the rows rather than
// subtracting settled ones from base matters: the raw total and the
// list's unread rows are counted by different halves and need not match.
func (d Deps) unsettledUnread(ctx context.Context, who string, base int) int {
	key := settleKey{d.Repos, who}
	now := settleNow()
	if v, ok := unsettledCache.Load(key); ok {
		if e := v.(unsettledEntry); e.base == base && now.Sub(e.at) < unsettledTTL {
			return e.n
		}
	}
	n, before := 0, ""
	for page := 0; page < unsettledPages; page++ {
		out, err := d.inboxPage(ctx, inboxListIn{Limit: 200, Before: before})
		if err != nil {
			if page == 0 {
				return base
			}
			break
		}
		for _, row := range out.Rows {
			if !row.Read && !row.Settled {
				n++
			}
		}
		if out.Next == "" {
			break
		}
		before = out.Next
	}
	unsettledCache.Store(key, unsettledEntry{at: now, base: base, n: n})
	return n
}

// repliesLike says a reason or kind is somebody talking to the reader,
// which stays until read whatever state its subject is in.
func repliesLike(k string) bool {
	noun, action, _ := strings.Cut(k, ".")
	switch noun {
	case "reply", "chat", "forum":
		return true
	}
	return action == "commented" || action == "replied"
}

// settleRows sets Settled on the unread rows whose subject has settled.
// It does nothing when no unread row names a landing, ticket or request,
// reads each landing by id, and shares its answers per reader for a few
// seconds. A repository the reader may no longer see settles nothing.
func (d Deps) settleRows(ctx context.Context, who string, rows []inboxRow) {
	keys := make([]string, len(rows))
	any := false
	for i, row := range rows {
		if k, ok := settleSubject(row); ok {
			keys[i], any = k, true
		}
	}
	if !any {
		return
	}
	ci, _ := settleCaches.LoadOrStore(settleKey{d.Repos, who}, &settleCache{m: map[string]settleEntry{}})
	c := ci.(*settleCache)
	c.mu.Lock()
	defer c.mu.Unlock()
	now := settleNow()
	for k, e := range c.m {
		if now.Sub(e.at) > settleTTL {
			delete(c.m, k)
		}
	}
	counted := false
	for i := range rows {
		if keys[i] == "" {
			continue
		}
		e, hit := c.m[keys[i]]
		if !hit {
			if !counted {
				settlePasses.Add(1)
				counted = true
			}
			e = settleEntry{at: now, settled: d.settledRow(ctx, who, rows[i])}
			c.m[keys[i]] = e
		}
		rows[i].Settled = e.settled
	}
}

func (d Deps) settledRow(ctx context.Context, who string, row inboxRow) bool {
	u, err := url.Parse(row.Link)
	if err != nil {
		return false
	}
	path := u.Path
	if opsRow(row.Reason, path) {
		return d.opsSettled(who, row, u.Fragment)
	}
	if id, ok := strings.CutPrefix(path, "/me/requests/"); ok {
		if d.SignOffs == nil || id == "" {
			return false
		}
		s, found, err := d.SignOffs.SignOffByID(id)
		if err != nil || !found || (s.Owner != who && s.Agent != who) || !d.attentionListable(ctx, AttentionEvent{Repo: s.Repo}) {
			return false
		}
		return s.State != "pending"
	}
	repo := row.Repo
	if k := strings.Index(path, "/landing/"); k >= 0 {
		if repo == "" {
			repo = repoKeyOf(path[:k])
		}
		r := d.visibleRepo(ctx, repo)
		if r == nil {
			return false
		}
		id := path[k+len("/landing/"):]
		l, found, err := r.Index.Landing(id)
		if err == nil && !found && len(id) >= 4 {
			l, found, err = r.Index.LandingByPrefix(id)
		}
		if err != nil || !found {
			return false
		}
		if l.State != "open" {
			return true
		}
		if row.kind == kindDisarmed && d.Auto != nil {
			_, armed := d.Auto.AutoAcceptOf(repo, l.ID)
			return armed
		}
		return false
	}
	if k := strings.Index(path, "/ticket/"); k >= 0 {
		if repo == "" {
			repo = repoKeyOf(path[:k])
		}
		r := d.visibleRepo(ctx, repo)
		if r == nil {
			return false
		}
		t, found, err := r.Index.TicketByPrefix(path[k+len("/ticket/"):])
		return err == nil && found && index.IsClosedStatus(ticketField(t, "status"))
	}
	return false
}

// visibleRepo is the repository when the reader may still see it, by
// the rule attentionListable applies; nil otherwise.
func (d Deps) visibleRepo(ctx context.Context, name string) *Repo {
	if name == "" || !d.attentionListable(ctx, AttentionEvent{Repo: name}) {
		return nil
	}
	r, err := d.repo(name)
	if err != nil || r.Index == nil {
		return nil
	}
	return r
}

// repoKeyOf is the repository named by the "/r/..." head of a link's
// path: the last segment, which is the key on a flat address and the
// handle on a namespaced one.
func repoKeyOf(head string) string {
	head = strings.TrimPrefix(head, "/r/")
	return head[strings.LastIndex(head, "/")+1:]
}