/
server.go
457 lines (403 loc) · 12.9 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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package net
import (
"bytes"
"context"
"errors"
"fmt"
"sync"
"github.com/dcnetio/gothreads-lib/cbor"
lstore "github.com/dcnetio/gothreads-lib/core/logstore"
"github.com/dcnetio/gothreads-lib/core/thread"
"github.com/dcnetio/gothreads-lib/logstore/lstoreds"
pb "github.com/dcnetio/gothreads-lib/net/pb"
"github.com/dcnetio/gothreads-lib/util"
"github.com/gogo/status"
"github.com/ipfs/go-cid"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/peer"
ma "github.com/multiformats/go-multiaddr"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
grpcpeer "google.golang.org/grpc/peer"
)
var (
errNoAddrsEdge = errors.New("no addresses to compute edge")
errNoHeadsEdge = errors.New("no heads to compute edge")
)
// server implements the net gRPC server.
type server struct {
net *net
opts []grpc.DialOption
conns map[peer.ID]*grpc.ClientConn
ps *pubsub.PubSub
sync.Mutex
}
// newServer creates a new network server.
func newServer(n *net, opts ...grpc.DialOption) (*server, error) {
var (
s = &server{
net: n,
conns: make(map[peer.ID]*grpc.ClientConn),
}
defaultOpts = []grpc.DialOption{
s.getLibp2pDialer(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
}
)
s.opts = append(defaultOpts, opts...)
if n.conf.PubSub {
var err error
s.ps, err = pubsub.NewGossipSub(
n.ctx,
n.host,
pubsub.WithPeerExchange(true),
pubsub.WithFloodPublish(true),
)
if err != nil {
return nil, err
}
}
return s, nil
}
// GetLogs receives a get logs request.
func (s *server) GetLogs(ctx context.Context, req *pb.GetLogsRequest) (*pb.GetLogsReply, error) {
pid, err := peerIDFromContext(ctx)
if err != nil {
return nil, err
}
log.Debugf("received get logs request from %s", pid)
pblgs := &pb.GetLogsReply{}
if err := s.checkServiceKey(req.Body.ThreadID.ID, req.Body.ServiceKey); err != nil {
return pblgs, err
}
info, err := s.net.store.GetThread(req.Body.ThreadID.ID) // Safe since putRecords will change head when fully-available
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
pblgs.Logs = make([]*pb.Log, len(info.Logs))
for i, l := range info.Logs {
pblgs.Logs[i] = logToProto(l)
}
log.Debugf("sending %d logs to %s", len(info.Logs), pid)
return pblgs, nil
}
// PushLog receives a push log request.
func (s *server) PushLog(ctx context.Context, req *pb.PushLogRequest) (*pb.PushLogReply, error) {
pid, err := peerIDFromContext(ctx)
if err != nil {
return nil, err
}
log.Debugf("received push log request from %s", pid)
// Pick up missing keys
info, err := s.net.store.GetThread(req.Body.ThreadID.ID)
if err != nil && !errors.Is(err, lstore.ErrThreadNotFound) {
return nil, status.Error(codes.Internal, err.Error())
}
if !info.Key.Defined() {
if req.Body.ServiceKey != nil && req.Body.ServiceKey.Key != nil {
if err = s.net.store.AddServiceKey(req.Body.ThreadID.ID, req.Body.ServiceKey.Key); err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
} else {
return nil, status.Error(codes.NotFound, lstore.ErrThreadNotFound.Error())
}
} else if !info.Key.CanRead() {
if req.Body.ReadKey != nil && req.Body.ReadKey.Key != nil {
if err = s.net.store.AddReadKey(req.Body.ThreadID.ID, req.Body.ReadKey.Key); err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
}
}
lg := logFromProto(req.Body.Log)
if err = s.net.createExternalLogsIfNotExist(req.Body.ThreadID.ID, []thread.LogInfo{lg}); err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
if s.net.queueGetRecords.Schedule(pid, req.Body.ThreadID.ID, callPriorityLow, s.net.updateRecordsFromPeer) {
log.Debugf("record update for thread %s from %s scheduled", req.Body.ThreadID.ID, pid)
}
return &pb.PushLogReply{}, nil
}
// GetRecords receives a get records request.
func (s *server) GetRecords(ctx context.Context, req *pb.GetRecordsRequest) (*pb.GetRecordsReply, error) {
pid, err := peerIDFromContext(ctx)
if err != nil {
return nil, err
}
log.Debugf("received get records request from %s", pid)
var pbrecs = &pb.GetRecordsReply{}
if err := s.checkServiceKey(req.Body.ThreadID.ID, req.Body.ServiceKey); err != nil {
return pbrecs, err
}
// fast check if requested offsets are equal with thread heads
if changed, err := s.headsChanged(req); err != nil {
return nil, err
} else if !changed {
return pbrecs, nil
}
reqd := make(map[peer.ID]*pb.GetRecordsRequest_Body_LogEntry)
for _, l := range req.Body.Logs {
reqd[l.LogID.ID] = l
}
info, err := s.net.store.GetThread(req.Body.ThreadID.ID)
if err != nil {
return nil, err
} else if len(info.Logs) == 0 {
return pbrecs, nil
}
pbrecs.Logs = make([]*pb.GetRecordsReply_LogEntry, 0, len(info.Logs))
var (
mx sync.Mutex
wg sync.WaitGroup
)
for _, lg := range info.Logs {
var (
offset cid.Cid
limit int
counter int64
pblg = logToProto(lg)
)
if opts, ok := reqd[lg.ID]; ok {
offset = opts.Offset.Cid
counter = opts.Counter
limit = int(opts.Limit)
} else {
offset = cid.Undef
limit = int(s.net.conf.NetPullingLimit)
counter = thread.CounterUndef
}
wg.Add(1)
go func(tid thread.ID, lid peer.ID, off cid.Cid, lim int) {
defer wg.Done()
// if we don't have records in the log then skipping it
if pblg.Counter == thread.CounterUndef {
return
}
recs, err := s.net.getLocalRecords(ctx, tid, lid, off, lim, counter)
if err != nil {
log.Errorf("getting local records (thread %s, log %s): %v", tid, lid, err)
}
pblg.Counter = counter + int64(len(recs))
var prs = make([]*pb.Log_Record, 0, len(recs))
for _, r := range recs {
pr, err := cbor.RecordToProto(ctx, s.net, r)
if err != nil {
log.Errorf("constructing proto-record %s (thread %s, log %s): %v", r.Cid(), tid, lid, err)
break
}
prs = append(prs, pr)
}
if len(prs) == 0 {
// do not include logs with no records in reply
return
}
mx.Lock()
pbrecs.Logs = append(pbrecs.Logs, &pb.GetRecordsReply_LogEntry{
LogID: &pb.ProtoPeerID{ID: lid},
Records: prs,
Log: pblg,
})
mx.Unlock()
log.Debugf("sending %d records in log %s-%s to %s inCounter %d outCounter %d", len(recs), req.Body.ThreadID.ID.String(), lid, pid, counter, pblg.Counter)
}(req.Body.ThreadID.ID, lg.ID, offset, limit)
}
wg.Wait()
return pbrecs, nil
}
// PushRecord receives a push record request.
func (s *server) PushRecord(ctx context.Context, req *pb.PushRecordRequest) (*pb.PushRecordReply, error) {
pid, err := peerIDFromContext(ctx)
if err != nil {
return nil, err
}
log.Debugf("received push record request from %s", pid)
// A log is required to accept new records
logpk, err := s.net.store.PubKey(req.Body.ThreadID.ID, req.Body.LogID.ID)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
if logpk == nil {
return nil, status.Error(codes.NotFound, "log not found")
}
key, err := s.net.store.ServiceKey(req.Body.ThreadID.ID)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
rec, err := cbor.RecordFromProto(req.Body.Record, key)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
if err = rec.Verify(logpk); err != nil {
return nil, status.Error(codes.Unauthenticated, err.Error())
}
if err = s.net.PutRecord(ctx, req.Body.ThreadID.ID, req.Body.LogID.ID, rec, req.Counter); err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &pb.PushRecordReply{}, nil
}
// ExchangeEdges receives an exchange edges request.
func (s *server) ExchangeEdges(ctx context.Context, req *pb.ExchangeEdgesRequest) (*pb.ExchangeEdgesReply, error) {
pid, err := peerIDFromContext(ctx)
if err != nil {
return nil, err
}
log.Debugf("received exchange edges request from %s", pid)
var reply pb.ExchangeEdgesReply
for _, entry := range req.Body.Threads {
var tid = entry.ThreadID.ID
switch addrsEdgeLocal, headsEdgeLocal, err := s.localEdges(tid); err {
case errNoAddrsEdge, errNoHeadsEdge, nil:
var (
addrsEdgeRemote = entry.AddressEdge
headsEdgeRemote = entry.HeadsEdge
)
// need to get new logs only if we have non empty addresses on remote and the hashes are different
if addrsEdgeRemote != lstoreds.EmptyEdgeValue && addrsEdgeLocal != addrsEdgeRemote {
prt := callPriorityLow
updateLogs := s.net.updateLogsFromPeer
// if we don't have the thread locally
if addrsEdgeLocal == lstoreds.EmptyEdgeValue {
prt = callPriorityHigh // we have to add thread in pubsub, not just update its logs
updateLogs = func(ctx context.Context, p peer.ID, t thread.ID) error {
return s.net.updateLogsFromPeer(ctx, p, t)
}
}
if s.net.queueGetLogs.Schedule(pid, tid, prt, updateLogs) {
log.Debugf("log information update for thread %s from %s scheduled", tid, pid)
}
}
// need to get new records only if we have non empty heads on remote and the hashes are different
if headsEdgeRemote != lstoreds.EmptyEdgeValue && headsEdgeLocal != headsEdgeRemote {
if s.net.queueGetRecords.Schedule(pid, tid, callPriorityLow, s.net.updateRecordsFromPeer) {
log.Debugf("record update for thread %s from %s scheduled", tid, pid)
}
}
// setting "exists" for backwards compatibility with older versions
// to get exactly same behaviour as was before
exists := true
if addrsEdgeLocal == lstoreds.EmptyEdgeValue || headsEdgeLocal == lstoreds.EmptyEdgeValue {
exists = false
}
reply.Edges = append(reply.Edges, &pb.ExchangeEdgesReply_ThreadEdges{
ThreadID: &pb.ProtoThreadID{ID: tid},
Exists: exists,
AddressEdge: addrsEdgeLocal,
HeadsEdge: headsEdgeLocal,
})
default:
return nil, fmt.Errorf("getting edges for %s: %w", tid, err)
}
}
return &reply, nil
}
// checkServiceKey compares a key with the one stored under thread.
func (s *server) checkServiceKey(id thread.ID, k *pb.ProtoKey) error {
if k == nil || k.Key == nil {
return status.Error(codes.Unauthenticated, "a service-key is required to get logs")
}
sk, err := s.net.store.ServiceKey(id)
if err != nil {
return status.Error(codes.Internal, err.Error())
}
if sk == nil {
return status.Error(codes.NotFound, lstore.ErrThreadNotFound.Error())
}
if !bytes.Equal(k.Key.Bytes(), sk.Bytes()) {
return status.Error(codes.Unauthenticated, "invalid service-key")
}
return nil
}
// headsChanged determines if thread heads are different from the requested offsets.
func (s *server) headsChanged(req *pb.GetRecordsRequest) (bool, error) {
var reqHeads = make([]util.LogHead, len(req.Body.Logs))
for i, l := range req.Body.GetLogs() {
reqHeads[i] = util.LogHead{
Head: thread.Head{
ID: l.Offset.Cid,
Counter: l.Counter,
},
LogID: l.LogID.ID,
}
}
var currEdge, err = s.net.store.HeadsEdge(req.Body.ThreadID.ID)
switch {
case err == nil:
return util.ComputeHeadsEdge(reqHeads) != currEdge, nil
case errors.Is(err, lstore.ErrThreadNotFound):
// no local heads, but there could be missing logs info in reply
return true, nil
default:
return false, err
}
}
// localEdges returns values of local addresses/heads edges for the thread.
func (s *server) localEdges(tid thread.ID) (addrsEdge, headsEdge uint64, err error) {
headsEdge = lstoreds.EmptyEdgeValue
addrsEdge, err = s.net.store.AddrsEdge(tid)
if err != nil {
if errors.Is(err, lstore.ErrThreadNotFound) {
err = errNoAddrsEdge
} else {
err = fmt.Errorf("address edge: %w", err)
}
return
}
headsEdge, err = s.net.store.HeadsEdge(tid)
if err != nil {
if errors.Is(err, lstore.ErrThreadNotFound) {
err = errNoHeadsEdge
} else {
err = fmt.Errorf("heads edge: %w", err)
}
}
return
}
// peerIDFromContext returns peer ID from the GRPC context
func peerIDFromContext(ctx context.Context) (peer.ID, error) {
ctxPeer, ok := grpcpeer.FromContext(ctx)
if !ok {
return "", errors.New("unable to identify stream peer")
}
pid, err := peer.Decode(ctxPeer.Addr.String())
if err != nil {
return "", fmt.Errorf("parsing stream peer id: %v", err)
}
return pid, nil
}
// logToProto returns a proto log from a thread log.
func logToProto(l thread.LogInfo) *pb.Log {
return &pb.Log{
ID: &pb.ProtoPeerID{ID: l.ID},
PubKey: &pb.ProtoPubKey{PubKey: l.PubKey},
Addrs: addrsToProto(l.Addrs),
Head: &pb.ProtoCid{Cid: l.Head.ID},
Counter: l.Head.Counter,
}
}
// logFromProto returns a thread log from a proto log.
func logFromProto(l *pb.Log) thread.LogInfo {
return thread.LogInfo{
ID: l.ID.ID,
PubKey: l.PubKey.PubKey,
Addrs: addrsFromProto(l.Addrs),
Head: thread.Head{
ID: l.Head.Cid,
Counter: l.Counter,
},
}
}
func addrsToProto(mas []ma.Multiaddr) []pb.ProtoAddr {
pas := make([]pb.ProtoAddr, len(mas))
for i, a := range mas {
pas[i] = pb.ProtoAddr{Multiaddr: a}
}
return pas
}
func addrsFromProto(pa []pb.ProtoAddr) []ma.Multiaddr {
mas := make([]ma.Multiaddr, len(pa))
for i, a := range pa {
mas[i] = a.Multiaddr
}
return mas
}