use chrono::{DateTime, Utc};
use ruststream::OutgoingMessage;
use serde::{Deserialize, Serialize};
use sqlx::{Sqlite, SqliteConnection};
use ruststream_sqlx::prelude::*;
use sqlx::Connection;
use sqlx::sqlite::SqlitePoolOptions;
#[derive(Inbox, sqlx::FromRow)]
#[inbox(table = "image_jobs")]
struct Resize {
#[field(id, generated)]
id: i64,
#[field(locked_until)]
locked_until: Option<DateTime<Utc>>,
#[field(payload)]
payload: Vec<u8>,
}
#[derive(Inbox, sqlx::FromRow)]
#[inbox(table = "ledger_jobs")]
struct Post {
#[field(id, generated)]
id: i64,
#[field(partition_key)]
account: String,
#[field(locked_until)]
locked_until: Option<DateTime<Utc>>,
#[field(payload)]
payload: Vec<u8>,
}
#[subscriber(InboxQueue::<Resize>::new("images"))]
async fn resize(image: &Image) -> HandlerOutcome {
tracing::info!(path = %image.path, "resizing");
HandlerOutcome::ack()
}
#[subscriber(InboxQueue::<Post>::new("postings"))]
async fn post(posting: &Posting) -> HandlerOutcome {
tracing::info!(account = %posting.account, posting.n, "posting");
HandlerOutcome::ack()
}
fn service(url: &str) -> RustStream {
let schema_url = url.to_owned();
let broker = SqlxBroker::from_url(url, SqlitePoolOptions::new());
let broker = broker.route::<Resize>("images").route::<Post>("postings");
RustStream::new(AppInfo::new("back-office", "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(resize.workers(nonzero!(4)));
b.include(post.workers_by_key(nonzero!(4)));
})
}
#[ruststream::app]
fn app() -> impl App {
service("sqlite:back-office.db?mode=rwc")
}
const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS image_jobs (
id INTEGER PRIMARY KEY,
locked_until TEXT,
payload BLOB NOT NULL
);
CREATE TABLE IF NOT EXISTS ledger_jobs (
id INTEGER PRIMARY KEY,
account TEXT NOT NULL,
locked_until TEXT,
payload BLOB NOT NULL
)";
impl Publish<Sqlite> for Resize {
async fn publish(
conn: &mut SqliteConnection,
message: &OutgoingMessage<'_>,
) -> Result<(), sqlx::Error> {
sqlx::query("INSERT INTO image_jobs (payload) VALUES (?)")
.bind(message.payload())
.execute(conn)
.await?;
Ok(())
}
}
impl Publish<Sqlite> for Post {
async fn publish(
conn: &mut SqliteConnection,
message: &OutgoingMessage<'_>,
) -> Result<(), sqlx::Error> {
sqlx::query(
"INSERT INTO ledger_jobs (account, payload) \
VALUES (json_extract(CAST(?1 AS TEXT), '$.account'), ?1)",
)
.bind(message.payload())
.execute(conn)
.await?;
Ok(())
}
}
#[derive(Debug, PartialEq, Deserialize, Serialize, Outgoing)]
#[outgoing(name = "images")]
struct Image {
path: String,
}
#[derive(Debug, PartialEq, Deserialize, Serialize, Outgoing)]
#[outgoing(name = "postings")]
struct Posting {
account: String,
n: u32,
}
#[cfg(test)]
mod tests {
use std::error::Error;
use futures::future::try_join_all;
use ruststream::testing::TestApp;
use ruststream_sqlx::prelude::*;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use sqlx::{Connection, Sqlite, SqliteConnection, SqlitePool};
use super::{Image, Posting, 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 every_image_is_resized_once() -> Result<(), Box<dyn Error>> {
let (url, _pool, _keeper) = database("sqlx_subscriptions_workers_images").await?;
let tb = TestApp::start(service(&url)).await?;
let images: Vec<Image> = (1..=6)
.map(|n| Image {
path: format!("upload/{n}.png"),
})
.collect();
let broker = tb.broker::<SqlxBroker<Sqlite>>();
try_join_all(images.iter().map(|image| broker.message(image).publish())).await?;
let mut resized: Vec<Image> = broker.subscriber("images").received();
resized.sort_by(|left, right| left.path.cmp(&right.path));
assert_eq!(resized, images);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn each_accounts_postings_keep_their_order() -> Result<(), Box<dyn Error>> {
let (url, _pool, _keeper) = database("sqlx_subscriptions_workers_postings").await?;
let tb = TestApp::start(service(&url)).await?;
let postings: Vec<Posting> = (1..=8)
.map(|n| Posting {
account: if n % 2 == 0 { "acme" } else { "globex" }.to_owned(),
n,
})
.collect();
let broker = tb.broker::<SqlxBroker<Sqlite>>();
try_join_all(
postings
.iter()
.map(|posting| broker.message(posting).publish()),
)
.await?;
let received: Vec<Posting> = broker.subscriber("postings").received();
for account in ["acme", "globex"] {
let order: Vec<u32> = received
.iter()
.filter(|posting| posting.account == account)
.map(|posting| posting.n)
.collect();
let written: Vec<u32> = postings
.iter()
.filter(|posting| posting.account == account)
.map(|posting| posting.n)
.collect();
assert_eq!(order, written, "the postings of {account}");
}
Ok(())
}
}