From 7175543e00caa9ce35487fa7f8b1b479c1ba00a2 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 02:54:21 +0100 Subject: M0: streaming provider, SSE decoder, mock provider, i686 build gate --- src/session.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/session.rs (limited to 'src/session.rs') diff --git a/src/session.rs b/src/session.rs new file mode 100644 index 0000000..aef4835 --- /dev/null +++ b/src/session.rs @@ -0,0 +1,39 @@ +use std::hash::{Hash, Hasher}; +use std::io::Read; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// A session id is opaque to the provider: it only has to be stable for the life +/// of one conversation. 16 random-ish bytes as lowercase hex is plenty and keeps +/// it usable as a file name. +pub fn new_id() -> String { + let mut bytes = random_bytes(); + // Put the creation time in the first bytes so ids sort roughly by age. + let ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0); + bytes[..8].copy_from_slice(&ms.to_be_bytes()); + + let mut out = String::with_capacity(32); + for b in bytes { + out.push_str(&format!("{b:02x}")); + } + out +} + +fn random_bytes() -> [u8; 16] { + let mut bytes = [0u8; 16]; + if let Ok(mut f) = std::fs::File::open("/dev/urandom") { + if f.read_exact(&mut bytes).is_ok() { + return bytes; + } + } + // Fallback: not cryptographic, but an id only has to not collide. + let mut h = std::collections::hash_map::DefaultHasher::new(); + SystemTime::now().hash(&mut h); + std::process::id().hash(&mut h); + let v = h.finish(); + bytes[..8].copy_from_slice(&v.to_be_bytes()); + bytes[8..].copy_from_slice(&(v ^ 0x9e37_79b9_7f4a_7c15).to_be_bytes()); + bytes +} -- cgit v1.2.3