-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathstatic-plugin-factory.go
80 lines (70 loc) · 1.88 KB
/
static-plugin-factory.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
package plugin
import (
"context"
"sync"
"github.com/aperturerobotics/controllerbus/bus"
"github.com/aperturerobotics/controllerbus/config"
"github.com/aperturerobotics/controllerbus/controller"
)
// StaticPluginFactory wraps a factory with a pre-close hook.
type StaticPluginFactory struct {
controller.Factory
ctx context.Context
ctxCancel context.CancelFunc
binaryID string
bus bus.Bus
mtx sync.Mutex
preUnload []func()
}
// NewStaticPluginFactory constructs a new static plugin factory.
func NewStaticPluginFactory(
ctx context.Context,
ft controller.Factory,
binaryID string,
bus bus.Bus,
) *StaticPluginFactory {
nctx, nctxCancel := context.WithCancel(ctx)
return &StaticPluginFactory{
Factory: ft,
binaryID: binaryID,
bus: bus,
ctx: nctx,
ctxCancel: nctxCancel,
}
}
// GetContext returns a context that is canceled if the factory is unloaded.
func (s *StaticPluginFactory) GetFactoryContext() context.Context {
return s.ctx
}
// Construct constructs the associated controller given configuration.
func (s *StaticPluginFactory) Construct(
ctx context.Context,
conf config.Config,
opts controller.ConstructOpts,
) (controller.Controller, error) {
subController, err := s.Factory.Construct(ctx, conf, opts)
if err != nil {
return subController, err
}
// Augment logging fields.
opts.Logger = opts.Logger.WithField("plugin-binary-id", s.binaryID)
// Ensure that the controller is removed just before we unload.
s.mtx.Lock()
s.preUnload = append(s.preUnload, func() {
s.bus.RemoveController(subController)
})
s.mtx.Unlock()
return subController, err
}
// Close closes the static plugin factory.
func (s *StaticPluginFactory) Close() {
s.ctxCancel()
s.mtx.Lock()
for _, f := range s.preUnload {
f()
}
s.preUnload = nil
s.mtx.Unlock()
}
// _ is a type assertion
var _ controller.FactoryWithContext = ((*StaticPluginFactory)(nil))