rutina/options.go

123 lines
1.9 KiB
Go
Raw Permalink Normal View History

2019-01-17 07:54:39 +03:00
package rutina
import (
"context"
2021-03-18 17:58:00 +03:00
"os"
"time"
)
type Options struct {
ParentContext context.Context
2021-03-18 17:58:00 +03:00
ListenOsSignals []os.Signal
Logger func(format string, v ...interface{})
Errors chan error
}
2021-03-18 17:58:00 +03:00
func ParentContext(ctx context.Context) Options {
return Options{
ParentContext: ctx,
}
}
2021-03-18 17:58:00 +03:00
func ListenOsSignals(signals ...os.Signal) Options {
return Options{
ListenOsSignals: signals,
}
}
2021-03-18 17:58:00 +03:00
func Logger(l logger) Options {
return Options{
Logger: l,
}
}
2021-03-18 17:58:00 +03:00
func Errors(errCh chan error) Options {
return Options{
Errors: errCh,
}
}
2021-03-18 17:58:00 +03:00
func composeOptions(opts []Options) Options {
res := Options{
ParentContext: context.Background(),
Logger: nopLogger,
ListenOsSignals: []os.Signal{},
}
for _, o := range opts {
if o.ParentContext != nil {
res.ParentContext = o.ParentContext
}
if o.Errors != nil {
res.Errors = o.Errors
}
if o.ListenOsSignals != nil {
res.ListenOsSignals = o.ListenOsSignals
}
if o.Logger != nil {
res.Logger = o.Logger
}
}
return res
}
type Policy int
const (
DoNothing Policy = iota
Shutdown
Restart
2019-01-17 07:54:39 +03:00
)
type RunOptions struct {
OnDone Policy
OnError Policy
Timeout *time.Duration
MaxCount *int
}
2021-03-18 17:58:00 +03:00
func OnDone(policy Policy) RunOptions {
return RunOptions{
OnDone: policy,
}
}
2021-03-18 17:58:00 +03:00
func OnError(policy Policy) RunOptions {
return RunOptions{
OnError: policy,
}
}
2021-03-18 17:58:00 +03:00
func Timeout(timeout time.Duration) RunOptions {
return RunOptions{
Timeout: &timeout,
}
}
2021-03-18 17:58:00 +03:00
func MaxCount(maxCount int) RunOptions {
return RunOptions{
MaxCount: &maxCount,
}
}
2021-03-18 17:58:00 +03:00
func composeRunOptions(opts []RunOptions) RunOptions {
res := RunOptions{
OnDone: Shutdown,
OnError: Shutdown,
}
for _, o := range opts {
if o.OnDone != res.OnDone {
res.OnDone = o.OnDone
}
if o.OnError != res.OnError {
res.OnError = o.OnError
}
if o.MaxCount != nil {
res.MaxCount = o.MaxCount
}
if o.Timeout != nil {
res.Timeout = o.Timeout
}
}
return res
}