Skip to main content

shaul_core/
blocking.rs

1use std::path::PathBuf;
2use std::sync::Arc;
3
4use tokio::runtime::{Builder, Runtime};
5use tokio_util::sync::CancellationToken;
6
7use crate::config::Config;
8use crate::engine::DownloadEngine;
9use crate::error::{Error, Result};
10use crate::event::DownloadEvent;
11use crate::link::Link;
12use crate::router::Router;
13use crate::store::TaskStore;
14use crate::task::{Task, TaskId, TaskOptions};
15
16/// Synchronous facade for callers that do not want to own a Tokio runtime.
17/// The async engine remains the single implementation.
18pub struct BlockingEngine {
19    runtime: Runtime,
20    engine: Arc<DownloadEngine>,
21}
22
23impl BlockingEngine {
24    /// Creates an engine backed by a dedicated multi-threaded Tokio runtime.
25    pub fn new(router: Router, store: Arc<dyn TaskStore>, config: Config) -> Result<Self> {
26        let runtime = Builder::new_multi_thread()
27            .enable_all()
28            .build()
29            .map_err(Error::Io)?;
30        let engine = Arc::new(DownloadEngine::new(Arc::new(router), store, config));
31        Ok(Self { runtime, engine })
32    }
33
34    /// Returns a reference to the underlying asynchronous engine.
35    pub fn engine(&self) -> &DownloadEngine {
36        &self.engine
37    }
38
39    /// Subscribes to engine events, delivered over a standard library channel.
40    pub fn subscribe(&self) -> std::sync::mpsc::Receiver<DownloadEvent> {
41        let (sender, receiver) = std::sync::mpsc::channel();
42        let mut events = self.engine.subscribe();
43        self.runtime.spawn(async move {
44            while let Ok(event) = events.recv().await {
45                if sender.send(event).is_err() {
46                    break;
47                }
48            }
49        });
50        receiver
51    }
52
53    /// Adds a task and runs it to completion, blocking the current thread.
54    pub fn download(&self, link: Link, destination: PathBuf, options: TaskOptions) -> Result<Task> {
55        self.runtime.block_on(async {
56            let task = self.engine.add(link, destination, options).await?;
57            self.engine.run_task(task.id).await
58        })
59    }
60
61    /// Registers a task without running it.
62    pub fn add(&self, link: Link, destination: PathBuf, options: TaskOptions) -> Result<Task> {
63        self.runtime
64            .block_on(self.engine.add(link, destination, options))
65    }
66
67    /// Blocks until the given task finishes and returns its final state.
68    pub fn run_task(&self, id: TaskId) -> Result<Task> {
69        self.runtime.block_on(self.engine.run_task(id))
70    }
71
72    /// Lists all stored tasks.
73    pub fn list(&self) -> Result<Vec<Task>> {
74        self.runtime.block_on(self.engine.list())
75    }
76
77    /// Loads a single task by id.
78    pub fn status(&self, id: TaskId) -> Result<Task> {
79        self.runtime.block_on(self.engine.status(id))
80    }
81
82    /// Marks a task paused and cancels its in-flight transfer.
83    pub fn pause(&self, id: TaskId) -> Result<Task> {
84        self.runtime.block_on(self.engine.pause(id))
85    }
86
87    /// Moves a non-completed task back to `Pending`.
88    pub fn resume(&self, id: TaskId) -> Result<Task> {
89        self.runtime.block_on(self.engine.resume(id))
90    }
91
92    /// Marks a task cancelled.
93    pub fn cancel(&self, id: TaskId) -> Result<Task> {
94        self.runtime.block_on(self.engine.cancel(id))
95    }
96
97    /// Runs every pending task, at most `jobs` at a time.
98    pub fn run_pending(&self, jobs: usize, cancel: CancellationToken) -> Result<Vec<Task>> {
99        self.runtime.block_on(self.engine.run_pending(jobs, cancel))
100    }
101
102    /// Requeues tasks left in `Running` by a previous process.
103    pub fn requeue_stale(&self) -> Result<Vec<TaskId>> {
104        self.runtime.block_on(self.engine.requeue_stale())
105    }
106}