1
use anyhow::Result;
2
use std::sync::{Arc, Mutex};
3
use wasmtime::{Caller, Func, Memory, Store};
4

            
5
pub struct DataStore<Data> {
6
    pub data: Mutex<Data>,
7
    pub memory: Mutex<Option<Memory>>,
8
}
9

            
10
380
pub fn wrap_wasm_str_transform<Data, Transform>(
11
380
    store: &mut Store<Arc<DataStore<Data>>>,
12
380
    transform: Transform,
13
380
) -> Func
14
380
where
15
380
    Data: Send + 'static,
16
380
    Transform: Fn(&Data, String) -> Result<String, anyhow::Error> + Send + Sync + 'static,
17
{
18
380
    Func::wrap(
19
380
        store,
20
        move |mut caller: Caller<'_, Arc<DataStore<Data>>>,
21
              tag_ptr: i32,
22
              tag_len: i32,
23
              buf_ptr: i32,
24
              buf_len: i32|
25
190
              -> i32 {
26
190
            let data = Arc::clone(caller.data());
27

            
28
            // Define the inner logic
29
190
            let result = (|| -> Result<i32, anyhow::Error> {
30
                // Lock the WASM memory
31
190
                let memory = data
32
190
                    .memory
33
190
                    .lock()
34
                    .map_err(|_| anyhow::anyhow!("Failed to lock memory"))?;
35
190
                let memory = memory
36
190
                    .as_ref()
37
                    .ok_or_else(|| anyhow::anyhow!("Memory not initialized"))?;
38
190
                let mem = memory.data(&caller);
39

            
40
                // Validate memory bounds for the input key
41
190
                if (tag_ptr as usize + tag_len as usize) > mem.len() {
42
                    return Err(anyhow::anyhow!("Input memory bounds error"));
43
190
                }
44

            
45
                // Extract the key string from memory
46
190
                let key = String::from_utf8(
47
190
                    mem[tag_ptr as usize..tag_ptr as usize + tag_len as usize].to_vec(),
48
190
                )
49
                .map_err(|_| anyhow::anyhow!("Failed to decode input string"))?;
50

            
51
                // Lock the data and call the transform function
52
190
                let data_lock = data
53
190
                    .data
54
190
                    .lock()
55
                    .map_err(|_| anyhow::anyhow!("Failed to lock data"))?;
56
190
                let output = transform(&*data_lock, key)?;
57

            
58
                // Get output bytes
59
190
                let output_bytes = output.as_bytes();
60
190
                let output_len = output_bytes.len();
61

            
62
                // Validate that the output fits within the provided buffer length
63
190
                if output_len > buf_len as usize {
64
                    return Err(anyhow::anyhow!("Output exceeds buffer size"));
65
190
                }
66

            
67
                // Validate memory bounds for the output buffer
68
190
                if (buf_ptr as usize + output_len) > mem.len() {
69
                    return Err(anyhow::anyhow!("Output memory bounds error"));
70
190
                }
71

            
72
                // Write the result string into the output buffer
73
190
                memory.data_mut(&mut caller)[buf_ptr as usize..buf_ptr as usize + output_len]
74
190
                    .copy_from_slice(output_bytes);
75

            
76
190
                Ok(output_len as i32)
77
            })();
78

            
79
            // Handle the result or return an error code
80
190
            match result {
81
190
                Ok(len) => len,
82
                Err(e) => {
83
                    tracing::error!("Error in wrap_wasm_str_transform: {e:?}");
84
                    -1 // Indicate failure
85
                }
86
            }
87
190
        },
88
    )
89
380
}
90

            
91
380
pub fn wrap_wasm_str_list_get<Data, Getter>(
92
380
    store: &mut Store<Arc<DataStore<Data>>>,
93
380
    getter: Getter,
94
380
) -> Func
95
380
where
96
380
    Data: Send + 'static,
97
380
    Getter: Fn(&Data) -> Result<Vec<String>, anyhow::Error> + Send + Sync + 'static,
98
{
99
380
    Func::wrap(
100
380
        store,
101
380
        move |mut caller: Caller<'_, Arc<DataStore<Data>>>, loc: i32, max_len: i32| -> i32 {
102
380
            let data = Arc::clone(caller.data());
103

            
104
            // Try to execute the getter and handle potential errors
105
380
            let result = (|| -> Result<i32> {
106
380
                let builder = data
107
380
                    .data
108
380
                    .lock()
109
                    .map_err(|_| anyhow::anyhow!("Failed to lock data"))?;
110
380
                let list = getter(&builder)?; // Call getter, which may return an error
111
380
                let mut bytes = Vec::new();
112

            
113
380
                for s in list {
114
570
                    bytes.extend_from_slice(s.as_bytes());
115
570
                    bytes.push(0); // Null terminator
116
                }
117

            
118
380
                let len = bytes.len().min(max_len as usize);
119

            
120
380
                let memory = data
121
380
                    .memory
122
380
                    .lock()
123
                    .map_err(|_| anyhow::anyhow!("Failed to lock memory"))?;
124
380
                if let Some(memory) = &*memory {
125
380
                    let mem = memory.data_mut(&mut caller);
126

            
127
380
                    if (loc as usize + len) <= mem.len() {
128
380
                        mem[loc as usize..loc as usize + len].copy_from_slice(&bytes[..len]);
129
380
                        return Ok(len as i32);
130
                    }
131
                    return Err(anyhow::anyhow!("Memory bounds error"));
132
                }
133

            
134
                Err(anyhow::anyhow!("Memory not available"))
135
            })();
136

            
137
            // Return the result or indicate failure (-1)
138
380
            match result {
139
380
                Ok(len) => len,
140
                Err(e) => {
141
                    tracing::error!("Error in wrap_wasm_str_list_get: {e:?}");
142
                    -1
143
                }
144
            }
145
380
        },
146
    )
147
380
}
148

            
149
380
pub fn wrap_wasm_str_map<Data>(
150
380
    store: &mut Store<Arc<DataStore<Data>>>,
151
380
    updater: impl Fn(&mut Data, String, String) -> Result<(), anyhow::Error> + Send + Sync + 'static,
152
380
) -> Func
153
380
where
154
380
    Data: Send + 'static,
155
{
156
380
    Func::wrap(
157
380
        store,
158
        move |caller: Caller<'_, Arc<DataStore<Data>>>,
159
              key_loc: i32,
160
              key_len: i32,
161
              value_loc: i32,
162
              value_len: i32|
163
570
              -> i32 {
164
570
            let data = caller.data();
165

            
166
570
            let result = (|| -> Result<()> {
167
570
                let memory = data
168
570
                    .memory
169
570
                    .lock()
170
                    .map_err(|_| anyhow::anyhow!("Failed to lock memory"))?;
171
570
                if let Some(memory) = &*memory {
172
570
                    let mem = memory.data(&caller);
173

            
174
570
                    if (key_loc as usize + key_len as usize) > mem.len()
175
570
                        || (value_loc as usize + value_len as usize) > mem.len()
176
                    {
177
                        return Err(anyhow::anyhow!("Memory bounds error"));
178
570
                    }
179

            
180
570
                    let key = String::from_utf8(
181
570
                        mem[key_loc as usize..key_loc as usize + key_len as usize].to_vec(),
182
570
                    )?;
183
570
                    let value = String::from_utf8(
184
570
                        mem[value_loc as usize..value_loc as usize + value_len as usize].to_vec(),
185
570
                    )?;
186

            
187
570
                    let mut builder = data
188
570
                        .data
189
570
                        .lock()
190
                        .map_err(|_| anyhow::anyhow!("Failed to lock data"))?;
191
570
                    updater(&mut builder, key, value)?;
192

            
193
570
                    Ok(())
194
                } else {
195
                    Err(anyhow::anyhow!("Memory not available"))
196
                }
197
            })();
198

            
199
570
            match result {
200
570
                Ok(()) => 0,
201
                Err(e) => {
202
                    tracing::error!("Error in wrap_wasm_str_map: {e:?}");
203
                    -1
204
                }
205
            }
206
570
        },
207
    )
208
380
}