cic-custodial/internal/tasker/server.go

78 lines
1.7 KiB
Go
Raw Permalink Normal View History

2022-11-30 10:51:24 +01:00
package tasker
import (
"context"
"time"
"github.com/grassrootseconomics/cic-custodial/pkg/logg"
2022-11-30 10:51:24 +01:00
"github.com/grassrootseconomics/cic-custodial/pkg/redis"
"github.com/hibiken/asynq"
"github.com/zerodha/logf"
)
const (
retryRequeueInterval = 2 * time.Second
2022-11-30 10:51:24 +01:00
)
type TaskerServerOpts struct {
Concurrency int
ErrorHandler asynq.ErrorHandler
IsFailureHandler func(error) bool
Logg logf.Logger
LogLevel asynq.LogLevel
RedisPool *redis.RedisPool
RetryHandler asynq.RetryDelayFunc
2022-11-30 10:51:24 +01:00
}
type TaskerServer struct {
mux *asynq.ServeMux
server *asynq.Server
}
func NewTaskerServer(o TaskerServerOpts) *TaskerServer {
server := asynq.NewServer(
o.RedisPool,
asynq.Config{
Concurrency: o.Concurrency,
DelayedTaskCheckInterval: retryRequeueInterval,
ErrorHandler: o.ErrorHandler,
IsFailure: o.IsFailureHandler,
LogLevel: o.LogLevel,
Logger: logg.AsynqCompatibleLogger(o.Logg),
2022-11-30 10:51:24 +01:00
Queues: map[string]int{
string(HighPriority): 7,
string(DefaultPriority): 3,
2022-11-30 10:51:24 +01:00
},
RetryDelayFunc: o.RetryHandler,
2022-11-30 10:51:24 +01:00
},
)
mux := asynq.NewServeMux()
return &TaskerServer{
mux: mux,
server: server,
}
}
func (ts *TaskerServer) RegisterMiddlewareStack(middlewareStack []asynq.MiddlewareFunc) {
ts.mux.Use(middlewareStack...)
}
2022-11-30 10:51:24 +01:00
func (ts *TaskerServer) RegisterHandlers(taskName TaskName, taskHandler func(context.Context, *asynq.Task) error) {
ts.mux.HandleFunc(string(taskName), taskHandler)
}
func (ts *TaskerServer) Start() error {
if err := ts.server.Start(ts.mux); err != nil {
return err
}
return nil
}
func (ts *TaskerServer) Stop() {
ts.server.Stop()
ts.server.Shutdown()
}