Kantoor. Maintenance. Lock
(Kantoor v1.0.0)
The "only one node runs a job at a time" lock of Kantoor.Maintenance, for a
database reached through PgBouncer in transaction pooling mode
(KANTOOR_DATABASE_POOLER=true).
Without a pooler a job holds a Postgres session advisory lock
(pg_try_advisory_lock) on one checked-out connection. Through a transaction
pooler that does not work: the lock and the unlock are separate statements, each
may reach a different server connection, so the unlock fails (a warning) and the
lock stays with a server connection nobody owns, which blocks the job on every node
until PgBouncer closes that connection.
Here the lock is pg_try_advisory_xact_lock, taken in a transaction that lives
exactly as long as the job. That transaction runs on a connection of its own, a
process that only waits: the job itself runs on the normal pool, with the
transactions it always had, and keeps its semantics. A transaction keeps its server
connection in transaction mode, so the lock is held where it was taken, and it ends
with the transaction: when the job ends, when the holder dies, or when the node
does (Postgres rolls the transaction back). It never outlives its owner.
What it costs: one more database connection while a job runs (the jobs run one at a
time in Kantoor.Maintenance), held idle in a transaction for the length of the
job. A pooler with idle_transaction_timeout set shorter than the longest job would
end it, and the lock with it; the jobs are idempotent, so the cost is a second run
on another node, not damage.
Summary
Functions
True when KANTOOR_DATABASE_POOLER is on.
Runs fun while holding the transaction-scoped advisory lock {ns, id}.
Returns {:ok, result}, or :locked when another session holds it. Raises when the
database cannot be reached; the lock is released whatever fun does.
Functions
@spec pooled?() :: boolean()
True when KANTOOR_DATABASE_POOLER is on.
Runs fun while holding the transaction-scoped advisory lock {ns, id}.
Returns {:ok, result}, or :locked when another session holds it. Raises when the
database cannot be reached; the lock is released whatever fun does.