-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpuller.go
121 lines (92 loc) · 2.03 KB
/
puller.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
120
121
package main
import (
"fmt"
"time"
"github.com/spf13/viper"
"github.com/train-cat/client-train-go"
"github.com/train-cat/watcher-transilien/cache"
"github.com/train-cat/watcher-transilien/sncf"
"github.com/train-cat/watcher-transilien/utils"
"github.com/train-cat/client-train-go/filters"
)
var (
stations = []traincat.Station{}
limitPerWave = 0
cj = make(chan job)
// ErrNoStationsAvailable is returned when no stations is available for realtime
ErrNoStationsAvailable = fmt.Errorf("no stations available")
)
func init() {
limitPerWave = viper.GetInt("watcher.max_call_per_wave")
}
func pull(quit <-chan struct{}) (chan job, error) {
ticker := time.NewTicker(time.Second * time.Duration(viper.GetInt("watcher.second_between_call")))
cs, err := stationDistributor()
if err != nil {
return nil, err
}
f := wave(cs)
go func() {
for {
select {
case <-ticker.C:
f()
case <-quit:
fmt.Println("Puller stopped")
ticker.Stop()
close(cj)
return
}
}
}()
return cj, nil
}
func wave(c <-chan traincat.Station) func() {
return func() {
for i := 0; i < limitPerWave; i++ {
go func() {
station := <-c
passages, err := sncf.API.GetPassages(station)
if err != nil {
utils.Error(err.Error())
return
}
if len(passages) == 0 {
cache.Ban(cache.BuildKeyBanStation(station), viper.GetInt("watcher.ban.no_passage"))
return
}
cj <- job{station: station, passages: passages}
}()
}
}
}
func stationDistributor() (<-chan traincat.Station, error) {
var err error
max := 100
f := &filters.Station{Pagination: filters.Pagination{MaxPerPage: &max}}
stations, err = traincat.CGetAllStations(f)
if err != nil {
return nil, err
}
l := len(stations)
if l == 0 {
return nil, ErrNoStationsAvailable
}
c := make(chan traincat.Station)
go func() {
// TODO refresh list stations sometimes
defer close(c)
i := 0
for {
s := stations[i]
if !IsBan(s) {
c <- s
}
i++
if i == l {
i = 0
}
}
}()
return c, nil
}