use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::time::Duration;
use ruststream_sqlx::prelude::*;
use sqlx::sqlite::SqlitePoolOptions;
use sqlx::{Connection, SqliteConnection};
#[derive(Inbox, sqlx::FromRow)]
#[inbox(table = "export_jobs")]
struct Export {
#[field(id, generated)]
id: i64,
#[field(locked_until)]
locked_until: Option<DateTime<Utc>>,
#[field(payload)]
payload: Vec<u8>,
}
#[subscriber(InboxQueue::<Export>::new("exports").poll_interval(Duration::from_millis(200)))]
async fn upload(file: &ExportFile) -> HandlerOutcome {
tracing::info!(path = %file.path, "uploading an export");
HandlerOutcome::ack()
}
fn service(url: &str) -> RustStream {
let schema_url = url.to_owned();
let broker = SqlxBroker::from_url(url, SqlitePoolOptions::new());
let broker = broker.poll_interval(Duration::from_secs(5));
RustStream::new(AppInfo::new("exports", "0.1.0"))
.on_startup(async move |()| {
let mut conn = SqliteConnection::connect(&schema_url).await?;
sqlx::raw_sql(SCHEMA).execute(&mut conn).await?;
conn.close().await
})
.with_broker(broker, |b| {
b.include(upload);
})
}
#[ruststream::app]
fn app() -> impl App {
service("sqlite:exports.db?mode=rwc")
}
const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS export_jobs (
id INTEGER PRIMARY KEY,
locked_until TEXT,
payload BLOB NOT NULL
)";
#[derive(Debug, PartialEq, Deserialize, Serialize)]
struct ExportFile {
path: String,
}
#[cfg(test)]
mod tests {
use std::error::Error;
use std::time::Duration;
use ruststream::testing::TestApp;
use ruststream_sqlx::prelude::*;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use sqlx::{Connection, Sqlite, SqliteConnection, SqlitePool};
use super::{ExportFile, SCHEMA, service};
async fn database(
name: &str,
) -> Result<(String, SqlitePool, SqliteConnection), Box<dyn Error>> {
let url = format!("sqlite:file:{name}?mode=memory&cache=shared");
let options: SqliteConnectOptions = url.parse()?;
let keeper = SqliteConnection::connect_with(&options).await?;
let pool = SqlitePoolOptions::new()
.min_connections(1)
.idle_timeout(None)
.connect_with(options)
.await?;
sqlx::raw_sql(SCHEMA).execute(&pool).await?;
Ok((url, pool, keeper))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_row_written_by_another_system_is_claimed_at_the_poll_interval()
-> Result<(), Box<dyn Error>> {
let (url, pool, _keeper) = database("sqlx_subscriptions_poll").await?;
let tb = TestApp::start_live(service(&url)).await?;
tb.advance(Duration::from_millis(300)).await?;
let file = ExportFile {
path: "exports/2026-10-18.csv".to_owned(),
};
sqlx::query("INSERT INTO export_jobs (payload) VALUES (?)")
.bind(serde_json::to_vec(&file)?)
.execute(&pool)
.await?;
tb.advance(Duration::from_secs(1)).await?;
tb.broker::<SqlxBroker<Sqlite>>()
.subscriber("exports")
.assert_called_once()
.with(&file)
.settled(HandlerOutcome::ack());
Ok(())
}
}