-
Notifications
You must be signed in to change notification settings - Fork 43
/
payload_channel.go
282 lines (240 loc) · 6.98 KB
/
payload_channel.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
package mediasoup
import (
"encoding/json"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/go-logr/logr"
"github.com/jiyeyuran/mediasoup-go/netcodec"
)
type payloadChannelSubscriber func(event string, data, payload []byte)
type notifyInfo struct {
requestData []byte
payloadData []byte
respCh chan workerResponse
}
type PayloadChannel struct {
locker sync.Mutex
codec netcodec.Codec
logger logr.Logger
closed int32
nextId int64
sents sync.Map
pendingNotification *notification
sentChan chan sentInfo
closeCh chan struct{}
useHandlerID bool
subscribers sync.Map
}
func newPayloadChannel(codec netcodec.Codec, useHandlerID bool) *PayloadChannel {
logger := NewLogger("PayloadChannel")
logger.V(1).Info("constructor()", "useHandlerID", useHandlerID)
channel := &PayloadChannel{
logger: logger,
codec: codec,
sentChan: make(chan sentInfo),
closeCh: make(chan struct{}),
useHandlerID: useHandlerID,
}
return channel
}
func (c *PayloadChannel) Start() {
go c.runWriteLoop()
go c.runReadLoop()
}
func (c *PayloadChannel) Close() error {
if atomic.CompareAndSwapInt32(&c.closed, 0, 1) {
c.logger.V(1).Info("close()")
close(c.closeCh)
return c.codec.Close()
}
return nil
}
func (c *PayloadChannel) Closed() bool {
return atomic.LoadInt32(&c.closed) > 0
}
func (c *PayloadChannel) Notify(event string, internal internalData, data string, payload []byte) (err error) {
if c.Closed() {
return NewInvalidStateError("PayloadChannel closed")
}
var request []byte
if c.useHandlerID {
request = []byte(fmt.Sprintf("n:%s:%s:%s", event, internal.HandlerID(event), data))
} else {
rawData, _ := json.Marshal(H{"ppid": data})
notification := workerNotification{
Event: event,
Internal: internal,
Data: rawData,
}
request, _ = json.Marshal(notification)
}
if len(request) > NS_MESSAGE_MAX_LEN {
return errors.New("PayloadChannel notification too big")
}
if len(payload) > NS_PAYLOAD_MAX_LEN {
return errors.New("PayloadChannel payload too big")
}
return c.writeAll(request, payload)
}
func (c *PayloadChannel) Request(method string, internal internalData, data string, payload []byte) (rsp workerResponse) {
if c.Closed() {
rsp.err = NewInvalidStateError("PayloadChannel closed")
return
}
id := atomic.AddInt64(&c.nextId, 1)
atomic.CompareAndSwapInt64(&c.nextId, 4294967295, 1)
c.logger.V(1).Info("request()", "method", method, "id", id)
var request []byte
if c.useHandlerID {
handlerID := internal.HandlerID(method)
request = []byte(fmt.Sprintf("r:%d:%s:%s:%s", id, method, handlerID, data))
} else {
rawData, _ := json.Marshal(H{"ppid": data})
request, _ = json.Marshal(workerRequest{
Id: id,
Method: method,
Internal: internal,
Data: rawData,
})
}
if len(request) > NS_MESSAGE_MAX_LEN {
return workerResponse{err: errors.New("PayloadChannel request too big")}
}
if len(payload) > NS_PAYLOAD_MAX_LEN {
return workerResponse{err: errors.New("PayloadChannel payload too big")}
}
sent := sentInfo{
method: method,
request: request,
payload: payload,
respCh: make(chan workerResponse),
}
c.sents.Store(id, sent)
defer c.sents.Delete(id)
timer := time.NewTimer(3 * time.Second)
defer timer.Stop()
// send request
select {
case c.sentChan <- sent:
case <-timer.C:
rsp.err = fmt.Errorf("PayloadChannel request timeout, id: %d, method: %s", id, method)
case <-c.closeCh:
rsp.err = NewInvalidStateError("PayloadChannel closed, id: %d, method: %s", id, method)
}
if rsp.err != nil {
return
}
// wait response
select {
case rsp = <-sent.respCh:
case <-timer.C:
rsp.err = fmt.Errorf("PayloadChannel response timeout, id: %d, method: %s", id, method)
case <-c.closeCh:
rsp.err = NewInvalidStateError("PayloadChannel closed, id: %d, method: %s", id, method)
}
return
}
func (c *PayloadChannel) Subscribe(targetId string, handler payloadChannelSubscriber) {
c.subscribers.Store(targetId, handler)
}
func (c *PayloadChannel) Unsubscribe(targetId string) {
c.subscribers.Delete(targetId)
}
func (c *PayloadChannel) runWriteLoop() {
defer c.Close()
for {
select {
case sentInfo := <-c.sentChan:
if err := c.writeAll(sentInfo.request, sentInfo.payload); err != nil {
sentInfo.respCh <- workerResponse{err: err}
break
}
case <-c.closeCh:
return
}
}
}
func (c *PayloadChannel) writeAll(data, payload []byte) (err error) {
c.locker.Lock()
defer c.locker.Unlock()
if err = c.codec.WritePayload(data); err != nil {
return
}
if len(payload) > 0 {
if err = c.codec.WritePayload(payload); err != nil {
return
}
}
return
}
func (c *PayloadChannel) runReadLoop() {
defer c.Close()
for {
payload, err := c.codec.ReadPayload()
if err != nil {
c.logger.Error(err, "read failed")
break
}
c.processPayload(payload)
}
}
func (c *PayloadChannel) processPayload(payload []byte) {
if notify := c.pendingNotification; notify != nil {
c.pendingNotification = nil
if handler, ok := c.subscribers.Load(notify.TargetId); ok {
handler.(payloadChannelSubscriber)(notify.Event, notify.Data, payload)
c.logger.V(1).Info("received a notification", "targetId", notify.TargetId, "event", notify.Event)
} else {
c.logger.V(1).Info("received an unhandled notification", "targetId", notify.TargetId, "event", notify.Event)
}
return
}
var msg struct {
// response meta info
Id int64 `json:"id,omitempty"`
Accepted bool `json:"accepted,omitempty"`
Error string `json:"error,omitempty"`
Reason string `json:"reason,omitempty"`
// notification meta info
TargetId string `json:"targetId,omitempty"`
Event string `json:"event,omitempty"`
// response or notification data
Data json.RawMessage `json:"data,omitempty"`
}
if err := json.Unmarshal(payload, &msg); err != nil {
c.logger.Error(err, "received response unmarshal failed", "id", msg.Id, "payload", payload)
return
}
if msg.Id > 0 {
value, ok := c.sents.Load(msg.Id)
if !ok {
c.logger.Error(nil, "received response does not match any sent request", "id", msg.Id)
return
}
sent := value.(sentInfo)
if msg.Accepted {
c.logger.V(1).Info("request succeeded", "method", sent.method, "id", msg.Id)
sent.respCh <- workerResponse{data: msg.Data}
} else if len(msg.Error) > 0 {
c.logger.Error(errors.New(msg.Reason), "request failed", "method", sent.method, "id", msg.Id)
if msg.Error == "TypeError" {
sent.respCh <- workerResponse{err: NewTypeError(msg.Reason)}
} else {
sent.respCh <- workerResponse{err: errors.New(msg.Reason)}
}
} else {
c.logger.Error(nil, "received response is not accepted nor rejected", "method", sent.method, "id", msg.Id)
}
} else if len(msg.TargetId) > 0 && len(msg.Event) > 0 {
c.pendingNotification = ¬ification{
TargetId: msg.TargetId,
Event: msg.Event,
Data: msg.Data,
}
} else {
c.logger.Error(nil, "received message is not a response nor a notification")
}
}