Skip to main content

alun_task/
types.rs

1//! 任务类型、状态、优先级、重试策略等枚举和配置
2
3use serde::{Deserialize, Serialize};
4
5/// 任务状态枚举
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
7#[repr(i16)]
8pub enum TaskStatus {
9    /// 待处理
10    Pending = 1,
11    /// 处理中
12    Processing = 2,
13    /// 已完成
14    Completed = 3,
15    /// 失败
16    Failed = 4,
17    /// 已取消
18    Cancelled = 5,
19    /// 已调度(定时任务)
20    Scheduled = 6,
21    /// 死信队列 —— 超过最大重试次数后转入此状态
22    DeadLetter = 7,
23}
24
25impl TaskStatus {
26    /// 从 i16 值转换为 TaskStatus 枚举
27    pub fn from_i16(v: i16) -> Option<Self> {
28        match v {
29            1 => Some(Self::Pending),
30            2 => Some(Self::Processing),
31            3 => Some(Self::Completed),
32            4 => Some(Self::Failed),
33            5 => Some(Self::Cancelled),
34            6 => Some(Self::Scheduled),
35            7 => Some(Self::DeadLetter),
36            _ => None,
37        }
38    }
39
40    /// 将 TaskStatus 枚举转换为 i16 值
41    pub fn to_i16(self) -> i16 {
42        self as i16
43    }
44
45    /// 判断是否为终态(不会再流转)
46    pub fn is_terminal(self) -> bool {
47        matches!(self, Self::Completed | Self::Cancelled | Self::DeadLetter)
48    }
49}
50
51/// 任务优先级
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
53#[repr(i16)]
54pub enum TaskPriority {
55    /// 低优先级
56    Low = 1,
57    /// 普通优先级
58    Normal = 2,
59    /// 高优先级
60    High = 3,
61    /// 紧急优先级
62    Critical = 4,
63}
64
65impl TaskPriority {
66    /// 从 i16 值转换为 TaskPriority 枚举
67    pub fn from_i16(v: i16) -> Self {
68        match v {
69            3 => Self::High,
70            4 => Self::Critical,
71            1 => Self::Low,
72            _ => Self::Normal,
73        }
74    }
75
76    /// 将 TaskPriority 枚举转换为 i16 值
77    pub fn to_i16(self) -> i16 {
78        self as i16
79    }
80}
81
82/// 重试策略
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub enum RetryStrategy {
85    /// 固定延迟重试
86    Fixed,
87    /// 线性递增延迟重试
88    Linear,
89    /// 指数退避延迟重试
90    Exponential,
91}
92
93/// 任务配置 —— 每种 task_type 对应一份配置
94#[derive(Debug, Clone)]
95pub struct TaskConfig {
96    /// 任务类型标识
97    pub task_type: i16,
98    /// 任务优先级
99    pub priority: TaskPriority,
100    /// Kafka topic 名称
101    pub topic: String,
102    /// 任务执行超时时间(秒)
103    pub timeout_seconds: u64,
104    /// 最大重试次数
105    pub max_retries: u32,
106    /// 重试策略
107    pub retry_strategy: RetryStrategy,
108    /// 重试延迟基础时间(秒)
109    pub retry_delay_seconds: u64,
110    /// 最大重试延迟时间(秒)
111    pub max_retry_delay_seconds: u64,
112    /// 任务描述
113    pub description: &'static str,
114    /// 死信队列 topic —— 超过 max_retries 后转发到此 topic(None 则不启用)
115    pub dead_letter_topic: Option<String>,
116}
117
118/// TaskWorker 运行时配置(可从配置文件 `[task]` section 反序列化)
119#[derive(Debug, Clone, Deserialize)]
120pub struct TaskWorkerConfig {
121    /// Kafka broker 地址
122    pub brokers: String,
123    /// 消费组 ID
124    pub group_id: String,
125    /// 重试扫描间隔(秒)
126    pub scan_interval_secs: u64,
127    /// 每批次扫描最大任务数
128    pub max_batch_size: usize,
129    /// 消息最大时效(秒),超过此时间的消息将被跳过
130    pub max_message_age_secs: u64,
131    /// 是否在启动时自动创建 topic
132    pub auto_create_topics: bool,
133    /// topic 分区数(auto_create_topics 时使用)
134    pub topic_partitions: i32,
135    /// topic 副本数(auto_create_topics 时使用)
136    pub topic_replication: i16,
137}
138
139impl Default for TaskWorkerConfig {
140    fn default() -> Self {
141        Self {
142            brokers: "localhost:9092".into(),
143            group_id: "alun-task-worker".into(),
144            scan_interval_secs: 30,
145            max_batch_size: 100,
146            max_message_age_secs: 3600,
147            auto_create_topics: false,
148            topic_partitions: 1,
149            topic_replication: 1,
150        }
151    }
152}
153
154/// 资源类型
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
156#[repr(i16)]
157pub enum ResourceType {
158    /// 用户资源
159    User = 1,
160    /// 订单资源
161    Order = 2,
162    /// 商品资源
163    Product = 3,
164    /// 门店资源
165    Store = 4,
166    /// 文件资源
167    File = 5,
168}
169
170impl ResourceType {
171    /// 从 i16 值转换为 ResourceType 枚举
172    pub fn from_i16(v: i16) -> Option<Self> {
173        match v {
174            1 => Some(Self::User),
175            2 => Some(Self::Order),
176            3 => Some(Self::Product),
177            4 => Some(Self::Store),
178            5 => Some(Self::File),
179            _ => None,
180        }
181    }
182
183    /// 将 ResourceType 枚举转换为 i16 值
184    pub fn to_i16(self) -> i16 {
185        self as i16
186    }
187}
188
189/// 任务提交参数
190#[derive(Debug, Clone)]
191pub struct SubmitTaskParams {
192    /// 任务类型标识
193    pub task_type: i16,
194    /// 任务载荷(JSON 格式的业务数据)
195    pub payload: serde_json::Value,
196    /// 优先级(None 使用配置默认值)
197    pub priority: Option<TaskPriority>,
198    /// 提交用户 ID(可选,用于审计)
199    pub user_id: Option<String>,
200    /// 关联资源 ID(可选)
201    pub resource_id: Option<String>,
202    /// 关联资源类型(可选)
203    pub resource_type: Option<ResourceType>,
204}
205
206/// 批量任务提交参数
207#[derive(Debug, Clone)]
208pub struct SubmitBatchParams {
209    /// 任务列表
210    pub tasks: Vec<SubmitTaskParams>,
211}
212
213/// 从 Kafka 消费到的任务消息
214#[derive(Debug, Clone, Serialize, Deserialize)]
215pub struct TaskMessage {
216    /// 任务 ID
217    pub task_id: String,
218    /// 任务类型标识
219    pub task_type: i16,
220    /// 任务载荷(JSON 格式的业务数据)
221    pub payload: serde_json::Value,
222    /// 任务优先级数值
223    pub priority: i16,
224    /// 提交用户 ID(可选)
225    pub user_id: Option<String>,
226    /// 关联资源 ID(可选)
227    pub resource_id: Option<String>,
228    /// 关联资源类型(可选)
229    pub resource_type: Option<i16>,
230    /// 任务提交时间(ISO 8601 格式)
231    pub submitted_at: String,
232}