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>
34 lines
849 B
Go
34 lines
849 B
Go
package infra
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
// JobCleanup deletes jobs in terminal states (completed, failed, dead) that are
|
|
// older than olderThan. Returns the number of rows deleted.
|
|
// This is useful for keeping the jobs table small in long-running applications.
|
|
func JobCleanup(q *JobQueue, olderThan time.Duration) (int64, error) {
|
|
if q == nil {
|
|
return 0, fmt.Errorf("job_cleanup: queue must not be nil")
|
|
}
|
|
|
|
cutoff := time.Now().UTC().Add(-olderThan).Format(time.RFC3339)
|
|
|
|
query := fmt.Sprintf(`
|
|
DELETE FROM %s
|
|
WHERE status IN ('completed', 'failed', 'dead')
|
|
AND created_at < ?
|
|
`, q.TableName)
|
|
|
|
res, err := q.DB.Exec(query, cutoff)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("job_cleanup: delete: %w", err)
|
|
}
|
|
n, err := res.RowsAffected()
|
|
if err != nil {
|
|
return 0, fmt.Errorf("job_cleanup: rows affected: %w", err)
|
|
}
|
|
return n, nil
|
|
}
|