forked from ty2/ctrader-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
191 lines (157 loc) · 3.68 KB
/
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
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
package ctrader
import (
"bufio"
"crypto/tls"
"encoding/binary"
"errors"
"github.com/google/uuid"
"github.com/ty2/ctrader-go/proto/openapi"
"github.com/vmware/transport-go/bus"
"google.golang.org/protobuf/proto"
"io"
"sync"
"time"
"unsafe"
)
const (
ConnOnClosed = "onClosed"
)
type Conn struct {
addr string
certificate []tls.Certificate
conn *tls.Conn
connected bool
reader io.Reader
messageHandler func(b []byte) error
eventBus bus.EventBus
connCloseMutex sync.Mutex
}
func NewConn(addr string, options ...ConnOption) *Conn {
conn := &Conn{addr: addr, eventBus: bus.NewEventBusInstance()}
for _, option := range options {
option(conn)
}
conn.eventBus.GetChannelManager().CreateChannel(ConnOnClosed)
return conn
}
func (conn *Conn) Connect() error {
if conn.connected {
return nil
}
tlsConfig := &tls.Config{}
if conn.certificate != nil {
tlsConfig.Certificates = conn.certificate
}
c, err := tls.Dial("tcp", conn.addr, tlsConfig)
if err != nil {
return err
}
conn.conn = c
conn.reader = bufio.NewReader(c)
conn.connected = true
go conn.messageLoop()
go conn.keepAlive()
return nil
}
func (conn *Conn) messageLoop() {
for {
err := conn.readMessage()
if err != nil {
err := conn.close(err.Error())
if err != nil {
panic(err)
}
break
}
}
}
func (conn *Conn) readMessage() error {
// read message length
msgLen := make([]byte, 4)
_, err := conn.reader.Read(msgLen)
if err != nil {
return err
}
messageLen := binary.BigEndian.Uint32(msgLen)
// read message content
b := make([]byte, messageLen)
_, err = io.ReadFull(conn.reader, b)
if err != nil {
return err
}
if conn.messageHandler != nil {
return conn.messageHandler(b)
}
return nil
}
func (conn *Conn) keepAlive() {
for range time.Tick(time.Second * 10) {
if conn.connected {
req := &openapi.ProtoOASubscribeSpotsReq{}
_, _ = conn.SendMessage(uint32(openapi.ProtoPayloadType_HEARTBEAT_EVENT), req, nil)
}
}
}
func (conn *Conn) SendByte(b []byte) error {
if conn.conn == nil {
return errors.New("connection is not established")
}
size := ToByteArray(len(b))
Reverse(size)
if err := conn.conn.SetWriteDeadline(time.Now().Add(time.Second * 5)); err != nil {
return err
}
if _, err := conn.conn.Write(size); err != nil {
return err
}
if err := conn.conn.SetWriteDeadline(time.Now().Add(time.Second * 5)); err != nil {
return err
}
if _, err := conn.conn.Write(b); err != nil {
return err
}
return nil
}
func (conn *Conn) SendMessage(reqType uint32, req proto.Message, clientMsgUuid *uuid.UUID) (*uuid.UUID, error) {
msgUuid, m := RequestMessageToProtoMessage(reqType, req, clientMsgUuid)
b, err := proto.Marshal(m)
if err != nil {
return msgUuid, err
}
return clientMsgUuid, conn.SendByte(b)
}
func (conn *Conn) close(reason string) error {
conn.connCloseMutex.Lock()
defer conn.connCloseMutex.Unlock()
if conn.connected == false {
return nil
}
conn.connected = false
if err := conn.conn.Close(); err != nil {
return err
}
return conn.eventBus.SendBroadcastMessage(ConnOnClosed, reason)
}
func (conn *Conn) OnClosed() (bus.MessageHandler, error) {
return conn.eventBus.ListenFirehose(ConnOnClosed)
}
type ConnOption func(conn *Conn)
func TlsCertificatesConnOption(certificates []tls.Certificate) ConnOption {
return func(conn *Conn) {
conn.certificate = certificates
}
}
func ToByteArray(num int) []byte {
size := 4
arr := make([]byte, size)
for i := 0; i < size; i++ {
byt := *(*uint8)(unsafe.Pointer(uintptr(unsafe.Pointer(&num)) + uintptr(i)))
arr[i] = byt
}
return arr
}
func Reverse(s []byte) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}