Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1256,6 +1256,8 @@ pub fn run() {
upstreams::test_proxy,
notices_list,
dismiss_notice,
notice_prefs,
set_notice_pref,
chatgpt::start_chatgpt_login,
chatgpt::reopen_chatgpt_login,
chatgpt::chatgpt_login_status,
Expand Down Expand Up @@ -1326,7 +1328,7 @@ pub fn run() {
Box::new(notices::sink::AppSink::new(handle.clone())),
Box::new(notices::SystemSink::new(handle.clone())),
],
Some(data_dir().join("notices.json")),
Some(data_dir()),
);
app.manage(notices.clone());
app.manage(AppState {
Expand Down Expand Up @@ -1632,6 +1634,43 @@ fn dismiss_notice(notices: tauri::State<'_, Arc<notices::Notices>>, key: String)
notices.dismiss(&key);
}

/// 设置页上的一行:一类提醒,和它现在怎么对待
#[derive(serde::Serialize)]
struct NoticePref {
category: notices::Category,
label: &'static str,
mode: notices::Mode,
}

fn notice_prefs_view(n: &notices::Notices) -> Vec<NoticePref> {
n.modes()
.into_iter()
.map(|(category, mode)| NoticePref {
category,
label: category.label(),
mode,
})
.collect()
}

#[tauri::command]
fn notice_prefs(notices: tauri::State<'_, Arc<notices::Notices>>) -> Vec<NoticePref> {
notice_prefs_view(&notices)
}

/// 改一类提醒的对待方式。**返回改完之后的全部**,界面以它为准
#[tauri::command]
fn set_notice_pref(
notices: tauri::State<'_, Arc<notices::Notices>>,
category: notices::Category,
mode: notices::Mode,
) -> Result<Vec<NoticePref>, String> {
notices
.set_mode(category, mode)
.map_err(|e| format!("无法保存设置:{e}"))?;
Ok(notice_prefs_view(&notices))
}

/// 第一次开机自启之后提示一次「我在菜单栏这儿」,之后永不再弹。
///
/// **每次开机都弹是噪音**,而噪音的代价是用户学会忽略通知 —— 包括那些
Expand Down
85 changes: 76 additions & 9 deletions src-tauri/src/notices/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@ use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

pub mod prefs;
pub mod rules;
pub mod sink;
mod store;

pub use prefs::{Category, Mode};
pub use sink::{Sink, SystemSink};

/// 去抖:故障类要持续这么久才说。用户已经在等结果的那几件事不等(见 [`Signal::hold`])
Expand Down Expand Up @@ -142,6 +144,8 @@ impl Signal {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Notice {
pub key: String,
/// 属于哪一类。「不再通知此类」按它来
pub category: Category,
pub level: Level,
pub title: String,
pub body: String,
Expand Down Expand Up @@ -184,14 +188,26 @@ struct State {
pub struct Notices {
state: Mutex<State>,
sinks: Vec<Box<dyn Sink>>,
/// 落盘的位置。关窗期间发生的事要留得住
file: Option<std::path::PathBuf>,
/// 每一类怎么对待
prefs: Mutex<prefs::Prefs>,
/// 落盘的目录。关窗期间发生的事要留得住,设置也在这里
dir: Option<std::path::PathBuf>,
}

const OPEN_FILE: &str = "notices.json";
const PREFS_FILE: &str = "notice-prefs.json";

impl Notices {
/// `file` 是留存的位置;`None` 表示只在内存里(测试用)
pub fn new(sinks: Vec<Box<dyn Sink>>, file: Option<std::path::PathBuf>) -> Arc<Self> {
let open = file.as_deref().map(store::load).unwrap_or_default();
/// `dir` 是留存的目录;`None` 表示只在内存里(测试用)
pub fn new(sinks: Vec<Box<dyn Sink>>, dir: Option<std::path::PathBuf>) -> Arc<Self> {
let open = dir
.as_deref()
.map(|d| store::load(&d.join(OPEN_FILE)))
.unwrap_or_default();
let prefs = dir
.as_deref()
.map(|d| prefs::load(&d.join(PREFS_FILE)))
.unwrap_or_default();
Arc::new(Self {
state: Mutex::new(State {
open: open
Expand All @@ -211,10 +227,53 @@ impl Notices {
..Default::default()
}),
sinks,
file,
prefs: Mutex::new(prefs),
dir,
})
}

/// 每一类现在怎么对待,按设置页的顺序
pub fn modes(&self) -> Vec<(Category, Mode)> {
let p = self.prefs.lock().expect("锁未中毒");
Category::ALL.iter().map(|c| (*c, p.mode(*c))).collect()
}

/// 改一类的对待方式。**改成「关闭」时,这一类挂着的也一并撤掉** —— 用户说的是
/// 「这类事别再出现」,留着一条旧的等于没听见
pub fn set_mode(&self, category: Category, mode: Mode) -> std::io::Result<()> {
let saved = {
let mut p = self.prefs.lock().expect("锁未中毒");
p.set(category, mode);
p.clone()
};
if let Some(dir) = &self.dir {
prefs::save(&dir.join(PREFS_FILE), &saved)?;
}
if mode == Mode::Off {
let gone: Vec<String> = {
let mut g = self.state.lock().expect("锁未中毒");
let keys: Vec<String> = g
.open
.values()
.filter(|o| o.notice.category == category)
.map(|o| o.notice.key.clone())
.collect();
for k in &keys {
g.open.remove(k);
}
keys
};
for k in &gone {
for s in &self.sinks {
s.withdraw(k);
}
}
self.persist();
self.changed();
}
Ok(())
}

/// 界面要显示的那一份,最近的在前
pub fn list(&self) -> Vec<Notice> {
let g = self.state.lock().expect("锁未中毒");
Expand Down Expand Up @@ -263,6 +322,11 @@ impl Notices {
}

fn raise(self: &Arc<Self>, signal: Signal, at_ms: u64) {
let category = Category::of(&signal.key);
let mode = self.prefs.lock().expect("锁未中毒").mode(category);
if mode == Mode::Off {
return;
}
let now = Instant::now();
let (notice, deliver, due) = {
let mut g = self.state.lock().expect("锁未中毒");
Expand All @@ -285,6 +349,7 @@ impl Notices {
},
None => Notice {
key: signal.key.clone(),
category,
level: signal.level,
title: signal.title.clone(),
body: signal.body.clone(),
Expand All @@ -297,7 +362,8 @@ impl Notices {
};
// 抖动中、被抑制、或者已经弹过:只留记号
let quiet = muted.is_some_and(|until| now < until) || suppressed || notice.notified;
let wants = signal.level.interrupts() && !quiet;
// 用户说了「只进应用内」的,级别再高也不打断
let wants = mode == Mode::System && signal.level.interrupts() && !quiet;
let due = (wants && signal.hold).then(|| now + HOLD);
let deliver = wants && !signal.hold && take_token(&mut g, signal.level);
g.open.insert(
Expand Down Expand Up @@ -416,6 +482,7 @@ impl Notices {
for s in &self.sinks {
s.show(&Notice {
key: format!("{key}:recovered"),
category: was.notice.category,
level: Level::Info,
title: format!("{}已恢复", was.notice.title),
body: String::new(),
Expand All @@ -432,9 +499,9 @@ impl Notices {
}

fn persist(&self) {
let Some(file) = &self.file else { return };
let Some(dir) = &self.dir else { return };
let list = self.list();
store::save(file, &list);
store::save(&dir.join(OPEN_FILE), &list);
}

/// 界面在开着的话,让它重画
Expand Down
134 changes: 134 additions & 0 deletions src-tauri/src/notices/prefs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
//! 每一类提醒怎么对待:弹系统通知、只进应用内、还是不要。
//!
//! **按类,不按条。**「不再提醒这一条」对一个明天还会再发生的事没有意义;用户
//! 真正要表达的是「这一类事别打断我」。

use std::collections::BTreeMap;
use std::path::Path;

/// 提醒的类别。**和去重键的前缀一一对应**(见 [`Category::of`])
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
pub enum Category {
/// 网关停止转发
Gateway,
/// 上游无法连接
Upstream,
/// 订阅额度用完
Quota,
/// 凭据失效、被拒绝、写不回配置
Credential,
/// 代理不通
Proxy,
/// 可疑的工具调用、客户端配置里出现的可疑内容
Security,
/// 配置文件没过校验
Config,
/// 磁盘空间不足
Storage,
}

impl Category {
/// 设置页上的顺序:先是「什么都用不了了」,再是「某一处要处理」
pub const ALL: [Category; 8] = [
Category::Gateway,
Category::Upstream,
Category::Quota,
Category::Credential,
Category::Proxy,
Category::Security,
Category::Config,
Category::Storage,
];

/// 去重键属于哪一类
pub fn of(key: &str) -> Category {
let kind = key.split(':').next().unwrap_or(key);
match kind {
"gateway" => Category::Gateway,
"upstream" => Category::Upstream,
"quota" => Category::Quota,
"credential" | "auth" | "writeback" => Category::Credential,
"proxy" => Category::Proxy,
"toolwall" | "scan" => Category::Security,
"storage" => Category::Storage,
// 认不出来的归到配置:那是唯一一个不挂在某个对象上的类
_ => Category::Config,
}
}

pub fn label(self) -> &'static str {
match self {
Category::Gateway => "网关停止转发",
Category::Upstream => "上游无法连接",
Category::Quota => "订阅额度用完",
Category::Credential => "凭据失效或被拒绝",
Category::Proxy => "代理不通",
Category::Security => "可疑的工具调用与客户端配置",
Category::Config => "配置文件未通过校验",
Category::Storage => "磁盘空间不足",
}
}

/// 出厂设置。
///
/// **上游无法连接默认只进应用内**:多数人配了回退,一家上游挂了请求照样有人接,
/// 为一次被接住的故障打断用户不值得;而熔断信号本身就会随流量开开合合。
fn default_mode(self) -> Mode {
match self {
Category::Upstream => Mode::App,
_ => Mode::System,
}
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Mode {
/// 弹系统通知(级别够的话)
System,
/// 只进应用内的提醒列表
App,
/// 不记录
Off,
}

/// 用户改过的那几类。**没改过的不存**,出厂设置变了会跟着变
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct Prefs {
#[serde(default)]
modes: BTreeMap<Category, Mode>,
}

impl Prefs {
pub fn mode(&self, c: Category) -> Mode {
self.modes.get(&c).copied().unwrap_or(c.default_mode())
}

pub fn set(&mut self, c: Category, m: Mode) {
if m == c.default_mode() {
self.modes.remove(&c);
} else {
self.modes.insert(c, m);
}
}
}

/// 读不出来就按出厂设置:一份坏掉的设置不该挡住提醒
pub fn load(file: &Path) -> Prefs {
std::fs::read(file)
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_default()
}

pub fn save(file: &Path, p: &Prefs) -> std::io::Result<()> {
if let Some(dir) = file.parent() {
std::fs::create_dir_all(dir)?;
}
let mut text = serde_json::to_vec_pretty(p).map_err(std::io::Error::other)?;
text.push(b'\n');
std::fs::write(file, text)
}
20 changes: 20 additions & 0 deletions src-tauri/src/notices/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const CONFIG: &str = "config";
pub fn suppresses(key: &str) -> &'static [&'static str] {
match key {
"gateway" => &[
"upstream:",
"quota:",
"credential:",
"auth:",
Expand Down Expand Up @@ -69,6 +70,25 @@ pub fn from_event(ev: &Event) -> Vec<Signal> {
.filter(|w| w.status.as_deref() != Some("rejected"))
.map(|w| Signal::cleared(format!("quota:{provider}:{}", w.window)))
.collect(),
// **熔断打开才算出事。**冷却到点的那条 `closed` 只是「可以再试」,不是恢复了 ——
// 当成恢复的话,一家一直不通的上游每分钟开合一次,去抖永远等不满
Event::HealthChanged {
provider, state, ..
} if state == "open" => vec![
Signal::raised(
format!("upstream:{provider}"),
Level::Warning,
format!("上游「{provider}」无法连接"),
)
.body("连续多次请求失败,暂停向其转发。".to_string())
.view(UPSTREAMS),
],
// 恢复要有证据:这家真的又接下了一个请求
Event::RequestRouted { attempts, .. } => attempts
.iter()
.filter(|a| a.outcome == "served")
.map(|a| Signal::cleared(format!("upstream:{}", a.provider)))
.collect(),
Event::CredentialExpired {
provider, detail, ..
} => vec![
Expand Down
Loading
Loading