use std::collections::HashMap;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use super::notify::Level;
use crate::inbox::ShownPopup;
pub fn desktop_argv(os: &str, instance: &str, popup: &ShownPopup) -> Option<Vec<String>> {
match os {
"linux" => {
let urgency = match popup.level {
Level::Info | Level::Warn => "normal",
Level::Error => "critical",
};
Some(vec![
"notify-send".into(),
"--app-name=devsandbox".into(),
"-u".into(),
urgency.into(),
"--".into(),
format!("devsandbox: {instance}"),
popup.body.clone(),
])
}
"macos" => {
let script = format!(
"display notification {} with title \"devsandbox\" subtitle {}",
applescript_string(&popup.body),
applescript_string(instance)
);
Some(vec!["osascript".into(), "-e".into(), script])
}
_ => None,
}
}
fn applescript_string(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
if matches!(c, '\\' | '"') {
out.push('\\');
}
out.push(c);
}
out.push('"');
out
}
pub fn notify_desktop(instance: &str, popup: &ShownPopup) {
let Some(argv) = desktop_argv(std::env::consts::OS, instance, popup) else { return };
let spawned = Command::new(&argv[0])
.args(&argv[1..])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn();
if let Ok(mut child) = spawned {
std::thread::spawn(move || {
let _ = child.wait();
});
}
}
const RATE_BURST: u32 = 3;
const RATE_REFILL: Duration = Duration::from_secs(10);
const COALESCE_WINDOW: Duration = Duration::from_secs(60);
pub struct RateLimit {
burst: u32,
refill: Duration,
buckets: HashMap<String, (u32, Instant)>,
shown: HashMap<(String, String), Instant>,
}
impl Default for RateLimit {
fn default() -> Self {
RateLimit::new(RATE_BURST, RATE_REFILL)
}
}
impl RateLimit {
pub fn new(burst: u32, refill: Duration) -> Self {
RateLimit { burst, refill, buckets: HashMap::new(), shown: HashMap::new() }
}
pub fn allow(&mut self, instance: &str, key: Option<&str>, now: Instant) -> bool {
self.shown.retain(|_, at| now.saturating_duration_since(*at) < COALESCE_WINDOW);
let key = key.map(|k| (instance.to_string(), k.to_string()));
if key.as_ref().is_some_and(|k| self.shown.contains_key(k)) {
return false;
}
let (burst, refill) = (self.burst, self.refill);
let (tokens, since) = self.buckets.entry(instance.to_string()).or_insert((burst, now));
let earned = (now.saturating_duration_since(*since).as_nanos() / refill.as_nanos()) as u32;
if earned > 0 {
*tokens = (*tokens).saturating_add(earned).min(burst);
*since += refill * earned;
}
if *tokens == 0 {
return false;
}
*tokens -= 1;
if let Some(k) = key {
self.shown.insert(k, now);
}
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rate_limit_bursts_then_refills_per_instance() {
let mut rl = RateLimit::default();
let t0 = Instant::now();
for _ in 0..RATE_BURST {
assert!(rl.allow("a", None, t0));
}
assert!(!rl.allow("a", None, t0), "burst spent");
assert!(rl.allow("b", None, t0));
assert!(!rl.allow("a", None, t0 + RATE_REFILL - Duration::from_millis(1)));
assert!(rl.allow("a", None, t0 + RATE_REFILL), "one token refilled");
assert!(!rl.allow("a", None, t0 + RATE_REFILL));
let later = t0 + RATE_REFILL * 100;
for _ in 0..RATE_BURST {
assert!(rl.allow("a", None, later));
}
assert!(!rl.allow("a", None, later));
}
#[test]
fn rate_limit_coalesces_repeated_keys() {
let mut rl = RateLimit::default();
let t0 = Instant::now();
let s1 = t0 + Duration::from_secs(1);
assert!(rl.allow("a", Some("pr-1"), t0));
assert!(!rl.allow("a", Some("pr-1"), s1), "repeat coalesced");
assert!(rl.allow("a", Some("thread:pr-1"), s1));
assert!(rl.allow("b", Some("pr-1"), s1));
assert!(rl.allow("a", None, s1));
assert!(rl.allow("a", Some("pr-1"), t0 + COALESCE_WINDOW + Duration::from_secs(1)));
}
fn popup(level: Level, body: &str) -> ShownPopup {
ShownPopup { key: None, level, body: body.into() }
}
fn strs(v: &[&str]) -> Vec<String> {
v.iter().map(|s| s.to_string()).collect()
}
#[test]
fn linux_uses_notify_send_with_urgency() {
let argv = desktop_argv("linux", "web-pr-1", &popup(Level::Info, "PR 1 needs you")).unwrap();
assert_eq!(
argv,
strs(&["notify-send", "--app-name=devsandbox", "-u", "normal", "--", "devsandbox: web-pr-1", "PR 1 needs you"])
);
let warn = desktop_argv("linux", "web-pr-1", &popup(Level::Warn, "m")).unwrap();
assert_eq!(warn[3], "normal");
let error = desktop_argv("linux", "web-pr-1", &popup(Level::Error, "-m\nhttps://x/1")).unwrap();
assert_eq!(error[3], "critical");
assert_eq!(error.last().unwrap(), "-m\nhttps://x/1");
}
#[test]
fn macos_uses_osascript_with_escaped_strings() {
let body = "say \"hi\" \\ bye\nhttps://x/1";
let argv = desktop_argv("macos", "web-pr-1", &popup(Level::Warn, body)).unwrap();
assert_eq!(
argv,
strs(&[
"osascript",
"-e",
"display notification \"say \\\"hi\\\" \\\\ bye\nhttps://x/1\" with title \"devsandbox\" subtitle \"web-pr-1\"",
])
);
assert_eq!(applescript_string(""), "\"\"");
assert_eq!(applescript_string(r#"a"\"#), r#""a\"\\""#);
}
#[test]
fn other_os_has_no_notifier() {
assert_eq!(desktop_argv("windows", "a", &popup(Level::Info, "m")), None);
assert_eq!(desktop_argv("freebsd", "a", &popup(Level::Info, "m")), None);
}
}