-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathhandler.go
287 lines (228 loc) · 7.19 KB
/
handler.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
package simplefixgo
import (
"context"
"errors"
"fmt"
"sync"
"github.com/b2broker/simplefix-go/fix"
"github.com/b2broker/simplefix-go/session/messages"
"github.com/b2broker/simplefix-go/utils"
)
const AllMsgTypes = "ALL"
// SendingMessage provides a basic method for sending messages.
type SendingMessage interface {
HeaderBuilder() messages.HeaderBuilder
MsgType() string
ToBytes() ([]byte, error)
}
// DefaultHandler is a standard handler for the Acceptor and Initiator objects.
type DefaultHandler struct {
mu sync.Mutex
out chan []byte
incoming chan []byte
incomingHandlers IncomingHandlerPool
outgoingHandlers OutgoingHandlerPool
eventHandlers *utils.EventHandlerPool
msgTypeTag string
ctx context.Context
cancel context.CancelFunc
errors chan error
}
// NewAcceptorHandler creates a handler for an Acceptor object.
func NewAcceptorHandler(ctx context.Context, msgTypeTag string, bufferSize int) *DefaultHandler {
sh := &DefaultHandler{
msgTypeTag: msgTypeTag,
eventHandlers: utils.NewEventHandlerPool(),
out: make(chan []byte, bufferSize),
incoming: make(chan []byte, bufferSize),
errors: make(chan error),
incomingHandlers: NewIncomingHandlerPool(),
outgoingHandlers: NewOutgoingHandlerPool(),
}
sh.ctx, sh.cancel = context.WithCancel(ctx)
return sh
}
// NewInitiatorHandler creates a handler for the Initiator object.
func NewInitiatorHandler(ctx context.Context, msgTypeTag string, bufferSize int) *DefaultHandler {
sh := &DefaultHandler{
msgTypeTag: msgTypeTag,
eventHandlers: utils.NewEventHandlerPool(),
out: make(chan []byte, bufferSize),
incoming: make(chan []byte, bufferSize),
errors: make(chan error),
incomingHandlers: NewIncomingHandlerPool(),
outgoingHandlers: NewOutgoingHandlerPool(),
}
sh.ctx, sh.cancel = context.WithCancel(ctx)
return sh
}
func (h *DefaultHandler) sendRaw(data []byte) error {
select {
case h.out <- data:
case <-h.ctx.Done():
return fmt.Errorf("the handler is stopped")
}
return nil
}
func (h *DefaultHandler) send(msg SendingMessage) error {
ok := h.outgoingHandlers.Range(AllMsgTypes, func(handle OutgoingHandlerFunc) bool {
return handle(msg)
})
if !ok {
return errors.New("the handler for all message types has refused the message and returned false")
}
ok = h.outgoingHandlers.Range(msg.MsgType(), func(handle OutgoingHandlerFunc) bool {
return handle(msg)
})
if !ok {
return errors.New("the handler for the current type has refused the message and returned false")
}
data, err := msg.ToBytes()
if err != nil {
return err
}
return h.sendRaw(data)
}
// SendRaw sends a message in the byte array format
// without involving any additional handlers.
func (h *DefaultHandler) SendRaw(data []byte) error {
return h.sendRaw(data)
}
// Send is a function that sends a previously prepared message.
func (h *DefaultHandler) Send(message SendingMessage) error {
h.mu.Lock()
defer h.mu.Unlock()
return h.send(message)
}
// SendBatch is a function that sends previously prepared messages.
func (h *DefaultHandler) SendBatch(messages []SendingMessage) error {
h.mu.Lock()
defer h.mu.Unlock()
for _, message := range messages {
err := h.send(message)
if err != nil {
return err
}
}
return nil
}
// RemoveIncomingHandler removes an existing handler for incoming messages.
func (h *DefaultHandler) RemoveIncomingHandler(msgType string, id int64) (err error) {
return h.incomingHandlers.Remove(msgType, id)
}
// RemoveOutgoingHandler removes an existing handler for outgoing messages.
func (h *DefaultHandler) RemoveOutgoingHandler(msgType string, id int64) (err error) {
return h.outgoingHandlers.Remove(msgType, id)
}
// HandleIncoming subscribes a handler function to incoming messages with a specific msgType.
// To subscribe to all messages, specify the AllMsgTypes constant for the msgType field
// (such messages will have a higher priority than the ones assigned to specific handlers).
func (h *DefaultHandler) HandleIncoming(msgType string, handle IncomingHandlerFunc) (id int64) {
return h.incomingHandlers.Add(msgType, handle)
}
// HandleOutgoing subscribes a handler function to outgoing messages with a specific msgType
// (this may be required for modifying messages before sending).
// To subscribe to all messages, specify the AllMsgTypes constant for the msgType field
// (such messages will have a higher priority than the ones assigned to specific handlers).
func (h *DefaultHandler) HandleOutgoing(msgType string, handle OutgoingHandlerFunc) (id int64) {
return h.outgoingHandlers.Add(msgType, handle)
}
// ServeIncoming is an internal method for handling incoming messages.
func (h *DefaultHandler) ServeIncoming(msg []byte) {
h.incoming <- msg
}
func (h *DefaultHandler) serve(msg []byte) (err error) {
msgTypeB, err := fix.ValueByTag(msg, h.msgTypeTag)
if err != nil {
return fmt.Errorf("msg type: %w", err)
}
msgType := string(msgTypeB)
h.incomingHandlers.Range(AllMsgTypes, func(handle IncomingHandlerFunc) bool {
return handle(msg)
})
h.incomingHandlers.Range(msgType, func(handle IncomingHandlerFunc) bool {
return handle(msg)
})
return nil
}
// Run is a function that is used for listening and processing messages.
func (h *DefaultHandler) Run() (err error) {
h.eventHandlers.Trigger(utils.EventConnect)
defer h.processRemainingErrors()
for {
select {
case msg, ok := <-h.incoming:
if !ok {
return ErrConnClosed
}
err = h.serve(msg)
if err != nil {
return err
}
case <-h.ctx.Done():
h.processRemainingIncoming()
h.eventHandlers.Trigger(utils.EventStopped)
return
case err := <-h.errors:
h.processRemainingIncoming()
if errors.Is(err, ErrConnClosed) {
h.eventHandlers.Trigger(utils.EventDisconnect)
}
return err
}
}
}
func (h *DefaultHandler) processRemainingIncoming() {
for {
select {
case msg, ok := <-h.incoming:
if ok {
_ = h.serve(msg)
}
default:
return
}
}
}
func (h *DefaultHandler) processRemainingErrors() {
go func() {
for {
_, ok := <-h.errors
if !ok {
return
}
}
}()
}
func (h *DefaultHandler) Context() context.Context {
return h.ctx
}
// Outgoing is a service method that provides an outgoing channel
// to the server or client connection manager.
func (h *DefaultHandler) Outgoing() <-chan []byte {
return h.out
}
// Stop is a function that enables graceful termination of a session.
func (h *DefaultHandler) Stop() {
h.cancel()
}
// StopWithError is a function that enables graceful termination of a session with throwing an error.
func (h *DefaultHandler) StopWithError(err error) {
h.errors <- err
}
// CloseErrorChan is a function that closes the handler's error chan.
func (h *DefaultHandler) CloseErrorChan() {
close(h.errors)
}
// OnDisconnect handles disconnection events.
func (h *DefaultHandler) OnDisconnect(handlerFunc utils.EventHandlerFunc) {
h.eventHandlers.Handle(utils.EventDisconnect, handlerFunc)
}
// OnConnect handles connection events.
func (h *DefaultHandler) OnConnect(handlerFunc utils.EventHandlerFunc) {
h.eventHandlers.Handle(utils.EventConnect, handlerFunc)
}
// OnStopped handles session termination events.
func (h *DefaultHandler) OnStopped(handlerFunc utils.EventHandlerFunc) {
h.eventHandlers.Handle(utils.EventStopped, handlerFunc)
}