-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
133 lines (116 loc) · 2.48 KB
/
config.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
package tentacle
import (
"fmt"
"strconv"
"sync"
"time"
"github.com/hashicorp/yamux"
)
// NameFn define protocol name, default is "/p2p/protocol_id"
//
// Used to interact with the remote service to determine whether the protocol is supported.
//
// If not found, the protocol connection(not session just sub stream) will be closed,
// and return a `ProtocolSelectError` event.
type NameFn = func(ProtocolID) string
// DefaultNameFn default protocol name
var DefaultNameFn = func(id ProtocolID) string {
return fmt.Sprintf("/p2p/%s", strconv.Itoa(int(id)))
}
type meta struct {
id ProtocolID
name NameFn
supportVersions []string
codec CodecFn
selectVersion SelectFn
beforeReceive BeforeReceive
spawn ProtocolSpawn
}
// ProtocolMeta define the minimum data required for a custom protocol
type ProtocolMeta struct {
inner *meta
serviceHandle ServiceProtocol
sessionHandleFn SessionProtocolFn
beforeSend BeforeSend
}
type serviceConfig struct {
timeout time.Duration
yamuxConfig *yamux.Config
maxConnectionNumber uint
channelSize uint
tcpBind *string
wsBind *string
}
const (
// All try open all protocol, target is nil
All uint8 = iota
// Single try open one protocol, target is ProtocolID/SessionID
Single
// Multi try open some protocol, target is []ProtocolID/[]SessionID
Multi
)
// TargetProtocol when dial, specify which protocol want to open
type TargetProtocol struct {
// must use All/Single/Multi
Tag uint8
Target interface{}
}
// TargetSession when sending a message, select the specified session
type TargetSession struct {
// must use All/Single/Multi
Tag uint8
Target interface{}
}
const (
running uint8 = iota
forever
preShutdown
)
type serviceState struct {
workers uint
tag uint8
sync.Mutex
}
func (s *serviceState) decrease() {
s.Lock()
defer s.Unlock()
switch s.tag {
case running:
s.workers--
}
}
func (s *serviceState) increase() {
s.Lock()
defer s.Unlock()
switch s.tag {
case running:
s.workers++
}
}
func (s *serviceState) preShutdown() {
s.Lock()
defer s.Unlock()
s.tag = preShutdown
}
func (s *serviceState) isShutdown() bool {
s.Lock()
defer s.Unlock()
var res bool
switch s.tag {
case running:
res = s.workers == 0
case preShutdown:
res = true
case forever:
res = false
}
return res
}
func (s *serviceState) inner() uint {
switch s.tag {
case running:
return s.workers
default:
return 0
}
}