Skip to content

Commit 16eb0b6

Browse files
TheSentinel454Elrond
andauthored
feat(buzz-db): run push enqueue and channel TTL refresh in app code (#8135)
## Summary Moves the producer side of the two event follow-up triggers into application code. The triggers stay in place, so both producers run until a later change drops the triggers after this ships to every pod. Builds on #8130 (`AdmittedTx`). Refs BUZZ-176. ### Push match enqueue New `store::event_follow_up::enqueue_push_match` replaces the `events_enqueue_push_match` trigger (`schema/functions/enqueue_push_match_job.sql`, migration 0023) and matches it exactly: - Same kind allowlist (9, 40002, 45001, 45003), now `PUSH_MATCH_KINDS`. - Takes the same SHARED `buzz_push_gate:<community>` advisory lock as its own statement, so under READ COMMITTED the lease check gets a snapshot taken after the lock is granted. Lease activations still take it EXCLUSIVE in `push.rs`. - Same lease predicate (`active AND endpoint_enabled AND expires_at > now`), then `INSERT push_match_queue ... ON CONFLICT DO NOTHING`. - Fails closed: any error rejects the event, as the trigger did. It runs right after the INSERT, only when the insert affected a row. The consumer side (claims, `lease_until`, attempts, reaper) is already app-owned and is unchanged. ### Channel TTL refresh `AdmittedTx` now records every channel that received an event (except kind 9007 and channel-less events). `AdmittedTx::commit()` refreshes their `ttl_deadline` as the last statement before COMMIT, which keeps the commit-time behavior of the deferred `events_refresh_channel_ttl` trigger (migration 0024): - One savepoint per channel, in sorted order, under the same SHARED `buzz_channel_ttl:<community>:<channel>` lock. - Runs the same `UPDATE` with the same `archived_at`/`deleted_at` filters as its own statement after the lock, so its snapshot follows the lock grant. Its `ttl_seconds IS NOT NULL` qual filters a permanent channel before any tuple lock, so a permanent channel's row is never locked. An ephemeral channel's row lock is held through the remaining refreshes and the COMMIT round trip (the trigger held it only inside COMMIT). - Lock keys come from one builder per protocol (`channel::channel_ttl_lock_key`, `push::push_gate_lock_key`), shared by the SHARED and EXCLUSIVE sides. The shared push-gate wait is observed through `observe_advisory_lock(LockType::PushGate, …)`. - On failure it rolls back the savepoint, logs a warning, and increments `buzz_db_channel_ttl_refresh_failures_total{reason}`, where `reason` is `lock_timeout` or `error`. The event still commits, matching the trigger's `EXCEPTION WHEN OTHERS`. A cancelled statement (`57014`) still rejects the transaction, because plpgsql never caught that either. - While both producers run, an app refresh that hits `lock_timeout` is counted, and then the trigger retries it inside COMMIT and may succeed. So during the dual window the failure counter can over-report and the worst-case wait doubles. Both go away when the retirement PR drops the triggers, after which the counter is exact. ### Call sites Every production `INSERT INTO events` calls `event_follow_up::after_admitted_insert`: - `insert_event_on` - `insert_event_with_thread_metadata_tx` - `LockedMemberSnapshot::replace_member_event` - `replace_addressable_event` - `publish_nip43_membership_locked` - `accept_lease_event` (kind 30350, a no-op today, kept so the policy has no exceptions) `replace_parameterized_event_in_transaction_impl` inserts inside the `parameterized_replace` savepoint. It enqueues the push job inside the savepoint, so a rollback to that savepoint also drops the job, and records the TTL channel only after the savepoint is released. The two rolled-back verification probes (`verify_floor_guard_behavior`, `verify_channel_roster_fence_behavior`) are named exceptions, because they never commit. ### Source policy `tests/observability_source.rs` adds `every_production_event_insert_runs_the_follow_up_hook`. It scans every `crates/*/src` and fails on any function that inserts into `events` without the hook. Matching is normalized (letter case, whitespace, `\` continuations, `\n`/`\t`/`\r` escapes, optional `public.`). The file is masked once first: comments (`//`, nested `/* */`) and string, raw-string (including `br"`/`cr"`), and char literals become spaces. `#[cfg(test)]` markers, `fn` signatures and the hook are all found in that masked view, so a marker in a comment (even a multiline block comment) strips nothing, an `fn` line inside a multiline string doesn't split a function, and a commented-out or quoted hook doesn't count. SQL is still matched in the original text. A table test pins the masker's output for each literal form. A fixture test pins what the scan rejects (no hook, push without TTL, a hook in a line comment, block comment, or string, lowercase or line-broken or escaped SQL, writers after test-only items or under comment mentions) and what it ignores (writers in `#[cfg(test)] mod`). A floor of seven hooked writers catches a scan that silently stops seeing writers. ### Tests `src/store/event_follow_up_postgres_tests.rs` is the contract suite from the BUZZ-176 discovery work, ported to the `AdmittedTx` API. It is a crate-internal `#[cfg(test)]` module because it runs `SET LOCAL` timeouts and in-transaction reads through the crate-private `AdmittedTx::conn()`. It runs on both the desired and migration schemas, in two arms: - **dual**: production during the migration window, with the triggers and the app code both running. - **app-only**: drops both triggers in the disposable database (and asserts no partition clones remain), the way the retirement migration will. The trigger-only baseline is the base branch, where the same suite passed before this change. The suite also pins the two branches that differ from "swallow everything": a `lock_timeout` failure increments `buzz_db_channel_ttl_refresh_failures_total{reason="lock_timeout"}` exactly once, and a statement cancel (`57014`) during the refresh rejects the event with no row, job, or deadline change. ## What got simpler Nothing yet. This adds a parallel producer during the migration window. It is what lets the follow-up PR delete two plpgsql functions, two triggers, and the "keep in sync with migrations/00xx" duplication between `schema/functions/` and `push.rs`. ## Verification Rebased onto `main` @ `745501962`. All runs used a Linux cloud workstation with the pinned toolchain (rustc/clippy 1.95.0, hermit), and the tree was clean before and after each run. The final head, `c5a06a82`, changes only `crates/buzz-db/tests/observability_source.rs` compared with `1eb11bde` (via `fbc9a598`, `7c0baa41`, `9199992c` and `d405b2f6`). Production source is identical between the two. | Check | SHA | Result | |---|---|---| | `cargo fmt --check`, `cargo clippy -p buzz-db --all-targets -D warnings` | `fbc9a598` | pass | | `cargo clippy` (workspace) | `1eb11bde` | pass | | source policy (`--test observability_source`), fmt, buzz-db clippy | `c5a06a82` | 17/17, pass, pass | | `cargo test --locked -p buzz-db` (non-PG) | `c5a06a82` | 148 lib + 17 policy + 5 doctests | | source policy (`--test observability_source`) | `fbc9a598` | 16/16 | | `cargo test --locked -p buzz-db` (non-PG) | `fbc9a598` | 148 lib + 16 policy + 5 doctests | | contract suite (`store::event_follow_up_postgres_tests`, desired/migration × dual/app-only) | `1eb11bde` | 4/4 | | buzz-db PG full | `1eb11bde` | 464/464 | | buzz-relay PG | `1eb11bde` | 378/378 | | GitHub CI | `fbc9a598` | 53 pass, 0 fail (Codex security review pending) | **Falsifications** (each mutation made the named test fail, then was reverted): - dropping the `relay_members` hook → policy names `publish_nip43_membership_locked` - no-op push producer → app-only arms fail, dual arms pass (trigger covers) - skipping the TTL refresh → app-only fails on the deadline; dual fails on the failure-metric assertion - swallowing `57014` → all four arms fail - dropping the metric increment → all four arms fail - unanchored `#[cfg(test)]` match, or no escape handling → fixture test fails - a `#[cfg(test)]` constructor that skips admission, added inside `impl AdmittedTx` (indented or as a column-0 `mod`) → `admitted_tx_is_constructed_only_by_admitting_constructors` fails; putting the strip back into the constructor scan → its fixture test fails - at `7c0baa41`: `accept_lease_event`'s hook commented out and the real call made through an alias → policy names `accept_lease_event` (the same mutation passes under the `fbc9a598` policy); hook matching on unmasked text → the comment/string fixtures fail - at `9199992c`/`d405b2f6`: no nested block-comment depth, no string-escape skip, no `br"`/`cr"` raw-literal prefix, or no raw-string branch at all in the masker → the follow-up fixture test fails - at `c5a06a82`: finding `#[cfg(test)]` in the unmasked text → `writer_after_block_commented_cfg_test` is no longer reported; finding `fn` signatures in the unmasked text → `writer_after_raw_string_example` is no longer reported; no `cr` raw prefix → the masker table test fails on `cr"` - unhooked writers appended to `side_effects.rs` (after test-only items, under a doc-comment mention, with an escaped newline) → policy names each **Live relay E2E**: an independent reviewer ran this at `1eb11bde` against a real relay and CLI, with PostgreSQL 17 and Redis 7, the follow-up triggers absent, and no partition clones. - A kind 9 on a TTL channel advanced the shortened deadline by about 580 s. On a permanent channel, the deadline stayed NULL. - Each accepted event produced exactly one pending `push_match_queue` row with the same event id. - An exact signed replay was a no-op. - While the exclusive TTL lock was held, the event and its job stayed invisible and the deadline didn't change. After release, both persisted once. - Roster create/join/add/remove kept SQL and wire state in step (1→2→3→2), with one current 39002 head. - NIP-33 replace, duplicate, stale, failure and retry cases all passed. Limits: the push lease was a SQL fixture, and push consumers were disabled. Kind 30023 is global, so channel-scoped TTL on the parameterized path is covered only by the PG contracts. No live relay rerun was done at `fbc9a598`, because that delta is test-only. **Latency** (measured at pre-rebase `f8380927`, same production delta; debug build on loopback, 1,000 samples per cell, EVENT→OK): head app-only p50/p99 3.80/4.58 ms (permanent) and 3.87/4.64 ms (TTL), against base trigger-only 3.49–3.53/4.00–4.03 ms and 3.56–3.62/4.30–4.46 ms. About +0.3 ms p50, from the extra client round trips (lock, UPDATE, savepoints, push lock/insert) that the triggers ran server-side. One debug loopback run, not a production p99. Not measured: contention from many writers on one hot TTL channel, where each writer now waits on the channel row lock for about two more client round trips (RELEASE SAVEPOINT and COMMIT) than with the trigger. In review, a burst of 8 concurrent posts to one TTL channel committed with no deadlock or lock timeout. Watch send p99 and `pg_locks` waits on `channels` during rollout. **Known pre-existing, not touched here:** `api::mesh_demo::tests::demo_join_forwarded_arm_round_trips_echo` is flaky when Redis is present. It returns a 504 in 4 of 5 runs at base `745501962` and 2 of 5 at `fbc9a598`, always at the same assertion. No CI lane selects it. --------- Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
1 parent b6d97a6 commit 16eb0b6

11 files changed

Lines changed: 1691 additions & 74 deletions

File tree

‎crates/buzz-db/src/runtime/admitted_tx.rs‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
//! Community-admitted event-write transactions.
22
3+
use std::collections::BTreeSet;
4+
35
use buzz_core::CommunityId;
46
use sqlx::{PgConnection, Postgres, Transaction};
7+
use uuid::Uuid;
58

69
use crate::deletion::{DeletionStore, ServingWriteLease};
710
use crate::Result;
@@ -68,6 +71,8 @@ use crate::Result;
6871
pub struct AdmittedTx {
6972
tx: Transaction<'static, Postgres>,
7073
community: CommunityId,
74+
/// Channels whose TTL deadline [`AdmittedTx::commit`] refreshes.
75+
ttl_refresh_channels: BTreeSet<Uuid>,
7176
}
7277

7378
impl AdmittedTx {
@@ -78,7 +83,11 @@ impl AdmittedTx {
7883
community: CommunityId,
7984
) -> Result<Self> {
8085
store.guard_transaction(&mut tx, community).await?;
81-
Ok(Self { tx, community })
86+
Ok(Self {
87+
tx,
88+
community,
89+
ttl_refresh_channels: BTreeSet::new(),
90+
})
8291
}
8392

8493
/// Validate `lease` on `tx` under the community admission lock and wrap
@@ -94,6 +103,7 @@ impl AdmittedTx {
94103
Ok(Self {
95104
tx,
96105
community: lease.community_id,
106+
ttl_refresh_channels: BTreeSet::new(),
97107
})
98108
}
99109

@@ -111,9 +121,29 @@ impl AdmittedTx {
111121
&mut self.tx
112122
}
113123

124+
/// Record that an event committed with this transaction belongs to
125+
/// `channel_id`, so [`AdmittedTx::commit`] refreshes the channel's TTL.
126+
pub(crate) fn record_channel_event(&mut self, channel_id: Option<Uuid>, kind: i32) {
127+
if let Some(channel) = crate::store::event_follow_up::ttl_refresh_channel(channel_id, kind)
128+
{
129+
self.ttl_refresh_channels.insert(channel);
130+
}
131+
}
132+
114133
/// Commit the transaction. This is the only commit path for admitted
115134
/// event writes.
116-
pub async fn commit(self) -> Result<()> {
135+
///
136+
/// Refreshes the TTL of every channel that received an event first, as
137+
/// the last statement before COMMIT.
138+
pub async fn commit(mut self) -> Result<()> {
139+
if !self.ttl_refresh_channels.is_empty() {
140+
crate::store::event_follow_up::refresh_channel_ttls(
141+
&mut self.tx,
142+
self.community,
143+
&self.ttl_refresh_channels,
144+
)
145+
.await?;
146+
}
117147
self.tx.commit().await?;
118148
Ok(())
119149
}

‎crates/buzz-db/src/store/channel.rs‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -585,11 +585,7 @@ pub async fn update_channel(
585585
if updates.ttl_seconds.is_some() {
586586
let mut tx = begin_event_write_transaction(pool).await?;
587587
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))")
588-
.bind(format!(
589-
"buzz_channel_ttl:{}:{}",
590-
community_id.as_uuid(),
591-
channel_id
592-
))
588+
.bind(channel_ttl_lock_key(community_id, channel_id))
593589
.execute(&mut *tx)
594590
.await?;
595591
let result = q.execute(&mut *tx).await?;
@@ -1012,6 +1008,14 @@ impl Db {
10121008
}
10131009
}
10141010

1011+
/// The per-channel TTL advisory lock key. Event commits take it SHARED
1012+
/// (`event_follow_up::refresh_channel_ttls`, and the 0024 trigger until it is
1013+
/// retired); TTL transitions in [`update_channel`] take it EXCLUSIVE. Both
1014+
/// sides build it here, so the keys cannot drift.
1015+
pub(crate) fn channel_ttl_lock_key(community: CommunityId, channel: Uuid) -> String {
1016+
format!("buzz_channel_ttl:{}:{channel}", community.as_uuid())
1017+
}
1018+
10151019
#[cfg(test)]
10161020
mod postgres_tests {
10171021
use super::*;

‎crates/buzz-db/src/store/channel_members.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,13 @@ impl LockedMemberSnapshot {
398398
"member snapshot event id already exists".into(),
399399
));
400400
}
401+
crate::store::event_follow_up::after_admitted_insert(
402+
&mut self.tx,
403+
event.id.as_bytes().as_slice(),
404+
kind,
405+
Some(channel_id),
406+
)
407+
.await?;
401408
crate::insert_mentions_in_transaction(&mut self.tx, event, Some(channel_id)).await?;
402409
Ok((
403410
buzz_core::StoredEvent::with_received_at(

‎crates/buzz-db/src/store/event.rs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,15 @@ async fn insert_event_on(
500500
.await?;
501501

502502
let was_inserted = result.rows_affected() > 0;
503+
if was_inserted {
504+
crate::store::event_follow_up::after_admitted_insert(
505+
tx,
506+
id_bytes.as_slice(),
507+
kind_i32,
508+
channel_id,
509+
)
510+
.await?;
511+
}
503512

504513
Ok((
505514
StoredEvent::with_received_at(event.clone(), received_at, channel_id, true),
@@ -1744,6 +1753,14 @@ pub(crate) async fn insert_event_with_thread_metadata_tx(
17441753
let was_inserted = result.rows_affected() > 0;
17451754

17461755
if was_inserted {
1756+
crate::store::event_follow_up::after_admitted_insert(
1757+
tx,
1758+
id_bytes.as_slice(),
1759+
kind_i32,
1760+
channel_id,
1761+
)
1762+
.await?;
1763+
17471764
if let Some(ref meta) = thread_meta {
17481765
let broadcast_val: bool = meta.broadcast;
17491766

Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
//! App-owned follow-up work for a newly inserted `events` row.
2+
//!
3+
//! Two pieces of work follow every durable event insert:
4+
//!
5+
//! - **Push match enqueue.** Push-eligible kinds get a `push_match_queue` row
6+
//! when the community has an eligible lease. This runs right after the
7+
//! INSERT, in the same transaction, and any failure rejects the event.
8+
//! - **Channel TTL refresh.** A channel-scoped event pushes its ephemeral
9+
//! channel's `ttl_deadline` forward. [`AdmittedTx`] records the channel and
10+
//! runs the refresh as the last statement before COMMIT (see
11+
//! [`refresh_channel_ttls`]). A refresh failure is logged and counted, and
12+
//! the event still commits.
13+
//!
14+
//! This is the application-side replacement for the `events_enqueue_push_match`
15+
//! and `events_refresh_channel_ttl` triggers (migrations 0023, 0024, 0040).
16+
//! Both run during the migration window; the push enqueue is idempotent
17+
//! (`ON CONFLICT DO NOTHING`) and a second TTL refresh is harmless. Every
18+
//! production `INSERT INTO events` must call this module, which
19+
//! `tests/observability_source.rs` enforces.
20+
21+
use std::collections::BTreeSet;
22+
23+
use buzz_core::CommunityId;
24+
use sqlx::PgConnection;
25+
use uuid::Uuid;
26+
27+
use crate::{AdmittedTx, DbError, Result};
28+
29+
/// Event kinds that wake push subscribers. Keep identical to the relay's
30+
/// validated NIP-PL descriptor.
31+
pub(crate) const PUSH_MATCH_KINDS: [i32; 4] = [9, 40002, 45001, 45003];
32+
33+
/// Kind 9007 creates the channel and initializes its deadline itself.
34+
const KIND_CHANNEL_CREATE: i32 = 9007;
35+
36+
/// SQLSTATE `lock_not_available`, raised when `lock_timeout` expires.
37+
const SQLSTATE_LOCK_NOT_AVAILABLE: &str = "55P03";
38+
39+
/// Follow-up for an event row inserted in an admitted transaction.
40+
///
41+
/// Call only when the INSERT affected a row. Enqueues the push match job now
42+
/// and records the channel for the pre-commit TTL refresh.
43+
///
44+
/// If the insert ran inside a savepoint that may still roll back, call
45+
/// [`enqueue_push_match`] inside the savepoint and
46+
/// [`AdmittedTx::record_channel_event`] after it is released instead.
47+
pub(crate) async fn after_admitted_insert(
48+
tx: &mut AdmittedTx,
49+
event_id: &[u8],
50+
kind: i32,
51+
channel_id: Option<Uuid>,
52+
) -> Result<()> {
53+
let community = tx.community();
54+
enqueue_push_match(tx.conn(), community, event_id, kind).await?;
55+
tx.record_channel_event(channel_id, kind);
56+
Ok(())
57+
}
58+
59+
/// Enqueue a push match job for a just-inserted event, if its kind is
60+
/// push-eligible and the community has an eligible lease.
61+
///
62+
/// Takes the push gate SHARED and holds it to transaction end. Lease
63+
/// activations take it EXCLUSIVE (`acquire_push_gate_lock` in `push.rs`), so
64+
/// an event either sees the committed lease or strictly precedes the
65+
/// activation, in which case no wake was owed. The lock must be its own
66+
/// statement: under READ COMMITTED the eligibility check needs a snapshot
67+
/// taken after the lock is granted.
68+
///
69+
/// Errors propagate and reject the event, as the trigger did.
70+
pub(crate) async fn enqueue_push_match(
71+
conn: &mut PgConnection,
72+
community: CommunityId,
73+
event_id: &[u8],
74+
kind: i32,
75+
) -> Result<()> {
76+
if !PUSH_MATCH_KINDS.contains(&kind) {
77+
return Ok(());
78+
}
79+
crate::observability::observe_advisory_lock(
80+
crate::observability::LockType::PushGate,
81+
sqlx::query("SELECT pg_advisory_xact_lock_shared(hashtextextended($1, 0))")
82+
.bind(crate::push::push_gate_lock_key(community))
83+
.execute(&mut *conn),
84+
)
85+
.await?;
86+
sqlx::query(
87+
"INSERT INTO push_match_queue (community_id, event_id) \
88+
SELECT $1, $2 \
89+
WHERE EXISTS ( \
90+
SELECT 1 FROM push_leases \
91+
WHERE community_id = $1 \
92+
AND active \
93+
AND endpoint_enabled \
94+
AND expires_at > EXTRACT(EPOCH FROM now())::bigint) \
95+
ON CONFLICT DO NOTHING",
96+
)
97+
.bind(community.as_uuid())
98+
.bind(event_id)
99+
.execute(&mut *conn)
100+
.await?;
101+
Ok(())
102+
}
103+
104+
/// The channel whose TTL an event of `kind` in `channel_id` refreshes, if any.
105+
pub(crate) fn ttl_refresh_channel(channel_id: Option<Uuid>, kind: i32) -> Option<Uuid> {
106+
channel_id.filter(|_| kind != KIND_CHANNEL_CREATE)
107+
}
108+
109+
/// Refresh the TTL deadline of every channel that received an event in this
110+
/// transaction. [`AdmittedTx::commit`] calls this as its last work before
111+
/// COMMIT, which keeps the deferred-trigger timing from migration 0024: the
112+
/// deadline is computed at commit. An ephemeral channel's row lock, taken by
113+
/// the UPDATE, is held through the remaining refreshes and the COMMIT round
114+
/// trip; the trigger held it only inside COMMIT. A permanent channel's row is
115+
/// never locked.
116+
///
117+
/// Channels are refreshed in sorted order, so two transactions that touch the
118+
/// same channels cannot deadlock on the shared locks against an exclusive
119+
/// waiter. Each refresh runs in its own savepoint. A failure is rolled back,
120+
/// logged, and counted, and the event still commits, as with the trigger's
121+
/// `EXCEPTION WHEN OTHERS`. A cancelled statement (`57014`) still rejects the
122+
/// transaction, because plpgsql never caught it either.
123+
pub(crate) async fn refresh_channel_ttls(
124+
conn: &mut PgConnection,
125+
community: CommunityId,
126+
channels: &BTreeSet<Uuid>,
127+
) -> Result<()> {
128+
for &channel in channels {
129+
sqlx::query("SAVEPOINT channel_ttl_refresh")
130+
.execute(&mut *conn)
131+
.await?;
132+
match refresh_channel_ttl(conn, community, channel).await {
133+
Ok(()) => {
134+
sqlx::query("RELEASE SAVEPOINT channel_ttl_refresh")
135+
.execute(&mut *conn)
136+
.await?;
137+
}
138+
Err(error) => {
139+
// plpgsql `WHEN OTHERS` never caught `query_canceled`, so a
140+
// cancelled refresh has always rejected the event.
141+
if error.is_statement_cancelled() {
142+
return Err(error);
143+
}
144+
sqlx::query("ROLLBACK TO SAVEPOINT channel_ttl_refresh")
145+
.execute(&mut *conn)
146+
.await?;
147+
sqlx::query("RELEASE SAVEPOINT channel_ttl_refresh")
148+
.execute(&mut *conn)
149+
.await?;
150+
let reason = if sqlstate(&error).as_deref() == Some(SQLSTATE_LOCK_NOT_AVAILABLE) {
151+
"lock_timeout"
152+
} else {
153+
"error"
154+
};
155+
metrics::counter!(
156+
"buzz_db_channel_ttl_refresh_failures_total",
157+
"reason" => reason,
158+
)
159+
.increment(1);
160+
tracing::warn!(
161+
%error,
162+
channel_id = %channel,
163+
reason,
164+
"channel TTL refresh failed; event committed without refreshing the deadline"
165+
);
166+
}
167+
}
168+
}
169+
Ok(())
170+
}
171+
172+
async fn refresh_channel_ttl(
173+
conn: &mut PgConnection,
174+
community: CommunityId,
175+
channel: Uuid,
176+
) -> Result<()> {
177+
// SHARED here, EXCLUSIVE in `update_channel` for TTL transitions: the same
178+
// total order the 0022 row lock gave, without serializing hot channels.
179+
sqlx::query("SELECT pg_advisory_xact_lock_shared(hashtextextended($1, 0))")
180+
.bind(crate::channel::channel_ttl_lock_key(community, channel))
181+
.execute(&mut *conn)
182+
.await?;
183+
// A separate statement, so its snapshot is taken after the lock is
184+
// granted. `ttl_seconds IS NOT NULL` filters a permanent channel before
185+
// any tuple lock is taken, so its row is never locked (migration 0024).
186+
sqlx::query(
187+
"UPDATE channels \
188+
SET ttl_deadline = clock_timestamp() + make_interval(secs => ttl_seconds) \
189+
WHERE community_id = $1 AND id = $2 \
190+
AND ttl_seconds IS NOT NULL \
191+
AND archived_at IS NULL \
192+
AND deleted_at IS NULL",
193+
)
194+
.bind(community.as_uuid())
195+
.bind(channel)
196+
.execute(&mut *conn)
197+
.await?;
198+
Ok(())
199+
}
200+
201+
fn sqlstate(error: &DbError) -> Option<String> {
202+
match error {
203+
DbError::Sqlx(sqlx::Error::Database(database_error)) => {
204+
database_error.code().map(|code| code.into_owned())
205+
}
206+
_ => None,
207+
}
208+
}

0 commit comments

Comments
 (0)