/
mem_crawler.go
84 lines (73 loc) · 1.99 KB
/
mem_crawler.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
package queue
import (
"context"
"fmt"
"time"
pkgctx "github.com/arschles/crathens/pkg/ctx"
"github.com/arschles/crathens/pkg/log"
"github.com/arschles/crathens/pkg/resp"
"github.com/google/go-github/github"
"github.com/pkg/errors"
)
type inMemoryCrawler struct {
ghFetchCoord pkgctx.Coordinator
athensWarmCoord pkgctx.Coordinator
}
// InMemory creates a new crawler implementation that works only in memory
func InMemory(
ctx context.Context,
endpoint string,
ghCl *github.Client,
ghTickDur time.Duration,
athensTickDur time.Duration,
) Crawler {
ghFetchCoordinator := pkgctx.CoordinatorFromCtx(ctx, ghTickDur)
athensWarmCoordinator := pkgctx.CoordinatorFromCtx(ctx, athensTickDur)
go ghFetcher(ghFetchCoordinator, ghCl, athensWarmCoordinator.Ch())
go athensWarmer(endpoint, athensWarmCoordinator)
return &inMemoryCrawler{
ghFetchCoord: ghFetchCoordinator,
athensWarmCoord: athensWarmCoordinator,
}
}
func (i *inMemoryCrawler) Enqueue(
ctx context.Context,
mav resp.ModuleAndVersion,
) error {
select {
case i.ghFetchCoord.Ch() <- mav:
log.Debug("enqueued %s onto the in-memory crawler", mav)
return nil
case <-ctx.Done():
return errors.WithStack(fmt.Errorf(
"Failed to start crawling module %s due to context timeout",
mav.Module,
))
}
}
func (i *inMemoryCrawler) Wait(context.Context) error {
select {
case <-i.athensWarmCoord.DoneCh():
log.Debug(
"The Athens warmer stopped, cleaning up tickers/contexts and error-ing",
)
i.stopTickers()
i.stopContexts()
return errors.WithStack(fmt.Errorf("Athens fetcher stopped"))
case <-i.ghFetchCoord.DoneCh():
log.Debug(
"The GitHub fetcher stopped, cleaning up tickers/contexts and error-ing",
)
i.stopTickers()
i.stopContexts()
return errors.WithStack(fmt.Errorf("Github fetcher stopped"))
}
}
func (i *inMemoryCrawler) stopTickers() {
i.ghFetchCoord.Ticker().Stop()
i.athensWarmCoord.Ticker().Stop()
}
func (i *inMemoryCrawler) stopContexts() {
i.ghFetchCoord.StopCtx()
i.athensWarmCoord.StopCtx()
}