aboutsummaryrefslogtreecommitdiff
path: root/internal/net/server_test.go
blob: 6a3b3768a08bcb6bf4779780f8e4de0390a45280 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package net

import (
	"bytes"
	"errors"
	"io"
	"net"
	"strings"
	"sync"
	"testing"
	"time"
)

func TestHubConcurrency(t *testing.T) {
	h := NewHub()
	h.OnRemove(func(s *Session) {})

	var wg sync.WaitGroup
	const n = 50

	for i := 0; i < n; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			s := &Session{}
			h.Add(s)
			h.EnterRoom(s, 1)
			h.PlayersInRoom(1)
			h.LeaveRoom(s)
			h.HardRemove(s)
		}()
	}

	for i := 0; i < n; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			h.AllSessions()
		}()
	}

	wg.Wait()
}

type testConn struct{ data []byte }

func (c *testConn) ReadMessage() (string, error)     { return "", nil }
func (c *testConn) Write(b []byte) (int, error)      { c.data = append(c.data, b...); return len(b), nil }
func (c *testConn) SetWriteDeadline(time.Time) error { return nil }

func (c *testConn) Close() error       { return nil }
func (c *testConn) SetEcho(bool) error { return nil }

// fakeNetConn is a net.Conn stub for the session read loop: Read reports the
// peer hung up so the read loop ends immediately, Write captures what the
// server sent, and read deadlines are recorded so a test can assert the
// transport was armed.
type fakeNetConn struct {
	mu       sync.Mutex
	written  bytes.Buffer
	deadline time.Time
}

func newFakeNetConn() *fakeNetConn { return &fakeNetConn{} }

func (c *fakeNetConn) Read([]byte) (int, error) { return 0, io.EOF }

func (c *fakeNetConn) Write(b []byte) (int, error) {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.written.Write(b)
}

func (c *fakeNetConn) Close() error { return nil }

func (c *fakeNetConn) LocalAddr() net.Addr  { return nil }
func (c *fakeNetConn) RemoteAddr() net.Addr { return nil }

func (c *fakeNetConn) SetDeadline(t time.Time) error { return c.SetReadDeadline(t) }

func (c *fakeNetConn) SetReadDeadline(t time.Time) error {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.deadline = t
	return nil
}

func (c *fakeNetConn) SetWriteDeadline(time.Time) error { return nil }

func (c *fakeNetConn) output() string {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.written.String()
}

func (c *fakeNetConn) readDeadline() time.Time {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.deadline
}

// TestEnterRoomClearsCasinoWatch: detailed table watch is scoped to the room
// it was set in, so entering a room stops a stale watch instead of silently
// resuming it when the player returns.
func TestEnterRoomClearsCasinoWatch(t *testing.T) {
	h := NewHub()
	s := &Session{}
	h.Add(s)
	s.CasinoWatchRoom = 7
	s.CasinoWatchTable = "bj1"
	h.EnterRoom(s, 9)
	if s.CasinoWatchRoom != 0 || s.CasinoWatchTable != "" {
		t.Fatalf("watch survived a room change: room=%d table=%q", s.CasinoWatchRoom, s.CasinoWatchTable)
	}
}

// TestConnectionCapRefusalKeepsTheServerDrained: at maxConnections a new
// connection is refused without holding a slot (the counter stays at the cap),
// and the refused peer is told why. Once the admitted sessions end, the live
// count is back to zero.
func TestConnectionCapRefusalKeepsTheServerDrained(t *testing.T) {
	s := &Server{hub: NewHub()}
	s.handler = func(*Session, string) {}

	for i := 0; i < maxConnections; i++ {
		if !s.admitConnection() {
			t.Fatalf("connection %d of %d refused below the cap", i+1, maxConnections)
		}
	}

	refused := newFakeNetConn()
	s.handleSession(&Session{Conn: newTCPConn(refused)}, s.handler)

	if got := s.conns.Load(); got != maxConnections {
		t.Fatalf("live connection count after a refusal = %d, want %d (the refused connection held a slot)", got, maxConnections)
	}
	if !strings.Contains(refused.output(), "full capacity") {
		t.Fatalf("refused connection was not told the server is full: %q", refused.output())
	}

	for i := 0; i < maxConnections; i++ {
		s.releaseConnection()
	}
	if got := s.conns.Load(); got != 0 {
		t.Fatalf("live connection count after every session ended = %d, want 0", got)
	}
}

// TestAdmittedSessionReleasesItsSlot: an admitted session whose client hangs
// up returns its slot, so a client cannot leak capacity by disconnecting.
func TestAdmittedSessionReleasesItsSlot(t *testing.T) {
	s := &Server{hub: NewHub()}
	s.handler = func(*Session, string) {}

	s.handleSession(&Session{Conn: newTCPConn(newFakeNetConn())}, s.handler)

	if got := s.conns.Load(); got != 0 {
		t.Fatalf("live connection count after the session ended = %d, want 0", got)
	}
}

// TestArmReadDeadlineArmsTheTransport: the idle window is applied to the real
// transport (not just computed), and the window itself depends on the protocol
// state: pre-auth prompts get the short one.
func TestArmReadDeadlineArmsTheTransport(t *testing.T) {
	rec := newFakeNetConn()
	sess := &Session{Conn: newTCPConn(rec)}

	before := time.Now()
	armReadDeadline(sess, loginReadTimeout)
	got := rec.readDeadline()
	if got.Before(before.Add(loginReadTimeout)) || got.After(time.Now().Add(loginReadTimeout)) {
		t.Fatalf("armed read deadline = %v, want about %v", got, before.Add(loginReadTimeout))
	}

	sess.SetState(StateAccountName)
	if got := sessionIdleTimeout(sess); got != loginReadTimeout {
		t.Fatalf("account-name window = %v, want %v", got, loginReadTimeout)
	}
	sess.SetState(StatePassword)
	if got := sessionIdleTimeout(sess); got != loginReadTimeout {
		t.Fatalf("password window = %v, want %v", got, loginReadTimeout)
	}
	sess.SetState(StateGame)
	if got := sessionIdleTimeout(sess); got != idleReadTimeout {
		t.Fatalf("in-game window = %v, want %v", got, idleReadTimeout)
	}
}

// TestIdleSessionDroppedWithoutAffectingActiveOne: an idle socket is dropped
// once its armed read deadline expires, while a client that keeps sending
// messages survives well past that window because every read re-arms the
// deadline.
func TestIdleSessionDroppedWithoutAffectingActiveOne(t *testing.T) {
	s := &Server{hub: NewHub()}
	var mu sync.Mutex
	served := 0
	s.handler = func(*Session, string) {
		mu.Lock()
		served++
		mu.Unlock()
	}
	const window = 200 * time.Millisecond
	s.idleTimeout = func(*Session) time.Duration { return window }

	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	defer ln.Close()
	go func() {
		for {
			conn, err := ln.Accept()
			if err != nil {
				return
			}
			sess := &Session{Conn: newTCPConn(conn)}
			sess.SetState(StateAccountName)
			s.hub.Add(sess)
			go s.handleSession(sess, s.handler)
		}
	}()

	idle, err := net.Dial("tcp", ln.Addr().String())
	if err != nil {
		t.Fatal(err)
	}
	defer idle.Close()
	active, err := net.Dial("tcp", ln.Addr().String())
	if err != nil {
		t.Fatal(err)
	}
	defer active.Close()

	// The active client talks for five windows' worth of messages: it can only
	// be served to the end if each message re-armed its read deadline.
	sent := 10
	done := make(chan struct{})
	go func() {
		defer close(done)
		for i := 0; i < sent; i++ {
			if _, err := active.Write([]byte("look\r\n")); err != nil {
				return
			}
			time.Sleep(window / 4)
		}
	}()

	// The silent client is dropped: its socket is closed by the server as soon
	// as the armed deadline expires.
	if err := idle.SetReadDeadline(time.Now().Add(10 * window)); err != nil {
		t.Fatal(err)
	}
	buf := make([]byte, 4096)
	for {
		n, err := idle.Read(buf)
		if n > 0 {
			continue
		}
		if err == nil {
			continue
		}
		if errors.Is(err, io.EOF) {
			break
		}
		t.Fatalf("idle client was not dropped after its read deadline: %v", err)
	}

	<-done
	mu.Lock()
	got := served
	mu.Unlock()
	if got < sent-2 {
		t.Fatalf("the active client was served %d of %d messages; its read deadline was not re-armed per message", got, sent)
	}
}

func TestSessionWriteConcurrency(t *testing.T) {
	conn := &testConn{}
	sess := &Session{Conn: conn}

	var wg sync.WaitGroup
	const n = 50

	for i := 0; i < n; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			sess.Write("hello")
			sess.WriteLine("world")
			sess.Writef("formatted %d", 42)
		}()
	}

	wg.Wait()
}