-
Notifications
You must be signed in to change notification settings - Fork 211
/
server.go
209 lines (186 loc) · 5.11 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
package server
import (
"bufio"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"time"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/protocol"
"github.com/multiformats/go-varint"
"github.com/spacemeshos/go-spacemesh/codec"
"github.com/spacemeshos/go-spacemesh/log"
)
// ErrNotConnected is returned when peer is not connected.
var ErrNotConnected = errors.New("peer is not connected")
// Opt is a type to configure a server.
type Opt func(s *Server)
// WithTimeout configures stream timeout.
func WithTimeout(timeout time.Duration) Opt {
return func(s *Server) {
s.timeout = timeout
}
}
// WithLog configures logger for the server.
func WithLog(log log.Log) Opt {
return func(s *Server) {
s.logger = log
}
}
// WithContext configures parent context for contexts that are passed to the handler.
func WithContext(ctx context.Context) Opt {
return func(s *Server) {
s.ctx = ctx
}
}
func WithRequestSizeLimit(limit int) Opt {
return func(s *Server) {
s.requestLimit = limit
}
}
// Handler is the handler to be defined by the application.
type Handler func(context.Context, []byte) ([]byte, error)
//go:generate scalegen -types Response
// Response is a server response.
type Response struct {
Data []byte `scale:"max=10485760"` // 10 MiB
Error string `scale:"max=1024"` // TODO(mafa): make error code instead of string
}
//go:generate mockgen -typed -package=mocks -destination=./mocks/mocks.go -source=./server.go
// Host is a subset of libp2p Host interface that needs to be implemented to be usable with server.
type Host interface {
SetStreamHandler(protocol.ID, network.StreamHandler)
NewStream(context.Context, peer.ID, ...protocol.ID) (network.Stream, error)
Network() network.Network
}
// Server for the Handler.
type Server struct {
logger log.Log
protocol string
handler Handler
timeout time.Duration
requestLimit int
h Host
ctx context.Context
}
// New server for the handler.
func New(h Host, proto string, handler Handler, opts ...Opt) *Server {
srv := &Server{
ctx: context.Background(),
logger: log.NewNop(),
protocol: proto,
handler: handler,
h: h,
timeout: 10 * time.Second,
requestLimit: 10240,
}
for _, opt := range opts {
opt(srv)
}
h.SetStreamHandler(protocol.ID(proto), srv.streamHandler)
return srv
}
func (s *Server) streamHandler(stream network.Stream) {
defer stream.Close()
_ = stream.SetDeadline(time.Now().Add(s.timeout))
defer stream.SetDeadline(time.Time{})
rd := bufio.NewReader(stream)
size, err := varint.ReadUvarint(rd)
if err != nil {
return
}
if size > uint64(s.requestLimit) {
s.logger.Warning("request limit overflow",
log.Int("limit", s.requestLimit),
log.Uint64("request", size),
)
stream.Conn().Close()
return
}
buf := make([]byte, size)
_, err = io.ReadFull(rd, buf)
if err != nil {
return
}
start := time.Now()
buf, err = s.handler(log.WithNewRequestID(s.ctx), buf)
s.logger.With().Debug("protocol handler execution time",
log.String("protocol", s.protocol),
log.Duration("duration", time.Since(start)),
)
var resp Response
if err != nil {
resp.Error = err.Error()
} else {
resp.Data = buf
}
wr := bufio.NewWriter(stream)
if _, err := codec.EncodeTo(wr, &resp); err != nil {
s.logger.With().Warning("failed to write response", log.Err(err))
return
}
if err := wr.Flush(); err != nil {
s.logger.With().Warning("failed to flush stream", log.Err(err))
}
}
// Request sends a binary request to the peer. Request is executed in the background, one of the callbacks
// is guaranteed to be called on success/error.
func (s *Server) Request(ctx context.Context, pid peer.ID, req []byte, resp func([]byte), failure func(error)) error {
if len(req) > s.requestLimit {
return fmt.Errorf("request length (%d) is longer than limit %d", len(req), s.requestLimit)
}
if s.h.Network().Connectedness(pid) != network.Connected {
return fmt.Errorf("%w: %s", ErrNotConnected, pid)
}
go func() {
start := time.Now()
defer func() {
s.logger.WithContext(ctx).With().Debug("request execution time",
log.String("protocol", s.protocol),
log.Duration("duration", time.Since(start)),
)
}()
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
stream, err := s.h.NewStream(network.WithNoDial(ctx, "existing connection"), pid, protocol.ID(s.protocol))
if err != nil {
failure(err)
return
}
defer stream.Close()
defer stream.SetDeadline(time.Time{})
_ = stream.SetDeadline(time.Now().Add(s.timeout))
wr := bufio.NewWriter(stream)
sz := make([]byte, binary.MaxVarintLen64)
n := binary.PutUvarint(sz, uint64(len(req)))
_, err = wr.Write(sz[:n])
if err != nil {
failure(err)
return
}
_, err = wr.Write(req)
if err != nil {
failure(err)
return
}
if err := wr.Flush(); err != nil {
failure(err)
return
}
rd := bufio.NewReader(stream)
var r Response
if _, err := codec.DecodeFrom(rd, &r); err != nil {
failure(err)
return
}
if len(r.Error) > 0 {
failure(errors.New(r.Error))
} else {
resp(r.Data)
}
}()
return nil
}