Skip to content

Commit e875a9d

Browse files
author
Kamaleshwar Nair
committed
cleaned up mutex usage, close client context on remove
1 parent d5f0d05 commit e875a9d

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

extensions/sse/client.go

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,33 +44,41 @@ func (cs *Clients) New(ctx context.Context, w http.ResponseWriter, clientID stri
4444
}
4545

4646
cs.locker.Lock()
47+
defer cs.locker.Unlock()
48+
4749
cs.clients[clientID] = cli
48-
count := len(cs.clients)
49-
cs.locker.Unlock()
5050

51-
return cli, count
51+
return cli, len(cs.clients)
5252
}
5353

5454
func (cs *Clients) Range(f func(cli *Client)) {
5555
cs.locker.Lock()
56+
copied := make([]*Client, 0, len(cs.clients))
5657
for clientID := range cs.clients {
57-
f(cs.clients[clientID])
58+
copied = append(copied, cs.clients[clientID])
5859
}
5960
cs.locker.Unlock()
61+
62+
for i := range copied {
63+
f(copied[i])
64+
}
6065
}
6166

6267
func (cs *Clients) Remove(clientID string) int {
6368
cs.locker.Lock()
69+
defer cs.locker.Unlock()
70+
6471
delete(cs.clients, clientID)
6572
count := len(cs.clients)
66-
cs.locker.Unlock()
73+
6774
return count
6875
}
6976

7077
func (cs *Clients) Active() int {
7178
cs.locker.Lock()
79+
defer cs.locker.Unlock()
80+
7281
count := len(cs.clients)
73-
cs.locker.Unlock()
7482
return count
7583

7684
}
@@ -80,20 +88,22 @@ func (cs *Clients) Active() int {
8088
func (cs *Clients) Clients() []*Client {
8189
idx := 0
8290
cs.locker.Lock()
91+
defer cs.locker.Unlock()
92+
8393
list := make([]*Client, len(cs.clients))
8494
for clientID := range cs.clients {
8595
cli := cs.clients[clientID]
8696
list[idx] = cli
8797
idx++
8898
}
89-
cs.locker.Unlock()
99+
90100
return list
91101
}
92102

93103
func (cs *Clients) Client(clientID string) *Client {
94104
cs.locker.Lock()
105+
defer cs.locker.Unlock()
95106
cli := cs.clients[clientID]
96-
cs.locker.Unlock()
97107

98108
return cli
99109
}

extensions/sse/sse.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ func (sse *SSE) RemoveClient(ctx context.Context, clientID string) {
104104
cli := sse.Clients.Client(clientID)
105105
if cli != nil {
106106
close(cli.Msg)
107+
cli.Ctx.Done()
107108
}
108109

109110
sse.OnRemoveClient(
@@ -116,6 +117,7 @@ func (sse *SSE) RemoveClient(ctx context.Context, clientID string) {
116117
func (sse *SSE) Client(id string) *Client {
117118
return sse.Clients.Client(id)
118119
}
120+
119121
func DefaultCreateHook(ctx context.Context, client *Client, count int) {}
120122
func DefaultRemoveHook(ctx context.Context, clientID string, count int) {}
121123
func DefaultOnSend(ctx context.Context, client *Client, err error) {}

0 commit comments

Comments
 (0)