tavern/job/job.go

42 lines
865 B
Go

package job
import (
"context"
"net/http"
"time"
"github.com/oklog/run"
"go.uber.org/zap"
)
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
type Job interface {
Run(context.Context) error
Shutdown(context.Context) error
}
func RunWorker(group *run.Group, logger *zap.Logger, j Job, parent context.Context) {
group.Add(func() error {
logger.Info("starting job")
return ignoreCanceled(j.Run(parent))
}, func(error) {
shutdownCtx, shutdownCtxCancel := context.WithTimeout(context.Background(), 30*time.Second)
defer shutdownCtxCancel()
logger.Info("stopping publisher")
err := ignoreCanceled(j.Shutdown(shutdownCtx))
if err != nil {
logger.Error("error stopping job", zap.Error(err))
}
})
}
func ignoreCanceled(err error) error {
if err == nil || err == context.Canceled {
return nil
}
return err
}