```
feat(target-lists): 新增黑白名单管理与实时告警功能 - rid-shared 新增 target_lists 模块,定义名单数据契约 - 地图适配器支持按名单类型着色渲染目标(白/黑/未知) - 新增名单筛选器与目标目录过滤联动 - 实时详情面板支持加入/编辑白名单与黑名单操作 - 新增黑名单命中告警横幅与事件日志高亮 - 新增名单管理浮层(Manager 组件)与徽章展示 - 底图默认切换为影像图,相机初始俯仰角归零 - color-scheme 切换为 dark,新增 glass/workbench 样式 ```
This commit is contained in:
+18
-1
@@ -112,7 +112,7 @@ async fn handle(State(worker): State<Worker>, req: Request) -> Response {
|
||||
Ok(q) => q.0,
|
||||
Err(_) => return error("查询参数无效".into()),
|
||||
};
|
||||
let body = if method == "POST" || method == "PATCH" {
|
||||
let body = if method == "POST" || method == "PATCH" || method == "PUT" {
|
||||
match axum::body::to_bytes(req.into_body(), 16 * 1024 * 1024).await {
|
||||
Ok(b) => {
|
||||
if path == "/api/archive/retry" && b.is_empty() {
|
||||
@@ -135,6 +135,23 @@ async fn handle(State(worker): State<Worker>, req: Request) -> Response {
|
||||
return binary(bytes.to_vec(), mime, None, None);
|
||||
}
|
||||
let result=worker.run(move|s|{
|
||||
if method=="GET"&&path=="/api/target-lists"{
|
||||
if let Some(known)=params.get("revision") {
|
||||
let known=known.parse::<u64>().map_err(|_|AppError::Validation("名单版本无效".into()))?;
|
||||
if crate::target_lists::revision(&s.db)?==known{return Ok(StatusCode::NOT_MODIFIED.into_response())}
|
||||
}
|
||||
return Ok(json_response(StatusCode::OK,serde_json::to_value(crate::target_lists::load(&s.db)?).map_err(|e|AppError::Internal(e.to_string()))?));
|
||||
}
|
||||
if let Some(id)=path.strip_prefix("/api/target-lists/") {
|
||||
let snapshot=if method=="PUT"{
|
||||
let mutation=serde_json::from_value(body).map_err(|_|AppError::Validation("名单类型、备注或版本无效".into()))?;
|
||||
crate::target_lists::save(&mut s.db,id,mutation)?
|
||||
}else if method=="DELETE"{
|
||||
let expected=params.get("revision").and_then(|v|v.parse::<u64>().ok()).ok_or(AppError::Validation("请提供有效的名单版本".into()))?;
|
||||
crate::target_lists::remove(&mut s.db,id,expected)?
|
||||
}else{return Err(AppError::NotFound("名单接口不存在"))};
|
||||
return Ok(json_response(StatusCode::OK,serde_json::to_value(snapshot).map_err(|e|AppError::Internal(e.to_string()))?));
|
||||
}
|
||||
if path=="/api/appearance" && (method=="GET" || method=="PATCH") {
|
||||
let value=if method=="GET" { crate::appearance::load(&s.db)? } else { crate::appearance::save(&mut s.db,body)? };
|
||||
return Ok(json_response(StatusCode::OK,serde_json::to_value(value).map_err(|e|AppError::Internal(e.to_string()))?));
|
||||
|
||||
@@ -6,6 +6,7 @@ mod maps;
|
||||
mod realtime;
|
||||
mod receiver;
|
||||
mod store;
|
||||
mod target_lists;
|
||||
mod web_assets {
|
||||
include!(concat!(env!("OUT_DIR"), "/web_assets.rs"));
|
||||
}
|
||||
|
||||
@@ -133,6 +133,7 @@ impl Store {
|
||||
std::fs::create_dir_all(root.join("registry/data"))?;
|
||||
let mut db = Connection::open(root.join("registry/data/registry.sqlite"))?;
|
||||
db.busy_timeout(std::time::Duration::from_secs(5))?;
|
||||
crate::target_lists::init(&mut db)?;
|
||||
db.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS app_settings(key TEXT PRIMARY KEY,value TEXT NOT NULL);",
|
||||
)?;
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
//! SQLite-backed manual lists. Target identity is exact and never inferred from registration.
|
||||
use crate::error::{AppError, Result};
|
||||
use rid_shared::target_lists::{
|
||||
Entry, ListKind, MAX_ENTRIES, MAX_NOTE_CHARS, Mutation, Snapshot, valid_target_id,
|
||||
};
|
||||
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
|
||||
|
||||
pub fn init(db: &mut Connection) -> Result<()> {
|
||||
let tx = db.transaction()?;
|
||||
tx.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS target_list_entries(
|
||||
target_id TEXT PRIMARY KEY COLLATE BINARY,
|
||||
list_kind TEXT NOT NULL CHECK(list_kind IN ('white','black')),
|
||||
note TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS target_list_state(
|
||||
id INTEGER PRIMARY KEY CHECK(id=1), revision INTEGER NOT NULL CHECK(revision>=0)
|
||||
);
|
||||
INSERT OR IGNORE INTO target_list_state(id,revision) VALUES(1,0);",
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn revision(db: &Connection) -> Result<u64> {
|
||||
let value: i64 = db.query_row(
|
||||
"SELECT revision FROM target_list_state WHERE id=1",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
u64::try_from(value).map_err(|_| AppError::Internal("名单版本损坏".into()))
|
||||
}
|
||||
|
||||
pub fn load(db: &Connection) -> Result<Snapshot> {
|
||||
let mut statement = db.prepare("SELECT target_id,list_kind,note,updated_at FROM target_list_entries ORDER BY target_id COLLATE BINARY")?;
|
||||
let entries = statement
|
||||
.query_map([], |row| {
|
||||
let kind: String = row.get(1)?;
|
||||
let list_kind = match kind.as_str() {
|
||||
"white" => ListKind::White,
|
||||
"black" => ListKind::Black,
|
||||
_ => return Err(rusqlite::Error::InvalidQuery),
|
||||
};
|
||||
Ok(Entry {
|
||||
target_id: row.get(0)?,
|
||||
list_kind,
|
||||
note: row.get(2)?,
|
||||
updated_at: row.get(3)?,
|
||||
})
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(Snapshot {
|
||||
revision: revision(db)?,
|
||||
entries,
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_id(id: &str) -> Result<()> {
|
||||
if !valid_target_id(id) {
|
||||
return Err(AppError::Validation(
|
||||
"目标标识须为 1–64 位字母、数字、短横线或下划线".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_revision(db: &Connection, expected: u64) -> Result<()> {
|
||||
if revision(db)? != expected {
|
||||
return Err(AppError::Validation(
|
||||
"名单已被其他页面修改,请刷新后重试".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn save(db: &mut Connection, id: &str, mutation: Mutation) -> Result<Snapshot> {
|
||||
validate_id(id)?;
|
||||
let note = mutation.note.trim();
|
||||
if note.chars().count() > MAX_NOTE_CHARS {
|
||||
return Err(AppError::Validation("名单备注最多 200 字".into()));
|
||||
}
|
||||
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
check_revision(&tx, mutation.expected_revision)?;
|
||||
let old: Option<(String, String)> = tx
|
||||
.query_row(
|
||||
"SELECT list_kind,note FROM target_list_entries WHERE target_id=?1",
|
||||
[id],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let kind = match mutation.list_kind {
|
||||
ListKind::White => "white",
|
||||
ListKind::Black => "black",
|
||||
};
|
||||
if old.is_none() {
|
||||
let count: i64 =
|
||||
tx.query_row("SELECT COUNT(*) FROM target_list_entries", [], |r| r.get(0))?;
|
||||
if count >= MAX_ENTRIES as i64 {
|
||||
return Err(AppError::Validation(
|
||||
"名单已达到 5000 条上限,请先移除不再使用的条目".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
if old
|
||||
.as_ref()
|
||||
.is_none_or(|(old_kind, old_note)| old_kind != kind || old_note != note)
|
||||
{
|
||||
let updated_at = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
|
||||
tx.execute("INSERT INTO target_list_entries(target_id,list_kind,note,updated_at) VALUES(?1,?2,?3,?4) ON CONFLICT(target_id) DO UPDATE SET list_kind=excluded.list_kind,note=excluded.note,updated_at=excluded.updated_at", params![id,kind,note,updated_at])?;
|
||||
tx.execute(
|
||||
"UPDATE target_list_state SET revision=revision+1 WHERE id=1",
|
||||
[],
|
||||
)?;
|
||||
}
|
||||
let snapshot = load(&tx)?;
|
||||
tx.commit()?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
pub fn remove(db: &mut Connection, id: &str, expected: u64) -> Result<Snapshot> {
|
||||
validate_id(id)?;
|
||||
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
check_revision(&tx, expected)?;
|
||||
if tx.execute("DELETE FROM target_list_entries WHERE target_id=?1", [id])? > 0 {
|
||||
tx.execute(
|
||||
"UPDATE target_list_state SET revision=revision+1 WHERE id=1",
|
||||
[],
|
||||
)?;
|
||||
}
|
||||
let snapshot = load(&tx)?;
|
||||
tx.commit()?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn mutation(kind: ListKind, revision: u64) -> Mutation {
|
||||
Mutation {
|
||||
list_kind: kind,
|
||||
note: " 作业备注 ".into(),
|
||||
expected_revision: revision,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_membership_is_exclusive_persistent_and_independent() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut store = crate::store::Store::open(dir.path().to_owned()).unwrap();
|
||||
let first = save(&mut store.db, "DRONE-1", mutation(ListKind::Black, 0)).unwrap();
|
||||
assert_eq!(first.revision, 1);
|
||||
assert_eq!(first.entries[0].note, "作业备注");
|
||||
let second = save(&mut store.db, "DRONE-1", mutation(ListKind::White, 1)).unwrap();
|
||||
assert_eq!(second.entries.len(), 1);
|
||||
assert_eq!(second.entries[0].list_kind, ListKind::White);
|
||||
save(&mut store.db, "drone-1", mutation(ListKind::Black, 2)).unwrap();
|
||||
assert_eq!(store.list("").unwrap().len(), 0);
|
||||
drop(store);
|
||||
let mut store = crate::store::Store::open(dir.path().to_owned()).unwrap();
|
||||
assert_eq!(load(&store.db).unwrap().entries.len(), 2);
|
||||
assert_eq!(
|
||||
remove(&mut store.db, "DRONE-1", 3).unwrap().entries[0].target_id,
|
||||
"drone-1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_stale_and_repeated_updates_do_not_corrupt_state() {
|
||||
let mut db = Connection::open_in_memory().unwrap();
|
||||
init(&mut db).unwrap();
|
||||
save(&mut db, "A", mutation(ListKind::Black, 0)).unwrap();
|
||||
assert!(save(&mut db, "A", mutation(ListKind::White, 0)).is_err());
|
||||
assert!(remove(&mut db, "A", 0).is_err());
|
||||
for id in ["", "A B", "../A", &"A".repeat(65)] {
|
||||
assert!(save(&mut db, id, mutation(ListKind::White, 1)).is_err());
|
||||
}
|
||||
let mut long = mutation(ListKind::White, 1);
|
||||
long.note = "注".repeat(201);
|
||||
assert!(save(&mut db, "A", long).is_err());
|
||||
assert_eq!(
|
||||
save(&mut db, "A", mutation(ListKind::Black, 1))
|
||||
.unwrap()
|
||||
.revision,
|
||||
1
|
||||
);
|
||||
assert_eq!(remove(&mut db, "absent", 1).unwrap().revision, 1);
|
||||
assert_eq!(remove(&mut db, "A", 1).unwrap().revision, 2);
|
||||
assert!(load(&db).unwrap().entries.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capacity_and_revision_failures_preserve_existing_entries() {
|
||||
let mut db = Connection::open_in_memory().unwrap();
|
||||
init(&mut db).unwrap();
|
||||
let tx = db.transaction().unwrap();
|
||||
for index in 0..MAX_ENTRIES {
|
||||
tx.execute(
|
||||
"INSERT INTO target_list_entries VALUES(?1,'white','','time')",
|
||||
[format!("ID-{index}")],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
tx.commit().unwrap();
|
||||
assert!(save(&mut db, "ONE-MORE", mutation(ListKind::Black, 0)).is_err());
|
||||
assert_eq!(
|
||||
save(&mut db, "ID-0", mutation(ListKind::Black, 0))
|
||||
.unwrap()
|
||||
.revision,
|
||||
1
|
||||
);
|
||||
db.execute_batch("CREATE TRIGGER fail_list_revision BEFORE UPDATE ON target_list_state BEGIN SELECT RAISE(ABORT,'test failure'); END;").unwrap();
|
||||
assert!(save(&mut db, "ID-0", mutation(ListKind::White, 1)).is_err());
|
||||
let snapshot = load(&db).unwrap();
|
||||
assert_eq!(snapshot.revision, 1);
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.entries
|
||||
.iter()
|
||||
.find(|e| e.target_id == "ID-0")
|
||||
.unwrap()
|
||||
.list_kind,
|
||||
ListKind::Black
|
||||
);
|
||||
assert_eq!(snapshot.entries.len(), MAX_ENTRIES);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_crud_conditional_read_validation_and_origin_checks() {
|
||||
use axum::{body::Body, http::Request};
|
||||
use tower::ServiceExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut store = crate::store::Store::open(dir.path().to_owned()).unwrap();
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel::<crate::Job>(16);
|
||||
std::thread::spawn(move || {
|
||||
while let Some(job) = rx.blocking_recv() {
|
||||
match job {
|
||||
crate::Job::Execute(job) => job(&mut store),
|
||||
crate::Job::Shutdown => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
let app = crate::http::router(crate::Worker(tx));
|
||||
let body = serde_json::json!({"list_kind":"black","note":"关注","expected_revision":0});
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("PUT")
|
||||
.uri("/api/target-lists/HTTP_001")
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
let value: serde_json::Value = serde_json::from_slice(
|
||||
&axum::body::to_bytes(response.into_body(), 65536)
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(value["revision"], 1);
|
||||
assert_eq!(value["entries"][0]["target_id"], "HTTP_001");
|
||||
let body_text = body.to_string();
|
||||
for (method, url, origin, payload, expected) in [
|
||||
("GET", "/api/target-lists?revision=1", None, "", 304),
|
||||
("GET", "/api/target-lists?revision=bad", None, "", 400),
|
||||
(
|
||||
"PUT",
|
||||
"/api/target-lists/HTTP_001",
|
||||
None,
|
||||
body_text.as_str(),
|
||||
400,
|
||||
),
|
||||
(
|
||||
"PUT",
|
||||
"/api/target-lists/HTTP_002",
|
||||
Some("https://example.com"),
|
||||
body_text.as_str(),
|
||||
403,
|
||||
),
|
||||
("PUT", "/api/target-lists/HTTP_002", None, "not JSON", 400),
|
||||
("DELETE", "/api/target-lists/HTTP_001", None, "", 400),
|
||||
(
|
||||
"DELETE",
|
||||
"/api/target-lists/HTTP_001?revision=1",
|
||||
None,
|
||||
"",
|
||||
200,
|
||||
),
|
||||
] {
|
||||
let mut builder = Request::builder().method(method).uri(url);
|
||||
if let Some(origin) = origin {
|
||||
builder = builder.header("origin", origin)
|
||||
}
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(builder.body(Body::from(payload.to_owned())).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status().as_u16(), expected, "{method} {url}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user