github.com/juju/juju@v0.0.0-20240327075706-a90865de2538/worker/filenotifywatcher/manifold.go (about) 1 // Copyright 2023 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package filenotifywatcher 5 6 import ( 7 "github.com/juju/clock" 8 "github.com/juju/errors" 9 "github.com/juju/worker/v3" 10 "github.com/juju/worker/v3/dependency" 11 12 "github.com/juju/juju/worker/common" 13 ) 14 15 // Logger represents the logging methods called. 16 type Logger interface { 17 Errorf(message string, args ...interface{}) 18 Warningf(message string, args ...interface{}) 19 Infof(message string, args ...interface{}) 20 Debugf(message string, args ...interface{}) 21 Tracef(message string, args ...interface{}) 22 IsTraceEnabled() bool 23 } 24 25 // WatcherFn is a function that returns a new Watcher. 26 type WatcherFn = func(string, ...Option) (FileWatcher, error) 27 28 // ManifoldConfig defines the names of the manifolds on which a Manifold will 29 // depend. 30 type ManifoldConfig struct { 31 Clock clock.Clock 32 Logger Logger 33 NewWatcher WatcherFn 34 NewINotifyWatcher func() (INotifyWatcher, error) 35 } 36 37 func (cfg ManifoldConfig) Validate() error { 38 if cfg.Clock == nil { 39 return errors.NotValidf("nil Clock") 40 } 41 if cfg.Logger == nil { 42 return errors.NotValidf("nil Logger") 43 } 44 if cfg.NewWatcher == nil { 45 return errors.NotValidf("nil NewWatcher") 46 } 47 if cfg.NewINotifyWatcher == nil { 48 return errors.NotValidf("nil NewINotifyWatcher") 49 } 50 return nil 51 } 52 53 // Manifold returns a dependency manifold that runs the filenotifywatcher 54 // worker, using the resource names defined in the supplied config. 55 func Manifold(config ManifoldConfig) dependency.Manifold { 56 return dependency.Manifold{ 57 Inputs: []string{}, 58 Output: fileNotifyWatcherOutput, 59 Start: func(context dependency.Context) (worker.Worker, error) { 60 if err := config.Validate(); err != nil { 61 return nil, errors.Trace(err) 62 } 63 64 cfg := WorkerConfig{ 65 Clock: config.Clock, 66 Logger: config.Logger, 67 NewWatcher: config.NewWatcher, 68 NewINotifyWatcher: config.NewINotifyWatcher, 69 } 70 71 w, err := newWorker(cfg) 72 if err != nil { 73 return nil, errors.Trace(err) 74 } 75 return w, nil 76 }, 77 } 78 } 79 80 func fileNotifyWatcherOutput(in worker.Worker, out interface{}) error { 81 if w, ok := in.(*common.CleanupWorker); ok { 82 in = w.Worker 83 } 84 w, ok := in.(*fileNotifyWorker) 85 if !ok { 86 return errors.Errorf("in should be a *fileNotifyWorker; got %T", in) 87 } 88 89 switch out := out.(type) { 90 case *FileNotifyWatcher: 91 var target FileNotifyWatcher = w 92 *out = target 93 default: 94 return errors.Errorf("out should be a *filenotifywatcher.FileNotifyWatcher; got %T", out) 95 } 96 return nil 97 }