From 29f7333d3f5545a37a743d2abf83e0dfb4f9c55f Mon Sep 17 00:00:00 2001 From: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@sprout-oss.stage.blox.sqprod.co> Date: Fri, 26 Jun 2026 13:14:54 -0400 Subject: [PATCH] feat(db): add cron claim primitives Co-authored-by: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@sprout-oss.stage.blox.sqprod.co> Signed-off-by: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@sprout-oss.stage.blox.sqprod.co> --- crates/buzz-db/src/event.rs | 45 ++++++++++++++++++++++++++++-- crates/buzz-db/src/lib.rs | 40 ++++++++++++++++++++++++++ crates/buzz-db/src/migration.rs | 7 +++++ crates/buzz-db/src/workflow.rs | 29 +++++++++++++++++++ migrations/0001_initial_schema.sql | 14 ++++++++++ schema/schema.sql | 14 ++++++++++ 6 files changed, 147 insertions(+), 2 deletions(-) diff --git a/crates/buzz-db/src/event.rs b/crates/buzz-db/src/event.rs index 9cef6c53c3..2b80b81d8c 100644 --- a/crates/buzz-db/src/event.rs +++ b/crates/buzz-db/src/event.rs @@ -1083,7 +1083,19 @@ pub async fn claim_due_reminder( event_id: &[u8], event_created_at: DateTime, ) -> Result { - let now_epoch = Utc::now().timestamp(); + claim_due_reminder_with_stamp(pool, event_id, event_created_at, Utc::now().timestamp()).await +} + +/// Atomically claim a due reminder using a caller-supplied delivery stamp. +/// +/// The same stamp should be passed to [`release_due_reminder`] if the publish +/// side effect fails, so rollback can compare-and-clear only this pod's claim. +pub async fn claim_due_reminder_with_stamp( + pool: &PgPool, + event_id: &[u8], + event_created_at: DateTime, + delivery_stamp: i64, +) -> Result { let result = sqlx::query( r#" UPDATE events @@ -1091,7 +1103,7 @@ pub async fn claim_due_reminder( WHERE created_at = $2 AND id = $3 AND delivered_at IS NULL "#, ) - .bind(now_epoch) + .bind(delivery_stamp) .bind(event_created_at) .bind(event_id) .execute(pool) @@ -1100,6 +1112,35 @@ pub async fn claim_due_reminder( Ok(result.rows_affected() > 0) } +/// Release a previously claimed reminder when publish fails. +/// +/// The `delivery_stamp` must be the exact value written by the claiming pod; +/// that compare-and-clear prevents one pod from rolling back another pod's +/// later claim after a retry/race. +pub async fn release_due_reminder( + pool: &PgPool, + event_id: &[u8], + event_created_at: DateTime, + delivery_stamp: i64, +) -> Result<()> { + sqlx::query( + r#" + UPDATE events + SET delivered_at = NULL + WHERE created_at = $1 + AND id = $2 + AND delivered_at = $3 + "#, + ) + .bind(event_created_at) + .bind(event_id) + .bind(delivery_stamp) + .execute(pool) + .await?; + + Ok(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index 2e18fdbbf6..2b3ce6deb4 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -647,6 +647,27 @@ impl Db { event::claim_due_reminder(&self.pool, event_id, event_created_at).await } + /// Atomically claim a due reminder using a caller-supplied delivery stamp. + pub async fn claim_due_reminder_with_stamp( + &self, + event_id: &[u8], + event_created_at: chrono::DateTime, + delivery_stamp: i64, + ) -> Result { + event::claim_due_reminder_with_stamp(&self.pool, event_id, event_created_at, delivery_stamp) + .await + } + + /// Release a claimed due reminder after a publish failure. + pub async fn release_due_reminder( + &self, + event_id: &[u8], + event_created_at: chrono::DateTime, + delivery_stamp: i64, + ) -> Result<()> { + event::release_due_reminder(&self.pool, event_id, event_created_at, delivery_stamp).await + } + /// Ensure a user record exists (upsert). pub async fn ensure_user(&self, pubkey: &[u8]) -> Result<()> { user::ensure_user(&self.pool, pubkey).await @@ -1227,6 +1248,25 @@ impl Db { workflow::list_all_enabled_workflows(&self.pool).await } + /// Claim a scheduled workflow fire for a quantized schedule window. + /// + /// Returns `true` only for the first pod to claim `(workflow_id, + /// scheduled_for)`; all other pods must skip creating a run. + pub async fn claim_scheduled_workflow_fire( + &self, + community_id: CommunityId, + workflow_id: Uuid, + scheduled_for: chrono::DateTime, + ) -> Result { + workflow::claim_scheduled_workflow_fire( + &self.pool, + community_id, + workflow_id, + scheduled_for, + ) + .await + } + /// Update a workflow's name, definition, and hash. pub async fn update_workflow( &self, diff --git a/crates/buzz-db/src/migration.rs b/crates/buzz-db/src/migration.rs index de902f636b..84fc50a6b9 100644 --- a/crates/buzz-db/src/migration.rs +++ b/crates/buzz-db/src/migration.rs @@ -138,6 +138,13 @@ mod tests { .contains("CREATE TABLE communities"), "initial schema migration should include tenant host map" ); + assert!( + migrations[0] + .sql + .as_str() + .contains("CREATE TABLE scheduled_workflow_fires"), + "initial schema migration should include workflow cron claim table" + ); assert!( migrations[0].sql.as_str().contains("CREATE TABLE channels"), "initial schema migration should include Buzz core tables" diff --git a/crates/buzz-db/src/workflow.rs b/crates/buzz-db/src/workflow.rs index 993dbf19de..a35812b282 100644 --- a/crates/buzz-db/src/workflow.rs +++ b/crates/buzz-db/src/workflow.rs @@ -15,6 +15,8 @@ use sha2::{Digest, Sha256}; use sqlx::{PgPool, Row}; use uuid::Uuid; +use buzz_core::CommunityId; + use crate::error::{DbError, Result}; // -- Token hashing ------------------------------------------------------------ @@ -376,6 +378,33 @@ pub async fn list_all_enabled_workflows(pool: &PgPool) -> Result, +) -> Result { + let result = sqlx::query( + r#" + INSERT INTO scheduled_workflow_fires (community_id, workflow_id, scheduled_for) + VALUES ($1, $2, $3) + ON CONFLICT (community_id, workflow_id, scheduled_for) DO NOTHING + "#, + ) + .bind(community_id.as_uuid()) + .bind(workflow_id) + .bind(scheduled_for) + .execute(pool) + .await?; + + Ok(result.rows_affected() == 1) +} + /// Update a workflow's name, definition, and definition_hash. pub async fn update_workflow( pool: &PgPool, diff --git a/migrations/0001_initial_schema.sql b/migrations/0001_initial_schema.sql index 99bbc870e6..e7f94b7f90 100644 --- a/migrations/0001_initial_schema.sql +++ b/migrations/0001_initial_schema.sql @@ -223,6 +223,20 @@ CREATE TABLE workflows ( CREATE INDEX idx_workflows_channel_active ON workflows (channel_id, status, enabled); +-- Restart-safe horizontal-scaling claim table for scheduled workflow fires. +-- Each schedule tick must win this insert before creating a workflow run; this +-- replaces per-pod in-memory last-fired state as the deduplication boundary. +CREATE TABLE scheduled_workflow_fires ( + community_id UUID NOT NULL REFERENCES communities(id), + workflow_id UUID NOT NULL REFERENCES workflows(id) ON DELETE CASCADE, + scheduled_for TIMESTAMPTZ NOT NULL, + claimed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (community_id, workflow_id, scheduled_for) +); + +CREATE INDEX idx_scheduled_workflow_fires_scheduled_for + ON scheduled_workflow_fires (community_id, scheduled_for); + -- ── Workflow runs ───────────────────────────────────────────────────────────── CREATE TABLE workflow_runs ( diff --git a/schema/schema.sql b/schema/schema.sql index a3882804ef..ccb73bf58a 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -228,6 +228,20 @@ CREATE TABLE workflows ( CREATE INDEX idx_workflows_channel_active ON workflows (channel_id, status, enabled); +-- Restart-safe horizontal-scaling claim table for scheduled workflow fires. +-- Each schedule tick must win this insert before creating a workflow run; this +-- replaces per-pod in-memory last-fired state as the deduplication boundary. +CREATE TABLE scheduled_workflow_fires ( + community_id UUID NOT NULL REFERENCES communities(id), + workflow_id UUID NOT NULL REFERENCES workflows(id) ON DELETE CASCADE, + scheduled_for TIMESTAMPTZ NOT NULL, + claimed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (community_id, workflow_id, scheduled_for) +); + +CREATE INDEX idx_scheduled_workflow_fires_scheduled_for + ON scheduled_workflow_fires (community_id, scheduled_for); + -- ── Workflow runs ───────────────────────────────────────────────────────────── CREATE TABLE workflow_runs (