summaryrefslogtreecommitdiffstats
path: root/plugins/plugin_fdman/src/plugin.rs
blob: 2d2fa008e74fc8e7ffa403d7e5ffa246c7e2e9c8 (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
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
use std::sync::{atomic::AtomicU64, Arc};

use async_trait::async_trait;

use tedge_api::{
    plugin::{Handle, Plugin},
    PluginError,
};

use crate::{
    error::Error,
    guard::Guard,
    message::{
        Copy, CopyError, CopyResult, MessageResult, OpenOptions, OpenOptionsError,
        OpenOptionsResult, Rename, RenameError, RenameResult,
    },
};

#[derive(Debug)]
pub struct FdManPlugin {
    max_fds: u64,
    currently_held_count: Arc<AtomicU64>,
}

impl FdManPlugin {
    pub fn new(max_fds: u64) -> Self {
        Self {
            max_fds,
            currently_held_count: Arc::new(AtomicU64::from(0)),
        }
    }

    fn aquire_handles(&self, count: u64) -> Result<Guard, Error> {
        let old_value = self
            .currently_held_count
            .fetch_add(count, std::sync::atomic::Ordering::SeqCst);

        if old_value >= self.max_fds {
            self.currently_held_count
                .fetch_sub(count, std::sync::atomic::Ordering::SeqCst);
            Err(Error::InsufficientHandles {
                required: count,
                received: (old_value - self.max_fds),
            })
        } else {
            Ok(Guard::new(count, self.currently_held_count.clone()))
        }
    }
}

impl tedge_api::plugin::PluginDeclaration for FdManPlugin {
    type HandledMessages = (OpenOptions,);
}

#[async_trait]
impl Plugin for FdManPlugin {}

#[async_trait::async_trait]
impl Handle<OpenOptions> for FdManPlugin {
    async fn handle_message(
        &self,
        message: OpenOptions,
        sender: tedge_api::address::ReplySenderFor<OpenOptions>,
    ) -> Result<(), PluginError> {
        async fn inner(guard: Guard, message: OpenOptions) -> OpenOptionsResult {
            let file_result = message
                .as_std()
                .open(message.path())
                .map(|file| crate::file::FileGuard::new(file, guard))
                .map_err(Error::from)
                .map_err(OpenOptionsError::from);
            OpenOptionsResult::new(message, file_result)
        }

        HandleWithGuard::new(self, message, sender)
            .with_handles(1, inner)
            .await
    }
}

#[async_trait::async_trait]
impl Handle<Copy> for FdManPlugin {
    async fn handle_message(
        &self,
        message: Copy,
        sender: tedge_api::address::ReplySenderFor<Copy>,
    ) -> Result<(), PluginError> {
        async fn inner(guard: Guard, message: Copy) -> CopyResult {
            let copy_res = tokio::fs::copy(message.src(), message.dst())
                .await
                .map_err(Error::from)
                .map_err(CopyError::from);
            drop(guard); // We can now drop the guard, as the copy process is done
            CopyResult::new(message, copy_res)
        }

        HandleWithGuard::new(self, message, sender)
            .with_handles(2, inner)
            .await
    }
}

#[async_trait::async_trait]
impl Handle<Rename> for FdManPlugin {
    async fn handle_message(
        &self,
        message: Rename,
        sender: tedge_api::address::ReplySenderFor<Rename>,
    ) -> Result<(), PluginError> {
        async fn inner(guard: Guard, message: Rename) -> RenameResult {
            let rename_res = tokio::fs::rename(message.src(), message.dst())
                .await
                .map_err(Error::from)
                .map_err(RenameError::from);
            drop(guard); // We can now drop the guard, as the copy process is done
            RenameResult::new(message, rename_res)
        }

        HandleWithGuard::new(self, message, sender)
            .with_handles(2, inner)
            .await
    }
}

struct HandleWithGuard<'a, M, Res, RT, Err>
where
    M: tedge_api::Message + tedge_api::message::AcceptsReplies<Reply = Res>,
    Res: tedge_api::Message + MessageResult<M, RT, Err>,
    Err: From<Error> + std::error::Error,
{
    plugin: &'a FdManPlugin,
    message: M,
    sender: tedge_api::address::ReplySenderFor<M>,
    _pd_res: std::marker::PhantomData<Res>,
    _pd_rt: std::marker::PhantomData<RT>,
    _pd_err: std::marker::PhantomData<Err>,
}

impl<'a, M, Res, RT, Err> HandleWithGuard<'a, M, Res, RT, Err>
where
    M: tedge_api::Message + tedge_api::message::AcceptsReplies<Reply = Res>,
    Res: tedge_api::Message + MessageResult<M, RT, Err>,
    Err: From<Error> + std::error::Error,
{
    fn new(
        plugin: &'a FdManPlugin,
        message: M,
        sender: tedge_api::address::ReplySenderFor<M>,
    ) -> Self {
        Self {
            plugin,
            message,
            sender,
            _pd_res: std::marker::PhantomData,
            _pd_rt: std::marker::PhantomData,
            _pd_err: std::marker::PhantomData,
        }
    }

    async fn with_handles<F, Fut>(self, handles_to_aquire: u64, fun: F) -> Result<(), PluginError>
    where
        F: Fn(Guard, M) -> Fut,
        Fut: std::future::Future<Output = Res>,
    {
        match self.plugin.aquire_handles(handles_to_aquire) {
            Ok(guard) => {
                let res: Res = fun(guard, self.message).await;

                self.sender
                    .reply(res)
                    .map_err(|_| Error::SendingReply)
                    .map_err(PluginError::from)
            }
            Err(err @ Error::InsufficientHandles { .. }) => self
                .sender
                .reply(Res::new(self.message, Err(Err::from(err))))
                .map_err(|_| Error::SendingReply)
                .map_err(PluginError::from),
            Err(other) => Err(PluginError::from(other)),
        }
    }
}