b5a867ca5a
Implementa el subsistema completo de background jobs para apps Go en el dominio infra. 9 funciones + 3 tipos + 17 tests, todos pasando. - Tipos: Job (product), JobQueue (product), JobStatus (sum) con JobHandler, EnqueueOption y WorkerOption usando functional options pattern - job_queue_create: CREATE TABLE + indices + WAL mode - job_enqueue: INSERT con UUID (github.com/google/uuid), WithPriority/WithScheduledAt/WithMaxAttempts - job_dequeue: SELECT+UPDATE atomico en transaccion exclusiva, filtro por jobTypes - job_complete / job_fail: transiciones de estado; fail → dead cuando attempts >= max_attempts - job_status_summary: pura, formatea conteo de jobs por estado - job_worker: poll loop bloqueante, context-cancelable, graceful shutdown - job_worker_pool: N workers con golang.org/x/sync/errgroup - job_cleanup: DELETE jobs terminales mas viejos que olderThan Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
37 lines
1022 B
Go
37 lines
1022 B
Go
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()
|
|
}
|