-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
230 lines (209 loc) · 5.71 KB
/
server.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
221
222
223
224
225
226
227
228
229
230
package retro
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"strings"
sync "sync"
"time"
"github.com/gorilla/websocket"
"golang.org/x/exp/rand"
"google.golang.org/protobuf/proto"
)
const UserNameHeaderKey = "X-User-Name"
const maxUserNameLength = 20
var upgrader = websocket.Upgrader{
CheckOrigin: func(_ *http.Request) bool {
return true
},
}
type Server struct {
*http.Server
conns map[string]*websocket.Conn
tickRate time.Duration
state *State
mutex sync.Mutex
}
func NewServer(addr string, tickRate time.Duration, state *State) *Server {
if state == nil {
state = new(State)
}
s := &Server{
Server: &http.Server{
Addr: addr,
},
conns: make(map[string]*websocket.Conn),
tickRate: tickRate,
state: state,
}
http.HandleFunc("/connect", s.connect)
http.Handle("/", http.FileServer(http.Dir("./public")))
return s
}
func (s *Server) Run(ctx context.Context) {
go func() {
if err := s.ListenAndServe(); err != nil {
slog.Info("server closed", slog.Any("error", err))
}
}()
ticker := time.NewTicker(s.tickRate)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
data, err := proto.Marshal(s.state)
if err != nil {
slog.Error("proto marshal error", slog.Any("error", err))
}
for userID, conn := range s.conns {
if err := conn.WriteMessage(websocket.BinaryMessage, data); err != nil {
slog.Error("write message error", slog.Any("error", err), slog.Any("userID", userID))
}
}
}
}
}
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func randString() string {
b := make([]byte, 10)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
func (s *Server) addConn(c *websocket.Conn, name string) (string, error) {
id := "u-" + randString()
if err := c.WriteMessage(websocket.TextMessage, []byte(id)); err != nil {
return "", fmt.Errorf("send userID error", err)
}
s.conns[id] = c
s.state.Users[id] = &User{Name: name}
return id, nil
}
func (s *Server) connect(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "connection error")
slog.Error("upgrade connection error", slog.Any("error", err))
return
}
defer c.Close()
userName := r.Header.Get(UserNameHeaderKey)
userName = strings.TrimSpace(userName)
userName = userName[:min(maxUserNameLength, len(userName))]
userID, err := s.addConn(c, userName)
if err != nil {
slog.Error("addConn error", slog.Any("error", err), slog.Any("userID", userID))
return
}
log := slog.With(slog.Any("userID", userID), slog.Any("userName", userName))
log.Info("client connected")
defer delete(s.conns, userID)
for {
mt, msg, err := c.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure) {
log.Error("read error", slog.Any("error", err))
}
log.Info("client disconnected")
return
}
if mt == websocket.BinaryMessage {
a := new(Action)
if err := proto.Unmarshal(msg, a); err != nil {
log.Error("proto unmarshal error", slog.Any("error", err))
continue
}
if err := s.applyAction(a, userID); err != nil {
log.Warn("apply action error", slog.Any("error", err))
continue
}
} else {
log.Warn("unsupported message type read", slog.Any("messageType", mt), slog.Any("message", fmt.Sprintf("%v", msg)))
}
}
}
func (s *Server) applyAction(a *Action, userID string) error {
if s.state == nil {
return errors.New("state is nil")
}
if a == nil {
return errors.New("action is nil")
}
s.mutex.Lock()
defer s.mutex.Unlock()
switch a.Action.(type) {
case *Action_Select:
selectAction := a.Action.(*Action_Select).Select
sticky, ok := s.state.Stickies[selectAction.StickyID]
if !ok {
return errors.New("select: sticky not found")
}
if err := selection(s.state, sticky, selectAction.StickyID, userID); err != nil {
return fmt.Errorf("select: %w", err)
}
case *Action_Add:
addAction := a.Action.(*Action_Add).Add
stickyID := "s-" + randString()
sticky := &Sticky{
X: addAction.X,
Y: addAction.Y,
}
s.state.Stickies[stickyID] = sticky
if err := selection(s.state, sticky, stickyID, userID); err != nil {
return fmt.Errorf("add: %w", err)
}
case *Action_Move:
moveAction := a.Action.(*Action_Move).Move
sticky, ok := s.state.Stickies[moveAction.StickyID]
if !ok {
return errors.New("move: sticky not found")
}
if sticky.SelectedBy == nil {
if err := selection(s.state, sticky, moveAction.StickyID, userID); err != nil {
return fmt.Errorf("move: %w", err)
}
} else if *sticky.SelectedBy != userID {
return fmt.Errorf("move: sticky is selected by another user (%s)", *sticky.SelectedBy)
}
sticky.X = moveAction.X
sticky.Y = moveAction.Y
case *Action_Edit:
editAction := a.Action.(*Action_Edit).Edit
sticky, ok := s.state.Stickies[editAction.StickyID]
if !ok {
return errors.New("edit: sticky not found")
}
if sticky.SelectedBy == nil {
if err := selection(s.state, sticky, editAction.StickyID, userID); err != nil {
return fmt.Errorf("move: %w", err)
}
} else if *sticky.SelectedBy != userID {
return fmt.Errorf("edit: sticky is selected by another user (%s)", *sticky.SelectedBy)
}
sticky.Content = editAction.Content
default:
return fmt.Errorf("unknown action type (%T)", a.Action)
}
return nil
}
func selection(s *State, sticky *Sticky, stickyID, userID string) error {
user, ok := s.Users[userID]
if !ok {
return errors.New("user not found")
}
if user.HasSelected != nil {
selected, ok := s.Stickies[*user.HasSelected]
if ok {
selected.SelectedBy = nil
}
}
sticky.SelectedBy = &userID
user.HasSelected = &stickyID
return nil
}