-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipe.go
597 lines (502 loc) · 11.5 KB
/
pipe.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
// MIT License
//
// Copyright (c) 2023 Lack
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package flow
import (
"context"
"fmt"
"io"
"sync"
"time"
"github.com/vine-io/flow/api"
log "github.com/vine-io/vine/lib/logger"
)
type CallPack struct {
ctx context.Context
chunk *api.PipeCallRequest
rsp chan []byte
ech chan error
exit chan struct{}
}
func NewCall(ctx context.Context, chunk *api.PipeCallRequest) *CallPack {
p := &CallPack{
ctx: ctx,
chunk: chunk,
rsp: make(chan []byte, 1),
ech: make(chan error, 1),
exit: make(chan struct{}, 1),
}
return p
}
func (p *CallPack) Apply(data []byte) {
select {
case <-p.exit:
default:
p.rsp <- data
}
}
func (p *CallPack) ApplyErr(err error) {
select {
case <-p.exit:
default:
p.ech <- err
}
}
func (p *CallPack) Destroy() {
close(p.rsp)
close(p.ech)
close(p.exit)
}
type StepPack struct {
ctx context.Context
chunk *api.PipeStepRequest
rsp chan map[string]string
ech chan error
exit chan struct{}
}
func NewStep(ctx context.Context, chunk *api.PipeStepRequest) *StepPack {
p := &StepPack{
ctx: ctx,
chunk: chunk,
rsp: make(chan map[string]string, 1),
ech: make(chan error, 1),
exit: make(chan struct{}, 1),
}
return p
}
func (p *StepPack) Apply(data map[string]string) {
select {
case <-p.exit:
default:
p.rsp <- data
}
}
func (p *StepPack) ApplyErr(err error) {
select {
case <-p.exit:
default:
p.ech <- err
}
}
func (p *StepPack) Destroy() {
close(p.rsp)
close(p.ech)
close(p.exit)
}
type PipeStream interface {
Context() context.Context
Send(*api.PipeResponse) error
Recv() (*api.PipeRequest, error)
Close() error
}
type MemberPipeHandler func(*api.PipeResponse) (*api.PipeRequest, error)
type MemberPipeStream struct {
ctx context.Context
cancel context.CancelFunc
id string
queue chan *api.PipeResponse
handler MemberPipeHandler
}
func NewMemberPipeStream(ctx context.Context, id string, handler MemberPipeHandler) *MemberPipeStream {
ctx, cancel := context.WithCancel(ctx)
s := &MemberPipeStream{
ctx: ctx,
cancel: cancel,
id: id,
queue: make(chan *api.PipeResponse, 3),
handler: handler,
}
return s
}
func (s *MemberPipeStream) Context() context.Context {
return s.ctx
}
func (s *MemberPipeStream) Send(req *api.PipeResponse) error {
if s.isClosed() {
return fmt.Errorf("stream closed")
}
s.queue <- req
return nil
}
func (s *MemberPipeStream) Recv() (*api.PipeRequest, error) {
select {
case <-s.ctx.Done():
return nil, io.EOF
case data := <-s.queue:
return s.handler(data)
}
}
func (s *MemberPipeStream) isClosed() bool {
select {
case <-s.ctx.Done():
return true
default:
return false
}
}
func (s *MemberPipeStream) Close() error {
select {
case <-s.ctx.Done():
return fmt.Errorf("already closed")
default:
}
s.cancel()
return nil
}
type Peer struct {
Server string
Client string
}
type ClientPipe struct {
ctx context.Context
Id string
pr *Peer
// sync.RWMutex for revision
rmu sync.Mutex
revision *api.Revision
stream PipeStream
// the queue of the call request
cqueue chan *CallPack
// sync.RWMutex for cmc
cmu sync.RWMutex
// the map of call chancel
cmc map[string]*CallPack
// the queue of the step request
squeue chan *StepPack
// sync.RWMutex for smc
smu sync.RWMutex
// the map of step channel
smc map[string]*StepPack
exit chan struct{}
}
func NewPipe(ctx context.Context, id string, pr *Peer, stream PipeStream) *ClientPipe {
return &ClientPipe{
ctx: ctx,
Id: id,
pr: pr,
revision: api.NewRevision(),
stream: stream,
cmc: map[string]*CallPack{},
cqueue: make(chan *CallPack, 10),
smc: map[string]*StepPack{},
squeue: make(chan *StepPack, 10),
exit: make(chan struct{}, 1),
}
}
func (p *ClientPipe) Call(pack *CallPack) (<-chan []byte, <-chan error) {
select {
case <-p.exit:
pack.ApplyErr(api.ErrCancel("pipe closed"))
case p.cqueue <- pack:
select {
case <-p.ctx.Done():
pack.ApplyErr(api.ErrCancel("pipe closed"))
default:
}
}
return pack.rsp, pack.ech
}
func (p *ClientPipe) Step(pack *StepPack) (<-chan map[string]string, <-chan error) {
select {
case <-p.exit:
pack.ApplyErr(api.ErrCancel("pipe closed"))
case p.squeue <- pack:
}
return pack.rsp, pack.ech
}
func (p *ClientPipe) Start() {
go p.receiving()
p.process()
}
func (p *ClientPipe) process() {
for {
select {
case <-p.exit:
goto EXIT
case pack, ok := <-p.cqueue:
if !ok {
goto EXIT
}
revision := p.forward()
log.Debugf("send call request to %s in %s", p.Id, revision.Readably())
err := p.stream.Send(&api.PipeResponse{
Topic: api.Topic_T_CALL,
Revision: revision,
Call: pack.chunk,
})
if err != nil {
pack.ApplyErr(err)
goto EXIT
}
p.newCallPack(revision.Readably(), pack)
go func() {
select {
case <-p.ctx.Done():
pack.ApplyErr(api.ErrCancel("pipe closed"))
p.delCallPack(revision.Readably())
case <-pack.ctx.Done():
}
}()
case pack, ok := <-p.squeue:
if !ok {
goto EXIT
}
revision := p.forward()
log.Debugf("send step request to %s in %s", p.Id, revision.Readably())
err := p.stream.Send(&api.PipeResponse{
Topic: api.Topic_T_STEP,
Revision: revision,
Step: pack.chunk,
})
if err != nil {
pack.ApplyErr(err)
goto EXIT
}
p.newStepPack(revision.Readably(), pack)
go func() {
select {
case <-p.ctx.Done():
pack.ApplyErr(api.ErrCancel("pipe closed"))
p.delStepPack(revision.Readably())
case <-pack.ctx.Done():
}
}()
}
}
EXIT:
log.Infof("stop worker pipe <%s,%s> process", p.Id, p.pr.Client)
}
func (p *ClientPipe) forward() *api.Revision {
p.rmu.Lock()
defer p.rmu.Unlock()
p.revision.Add()
return p.revision.DeepCopy()
}
func (p *ClientPipe) getCallPack(revision string) (*CallPack, bool) {
p.cmu.RLock()
pack, ok := p.cmc[revision]
p.cmu.RUnlock()
return pack, ok
}
func (p *ClientPipe) newCallPack(revision string, pack *CallPack) {
p.cmu.Lock()
p.cmc[revision] = pack
p.cmu.Unlock()
}
func (p *ClientPipe) delCallPack(revision string) {
p.cmu.Lock()
delete(p.cmc, revision)
p.cmu.Unlock()
}
func (p *ClientPipe) getStepPack(revision string) (*StepPack, bool) {
p.smu.RLock()
pack, ok := p.smc[revision]
p.smu.RUnlock()
return pack, ok
}
func (p *ClientPipe) newStepPack(revision string, pack *StepPack) {
p.smu.Lock()
p.smc[revision] = pack
p.smu.Unlock()
}
func (p *ClientPipe) delStepPack(revision string) {
p.smu.Lock()
delete(p.smc, revision)
p.smu.Unlock()
}
func (p *ClientPipe) handlePing(rsp *api.PipeRequest) {
log.Debugf("reply pong response")
err := p.stream.Send(&api.PipeResponse{Topic: api.Topic_T_PING})
if err != nil {
log.Errorf("reply pong response: %v", err)
}
}
func (p *ClientPipe) handleCall(rsp *api.PipeRequest) {
revision := rsp.Revision.Readably()
pack, ok := p.getCallPack(revision)
if !ok {
log.Errorf("call %s response abort, missing receiver", revision)
return
}
defer p.delCallPack(revision)
select {
case <-pack.ctx.Done():
pack.ApplyErr(api.ErrCancel("pipe handle call request"))
log.Errorf("call %s response abort, receiver cancelled", revision)
return
default:
}
if rsp.Call == nil {
pack.ApplyErr(fmt.Errorf("response is empty"))
return
}
if e := rsp.Call.Error; e != "" {
pack.ApplyErr(api.Parse(e))
return
}
pack.Apply(rsp.Call.Data)
log.Debugf("call %s response finished", revision)
}
func (p *ClientPipe) handleStep(rsp *api.PipeRequest) {
revision := rsp.Revision.Readably()
pack, ok := p.getStepPack(revision)
if !ok {
log.Errorf("step %s response abort, missing receiver", revision)
return
}
defer p.delStepPack(revision)
select {
case <-pack.ctx.Done():
pack.ApplyErr(api.ErrCancel("pipe handle step request"))
log.Errorf("step %s response abort, receiver cancelled", revision)
return
default:
}
log.Debugf("step %s response finished", revision)
if rsp.Step == nil {
pack.ApplyErr(fmt.Errorf("response is empty"))
return
}
if e := rsp.Step.Error; e != "" {
pack.ApplyErr(api.Parse(e))
return
}
pack.Apply(rsp.Step.Out)
}
func (p *ClientPipe) receiving() {
for {
rsp, err := p.stream.Recv()
if err == io.EOF || (err != nil && IsCancelErr(err)) {
log.Infof("pipe %s stop receiving handler", p.Id)
return
}
if err != nil {
log.Errorf("pipe %s receive exception: %+v", p.Id, err)
return
}
log.Debugf("[%s] receive data from %v", rsp.Topic.Readably(), p.pr.Client)
switch rsp.Topic {
case api.Topic_T_PING:
p.handlePing(rsp)
case api.Topic_T_CALL:
p.handleCall(rsp)
case api.Topic_T_STEP:
p.handleStep(rsp)
}
}
}
func (p *ClientPipe) Close() {
p.close()
}
func (p *ClientPipe) close() {
close(p.cqueue)
close(p.squeue)
close(p.exit)
p.smu.Lock()
items := make([]string, 0)
for k, _ := range p.smc {
items = append(items, k)
}
for _, name := range items {
delete(p.smc, name)
}
p.smu.Unlock()
p.cmu.Lock()
items = make([]string, 0)
for k, _ := range p.cmc {
items = append(items, k)
}
for _, name := range items {
delete(p.cmc, name)
}
p.cmu.Unlock()
}
type PipeSet struct {
sync.RWMutex
sets map[string]*ClientPipe
}
func NewPipeSet() *PipeSet {
return &PipeSet{sets: map[string]*ClientPipe{}}
}
func (ps *PipeSet) Add(p *ClientPipe) {
ps.Lock()
defer ps.Unlock()
ps.sets[p.Id] = p
}
func (ps *PipeSet) Del(p *ClientPipe) {
ps.Lock()
defer ps.Unlock()
delete(ps.sets, p.Id)
}
func (ps *PipeSet) Get(id string) (*ClientPipe, bool) {
ps.RLock()
defer ps.RUnlock()
p, ok := ps.sets[id]
return p, ok
}
type WorkerSub struct {
sync.RWMutex
sets map[string]api.FlowRpc_WorkHookStream
}
func NewWorkSub() *WorkerSub {
return &WorkerSub{sets: map[string]api.FlowRpc_WorkHookStream{}}
}
func (ws *WorkerSub) Add(id string, stream api.FlowRpc_WorkHookStream) {
ws.Lock()
defer ws.Unlock()
ws.sets[id] = stream
go streamPing(stream)
return
}
func streamPing(s api.FlowRpc_WorkHookStream) {
ctx := s.Context()
timer := time.NewTicker(time.Second * 10)
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case <-timer.C:
_ = s.Send(
&api.WorkHookResponse{
Result: &api.WorkHookResult{Action: api.HookAction_HA_UNKNOWN}},
)
}
}
}
func (ws *WorkerSub) Del(id string) {
ws.Lock()
delete(ws.sets, id)
ws.Unlock()
return
}
func (ws *WorkerSub) Pub(result *api.WorkHookResult) {
ws.RLock()
defer ws.RUnlock()
for _, stream := range ws.sets {
select {
case <-stream.Context().Done():
continue
default:
_ = stream.Send(&api.WorkHookResponse{Result: result})
}
}
}