-
Notifications
You must be signed in to change notification settings - Fork 394
/
endpoint.go
69 lines (59 loc) · 1.78 KB
/
endpoint.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
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package contact
import (
"context"
"sync"
"time"
"go.uber.org/zap"
"storj.io/common/identity"
"storj.io/common/pb"
"storj.io/common/rpc/rpcpeer"
"storj.io/common/rpc/rpcstatus"
)
// Endpoint implements the contact service Endpoints.
//
// architecture: Endpoint
type Endpoint struct {
log *zap.Logger
pingStats *PingStats
}
// PingStats contains information regarding when the node was last pinged.
type PingStats struct {
mu sync.Mutex
lastPinged time.Time
}
// NewEndpoint returns a new contact service endpoint.
func NewEndpoint(log *zap.Logger, pingStats *PingStats) *Endpoint {
return &Endpoint{
log: log,
pingStats: pingStats,
}
}
// PingNode provides an easy way to verify a node is online and accepting requests.
func (endpoint *Endpoint) PingNode(ctx context.Context, req *pb.ContactPingRequest) (_ *pb.ContactPingResponse, err error) {
defer mon.Task()(&ctx)(&err)
peer, err := rpcpeer.FromContext(ctx)
if err != nil {
return nil, rpcstatus.Error(rpcstatus.Internal, err.Error())
}
peerID, err := identity.PeerIdentityFromPeer(peer)
if err != nil {
return nil, rpcstatus.Error(rpcstatus.Unauthenticated, err.Error())
}
endpoint.log.Debug("pinged", zap.Stringer("by", peerID.ID), zap.Stringer("srcAddr", peer.Addr))
endpoint.pingStats.WasPinged(time.Now())
return &pb.ContactPingResponse{}, nil
}
// WhenLastPinged returns last time someone pinged this node.
func (stats *PingStats) WhenLastPinged() (when time.Time) {
stats.mu.Lock()
defer stats.mu.Unlock()
return stats.lastPinged
}
// WasPinged notifies the service it has been remotely pinged.
func (stats *PingStats) WasPinged(when time.Time) {
stats.mu.Lock()
defer stats.mu.Unlock()
stats.lastPinged = when
}