-
Notifications
You must be signed in to change notification settings - Fork 0
/
workspace.go
145 lines (110 loc) · 2.48 KB
/
workspace.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
package main
import (
"errors"
"net"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
"github.com/labstack/gommon/log"
)
type Workspace struct {
mu sync.RWMutex
connections map[*websocket.Conn]struct{}
inLoop bool
tm *TaskManager
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func newWorkspace(config *Config) *Workspace {
return &Workspace{
connections: make(map[*websocket.Conn]struct{}),
tm: newTaskManager(config),
}
}
func (w *Workspace) serveConnectionsLoop() {
defer w.Close()
w.inLoop = true
log.Info("starting new loop...")
for {
tasks := w.tm.GetTasks()
err := w.WriteMessage(websocket.TextMessage, mustJSONEncode(tasks))
if err != nil {
if errors.Is(err, ErrNoConnectionsInWorkspace) {
log.Debug("no connections in workspace...")
} else {
log.Error(err)
}
log.Info("closing tasks loop...")
w.inLoop = false
break
}
time.Sleep(time.Second)
}
}
func (w *Workspace) GetConnectionCount() uint64 {
w.mu.RLock()
defer w.mu.RUnlock()
return uint64(len(w.connections))
}
func (w *Workspace) WriteMessage(messageType int, data []byte) error {
w.mu.Lock()
defer w.mu.Unlock()
if len(w.connections) == 0 {
return ErrNoConnectionsInWorkspace
}
for conn := range w.connections {
err := conn.WriteMessage(messageType, data)
if err != nil {
if websocket.IsCloseError(err) || websocket.IsUnexpectedCloseError(err) {
delete(w.connections, conn)
conn.Close()
}
log.Error(err)
if _, ok := err.(*net.OpError); ok {
delete(w.connections, conn)
conn.Close()
}
}
}
if len(w.connections) == 0 {
return ErrNoConnectionsInWorkspace
}
return nil
}
func (w *Workspace) WSSubscribeToTasks(c echo.Context) error {
conn, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
if err != nil {
return err
}
w.mu.Lock()
w.connections[conn] = struct{}{}
w.mu.Unlock()
return nil
}
func (w *Workspace) GetTasks() []*Task {
return w.tm.GetTasks()
}
func (w *Workspace) AddTask(name string, taskType TaskType) *Task {
return w.tm.AddTask(name, taskType)
}
func (w *Workspace) DeleteTask(id uint64) error {
return w.tm.DeleteTask(id)
}
func (w *Workspace) FlushTasks() error {
return w.tm.FlushTasks()
}
func (w *Workspace) Close() {
w.mu.Lock()
for conn := range w.connections {
delete(w.connections, conn)
if err := conn.Close(); err != nil {
log.Error(err)
}
}
w.mu.Unlock()
}