package webhook
import (
"context"
"net/http"
"net/http/httptest"
"path/filepath"
"sync/atomic"
"testing"
"time"
"craftdesign.group/quarry/internal/events"
)
// holdFixture is one endpoint, one embedded stream and a dispatcher that
// has not started delivering, so a test places events on the queue
// before the worker can take them.
func holdFixture(t *testing.T) (d *Dispatcher, hits *atomic.Int32, start func()) {
t.Helper()
hits = new(atomic.Int32)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(srv.Close)
ev, err := events.Start(filepath.Join(t.TempDir(), "nats"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(ev.Close)
d, err = New(ev.JS(), &fakeSubs{subs: map[int64]Sub{1: {ID: 1, URL: srv.URL, Secret: "k", Active: true}}})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
return d, hits, func() {
if err := d.Start(ctx); err != nil {
t.Fatal(err)
}
}
}
func waitHits(hits *atomic.Int32, want int32) bool {
deadline := time.Now().Add(15 * time.Second)
for time.Now().Before(deadline) {
if hits.Load() >= want {
return true
}
time.Sleep(20 * time.Millisecond)
}
return false
}
// RFC 0023: "Webhooks and CI | paused | paused". An event about a
// repository under a takedown is dropped, not queued for the lift, so
// the subscriber learns nothing of it, and the takedown itself is no
// webhook event either.
func TestHeldRepositoryEventReachesNoWebhookSubscriber(t *testing.T) {
d, hits, start := holdFixture(t)
held := map[string]bool{"sealed": true}
d.Hold(func(repo string) bool { return held[repo] }, nil)
start()
if err := d.Raise(Event{ID: "e1", Repo: "sealed", Kind: "ticket.new"}); err != nil {
t.Fatal(err)
}
if err := d.Raise(Event{ID: "e2", Repo: "open", Kind: "ticket.new"}); err != nil {
t.Fatal(err)
}
if !waitHits(hits, 1) {
t.Fatal("FAIL: the control event for an open repository never arrived")
}
time.Sleep(500 * time.Millisecond)
if n := hits.Load(); n != 1 {
t.Errorf("FAIL: %d deliveries, want exactly the open repository's one", n)
}
if !t.Failed() {
t.Log("ok")
}
}
// A delivery queued before the hold landed is not sent after it: the
// worker asks again at send time and discards what it finds held.
func TestHeldRepositoryQueuedDeliveryIsDiscardedNotSent(t *testing.T) {
d, hits, start := holdFixture(t)
var held atomic.Bool
d.Hold(func(repo string) bool { return repo == "sealed" && held.Load() }, nil)
if err := d.Raise(Event{ID: "e1", Repo: "sealed", Kind: "ticket.new"}); err != nil {
t.Fatal(err)
}
if err := d.Raise(Event{ID: "e2", Repo: "open", Kind: "ticket.new"}); err != nil {
t.Fatal(err)
}
held.Store(true) // the hold lands with both on the queue
start()
if !waitHits(hits, 1) {
t.Fatal("FAIL: the control delivery never arrived")
}
time.Sleep(500 * time.Millisecond)
if n := hits.Load(); n != 1 {
t.Errorf("FAIL: %d deliveries, want only the open repository's", n)
}
// Lifted afterwards, the discarded one does not come back.
held.Store(false)
time.Sleep(500 * time.Millisecond)
if n := hits.Load(); n != 1 {
t.Errorf("FAIL: a discarded delivery was sent after the lift (%d)", n)
}
if !t.Failed() {
t.Log("ok")
}
}
// An administrator's replay of a delivery is a send like any other.
func TestHeldRepositoryReplayIsRefused(t *testing.T) {
d, hits, _ := holdFixture(t)
d.Hold(func(repo string) bool { return repo == "sealed" }, nil)
out := d.Replay(context.Background(), Sub{ID: 1, URL: "http://127.0.0.1:1/", Active: true},
Event{ID: "e1", Repo: "sealed", Kind: "ticket.new"}, []byte(`{}`))
if out.Status != 0 || out.Err == "" {
t.Errorf("FAIL: replay of a held repository's event went out: %+v", out)
}
if hits.Load() != 0 {
t.Errorf("FAIL: the endpoint was called")
}
if !t.Failed() {
t.Log("ok")
}
}
// A restart queues nothing for want of an answer: before the takedown
// state is known the dispatcher reads nothing, so the backlog of every
// repository survives to be judged, and only then is a held repository's
// discarded and an open one's delivered.
func TestRestartDoesNotDiscardTheBacklogBeforeTheHoldIsKnown(t *testing.T) {
hits := new(atomic.Int32)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(srv.Close)
ev, err := events.Start(filepath.Join(t.TempDir(), "nats"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(ev.Close)
subs := &fakeSubs{subs: map[int64]Sub{1: {ID: 1, URL: srv.URL, Secret: "k", Active: true}}}
before, err := New(ev.JS(), subs)
if err != nil {
t.Fatal(err)
}
for _, e := range []Event{{ID: "e1", Repo: "sealed", Kind: "ticket.new"}, {ID: "e2", Repo: "open", Kind: "ticket.new"}} {
if err := before.Raise(e); err != nil {
t.Fatal(err)
}
}
// The restarted process: a fresh dispatcher whose state is unknown and
// whose answer, when asked early, is "held" for everything.
var known atomic.Bool
after, err := New(ev.JS(), subs)
if err != nil {
t.Fatal(err)
}
after.Hold(func(repo string) bool { return !known.Load() || repo == "sealed" }, known.Load)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
if err := after.Start(ctx); err != nil {
t.Fatal(err)
}
if err := after.Raise(Event{ID: "e3", Repo: "open", Kind: "ticket.new"}); err == nil {
t.Error("FAIL: an event raised before the state was known was taken or dropped silently")
}
time.Sleep(700 * time.Millisecond)
if hits.Load() != 0 {
t.Errorf("FAIL: %d deliveries before the state was known", hits.Load())
}
known.Store(true)
if !waitHits(hits, 1) {
t.Fatal("FAIL: the open repository's backlog was lost across the restart")
}
time.Sleep(700 * time.Millisecond)
if n := hits.Load(); n != 1 {
t.Errorf("FAIL: %d deliveries, want the open repository's one (the held one is discarded)", n)
}
if !t.Failed() {
t.Log("ok")
}
}