-
Notifications
You must be signed in to change notification settings - Fork 30
/
main.go
122 lines (102 loc) · 2.17 KB
/
main.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
package source
import (
"context"
"errors"
"fmt"
"net"
"runtime"
"sync/atomic"
"time"
"github.com/replicase/pgcapture/pkg/cursor"
"github.com/replicase/pgcapture/pkg/pb"
)
type Change struct {
Checkpoint cursor.Checkpoint
Message *pb.Message
}
type Source interface {
Capture(cp cursor.Checkpoint) (changes chan Change, err error)
Commit(cp cursor.Checkpoint)
Error() error
Stop() error
}
type RequeueSource interface {
Source
Requeue(cp cursor.Checkpoint, reason string)
}
type BaseSource struct {
ReadTimeout time.Duration
state int64
stopped chan struct{}
err atomic.Value
}
func (b *BaseSource) Capture(cp cursor.Checkpoint) (changes chan Change, err error) {
panic("implement me")
}
func (b *BaseSource) Commit(cp cursor.Checkpoint) {
panic("implement me")
}
func (b *BaseSource) Stop() error {
switch atomic.LoadInt64(&b.state) {
case 1, 2:
for !atomic.CompareAndSwapInt64(&b.state, 2, 3) {
runtime.Gosched()
}
fallthrough
case 3:
<-b.stopped
}
return b.Error()
}
func (b *BaseSource) Error() error {
if err, ok := b.err.Load().(error); ok {
return err
}
return nil
}
func (b *BaseSource) capture(readFn ReadFn, flushFn FlushFn) (chan Change, error) {
if !atomic.CompareAndSwapInt64(&b.state, 0, 1) {
return nil, nil
}
b.stopped = make(chan struct{})
changes := make(chan Change, 1000)
atomic.StoreInt64(&b.state, 2)
timeout := b.ReadTimeout
if timeout == 0 {
timeout = 5 * time.Second
}
go func() {
defer close(b.stopped)
defer close(changes)
defer flushFn()
for {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
change, err := readFn(ctx)
cancel()
if atomic.LoadInt64(&b.state) != 2 {
return
}
if isTimeout(err) {
continue
}
if err != nil {
b.err.Store(fmt.Errorf("%w", err))
return
}
if change.Message != nil {
changes <- change
}
}
}()
return changes, nil
}
type CaptureFn func(changes chan Change) error
type FlushFn func()
type ReadFn func(ctx context.Context) (Change, error)
func isTimeout(err error) bool {
if errors.Is(err, context.DeadlineExceeded) {
return true
}
var netErr net.Error
return errors.As(err, &netErr) && netErr.Timeout()
}