Skip to content
quarry Artifact [bc358fbb43]
Login

Artifact [bc358fbb43]

Artifact bc358fbb43a7c2d186d77e2d371a437e3ffa0bccf8bc1cd33906ce92b1d47647:


package main

import (
	"errors"
	"path/filepath"
	"strings"
	"testing"
	"time"

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

type chatKeyRig struct {
	odb  *oltp.DB
	room *chat.Room
}

func newChatKeyRig(t *testing.T) *chatKeyRig {
	t.Helper()
	ev, err := events.Start(filepath.Join(t.TempDir(), "nats"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(ev.Close)
	room, err := chat.New(ev.Conn(), ev.JS())
	if err != nil {
		t.Fatal(err)
	}
	odb, err := oltp.Open(filepath.Join(t.TempDir(), "oltp.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { odb.Close() })
	room.Robots = odb
	return &chatKeyRig{odb: odb, room: room}
}

// repo registers a repository holding code, as a registry written before
// chat keys has it: no key.
func (r *chatKeyRig) repo(t *testing.T, name, vis, code string) {
	t.Helper()
	if err := r.odb.AddRepo(name, t.TempDir(), "", vis); err != nil {
		t.Fatal(err)
	}
	if code != "" {
		if err := r.odb.SetRepoCode(name, code); err != nil {
			t.Fatal(err)
		}
	}
}

func (r *chatKeyRig) say(t *testing.T, key, text string, ref uint64) uint64 {
	t.Helper()
	seq, err := r.room.Post(key, chat.Message{Repo: "old", User: "u", Text: text, Ref: ref})
	if err != nil {
		t.Fatal(err)
	}
	return seq
}

func (r *chatKeyRig) key(t *testing.T, name string) string {
	t.Helper()
	k, err := r.odb.ChatKey(name)
	if err != nil {
		t.Fatal(err)
	}
	return k
}

func (r *chatKeyRig) texts(t *testing.T, key string) []string {
	t.Helper()
	msgs, err := r.room.Range(key, 0, 0)
	if err != nil {
		t.Fatal(err)
	}
	var out []string
	for _, m := range msgs {
		out = append(out, m.Text)
	}
	return out
}

func noRead(string) (string, error) { return "", errors.New("not read") }

// One repository holding a code keeps its history where it is, under the
// code; a repository with no code starts empty; and a second run changes
// nothing.
func TestChatKeysMigrationKeepsASoleHoldersChannel(t *testing.T) {
	r := newChatKeyRig(t)
	r.repo(t, "solo", oltp.Public, "codeS")
	r.repo(t, "bare", oltp.Public, "")
	r.say(t, "codeS", "hello", 0)
	r.odb.RecordRobotLine("codeS", 9, time.Now().UTC().Format(time.RFC3339Nano))

	// bare's store has a code nothing was ever said under.
	read := func(string) (string, error) { return "codeBare", nil }
	if err := migrateChatKeys(r.odb, r.room, read); err != nil {
		t.Fatal(err)
	}
	if got := r.key(t, "solo"); got != "codeS" {
		t.Errorf("FAIL: solo's key = %q, want the code its history is under", got)
	}
	if got := r.key(t, "bare"); got != "codeBare" {
		t.Errorf("FAIL: bare's key = %q, want its code, as every sole holder's", got)
	}
	if got := r.texts(t, "codeS"); len(got) != 1 {
		t.Errorf("FAIL: solo's channel reads %v", got)
	}
	if n, _ := r.odb.RobotLines("codeS", 0); n != 1 {
		t.Errorf("FAIL: %d robot lines under the kept channel, want 1", n)
	}
	if err := migrateChatKeys(r.odb, r.room, read); err != nil {
		t.Fatal(err)
	}
	if got := r.key(t, "solo"); got != "codeS" {
		t.Errorf("FAIL: a second run changed solo's key to %q", got)
	}
}

// A shared channel with a private repository among its holders goes to
// the private ones and never to a public one, however the names sort.
func TestChatKeysMigrationNeverGivesAPrivateChannelToAPublicRepository(t *testing.T) {
	r := newChatKeyRig(t)
	// "aa" sorts first and is public.
	r.repo(t, "aa-public", oltp.Public, "shared")
	r.repo(t, "bb-private", oltp.Private, "shared")
	r.repo(t, "cc-private", oltp.Private, "shared")
	first := r.say(t, "shared", "one", 0)
	r.say(t, "shared", "one, edited", first)
	r.odb.MarkChatRead("cc-private", "jan", first)
	r.odb.MarkChatRead("aa-public", "jan", first)

	if err := migrateChatKeys(r.odb, r.room, noRead); err != nil {
		t.Fatal(err)
	}
	pub := r.key(t, "aa-public")
	if pub != chat.RepoKey("aa-public") {
		t.Errorf("FAIL: the public repository's key = %q, want its own", pub)
	}
	if got := r.texts(t, pub); len(got) != 0 {
		t.Errorf("FAIL: the public repository inherited the private history: %v", got)
	}
	if got := r.key(t, "bb-private"); got != "shared" {
		t.Errorf("FAIL: the first private repository's key = %q, want the history kept in place", got)
	}
	cc := r.key(t, "cc-private")
	if cc != chat.RepoKey("cc-private") {
		t.Errorf("FAIL: the second private repository's key = %q, want its own", cc)
	}
	got := r.texts(t, cc)
	if len(got) != 2 || got[0] != "one" || got[1] != "one, edited" {
		t.Errorf("FAIL: the second private repository's copy reads %v", got)
	}
	// The copy's edit points at the copy's own first line.
	msgs, _ := r.room.Range(cc, 0, 0)
	if len(msgs) == 2 && msgs[1].Ref != msgs[0].Seq {
		t.Errorf("FAIL: the copied edit refers to %d, want its own first line %d", msgs[1].Ref, msgs[0].Seq)
	}
	if len(msgs) == 2 && strings.Contains(msgs[0].Repo, "old") {
		t.Errorf("FAIL: a copied line still names the repository it was copied from")
	}
	// The copy's read pointer follows the line it was on; the public
	// repository's is cleared with its history.
	if seq := r.odb.ChatReadSeq("cc-private", "jan"); len(msgs) == 2 && seq != msgs[0].Seq {
		t.Errorf("FAIL: the copy's read pointer = %d, want %d", seq, msgs[0].Seq)
	}
	if seq := r.odb.ChatReadSeq("aa-public", "jan"); seq != 0 {
		t.Errorf("FAIL: the public repository kept read pointer %d into history it does not have", seq)
	}
	// Idempotent: nothing is copied twice.
	if err := migrateChatKeys(r.odb, r.room, noRead); err != nil {
		t.Fatal(err)
	}
	if got := r.texts(t, cc); len(got) != 2 {
		t.Errorf("FAIL: a second run left %v in the copy", got)
	}
}

// Where every holder is public the history is shared: the first keeps it
// and each other gets a copy.
func TestChatKeysMigrationCopiesASharedPublicChannelToEachHolder(t *testing.T) {
	r := newChatKeyRig(t)
	r.repo(t, "pub-a", oltp.Public, "shared")
	r.repo(t, "pub-b", oltp.Public, "shared")
	r.say(t, "shared", "hi", 0)
	robot, err := r.room.Post("shared", chat.Message{Kind: chat.KindRobot, Origin: "robot", User: "robot", Text: "tip moved"})
	if err != nil {
		t.Fatal(err)
	}
	_ = robot
	if err := migrateChatKeys(r.odb, r.room, noRead); err != nil {
		t.Fatal(err)
	}
	if got := r.key(t, "pub-a"); got != "shared" {
		t.Errorf("FAIL: pub-a's key = %q", got)
	}
	kb := r.key(t, "pub-b")
	if kb != chat.RepoKey("pub-b") {
		t.Fatalf("FAIL: pub-b's key = %q, want its own", kb)
	}
	if got := r.texts(t, kb); len(got) != 2 || got[0] != "hi" {
		t.Errorf("FAIL: pub-b's copy reads %v", got)
	}
	// The robot line was recorded for the copy, so its badge ignores it.
	if n, _ := r.odb.RobotLines(kb, 0); n != 1 {
		t.Errorf("FAIL: %d robot lines under the copy, want 1", n)
	}
	// From here on they are independent.
	r.say(t, kb, "only in b", 0)
	if got := r.texts(t, "shared"); len(got) != 2 {
		t.Errorf("FAIL: a post in pub-b reached pub-a: %v", got)
	}
}

// A Ready repository whose row records no code is asked its store; one
// whose store cannot be read is left for the next start rather than
// given an empty channel over its history.
func TestChatKeysMigrationLeavesAnUnreadableStoreForNextTime(t *testing.T) {
	r := newChatKeyRig(t)
	r.repo(t, "readable", oltp.Public, "")
	r.repo(t, "broken", oltp.Public, "")
	r.say(t, "codeR", "kept", 0)
	read := func(path string) (string, error) {
		row, _, _ := r.odb.RepoByName("readable")
		if path == row.Path {
			return "codeR", nil
		}
		return "", errors.New("unreadable")
	}
	if err := migrateChatKeys(r.odb, r.room, read); err != nil {
		t.Fatal(err)
	}
	if got := r.key(t, "readable"); got != "codeR" {
		t.Errorf("FAIL: readable's key = %q, want the code its store has", got)
	}
	if got := r.key(t, "broken"); got != "" {
		t.Errorf("FAIL: an unreadable store was given key %q", got)
	}
}

// A repository that appears after the keys were settled is given its own
// key and an empty channel, never a copy of the channel of one that holds
// the same project code, whatever was said in it since.
func TestChatKeysMigrationNeverCopiesToARepositoryThatAppearsLater(t *testing.T) {
	r := newChatKeyRig(t)
	r.repo(t, "owner", oltp.Private, "shared")
	r.say(t, "shared", "before", 0)
	if err := migrateChatKeys(r.odb, r.room, noRead); err != nil {
		t.Fatal(err)
	}
	if got := r.key(t, "owner"); got != "shared" {
		t.Fatalf("FAIL: owner's key = %q", got)
	}
	r.say(t, "shared", "a secret said after the split", 0)
	// A second private mirror of the same upstream, Ready but not yet
	// registered when the forge restarts.
	r.repo(t, "late", oltp.Private, "shared")
	if err := migrateChatKeys(r.odb, r.room, noRead); err != nil {
		t.Fatal(err)
	}
	late := r.key(t, "late")
	if late != chat.RepoKey("late") {
		t.Errorf("FAIL: the later repository's key = %q, want its own", late)
	}
	if got := r.texts(t, late); len(got) != 0 {
		t.Errorf("FAIL: the later repository's channel holds %v, want it empty", got)
	}
	if got := r.texts(t, "shared"); len(got) != 2 {
		t.Errorf("FAIL: the owner's channel reads %v", got)
	}
}

// A sole holder always keeps its code as its key and nothing it keeps
// about its channel is touched, however quiet the channel is.
func TestChatKeysMigrationLeavesAQuietSoleHolderUntouched(t *testing.T) {
	r := newChatKeyRig(t)
	r.repo(t, "quiet", oltp.Public, "quietcode")
	if err := r.odb.MarkChatRead("quiet", "jan", 41); err != nil {
		t.Fatal(err)
	}
	if err := r.odb.RecordMention("quiet", "chat:41", "jan", "kim"); err != nil {
		t.Fatal(err)
	}
	if err := migrateChatKeys(r.odb, r.room, noRead); err != nil {
		t.Fatal(err)
	}
	if got := r.key(t, "quiet"); got != "quietcode" {
		t.Errorf("FAIL: the quiet holder's key = %q, want its code", got)
	}
	if got := r.odb.ChatReadSeq("quiet", "jan"); got != 41 {
		t.Errorf("FAIL: its read pointer became %d", got)
	}
	if who, _ := r.odb.Mentions("quiet", "chat:41"); len(who) != 1 {
		t.Errorf("FAIL: its mention rows became %v", who)
	}
}

// A copy cut short and repeated at once completes the copy and adds
// nothing twice, and does not depend on the broker's duplicate window.
func TestACopyCutShortIsResumedNotRepeated(t *testing.T) {
	r := newChatKeyRig(t)
	first := r.say(t, "src", "one", 0)
	r.say(t, "src", "two", first)
	m1, err := r.room.Copy("src", "dst", "dstrepo", ^uint64(0))
	if err != nil {
		t.Fatal(err)
	}
	// More arrives at the source, as if the first run stopped early.
	r.say(t, "src", "three", 0)
	m2, err := r.room.Copy("src", "dst", "dstrepo", ^uint64(0))
	if err != nil {
		t.Fatal(err)
	}
	m3, err := r.room.Copy("src", "dst", "dstrepo", ^uint64(0))
	if err != nil {
		t.Fatal(err)
	}
	if got := r.texts(t, "dst"); len(got) != 3 || got[2] != "three" {
		t.Errorf("FAIL: the copy reads %v, want three lines once each", got)
	}
	for src, seq := range m1 {
		if m2[src] != seq || m3[src] != seq {
			t.Errorf("FAIL: line %d moved from %d to %d/%d on a repeat", src, seq, m2[src], m3[src])
		}
	}
	if len(m3) != 3 {
		t.Errorf("FAIL: the answer maps %d lines, want 3", len(m3))
	}
}

// A cohort repository whose store could not be read at the first start
// and is settled at a later one is given what was said before the split
// and nothing said after it.
func TestChatKeysMigrationLateSettledCohortGetsNothingSaidAfterTheSplit(t *testing.T) {
	r := newChatKeyRig(t)
	r.repo(t, "aowner", oltp.Private, "C")
	r.repo(t, "zlate", oltp.Private, "")
	r.say(t, "C", "before split", 0)
	if err := migrateChatKeys(r.odb, r.room, noRead); err != nil {
		t.Fatal(err)
	}
	if got := r.key(t, "zlate"); got != "" {
		t.Fatalf("FAIL: the unreadable repository was given key %q", got)
	}
	r.say(t, "C", "SECRET after split", 0)
	if err := migrateChatKeys(r.odb, r.room, func(string) (string, error) { return "C", nil }); err != nil {
		t.Fatal(err)
	}
	k := r.key(t, "zlate")
	if k != chat.RepoKey("zlate") {
		t.Fatalf("FAIL: zlate's key = %q, want its own", k)
	}
	got := r.texts(t, k)
	if len(got) != 1 || got[0] != "before split" {
		t.Errorf("FAIL: the late repository's channel reads %v, want only what was said before the split", got)
	}
}

// An empty channel key reaches no channel, whatever the call.
func TestAnEmptyChannelKeyReachesNoChannel(t *testing.T) {
	r := newChatKeyRig(t)
	if _, err := r.room.Post("", chat.Message{User: "u", Text: "x"}); !errors.Is(err, chat.ErrNoChannel) {
		t.Errorf("FAIL: Post with no key: %v", err)
	}
	if _, err := r.room.Range("", 0, 0); !errors.Is(err, chat.ErrNoChannel) {
		t.Errorf("FAIL: Range with no key: %v", err)
	}
	if _, _, err := r.room.History("", 0, 10); !errors.Is(err, chat.ErrNoChannel) {
		t.Errorf("FAIL: History with no key: %v", err)
	}
	if _, err := r.room.Unread("", 0); !errors.Is(err, chat.ErrNoChannel) {
		t.Errorf("FAIL: Unread with no key: %v", err)
	}
	ch, stop := r.room.Tail("", 0)
	defer stop()
	if _, open := <-ch; open {
		t.Errorf("FAIL: Tail with no key delivered")
	}
	// Nothing was published under the empty subject by any of it.
	last, err := r.room.LastSeq()
	if err != nil || last != 0 {
		t.Errorf("FAIL: the stream holds up to %d (%v), want nothing", last, err)
	}
}