This repository has been archived by the owner on Feb 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
grpc_conn.go
92 lines (71 loc) · 1.55 KB
/
grpc_conn.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
package hostpool
import (
"fmt"
"sync"
"time"
"github.com/magicpool-co/pool/internal/log"
)
type grpcConn struct {
id string
mu sync.RWMutex
errors uint
enabled bool
synced bool
client GRPCClient
}
func (gc *grpcConn) healthy() bool {
gc.mu.RLock()
defer gc.mu.RUnlock()
return gc.errors < 3
}
func (gc *grpcConn) usable(needsSynced bool) bool {
gc.mu.RLock()
defer gc.mu.RUnlock()
healthy := gc.enabled && gc.errors < 3
if needsSynced {
return healthy && gc.synced
}
return healthy
}
// Run a healthcheck on the given TCP connection.
func (gc *grpcConn) healthCheck(healthCheck *GRPCHealthCheck, logger *log.Logger) int {
var unit = time.Nanosecond
var maxLatency = int(healthCheck.Timeout/unit) * 2
start := time.Now()
_, _, err := gc.exec(healthCheck.Request)
if err != nil {
logger.Error(fmt.Errorf("grpcconn: healthcheck: %s: %v", gc.id, err))
return maxLatency
}
gc.markHealthy(true)
latency := int(time.Since(start) / unit)
return latency
}
// Change a host's healthiness.
func (gc *grpcConn) markHealthy(healthy bool) {
if !healthy {
gc.client.Reconnect()
}
gc.mu.Lock()
defer gc.mu.Unlock()
if healthy {
gc.errors = 0
} else {
gc.errors++
}
}
// Change a host's sync status.
func (gc *grpcConn) markSynced(synced bool) {
gc.mu.Lock()
defer gc.mu.Unlock()
gc.synced = synced
}
// Execute a request.
func (gc *grpcConn) exec(req interface{}) (interface{}, string, error) {
res, err := gc.client.Send(req)
if err != nil {
gc.markHealthy(false)
return nil, gc.id, err
}
return res, gc.id, nil
}