2022-11-30 10:51:24 +01:00
|
|
|
package tasker
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
2023-03-06 09:18:41 +01:00
|
|
|
"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 (
|
2023-03-06 09:18:41 +01:00
|
|
|
retryRequeueInterval = 2 * time.Second
|
2022-11-30 10:51:24 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type TaskerServerOpts struct {
|
2023-03-06 09:18:41 +01:00
|
|
|
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{
|
2023-03-06 09:18:41 +01:00
|
|
|
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{
|
2023-03-06 09:18:41 +01:00
|
|
|
string(HighPriority): 7,
|
|
|
|
string(DefaultPriority): 3,
|
2022-11-30 10:51:24 +01:00
|
|
|
},
|
2023-03-06 09:18:41 +01:00
|
|
|
RetryDelayFunc: o.RetryHandler,
|
2022-11-30 10:51:24 +01:00
|
|
|
},
|
|
|
|
)
|
|
|
|
|
|
|
|
mux := asynq.NewServeMux()
|
|
|
|
|
|
|
|
return &TaskerServer{
|
|
|
|
mux: mux,
|
|
|
|
server: server,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-06 09:18:41 +01:00
|
|
|
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()
|
|
|
|
}
|