aboutsummaryrefslogtreecommitdiff
path: root/src/app/mod.rs
blob: 278460654d537208f6e17dc079f9012ade5db805 (plain)
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
// SPDX-License-Identifier: MIT
// Copyright (c) 2023 Robin Jarry

use std::collections::HashMap;
use std::sync::Arc;

use tokio::sync::mpsc::channel;
use tokio::sync::mpsc::Receiver;
use tokio::sync::mpsc::Sender;
use tokio::sync::Mutex;
use tokio::task::JoinHandle;

use crate::config::AccountConfig;
use crate::config::Config;
use crate::worker::Worker;
use crate::worker::WorkerMessage;

pub struct App {
    config: Arc<Mutex<Config>>,
    worker_tasks: Vec<JoinHandle<()>>,
    to_workers: HashMap<String, Sender<WorkerMessage>>,
    from_workers: HashMap<String, Receiver<WorkerMessage>>,
    // app internal state change notifications for UI
    updates: Sender<()>,
}

impl App {
    pub fn new(config: Arc<Mutex<Config>>, updates: Sender<()>) -> Self {
        App {
            config,
            updates,
            worker_tasks: Vec::new(),
            to_workers: HashMap::new(),
            from_workers: HashMap::new(),
        }
    }

    pub fn invalidate(&self) {
        // ignore if a pending tick is already present in the channel
        let _ = self.updates.try_send(());
    }

    pub fn start_worker(&mut self, config: AccountConfig) {
        let (from_worker_tx, from_worker_rx) = channel::<WorkerMessage>(32);
        let (to_worker_tx, to_worker_rx) = channel::<WorkerMessage>(32);

        self.to_workers.insert(config.name.clone(), to_worker_tx);
        self.from_workers
            .insert(config.name.clone(), from_worker_rx);

        let handle = tokio::spawn(async move {
            let worker = Worker::new(config, to_worker_rx, from_worker_tx);
            let run = worker.run();
            tokio::pin!(run);
            run.await;
        });
        self.worker_tasks.push(handle);
    }

    pub async fn stop_workers(&self) {}
}