apollo-backend/internal/cmd/worker.go

88 lines
1.8 KiB
Go
Raw Permalink Normal View History

package cmd
import (
"context"
"fmt"
"runtime"
"github.com/spf13/cobra"
"github.com/christianselig/apollo-backend/internal/cmdutil"
"github.com/christianselig/apollo-backend/internal/worker"
)
var (
queues = map[string]worker.NewWorkerFn{
"notifications": worker.NewNotificationsWorker,
2021-09-25 16:56:01 +00:00
"subreddits": worker.NewSubredditsWorker,
2021-10-10 15:51:42 +00:00
"trending": worker.NewTrendingWorker,
2021-10-09 14:59:20 +00:00
"users": worker.NewUsersWorker,
}
)
func WorkerCmd(ctx context.Context) *cobra.Command {
var multiplier int
var queueID string
cmd := &cobra.Command{
Use: "worker",
Args: cobra.ExactArgs(0),
Short: "Work through job queues.",
RunE: func(cmd *cobra.Command, args []string) error {
if queueID == "" {
return fmt.Errorf("need a queue to work on")
}
logger := cmdutil.NewLogrusLogger(false)
2021-10-12 16:04:20 +00:00
tag := fmt.Sprintf("worker:%s", queueID)
statsd, err := cmdutil.NewStatsdClient(tag)
if err != nil {
return err
}
defer statsd.Close()
2021-07-15 17:47:22 +00:00
consumers := runtime.NumCPU() * multiplier
2021-07-23 01:16:41 +00:00
poolSize := multiplier / 4
2021-07-15 17:47:22 +00:00
2021-07-23 01:11:27 +00:00
db, err := cmdutil.NewDatabasePool(ctx, poolSize)
if err != nil {
return err
}
defer db.Close()
redis, err := cmdutil.NewRedisClient(ctx)
if err != nil {
return err
}
defer redis.Close()
queue, err := cmdutil.NewQueueClient(logger, redis, "worker")
if err != nil {
return err
}
workerFn, ok := queues[queueID]
if !ok {
return fmt.Errorf("invalid queue: %s", queueID)
}
2021-07-14 00:09:44 +00:00
worker := workerFn(logger, statsd, db, redis, queue, consumers)
2021-09-25 13:19:42 +00:00
if err := worker.Start(); err != nil {
return err
}
<-ctx.Done()
worker.Stop()
return nil
},
}
cmd.Flags().IntVar(&multiplier, "multiplier", 12, "The multiplier (by CPUs) to run")
cmd.Flags().StringVar(&queueID, "queue", "", "The queue to work on")
return cmd
}