-
Notifications
You must be signed in to change notification settings - Fork 0
/
wsserver.go
220 lines (185 loc) · 5.59 KB
/
wsserver.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
219
220
package main
import (
"context"
"encoding/json"
"net/http"
"sync"
"github.com/monodop/devlog/log"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
)
type wsMessage struct {
Message string
}
func startWsListener(exitChannel chan bool, messageChannel chan string) {
address := ":9091"
man := workerManager{
nextWorkerId: 0,
nextDataId: 100,
workers: make(map[int]chan string),
data: []string{
// `{"id": 1, "app": "test", "logger": "MyApp.MyLogger", "message": "Hello World!"}`,
// `{"id": 2, "app": "test", "logger": "MyApp.MyLogger", "message": "New message"}`,
// `{"id": 3, "app": "other", "logger": "MyApp.Boi", "message": "New message"}`,
// `{"id": 4, "app": "other", "logger": "MyApp.Boi", "message": "World Hello!"}`,
// `{"id": 5, "app": "other", "logger": "MyApp.Boi", "message": "World Hello!"}`,
// `{"id": 6, "app": "other", "logger": "MyApp.Boi", "message": "World Hello!"}`,
// `{"id": 7, "app": "other", "logger": "MyApp.Boi", "message": "World Hello!"}`,
// `{"id": 8, "app": "other", "logger": "MyApp.Boi", "message": "World Hello!"}`,
// `{"id": 9, "app": "other", "logger": "MyApp.Boi", "message": "World Hello!"}`,
// `{"id": 10, "app": "other", "logger": "MyApp.Boi", "message": "World Hello!"}`,
// `{"id": 11, "app": "other", "logger": "MyApp.Boi", "message": "World Hello!"}`,
// `{"id": 12, "app": "other", "logger": "MyApp.Boi", "message": "World Hello!"}`,
// `{"id": 13, "app": "other", "logger": "MyApp.Boi", "message": "World Hello!"}`,
// `{"id": 14, "app": "other", "logger": "MyApp.Boi", "message": "World Hello!"}`,
// `{"id": 15, "app": "other", "logger": "MyApp.Boi", "message": "World Hello!"}`,
// `{"id": 16, "superduperlong": "other", "logger": "MyApp.Boi", "message": "World Hello!"}`,
},
}
go func() {
for {
msg := <-messageChannel
man.AddMessage(msg)
}
}()
http.HandleFunc("/ws", func(writer http.ResponseWriter, request *http.Request) {
connection, err := websocket.Accept(writer, request, &websocket.AcceptOptions{
OriginPatterns: []string{"*"},
})
if err != nil {
log.Exception(err)
return
}
defer connection.Close(websocket.StatusInternalError, "Unexpected error. Connection closing")
handleWsConnection(connection, request, &man)
})
http.Handle("/", http.FileServer(http.Dir("./frontend")))
log.Info("WebSocket server now listening on %s", address)
err := http.ListenAndServe(address, nil)
log.Exception(err)
}
func handleWsConnection(connection *websocket.Conn, request *http.Request, man *workerManager) {
ctx, cancel := context.WithCancel(request.Context())
defer cancel()
channel := make(chan string)
id := man.AddWorker(channel)
defer man.RemoveWorker(id)
log.Info("Opened WS connection %d to %s", id, request.RemoteAddr)
defer log.Info("Closed WS connection %d to %s", id, request.RemoteAddr)
ctx = connection.CloseRead(ctx)
for _, m := range man.data {
err := wsjson.Write(ctx, connection, wsMessage{
Message: m,
})
if err != nil {
log.Exception(err)
return
}
}
for {
select {
case <-ctx.Done():
connection.Close(websocket.StatusNormalClosure, "")
return
case msg := <-channel:
err := wsjson.Write(ctx, connection, wsMessage{
Message: msg,
})
if err != nil {
log.Exception(err)
return
}
}
}
}
func startWsTestConnection() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
connection, _, err := websocket.Dial(ctx, "ws://localhost:9091/ws", nil)
if err != nil {
log.Exception(err)
return
}
defer connection.Close(websocket.StatusInternalError, "Unexpected error, closing connection")
for {
message := wsMessage{}
err = wsjson.Read(ctx, connection, &message)
if err != nil {
log.Exception(err)
return
}
log.Info("ws: %s", message.Message)
}
}
type workerManager struct {
sync.Mutex
workers map[int]chan string
data []string
nextDataId int
nextWorkerId int
}
func (man *workerManager) AddWorker(worker chan string) int {
man.Lock()
defer man.Unlock()
id := man.nextWorkerId
man.nextWorkerId++
man.workers[id] = worker
return id
}
func (man *workerManager) RemoveWorker(id int) {
man.Lock()
defer man.Unlock()
delete(man.workers, id)
}
func (man *workerManager) Iter(routine func(chan string)) {
man.Lock()
defer man.Unlock()
for _, worker := range man.workers {
routine(worker)
}
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func (man *workerManager) AddMessage(message string) {
man.Lock()
locked := true
unlock := func() {
if locked {
man.Unlock()
}
locked = false
}
defer unlock()
// Generate new unique id for message
id := man.nextDataId
man.nextDataId++
// Parse message
var parsed map[string]interface{}
err := json.Unmarshal([]byte(message), &parsed)
if err != nil {
log.Error("Error serializing message: %s", err)
return
}
// Tag message with unique id
parsed["_id"] = id
// Re-serialize message
bytes, err := json.Marshal(parsed)
if err != nil {
log.Error("Error serializing message: %s", err)
return
}
// Add message to short-term memory
finalMessage := string(bytes)
man.data = append(man.data, finalMessage)
// Clear short-term memory that's older than 100 messages
maxLength := 100
numToRemove := max(0, len(man.data)-maxLength)
man.data = man.data[numToRemove:]
// Send message to all listeners
unlock()
man.Iter(func(w chan string) { w <- finalMessage })
}