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>
44 lines
1.1 KiB
Go
44 lines
1.1 KiB
Go
package infra
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
// JobFail increments the attempt counter and transitions the job to:
|
|
// - "failed" when attempts < max_attempts (eligible for retry)
|
|
// - "dead" when attempts >= max_attempts (no more retries)
|
|
//
|
|
// errMsg is stored in the error column for debugging.
|
|
func JobFail(q *JobQueue, jobID string, errMsg string) error {
|
|
if q == nil {
|
|
return fmt.Errorf("job_fail: queue must not be nil")
|
|
}
|
|
if jobID == "" {
|
|
return fmt.Errorf("job_fail: jobID must not be empty")
|
|
}
|
|
|
|
now := time.Now().UTC().Format(time.RFC3339)
|
|
|
|
// Atomically increment attempts and decide status.
|
|
query := fmt.Sprintf(`
|
|
UPDATE %s
|
|
SET
|
|
attempts = attempts + 1,
|
|
status = CASE WHEN (attempts + 1) >= max_attempts THEN 'dead' ELSE 'failed' END,
|
|
error = ?,
|
|
completed_at = ?
|
|
WHERE id = ?
|
|
`, q.TableName)
|
|
|
|
res, err := q.DB.Exec(query, errMsg, now, jobID)
|
|
if err != nil {
|
|
return fmt.Errorf("job_fail: update: %w", err)
|
|
}
|
|
n, _ := res.RowsAffected()
|
|
if n == 0 {
|
|
return fmt.Errorf("job_fail: job %q not found", jobID)
|
|
}
|
|
return nil
|
|
}
|