package net import ( "testing" "time" "git.smesh.lol/torly/pkg/nostr" tinyspawn "git.smesh.lol/torly/pkg/tinyspawn" "git.smesh.lol/torly/pkg/wire" ) // newTestServer builds a server whose worker links can be driven and observed // directly. The database, verify and Blob responses are left as zero duplexes: // a nil channel never fires, so TryRecv reports nothing pending. func newTestServer(workers int) (*server, []tinyspawn.Duplex[wire.Inbound], []tinyspawn.Duplex[wire.Outbound]) { s := &server{ conns: make(map[wire.ConnID]*connState), pos: make(map[wire.ConnID]int), pending: make(map[wire.ReqID]*verifyCtx), dbCtx: make(map[wire.ReqID]*dbCtx), blobCtx: make(map[wire.ReqID]*blobCtx), busy: make([]bool, 1), httpOut: make([][]wire.Outbound, workers), } var feed []tinyspawn.Duplex[wire.Inbound] var out []tinyspawn.Duplex[wire.Outbound] for i := 0; i < workers; i++ { f, srv := tinyspawn.NewBufferedDuplex[wire.Inbound](1024) o, obs := tinyspawn.NewBufferedDuplex[wire.Outbound](4096) s.ch.Workers = append(s.ch.Workers, WorkerLink{In: srv, Out: o}) feed = append(feed, f) out = append(out, obs) } return s, feed, out } // addConn registers a connection subscribed to one catch-all filter. func (s *server) addConn(id wire.ConnID) *connState { c := &connState{id: id, worker: 0, subs: map[string][]nostr.Filter{"s": {{}}}} s.conns[id] = c s.pos[id] = len(s.order) s.order = append(s.order, id) return c } // drainOut counts and discards the frames waiting on one worker link. func drainOut(d tinyspawn.Duplex[wire.Outbound]) int { n := 0 for { if _, ok := tinyspawn.TryRecv(d); !ok { return n } n++ } } // TestAdvanceQueryChunks: a REQ result must be delivered a chunk at a time, so // the network loop returns to its breaker check between chunks. func TestAdvanceQueryChunks(t *testing.T) { s, _, out := newTestServer(1) c := s.addConn(1) const total = 200 events := make([]nostr.Event, total) for i := range events { events[i].Kind = 1 events[i].CreatedAt = int64(i) events[i].ID[0] = byte(i) } job := &queryJob{conn: c, sub: "s", events: events} s.queries = append(s.queries, job) if more := s.advanceQuery(job); !more { t.Fatal("advanceQuery reported done with 200 events pending") } if n := drainOut(out[0]); n != queryChunk { t.Fatalf("first turn delivered %d events, want %d", n, queryChunk) } for s.advanceQuery(job) { } rest := drainOut(out[0]) // The remaining events plus one EOSE. if want := total - queryChunk + 1; rest != want { t.Fatalf("later turns delivered %d frames, want %d", rest, want) } if len(s.queries) != 0 { t.Fatalf("job not dropped: %d queries queued", len(s.queries)) } } // TestAdvanceQuerySkipsClosedConn: a client that disconnects mid-result must // have its job dropped, not delivered to a dead connection. func TestAdvanceQuerySkipsClosedConn(t *testing.T) { s, _, out := newTestServer(1) c := s.addConn(1) job := &queryJob{conn: c, sub: "s", events: make([]nostr.Event, 10)} s.queries = append(s.queries, job) s.forget(c) if more := s.advanceQuery(job); more { t.Fatal("advanceQuery continued for a closed connection") } if n := drainOut(out[0]); n != 0 { t.Fatalf("sent %d frames to a closed connection", n) } if len(s.queries) != 0 { t.Fatal("job for a closed connection was not dropped") } } // TestAdvanceBroadcastChunks: live fan-out must be resumable across turns. func TestAdvanceBroadcastChunks(t *testing.T) { s, _, out := newTestServer(1) const total = 1000 for i := 1; i <= total; i++ { s.addConn(wire.ConnID(i)) } ev := &nostr.Event{Kind: 1} job := &broadcastJob{ev: ev, data: ev.AppendJSON(nil)} s.jobs = append(s.jobs, job) if more := s.advanceBroadcast(job); !more { t.Fatal("advanceBroadcast reported done with connections pending") } if n := drainOut(out[0]); n != broadcastChunk { t.Fatalf("first turn offered %d connections, want %d", n, broadcastChunk) } for s.advanceBroadcast(job) { } if n := drainOut(out[0]); n != total-broadcastChunk { t.Fatalf("later turns offered %d connections, want %d", n, total-broadcastChunk) } } // TestBroadcastSkipsClosedSlot: a connection that closes mid-pass leaves a hole // in the order slice. The hole must be skipped, never visited twice. func TestBroadcastSkipsClosedSlot(t *testing.T) { s, _, out := newTestServer(1) const total = 800 for i := 1; i <= total; i++ { s.addConn(wire.ConnID(i)) } ev := &nostr.Event{Kind: 1} job := &broadcastJob{ev: ev, data: ev.AppendJSON(nil)} s.jobs = append(s.jobs, job) s.advanceBroadcast(job) drainOut(out[0]) // Close a connection the pass has not reached yet. s.forget(s.conns[600]) for s.advanceBroadcast(job) { } if n := drainOut(out[0]); n != total-broadcastChunk-1 { t.Fatalf("later turns offered %d connections, want %d", n, total-broadcastChunk-1) } if len(s.order) != total-1 { t.Fatalf("order still holds %d slots after compaction, want %d", len(s.order), total-1) } for _, id := range s.order { if id == 0 { t.Fatal("compaction left a closed slot in order") } } } // TestDrainBudget: one pass handles at most netUnitBudget inputs, whatever the // channel depth. This is the bound that keeps a flood from hiding a shutdown. func TestDrainBudget(t *testing.T) { const workers = 4 s, feed, _ := newTestServer(workers) for i := 0; i < 1000; i++ { feed[i%workers].Send(wire.Inbound{Kind: wire.InClosed}) } budget := netUnitBudget s.drain(&budget) if budget != 0 { t.Fatalf("drain used %d of its %d budget", netUnitBudget-budget, netUnitBudget) } // A second pass must still find work: the budget bounds a turn, it does not // discard input. budget = netUnitBudget s.drain(&budget) if budget == netUnitBudget { t.Fatal("second pass found no work") } } // TestRunStopsUnderContinuousInput: a domain with input still arriving must stop // promptly when the breaker closes. // // It does not prove the loop reaches the breaker when the input never drains: // a full channel is emptied inside the pass that observes it, so no client-side // rate can force starvation. That property is checked structurally, by // relay.TestDomainLoopsCheckTheBreaker. This one is the behavioural half: it // would catch a domain that only checks its breaker after the queue empties. func TestRunStopsUnderContinuousInput(t *testing.T) { // Unbuffered on purpose: a blocked sender is always ready to rendezvous, so // every TryRecv in drain succeeds and the loop never runs out of work. feed, srv := tinyspawn.NewDuplex[wire.Inbound]() out, _ := tinyspawn.NewBufferedDuplex[wire.Outbound](64) ready := make(chan wire.Ready, 1) stop := tinyspawn.NewBreaker() done := make(chan struct{}) go func() { Run(Data{}, Chans{ Workers: []WorkerLink{{In: srv, Out: out}}, Ready: ready, Stop: stop, }) close(done) }() select { case <-ready: case <-time.After(2 * time.Second): t.Fatal("network domain never reported ready") } go func() { for { select { case <-stop.Done(): return case feed.Tx <- wire.Inbound{Kind: wire.InClosed}: } } }() // Let the flood establish itself. time.Sleep(20 * time.Millisecond) start := time.Now() stop.Close() select { case <-done: case <-time.After(2 * time.Second): t.Fatalf("network domain did not stop within 2s of the breaker closing") } if elapsed := time.Since(start); elapsed > 250*time.Millisecond { t.Fatalf("network domain took %s to stop under load, want under 250ms", elapsed) } }