forked from testground/sync-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
105 lines (84 loc) · 2.04 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
package sync
import (
"context"
"errors"
"net"
"net/http"
"strconv"
"github.com/hashicorp/go-multierror"
"github.com/testground/testground/pkg/logging"
"nhooyr.io/websocket"
)
var log = logging.S()
type Server struct {
service Service
server *http.Server
l net.Listener
}
func NewServer(service Service, port int) (srv *Server, err error) {
srv = &Server{
service: service,
}
srv.server = &http.Server{
Handler: http.HandlerFunc(srv.handler),
}
srv.l, err = net.Listen("tcp", ":"+strconv.Itoa(port))
if err != nil {
return nil, err
}
return srv, err
}
func (s *Server) Serve() error {
return s.server.Serve(s.l)
}
func (s *Server) Addr() string {
return s.l.Addr().String()
}
func (s *Server) Port() int {
return s.l.Addr().(*net.TCPAddr).Port
}
func (s *Server) Shutdown(ctx context.Context) error {
var result *multierror.Error
result = multierror.Append(
result,
s.server.Shutdown(ctx),
s.service.Close(),
)
return result.ErrorOrNil()
}
func (s *Server) handler(w http.ResponseWriter, r *http.Request) {
c, err := websocket.Accept(w, r, &websocket.AcceptOptions{
InsecureSkipVerify: true, // Accept requests from all domains.
})
if err != nil {
log.Warnf("could not upgrade connection: %v", err)
return
}
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
conn := &connection{
Conn: c,
service: s.service,
ctx: ctx,
responses: make(chan *Response),
cancelFuncs: map[string]context.CancelFunc{},
}
go func() {
_ = conn.consumeResponses()
}()
err = conn.consumeRequests()
if err == nil {
_ = c.Close(websocket.StatusNormalClosure, "")
return
}
if errors.Is(err, context.Canceled) ||
websocket.CloseStatus(err) == websocket.StatusNormalClosure ||
websocket.CloseStatus(err) == websocket.StatusGoingAway {
// Client closed the connection by itself.
log.Info("client closed connection")
_ = c.Close(websocket.StatusNormalClosure, "")
return
}
log.Warnf("websocket closed unexpectedly: %v", err)
_ = c.Close(websocket.StatusInternalError, "")
}