use chrono::{DateTime, Utc};
use ruststream::OutgoingMessage;
use serde::{Deserialize, Serialize};
use sqlx::SqliteConnection;
use ruststream_sqlx::prelude::*;
use sqlx::Connection;
use sqlx::Sqlite;
use sqlx::sqlite::SqlitePoolOptions;
#[derive(Inbox, sqlx::FromRow)]
#[inbox(table = "signup_jobs")]
struct OpenAccount {
#[field(id, generated)]
id: i64,
#[field(attempt, generated)]
attempt: i16,
#[field(locked_until)]
locked_until: Option<DateTime<Utc>>,
#[field(payload)]
payload: Vec<u8>,
}
#[subscriber(InboxQueue::<OpenAccount>::new("signups"))]
async fn open_account(
signup: &Signup,
Ctx(mut tx): Ctx<keys::Tx<Sqlite>>,
Ctx(pool): Ctx<keys::Pool<Sqlite>>,
Ctx(attempt): Ctx<keys::Attempt>,
) -> HandlerOutcome {
let _ = sqlx::query("INSERT INTO signup_log (email, attempt) VALUES (?, ?)")
.bind(&signup.email)
.bind(attempt.and_then(|attempt| i64::try_from(attempt).ok()))
.execute(&pool)
.await;
let opened = sqlx::query("INSERT INTO accounts (email) VALUES (?)")
.bind(&signup.email)
.execute(&mut *tx)
.await;
if opened.is_err() || !register(signup, attempt).await {
return HandlerOutcome::retry();
}
HandlerOutcome::ack()
}
fn service(url: &str) -> RustStream {
let schema_url = url.to_owned();
let broker = SqlxBroker::from_url(url, SqlitePoolOptions::new());
RustStream::new(AppInfo::new("accounts", "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.route::<OpenAccount>("signups"), |b| {
b.include(open_account.transactional());
})
}
async fn register(signup: &Signup, attempt: Option<u64>) -> bool {
tokio::task::yield_now().await;
tracing::info!(email = %signup.email, ?attempt, "registering the account");
attempt != Some(1)
}
#[ruststream::app]
fn app() -> impl App {
service("sqlite:accounts.db?mode=rwc")
}
const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS signup_jobs (
id INTEGER PRIMARY KEY,
attempt INTEGER NOT NULL DEFAULT 1,
locked_until TEXT,
payload BLOB NOT NULL
);
CREATE TABLE IF NOT EXISTS signup_log (email TEXT NOT NULL, attempt INTEGER);
CREATE TABLE IF NOT EXISTS accounts (email TEXT PRIMARY KEY)";
impl Publish<Sqlite> for OpenAccount {
async fn publish(
conn: &mut SqliteConnection,
message: &OutgoingMessage<'_>,
) -> Result<(), sqlx::Error> {
sqlx::query("INSERT INTO signup_jobs (payload) VALUES (?)")
.bind(message.payload())
.execute(conn)
.await?;
Ok(())
}
}
#[derive(Debug, PartialEq, Deserialize, Serialize, Outgoing)]
#[outgoing(name = "signups")]
struct Signup {
email: String,
}
#[cfg(test)]
mod tests {
use std::error::Error;
use ruststream::testing::TestApp;
use ruststream_sqlx::prelude::*;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use sqlx::{Connection, Sqlite, SqliteConnection, SqlitePool};
use super::{SCHEMA, Signup, 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 the_log_keeps_every_attempt_and_the_account_commits_once() -> Result<(), Box<dyn Error>>
{
let (url, pool, _keeper) = database("sqlx_context").await?;
let tb = TestApp::start(service(&url)).await?;
let signup = Signup {
email: "ada@example.com".to_owned(),
};
tb.broker::<SqlxBroker<Sqlite>>()
.message(&signup)
.publish()
.await?;
let logged: Vec<i64> =
sqlx::query_scalar("SELECT attempt FROM signup_log ORDER BY attempt")
.fetch_all(&pool)
.await?;
assert_eq!(logged, [1, 2], "the pool's writes outlived the retry");
let accounts: i64 = sqlx::query_scalar("SELECT count(*) FROM accounts")
.fetch_one(&pool)
.await?;
assert_eq!(accounts, 1, "the retry rolled the first account back");
Ok(())
}
}