package outbound import ( "context" "encoding/json" "errors" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" ) var ( // ErrJobLeaseLost reports that a claimed job no longer belongs to the // attempt: it was canceled, or another worker reclaimed it after the // lease expired. Nothing of the attempt was committed. ErrJobLeaseLost = errors.New("scheduled job lease lost") // ErrJobEffectRejected reports that PostgreSQL refused to commit the // effect of a job handler that returned nil: the handler ignored a // failed statement, or a deferred integrity constraint failed at commit. // Nothing was committed, and the worker counts it as a failed attempt. ErrJobEffectRejected = errors.New("scheduled job effect rejected by the database") // ErrJobCompletionConflict reports that the handler transaction left its // own job in a state that the completion cannot accept, other than // canceling it. Nothing was committed; retrying would repeat it, so the // worker makes the job dead. ErrJobCompletionConflict = errors.New("scheduled job changed by its own handler") ) // JobScheduler schedules and cancels jobs in the caller's transaction, so a // job exists exactly when the business change that needs it committed. // // A job handler runs while it holds the row lock of its job and may then // lock product rows. A transaction that cancels a job should cancel it // before it locks the rows that the handler touches; the opposite order can // deadlock with a running handler, which PostgreSQL resolves by aborting one // side with ErrTransactionConflict. type JobScheduler interface { // Schedule inserts job unless its (kind, key) pair exists, in any state: // the first schedule wins and a repeat reports scheduled=false without // changing the due time or the payload. A concurrent schedule of the // same pair waits for the first transaction. Schedule(ctx context.Context, job domain.ScheduledJob) (scheduled bool, err error) // Cancel stops a job that has not finished and reports whether it did. // When the job's handler transaction is in progress, Cancel waits for // it: after its commit the job is done and Cancel reports false. A // canceled job keeps its key reserved, so a later Schedule of the same // pair does nothing. Cancel(ctx context.Context, kind, key string) (cancelled bool, err error) } // JobErrorClass is the bounded cause of a failed or abandoned attempt. It is // stored with the job and never carries handler text. type JobErrorClass string const ( // JobErrorHandlerFailed: the handler returned an error; retried. JobErrorHandlerFailed JobErrorClass = "handler_failed" // JobErrorHandlerRejected: the handler can never run the job; final. JobErrorHandlerRejected JobErrorClass = "handler_rejected" // JobErrorHandlerPanic: the handler panicked; final. JobErrorHandlerPanic JobErrorClass = "handler_panic" // JobErrorTimeout: the attempt outlasted its lease; retried. JobErrorTimeout JobErrorClass = "timeout" // JobErrorConflict: a deadlock or serialization failure; retried. JobErrorConflict JobErrorClass = "conflict" // JobErrorEffectRejected: PostgreSQL refused the commit; retried. JobErrorEffectRejected JobErrorClass = "effect_rejected" // JobErrorLeaseExpired: the worker stopped without finishing a started // attempt, and a later claim found its lease expired. JobErrorLeaseExpired JobErrorClass = "lease_expired" // JobErrorCompletionConflict: the handler left its own job in a state // the completion cannot accept; final. JobErrorCompletionConflict JobErrorClass = "completion_conflict" ) // JobClaim asks for due jobs. Now is the application clock; the database // clock never decides whether a job is due or a lease expired. type JobClaim struct { // Owner identifies the worker instance in the lease. Owner uuid.UUID // Kinds are the kinds the worker has handlers for. Jobs of other kinds // stay untouched, so an instance without a newer handler leaves those // jobs to instances that have it. Kinds []string Now time.Time // Lease is how long a claimed job belongs to Owner. Lease time.Duration // Limit bounds the jobs of one claim. Limit int // DefaultMaxAttempts applies to jobs scheduled without their own limit. DefaultMaxAttempts int } // ClaimedJob is one job of a claim. type ClaimedJob struct { ID int64 Kind string Key string Payload json.RawMessage // DueAt is the deadline the job stands for, as scheduled. Retries keep // it; only the time the job may be claimed again moves. DueAt time.Time // Attempt counts this attempt; the first one is 1. Attempt int MaxAttempts int LeaseOwner uuid.UUID // LeaseExpiresAt is by the application clock. LeaseExpiresAt time.Time // Exhausted reports a running job whose lease expired on its last // allowed attempt. The claim made it dead; it must not run. Exhausted bool } // JobFailure records a failed attempt. type JobFailure struct { Class JobErrorClass // Dead ends the job; otherwise it may be claimed again at RetryAt. Dead bool RetryAt time.Time } // JobBacklog describes waiting and dead jobs at one moment. type JobBacklog struct { // Due counts jobs that a worker may claim now: due, or due for their // retry. Due int64 // OldestDueAge is how long the earliest of them has waited; zero // without such jobs. OldestDueAge time.Duration // Dead counts dead jobs, which need an operator. Dead int64 } // ApplyJob runs the handler of one job inside the transaction that // completes it. type ApplyJob func(ctx context.Context, unit UnitOfWork) error // JobStore keeps scheduled jobs for the worker. type JobStore interface { // Claim leases up to claim.Limit jobs that may be claimed at claim.Now // (due, or due for their retry) in one atomic statement, skipping rows // that another worker locks, and counts one attempt for each. Running // jobs whose lease expired by claim.Now are claimed again; an expired // attempt that never started is reused rather than counted again. Jobs // are returned in due order. Claim(ctx context.Context, claim JobClaim) ([]ClaimedJob, error) // Start renews the lease of a claimed job from now and records that its // attempt started, committed on its own, right before Run. started is // false, with nothing changed, when the lease expired by now or no // longer belongs to the attempt; the job must not run then. The // returned job carries the new lease expiry. Start(ctx context.Context, job ClaimedJob, now time.Time, lease time.Duration) (started ClaimedJob, ok bool, err error) // Run opens a transaction, locks job, checks that its lease still // belongs to this attempt, runs apply, marks the job done, and commits, // so the effect of apply and the completion commit together. When apply // canceled the job itself through the unit, the effect commits and the // job stays cancelled; any other change of the job by apply rolls back // and returns ErrJobCompletionConflict. A lost lease returns // ErrJobLeaseLost without calling apply. An error from // apply rolls back and keeps its identity, with any PostgreSQL text // replaced. A commit that PostgreSQL refuses matches // ErrJobEffectRejected, and a deadlock or serialization failure // ErrTransactionConflict. Run(ctx context.Context, job ClaimedJob, apply ApplyJob) error // Fail records a failed attempt of job if its lease still belongs to the // attempt, and reports whether it did. Fail(ctx context.Context, job ClaimedJob, failure JobFailure) (bool, error) // Release returns jobs whose attempts did not finish to the waiting // state without counting the attempts, skipping jobs whose lease no // longer belongs to the attempt, and returns the IDs it released. Release(ctx context.Context, jobs []ClaimedJob) (released []int64, err error) // Backlog reads the due and dead jobs at now without locking them. Backlog(ctx context.Context, now time.Time) (JobBacklog, error) }