Added CODE_CONVENTIONS.md and linters to enforce it, and applied it across the codebase

CODE_CONVENTIONS.md sets out the conventions for Go code in this
repository: naming, layout, comments, errors, logging, configuration and
tests. .golangci.json enables the linters that check the parts that can be
checked (each limited to the rules the conventions use); the rest is
applied by hand.

Applied across the codebase:
- Naming: full-word names in application code, initialisms in one case
  (BuyerID, PrintJSON, PrintYAML, ocdsGetBuyerID), no names shadowing
  built-ins (min/max are minGap/maxGap), mustRaw renamed rawJSON as it
  returns nil rather than panicking, and config.ConfigLevelToLogLevel
  renamed LevelToLogLevel.
- Layout: lines kept to 80 characters where possible, assignments taken
  out of if and for statements that don't fit, wrapped arguments all on
  one line or one per line, steps separated by blank lines, no else after
  a return, function and struct literals wrapped.
- Comments: doc comments on every exported name (including each section's
  Map, Flatten, TypeOf, ValueOf and SetValue), section banners, British
  spelling.
- Errors: a created error starts with its package name, a wrapping error
  adds only what was being done, sentinels in one commented var block,
  errors.Is and errors.As in place of == and type assertions, and no
  err := shadowing of a named result. That fixes the mock server losing
  its access log's close error.
- Logging: the fetcher passes its workers an untagged logger, so
  findatender's lines are tagged with their own component rather than
  with fetcher's as well; cmd/mock-fts logs "stopped" with slog.
- Configuration: util.WithTimeout (moved from the websocket package)
  applies a timeout of 0 or less as no limit, used for the websocket
  write and ping, TCP close and tcpserver shutdown timeouts; every setting
  documents what 0 or empty means, including the rate limit rule's keys
  in internal/config/README.md.
- Tests: related tests merged into table-driven ones with named cases.

Separately from CODE_CONVENTIONS.md, internal/store/README.md gains a soft
SQL style convention for the queries in internal/store/queries.go, and the
queries are reformatted to follow it.
This commit is contained in:
bwilliams committed 2026-10-15 16:26:42 +01:00
1 parent 465358609a
commit 67215a6aaa
104 files changed
+3189 -1206

No files matched your search

+18 -23
View File
@@ -12,6 +12,8 @@ import (
"github.com/coder/websocket"
"golang.org/x/time/rate"
"git.avsdev.uk/Go/job-search/internal/util"
)
// clientSendBuffer is how many messages are queued for a client before it
@@ -26,7 +28,9 @@ const logMessageLimit = 1 << 10
// *websocket.Conn, or a tcpConn for plain TCP clients (see tcp.go).
type msgConn interface {
Read(ctx context.Context) (websocket.MessageType, []byte, error)
Write(ctx context.Context, messageType websocket.MessageType, payload []byte) error
Write(
ctx context.Context, messageType websocket.MessageType, payload []byte,
) error
Ping(ctx context.Context) error
Close(code websocket.StatusCode, reason string) error
CloseNow() error
@@ -49,7 +53,7 @@ type client struct {
// errUnsupportedData is returned by readLoop (and a tcpConn's Write) for a
// binary message.
var errUnsupportedData = errors.New("binary frames are not supported")
var errUnsupportedData = errors.New("websocket: binary frames are not supported")
// newClient creates a client for conn. cancel cancels the context the client
// runs with; the client calls it when it finishes or is closed. The client's
@@ -59,10 +63,7 @@ func newClient(
) *client {
limiter := rate.NewLimiter(rate.Inf, 0)
if rule := hub.conf.MessageRateLimit; rule.Enabled && rule.PerSecond > 0 {
limiter = rate.NewLimiter(
rate.Limit(rule.PerSecond),
max(rule.Burst, 1),
)
limiter = rate.NewLimiter(rate.Limit(rule.PerSecond), max(rule.Burst, 1))
}
client := &client{
@@ -95,7 +96,7 @@ func (c *client) run(ctx context.Context) {
c.sendEnvelope(Envelope{
Type: TypeWelcome,
Payload: mustRaw(map[string]any{
Payload: rawJSON(map[string]any{
"clientId": c.id,
}),
})
@@ -129,16 +130,20 @@ func (c *client) readLoop(ctx context.Context) error {
if err != nil {
return err
}
c.logMessage(ctx, "message received", data)
c.lastSeen.Store(time.Now().UnixNano())
if messageType != websocket.MessageText {
return errUnsupportedData
}
// Check if the client is rate limited for early discard
if !c.limiter.Allow() {
c.sendError("", "rate limited")
continue
}
// Unpack the envelope and pass to handle to process if valid
var envelope Envelope
if err := json.Unmarshal(data, &envelope); err != nil {
@@ -157,7 +162,7 @@ func (c *client) handle(envelope Envelope) {
c.sendEnvelope(Envelope{
Type: TypePong,
ID: envelope.ID,
Payload: mustRaw(map[string]any{"time": time.Now().UTC()}),
Payload: rawJSON(map[string]any{"time": time.Now().UTC()}),
})
case TypeEcho:
@@ -180,7 +185,7 @@ func (c *client) writeLoop(ctx context.Context) {
case <-ctx.Done():
return
case msg := <-c.send:
writeCtx, cancel := withTimeout(ctx, c.hub.conf.WriteTimeout)
writeCtx, cancel := util.WithTimeout(ctx, c.hub.conf.WriteTimeout)
err := c.conn.Write(writeCtx, websocket.MessageText, msg)
cancel()
if err != nil {
@@ -217,7 +222,7 @@ func (c *client) pingLoop(ctx context.Context) {
if time.Now().Before(lastSeen.Add(pingInterval)) {
continue
}
pingCtx, cancel := withTimeout(ctx, pongTimeout)
pingCtx, cancel := util.WithTimeout(ctx, pongTimeout)
err := c.conn.Ping(pingCtx)
cancel()
if err != nil {
@@ -283,29 +288,19 @@ func (c *client) logMessage(ctx context.Context, event string, data []byte) {
if !logger.Enabled(ctx, slog.LevelDebug) {
return
}
logged, truncated := data, false
if len(logged) > logMessageLimit {
logged, truncated = logged[:logMessageLimit], true
}
logger.LogAttrs(
ctx,
slog.LevelDebug,
event,
event, //nolint:sloglint // a constant message from the caller
slog.String("client", c.id),
slog.Int("bytes", len(data)),
slog.String("message", string(logged)),
slog.Bool("truncated", truncated),
)
}
// withTimeout returns ctx with the timeout applied, or ctx itself if the
// timeout is 0 or less (no limit).
func withTimeout(
ctx context.Context, timeout time.Duration,
) (context.Context, context.CancelFunc) {
if timeout <= 0 {
return ctx, func() {
}
}
return context.WithTimeout(ctx, timeout)
}
+19 -20
View File
@@ -34,7 +34,9 @@ func (f *fakeConn) Read(ctx context.Context) (ws.MessageType, []byte, error) {
return 0, nil, ctx.Err()
}
func (f *fakeConn) Write(context.Context, ws.MessageType, []byte) error { return nil }
func (f *fakeConn) Write(context.Context, ws.MessageType, []byte) error {
return nil
}
func (f *fakeConn) Ping(context.Context) error { return nil }
@@ -102,8 +104,10 @@ func TestSendEnvelopeSlowConsumer(t *testing.T) {
func TestClientCloseOnce(t *testing.T) {
f := newFakeConn()
c, _ := newTestClient(f)
c.close(ws.StatusGoingAway, "bye")
c.close(ws.StatusNormalClosure, "again")
if code := <-f.closed; code != ws.StatusGoingAway {
t.Errorf("closed with %v; want going away", code)
}
@@ -147,12 +151,17 @@ func TestClientMessageRateLimit(t *testing.T) {
})
c.limiter.Allow()
if limited := !c.limiter.Allow(); limited != tt.limited {
t.Errorf("rule %+v: second message limited = %v; want %v", tt.rule, limited, tt.limited)
t.Errorf(
"rule %+v: second message limited = %v; want %v",
tt.rule,
limited,
tt.limited,
)
}
}
}
func TestMustRaw(t *testing.T) {
func TestRawJSON(t *testing.T) {
raw := json.RawMessage(`{"a":1}`)
tests := []struct {
name string
@@ -166,25 +175,12 @@ func TestMustRaw(t *testing.T) {
}, ""},
}
for _, tt := range tests {
if got := string(mustRaw(tt.v)); got != tt.want {
t.Errorf("%s: mustRaw = %q; want %q", tt.name, got, tt.want)
if got := string(rawJSON(tt.v)); got != tt.want {
t.Errorf("%s: rawJSON = %q; want %q", tt.name, got, tt.want)
}
}
}
func TestWithTimeout(t *testing.T) {
ctx, cancel := withTimeout(context.Background(), 0)
defer cancel()
if _, ok := ctx.Deadline(); ok {
t.Error("timeout 0 set a deadline")
}
ctx, cancel = withTimeout(context.Background(), time.Minute)
defer cancel()
if _, ok := ctx.Deadline(); !ok {
t.Error("timeout 1m set no deadline")
}
}
// syncBuffer is a bytes.Buffer safe for the client's goroutines to log to.
type syncBuffer struct {
mu sync.Mutex
@@ -202,6 +198,7 @@ func (b *syncBuffer) entries(t *testing.T) []map[string]any {
t.Helper()
b.mu.Lock()
defer b.mu.Unlock()
var entries []map[string]any
for line := range strings.Lines(b.buf.String()) {
var e map[string]any
@@ -210,6 +207,7 @@ func (b *syncBuffer) entries(t *testing.T) []map[string]any {
}
entries = append(entries, e)
}
return entries
}
@@ -283,8 +281,9 @@ func TestLogMessageLimit(t *testing.T) {
t.Fatalf("logged %d entries; want 1", len(entries))
}
e := entries[0]
if e["message"] != long[:logMessageLimit] || e["bytes"] != float64(len(long)) ||
e["truncated"] != true || e["client"] != c.id {
if e["message"] != long[:logMessageLimit] ||
e["bytes"] != float64(len(long)) || e["truncated"] != true ||
e["client"] != c.id {
t.Errorf("entry = %v", e)
}
+11 -2
View File
@@ -38,10 +38,12 @@ func dialWS(t *testing.T, ctx context.Context, url string) *ws.Conn {
t.Cleanup(func() {
conn.CloseNow()
})
var e Envelope
if err := wsjson.Read(ctx, conn, &e); err != nil || e.Type != TypeWelcome {
t.Fatalf("want welcome, got %+v, %v", e, err)
}
return conn
}
@@ -66,7 +68,8 @@ func TestHTTPMessages(t *testing.T) {
t.Fatal(err)
}
var e Envelope
if err := wsjson.Read(ctx, conn, &e); err != nil || e.Type != TypePong || e.ID != "1" {
if err := wsjson.Read(ctx, conn, &e); err != nil || e.Type != TypePong ||
e.ID != "1" {
t.Fatalf("want pong 1, got %+v, %v", e, err)
}
}
@@ -75,6 +78,7 @@ func TestHTTPMessages(t *testing.T) {
func TestPushReachesBothTransports(t *testing.T) {
h, addr := tcpHub(t, nil)
url := wsHub(t, h)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
conn := dialWS(t, ctx, url)
@@ -155,7 +159,8 @@ func TestHTTPMessageRateLimit(t *testing.T) {
}
}
var e Envelope
if err := wsjson.Read(ctx, conn, &e); err != nil || e.Type != TypePong || e.ID != "1" {
if err := wsjson.Read(ctx, conn, &e); err != nil || e.Type != TypePong ||
e.ID != "1" {
t.Fatalf("first: want pong 1, got %+v, %v", e, err)
}
err := wsjson.Read(ctx, conn, &e)
@@ -173,11 +178,13 @@ func TestHTTPNotAnUpgrade(t *testing.T) {
h := NewHub(config.JSCServerWebSocket{}, WithLogger(discardLog))
srv := httptest.NewServer(h)
defer srv.Close()
res, err := http.Get(srv.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if res.StatusCode < 400 {
t.Errorf("status = %d; want an error", res.StatusCode)
}
@@ -194,6 +201,7 @@ func TestHTTPRefusedAfterShutdown(t *testing.T) {
if err := h.Shutdown(context.Background()); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
conn, _, err := ws.Dial(ctx, url, nil)
@@ -201,6 +209,7 @@ func TestHTTPRefusedAfterShutdown(t *testing.T) {
t.Fatalf("dial: %v", err)
}
defer conn.CloseNow()
if _, _, err := conn.Read(ctx); ws.CloseStatus(err) != ws.StatusGoingAway {
t.Fatalf("read = %v; want close 1001", err)
}
+8 -1
View File
@@ -91,7 +91,11 @@ func (h *Hub) Push(msgType string, payload any) {
h.mu.RUnlock()
for _, client := range slow {
h.logger().Warn("dropping slow client", "client", client.id, "ip", client.ip)
h.logger().Warn(
"dropping slow client",
"client", client.id,
"ip", client.ip,
)
go client.close(ws.StatusPolicyViolation, "slow consumer")
}
}
@@ -166,11 +170,14 @@ func (h *Hub) maxMessageSize() int {
func (h *Hub) register(client *client) bool {
h.mu.Lock()
defer h.mu.Unlock()
if h.closed {
return false
}
h.clients[client] = struct{}{}
h.wg.Add(1)
return true
}
+9 -1
View File
@@ -21,16 +21,19 @@ func pipeClient(t *testing.T, h *Hub) (net.Conn, chan struct{}) {
server.Close()
peer.Close()
})
done := make(chan struct{})
go func() {
h.ServeTCP(context.Background(), server)
close(done)
}()
peer.SetReadDeadline(time.Now().Add(time.Second))
if _, err := bufio.NewReader(peer).ReadString('\n'); err != nil {
t.Fatalf("welcome: %v", err)
}
waitCount(t, h, 1)
return peer, done
}
@@ -100,7 +103,12 @@ func TestMaxMessageSize(t *testing.T) {
for _, tt := range tests {
h := NewHub(tt.conf, WithLogger(discardLog))
if got := h.maxMessageSize(); got != tt.want {
t.Errorf("maxMessageSize(%d) = %d; want %d", tt.conf.MaxMessageSize, got, tt.want)
t.Errorf(
"maxMessageSize(%d) = %d; want %d",
tt.conf.MaxMessageSize,
got,
tt.want,
)
}
}
}
+3 -2
View File
@@ -55,15 +55,16 @@ const (
TypeError = "error"
)
// mustRaw returns value as raw JSON: value itself if it is already
// rawJSON returns value as raw JSON: value itself if it is already
// json.RawMessage, nil if value is nil or can't be marshalled.
func mustRaw(value any) json.RawMessage {
func rawJSON(value any) json.RawMessage {
if value == nil {
return nil
}
if raw, ok := value.(json.RawMessage); ok {
return raw
}
encoded, err := json.Marshal(value)
if err != nil {
return nil
+24 -12
View File
@@ -13,6 +13,8 @@ import (
"time"
ws "github.com/coder/websocket"
"git.avsdev.uk/Go/job-search/internal/util"
)
// Plain TCP clients join the hub as if they were WebSocket clients. Instead
@@ -55,7 +57,8 @@ func (h *Hub) ServeTCP(ctx context.Context, newConn net.Conn) {
}
ip := ""
if addrPort, err := netip.ParseAddrPort(newConn.RemoteAddr().String()); err == nil {
addrPort, err := netip.ParseAddrPort(newConn.RemoteAddr().String())
if err == nil {
ip = addrPort.Addr().Unmap().String()
}
@@ -71,10 +74,20 @@ func (h *Hub) ServeTCP(ctx context.Context, newConn net.Conn) {
}
defer h.unregister(client)
h.logger().Info("client connected", "client", client.id, "ip", ip, "transport", "tcp")
h.logger().Info(
"client connected",
"client", client.id,
"ip", ip,
"transport", "tcp",
)
client.run(ctx)
conn.CloseNow() //nolint:errcheck,gosec // finished with; it may already be closed
h.logger().Info("client disconnected", "client", client.id, "ip", ip, "transport", "tcp")
h.logger().Info(
"client disconnected",
"client", client.id,
"ip", ip,
"transport", "tcp",
)
}
// ---------- tcpConn ----------
@@ -88,7 +101,7 @@ type tcpConn struct {
scan *bufio.Scanner
closeTimeout time.Duration // caps Close's message; 0 or less for none
wm sync.Mutex // serialises writes
writeMu sync.Mutex // serialises writes
closeOnce sync.Once // records the first close
closed chan struct{} // closed by the first Close or CloseNow
@@ -153,6 +166,7 @@ func (t *tcpConn) Read(ctx context.Context) (ws.MessageType, []byte, error) {
t.Close(ws.StatusMessageTooBig, "message too long") //nolint:errcheck,gosec // dropped anyway
return 0, nil, t.closeErr
}
return 0, nil, err
}
@@ -185,12 +199,9 @@ func (t *tcpConn) Close(code ws.StatusCode, reason string) error {
return nil
}
ctx := context.Background()
if t.closeTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, t.closeTimeout)
defer cancel()
}
// No deadline if closeTimeout is 0 or less.
ctx, cancel := util.WithTimeout(context.Background(), t.closeTimeout)
defer cancel()
message, err := json.Marshal(Envelope{
Type: TypeError,
@@ -203,6 +214,7 @@ func (t *tcpConn) Close(code ws.StatusCode, reason string) error {
if err := t.conn.Close(); err != nil && !errors.Is(err, net.ErrClosed) {
return err
}
return nil
}
@@ -244,8 +256,8 @@ func (t *tcpConn) isClosed() bool {
// write writes data whole, giving up at ctx's deadline or when ctx is
// cancelled.
func (t *tcpConn) write(ctx context.Context, data []byte) error {
t.wm.Lock()
defer t.wm.Unlock()
t.writeMu.Lock()
defer t.writeMu.Unlock()
deadline, _ := ctx.Deadline() // zero means none
if err := t.conn.SetWriteDeadline(deadline); err != nil {
+36 -8
View File
@@ -18,11 +18,13 @@ import (
"git.avsdev.uk/Go/job-search/internal/config"
)
var discardLog = slog.New(slog.NewTextHandler(io.Discard, nil))
var discardLog = slog.New(slog.DiscardHandler)
// tcpHub starts a hub serving plain TCP clients, via ServeTCP, on a local
// port and returns it with the address. It is shut down when the test ends.
func tcpHub(t *testing.T, mutate func(*config.JSCServerWebSocket)) (*Hub, string) {
func tcpHub(
t *testing.T, mutate func(*config.JSCServerWebSocket),
) (*Hub, string) {
t.Helper()
conf := config.JSCServerWebSocket{
MaxMessageSize: 1 << 10,
@@ -31,11 +33,13 @@ func tcpHub(t *testing.T, mutate func(*config.JSCServerWebSocket)) (*Hub, string
if mutate != nil {
mutate(&conf)
}
h := NewHub(conf, WithLogger(discardLog))
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
go func() {
for {
@@ -46,6 +50,7 @@ func tcpHub(t *testing.T, mutate func(*config.JSCServerWebSocket)) (*Hub, string
go h.ServeTCP(ctx, conn)
}
}()
t.Cleanup(func() {
ln.Close()
sctx, scancel := context.WithTimeout(context.Background(), time.Second)
@@ -53,6 +58,7 @@ func tcpHub(t *testing.T, mutate func(*config.JSCServerWebSocket)) (*Hub, string
h.Shutdown(sctx)
cancel()
})
return h, ln.Addr().String()
}
@@ -94,10 +100,12 @@ func (c *tcpClient) read() Envelope {
if err != nil {
c.t.Fatalf("read: %v (got %q)", err, line)
}
var env Envelope
if err := json.Unmarshal([]byte(line), &env); err != nil {
c.t.Fatalf("bad envelope %q: %v", line, err)
}
return env
}
@@ -107,7 +115,8 @@ func (c *tcpClient) read() Envelope {
func (c *tcpClient) waitClosed() {
c.t.Helper()
c.conn.SetReadDeadline(time.Now().Add(time.Second))
if _, err := io.ReadAll(c.r); err != nil && !errors.Is(err, syscall.ECONNRESET) {
if _, err := io.ReadAll(c.r); err != nil &&
!errors.Is(err, syscall.ECONNRESET) {
c.t.Fatalf("connection not closed: %v", err)
}
}
@@ -139,7 +148,8 @@ func TestTCPMessages(t *testing.T) {
t.Fatalf("want pong 1, got %+v", e)
}
c.send(`{"type":"echo","id":"2","payload":{"a":1}}` + "\n")
if e := c.read(); e.Type != TypeEcho || e.ID != "2" || string(e.Payload) != `{"a":1}` {
if e := c.read(); e.Type != TypeEcho || e.ID != "2" ||
string(e.Payload) != `{"a":1}` {
t.Fatalf("want echo 2, got %+v", e)
}
c.send("not json\n")
@@ -153,7 +163,8 @@ func TestTCPMessages(t *testing.T) {
// Pushed messages reach TCP clients.
h.Push("item.created", map[string]string{"id": "x"})
if e := c.read(); e.Type != "item.created" || string(e.Payload) != `{"id":"x"}` {
if e := c.read(); e.Type != "item.created" ||
string(e.Payload) != `{"id":"x"}` {
t.Fatalf("want item.created, got %+v", e)
}
}
@@ -164,10 +175,12 @@ func TestTCPNoWriteTimeout(t *testing.T) {
_, addr := tcpHub(t, func(c *config.JSCServerWebSocket) {
c.WriteTimeout = 0
})
c := dialTCP(t, addr)
if e := c.read(); e.Type != TypeWelcome {
t.Fatalf("want welcome, got %+v", e)
}
c.send(`{"type":"ping","id":"1"}` + "\n")
if e := c.read(); e.Type != TypePong {
t.Fatalf("want pong, got %+v", e)
@@ -179,6 +192,7 @@ func TestTCPClientDisconnect(t *testing.T) {
c := dialTCP(t, addr)
c.read() // welcome
waitCount(t, h, 1)
c.conn.Close()
waitCount(t, h, 0)
}
@@ -190,6 +204,7 @@ func TestTCPLineTooLong(t *testing.T) {
})
c := dialTCP(t, addr)
c.read() // welcome
c.send(`{"type":"echo","payload":"` + strings.Repeat("x", 100) + `"}` + "\n")
c.waitClosed()
waitCount(t, h, 0)
@@ -214,7 +229,8 @@ func TestTCPShutdown(t *testing.T) {
c.waitClosed()
late := dialTCP(t, addr)
if e := late.read(); e.Type != TypeError || e.Error != "server shutting down" {
if e := late.read(); e.Type != TypeError ||
e.Error != "server shutting down" {
t.Fatalf("late client: want shutdown error, got %+v", e)
}
late.waitClosed()
@@ -229,11 +245,13 @@ func TestTCPPing(t *testing.T) {
})
c := dialTCP(t, addr)
c.read() // welcome
c.conn.SetReadDeadline(time.Now().Add(time.Second))
line, err := c.r.ReadString('\n')
if err != nil || line != "\n" {
t.Fatalf("want a blank ping line, got %q, %v", line, err)
}
for i := range 5 {
c.send(`{"type":"ping"}` + "\n")
for {
@@ -291,12 +309,14 @@ func TestTCPNoPongTimeout(t *testing.T) {
})
c := dialTCP(t, addr)
c.read() // welcome
for range 3 {
c.conn.SetReadDeadline(time.Now().Add(time.Second))
if line, err := c.r.ReadString('\n'); err != nil || line != "\n" {
t.Fatalf("want a blank ping line, got %q, %v", line, err)
}
}
waitCount(t, h, 1)
}
@@ -307,7 +327,9 @@ func TestTCPDefaultMessageSize(t *testing.T) {
})
c := dialTCP(t, addr)
c.read() // welcome
c.send(`{"type":"echo","id":"1","payload":"` + strings.Repeat("x", 4096) + `"}` + "\n")
payload := strings.Repeat("x", 4096)
c.send(`{"type":"echo","id":"1","payload":"` + payload + `"}` + "\n")
if e := c.read(); e.Type != TypeEcho || e.ID != "1" {
t.Fatalf("want echo, got %+v", e)
}
@@ -333,10 +355,12 @@ func TestTCPConnRead(t *testing.T) {
io.WriteString(peer, "\r\n{\"a\":1}\r\n")
peer.Close()
}()
typ, data, err := tc.Read(context.Background())
if err != nil || typ != ws.MessageText || string(data) != `{"a":1}` {
t.Fatalf("Read = %v, %q, %v", typ, data, err)
}
// The peer closing is a normal closure.
_, _, err = tc.Read(context.Background())
if ws.CloseStatus(err) != ws.StatusNormalClosure {
@@ -370,17 +394,21 @@ func TestTCPConnClose(t *testing.T) {
line, _ := bufio.NewReader(peer).ReadString('\n')
got <- line
}()
if err := tc.Close(ws.StatusGoingAway, "bye"); err != nil {
t.Fatalf("Close: %v", err)
}
if line := <-got; line != `{"type":"error","error":"bye"}`+"\n" {
t.Errorf("peer got %q", line)
}
_, _, err := tc.Read(context.Background())
var ce ws.CloseError
if !errors.As(err, &ce) || ce.Code != ws.StatusGoingAway || ce.Reason != "bye" {
if !errors.As(err, &ce) || ce.Code != ws.StatusGoingAway ||
ce.Reason != "bye" {
t.Errorf("Read after Close = %v; want going away, bye", err)
}
if err := tc.Close(ws.StatusNormalClosure, "again"); err != nil {
t.Errorf("second Close: %v", err)
}
+8 -9
View File
@@ -17,6 +17,7 @@ import (
"git.avsdev.uk/Go/job-search/internal/config"
"git.avsdev.uk/Go/job-search/internal/middleware"
"git.avsdev.uk/Go/job-search/internal/util"
"git.avsdev.uk/Go/job-search/internal/websocket"
)
@@ -64,7 +65,7 @@ func (s *Server) logger() *slog.Logger {
if log == nil {
log = slog.Default()
}
return log.With("component", "tcp")
return log.With("component", "tcp_server")
}
// Run listens on the configured host and port and serves plain TCP clients
@@ -102,19 +103,17 @@ func (s *Server) serve(ctx context.Context, listen net.Listener) error {
listen.Close() //nolint:errcheck,gosec // closed already when ctx was cancelled
s.logger().Info("shutting down")
shutdownCtx := context.Background()
if s.conf.Timeouts.ShutdownTimeout > 0 {
var cancel context.CancelFunc
shutdownCtx, cancel = context.WithTimeout(
shutdownCtx, s.conf.Timeouts.ShutdownTimeout,
)
defer cancel()
}
// No deadline if the shutdown timeout is 0 or less.
shutdownCtx, cancel := util.WithTimeout(
context.Background(), s.conf.Timeouts.ShutdownTimeout,
)
defer cancel()
errs := []error{acceptErr}
if err := s.hub.Shutdown(shutdownCtx); err != nil {
errs = append(errs, fmt.Errorf("websocket shutdown: %w", err))
}
return errors.Join(errs...)
}
+23 -7
View File
@@ -17,7 +17,7 @@ import (
"git.avsdev.uk/Go/job-search/internal/websocket"
)
var discardLog = slog.New(slog.NewTextHandler(io.Discard, nil))
var discardLog = slog.New(slog.DiscardHandler)
// testConf is a server configuration for tests, changed by mutate if it is
// not nil.
@@ -55,12 +55,14 @@ func startServer(
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
done := make(chan error, 1)
go func() {
done <- s.serve(ctx, ln)
}()
return h, ln.Addr().String(), cancel, done
}
@@ -95,10 +97,12 @@ func (c *tcpClient) read() websocket.Envelope {
if err != nil {
c.t.Fatalf("read: %v (got %q)", err, line)
}
var env websocket.Envelope
if err := json.Unmarshal([]byte(line), &env); err != nil {
c.t.Fatalf("bad envelope %q: %v", line, err)
}
return env
}
@@ -107,7 +111,8 @@ func (c *tcpClient) read() websocket.Envelope {
func (c *tcpClient) waitClosed() {
c.t.Helper()
c.conn.SetReadDeadline(time.Now().Add(time.Second))
if _, err := io.ReadAll(c.r); err != nil && !errors.Is(err, syscall.ECONNRESET) {
if _, err := io.ReadAll(c.r); err != nil &&
!errors.Is(err, syscall.ECONNRESET) {
c.t.Fatalf("connection not closed: %v", err)
}
}
@@ -129,7 +134,8 @@ func TestServerShutdown(t *testing.T) {
}
cancel()
if e := c.read(); e.Type != websocket.TypeError || e.Error != "server shutting down" {
if e := c.read(); e.Type != websocket.TypeError ||
e.Error != "server shutting down" {
t.Fatalf("want shutdown error, got %+v", e)
}
c.waitClosed()
@@ -152,7 +158,9 @@ func TestServerShutdown(t *testing.T) {
func TestServerConnectionLimit(t *testing.T) {
conf := testConf(func(c *config.JSCServer) {
c.WebSocket.ConnectionLimit = config.JSCRateLimitRule{
Enabled: true, PerSecond: 1, Burst: 1,
Enabled: true,
PerSecond: 1,
Burst: 1,
}
c.RateLimits.IdleTTL = time.Minute
})
@@ -164,7 +172,8 @@ func TestServerConnectionLimit(t *testing.T) {
t.Fatalf("first: want welcome, got %+v", e)
}
second := dial(t, addr)
if e := second.read(); e.Type != websocket.TypeError || e.Error != "rate limited" {
if e := second.read(); e.Type != websocket.TypeError ||
e.Error != "rate limited" {
t.Fatalf("second: want rate limited, got %+v", e)
}
second.waitClosed()
@@ -203,7 +212,8 @@ func TestServerRunListenError(t *testing.T) {
s, _ := newServer(testConf(func(c *config.JSCServer) {
c.Port = -1
}))
if err := s.Run(context.Background()); err == nil || !strings.Contains(err.Error(), "listen") {
if err := s.Run(context.Background()); err == nil ||
!strings.Contains(err.Error(), "listen") {
t.Fatalf("Run = %v; want a listen error", err)
}
}
@@ -231,13 +241,17 @@ func TestServerAcceptRetries(t *testing.T) {
t.Fatal(err)
}
defer ln.Close()
fl := &flakyListener{
Listener: ln,
fails: 3,
}
err = s.accept(context.Background(), context.Background(), fl)
if !errors.Is(err, net.ErrClosed) || fl.fails != 0 {
t.Fatalf("accept = %v with %d failures left; want net.ErrClosed", err, fl.fails)
t.Fatalf(
"accept = %v with %d failures left; want net.ErrClosed", err, fl.fails,
)
}
}
@@ -249,11 +263,13 @@ func TestServerAcceptCancelledInBackOff(t *testing.T) {
t.Fatal(err)
}
defer ln.Close()
ctx, cancel := context.WithCancel(context.Background())
fl := &flakyListener{
Listener: ln,
fails: 1 << 30,
}
time.AfterFunc(20*time.Millisecond, cancel)
if err := s.accept(ctx, ctx, fl); !errors.Is(err, context.Canceled) {
t.Fatalf("accept = %v; want context.Canceled", err)