-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworkerpool.go
More file actions
109 lines (92 loc) · 2.48 KB
/
workerpool.go
File metadata and controls
109 lines (92 loc) · 2.48 KB
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
/*
Package workerpool provides a service for running small parts of code (called jobs) in a background.
Jobs could have contexts, timeouts, rich retry strategies.
*/
package workerpool
import (
"context"
"runtime"
"sync"
"time"
"github.com/rs/xid"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
// Job is a function that receives context and being run asynchronously by the worker pool.
type Job func(ctx context.Context) error
type Pool struct {
wg *sync.WaitGroup
logger zerolog.Logger
jobs chan Job
stop chan struct{}
numWorkers int
// DefaultContext is a context factory, generates default context for every job
DefaultContext func() context.Context
}
// PoolOption is a functional parameter used in constructor
type PoolOption func(service *Pool)
// New Pool constructor
func New(opts ...PoolOption) *Pool {
s := &Pool{
wg: &sync.WaitGroup{},
logger: log.Logger,
numWorkers: runtime.GOMAXPROCS(0) * 2,
DefaultContext: func() context.Context {
return context.Background()
},
}
for _, o := range opts {
o(s)
}
return s
}
// WithLogger replaces the default logger with the specified one.
func WithLogger(zl zerolog.Logger) PoolOption {
return func(service *Pool) {
service.logger = zl
}
}
// Start required num of workers.
func (s *Pool) Start() {
s.logger.Debug().Int("worker_num", s.numWorkers).Msg("Starting workers")
s.stop = make(chan struct{})
s.jobs = make(chan Job)
s.wg.Add(s.numWorkers)
for i := 0; i < s.numWorkers; i++ {
go func(workerID int) {
defer s.wg.Done()
l := s.logger.With().Int("worker_id", workerID).Logger()
for {
select {
case <-s.stop:
return
case job := <-s.jobs:
id := xid.New()
now := time.Now()
ll := l.With().Str("job_id", id.String()).Logger()
ll.Debug().Msg("Running job")
if err := AddLogger(AddPanicRecovery(job), ll)(s.DefaultContext()); err != nil {
ll.Error().Err(err).Msg("Error running job")
}
ll.Info().Dur("job_duration", time.Since(now)).Msg("Done running job")
}
}
}(i)
}
s.logger.Debug().Msg("Done starting workers")
}
// Stop all active workers.
// Don't forget to call this on your application shutdown.
//
// This call is blocking and waits for all the jobs to complete.
func (s *Pool) Stop() {
s.logger.Debug().Msg("Shutting down workers")
close(s.stop)
s.wg.Wait()
close(s.jobs)
s.logger.Debug().Msg("Done shutting down workers")
}
// Run job within the pool
func (s *Pool) Run(job Job) {
s.jobs <- job
}