Skip to content
1        10        20        30        40        50        60        70        80        901use std::sync::{Arc, Mutex, PoisonError};2use std::time::{SystemTime, UNIX_EPOCH};34use actix_web::http::header::AUTHORIZATION;5use actix_web::{HttpRequest, HttpResponse, Result, error, get, post, web};6use rusqlite::{Connection, params};7use serde::{Deserialize, Serialize};89/// Shared handle to the SQLite database file.10pub type Db = Arc<Mutex<Connection>>;1112/// The API key that publishers and subscribers must present as13/// `Authorization: Bearer <key>`. The health check does not require it.14#[derive(Clone)]15pub struct ApiKey(pub String);1617/// Opens (or creates) the broker database at `path`, e.g. `"dial.db"`,18/// or `":memory:"` for a throwaway broker.19pub fn open(path: &str) -> rusqlite::Result<Db> {20    let conn = Connection::open(path)?;21    conn.pragma_update(None, "journal_mode", "WAL")?;22    conn.execute_batch(23        "CREATE TABLE IF NOT EXISTS messages (24             id         INTEGER PRIMARY KEY AUTOINCREMENT,25             topic      TEXT    NOT NULL,26             payload    TEXT    NOT NULL,27             created_at INTEGER NOT NULL28         );29         CREATE INDEX IF NOT EXISTS messages_topic_id ON messages (topic, id);",30    )?;31    Ok(Arc::new(Mutex::new(conn)))32}3334/// Registers the health check and the publish and subscribe routes.35/// Expects `web::Data<Db>` and `web::Data<ApiKey>` in the app.36pub fn configure(cfg: &mut web::ServiceConfig) {37    cfg.service(up).service(publish).service(subscribe);38}3940/// Rejects the request unless it carries the configured bearer token.41fn authorize(req: &HttpRequest, key: &ApiKey) -> Result<()> {42    let presented = req43        .headers()44        .get(AUTHORIZATION)45        .and_then(|value| value.to_str().ok())46        .and_then(|value| value.strip_prefix("Bearer "))47        .unwrap_or("");48    if constant_time_eq(presented.as_bytes(), key.0.as_bytes()) {49        Ok(())50    } else {51        Err(error::ErrorUnauthorized("missing or invalid API key"))52    }53}5455/// Compares two byte strings without exiting early on the first mismatch.56/// The length is not hidden, which is acceptable for a fixed-length key.57fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {58    a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 059}6061/// Health check used by the Once/ino deployment: returns 200 when the broker is serving.62#[get("/up")]63async fn up() -> HttpResponse {64    HttpResponse::Ok().finish()65}6667#[derive(Serialize)]68struct Published {69    id: i64,70}7172/// Ingest point: stores the request body as one message on `topic`.73#[post("/publish/{topic}")]74async fn publish(75    req: HttpRequest,76    key: web::Data<ApiKey>,77    db: web::Data<Db>,78    topic: web::Path<String>,79    body: String,80) -> Result<HttpResponse> {81    authorize(&req, &key)?;82    let db = db.get_ref().clone();83    let topic = topic.into_inner();84    let created_at = now_millis();85    let id = web::block(move || -> rusqlite::Result<i64> {86        let conn = db.lock().unwrap_or_else(PoisonError::into_inner);87        conn.execute(88            "INSERT INTO messages (topic, payload, created_at) VALUES (?1, ?2, ?3)",89            params![topic, body, created_at],90        )?;91        Ok(conn.last_insert_rowid())92    })93    .await94    .map_err(error::ErrorInternalServerError)?95    .map_err(error::ErrorInternalServerError)?;96    Ok(HttpResponse::Created().json(Published { id }))97}9899#[derive(Deserialize)]100struct SubscribeQuery {101    /// Return only messages with an id greater than this. Use the last id you saw.102    #[serde(default)]103    after: i64,104    /// Maximum number of messages to return (1..=1000).105    #[serde(default = "default_limit")]106    limit: u32,107}108109fn default_limit() -> u32 {110    100111}112113#[derive(Serialize)]114struct Message {115    id: i64,116    payload: String,117    created_at: i64,118}119120/// Subscription point: returns messages on `topic` in id order, starting after the cursor.121#[get("/subscribe/{topic}")]122async fn subscribe(123    req: HttpRequest,124    key: web::Data<ApiKey>,125    db: web::Data<Db>,126    topic: web::Path<String>,127    query: web::Query<SubscribeQuery>,128) -> Result<HttpResponse> {129    authorize(&req, &key)?;130    let db = db.get_ref().clone();131    let topic = topic.into_inner();132    let after = query.after;133    let limit = query.limit.clamp(1, 1000);134    let messages = web::block(move || -> rusqlite::Result<Vec<Message>> {135        let conn = db.lock().unwrap_or_else(PoisonError::into_inner);136        let mut stmt = conn.prepare(137            "SELECT id, payload, created_at FROM messages138             WHERE topic = ?1 AND id > ?2 ORDER BY id LIMIT ?3",139        )?;140        let rows = stmt.query_map(params![topic, after, limit], |row| {141            Ok(Message {142                id: row.get(0)?,143                payload: row.get(1)?,144                created_at: row.get(2)?,145            })146        })?;147        rows.collect()148    })149    .await150    .map_err(error::ErrorInternalServerError)?151    .map_err(error::ErrorInternalServerError)?;152    Ok(HttpResponse::Ok().json(messages))153}154155fn now_millis() -> i64 {156    SystemTime::now()157        .duration_since(UNIX_EPOCH)158        .map(|d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))159        .unwrap_or(0)160}