-
Notifications
You must be signed in to change notification settings - Fork 33
/
server.go
263 lines (209 loc) · 5.52 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
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
package main
import (
"fmt"
"io"
"math/rand"
"net"
"sync"
"time"
"github.com/pkg/errors"
chat "github.com/rodaine/grpc-chat/protos"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
const tokenHeader = "x-chat-token"
type server struct {
Host, Password string
Broadcast chan *chat.StreamResponse
ClientNames map[string]string
ClientStreams map[string]chan *chat.StreamResponse
namesMtx, streamsMtx sync.RWMutex
chat.UnimplementedChatServer
}
func Server(host, pass string) *server {
return &server{
Host: host,
Password: pass,
Broadcast: make(chan *chat.StreamResponse, 1000),
ClientNames: make(map[string]string),
ClientStreams: make(map[string]chan *chat.StreamResponse),
}
}
func (s *server) Run(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ServerLogf(time.Now(),
"starting on %s with password %q",
s.Host, s.Password)
srv := grpc.NewServer()
chat.RegisterChatServer(srv, s)
l, err := net.Listen("tcp", s.Host)
if err != nil {
return errors.WithMessage(err,
"server unable to bind on provided host")
}
go s.broadcast(ctx)
go func() {
_ = srv.Serve(l)
cancel()
}()
<-ctx.Done()
s.Broadcast <- &chat.StreamResponse{
Timestamp: timestamppb.Now(),
Event: &chat.StreamResponse_ServerShutdown{
ServerShutdown: &chat.StreamResponse_Shutdown{}}}
close(s.Broadcast)
ServerLogf(time.Now(), "shutting down")
srv.GracefulStop()
return nil
}
func (s *server) Login(_ context.Context, req *chat.LoginRequest) (*chat.LoginResponse, error) {
switch {
case req.Password != s.Password:
return nil, status.Error(codes.Unauthenticated, "password is incorrect")
case req.Name == "":
return nil, status.Error(codes.InvalidArgument, "username is required")
}
tkn := s.genToken()
s.setName(tkn, req.Name)
ServerLogf(time.Now(), "%s (%s) has logged in", tkn, req.Name)
s.Broadcast <- &chat.StreamResponse{
Timestamp: timestamppb.Now(),
Event: &chat.StreamResponse_ClientLogin{ClientLogin: &chat.StreamResponse_Login{
Name: req.Name,
}},
}
return &chat.LoginResponse{Token: tkn}, nil
}
func (s *server) Logout(_ context.Context, req *chat.LogoutRequest) (*chat.LogoutResponse, error) {
name, ok := s.delName(req.Token)
if !ok {
return nil, status.Error(codes.NotFound, "token not found")
}
ServerLogf(time.Now(), "%s (%s) has logged out", req.Token, name)
s.Broadcast <- &chat.StreamResponse{
Timestamp: timestamppb.Now(),
Event: &chat.StreamResponse_ClientLogout{ClientLogout: &chat.StreamResponse_Logout{
Name: name,
}},
}
return new(chat.LogoutResponse), nil
}
func (s *server) Stream(srv chat.Chat_StreamServer) error {
tkn, ok := s.extractToken(srv.Context())
if !ok {
return status.Error(codes.Unauthenticated, "missing token header")
}
name, ok := s.getName(tkn)
if !ok {
return status.Error(codes.Unauthenticated, "invalid token")
}
go s.sendBroadcasts(srv, tkn)
for {
req, err := srv.Recv()
if err == io.EOF {
break
} else if err != nil {
return err
}
s.Broadcast <- &chat.StreamResponse{
Timestamp: timestamppb.Now(),
Event: &chat.StreamResponse_ClientMessage{ClientMessage: &chat.StreamResponse_Message{
Name: name,
Message: req.Message,
}},
}
}
<-srv.Context().Done()
return srv.Context().Err()
}
func (s *server) sendBroadcasts(srv chat.Chat_StreamServer, tkn string) {
stream := s.openStream(tkn)
defer s.closeStream(tkn)
for {
select {
case <-srv.Context().Done():
return
case res := <-stream:
if s, ok := status.FromError(srv.Send(res)); ok {
switch s.Code() {
case codes.OK:
// noop
case codes.Unavailable, codes.Canceled, codes.DeadlineExceeded:
DebugLogf("client (%s) terminated connection", tkn)
return
default:
ClientLogf(time.Now(), "failed to send to client (%s): %v", tkn, s.Err())
return
}
}
}
}
}
func (s *server) broadcast(_ context.Context) {
for res := range s.Broadcast {
s.streamsMtx.RLock()
for _, stream := range s.ClientStreams {
select {
case stream <- res:
// noop
default:
ServerLogf(time.Now(), "client stream full, dropping message")
}
}
s.streamsMtx.RUnlock()
}
}
func (s *server) openStream(tkn string) (stream chan *chat.StreamResponse) {
stream = make(chan *chat.StreamResponse, 100)
s.streamsMtx.Lock()
s.ClientStreams[tkn] = stream
s.streamsMtx.Unlock()
DebugLogf("opened stream for client %s", tkn)
return
}
func (s *server) closeStream(tkn string) {
s.streamsMtx.Lock()
if stream, ok := s.ClientStreams[tkn]; ok {
delete(s.ClientStreams, tkn)
close(stream)
}
DebugLogf("closed stream for client %s", tkn)
s.streamsMtx.Unlock()
}
func (s *server) genToken() string {
tkn := make([]byte, 4)
rand.Read(tkn)
return fmt.Sprintf("%x", tkn)
}
func (s *server) getName(tkn string) (name string, ok bool) {
s.namesMtx.RLock()
name, ok = s.ClientNames[tkn]
s.namesMtx.RUnlock()
return
}
func (s *server) setName(tkn string, name string) {
s.namesMtx.Lock()
s.ClientNames[tkn] = name
s.namesMtx.Unlock()
}
func (s *server) delName(tkn string) (name string, ok bool) {
name, ok = s.getName(tkn)
if ok {
s.namesMtx.Lock()
delete(s.ClientNames, tkn)
s.namesMtx.Unlock()
}
return
}
func (s *server) extractToken(ctx context.Context) (tkn string, ok bool) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok || len(md[tokenHeader]) == 0 {
return "", false
}
return md[tokenHeader][0], true
}