/
sched.go
119 lines (104 loc) · 2.14 KB
/
sched.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
package config
import (
"context"
"time"
"github.com/undeconstructed/sample/common"
)
type schedReq struct {
resCh chan common.FetchWork
}
type schedEntry struct {
source common.RestSource
time int64
}
type schedTable map[string]*schedEntry
type sched struct {
reqCh chan schedReq
cfgCh chan *cfg
table schedTable
}
func makeSched() (*sched, error) {
reqCh := make(chan schedReq)
cfgCh := make(chan *cfg)
return &sched{
reqCh: reqCh,
cfgCh: cfgCh,
table: schedTable{},
}, nil
}
func (s *sched) Start(ctx context.Context) error {
err := s.loop(ctx)
return err
}
func (s *sched) loop(ctx context.Context) error {
for {
now := time.Now().Unix()
cutoff := now - 60
toDo := findNext(s.table, cutoff)
if toDo == nil {
t := time.After(60 * time.Second)
select {
case <-t:
continue
case c := <-s.cfgCh:
s.table = updateTable(s.table, c.Sources)
case <-ctx.Done():
return ctx.Err()
}
} else {
select {
case r := <-s.reqCh:
toDo.time = now
r.resCh <- common.FetchWork{
Jobs: []*common.FetchJob{
&common.FetchJob{
ID: toDo.source.ID,
URL: toDo.source.Spec.URL,
Store: toDo.source.Spec.Store,
},
},
}
case c := <-s.cfgCh:
s.table = updateTable(s.table, c.Sources)
case <-ctx.Done():
return ctx.Err()
}
}
}
}
func (s *sched) getWork(ctx context.Context) (common.FetchWork, error) {
resCh := make(chan common.FetchWork)
// well, this is horrible now
select {
case s.reqCh <- schedReq{resCh}:
case <-ctx.Done():
return common.FetchWork{}, ctx.Err()
}
select {
case r := <-resCh:
return r, nil
case <-ctx.Done():
return common.FetchWork{}, ctx.Err()
}
}
func updateTable(table schedTable, sources map[string]common.RestSource) schedTable {
ntable := schedTable{}
for _, source := range sources {
old, exists := table[source.ID]
if !exists {
ntable[source.ID] = &schedEntry{source: source}
} else {
// TODO - changed entry
ntable[source.ID] = old
}
}
return ntable
}
func findNext(table schedTable, cutoff int64) *schedEntry {
for _, e := range table {
if e.time < cutoff {
return e
}
}
return nil
}