package infra import ( "context" "fmt" "golang.org/x/sync/errgroup" ) // JobWorkerPool starts n workers concurrently, all sharing the same queue and // handler. It uses errgroup for structured concurrency and supports graceful // shutdown via ctx cancellation. // // The function blocks until all workers exit. It returns the first non-context // error encountered, or ctx.Err() if all workers stopped due to cancellation. // // Options: WithPollInterval, WithJobTypes (applied to every worker). func JobWorkerPool(ctx context.Context, q *JobQueue, n int, handler JobHandler, opts ...WorkerOption) error { if q == nil { return fmt.Errorf("job_worker_pool: queue must not be nil") } if handler == nil { return fmt.Errorf("job_worker_pool: handler must not be nil") } if n <= 0 { return fmt.Errorf("job_worker_pool: n must be > 0, got %d", n) } g, gctx := errgroup.WithContext(ctx) for i := 0; i < n; i++ { g.Go(func() error { return JobWorker(gctx, q, handler, opts...) }) } return g.Wait() }