Abstract worker process for nacelle.
A worker is a process that periodically polls an external resource in order to discover or perform its main unit of work. A base worker is an abstract process whose behavior can be be configured by implementing the WorkerSpec
interface.
This library comes with an example project. You can see an additional example of a worker process in the example repository, specifically the worker spec definition.
A worker process is created by supplying a specification, described below, that controls its behavior.
worker := workerbase.NewWorker(NewWorkerSpec(), options...)
A worker specification is a struct with an Init
and a Tick
method. The initialization method, like the process that runs it, that takes a config object as a parameter. The tick method takes a context object as a parameter. On process shutdown, this context object is cancelled so that any long-running work in the tick method can be cleanly abandoned. Each method may return an error value, which signals a fatal error to the process that runs it.
The following example uses a database connection injected by the service container, and pings it to logs its latency. The worker process will call the tick method in a loop based on its interval configuration while the process remains active.
type Spec struct {
DB *sqlx.DB `service:"db"`
Logger nacelle.Logger `service:"logger"`
}
func (s *Spec) Init(config nacelle.Config) error {
return nil
}
func (s *Spec) Tick(ctx context.Context) error {
start := time.Now()
err := s.DB.Ping()
duration := time.Now().Sub(start)
durationMs := float64(duration) / float64(time.Milliseconds)
if err != nil {
return err
}
s.Logger.Debug("Ping took %.2fms", durationMs)
}
If the worker specification also implements the Finalize
method, it will be called after the last invocation of the tick method (regardless of its return value).
func (s *Spec) Finalize() error {
s.Logger.Debug("Shutting down")
return nil
}
The following options can be supplied to the worker process instance on construction.
- WithTagModifiers
- WithTagModifiers registers the tag modifiers to be used when loading process configuration (see below). This can be used to change the default tick interval, or prefix all target environment variables in the case where more than one worker process is registered per application.
The default process behavior can be configured by the following environment variables.
Environment Variable | Default | Description |
---|---|---|
WORKER_STRICT_CLOCK | false | Subtract the duration of the previous tick from the time between calls to the spec's tick function. |
WORKER_TICK_INTERVAL | 0 | The time (in seconds) between calls to the spec's tick function. |