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>
This commit is contained in:
npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf
2026-06-26 13:14:54 -04:00
parent 48bc606abf
commit 29f7333d3f
6 changed files with 147 additions and 2 deletions

View File

@@ -1083,7 +1083,19 @@ pub async fn claim_due_reminder(
event_id: &[u8],
event_created_at: DateTime<Utc>,
) -> Result<bool> {
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<Utc>,
delivery_stamp: i64,
) -> Result<bool> {
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<Utc>,
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::*;

View File

@@ -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<chrono::Utc>,
delivery_stamp: i64,
) -> Result<bool> {
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<chrono::Utc>,
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<chrono::Utc>,
) -> Result<bool> {
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,

View File

@@ -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"

View File

@@ -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<Vec<WorkflowRec
rows.into_iter().map(row_to_workflow_record).collect()
}
/// Claim a scheduled workflow fire for a quantized schedule window.
///
/// Returns `true` only for the first pod that claims `(workflow_id,
/// scheduled_for)`. All other pods receive `false` and must skip creating a
/// workflow run. This is the restart-safe cross-pod dedupe boundary for cron.
pub async fn claim_scheduled_workflow_fire(
pool: &PgPool,
community_id: CommunityId,
workflow_id: Uuid,
scheduled_for: DateTime<Utc>,
) -> Result<bool> {
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,

View File

@@ -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 (

View File

@@ -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 (