-
Notifications
You must be signed in to change notification settings - Fork 1
/
timer.go
64 lines (53 loc) · 1.61 KB
/
timer.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
package incr
import (
"context"
"fmt"
"time"
)
// Timer returns a special node type that fires if a given duration
// has elapsed since it last stabilized.
//
// When it stabilizes, it assumes the value of the input node, and causes
// any children (i.e. nodes that take the timer as input) to recompute if this
// is the first stabilization or if the timer has elapsed.
func Timer[A any](scope Scope, input Incr[A], every time.Duration) Incr[A] {
return WithinScope(scope, &timerIncr[A]{
n: NewNode("timer"),
clockSource: func(_ context.Context) time.Time { return time.Now().UTC() },
every: every,
input: input,
})
}
var (
_ Incr[struct{}] = (*timerIncr[struct{}])(nil)
_ IAlways = (*timerIncr[struct{}])(nil)
_ ICutoff = (*timerIncr[struct{}])(nil)
_ IStabilize = (*timerIncr[struct{}])(nil)
_ fmt.Stringer = (*timerIncr[struct{}])(nil)
)
type timerIncr[A any] struct {
n *Node
clockSource func(context.Context) time.Time
last time.Time
every time.Duration
input Incr[A]
value A
}
func (ti *timerIncr[A]) Parents() []INode {
return []INode{ti.input}
}
func (ti *timerIncr[A]) Node() *Node { return ti.n }
func (ti *timerIncr[A]) Value() A { return ti.value }
func (ti *timerIncr[A]) Always() {}
func (ti *timerIncr[A]) Cutoff(ctx context.Context) (bool, error) {
now := ti.clockSource(ctx)
return now.Sub(ti.last) < ti.every, nil
}
func (ti *timerIncr[A]) Stabilize(ctx context.Context) error {
ti.last = ti.clockSource(ctx)
ti.value = ti.input.Value()
return nil
}
func (ti *timerIncr[A]) String() string {
return ti.n.String()
}