Skip to main content

wist_contracts/
work.rs

1//! **工作授权快照**:网关授权(grant)、agentd 拉取(`WorkGrant`)并确认。
2//!
3//! ## 为什么是「快照」而不是「指令流」
4//!
5//! 常驻工作(`StandingWork`)表达的是**期望状态**:某个采集面应当持续执行什么。
6//! 期望状态天然是幂等的(同一份重复拉取不产生副作用),断了网、重启了进程,
7//! 再拉一次就回到期望 —— 不必让网关记住「上次推到哪条」。
8//! 这跟 `PollControlCommands` 的长轮询指令流是两种东西:那条要求**不重放**,这条要求**可重拉**。
9//!
10//! 一次性工作(`OneShotWork`)是命令式的,但它也搭这份快照回来:
11//! 决定「现在还该做吗」的是它的状态(未了结才出现在快照里),不是「推没推过」。
12//!
13//! ## 为什么在契约 crate
14//!
15//! 这是**两侧都要解析**的字节:网关写授权、agentd 读并执行。各写一份结构体,
16//! 迟早出现「网关发了 `plan_version`、agentd 读的是 `version`」这种只能在真机联调时才发现的分叉。
17//! 与 `DiscoveryAspectPolicySet` 同一个理由。
18//!
19//! ## 与本地保护暂停的区别
20//!
21//! agentd 自己也会暂停(如 `spool over limit`),那是**本地保护**:自动、临时、本机可见。
22//! 这里下发的 `paused` 是**授权层状态**:人工、持久、跨重启。两者在观测里必须能分辨,
23//! 不要合并成一个 paused —— 合并之后「谁把采集停了」就再也说不清。
24
25use serde::{Deserialize, Serialize};
26
27use crate::capability_report::LogsCapabilities;
28
29/// 常驻工作的状态取值(对应模型 `StandingWork.status`)。
30///
31/// `superseded` 与 `revoked` 都不出现在 `WorkGrant.standing` 里:前者是「被新版本取代」,
32/// 后者是「授权被撤」。两者都要留痕,所以还是要有状态而不是删行。
33pub const STANDING_WORK_STATUSES: [&str; 4] = ["active", "paused", "superseded", "revoked"];
34
35/// 一次性工作的状态取值(对应模型 `OneShotWork.status`)。
36pub const ONE_SHOT_WORK_STATUSES: [&str; 9] = [
37    "dispatched",
38    "accepted",
39    "running",
40    "paused",
41    "succeeded",
42    "failed",
43    "timed_out",
44    "canceled",
45    "expired",
46];
47
48/// Agent **允许上报**的一次性工作状态([`ONE_SHOT_WORK_STATUSES`] 的真子集)。
49///
50/// 为什么不是全集:`dispatched` 是网关自己写的(派下去那一刻),`paused` / `canceled` / `expired`
51/// 归**控制面与期限**管(运维暂停撤回、或过了截止)—— agent 无权把它们写回去。
52/// 剩下的问题只有一种:「这件活做完了没有」,答案就这三种。
53pub const AGENT_REPORTABLE_WORK_STATUSES: [&str; 3] = ["running", "succeeded", "failed"];
54
55/// 一次性工作的**终态**:到了这几个状态就了结了,不再出现在快照里。
56pub const ONE_SHOT_TERMINAL_STATUSES: [&str; 5] =
57    ["succeeded", "failed", "timed_out", "canceled", "expired"];
58
59/// 工作类型:常驻(持续到被替换或撤回)与一次性(有期限与终态)。
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ::jumo_derive::Jumo)]
61#[jumo(kind = "state", domain = "Control", module = "Control.Agent.Work")]
62#[serde(rename_all = "PascalCase")]
63pub enum WorkKind {
64    /// 常驻工作:按**采集面**授权,一个面一份。
65    Standing,
66    /// 一次性工作:按**动作**授权。
67    OneShot,
68}
69
70/// 常驻工作:网关声明该 Agent 应当持续执行的工作。
71///
72/// 粒度是**采集面**(一个面 = 一份工作),不是 capability:一份 `collect_logs` 会裹住十几个面,
73/// 那样「按面暂停 / 限流 / 审计」全都无从下手。面由模板的 `family_scope` 展开而来,
74/// **不携带 capability** —— 该面由哪个采集器承接,由 `spec` 里的单元各自决定。
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ::jumo_derive::Jumo)]
76#[jumo(kind = "struct", domain = "Control", module = "Control.Agent.Work")]
77#[serde(deny_unknown_fields)]
78pub struct StandingWork {
79    pub work_id: String,
80    pub agent_id: String,
81    /// 采集面(`CollectionFamily`)。
82    pub family: String,
83    /// 工作参数:由采集目录的条目组合而成(**不是自由文本**),随 `plan_version` 整体替换。
84    pub spec: String,
85    /// 本工作按哪一版目录展开:目录换版**不追改**已授权工作(要跟新版得走新提案 + 审定)。
86    pub catalog_version: i64,
87    /// 生效依据:指向已批准的提案(人工直填 spec 时为空)。
88    #[serde(default)]
89    pub proposal_id: Option<String>,
90    /// 期望版本:网关每次改动 +1;agentd 回报实际版本,与它比对即得漂移。
91    pub plan_version: i64,
92    pub effective_from: String,
93    /// 见 [`STANDING_WORK_STATUSES`]。
94    pub status: String,
95    pub updated_by: String,
96    pub updated_at: String,
97}
98
99/// 一次性工作:有计划开始时间与期限,有明确终态。
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ::jumo_derive::Jumo)]
101#[jumo(kind = "struct", domain = "Control", module = "Control.Agent.Work")]
102#[serde(deny_unknown_fields)]
103pub struct OneShotWork {
104    pub work_id: String,
105    pub agent_id: String,
106    /// 动作面:upgrade / snapshot / exec / ...(执行载体是 Reporting 域的 ActionPlan)。
107    pub action: String,
108    pub spec: String,
109    /// 计划开始时间:到点前不应执行(与「立即派发」区分开)。
110    pub scheduled_at: String,
111    /// 绝对截止:业务要求的时间点,**暂停也照走**(不由暂停顺延)。
112    pub deadline_at: String,
113    /// 执行预算(秒):**只在实际执行时消耗**,暂停期间不计。
114    pub timeout_seconds: i64,
115    /// 可中断性:只有可中断的动作才允许运行中暂停。
116    pub interruptible: bool,
117    /// 见 [`ONE_SHOT_WORK_STATUSES`]。
118    pub status: String,
119    /// 当前暂停的起点(运行中暂停才有;恢复后清空)。
120    #[serde(default)]
121    pub paused_at: Option<String>,
122    /// 累计暂停时长(秒):用于审计与「预算未被暂停消耗」的核对。
123    pub paused_total_seconds: i64,
124    /// 步级断点:已完成步骤保留、`current_step` 在恢复时重做。
125    #[serde(default)]
126    pub current_step: Option<String>,
127    #[serde(default)]
128    pub completed_steps: Vec<String>,
129    /// 已尝试次数(含恢复后的重做)。
130    pub attempt: i64,
131    pub issued_by: String,
132    pub issued_at: String,
133}
134
135impl OneShotWork {
136    /// 是否**未了结**(快照里只带未了结的活)。
137    pub fn is_outstanding(&self) -> bool {
138        !ONE_SHOT_TERMINAL_STATUSES.contains(&self.status.as_str())
139    }
140
141    /// 是否允许在运行期间暂停。
142    ///
143    /// 两条都要满足:动作声明了 `interruptible`,且此刻确实在做(`accepted`/`running`)。
144    /// 不可中断的动作**拒绝**而不是「尽力暂停」—— 挂起半个升级进程比不暂停更危险。
145    pub fn can_pause(&self) -> bool {
146        self.interruptible && matches!(self.status.as_str(), "accepted" | "running")
147    }
148}
149
150/// 管理面授权或撤回工作的回执:一份工作一次。
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ::jumo_derive::Jumo)]
152#[jumo(kind = "struct", domain = "Control", module = "Control.Agent.Work")]
153#[serde(deny_unknown_fields)]
154pub struct WorkReceipt {
155    pub work_id: String,
156    pub agent_id: String,
157    pub work_kind: WorkKind,
158    /// accepted | paused | resumed | revoked | rejected。
159    pub status: String,
160    pub plan_version: i64,
161    pub created_at: String,
162}
163
164// ─────────────────────────────────────────────────────────────────────────────
165// 工作参数(`StandingWork.spec` 的内容)
166// ─────────────────────────────────────────────────────────────────────────────
167//
168// 模型里 `StandingWork.spec` 是一个 `String`,语义是「工作参数:由采集目录的条目
169// 组合而成,**不是自由文本**」。这里的三个类型就是它的**编码**:一串已物化的采集单元。
170//
171// 为什么必须带上来源与规则标识,而不是只给一串 `unit_id`:agentd 拿到工作要能
172// **直接照做**。单元的采集来源(`sources`)与数据面规则标识(`rule_ref`)本来都只
173// 存在于网关的采集目录里,只发 id 等于发了一张自己去不了的地址 —— 于是要么再去网关
174// 拉一次目录(多一条必须鉴权的路径),要么两边各维护一份目录(必然漂移)。
175//
176// 为什么不把它们塞成 `StandingWork` 的字段:那会把「工作」与「内容目录」的边界糊掉;
177// 模型里这个字段就是**不透明的工作参数**,保持它不透明是两侧能独立演进的前提。
178
179/// 一份常驻工作的工作参数。
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181#[serde(deny_unknown_fields)]
182pub struct WorkSpec {
183    /// 本工作包含的采集单元(已按该机器的事实裁剪过)。
184    #[serde(default)]
185    pub units: Vec<WorkSpecUnit>,
186}
187
188/// 一个已物化的采集单元:只说「采什么、怎么落地」,不复述策展元信息。
189///
190/// 刻意不带 `status` / `match` / `catalog_version`:那些是网关策展与裁剪的输入,
191/// 工作一旦发出去就已经裁剪完了。带上它们会让 agentd 有「再判断一次」的空间,
192/// 而 agentd 不是第二个策展器。
193#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
194#[serde(deny_unknown_fields)]
195pub struct WorkSpecUnit {
196    pub unit_id: String,
197    /// `collect_logs` | `collect_metrics`:该单元由哪类采集器承接。
198    pub capability: String,
199    /// 数据面 rule/oml 标识(空 = 该单元还没接上规则,理论不会入工作)。
200    #[serde(default)]
201    pub rule_ref: String,
202    /// `none` | `root` | `fda`:要采到这东西得有什么权限 —— 缺权限时应**说清缺什么**,
203    /// 而不是安静地采不到。
204    #[serde(default)]
205    pub requires_privilege: String,
206    #[serde(default)]
207    pub sources: Vec<WorkSpecSource>,
208}
209
210/// 采集来源:`kind` ∈ `FileGlob` | `Exporter` | `UnifiedLogPredicate` | `MetricInterval`。
211///
212/// 与模型 `CollectionSource` 同形:`target` 的含义由 `kind` 决定
213/// (路径通配 / 导出器标识 / 谓词 / 周期)。
214#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(deny_unknown_fields)]
216pub struct WorkSpecSource {
217    pub kind: String,
218    pub target: String,
219    /// 怎么读这条来源:`none`(一行一条)| `indented`(行首缩进是上一条的续行)|
220    /// `mysql_slow`(`# Time:` 起块)| `postgres_csv`(**引号外**的换行才切记录)。
221    ///
222    /// 只对可 tail 的 `FileGlob` 有意义,其余 kind 恒为 `none`。**不是**"要不要多行"这个偏好,
223    /// 而是这条日志的**固有格式**:说错了要么把多行记录拆散、要么把独立记录粘成一条。
224    #[serde(default = "default_multiline")]
225    pub multiline: String,
226    /// 从 `target` 匹配集合里剔掉的**绝对路径 glob**(默认空)。
227    ///
228    /// 只对 `FileGlob` 有意义,按**展开后的完整路径**匹配(不是文件名)。为什么需要它:
229    /// 容器日志的选源根是 `/var/log/containers/*.log`,而目录里同时有不该采的容器
230    /// (sidecar / init / 平台自身的 pod);没有排除项就只能把业务服务名写进 pattern,
231    /// 而服务名会随集群漂移。
232    ///
233    /// 空数组**不序列化**:旧 agent 的 `WorkSpecSource` 是 `deny_unknown_fields` 的,
234    /// 发一个空字段过去只会给旧机队添一种没必要的解析失败。
235    #[serde(default, skip_serializing_if = "Vec::is_empty")]
236    pub exclude_globs: Vec<String>,
237    /// 容器选源的结构化过滤器(默认空)。只对 `FileGlob` 有意义。
238    ///
239    /// 空(两个列表都空)**不序列化**:与 `exclude_globs` 同一个理由 —— 旧 agent 的
240    /// `WorkSpecSource` 是 `deny_unknown_fields` 的,发一个空字段过去只会给旧机队
241    /// 添一种没必要的解析失败。
242    ///
243    /// ⚠ 非空时**要求 agent 支持**(与 glob 单元同一条纪律):能力轴是
244    /// `LogsCapabilities.filters`(`namespace_in` / `pod_not_in`),网关在派活时裁掉
245    /// 不支持的来源;旧 agent 收到非空 `filters` 会拒收整份 spec。
246    #[serde(default, skip_serializing_if = "ContainerFilters::is_empty")]
247    pub filters: ContainerFilters,
248    /// 读进来的记录里,含这些**子串**的整条丢掉(默认空 = 不丢)。只对 `FileGlob` 有意义。
249    ///
250    /// 为什么是子串、不是正则:这是**噪音行**的白名单(`pam_unix(cron:session)` 这类
251    /// 每分钟一条、信息量为零的行),不是解析。正则意味着在采集端维护一套可执行表达式
252    /// (回溯、超时、误匹配都是新故障面),而子串能做到的事不需要它。
253    ///
254    /// 语义是“整条记录”:子串命中就丢整条,**不会只删命中那一行**而留下半条多行记录。
255    /// 丢弃数进 agentd 自观测(`telemetry noise dropped …`),不然“怎么少了”无处可查。
256    ///
257    /// 空数组**不序列化**:旧 agent 的 `WorkSpecSource` 是 `deny_unknown_fields` 的。
258    /// 非空时要求 agent 支持 `LogsCapabilities.drop_if_contains`(`substring`),网关据此裁源。
259    #[serde(default, skip_serializing_if = "Vec::is_empty")]
260    pub drop_if_contains: Vec<String>,
261}
262
263/// 容器日志的选源根(写死,D4)。
264///
265/// `/var/log/pods` 下有 `0.log` / `1.log` 与重启序号歧义;`/var/log/containers` 里
266/// 每个活容器恰好一条 symlink,文件名自带 pod / ns / container。
267pub const CONTAINER_LOG_ROOT: &str = "/var/log/containers";
268
269/// 容器选源的结构化过滤器(默认全空 = 不过滤)。
270///
271/// 为什么不是「再写几条 pattern」:k8s 的容器日志文件名本身就是
272/// `<pod>_<namespace>_<container>-<id>.log`,选源要用的三个维度全在里面;纯 Docker 载体
273/// 只有 id,名字/镜像要读同目录的 `config.v2.json`。把 namespace 白名单散成 N 条 path
274/// pattern 会随集群漂移,而过滤器是**结构化**的、与文件名格式解耦。
275///
276/// 求值位置:**发现阶段**(agentd 展开 glob、剔完 `exclude_globs` 之后,读之前),
277/// 读取器不参与 —— 所以它不影响 tail / checkpoint / 轮转语义。
278///
279/// 组合语义(四个维度之间):维度**内**是 OR,维度**间**是 AND;
280/// `*_not_in` 是排除(命中即不收),`*_in` 是包含(不在名单里就不收)。
281/// 同一个值同时出现在 `name_in` 与 `name_not_in` 时,**排除优先**(结果为空集)。
282#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
283#[serde(deny_unknown_fields)]
284pub struct ContainerFilters {
285    /// 只采这些 namespace(空 = 不限)。
286    #[serde(default, skip_serializing_if = "Vec::is_empty")]
287    pub namespace_in: Vec<String>,
288    /// 这些 pod 不采(空 = 不排除)。
289    #[serde(default, skip_serializing_if = "Vec::is_empty")]
290    pub pod_not_in: Vec<String>,
291    /// 只采这些**容器名**(空 = 不限)。
292    ///
293    /// 两类载体上的含义:
294    /// - k8s(`<pod>_<ns>_<container>-<id>.log`):文件名里的 `<container>` 段;
295    /// - 纯 Docker(`<root>/containers/<id>/<id>-json.log`):文件名里**没有名字**,
296    ///   由采集端从同目录的 `config.v2.json` 取(与帧上的 `container.name` 同源)。
297    ///   取不到身份的候选**不算命中**(包含式过滤要求“证明确实是它”)。
298    #[serde(default, skip_serializing_if = "Vec::is_empty")]
299    pub name_in: Vec<String>,
300    /// 这些容器名不采(空 = 不排除)。
301    ///
302    /// 与 [`Self::name_in`] 相反:取不到身份的候选**保留** —— 排除式只负责“确实是你时才剔”,
303    /// 读不到身份不等于“就是它”,丢掉只会静默少采。
304    #[serde(default, skip_serializing_if = "Vec::is_empty")]
305    pub name_not_in: Vec<String>,
306}
307
308/// 容器过滤器的维度名(**能力词表**的值):与 [`ContainerFilters`] 的字段同名。
309///
310/// 为什么能力名 = 字段名:网关的报错文案(`filters:namespace_in`)与目录里的写法
311/// (`filters = { namespace_in = [...] }`)能一一对上,排查时不用再查一份映射表。
312pub const FILTER_NAMESPACE_IN: &str = "namespace_in";
313/// 见 [`FILTER_NAMESPACE_IN`]。
314pub const FILTER_POD_NOT_IN: &str = "pod_not_in";
315/// 只采这些容器名(Docker 载体靠 `config.v2.json` 取名)。
316pub const FILTER_NAME_IN: &str = "name_in";
317/// 这些容器名不采。
318pub const FILTER_NAME_NOT_IN: &str = "name_not_in";
319
320/// 协议里**定义**的全部容器过滤维度(与 [`ContainerFilters::used_dimensions`] 同源)。
321///
322/// 这是**词表**,不是“实现了的清单”:agentd 上报自己支持的维度时必须**显式**列出,
323/// 不能直接抄这个常量——否则“契约加了一维”会自动变成“我也支持”(见各 agent 的上报点)。
324///
325/// 新增一个过滤维度时:先在 [`ContainerFilters`] 里加字段,再往这里加名字 ——
326/// 两侧对不上的漂移由 `a_fully_declared_agent_is_missing_nothing_the_contract_calls_executable` 钉住。
327pub const CONTAINER_FILTERS: &[&str] = &[
328    FILTER_NAMESPACE_IN,
329    FILTER_POD_NOT_IN,
330    FILTER_NAME_IN,
331    FILTER_NAME_NOT_IN,
332];
333
334/// 噪音行丢弃的**求值方式**(能力词表的值)。
335///
336/// 目前只有子串一种 —— 它跟正则不是同一个东西(见 [`WorkSpecSource::drop_if_contains`])。
337/// 以后真要加正则,那是新的一项能力:旧 agent 不该被当成“也懂正则”。
338pub const DROP_IF_CONTAINS_SUBSTRING: &str = "substring";
339/// agentd 能承接的全部噪音行丢弃方式(目前只有子串)。
340pub const DROP_IF_CONTAINS_MODES: &[&str] = &[DROP_IF_CONTAINS_SUBSTRING];
341
342/// `drop_if_contains` 的条数上限(超过就是“在采集端写解析规则”,那条路不该走)。
343pub const DROP_IF_CONTAINS_MAX_ITEMS: usize = 8;
344/// 单个子串的长度上限(字节)。
345pub const DROP_IF_CONTAINS_MAX_BYTES: usize = 200;
346
347/// 校验 `drop_if_contains` 的形状:精确子串,不是 pattern。
348///
349/// 网关装载期、agentd 配置校验、web 表单三处共用同一口径(否则会出现“页面能填、
350/// agentd 不认”)。只拦“一定有意义不明”的形态:空串 / 首尾空白 / 控制字符 / 过长 / 太多 / 重复。
351pub fn validate_drop_if_contains(needles: &[String]) -> Result<(), String> {
352    if needles.len() > DROP_IF_CONTAINS_MAX_ITEMS {
353        return Err(format!(
354            "drop_if_contains 条数过多({},上限 {DROP_IF_CONTAINS_MAX_ITEMS})",
355            needles.len()
356        ));
357    }
358    for (index, needle) in needles.iter().enumerate() {
359        if needle.trim().is_empty() {
360            return Err(format!("drop_if_contains[{index}] 是空串"));
361        }
362        if needle.trim() != needle {
363            return Err(format!("drop_if_contains[{index}] {needle:?} 带首尾空白"));
364        }
365        if needle.chars().any(char::is_control) {
366            return Err(format!("drop_if_contains[{index}] {needle:?} 含控制字符"));
367        }
368        if needle.len() > DROP_IF_CONTAINS_MAX_BYTES {
369            return Err(format!(
370                "drop_if_contains[{index}] 过长({} 字节,上限 {DROP_IF_CONTAINS_MAX_BYTES})",
371                needle.len()
372            ));
373        }
374        if needles[..index].contains(needle) {
375            return Err(format!("drop_if_contains[{index}] {needle:?} 重复"));
376        }
377    }
378    Ok(())
379}
380
381impl ContainerFilters {
382    /// 四个列表都空 = 不过滤(空过滤器不上线,见 [`WorkSpecSource::filters`])。
383    pub fn is_empty(&self) -> bool {
384        self.namespace_in.is_empty()
385            && self.pod_not_in.is_empty()
386            && self.name_in.is_empty()
387            && self.name_not_in.is_empty()
388    }
389
390    /// 这条来源**实际用到**的过滤器维度(空 = 不过滤)。
391    ///
392    /// 能力判定([`missing_log_capabilities`])与 agentd 的能力上报都从这里取:
393    /// 只写一遍字段 → 能力名的对应关系,少一处「新增一个过滤字段、忘了加进能力词表」的漏判。
394    pub fn used_dimensions(&self) -> Vec<&'static str> {
395        let mut used = Vec::new();
396        if !self.namespace_in.is_empty() {
397            used.push(FILTER_NAMESPACE_IN);
398        }
399        if !self.pod_not_in.is_empty() {
400            used.push(FILTER_POD_NOT_IN);
401        }
402        if !self.name_in.is_empty() {
403            used.push(FILTER_NAME_IN);
404        }
405        if !self.name_not_in.is_empty() {
406            used.push(FILTER_NAME_NOT_IN);
407        }
408        used
409    }
410
411    /// 形状校验:过滤器里的值是**精确名字**,不是 pattern。
412    ///
413    /// 网关、web、agentd 三处共用这一份(否则会出现「页面能填、agentd 不认」)。
414    /// 不强制 RFC1123:这里只拦“一定对不上”的形态(空串 / 空白 / 通配符 / 超长),
415    /// 名字是否真存在由集群决定,不是配置校验能回答的。
416    pub fn validate(&self) -> Result<(), String> {
417        for (field, values) in [
418            (FILTER_NAMESPACE_IN, &self.namespace_in),
419            (FILTER_POD_NOT_IN, &self.pod_not_in),
420            (FILTER_NAME_IN, &self.name_in),
421            (FILTER_NAME_NOT_IN, &self.name_not_in),
422        ] {
423            for value in values {
424                if value.trim().is_empty() {
425                    return Err(format!("{field} 里有空值"));
426                }
427                if value.trim() != value {
428                    return Err(format!("{field} 里 {value:?} 带首尾空白"));
429                }
430                if value.contains(['*', '?', '[', ']']) {
431                    return Err(format!(
432                        "{field} 里 {value:?} 含通配符(这里是精确名字,不是 pattern)"
433                    ));
434                }
435                if value.len() > 253 {
436                    return Err(format!("{field} 里 {value:?} 过长(>253)"));
437                }
438            }
439        }
440        Ok(())
441    }
442}
443
444fn default_multiline() -> String {
445    "none".to_string()
446}
447
448impl WorkSpec {
449    /// 解析 `StandingWork.spec`。
450    ///
451    /// 解析失败**不当作空工作**:空工作会让「参数坏了」退化成「没事可做」,
452    /// 两种情形的运维动作完全不同。
453    pub fn parse(spec: &str) -> Result<Self, serde_json::Error> {
454        serde_json::from_str(spec)
455    }
456
457    /// 序列化(网关写 `spec` 用)。字段顺序固定 → 同一份工作每次编码都一样,
458    /// `plan_version` 之外的字节也稳定,方便对账。
459    pub fn encode(&self) -> Result<String, serde_json::Error> {
460        serde_json::to_string(self)
461    }
462
463    /// 周期类来源声明的间隔(秒):取所有 `MetricInterval` 里最密的那一个。
464    ///
465    /// 取最密而不是取第一个:一份工作里若有两个指标单元,采慢的那个会
466    /// 静默压掉采密的要求,而“要得最急”的需求才是上送频率的下界。
467    pub fn metric_interval_seconds(&self) -> Option<i64> {
468        self.units
469            .iter()
470            .flat_map(|unit| unit.sources.iter())
471            .filter(|source| source.kind == "MetricInterval")
472            .filter_map(|source| parse_interval_seconds(&source.target))
473            .min()
474    }
475
476    /// 是否要采日志(有 `collect_logs` 单元)。
477    pub fn collects_logs(&self) -> bool {
478        self.units
479            .iter()
480            .any(|unit| unit.capability == "collect_logs")
481    }
482}
483
484/// agentd **有可能真的执行**的来源 kind(其余 kind 一律 `unsupported`,不当没看见)。
485///
486/// 注意:kind 对了**还不够** —— 目标形态也有限制,见 [`is_executable_source`]:
487/// `FileGlob` 要是**绝对路径**(显式路径或受支持的 glob)、`Exporter` 要是**已知导出器 ID**。
488/// 只按 kind 判会把「`**` 递归」「`~` 与相对路径」「写错的导出器」当成可采,而那在采集端落不了地。
489pub const EXECUTABLE_SOURCE_KINDS: &[&str] = &["FileGlob", "MetricInterval", "Exporter"];
490
491/// 目标里有没有通配元字符 —— 有就说明它不是**显式单路径**。
492pub fn has_glob_meta(target: &str) -> bool {
493    target.contains(['*', '?', '['])
494}
495
496/// 这个目标是不是采集端今天**真能打开**的路径:**绝对路径、无通配**。
497///
498/// 采集端(agentd 第一版)只实现显式单路径输入:**不做 glob 展开、也不展开 `~`**
499/// (见 `wist/wist-agentd/docs/design/log-file-input-spec.md` §2 的能力边界)。
500/// 单层 glob 从 W1 起可采,但那走 [`is_glob_path`];`~` 与相对路径仍永远不可采。
501///
502/// 从 W1 起,带通配的目标由 [`is_glob_path`] / [`is_file_target`] 判定 —— 它们才是
503/// 「采集端接不接得了」的口径;本函数只留给**单文件**场景(例如「一个显式路径能否参与
504/// 存在性裁剪」:那一步只能对显式路径做,探测不到的路径不能当不存在)。
505pub fn is_explicit_path(target: &str) -> bool {
506    target.starts_with('/') && !has_glob_meta(target)
507}
508
509/// 这个目标是不是**受支持的文件族 glob**:**绝对路径、有通配、不含 `**`**。
510///
511/// `**` 被拒不是保守,而是口径:采集端只扫 pattern 的固定前缀目录、`*` 不跨目录
512/// (`literal_separator`),递归展开既没实现也无法给出上限 —— 让它在目录装载期就被挡住,
513/// 比让 agent 每轮报一次 IO 错误好。
514pub fn is_glob_path(target: &str) -> bool {
515    target.starts_with('/') && has_glob_meta(target) && !target.contains("**")
516}
517
518/// 这个目标是不是采集端**能承接的文件目标**:显式绝对路径,或受支持的文件族 glob。
519///
520/// 不展开 `~`、不接受相对路径:相对路径的结果取决于进程 cwd,同一台机器换一种启动方式
521/// 就换一个采集对象,那不是「配置」,是运气。
522pub fn is_file_target(target: &str) -> bool {
523    is_explicit_path(target) || is_glob_path(target)
524}
525
526/// 这个目标是不是**容器日志来源**的形状(k8s 与 Docker 两种载体共用)。
527///
528/// 判据刻意只要求“路径里有一个 `containers` 段”:
529/// * k8s 载体是 `/var/log/containers`([`CONTAINER_LOG_ROOT`]);
530/// * Docker 载体的根目录可以被 `--data-root` 改掉,写死 `/var/lib/docker` 会误拒现场。
531///
532/// 代价是同名目录(`/srv/containers/*.log`)也会被认成容器来源 —— 这一层只能靠现场,
533/// 装载期不做“猜”。本函数只拦相对路径与完全不像的路径。
534pub fn is_container_log_target(target: &str) -> bool {
535    target.starts_with('/') && target.split('/').any(|segment| segment == "containers")
536}
537
538/// 内核日志导出器(W3):`journalctl -k -p 4 -o json`,**靠游标续读**。
539///
540/// 与其余导出器不同,它是**有状态**的:上一轮读到的游标落盘,下一轮从那里接着读。
541/// 契约只承诺 ID 与「可执行」;游标怎么存、失效(被 vacuum)怎么回退是采集端的事
542/// (见 `linux-server-log-coverage-plan.md` §6 W3 / D6)。
543///
544/// 为什么单独给个常量:agentd 的 `argv` 与状态处理要**按 ID 分支**,字面量散在两侧
545/// 迟早会漂(一处改名、另一处还在按旧名特判,表现就是「游标不生效、每轮重读」)。
546pub const KERNEL_LOG_EXPORTER: &str = "journalctl-kernel";
547
548/// 这条来源缺哪些日志能力(空 = 齐了)。
549///
550/// `None` = 这个 kind 不归 logs 能力管(`MetricInterval` 是指标;未知/不可执行的形态
551/// 已经被 [`is_executable_source`] 拦下,不需要第二套说法)。
552///
553/// 返回值是「桶:值」(`file_inputs:glob` / `multiline_modes:indented` /
554/// `filters:namespace_in` / `drop_if_contains:substring` / `exporters:journalctl-kernel`),
555/// 可以直接用在拒绝文案与自观测里。
556///
557/// 为什么收整条来源而不是拆成 `kind` / `target` / `multiline`:每加一个**选源/读法字段**
558/// (W2 的 `filters`、W4 的 `drop_if_contains`)都要重新讨论「要不要传」,而“忘了传”
559/// 在这里的后果是**整份 spec 被旧 agentd 拒收**(`deny_unknown_fields`),不是少采一条。
560/// 收整条来源,新增字段时编译器会直接把所有调用点指出来。
561///
562/// 为什么把判定放契约:网关(派活时)与 agentd(上报时)必须用**同一份**词表。
563/// 两边各写一份的结果是「agent 说自己支持 glob、网关按一套旧名单判它不支持」——
564/// 而且这种矛盾只能靠人去两台机器上对日志才能发现。
565pub fn missing_log_capabilities(
566    source: &WorkSpecSource,
567    declared: &LogsCapabilities,
568) -> Option<Vec<String>> {
569    let declared_has = |bucket: &[String], value: &str| bucket.iter().any(|item| item == value);
570    let kind = source.kind.as_str();
571    let target = source.target.as_str();
572
573    match kind {
574        "FileGlob" => {
575            // 不可执行的形态交给 `is_executable_source` 说,不在这里扣一顶“能力不够”的帽子。
576            if !is_file_target(target) {
577                return None;
578            }
579            let mut missing = Vec::new();
580            let need = if is_glob_path(target) {
581                FILE_INPUT_GLOB
582            } else {
583                FILE_INPUT_ABSOLUTE_PATH
584            };
585            if !declared_has(&declared.file_inputs, need) {
586                missing.push(format!("file_inputs:{need}"));
587            }
588            // `none` 是老读法(一行一条),不算一项需要协商的能力。
589            if source.multiline != "none"
590                && !declared_has(&declared.multiline_modes, &source.multiline)
591            {
592                missing.push(format!("multiline_modes:{}", source.multiline));
593            }
594            // 过滤器是**选源层**的能力(与读法正交):旧 agentd 收到 `filters` 会拒收整份
595            // spec,所以逐维度点名。
596            for dimension in source.filters.used_dimensions() {
597                if !declared_has(&declared.filters, dimension) {
598                    missing.push(format!("filters:{dimension}"));
599                }
600            }
601            // 噪音行丢弃(W4):同样是新字段,旧 agentd 会把整份 spec 当未知字段拒收。
602            // 注意:网关对这项**不裁源**,而是去掉字段降级(它是减法,少采不如多采);
603            // 这里仍如实报告“缺这项能力”,供其它消费方与诊断使用。
604            if !source.drop_if_contains.is_empty()
605                && !declared_has(&declared.drop_if_contains, DROP_IF_CONTAINS_SUBSTRING)
606            {
607                missing.push(format!("drop_if_contains:{DROP_IF_CONTAINS_SUBSTRING}"));
608            }
609            Some(missing)
610        }
611        "Exporter" => {
612            let (id, _) = parse_exporter_target(target)?;
613            Some(if declared_has(&declared.exporters, id) {
614                Vec::new()
615            } else {
616                vec![format!("exporters:{id}")]
617            })
618        }
619        _ => None,
620    }
621}
622
623/// agentd 能承接的**文件输入形态**(能力名)。
624///
625/// 与 [`is_file_target`] 同源:判定能采的形态,就是这里要声明的形态 —— 两边各写一份必然漂。
626pub const FILE_INPUT_ABSOLUTE_PATH: &str = "absolute-path";
627/// 见 [`FILE_INPUT_ABSOLUTE_PATH`]。
628pub const FILE_INPUT_GLOB: &str = "glob";
629
630/// agentd 支持的 `multiline` 模式(与 [`WorkSpecSource::multiline`] 的取值同源)。
631///
632/// * `none` / `indented`:W1;
633/// * `mysql_slow`:MySQL slow log,`# Time:` 起块(W4);
634/// * `postgres_csv`:PostgreSQL csvlog,**引号外**的换行才切记录(W4)。
635pub const MULTILINE_MODES: &[&str] = &["none", "indented", "mysql_slow", "postgres_csv"];
636
637/// 定时导出器(`Exporter`)的**已知 ID**:协议层词表,网关 / agentd / web 三侧共用。
638///
639/// 为什么词表放这里:`is_executable_source` 要判「这条 `Exporter` 目标今天真能不能采」,
640/// 而网关的采集就绪度与 agentd 的「接不接得了」必须是**同一个判据**(见 [`is_executable_source`])。
641/// 词表只收**已实现**的导出器 —— 收录一个 ID 就等于承诺 agentd 能跑它;未知 ID(旧网关发新 ID、
642/// 或写错)一律当不可采,不要「写了就算」。新增能力 = 四侧(本 crate + 网关 + agentd + web)
643/// 一起改 + 知识库把对应单元开 `active`。
644pub const EXPORTER_IDS: &[&str] = &[
645    "journalctl-unit",
646    "journalctl-shutdown",
647    "last-reboot",
648    "nft-ruleset",
649    "iptables-save",
650    "smartctl",
651    "dmesg",
652    "auditd-execve",
653    KERNEL_LOG_EXPORTER,
654];
655
656/// 把一个 `Exporter` 目标拆成 `(id, arg)`:`"dmesg:panic"` → `("dmesg", Some("panic"))`。
657///
658/// 无 `:` 时 `arg` 为 `None`;空 id 或含空白的 id 视为无效(返回 `None`)。`arg` 是**声明式的窄选项**
659/// (如 `dmesg` 的过滤键),不是命令行片段 —— 实现侧各自解释,绝不拼进 shell。
660pub fn parse_exporter_target(target: &str) -> Option<(&str, Option<&str>)> {
661    let (id, arg) = match target.split_once(':') {
662        Some((id, arg)) => (id, Some(arg)),
663        None => (target, None),
664    };
665    let id = id.trim();
666    if id.is_empty() || id.contains(char::is_whitespace) {
667        return None;
668    }
669    Some((id, arg))
670}
671
672/// 这条 `Exporter` 目标的 ID 是不是**已知且已实现**的导出器。
673pub fn is_known_exporter(target: &str) -> bool {
674    match parse_exporter_target(target) {
675        Some((id, _)) => EXPORTER_IDS.contains(&id),
676        None => false,
677    }
678}
679
680/// 一条来源今天**能不能被采**:`kind` 要 agentd 能执行,`target` 还要是它接得住的形态。
681///
682/// 为什么把两件事放在一个函数里:网关的采集就绪度(「这个面能不能派下去」)与 agentd 的
683/// 「这条来源接不接得了」必须是**同一个判据**,否则会出现「网关说可采、agent 拿到后报
684/// unsupported」这种没人能发现的矛盾。加一种 kind 支持时**只改这里**。
685pub fn is_executable_source(kind: &str, target: &str) -> bool {
686    match kind {
687        // 本地文件采集:显式绝对路径,或受支持的文件族 glob(无 `**`、无 `~`)。
688        "FileGlob" => is_file_target(target),
689        // 指标:`target` 是采集周期(如 `15s`、`60s`),不是路径。
690        "MetricInterval" => true,
691        // 定时导出器:`target` 要是**已知导出器 ID**(可带 `:arg`)。未知 ID 不可执行。
692        "Exporter" => is_known_exporter(target),
693        _ => false,
694    }
695}
696
697impl WorkSpecUnit {
698    /// 该单元里可以交给本地文件采集器的来源(`FileGlob`)。
699    ///
700    /// 其它来源(导出器 / 统一日志谓词)不是本地 tail 一个文件能承接的:
701    /// 调用方应当把它们当成**还没支持的单元**如实报出来,而不是当没看见。
702    pub fn file_sources(&self) -> Vec<&WorkSpecSource> {
703        self.sources
704            .iter()
705            .filter(|source| source.kind == "FileGlob")
706            .collect()
707    }
708
709    /// 本单元有没有 agentd 目前接不了的来源(kind 不认识,或目标不是可采的绝对路径)。
710    pub fn unsupported_sources(&self) -> Vec<&WorkSpecSource> {
711        self.sources
712            .iter()
713            .filter(|source| !is_executable_source(&source.kind, &source.target))
714            .collect()
715    }
716
717    /// 本单元至少有一条来源是 agentd **今天真能采**的。
718    ///
719    /// 「能不能采」只看这个:与解析规则(`rule_ref`)无关 —— 采原文不需要规则,
720    /// 规则只决定采下来的东西能不能被归类、抽字段。
721    pub fn has_executable_source(&self) -> bool {
722        self.sources
723            .iter()
724            .any(|source| is_executable_source(&source.kind, &source.target))
725    }
726}
727
728/// 解析 `15s` / `60s` / `5m` 这类周期写法(与目录里 `MetricInterval` 的写法一致)。
729///
730/// 只认秒与分两种后缀:目录里的值是人写的,多一个单位就多一种笔误的可能,
731/// 而解析不了时返回 `None` 会让调用方回退到自己的默认值(不静默取 0)。
732pub fn parse_interval_seconds(raw: &str) -> Option<i64> {
733    let raw = raw.trim();
734    if let Some(value) = raw.strip_suffix('s') {
735        return value.trim().parse::<i64>().ok().filter(|value| *value > 0);
736    }
737    if let Some(value) = raw.strip_suffix('m') {
738        let minutes = value.trim().parse::<i64>().ok()?;
739        // `checked_mul`:`123456789012345678m` 这类输入会让 `minutes * 60` 溢出 i64。
740        // 契约是「解析不了返回 None」(调用方回退到自己的默认值),不能让它 panic(debug)
741        // 或悄悄回绕成一个错的间隔(release)。
742        return minutes.checked_mul(60).filter(|value| *value > 0);
743    }
744    None
745}
746
747#[cfg(test)]
748mod tests {
749    use super::*;
750    use crate::capability_report::LogsCapabilities;
751
752    fn one_shot(status: &str, interruptible: bool) -> OneShotWork {
753        OneShotWork {
754            work_id: "work-1".to_string(),
755            agent_id: "agent-1".to_string(),
756            action: "upgrade".to_string(),
757            spec: "0.1.4".to_string(),
758            scheduled_at: "2026-09-23T00:00:00Z".to_string(),
759            deadline_at: "2026-09-24T00:00:00Z".to_string(),
760            timeout_seconds: 600,
761            interruptible,
762            status: status.to_string(),
763            paused_at: None,
764            paused_total_seconds: 0,
765            current_step: None,
766            completed_steps: vec![],
767            attempt: 0,
768            issued_by: "admin".to_string(),
769            issued_at: "2026-09-23T00:00:00Z".to_string(),
770        }
771    }
772
773    #[test]
774    fn terminal_one_shot_work_is_not_outstanding() {
775        // 未了结的活才进快照:终态留在库里供审计,但不必再发给 agent。
776        for status in ONE_SHOT_TERMINAL_STATUSES {
777            assert!(!one_shot(status, true).is_outstanding(), "{status}");
778        }
779        for status in ["dispatched", "accepted", "running", "paused"] {
780            assert!(one_shot(status, true).is_outstanding(), "{status}");
781        }
782    }
783
784    #[test]
785    fn only_interruptible_running_work_can_pause() {
786        // 不可中断:拒绝,而不是「尽力暂停」。
787        assert!(!one_shot("running", false).can_pause());
788        // 可中断但没在做(还没到点 / 已经了结):也没什么可暂停的。
789        assert!(!one_shot("dispatched", true).can_pause());
790        assert!(!one_shot("succeeded", true).can_pause());
791        assert!(one_shot("accepted", true).can_pause());
792        assert!(one_shot("running", true).can_pause());
793    }
794
795    #[test]
796    fn work_kind_serializes_as_the_model_names() {
797        assert_eq!(
798            serde_json::to_string(&WorkKind::Standing).expect("serialize"),
799            "\"Standing\""
800        );
801        assert_eq!(
802            serde_json::to_string(&WorkKind::OneShot).expect("serialize"),
803            "\"OneShot\""
804        );
805    }
806
807    #[test]
808    fn only_explicit_absolute_paths_are_collectable_file_targets() {
809        // `is_explicit_path` 现在只服务「单文件」语义(例如存在性裁剪只能对显式路径做)。
810        // 这个判据被两侧共用(网关的采集就绪度 + agentd 的接受逻辑),所以在这里钉死。
811        assert!(is_explicit_path("/var/log/install.log"));
812        assert!(!is_explicit_path("/var/log/wifi.log*"));
813        assert!(!is_explicit_path("/Library/Logs/DiagnosticReports/*.ips"));
814        assert!(!is_explicit_path("~/Library/Logs/Homebrew/*"));
815        assert!(!is_explicit_path("relative/app.log"));
816    }
817
818    #[test]
819    fn file_targets_accept_single_level_globs_and_reject_recursion() {
820        // W1:`FileGlob` 判据从「显式路径」放宽为「绝对路径,允许通配」。
821        assert!(is_glob_path("/var/log/containers/*.log"));
822        assert!(is_glob_path("/var/log/pods/*/*/*.log"));
823        assert!(is_glob_path("/var/lib/postgresql/*/data/log/*.csv"));
824        assert!(is_file_target("/var/log/containers/*.log"));
825        // 显式路径仍是合法文件目标(单文件 input 走它)。
826        assert!(is_file_target("/var/log/auth.log"));
827        // `**` 不展开:采集端只扫固定前缀目录,接受它只会在采集端变成每轮 IO 错误。
828        assert!(!is_glob_path("/var/log/**/*.log"));
829        assert!(!is_file_target("/var/log/**/*.log"));
830        // `~` / 相对路径不展开。
831        assert!(!is_glob_path("~/Library/Logs/*.log"));
832        assert!(!is_file_target("relative/*.log"));
833        // 空目标不是文件目标。
834        assert!(!is_file_target(""));
835    }
836
837    #[test]
838    fn executability_needs_both_a_supported_kind_and_a_supported_target() {
839        // 指标:`target` 是周期不是路径,不管显式路径那一条。
840        assert!(is_executable_source("MetricInterval", "15s"));
841        // 文件:显式路径与单层 glob 都可执行;`**` / `~` 不可执行(网关不能把它们报成“可采”)。
842        assert!(is_executable_source("FileGlob", "/var/log/app.log"));
843        assert!(is_executable_source(
844            "FileGlob",
845            "/var/log/containers/*.log"
846        ));
847        assert!(!is_executable_source("FileGlob", "/var/log/**/*.log"));
848        assert!(!is_executable_source("FileGlob", "~/logs/*.log"));
849        // 导出器:kind 对了,ID 还得是**已知的**(`last,lastb` 是 macOS 侧、尚未实现)。
850        assert!(is_executable_source("Exporter", "smartctl"));
851        assert!(is_executable_source("Exporter", "dmesg:panic"));
852        assert!(!is_executable_source("Exporter", "last,lastb"));
853        // 还没实现的 kind:一律不可执行。
854        assert!(!is_executable_source("UnifiedLogPredicate", "syspolicyd"));
855    }
856
857    #[test]
858    fn exporter_targets_split_into_a_known_id_and_an_optional_arg() {
859        assert_eq!(parse_exporter_target("smartctl"), Some(("smartctl", None)));
860        assert_eq!(
861            parse_exporter_target("dmesg:panic"),
862            Some(("dmesg", Some("panic")))
863        );
864        // 空 id / 含空白的 id 不是合法 ID。
865        assert_eq!(parse_exporter_target(":panic"), None);
866        assert_eq!(parse_exporter_target(" dm esg"), None);
867        // 判定只看冒号前的 ID,`arg` 不参与。
868        assert!(is_known_exporter("dmesg:nvidia-xid"));
869        assert!(!is_known_exporter("nope"));
870    }
871
872    #[test]
873    fn the_kernel_log_exporter_is_in_the_contract_vocabulary() {
874        // 词表只增不改名:这一条丢了,网关会把内核单元判成「不可采」(`active` 直接被拦),
875        // agentd 也会把它报成 unsupported。
876        assert!(EXPORTER_IDS.contains(&KERNEL_LOG_EXPORTER));
877        assert!(is_known_exporter(KERNEL_LOG_EXPORTER));
878        assert!(is_executable_source("Exporter", KERNEL_LOG_EXPORTER));
879        // 前缀相似但不是同一个 ID:不能靠 starts_with 之类的模糊匹配混过去。
880        assert!(!is_known_exporter("journalctl-kernelx"));
881    }
882
883    // ── 能力协商(D7):词表与判定同源 ──
884
885    /// 一条测试来源:只关心 kind / target / multiline 时用它(不带 filters / exclude)。
886    fn source(kind: &str, target: &str, multiline: &str) -> WorkSpecSource {
887        WorkSpecSource {
888            kind: kind.to_string(),
889            target: target.to_string(),
890            multiline: multiline.to_string(),
891            exclude_globs: Vec::new(),
892            filters: ContainerFilters::default(),
893            drop_if_contains: Vec::new(),
894        }
895    }
896
897    /// 一条容器来源(`FileGlob` + 给定过滤器)。
898    fn container_source(target: &str, filters: ContainerFilters) -> WorkSpecSource {
899        WorkSpecSource {
900            filters,
901            ..source("FileGlob", target, "none")
902        }
903    }
904
905    /// [`missing_log_capabilities`] 的简写:不带筛选条件的来源。
906    fn missing(
907        kind: &str,
908        target: &str,
909        multiline: &str,
910        declared: &LogsCapabilities,
911    ) -> Option<Vec<String>> {
912        missing_log_capabilities(&source(kind, target, multiline), declared)
913    }
914
915    /// 一个“什么都支持”的 agent 声明(agentd 上报的就是这一份的全集)。
916    fn full_logs() -> LogsCapabilities {
917        LogsCapabilities {
918            file_inputs: vec![
919                FILE_INPUT_ABSOLUTE_PATH.to_string(),
920                FILE_INPUT_GLOB.to_string(),
921            ],
922            multiline_modes: MULTILINE_MODES
923                .iter()
924                .map(|mode| mode.to_string())
925                .collect(),
926            exporters: EXPORTER_IDS.iter().map(|id| id.to_string()).collect(),
927            filters: CONTAINER_FILTERS.iter().map(|di| di.to_string()).collect(),
928            drop_if_contains: DROP_IF_CONTAINS_MODES
929                .iter()
930                .map(|m| m.to_string())
931                .collect(),
932            ..LogsCapabilities::default()
933        }
934    }
935
936    #[test]
937    fn capability_gaps_name_the_bucket_and_value() {
938        let old_agent = LogsCapabilities {
939            // W1 之前的 agentd:只会显式路径,不认识导出器能力。
940            file_inputs: vec![FILE_INPUT_ABSOLUTE_PATH.to_string()],
941            ..LogsCapabilities::default()
942        };
943        assert_eq!(
944            missing("FileGlob", "/var/log/app.log", "none", &old_agent),
945            Some(Vec::new())
946        );
947        assert_eq!(
948            missing("FileGlob", "/var/log/app/*.log", "none", &old_agent),
949            Some(vec!["file_inputs:glob".to_string()])
950        );
951        // 多行模式也是能力:说错了会把记录拼碎。
952        assert_eq!(
953            missing("FileGlob", "/var/log/a.log", "indented", &old_agent),
954            Some(vec!["multiline_modes:indented".to_string()])
955        );
956        // 导出器是具名能力:新 ID(如 W3 的内核日志)旧 agent 一定不认识。
957        assert_eq!(
958            missing("Exporter", KERNEL_LOG_EXPORTER, "none", &old_agent),
959            Some(vec![format!("exporters:{KERNEL_LOG_EXPORTER}")])
960        );
961        // `arg` 不参与判定(与 `is_known_exporter` 同口径)。
962        assert_eq!(
963            missing("Exporter", "dmesg:panic", "none", &full_logs()),
964            Some(Vec::new())
965        );
966        // 空的过滤器不要求任何能力:它不上线(`skip_serializing_if`)。
967        assert_eq!(
968            missing("FileGlob", "/var/log/containers/*.log", "none", &old_agent),
969            Some(vec!["file_inputs:glob".to_string()])
970        );
971    }
972
973    #[test]
974    fn container_filter_dimensions_are_negotiated_separately() {
975        // 0.9.4 的 agentd:已经有 glob / multiline / exporters,但**不认识 `filters`**。
976        // 带 filters 的来源必须被点名 —— 否则那份 spec 会被 `deny_unknown_fields` 整份拒收。
977        let before_w2 = LogsCapabilities {
978            filters: Vec::new(),
979            ..full_logs()
980        };
981        let namespace_only = ContainerFilters {
982            namespace_in: vec!["prod".to_string()],
983            pod_not_in: Vec::new(),
984
985            name_in: Vec::new(),
986            name_not_in: Vec::new(),
987        };
988        let target = "/var/log/containers/*.log";
989        assert_eq!(
990            missing_log_capabilities(&container_source(target, namespace_only), &before_w2),
991            Some(vec!["filters:namespace_in".to_string()])
992        );
993        // 两个维度都用到 → 两个都点名(按字段顺序,文案可对账)。
994        let both = ContainerFilters {
995            namespace_in: vec!["prod".to_string()],
996            pod_not_in: vec!["debug-pod".to_string()],
997
998            name_in: Vec::new(),
999            name_not_in: Vec::new(),
1000        };
1001        assert_eq!(
1002            missing_log_capabilities(&container_source(target, both.clone()), &before_w2),
1003            Some(vec![
1004                "filters:namespace_in".to_string(),
1005                "filters:pod_not_in".to_string(),
1006            ])
1007        );
1008        // 声明了这两个维度就齐了。
1009        assert_eq!(
1010            missing_log_capabilities(&container_source(target, both), &full_logs()),
1011            Some(Vec::new())
1012        );
1013        // 能力名就是过滤器的字段名(网关文案与目录写法能一一对上)。
1014        assert_eq!(
1015            ContainerFilters {
1016                namespace_in: vec!["a".to_string()],
1017                pod_not_in: vec!["b".to_string()],
1018
1019                name_in: Vec::new(),
1020                name_not_in: Vec::new(),
1021            }
1022            .used_dimensions(),
1023            vec![FILTER_NAMESPACE_IN, FILTER_POD_NOT_IN]
1024        );
1025        assert!(ContainerFilters::default().used_dimensions().is_empty());
1026    }
1027
1028    #[test]
1029    fn noise_drop_needles_are_a_capability_of_their_own() {
1030        // W4 之前的 agentd:有 glob / filters,但**不认识 `drop_if_contains`**。
1031        // 不点名就会把整份 spec 送给一个 `deny_unknown_fields` 的旧版本。
1032        let before_w4 = LogsCapabilities {
1033            drop_if_contains: Vec::new(),
1034            ..full_logs()
1035        };
1036        let mut source = source("FileGlob", "/var/log/auth.log", "none");
1037        source.drop_if_contains = vec!["pam_unix(cron:session)".to_string()];
1038        assert_eq!(
1039            missing_log_capabilities(&source, &before_w4),
1040            Some(vec!["drop_if_contains:substring".to_string()])
1041        );
1042        // 声明了(本版只有子串一种)就齐了。
1043        assert_eq!(
1044            missing_log_capabilities(&source, &full_logs()),
1045            Some(Vec::new())
1046        );
1047    }
1048
1049    #[test]
1050    fn drop_if_contains_is_substring_shaped_and_stays_out_of_the_wire_when_empty() {
1051        // 空列表不上线(与 `exclude_globs` / `filters` 同一条纪律)。
1052        let mut source = source("FileGlob", "/var/log/auth.log", "none");
1053        assert!(
1054            !serde_json::to_string(&source)
1055                .expect("serialize")
1056                .contains("drop_if_contains")
1057        );
1058
1059        source.drop_if_contains = vec!["pam_unix(cron:session)".to_string()];
1060        let json = serde_json::to_string(&source).expect("serialize");
1061        assert!(
1062            json.contains(r#""drop_if_contains":["pam_unix(cron:session)"]"#),
1063            "{json}"
1064        );
1065        assert_eq!(
1066            serde_json::from_str::<WorkSpecSource>(&json).expect("parse"),
1067            source
1068        );
1069
1070        // 形状校验:空串 / 首尾空白 / 控制字符 / 过长 / 太多 / 重复都要拒。
1071        assert!(validate_drop_if_contains(&["ok".to_string()]).is_ok());
1072        assert!(validate_drop_if_contains(&[]).is_ok());
1073        for bad in ["", " x", "x ", "line\nbreak", " nul\0"] {
1074            assert!(
1075                validate_drop_if_contains(&[bad.to_string()]).is_err(),
1076                "{bad:?} should be rejected"
1077            );
1078        }
1079        assert!(validate_drop_if_contains(&["x".repeat(DROP_IF_CONTAINS_MAX_BYTES + 1)]).is_err());
1080        let too_many: Vec<String> = (0..=DROP_IF_CONTAINS_MAX_ITEMS)
1081            .map(|i| format!("needle-{i}"))
1082            .collect();
1083        assert!(validate_drop_if_contains(&too_many).is_err());
1084        assert!(validate_drop_if_contains(&["dup".to_string(), "dup".to_string()]).is_err());
1085    }
1086
1087    #[test]
1088    fn the_new_multiline_modes_are_in_the_contract_vocabulary() {
1089        // 网关装载期与 agentd 配置校验都看这份词表:漏一项,目录里写了也会被当成非法。
1090        for mode in ["mysql_slow", "postgres_csv"] {
1091            assert!(MULTILINE_MODES.contains(&mode), "{mode}");
1092        }
1093        // 新读法一律要求能力声明(`none` 除外)。
1094        let old_agent = LogsCapabilities {
1095            multiline_modes: vec!["none".to_string(), "indented".to_string()],
1096            ..full_logs()
1097        };
1098        assert_eq!(
1099            missing(
1100                "FileGlob",
1101                "/var/log/postgresql/x.csv",
1102                "postgres_csv",
1103                &old_agent
1104            ),
1105            Some(vec!["multiline_modes:postgres_csv".to_string()])
1106        );
1107        assert_eq!(
1108            missing(
1109                "FileGlob",
1110                "/var/log/mysql/slow.log",
1111                "mysql_slow",
1112                &old_agent
1113            ),
1114            Some(vec!["multiline_modes:mysql_slow".to_string()])
1115        );
1116    }
1117
1118    #[test]
1119    fn an_exporter_id_outside_the_vocabulary_is_reported_as_missing() {
1120        // 写错 ID / 未来 ID 遇到旧 agent:都是“没声明这个能力”,不能当成“不归我管”放过 ——
1121        // 放过的后果是派下去、agent 回 unsupported。
1122        assert_eq!(
1123            missing("Exporter", "journalctl-kernelx", "none", &full_logs()),
1124            Some(vec!["exporters:journalctl-kernelx".to_string()])
1125        );
1126        // 带 `arg` 也一样:只按 ID 判。
1127        assert_eq!(
1128            missing("Exporter", "dmesg:panic", "none", &old_style_logs()),
1129            Some(vec!["exporters:dmesg".to_string()])
1130        );
1131    }
1132
1133    /// 只声明了“显式路径 + 任何导出器”这类旧能力的 agent。
1134    fn old_style_logs() -> LogsCapabilities {
1135        LogsCapabilities {
1136            file_inputs: vec![FILE_INPUT_ABSOLUTE_PATH.to_string()],
1137            exporters: vec!["smartctl".to_string()],
1138            ..LogsCapabilities::default()
1139        }
1140    }
1141
1142    #[test]
1143    fn capability_checks_say_nothing_about_things_they_do_not_own() {
1144        // 指标不走 logs 能力;不可执行的形态由 `is_executable_source` 说,不重复扣帽子。
1145        assert_eq!(missing("MetricInterval", "15s", "none", &full_logs()), None);
1146        assert_eq!(missing("FileGlob", "~/a/*.log", "none", &full_logs()), None);
1147        assert_eq!(
1148            missing("UnifiedLogPredicate", "syspolicyd", "none", &full_logs()),
1149            None
1150        );
1151    }
1152
1153    #[test]
1154    fn a_fully_declared_agent_is_missing_nothing_the_contract_calls_executable() {
1155        // 防漂:契约说“能执行”的每一种形态,声明了全集就必须不报缺。
1156        // 新增一个导出器 ID / 一种 multiline 模式 / 一个过滤维度而忘了加到常量里,这条会红。
1157        let full = full_logs();
1158        for target in ["/var/log/a.log", "/var/log/containers/*.log"] {
1159            assert_eq!(
1160                missing("FileGlob", target, "none", &full),
1161                Some(Vec::new()),
1162                "{target}"
1163            );
1164        }
1165        for mode in MULTILINE_MODES {
1166            assert_eq!(
1167                missing("FileGlob", "/var/log/a.log", mode, &full),
1168                Some(Vec::new()),
1169                "{mode}"
1170            );
1171        }
1172        for id in EXPORTER_IDS {
1173            assert_eq!(
1174                missing("Exporter", id, "none", &full),
1175                Some(Vec::new()),
1176                "{id}"
1177            );
1178        }
1179        // 每一个过滤维度都真的能“声明全了就不报缺”。
1180        let filters = ContainerFilters {
1181            namespace_in: vec!["prod".to_string()],
1182            pod_not_in: vec!["debug-pod".to_string()],
1183            name_in: vec!["mysql".to_string()],
1184            name_not_in: vec!["fluent-bit".to_string()],
1185        };
1186        assert_eq!(
1187            filters.used_dimensions(),
1188            CONTAINER_FILTERS,
1189            "`used_dimensions` 与 `CONTAINER_FILTERS` 漂了"
1190        );
1191        assert_eq!(
1192            missing_log_capabilities(
1193                &container_source("/var/log/containers/*.log", filters),
1194                &full
1195            ),
1196            Some(Vec::new())
1197        );
1198    }
1199
1200    #[test]
1201    fn every_filter_dimension_alone_pins_is_empty_serialization_and_capability_name() {
1202        // 一条测试同时钉住三处最容易被新增维度漏掉的同源:
1203        //   1. `is_empty`(= `skip_serializing_if` 的判据)—— 漏了会让整个 `filters` 被静默丢掉,
1204        //      来源按“全收”执行(策略被无声撤销);
1205        //   2. serde 键名(报文里的字段名);
1206        //   3. `used_dimensions()`(网关裁源用的能力名)。
1207        // 只填一维时,三者必须都只反映这一维。
1208        let cases: [(ContainerFilters, &'static str); 4] = [
1209            (
1210                ContainerFilters {
1211                    namespace_in: vec!["prod".to_string()],
1212                    ..Default::default()
1213                },
1214                FILTER_NAMESPACE_IN,
1215            ),
1216            (
1217                ContainerFilters {
1218                    pod_not_in: vec!["debug-pod".to_string()],
1219                    ..Default::default()
1220                },
1221                FILTER_POD_NOT_IN,
1222            ),
1223            (
1224                ContainerFilters {
1225                    name_in: vec!["mysql".to_string()],
1226                    ..Default::default()
1227                },
1228                FILTER_NAME_IN,
1229            ),
1230            (
1231                ContainerFilters {
1232                    name_not_in: vec!["fluent-bit".to_string()],
1233                    ..Default::default()
1234                },
1235                FILTER_NAME_NOT_IN,
1236            ),
1237        ];
1238        for (filters, dimension) in cases {
1239            assert!(
1240                !filters.is_empty(),
1241                "{dimension} 非空时 is_empty 必须为 false"
1242            );
1243            assert_eq!(filters.used_dimensions(), vec![dimension], "{dimension}");
1244            let json = serde_json::to_value(&filters).expect("serialize");
1245            let object = json.as_object().expect("object");
1246            assert_eq!(
1247                object.keys().map(String::as_str).collect::<Vec<_>>(),
1248                vec![dimension],
1249                "{dimension}:序列化键名必须与能力名逐字一致"
1250            );
1251            assert_eq!(
1252                object[dimension].as_array().map(Vec::len),
1253                Some(1),
1254                "{dimension}:该维的值要完整发出去"
1255            );
1256        }
1257        // 全空 = 整个字段不出现(旧 agent 的 `deny_unknown_fields` 靠这个不被惊动)。
1258        assert!(ContainerFilters::default().is_empty());
1259        assert_eq!(
1260            serde_json::to_value(ContainerFilters::default()).expect("serialize"),
1261            serde_json::json!({})
1262        );
1263    }
1264
1265    // ── 工作参数(`spec`)的编码 ──
1266
1267    fn spec() -> WorkSpec {
1268        WorkSpec {
1269            units: vec![
1270                WorkSpecUnit {
1271                    unit_id: "mac-host-metrics".to_string(),
1272                    capability: "collect_metrics".to_string(),
1273                    rule_ref: "agent_uplink".to_string(),
1274                    requires_privilege: "none".to_string(),
1275                    sources: vec![WorkSpecSource {
1276                        kind: "MetricInterval".to_string(),
1277                        target: "15s".to_string(),
1278                        multiline: "none".to_string(),
1279                        exclude_globs: Vec::new(),
1280                        filters: ContainerFilters::default(),
1281                        drop_if_contains: Vec::new(),
1282                    }],
1283                },
1284                WorkSpecUnit {
1285                    unit_id: "mac-privacy-tcc".to_string(),
1286                    capability: "collect_logs".to_string(),
1287                    rule_ref: "macos/tcc".to_string(),
1288                    requires_privilege: "fda".to_string(),
1289                    sources: vec![
1290                        WorkSpecSource {
1291                            kind: "Exporter".to_string(),
1292                            target: "sqlite-snapshot(TCC.db)".to_string(),
1293                            multiline: "none".to_string(),
1294                            exclude_globs: Vec::new(),
1295                            filters: ContainerFilters::default(),
1296                            drop_if_contains: Vec::new(),
1297                        },
1298                        WorkSpecSource {
1299                            kind: "FileGlob".to_string(),
1300                            // 显式单路径:单文件采集走 `startup_position` / 检查点的单文件语义。
1301                            target: "/var/log/tccd.log".to_string(),
1302                            // 多行格式是这条日志的固有属性,跟着来源走。
1303                            multiline: "indented".to_string(),
1304                            exclude_globs: Vec::new(),
1305                            filters: ContainerFilters::default(),
1306                            drop_if_contains: Vec::new(),
1307                        },
1308                    ],
1309                },
1310            ],
1311        }
1312    }
1313
1314    #[test]
1315    fn spec_round_trips_and_reports_what_agentd_can_do() {
1316        let encoded = spec().encode().expect("encode");
1317        let decoded = WorkSpec::parse(&encoded).expect("parse");
1318        assert_eq!(decoded, spec());
1319
1320        assert!(decoded.collects_logs());
1321        // 取了最密的周期:要得最急的才是上送频率的下界。
1322        assert_eq!(decoded.metric_interval_seconds(), Some(15));
1323        // 可本地 tail 的来源挑得出来,接不了的来源也报得出来(而不是当没看见)。
1324        let files = decoded.units[1].file_sources();
1325        assert_eq!(files.len(), 1);
1326        assert_eq!(files[0].target, "/var/log/tccd.log");
1327        assert_eq!(files[0].multiline, "indented");
1328        assert_eq!(decoded.units[1].unsupported_sources().len(), 1);
1329        assert_eq!(decoded.units[1].unsupported_sources()[0].kind, "Exporter");
1330    }
1331
1332    #[test]
1333    fn a_glob_file_source_is_collectable_but_recursive_globs_are_not() {
1334        // W1 起:单层 glob 是采集端能执行的来源(容器日志就靠它)。
1335        let mut unit = WorkSpecUnit {
1336            unit_id: "linux-container-stdout".to_string(),
1337            capability: "collect_logs".to_string(),
1338            rule_ref: String::new(),
1339            requires_privilege: "root".to_string(),
1340            sources: vec![WorkSpecSource {
1341                kind: "FileGlob".to_string(),
1342                target: "/var/log/containers/*.log".to_string(),
1343                multiline: "none".to_string(),
1344                exclude_globs: vec!["/var/log/containers/*_kube-system_*.log".to_string()],
1345                filters: ContainerFilters::default(),
1346                drop_if_contains: Vec::new(),
1347            }],
1348        };
1349        assert_eq!(unit.file_sources().len(), 1, "它是一条文件来源");
1350        assert!(unit.unsupported_sources().is_empty());
1351        assert!(unit.has_executable_source());
1352
1353        // `**` 仍不可执行:递归展开没实现,接受它就等于承诺一个采不到的面。
1354        unit.sources[0].target = "/var/log/**/*.log".to_string();
1355        assert_eq!(unit.unsupported_sources().len(), 1);
1356        assert!(!unit.has_executable_source());
1357    }
1358
1359    #[test]
1360    fn exclude_globs_round_trip_and_stay_out_of_the_wire_when_empty() {
1361        let mut source = WorkSpecSource {
1362            kind: "FileGlob".to_string(),
1363            target: "/var/log/containers/*.log".to_string(),
1364            multiline: "none".to_string(),
1365            exclude_globs: Vec::new(),
1366            filters: ContainerFilters::default(),
1367            drop_if_contains: Vec::new(),
1368        };
1369        // 空排除项不进 JSON:旧 agent 的 `WorkSpecSource` 是 `deny_unknown_fields` 的。
1370        assert_eq!(
1371            serde_json::to_string(&source).expect("serialize"),
1372            r#"{"kind":"FileGlob","target":"/var/log/containers/*.log","multiline":"none"}"#
1373        );
1374
1375        source.exclude_globs = vec!["/var/log/containers/*_kube-system_*.log".to_string()];
1376        let json = serde_json::to_string(&source).expect("serialize");
1377        assert_eq!(
1378            serde_json::from_str::<WorkSpecSource>(&json).expect("parse"),
1379            source
1380        );
1381        // 老网关发来的来源没有这两个字段:默认必须能解出来。
1382        let old = r#"{"kind":"FileGlob","target":"/a/*"}"#;
1383        let parsed: WorkSpecSource = serde_json::from_str(old).expect("parse legacy source");
1384        assert!(parsed.exclude_globs.is_empty());
1385        assert!(parsed.filters.is_empty());
1386        assert_eq!(parsed.multiline, "none");
1387    }
1388
1389    #[test]
1390    fn container_filters_round_trip_and_stay_out_of_the_wire_when_empty() {
1391        let mut source = WorkSpecSource {
1392            kind: "FileGlob".to_string(),
1393            target: "/var/log/containers/*.log".to_string(),
1394            multiline: "none".to_string(),
1395            exclude_globs: Vec::new(),
1396            filters: ContainerFilters::default(),
1397            drop_if_contains: Vec::new(),
1398        };
1399        // 空过滤器不进 JSON(与 exclude_globs 同一条纪律:旧 agent 是 deny_unknown_fields)。
1400        let json = serde_json::to_string(&source).expect("serialize");
1401        assert!(!json.contains("filters"), "{json}");
1402
1403        source.filters = ContainerFilters {
1404            namespace_in: vec!["prod".to_string()],
1405            pod_not_in: vec!["debug-pod".to_string()],
1406
1407            name_in: Vec::new(),
1408            name_not_in: Vec::new(),
1409        };
1410        let json = serde_json::to_string(&source).expect("serialize");
1411        assert!(
1412            json.contains(r#""filters":{"namespace_in":["prod"],"pod_not_in":["debug-pod"]}"#),
1413            "{json}"
1414        );
1415        assert_eq!(
1416            serde_json::from_str::<WorkSpecSource>(&json).expect("parse"),
1417            source
1418        );
1419
1420        // 只给一半也要能解:另一侧默认空。
1421        let half = r#"{"kind":"FileGlob","target":"/var/log/containers/*.log","filters":{"namespace_in":["prod"]}}"#;
1422        let parsed: WorkSpecSource = serde_json::from_str(half).expect("parse half filters");
1423        assert_eq!(parsed.filters.namespace_in, vec!["prod".to_string()]);
1424        assert!(parsed.filters.pod_not_in.is_empty());
1425    }
1426
1427    #[test]
1428    fn an_explicitly_empty_filters_object_is_not_serialized() {
1429        // 策展/页面可能显式写一个空对象(`filters = {}`):它仍然等于“不过滤”,
1430        // 不能在线上多出一个键 —— 旧 agent 是 `deny_unknown_fields` 的。
1431        let source = WorkSpecSource {
1432            kind: "FileGlob".to_string(),
1433            target: "/var/log/containers/*.log".to_string(),
1434            multiline: "none".to_string(),
1435            exclude_globs: Vec::new(),
1436            filters: ContainerFilters {
1437                namespace_in: Vec::new(),
1438                pod_not_in: Vec::new(),
1439
1440                name_in: Vec::new(),
1441                name_not_in: Vec::new(),
1442            },
1443            drop_if_contains: Vec::new(),
1444        };
1445        let json = serde_json::to_string(&source).expect("serialize");
1446        assert!(!json.contains("filters"), "{json}");
1447    }
1448
1449    #[test]
1450    fn name_filters_are_a_capability_of_their_own() {
1451        // Docker 载体上的容器名过滤(文件名里只有容器 id):单独两个能力维度。
1452        // 旧 agentd 不声明 → 网关裁掉带该过滤的来源,而不是整份拒收。
1453        let include = ContainerFilters {
1454            name_in: vec!["mysql".to_string()],
1455            ..ContainerFilters::default()
1456        };
1457        assert_eq!(include.used_dimensions(), vec![FILTER_NAME_IN]);
1458        let exclude = ContainerFilters {
1459            name_not_in: vec!["fluent-bit".to_string()],
1460            ..ContainerFilters::default()
1461        };
1462        assert_eq!(exclude.used_dimensions(), vec![FILTER_NAME_NOT_IN]);
1463
1464        // 值是**精确名字**:通配符/空串在装载期就要拦下。
1465        assert!(
1466            ContainerFilters {
1467                name_in: vec!["mysql*".to_string()],
1468                ..ContainerFilters::default()
1469            }
1470            .validate()
1471            .is_err()
1472        );
1473        assert!(
1474            ContainerFilters {
1475                name_not_in: vec![" ".to_string()],
1476                ..ContainerFilters::default()
1477            }
1478            .validate()
1479            .is_err()
1480        );
1481        assert!(include.validate().is_ok());
1482    }
1483
1484    #[test]
1485    fn container_filters_keep_values_verbatim() {
1486        // 名字**不做归一化**(不折叠大小写、不去前后缀):k8s 名字永远小写,
1487        // 归一化反而会把写错的值当成能用。逐字保存、逐字比较(比较在 agentd)。
1488        let filters = ContainerFilters {
1489            namespace_in: vec!["Prod".to_string()],
1490            pod_not_in: vec!["debug-pod".to_string()],
1491
1492            name_in: Vec::new(),
1493            name_not_in: Vec::new(),
1494        };
1495        let json = serde_json::to_string(&filters).expect("serialize");
1496        let parsed: ContainerFilters = serde_json::from_str(&json).expect("parse");
1497        assert_eq!(parsed.namespace_in, vec!["Prod".to_string()]);
1498        assert_eq!(parsed.pod_not_in, vec!["debug-pod".to_string()]);
1499    }
1500
1501    #[test]
1502    fn container_filters_reject_unknown_keys() {
1503        // `deny_unknown_fields`:拼错一个键(`namespaces`)不能静默当空过滤器 ——
1504        // 那会让策展人以为「只采 prod」,实际全采。
1505        assert!(serde_json::from_str::<ContainerFilters>(r#"{"namespaces":["prod"]}"#).is_err());
1506        assert!(serde_json::from_str::<ContainerFilters>(r#"{"namespace_in":["prod"]}"#).is_ok());
1507    }
1508
1509    #[test]
1510    fn container_filters_reject_values_that_can_never_match() {
1511        let ok = |namespace: &[&str], pods: &[&str]| ContainerFilters {
1512            namespace_in: namespace.iter().map(|v| v.to_string()).collect(),
1513            pod_not_in: pods.iter().map(|v| v.to_string()).collect(),
1514
1515            name_in: Vec::new(),
1516            name_not_in: Vec::new(),
1517        };
1518
1519        assert!(
1520            ok(&["prod", "kube-system"], &["debug-pod"])
1521                .validate()
1522                .is_ok()
1523        );
1524        assert!(ok(&[], &[]).is_empty());
1525        // 这些一定对不上(过滤器存的是**精确名字**,不是 pattern):错在最早的入口就说。
1526        assert!(ok(&[""], &[]).validate().is_err());
1527        assert!(ok(&[" prod"], &[]).validate().is_err());
1528        assert!(ok(&["prod*"], &[]).validate().is_err());
1529        assert!(ok(&[], &["debug?pod"]).validate().is_err());
1530        assert!(ok(&[&"x".repeat(254)], &[]).validate().is_err());
1531    }
1532
1533    #[test]
1534    fn a_source_without_multiline_decodes_as_single_line() {
1535        // 老网关发来的 spec 没有 `multiline`:默认必须是一行一条。
1536        // 取错默认值会把多行日志**粘**成一条 —— 那是无声的内容损坏,不是格式问题。
1537        let json = r#"{"units":[{"unit_id":"u","capability":"collect_logs","sources":[{"kind":"FileGlob","target":"/a/*"}]}]}"#;
1538        let spec = WorkSpec::parse(json).expect("parse");
1539        assert_eq!(spec.units[0].sources[0].multiline, "none");
1540        // 再编码出去会把默认值写实:新网关发的 spec 字段总是齐的。
1541        assert_eq!(
1542            spec.encode().expect("encode"),
1543            r#"{"units":[{"unit_id":"u","capability":"collect_logs","rule_ref":"","requires_privilege":"","sources":[{"kind":"FileGlob","target":"/a/*","multiline":"none"}]}]}"#
1544        );
1545    }
1546
1547    #[test]
1548    fn a_broken_spec_is_an_error_not_an_empty_work() {
1549        // 参数坏了与「没事可做」是两回事:前者要人去看,后者什么都不用做。
1550        assert!(WorkSpec::parse("mac-host-metrics").is_err());
1551        assert!(WorkSpec::parse("{").is_err());
1552        // 空工作本身是合法的(能表示「这个面暂时没东西可采」)。
1553        assert!(WorkSpec::parse(r#"{"units":[]}"#).unwrap().units.is_empty());
1554        assert_eq!(
1555            WorkSpec::parse(r#"{"units":[]}"#)
1556                .unwrap()
1557                .metric_interval_seconds(),
1558            None
1559        );
1560    }
1561
1562    #[test]
1563    fn interval_parsing_accepts_seconds_and_minutes_only() {
1564        assert_eq!(parse_interval_seconds("15s"), Some(15));
1565        assert_eq!(parse_interval_seconds(" 5s "), Some(5));
1566        assert_eq!(parse_interval_seconds("5m"), Some(300));
1567        // 认不出来的回 None(调用方回退到自己的默认值),而不是静默当 0。
1568        assert_eq!(parse_interval_seconds("15"), None);
1569        assert_eq!(parse_interval_seconds("0s"), None);
1570        assert_eq!(parse_interval_seconds(""), None);
1571    }
1572
1573    #[test]
1574    fn interval_parsing_never_overflows_on_huge_values() {
1575        // 契约是「解析不了返回 None」,不是 panic:溢出在 debug 下 panic、release 下回绕成一个
1576        // 错误的间隔 —— 两个后果都不能接受。这是两侧都要解析的字节,输入可能来自远端。
1577        assert_eq!(parse_interval_seconds("922337203685477580m"), None);
1578        assert_eq!(parse_interval_seconds("153722867280912931m"), None);
1579        // 秒分支本来就靠 parse 失败兜底。
1580        assert_eq!(parse_interval_seconds("99999999999999999999s"), None);
1581        // 合法但很大的分钟值仍要算得出来(不误伤)。
1582        assert_eq!(parse_interval_seconds("600m"), Some(36_000));
1583    }
1584
1585    #[test]
1586    fn metric_interval_ignores_unparseable_targets_instead_of_treating_them_as_zero() {
1587        // 认不出的周期不能静默当 0(0 会被当成「无限密」),而要如实跳过,只取能解析的最密值。
1588        let unit = |target: &str| WorkSpecUnit {
1589            unit_id: "u".to_string(),
1590            capability: "collect_metrics".to_string(),
1591            rule_ref: String::new(),
1592            requires_privilege: String::new(),
1593            sources: vec![WorkSpecSource {
1594                kind: "MetricInterval".to_string(),
1595                target: target.to_string(),
1596                multiline: "none".to_string(),
1597                exclude_globs: Vec::new(),
1598                filters: ContainerFilters::default(),
1599                drop_if_contains: Vec::new(),
1600            }],
1601        };
1602        let mixed = WorkSpec {
1603            units: vec![unit("garbage"), unit("30s")],
1604        };
1605        assert_eq!(mixed.metric_interval_seconds(), Some(30));
1606
1607        let all_bad = WorkSpec {
1608            units: vec![unit("nope")],
1609        };
1610        assert_eq!(all_bad.metric_interval_seconds(), None);
1611    }
1612}