Skip to content
19 changes: 18 additions & 1 deletion config/queue.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package config

// queueDriver is how jobs run: sync where they are dispatched, redis on
// the worker.
type queueDriver string

const (
Expand All @@ -18,14 +20,29 @@ func (driver queueDriver) String() string {
return string(driver)
}

// Queue is how the queue runs, handed to queueing.WithConfig: the driver,
// the workers of the default queue, and each group's.
type Queue struct {
Driver queueDriver
Driver queueDriver
// Concurrency is how many jobs of the default queue run at once: every
// job registered outside a group.
Concurrency int
// Groups is each queue group's workers of its own, by the name
// engine.Group registers its jobs under. A group registered without one
// stops the worker from starting.
Groups map[string]QueueGroup

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not call it channel and also call it engine.channel? or is that confusing with the queue() on the job itself?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping Group: "channel" reads as a Go chan, and a group is more than a queue name, it's its jobs plus workers of their own. It also stays apart from a job's Queue(), which the group overrides.

Connections struct {
Redis RedisQueueConnection
}
}

// QueueGroup is how a group's jobs run.
type QueueGroup struct {
// Concurrency is how many of its jobs run at once, on workers of its
// own: the other queues never take them.
Concurrency int
}

type RedisQueueConnection struct {
Driver queueDriver
Connection RedisConnectionType
Expand Down
72 changes: 58 additions & 14 deletions queueing/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,90 @@ package queueing

import (
"context"
"fmt"
"time"

"github.com/gonstruct/core/cache"
"github.com/gonstruct/core/config"
"github.com/gonstruct/core/queueing/job"
"github.com/gonstruct/core/queueing/resolvers"

"github.com/rs/zerolog/log"

"github.com/gonstruct/validation/env"
"github.com/hibiken/asynq"
)

func NewEngine() (*Engine, error) {
func NewEngine(queue config.Queue) (*Engine, error) {
sharedCache := cache.New()

return &Engine{
EngineResolver: map[string]EngineResolver{
"sync": &resolvers.Sync{Cache: sharedCache},
"redis": &resolvers.Redis{
Client: *asynq.NewClient(resolvers.RedisClient{}),
Cache: sharedCache,
},
}[env.String("QUEUE_DRIVER")],
jobs: make(map[string]job.Job),
}, nil
var resolver EngineResolver
switch queue.Driver {
case config.SynchronousQueueDriver:
resolver = &resolvers.Sync{Cache: sharedCache}
case config.RedisQueueDriver:
connection := resolvers.RedisClient{Connection: queue.Connections.Redis.Connection.String()}
resolver = &resolvers.Redis{Client: *asynq.NewClient(connection), Connection: connection, Cache: sharedCache, Config: queue}
default:
return nil, fmt.Errorf("[queueing] unknown queue driver %q", queue.Driver)
}

return &Engine{EngineResolver: resolver, jobs: make(map[string]job.Job), groups: make(map[string]string)}, nil
}

type Engine struct {
EngineResolver

jobs map[string]job.Job
// groups is the group each job registered in one is in, by job name.
groups map[string]string
}

type EngineResolver interface {
Consume(map[string]job.Job) error
Dispatch(context.Context, job.Job, ...time.Duration) error
// Consume runs the jobs; groups names the group of each job in one.
Consume(jobs map[string]job.Job, groups map[string]string) error
// Dispatch puts a job on a queue: its group's, or "" for the job's own.
Dispatch(ctx context.Context, job job.Job, queue string, delay ...time.Duration) error
}

func (e *Engine) Job(job job.Job) {
log.Info().Msgf("[queueing] registering job %s", job.Name())

e.jobs[job.Name()] = job
}

// Group registers jobs on a queue of their own, with workers of their own,
// as many as the config's Groups says for its name:
//
// engine.Group("ci", func(group *queueing.Group) {
// group.Job(new(LaunchRunnerJob))
// })
//
// A job in a group goes on the group's queue, whatever its Queue() says,
// and only the group's workers run it, so no other job can hold it up. Jobs
// outside a group share the default workers; their Queue() and Priority()
// only weight which of them those take next.
func (e *Engine) Group(name string, register func(*Group)) {
register(&Group{name: name, engine: e})
}

// QueueOf is the queue a job goes on: its group's, or "" when it is in none
// and says for itself.
func (e *Engine) QueueOf(job job.Job) string {
return e.groups[job.Name()]
}

// Group is the jobs registering in one.
type Group struct {
name string
engine *Engine
}

func (g *Group) Job(job job.Job) {
if named, ok := job.(interface{ Queue() string }); ok && named.Queue() != g.name {
log.Warn().Msgf("[queueing] job %s says queue %s but is in group %s: it goes on %s", job.Name(), named.Queue(), g.name, g.name)
}
log.Info().Msgf("[queueing] registering job %s in group %s", job.Name(), g.name)

g.engine.jobs[job.Name()] = job
g.engine.groups[job.Name()] = g.name
}
7 changes: 7 additions & 0 deletions queueing/job/job.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,19 @@ type JobWithTries interface {
Tries() int
}

// JobWithQueue is a job outside a group that waits on a queue of its own
// name instead of the default one. It still runs on the default workers,
// which take from its queue by its Priority: it reserves no workers, as a
// group does. In a group, Queue() is ignored.
type JobWithQueue interface {
Job

Queue() string
}

// JobWithPriority is how much more often the default workers take from
// its queue than from one of priority 1, when both have jobs waiting: a
// weight, not a reservation.
type JobWithPriority interface {
Job

Expand Down
10 changes: 10 additions & 0 deletions queueing/options.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
package queueing

import "github.com/gonstruct/core/config"

type Option func(*Queueing)

func WithQueues(queues ...func(*Engine)) Option {
return func(r *Queueing) {
r.Queues = append(r.Queues, queues...)
}
}

// WithConfig is how the queue runs: its driver, and how many workers the
// default queue and each group have. Queueing needs it.
func WithConfig(queue config.Queue) Option {
return func(r *Queueing) {
r.Config = &queue
}
}
13 changes: 10 additions & 3 deletions queueing/queueing.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@ package queueing

import (
"context"
"errors"
"fmt"
"sync"
"time"

"github.com/gonstruct/core/config"
"github.com/gonstruct/core/queueing/job"

"github.com/rs/zerolog/log"
)

type Queueing struct {
Queues []func(*Engine)
Config *config.Queue

engine *Engine
mu sync.Mutex
Expand All @@ -33,7 +36,7 @@ func (q *Queueing) Run() error {
return err
}

return q.engine.Consume(q.engine.jobs)
return q.engine.Consume(q.engine.jobs, q.engine.groups)
}

func (q *Queueing) Dispatch(ctx context.Context, current job.Job, delay ...time.Duration) error {
Expand All @@ -55,7 +58,7 @@ func (q *Queueing) Dispatch(ctx context.Context, current job.Job, delay ...time.
}

log.Info().Msgf("[queueing] dispatching job: %s", prepared.Name())
if err := q.engine.Dispatch(ctx, prepared, delay...); err != nil {
if err := q.engine.Dispatch(ctx, prepared, q.engine.QueueOf(prepared), delay...); err != nil {
log.Error().Err(err).Msgf("[queueing] failed to dispatch job: %s", prepared.Name())
return fmt.Errorf("[queueing] failed to dispatch job: %w", err)
}
Expand All @@ -71,7 +74,11 @@ func (q *Queueing) ensureEngine() error {
return nil
}

engine, err := NewEngine()
if q.Config == nil {
return errors.New("[queueing] no config: pass queueing.WithConfig")
}

engine, err := NewEngine(*q.Config)
if err != nil {
return err
}
Expand Down
101 changes: 79 additions & 22 deletions queueing/resolvers/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,31 @@ import (
"encoding/json"
"errors"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"

"github.com/gonstruct/core/cache"
"github.com/gonstruct/core/config"
"github.com/gonstruct/core/otel"
"github.com/gonstruct/core/queueing/job"
redisconnection "github.com/gonstruct/core/redis"

"github.com/rs/zerolog/log"

"github.com/gonstruct/validation/env"
"github.com/hibiken/asynq"
)

type Redis struct {
Client asynq.Client
Cache *cache.Cache
Client asynq.Client
Connection RedisClient
Cache *cache.Cache
Config config.Queue
}

func (e *Redis) Dispatch(ctx context.Context, constructor job.Job, delay ...time.Duration) error {
func (e *Redis) Dispatch(ctx context.Context, constructor job.Job, queue string, delay ...time.Duration) error {
payload, err := json.Marshal(constructor)
if err != nil {
return err
Expand All @@ -49,7 +54,9 @@ func (e *Redis) Dispatch(ctx context.Context, constructor job.Job, delay ...time
options = append(options, asynq.MaxRetry(option.Tries()-1))
}

if option, hasCustomQueue := constructor.(job.JobWithQueue); hasCustomQueue {
if queue != "" {
options = append(options, asynq.Queue(queue))
} else if option, hasCustomQueue := constructor.(job.JobWithQueue); hasCustomQueue {
options = append(options, asynq.Queue(option.Queue()))
}

Expand All @@ -75,20 +82,10 @@ func (e *Redis) Dispatch(ctx context.Context, constructor job.Job, delay ...time
return err
}

//nolint:gocognit
func (e *Redis) Consume(jobs map[string]job.Job) error {
func (e *Redis) Consume(jobs map[string]job.Job, groups map[string]string) error {
handler := asynq.NewServeMux()

queues := map[string]int{}
for _, jobHandler := range jobs {
if jobWithQueue, ok := jobHandler.(job.JobWithQueue); ok {
queues[jobWithQueue.Queue()] = 1

if jobWithPriority, ok := jobHandler.(job.JobWithPriority); ok {
queues[jobWithQueue.Queue()] = jobWithPriority.Priority()
}
}

_, isDebounceableHandler := jobHandler.(job.JobWithDebounce)
_, hasOverlapGuard := jobHandler.(job.JobWithoutOverlapping)
if isDebounceableHandler && hasOverlapGuard {
Expand Down Expand Up @@ -132,9 +129,61 @@ func (e *Redis) Consume(jobs map[string]job.Job) error {
})
}

return asynq.NewServer(RedisClient{}, asynq.Config{
Concurrency: env.Number("QUEUE_CONCURRENCY"),
Queues: queues,
planned, err := Servers(jobs, groups, e.Config)
if err != nil {
return err
}
servers := make([]*asynq.Server, 0, len(planned))
for _, server := range planned {
name := server.Group
if name == "" {
name = "default"
}
log.Info().Msgf("[queueing] %s: %d workers for %v", name, server.Concurrency, server.Queues)
servers = append(servers, asynq.NewServer(e.Connection, e.config(jobs, server)))
}

return serve(servers, handler)
}

// serve runs every server until the process is asked to stop: SIGTERM
// or an interrupt shuts them all down, letting their jobs in flight finish;
// SIGTSTP has them stop taking new ones first, as asynq's own Run does.
func serve(servers []*asynq.Server, handler asynq.Handler) error {
started := make([]*asynq.Server, 0, len(servers))
defer func() {
for _, server := range started {
server.Shutdown()
}
}()
for _, server := range servers {
if err := server.Start(handler); err != nil {
return err
}
started = append(started, server)
}

signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT, syscall.SIGTSTP)
defer signal.Stop(signals)
for received := range signals {
if received != syscall.SIGTSTP {
return nil
}
for _, server := range started {
server.Stop()
}
}

return nil
}

// config is a server's asynq config: its workers and queues, and how every
// job is retried and failed, the same on every server.
func (e *Redis) config(jobs map[string]job.Job, server Server) asynq.Config {
return asynq.Config{
Concurrency: server.Concurrency,
Queues: server.Queues,
RetryDelayFunc: func(retries int, err error, task *asynq.Task) time.Duration {
if release, ok := job.AsRelease(err); ok {
return release.Delay
Expand Down Expand Up @@ -206,13 +255,21 @@ func (e *Redis) Consume(jobs map[string]job.Job) error {
log.Warn().Ctx(ctx).Err(taskErr).Msgf("[queueing] Task %s failed on attempt %d/%d, will retry", task.Type(), retried, maxRetry)
}
}),
}).Run(handler)
}
}

type RedisClient struct{}
// RedisClient is the Redis connection the queue runs on, by name: the
// config's Connections.Redis.Connection, or the default one.
type RedisClient struct {
Connection string
}

func (c RedisClient) MakeRedisClient() any {
client, err := redisconnection.NewClient(env.String("QUEUE_REDIS_CONNECTION", redisconnection.DefaultConnection))
connection := c.Connection
if connection == "" {
connection = redisconnection.DefaultConnection
}
client, err := redisconnection.NewClient(connection)
if err != nil {
panic(fmt.Errorf("[queueing] invalid Redis configuration: %w", err))
}
Expand Down
Loading