feat: reorganize to one flake one rust project
This commit is contained in:
parent
5183130427
commit
e8b60519e7
23 changed files with 792 additions and 2144 deletions
2209
remote/Cargo.lock
generated
2209
remote/Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -1,3 +0,0 @@
|
|||
[workspace]
|
||||
members = ["noisebell-common", "cache-service", "discord-bot", "rss-service"]
|
||||
resolver = "2"
|
||||
|
|
@ -23,6 +23,8 @@ pub struct AppState {
|
|||
pub webhooks: Vec<WebhookTarget>,
|
||||
pub retry_attempts: u32,
|
||||
pub retry_base_delay_secs: u64,
|
||||
pub webhook_last_request: std::sync::atomic::AtomicU64,
|
||||
pub webhook_tokens: std::sync::atomic::AtomicU32,
|
||||
}
|
||||
|
||||
fn unix_now() -> u64 {
|
||||
|
|
@ -32,6 +34,9 @@ fn unix_now() -> u64 {
|
|||
.as_secs()
|
||||
}
|
||||
|
||||
const WEBHOOK_RATE_LIMIT: u32 = 10;
|
||||
const WEBHOOK_RATE_WINDOW_SECS: u64 = 60;
|
||||
|
||||
pub async fn post_webhook(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
|
|
@ -41,6 +46,22 @@ pub async fn post_webhook(
|
|||
return StatusCode::UNAUTHORIZED;
|
||||
}
|
||||
|
||||
// Simple rate limiting: reset tokens every window, reject if exhausted
|
||||
let now = unix_now();
|
||||
let last = state.webhook_last_request.load(std::sync::atomic::Ordering::Relaxed);
|
||||
if now.saturating_sub(last) >= WEBHOOK_RATE_WINDOW_SECS {
|
||||
state.webhook_tokens.store(WEBHOOK_RATE_LIMIT, std::sync::atomic::Ordering::Relaxed);
|
||||
state.webhook_last_request.store(now, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
let remaining = state.webhook_tokens.fetch_update(
|
||||
std::sync::atomic::Ordering::Relaxed,
|
||||
std::sync::atomic::Ordering::Relaxed,
|
||||
|n| if n > 0 { Some(n - 1) } else { None },
|
||||
);
|
||||
if remaining.is_err() {
|
||||
return StatusCode::TOO_MANY_REQUESTS;
|
||||
}
|
||||
|
||||
let Some(status) = DoorStatus::from_str(&body.status) else {
|
||||
return StatusCode::BAD_REQUEST;
|
||||
};
|
||||
|
|
@ -148,17 +169,16 @@ pub async fn get_image(State(state): State<Arc<AppState>>) -> impl IntoResponse
|
|||
let db = state.db.clone();
|
||||
let status = tokio::task::spawn_blocking(move || {
|
||||
let conn = db.blocking_lock();
|
||||
db::get_current_status_str(&conn)
|
||||
db::get_current_status(&conn)
|
||||
})
|
||||
.await
|
||||
.expect("db task panicked")
|
||||
.ok()
|
||||
.flatten();
|
||||
.unwrap_or(DoorStatus::Offline);
|
||||
|
||||
let image = match status.as_deref() {
|
||||
Some("open") => OPEN_PNG,
|
||||
Some("closed") => CLOSED_PNG,
|
||||
_ => OFFLINE_PNG,
|
||||
let image = match status {
|
||||
DoorStatus::Open => OPEN_PNG,
|
||||
DoorStatus::Closed => CLOSED_PNG,
|
||||
DoorStatus::Offline => OFFLINE_PNG,
|
||||
};
|
||||
([(header::CONTENT_TYPE, "image/png"), (header::CACHE_CONTROL, "public, max-age=5")], image)
|
||||
}
|
||||
|
|
@ -167,17 +187,16 @@ pub async fn get_badge(State(state): State<Arc<AppState>>) -> impl IntoResponse
|
|||
let db = state.db.clone();
|
||||
let status = tokio::task::spawn_blocking(move || {
|
||||
let conn = db.blocking_lock();
|
||||
db::get_current_status_str(&conn)
|
||||
db::get_current_status(&conn)
|
||||
})
|
||||
.await
|
||||
.expect("db task panicked")
|
||||
.ok()
|
||||
.flatten();
|
||||
.unwrap_or(DoorStatus::Offline);
|
||||
|
||||
let (label, color) = match status.as_deref() {
|
||||
Some("open") => ("open", "#57f287"),
|
||||
Some("closed") => ("closed", "#ed4245"),
|
||||
_ => ("offline", "#99aab5"),
|
||||
let (label, color) = match status {
|
||||
DoorStatus::Open => ("open", "#57f287"),
|
||||
DoorStatus::Closed => ("closed", "#ed4245"),
|
||||
DoorStatus::Offline => ("offline", "#99aab5"),
|
||||
};
|
||||
|
||||
let label_width = 70u32;
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@ pub fn init(path: &str) -> Result<Connection> {
|
|||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
status TEXT,
|
||||
timestamp INTEGER,
|
||||
last_seen INTEGER
|
||||
last_seen INTEGER,
|
||||
last_checked INTEGER
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS state_log (
|
||||
|
|
@ -28,17 +29,29 @@ pub fn init(path: &str) -> Result<Connection> {
|
|||
fetched_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
INSERT OR IGNORE INTO current_state (id, status, timestamp, last_seen) VALUES (1, NULL, NULL, NULL);
|
||||
INSERT OR IGNORE INTO current_state (id, status, timestamp, last_seen, last_checked) VALUES (1, 'offline', NULL, NULL, NULL);
|
||||
INSERT OR IGNORE INTO pi_info (id, data, fetched_at) VALUES (1, '{}', 0);
|
||||
",
|
||||
)
|
||||
.context("failed to initialize database schema")?;
|
||||
|
||||
// Migration: add last_checked column if missing (existing databases)
|
||||
let has_last_checked: bool = conn
|
||||
.prepare("SELECT last_checked FROM current_state LIMIT 1")
|
||||
.is_ok();
|
||||
if !has_last_checked {
|
||||
conn.execute_batch("ALTER TABLE current_state ADD COLUMN last_checked INTEGER")?;
|
||||
}
|
||||
|
||||
// Migration: convert NULL status to 'offline'
|
||||
conn.execute("UPDATE current_state SET status = 'offline' WHERE status IS NULL", [])?;
|
||||
|
||||
Ok(conn)
|
||||
}
|
||||
|
||||
pub fn get_status(conn: &Connection) -> Result<StatusResponse> {
|
||||
let (status, timestamp, last_seen) = conn.query_row(
|
||||
"SELECT status, timestamp, last_seen FROM current_state WHERE id = 1",
|
||||
let (status_str, timestamp, last_checked) = conn.query_row(
|
||||
"SELECT status, timestamp, last_checked FROM current_state WHERE id = 1",
|
||||
[],
|
||||
|row| {
|
||||
Ok((
|
||||
|
|
@ -48,10 +61,14 @@ pub fn get_status(conn: &Connection) -> Result<StatusResponse> {
|
|||
))
|
||||
},
|
||||
)?;
|
||||
let status = status_str
|
||||
.as_deref()
|
||||
.and_then(DoorStatus::from_str)
|
||||
.unwrap_or(DoorStatus::Offline);
|
||||
Ok(StatusResponse {
|
||||
status: status.unwrap_or_else(|| "offline".to_string()),
|
||||
timestamp,
|
||||
last_seen,
|
||||
status,
|
||||
since: timestamp,
|
||||
last_checked,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -59,7 +76,7 @@ pub fn update_state(conn: &Connection, status: DoorStatus, timestamp: u64, now:
|
|||
let status_str = status.as_str();
|
||||
conn.execute(
|
||||
"UPDATE current_state SET status = ?1, timestamp = ?2, last_seen = ?3 WHERE id = 1",
|
||||
rusqlite::params![status_str, timestamp, now],
|
||||
rusqlite::params![status_str, now, now],
|
||||
)?;
|
||||
conn.execute(
|
||||
"INSERT INTO state_log (status, timestamp, recorded_at) VALUES (?1, ?2, ?3)",
|
||||
|
|
@ -76,10 +93,18 @@ pub fn update_last_seen(conn: &Connection, now: u64) -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_last_checked(conn: &Connection, now: u64) -> Result<()> {
|
||||
conn.execute(
|
||||
"UPDATE current_state SET last_checked = ?1 WHERE id = 1",
|
||||
rusqlite::params![now],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn mark_offline(conn: &Connection, now: u64) -> Result<()> {
|
||||
conn.execute(
|
||||
"UPDATE current_state SET status = NULL WHERE id = 1",
|
||||
[],
|
||||
"UPDATE current_state SET status = 'offline', timestamp = ?1 WHERE id = 1",
|
||||
rusqlite::params![now],
|
||||
)?;
|
||||
conn.execute(
|
||||
"INSERT INTO state_log (status, timestamp, recorded_at) VALUES ('offline', ?1, ?1)",
|
||||
|
|
@ -88,13 +113,16 @@ pub fn mark_offline(conn: &Connection, now: u64) -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_current_status_str(conn: &Connection) -> Result<Option<String>> {
|
||||
let status = conn.query_row(
|
||||
pub fn get_current_status(conn: &Connection) -> Result<DoorStatus> {
|
||||
let status_str: Option<String> = conn.query_row(
|
||||
"SELECT status FROM current_state WHERE id = 1",
|
||||
[],
|
||||
|row| row.get::<_, Option<String>>(0),
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
Ok(status)
|
||||
Ok(status_str
|
||||
.as_deref()
|
||||
.and_then(DoorStatus::from_str)
|
||||
.unwrap_or(DoorStatus::Offline))
|
||||
}
|
||||
|
||||
pub fn get_history(conn: &Connection, limit: u32) -> Result<Vec<noisebell_common::HistoryEntry>> {
|
||||
|
|
@ -131,3 +159,105 @@ pub fn update_pi_info(conn: &Connection, data: &serde_json::Value, now: u64) ->
|
|||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn test_db() -> Connection {
|
||||
init(":memory:").expect("failed to init test db")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_status_is_offline() {
|
||||
let conn = test_db();
|
||||
let status = get_status(&conn).unwrap();
|
||||
assert_eq!(status.status, DoorStatus::Offline);
|
||||
assert!(status.since.is_none());
|
||||
assert!(status.last_checked.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_state_changes_status() {
|
||||
let conn = test_db();
|
||||
update_state(&conn, DoorStatus::Open, 1000, 1001).unwrap();
|
||||
|
||||
let status = get_status(&conn).unwrap();
|
||||
assert_eq!(status.status, DoorStatus::Open);
|
||||
assert_eq!(status.since, Some(1001));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mark_offline_sets_offline_status() {
|
||||
let conn = test_db();
|
||||
update_state(&conn, DoorStatus::Open, 1000, 1001).unwrap();
|
||||
mark_offline(&conn, 2000).unwrap();
|
||||
|
||||
let status = get_status(&conn).unwrap();
|
||||
assert_eq!(status.status, DoorStatus::Offline);
|
||||
assert_eq!(status.since, Some(2000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_current_status_matches_get_status() {
|
||||
let conn = test_db();
|
||||
assert_eq!(get_current_status(&conn).unwrap(), DoorStatus::Offline);
|
||||
|
||||
update_state(&conn, DoorStatus::Closed, 1000, 1001).unwrap();
|
||||
assert_eq!(get_current_status(&conn).unwrap(), DoorStatus::Closed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_last_checked_is_readable() {
|
||||
let conn = test_db();
|
||||
update_last_checked(&conn, 5000).unwrap();
|
||||
|
||||
let status = get_status(&conn).unwrap();
|
||||
assert_eq!(status.last_checked, Some(5000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_records_state_changes() {
|
||||
let conn = test_db();
|
||||
update_state(&conn, DoorStatus::Open, 1000, 1001).unwrap();
|
||||
update_state(&conn, DoorStatus::Closed, 2000, 2001).unwrap();
|
||||
mark_offline(&conn, 3000).unwrap();
|
||||
|
||||
let history = get_history(&conn, 10).unwrap();
|
||||
assert_eq!(history.len(), 3);
|
||||
assert_eq!(history[0].status, "offline");
|
||||
assert_eq!(history[1].status, "closed");
|
||||
assert_eq!(history[2].status, "open");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_response_serializes_correctly() {
|
||||
let resp = StatusResponse {
|
||||
status: DoorStatus::Open,
|
||||
since: Some(1234),
|
||||
last_checked: Some(5678),
|
||||
};
|
||||
let json = serde_json::to_value(&resp).unwrap();
|
||||
assert_eq!(json["status"], "open");
|
||||
assert_eq!(json["since"], 1234);
|
||||
assert_eq!(json["last_checked"], 5678);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_status_migration_converts_to_offline() {
|
||||
// Simulate an old database with NULL status
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
conn.execute_batch("
|
||||
CREATE TABLE current_state (id INTEGER PRIMARY KEY CHECK (id = 1), status TEXT, timestamp INTEGER, last_seen INTEGER);
|
||||
INSERT INTO current_state (id, status, timestamp, last_seen) VALUES (1, NULL, NULL, NULL);
|
||||
CREATE TABLE state_log (id INTEGER PRIMARY KEY AUTOINCREMENT, status TEXT NOT NULL, timestamp INTEGER NOT NULL, recorded_at INTEGER NOT NULL);
|
||||
CREATE TABLE pi_info (id INTEGER PRIMARY KEY CHECK (id = 1), data TEXT NOT NULL, fetched_at INTEGER NOT NULL);
|
||||
INSERT INTO pi_info (id, data, fetched_at) VALUES (1, '{}', 0);
|
||||
").unwrap();
|
||||
|
||||
// Re-init should migrate
|
||||
let conn = init(":memory:").unwrap();
|
||||
let status = get_current_status(&conn).unwrap();
|
||||
assert_eq!(status, DoorStatus::Offline);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ use anyhow::{Context, Result};
|
|||
use axum::routing::{get, post};
|
||||
use axum::Router;
|
||||
use tokio::sync::Mutex;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use tower_http::trace::TraceLayer;
|
||||
use tracing::{info, Level};
|
||||
|
||||
|
|
@ -122,6 +123,8 @@ async fn main() -> Result<()> {
|
|||
webhooks,
|
||||
retry_attempts,
|
||||
retry_base_delay_secs,
|
||||
webhook_last_request: AtomicU64::new(0),
|
||||
webhook_tokens: std::sync::atomic::AtomicU32::new(10),
|
||||
});
|
||||
|
||||
let app = Router::new()
|
||||
|
|
|
|||
|
|
@ -37,6 +37,18 @@ pub fn spawn_status_poller(
|
|||
let mut was_offline = false;
|
||||
|
||||
loop {
|
||||
{
|
||||
let now = unix_now();
|
||||
let db = db.clone();
|
||||
let _ = tokio::task::spawn_blocking(move || {
|
||||
let conn = db.blocking_lock();
|
||||
if let Err(e) = db::update_last_checked(&conn, now) {
|
||||
error!(error = %e, "failed to update last_checked");
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
let result = client
|
||||
.get(format!("{}/", config.pi_address))
|
||||
.bearer_auth(&config.pi_api_key)
|
||||
|
|
@ -65,10 +77,9 @@ pub fn spawn_status_poller(
|
|||
|
||||
if let Some(ref status_str) = status_str {
|
||||
if let Some(status) = DoorStatus::from_str(status_str) {
|
||||
let current = db::get_current_status_str(&conn);
|
||||
let current = db::get_current_status(&conn);
|
||||
let changed = match ¤t {
|
||||
Ok(Some(s)) => s != status.as_str(),
|
||||
Ok(None) => true,
|
||||
Ok(current) => *current != status,
|
||||
Err(_) => true,
|
||||
};
|
||||
if changed {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
|
|||
pub enum DoorStatus {
|
||||
Open,
|
||||
Closed,
|
||||
Offline,
|
||||
}
|
||||
|
||||
impl DoorStatus {
|
||||
|
|
@ -12,6 +13,7 @@ impl DoorStatus {
|
|||
match self {
|
||||
DoorStatus::Open => "open",
|
||||
DoorStatus::Closed => "closed",
|
||||
DoorStatus::Offline => "offline",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -19,6 +21,7 @@ impl DoorStatus {
|
|||
match s {
|
||||
"open" => Some(DoorStatus::Open),
|
||||
"closed" => Some(DoorStatus::Closed),
|
||||
"offline" => Some(DoorStatus::Offline),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
|
@ -26,9 +29,9 @@ impl DoorStatus {
|
|||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct StatusResponse {
|
||||
pub status: String, // "open", "closed", or "offline"
|
||||
pub timestamp: Option<u64>,
|
||||
pub last_seen: Option<u64>,
|
||||
pub status: DoorStatus,
|
||||
pub since: Option<u64>, // when the current status was set
|
||||
pub last_checked: Option<u64>, // when the cache last attempted to poll
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
|
|
@ -36,3 +39,34 @@ pub struct WebhookTarget {
|
|||
pub url: String,
|
||||
pub secret: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn door_status_round_trip() {
|
||||
for status in [DoorStatus::Open, DoorStatus::Closed, DoorStatus::Offline] {
|
||||
let s = status.as_str();
|
||||
assert_eq!(DoorStatus::from_str(s), Some(status));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn door_status_from_str_rejects_unknown() {
|
||||
assert_eq!(DoorStatus::from_str("unknown"), None);
|
||||
assert_eq!(DoorStatus::from_str(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn door_status_serde_lowercase() {
|
||||
let json = serde_json::to_string(&DoorStatus::Open).unwrap();
|
||||
assert_eq!(json, "\"open\"");
|
||||
|
||||
let deserialized: DoorStatus = serde_json::from_str("\"closed\"").unwrap();
|
||||
assert_eq!(deserialized, DoorStatus::Closed);
|
||||
|
||||
let deserialized: DoorStatus = serde_json::from_str("\"offline\"").unwrap();
|
||||
assert_eq!(deserialized, DoorStatus::Offline);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ edition = "2021"
|
|||
anyhow = "1.0"
|
||||
axum = "0.8"
|
||||
noisebell-common = { path = "../noisebell-common" }
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
serenity = { version = "0.12", default-features = false, features = ["client", "gateway", "model", "rustls_backend"] }
|
||||
|
|
|
|||
|
|
@ -33,6 +33,17 @@ in
|
|||
type = lib.types.path;
|
||||
description = "Path to file containing the webhook secret.";
|
||||
};
|
||||
|
||||
imageBaseUrl = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "https://noisebell.extremist.software/image";
|
||||
description = "Base URL for status images used in Discord embeds.";
|
||||
};
|
||||
|
||||
cacheUrl = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
description = "URL of the cache service for slash commands (e.g. http://localhost:3000).";
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
|
|
@ -54,6 +65,8 @@ in
|
|||
environment = {
|
||||
NOISEBELL_DISCORD_PORT = toString cfg.port;
|
||||
NOISEBELL_DISCORD_CHANNEL_ID = cfg.channelId;
|
||||
NOISEBELL_DISCORD_IMAGE_BASE_URL = cfg.imageBaseUrl;
|
||||
NOISEBELL_DISCORD_CACHE_URL = cfg.cacheUrl;
|
||||
RUST_LOG = "info";
|
||||
};
|
||||
script = ''
|
||||
|
|
|
|||
|
|
@ -2,28 +2,37 @@ use std::sync::Arc;
|
|||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use axum::extract::State;
|
||||
use axum::extract::State as AxumState;
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Json, Router};
|
||||
use noisebell_common::{validate_bearer, WebhookPayload};
|
||||
use serenity::all::{ChannelId, Colour, CreateEmbed, CreateMessage, GatewayIntents};
|
||||
use serenity::all::{
|
||||
ChannelId, Colour, CommandInteraction, CreateCommand, CreateEmbed, CreateInteractionResponse,
|
||||
CreateInteractionResponseMessage, CreateMessage, GatewayIntents, Interaction,
|
||||
};
|
||||
use serenity::async_trait;
|
||||
use tower_http::trace::TraceLayer;
|
||||
use tracing::{error, info, Level};
|
||||
use tracing::{error, info, warn, Level};
|
||||
|
||||
struct AppState {
|
||||
http: Arc<serenity::all::Http>,
|
||||
channel_id: ChannelId,
|
||||
webhook_secret: String,
|
||||
image_base_url: String,
|
||||
cache_url: String,
|
||||
client: reqwest::Client,
|
||||
}
|
||||
|
||||
fn build_embed(status: &str, timestamp: u64) -> CreateEmbed {
|
||||
let (colour, title, description, image_url) = match status {
|
||||
"open" => (Colour::from_rgb(0, 255, 0), "Noisebridge is Open!", "It's time to start hacking.", "https://noisebell.extremist.software/image/open.png"),
|
||||
"closed" => (Colour::from_rgb(255, 0, 0), "Noisebridge is Closed!", "We'll see you again soon.", "https://noisebell.extremist.software/image/closed.png"),
|
||||
_ => (Colour::from_rgb(153, 170, 181), "Noisebridge is Offline", "The Noisebridge Pi is not responding.", "https://noisebell.extremist.software/image/offline.png"),
|
||||
fn build_embed(status: &str, timestamp: u64, image_base_url: &str) -> CreateEmbed {
|
||||
let (colour, title, description, image_file) = match status {
|
||||
"open" => (Colour::from_rgb(0, 255, 0), "Noisebridge is Open!", "It's time to start hacking.", "open.png"),
|
||||
"closed" => (Colour::from_rgb(255, 0, 0), "Noisebridge is Closed!", "We'll see you again soon.", "closed.png"),
|
||||
_ => (Colour::from_rgb(153, 170, 181), "Noisebridge is Offline", "The Noisebridge Pi is not responding.", "offline.png"),
|
||||
};
|
||||
|
||||
let image_url = format!("{image_base_url}/{image_file}");
|
||||
|
||||
CreateEmbed::new()
|
||||
.title(title)
|
||||
.description(description)
|
||||
|
|
@ -33,7 +42,7 @@ fn build_embed(status: &str, timestamp: u64) -> CreateEmbed {
|
|||
}
|
||||
|
||||
async fn post_webhook(
|
||||
State(state): State<Arc<AppState>>,
|
||||
AxumState(state): AxumState<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(body): Json<WebhookPayload>,
|
||||
) -> StatusCode {
|
||||
|
|
@ -43,7 +52,7 @@ async fn post_webhook(
|
|||
|
||||
info!(status = %body.status, timestamp = body.timestamp, "received webhook");
|
||||
|
||||
let embed = build_embed(&body.status, body.timestamp);
|
||||
let embed = build_embed(&body.status, body.timestamp, &state.image_base_url);
|
||||
let message = CreateMessage::new().embed(embed);
|
||||
|
||||
match state.channel_id.send_message(&state.http, message).await {
|
||||
|
|
@ -58,9 +67,227 @@ async fn post_webhook(
|
|||
}
|
||||
}
|
||||
|
||||
struct Handler;
|
||||
fn unix_now() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs()
|
||||
}
|
||||
|
||||
impl serenity::all::EventHandler for Handler {}
|
||||
fn format_timestamp(ts: u64) -> String {
|
||||
format!("<t:{}:R>", ts)
|
||||
}
|
||||
|
||||
async fn handle_status(state: &AppState, _command: &CommandInteraction) -> CreateInteractionResponse {
|
||||
let url = format!("{}/status", state.cache_url);
|
||||
let resp = state.client.get(&url).send().await;
|
||||
|
||||
let embed = match resp {
|
||||
Ok(resp) if resp.status().is_success() => {
|
||||
match resp.json::<serde_json::Value>().await {
|
||||
Ok(data) => {
|
||||
let status = data.get("status").and_then(|s| s.as_str()).unwrap_or("unknown");
|
||||
let since = data.get("since").and_then(|t| t.as_u64());
|
||||
let last_checked = data.get("last_checked").and_then(|t| t.as_u64());
|
||||
|
||||
let mut embed = build_embed(status, since.unwrap_or(unix_now()), &state.image_base_url);
|
||||
|
||||
let mut fields = Vec::new();
|
||||
if let Some(ts) = since {
|
||||
fields.push(("Since", format_timestamp(ts), true));
|
||||
}
|
||||
if let Some(ts) = last_checked {
|
||||
fields.push(("Last Checked", format_timestamp(ts), true));
|
||||
}
|
||||
if !fields.is_empty() {
|
||||
embed = embed.fields(fields);
|
||||
}
|
||||
embed
|
||||
}
|
||||
Err(e) => {
|
||||
error!(error = %e, "failed to parse status response");
|
||||
CreateEmbed::new()
|
||||
.title("Error")
|
||||
.description("Failed to parse status response.")
|
||||
.colour(Colour::from_rgb(255, 0, 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
CreateEmbed::new()
|
||||
.title("Error")
|
||||
.description("Failed to reach the cache service.")
|
||||
.colour(Colour::from_rgb(255, 0, 0))
|
||||
}
|
||||
};
|
||||
|
||||
CreateInteractionResponse::Message(
|
||||
CreateInteractionResponseMessage::new().embed(embed)
|
||||
)
|
||||
}
|
||||
|
||||
async fn handle_info(state: &AppState, _command: &CommandInteraction) -> CreateInteractionResponse {
|
||||
let url = format!("{}/info", state.cache_url);
|
||||
let resp = state.client.get(&url).send().await;
|
||||
|
||||
let embed = match resp {
|
||||
Ok(resp) if resp.status().is_success() => {
|
||||
match resp.json::<serde_json::Value>().await {
|
||||
Ok(data) => {
|
||||
let mut fields = Vec::new();
|
||||
|
||||
if let Some(temp) = data.get("cpu_temp_celsius").and_then(|t| t.as_f64()) {
|
||||
fields.push(("CPU Temp", format!("{:.1}°C", temp), true));
|
||||
}
|
||||
if let Some(load) = data.get("load_average").and_then(|l| l.as_array()) {
|
||||
let loads: Vec<String> = load.iter().filter_map(|v| v.as_f64()).map(|v| format!("{:.2}", v)).collect();
|
||||
fields.push(("Load Average", loads.join(", "), true));
|
||||
}
|
||||
if let Some(total) = data.get("memory_total_kb").and_then(|t| t.as_u64()) {
|
||||
if let Some(avail) = data.get("memory_available_kb").and_then(|a| a.as_u64()) {
|
||||
let used = total.saturating_sub(avail);
|
||||
fields.push(("Memory", format!("{} / {} MB", used / 1024, total / 1024), true));
|
||||
}
|
||||
}
|
||||
if let Some(total) = data.get("disk_total_bytes").and_then(|t| t.as_u64()) {
|
||||
if let Some(avail) = data.get("disk_available_bytes").and_then(|a| a.as_u64()) {
|
||||
let used = total.saturating_sub(avail);
|
||||
fields.push(("Disk", format!("{:.1} / {:.1} GB", used as f64 / 1e9, total as f64 / 1e9), true));
|
||||
}
|
||||
}
|
||||
if let Some(uptime) = data.get("uptime_secs").and_then(|u| u.as_u64()) {
|
||||
let hours = uptime / 3600;
|
||||
let mins = (uptime % 3600) / 60;
|
||||
fields.push(("Uptime", format!("{}h {}m", hours, mins), true));
|
||||
}
|
||||
if let Some(version) = data.get("nixos_version").and_then(|v| v.as_str()) {
|
||||
fields.push(("NixOS", version.to_string(), true));
|
||||
}
|
||||
if let Some(commit) = data.get("commit").and_then(|c| c.as_str()) {
|
||||
fields.push(("Commit", commit.to_string(), true));
|
||||
}
|
||||
|
||||
CreateEmbed::new()
|
||||
.title("Noisebridge Pi Info")
|
||||
.colour(Colour::BLUE)
|
||||
.fields(fields)
|
||||
}
|
||||
Err(e) => {
|
||||
error!(error = %e, "failed to parse info response");
|
||||
CreateEmbed::new()
|
||||
.title("Error")
|
||||
.description("Failed to parse Pi info.")
|
||||
.colour(Colour::from_rgb(255, 0, 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
CreateEmbed::new()
|
||||
.title("Error")
|
||||
.description("Failed to reach the cache service.")
|
||||
.colour(Colour::from_rgb(255, 0, 0))
|
||||
}
|
||||
};
|
||||
|
||||
CreateInteractionResponse::Message(
|
||||
CreateInteractionResponseMessage::new().embed(embed)
|
||||
)
|
||||
}
|
||||
|
||||
async fn handle_history(state: &AppState, _command: &CommandInteraction) -> CreateInteractionResponse {
|
||||
let url = format!("{}/history", state.cache_url);
|
||||
let resp = state.client.get(&url).send().await;
|
||||
|
||||
let embed = match resp {
|
||||
Ok(resp) if resp.status().is_success() => {
|
||||
match resp.json::<Vec<serde_json::Value>>().await {
|
||||
Ok(entries) => {
|
||||
let lines: Vec<String> = entries.iter().take(10).map(|entry| {
|
||||
let status = entry.get("status").and_then(|s| s.as_str()).unwrap_or("unknown");
|
||||
let ts = entry.get("timestamp").and_then(|t| t.as_u64()).unwrap_or(0);
|
||||
let emoji = match status {
|
||||
"open" => "🟢",
|
||||
"closed" => "🔴",
|
||||
"offline" => "⚪",
|
||||
_ => "❓",
|
||||
};
|
||||
format!("{} **{}** — {}", emoji, status, format_timestamp(ts))
|
||||
}).collect();
|
||||
|
||||
let description = if lines.is_empty() {
|
||||
"No history available.".to_string()
|
||||
} else {
|
||||
lines.join("\n")
|
||||
};
|
||||
|
||||
CreateEmbed::new()
|
||||
.title("Recent Door History")
|
||||
.description(description)
|
||||
.colour(Colour::BLUE)
|
||||
}
|
||||
Err(e) => {
|
||||
error!(error = %e, "failed to parse history response");
|
||||
CreateEmbed::new()
|
||||
.title("Error")
|
||||
.description("Failed to parse history.")
|
||||
.colour(Colour::from_rgb(255, 0, 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
CreateEmbed::new()
|
||||
.title("Error")
|
||||
.description("Failed to reach the cache service.")
|
||||
.colour(Colour::from_rgb(255, 0, 0))
|
||||
}
|
||||
};
|
||||
|
||||
CreateInteractionResponse::Message(
|
||||
CreateInteractionResponseMessage::new().embed(embed)
|
||||
)
|
||||
}
|
||||
|
||||
struct Handler {
|
||||
state: Arc<AppState>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl serenity::all::EventHandler for Handler {
|
||||
async fn ready(&self, ctx: serenity::all::Context, ready: serenity::model::gateway::Ready) {
|
||||
info!(user = %ready.user.name, "Discord bot connected");
|
||||
|
||||
let commands = vec![
|
||||
CreateCommand::new("status").description("Show the current door status"),
|
||||
CreateCommand::new("info").description("Show Pi system information"),
|
||||
CreateCommand::new("history").description("Show recent door history"),
|
||||
];
|
||||
|
||||
if let Err(e) = serenity::all::Command::set_global_commands(&ctx.http, commands).await {
|
||||
error!(error = %e, "failed to register slash commands");
|
||||
} else {
|
||||
info!("slash commands registered");
|
||||
}
|
||||
}
|
||||
|
||||
async fn interaction_create(&self, ctx: serenity::all::Context, interaction: Interaction) {
|
||||
if let Interaction::Command(command) = interaction {
|
||||
let response = match command.data.name.as_str() {
|
||||
"status" => handle_status(&self.state, &command).await,
|
||||
"info" => handle_info(&self.state, &command).await,
|
||||
"history" => handle_history(&self.state, &command).await,
|
||||
_ => {
|
||||
CreateInteractionResponse::Message(
|
||||
CreateInteractionResponseMessage::new().content("Unknown command.")
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = command.create_response(&ctx.http, response).await {
|
||||
error!(error = %e, command = %command.data.name, "failed to respond to slash command");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
|
|
@ -84,20 +311,47 @@ async fn main() -> Result<()> {
|
|||
.parse()
|
||||
.context("NOISEBELL_DISCORD_PORT must be a valid u16")?;
|
||||
|
||||
let image_base_url = std::env::var("NOISEBELL_DISCORD_IMAGE_BASE_URL")
|
||||
.unwrap_or_else(|_| "https://noisebell.extremist.software/image".into())
|
||||
.trim_end_matches('/')
|
||||
.to_string();
|
||||
|
||||
let cache_url = std::env::var("NOISEBELL_DISCORD_CACHE_URL")
|
||||
.context("NOISEBELL_DISCORD_CACHE_URL is required")?
|
||||
.trim_end_matches('/')
|
||||
.to_string();
|
||||
|
||||
info!(port, channel_id, "starting noisebell-discord");
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(10))
|
||||
.build()
|
||||
.context("failed to build HTTP client")?;
|
||||
|
||||
let intents = GatewayIntents::empty();
|
||||
let mut initial_client = serenity::Client::builder(&discord_token, intents)
|
||||
.event_handler(Handler)
|
||||
let mut discord_client = serenity::Client::builder(&discord_token, intents)
|
||||
.event_handler_arc(Arc::new(Handler {
|
||||
state: Arc::new(AppState {
|
||||
http: Arc::new(serenity::all::Http::new(&discord_token)),
|
||||
channel_id: ChannelId::new(channel_id),
|
||||
webhook_secret: webhook_secret.clone(),
|
||||
image_base_url: image_base_url.clone(),
|
||||
cache_url: cache_url.clone(),
|
||||
client: client.clone(),
|
||||
}),
|
||||
}))
|
||||
.await
|
||||
.context("failed to create Discord client")?;
|
||||
|
||||
let http = initial_client.http.clone();
|
||||
let http = discord_client.http.clone();
|
||||
|
||||
let app_state = Arc::new(AppState {
|
||||
http,
|
||||
channel_id: ChannelId::new(channel_id),
|
||||
webhook_secret,
|
||||
image_base_url,
|
||||
cache_url,
|
||||
client,
|
||||
});
|
||||
|
||||
let app = Router::new()
|
||||
|
|
@ -116,28 +370,14 @@ async fn main() -> Result<()> {
|
|||
|
||||
info!(port, "webhook listener ready");
|
||||
|
||||
// Gateway reconnect loop — the Http client for sending messages is independent
|
||||
let token_for_gateway = discord_token.clone();
|
||||
// Spawn gateway connection for slash commands
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = initial_client.start().await {
|
||||
error!(error = %e, "Discord gateway disconnected");
|
||||
}
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
info!("reconnecting to Discord gateway");
|
||||
match serenity::Client::builder(&token_for_gateway, GatewayIntents::empty())
|
||||
.event_handler(Handler)
|
||||
.await
|
||||
{
|
||||
Ok(mut client) => {
|
||||
if let Err(e) = client.start().await {
|
||||
error!(error = %e, "Discord gateway disconnected");
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!(error = %e, "failed to create Discord client");
|
||||
}
|
||||
if let Err(e) = discord_client.start().await {
|
||||
error!(error = %e, "Discord gateway disconnected");
|
||||
}
|
||||
warn!("reconnecting to Discord gateway in 5s");
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
64
remote/flake.lock
generated
64
remote/flake.lock
generated
|
|
@ -1,64 +0,0 @@
|
|||
{
|
||||
"nodes": {
|
||||
"crane": {
|
||||
"locked": {
|
||||
"lastModified": 1773115265,
|
||||
"narHash": "sha256-5fDkKTYEgue2klksd52WvcXfZdY1EIlbk0QggAwpFog=",
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"rev": "27711550d109bf6236478dc9f53b9e29c1a374c5",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1772963539,
|
||||
"narHash": "sha256-9jVDGZnvCckTGdYT53d/EfznygLskyLQXYwJLKMPsZs=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "9dcb002ca1690658be4a04645215baea8b95f31d",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"crane": "crane",
|
||||
"nixpkgs": "nixpkgs",
|
||||
"rust-overlay": "rust-overlay"
|
||||
}
|
||||
},
|
||||
"rust-overlay": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1773115373,
|
||||
"narHash": "sha256-bfK9FJFcQth6f3ydYggS5m0z2NRGF/PY6Y2XgZDJ6pg=",
|
||||
"owner": "oxalica",
|
||||
"repo": "rust-overlay",
|
||||
"rev": "1924b4672a2b8e4aee6e6652ec2e59a8d3c5648e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "oxalica",
|
||||
"repo": "rust-overlay",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
{
|
||||
description = "Noisebell remote services";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
crane.url = "github:ipetkov/crane";
|
||||
rust-overlay = {
|
||||
url = "github:oxalica/rust-overlay";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs, crane, rust-overlay }:
|
||||
let
|
||||
system = "x86_64-linux";
|
||||
pkgs = import nixpkgs {
|
||||
inherit system;
|
||||
overlays = [ rust-overlay.overlays.default ];
|
||||
};
|
||||
|
||||
rustToolchain = pkgs.rust-bin.stable.latest.default;
|
||||
craneLib = (crane.mkLib pkgs).overrideToolchain rustToolchain;
|
||||
|
||||
src = craneLib.cleanCargoSource ./.;
|
||||
|
||||
commonArgs = {
|
||||
inherit src;
|
||||
pname = "noisebell";
|
||||
version = "0.1.0";
|
||||
strictDeps = true;
|
||||
doCheck = false;
|
||||
};
|
||||
|
||||
cargoArtifacts = craneLib.buildDepsOnly commonArgs;
|
||||
|
||||
buildMember = name: craneLib.buildPackage (commonArgs // {
|
||||
inherit cargoArtifacts;
|
||||
cargoExtraArgs = "-p ${name}";
|
||||
});
|
||||
|
||||
noisebell-cache = buildMember "noisebell-cache";
|
||||
noisebell-discord = buildMember "noisebell-discord";
|
||||
noisebell-rss = buildMember "noisebell-rss";
|
||||
in
|
||||
{
|
||||
packages.${system} = {
|
||||
inherit noisebell-cache noisebell-discord noisebell-rss;
|
||||
default = noisebell-cache;
|
||||
};
|
||||
|
||||
nixosModules = {
|
||||
cache = import ./cache-service/module.nix noisebell-cache;
|
||||
discord = import ./discord-bot/module.nix noisebell-discord;
|
||||
rss = import ./rss-service/module.nix noisebell-rss;
|
||||
default = { imports = [
|
||||
(import ./cache-service/module.nix noisebell-cache)
|
||||
(import ./discord-bot/module.nix noisebell-discord)
|
||||
(import ./rss-service/module.nix noisebell-rss)
|
||||
]; };
|
||||
};
|
||||
|
||||
devShells.${system}.default = craneLib.devShell {
|
||||
packages = [ pkgs.rust-analyzer ];
|
||||
};
|
||||
};
|
||||
}
|
||||
|
|
@ -6,3 +6,6 @@ edition = "2021"
|
|||
[dependencies]
|
||||
axum = "0.8"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1.0"
|
||||
|
|
|
|||
|
|
@ -22,3 +22,44 @@ pub struct HistoryEntry {
|
|||
pub timestamp: u64,
|
||||
pub recorded_at: u64,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn validate_bearer_accepts_correct_token() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("authorization", "Bearer secret123".parse().unwrap());
|
||||
assert!(validate_bearer(&headers, "secret123"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_bearer_rejects_wrong_token() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("authorization", "Bearer wrong".parse().unwrap());
|
||||
assert!(!validate_bearer(&headers, "secret123"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_bearer_rejects_missing_header() {
|
||||
let headers = HeaderMap::new();
|
||||
assert!(!validate_bearer(&headers, "secret123"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_bearer_rejects_non_bearer_scheme() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("authorization", "Basic secret123".parse().unwrap());
|
||||
assert!(!validate_bearer(&headers, "secret123"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webhook_payload_round_trips() {
|
||||
let payload = WebhookPayload { status: "open".into(), timestamp: 1234567890 };
|
||||
let json = serde_json::to_string(&payload).unwrap();
|
||||
let deserialized: WebhookPayload = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(deserialized.status, "open");
|
||||
assert_eq!(deserialized.timestamp, 1234567890);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue