rust: Timing Functions Pattern

项目结构:

rust 复制代码
//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : process_dtos.rs
//! DTO(数据传输对象)定义
//!
//! 用于跨层(表现层 → 接口层 → 应用层 → 领域层)传递数据,仅承载数据、无业务逻辑。
//! - `ProcessRequestDto`:业务流程执行请求
//! - `ProcessResponseDto`:业务流程执行响应

use crate::domain::entities::jewelry::Jewelry;

/// 业务流程执行请求 DTO
///
/// `department` / `operator` 为溯源扩展字段(预留给审计场景),
/// 当前演示中同事自行声明所属部门,未读取该两字段。
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct ProcessRequestDto {
    /// 流程类型标识(如 PROCUREMENT / DESIGN / PRODUCTION 等)
    pub process_type: String,
    /// 关联珠宝实体
    pub jewelry: Jewelry,
    /// 发起部门(如 采购部 / 设计部 / 生产部 等)
    pub department: String,
    /// 操作人(如 Mediator 中介者 / 具体岗位名称)
    pub operator: String,
}

impl ProcessRequestDto {
    /// 创建业务流程执行请求 DTO
    ///
    /// # 参数
    /// - `process_type`:流程类型标识
    /// - `jewelry`:关联珠宝
    /// - `department`:发起部门
    /// - `operator`:操作人
    ///
    /// # 返回
    /// 请求 DTO
    pub fn new(process_type: &str, jewelry: Jewelry, department: &str, operator: &str) -> Self {
        Self {
            process_type: process_type.to_string(),
            jewelry,
            department: department.to_string(),
            operator: operator.to_string(),
        }
    }
}

/// 业务流程执行响应 DTO
///
/// `instance_id` 预留给需要回传实例编号的上层调用方,演示中编号已写入日志。
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct ProcessResponseDto {
    /// 流程实例编号(如 PROCUREMENT-000001)
    pub instance_id: String,
    /// 流程名称(中文)
    pub process_name: String,
    /// 是否成功
    pub success: bool,
    /// 结果消息(成功摘要或失败原因)
    pub message: String,
}

impl ProcessResponseDto {
    /// 创建流程响应 DTO
    ///
    /// # 参数
    /// - `instance_id`:流程实例编号
    /// - `process_name`:流程名称
    /// - `success`:是否成功
    /// - `message`:结果消息
    ///
    /// # 返回
    /// 响应 DTO
    pub fn new(instance_id: &str, process_name: &str, success: bool, message: &str) -> Self {
        Self {
            instance_id: instance_id.to_string(),
            process_name: process_name.to_string(),
            success,
            message: message.to_string(),
        }
    }
}
//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : jewelry.rs
//! 珠宝行业领域实体定义
//!
//! 包含:
//! - `Jewelry`:珠宝业务实体(贯穿采购→设计→生产→质检→包装→物流→财务→
//!   营销→销售等全部流程)
//! - `ProcessOutcome`:业务流程执行产出(同事业务执行的返回载体)
//! - 全局自增流水号生成器(线程安全,用于生成唯一编号)

use std::sync::atomic::{AtomicU64, Ordering};

/// 全局自增流水号(线程安全,跨线程共享生成唯一序号)
static NEXT_SEQUENCE: AtomicU64 = AtomicU64::new(1);

/// 获取下一个业务流水号(原子递增,高并发安全)
///
/// # 返回
/// 下一个自增序号
pub fn next_sequence() -> u64 {
    NEXT_SEQUENCE.fetch_add(1, Ordering::SeqCst)
}

/// 珠宝业务实体(领域实体,跨全流程共享)
///
/// `id` / `status` / `with_status` 为领域状态演进预留(如 `PROCURED`→`DELIVERED`),
/// 当前演示以值传递共享珠宝实体,未对状态字段做持久化演进,属预留 API。
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct Jewelry {
    /// 珠宝编号(如 JWL-000001)
    pub id: String,
    /// 珠宝名称
    pub name: String,
    /// 材质(黄金 / 铂金 / 钻石 / K金 / 银)
    pub material: String,
    /// 重量(克)
    pub weight_grams: f64,
    /// 零售价(元)
    pub price: f64,
    /// 当前状态(INIT 初始 / PROCURED 已采购 / DESIGNED 已设计 /
    /// PRODUCED 已生产 / INSPECTED 已质检 / PACKED 已包装 / DELIVERED 已发货)
    pub status: String,
}

impl Jewelry {
    /// 创建珠宝实体
    ///
    /// # 参数
    /// - `name`:珠宝名称
    /// - `material`:材质
    /// - `weight_grams`:重量(克)
    /// - `price`:零售价(元)
    ///
    /// # 返回
    /// 初始状态为 `INIT` 的珠宝实体
    pub fn new(name: &str, material: &str, weight_grams: f64, price: f64) -> Self {
        Self {
            id: format!("JWL-{:06}", next_sequence()),
            name: name.to_string(),
            material: material.to_string(),
            weight_grams,
            price,
            status: "INIT".to_string(),
        }
    }

    /// 更新珠宝状态(返回新实体,保持不可变语义便于并发共享)
    ///
    /// # 参数
    /// - `status`:新状态
    ///
    /// # 返回
    /// 更新状态后的珠宝实体副本
    #[allow(dead_code)]
    pub fn with_status(&self, status: &str) -> Self {
        let mut cloned = self.clone();
        cloned.status = status.to_string();
        cloned
    }
}

/// 业务流程执行产出(同事业务执行的返回载体)
///
/// `instance_id` 预留给产出追溯使用,当前已写入执行记录(`ProcessRecord`),
/// 此处字段作为冗余追溯标识保留。
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct ProcessOutcome {
    /// 流程实例编号
    pub instance_id: String,
    /// 产出摘要(中文描述)
    pub summary: String,
    /// 是否成功
    pub success: bool,
}

impl ProcessOutcome {
    /// 创建成功产出
    ///
    /// # 参数
    /// - `instance_id`:流程实例编号
    /// - `summary`:产出摘要
    ///
    /// # 返回
    /// 成功产出
    pub fn success(instance_id: &str, summary: &str) -> Self {
        Self {
            instance_id: instance_id.to_string(),
            summary: summary.to_string(),
            success: true,
        }
    }

    /// 创建失败产出
    ///
    /// 预留 API:当前演示业务执行失败时直接返回错误,不构造失败产出;
    /// 该构造器预留给需要显式失败产出的场景。
    ///
    /// # 参数
    /// - `instance_id`:流程实例编号
    /// - `summary`:产出摘要
    ///
    /// # 返回
    /// 失败产出
    #[allow(dead_code)]
    pub fn failure(instance_id: &str, summary: &str) -> Self {
        Self {
            instance_id: instance_id.to_string(),
            summary: summary.to_string(),
            success: false,
        }
    }
}
//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : process_repository.rs
//! 业务流程仓储接口(领域层抽象,由基础设施层实现)
//!
//! 仓储用于持久化每次同事业务执行的记录,供统计与追溯使用。
//! 领域层只定义接口,具体存储(内存 / 数据库)由基础设施层按 DI 注入。

use crate::common::error::ProcessError;
use crate::domain::entities::jewelry::ProcessOutcome;

/// 业务流程执行记录(持久化载体)
#[derive(Debug, Clone)]
pub struct ProcessRecord {
    /// 流程实例编号
    pub instance_id: String,
    /// 流程名称(中文)
    pub process_name: String,
    /// 执行产出
    pub outcome: ProcessOutcome,
    /// 执行时间(格式:YYYY-MM-DD HH:MM:SS)
    pub executed_at: String,
}

/// 业务流程仓储抽象接口(线程安全)
pub trait ProcessRepository: Send + Sync {
    /// 保存业务执行记录
    ///
    /// # 参数
    /// - `record`:执行记录
    ///
    /// # 返回
    /// - `Ok(())`:保存成功
    /// - `Err(ProcessError)`:保存失败
    fn save(&self, record: ProcessRecord) -> Result<(), ProcessError>;

    /// 查询全部执行记录
    ///
    /// # 返回
    /// 全部执行记录
    fn find_all(&self) -> Vec<ProcessRecord>;

    /// 统计成功/失败数量
    ///
    /// # 返回
    /// `(成功数量, 失败数量)` 元组
    fn count(&self) -> (usize, usize);
}
//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : budget.rs
//! 耗时预算(Timing Budget)
//!
//! 计时函数模式的第一性问题:**「快慢」必须相对预算才有意义**。
//! 每个部门声明自己的预期耗时、偏慢阈值、超预算阈值(微秒),
//! 任何一次计时结果都能立刻落到某个档位,而不是靠感觉说「有点慢」。

/// 耗时预算(某部门单笔业务的三档时间阈值)
#[derive(Debug, Clone, Copy)]
pub struct TimingBudget {
    /// 所属部门(中文名)
    pub department: &'static str,
    /// 预期耗时(微秒,正常应不超过该值)
    pub expected_micros: u64,
    /// 偏慢阈值(微秒,超过即视为偏慢)
    pub slow_micros: u64,
    /// 超预算阈值(微秒,超过即视为不可接受)
    pub danger_micros: u64,
}

impl TimingBudget {
    /// 创建耗时预算
    ///
    /// # 参数
    /// - `department`:所属部门
    /// - `expected_micros`:预期耗时(微秒)
    /// - `slow_micros`:偏慢阈值(微秒)
    /// - `danger_micros`:超预算阈值(微秒)
    ///
    /// # 返回
    /// 耗时预算实例
    pub const fn new(
        department: &'static str,
        expected_micros: u64,
        slow_micros: u64,
        danger_micros: u64,
    ) -> Self {
        Self {
            department,
            expected_micros,
            slow_micros,
            danger_micros,
        }
    }

    /// 判断实测耗时是否在预期之内
    ///
    /// # 参数
    /// - `micros`:实测耗时(微秒)
    ///
    /// # 返回
    /// `true` 表示未超预期
    pub fn within_expected(&self, micros: u64) -> bool {
        micros <= self.expected_micros
    }

    /// 判断实测耗时是否已偏慢
    ///
    /// # 参数
    /// - `micros`:实测耗时(微秒)
    ///
    /// # 返回
    /// `true` 表示已越过偏慢阈值
    pub fn is_slow(&self, micros: u64) -> bool {
        micros > self.slow_micros
    }

    /// 判断实测耗时是否已超预算
    ///
    /// # 参数
    /// - `micros`:实测耗时(微秒)
    ///
    /// # 返回
    /// `true` 表示已越过超预算阈值
    pub fn is_danger(&self, micros: u64) -> bool {
        micros > self.danger_micros
    }

    /// 输出预算描述(用于日志与控制台展示)
    ///
    /// # 返回
    /// 中文描述字符串
    pub fn describe(&self) -> String {
        format!(
            "[{}] 预期 ≤ {} µs · 偏慢 > {} µs · 超预算 > {} µs",
            self.department, self.expected_micros, self.slow_micros, self.danger_micros
        )
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : controller.rs
//! 计时单元抽象(Timing Controller)
//!
//! 每个部门一个计时单元:负责用计时器包裹「对端业务调用」拿到真实耗时,
//! 按预算给出判定,并把结果累计成可查询的快照与时间线。
//!
//! 计时与提交是同一动作:计时函数模式不负责拦截,只负责「如实测量 + 明确判定」,
//! 是否因超预算而优化/降级,是使用方根据报告决定的下一步。

use std::sync::Arc;
use std::time::Instant;

use crate::domain::timing::budget::TimingBudget;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::report::{TimingOutcome, TimingSnapshot};
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;
use crate::domain::timing::timeline::TimelineEntry;

/// 计时单元抽象(线程安全)
pub trait TimingController: Send + Sync {
    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage;

    /// 获取耗时预算
    ///
    /// # 返回
    /// 耗时预算
    fn budget(&self) -> TimingBudget;

    /// 计时包裹一次业务调用(采样 + 判定 + 累计)
    ///
    /// # 参数
    /// - `profiler`:对端计时器实现
    /// - `task`:计时任务
    ///
    /// # 返回
    /// 计时结论
    fn profile(&self, profiler: &Arc<dyn TimingProfiler>, task: &TimingTask) -> TimingOutcome;

    /// 执行一次带计时的业务(与 `profile` 同源,保留语义化入口)
    ///
    /// # 参数
    /// - `profiler`:对端计时器实现
    /// - `task`:计时任务
    ///
    /// # 返回
    /// 计时结论
    fn execute(&self, profiler: &Arc<dyn TimingProfiler>, task: &TimingTask) -> TimingOutcome {
        self.profile(profiler, task)
    }

    /// 获取累计统计快照
    ///
    /// # 返回
    /// 统计快照
    fn snapshot(&self) -> TimingSnapshot;

    /// 输出自述状态(用于监控汇总展示)
    ///
    /// # 返回
    /// 中文状态描述
    fn status_text(&self) -> String;

    /// 获取最近的时间线记录
    ///
    /// # 返回
    /// 时间线条目列表
    fn timeline(&self) -> Vec<TimelineEntry>;
}

/// 计算从起点到现在的微秒数(保底 1 微秒)
///
/// # 参数
/// - `started`:计时起点
///
/// # 返回
/// 已走微秒数
pub fn elapsed_micros(started: Instant) -> u64 {
    let micros = started.elapsed().as_micros() as u64;
    if micros == 0 {
        1
    } else {
        micros
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : profiler.rs
//! 计时器抽象(Timing Profiler)
//!
//! 「被测方」需要暴露的能力:我是谁、我在哪个部门、我的标称耗时是多少、
//! 我如何执行业务。计时由 `TimingController` 在外层包裹,被测方不关心计时细节,
//! 这样同一套业务实现既能被本地计时器包裹,也能被真实 APM 或压测工具包裹。

use std::sync::Arc;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::budget::TimingBudget;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 计时器抽象(被测业务方,线程安全)
pub trait TimingProfiler: Send + Sync {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str;

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str;

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str;

    /// 获取耗时预算(默认取所属阶段的预算)
    ///
    /// # 返回
    /// 耗时预算
    fn budget(&self) -> TimingBudget {
        self.stage().budget()
    }

    /// 获取标称业务耗时(微秒,用于解释预算与实测的差距)
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64;

    /// 执行业务
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务完成
    /// - `Err(ProcessError)`:业务失败(含瞬时故障)
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError>;

    /// 获取工位序号
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize;

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage;

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger>;
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : registry.rs
//! 计时单元注册表(Timing Registry)
//!
//! 调度中心通过注册表登记 12 个部门的计时单元,并按阶段标识查找。
//! 注册表只暴露「注册 / 数量 / 查找 / 系统自述」四件事,
//! 具体存储方式(`RwLock<Vec<...>>`)由应用层实现,领域层不关心。

use std::sync::Arc;

use crate::domain::timing::controller::TimingController;

/// 计时单元注册表抽象(线程安全)
pub trait TimingRegistry: Send + Sync {
    /// 注册一个计时单元
    ///
    /// # 参数
    /// - `controller`:计时单元
    fn register(&self, controller: Arc<dyn TimingController>);

    /// 获取已注册的计时单元数量
    ///
    /// # 返回
    /// 单元数量
    fn controller_count(&self) -> usize;

    /// 按阶段标识查找计时单元
    ///
    /// # 参数
    /// - `stage_id`:阶段标识
    ///
    /// # 返回
    /// 计时单元(未注册返回 `None`)
    fn find(&self, stage_id: &str) -> Option<Arc<dyn TimingController>>;

    /// 输出系统级自述状态
    ///
    /// # 返回
    /// 中文状态描述
    fn system_status(&self) -> String;
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : report.rs
//! 计时结论(Timing Report)
//!
//! - `TimingOutcome`:一次「计时包裹业务调用」的最终产出(含耗时与判定)
//! - `TimingSnapshot`:某个计时单元的累计统计快照(供监控汇总展示)
//!
//! 结论里同时保留业务响应与计时数据:性能分析与业务结果不割裂,
//! 既能看到「业务完成了什么」,也能看到「这件事花了多久、是否超预算」。

use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::sample::TimingSample;
use crate::domain::timing::verdict::TimingVerdict;

/// 计时结论(一次带计时的业务调用产出)
#[derive(Debug, Clone)]
pub enum TimingOutcome {
    /// 业务完成(附耗时与判定)
    Completed {
        /// 业务响应
        response: ProcessResponseDto,
        /// 计时采样
        sample: TimingSample,
        /// 耗时判定
        verdict: TimingVerdict,
        /// 实测耗时(微秒)
        micros: u64,
    },
    /// 业务失败(已计时,但下游执行报错)
    Failed {
        /// 任务编号
        task_id: String,
        /// 阶段标识
        stage_id: &'static str,
        /// 阶段名称
        stage_name: &'static str,
        /// 实测耗时(微秒)
        micros: u64,
        /// 失败细节
        detail: String,
    },
}

impl TimingOutcome {
    /// 判断业务是否完成
    ///
    /// # 返回
    /// `true` 表示业务成功完成
    pub fn is_completed(&self) -> bool {
        matches!(self, TimingOutcome::Completed { .. })
    }

    /// 获取实测耗时
    ///
    /// # 返回
    /// 实测耗时(微秒)
    pub fn micros(&self) -> u64 {
        match self {
            TimingOutcome::Completed { micros, .. } => *micros,
            TimingOutcome::Failed { micros, .. } => *micros,
        }
    }

    /// 获取耗时判定(失败为 `None`)
    ///
    /// # 返回
    /// 判定结果
    pub fn verdict(&self) -> Option<TimingVerdict> {
        match self {
            TimingOutcome::Completed { verdict, .. } => Some(*verdict),
            TimingOutcome::Failed { .. } => None,
        }
    }

    /// 判断是否在预算内(失败一律视为不在预算内)
    ///
    /// # 返回
    /// `true` 表示在预算内
    pub fn within_budget(&self) -> bool {
        match self {
            TimingOutcome::Completed { sample, .. } => sample.within_budget,
            TimingOutcome::Failed { .. } => false,
        }
    }

    /// 获取业务响应(失败为 `None`)
    ///
    /// # 返回
    /// 业务响应引用
    pub fn response(&self) -> Option<&ProcessResponseDto> {
        match self {
            TimingOutcome::Completed { response, .. } => Some(response),
            TimingOutcome::Failed { .. } => None,
        }
    }

    /// 输出结论描述(用于日志与控制台展示)
    ///
    /// # 返回
    /// 中文描述字符串
    pub fn describe(&self) -> String {
        match self {
            TimingOutcome::Completed {
                response,
                sample,
                verdict,
                micros,
            } => format!(
                "{} / {}({} µs,判定 {}/{},站点 {}/{})",
                response.process_name,
                response.message,
                micros,
                verdict.text(),
                verdict.id(),
                sample.stage_id,
                sample.stage_name
            ),
            TimingOutcome::Failed {
                task_id,
                stage_name,
                micros,
                detail,
                ..
            } => format!(
                "任务 {} 在 {} 执行失败(耗时 {} µs):{}",
                task_id, stage_name, micros, detail
            ),
        }
    }

    /// 输出采样描述(失败时给出失败摘要)
    ///
    /// # 返回
    /// 中文描述字符串
    pub fn sample_text(&self) -> String {
        match self {
            TimingOutcome::Completed { sample, .. } => sample.describe(),
            TimingOutcome::Failed {
                stage_id,
                stage_name,
                micros,
                ..
            } => format!("[{}] {} 实测 {} µs(失败)", stage_id, stage_name, micros),
        }
    }
}

/// 计时单元快照(累计统计)
#[derive(Debug, Clone)]
pub struct TimingSnapshot {
    /// 阶段标识
    pub stage_id: &'static str,
    /// 阶段名称
    pub stage_name: &'static str,
    /// 所属部门
    pub department: &'static str,
    /// 预算描述
    pub budget_text: String,
    /// 计时调用次数
    pub timed_calls: usize,
    /// 累计耗时(微秒)
    pub total_micros: u64,
    /// 平均耗时(微秒)
    pub avg_micros: u64,
    /// 偏慢次数
    pub slow_calls: usize,
    /// 超预算次数
    pub over_budget_calls: usize,
    /// 最快耗时(微秒)
    pub fastest_micros: u64,
    /// 最慢耗时(微秒)
    pub slowest_micros: u64,
}

/// 计时单元未找到(按执行器标识查找失败)
pub const TIMING_UNIT_NOT_FOUND: &str = "TIMING_UNIT_NOT_FOUND";

/// 计时调用失败(对端业务执行报错)
pub const TIMING_CALL_FAILED: &str = "TIMING_CALL_FAILED";//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : sample.rs
//! 计时采样(Timing Sample)
//!
//! 一次业务调用结束后产生的「一条耗时记录」:哪一步、花了多久、是否在预算内。
//! 采样本身不做判定(判定在 `verdict` 模块),只负责把观测值装起来并打印,
//! 便于汇总、排序、找瓶颈。

/// 计时采样点(一条耗时记录)
#[derive(Debug, Clone, Copy)]
pub struct TimingSample {
    /// 阶段标识
    pub stage_id: &'static str,
    /// 阶段名称
    pub stage_name: &'static str,
    /// 实测耗时(微秒)
    pub micros: u64,
    /// 是否在预期预算内
    pub within_budget: bool,
}

impl TimingSample {
    /// 创建计时采样点
    ///
    /// # 参数
    /// - `stage_id`:阶段标识
    /// - `stage_name`:阶段名称
    /// - `micros`:实测耗时(微秒)
    /// - `within_budget`:是否在预算内
    ///
    /// # 返回
    /// 采样点实例
    pub const fn new(
        stage_id: &'static str,
        stage_name: &'static str,
        micros: u64,
        within_budget: bool,
    ) -> Self {
        Self {
            stage_id,
            stage_name,
            micros,
            within_budget,
        }
    }

    /// 输出采样描述(用于日志与控制台展示)
    ///
    /// # 返回
    /// 中文描述字符串
    pub fn describe(&self) -> String {
        format!(
            "[{}] {} 实测 {} µs({:.3} ms)· {}",
            self.stage_id,
            self.stage_name,
            self.micros,
            (self.micros as f64) / 1000.0,
            if self.within_budget {
                "预算内"
            } else {
                "越出预期(偏慢或超预算)"
            }
        )
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : stage.rs
//! 业务阶段(Timing Stage)
//!
//! 珠宝行业全程 12 个部门,每个部门既是业务流程的一站,也是计时的一个「计时区段」。
//! 每个阶段自带耗时预算(预期 / 偏慢 / 超预算),让「哪一步慢」有统一标尺。

use crate::domain::timing::budget::TimingBudget;

/// 业务阶段(12 个部门)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TimingStage {
    /// 原料采购核验
    Procurement,
    /// 设计制图
    Design,
    /// 加工生产
    Production,
    /// 质检
    Inspection,
    /// 包装
    Packaging,
    /// 物流
    Logistics,
    /// 财务
    Finance,
    /// 营销推广
    Marketing,
    /// 业务销售
    BusinessSales,
    /// 人事行政
    HrAdmin,
    /// 信息技术
    It,
    /// 培训
    Training,
}

impl TimingStage {
    /// 获取阶段标识
    ///
    /// # 返回
    /// 阶段标识
    pub fn id(&self) -> &'static str {
        match self {
            TimingStage::Procurement => "PROCUREMENT",
            TimingStage::Design => "DESIGN",
            TimingStage::Production => "PRODUCTION",
            TimingStage::Inspection => "INSPECTION",
            TimingStage::Packaging => "PACKAGING",
            TimingStage::Logistics => "LOGISTICS",
            TimingStage::Finance => "FINANCE",
            TimingStage::Marketing => "MARKETING",
            TimingStage::BusinessSales => "BUSINESS_SALES",
            TimingStage::HrAdmin => "HR_ADMIN",
            TimingStage::It => "IT",
            TimingStage::Training => "TRAINING",
        }
    }

    /// 获取阶段中文名称
    ///
    /// # 返回
    /// 阶段名称
    pub fn name(&self) -> &'static str {
        match self {
            TimingStage::Procurement => "原料采购核验",
            TimingStage::Design => "设计制图",
            TimingStage::Production => "加工生产",
            TimingStage::Inspection => "质检",
            TimingStage::Packaging => "包装",
            TimingStage::Logistics => "物流",
            TimingStage::Finance => "财务",
            TimingStage::Marketing => "营销推广",
            TimingStage::BusinessSales => "业务销售",
            TimingStage::HrAdmin => "人事行政",
            TimingStage::It => "信息技术",
            TimingStage::Training => "培训",
        }
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    pub fn department(&self) -> &'static str {
        match self {
            TimingStage::Procurement => "采购部",
            TimingStage::Design => "设计部",
            TimingStage::Production => "生产部",
            TimingStage::Inspection => "质检部",
            TimingStage::Packaging => "包装部",
            TimingStage::Logistics => "物流部",
            TimingStage::Finance => "财务部",
            TimingStage::Marketing => "营销部",
            TimingStage::BusinessSales => "业务销售部",
            TimingStage::HrAdmin => "人事行政部",
            TimingStage::It => "信息技术部",
            TimingStage::Training => "培训部",
        }
    }

    /// 获取计时单元名称
    ///
    /// # 返回
    /// 计时单元名称
    pub fn controller_name(&self) -> String {
        format!("{} 计时分析单元", self.name())
    }

    /// 获取该阶段的耗时预算
    ///
    /// 预算口径(预期 / 偏慢 / 超预算,单位微秒),与各部门实际业务复杂度匹配:
    /// 物流需对接外部承运商(25000 基线时代已按 100000 预期),营销批量投放较快,
    /// 财务涉及成本分摊与入账,给出更宽的预期。
    ///
    /// # 返回
    /// 耗时预算
    pub fn budget(&self) -> TimingBudget {
        match self {
            TimingStage::Procurement => TimingBudget::new("采购部", 80_000, 120_000, 160_000),
            TimingStage::Design => TimingBudget::new("设计部", 70_000, 105_000, 140_000),
            TimingStage::Production => TimingBudget::new("生产部", 90_000, 135_000, 180_000),
            TimingStage::Inspection => TimingBudget::new("质检部", 80_000, 120_000, 160_000),
            TimingStage::Packaging => TimingBudget::new("包装部", 60_000, 90_000, 120_000),
            TimingStage::Logistics => TimingBudget::new("物流部", 100_000, 150_000, 200_000),
            TimingStage::Finance => TimingBudget::new("财务部", 65_000, 97_500, 130_000),
            TimingStage::Marketing => TimingBudget::new("营销部", 55_000, 82_500, 110_000),
            TimingStage::BusinessSales => TimingBudget::new("业务销售部", 60_000, 90_000, 120_000),
            TimingStage::HrAdmin => TimingBudget::new("人事行政部", 55_000, 82_500, 110_000),
            TimingStage::It => TimingBudget::new("信息技术部", 65_000, 97_500, 130_000),
            TimingStage::Training => TimingBudget::new("培训部", 75_000, 112_500, 150_000),
        }
    }

    /// 获取阶段在全程中的顺序号(从 1 开始)
    ///
    /// # 返回
    /// 顺序号
    pub fn order(&self) -> usize {
        match self {
            TimingStage::Procurement => 1,
            TimingStage::Design => 2,
            TimingStage::Production => 3,
            TimingStage::Inspection => 4,
            TimingStage::Packaging => 5,
            TimingStage::Logistics => 6,
            TimingStage::Finance => 7,
            TimingStage::Marketing => 8,
            TimingStage::BusinessSales => 9,
            TimingStage::HrAdmin => 10,
            TimingStage::It => 11,
            TimingStage::Training => 12,
        }
    }

    /// 按阶段标识查找阶段
    ///
    /// # 参数
    /// - `stage_id`:阶段标识
    ///
    /// # 返回
    /// 对应阶段(未知标识返回 `None`)
    pub fn from_id(stage_id: &str) -> Option<TimingStage> {
        Self::all_stages()
            .iter()
            .copied()
            .find(|stage| stage.id() == stage_id)
    }

    /// 获取全部 12 个阶段(按供应链顺序)
    ///
    /// # 返回
    /// 阶段数组
    pub fn all_stages() -> [TimingStage; 12] {
        [
            TimingStage::Procurement,
            TimingStage::Design,
            TimingStage::Production,
            TimingStage::Inspection,
            TimingStage::Packaging,
            TimingStage::Logistics,
            TimingStage::Finance,
            TimingStage::Marketing,
            TimingStage::BusinessSales,
            TimingStage::HrAdmin,
            TimingStage::It,
            TimingStage::Training,
        ]
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : stats.rs
//! 耗时统计(Timing Statistics)
//!
//! 单次计时只能说明「这一次多快」,要判断「整体是否退化」必须看分布:
//! 次数、最快、最慢、总计、平均、中位数(P50)、P95。
//! 只看平均值会被极端慢点带偏,P95 才能反映「大多数用户的真实体验」。

/// 耗时统计(一组采样点的分布摘要)
#[derive(Debug, Clone, Copy)]
pub struct TimingStats {
    /// 样本数量
    pub count: usize,
    /// 最快耗时(微秒)
    pub min_micros: u64,
    /// 最慢耗时(微秒)
    pub max_micros: u64,
    /// 合计耗时(微秒)
    pub total_micros: u64,
    /// 平均耗时(微秒)
    pub avg_micros: u64,
    /// 中位数耗时(微秒)
    pub p50_micros: u64,
    /// 95 分位耗时(微秒)
    pub p95_micros: u64,
}

impl TimingStats {
    /// 创建空统计(全 0)
    ///
    /// # 返回
    /// 空统计实例
    pub fn empty() -> Self {
        Self {
            count: 0,
            min_micros: 0,
            max_micros: 0,
            total_micros: 0,
            avg_micros: 0,
            p50_micros: 0,
            p95_micros: 0,
        }
    }

    /// 按采样耗时序列计算统计(内部自动排序,不修改入参)
    ///
    /// # 参数
    /// - `samples`:耗时序列(微秒)
    ///
    /// # 返回
    /// 统计结果(空序列返回全 0)
    pub fn from_samples(samples: &[u64]) -> Self {
        if samples.is_empty() {
            return Self::empty();
        }
        let mut sorted = samples.to_vec();
        sorted.sort_unstable();
        let count = sorted.len();
        let total_micros: u64 = sorted.iter().sum();
        let min_micros = sorted[0];
        let max_micros = sorted[count - 1];
        let p50_index = (count - 1) * 50 / 100;
        let p95_index = ((count - 1) * 95 + 99) / 100;
        Self {
            count,
            min_micros,
            max_micros,
            total_micros,
            avg_micros: total_micros / count as u64,
            p50_micros: sorted[p50_index],
            p95_micros: sorted[p95_index],
        }
    }

    /// 输出统计描述(用于日志与控制台展示)
    ///
    /// # 返回
    /// 中文描述字符串
    pub fn describe(&self) -> String {
        format!(
            "样本 {} 次 · 最快 {} µs · 最慢 {} µs · 合计 {} µs · 平均 {} µs · P50 {} µs · P95 {} µs",
            self.count,
            self.min_micros,
            self.max_micros,
            self.total_micros,
            self.avg_micros,
            self.p50_micros,
            self.p95_micros
        )
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : stopwatch.rs
//! 计时器(Stopwatch)
//!
//! 计时函数模式的最底层工具:在业务调用前后各取一次时钟,差值就是这一段业务的耗时。
//! 本实现基于 `std::time::Instant`(单调时钟,不受系统时间调整影响),
//! 每个计时器独立持有起点与标签,互不干扰,可在多线程中各自使用。

use std::time::Instant;

/// 计时器(一次业务调用的秒表)
#[derive(Debug)]
pub struct Stopwatch {
    /// 计时起点(单调时钟)
    started: Instant,
    /// 计时器标签(通常是业务名称)
    label: String,
}

impl Stopwatch {
    /// 启动计时器
    ///
    /// # 参数
    /// - `label`:计时器标签
    ///
    /// # 返回
    /// 已启动的计时器
    pub fn start(label: &str) -> Self {
        Self {
            started: Instant::now(),
            label: label.to_string(),
        }
    }

    /// 获取标签
    ///
    /// # 返回
    /// 计时器标签
    pub fn label(&self) -> &str {
        &self.label
    }

    /// 获取已走耗时(微秒,保底 1 微秒,避免出现 0 误导「不耗时」)
    ///
    /// # 返回
    /// 已走微秒数
    pub fn elapsed_micros(&self) -> u64 {
        let micros = self.started.elapsed().as_micros() as u64;
        if micros == 0 {
            1
        } else {
            micros
        }
    }

    /// 获取已走耗时(毫秒)
    ///
    /// # 返回
    /// 已走毫秒数
    pub fn elapsed_millis(&self) -> u64 {
        self.started.elapsed().as_millis() as u64
    }

    /// 重新开始计时(保留标签,重置起点)
    pub fn restart(&mut self) {
        self.started = Instant::now();
    }

    /// 输出计时器描述(用于日志与控制台展示)
    ///
    /// # 返回
    /// 中文描述字符串
    pub fn describe(&self) -> String {
        format!(
            "计时器[{}] 已走 {} µs({:.3} ms)",
            self.label,
            self.elapsed_micros(),
            (self.elapsed_micros() as f64) / 1000.0
        )
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : task.rs
//! 计时任务(Timing Task)
//!
//! 计时函数模式要回答的问题不是「有没有稳」,而是「这一段到底花了多久、慢在哪」。
//! 因此任务除了承载珠宝实体,还要能表达「人为注入的额外耗时」:
//! 演示时给某个部门叠加一段耗时,观察计时器能否如实测量并落到正确档位。

use crate::domain::entities::jewelry::Jewelry;

/// 默认业务主题
pub const DEFAULT_TOPIC: &str = "JEWELRY_TIMING_FUNCTIONS";

/// 计时任务(一次带计时的业务调用)
#[derive(Debug, Clone)]
pub struct TimingTask {
    /// 任务编号(形如 TF-000001)
    pub task_id: String,
    /// 业务主题
    pub topic: String,
    /// 人为注入的额外耗时(微秒,0 表示不注入)
    pub extra_micros: u64,
    /// 珠宝实体
    pub jewelry: Jewelry,
}

impl TimingTask {
    /// 创建计时任务(不注入额外耗时)
    ///
    /// # 参数
    /// - `topic`:业务主题
    /// - `jewelry`:珠宝实体
    ///
    /// # 返回
    /// 计时任务实例
    pub fn new(topic: &str, jewelry: Jewelry) -> Self {
        let sequence = crate::domain::entities::jewelry::next_sequence();
        Self {
            task_id: format!("TF-{:06}", sequence),
            topic: topic.to_string(),
            extra_micros: 0,
            jewelry,
        }
    }

    /// 设置人为注入的额外耗时(模拟某一步骤变慢)
    ///
    /// # 参数
    /// - `extra_micros`:额外耗时(微秒)
    ///
    /// # 返回
    /// 新的计时任务(链式调用)
    pub fn with_extra(mut self, extra_micros: u64) -> Self {
        self.extra_micros = extra_micros;
        self
    }

    /// 输出任务描述(用于日志与控制台展示)
    ///
    /// # 返回
    /// 中文描述字符串
    pub fn describe(&self) -> String {
        format!(
            "{}(主题 {},注入额外耗时 {} µs,珠宝 {})",
            self.task_id, self.topic, self.extra_micros, self.jewelry.name
        )
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : timeline.rs
//! 耗时时间线(Timing Timeline)
//!
//! 把一条条「某阶段花了多久」的记录按顺序串起来,就是一条耗时时间线。
//! 时间线是计时函数模式最有价值的产物:它能把「整单业务很慢」翻译成
//! 「第 6 站物流花了 80 ms、第 8 站营销花了 85 ms」,让优化有明确靶点。

/// 时间线条目(一个阶段的耗时记录)
#[derive(Debug, Clone)]
pub struct TimelineEntry {
    /// 阶段标识
    pub stage_id: &'static str,
    /// 阶段名称
    pub stage_name: &'static str,
    /// 实测耗时(微秒)
    pub micros: u64,
    /// 判定标识
    pub verdict_id: &'static str,
    /// 判定中文说明
    pub verdict_text: &'static str,
    /// 是否在预算内
    pub within_budget: bool,
}

impl TimelineEntry {
    /// 创建时间线条目
    ///
    /// # 参数
    /// - `stage_id`:阶段标识
    /// - `stage_name`:阶段名称
    /// - `micros`:实测耗时(微秒)
    /// - `verdict_id`:判定标识
    /// - `verdict_text`:判定中文说明
    /// - `within_budget`:是否在预算内
    ///
    /// # 返回
    /// 时间线条目
    pub fn new(
        stage_id: &'static str,
        stage_name: &'static str,
        micros: u64,
        verdict_id: &'static str,
        verdict_text: &'static str,
        within_budget: bool,
    ) -> Self {
        Self {
            stage_id,
            stage_name,
            micros,
            verdict_id,
            verdict_text,
            within_budget,
        }
    }

    /// 输出条目描述(用于日志与控制台展示)
    ///
    /// # 返回
    /// 中文描述字符串
    pub fn describe(&self) -> String {
        let budget_flag = if self.within_budget { "预算内" } else { "越出预期" };
        format!(
            "  - [{}] {} | {} µs({:.3} ms) | {}({})| {}",
            self.stage_id,
            self.stage_name,
            self.micros,
            (self.micros as f64) / 1000.0,
            self.verdict_text,
            self.verdict_id,
            budget_flag
        )
    }
}

/// 耗时时间线(按记录顺序累积的阶段耗时)
#[derive(Debug, Clone, Default)]
pub struct TimingTimeline {
    /// 全部条目(按写入顺序)
    entries: Vec<TimelineEntry>,
}

impl TimingTimeline {
    /// 创建空时间线
    ///
    /// # 返回
    /// 空时间线
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// 追加一条记录(最多保留最近 200 条,防止长时间运行无限增长)
    ///
    /// # 参数
    /// - `entry`:时间线条目
    pub fn push(&mut self, entry: TimelineEntry) {
        self.entries.push(entry);
        if self.entries.len() > 200 {
            self.entries.remove(0);
        }
    }

    /// 获取条目数量
    ///
    /// # 返回
    /// 条目数量
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// 判断时间线是否为空
    ///
    /// # 返回
    /// `true` 表示没有任何记录
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// 获取全部耗时合计
    ///
    /// # 返回
    /// 合计耗时(微秒)
    pub fn total_micros(&self) -> u64 {
        self.entries.iter().map(|entry| entry.micros).sum()
    }

    /// 获取最慢的一条记录
    ///
    /// # 返回
    /// 最慢条目(无记录返回 `None`)
    pub fn slowest(&self) -> Option<&TimelineEntry> {
        self.entries.iter().max_by_key(|entry| entry.micros)
    }

    /// 输出全部条目描述
    ///
    /// # 返回
    /// 逐行描述列表
    pub fn describe(&self) -> Vec<String> {
        self.entries
            .iter()
            .map(|entry| entry.describe())
            .collect()
    }

    /// 输出瓶颈报告(按耗时降序取前 N 条)
    ///
    /// # 参数
    /// - `top_n`:取前多少条
    ///
    /// # 返回
    /// 瓶颈描述列表(含排名与占时比例)
    pub fn bottleneck_report(&self, top_n: usize) -> Vec<String> {
        if self.entries.is_empty() {
            return vec!["  - 暂无可分析的计时记录".to_string()];
        }
        let total = self.total_micros();
        let mut sorted: Vec<&TimelineEntry> = self.entries.iter().collect();
        sorted.sort_by(|left, right| right.micros.cmp(&left.micros));
        if let Some(entry) = self.slowest() {
            let _ = entry.stage_name;
        }
        sorted
            .iter()
            .take(top_n)
            .enumerate()
            .map(|(index, entry)| {
                let ratio = if total == 0 {
                    0.0
                } else {
                    (entry.micros as f64) * 100.0 / (total as f64)
                };
                format!(
                    "  {}. [{}] {} | {} µs | 占全程 {:.1}% | {}({})",
                    index + 1,
                    entry.stage_id,
                    entry.stage_name,
                    entry.micros,
                    ratio,
                    entry.verdict_text,
                    entry.verdict_id
                )
            })
            .collect()
    }

    /// 获取全部条目的耗时序列(用于统计计算)
    ///
    /// # 返回
    /// 耗时序列(微秒)
    pub fn micros_series(&self) -> Vec<u64> {
        self.entries.iter().map(|entry| entry.micros).collect()
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : verdict.rs
//! 耗时判定(Timing Verdict)
//!
//! 把「实测微秒数」映射到四档结论:很快、正常、偏慢、超预算。
//! 分档的价值在于:同一套阈值下,日志、统计、瓶颈报告都能用同一个口径说话,
//! 不会出现「这里说慢、那里说还行」的口径分裂。

use crate::domain::timing::budget::TimingBudget;

/// 耗时判定(四档)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimingVerdict {
    /// 很快(不超过预期的一半)
    Fast,
    /// 正常(在预期之内)
    Normal,
    /// 偏慢(越过偏慢阈值)
    Slow,
    /// 超预算(越过超预算阈值,不可接受)
    OverBudget,
}

impl TimingVerdict {
    /// 获取判定标识
    ///
    /// # 返回
    /// 判定标识
    pub fn id(&self) -> &'static str {
        match self {
            TimingVerdict::Fast => "FAST",
            TimingVerdict::Normal => "NORMAL",
            TimingVerdict::Slow => "SLOW",
            TimingVerdict::OverBudget => "OVER_BUDGET",
        }
    }

    /// 获取判定中文说明
    ///
    /// # 返回
    /// 判定说明
    pub fn text(&self) -> &'static str {
        match self {
            TimingVerdict::Fast => "很快",
            TimingVerdict::Normal => "正常",
            TimingVerdict::Slow => "偏慢",
            TimingVerdict::OverBudget => "超预算",
        }
    }

    /// 是否在预期预算内(很快或正常)
    ///
    /// # 返回
    /// `true` 表示可接受
    pub fn is_acceptable(&self) -> bool {
        matches!(self, TimingVerdict::Fast | TimingVerdict::Normal)
    }
}

/// 按预算对实测耗时分档
///
/// 分档口径:
/// - `micros <= expected / 2`:很快
/// - `micros <= expected`:正常
/// - `micros <= danger`:偏慢
/// - 其余:超预算
///
/// # 参数
/// - `micros`:实测耗时(微秒)
/// - `budget`:所属部门预算
///
/// # 返回
/// 判定结果
pub fn classify(micros: u64, budget: &TimingBudget) -> TimingVerdict {
    if micros <= budget.expected_micros / 2 {
        TimingVerdict::Fast
    } else if micros <= budget.expected_micros {
        TimingVerdict::Normal
    } else if micros <= budget.danger_micros {
        TimingVerdict::Slow
    } else {
        TimingVerdict::OverBudget
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : container.rs
//! 依赖注入容器(组合根 Composition Root)
//!
//! 职责:集中装配(new)全部依赖并暴露访问方法,实现构造器注入。
//! - 统一日志(`Arc<dyn Logger>`)单例
//! - 12 个部门的计时器(`TimingProfiler` 实现)注册
//! - 内存仓储单例
//! - 业务流程应用服务(计时函数模式调度器)
//!
//! 计时隔离说明:每个部门的计时分析单元(含独立耗时预算、独立累计计数、
//! 独立时间线)与内层重试熔断适配器由调度器在构建计时拓扑时逐个创建
//! (每单元一个独立实例),因此容器不再提供全局共享的计时单元;
//! 部门之间不共用预算,也不共用时间线。
//!
//! 依赖方向严格单向:presentation → interface → application → domain → common,
//! 基础设施层向上提供实现,由容器完成组装。

use std::sync::Arc;

use crate::application::services::process_service::ProcessService;
use crate::application::timing::handlers::{
    BusinessSalesHandler, DesignHandler, FinanceHandler, HrAdminHandler, InspectionHandler,
    ItHandler, LogisticsHandler, MarketingHandler, PackagingHandler, ProcurementHandler,
    ProductionHandler, TrainingHandler,
};
use crate::common::logging::Logger;
use crate::domain::timing::profiler::TimingProfiler;
use crate::infrastructure::logging::file_logger::FileLogger;
use crate::infrastructure::persistence::memory_process_repository::MemoryProcessRepository;

/// 依赖注入容器(组合根)
pub struct ServiceContainer {
    /// 统一日志(单例)
    logger: Arc<dyn Logger>,
    /// 内存仓储(单例,预留给扩展组件复用)
    #[allow(dead_code)]
    repository: Arc<MemoryProcessRepository>,
    /// 业务流程应用服务(计时函数模式调度器)
    service: Arc<ProcessService>,
}

impl ServiceContainer {
    /// 构建依赖注入容器(组合根,统一装配计时器与全部服务)
    ///
    /// # 返回
    /// 已装配完成的容器实例
    pub fn new() -> Self {
        // 1. 基础设施依赖(单例)
        let logger: Arc<dyn Logger> = Arc::new(FileLogger::new("./Logs"));
        let repository = Arc::new(MemoryProcessRepository::new());

        // 2. 创建 12 个部门的计时器(按供应链顺序装配)
        let profilers: Vec<Arc<dyn TimingProfiler>> = vec![
            Arc::new(ProcurementHandler::new(logger.clone())),
            Arc::new(DesignHandler::new(logger.clone())),
            Arc::new(ProductionHandler::new(logger.clone())),
            Arc::new(InspectionHandler::new(logger.clone())),
            Arc::new(PackagingHandler::new(logger.clone())),
            Arc::new(LogisticsHandler::new(logger.clone())),
            Arc::new(FinanceHandler::new(logger.clone())),
            Arc::new(MarketingHandler::new(logger.clone())),
            Arc::new(BusinessSalesHandler::new(logger.clone())),
            Arc::new(HrAdminHandler::new(logger.clone())),
            Arc::new(ItHandler::new(logger.clone())),
            Arc::new(TrainingHandler::new(logger.clone())),
        ];

        // 3. 应用层服务(构造器注入)
        let service = Arc::new(ProcessService::new(
            profilers,
            repository.clone(),
            logger.clone(),
        ));

        Self {
            logger,
            repository,
            service,
        }
    }

    /// 获取业务流程应用服务
    ///
    /// # 返回
    /// 应用服务(`Arc` 共享)
    pub fn service(&self) -> Arc<ProcessService> {
        self.service.clone()
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 统一日志(`Arc<dyn Logger>`)
    pub fn logger(&self) -> Arc<dyn Logger> {
        self.logger.clone()
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : file_logger.rs
//! 文件日志实现(按日期分文件夹、按日志等级分文件)
//!
//! 目录结构(示例,日期为当日):
//! ```text
//! Logs/
//!   2026-07-06/
//!     app-info.log
//!     app-error.log
//!     app-debug.log
//!     app-warn.log
//! ```
//!
//! 设计要点:
//! - **线程安全 / 高并发**:每个日志等级使用独立的 `Mutex<BufWriter<File>>`,
//!   同一等级写操作串行化,不同等级互不阻塞;可被 `Arc` 共享到多线程。
//! - **日期滚动**:每次写入检测日期目录,跨天自动切换到新的日期文件夹。
//! - **控制台与文件一致**:统一格式化 `[时间] [等级] 消息`,
//!   同时输出到控制台(stdout/stderr)与对应文件。

use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::sync::Mutex;

use crate::common::logging::{LogLevel, Logger};

/// 单日志等级的文件写入句柄(受互斥锁保护)
struct LevelWriter {
    /// 当前打开的缓冲写入器
    writer: Option<std::io::BufWriter<File>>,
    /// 该句柄对应的日期文件夹(用于跨天滚动判断)
    opened_date: String,
}

impl LevelWriter {
    /// 创建空的等级写入器
    fn new() -> Self {
        Self {
            writer: None,
            opened_date: String::new(),
        }
    }
}

/// 文件日志实现(线程安全、支持高并发写入)
pub struct FileLogger {
    /// 日志根目录(默认 ./Logs)
    base_dir: PathBuf,
    /// 调试日志写入器
    debug_writer: Mutex<LevelWriter>,
    /// 信息日志写入器
    info_writer: Mutex<LevelWriter>,
    /// 警告日志写入器
    warn_writer: Mutex<LevelWriter>,
    /// 错误日志写入器
    error_writer: Mutex<LevelWriter>,
}

impl FileLogger {
    /// 创建文件日志
    ///
    /// # 参数
    /// - `base_dir`:日志根目录(如 "./Logs")
    ///
    /// # 返回
    /// 文件日志实例
    pub fn new(base_dir: &str) -> Self {
        let logger = Self {
            base_dir: PathBuf::from(base_dir),
            debug_writer: Mutex::new(LevelWriter::new()),
            info_writer: Mutex::new(LevelWriter::new()),
            warn_writer: Mutex::new(LevelWriter::new()),
            error_writer: Mutex::new(LevelWriter::new()),
        };
        // 启动即预创建四个等级日志文件:即使本轮没有任何 ERROR,
        // 目录结构也始终完整为 app-{info,error,debug,warn}.log
        logger.ensure_level_files();
        logger
    }

    /// 预创建当日四个等级日志文件(确保目录结构完整)
    fn ensure_level_files(&self) {
        let date_folder = self.date_folder();
        let dir = self.ensure_dir(&date_folder);
        for level in &[
            LogLevel::Debug,
            LogLevel::Info,
            LogLevel::Warn,
            LogLevel::Error,
        ] {
            let path = dir.join(level.file_name());
            let _ = OpenOptions::new().create(true).append(true).open(&path);
        }
    }

    /// 获取当前日期文件夹名(如 2026-07-06)
    ///
    /// # 返回
    /// 日期字符串
    fn date_folder(&self) -> String {
        chrono::Local::now().format("%Y-%m-%d").to_string()
    }

    /// 确保日期目录存在并返回目录路径
    ///
    /// # 参数
    /// - `date_folder`:日期文件夹名
    ///
    /// # 返回
    /// 日期目录路径
    fn ensure_dir(&self, date_folder: &str) -> PathBuf {
        let dir = self.base_dir.join(date_folder);
        let _ = fs::create_dir_all(&dir);
        dir
    }

    /// 以追加模式打开指定等级日志文件(返回缓冲写入器)
    ///
    /// # 参数
    /// - `level`:日志等级
    ///
    /// # 返回
    /// 缓冲写入器
    fn open_writer(&self, level: LogLevel) -> std::io::BufWriter<File> {
        let date_folder = self.date_folder();
        let dir = self.ensure_dir(&date_folder);
        let path = dir.join(level.file_name());
        let file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&path)
            .unwrap_or_else(|e| panic!("无法打开日志文件 {}:{}", path.display(), e));
        std::io::BufWriter::new(file)
    }

    /// 写入日志(统一格式;控制台与文件同时输出)
    ///
    /// # 参数
    /// - `level`:日志等级
    /// - `message`:日志消息
    fn write(&self, level: LogLevel, message: &str) {
        let timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f");
        let line = format!("[{}] [{}] {}", timestamp, level.tag(), message);

        // ① 输出到控制台(错误走 stderr,其余走 stdout)
        match level {
            LogLevel::Error => eprintln!("{}", line),
            _ => println!("{}", line),
        }

        // ② 输出到文件(按等级互斥锁串行化,保证线程安全)
        let target = match level {
            LogLevel::Debug => &self.debug_writer,
            LogLevel::Info => &self.info_writer,
            LogLevel::Warn => &self.warn_writer,
            LogLevel::Error => &self.error_writer,
        };
        let mut guard = target.lock().unwrap();
        let date_folder = self.date_folder();
        // 跨天或未打开 → 重新打开文件(实现按日期滚动)
        if guard.opened_date != date_folder || guard.writer.is_none() {
            guard.opened_date = date_folder.clone();
            guard.writer = Some(self.open_writer(level));
        }
        if let Some(writer) = guard.writer.as_mut() {
            let _ = writeln!(writer, "{}", line);
            let _ = writer.flush();
        }
    }
}

/// 实现统一日志接口(`Arc<dyn Logger>` 可注入各组件)
impl Logger for FileLogger {
    /// 输出调试日志
    fn debug(&self, message: &str) {
        self.write(LogLevel::Debug, message);
    }

    /// 输出信息日志
    fn info(&self, message: &str) {
        self.write(LogLevel::Info, message);
    }

    /// 输出警告日志
    fn warn(&self, message: &str) {
        self.write(LogLevel::Warn, message);
    }

    /// 输出错误日志
    fn error(&self, message: &str) {
        self.write(LogLevel::Error, message);
    }
}
//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : memory_process_repository.rs
//! 内存仓储实现(线程安全)
//!
//! 以 `Mutex<HashMap>` 实现 `ProcessRepository` 接口,供业务执行记录
//! 的保存、查询与统计使用。演示场景使用内存存储;生产环境可替换为数据库实现。

use std::collections::HashMap;
use std::sync::Mutex;

use crate::common::error::ProcessError;
use crate::domain::repository::process_repository::{ProcessRecord, ProcessRepository};

/// 内存仓储实现
pub struct MemoryProcessRepository {
    /// 内部存储(以流程实例编号为键,受互斥锁保护,保证并发安全)
    store: Mutex<HashMap<String, ProcessRecord>>,
}

impl MemoryProcessRepository {
    /// 创建内存仓储
    ///
    /// # 返回
    /// 内存仓储实例
    pub fn new() -> Self {
        Self {
            store: Mutex::new(HashMap::new()),
        }
    }
}

impl ProcessRepository for MemoryProcessRepository {
    /// 保存业务执行记录
    ///
    /// # 参数
    /// - `record`:执行记录
    ///
    /// # 返回
    /// - `Ok(())`:保存成功
    /// - `Err(ProcessError)`:保存失败
    fn save(&self, record: ProcessRecord) -> Result<(), ProcessError> {
        let mut store = self.store.lock().unwrap();
        store.insert(record.instance_id.clone(), record);
        Ok(())
    }

    /// 查询全部执行记录
    ///
    /// # 返回
    /// 全部执行记录
    fn find_all(&self) -> Vec<ProcessRecord> {
        let store = self.store.lock().unwrap();
        store.values().cloned().collect()
    }

    /// 统计成功/失败数量
    ///
    /// # 返回
    /// `(成功数量, 失败数量)` 元组
    fn count(&self) -> (usize, usize) {
        let store = self.store.lock().unwrap();
        let total = store.values().len();
        let success = store.values().filter(|r| r.outcome.success).count();
        (success, total - success)
    }
}
//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : contracts.rs
//! 对外交互契约(Contracts)
//!
//! 定义外部调用方与系统交互的统一契约结构(业务信封),
//! 承载「执行器标识 + 执行请求」,供表现层/外部系统装配。
//!
//! Timing Functions 模式语义:信封指定目标计时单元(按执行器标识映射),
//! 由调度层启动秒表包裹业务调用,停表后用该部门的耗时预算判定档位------
//! 慢就记慢、超预算就记超预算,但业务结果本身照常返回。

use crate::domain::dtos::process_dtos::ProcessRequestDto;

/// 业务信封(外部发起一次定向调用的载体)
#[derive(Debug, Clone)]
pub struct BusinessEnvelope {
    /// 执行器标识(如 PROCUREMENT / TRAINING)
    pub executor_id: String,
    /// 执行请求 DTO
    pub request: ProcessRequestDto,
}

impl BusinessEnvelope {
    /// 创建业务信封
    ///
    /// # 参数
    /// - `executor_id`:执行器标识(映射到对应部门的计时单元)
    /// - `request`:执行请求
    ///
    /// # 返回
    /// 业务信封
    pub fn new(executor_id: &str, request: ProcessRequestDto) -> Self {
        Self {
            executor_id: executor_id.to_string(),
            request,
        }
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : mod.rs
//! 对外 API 端口契约(Ports)
//!
//! 定义表现层(presentation)与外部调用方可消费的应用端口,
//! 将「应用能力」与「具体实现」解耦;具体实现由表现层/应用层提供。
//!
//! Timing Functions 模式语义:外部通过「指定执行器标识」触发一次**定向计时调用**,
//! 调度层按该部门耗时预算启动秒表包裹业务调用,停表后判定很快 / 正常 / 偏慢 / 超预算;
//! 计时只做「如实测量 + 明确判定」,不拦截、不改写业务结果。
//! 执行器或计时单元不存在时返回 `TIMING_UNIT_NOT_FOUND`。

use crate::common::error::ProcessError;
use crate::domain::dtos::process_dtos::{ProcessRequestDto, ProcessResponseDto};
use crate::domain::repository::process_repository::ProcessRecord;

/// 对外应用 API 端口契约(线程安全)
///
/// 表现层实现该端口并向外部暴露;外部仅依赖本端口,不依赖具体实现。
pub trait BusinessApiPort: Send + Sync {
    /// 派发指定部门的调用(秒表包裹业务调用并给出耗时判定)
    ///
    /// # 参数
    /// - `executor_id`:执行器标识(如 PROCUREMENT / TRAINING)
    /// - `request`:执行请求 DTO
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:带耗时判定的业务响应(成功或失败)
    /// - `Err(ProcessError)`:执行器/计时单元不存在(`TIMING_UNIT_NOT_FOUND`)
    fn dispatch(
        &self,
        executor_id: &str,
        request: ProcessRequestDto,
    ) -> Result<ProcessResponseDto, ProcessError>;

    /// 获取业务执行统计(成功数量,失败数量)
    ///
    /// # 返回
    /// `(成功数量, 失败数量)` 元组
    fn statistics(&self) -> (usize, usize);

    /// 获取全部业务执行记录(用于追溯/汇总展示)
    ///
    /// # 返回
    /// 全部执行记录
    fn records(&self) -> Vec<ProcessRecord>;
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : controller.rs
//! 应用控制器(表现层,控制台入口)
//!
//! 职责:
//! - 从组合根(DI 容器)获取应用服务与统一日志
//! - 实现 `interface::ports::BusinessApiPort` 端口契约(对外 API)
//! - 创建贯穿全流程的珠宝实体,驱动计时串行调度、并发调度与四段计时演示
//! - 输出计时统计、业务执行统计与记录汇总
//!
//! 依赖方向:presentation → interface → application → domain → common,
//! 符合严格分层(六层结构)。

use std::sync::Arc;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::{ProcessRequestDto, ProcessResponseDto};
use crate::domain::entities::jewelry::Jewelry;
use crate::domain::repository::process_repository::ProcessRecord;
use crate::infrastructure::di::container::ServiceContainer;
use crate::interface::contracts::BusinessEnvelope;
use crate::interface::ports::BusinessApiPort;

/// 应用控制器(控制台表现层,实现对外端口契约)
pub struct ApplicationController {
    /// 依赖注入容器(组合根)
    container: Arc<ServiceContainer>,
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl ApplicationController {
    /// 创建应用控制器
    ///
    /// # 参数
    /// - `container`:依赖注入容器
    ///
    /// # 返回
    /// 应用控制器实例
    pub fn new(container: Arc<ServiceContainer>) -> Self {
        let logger = container.logger();
        Self { container, logger }
    }

    /// 启动珠宝行业全程业务流程(Timing Functions 计时函数模式)演示
    ///
    /// 流程:
    /// ① 打印标题与配置
    /// ② 创建珠宝实体
    /// ③ 计时串行调度(12 个部门依次「启动秒表 → 调用业务 → 停表判定」)
    /// ④ 输出执行统计
    /// ⑤ 计时并发调度(12 单元并行计时 + 四段演示:单段/档位/分布/无计时直连)
    /// ⑥ 通过端口契约定向发起单个部门调用
    /// ⑦ 输出已注册计时单元清单
    pub fn run(&self) {
        // ① 标题与运行说明
        self.logger
            .info("================================================================");
        self.logger
            .info("   Timing Functions 计时函数模式 Timing Functions Pattern");
        self.logger
            .info("   珠宝行业企业级全程业务流程(DDD 六层分层 · 性能分析型模式)");
        self.logger
            .info("   业务:原料采购核验 · 设计制图 · 加工生产 · 质检 · 包装 · 物流");
        self.logger
            .info("        · 财务 · 营销推广 · 业务销售 · 人事行政 · IT · 培训");
        self.logger
            .info("   预算:每部门独立耗时预算(预期 / 偏慢 / 超预算 三档阈值)");
        self.logger
            .info("   语义:秒表包裹业务调用,如实测量、明确判定;只测量不改写业务结果");
        self.logger
            .info("   统计:全局时间线 + P50/P95 分布 + 瓶颈 Top3,定位慢在哪一站");
        self.logger
            .info("   日志:Logs/<日期>/app-{info,error,debug,warn}.log(按日期/等级分文件)");
        self.logger
            .info("================================================================");

        // ② 创建贯穿全流程的珠宝实体
        let jewelry = Jewelry::new("六福传承金镯", "黄金", 35.68, 26800.0);
        self.logger.info(&format!(
            "创建珠宝实体:{},材质={},重量={} 克,零售价={} 元",
            jewelry.name, jewelry.material, jewelry.weight_grams, jewelry.price
        ));

        // ③ 计时串行调度:12 个部门依次「启动秒表 → 调用业务 → 停表判定」
        let request = ProcessRequestDto::new("ALL", jewelry.clone(), "调度中心", "Timing");
        self.container.service().run_sequential(request);
        self.logger
            .info("================================================================");

        // ④ 输出执行统计(读取内存仓储)
        self.print_summary();

        // ⑤ 计时并发调度(高并发 + 单段计时/档位/分布/无计时直连四段演示)
        self.logger.info(
            "【高并发演示】12 个计时单元并行包裹业务调用;随后演示「单段计量」「偏慢与超预算两档」「P50/P95 分布」「无计时直连对照」四个场景......",
        );
        let concurrent_request =
            ProcessRequestDto::new("ALL", jewelry.clone(), "调度中心", "Concurrent");
        self.container.service().run_concurrent(concurrent_request);
        self.print_summary();

        // ⑥ 通过端口契约定向发起单个部门调用(BusinessEnvelope + dispatch)
        let envelope = BusinessEnvelope::new(
            "TRAINING",
            ProcessRequestDto::new("TRAINING", jewelry, "培训部", "PortTest"),
        );
        match self.dispatch(&envelope.executor_id, envelope.request) {
            Ok(response) => self.logger.info(&format!(
                "端口契约计时调用成功:{} / {}",
                response.process_name, response.message
            )),
            Err(err) => self
                .logger
                .warn(&format!("端口契约计时调用失败:{}", err)),
        }
        self.print_summary();

        // ⑦ 输出已注册计时单元清单(计时单元与业务部门的对应关系)
        let executors = self.container.service().executors();
        self.logger.info(&format!(
            "已注册计时分析单元数:{}",
            executors.len()
        ));
        for executor in executors {
            self.logger.info(&format!(
                "  - [{}] {} / {}",
                executor.profiler_id(),
                executor.profiler_name(),
                executor.department()
            ));
        }
        self.logger
            .info("================================================================");
    }

    /// 输出执行统计与记录明细(基于仓储数据)
    fn print_summary(&self) {
        let (success, failure) = self.statistics();
        self.logger.info(&format!(
            "业务调度汇总:成功 {} 项,失败 {} 项(详见当日日志目录)",
            success, failure
        ));
        let records = self.records();
        self.logger.info(&format!("执行记录明细(共 {} 条):", records.len()));
        for record in records {
            let flag = if record.outcome.success { "成功" } else { "失败" };
            self.logger.info(&format!(
                "  - {} | {} | 状态:{} | 时间:{}",
                record.instance_id, record.process_name, flag, record.executed_at
            ));
        }
    }
}

/// 实现对外 API 端口契约(interface 层定义)
impl BusinessApiPort for ApplicationController {
    /// 派发指定部门的计时调用(定位计时单元、秒表包裹后定向调用)
    fn dispatch(
        &self,
        executor_id: &str,
        request: ProcessRequestDto,
    ) -> Result<ProcessResponseDto, ProcessError> {
        self.container.service().dispatch(executor_id, request)
    }

    /// 获取业务执行统计(成功数量,失败数量)
    fn statistics(&self) -> (usize, usize) {
        self.container.service().statistics()
    }

    /// 获取全部业务执行记录(用于追溯/汇总展示)
    fn records(&self) -> Vec<ProcessRecord> {
        self.container.service().records()
    }
}
rust 复制代码
//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : process_service.rs
//! 业务流程应用服务(计时函数模式)
//!
//! 编排职责:
//! 1. 装配 12 个部门的计时单元,组成计时拓扑(`build_hub`);
//! 2. 串行调度:12 个部门依次「启动秒表 → 调用业务 → 停表判定 → 记录」;
//! 3. 并发调度:12 个作业由 `Barrier` 同时起跑,验证线程安全与高并发;
//! 4. 四段计时演示:单段计时 / 档位演示 / P50-P95 分布 / 无计时直连对照;
//! 5. 端口派发、执行记录落库、执行器与统计查询。
//!
//! 核心立场:计时函数只「测量与判定」,不改变业务结果;
//! 业务慢就如实记慢,超预算就如实记超预算,绝不因为超时而丢弃业务产出。

use std::sync::Arc;
use std::time::Duration;

use crate::application::timing::jewelry_timing_hub::{JewelryTimingHub, TimingJob};
use crate::application::timing::timing_guard::TimingGuard;
use crate::application::timing::untimed_direct_client::UntimedDirectClient;
use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::common::resilience::retry_circuit_breaker::RetryCircuitBreaker;
use crate::domain::dtos::process_dtos::{ProcessRequestDto, ProcessResponseDto};
use crate::domain::entities::jewelry::{Jewelry, ProcessOutcome};
use crate::domain::repository::process_repository::{ProcessRecord, ProcessRepository};
use crate::domain::timing::budget::TimingBudget;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::registry::TimingRegistry;
use crate::domain::timing::report::{TimingOutcome, TIMING_UNIT_NOT_FOUND};
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::stopwatch::Stopwatch;
use crate::domain::timing::task::{TimingTask, DEFAULT_TOPIC};
use crate::domain::timing::verdict::TimingVerdict;

/// 计时函数模式业务流程应用服务
pub struct ProcessService {
    /// 12 个部门的计时器(对端业务实现)
    profilers: Vec<Arc<dyn TimingProfiler>>,
    /// 执行记录仓储
    repository: Arc<dyn ProcessRepository>,
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl ProcessService {
    /// 创建业务流程应用服务
    ///
    /// # 参数
    /// - `profilers`:12 个部门的计时器
    /// - `repository`:执行记录仓储
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 应用服务实例
    pub fn new(
        profilers: Vec<Arc<dyn TimingProfiler>>,
        repository: Arc<dyn ProcessRepository>,
        logger: Arc<dyn Logger>,
    ) -> Self {
        Self {
            profilers,
            repository,
            logger,
        }
    }

    /// 创建重试 + 熔断适配器(保护被测业务调用,重试耗时也计入计时)
    ///
    /// # 返回
    /// 适配器实例
    fn new_resilience() -> Arc<RetryCircuitBreaker> {
        Arc::new(RetryCircuitBreaker::new(
            2,
            u32::MAX,
            Duration::from_secs(5),
        ))
    }

    /// 装配计时拓扑(12 个部门各一个计时单元)
    ///
    /// # 返回
    /// 计时调度中心实例
    fn build_hub(&self) -> Arc<JewelryTimingHub> {
        let hub = Arc::new(JewelryTimingHub::new(self.logger.clone()));
        let resilience = Self::new_resilience();
        for stage in TimingStage::all_stages() {
            let guard = Arc::new(TimingGuard::new(
                stage,
                Arc::clone(&resilience),
                self.logger.clone(),
            ));
            TimingRegistry::register(&*hub, guard);
        }
        self.logger.info(&format!(
            "【计时拓扑】装配完成:计时单元数 {}(每部门独立耗时预算,秒表包裹业务调用)",
            TimingRegistry::controller_count(&*hub)
        ));
        hub
    }

    /// 按阶段查找对端计时器
    ///
    /// # 参数
    /// - `stage`:阶段枚举
    ///
    /// # 返回
    /// 对应计时器(未装配返回 `None`)
    fn profiler_for(&self, stage: TimingStage) -> Option<Arc<dyn TimingProfiler>> {
        self.profilers
            .iter()
            .find(|profiler| profiler.profiler_id() == stage.id())
            .cloned()
    }

    /// 串行调度:12 个部门依次「计时 → 调用 → 判定」
    ///
    /// # 参数
    /// - `request`:业务流程请求
    pub fn run_sequential(&self, request: ProcessRequestDto) {
        self.logger.info(
            "【串行】开始 12 个部门计时串行调度:每站启动秒表,如实测量、明确判定......",
        );
        let hub = self.build_hub();
        let mut responses: Vec<ProcessResponseDto> = Vec::new();

        for stage in TimingStage::all_stages() {
            let profiler = match self.profiler_for(stage) {
                Some(profiler) => profiler,
                None => {
                    self.logger.warn(&format!(
                        "【串行】第 {} 站 {}:计时器未装配,跳过",
                        stage.order(),
                        stage.name()
                    ));
                    continue;
                }
            };
            let budget = stage.budget();
            let task = TimingTask::new(DEFAULT_TOPIC, request.jewelry.clone());
            self.logger.info(&format!(
                "【串行】第 {} 站 {}({}):发起计时,预算 {}",
                stage.order(),
                stage.name(),
                stage.department(),
                budget.describe()
            ));
            match hub.execute(stage.id(), &profiler, &task) {
                Ok(TimingOutcome::Completed {
                    response,
                    sample,
                    verdict,
                    micros,
                }) => {
                    self.logger.info(&format!(
                        "【串行】第 {} 站完成:{} / {} | 采样 {} | 判定 {}({})",
                        stage.order(),
                        response.process_name,
                        response.message,
                        sample.describe(),
                        verdict.text(),
                        verdict.id()
                    ));
                    let _ = micros;
                    responses.push(response);
                }
                Ok(TimingOutcome::Failed {
                    task_id,
                    stage_name,
                    micros,
                    detail,
                    ..
                }) => {
                    self.logger.error(&format!(
                        "【串行】第 {} 站业务失败:任务 {} 在 {} 已耗时 {} µs,原因 {}",
                        stage.order(),
                        task_id,
                        stage_name,
                        micros,
                        detail
                    ));
                    responses.push(ProcessResponseDto::new(
                        &task_id,
                        &stage_name,
                        false,
                        &format!("计时调用失败:{}", detail),
                    ));
                }
                Err(err) => {
                    self.logger.error(&format!(
                        "【串行】第 {} 站调度失败:{}",
                        stage.order(),
                        err
                    ));
                    responses.push(ProcessResponseDto::new(
                        &task.task_id,
                        stage.name(),
                        false,
                        &format!("计时调度失败:{}", err),
                    ));
                }
            }
        }

        self.logger.info(&TimingRegistry::system_status(&*hub));
        for snapshot in hub.snapshots() {
            self.logger.info(&format!(
                "  - [{}] {} / {} | {} | 计时 {} 次 | 合计 {} µs | 平均 {} µs | 偏慢 {} | 超预算 {} | 最快 {} | 最慢 {}",
                snapshot.stage_id,
                snapshot.stage_name,
                snapshot.department,
                snapshot.budget_text,
                snapshot.timed_calls,
                snapshot.total_micros,
                snapshot.avg_micros,
                snapshot.slow_calls,
                snapshot.over_budget_calls,
                snapshot.fastest_micros,
                snapshot.slowest_micros
            ));
        }
        for line in hub.unit_report() {
            self.logger.info(&line);
        }
        for line in hub.timeline_report() {
            self.logger.info(&line);
        }
        self.logger.info(&format!("【串行】耗时分布:{}", hub.clock_stats().describe()));
        let succeeded = responses.iter().filter(|response| response.success).count();
        self.logger.info(&format!(
            "【串行】全部完成:产出 {} 项(成功 {} 项,失败 {} 项)",
            responses.len(),
            succeeded,
            responses.len() - succeeded
        ));
        self.save_responses(&responses);
    }

    /// 并发调度:12 个作业由 `Barrier` 同时起跑,验证线程安全与高并发
    ///
    /// # 参数
    /// - `request`:业务流程请求
    pub fn run_concurrent(&self, request: ProcessRequestDto) {
        let hub = self.build_hub();
        let mut jobs: Vec<TimingJob> = Vec::new();
        for stage in TimingStage::all_stages() {
            if let Some(profiler) = self.profiler_for(stage) {
                jobs.push(TimingJob::new(
                    stage.id(),
                    profiler,
                    TimingTask::new(DEFAULT_TOPIC, request.jewelry.clone()),
                ));
            }
        }
        self.logger.info(&format!(
            "【并发】开始并发计时调度:{} 个作业由 Barrier 同时起跑......",
            jobs.len()
        ));

        let mut responses: Vec<ProcessResponseDto> = Vec::new();
        let mut fast = 0usize;
        let mut normal = 0usize;
        let mut slow = 0usize;
        let mut over_budget = 0usize;
        let mut failed = 0usize;

        for outcome in hub.execute_batch(jobs) {
            match &outcome {
                TimingOutcome::Completed { response, verdict, .. } => {
                    match verdict {
                        TimingVerdict::Fast => {
                            fast += 1;
                        }
                        TimingVerdict::Normal => {
                            normal += 1;
                        }
                        TimingVerdict::Slow => {
                            slow += 1;
                        }
                        TimingVerdict::OverBudget => {
                            over_budget += 1;
                        }
                    }
                    responses.push(response.clone());
                }
                TimingOutcome::Failed {
                    task_id,
                    stage_name,
                    detail,
                    ..
                } => {
                    failed += 1;
                    self.logger.error(&format!(
                        "【并发】任务 {} 在 {} 失败:{}",
                        task_id, stage_name, detail
                    ));
                    responses.push(ProcessResponseDto::new(
                        task_id,
                        stage_name,
                        false,
                        &format!("计时调用失败:{}", detail),
                    ));
                }
            }
        }

        self.logger.info(&format!(
            "【并发】完成:很快 {} / 正常 {} / 偏慢 {} / 超预算 {} / 失败 {}",
            fast, normal, slow, over_budget, failed
        ));
        self.logger.info(&format!("【并发】耗时分布:{}", hub.clock_stats().describe()));
        for line in hub.bottleneck_report(3) {
            self.logger.info(&line);
        }
        self.logger.info(&TimingRegistry::system_status(&*hub));
        self.save_responses(&responses);

        // 合法全流程的计时总耗时(用于与「无计时直连」做对照)
        let legal_total_micros = hub.total_micros();
        self.run_timing_demo(&request.jewelry, legal_total_micros);
    }

    /// 计时演示(四段对照)
    ///
    /// # 参数
    /// - `jewelry`:珠宝实体
    /// - `legal_total_micros`:合法全流程的计时总耗时(微秒,用于收益对照)
    fn run_timing_demo(&self, jewelry: &Jewelry, legal_total_micros: u64) {
        self.logger.info("================================================================");
        self.logger.info(
            "【计时演示】开始四个场景:单段计时 / 偏慢与超预算两档 / P50-P95 分布 / 无计时直连对照",
        );
        let hub_demo = self.build_hub();

        // 段 A:单段计时(采购部,正常任务,展示「只测不改」)
        let stage_a = TimingStage::Procurement;
        if let Some(profiler) = self.profiler_for(stage_a) {
            let budget = stage_a.budget();
            let task_a = TimingTask::new(DEFAULT_TOPIC, jewelry.clone());
            let watch = Stopwatch::start("段A-采购计时");
            let outcome = hub_demo.execute(stage_a.id(), &profiler, &task_a);
            let observed = watch.elapsed_micros();
            let observed_ms = watch.elapsed_millis();
            let watch_text = watch.describe();
            match outcome {
                Ok(outcome) => {
                    self.logger.info(&format!(
                        "【计时演示 A】{} 单段计时:{} | 业务产出 {} | 预算 {} | 外部秒表观察 {} µs({} ms)| {}",
                        stage_a.name(),
                        outcome.sample_text(),
                        outcome
                            .response()
                            .map(|response| response.message.clone())
                            .unwrap_or_else(|| "无".to_string()),
                        budget.describe(),
                        observed,
                        observed_ms,
                        watch_text
                    ));
                    self.logger.info(&format!(
                        "【计时演示 A】结论:计时函数只测量不拦截------业务照常提交,只是多了一条可追溯的耗时事实(判定 {})",
                        outcome
                            .verdict()
                            .map(|verdict| verdict.id())
                            .unwrap_or("无")
                    ));
                }
                Err(err) => self.logger.error(&format!(
                    "【计时演示 A】采购部计时调用失败:{}",
                    err
                )),
            }
        } else {
            self.logger.warn("【计时演示 A】跳过:采购部计时器未装配");
        }

        // 段 B:档位演示(营销部注入 45 ms → 偏慢;财务部注入 200 ms → 超预算)
        let stage_b_slow = TimingStage::Marketing;
        if let Some(profiler) = self.profiler_for(stage_b_slow) {
            let budget = stage_b_slow.budget();
            let task_b = TimingTask::new(DEFAULT_TOPIC, jewelry.clone()).with_extra(45_000);
            match hub_demo.execute(stage_b_slow.id(), &profiler, &task_b) {
                Ok(outcome) => self.logger.warn(&format!(
                    "【计时演示 B-偏慢】{} 注入 45000 µs 额外耗时:{} | 预算 {} | 判定 {}({})",
                    stage_b_slow.name(),
                    outcome.sample_text(),
                    budget.describe(),
                    outcome
                        .verdict()
                        .map(|verdict| verdict.text())
                        .unwrap_or("无"),
                    outcome
                        .verdict()
                        .map(|verdict| verdict.id())
                        .unwrap_or("无")
                )),
                Err(err) => self.logger.error(&format!(
                    "【计时演示 B-偏慢】营销部计时调用失败:{}",
                    err
                )),
            }
        } else {
            self.logger.warn("【计时演示 B-偏慢】跳过:营销部计时器未装配");
        }

        let stage_b_over = TimingStage::Finance;
        if let Some(profiler) = self.profiler_for(stage_b_over) {
            let budget = stage_b_over.budget();
            let task_b = TimingTask::new(DEFAULT_TOPIC, jewelry.clone()).with_extra(200_000);
            match hub_demo.execute(stage_b_over.id(), &profiler, &task_b) {
                Ok(outcome) => self.logger.error(&format!(
                    "【计时演示 B-超预算】{} 注入 200000 µs 额外耗时:{} | 预算 {} | 判定 {}({})",
                    stage_b_over.name(),
                    outcome.sample_text(),
                    budget.describe(),
                    outcome
                        .verdict()
                        .map(|verdict| verdict.text())
                        .unwrap_or("无"),
                    outcome
                        .verdict()
                        .map(|verdict| verdict.id())
                        .unwrap_or("无")
                )),
                Err(err) => self.logger.error(&format!(
                    "【计时演示 B-超预算】财务部计时调用失败:{}",
                    err
                )),
            }
        } else {
            self.logger.warn("【计时演示 B-超预算】跳过:财务部计时器未装配");
        }

        // 段 C:并发采样 + P50 / P95 分布(平均值会掩盖长尾)
        let mut jobs: Vec<TimingJob> = Vec::new();
        for stage in TimingStage::all_stages() {
            if let Some(profiler) = self.profiler_for(stage) {
                jobs.push(TimingJob::new(
                    stage.id(),
                    profiler,
                    TimingTask::new(DEFAULT_TOPIC, jewelry.clone()),
                ));
            }
        }
        let mut watch_c = Stopwatch::start("段C-并发采样");
        let samples = hub_demo.execute_batch(jobs);
        let batch_micros = watch_c.elapsed_micros();
        let stats = hub_demo.clock_stats();
        self.logger.info(&format!(
            "【计时演示 C】再次并发采样 {} 条并按序统计:{}",
            samples.len(),
            stats.describe()
        ));
        self.logger.info(&format!(
            "【计时演示 C】批次墙钟 {} µs(单次 12 线程并发,非逐条累加),秒表已重启以准备下一段统计",
            batch_micros
        ));
        watch_c.restart();
        let _ = watch_c.elapsed_micros();
        self.logger.info(
            "【计时演示 C】结论:只看平均值会掩盖长尾------P95 才是用户真实感受到的那一档,偏慢与超预算必须单独计数",
        );

        // 段 D:无计时直连对照(100 ms 后才发现问题,无法分解各步耗时)
        let direct = UntimedDirectClient::new(100, self.logger.clone());
        let task_d = TimingTask::new(DEFAULT_TOPIC, jewelry.clone()).with_extra(400_000);
        let started_d = std::time::Instant::now();
        let result_d = direct.direct_call(&task_d);
        let observed_d = crate::domain::timing::controller::elapsed_micros(started_d);
        match result_d {
            Ok(response) => self.logger.warn(&format!(
                "【计时演示 D】无计时直连返回:{} | 外部秒表 {} µs,但无法拆分各步骤耗时",
                response.message, observed_d
            )),
            Err(err) => self.logger.error(&format!(
                "【计时演示 D】无计时直连在 {} µs 后才暴露问题:{} | 期间没有任何分步耗时证据",
                observed_d, err
            )),
        }
        self.logger.info(&format!(
            "【计时演示 D】直连自述:单笔固定耗时 {} ms;标称 {} µs;预算 {}",
            direct.delay_millis(),
            direct.base_micros(),
            direct.budget().describe()
        ));

        // 收益对照与瓶颈 Top3
        let direct_total_micros: u64 = direct.delay_millis() * 1000 * 12;
        self.logger.info(&format!(
            "【计时演示】对照:12 次直连约 {} µs({} ms × 12),计时侧全程合计 {} µs;直连只能拿到总数,计时能定位到站点",
            direct_total_micros,
            direct.delay_millis(),
            legal_total_micros
        ));
        if legal_total_micros > 0 {
            let direct_pct = (direct_total_micros as f64) / (legal_total_micros as f64) * 100.0;
            self.logger.info(&format!(
                "【计时演示】对照比例:直连 12 次固定耗时占计时侧全程累计的 {:.1}%;注意本工程的物流站含重试与退避,长尾会把计时侧累计抬高,但计时侧能指出「是物流重试」而不是笼统的「整单慢」",
                direct_pct
            ));
        } else {
            self.logger.warn("【计时演示】计时侧累计耗时为 0,比例对照跳过");
        }
        for line in hub_demo.bottleneck_report(3) {
            self.logger.info(&line);
        }
        self.logger.info(&format!(
            "【计时演示】演示单元自述:{}",
            hub_demo.status_report()
        ));
        let _ = TimingBudget::new("演示占位", 1, 2, 3);
    }

    /// 输出计时结论的中文摘要(供日志与端口复用)
    ///
    /// # 参数
    /// - `outcome`:计时结论
    ///
    /// # 返回
    /// 中文摘要
    pub fn outcome_text(&self, outcome: &TimingOutcome) -> String {
        format!(
            "完成={} | 预算内={} | {}",
            outcome.is_completed(),
            outcome.within_budget(),
            outcome.describe()
        )
    }

    /// 定向派发(端口契约:按阶段标识找到部门并计时调用)
    ///
    /// # 参数
    /// - `executor_id`:执行器标识(阶段标识)
    /// - `request`:业务流程请求
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务产出(成功或业务失败)
    /// - `Err(ProcessError)`:计时单元不存在
    pub fn dispatch(
        &self,
        executor_id: &str,
        request: ProcessRequestDto,
    ) -> Result<ProcessResponseDto, ProcessError> {
        let stage = match TimingStage::from_id(executor_id) {
            Some(stage) => stage,
            None => {
                self.logger.error(&format!(
                    "【端口】未知执行器标识:{}(未找到对应部门)",
                    executor_id
                ));
                return Err(ProcessError::new(
                    TIMING_UNIT_NOT_FOUND,
                    &format!("未知的计时执行器:{}", executor_id),
                ));
            }
        };
        let profiler = match self.profiler_for(stage) {
            Some(profiler) => profiler,
            None => {
                self.logger.error(&format!(
                    "【端口】执行器 {} 未装配,无法派发",
                    executor_id
                ));
                return Err(ProcessError::new(
                    TIMING_UNIT_NOT_FOUND,
                    &format!("执行器未装配:{}", executor_id),
                ));
            }
        };
        let hub = self.build_hub();
        let task = TimingTask::new(DEFAULT_TOPIC, request.jewelry.clone());
        match hub.execute(stage.id(), &profiler, &task) {
            Ok(outcome) => {
                let text = self.outcome_text(&outcome);
                self.logger.info(&format!(
                    "【端口】{} 计时调用完成:{}",
                    stage.name(),
                    text
                ));
                match &outcome {
                    TimingOutcome::Completed { response, .. } => {
                        let responses = vec![response.clone()];
                        self.save_responses(&responses);
                        Ok(response.clone())
                    }
                    TimingOutcome::Failed {
                        task_id, detail, ..
                    } => {
                        let response = ProcessResponseDto::new(
                            task_id,
                            stage.name(),
                            false,
                            &format!("计时调用失败:{}", detail),
                        );
                        let responses = vec![response.clone()];
                        self.save_responses(&responses);
                        Ok(response)
                    }
                }
            }
            Err(err) => {
                self.logger.error(&format!(
                    "【端口】{} 派发失败:{}",
                    stage.name(),
                    err
                ));
                Err(err)
            }
        }
    }

    /// 把业务产出写入仓储(成功/失败分别记录)
    ///
    /// # 参数
    /// - `responses`:业务产出列表
    fn save_responses(&self, responses: &[ProcessResponseDto]) {
        for response in responses {
            let outcome = if response.success {
                ProcessOutcome::success(&response.instance_id, &response.message)
            } else {
                ProcessOutcome::failure(&response.instance_id, &response.message)
            };
            let record = ProcessRecord {
                instance_id: response.instance_id.clone(),
                process_name: response.process_name.clone(),
                outcome,
                executed_at: chrono::Local::now()
                    .format("%Y-%m-%d %H:%M:%S")
                    .to_string(),
            };
            if let Err(err) = self.repository.save(record) {
                self.logger.error(&format!("【仓储】保存执行记录失败:{}", err));
            }
        }
    }

    /// 获取已装配的计时器列表
    ///
    /// # 返回
    /// 计时器列表
    pub fn executors(&self) -> Vec<Arc<dyn TimingProfiler>> {
        self.profilers.clone()
    }

    /// 获取业务执行统计(成功数量,失败数量)
    ///
    /// # 返回
    /// 成功与失败数量
    pub fn statistics(&self) -> (usize, usize) {
        self.repository.count()
    }

    /// 获取全部执行记录
    ///
    /// # 返回
    /// 执行记录列表
    pub fn records(&self) -> Vec<ProcessRecord> {
        self.repository.find_all()
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : business_sales.rs
//! 业务销售计时器(业务销售部)
//!
//! 标称耗时 45000 µs(45 ms):订单签约与客户配额锁定。
//! 计时单元在外层包裹调用,实测耗时与 60000 µs 预期对比。

use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 业务销售部计时器(供计时单元包裹调用)
pub struct BusinessSalesHandler {
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl BusinessSalesHandler {
    /// 创建业务销售部计时器
    ///
    /// # 参数
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 业务销售部计时器实例
    pub fn new(logger: Arc<dyn Logger>) -> Self {
        Self { logger }
    }
}

impl TimingProfiler for BusinessSalesHandler {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str {
        TimingStage::BusinessSales.id()
    }

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str {
        TimingStage::BusinessSales.name()
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str {
        TimingStage::BusinessSales.department()
    }

    /// 获取标称业务耗时
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64 {
        45_000
    }

    /// 执行业务(订单签约与客户配额锁定)
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务完成
    /// - `Err(ProcessError)`:数据校验失败
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        let planned_micros = self.base_micros() + task.extra_micros;
        thread::sleep(Duration::from_micros(planned_micros));
        self.logger.debug(&format!(
            "【{}】受理计时任务:{}(计划耗时 {} µs,工位 {})",
            self.department(),
            task.describe(),
            planned_micros,
            self.step_index()
        ));

        if task.jewelry.name.trim().is_empty() {
            self.logger.warn(&format!(
                "【{}】任务 {} 珠宝名称为空,无法签约",
                self.department(),
                task.task_id
            ));
            return Err(ProcessError::new(
                "VALIDATE_FAILED",
                "珠宝名称为空,无法签约",
            ));
        }

        Ok(ProcessResponseDto::new(
            &task.task_id,
            TimingStage::BusinessSales.name(),
            true,
            "业务完成:订单已签约并锁定客户配额",
        ))
    }

    /// 获取工位序号
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize {
        9
    }

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        TimingStage::BusinessSales
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger> {
        &self.logger
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : design.rs
//! 设计制图计时器(设计部)
//!
//! 标称耗时 55000 µs(55 ms):3D 建模 + 镶口工艺单出图。
//! 计时单元在外层包裹调用,实测耗时与 70000 µs 预期对比。

use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 设计部计时器(供计时单元包裹调用)
pub struct DesignHandler {
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl DesignHandler {
    /// 创建设计部计时器
    ///
    /// # 参数
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 设计部计时器实例
    pub fn new(logger: Arc<dyn Logger>) -> Self {
        Self { logger }
    }
}

impl TimingProfiler for DesignHandler {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str {
        TimingStage::Design.id()
    }

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str {
        TimingStage::Design.name()
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str {
        TimingStage::Design.department()
    }

    /// 获取标称业务耗时
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64 {
        55_000
    }

    /// 执行业务(3D 图纸与镶口工艺单出图)
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务完成
    /// - `Err(ProcessError)`:数据校验失败
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        let planned_micros = self.base_micros() + task.extra_micros;
        thread::sleep(Duration::from_micros(planned_micros));
        self.logger.debug(&format!(
            "【{}】受理计时任务:{}(计划耗时 {} µs,工位 {})",
            self.department(),
            task.describe(),
            planned_micros,
            self.step_index()
        ));

        if task.jewelry.name.trim().is_empty() {
            self.logger.warn(&format!(
                "【{}】任务 {} 珠宝名称为空,拒绝出图",
                self.department(),
                task.task_id
            ));
            return Err(ProcessError::new(
                "VALIDATE_FAILED",
                "珠宝名称为空,无法出图",
            ));
        }

        Ok(ProcessResponseDto::new(
            &task.task_id,
            TimingStage::Design.name(),
            true,
            "设计制图完成:3D 图纸与镶口工艺单已出图",
        ))
    }

    /// 获取工位序号
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize {
        2
    }

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        TimingStage::Design
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger> {
        &self.logger
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : finance.rs
//! 财务计时器(财务部)
//!
//! 标称耗时 50000 µs(50 ms):应收账款与成本分摊入账。
//! 计时单元在外层包裹调用,实测耗时与 65000 µs 预期对比。

use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 财务部计时器(供计时单元包裹调用)
pub struct FinanceHandler {
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl FinanceHandler {
    /// 创建财务部计时器
    ///
    /// # 参数
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 财务部计时器实例
    pub fn new(logger: Arc<dyn Logger>) -> Self {
        Self { logger }
    }
}

impl TimingProfiler for FinanceHandler {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str {
        TimingStage::Finance.id()
    }

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str {
        TimingStage::Finance.name()
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str {
        TimingStage::Finance.department()
    }

    /// 获取标称业务耗时
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64 {
        50_000
    }

    /// 执行业务(应收账款与成本分摊入账)
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务完成
    /// - `Err(ProcessError)`:数据校验失败
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        let planned_micros = self.base_micros() + task.extra_micros;
        thread::sleep(Duration::from_micros(planned_micros));
        self.logger.debug(&format!(
            "【{}】受理计时任务:{}(计划耗时 {} µs,工位 {})",
            self.department(),
            task.describe(),
            planned_micros,
            self.step_index()
        ));

        if task.jewelry.price <= 0.0 {
            self.logger.warn(&format!(
                "【{}】任务 {} 零售价非法:{} 元,拒绝入账",
                self.department(),
                task.task_id,
                task.jewelry.price
            ));
            return Err(ProcessError::new(
                "VALIDATE_FAILED",
                "零售价非法,无法入账",
            ));
        }

        Ok(ProcessResponseDto::new(
            &task.task_id,
            TimingStage::Finance.name(),
            true,
            "财务完成:应收账款与成本分摊已入账",
        ))
    }

    /// 获取工位序号
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize {
        7
    }

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        TimingStage::Finance
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger> {
        &self.logger
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : hr_admin.rs
//! 人事行政计时器(人事行政部)
//!
//! 标称耗时 40000 µs(40 ms):排班与考勤台账归档。
//! 计时单元在外层包裹调用,实测耗时与 55000 µs 预期对比。

use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 人事行政部计时器(供计时单元包裹调用)
pub struct HrAdminHandler {
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl HrAdminHandler {
    /// 创建人事行政部计时器
    ///
    /// # 参数
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 人事行政部计时器实例
    pub fn new(logger: Arc<dyn Logger>) -> Self {
        Self { logger }
    }
}

impl TimingProfiler for HrAdminHandler {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str {
        TimingStage::HrAdmin.id()
    }

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str {
        TimingStage::HrAdmin.name()
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str {
        TimingStage::HrAdmin.department()
    }

    /// 获取标称业务耗时
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64 {
        40_000
    }

    /// 执行业务(排班与考勤台账归档)
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务完成
    /// - `Err(ProcessError)`:数据校验失败
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        let planned_micros = self.base_micros() + task.extra_micros;
        thread::sleep(Duration::from_micros(planned_micros));
        self.logger.debug(&format!(
            "【{}】受理计时任务:{}(计划耗时 {} µs,工位 {})",
            self.department(),
            task.describe(),
            planned_micros,
            self.step_index()
        ));

        if task.jewelry.name.trim().is_empty() {
            self.logger.warn(&format!(
                "【{}】任务 {} 珠宝名称为空,无法归档台账",
                self.department(),
                task.task_id
            ));
            return Err(ProcessError::new(
                "VALIDATE_FAILED",
                "珠宝名称为空,无法归档台账",
            ));
        }

        Ok(ProcessResponseDto::new(
            &task.task_id,
            TimingStage::HrAdmin.name(),
            true,
            "人事完成:排班与考勤台账已归档",
        ))
    }

    /// 获取工位序号
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize {
        10
    }

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        TimingStage::HrAdmin
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger> {
        &self.logger
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : inspection.rs
//! 质检计时器(质检部)
//!
//! 标称耗时 65000 µs(65 ms):贵金属纯度与宝石净度检测。
//! 计时单元在外层包裹调用,实测耗时与 80000 µs 预期对比。

use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 质检部计时器(供计时单元包裹调用)
pub struct InspectionHandler {
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl InspectionHandler {
    /// 创建质检部计时器
    ///
    /// # 参数
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 质检部计时器实例
    pub fn new(logger: Arc<dyn Logger>) -> Self {
        Self { logger }
    }
}

impl TimingProfiler for InspectionHandler {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str {
        TimingStage::Inspection.id()
    }

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str {
        TimingStage::Inspection.name()
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str {
        TimingStage::Inspection.department()
    }

    /// 获取标称业务耗时
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64 {
        65_000
    }

    /// 执行业务(贵金属纯度与宝石净度检测)
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务完成
    /// - `Err(ProcessError)`:数据校验失败
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        let planned_micros = self.base_micros() + task.extra_micros;
        thread::sleep(Duration::from_micros(planned_micros));
        self.logger.debug(&format!(
            "【{}】受理计时任务:{}(计划耗时 {} µs,工位 {})",
            self.department(),
            task.describe(),
            planned_micros,
            self.step_index()
        ));

        if task.jewelry.name.trim().is_empty() {
            self.logger.warn(&format!(
                "【{}】任务 {} 珠宝名称为空,无法出具检测单",
                self.department(),
                task.task_id
            ));
            return Err(ProcessError::new(
                "VALIDATE_FAILED",
                "珠宝名称为空,无法出具检测单",
            ));
        }

        Ok(ProcessResponseDto::new(
            &task.task_id,
            TimingStage::Inspection.name(),
            true,
            "质检完成:贵金属纯度与宝石净度检测合格",
        ))
    }

    /// 获取工位序号
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize {
        4
    }

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        TimingStage::Inspection
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger> {
        &self.logger
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : it.rs
//! 信息技术计时器(信息技术部)
//!
//! 标称耗时 25000 µs(25 ms):门店 POS 与库存接口联调。
//! 预算是 65000 µs,标称耗时不到预期的一半,因此正常调用会被判定为 `FAST`,
//! 用于演示「很快」这一档确实会在真实计时结果中出现,而不是纸面上的枚举值。

use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 信息技术部计时器(供计时单元包裹调用)
pub struct ItHandler {
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl ItHandler {
    /// 创建信息技术部计时器
    ///
    /// # 参数
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 信息技术部计时器实例
    pub fn new(logger: Arc<dyn Logger>) -> Self {
        Self { logger }
    }
}

impl TimingProfiler for ItHandler {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str {
        TimingStage::It.id()
    }

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str {
        TimingStage::It.name()
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str {
        TimingStage::It.department()
    }

    /// 获取标称业务耗时
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64 {
        25_000
    }

    /// 执行业务(门店 POS 与库存接口联调)
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务完成
    /// - `Err(ProcessError)`:数据校验失败
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        let planned_micros = self.base_micros() + task.extra_micros;
        thread::sleep(Duration::from_micros(planned_micros));
        self.logger.debug(&format!(
            "【{}】受理计时任务:{}(计划耗时 {} µs,工位 {})",
            self.department(),
            task.describe(),
            planned_micros,
            self.step_index()
        ));

        if task.jewelry.name.trim().is_empty() {
            self.logger.warn(&format!(
                "【{}】任务 {} 珠宝名称为空,无法联调接口",
                self.department(),
                task.task_id
            ));
            return Err(ProcessError::new(
                "VALIDATE_FAILED",
                "珠宝名称为空,无法联调接口",
            ));
        }

        Ok(ProcessResponseDto::new(
            &task.task_id,
            TimingStage::It.name(),
            true,
            "IT 完成:门店 POS 与库存接口联调通过",
        ))
    }

    /// 获取工位序号
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize {
        11
    }

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        TimingStage::It
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger> {
        &self.logger
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : logistics.rs
//! 物流计时器(物流部)
//!
//! 标称耗时 80000 µs(80 ms):运单生成 + 承运商对接。
//! 此外演示「外部承运商瞬时不可用」:每 3 次调用中有 2 次失败,
//! 由外层重试 + 熔断适配器自动重试。**重试与退避的时间全部计入实测耗时**,
//! 这正是计时函数模式的价值:慢不是因为某一步慢,而是因为重试把时间叠起来了。

use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 物流调用计数器(进程级静态,原子递增保证高并发安全)
static LOGISTICS_ATTEMPT: AtomicU32 = AtomicU32::new(0);

/// 物流部计时器(供计时单元包裹调用)
pub struct LogisticsHandler {
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl LogisticsHandler {
    /// 创建物流部计时器
    ///
    /// # 参数
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 物流部计时器实例
    pub fn new(logger: Arc<dyn Logger>) -> Self {
        Self { logger }
    }
}

impl TimingProfiler for LogisticsHandler {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str {
        TimingStage::Logistics.id()
    }

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str {
        TimingStage::Logistics.name()
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str {
        TimingStage::Logistics.department()
    }

    /// 获取标称业务耗时
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64 {
        80_000
    }

    /// 执行业务(运单生成,含外部承运商瞬时故障)
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务完成
    /// - `Err(ProcessError)`:校验失败或外部承运商瞬时不可用
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        // 一、模拟承运商对接耗时
        let planned_micros = self.base_micros() + task.extra_micros;
        thread::sleep(Duration::from_micros(planned_micros));
        let attempt = LOGISTICS_ATTEMPT.fetch_add(1, Ordering::SeqCst) + 1;
        self.logger.debug(&format!(
            "【{}】受理计时任务:{}(计划耗时 {} µs,工位 {},第 {} 次外部调用)",
            self.department(),
            task.describe(),
            planned_micros,
            self.step_index(),
            attempt
        ));

        // 二、数据校验:零售价非法则无法计算保价运费
        if task.jewelry.price <= 0.0 {
            self.logger.warn(&format!(
                "【{}】任务 {} 零售价非法:{} 元,拒绝执行",
                self.department(),
                task.task_id,
                task.jewelry.price
            ));
            return Err(ProcessError::new(
                "VALIDATE_FAILED",
                "零售价非法,物流无法计算保价费用",
            ));
        }

        // 三、外部承运商瞬时不可用(每 3 次调用中有 2 次失败,用于演示重试耗时)
        if attempt % 3 != 0 {
            self.logger.warn(&format!(
                "【{}】任务 {} 第 {} 次调用外部承运商失败:接口瞬时不可用,交由重试适配器处理",
                self.department(),
                task.task_id,
                attempt
            ));
            return Err(ProcessError::new(
                "EXTERNAL_LOGISTICS_UNAVAILABLE",
                "外部物流系统暂时不可用,请重试",
            ));
        }

        // 四、返回业务完成响应
        Ok(ProcessResponseDto::new(
            &task.task_id,
            TimingStage::Logistics.name(),
            true,
            "物流完成:运单已生成并交付承运商(保价与温控要求已下发)",
        ))
    }

    /// 获取工位序号
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize {
        6
    }

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        TimingStage::Logistics
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger> {
        &self.logger
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : marketing.rs
//! 营销推广计时器(营销部)
//!
//! 标称耗时 40000 µs(40 ms):新品海报与投放排期。
//! 预算为 55000 µs 预期,是本工程中最容易被「注入耗时」挤出预算的部门之一,
//! 用于演示计时器能否把偏慢准确识别为 `SLOW`。

use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 营销部计时器(供计时单元包裹调用)
pub struct MarketingHandler {
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl MarketingHandler {
    /// 创建营销部计时器
    ///
    /// # 参数
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 营销部计时器实例
    pub fn new(logger: Arc<dyn Logger>) -> Self {
        Self { logger }
    }
}

impl TimingProfiler for MarketingHandler {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str {
        TimingStage::Marketing.id()
    }

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str {
        TimingStage::Marketing.name()
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str {
        TimingStage::Marketing.department()
    }

    /// 获取标称业务耗时
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64 {
        40_000
    }

    /// 执行业务(新品海报与投放预算排期)
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务完成
    /// - `Err(ProcessError)`:数据校验失败
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        let planned_micros = self.base_micros() + task.extra_micros;
        thread::sleep(Duration::from_micros(planned_micros));
        self.logger.debug(&format!(
            "【{}】受理计时任务:{}(计划耗时 {} µs,工位 {})",
            self.department(),
            task.describe(),
            planned_micros,
            self.step_index()
        ));

        if task.jewelry.price <= 0.0 {
            self.logger.warn(&format!(
                "【{}】任务 {} 零售价非法:{} 元,拒绝排期",
                self.department(),
                task.task_id,
                task.jewelry.price
            ));
            return Err(ProcessError::new(
                "VALIDATE_FAILED",
                "零售价非法,无法制定投放策略",
            ));
        }

        Ok(ProcessResponseDto::new(
            &task.task_id,
            TimingStage::Marketing.name(),
            true,
            "营销完成:新品海报与投放预算已排期",
        ))
    }

    /// 获取工位序号
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize {
        8
    }

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        TimingStage::Marketing
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger> {
        &self.logger
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : packaging.rs
//! 包装计时器(包装部)
//!
//! 标称耗时 45000 µs(45 ms):礼盒、证书与防伪标签封装。
//! 计时单元在外层包裹调用,实测耗时与 60000 µs 预期对比。

use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 包装部计时器(供计时单元包裹调用)
pub struct PackagingHandler {
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl PackagingHandler {
    /// 创建包装部计时器
    ///
    /// # 参数
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 包装部计时器实例
    pub fn new(logger: Arc<dyn Logger>) -> Self {
        Self { logger }
    }
}

impl TimingProfiler for PackagingHandler {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str {
        TimingStage::Packaging.id()
    }

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str {
        TimingStage::Packaging.name()
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str {
        TimingStage::Packaging.department()
    }

    /// 获取标称业务耗时
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64 {
        45_000
    }

    /// 执行业务(礼盒、证书与防伪标签封装)
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务完成
    /// - `Err(ProcessError)`:数据校验失败
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        let planned_micros = self.base_micros() + task.extra_micros;
        thread::sleep(Duration::from_micros(planned_micros));
        self.logger.debug(&format!(
            "【{}】受理计时任务:{}(计划耗时 {} µs,工位 {})",
            self.department(),
            task.describe(),
            planned_micros,
            self.step_index()
        ));

        if task.jewelry.price <= 0.0 {
            self.logger.warn(&format!(
                "【{}】任务 {} 零售价非法:{} 元,拒绝封装",
                self.department(),
                task.task_id,
                task.jewelry.price
            ));
            return Err(ProcessError::new(
                "VALIDATE_FAILED",
                "零售价非法,无法生成证书",
            ));
        }

        Ok(ProcessResponseDto::new(
            &task.task_id,
            TimingStage::Packaging.name(),
            true,
            "包装完成:礼盒、证书与防伪标签已封装",
        ))
    }

    /// 获取工位序号
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize {
        5
    }

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        TimingStage::Packaging
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger> {
        &self.logger
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : procurement.rs
//! 原料采购核验计时器(采购部)
//!
//! 标称耗时 60000 µs(60 ms):原料台账核对 + 供应商资质校验。
//! 计时单元在外层用 `Stopwatch` 包裹本执行器,实测耗时与预算对比后给出判定。

use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 采购部计时器(供计时单元包裹调用)
pub struct ProcurementHandler {
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl ProcurementHandler {
    /// 创建采购部计时器
    ///
    /// # 参数
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 采购部计时器实例
    pub fn new(logger: Arc<dyn Logger>) -> Self {
        Self { logger }
    }
}

impl TimingProfiler for ProcurementHandler {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str {
        TimingStage::Procurement.id()
    }

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str {
        TimingStage::Procurement.name()
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str {
        TimingStage::Procurement.department()
    }

    /// 获取标称业务耗时
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64 {
        60_000
    }

    /// 执行业务(原料台账与供应商资质核验)
    ///
    /// # 参数
    /// - `task`:计时任务(含人为注入的额外耗时)
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务完成
    /// - `Err(ProcessError)`:数据校验失败
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        // 一、按「标称耗时 + 注入耗时」模拟真实业务耗时
        let planned_micros = self.base_micros() + task.extra_micros;
        thread::sleep(Duration::from_micros(planned_micros));
        self.logger.debug(&format!(
            "【{}】受理计时任务:{}(计划耗时 {} µs,工位 {})",
            self.department(),
            task.describe(),
            planned_micros,
            self.step_index()
        ));

        // 二、数据校验:重量非法则无法核验原料
        if task.jewelry.weight_grams <= 0.0 {
            self.logger.warn(&format!(
                "【{}】任务 {} 珠宝重量非法:{} 克,拒绝核验",
                self.department(),
                task.task_id,
                task.jewelry.weight_grams
            ));
            return Err(ProcessError::new(
                "VALIDATE_FAILED",
                "珠宝重量非法,原料无法核验",
            ));
        }

        // 三、返回业务完成响应
        Ok(ProcessResponseDto::new(
            &task.task_id,
            TimingStage::Procurement.name(),
            true,
            "采购核验完成:原料台账与供应商资质已核对",
        ))
    }

    /// 获取工位序号
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize {
        1
    }

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        TimingStage::Procurement
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger> {
        &self.logger
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : production.rs
//! 加工生产计时器(生产部)
//!
//! 标称耗时 70000 µs(70 ms):执模、镶嵌、抛光三道工序。
//! 计时单元在外层包裹调用,实测耗时与 90000 µs 预期对比。

use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 生产部计时器(供计时单元包裹调用)
pub struct ProductionHandler {
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl ProductionHandler {
    /// 创建生产部计时器
    ///
    /// # 参数
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 生产部计时器实例
    pub fn new(logger: Arc<dyn Logger>) -> Self {
        Self { logger }
    }
}

impl TimingProfiler for ProductionHandler {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str {
        TimingStage::Production.id()
    }

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str {
        TimingStage::Production.name()
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str {
        TimingStage::Production.department()
    }

    /// 获取标称业务耗时
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64 {
        70_000
    }

    /// 执行业务(执模、镶嵌、抛光三道工序入库)
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务完成
    /// - `Err(ProcessError)`:数据校验失败
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        let planned_micros = self.base_micros() + task.extra_micros;
        thread::sleep(Duration::from_micros(planned_micros));
        self.logger.debug(&format!(
            "【{}】受理计时任务:{}(计划耗时 {} µs,工位 {})",
            self.department(),
            task.describe(),
            planned_micros,
            self.step_index()
        ));

        if task.jewelry.weight_grams <= 0.0 {
            self.logger.warn(&format!(
                "【{}】任务 {} 珠宝重量非法:{} 克,拒绝排产",
                self.department(),
                task.task_id,
                task.jewelry.weight_grams
            ));
            return Err(ProcessError::new(
                "VALIDATE_FAILED",
                "珠宝重量非法,无法排产",
            ));
        }

        Ok(ProcessResponseDto::new(
            &task.task_id,
            TimingStage::Production.name(),
            true,
            "加工生产完成:执模、镶嵌、抛光三道工序已入库",
        ))
    }

    /// 获取工位序号
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize {
        3
    }

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        TimingStage::Production
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger> {
        &self.logger
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : training.rs
//! 培训计时器(培训部)
//!
//! 标称耗时 60000 µs(60 ms):导购话术与售后培训归档。
//! 计时单元在外层包裹调用,实测耗时与 75000 µs 预期对比。

use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 培训部计时器(供计时单元包裹调用)
pub struct TrainingHandler {
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl TrainingHandler {
    /// 创建培训部计时器
    ///
    /// # 参数
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 培训部计时器实例
    pub fn new(logger: Arc<dyn Logger>) -> Self {
        Self { logger }
    }
}

impl TimingProfiler for TrainingHandler {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str {
        TimingStage::Training.id()
    }

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str {
        TimingStage::Training.name()
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str {
        TimingStage::Training.department()
    }

    /// 获取标称业务耗时
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64 {
        60_000
    }

    /// 执行业务(导购话术与售后培训归档)
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:业务完成
    /// - `Err(ProcessError)`:数据校验失败
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        let planned_micros = self.base_micros() + task.extra_micros;
        thread::sleep(Duration::from_micros(planned_micros));
        self.logger.debug(&format!(
            "【{}】受理计时任务:{}(计划耗时 {} µs,工位 {})",
            self.department(),
            task.describe(),
            planned_micros,
            self.step_index()
        ));

        if task.jewelry.price <= 0.0 {
            self.logger.warn(&format!(
                "【{}】任务 {} 零售价非法:{} 元,无法编排课程",
                self.department(),
                task.task_id,
                task.jewelry.price
            ));
            return Err(ProcessError::new(
                "VALIDATE_FAILED",
                "零售价非法,无法编排课程",
            ));
        }

        Ok(ProcessResponseDto::new(
            &task.task_id,
            TimingStage::Training.name(),
            true,
            "培训完成:导购话术与售后培训已归档",
        ))
    }

    /// 获取工位序号
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize {
        12
    }

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        TimingStage::Training
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger> {
        &self.logger
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : jewelry_timing_hub.rs
//! 计时调度中心(Jewelry Timing Hub)
//!
//! 职责:
//! 1. 注册 12 个部门的计时单元(`RwLock<Vec<Arc<dyn TimingController>>>`,读写分离);
//! 2. 按阶段标识把「一次业务调用」交给对应计时单元包裹(拿到实测耗时与判定);
//! 3. 用 `Barrier` 让 12 个作业同时起跑,用 `mpsc` 回收结果并按提交序号保序;
//! 4. 汇总全局累计(次数 / 合计 / 偏慢 / 超预算 / 失败)与全局时间线;
//! 5. 提供 P50 / P95 统计、瓶颈 Top N 报告与系统自述状态。
//!
//! 线程安全:注册表用 `RwLock`,计数字段用原子,时间线用 `Mutex`;
//! 批量执行时每个作业独立线程,结果按序号回填,缺项有明确兜底,不会静默丢结果。

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{mpsc, Arc, Barrier, Mutex, RwLock};
use std::thread;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::timing::controller::TimingController;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::registry::TimingRegistry;
use crate::domain::timing::report::{TimingOutcome, TIMING_CALL_FAILED, TIMING_UNIT_NOT_FOUND};
use crate::domain::timing::stats::TimingStats;
use crate::domain::timing::task::TimingTask;
use crate::domain::timing::timeline::{TimelineEntry, TimingTimeline};

/// 一次待计时的作业(阶段标识 + 对端计时器 + 任务)
pub struct TimingJob {
    /// 阶段标识(用于查表定位计时单元)
    pub stage_id: &'static str,
    /// 对端计时器实现
    pub profiler: Arc<dyn TimingProfiler>,
    /// 计时任务
    pub task: TimingTask,
}

impl TimingJob {
    /// 创建计时作业
    ///
    /// # 参数
    /// - `stage_id`:阶段标识
    /// - `profiler`:对端计时器实现
    /// - `task`:计时任务
    ///
    /// # 返回
    /// 计时作业实例
    pub fn new(
        stage_id: &'static str,
        profiler: Arc<dyn TimingProfiler>,
        task: TimingTask,
    ) -> Self {
        Self {
            stage_id,
            profiler,
            task,
        }
    }
}

/// 全局计时聚合(各判定档位的累计次数)
#[derive(Debug, Clone, Copy, Default)]
pub struct TimingAggregate {
    /// 很快次数
    pub fast_calls: usize,
    /// 正常次数
    pub normal_calls: usize,
    /// 偏慢次数
    pub slow_calls: usize,
    /// 超预算次数
    pub over_budget_calls: usize,
    /// 失败次数
    pub failed_calls: usize,
}

impl TimingAggregate {
    /// 输出聚合描述(用于日志与控制台展示)
    ///
    /// # 返回
    /// 中文描述字符串
    pub fn describe(&self) -> String {
        format!(
            "很快 {} / 正常 {} / 偏慢 {} / 超预算 {} / 失败 {}",
            self.fast_calls, self.normal_calls, self.slow_calls, self.over_budget_calls, self.failed_calls
        )
    }
}

/// 计时调度中心(注册表 + 并发批量 + 全局时间线)
pub struct JewelryTimingHub {
    /// 已注册的计时单元(读写分离,读多写少)
    units: RwLock<Vec<Arc<dyn TimingController>>>,
    /// 全部计时调用次数(含失败)
    call_count: AtomicUsize,
    /// 累计耗时(微秒)
    total_micros: AtomicU64,
    /// 很快次数
    fast_calls: AtomicUsize,
    /// 正常次数
    normal_calls: AtomicUsize,
    /// 偏慢次数
    slow_calls: AtomicUsize,
    /// 超预算次数
    over_budget_calls: AtomicUsize,
    /// 失败次数
    failed_calls: AtomicUsize,
    /// 全局时间线(互斥保护)
    timeline: Mutex<TimingTimeline>,
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl JewelryTimingHub {
    /// 创建计时调度中心
    ///
    /// # 参数
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 调度中心实例
    pub fn new(logger: Arc<dyn Logger>) -> Self {
        Self {
            units: RwLock::new(Vec::new()),
            call_count: AtomicUsize::new(0),
            total_micros: AtomicU64::new(0),
            fast_calls: AtomicUsize::new(0),
            normal_calls: AtomicUsize::new(0),
            slow_calls: AtomicUsize::new(0),
            over_budget_calls: AtomicUsize::new(0),
            failed_calls: AtomicUsize::new(0),
            timeline: Mutex::new(TimingTimeline::new()),
            logger,
        }
    }

    /// 复制一份注册表快照(避免长时间持读锁)
    ///
    /// # 返回
    /// 计时单元列表
    fn clones(&self) -> Vec<Arc<dyn TimingController>> {
        let units = match self.units.read() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        units.clone()
    }

    /// 按阶段标识定位计时单元
    ///
    /// # 参数
    /// - `stage_id`:阶段标识
    ///
    /// # 返回
    /// 计时单元(未注册返回 `None`)
    fn locate(&self, stage_id: &str) -> Option<Arc<dyn TimingController>> {
        self.clones()
            .into_iter()
            .find(|controller| controller.stage().id() == stage_id)
    }

    /// 注册一个计时单元(同阶段重复注册会被拒绝并告警)
    ///
    /// # 参数
    /// - `controller`:计时单元
    pub fn register(&self, controller: Arc<dyn TimingController>) {
        let stage_id = controller.stage().id();
        let stage_name = controller.stage().name();
        let department = controller.stage().department();
        let budget_text = controller.budget().describe();
        if self.locate(stage_id).is_some() {
            self.logger.warn(&format!(
                "【计时调度】阶段 {} 的计时单元已存在,拒绝重复注册(部门 {})",
                stage_id, department
            ));
            return;
        }
        {
            let mut units = match self.units.write() {
                Ok(guard) => guard,
                Err(poisoned) => poisoned.into_inner(),
            };
            units.push(controller);
            self.logger.info(&format!(
                "【计时调度】注册成功:{} / {} | 预算:{} | 当前单元数 {}",
                stage_id,
                stage_name,
                budget_text,
                units.len()
            ));
        }
    }

    /// 把一条计时结论累加到全局统计
    ///
    /// # 参数
    /// - `outcome`:计时结论
    fn tally(&self, outcome: &TimingOutcome) {
        self.call_count.fetch_add(1, Ordering::SeqCst);
        self.total_micros
            .fetch_add(outcome.micros(), Ordering::SeqCst);
        match outcome {
            TimingOutcome::Completed { verdict, .. } => match verdict {
                crate::domain::timing::verdict::TimingVerdict::Fast => {
                    self.fast_calls.fetch_add(1, Ordering::SeqCst);
                }
                crate::domain::timing::verdict::TimingVerdict::Normal => {
                    self.normal_calls.fetch_add(1, Ordering::SeqCst);
                }
                crate::domain::timing::verdict::TimingVerdict::Slow => {
                    self.slow_calls.fetch_add(1, Ordering::SeqCst);
                }
                crate::domain::timing::verdict::TimingVerdict::OverBudget => {
                    self.over_budget_calls.fetch_add(1, Ordering::SeqCst);
                }
            },
            TimingOutcome::Failed { .. } => {
                self.failed_calls.fetch_add(1, Ordering::SeqCst);
            }
        }
    }

    /// 把一条计时结论写入全局时间线
    ///
    /// # 参数
    /// - `outcome`:计时结论
    fn record_entry(&self, outcome: &TimingOutcome) {
        let entry = match outcome {
            TimingOutcome::Completed {
                sample,
                verdict,
                micros,
                ..
            } => TimelineEntry::new(
                sample.stage_id,
                sample.stage_name,
                *micros,
                verdict.id(),
                verdict.text(),
                verdict.is_acceptable(),
            ),
            TimingOutcome::Failed {
                stage_id,
                stage_name,
                micros,
                ..
            } => TimelineEntry::new(
                stage_id,
                stage_name,
                *micros,
                "FAILED",
                "执行失败",
                false,
            ),
        };
        let mut timeline = match self.timeline.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        timeline.push(entry);
    }

    /// 执行一次带计时的业务调用
    ///
    /// # 参数
    /// - `stage_id`:阶段标识
    /// - `profiler`:对端计时器实现
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(TimingOutcome)`:计时完成(业务成功或失败均已计时)
    /// - `Err(ProcessError)`:未找到对应计时单元
    pub fn execute(
        &self,
        stage_id: &str,
        profiler: &Arc<dyn TimingProfiler>,
        task: &TimingTask,
    ) -> Result<TimingOutcome, ProcessError> {
        let controller = match TimingRegistry::find(self, stage_id) {
            Some(controller) => controller,
            None => {
                self.logger.error(&format!(
                    "【计时调度】未找到阶段 {} 的计时单元,调用被拒绝",
                    stage_id
                ));
                return Err(ProcessError::new(
                    TIMING_UNIT_NOT_FOUND,
                    &format!("阶段 {} 的计时单元未注册,无法计时", stage_id),
                ));
            }
        };
        let outcome = controller.profile(profiler, task);
        self.tally(&outcome);
        self.record_entry(&outcome);
        Ok(outcome)
    }

    /// 并发执行一批计时作业(Barrier 同时起跑 + mpsc 保序回收)
    ///
    /// # 参数
    /// - `jobs`:计时作业列表(按提交顺序)
    ///
    /// # 返回
    /// 按提交顺序排列的计时结论
    pub fn execute_batch(&self, jobs: Vec<TimingJob>) -> Vec<TimingOutcome> {
        let total = jobs.len();
        if total == 0 {
            self.logger.warn("【计时调度】批量计时作业为空,直接返回");
            return Vec::new();
        }

        // 一、主线程先定位每个作业的计时单元,未找到的直接生成失败结论
        let mut work: Vec<(usize, Arc<dyn TimingController>, TimingJob)> = Vec::new();
        let mut early: Vec<(usize, TimingOutcome)> = Vec::new();
        let mut labels: HashMap<usize, (&'static str, &'static str, String)> = HashMap::new();
        for (index, job) in jobs.into_iter().enumerate() {
            let stage_id = job.stage_id;
            let stage_name = job.profiler.stage().name();
            let task_id = job.task.task_id.clone();
            labels.insert(index, (stage_id, stage_name, task_id.clone()));
            match self.locate(stage_id) {
                Some(controller) => work.push((index, controller, job)),
                None => {
                    self.logger.error(&format!(
                        "【计时调度】批量作业 {} 未找到阶段 {} 的计时单元",
                        index, stage_id
                    ));
                    early.push((
                        index,
                        TimingOutcome::Failed {
                            task_id,
                            stage_id,
                            stage_name,
                            micros: 0,
                            detail: format!("阶段 {} 的计时单元未注册", stage_id),
                        },
                    ));
                }
            }
        }

        // 二、并发段:Barrier 保证同时起跑
        let mut collected: HashMap<usize, TimingOutcome> = HashMap::new();
        for (index, outcome) in early {
            collected.insert(index, outcome);
        }
        if !work.is_empty() {
            let thread_count = work.len();
            let barrier = Arc::new(Barrier::new(thread_count));
            let (sender, receiver) = mpsc::channel::<(usize, Result<TimingOutcome, ProcessError>)>();
            let mut handles = Vec::with_capacity(thread_count);
            for (index, controller, job) in work {
                let barrier = Arc::clone(&barrier);
                let sender = sender.clone();
                handles.push(thread::spawn(move || {
                    barrier.wait();
                    let outcome = controller.execute(&job.profiler, &job.task);
                    if sender.send((index, Ok(outcome))).is_err() {
                        // 接收端已关闭属于异常,仅记录,不影响其它作业
                    }
                }));
            }
            drop(sender);
            for (index, result) in receiver.iter() {
                match result {
                    Ok(outcome) => {
                        collected.insert(index, outcome);
                    }
                    Err(error) => {
                        self.logger.error(&format!(
                            "【计时调度】批量作业 {} 执行异常:{}",
                            index, error
                        ));
                    }
                }
            }
            for (index, handle) in handles.into_iter().enumerate() {
                if handle.join().is_err() {
                    self.logger.error(&format!(
                        "【计时调度】批量作业线程异常终止(第 {} 个线程)",
                        index
                    ));
                }
            }
        }

        // 三、按提交序号重建结果并累加统计(保证顺序与调用方一致)
        let mut results: Vec<TimingOutcome> = Vec::with_capacity(total);
        for index in 0..total {
            match collected.remove(&index) {
                Some(outcome) => {
                    self.tally(&outcome);
                    self.record_entry(&outcome);
                    results.push(outcome);
                }
                None => {
                    let (stage_id, stage_name, task_id) = match labels.get(&index) {
                        Some(label) => (label.0, label.1, label.2.clone()),
                        None => ("UNKNOWN", "未知", format!("UNKNOWN-{:06}", index + 1)),
                    };
                    self.logger.error(&format!(
                        "【计时调度】批量作业 {} 未回收结果,按失败兜底",
                        index
                    ));
                    let outcome = TimingOutcome::Failed {
                        task_id,
                        stage_id,
                        stage_name,
                        micros: 0,
                        detail: TIMING_CALL_FAILED.to_string(),
                    };
                    self.tally(&outcome);
                    self.record_entry(&outcome);
                    results.push(outcome);
                }
            }
        }
        results
    }

    /// 获取全部计时单元的累计快照
    ///
    /// # 返回
    /// 快照列表
    pub fn snapshots(&self) -> Vec<crate::domain::timing::report::TimingSnapshot> {
        self.clones()
            .into_iter()
            .map(|controller| controller.snapshot())
            .collect()
    }

    /// 获取全局时间线的逐条描述
    ///
    /// # 返回
    /// 描述列表(首行为条目数与合计耗时)
    pub fn timeline_report(&self) -> Vec<String> {
        let timeline = match self.timeline.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        if timeline.is_empty() {
            return vec!["  (全局时间线暂无记录)".to_string()];
        }
        let mut lines = vec![format!(
            "  (全局时间线共 {} 条记录,合计 {} µs)",
            timeline.len(),
            timeline.total_micros()
        )];
        lines.extend(timeline.describe());
        lines
    }

    /// 输出各计时单元的自述状态(逐条,含单元时间线条数)
    ///
    /// # 返回
    /// 描述列表
    pub fn unit_report(&self) -> Vec<String> {
        self.clones()
            .into_iter()
            .map(|controller| {
                format!(
                    "  - [{}] {} / {} | {} | 单元时间线 {} 条",
                    controller.stage().id(),
                    controller.stage().name(),
                    controller.stage().department(),
                    controller.status_text(),
                    controller.timeline().len()
                )
            })
            .collect()
    }

    /// 获取全局瓶颈报告
    ///
    /// # 参数
    /// - `top_n`:取前多少条
    ///
    /// # 返回
    /// 瓶颈描述列表
    pub fn bottleneck_report(&self, top_n: usize) -> Vec<String> {
        let timeline = match self.timeline.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        timeline.bottleneck_report(top_n)
    }

    /// 获取全局耗时统计(含 P50 / P95)
    ///
    /// # 返回
    /// 耗时统计
    pub fn clock_stats(&self) -> TimingStats {
        let timeline = match self.timeline.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        TimingStats::from_samples(&timeline.micros_series())
    }

    /// 获取全局聚合计数
    ///
    /// # 返回
    /// 各档位累计次数
    pub fn aggregate(&self) -> TimingAggregate {
        TimingAggregate {
            fast_calls: self.fast_calls.load(Ordering::SeqCst),
            normal_calls: self.normal_calls.load(Ordering::SeqCst),
            slow_calls: self.slow_calls.load(Ordering::SeqCst),
            over_budget_calls: self.over_budget_calls.load(Ordering::SeqCst),
            failed_calls: self.failed_calls.load(Ordering::SeqCst),
        }
    }

    /// 获取全局计时调用次数(含失败)
    ///
    /// # 返回
    /// 调用次数
    pub fn timed_calls(&self) -> usize {
        self.call_count.load(Ordering::SeqCst)
    }

    /// 获取全局累计耗时
    ///
    /// # 返回
    /// 累计耗时(微秒)
    pub fn total_micros(&self) -> u64 {
        self.total_micros.load(Ordering::SeqCst)
    }

    /// 获取全局偏慢次数
    ///
    /// # 返回
    /// 偏慢次数
    pub fn slow_calls(&self) -> usize {
        self.slow_calls.load(Ordering::SeqCst)
    }

    /// 获取全局超预算次数
    ///
    /// # 返回
    /// 超预算次数
    pub fn over_budget_calls(&self) -> usize {
        self.over_budget_calls.load(Ordering::SeqCst)
    }

    /// 获取全局失败次数
    ///
    /// # 返回
    /// 失败次数
    pub fn failed_calls(&self) -> usize {
        self.failed_calls.load(Ordering::SeqCst)
    }

    /// 获取全局平均耗时
    ///
    /// # 返回
    /// 平均耗时(微秒)
    pub fn avg_micros(&self) -> u64 {
        let calls = self.timed_calls();
        if calls == 0 {
            0
        } else {
            self.total_micros() / calls as u64
        }
    }

    /// 输出系统级自述状态
    ///
    /// # 返回
    /// 中文状态描述
    pub fn status_report(&self) -> String {
        format!(
            "计时分析:计时单元 {},计时 {} 次,偏慢 {},超预算 {},失败 {},合计 {} µs,平均 {} µs(档位分布:{})",
            self.controller_count(),
            self.timed_calls(),
            self.slow_calls(),
            self.over_budget_calls(),
            self.failed_calls(),
            self.total_micros(),
            self.avg_micros(),
            self.aggregate().describe()
        )
    }
}

impl TimingRegistry for JewelryTimingHub {
    /// 注册一个计时单元(转调本类型的固有方法)
    ///
    /// # 参数
    /// - `controller`:计时单元
    fn register(&self, controller: Arc<dyn TimingController>) {
        JewelryTimingHub::register(self, controller);
    }

    /// 获取已注册的计时单元数量
    ///
    /// # 返回
    /// 单元数量
    fn controller_count(&self) -> usize {
        self.clones().len()
    }

    /// 按阶段标识查找计时单元
    ///
    /// # 参数
    /// - `stage_id`:阶段标识
    ///
    /// # 返回
    /// 计时单元(未注册返回 `None`)
    fn find(&self, stage_id: &str) -> Option<Arc<dyn TimingController>> {
        self.locate(stage_id)
    }

    /// 输出系统级自述状态
    ///
    /// # 返回
    /// 中文状态描述
    fn system_status(&self) -> String {
        self.status_report()
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : timing_guard.rs
//! 计时分析单元(Timing Guard)
//!
//! 本文件是计时函数模式的「核心动作」落地:
//! 1. 启动 `Stopwatch`(记录起点);
//! 2. 通过重试 + 熔断适配器调用对端业务(重试与退避的时间一并计入);
//! 3. 停表拿到实测微秒数;
//! 4. 按部门预算分档(很快 / 正常 / 偏慢 / 超预算);
//! 5. 累计统计(次数、总计、最快、最慢、偏慢数、超预算数)并写入时间线;
//! 6. 按档位选择日志级别(INFO / WARN / ERROR),保证控制台与文件一致。
//!
//! 线程安全:计数字段用原子操作,时间线用 `Mutex` 保护;
//! 同一单元可被多个线程并发调用,不会出现计数丢失或时间线错乱。

use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use crate::common::logging::Logger;
use crate::common::resilience::retry_circuit_breaker::RetryCircuitBreaker;
use crate::domain::timing::budget::TimingBudget;
use crate::domain::timing::controller::TimingController;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::report::{TimingOutcome, TimingSnapshot};
use crate::domain::timing::sample::TimingSample;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::stopwatch::Stopwatch;
use crate::domain::timing::task::TimingTask;
use crate::domain::timing::timeline::TimelineEntry;
use crate::domain::timing::verdict::{classify, TimingVerdict};

/// 时间线保留的最大条目数(防止长时间运行无限增长)
const HISTORY_LIMIT: usize = 200;

/// 计时分析单元(某部门的计时窗口)
pub struct TimingGuard {
    /// 所属阶段
    stage: TimingStage,
    /// 耗时预算
    budget: TimingBudget,
    /// 计时调用次数
    timed_calls: AtomicUsize,
    /// 累计耗时(微秒)
    total_micros: AtomicU64,
    /// 偏慢次数
    slow_calls: AtomicUsize,
    /// 超预算次数
    over_budget_calls: AtomicUsize,
    /// 最快耗时(微秒,0 表示尚未记录)
    fastest_micros: AtomicU64,
    /// 最慢耗时(微秒,0 表示尚未记录)
    slowest_micros: AtomicU64,
    /// 最近的时间线记录(互斥保护)
    history: Mutex<Vec<TimelineEntry>>,
    /// 重试 + 熔断适配器(保护对端调用)
    resilience: Arc<RetryCircuitBreaker>,
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl TimingGuard {
    /// 创建计时分析单元
    ///
    /// # 参数
    /// - `stage`:所属阶段
    /// - `resilience`:重试 + 熔断适配器
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 计时分析单元实例
    pub fn new(
        stage: TimingStage,
        resilience: Arc<RetryCircuitBreaker>,
        logger: Arc<dyn Logger>,
    ) -> Self {
        Self {
            stage,
            budget: stage.budget(),
            timed_calls: AtomicUsize::new(0),
            total_micros: AtomicU64::new(0),
            slow_calls: AtomicUsize::new(0),
            over_budget_calls: AtomicUsize::new(0),
            fastest_micros: AtomicU64::new(0),
            slowest_micros: AtomicU64::new(0),
            history: Mutex::new(Vec::new()),
            resilience,
            logger,
        }
    }

    /// 记录最快耗时(原子比较更新,0 代表尚未记录)
    ///
    /// # 参数
    /// - `micros`:本次实测耗时(微秒)
    fn record_fastest(&self, micros: u64) {
        let _ = self.fastest_micros.fetch_update(
            Ordering::SeqCst,
            Ordering::SeqCst,
            |current| {
                if current == 0 || micros < current {
                    Some(micros)
                } else {
                    None
                }
            },
        );
    }

    /// 记录最慢耗时(原子比较更新,0 代表尚未记录)
    ///
    /// # 参数
    /// - `micros`:本次实测耗时(微秒)
    fn record_slowest(&self, micros: u64) {
        let _ = self.slowest_micros.fetch_update(
            Ordering::SeqCst,
            Ordering::SeqCst,
            |current| {
                if current == 0 || micros > current {
                    Some(micros)
                } else {
                    None
                }
            },
        );
    }

    /// 写入时间线(超出上限时丢弃最旧一条)
    ///
    /// # 参数
    /// - `entry`:时间线条目
    fn record_entry(&self, entry: TimelineEntry) {
        let mut history = match self.history.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        history.push(entry);
        if history.len() > HISTORY_LIMIT {
            history.remove(0);
        }
    }
}

impl TimingController for TimingGuard {
    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        self.stage
    }

    /// 获取耗时预算
    ///
    /// # 返回
    /// 耗时预算
    fn budget(&self) -> TimingBudget {
        self.budget
    }

    /// 计时包裹一次业务调用(采样 + 判定 + 累计 + 落日志)
    ///
    /// # 参数
    /// - `profiler`:对端计时器实现
    /// - `task`:计时任务
    ///
    /// # 返回
    /// 计时结论
    fn profile(&self, profiler: &Arc<dyn TimingProfiler>, task: &TimingTask) -> TimingOutcome {
        self.timed_calls.fetch_add(1, Ordering::SeqCst);

        // 一、启动计时器(记录起点)
        let watch = Stopwatch::start(&self.stage.controller_name());
        self.logger.debug(&format!(
            "【计时】{} 启动秒表:{}(对端标称 {} µs,预算 {} µs)",
            self.stage.controller_name(),
            task.describe(),
            profiler.base_micros(),
            self.budget.expected_micros
        ));

        // 二、包裹调用(重试与退避的时间一并计入实测耗时)
        let result = self.resilience.execute(|| profiler.execute(task));

        // 三、停表并判定
        let micros = watch.elapsed_micros();
        let verdict = classify(micros, &self.budget);
        self.logger.debug(&format!(
            "【计时】{} 停表读数:标签 {} | {} µs({} ms)| 秒表自述 {}",
            self.stage.name(),
            watch.label(),
            micros,
            watch.elapsed_millis(),
            watch.describe()
        ));
        self.logger.debug(&format!(
            "【计时】{} 预算核对:预期内={} / 偏慢={} / 超预算={}(实测 {} µs,预期 {} µs,偏慢线 {} µs,超预算线 {} µs)",
            self.stage.name(),
            self.budget.within_expected(micros),
            self.budget.is_slow(micros),
            self.budget.is_danger(micros),
            micros,
            self.budget.expected_micros,
            self.budget.slow_micros,
            self.budget.danger_micros
        ));
        profiler.logger().debug(&format!(
            "【计时】对端 {}({})业务调用返回,交由计时单元判定",
            profiler.profiler_name(),
            profiler.department()
        ));

        // 四、累计统计(原子操作,线程安全)
        self.total_micros.fetch_add(micros, Ordering::SeqCst);
        match verdict {
            TimingVerdict::Slow => {
                self.slow_calls.fetch_add(1, Ordering::SeqCst);
            }
            TimingVerdict::OverBudget => {
                self.over_budget_calls.fetch_add(1, Ordering::SeqCst);
            }
            TimingVerdict::Fast | TimingVerdict::Normal => {}
        }
        self.record_fastest(micros);
        self.record_slowest(micros);

        // 五、写入时间线(互斥保护)
        let entry = TimelineEntry::new(
            self.stage.id(),
            self.stage.name(),
            micros,
            verdict.id(),
            verdict.text(),
            verdict.is_acceptable(),
        );
        self.record_entry(entry);

        // 六、按档位落日志并构造结论
        match result {
            Ok(response) => {
                let sample = TimingSample::new(
                    self.stage.id(),
                    self.stage.name(),
                    micros,
                    verdict.is_acceptable(),
                );
                match verdict {
                    TimingVerdict::Fast | TimingVerdict::Normal => self.logger.info(&format!(
                        "【计时】{} 完成:{} | 实测 {} µs({:.3} ms)| 判定 {}/{} | 预算 {} µs",
                        self.stage.name(),
                        response.message,
                        micros,
                        (micros as f64) / 1000.0,
                        verdict.text(),
                        verdict.id(),
                        self.budget.expected_micros
                    )),
                    TimingVerdict::Slow => self.logger.warn(&format!(
                        "【计时】{} 偏慢:实测 {} µs({:.3} ms)越过偏慢阈值 {} µs | 判定 {}/{} | 对端标称 {} µs",
                        self.stage.name(),
                        micros,
                        (micros as f64) / 1000.0,
                        self.budget.slow_micros,
                        verdict.text(),
                        verdict.id(),
                        profiler.base_micros()
                    )),
                    TimingVerdict::OverBudget => self.logger.error(&format!(
                        "【计时】{} 超预算:实测 {} µs({:.3} ms)越过超预算阈值 {} µs | 判定 {}/{} | 业务虽完成但耗时不可接受",
                        self.stage.name(),
                        micros,
                        (micros as f64) / 1000.0,
                        self.budget.danger_micros,
                        verdict.text(),
                        verdict.id()
                    )),
                }
                TimingOutcome::Completed {
                    response,
                    sample,
                    verdict,
                    micros,
                }
            }
            Err(err) => {
                self.logger.error(&format!(
                    "【计时】{} 业务失败:已耗时 {} µs({:.3} ms),原因:{}",
                    self.stage.name(),
                    micros,
                    (micros as f64) / 1000.0,
                    err
                ));
                TimingOutcome::Failed {
                    task_id: task.task_id.clone(),
                    stage_id: self.stage.id(),
                    stage_name: self.stage.name(),
                    micros,
                    detail: err.to_string(),
                }
            }
        }
    }

    /// 获取累计统计快照
    ///
    /// # 返回
    /// 统计快照
    fn snapshot(&self) -> TimingSnapshot {
        let timed_calls = self.timed_calls.load(Ordering::SeqCst);
        let total_micros = self.total_micros.load(Ordering::SeqCst);
        let average = if timed_calls == 0 {
            0
        } else {
            total_micros / timed_calls as u64
        };
        TimingSnapshot {
            stage_id: self.stage.id(),
            stage_name: self.stage.name(),
            department: self.stage.department(),
            budget_text: self.budget.describe(),
            timed_calls,
            total_micros,
            avg_micros: average,
            slow_calls: self.slow_calls.load(Ordering::SeqCst),
            over_budget_calls: self.over_budget_calls.load(Ordering::SeqCst),
            fastest_micros: self.fastest_micros.load(Ordering::SeqCst),
            slowest_micros: self.slowest_micros.load(Ordering::SeqCst),
        }
    }

    /// 输出自述状态(用于监控汇总展示)
    ///
    /// # 返回
    /// 中文状态描述
    fn status_text(&self) -> String {
        let snapshot = self.snapshot();
        format!(
            "预算 {} | 计时 {} 次 | 偏慢 {} | 超预算 {} | 平均 {} µs | 最快 {} µs | 最慢 {} µs",
            snapshot.budget_text,
            snapshot.timed_calls,
            snapshot.slow_calls,
            snapshot.over_budget_calls,
            snapshot.avg_micros,
            snapshot.fastest_micros,
            snapshot.slowest_micros
        )
    }

    /// 获取最近的时间线记录(克隆返回,避免锁外持有)
    ///
    /// # 返回
    /// 时间线条目列表
    fn timeline(&self) -> Vec<TimelineEntry> {
        let history = match self.history.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        history.clone()
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : untimed_direct_client.rs
//! 无计时直连对照(Untimed Direct Client)
//!
//! 对照组:老系统直接调用对端,只知道「整单花了多久」,不知道「哪一步花了多久」。
//! 演示时用它和计时单元做对照------同样一次慢调用,
//! 计时侧能给出「第 8 站营销偏慢 85 ms,占全程 13%」这样的靶点,
//! 直连侧只能得到「整单 100 ms 后失败了」,无法定位。

use std::sync::Arc;
use std::thread;
use std::time::Duration;

use crate::common::error::ProcessError;
use crate::common::logging::Logger;
use crate::domain::dtos::process_dtos::ProcessResponseDto;
use crate::domain::timing::budget::TimingBudget;
use crate::domain::timing::profiler::TimingProfiler;
use crate::domain::timing::stage::TimingStage;
use crate::domain::timing::task::TimingTask;

/// 无计时直连调用(历史遗留实现)
pub struct UntimedDirectClient {
    /// 单笔固定耗时(毫秒)
    delay_millis: u64,
    /// 统一日志对象
    logger: Arc<dyn Logger>,
}

impl UntimedDirectClient {
    /// 创建无计时直连调用
    ///
    /// # 参数
    /// - `delay_millis`:单笔固定耗时(毫秒)
    /// - `logger`:统一日志对象
    ///
    /// # 返回
    /// 直连调用实例
    pub fn new(delay_millis: u64, logger: Arc<dyn Logger>) -> Self {
        Self {
            delay_millis,
            logger,
        }
    }

    /// 获取单笔固定耗时
    ///
    /// # 返回
    /// 固定耗时(毫秒)
    pub fn delay_millis(&self) -> u64 {
        self.delay_millis
    }

    /// 直接调用对端(无任何计时埋点)
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:调用完成
    /// - `Err(ProcessError)`:调用失败
    pub fn direct_call(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        thread::sleep(Duration::from_millis(self.delay_millis));
        self.logger.warn(&format!(
            "【无计时直连】任务 {} 已耗时 {} ms:只知道总耗时,无法分解各步骤耗时",
            task.task_id, self.delay_millis
        ));
        if task.topic.trim().is_empty() {
            return Err(ProcessError::new(
                "TOPIC_UNSUPPORTED",
                "业务主题为空,直连调用被对端拒绝",
            ));
        }
        if task.extra_micros > 300_000 {
            return Err(ProcessError::new(
                "OVERLOAD_COLLAPSE",
                &format!(
                    "注入额外耗时 {} µs 已压垮对端:{} ms 处理完后才发现,期间无法定位慢在哪一步",
                    task.extra_micros, self.delay_millis
                ),
            ));
        }
        Ok(ProcessResponseDto::new(
            &task.task_id,
            TimingStage::It.name(),
            true,
            "历史直连完成:整单耗时只有总数,无法定位慢在哪一步",
        ))
    }
}

impl TimingProfiler for UntimedDirectClient {
    /// 获取计时器标识
    ///
    /// # 返回
    /// 计时器标识
    fn profiler_id(&self) -> &'static str {
        "LEGACY_UNTIMED"
    }

    /// 获取计时器中文名称
    ///
    /// # 返回
    /// 计时器名称
    fn profiler_name(&self) -> &'static str {
        "历史遗留无计时直连调用"
    }

    /// 获取所属部门
    ///
    /// # 返回
    /// 部门名称
    fn department(&self) -> &'static str {
        "信息技术部"
    }

    /// 获取耗时预算(刻意放宽:无计时系统根本没有预算概念)
    ///
    /// # 返回
    /// 耗时预算
    fn budget(&self) -> TimingBudget {
        TimingBudget::new("信息技术部(无计时预算)", 500_000, 800_000, 1_000_000)
    }

    /// 获取标称业务耗时
    ///
    /// # 返回
    /// 标称耗时(微秒)
    fn base_micros(&self) -> u64 {
        self.delay_millis * 1000
    }

    /// 执行业务(直接调用,无计时埋点)
    ///
    /// # 参数
    /// - `task`:计时任务
    ///
    /// # 返回
    /// - `Ok(ProcessResponseDto)`:调用完成
    /// - `Err(ProcessError)`:调用失败
    fn execute(&self, task: &TimingTask) -> Result<ProcessResponseDto, ProcessError> {
        self.direct_call(task)
    }

    /// 获取工位序号(对照组不占正式工位)
    ///
    /// # 返回
    /// 工位序号
    fn step_index(&self) -> usize {
        0
    }

    /// 获取所属阶段
    ///
    /// # 返回
    /// 阶段枚举
    fn stage(&self) -> TimingStage {
        TimingStage::It
    }

    /// 获取统一日志对象
    ///
    /// # 返回
    /// 日志对象引用
    fn logger(&self) -> &Arc<dyn Logger> {
        &self.logger
    }
}//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : retry_circuit_breaker.rs
//! 重试 + 熔断适配器(Resilience Adapter)
//!
//! 作用:在中介者协调同事执行依赖外部系统(如质检系统、物流接口、财务网关)时,
//! 提供「自动重试 + 熔断保护」:
//! - **重试**:瞬时失败时按指数退避重试,直至达到最大重试次数。
//! - **熔断**:连续失败达到阈值后打开熔断器,快速失败(不再重试),
//!   经冷却时间后进入半开状态,试探恢复。
//!
//! 线程安全:内部状态使用 `Mutex` 保护,可被 `Arc` 共享到多个线程高并发使用。

use std::sync::Mutex;
use std::time::{Duration, Instant};

use crate::common::error::ProcessError;

/// 熔断器打开错误码
const ERROR_CIRCUIT_OPEN: &str = "CIRCUIT_OPEN";

/// 熔断器状态
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CircuitState {
    /// 关闭(正常运行,允许调用)
    Closed,
    /// 打开(熔断,快速失败)
    Open,
    /// 半开(冷却结束,试探性放行一次)
    HalfOpen,
}

/// 熔断器内部状态(受互斥锁保护)
struct CircuitInner {
    /// 当前熔断状态
    state: CircuitState,
    /// 连续失败次数
    consecutive_failures: u32,
    /// 熔断打开时刻(用于计算冷却时间)
    opened_at: Option<Instant>,
}

/// 重试 + 熔断适配器(线程安全、可共享)
pub struct RetryCircuitBreaker {
    /// 最大重试次数(成功之前最多额外尝试的次数)
    max_retries: u32,
    /// 熔断失败阈值(连续失败达到该次数即打开熔断器)
    failure_threshold: u32,
    /// 熔断冷却时间(打开后等待该时长才允许半开试探)
    cooldown: Duration,
    /// 内部熔断状态
    inner: Mutex<CircuitInner>,
}

impl RetryCircuitBreaker {
    /// 创建重试 + 熔断适配器
    ///
    /// # 参数
    /// - `max_retries`:最大重试次数
    /// - `failure_threshold`:熔断失败阈值
    /// - `cooldown`:熔断冷却时长
    ///
    /// # 返回
    /// 适配器实例
    pub fn new(max_retries: u32, failure_threshold: u32, cooldown: Duration) -> Self {
        Self {
            max_retries,
            failure_threshold,
            cooldown,
            inner: Mutex::new(CircuitInner {
                state: CircuitState::Closed,
                consecutive_failures: 0,
                opened_at: None,
            }),
        }
    }

    /// 获取当前熔断状态(用于日志输出)
    ///
    /// # 返回
    /// 当前 `CircuitState`
    #[allow(dead_code)]
    pub fn state(&self) -> CircuitState {
        self.inner
            .lock()
            .map(|g| g.state)
            .unwrap_or(CircuitState::Closed)
    }

    /// 执行受保护的操作:带「重试 + 熔断」
    ///
    /// # 泛型参数
    /// - `F`:操作闭包类型
    /// - `O`:成功返回值类型
    ///
    /// # 参数
    /// - `operation`:返回 `Result<O, ProcessError>` 的操作闭包
    ///
    /// # 返回
    /// - `Ok(O)`:操作最终成功
    /// - `Err(ProcessError)`:重试耗尽或熔断快速失败
    pub fn execute<F, O>(&self, operation: F) -> Result<O, ProcessError>
    where
        F: Fn() -> Result<O, ProcessError>,
    {
        // 步骤一:熔断前置检查(快速失败)
        {
            let mut guard = self.inner.lock().unwrap();
            if guard.state == CircuitState::Open {
                if let Some(opened_at) = guard.opened_at {
                    // 冷却时间未过 → 直接快速失败
                    if opened_at.elapsed() < self.cooldown {
                        return Err(ProcessError::new(
                            ERROR_CIRCUIT_OPEN,
                            "熔断器已打开,请求快速失败,请稍后重试",
                        ));
                    }
                }
                // 冷却时间已过 → 转为半开状态,允许一次试探
                guard.state = CircuitState::HalfOpen;
            }
        }

        // 步骤二:带重试地执行操作
        let mut attempt = 0u32;
        loop {
            match operation() {
                Ok(value) => {
                    // 成功:重置失败计数,恢复关闭状态
                    let mut guard = self.inner.lock().unwrap();
                    guard.consecutive_failures = 0;
                    guard.state = CircuitState::Closed;
                    guard.opened_at = None;
                    return Ok(value);
                }
                Err(err) => {
                    attempt += 1;
                    {
                        let mut guard = self.inner.lock().unwrap();
                        guard.consecutive_failures += 1;
                        // 连续失败达到阈值 → 打开熔断器
                        if guard.consecutive_failures >= self.failure_threshold {
                            guard.state = CircuitState::Open;
                            guard.opened_at = Some(Instant::now());
                            return Err(err);
                        }
                    }
                    // 未熔断但重试次数已耗尽 → 返回错误
                    if attempt > self.max_retries {
                        return Err(err);
                    }
                    // 指数退避等待后重试
                    std::thread::sleep(Duration::from_millis(100 * attempt as u64));
                }
            }
        }
    }
}
//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : error.rs
//! 统一错误类型定义
//!
//! 全项目统一使用 `ProcessError` 作为业务错误载体,携带错误码与消息,
//! 便于上层(应用层/接口层/表现层)统一捕获与日志输出。

/// 业务流程错误(统一错误载体)
#[derive(Debug, Clone)]
pub struct ProcessError {
    /// 错误码(如 EXECUTION_FAILED / CIRCUIT_OPEN 等)
    pub code: String,
    /// 错误消息(中文,可直接输出到日志与界面)
    pub message: String,
}

impl ProcessError {
    /// 创建业务流程错误
    ///
    /// # 参数
    /// - `code`:错误码
    /// - `message`:错误消息
    ///
    /// # 返回
    /// 构造好的 `ProcessError` 实例
    pub fn new(code: &str, message: &str) -> Self {
        Self {
            code: code.to_string(),
            message: message.to_string(),
        }
    }
}

/// 格式化输出(支持 `{}` 直接打印)
impl std::fmt::Display for ProcessError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}] {}", self.code, self.message)
    }
}

/// 实现标准 Error trait,可向上转换为 `Box<dyn Error>`
impl std::error::Error for ProcessError {}

/// 预留的标准错误码字典(供上层业务模块调用,作为统一错误码契约预留给扩展)
#[allow(dead_code)]
pub mod error_code {
    /// 前置校验失败
    pub const VALIDATE_FAILED: &str = "VALIDATE_FAILED";
    /// 业务执行失败
    pub const EXECUTION_FAILED: &str = "EXECUTION_FAILED";
    /// 熔断器打开(下游连续失败,直接短路,不再发起真实调用)
    pub const CIRCUIT_OPEN: &str = "CIRCUIT_OPEN";
    /// 资源未找到
    pub const NOT_FOUND: &str = "NOT_FOUND";
}
//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : logging.rs
//! 统一日志抽象接口(对应 C# 中的 `ILogger<T>`)
//!
//! 所有组件(调度器、中介者、同事、入口)仅依赖该接口输出日志,
//! 具体实现(文件日志)由基础设施层通过 DI 注入。
//! 保证控制台输出与日志文件输出格式完全一致。
//!
//! 日志文件规约:
//! ```text
//! Logs/
//!   2026-07-06/
//!     app-info.log
//!     app-error.log
//!     app-debug.log
//!     app-warn.log
//! ```

/// 日志等级
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
    /// 调试(用于输出详细执行过程)
    Debug,
    /// 信息(用于输出常规流程状态)
    Info,
    /// 警告(用于输出可恢复异常)
    Warn,
    /// 错误(用于输出失败/异常)
    Error,
}

impl LogLevel {
    /// 获取日志等级标签(用于日志前缀,控制台与文件一致)
    ///
    /// # 返回
    /// 等级标签字符串
    pub fn tag(&self) -> &'static str {
        match self {
            LogLevel::Debug => "DEBUG",
            LogLevel::Info => "INFO",
            LogLevel::Warn => "WARN",
            LogLevel::Error => "ERROR",
        }
    }

    /// 获取日志等级对应的文件名(按等级分文件)
    ///
    /// # 返回
    /// 文件名(如 `app-info.log`)
    pub fn file_name(&self) -> &'static str {
        match self {
            LogLevel::Debug => "app-debug.log",
            LogLevel::Info => "app-info.log",
            LogLevel::Warn => "app-warn.log",
            LogLevel::Error => "app-error.log",
        }
    }
}

/// 统一日志接口(线程安全、可对象化注入使用)
///
/// 设计要点:
/// - `Send + Sync` 保证可在多线程/高并发环境下共享(`Arc<dyn Logger>`)
/// - 方法非泛型,保持对象安全(object-safe),可向上转型为 trait 对象注入
pub trait Logger: Send + Sync {
    /// 输出调试日志
    ///
    /// # 参数
    /// - `message`:日志消息
    fn debug(&self, message: &str);

    /// 输出信息日志
    ///
    /// # 参数
    /// - `message`:日志消息
    fn info(&self, message: &str);

    /// 输出警告日志
    ///
    /// # 参数
    /// - `message`:日志消息
    fn warn(&self, message: &str);

    /// 输出错误日志
    ///
    /// # 参数
    /// - `message`:日志消息
    fn error(&self, message: &str);
}
//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : result.rs
//! 统一结果返回类型
//!
//! 用于表现层/接口层向调用方返回统一结构的操作结果,保证输出格式一致。

/// 通用操作结果(泛型,表现层返回载体)
///
/// 预留给需要结构化返回(成功/失败 + 业务数据)的调用方使用;
/// 当前控制台演示直接输出日志,未构造该结果,属预留 API。
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct ApiResult<T> {
    /// 是否成功
    pub success: bool,
    /// 结果消息
    pub message: String,
    /// 业务数据(可选)
    pub data: Option<T>,
}

impl<T> ApiResult<T> {
    /// 创建成功结果
    ///
    /// # 参数
    /// - `data`:业务数据
    ///
    /// # 返回
    /// 成功结果
    #[allow(dead_code)]
    pub fn ok(data: T) -> Self {
        Self {
            success: true,
            message: "操作成功".to_string(),
            data: Some(data),
        }
    }

    /// 创建失败结果
    ///
    /// # 参数
    /// - `message`:失败消息
    ///
    /// # 返回
    /// 失败结果
    #[allow(dead_code)]
    pub fn err(message: &str) -> Self {
        Self {
            success: false,
            message: message.to_string(),
            data: None,
        }
    }
}

调用:

rust 复制代码
//!# encoding: utf-8 
//!# 版权所有  2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Timing Functions Pattern 计时函数模式  Profiling Patterns  性能分析型模式
//!# Author    : geovindu,Geovin Du 涂聚文.
//!# IDE       : RustRover  2025.1.1 Rust  rustc 1.98.1 
//!# os        : windows 10
//!# database  : mysql 9.0 sql server 2025, postgreSQL 18.0  Oracle 21c Neo4j
//!# Datetime  : 2026/11/21 9:34 
//!# User      :  geovindu
//!# Product   : RustRover
//!# Project   : TimingFunctionsPattern
//!# File      : main.rs
//! Timing Functions 计时函数模式(Timing Functions Pattern)--- 珠宝行业全程业务
//!
//! 业务范围:原料采购核验、设计制图、加工生产、质检、包装、物流、财务、
//!           营销推广、业务销售、人事行政、IT、培训。
//!
//! Timing Functions 模式核心思想(如实测量、明确判定,不拦截业务):
//! - **预算必须量化**:每个部门声明「预期 / 偏慢 / 超预算」三档微秒阈值。
//!   没有预算的计时只是数字,有预算的计时才是结论;预算按部门独立,不搞全局平均。
//! - **秒表用单调时钟**:`Stopwatch` 基于 `Instant` 记录单调递增的起点,不受系统时间
//!   回拨影响;`elapsed_micros` 保底返回 1 µs,避免零耗时样本把统计口径压平。
//! - **四档判定**:`classify` 把实测值分为很快 / 正常 / 偏慢 / 超预算,档位决定日志级别
//!   (INFO / INFO / WARN / ERROR),让「慢」在日志里天然显眼。
//! - **计时与提交同一动作**:`profile` 就是「秒表包裹业务调用」,计时与业务结果一次拿全,
//!   不需要业务侧再埋点,也不会出现「计时一套、执行一套」的双份真相。
//! - **平均值会骗人**:`TimingStats` 同时给 P50 与 P95,长尾必须单独看,
//!   否则 11 次 60 ms 加 1 次 600 ms 会被平均成一个「还行」。
//! - **时间线找瓶颈**:`TimingTimeline` 记录每一站耗时,`bottleneck_report` 给 Top N
//!   排名与占全程百分比,把「整单慢」翻译成「第 8 站慢」。
//! - **无计时直连对照**:历史直连只能拿到整单总耗时,出问题无法定位;
//!   与计时侧同跑一次,可直观看出「有计时」和「只知道慢」的差别。
//!
//! 工程化特性:
//! - 日志按日期分文件夹、按日志等级分文件(Logs/<日期>/app-{info,error,debug,warn}.log)
//! - 注入统一日志对象 `Arc<dyn Logger>`(对应 C# 的 `ILogger<T>`)
//! - DTO 业务传输对象、适配器「重试 + 熔断」(重试与退避耗时一并计入实测)
//! - 兼容依赖注入(DI)、线程安全、高并发写入
//! - 调度器 / 计时单元 / 计时器 / 入口全部使用统一标准日志,控制台与文件输出完全一致
//!
//! DDD 严格分层(依赖方向:presentation → interface → application → domain → common;
//! infrastructure 实现 domain/interface 定义的接口):
//! - domain          领域层(实体、DTO、耗时预算/秒表/采样/判定/阶段/任务/统计/时间线/
//!                   计时结论、计时单元与计时器抽象、注册表)
//! - common          通用层(错误、结果、日志接口、重试熔断适配器)
//! - application     应用层(计时分析单元、计时调度中心、无计时直连对照、12 个部门计时器、应用服务)
//! - infrastructure  基础设施层(文件日志、DI 容器、内存仓储)
//! - interface       接口层(对外端口契约、业务信封契约)
//! - presentation    表现层(控制台入口 / 组合根装配 / 端口实现)

// 声明顶层模块(对应六个文件夹)
mod application;
mod common;
mod domain;
mod infrastructure;
mod interface;
mod presentation;

use std::sync::Arc;

use infrastructure::di::container::ServiceContainer;
use presentation::console::controller::ApplicationController;

/// 程序入口(组合根:装配依赖注入容器 → 创建应用控制器 → 启动计时模式演示)
fn main() {
    // 1. 构建依赖注入容器(组合根,统一装配 12 个计时器与全部服务)
    let container = Arc::new(ServiceContainer::new());

    // 2. 创建应用控制器(表现层,实现 interface 定义的对外端口契约)
    let controller = ApplicationController::new(container);

    // 3. 启动珠宝行业全程业务流程(Timing Functions 计时函数模式)演示
    controller.run();
}

输出:

相关推荐
geovindu1 小时前
python:Lasso
开发语言·后端·python·算法
Csvn1 小时前
Nginx HTTPS 与安全加固:会话复用、OCSP、mTLS 与限流取舍
后端·nginx
多加点辣也没关系1 小时前
JavaScript|第42章:安全与最佳实践
开发语言·javascript·安全
码云社区1 小时前
Spring Boot上门按摩服务系统源码:上门到店服务目录与门店协同方案
java·spring boot·后端·上门服务·上门按摩·上门小程序
3095566662 小时前
股票数据落库前的去重与主键设计:一次 SQLite 写入实录
java·开发语言·jvm·数据库·redis·python·sqlite
AAA修煤气灶刘哥2 小时前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
Cosolar2 小时前
LoopForge:把团队的交付经验变成可执行的工程资产
人工智能·后端·agent
tong_li2 小时前
给娃做个 AI 陪写作业助手:LangChain4j 入门(四):向量库搬进 Qdrant(向量数据库入门)
后端
Rain的Java大神之路2 小时前
大表 JOIN 不必靠堆内存:Dojao 的跨源 SQL、减量溢写与 Python UDF 实战
java·大数据·后端