-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
383 lines (344 loc) · 7.53 KB
/
conn.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package main
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"sync"
"time"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
)
var emptyAnySlice = []any{}
type ExecErr struct {
Msg string
}
func (e *ExecErr)Error()(string){
return "ExecErr: " + e.Msg
}
type TermNotFoundErr struct {
TermId int
}
func (e *TermNotFoundErr)Error()(string){
return fmt.Sprintf("Term is not found with id %d", e.TermId)
}
type ConnEventListener = func(conn *Conn, event string, args List)
type Conn struct {
host *HostServer
req *http.Request
ws *websocket.Conn
addr string // as same as req.RemoteAddr
id int64
device string // The device's type, example are [turtle pocket computer]
label string
ctx context.Context
cancel context.CancelFunc
askMux sync.Mutex
askInc int
asking map[int]chan<- any
termMux sync.RWMutex
terms map[int]*Term
OnEvent ConnEventListener
TerminateHandler func(c *Conn)(ok bool)
}
func readCCID(req *http.Request)(id int64, err error){
sCcId := req.Header.Get("X-CC-ID")
var id0 int
id0, err = strconv.Atoi(sCcId)
if err != nil {
return -1, fmt.Errorf("The value of X-CC-ID (%q) is not a vaild integer", sCcId)
}
if id0 < 0 {
return -1, fmt.Errorf("X-CC-ID must be a non-negative integer, but got %d", id0)
}
id = (int64)(id0)
return
}
func AcceptConn(host *HostServer, rw http.ResponseWriter, req *http.Request)(c *Conn, err error){
c = &Conn{
host: host,
addr: req.RemoteAddr,
asking: make(map[int]chan<- any),
terms: make(map[int]*Term),
}
c.ws, err = websocket.Accept(rw, req, nil)
if err != nil {
return
}
c.ctx, c.cancel = context.WithCancel(host.ctx)
if c.id, err = readCCID(req); err != nil {
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprint(rw, err.Error())
}
c.device = req.Header.Get("X-CC-Device")
c.label = req.Header.Get("X-CC-Label")
go func(){
for {
select {
case <-time.After(10 * time.Second):
c.send(Map{
"type": "ping",
})
case <-c.ctx.Done():
return
}
}
}()
return
}
func (c *Conn)Host()(*HostServer){
return c.host
}
func (c *Conn)Addr()(string){
return c.addr
}
func (c *Conn)Id()(int64){
return c.id
}
func (c *Conn)Device()(string){
return c.device
}
func (c *Conn)Label()(string){
return c.label
}
func (c *Conn)Context()(context.Context){
return c.ctx
}
func (c *Conn)onEvent(event string, args ...any){
if c.OnEvent != nil {
c.OnEvent(c, event, (List)(args))
}
}
func (c *Conn)recv()(data Map, err error){
err = wsjson.Read(c.ctx, c.ws, &data)
return
}
func (c *Conn)send(data Map)(err error){
return wsjson.Write(c.ctx, c.ws, data)
}
func (c *Conn)Reply(id int, data any)(err error){
return c.send(Map{
"type": "reply",
"id": id,
"data": data,
})
}
func (c *Conn)Close()(err error){
err = c.send(Map{ "type": "terminate" })
c.cancel()
c.ws.Close(websocket.StatusNormalClosure, "remote closed")
return
}
func (c *Conn)Handle(){
defer c.ws.Close(websocket.StatusInternalError, "500 internal error")
defer c.cancel()
for {
data, err := c.recv()
if err != nil {
var cerr *websocket.CloseError
if errors.As(err, &cerr) {
loger.Infof("[%s]: Disconnected: %v", cerr)
}else{
loger.Errorf("[%s]: Error when recving data: %v", c.addr, err)
c.ws.Close(websocket.StatusInternalError, err.Error())
}
return
}
loger.Debugf("[%s]: Recv: %v", c.addr, data)
typ, _ := data.GetString("type")
switch typ {
case "terminated":
loger.Infof("[%s]: Terminated", c.addr)
c.ws.Close(websocket.StatusNormalClosure, "terminated")
return
case "terminate":
if c.TerminateHandler != nil {
if !c.TerminateHandler(c) {
loger.Debugf("[%s]: Terminate prevented by handler", c.addr)
continue
}
}
loger.Infof("[%s]: Terminating", c.addr)
if err = c.send(Map{ "type": "terminate" }); err != nil {
loger.Warnf("[%s]: Error when sending terminate: %v", c.addr, err)
c.ws.Close(websocket.StatusInternalError, err.Error())
return
}
c.ws.Close(websocket.StatusNormalClosure, "terminate")
return
case "reply":
rid, _ := data.GetInt("id")
c.onReply(rid, data["data"])
case "broadcast":
tdata, _ := data.GetMap("data")
c.host.broadcastExcept(tdata, c)
case "event":
event, _ := data.GetString("event")
args, _ := data.GetList("args")
c.onEvent(event, args...)
case "term_oper":
rid, ok := data.GetInt("id")
tdata, _ := data.GetMap("data")
tid, _ := tdata.GetInt("term")
oper, _ := tdata.GetString("oper")
args, _ := tdata.GetList("args")
res, err := c.onTermOper(tid, oper, args)
if ok {
if err != nil {
c.Reply(rid, Map{
"status": "error",
"error": err,
})
}else{
if res == nil {
res = emptyAnySlice
}
c.Reply(rid, Map{
"status": "ok",
"res": res,
})
}
}
default:
loger.Debugf("[%s]: Unknown packet type %q", c.addr, typ)
}
}
}
func (c *Conn)allocAskId()(id int, resCh <-chan any){
ch := make(chan any, 1)
resCh = ch
c.askMux.Lock()
ok := true
id = c.askInc
for ok {
id++
_, ok = c.asking[id]
}
c.askInc = id
c.asking[id] = ch
c.askMux.Unlock()
return
}
func (c *Conn)onReply(id int, data any){
c.askMux.Lock()
replyCh, ok := c.asking[id]
if ok {
delete(c.asking, id)
}
c.askMux.Unlock()
if ok {
replyCh <- data
}
}
func (c *Conn)Ask(typ string, data any)(res any, err error){
id, resCh := c.allocAskId()
if err = c.send(Map{
"id": id,
"type": typ,
"data": data,
}); err != nil {
return
}
select {
case res = <-resCh:
case <-c.ctx.Done():
err = c.ctx.Err()
}
return
}
func (c *Conn)Exec(codes string)(res List, err error){
r, err := c.Ask("exec", codes)
if err != nil {
return
}
r0 := (Map)(r.(map[string]any))
status, _ := r0.GetString("status")
if status != "ok" {
errmsg, ok := r0.GetString("err")
if !ok {
loger.Errorf("Unknown error: %v", r0)
errmsg = "Unknown error"
}
return nil, &ExecErr{ errmsg }
}
res, _ = r0.GetList("res")
return
}
func (c *Conn)Run(program string, args ...any)(term *Term, done <-chan bool, err error){
id, resCh := c.allocAskId()
term = NewTerm(51, 19, program)
c.termMux.Lock()
c.terms[id] = term
c.termMux.Unlock()
if err = c.send(Map{
"id": id,
"type": "run",
"data": Map{
"prog": program,
"args": args,
"width": term.width,
"height": term.height,
},
}); err != nil {
c.termMux.Lock()
delete(c.terms, id)
c.termMux.Unlock()
return
}
c.onEvent("#term.open", program, id, term.width, term.height)
doneCh := make(chan bool, 1)
done = doneCh
go func(){
var bv bool
select {
case v := <-resCh:
bv, _ = v.(bool)
doneCh <- bv
case <-c.ctx.Done():
close(doneCh)
return
}
c.onEvent("#term.close", id, bv)
c.termMux.Lock()
delete(c.terms, id)
c.termMux.Unlock()
}()
return
}
func (c *Conn)GetTerm(tid int)(t *Term){
return c.terms[tid]
}
type TermMeta struct {
Id int `json:"id"`
Title string `json:"title"`
}
func (c *Conn)GetTerms()(terms []TermMeta){
for id, t := range c.terms {
terms = append(terms, TermMeta{Id: id, Title: t.Title})
}
return
}
func (c *Conn)onTermOper(tid int, oper string, args List)(res []any, err error){
c.termMux.RLock()
term, ok := c.terms[tid]
c.termMux.RUnlock()
if !ok {
return nil, &TermNotFoundErr{tid}
}
res, err = term.oper(oper, args)
if err == nil {
c.onEvent("#term.oper", tid, oper, args)
}else{
loger.Tracef("Error when doing term operation [%s]: %v", oper, err)
}
return
}
func (c *Conn)FireEventOnTerm(tid int, event string, args List)(err error){
return c.send(Map{
"type": "term_event",
"term": tid,
"event": event,
"args": args,
})
}