-
Notifications
You must be signed in to change notification settings - Fork 31
/
main.go
102 lines (90 loc) · 2.08 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
package sink
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/replicase/pgcapture/pkg/cursor"
"github.com/replicase/pgcapture/pkg/source"
)
type CleanFn func()
type ApplyFn func(sourceRemaining int, message source.Change, committed chan cursor.Checkpoint) error
type Sink interface {
Setup() (cp cursor.Checkpoint, err error)
Apply(changes chan source.Change) (committed chan cursor.Checkpoint)
Error() error
Stop() error
}
type BaseSink struct {
CleanFn CleanFn
cleanOnce sync.Once
committed chan cursor.Checkpoint
state int64
err atomic.Value
}
func (b *BaseSink) Setup() (cp cursor.Checkpoint, err error) {
panic("implement me")
}
func (b *BaseSink) Apply(changes chan source.Change) (committed chan cursor.Checkpoint) {
panic("implement me")
}
func (b *BaseSink) apply(changes chan source.Change, applyFn ApplyFn) (committed chan cursor.Checkpoint) {
if !atomic.CompareAndSwapInt64(&b.state, 0, 1) {
return nil
}
b.committed = make(chan cursor.Checkpoint, 1000)
atomic.StoreInt64(&b.state, 2)
go func() {
ticker := time.NewTicker(time.Second)
for atomic.LoadInt64(&b.state) == 2 {
select {
case change, more := <-changes:
if !more {
goto cleanup
}
if err := applyFn(len(changes), change, b.committed); err != nil {
b.err.Store(fmt.Errorf("%w", err))
goto cleanup
}
case <-ticker.C:
}
}
cleanup:
ticker.Stop()
atomic.StoreInt64(&b.state, 4)
go b.Stop()
for range changes {
// this loop should do nothing and only exit when the input channel is closed
}
}()
return b.committed
}
func (b *BaseSink) Error() error {
if err, ok := b.err.Load().(error); ok {
return err
}
return nil
}
func (b *BaseSink) Stop() error {
switch atomic.LoadInt64(&b.state) {
case 0:
b.cleanOnce.Do(b.CleanFn)
case 1, 2:
for !atomic.CompareAndSwapInt64(&b.state, 2, 3) {
runtime.Gosched()
}
fallthrough
case 3:
for atomic.LoadInt64(&b.state) != 4 {
time.Sleep(time.Millisecond * 100)
}
fallthrough
case 4:
b.cleanOnce.Do(func() {
b.CleanFn()
close(b.committed)
})
}
return b.Error()
}