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
// Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement.  This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.

//! FFI for mutable data entry actions.

use App;
use ffi::helper::send_sync;
use ffi_utils::{FfiResult, catch_unwind_cb, vec_clone_from_raw_parts};
use object_cache::MDataEntryActionsHandle;
use routing::{EntryAction, Value};
use std::os::raw::c_void;

/// Create new entry actions.
///
/// Callback parameters: user data, error code, entry actions handle
#[no_mangle]
pub unsafe extern "C" fn mdata_entry_actions_new(
    app: *const App,
    user_data: *mut c_void,
    o_cb: extern "C" fn(user_data: *mut c_void,
                        result: FfiResult,
                        entry_actions_h: MDataEntryActionsHandle),
) {
    catch_unwind_cb(user_data, o_cb, || {
        send_sync(app, user_data, o_cb, |_, context| {
            let actions = Default::default();
            Ok(context.object_cache().insert_mdata_entry_actions(actions))
        })
    })
}

/// Add action to insert new entry.
///
/// Callback parameters: user data, error code
#[no_mangle]
pub unsafe extern "C" fn mdata_entry_actions_insert(
    app: *const App,
    actions_h: MDataEntryActionsHandle,
    key_ptr: *const u8,
    key_len: usize,
    value_ptr: *const u8,
    value_len: usize,
    user_data: *mut c_void,
    o_cb: extern "C" fn(user_data: *mut c_void, result: FfiResult),
) {
    add_action(app, actions_h, key_ptr, key_len, user_data, o_cb, || {
        EntryAction::Ins(Value {
            content: vec_clone_from_raw_parts(value_ptr, value_len),
            entry_version: 0,
        })
    })
}

/// Add action to update existing entry.
///
/// Callback parameters: user data, error code
#[no_mangle]
pub unsafe extern "C" fn mdata_entry_actions_update(
    app: *const App,
    actions_h: MDataEntryActionsHandle,
    key_ptr: *const u8,
    key_len: usize,
    value_ptr: *const u8,
    value_len: usize,
    entry_version: u64,
    user_data: *mut c_void,
    o_cb: extern "C" fn(user_data: *mut c_void, result: FfiResult),
) {
    add_action(app, actions_h, key_ptr, key_len, user_data, o_cb, || {
        EntryAction::Update(Value {
            content: vec_clone_from_raw_parts(value_ptr, value_len),
            entry_version: entry_version,
        })
    })
}

/// Add action to delete existing entry.
///
/// Callback parameters: user data, error code
#[no_mangle]
pub unsafe extern "C" fn mdata_entry_actions_delete(
    app: *const App,
    actions_h: MDataEntryActionsHandle,
    key_ptr: *const u8,
    key_len: usize,
    entry_version: u64,
    user_data: *mut c_void,
    o_cb: extern "C" fn(user_data: *mut c_void, result: FfiResult),
) {
    add_action(app, actions_h, key_ptr, key_len, user_data, o_cb, || {
        EntryAction::Del(entry_version)
    })
}

/// Free the entry actions from memory
///
/// Callback parameters: user data, error code
#[no_mangle]
pub unsafe extern "C" fn mdata_entry_actions_free(
    app: *const App,
    actions_h: MDataEntryActionsHandle,
    user_data: *mut c_void,
    o_cb: extern "C" fn(user_data: *mut c_void, result: FfiResult),
) {
    catch_unwind_cb(user_data, o_cb, || {
        send_sync(app, user_data, o_cb, move |_, context| {
            let _ = context.object_cache().remove_mdata_entry_actions(actions_h)?;
            Ok(())
        })
    })
}

// Add new action to the entry actions stored in the object cache. The action
// to add is the result of the passed in lambda `f`.
unsafe fn add_action<F>(
    app: *const App,
    actions_h: MDataEntryActionsHandle,
    key_ptr: *const u8,
    key_len: usize,
    user_data: *mut c_void,
    o_cb: extern "C" fn(user_data: *mut c_void, result: FfiResult),
    f: F,
) where
    F: FnOnce() -> EntryAction,
{
    catch_unwind_cb(user_data, o_cb, || {
        let key = vec_clone_from_raw_parts(key_ptr, key_len);
        let action = f();

        send_sync(app, user_data, o_cb, move |_, context| {
            let mut actions = context.object_cache().get_mdata_entry_actions(actions_h)?;
            let _ = actions.insert(key, action);
            Ok(())
        })
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use ffi_utils::test_utils::{call_0, call_1};
    use routing::{EntryAction, Value};
    use safe_core::utils;
    use test_utils::{create_app, run_now};

    // Test entry action basics such as insert, update, and delete.
    #[test]
    fn basics() {
        let app = create_app();

        let handle = unsafe { unwrap!(call_1(|ud, cb| mdata_entry_actions_new(&app, ud, cb))) };

        run_now(&app, move |_, context| {
            let actions = unwrap!(context.object_cache().get_mdata_entry_actions(handle));
            assert!(actions.is_empty());
        });

        let key0 = b"key0".to_vec();
        let key1 = b"key1".to_vec();
        let key2 = b"key2".to_vec();

        let value0 = unwrap!(utils::generate_random_vector(10));
        let value1 = unwrap!(utils::generate_random_vector(10));

        let version1 = 4;
        let version2 = 8;

        unsafe {
            unwrap!(call_0(|ud, cb| {
                mdata_entry_actions_insert(
                    &app,
                    handle,
                    key0.as_ptr(),
                    key0.len(),
                    value0.as_ptr(),
                    value0.len(),
                    ud,
                    cb,
                )
            }));

            unwrap!(call_0(|ud, cb| {
                mdata_entry_actions_update(
                    &app,
                    handle,
                    key1.as_ptr(),
                    key1.len(),
                    value1.as_ptr(),
                    value1.len(),
                    version1,
                    ud,
                    cb,
                )
            }));

            unwrap!(call_0(|ud, cb| {
                mdata_entry_actions_delete(
                    &app,
                    handle,
                    key2.as_ptr(),
                    key2.len(),
                    version2,
                    ud,
                    cb,
                )
            }));
        }

        run_now(&app, move |_, context| {
            let actions = unwrap!(context.object_cache().get_mdata_entry_actions(handle));
            assert_eq!(actions.len(), 3);

            match *unwrap!(actions.get(&key0)) {
                EntryAction::Ins(Value {
                                     ref content,
                                     entry_version: 0,
                                 }) if *content == value0 => (),
                _ => panic!("Unexpected action"),
            }

            match *unwrap!(actions.get(&key1)) {
                EntryAction::Update(Value {
                                        ref content,
                                        entry_version,
                                    }) if *content == value1 && entry_version == version1 => (),
                _ => panic!("Unexpected action"),
            }

            match *unwrap!(actions.get(&key2)) {
                EntryAction::Del(version) if version == version2 => (),
                _ => panic!("Unexpected action"),
            }
        });

        unsafe {
            unwrap!(call_0(
                |ud, cb| mdata_entry_actions_free(&app, handle, ud, cb),
            ))
        };

        run_now(&app, move |_, context| {
            assert!(
                context
                    .object_cache()
                    .get_mdata_entry_actions(handle)
                    .is_err()
            )
        });
    }
}