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
// Copyright (c) 2016-2021 Memgraph Ltd. [https://memgraph.com]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::ffi::CStr;

use crate::memgraph::*;
#[double]
use crate::mgp::ffi;
use mockall_double::double;

/// Defines a new procedure callable by Memgraph engine.
///
/// Wraps call to the Rust function provided as a second argument. In addition to the function
/// call, it also sets the catch_unwind hook and properly handles execution errors. The first macro
/// argument is the exact name of the C procedure Memgraph will be able to run (the exact same name
/// has to be registered inside [init_module] phase. The second argument has to be a function
/// accepting reference [Memgraph]. The [Memgraph] object could be used to interact with Memgraph
/// instance.
///
/// Example
///
/// ```no run
/// define_procedure!(procedure_name, |memgraph: &Memgraph| -> Result<(), MgpError> {
///     // Implementation
/// }
/// ```
#[macro_export]
macro_rules! define_procedure {
    ($c_name:ident, $rs_func:expr) => {
        #[no_mangle]
        extern "C" fn $c_name(
            args: *const mgp_list,
            graph: *const mgp_graph,
            result: *mut mgp_result,
            memory: *mut mgp_memory,
        ) {
            let prev_hook = panic::take_hook();
            panic::set_hook(Box::new(|_| { /* Do nothing. */ }));

            let procedure_result = panic::catch_unwind(|| {
                let memgraph = Memgraph::new(args, graph, result, memory, std::ptr::null_mut());
                match $rs_func(&memgraph) {
                    Ok(_) => (),
                    Err(e) => {
                        println!("{}", e);
                        let msg = e.to_string();
                        println!("{}", msg);
                        let c_msg =
                            CString::new(msg).expect("Unable to create Memgraph error message!");
                        set_memgraph_error_msg(&c_msg, &memgraph);
                    }
                }
            });

            panic::set_hook(prev_hook);
            match procedure_result {
                Ok(_) => {}
                // TODO(gitbuda): Take cause on panic and pass to mgp_result_set_error_msg.
                // Until figuring out how to take info from panic object, set error in-place.
                // As far as I know iterator can't return Result object and set error in-place.
                Err(e) => {
                    println!("Procedure panic!");
                    match e.downcast::<&str>() {
                        Ok(panic_msg) => {
                            println!("{}", panic_msg);
                        }
                        Err(_) => {
                            println!("Unknown type of panic!.");
                        }
                    }
                    // TODO(gitbuda): Fix backtrace somehow.
                    println!("{:?}", Backtrace::new());
                }
            }
        }
    };
}

/// Initializes Memgraph query module.
///
/// Example
///
/// ```no run
/// init_module!(|memgraph: &Memgraph| -> MgpResult<()> {
///     memgraph.add_read_procedure(
///         procedure_name,
///         c_str!("procedure_name"),
///         &[define_type!("list", FieldType::List, FieldType::Int),],
///     )?;
///     Ok(())
/// });
/// ```
#[macro_export]
macro_rules! init_module {
    ($init_func:expr) => {
        #[no_mangle]
        pub extern "C" fn mgp_init_module(
            module: *mut mgp_module,
            memory: *mut mgp_memory,
        ) -> c_int {
            // TODO(gitbuda): Add error handling (catch_unwind, etc.).
            let memgraph = Memgraph::new(
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                memory,
                module,
            );
            match $init_func(&memgraph) {
                Ok(_) => 0,
                Err(_) => 1,
            }
        }
    };
}

/// Closes Memgraph query module.
#[macro_export]
macro_rules! close_module {
    ($close_func:expr) => {
        #[no_mangle]
        pub extern "C" fn mgp_shutdown_module() -> c_int {
            // TODO(gitbuda): Add error handling (catch_unwind, etc.).
            $close_func()
        }
    };
}

/// Used to pass expected result field types during procedure registration.
pub enum FieldType {
    Any,
    Bool,
    Number,
    Int,
    Double,
    String,
    Map,
    Vertex,
    Edge,
    Path,
    Nullable,
    List,
}

/// Used to pass expected result field types during procedure registration.
///
/// Each procedure can have multiple returning fields, each one is represented by this struct.
/// Return type is deduced by processing types field from left to right. E.g., [FieldType::Any]
/// means any return type, [FieldType::List], [FieldType::Int] means a list of integer values.
pub struct ResultFieldType<'a> {
    pub name: &'a CStr,
    pub types: &'a [FieldType],
}

/// Defines single result field type.
///
/// Example of defining the field as a list of integers.
///
/// ```no run
/// define_type!("name", FieldType::List, FieldType::Int);
/// ```
#[macro_export]
macro_rules! define_type {
    ($name:literal, $($types:expr),+) => {
        ResultFieldType {
            name: &c_str!($name),
            types: &[$($types),+],
        }
    };
}

pub fn set_memgraph_error_msg(msg: &CStr, memgraph: &Memgraph) {
    unsafe {
        let status = ffi::mgp_result_set_error_msg(memgraph.result(), msg.as_ptr());
        if status == 0 {
            panic!("Unable to pass error message to the Memgraph engine.");
        }
    }
}

// TODO(gitbuda): Add transaction management (abort) stuff.
// TODO(gitbuda): Deal with optional arguments.
// TODO(gitbuda): Add support for depricated arguments.

#[cfg(test)]
mod tests {
    use c_str_macro::c_str;
    use serial_test::serial;

    use super::*;
    use crate::mgp::mock_ffi::*;
    use crate::{mock_mgp_once, with_dummy};

    #[test]
    #[serial]
    fn test_set_error_msg() {
        mock_mgp_once!(mgp_result_set_error_msg_context, |_, _| 1);

        with_dummy!(|memgraph: &Memgraph| {
            set_memgraph_error_msg(c_str!("test_error"), &memgraph);
        });
    }
}