diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9cb07c60cb0da063f747cfbf1b3b876ecb8ba03e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,34 @@ +# time 0.3.47+ requires Rust 1.88 (edition 2024) +FROM rust:1.88-slim as builder + +WORKDIR /build + +RUN apt-get update && \ + apt-get install -y pkg-config libssl-dev && \ + rm -rf /var/lib/apt/lists/* + +# Copy source and build. (Keep it simple to avoid remote build cache oddities.) +COPY . . +RUN cargo build --release --package slugsocial-server + +FROM debian:bookworm-slim + +RUN apt-get update && \ + apt-get install -y ca-certificates && \ + rm -rf /var/lib/apt/lists/* + +WORKDIR /app + +COPY --from=builder /build/target/release/slugsocial-server /app/slugsocial-server + +# Create data directory for persistent volume +RUN mkdir -p /data + +ENV SLUG_DATA_DIR=/data +ENV SLUG_EVENT_LOG=/data/events.jsonl +ENV PORT=8080 + +EXPOSE 8080 + +CMD ["/app/slugsocial-server"] + diff --git a/deps.edn b/deps.edn new file mode 100644 index 0000000000000000000000000000000000000000..0bf892d44f491cb2313e01ae8a942c3097c52948 --- /dev/null +++ b/deps.edn @@ -0,0 +1,10 @@ +{:paths ["." "test"] + :deps {cheshire/cheshire {:mvn/version "5.13.0"} + http-kit/http-kit {:mvn/version "2.8.0"} + babashka/fs {:mvn/version "0.5.32"} + babashka/process {:mvn/version "0.6.25"} + com.blockether/spel {:mvn/version "0.7.11"}} + :aliases + {:kaocha {:extra-deps {lambdaisland/kaocha {:mvn/version "1.91.1392"} + lambdaisland/kaocha-junit-xml {:mvn/version "1.17.101"}} + :main-opts ["-m" "kaocha.runner"]}}} diff --git a/event_log.rs b/event_log.rs new file mode 100644 index 0000000000000000000000000000000000000000..eaae0d495e43a45d6590603892265a62cc92906e --- /dev/null +++ b/event_log.rs @@ -0,0 +1,83 @@ +use std::path::{Path, PathBuf}; + +use tokio::{ + fs::{self, OpenOptions}, + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, +}; + +use crate::events::Event; + +#[derive(Debug, thiserror::Error)] +pub enum EventLogError { + #[error("io error: {0}")] + Io(#[from] std::io::Error), + #[error("json error: {0}")] + Json(#[from] serde_json::Error), +} + +#[derive(Debug, Clone)] +pub struct EventLog { + path: PathBuf, +} + +impl EventLog { + pub fn new(path: impl Into) -> Self { + Self { path: path.into() } + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub async fn ensure_parent_dir(&self) -> Result<(), EventLogError> { + if let Some(parent) = self.path.parent() { + fs::create_dir_all(parent).await?; + } + Ok(()) + } + + pub async fn append(&self, event: &Event) -> Result<(), EventLogError> { + self.ensure_parent_dir().await?; + let mut f: tokio::fs::File = OpenOptions::new() + .create(true) + .append(true) + .open(&self.path) + .await?; + + let mut line = serde_json::to_string(event)?; + line.push('\n'); + f.write_all(line.as_bytes()).await?; + f.flush().await?; + Ok(()) + } + + /// Load events from JSONL. Corrupt lines are skipped and returned as `(line_no, line)`. + pub async fn load_all(&self) -> Result<(Vec, Vec<(usize, String)>), EventLogError> { + if !fs::try_exists(&self.path).await? { + return Ok((vec![], vec![])); + } + + let f = fs::File::open(&self.path).await?; + let mut reader = BufReader::new(f).lines(); + + let mut events = Vec::new(); + let mut bad_lines = Vec::new(); + + let mut line_no: usize = 0; + while let Some(line) = reader.next_line().await? { + line_no += 1; + let trimmed = line.trim(); + if trimmed.is_empty() { + continue; + } + match serde_json::from_str::(trimmed) { + Ok(ev) => events.push(ev), + Err(_) => bad_lines.push((line_no, line)), + } + } + + Ok((events, bad_lines)) + } +} + + diff --git a/fly.toml b/fly.toml new file mode 100644 index 0000000000000000000000000000000000000000..bbb9345e527452db1d87a549213645c195eae5fc --- /dev/null +++ b/fly.toml @@ -0,0 +1,42 @@ +app = "slugsocial" +primary_region = "iad" + +[build] + dockerfile = "Dockerfile" + +[env] + SLUG_DATA_DIR = "/data" + SLUG_EVENT_LOG = "/data/events.jsonl" + PORT = "8080" + +[[services]] + internal_port = 8080 + protocol = "tcp" + + [[services.ports]] + port = 80 + handlers = ["http"] + force_https = true + + [[services.ports]] + port = 443 + handlers = ["tls", "http"] + + [services.concurrency] + type = "connections" + hard_limit = 1000 + soft_limit = 500 + + [[services.http_checks]] + interval = "10s" + timeout = "2s" + grace_period = "5s" + method = "GET" + path = "/healthz" + protocol = "http" + tls_skip_verify = false + +[[mounts]] + source = "slugsocial_data" + destination = "/data" + diff --git a/views.rs b/views.rs new file mode 100644 index 0000000000000000000000000000000000000000..d4f0ffc49475f014698b4da0de6f476884430813 --- /dev/null +++ b/views.rs @@ -0,0 +1,63 @@ +use std::{ + collections::HashMap, + sync::{Arc, Mutex}, +}; +use tokio::sync::mpsc; + +type CountMap = Arc>>; + +#[derive(Clone)] +pub struct ViewStore { + counts: CountMap, + flush_tx: mpsc::Sender<()>, +} + +impl ViewStore { + pub fn new(json_path: &str) -> Self { + // Load existing counts from disk on startup (best-effort) + let initial: HashMap = std::fs::read_to_string(json_path) + .ok() + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default(); + + let counts: CountMap = Arc::new(Mutex::new(initial)); + let (flush_tx, mut flush_rx) = mpsc::channel::<()>(64); + let path = json_path.to_string(); + + let counts_for_writer = counts.clone(); + tokio::spawn(async move { + while flush_rx.recv().await.is_some() { + while flush_rx.try_recv().is_ok() {} + + let snapshot: HashMap = { + counts_for_writer.lock().unwrap().clone() + }; + + let path = path.clone(); + let _ = tokio::task::spawn_blocking(move || { + if let Ok(json) = serde_json::to_string(&snapshot) { + let tmp = format!("{path}.tmp"); + if std::fs::write(&tmp, &json).is_ok() { + let _ = std::fs::rename(&tmp, &path); + } + } + }) + .await; + } + }); + + Self { counts, flush_tx } + } + + pub fn increment(&self, path: String) { + { + let mut map = self.counts.lock().unwrap(); + *map.entry(path).or_insert(0) += 1; + } + let _ = self.flush_tx.try_send(()); + } + + pub fn get_views(&self, path: &str) -> u64 { + self.counts.lock().unwrap().get(path).copied().unwrap_or(0) + } +}