Skip to content

Commit 2d7c074

Browse files
committed
Non-blocking subscriber teardown
1 parent 9d5cb2c commit 2d7c074

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

pkg/server/server.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ func (s *Server) Emit(ctx context.Context, e *models.Event, asJSON, compBytes []
296296
defer sub.lk.Unlock()
297297

298298
// Don't emit events to subscribers that are replaying and are too far behind
299-
if sub.cursor != nil && sub.seq < e.TimeUS-cutoverThresholdUS {
299+
if sub.cursor != nil && sub.seq < e.TimeUS-cutoverThresholdUS || sub.tearingDown {
300300
return
301301
}
302302

pkg/server/subscriber.go

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,15 @@ type WantedCollections struct {
2020
}
2121

2222
type Subscriber struct {
23-
ws *websocket.Conn
24-
conLk sync.Mutex
25-
realIP string
26-
lk sync.Mutex
27-
seq int64
28-
outbox chan *[]byte
29-
hello chan struct{}
30-
id int64
23+
ws *websocket.Conn
24+
conLk sync.Mutex
25+
realIP string
26+
lk sync.Mutex
27+
seq int64
28+
outbox chan *[]byte
29+
hello chan struct{}
30+
id int64
31+
tearingDown bool
3132

3233
// Subscriber options
3334

@@ -99,11 +100,16 @@ func emitToSubscriber(ctx context.Context, log *slog.Logger, sub *Subscriber, ti
99100
default:
100101
// Drop slow subscribers if they're live tailing and fall too far behind
101102
log.Error("failed to send event to subscriber, dropping", "error", "buffer full", "subscriber", sub.id)
102-
sub.Terminate("consuming too slowly")
103-
err := sub.ws.Close()
104-
if err != nil {
105-
log.Error("failed to close subscriber connection", "error", err)
106-
}
103+
104+
// Tearing down a subscriber can block, so do it in a goroutine
105+
go func() {
106+
sub.tearingDown = true
107+
sub.Terminate("consuming too slowly")
108+
err := sub.ws.Close()
109+
if err != nil {
110+
log.Error("failed to close subscriber connection", "error", err)
111+
}
112+
}()
107113
}
108114
}
109115

0 commit comments

Comments
 (0)