-
Notifications
You must be signed in to change notification settings - Fork 3
/
middleware.go
218 lines (180 loc) · 5.73 KB
/
middleware.go
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
package pubsub
import (
"context"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/MicahParks/websocket-pubsub/clients"
"github.com/MicahParks/websocket-pubsub/pubclient"
"github.com/MicahParks/websocket-pubsub/subclient"
)
// subscriptionCountdown holds a subscription and a waitgroup for it. When the waitgroup is done, the subscription is
// cancelled.
type subscriptionCountdown struct {
subscription *subscription
countdown sync.WaitGroup
}
// WebSocketHandler creates an HTTP handler via a closure that will upgrade the connection to a websocket and use that
// websocket as either a publisher or a subscriber.
func WebSocketHandler(ctx context.Context, options ...Options) http.HandlerFunc {
// Flatten the options.
flatOptions := flattenOptions(options)
option := *flatOptions.Options
upgrader := *flatOptions.Upgrader
// Create a map of paths to subscriptions.
subscriptMux := sync.Mutex{}
subscriptions := make(map[string]*subscriptionCountdown)
// Create the HTTP handler via a closure.
return func(writer http.ResponseWriter, req *http.Request) {
// Get the subscription topic.
subscriptionTopic := req.URL.EscapedPath()
// Get the client type from the header.
isPublisher := false
switch clientType := req.Header.Get(clients.ClientTypeHeader); clientType {
case pubclient.ClientType:
isPublisher = true
case subclient.ClientType:
// Keep isPublisher as false.
default:
// Report the event.
if option.Events != nil {
option.Events <- Event{
SubscriptionTopic: subscriptionTopic,
Type: EventTypeBadHTTPHeaders,
}
}
// Respond with a bad request.
writer.WriteHeader(http.StatusBadRequest)
return
}
// Get the client program name.
clientName := req.Header.Get(clients.ClientNameHeader)
// Upgrade the HTTP connection to a web socket.
conn, err := upgrader.Upgrade(writer, req, nil)
if err != nil {
// Report the event.
if option.Events != nil {
option.Events <- Event{
SubscriptionTopic: subscriptionTopic,
Type: EventTypeWebsocketUpgradeFailed,
}
}
// Respond with a bad request.
writer.WriteHeader(http.StatusBadRequest)
return
}
// Get or create the subscription in the subscription map.
subscriptMux.Lock()
subscriptCountdown, ok := subscriptions[subscriptionTopic]
if !ok {
// Create the new subscription.
subscript := newSubscription(ctx, option)
subscriptCountdown = &subscriptionCountdown{subscription: subscript}
// Add the new subscription to the subscription map.
subscriptions[subscriptionTopic] = subscriptCountdown
// Make sure the subscription gets cleaned up when there are no clients.
subscriptCountdown.countdown.Add(1)
go func() {
subscriptCountdown.countdown.Wait()
subscriptCountdown.subscription.cancel()
subscriptMux.Lock()
delete(subscriptions, subscriptionTopic)
subscriptMux.Unlock()
}()
} else {
// Add to the countdown.
subscriptCountdown.countdown.Add(1)
}
subscriptMux.Unlock()
subscript := subscriptCountdown.subscription
// When the client's socket is closed, cancel the client and decrement the wait group.
var client canceller
clientMux := sync.Mutex{}
once := sync.Once{}
conn.SetCloseHandler(func(code int, _ string) error {
// Only cancel the client and decrement the wait group once.
once.Do(func() {
clientMux.Lock()
client.Cancel()
clientMux.Unlock()
subscriptCountdown.countdown.Done()
})
// Perform the normal websocket close write.
message := websocket.FormatCloseMessage(code, "")
_ = conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(time.Second)) // Ignore any error.
return nil
})
// Treat the websocket connection as a publisher or subscriber as instructed.
if isPublisher {
// Create the publisher and launch its goroutines.
pub := newPublisher(subscript.ctx, clientName, conn, subscript.publish, subscriptionTopic, directClientOptions{
closeDeadline: option.CloseDeadline,
events: option.Events,
pongDeadline: option.PongDeadline,
})
// Report the event.
if option.Events != nil {
option.Events <- Event{
ClientID: pub.name,
SubscriptionTopic: subscriptionTopic,
Type: EventTypePublisherJoined,
}
}
// Keep track of the new publisher.
subscript.newPublisher <- pub
go func() {
<-pub.ctx.Done()
select {
case <-ctx.Done():
default:
select {
case <-ctx.Done():
case subscript.deletePublisher <- pub:
}
}
}()
// Keep a reference to the client.
clientMux.Lock()
client = pub
clientMux.Unlock()
} else {
// Create the subscriber and launch its goroutines.
sub := newSubscriber(subscript.ctx, clientName, conn, option.MessageBuffer, subscriptionTopic, directClientOptions{
closeDeadline: option.CloseDeadline,
events: option.Events,
pongDeadline: option.PongDeadline,
})
// Report the event.
if option.Events != nil {
option.Events <- Event{
ClientID: sub.name,
SubscriptionTopic: subscriptionTopic,
Type: EventTypeSubscriberJoined,
}
}
// Keep track of the new subscriber.
subscript.newSubscriber <- sub
go func() {
<-sub.ctx.Done()
select {
case <-ctx.Done():
default:
select {
case <-ctx.Done():
case subscript.deleteSubscriber <- sub:
}
}
}()
// Keep a reference to the client.
clientMux.Lock()
client = sub
clientMux.Unlock()
}
// Set the pong handler to expect another pong within the pong deadline.
conn.SetPongHandler(func(_ string) error {
// Expect another pong before the new deadline.
return setReadDeadline(conn, *option.PongDeadline)
})
}
}