package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"sync"
"testing"
"craftdesign.group/quarry/internal/ops"
)
// memPins is a PinStore in memory that keeps the order pins were made in.
type memPins struct {
mu sync.Mutex
pins map[string][]string
}
func (m *memPins) SetPin(account, repo string, pinned bool) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.pins == nil {
m.pins = map[string][]string{}
}
have := slices.Contains(m.pins[account], repo)
switch {
case pinned && !have:
m.pins[account] = append(m.pins[account], repo)
case !pinned && have:
m.pins[account] = slices.DeleteFunc(m.pins[account], func(r string) bool { return r == repo })
}
return nil
}
func (m *memPins) Pins(account string) ([]string, error) {
m.mu.Lock()
defer m.mu.Unlock()
return slices.Clone(m.pins[account]), nil
}
func pinForge(t *testing.T, pins PinStore, tune ...func(*Deps)) *ops.Registry {
t.Helper()
r := ops.NewRegistry()
d := Deps{Version: "v",
Repos: NewRepos(map[string]*Repo{
"alpha": forumRepoAt(t, "a", "2026-09-01T10:00:00", "first thread"),
"beta": forumRepoAt(t, "b", "2026-09-02T10:00:00", "second thread"),
"gamma": forumRepoAt(t, "c", "2026-09-03T10:00:00", "third thread"),
"secret": forumRepoAt(t, "d", "2026-09-04T10:00:00", "private thread"),
}),
Private: func() map[string]bool { return map[string]bool{"secret": true} },
CanRead: func(ctx context.Context, repo string) bool {
return repo != "secret" || ops.User(ctx) == "owner"
},
Pins: pins,
Accounts: stubAccounts{grants: map[string]map[string]string{
"dan": {"alpha": "admin", "beta": "admin", "gamma": "admin", "secret": "admin"},
"owner": {"secret": "admin"},
}}}
for _, f := range tune {
f(&d)
}
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
return r
}
// me.repos says what happened last in each repository, from the one
// event it already reads for the date, so the home board can show it
// without a second read.
func TestMeReposCarriesTheNewestEvent(t *testing.T) {
r := pinForge(t, &memPins{})
got, err := r.Invoke(ops.WithUser(context.Background(), "dan"), "me.repos", meReposIn{})
if err != nil {
t.Fatal(err)
}
rows := map[string]meReposRow{}
for _, row := range got.(meReposOut).Repos {
rows[row.Name] = row
}
beta := rows["beta"].Latest
if beta == nil || beta.Kind != "f" || beta.User != "dan" || beta.Date != "2026-09-02T10:00:00" || beta.Comment == "" {
t.Fatalf("FAIL: beta's newest event is %+v", beta)
}
if beta.Hash != strings.Repeat("b", 32) || beta.Ref == "" {
t.Errorf("FAIL: beta's newest event names no object to link to: %+v", beta)
}
if rows["beta"].LastActivity != beta.Date {
t.Errorf("FAIL: lastActivity %q disagrees with the event's date %q", rows["beta"].LastActivity, beta.Date)
}
if !t.Failed() {
t.Log("ok: me.repos carries the newest event")
}
}
// Pins ride me.repos as a position, for repositories the caller can read:
// a pin on one they cannot reach, or that is gone, is simply not there.
func TestMeReposCarriesPinsInOrder(t *testing.T) {
pins := &memPins{}
_ = pins.SetPin("dan", "gamma", true)
_ = pins.SetPin("dan", "gone", true) // no such repository any more
_ = pins.SetPin("dan", "alpha", true)
_ = pins.SetPin("owner", "alpha", true) // readable by anyone, though owner holds no grant on it
_ = pins.SetPin("owner", "secret", true)
r := pinForge(t, pins)
for user, want := range map[string]map[string]int{
"dan": {"gamma": 1, "alpha": 2},
"owner": {"alpha": 1, "secret": 2},
} {
got, err := r.Invoke(ops.WithUser(context.Background(), user), "me.repos", meReposIn{})
if err != nil {
t.Fatal(err)
}
have := map[string]int{}
for _, row := range got.(meReposOut).Repos {
if row.Pin != 0 {
have[row.Name] = row.Pin
}
}
if len(have) != len(want) {
t.Errorf("FAIL: %s sees pins %v, want %v", user, have, want)
}
for name, pos := range want {
if have[name] != pos {
t.Errorf("FAIL: %s sees pins %v, want %v", user, have, want)
}
}
}
}
// me.pin pins and unpins for the caller. A repository the caller cannot
// read answers exactly as one that does not exist, so the name of a
// private repository is not confirmed by the refusal.
func TestMePin(t *testing.T) {
pins := &memPins{}
r := pinForge(t, pins)
ctx := ops.WithUser(context.Background(), "dan")
call := func(c context.Context, repo string, pinned bool) (any, error) {
return r.Invoke(c, "me.pin", mePinIn{Repo: repo, Pinned: pinned})
}
for _, name := range []string{"gamma", "alpha"} {
if _, err := call(ctx, name, true); err != nil {
t.Fatalf("FAIL: pinning %s: %v", name, err)
}
}
if got, _ := pins.Pins("dan"); !slices.Equal(got, []string{"gamma", "alpha"}) {
t.Errorf("FAIL: dan's pins are %v", got)
}
out, err := call(ctx, "gamma", false)
if err != nil || out.(mePinOut).Pinned {
t.Errorf("FAIL: unpinning gamma answered %+v, %v", out, err)
}
if got, _ := pins.Pins("dan"); !slices.Equal(got, []string{"alpha"}) {
t.Errorf("FAIL: after the unpin dan's pins are %v", got)
}
// dan holds secret but cannot read it here; the refusal is the same
// as for a repository that is not there, down to the words.
_, errSecret := call(ctx, "secret", true)
_, errMissing := call(ctx, "nonesuch", true)
if !errors.Is(errSecret, ops.ErrNotFound) || !errors.Is(errMissing, ops.ErrNotFound) {
t.Fatalf("FAIL: refusals are %v and %v, want not found for both", errSecret, errMissing)
}
if strings.ReplaceAll(errSecret.Error(), "secret", "X") != strings.ReplaceAll(errMissing.Error(), "nonesuch", "X") {
t.Errorf("FAIL: an unreadable repository answers %q, a missing one %q", errSecret, errMissing)
}
if got, _ := pins.Pins("dan"); slices.Contains(got, "secret") {
t.Error("FAIL: a repository the caller cannot read was pinned")
}
// No account, no pin.
if _, err := call(context.Background(), "alpha", true); !errors.Is(err, ops.ErrNotFound) {
t.Errorf("FAIL: pinning with no account answered %v", err)
}
if got, _ := pins.Pins(""); len(got) != 0 {
t.Errorf("FAIL: pins were kept for nobody: %v", got)
}
if !t.Failed() {
t.Log("ok: me.pin pins, unpins and refuses what it cannot read")
}
}
// A forge with no pin store still documents the op and answers it
// honestly, so docs/api.md is one document on every deployment.
func TestMePinWithoutAStore(t *testing.T) {
r := pinForge(t, nil)
_, err := r.Invoke(ops.WithUser(context.Background(), "dan"), "me.pin", mePinIn{Repo: "alpha", Pinned: true})
if !errors.Is(err, ops.ErrUnavailable) {
t.Errorf("FAIL: with no store me.pin answered %v", err)
}
}
// dan holds a grant on secret that his reads do not honour here, and has
// a pin on it (made when he could read it). Neither the pin nor the
// grant puts the repository, or its name, in what me.repos answers.
func TestMeReposNeverNamesAPinnedRepositoryTheCallerCannotRead(t *testing.T) {
pins := &memPins{}
_ = pins.SetPin("dan", "secret", true)
_ = pins.SetPin("dan", "alpha", true)
r := pinForge(t, pins)
got, err := r.Invoke(ops.WithUser(context.Background(), "dan"), "me.repos", meReposIn{})
if err != nil {
t.Fatal(err)
}
b, err := json.Marshal(got)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(b), "secret") {
t.Errorf("FAIL: me.repos names a repository dan cannot read: %s", b)
}
for _, row := range got.(meReposOut).Repos {
if row.Name == "alpha" && row.Pin != 1 {
t.Errorf("FAIL: alpha's pin is %d, want 1 (the unreadable pin takes no place)", row.Pin)
}
}
if !t.Failed() {
t.Log("ok: a pin on an unreadable repository is not in me.repos")
}
}
// A pinned repository stays on the board when it is not among the most
// active the list is cut to.
func TestMeReposKeepsAPinOutsideTheMostActive(t *testing.T) {
repos := map[string]*Repo{}
grants := map[string]string{}
for i := 0; i < 205; i++ {
name := fmt.Sprintf("r%03d", i)
// Dates ascend with i, so r000 is the quietest.
repos[name] = forumRepoAt(t, fmt.Sprintf("%032x", i+1), fmt.Sprintf("2026-09-01T10:%02d:%02d", i/60, i%60), "thread "+name)
grants[name] = "admin"
}
pins := &memPins{}
_ = pins.SetPin("dan", "r000", true)
r := ops.NewRegistry()
if err := RegisterAll(r, Deps{Version: "v", Repos: NewRepos(repos), Pins: pins,
Accounts: stubAccounts{grants: map[string]map[string]string{"dan": grants}}}); err != nil {
t.Fatal(err)
}
got, err := r.Invoke(ops.WithUser(context.Background(), "dan"), "me.repos", meReposIn{})
if err != nil {
t.Fatal(err)
}
rows := got.(meReposOut).Repos
var pinned, quiet int
for _, row := range rows {
if row.Name == "r000" {
pinned = row.Pin
if row.Role != "admin" {
t.Errorf("FAIL: the pinned row's role is %q, want admin", row.Role)
}
}
if row.Name == "r001" {
quiet++
}
}
if pinned != 1 || quiet != 0 || len(rows) != 201 {
t.Errorf("FAIL: pin place %d, the next-quietest listed %d times, %d rows; want 1, 0, 201", pinned, quiet, len(rows))
}
if !t.Failed() {
t.Log("ok: a pin outlives the cut for activity")
}
}
// Under a legal hold the command gate answers before an op's own checks.
// me.pin is exempt from it, so a caller who cannot read a held
// repository is told exactly what they are told of one that does not
// exist, and unpinning a held repository still works: it clears the
// caller's own row and writes no repository.
func TestMePinOnAHeldRepository(t *testing.T) {
pins := &memPins{}
_ = pins.SetPin("dan", "gamma", true)
held := map[string]bool{"secret": true, "gamma": true}
r := pinForge(t, pins, func(d *Deps) {
d.LegalHold = func(repo string) bool { return held[repo] }
})
ctx := ops.WithUser(context.Background(), "dan")
call := func(repo string, pinned bool) error {
_, err := r.Invoke(ctx, "me.pin", mePinIn{Repo: repo, Pinned: pinned})
return err
}
errHeld, errMissing := call("secret", true), call("nonesuch", true)
if !errors.Is(errHeld, ops.ErrNotFound) || !errors.Is(errMissing, ops.ErrNotFound) {
t.Fatalf("FAIL: a held unreadable repository answers %v, a missing one %v; want not found for both", errHeld, errMissing)
}
if strings.ReplaceAll(errHeld.Error(), "secret", "X") != strings.ReplaceAll(errMissing.Error(), "nonesuch", "X") {
t.Errorf("FAIL: a held repository answers %q, a missing one %q", errHeld, errMissing)
}
if err := call("gamma", false); err != nil {
t.Errorf("FAIL: unpinning a held repository answered %v", err)
}
if got, _ := pins.Pins("dan"); slices.Contains(got, "gamma") {
t.Errorf("FAIL: the held repository is still pinned: %v", got)
}
if !t.Failed() {
t.Log("ok: me.pin answers a held repository as a missing one, and unpins it")
}
}