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
pub mod errors;
pub mod memory_manager;
pub mod module;

use bincode::ErrorKind;
use common::{assets::ASSETS_PATH, event::PluginHash, uid::Uid};
use serde::{Deserialize, Serialize};
use std::{
    collections::{HashMap, HashSet},
    fs,
    io::{Read, Write},
    path::{Path, PathBuf},
};
use tracing::{error, info};

use self::{
    errors::{PluginError, PluginModuleError},
    memory_manager::EcsWorld,
    module::PluginModule,
};

use sha2::Digest;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PluginData {
    name: String,
    modules: HashSet<PathBuf>,
    dependencies: HashSet<String>,
}

fn compute_hash(data: &[u8]) -> PluginHash {
    let shasum = sha2::Sha256::digest(data);
    let mut shasum_iter = shasum.iter();
    // a newer generic-array supports into_array ...
    let shasum: PluginHash = std::array::from_fn(|_| *shasum_iter.next().unwrap());
    shasum
}

fn cache_file_name(
    mut base_dir: PathBuf,
    hash: &PluginHash,
    create_dir: bool,
) -> Result<PathBuf, std::io::Error> {
    base_dir.push("server-plugins");
    if create_dir {
        std::fs::create_dir_all(base_dir.as_path())?;
    }
    let name = hex::encode(hash);
    base_dir.push(name);
    base_dir.set_extension("plugin.tar");
    Ok(base_dir)
}

// write received plugin to disk cache
pub fn store_server_plugin(base_dir: &Path, data: Vec<u8>) -> Result<PathBuf, std::io::Error> {
    let shasum = compute_hash(data.as_slice());
    let result = cache_file_name(base_dir.to_path_buf(), &shasum, true)?;
    let mut file = std::fs::File::create(result.as_path())?;
    file.write_all(data.as_slice())?;
    Ok(result)
}

pub fn find_cached(base_dir: &Path, hash: &PluginHash) -> Result<PathBuf, std::io::Error> {
    let local_path = cache_file_name(base_dir.to_path_buf(), hash, false)?;
    if local_path.as_path().exists() {
        Ok(local_path)
    } else {
        Err(std::io::Error::from(std::io::ErrorKind::NotFound))
    }
}

pub struct Plugin {
    data: PluginData,
    modules: Vec<PluginModule>,
    #[allow(dead_code)]
    hash: PluginHash,
    #[allow(dead_code)]
    path: PathBuf,
    #[allow(dead_code)]
    data_buf: Vec<u8>,
}

impl Plugin {
    pub fn from_path(path_buf: PathBuf) -> Result<Self, PluginError> {
        let mut reader = fs::File::open(path_buf.as_path()).map_err(PluginError::Io)?;
        let mut buf = Vec::new();
        reader.read_to_end(&mut buf).map_err(PluginError::Io)?;
        let shasum = compute_hash(buf.as_slice());

        let mut files = tar::Archive::new(&*buf)
            .entries()
            .map_err(PluginError::Io)?
            .map(|e| {
                e.and_then(|e| {
                    Ok((e.path()?.into_owned(), {
                        let offset = e.raw_file_position() as usize;
                        buf[offset..offset + e.size() as usize].to_vec()
                    }))
                })
            })
            .collect::<Result<HashMap<_, _>, _>>()
            .map_err(PluginError::Io)?;

        let data = toml::de::from_str::<PluginData>(
            std::str::from_utf8(
                files
                    .get(Path::new("plugin.toml"))
                    .ok_or(PluginError::NoConfig)?,
            )
            .map_err(|e| PluginError::Encoding(Box::new(ErrorKind::InvalidUtf8Encoding(e))))?,
        )
        .map_err(PluginError::Toml)?;

        let modules = data
            .modules
            .iter()
            .map(|path| {
                let wasm_data = files.remove(path).ok_or(PluginError::NoSuchModule)?;
                PluginModule::new(data.name.to_owned(), &wasm_data).map_err(|e| {
                    PluginError::PluginModuleError(data.name.to_owned(), "<init>".to_owned(), e)
                })
            })
            .collect::<Result<_, _>>()?;

        let data_buf = fs::read(&path_buf).map_err(PluginError::Io)?;

        Ok(Plugin {
            data,
            modules,
            hash: shasum,
            path: path_buf,
            data_buf,
        })
    }

    pub fn load_event(
        &mut self,
        ecs: &EcsWorld,
        mode: common::resources::GameMode,
    ) -> Result<(), PluginModuleError> {
        self.modules
            .iter_mut()
            .try_for_each(|module| module.load_event(ecs, mode))
    }

    pub fn command_event(
        &mut self,
        ecs: &EcsWorld,
        name: &str,
        args: &[String],
        player: common::uid::Uid,
    ) -> Result<Vec<String>, CommandResults> {
        let mut result = Err(CommandResults::UnknownCommand);
        self.modules.iter_mut().for_each(|module| {
            match module.command_event(ecs, name, args, player) {
                Ok(res) => result = Ok(res),
                Err(CommandResults::UnknownCommand) => (),
                Err(err) => {
                    if result.is_err() {
                        result = Err(err)
                    }
                },
            }
        });
        result
    }

    /// get the path to the plugin file
    pub fn path(&self) -> &Path { self.path.as_path() }

    /// Get the data of this plugin
    pub fn data_buf(&self) -> &[u8] { &self.data_buf }

    pub fn create_body(&mut self, name: &str) -> Option<module::Body> {
        let mut result = None;
        self.modules.iter_mut().for_each(|module| {
            if let Some(body) = module.create_body(name) {
                result = Some(body);
            }
        });
        result
    }

    pub fn update_skeleton(
        &mut self,
        body: &module::Body,
        dep: &module::Dependency,
        time: f32,
    ) -> Option<module::Skeleton> {
        let mut result = None;
        self.modules.iter_mut().for_each(|module| {
            if let Some(skel) = module.update_skeleton(body, dep, time) {
                result = Some(skel);
            }
        });
        result
    }
}

#[derive(Default)]
pub struct PluginMgr {
    plugins: Vec<Plugin>,
}

impl PluginMgr {
    pub fn from_asset_or_default() -> Self {
        match Self::from_assets() {
            Ok(plugin_mgr) => plugin_mgr,
            Err(e) => {
                tracing::error!(?e, "Failed to read plugins from assets");
                PluginMgr::default()
            },
        }
    }

    pub fn from_assets() -> Result<Self, PluginError> {
        let mut assets_path = (*ASSETS_PATH).clone();
        assets_path.push("plugins");
        info!("Searching {:?} for plugins...", assets_path);
        Self::from_dir(assets_path)
    }

    pub fn from_dir<P: AsRef<Path>>(path: P) -> Result<Self, PluginError> {
        let plugins = fs::read_dir(path)
            .map_err(PluginError::Io)?
            .filter_map(|e| e.ok())
            .map(|entry| {
                if entry.file_type().map(|ft| ft.is_file()).unwrap_or(false)
                    && entry
                        .path()
                        .file_name()
                        .and_then(|n| n.to_str())
                        .map(|s| s.ends_with(".plugin.tar"))
                        .unwrap_or(false)
                {
                    info!("Loading plugin at {:?}", entry.path());
                    Plugin::from_path(entry.path()).map(|plugin| {
                        if let Err(e) = common::assets::register_tar(entry.path()) {
                            error!("Plugin {:?} tar error {e:?}", entry.path());
                        }
                        Some(plugin)
                    })
                } else {
                    Ok(None)
                }
            })
            .filter_map(Result::transpose)
            .inspect(|p| {
                let _ = p.as_ref().map_err(|e| error!(?e, "Failed to load plugin"));
            })
            .collect::<Result<Vec<_>, _>>()?;

        for plugin in &plugins {
            info!(
                "Loaded plugin '{}' with {} module(s)",
                plugin.data.name,
                plugin.modules.len()
            );
        }

        Ok(Self { plugins })
    }

    /// Add a plugin received from the server
    pub fn load_server_plugin(&mut self, path: PathBuf) -> Result<PluginHash, PluginError> {
        Plugin::from_path(path.clone()).map(|plugin| {
            if let Err(e) = common::assets::register_tar(path.clone()) {
                error!("Plugin {:?} tar error {e:?}", path.as_path());
            }
            let hash = plugin.hash;
            self.plugins.push(plugin);
            hash
        })
    }

    pub fn cache_server_plugin(
        &mut self,
        base_dir: &Path,
        data: Vec<u8>,
    ) -> Result<PluginHash, PluginError> {
        let path = store_server_plugin(base_dir, data).map_err(PluginError::Io)?;
        self.load_server_plugin(path)
    }

    /// list all registered plugins
    pub fn plugin_list(&self) -> Vec<PluginHash> {
        self.plugins.iter().map(|plugin| plugin.hash).collect()
    }

    /// retrieve a specific plugin
    pub fn find(&self, hash: &PluginHash) -> Option<&Plugin> {
        self.plugins.iter().find(|plugin| &plugin.hash == hash)
    }

    pub fn load_event(
        &mut self,
        ecs: &EcsWorld,
        mode: common::resources::GameMode,
    ) -> Result<(), PluginModuleError> {
        self.plugins
            .iter_mut()
            .try_for_each(|plugin| plugin.load_event(ecs, mode))
    }

    pub fn command_event(
        &mut self,
        ecs: &EcsWorld,
        name: &str,
        args: &[String],
        player: Uid,
    ) -> Result<Vec<String>, CommandResults> {
        // return last value or last error
        let mut result = Err(CommandResults::UnknownCommand);
        self.plugins.iter_mut().for_each(|plugin| {
            match plugin.command_event(ecs, name, args, player) {
                Ok(val) => result = Ok(val),
                Err(CommandResults::UnknownCommand) => (),
                Err(err) => {
                    if result.is_err() {
                        result = Err(err);
                    }
                },
            }
        });
        result
    }

    pub fn create_body(&mut self, name: &str) -> Option<module::Body> {
        let mut result = None;
        self.plugins.iter_mut().for_each(|plugin| {
            if let Some(body) = plugin.create_body(name) {
                result = Some(body);
            }
        });
        result
    }

    pub fn update_skeleton(
        &mut self,
        body: &module::Body,
        dep: &module::Dependency,
        time: f32,
    ) -> Option<module::Skeleton> {
        let mut result = None;
        self.plugins.iter_mut().for_each(|plugin| {
            if let Some(skeleton) = plugin.update_skeleton(body, dep, time) {
                result = Some(skeleton);
            }
        });
        result
    }
}

/// Error returned by plugin based server commands
pub enum CommandResults {
    UnknownCommand,
    HostError(wasmtime::Error),
    PluginError(String),
}