-
Notifications
You must be signed in to change notification settings - Fork 13
/
workers.go
88 lines (72 loc) · 2.1 KB
/
workers.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
// Copyright 2015 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package workertest
import (
"gopkg.in/tomb.v2"
"github.com/juju/worker/v3"
)
// NewErrorWorker returns a Worker that runs until Kill()ed; at which point it
// fails with the supplied error. The caller takes responsibility for causing
// it to be Kill()ed, lest the goroutine be leaked, but the worker has no
// outside interactions or safety concerns so there's no particular need to
// Wait() for it.
func NewErrorWorker(err error) worker.Worker {
w := &errorWorker{err: err}
w.tomb.Go(func() error {
<-w.tomb.Dying()
return nil
})
return w
}
type errorWorker struct {
tomb tomb.Tomb
err error
}
// Kill is part of the worker.Worker interface.
func (w *errorWorker) Kill() {
w.tomb.Kill(w.err)
}
// Wait is part of the worker.Worker interface.
func (w *errorWorker) Wait() error {
return w.tomb.Wait()
}
// NewDeadWorker returns a Worker that's already dead, and always immediately
// returns the supplied error from Wait().
func NewDeadWorker(err error) worker.Worker {
return &deadWorker{err: err}
}
type deadWorker struct {
err error
}
// Kill is part of the worker.Worker interface.
func (w *deadWorker) Kill() {}
// Wait is part of the worker.Worker interface.
func (w *deadWorker) Wait() error {
return w.err
}
// NewForeverWorker returns a Worker that ignores Kill() calls. You must be sure
// to call ReallyKill() to cause the worker to fail with the supplied error,
// lest any goroutines trying to manage it be leaked or blocked forever.
func NewForeverWorker(err error) *ForeverWorker {
w := &ForeverWorker{err: err}
w.tomb.Go(func() error {
<-w.tomb.Dying()
return nil
})
return w
}
// ForeverWorker is a Worker that breaks its contract. Use with care.
type ForeverWorker struct {
tomb tomb.Tomb
err error
}
// Kill is part of the worker.Worker interface.
func (w *ForeverWorker) Kill() {}
// Wait is part of the worker.Worker interface.
func (w *ForeverWorker) Wait() error {
return w.tomb.Wait()
}
// ReallyKill does what Kill should.
func (w *ForeverWorker) ReallyKill() {
w.tomb.Kill(w.err)
}