This repository has been archived by the owner on Mar 1, 2024. It is now read-only.
forked from alpacahq/marketstore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
writtenIndexes.go
83 lines (72 loc) · 1.78 KB
/
writtenIndexes.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
package executor
import (
"runtime/debug"
"sync"
"time"
"github.com/golang/glog"
"github.com/alpacahq/marketstore/plugins/trigger"
)
var once sync.Once
var c chan writtenIndexes
var done chan struct{}
var m map[string][]int64
var triggerWg sync.WaitGroup
type writtenIndexes struct {
key string
indexes []int64
}
func setup() {
c = make(chan writtenIndexes, WriteChannelCommandDepth)
done = make(chan struct{})
go run()
}
// AddWrittenIndex collects the index value from the serialized buffer.
func addWrittenIndex(keyPath string, index int64) {
once.Do(setup)
if m == nil {
m = make(map[string][]int64)
}
m[keyPath] = append(m[keyPath], index)
}
// DispatchWrittenIndexes iterates over the registered triggers and fire the event
// if the file path matches the condition. This is meant to be
// run in a separate goroutine and recovers from panics in the triggers.
func dispatchWrittenIndexes() {
for key, indexes := range m {
c <- writtenIndexes{key: key, indexes: indexes}
}
m = nil // for GC
}
func run() {
defer func() { done <- struct{}{} }()
for wi := range c {
for _, tmatcher := range ThisInstance.TriggerMatchers {
if tmatcher.Match(wi.key) {
triggerWg.Add(1)
go fire(tmatcher.Trigger, wi.key, wi.indexes)
}
}
}
}
func fire(trig trigger.Trigger, key string, indexes []int64) {
defer func() {
triggerWg.Done()
if r := recover(); r != nil {
glog.Errorf("recovering from %v\n%s", r, string(debug.Stack()))
}
}()
trig.Fire(key, indexes)
}
// FinishAndWait closes the writtenIndexes channel, and waits
// for the remaining triggers to fire, returning
func FinishAndWait() {
triggerWg.Wait()
for {
if len(ThisInstance.TXNPipe.writeChannel) == 0 && len(c) == 0 {
close(c)
<-done
return
}
time.Sleep(500 * time.Millisecond)
}
}