package chat
import (
"context"
"strings"
"sync/atomic"
"testing"
"time"
"craftdesign.group/quarry/internal/events"
)
// RFC 0023: a held repository's channel is repository content. A bridge
// of it is paused, not halted: while the takedown stands the peer is
// asked nothing (no poll, no sign-in, no send), and what is said locally
// meanwhile is never relayed; lifted, the bridge resumes by itself, with
// nothing stored for a person to clear.
func TestHeldRepositoryBridgeAsksThePeerNothingAndResumesByItself(t *testing.T) {
ev, err := events.Start(t.TempDir())
if err != nil {
t.Fatal(err)
}
t.Cleanup(ev.Close)
r := room(t, ev)
peer := newPausePeer(t, peerOK)
store := newMemStore()
b := NewBridge(r, store, BridgeConfig{
Repo: "alpha", Code: "codeA", URL: peer.srv.URL, User: "bot", Secret: "pw", AllowPrivate: true,
})
var held atomic.Bool
held.Store(true)
b.Held = func(string) bool { return held.Load() }
b.HeldEvery = 20 * time.Millisecond
ctx, cancel := context.WithCancel(context.Background())
done := runDone(b, ctx)
t.Cleanup(func() { cancel(); <-done })
// Said during the hold, with the bridge already listening.
time.Sleep(200 * time.Millisecond)
if _, err := r.Post("codeA", Message{Repo: "alpha", User: "dan", Text: "said under the hold"}); err != nil {
t.Fatal(err)
}
time.Sleep(1500 * time.Millisecond)
if n := peer.hits.Load(); n != 0 {
t.Errorf("FAIL: the peer was asked %d times while the repository was held", n)
}
// The lift and the next message are as close as two calls can be:
// the message must find the bridge already listening.
held.Store(false)
if _, err := r.Post("codeA", Message{Repo: "alpha", User: "dan", Text: "said after the lift"}); err != nil {
t.Fatal(err)
}
deadline := time.Now().Add(60 * time.Second)
for peer.hits.Load() == 0 && time.Now().Before(deadline) {
time.Sleep(20 * time.Millisecond)
}
if peer.hits.Load() == 0 {
t.Fatal("FAIL: the lifted bridge did not resume polling by itself")
}
// The peer counts a send when it arrives and records its text a
// moment later, so wait for the text itself, generously.
var sent string
deadline = time.Now().Add(60 * time.Second)
for time.Now().Before(deadline) {
peer.mu.Lock()
sent = strings.Join(peer.sent, "|")
peer.mu.Unlock()
if strings.Contains(sent, "said after the lift") {
break
}
time.Sleep(20 * time.Millisecond)
}
if !strings.Contains(sent, "said after the lift") {
t.Errorf("FAIL: a message after the lift was not relayed: %q", sent)
}
if strings.Contains(sent, "said under the hold") {
t.Errorf("FAIL: a message said under the hold was relayed later: %q", sent)
}
if !t.Failed() {
t.Log("ok")
}
}