Skip to content
quarry Artifact [459b474f69]
Login

Artifact [459b474f69]

Artifact 459b474f694322834571916775942ba3b6bd9d97e5fc099104cd6d6aa5f7419d:


package api

import (
	"context"
	"sort"
	"strings"
	"sync"
	"testing"
	"time"

	"craftdesign.group/quarry/internal/chat"
	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
)

// memHighlights is the call_name and highlight_* tables in memory.
type memHighlights struct {
	mu      sync.Mutex
	names   map[string][]string
	prefs   map[string]oltp.HighlightPref
	pending map[string][]string // repo\x00account -> txns
	sent    map[string]time.Time
	modes   *memChatNotify
}

func newMemHighlights(modes *memChatNotify) *memHighlights {
	return &memHighlights{names: map[string][]string{}, prefs: map[string]oltp.HighlightPref{},
		pending: map[string][]string{}, sent: map[string]time.Time{}, modes: modes}
}

func (m *memHighlights) SetCallNames(a string, n []string) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.names[a] = n
	return nil
}
func (m *memHighlights) CallNames(a string) []string {
	m.mu.Lock()
	defer m.mu.Unlock()
	return m.names[a]
}
func (m *memHighlights) CallNameIndex() (map[string][]string, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	out := map[string][]string{}
	for a, ns := range m.names {
		for _, n := range ns {
			out[n] = append(out[n], a)
		}
	}
	return out, nil
}
func (m *memHighlights) SetHighlightPref(a string, p oltp.HighlightPref) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.prefs[a] = p
	return nil
}
func (m *memHighlights) HighlightPref(a string) oltp.HighlightPref {
	m.mu.Lock()
	defer m.mu.Unlock()
	if p, ok := m.prefs[a]; ok {
		return p
	}
	return oltp.HighlightPref{Hour: oltp.DefaultDigestHour, TZ: "UTC"}
}
func (m *memHighlights) AddHighlightPending(repo, a, txn string, _ time.Time) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.pending[repo+"\x00"+a] = append(m.pending[repo+"\x00"+a], txn)
	return nil
}
func (m *memHighlights) HasHighlightPending(repo, a string) bool {
	m.mu.Lock()
	defer m.mu.Unlock()
	return len(m.pending[repo+"\x00"+a]) > 0
}
func (m *memHighlights) TakeHighlightPending(repo, a string) ([]string, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	out := m.pending[repo+"\x00"+a]
	delete(m.pending, repo+"\x00"+a)
	return out, nil
}
func (m *memHighlights) ChatNotifyHighlights() ([]oltp.HighlightFollower, error) {
	m.modes.mu.Lock()
	defer m.modes.mu.Unlock()
	var out []oltp.HighlightFollower
	for k, mode := range m.modes.modes {
		if mode == oltp.ChatHighlights {
			repo, a, _ := strings.Cut(k, "\x00")
			out = append(out, oltp.HighlightFollower{Repo: repo, Account: a})
		}
	}
	sort.Slice(out, func(i, j int) bool { return out[i].Account < out[j].Account })
	return out, nil
}
func (m *memHighlights) HighlightDigestAt(repo, a string) time.Time {
	m.mu.Lock()
	defer m.mu.Unlock()
	return m.sent[repo+"\x00"+a]
}
func (m *memHighlights) SetHighlightDigestAt(repo, a string, at time.Time) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.sent[repo+"\x00"+a] = at
	return nil
}

// cancelNotify is a notify plane that can cancel, and says what it was
// asked to.
type cancelNotify struct {
	fakeNotify
	cmu       sync.Mutex
	cancelled []string
}

func (c *cancelNotify) Cancel(_ context.Context, txn string) error {
	c.cmu.Lock()
	defer c.cmu.Unlock()
	c.cancelled = append(c.cancelled, txn)
	return nil
}

func (c *cancelNotify) cancels() []string {
	c.cmu.Lock()
	defer c.cmu.Unlock()
	return append([]string(nil), c.cancelled...)
}

type hlRig struct {
	d     Deps
	fn    *cancelNotify
	modes *memChatNotify
	hl    *memHighlights
	seen  *memChatSMS
	fc    *fakeChat
	now   time.Time
}

func newHLRig(t *testing.T) *hlRig {
	t.Helper()
	g := &hlRig{fn: &cancelNotify{}, modes: &memChatNotify{}, seen: &memChatSMS{}, fc: &fakeChat{},
		now: time.Date(2026, 11, 25, 7, 5, 0, 0, time.UTC)}
	g.hl = newMemHighlights(g.modes)
	repos := NewRepos(map[string]*Repo{"alpha": {Chat: "alpha"}})
	g.d = Deps{Notify: g.fn, ChatNotify: g.modes, ChatSMS: g.seen, Highlights: g.hl, Chat: g.fc, Repos: repos,
		Now:     func() time.Time { return g.now },
		CapsFor: func(string, string) CapSet { return fakeCaps(anyCapLetters) }}
	return g
}

// waitEvents waits for n events to have been handed to notify.
func (g *hlRig) waitEvents(n int) []NotifyEvent {
	for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(time.Millisecond) {
		if evs := g.fn.snapshot(); len(evs) >= n {
			return evs
		}
	}
	return g.fn.snapshot()
}

func (g *hlRig) quiet() []NotifyEvent {
	time.Sleep(60 * time.Millisecond)
	return g.fn.snapshot()
}

// Names match as whole words, in any case, with or without @; a longer
// word that merely contains the name does not.
func TestCallNamesMatchWholeWords(t *testing.T) {
	index := map[string][]string{"daniel": {"dan"}, "zeitgeist": {"zg"}}
	cases := []struct {
		text string
		want []string
	}{
		{"hello Daniel, lunch?", []string{"dan"}},
		{"@daniel ping", []string{"dan"}},
		{"DANIEL", []string{"dan"}},
		{"daniel's branch", []string{"dan"}},
		{"danielle is here", nil},
		{"the zeitgeists", nil},
		{"mail [email protected]", nil},
		{"hi (daniel)", []string{"dan"}},
		{"nothing here", nil},
	}
	for _, c := range cases {
		got := callNamesIn(c.text, index)
		if strings.Join(got, ",") != strings.Join(c.want, ",") {
			t.Errorf("FAIL: callNamesIn(%q) = %v, want %v", c.text, got, c.want)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A name of several words matches as a whole phrase over any whitespace.
func TestCallNamesMatchPhrases(t *testing.T) {
	index := map[string][]string{"dan m": {"dan"}}
	for text, want := range map[string]bool{
		"thanks Dan  M!": true, "@dan m ping": true, "DAN\nM": true,
		"Dan Miller": false, "Jordan M": false, "dan": false,
	} {
		if got := len(callNamesIn(text, index)) == 1; got != want {
			t.Errorf("FAIL: %q matched = %v, want %v", text, got, want)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A name works where an @handle does: namedIn adds the accounts, and
// still honours the known filter.
func TestNamedInAddsCallNames(t *testing.T) {
	g := newHLRig(t)
	_ = g.hl.SetCallNames("dan", []string{"daniel"})
	_ = g.hl.SetCallNames("eve", []string{"evelyn"})
	known := func(h string) bool { return h != "eve" }
	got := g.d.namedIn("daniel and @gus and evelyn", known)
	sort.Strings(got)
	if strings.Join(got, ",") != "dan,gus" {
		t.Errorf("FAIL: namedIn = %v, want dan,gus", got)
	}
	// Nothing stored: only handles.
	g.d.Highlights = nil
	if got := g.d.namedIn("daniel @gus", nil); strings.Join(got, ",") != "gus" {
		t.Errorf("FAIL: without a store namedIn = %v", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A message naming a person on highlights is sent through the delayed
// workflow with a transaction id and recorded as pending; the person's
// own lines, the robot's and the upstream's announcements send nothing.
func TestHighlightSendsForAddressedMessages(t *testing.T) {
	g := newHLRig(t)
	_ = g.modes.SetChatNotify("alpha", "dan", oltp.ChatHighlights)
	_ = g.hl.SetCallNames("dan", []string{"daniel"})
	_ = g.d.ChatIdentities // none linked

	g.d.chatMentionAt("alpha", "ping Daniel about the release", "lou", 7)
	evs := g.waitEvents(1)
	if len(evs) != 1 || evs[0].Workflow != "quarry-chat-highlight" || evs[0].To != "dan" ||
		evs[0].TxnID != "highlight:alpha:7:dan" {
		t.Fatalf("FAIL: events = %+v, want one quarry-chat-highlight to dan keyed by seq", evs)
	}
	if !g.hl.HasHighlightPending("alpha", "dan") {
		t.Errorf("FAIL: the send is not recorded as pending")
	}

	for _, c := range []struct{ name, from, text string }{
		{"own line", "dan", "I am @dan"},
		{"same login upstream", "fossil:dan", "daniel here"},
		{"robot", "robot", "hello @dan"},
		{"timeline line", "fossil:lou", "to @dan: *MERGE* daniel (check-in: [abc123](/info/abc123) by lou)"},
	} {
		before := len(g.fn.snapshot())
		g.d.chatMentionAt("alpha", c.text, c.from, 8)
		if got := g.quiet(); len(got) != before {
			t.Errorf("FAIL: %s sent %+v", c.name, got[before:])
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A linked Fossil login is the person: their bridged line is their own.
func TestHighlightSkipsALinkedFossilLogin(t *testing.T) {
	g := newHLRig(t)
	ids := &memChatIdentity{}
	_ = ids.SetChatIdentity("alpha", "fossil:danm", "dan", "root")
	g.d.ChatIdentities = ids
	_ = g.modes.SetChatNotify("alpha", "dan", oltp.ChatHighlights)
	g.d.chatMentionAt("alpha", "@dan please look", "fossil:danm", 3)
	if got := g.quiet(); len(got) != 0 {
		t.Errorf("FAIL: a linked login's own line sent %+v", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// Visiting the channel cancels what is pending there, and only then
// does notify hear anything: no call when nothing is pending.
func TestHighlightCancelledByPresence(t *testing.T) {
	g := newHLRig(t)
	_ = g.modes.SetChatNotify("alpha", "dan", oltp.ChatHighlights)
	_ = g.modes.SetChatNotify("alpha", "eve", oltp.ChatHighlights)

	g.d.chatSeen("alpha", "dan") // nothing pending yet
	if got := g.quiet(); len(g.fn.cancels()) != 0 || len(got) != 0 {
		t.Fatalf("FAIL: cancel asked with nothing pending: %v", g.fn.cancels())
	}

	g.d.chatMentionAt("alpha", "@dan and @eve, lunch?", "lou", 5)
	g.waitEvents(2)
	g.d.chatSeen("alpha", "dan")
	for deadline := time.Now().Add(5 * time.Second); len(g.fn.cancels()) < 1 && time.Now().Before(deadline); time.Sleep(time.Millisecond) {
	}
	if got := g.fn.cancels(); len(got) != 1 || got[0] != "highlight:alpha:5:dan" {
		t.Errorf("FAIL: cancelled %v, want only dan's send", got)
	}
	if g.hl.HasHighlightPending("alpha", "dan") || !g.hl.HasHighlightPending("alpha", "eve") {
		t.Errorf("FAIL: pending after the visit: dan=%v eve=%v", g.hl.HasHighlightPending("alpha", "dan"), g.hl.HasHighlightPending("alpha", "eve"))
	}

	// Posting is being there too.
	g.d.chatMentionAt("alpha", "back now", "eve", 6)
	for deadline := time.Now().Add(5 * time.Second); len(g.fn.cancels()) < 2 && time.Now().Before(deadline); time.Sleep(time.Millisecond) {
	}
	if got := g.fn.cancels(); len(got) != 2 || got[1] != "highlight:alpha:5:eve" {
		t.Errorf("FAIL: after eve posted, cancelled %v", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func (g *hlRig) say(user, text string, at time.Time) uint64 {
	g.fc.mu.Lock()
	defer g.fc.mu.Unlock()
	seq := uint64(len(g.fc.msgs) + 1)
	g.fc.msgs = append(g.fc.msgs, chat.Message{Seq: seq, Kind: chat.KindMsg, Repo: "alpha", User: user, Text: text,
		At: at.UTC().Format(time.RFC3339Nano)})
	g.fc.codes = append(g.fc.codes, "alpha")
	return seq
}

// The digest names conversations as single lines, and leaves out the
// ones the person took part in, was named in, or has already seen.
func TestHighlightDigestSelectsConversations(t *testing.T) {
	g := newHLRig(t)
	base := g.now.Add(-20 * time.Hour)
	at := func(h int) time.Time { return base.Add(time.Duration(h) * time.Hour) }
	g.say("lou", "who broke the build", at(0)) // seen
	g.say("gus", "not me", at(0).Add(time.Minute))
	g.say("lou", "dan joined in here", at(2))
	g.say("dan", "I did it", at(2).Add(time.Minute)) // dan took part
	g.say("amy", "release notes draft", at(4))
	g.say("robot", "robot noise", at(5))
	g.say("fossil:lou", "*MERGE* x (check-in: [abc123](/info/abc123) by lou)", at(6)) // an announcement
	g.say("amy", "ping @dan about the deploy", at(8))                                 // named: sent as a highlight
	g.say("bob", "lunch plans", at(10))
	_ = g.seen.TouchChatSeen("alpha", "dan", at(1)) // read the first conversation, nothing after it

	lines, more := g.d.highlightDigest("alpha", "dan", g.now.Add(-24*time.Hour), g.now)
	var chats []digestLine
	for _, l := range lines {
		if l.Kind == "chat" {
			chats = append(chats, l)
		}
	}
	if more != 0 || len(chats) != 2 {
		t.Fatalf("FAIL: %d conversations (more %d), want 2: %+v", len(chats), more, chats)
	}
	if !strings.HasPrefix(chats[0].Line, "amy, 1 message") || !strings.HasSuffix(chats[0].Link, "/r/alpha/chat/5") {
		t.Errorf("FAIL: first line = %+v", chats[0])
	}
	if !strings.HasPrefix(chats[1].Line, "bob, 1 message") {
		t.Errorf("FAIL: second line = %+v", chats[1])
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// At most twelve conversations, then the count of the rest.
func TestHighlightDigestCapsAtTwelve(t *testing.T) {
	g := newHLRig(t)
	base := g.now.Add(-23 * time.Hour)
	for i := 0; i < 15; i++ {
		g.say("lou", "topic "+string(rune('a'+i)), base.Add(time.Duration(i)*time.Hour))
	}
	lines, more := g.d.highlightDigest("alpha", "dan", g.now.Add(-24*time.Hour), g.now)
	if len(lines) != highlightConvoMax || more != 3 {
		t.Errorf("FAIL: %d lines and %d more, want %d and 3", len(lines), more, highlightConvoMax)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The tick sends one digest at the person's hour in their zone, once,
// and sends nothing for a day with nothing in it.
func TestHighlightDigestsSendOnceAtTheChosenHour(t *testing.T) {
	g := newHLRig(t)
	_ = g.modes.SetChatNotify("alpha", "dan", oltp.ChatHighlights)
	g.say("lou", "something happened", g.now.Add(-5*time.Hour))

	g.now = time.Date(2026, 11, 25, 6, 0, 0, 0, time.UTC) // before 07:00 UTC
	g.d.ChatHighlightDigests()
	if got := g.quiet(); len(got) != 0 {
		t.Fatalf("FAIL: sent before the hour: %+v", got)
	}

	g.now = time.Date(2026, 11, 25, 7, 5, 0, 0, time.UTC)
	g.d.ChatHighlightDigests()
	evs := g.waitEvents(1)
	if len(evs) != 1 || evs[0].Workflow != "quarry-chat-highlights" || evs[0].To != "dan" {
		t.Fatalf("FAIL: events = %+v, want one quarry-chat-highlights to dan", evs)
	}
	items, _ := evs[0].Payload["items"].([]digestLine)
	if len(items) != 1 || items[0].Kind != "chat" {
		t.Errorf("FAIL: items = %+v", evs[0].Payload["items"])
	}

	g.now = g.now.Add(10 * time.Minute)
	g.d.ChatHighlightDigests()
	if got := g.quiet(); len(got) != 1 {
		t.Errorf("FAIL: a second digest the same day: %+v", got[1:])
	}

	// Next day, nothing new: the run is recorded and nothing is sent.
	g.now = time.Date(2026, 11, 26, 7, 5, 0, 0, time.UTC)
	g.d.ChatHighlightDigests()
	if got := g.quiet(); len(got) != 1 {
		t.Errorf("FAIL: an empty digest sent mail: %+v", got[1:])
	}
	if at := g.hl.HighlightDigestAt("alpha", "dan"); !at.Equal(g.now) {
		t.Errorf("FAIL: the empty run was not recorded: %v", at)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The digest hour is read in the person's own zone.
func TestHighlightDigestUsesTheirZone(t *testing.T) {
	g := newHLRig(t)
	_ = g.modes.SetChatNotify("alpha", "dan", oltp.ChatHighlights)
	_ = g.hl.SetHighlightPref("dan", oltp.HighlightPref{Hour: 7, TZ: "America/Chicago"})
	g.say("lou", "something happened", g.now.Add(-5*time.Hour))
	g.now = time.Date(2026, 11, 25, 7, 5, 0, 0, time.UTC) // 01:05 in Chicago
	g.d.ChatHighlightDigests()
	if got := g.quiet(); len(got) != 0 {
		t.Fatalf("FAIL: sent at 01:05 local: %+v", got)
	}
	g.now = time.Date(2026, 11, 25, 13, 5, 0, 0, time.UTC) // 07:05 in Chicago
	g.d.ChatHighlightDigests()
	if got := g.waitEvents(1); len(got) != 1 {
		t.Errorf("FAIL: nothing sent at 07:05 local: %+v", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// highlights is a bell choice like the others, and the account's names
// and digest hour round-trip, with short names and long lists refused.
func TestHighlightOpsRoundTrip(t *testing.T) {
	g := newHLRig(t)
	r := ops.NewRegistry()
	g.d.Version = "v"
	g.d.Repos = testRepos(wikiIndex(t))
	mustRepo(t, g.d.Repos, "test").Chat = "c1"
	if err := RegisterAll(r, g.d); err != nil {
		t.Fatal(err)
	}
	ctx := ops.WithUser(context.Background(), "dan")
	if _, err := r.Invoke(ctx, "chat.notify.set", chatNotifySetIn{Repo: "test", Mode: "highlights"}); err != nil {
		t.Fatalf("FAIL: chat.notify.set highlights: %v", err)
	}
	got, err := r.Invoke(ctx, "chat.notify", chatNotifyIn{Repo: "test"})
	if err != nil || got.(chatNotifyOut).Mode != "highlights" {
		t.Errorf("FAIL: chat.notify = %+v, %v", got, err)
	}

	out, err := r.Invoke(ctx, "me.highlights.set", highlightsSetIn{Names: []string{"@Daniel", "dmestas", "daniel"}, DigestHour: 9, TZ: "America/Chicago"})
	if err != nil {
		t.Fatalf("FAIL: me.highlights.set: %v", err)
	}
	h := out.(highlightsOut)
	if strings.Join(h.Names, ",") != "daniel,dmestas" || h.DigestHour != 9 || h.TZ != "America/Chicago" {
		t.Errorf("FAIL: set answered %+v", h)
	}
	read, _ := r.Invoke(ctx, "me.highlights", highlightsIn{})
	if r := read.(highlightsOut); strings.Join(r.Names, ",") != "daniel,dmestas" || r.DigestHour != 9 {
		t.Errorf("FAIL: read back %+v", r)
	}

	for name, in := range map[string]highlightsSetIn{
		"short":    {Names: []string{"dan"}},
		"phrase":   {Names: []string{"a b c"}},
		"eleven":   {Names: strings.Fields("aaaa bbbb cccc dddd eeee ffff gggg hhhh iiii jjjj kkkk")},
		"bad zone": {Names: []string{"daniel"}, TZ: "Mars/Olympus"},
	} {
		if _, err := r.Invoke(ctx, "me.highlights.set", in); err == nil || !strings.Contains(err.Error(), ops.ErrInvalid.Error()) {
			t.Errorf("FAIL: %s: err = %v, want invalid", name, err)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// Check-ins, forum posts and wiki edits by other people come first, one
// line each with its own link; the person's own do not.
func TestHighlightDigestListsActivityFirst(t *testing.T) {
	g := newHLRig(t)
	ix := wikiIndex(t)
	g.d.Repos = NewRepos(map[string]*Repo{"alpha": {Chat: "alpha", Index: ix}})
	g.say("lou", "a thought", g.now.Add(-time.Hour))
	long := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
	lines, _ := g.d.highlightDigest("alpha", "nobody", long, g.now)
	if len(lines) < 2 || lines[len(lines)-1].Kind != "chat" {
		t.Fatalf("FAIL: lines = %+v, want activity then one chat line", lines)
	}
	for _, l := range lines[:len(lines)-1] {
		if l.Kind == "chat" || l.Link == "" {
			t.Errorf("FAIL: activity line %+v", l)
		}
	}
	own, _ := g.d.highlightDigest("alpha", lines[0].Line[:strings.Index(lines[0].Line, " ")], long, g.now)
	if len(own) >= len(lines) {
		t.Errorf("FAIL: the person's own activity was not left out: %d vs %d", len(own), len(lines))
	}
	if !t.Failed() {
		t.Log("ok")
	}
}