Skip to content
quarry Artifact [e4dbcb727a]
Login

Artifact [e4dbcb727a]

Artifact e4dbcb727a7e50aa433b558cf28eaec4a7463253d12b1710083302a2082aa9d5:


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
	switch {
	case strings.HasPrefix(p, "/me/requests/"), strings.Contains(p, "/landing/"), strings.Contains(p, "/ticket/"):
		return row.Repo + "|" + p + "|" + row.kind, true
	}
	return "", false
}

// 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 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:]
}