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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
#![warn(unused_extern_crates)]

use smartnoise_validator::errors::*;

use prost::Message;
use smartnoise_validator::proto;

mod utilities;

#[cfg(feature = "use-direct-api")]
mod direct_api;

use smartnoise_validator::utilities::serial::{
    serialize_error, parse_release, serialize_release, parse_argument_properties,
    serialize_value_properties, parse_indexmap_release_node, serialize_component_expansion
};
use crate::utilities::{ptr_to_buffer, buffer_to_ptr};
use smartnoise_validator::base::Release;
use std::collections::HashMap;
use indexmap::map::IndexMap;

/// FFI wrapper for [validate_analysis](../fn.validate_analysis.html)
///
/// # Arguments
/// - `request_ptr` - a pointer to an array containing the serialized protobuf of [RequestValidateAnalysis](../proto/struct.RequestValidateAnalysis.html)
/// - `request_length` - the length of the array
///
/// # Returns
/// a [ByteBufferValidator struct](struct.ByteBufferValidator.html) containing a pointer to and length of the serialized protobuf of [proto::ResponseValidateAnalysis](../proto/struct.ResponseValidateAnalysis.html)
#[no_mangle]
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub extern "C" fn validate_analysis(
    request_ptr: *const u8, request_length: i32,
) -> ffi_support::ByteBuffer {
    let request_buffer = unsafe { ptr_to_buffer(request_ptr, request_length) };

    let response = proto::ResponseValidateAnalysis {
        value: match proto::RequestValidateAnalysis::decode(request_buffer) {
            Ok(request) => {
                let proto::RequestValidateAnalysis {
                    analysis, release
                } = request;

                let run = || -> Result<()> {
                    let proto::Analysis {
                        privacy_definition, computation_graph
                    } = analysis
                        .ok_or_else(|| Error::from("analysis must be defined"))?;
                    let release = parse_release(release
                        .ok_or_else(|| Error::from("release must be defined"))?);

                    let computation_graph = computation_graph
                        .ok_or_else(|| Error::from("computation_graph must be defined"))?.value;

                    smartnoise_validator::validate_analysis(privacy_definition, computation_graph, release)
                };

                match run() {
                    Ok(_) =>
                        Some(proto::response_validate_analysis::Value::Data(proto::response_validate_analysis::Validated {
                            value: true,
                            message: "The analysis is valid.".to_string(),
                        })),
                    Err(err) =>
                        Some(proto::response_validate_analysis::Value::Error(serialize_error(err))),
                }
            }
            Err(_) =>
                Some(proto::response_validate_analysis::Value::Error(serialize_error("unable to parse protobuf".into())))
        }
    };
    buffer_to_ptr(response)
}

/// FFI wrapper for [compute_privacy_usage](../fn.compute_privacy_usage.html)
///
/// # Arguments
/// - `request_ptr` - a pointer to an array containing the serialized protobuf of [RequestComputePrivacyUsage](../proto/struct.RequestComputePrivacyUsage.html)
/// - `request_length` - the length of the array
///
/// # Returns
/// a [ByteBufferValidator struct](struct.ByteBufferValidator.html) containing a pointer to and length of the serialized protobuf of [proto::ResponseComputePrivacyUsage](../proto/struct.ResponseComputePrivacyUsage.html)
#[no_mangle]
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub extern "C" fn compute_privacy_usage(
    request_ptr: *const u8, request_length: i32,
) -> ffi_support::ByteBuffer {
    let request_buffer = unsafe { ptr_to_buffer(request_ptr, request_length) };

    let response = proto::ResponseComputePrivacyUsage {
        value: match proto::RequestComputePrivacyUsage::decode(request_buffer) {
            Ok(request) => {
                let proto::RequestComputePrivacyUsage {
                    analysis, release
                } = request;


                let run = || -> Result<proto::PrivacyUsage> {
                    let proto::Analysis {
                        privacy_definition, computation_graph
                    } = analysis
                        .ok_or_else(|| Error::from("analysis must be defined"))?;
                    let release = parse_release(release
                        .ok_or_else(|| Error::from("release must be defined"))?);

                    let privacy_definition = privacy_definition
                        .ok_or_else(|| Error::from("privacy_definition must be defined"))?;
                    let computation_graph = computation_graph
                        .ok_or_else(|| Error::from("computation_graph must be defined"))?.value;

                    smartnoise_validator::compute_privacy_usage(privacy_definition, computation_graph, release)
                };

                match run() {
                    Ok(x) =>
                        Some(proto::response_compute_privacy_usage::Value::Data(x)),
                    Err(err) =>
                        Some(proto::response_compute_privacy_usage::Value::Error(serialize_error(err))),
                }
            }
            Err(_) =>
                Some(proto::response_compute_privacy_usage::Value::Error(serialize_error("unable to parse protobuf".into())))
        }
    };
    buffer_to_ptr(response)
}

/// FFI wrapper for [generate_report](../fn.generate_report.html)
///
/// # Arguments
/// - `request_ptr` - a pointer to an array containing the serialized protobuf of [RequestGenerateReport](../proto/struct.RequestGenerateReport.html)
/// - `request_length` - the length of the array
///
/// # Returns
/// a [ByteBufferValidator struct](struct.ByteBufferValidator.html) containing a pointer to and length of the serialized protobuf of [proto::ResponseGenerateReport](../proto/struct.ResponseGenerateReport.html)
#[no_mangle]
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub extern "C" fn generate_report(
    request_ptr: *const u8, request_length: i32,
) -> ffi_support::ByteBuffer {
    let request_buffer = unsafe { ptr_to_buffer(request_ptr, request_length) };

    let response = proto::ResponseGenerateReport {
        value: match proto::RequestGenerateReport::decode(request_buffer) {
            Ok(request) => {
                let run = || -> Result<String> {
                    let proto::Analysis {
                        privacy_definition, computation_graph
                    } = request.analysis
                        .ok_or_else(|| Error::from("analysis must be defined"))?;
                    let release = parse_release(request.release
                        .ok_or_else(|| Error::from("release must be defined"))?);

                    let privacy_definition = privacy_definition
                        .ok_or_else(|| Error::from("privacy_definition must be defined"))?;
                    let computation_graph = computation_graph
                        .ok_or_else(|| Error::from("computation_graph must be defined"))?.value;

                    smartnoise_validator::generate_report(privacy_definition, computation_graph, release)
                };

                match run() {
                    Ok(x) =>
                        Some(proto::response_generate_report::Value::Data(x)),
                    Err(err) =>
                        Some(proto::response_generate_report::Value::Error(serialize_error(err))),
                }
            }
            Err(_) =>
                Some(proto::response_generate_report::Value::Error(serialize_error("unable to parse protobuf".into())))
        }
    };
    buffer_to_ptr(response)
}

/// FFI wrapper for [accuracy_to_privacy_usage](../fn.accuracy_to_privacy_usage.html)
///
/// # Arguments
/// - `request_ptr` - a pointer to an array containing the serialized protobuf of [RequestAccuracyToPrivacyUsage](../proto/struct.RequestAccuracyToPrivacyUsage.html)
/// - `request_length` - the length of the array
///
/// # Returns
/// a [ByteBufferValidator struct](struct.ByteBufferValidator.html) containing a pointer to and length of the serialized protobuf of [proto::ResponseAccuracyToPrivacyUsage](../proto/struct.ResponseAccuracyToPrivacyUsage.html)
#[no_mangle]
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub extern "C" fn accuracy_to_privacy_usage(
    request_ptr: *const u8, request_length: i32,
) -> ffi_support::ByteBuffer {
    let request_buffer = unsafe { ptr_to_buffer(request_ptr, request_length) };

    let response = proto::ResponseAccuracyToPrivacyUsage {
        value: match proto::RequestAccuracyToPrivacyUsage::decode(request_buffer) {
            Ok(request) => {
                let proto::RequestAccuracyToPrivacyUsage {
                    component, privacy_definition, properties, accuracies, public_arguments
                } = request;


                // this function allows for catching errors via ?.
                let run = || -> Result<proto::PrivacyUsages> {
                    let component: proto::Component = component
                        .ok_or_else(|| Error::from("component must be defined"))?;
                    let privacy_definition: proto::PrivacyDefinition = privacy_definition
                        .ok_or_else(|| Error::from("privacy definition must be defined"))?;
                    let properties = parse_argument_properties(properties
                        .ok_or_else(|| Error::from("properties must be defined"))?);
                    let accuracies: proto::Accuracies = accuracies
                        .ok_or_else(|| Error::from("accuracies must be defined"))?;
                    let public_arguments = public_arguments
                        .map_or_else(IndexMap::new, parse_indexmap_release_node);

                    smartnoise_validator::accuracy_to_privacy_usage(
                        component, privacy_definition, properties, accuracies, public_arguments
                    )
                };

                match run() {
                    Ok(x) =>
                        Some(proto::response_accuracy_to_privacy_usage::Value::Data(x)),
                    Err(err) =>
                        Some(proto::response_accuracy_to_privacy_usage::Value::Error(serialize_error(err))),
                }
            }
            Err(_) =>
                Some(proto::response_accuracy_to_privacy_usage::Value::Error(serialize_error("unable to parse protobuf".into())))
        }
    };

    buffer_to_ptr(response)
}

/// FFI wrapper for [privacy_usage_to_accuracy](../fn.privacy_usage_to_accuracy.html)
///
/// # Arguments
/// - `request_ptr` - a pointer to an array containing the serialized protobuf of [RequestPrivacyUsageToAccuracy](../proto/struct.RequestPrivacyUsageToAccuracy.html)
/// - `request_length` - the length of the array
///
/// # Returns
/// a [ByteBufferValidator struct](struct.ByteBufferValidator.html) containing a pointer to and length of the serialized protobuf of [proto::ResponsePrivacyUsageToAccuracy](../proto/struct.ResponsePrivacyUsageToAccuracy.html)
#[no_mangle]
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub extern "C" fn privacy_usage_to_accuracy(
    request_ptr: *const u8, request_length: i32,
) -> ffi_support::ByteBuffer {
    let request_buffer = unsafe { ptr_to_buffer(request_ptr, request_length) };

    let response = proto::ResponsePrivacyUsageToAccuracy {
        value: match proto::RequestPrivacyUsageToAccuracy::decode(request_buffer) {
            Ok(request) => {
                let proto::RequestPrivacyUsageToAccuracy {
                    component, privacy_definition, properties, alpha, public_arguments
                } = request;

                let run = || -> Result<proto::Accuracies> {
                    let component: proto::Component = component
                        .ok_or_else(|| Error::from("component must be defined"))?;
                    let privacy_definition: proto::PrivacyDefinition = privacy_definition
                        .ok_or_else(|| Error::from("privacy definition must be defined"))?;
                    let properties = parse_argument_properties(properties
                        .ok_or_else(|| Error::from("properties must be defined"))?);
                    let public_arguments = public_arguments
                        .map_or_else(IndexMap::new, parse_indexmap_release_node);

                    smartnoise_validator::privacy_usage_to_accuracy(
                        component, privacy_definition, properties, public_arguments, alpha)
                };

                match run() {
                    Ok(x) =>
                        Some(proto::response_privacy_usage_to_accuracy::Value::Data(x)),
                    Err(err) =>
                        Some(proto::response_privacy_usage_to_accuracy::Value::Error(serialize_error(err))),
                }
            }
            Err(_) =>
                Some(proto::response_privacy_usage_to_accuracy::Value::Error(serialize_error("unable to parse protobuf".into())))
        }
    };
    buffer_to_ptr(response)
}

/// FFI wrapper for [get_properties](../fn.get_properties.html)
///
/// # Arguments
/// - `request_ptr` - a pointer to an array containing the serialized protobuf of [RequestGetProperties](../proto/struct.RequestGetProperties.html)
/// - `request_length` - the length of the array
///
/// # Returns
/// a [ByteBufferValidator struct](struct.ByteBufferValidator.html) containing a pointer to and length of the serialized protobuf of [proto::ResponseGetProperties](../proto/struct.ResponseGetProperties.html)
#[no_mangle]
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub extern "C" fn get_properties(
    request_ptr: *const u8, request_length: i32,
) -> ffi_support::ByteBuffer {
    let request_buffer = unsafe { ptr_to_buffer(request_ptr, request_length) };

    let response = proto::ResponseGetProperties {
        value: match proto::RequestGetProperties::decode(request_buffer) {
            Ok(request) => {
                let proto::RequestGetProperties {
                    analysis, release, node_ids
                } = request;

                let run = || -> Result<proto::GraphProperties> {
                    let proto::Analysis {
                        privacy_definition, computation_graph
                    } = analysis
                        .ok_or_else(|| Error::from("analysis must be defined"))?;
                    let release = parse_release(release
                        .ok_or_else(|| Error::from("release must be defined"))?);

                    let computation_graph = computation_graph
                        .ok_or_else(|| Error::from("computation_graph must be defined"))?.value;

                    let (properties, warnings) = smartnoise_validator::get_properties(
                        privacy_definition, computation_graph, release, node_ids)?;

                    Ok(proto::GraphProperties {
                        properties: properties.into_iter()
                            .map(|(node_id, properties)| (node_id, serialize_value_properties(properties)))
                            .collect::<HashMap<u32, proto::ValueProperties>>(),
                        warnings: warnings.into_iter().map(serialize_error).collect(),
                    })
                };

                match run() {
                    Ok(x) =>
                        Some(proto::response_get_properties::Value::Data(x)),
                    Err(err) =>
                        Some(proto::response_get_properties::Value::Error(serialize_error(err))),
                }
            }
            Err(_) =>
                Some(proto::response_get_properties::Value::Error(serialize_error("unable to parse protobuf".into())))
        }
    };
    buffer_to_ptr(response)
}

/// FFI wrapper for [expand_component](../fn.expand_component.html)
///
/// # Arguments
/// - `request_ptr` - a pointer to an array containing the serialized protobuf of [RequestExpandComponent](../proto/struct.RequestExpandComponent.html)
/// - `request_length` - the length of the array
///
/// # Returns
/// a [ByteBufferValidator struct](struct.ByteBufferValidator.html) containing a pointer to and length of the serialized protobuf of [proto::ResponseExpandComponent](../proto/struct.ResponseExpandComponent.html)
#[no_mangle]
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub extern "C" fn expand_component(
    request_ptr: *const u8, request_length: i32,
) -> ffi_support::ByteBuffer {
    let request_buffer = unsafe { ptr_to_buffer(request_ptr, request_length) };

    let response = proto::ResponseExpandComponent {
        value: match proto::RequestExpandComponent::decode(request_buffer) {
            Ok(request) => {
                let proto::RequestExpandComponent {
                    component, properties, arguments, privacy_definition, component_id, maximum_id,
                } = request;

                let run = || -> Result<proto::ComponentExpansion> {
                    let component = component
                        .ok_or_else(|| Error::from("component must be defined"))?;

                    let public_arguments = arguments
                        .map_or_else(IndexMap::new, parse_indexmap_release_node);

                    let properties = properties
                        .map_or_else(IndexMap::new, parse_argument_properties);

                    Ok(serialize_component_expansion(smartnoise_validator::expand_component(
                        component,
                        properties,
                        public_arguments,
                        privacy_definition,
                        component_id,
                        maximum_id)?))
                };

                match run() {
                    Ok(x) =>
                        Some(proto::response_expand_component::Value::Data(x)),
                    Err(err) =>
                        Some(proto::response_expand_component::Value::Error(serialize_error(err))),
                }
            }
            Err(_) =>
                Some(proto::response_expand_component::Value::Error(serialize_error("unable to parse protobuf".into())))
        }
    };
    buffer_to_ptr(response)
}

/// FFI wrapper for [release](fn.release.html)
///
/// # Arguments
/// - `request_ptr` - a pointer to an array containing the serialized protobuf of [RequestRelease](proto/struct.RequestRelease.html)
/// - `request_length` - the length of the array
///
/// # Returns
/// a [ByteBufferRuntime struct](struct.ByteBufferRuntime.html) containing a pointer to and length of the serialized protobuf of [proto::ResponseRelease](proto/struct.ResponseRelease.html)
#[cfg(feature = "use-runtime")]
#[no_mangle]
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub extern "C" fn release(
    request_ptr: *const u8, request_length: i32,
) -> ffi_support::ByteBuffer {
    let request_buffer = unsafe { ptr_to_buffer(request_ptr, request_length) };

    let response = proto::ResponseRelease {
        value: match proto::RequestRelease::decode(request_buffer) {
            Ok(request) => {
                let proto::RequestRelease {
                    analysis, release, stack_trace, filter_level
                } = request;


                let run = || -> Result<(Release, Vec<proto::Error>)> {
                    let proto::Analysis {
                        privacy_definition, computation_graph
                    } = analysis
                        .ok_or_else(|| Error::from("analysis must be defined"))?;
                    let computation_graph = computation_graph
                        .ok_or_else(|| Error::from("computation_graph must be defined"))?.value;
                    let release = parse_release(release
                        .ok_or_else(|| Error::from("release must be defined"))?);
                    let filter_level = proto::FilterLevel::from_i32(filter_level)
                        .ok_or_else(|| Error::from(format!("unrecognized filter level {:?}", filter_level)))?;

                    let (release, warnings) = smartnoise_runtime::release(
                        privacy_definition, computation_graph, release, filter_level)?;

                    Ok((release, warnings.into_iter().map(serialize_error).collect()))
                };

                match run() {
                    Ok((release, warnings)) => Some(proto::response_release::Value::Data(proto::response_release::Success {
                        release: Some(serialize_release(release)),
                        warnings: if stack_trace { warnings } else { Vec::new() },
                    })),
                    Err(err) => if stack_trace {
                        Some(proto::response_release::Value::Error(serialize_error(err)))
                    } else {
                        Some(proto::response_release::Value::Error(serialize_error("unspecified error while executing analysis".into())))
                    }
                }
            }
            Err(_) => Some(proto::response_release::Value::Error(serialize_error("unable to parse protobuf".into())))
        }
    };
    buffer_to_ptr(response)
}


ffi_support::define_bytebuffer_destructor!(smartnoise_destroy_bytebuffer);