LINE1 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.10pubtypeDb = 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)]15pubstructApiKey(pubString);1617/// Opens (or creates) the broker database at `path`, e.g. `"dial.db"`,18/// or `":memory:"` for a throwaway broker.19pubfnopen(path: &str) -> rusqlite::Result<Db> {20let 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 )?;31Ok(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.36pubfnconfigure(cfg: &mut web::ServiceConfig) {37 cfg.service(up).service(publish).service(subscribe);38}3940/// Rejects the request unless it carries the configured bearer token.41fnauthorize(req: &HttpRequest, key: &ApiKey) -> Result<()> {42let 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("");48ifconstant_time_eq(presented.as_bytes(), key.0.as_bytes()) {49Ok(())50 } else {51Err(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.57fnconstant_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")]63asyncfnup() -> HttpResponse {64HttpResponse::Ok().finish()65}6667#[derive(Serialize)]68structPublished {69 id: i64,70}7172/// Ingest point: stores the request body as one message on `topic`.73#[post("/publish/{topic}")]74asyncfnpublish(75 req: HttpRequest,76 key: web::Data<ApiKey>,77 db: web::Data<Db>,78 topic: web::Path<String>,79 body: String,80) -> Result<HttpResponse> {81authorize(&req, &key)?;82let db = db.get_ref().clone();83let topic = topic.into_inner();84let created_at = now_millis();85let id = web::block(move || -> rusqlite::Result<i64> {86let conn = db.lock().unwrap_or_else(PoisonError::into_inner);87 conn.execute(88"INSERT INTO messages (topic, payload, created_at) VALUES (?1, ?2, ?3)",89params![topic, body, created_at],90 )?;91Ok(conn.last_insert_rowid())92 })93 .await94 .map_err(error::ErrorInternalServerError)?95 .map_err(error::ErrorInternalServerError)?;96Ok(HttpResponse::Created().json(Published { id }))97}9899#[derive(Deserialize)]100structSubscribeQuery {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}108109fndefault_limit() -> u32 {110100111}112113#[derive(Serialize)]114structMessage {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}")]122asyncfnsubscribe(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> {129authorize(&req, &key)?;130let db = db.get_ref().clone();131let topic = topic.into_inner();132let after = query.after;133let limit = query.limit.clamp(1, 1000);134let messages = web::block(move || -> rusqlite::Result<Vec<Message>> {135let conn = db.lock().unwrap_or_else(PoisonError::into_inner);136letmut stmt = conn.prepare(137"SELECT id, payload, created_at FROM messages138 WHERE topic = ?1 AND id > ?2 ORDER BY id LIMIT ?3",139 )?;140let rows = stmt.query_map(params![topic, after, limit], |row| {141Ok(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)?;152Ok(HttpResponse::Ok().json(messages))153}154155fnnow_millis() -> i64 {156SystemTime::now()157 .duration_since(UNIX_EPOCH)158 .map(|d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))159 .unwrap_or(0)160}