1 package net
2 3 import (
4 "testing"
5 "time"
6 7 "git.smesh.lol/torly/pkg/nostr"
8 tinyspawn "git.smesh.lol/torly/pkg/tinyspawn"
9 "git.smesh.lol/torly/pkg/wire"
10 )
11 12 // newTestServer builds a server whose worker links can be driven and observed
13 // directly. The database, verify and Blob responses are left as zero duplexes:
14 // a nil channel never fires, so TryRecv reports nothing pending.
15 func newTestServer(workers int) (*server, []tinyspawn.Duplex[wire.Inbound], []tinyspawn.Duplex[wire.Outbound]) {
16 s := &server{
17 conns: make(map[wire.ConnID]*connState),
18 pos: make(map[wire.ConnID]int),
19 pending: make(map[wire.ReqID]*verifyCtx),
20 dbCtx: make(map[wire.ReqID]*dbCtx),
21 blobCtx: make(map[wire.ReqID]*blobCtx),
22 busy: make([]bool, 1),
23 httpOut: make([][]wire.Outbound, workers),
24 }
25 var feed []tinyspawn.Duplex[wire.Inbound]
26 var out []tinyspawn.Duplex[wire.Outbound]
27 for i := 0; i < workers; i++ {
28 f, srv := tinyspawn.NewBufferedDuplex[wire.Inbound](1024)
29 o, obs := tinyspawn.NewBufferedDuplex[wire.Outbound](4096)
30 s.ch.Workers = append(s.ch.Workers, WorkerLink{In: srv, Out: o})
31 feed = append(feed, f)
32 out = append(out, obs)
33 }
34 return s, feed, out
35 }
36 37 // addConn registers a connection subscribed to one catch-all filter.
38 func (s *server) addConn(id wire.ConnID) *connState {
39 c := &connState{id: id, worker: 0, subs: map[string][]nostr.Filter{"s": {{}}}}
40 s.conns[id] = c
41 s.pos[id] = len(s.order)
42 s.order = append(s.order, id)
43 return c
44 }
45 46 // drainOut counts and discards the frames waiting on one worker link.
47 func drainOut(d tinyspawn.Duplex[wire.Outbound]) int {
48 n := 0
49 for {
50 if _, ok := tinyspawn.TryRecv(d); !ok {
51 return n
52 }
53 n++
54 }
55 }
56 57 // TestAdvanceQueryChunks: a REQ result must be delivered a chunk at a time, so
58 // the network loop returns to its breaker check between chunks.
59 func TestAdvanceQueryChunks(t *testing.T) {
60 s, _, out := newTestServer(1)
61 c := s.addConn(1)
62 63 const total = 200
64 events := make([]nostr.Event, total)
65 for i := range events {
66 events[i].Kind = 1
67 events[i].CreatedAt = int64(i)
68 events[i].ID[0] = byte(i)
69 }
70 job := &queryJob{conn: c, sub: "s", events: events}
71 s.queries = append(s.queries, job)
72 73 if more := s.advanceQuery(job); !more {
74 t.Fatal("advanceQuery reported done with 200 events pending")
75 }
76 if n := drainOut(out[0]); n != queryChunk {
77 t.Fatalf("first turn delivered %d events, want %d", n, queryChunk)
78 }
79 80 for s.advanceQuery(job) {
81 }
82 rest := drainOut(out[0])
83 // The remaining events plus one EOSE.
84 if want := total - queryChunk + 1; rest != want {
85 t.Fatalf("later turns delivered %d frames, want %d", rest, want)
86 }
87 if len(s.queries) != 0 {
88 t.Fatalf("job not dropped: %d queries queued", len(s.queries))
89 }
90 }
91 92 // TestAdvanceQuerySkipsClosedConn: a client that disconnects mid-result must
93 // have its job dropped, not delivered to a dead connection.
94 func TestAdvanceQuerySkipsClosedConn(t *testing.T) {
95 s, _, out := newTestServer(1)
96 c := s.addConn(1)
97 job := &queryJob{conn: c, sub: "s", events: make([]nostr.Event, 10)}
98 s.queries = append(s.queries, job)
99 s.forget(c)
100 101 if more := s.advanceQuery(job); more {
102 t.Fatal("advanceQuery continued for a closed connection")
103 }
104 if n := drainOut(out[0]); n != 0 {
105 t.Fatalf("sent %d frames to a closed connection", n)
106 }
107 if len(s.queries) != 0 {
108 t.Fatal("job for a closed connection was not dropped")
109 }
110 }
111 112 // TestAdvanceBroadcastChunks: live fan-out must be resumable across turns.
113 func TestAdvanceBroadcastChunks(t *testing.T) {
114 s, _, out := newTestServer(1)
115 const total = 1000
116 for i := 1; i <= total; i++ {
117 s.addConn(wire.ConnID(i))
118 }
119 ev := &nostr.Event{Kind: 1}
120 job := &broadcastJob{ev: ev, data: ev.AppendJSON(nil)}
121 s.jobs = append(s.jobs, job)
122 123 if more := s.advanceBroadcast(job); !more {
124 t.Fatal("advanceBroadcast reported done with connections pending")
125 }
126 if n := drainOut(out[0]); n != broadcastChunk {
127 t.Fatalf("first turn offered %d connections, want %d", n, broadcastChunk)
128 }
129 130 for s.advanceBroadcast(job) {
131 }
132 if n := drainOut(out[0]); n != total-broadcastChunk {
133 t.Fatalf("later turns offered %d connections, want %d", n, total-broadcastChunk)
134 }
135 }
136 137 // TestBroadcastSkipsClosedSlot: a connection that closes mid-pass leaves a hole
138 // in the order slice. The hole must be skipped, never visited twice.
139 func TestBroadcastSkipsClosedSlot(t *testing.T) {
140 s, _, out := newTestServer(1)
141 const total = 800
142 for i := 1; i <= total; i++ {
143 s.addConn(wire.ConnID(i))
144 }
145 ev := &nostr.Event{Kind: 1}
146 job := &broadcastJob{ev: ev, data: ev.AppendJSON(nil)}
147 s.jobs = append(s.jobs, job)
148 149 s.advanceBroadcast(job)
150 drainOut(out[0])
151 // Close a connection the pass has not reached yet.
152 s.forget(s.conns[600])
153 154 for s.advanceBroadcast(job) {
155 }
156 if n := drainOut(out[0]); n != total-broadcastChunk-1 {
157 t.Fatalf("later turns offered %d connections, want %d", n, total-broadcastChunk-1)
158 }
159 if len(s.order) != total-1 {
160 t.Fatalf("order still holds %d slots after compaction, want %d", len(s.order), total-1)
161 }
162 for _, id := range s.order {
163 if id == 0 {
164 t.Fatal("compaction left a closed slot in order")
165 }
166 }
167 }
168 169 // TestDrainBudget: one pass handles at most netUnitBudget inputs, whatever the
170 // channel depth. This is the bound that keeps a flood from hiding a shutdown.
171 func TestDrainBudget(t *testing.T) {
172 const workers = 4
173 s, feed, _ := newTestServer(workers)
174 for i := 0; i < 1000; i++ {
175 feed[i%workers].Send(wire.Inbound{Kind: wire.InClosed})
176 }
177 178 budget := netUnitBudget
179 s.drain(&budget)
180 if budget != 0 {
181 t.Fatalf("drain used %d of its %d budget", netUnitBudget-budget, netUnitBudget)
182 }
183 184 // A second pass must still find work: the budget bounds a turn, it does not
185 // discard input.
186 budget = netUnitBudget
187 s.drain(&budget)
188 if budget == netUnitBudget {
189 t.Fatal("second pass found no work")
190 }
191 }
192 193 // TestRunStopsUnderContinuousInput: a domain with input still arriving must stop
194 // promptly when the breaker closes.
195 //
196 // It does not prove the loop reaches the breaker when the input never drains:
197 // a full channel is emptied inside the pass that observes it, so no client-side
198 // rate can force starvation. That property is checked structurally, by
199 // relay.TestDomainLoopsCheckTheBreaker. This one is the behavioural half: it
200 // would catch a domain that only checks its breaker after the queue empties.
201 func TestRunStopsUnderContinuousInput(t *testing.T) {
202 // Unbuffered on purpose: a blocked sender is always ready to rendezvous, so
203 // every TryRecv in drain succeeds and the loop never runs out of work.
204 feed, srv := tinyspawn.NewDuplex[wire.Inbound]()
205 out, _ := tinyspawn.NewBufferedDuplex[wire.Outbound](64)
206 ready := make(chan wire.Ready, 1)
207 stop := tinyspawn.NewBreaker()
208 209 done := make(chan struct{})
210 go func() {
211 Run(Data{}, Chans{
212 Workers: []WorkerLink{{In: srv, Out: out}},
213 Ready: ready,
214 Stop: stop,
215 })
216 close(done)
217 }()
218 select {
219 case <-ready:
220 case <-time.After(2 * time.Second):
221 t.Fatal("network domain never reported ready")
222 }
223 224 go func() {
225 for {
226 select {
227 case <-stop.Done():
228 return
229 case feed.Tx <- wire.Inbound{Kind: wire.InClosed}:
230 }
231 }
232 }()
233 234 // Let the flood establish itself.
235 time.Sleep(20 * time.Millisecond)
236 237 start := time.Now()
238 stop.Close()
239 select {
240 case <-done:
241 case <-time.After(2 * time.Second):
242 t.Fatalf("network domain did not stop within 2s of the breaker closing")
243 }
244 if elapsed := time.Since(start); elapsed > 250*time.Millisecond {
245 t.Fatalf("network domain took %s to stop under load, want under 250ms", elapsed)
246 }
247 }
248