Skip to content
quarry Artifact [99828b93b1]
Login

Artifact [99828b93b1]

Artifact 99828b93b16b828ede1bdad239c07266f898244a723b617cac9ade61c61bf208:


package api

import (
	"context"
	"errors"
	"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) *ops.Registry {
	t.Helper()
	r := ops.NewRegistry()
	if err := RegisterAll(r, 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"},
		}}}); 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, and only for repositories the caller
// holds: a pin on one they cannot reach 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) // owner holds nothing on alpha
	r := pinForge(t, pins)
	for user, want := range map[string]map[string]int{
		"dan":   {"gamma": 1, "alpha": 2},
		"owner": {},
	} {
		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)
	}
}