-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtimeweaver.go
101 lines (84 loc) · 1.91 KB
/
timeweaver.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
package phonelab
// TimeweaverProcessor weaves together two streams of data based on timestamp.
// The logs coming down the source channels must implement the
// MonotonicTimestamper interface, otherwise there will be a panic on a bad
// type assertion.
type TimeweaverProcessor struct {
lhs Processor
rhs Processor
}
type MonotonicTimestamper interface {
MonotonicTimestamp() float64
}
func NewTimeweaverProcessor(lhs, rhs Processor) *TimeweaverProcessor {
return &TimeweaverProcessor{
lhs: lhs,
rhs: rhs,
}
}
// State for tracking timeweaver sources
type timeweaverState struct {
source <-chan interface{}
get bool
ok bool
obj interface{}
}
func newTimeweaverState(source Processor) *timeweaverState {
return &timeweaverState{
source: source.Process(),
get: true,
ok: true,
obj: nil,
}
}
func (state *timeweaverState) updateIfneeded() {
if state.get {
state.obj, state.ok = <-state.source
state.get = false
}
}
func (state *timeweaverState) drain(outChan chan interface{}) {
if state.obj != nil {
outChan <- state.obj
}
for log := range state.source {
outChan <- log
}
}
func (state *timeweaverState) eof() bool {
return !state.ok
}
func (state *timeweaverState) timestamp() float64 {
return (state.obj.(MonotonicTimestamper)).MonotonicTimestamp()
}
func (state *timeweaverState) send(outChan chan interface{}) {
outChan <- state.obj
state.get = true
}
func (tw *TimeweaverProcessor) Process() <-chan interface{} {
lhs := newTimeweaverState(tw.lhs)
rhs := newTimeweaverState(tw.rhs)
outChan := make(chan interface{})
// Process
go func() {
for {
lhs.updateIfneeded()
rhs.updateIfneeded()
if lhs.eof() {
rhs.drain(outChan)
break
} else if rhs.eof() {
lhs.drain(outChan)
break
} else {
if lhs.timestamp() <= rhs.timestamp() {
lhs.send(outChan)
} else {
rhs.send(outChan)
}
}
}
close(outChan)
}()
return outChan
}