1use crate::command::{Command, CommandError, CommandRouter};
19use crate::pipeline::DataSink;
20use crate::types::DeviceMessage;
21use async_trait::async_trait;
22use parking_lot::RwLock;
23use serde::Serialize;
24use std::collections::BTreeMap;
25use std::fmt;
26use std::sync::Arc;
27
28fn now_millis() -> i64 {
29 chrono::Utc::now().timestamp_millis()
30}
31
32pub const OTA_PROGRESS_METRIC: &str = "ota_progress";
34
35#[derive(Debug, Clone, Serialize)]
37pub struct Firmware {
38 pub product: String,
40 pub version: String,
42 pub size: u64,
44 pub sha256: String,
46 pub url: String,
48}
49
50impl Firmware {
51 pub fn new(
53 product: impl Into<String>,
54 version: impl Into<String>,
55 size: u64,
56 sha256: impl Into<String>,
57 url: impl Into<String>,
58 ) -> Self {
59 Self {
60 product: product.into(),
61 version: version.into(),
62 size,
63 sha256: sha256.into(),
64 url: url.into(),
65 }
66 }
67}
68
69#[derive(Clone, Default)]
71pub struct FirmwareRepo {
72 inner: Arc<RwLock<BTreeMap<(String, String), Firmware>>>,
73}
74
75impl FirmwareRepo {
76 pub fn new() -> Self {
78 Self::default()
79 }
80
81 pub fn publish(&self, firmware: Firmware) {
83 self.inner.write().insert(
84 (firmware.product.clone(), firmware.version.clone()),
85 firmware,
86 );
87 }
88
89 pub fn get(&self, product: &str, version: &str) -> Option<Firmware> {
91 self.inner
92 .read()
93 .get(&(product.to_string(), version.to_string()))
94 .cloned()
95 }
96
97 pub fn list(&self) -> Vec<Firmware> {
99 self.inner.read().values().cloned().collect()
100 }
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
105#[serde(rename_all = "lowercase")]
106pub enum OtaState {
107 Pending,
109 Pushed,
111 Upgrading,
113 Success,
115 Failed,
117}
118
119impl OtaState {
120 pub fn is_terminal(self) -> bool {
122 matches!(self, OtaState::Success | OtaState::Failed)
123 }
124}
125
126#[derive(Debug, Clone, Serialize)]
128pub struct DeviceProgress {
129 pub state: OtaState,
131 pub percent: u8,
133 pub detail: String,
135 pub updated_millis: i64,
137}
138
139impl DeviceProgress {
140 fn pending() -> Self {
141 Self {
142 state: OtaState::Pending,
143 percent: 0,
144 detail: String::new(),
145 updated_millis: 0,
146 }
147 }
148}
149
150struct OtaTask {
151 firmware: Firmware,
152 batch_size: usize,
153 devices: BTreeMap<String, DeviceProgress>,
154}
155
156#[derive(Debug, Clone, Serialize)]
158pub struct OtaTaskSnapshot {
159 pub task_id: String,
161 pub firmware: Firmware,
163 pub total: usize,
165 pub pushed: usize,
167 pub success: usize,
169 pub failed: usize,
171 pub devices: BTreeMap<String, DeviceProgress>,
173}
174
175#[derive(Debug, Clone, PartialEq, Eq)]
177pub enum OtaError {
178 UnknownTask(String),
180 Command(CommandError),
182}
183
184impl fmt::Display for OtaError {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 match self {
187 OtaError::UnknownTask(t) => write!(f, "OTA 任务 {t} 不存在"),
188 OtaError::Command(e) => write!(f, "推送升级通知失败: {e}"),
189 }
190 }
191}
192
193impl std::error::Error for OtaError {}
194
195impl From<CommandError> for OtaError {
196 fn from(e: CommandError) -> Self {
197 OtaError::Command(e)
198 }
199}
200
201#[async_trait]
206pub trait OtaStorage: Send + Sync {
207 async fn persist_task(&self, snapshot: &OtaTaskSnapshot) -> std::result::Result<(), String>;
209
210 async fn persist_progress(
212 &self,
213 task_id: &str,
214 device: &str,
215 progress: &DeviceProgress,
216 ) -> std::result::Result<(), String>;
217}
218
219#[derive(Clone, Default)]
229pub struct OtaManager {
230 tasks: Arc<RwLock<BTreeMap<String, Arc<RwLock<OtaTask>>>>>,
231 device_index: Arc<RwLock<BTreeMap<String, Vec<String>>>>,
233 storage: Option<Arc<dyn OtaStorage>>,
235}
236
237impl OtaManager {
238 pub fn new() -> Self {
240 Self::default()
241 }
242
243 pub fn with_storage(&self, storage: Arc<dyn OtaStorage>) -> Self {
245 let mut s = self.clone();
246 s.storage = Some(storage);
247 s
248 }
249
250 fn notify_task(&self, snapshot: OtaTaskSnapshot) {
252 let Some(storage) = self.storage.clone() else {
253 return;
254 };
255 let Ok(handle) = tokio::runtime::Handle::try_current() else {
256 return;
257 };
258 handle.spawn(async move {
259 if let Err(e) = storage.persist_task(&snapshot).await {
260 tracing::warn!(err = %e, task = %snapshot.task_id, "OTA 任务持久化失败");
261 }
262 });
263 }
264
265 fn notify_progress(&self, task_id: &str, device: &str, progress: &DeviceProgress) {
267 let Some(storage) = self.storage.clone() else {
268 return;
269 };
270 let Ok(handle) = tokio::runtime::Handle::try_current() else {
271 return;
272 };
273 let task_id = task_id.to_string();
274 let device = device.to_string();
275 let progress = progress.clone();
276 handle.spawn(async move {
277 if let Err(e) = storage.persist_progress(&task_id, &device, &progress).await {
278 tracing::warn!(err = %e, task = %task_id, device = %device, "OTA 进度持久化失败");
279 }
280 });
281 }
282
283 pub fn create_task(
285 &self,
286 task_id: impl Into<String>,
287 firmware: Firmware,
288 devices: impl IntoIterator<Item = String>,
289 batch_size: usize,
290 ) {
291 let devices: BTreeMap<String, DeviceProgress> = devices
292 .into_iter()
293 .map(|d| (d, DeviceProgress::pending()))
294 .collect();
295 let task_id = task_id.into();
296 {
298 let mut index = self.device_index.write();
299 for device in devices.keys() {
300 let entry = index.entry(device.clone()).or_default();
301 if !entry.iter().any(|t| t == &task_id) {
302 entry.push(task_id.clone());
303 }
304 }
305 }
306 self.tasks.write().insert(
307 task_id.clone(),
308 Arc::new(RwLock::new(OtaTask {
309 firmware,
310 batch_size: batch_size.max(1),
311 devices,
312 })),
313 );
314 if let Some(snap) = self.snapshot(&task_id) {
316 self.notify_task(snap);
317 }
318 }
319
320 pub async fn push_batch(
323 &self,
324 task_id: &str,
325 router: &CommandRouter,
326 ) -> Result<usize, OtaError> {
327 let task = self
329 .tasks
330 .read()
331 .get(task_id)
332 .cloned()
333 .ok_or_else(|| OtaError::UnknownTask(task_id.to_string()))?;
334 let (payload, targets) = {
336 let task = task.read();
337 let fw = &task.firmware;
338 let payload = serde_json::json!({
340 "version": fw.version,
341 "url": fw.url,
342 "sha256": fw.sha256,
343 })
344 .to_string();
345 let targets: Vec<String> = task
346 .devices
347 .iter()
348 .filter(|(_, dp)| dp.state == OtaState::Pending)
349 .take(task.batch_size)
350 .map(|(d, _)| d.clone())
351 .collect();
352 (payload, targets)
353 };
354
355 let mut pushed = 0;
356 for device in targets {
357 let cmd = Command::text(&device, "ota", &payload);
358 let result = router.dispatch(&cmd).await;
359 let snapshot = {
361 let mut task = task.write();
362 let Some(dp) = task.devices.get_mut(&device) else {
363 continue;
364 };
365 match &result {
366 Ok(_) => {
367 dp.state = OtaState::Pushed;
368 dp.detail = "已推送升级通知".into();
369 pushed += 1;
370 }
371 Err(e) => {
372 dp.state = OtaState::Failed;
373 dp.detail = e.to_string();
374 }
375 }
376 dp.updated_millis = now_millis();
377 dp.clone()
378 };
379 self.notify_progress(task_id, &device, &snapshot);
380 }
381 Ok(pushed)
382 }
383
384 pub fn report(
386 &self,
387 task_id: &str,
388 device: &str,
389 state: OtaState,
390 percent: u8,
391 detail: impl Into<String>,
392 ) -> Result<(), OtaError> {
393 let task = self
394 .tasks
395 .read()
396 .get(task_id)
397 .cloned()
398 .ok_or_else(|| OtaError::UnknownTask(task_id.to_string()))?;
399 let snapshot = {
400 let mut task = task.write();
401 let Some(dp) = task.devices.get_mut(device) else {
402 return Ok(());
403 };
404 dp.state = state;
405 dp.percent = percent.min(100);
406 dp.detail = detail.into();
407 dp.updated_millis = now_millis();
408 dp.clone()
409 };
410 self.notify_progress(task_id, device, &snapshot);
411 Ok(())
412 }
413
414 pub fn snapshot(&self, task_id: &str) -> Option<OtaTaskSnapshot> {
416 let task = self.tasks.read().get(task_id).cloned()?;
417 let task = task.read();
418 Some(Self::to_snapshot(task_id, &task))
419 }
420
421 pub fn snapshot_all(&self) -> Vec<OtaTaskSnapshot> {
423 let tasks: Vec<(String, Arc<RwLock<OtaTask>>)> = self
424 .tasks
425 .read()
426 .iter()
427 .map(|(id, t)| (id.clone(), t.clone()))
428 .collect();
429 tasks
430 .iter()
431 .map(|(id, task)| Self::to_snapshot(id, &task.read()))
432 .collect()
433 }
434
435 fn to_snapshot(task_id: &str, task: &OtaTask) -> OtaTaskSnapshot {
436 let total = task.devices.len();
437 let mut pushed = 0;
438 let mut success = 0;
439 let mut failed = 0;
440 for dp in task.devices.values() {
441 match dp.state {
442 OtaState::Success => {
443 success += 1;
444 pushed += 1;
445 }
446 OtaState::Failed => failed += 1,
447 OtaState::Pushed | OtaState::Upgrading => pushed += 1,
448 OtaState::Pending => {}
449 }
450 }
451 OtaTaskSnapshot {
452 task_id: task_id.to_string(),
453 firmware: task.firmware.clone(),
454 total,
455 pushed,
456 success,
457 failed,
458 devices: task.devices.clone(),
459 }
460 }
461}
462
463#[async_trait]
466impl DataSink for OtaManager {
467 fn name(&self) -> &str {
468 "ota-progress"
469 }
470 async fn handle(&self, msg: &DeviceMessage) {
471 if msg.metric != OTA_PROGRESS_METRIC {
472 return;
473 }
474 let Some(pct) = msg.value.as_f64() else {
475 return;
476 };
477 let percent = pct.clamp(0.0, 100.0) as u8;
478 let task_ids: Vec<String> = self
481 .device_index
482 .read()
483 .get(&msg.device_id)
484 .cloned()
485 .unwrap_or_default();
486 for task_id in task_ids {
487 let Some(task) = self.tasks.read().get(&task_id).cloned() else {
488 continue;
489 };
490 let snapshot = {
491 let mut task = task.write();
492 let Some(dp) = task.devices.get_mut(&msg.device_id) else {
493 continue;
494 };
495 if dp.state.is_terminal() {
496 continue;
497 }
498 dp.percent = percent;
499 dp.updated_millis = msg.ts_millis;
500 dp.state = if percent >= 100 {
501 OtaState::Success
502 } else {
503 OtaState::Upgrading
504 };
505 dp.detail = "设备回报进度".into();
506 dp.clone()
507 };
508 self.notify_progress(&task_id, &msg.device_id, &snapshot);
509 }
510 }
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516 use crate::command::Downlink;
517 use crate::types::Protocol;
518 use parking_lot::Mutex;
519
520 fn fw() -> Firmware {
521 Firmware::new(
522 "sensor",
523 "1.2.0",
524 1024,
525 "abc123",
526 "https://fw/sensor-1.2.0.bin",
527 )
528 }
529
530 struct MockDownlink {
532 seen: Arc<Mutex<Vec<Command>>>,
533 deliver: u32,
534 }
535
536 #[async_trait]
537 impl Downlink for MockDownlink {
538 fn protocol(&self) -> Protocol {
539 Protocol::Mqtt
540 }
541 async fn dispatch(&self, cmd: &Command) -> Result<u32, CommandError> {
542 self.seen.lock().push(cmd.clone());
543 if self.deliver == 0 {
544 Err(CommandError::Unreachable(cmd.device_id.clone()))
545 } else {
546 Ok(self.deliver)
547 }
548 }
549 }
550
551 fn router_with(
552 seen: Arc<Mutex<Vec<Command>>>,
553 deliver: u32,
554 devices: &[&str],
555 ) -> CommandRouter {
556 let mut r = CommandRouter::new();
557 r.register_downlink(Arc::new(MockDownlink { seen, deliver }));
558 for d in devices {
559 r.bind_route(*d, Protocol::Mqtt);
560 }
561 r
562 }
563
564 #[test]
565 fn firmware_repo_publish_get_list() {
566 let repo = FirmwareRepo::new();
567 repo.publish(fw());
568 assert_eq!(repo.get("sensor", "1.2.0").unwrap().size, 1024);
569 assert!(repo.get("sensor", "9.9.9").is_none());
570 assert_eq!(repo.list().len(), 1);
571 }
572
573 #[tokio::test]
574 async fn push_respects_batch_size() {
575 let seen = Arc::new(Mutex::new(Vec::new()));
576 let router = router_with(seen.clone(), 1, &["d1", "d2", "d3"]);
577 let mgr = OtaManager::new();
578 mgr.create_task("t1", fw(), ["d1".into(), "d2".into(), "d3".into()], 2);
579
580 let n = mgr.push_batch("t1", &router).await.unwrap();
581 assert_eq!(n, 2, "首批仅推送 batch_size 台");
582 assert_eq!(seen.lock().len(), 2);
583 assert_eq!(seen.lock()[0].name, "ota");
585 assert!(String::from_utf8_lossy(&seen.lock()[0].payload).contains("1.2.0"));
586
587 let snap = mgr.snapshot("t1").unwrap();
588 assert_eq!(snap.total, 3);
589 assert_eq!(snap.pushed, 2);
590
591 let n2 = mgr.push_batch("t1", &router).await.unwrap();
593 assert_eq!(n2, 1);
594 assert_eq!(mgr.snapshot("t1").unwrap().pushed, 3);
595 assert_eq!(mgr.push_batch("t1", &router).await.unwrap(), 0);
597 }
598
599 #[tokio::test]
600 async fn unreachable_device_marked_failed() {
601 let seen = Arc::new(Mutex::new(Vec::new()));
602 let router = router_with(seen, 0, &["d1"]); let mgr = OtaManager::new();
604 mgr.create_task("t1", fw(), ["d1".into()], 5);
605 let n = mgr.push_batch("t1", &router).await.unwrap();
606 assert_eq!(n, 0);
607 let snap = mgr.snapshot("t1").unwrap();
608 assert_eq!(snap.failed, 1);
609 assert_eq!(snap.devices["d1"].state, OtaState::Failed);
610 }
611
612 #[tokio::test]
613 async fn progress_via_report_and_sink() {
614 let mgr = OtaManager::new();
615 mgr.create_task("t1", fw(), ["d1".into()], 5);
616
617 mgr.report("t1", "d1", OtaState::Upgrading, 40, "刷写中")
619 .unwrap();
620 assert_eq!(mgr.snapshot("t1").unwrap().devices["d1"].percent, 40);
621
622 let mut m = DeviceMessage::now("d1", OTA_PROGRESS_METRIC, 100i64, Protocol::Mqtt);
624 m.ts_millis = 9_000;
625 mgr.handle(&m).await;
626 let snap = mgr.snapshot("t1").unwrap();
627 assert_eq!(snap.success, 1);
628 assert_eq!(snap.devices["d1"].state, OtaState::Success);
629
630 let other = DeviceMessage::now("d1", "temperature", 20.0, Protocol::Mqtt);
632 mgr.handle(&other).await;
633 assert_eq!(
634 mgr.snapshot("t1").unwrap().devices["d1"].state,
635 OtaState::Success
636 );
637 }
638
639 #[tokio::test]
640 async fn unknown_task_errors() {
641 let mgr = OtaManager::new();
642 let err = mgr
643 .report("ghost", "d1", OtaState::Success, 100, "")
644 .unwrap_err();
645 assert_eq!(err, OtaError::UnknownTask("ghost".to_string()));
646 }
647}