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
use std::collections::{BTreeMap, VecDeque};

use crate::*;

static mut TIMER: std::sync::Mutex<Option<Timer>> = std::sync::Mutex::new(None);

/// A `Context` is used to store and manage plugins
pub struct Context {
    /// Plugin registry
    pub plugins: BTreeMap<PluginIndex, Plugin>,

    /// Error message
    pub error: Option<std::ffi::CString>,
    next_id: std::sync::atomic::AtomicI32,
    reclaimed_ids: VecDeque<PluginIndex>,

    // Timeout thread
    pub(crate) epoch_timer_tx: std::sync::mpsc::SyncSender<TimerAction>,
}

impl Default for Context {
    fn default() -> Self {
        Context::new()
    }
}

const START_REUSING_IDS: usize = 25;

impl Context {
    pub(crate) fn timer() -> std::sync::MutexGuard<'static, Option<Timer>> {
        match unsafe { TIMER.lock() } {
            Ok(x) => x,
            Err(e) => e.into_inner(),
        }
    }

    /// Create a new context
    pub fn new() -> Context {
        let timer = &mut *Self::timer();

        let tx = match timer {
            None => Timer::init(timer),
            Some(t) => t.tx.clone(),
        };

        Context {
            plugins: BTreeMap::new(),
            error: None,
            next_id: std::sync::atomic::AtomicI32::new(0),
            reclaimed_ids: VecDeque::new(),
            epoch_timer_tx: tx,
        }
    }

    /// Get the next valid plugin ID
    pub fn next_id(&mut self) -> Result<PluginIndex, Error> {
        // Make sure we haven't exhausted all plugin IDs, to reach this it would require the machine
        // running this code to have a lot of memory - no computer I tested on was able to allocate
        // the max number of plugins.
        //
        // Since `Context::remove` collects IDs that have been removed we will
        // try to use one of those before returning an error
        let exhausted = self.next_id.load(std::sync::atomic::Ordering::SeqCst) == PluginIndex::MAX;

        // If there are a significant number of old IDs we can start to re-use them
        if self.reclaimed_ids.len() >= START_REUSING_IDS || exhausted {
            if let Some(x) = self.reclaimed_ids.pop_front() {
                return Ok(x);
            }

            if exhausted {
                return Err(anyhow::format_err!(
                    "All plugin descriptors are in use, unable to allocate a new plugin"
                ));
            }
        }

        Ok(self
            .next_id
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst))
    }

    pub fn insert(&mut self, plugin: Plugin) -> PluginIndex {
        // Generate a new plugin ID
        let id: i32 = match self.next_id() {
            Ok(id) => id,
            Err(e) => {
                error!("Error creating Plugin: {:?}", e);
                self.set_error(e);
                return -1;
            }
        };
        self.plugins.insert(id, plugin);
        id
    }

    pub fn new_plugin<'a>(
        &mut self,
        data: impl AsRef<[u8]>,
        imports: impl IntoIterator<Item = &'a Function>,
        with_wasi: bool,
    ) -> PluginIndex {
        let plugin = match Plugin::new(data, imports, with_wasi) {
            Ok(x) => x,
            Err(e) => {
                error!("Error creating Plugin: {:?}", e);
                self.set_error(e);
                return -1;
            }
        };
        self.insert(plugin)
    }

    /// Set the context error
    pub fn set_error(&mut self, e: impl std::fmt::Debug) {
        trace!("Set context error: {:?}", e);
        self.error = Some(error_string(e));
    }

    /// Convenience function to set error and return the value passed as the final parameter
    pub fn error<T>(&mut self, e: impl std::fmt::Debug, x: T) -> T {
        self.set_error(e);
        x
    }

    /// Get a plugin from the context
    pub fn plugin(&mut self, id: PluginIndex) -> Option<*mut Plugin> {
        match self.plugins.get_mut(&id) {
            Some(x) => Some(x),
            None => None,
        }
    }

    pub fn plugin_exists(&mut self, id: PluginIndex) -> bool {
        self.plugins.contains_key(&id)
    }

    /// Remove a plugin from the context
    pub fn remove(&mut self, id: PluginIndex) {
        if self.plugins.remove(&id).is_some() {
            // Collect old IDs in case we need to re-use them
            self.reclaimed_ids.push_back(id);
        }
    }
}