kafru 1.0.4

kafru is a Python Celery-inspired queuing library for Rust, using cron for scheduling and SurrealDB for storing queues, metrics, and schedules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use crate::database::Db;
use crate::task::TaskRegistry;
use crate::queue::{
    Queue,
    QueueStatus,
    QueueListConditions
};
use surrealdb::RecordId;
use std::sync::Arc;
use std::collections::HashMap;
use std::u64;
use tokio::task::JoinHandle;
use tracing::{instrument, info, error};
use tokio::runtime::{Builder, Runtime, RuntimeMetrics};
use crate::metric::{Metric, MetricData, MetricKind};
use crate::Command;
use tokio::time::{Duration, Instant};
use crate::agent::{Agent, AgentData, AgentFilter, AgentKind, AgentStatus};


/// A struct representing a worker that processes tasks from a queue.
///
/// The `Worker` struct manages the execution of tasks by periodically polling a queue and executing tasks
/// with available worker threads.
#[derive(Debug,Clone)]
pub struct Worker {
    db: Option<Arc<Db>>,
    server: String,
    agent: Agent,
    author: String
}


/// Represents the status of a worker check.
///
/// This enum is used to determine whether a worker should continue monitoring 
/// or stop its operations. It provides two possible states:
/// - `Continue`: Indicates that the worker should continue monitoring.
/// - `Stop`: Indicates that the worker should cease monitoring.
#[derive(Debug,Clone, PartialEq)]
pub enum WorkerCheckStatus {
    Continue,
    Stop
}

type WorkerTasksHandles = HashMap<String,Option<JoinHandle<()>>>;

#[derive(Debug)]
pub struct WorkerTasks{
    handles: WorkerTasksHandles
}

impl WorkerTasks {
    /// Creates a new instance of `WorkerTasks`.
    ///
    /// Initializes the `WorkerTasks` struct with an empty collection of task handles.
    ///
    /// # Returns
    /// A new `WorkerTasks` instance.
    pub async fn new() -> Self {
        Self {
            handles: HashMap::new(),
        }
    }


    /// Adds a task to the worker's collection of handles.
    ///
    /// # Arguments
    /// * `queue_name` - The name of the queue the task belongs to.
    /// * `task_id` - A unique identifier for the task.
    /// * `handle` - An optional join handle associated with the task.
    ///
    /// The task is stored in the collection under a unique name generated by combining
    /// the queue name and task ID.
    pub async fn add(&mut self, queue_name: String, task_id: u64, handle: Option<JoinHandle<()>>) {
        let name: String = Agent::to_name(&queue_name, &task_id).await;
        self.handles.insert(name.clone(), handle);
    }

    /// Removes a task from the worker's collection by its unique name.
    ///
    /// # Arguments
    /// * `name` - The unique name of the task to be removed.
    pub async fn remove(&mut self, name: String) {
        self.handles.remove(&name);
    }

    /// Attempts to abort a running task by its unique name.
    ///
    /// # Arguments
    /// * `name` - The unique name of the task to be aborted.
    ///
    /// # Returns
    /// * `Ok(true)` if the task was successfully aborted.
    /// * `Err(String)` with an error message if the task could not be found or aborted.
    pub async fn abort(&self, name: String) -> Result<bool, String> {
        if let Some(handle) = self.handles.get(&name).clone() {
            if let Some(h) = handle {
                h.abort();
            }
            return Ok(true);
        }
        Err(format!("unable to abort worker task {}", name))
    }
}



impl Worker {
    /// Creates a new instance of the structure.
    ///
    /// This asynchronous function initializes a new instance, setting up the database connection,
    /// server identifier, and author information. It also creates an `Agent` instance for managing
    /// agent-related operations.
    ///
    /// # Arguments
    /// * `db` - An optional shared reference to the database connection (`Arc<Db>`). If `None`, 
    ///   a new database connection will be established.
    /// * `server` - A `String` representing the server name or identifier.
    /// * `author` - A `String` representing the author's name or identifier for tracking.
    ///
    /// # Returns
    /// A new instance of the structure.
    pub async fn new(db: Option<Arc<Db>>, server: String, author: String) -> Self {
        let agent = Agent::new(db.clone()).await;
        Self {
            db,
            server,
            agent,
            author
        }
    }

    /// Checks for and executes commands related to task management.
    ///
    /// This function processes commands associated with worker tasks and queues, such as removing tasks, 
    /// terminating tasks, and shutting down queues. It interacts with the provided runtime, worker tasks, 
    /// and database components to perform the necessary operations.
    ///
    /// # Arguments
    /// * `runtime` - A reference to the Tokio runtime, used to access runtime metrics.
    /// * `worker_tasks` - A mutable reference to the `WorkerTasks` structure, which manages active task handles.
    /// * `queue_name` - The name of the queue associated with the commands.
    ///
    /// # Returns
    /// * `Ok(WorkerCheckStatus::Continue)` if the worker should continue monitoring the queue.
    /// * `Ok(WorkerCheckStatus::Stop)` if the worker should stop monitoring the queue.
    /// * `Err(String)` if an error occurs while processing commands.
    pub async fn check_command(&self, runtime: &Runtime, worker_tasks: &mut WorkerTasks, queue_name: String) -> Result<WorkerCheckStatus,String>{
        let queue: Queue = Queue::new(self.db.clone()).await;
        let agent: Agent = Agent::new(self.db.clone()).await;
        
        let agent_names: Vec<String> = worker_tasks.handles.keys().map(|value| value.to_string()).collect();
        let agents: Vec<AgentData> = self.agent.list(AgentFilter { 
            names: Some(agent_names),
            ..Default::default()
        }).await?;
        if agents.len() > 0 {
            for agent_data in agents {
                if agent_data.command_is_executed == Some(false) {
                    if let Some(command) = agent_data.command {
                        let agent_name: String = if let Some(value) = agent_data.name { value } else { return Err("agent name is required for check command".to_string()) };
                        let agent_id: RecordId = if let Some(value) = agent_data.id { value } else { return Err("agent name is required for check command".to_string()) };        
                        match command {
                            Command::TaskRemove => { 
                                info!("remove task {:#?}",agent_name.clone()); 
                                worker_tasks.remove(agent_name.clone()).await;
                                if let Err(error) = agent.remove(agent_id,false).await {
                                    error!("{}",error);
                                }
                            },
                            Command::TaskTerminate => {
                                if let Some(agent_queue_id) = agent_data.queue_id {
                                    info!("terminate task {}",&queue_name);   
                                    worker_tasks.abort(agent_name).await?;                                                 
                                    if let Err(error) = queue.set_status(
                                        agent_queue_id,
                                        QueueStatus::Error,
                                        Some("task has been terminated".to_string())
                                    ).await {
                                        error!("{}",error);
                                    }
                                    if let Err(error) = agent.update(
                                        agent_id,
                                        AgentData {
                                            status: Some(AgentStatus::Terminated),
                                            command_is_executed: Some(true),
                                            message: None,
                                            ..Default::default()
                                        }
                                    ).await {
                                        error!("{}",error);
                                    }
                                }
                                else {
                                    return Err("unable to terminate task, queue_id is missing".to_string());
                                }
                            },
                            Command::QueueForceShutdown => {
                                info!("force shutdown queue {}",&queue_name);    
                                return Ok(WorkerCheckStatus::Stop);
                            }
                            Command::QueueGracefulShutdown => {
                                loop {
                                    if runtime.metrics().num_alive_tasks() == 0 {
                                        info!("graceful shutdown queue {}",&queue_name);
                                        return Ok(WorkerCheckStatus::Stop);
                                    }
                                    tokio::time::sleep_until(Instant::now() + Duration::from_secs(1)).await;
                                }
                            }
                            _ => {}
                        };
                    }
                }
            }
        }
        return Ok(WorkerCheckStatus::Continue);
    }

    /// Starts watching the task queue and processes tasks.
    ///
    /// This method sets up a multi-threaded Tokio runtime, polls the queue for tasks, and executes them
    /// using available worker threads. It periodically checks the queue, updates task statuses, and
    /// records metrics.
    ///
    /// # Parameters
    /// 
    /// - `task_registry`: An `Arc` of `TaskRegistry` for retrieving task handlers.
    /// - `num_threads`: The number of threads in the worker pool.
    /// - `queue_name`: (Optional) The name of the queue to poll. Defaults to "default" if not provided.
    /// - `poll_interval`: (Optional) The interval, in seconds, between queue polling. Defaults to 15 seconds if not provided.
    ///
    /// # Returns
    /// 
    /// Returns a `Result<(), String>`. On success, returns `Ok(())`. On failure, returns `Err(String)` with an error message.
    #[instrument(skip_all)]
    pub async fn watch(&self, task_registry: Arc<TaskRegistry>, num_threads: usize, queue_name: Option<String>, poll_interval: Option<u64>) -> Result<(), String> {
        let poll_interval = poll_interval.unwrap_or(15);
        let queue_name = format!("{}-{}",self.server,queue_name.unwrap_or(String::from("scheduler-default")));
        info!("Thread pool for {} has been created with {} number of threads", queue_name, num_threads);
        // Build a multi-threaded Tokio runtime
        match Builder::new_multi_thread()
            .thread_name(queue_name.clone())
            .worker_threads(num_threads)
            .enable_all()
            .build() {
            Ok(runtime) => {              
                let mut worker_tasks: WorkerTasks = WorkerTasks::new().await;
                let queue_agent: AgentData = self.agent.register(AgentData {
                    name: Some(Agent::to_name(&queue_name, &0).await),
                    kind: Some(AgentKind::Queue),
                    server: Some(self.server.clone()),
                    status: Some(AgentStatus::Running),
                    author: Some(self.author.clone()),
                    ..Default::default()
                }).await?;
                worker_tasks.add(queue_name.clone(), 0,  None).await;
                loop {
                    match self.check_command(&runtime, &mut worker_tasks, queue_name.clone() ).await {
                        Ok(wc_status) => {
                            if wc_status == WorkerCheckStatus::Stop  {
                                break;
                            }
                        }
                        Err(error) => {
                            error!(error);
                            return Err(error);
                        }
                    }
                    
                    let busy_threads = runtime.metrics().num_alive_tasks();
                    info!("Thread status {}/{}", busy_threads, num_threads);
                    if busy_threads < num_threads {
                        let idle_threads: usize = if busy_threads <= num_threads { num_threads - busy_threads } else { 0 };
                        let queue: Queue = Queue::new(self.db.clone()).await;
                        match queue.list(
                            QueueListConditions {
                                status: Some(vec![QueueStatus::Waiting.to_string()]),
                                queue: Some(vec![queue_name.clone()]),
                                limit: Some(idle_threads)
                            }).await {
                            Ok(records) => {
                                for record in records {
                                    let db: Option<Arc<Db>> = self.db.clone();
                                    let queue: Queue = Queue::new(self.db.clone()).await;
                                    let metric: Metric = Metric::new(self.db.clone()).await;
                                    let registry: Arc<TaskRegistry> = task_registry.clone();
                                    let rt_metrics: RuntimeMetrics = runtime.metrics();
                                    let parent_queue_name: String = queue_name.clone();
                                    let parent_queue_agent_id = queue_agent.id.clone().unwrap();
                                    let queue_id = record.id.clone().unwrap();
                                    let author: String = self.author.clone();
                                    let server: String = self.server.clone();

                                    // Set InProgress in order not to be picked up
                                    if let Err(error) = queue.set_status(queue_id.clone(),QueueStatus::InProgress,None).await {
                                        return Err(error);
                                    }
                                    //Spawn thread to execute the task
                                    let task_handle = runtime.spawn(async move {
                                        let agent: Agent = Agent::new(db.clone()).await;                                        
                                        let task_id: u64 = Agent::to_id(tokio::task::id()).await;                                                                  
                                        let agent_name = Agent::to_name(&parent_queue_name, &task_id).await ;  
                                        // Register the agent for monitoing
                                        match agent.register(AgentData {
                                            name: Some(agent_name.clone()),
                                            kind: Some(AgentKind::Task),
                                            status: Some(AgentStatus::Initialized),
                                            server: Some(server.clone()),
                                            parent_id: Some(parent_queue_agent_id.clone()),
                                            author: Some(author.clone()),
                                            queue_id: Some(queue_id.clone()),
                                            task_id: Some(task_id.clone()),
                                            ..Default::default()
                                        }).await {
                                            Ok(task_agent) => {
                                                if let Err(error) = metric.create(MetricData {
                                                    name: Some(parent_queue_name.clone()),
                                                    kind: Some(MetricKind::Worker),
                                                    num_alive_tasks: Some(rt_metrics.num_alive_tasks()),
                                                    num_workers: Some(rt_metrics.num_workers()),
                                                    ..Default::default()
                                                }).await {
                                                    error!("Worker metrics error: {}", error);
                                                }
                                                let record_name: String = record.name.unwrap();
                                                let record_handler: String = record.handler.unwrap();
                                                info!("Received task [{}]", record_name);
                                                match registry.get(record_handler).await {
                                                    Ok(handler) => {
                                                        info!("Executing task [{}]", record_name);     
                                                        let agent_id: RecordId = task_agent.id.unwrap();
                                                        if let Err(error) = agent.update(agent_id.clone(),AgentData {
                                                            status: Some(AgentStatus::Running),
                                                            command_is_executed: Some(false),
                                                            message: None,
                                                            ..Default::default()
                                                        }).await {
                                                            error!("task execution result error [{}]: {}", record_name, error);
                                                        }      
                                                        match handler().run(record.parameters.unwrap(),Some(queue_id.clone()),Some(agent_id.clone())).await {
                                                            Ok(_) => {
                                                                if let Err(error) = queue.set_status(queue_id.clone(),QueueStatus::Completed,None).await {
                                                                    error!("task execution result error [{}]: {}", record_name, error);
                                                                }                                                                
                                                                if let Err(error) = agent.update(agent_id.clone(),AgentData {
                                                                    status: Some(AgentStatus::Completed),
                                                                    command_is_executed: Some(false),
                                                                    message: None,
                                                                    ..Default::default()
                                                                }).await {
                                                                    error!("agent execution result error [{}]: {}", record_name, error);
                                                                }                                                         
                                                            }
                                                            Err(error) => {
                                                                if let Err(error) = queue.set_status(queue_id.clone(),QueueStatus::Error,Some(error.clone())).await {
                                                                    error!("task execution result error [{}]: {}", record_name, error);
                                                                }                                                                
                                                                if let Err(error) = agent.update(agent_id.clone(),AgentData {
                                                                    status: Some(AgentStatus::Error),
                                                                    command_is_executed: Some(false),
                                                                    message: Some(error.clone()),
                                                                    ..Default::default()
                                                                }).await {
                                                                    error!("agent execution result error [{}]: {}", record_name, error);
                                                                }    
                                                            }
                                                        }      
                                                    }
                                                    Err(error) => {
                                                        error!("task registry error [{}]: {}", record_name, error);
                                                    }
                                                }
                                                info!("exiting task [{}]", record_name);
                                            }  
                                            Err(error)=> {
                                                error!("{}",error);
                                            }
                                        } 
                                    });
                                    worker_tasks.add(
                                        queue_name.clone(), 
                                        Agent::to_id(task_handle.id()).await, 
                                        Some(task_handle)
                                    ).await;
                                    tokio::time::sleep_until(Instant::now() + Duration::from_millis(100)).await;
                                }
                            }
                            Err(error) => {
                                error!("Queue list error: {}", error);
                            }
                        }
                    }  
                    info!("sleeping for {} second(s)", poll_interval);
                    tokio::time::sleep_until(Instant::now() + Duration::from_secs(poll_interval)).await;
                }
                if let Err(error) = self.agent.remove(queue_agent.id.unwrap().clone(),true).await {
                    error!("task agent remove error [{}]: {}", queue_name, error);
                }
                runtime.shutdown_background();
                Ok(())
            }
            Err(error) => {
                Err(error.to_string())
            }
        }
    }
}