summaryrefslogtreecommitdiff
path: root/src/tasks/server.rs
blob: 45be9f1d2225f68f7f9a89fcb1117bd5e686c77d (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
use std::fmt::Display;

use crate::tasks::{IntoTaskErr, Task as BaseTask, TaskOutput};
use serde::Deserialize;
use tokio::net::TcpStream;

#[derive(Clone, Copy)]
pub struct ServerCtx<'a> {
    pub stream: &'a TcpStream,
}

pub struct Task<'a>(pub BaseTask<Name, ServerCtx<'a>>);

#[derive(Debug, Deserialize, Clone, Copy, PartialEq)]
pub enum Name {
    GetIp,
}

impl Display for Name {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:?}", self)
    }
}

pub const TASKS: &[Task] = &[Task(BaseTask { name: Name::GetIp, exec: get_ip })];

fn get_ip(_: &[&str], ctx: &ServerCtx) -> TaskOutput {
    match ctx.stream.peer_addr() {
        Ok(addr) => Ok(addr.ip().to_string()),
        Err(e) => Err(e.to_string()),
    }
}

impl<'a> TryFrom<Name> for &'static Task<'a> {
    type Error = IntoTaskErr;

    fn try_from(value: Name) -> Result<Self, Self::Error> {
        for task in TASKS {
            if task.0.name == value {
                return Ok(task);
            }
        }
        Err(IntoTaskErr::NotFound(value.to_string()))
    }
}

impl<'a> From<Task<'a>> for BaseTask<Name, ServerCtx<'a>> {
    fn from(value: Task<'a>) -> Self {
        value.0
    }
}

impl<'a> AsRef<BaseTask<Name, ServerCtx<'a>>> for Task<'a> {
    fn as_ref(&self) -> &BaseTask<Name, ServerCtx<'a>> {
        &self.0
    }
}