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
//! V4 ASynchronous messages

use std::collections::HashMap;

use anyhow::anyhow;
use bytes::Bytes;
use futures::executor::block_on;
use libc::{c_char, c_int, c_uchar, c_uint, EXIT_FAILURE, EXIT_SUCCESS, size_t};
use pact_matching::generators::apply_generators_to_async_message;
use pact_models::bodies::OptionalBody;
use pact_models::content_types::{ContentType, ContentTypeHint};
use pact_models::generators::GeneratorTestMode;
use pact_models::provider_states::ProviderState;
use pact_models::v4::async_message::AsynchronousMessage;
use pact_models::v4::message_parts::MessageContents;

use crate::{as_mut, as_ref, ffi_fn, safe_str};
use crate::models::message::ProviderStateIterator;
use crate::ptr;
use crate::util::*;
use crate::util::string::optional_str;

ffi_fn! {
    /// Get a mutable pointer to a newly-created default message on the heap.
    ///
    /// # Safety
    ///
    /// This function is safe.
    ///
    /// # Error Handling
    ///
    /// Returns NULL on error.
    fn pactffi_async_message_new() -> *mut AsynchronousMessage {
        let message = AsynchronousMessage::default();
        ptr::raw_to(message)
    } {
        std::ptr::null_mut()
    }
}

ffi_fn! {
    /// Destroy the `AsynchronousMessage` being pointed to.
    fn pactffi_async_message_delete(message: *const AsynchronousMessage) {
        ptr::drop_raw(message as *mut AsynchronousMessage);
    }
}

ffi_fn! {
    /// Get the message contents of an `AsynchronousMessage` as a `MessageContents` pointer.
    ///
    /// # Safety
    ///
    /// The data pointed to by the pointer this function returns will be deleted when the message
    /// is deleted. Trying to use if after the message is deleted will result in undefined behaviour.
    ///
    /// # Error Handling
    ///
    /// If the message is NULL, returns NULL.
    fn pactffi_async_message_get_contents(message: *const AsynchronousMessage) -> *const MessageContents {
        let message = as_ref!(message);
        &message.contents as *const MessageContents
    } {
        std::ptr::null()
    }
}

ffi_fn! {
    /// Generate the message contents of an `AsynchronousMessage` as a
    /// `MessageContents` pointer.
    ///
    /// This function differs from [`pactffi_async_message_get_contents`] in
    /// that it will process the message contents for any generators or matchers
    /// that are present in the message in order to generate the actual message
    /// contents as would be received by the consumer.
    ///
    /// # Safety
    ///
    /// The data pointed to by the pointer must be deleted with
    /// [`pactffi_message_contents_delete`][crate::models::contents::pactffi_message_contents_delete]
    ///
    /// # Error Handling
    ///
    /// If the message is NULL, returns NULL.
    fn pactffi_async_message_generate_contents(message: *const AsynchronousMessage) -> *const MessageContents {
        let message = as_ref!(message);
        let context = HashMap::new();
        let plugin_data = Vec::new();
        let interaction_data = HashMap::new();
        let contents = block_on(apply_generators_to_async_message(
            &message,
            &GeneratorTestMode::Consumer,
            &context,
            &plugin_data,
            &interaction_data,
        ));
        ptr::raw_to(contents) as *const MessageContents
    } {
        std::ptr::null()
    }
}

ffi_fn! {
    /// Get the message contents of an `AsynchronousMessage` in string form.
    ///
    /// # Safety
    ///
    /// The returned string must be deleted with `pactffi_string_delete`.
    ///
    /// The returned string can outlive the message.
    ///
    /// # Error Handling
    ///
    /// If the message is NULL, returns NULL. If the body of the message
    /// is missing, then this function also returns NULL. This means there's
    /// no mechanism to differentiate with this function call alone between
    /// a NULL message and a missing message body.
    fn pactffi_async_message_get_contents_str(message: *const AsynchronousMessage) -> *const c_char {
        let message = as_ref!(message);

        match message.contents.contents {
            // If it's missing, return a null pointer.
            OptionalBody::Missing => std::ptr::null(),
            // If empty or null, return an empty string on the heap.
            OptionalBody::Empty | OptionalBody::Null => {
                let content = string::to_c("")?;
                content as *const c_char
            }
            // Otherwise, get the contents, possibly still empty.
            _ => {
                let content = string::to_c(message.contents.contents.value_as_string().unwrap_or_default().as_str())?;
                content as *const c_char
            }
        }
    } {
        std::ptr::null()
    }
}

ffi_fn! {
  /// Sets the contents of the message as a string.
  ///
  /// * `message` - the message to set the contents for
  /// * `contents` - pointer to contents to copy from. Must be a valid NULL-terminated UTF-8 string pointer.
  /// * `content_type` - pointer to the NULL-terminated UTF-8 string containing the content type of the data.
  ///
  /// # Safety
  ///
  /// The message contents and content type must either be NULL pointers, or point to valid
  /// UTF-8 encoded NULL-terminated strings. Otherwise behaviour is undefined.
  ///
  /// # Error Handling
  ///
  /// If the contents is a NULL pointer, it will set the message contents as null. If the content
  /// type is a null pointer, or can't be parsed, it will set the content type as unknown.
  fn pactffi_async_message_set_contents_str(message: *mut AsynchronousMessage, contents: *const c_char, content_type: *const c_char) {
    let message = as_mut!(message);

    if contents.is_null() {
      message.contents.contents = OptionalBody::Null;
    } else {
      let contents = safe_str!(contents);
      let content_type = optional_str(content_type).map(|ct| ContentType::parse(ct.as_str()).ok()).flatten();
      message.contents.contents = OptionalBody::Present(Bytes::from(contents), content_type, Some(ContentTypeHint::TEXT));
    }
  }
}

ffi_fn! {
    /// Get the length of the contents of a `AsynchronousMessage`.
    ///
    /// # Safety
    ///
    /// This function is safe.
    ///
    /// # Error Handling
    ///
    /// If the message is NULL, returns 0. If the body of the request
    /// is missing, then this function also returns 0.
    fn pactffi_async_message_get_contents_length(message: *const AsynchronousMessage) -> size_t {
        let message = as_ref!(message);

        match &message.contents.contents {
            OptionalBody::Missing | OptionalBody::Empty | OptionalBody::Null => 0 as size_t,
            OptionalBody::Present(bytes, _, _) => bytes.len() as size_t
        }
    } {
        0 as size_t
    }
}

ffi_fn! {
    /// Get the contents of an `AsynchronousMessage` as a pointer to an array of bytes.
    ///
    /// # Safety
    ///
    /// The number of bytes in the buffer will be returned by `pactffi_async_message_get_contents_length`.
    /// It is safe to use the pointer while the message is not deleted or changed. Using the pointer
    /// after the message is mutated or deleted may lead to undefined behaviour.
    ///
    /// # Error Handling
    ///
    /// If the message is NULL, returns NULL. If the body of the message
    /// is missing, then this function also returns NULL.
    fn pactffi_async_message_get_contents_bin(message: *const AsynchronousMessage) -> *const c_uchar {
        let message = as_ref!(message);

        match &message.contents.contents {
            OptionalBody::Empty | OptionalBody::Null | OptionalBody::Missing => std::ptr::null(),
            OptionalBody::Present(bytes, _, _) => bytes.as_ptr()
        }
    } {
        std::ptr::null()
    }
}

ffi_fn! {
  /// Sets the contents of the message as an array of bytes.
  ///
  /// * `message` - the message to set the contents for
  /// * `contents` - pointer to contents to copy from
  /// * `len` - number of bytes to copy from the contents pointer
  /// * `content_type` - pointer to the NULL-terminated UTF-8 string containing the content type of the data.
  ///
  /// # Safety
  ///
  /// The contents pointer must be valid for reads of `len` bytes, and it must be properly aligned
  /// and consecutive. Otherwise behaviour is undefined.
  ///
  /// # Error Handling
  ///
  /// If the contents is a NULL pointer, it will set the message contents as null. If the content
  /// type is a null pointer, or can't be parsed, it will set the content type as unknown.
  fn pactffi_async_message_set_contents_bin(
    message: *mut AsynchronousMessage,
    contents: *const c_uchar,
    len: size_t,
    content_type: *const c_char
  ) {
    let message = as_mut!(message);

    if contents.is_null() {
      message.contents.contents = OptionalBody::Null;
    } else {
      let slice = unsafe { std::slice::from_raw_parts(contents, len) };
      let contents = Bytes::from(slice);
      let content_type = optional_str(content_type).map(|ct| ContentType::parse(ct.as_str()).ok()).flatten();
      message.contents.contents = OptionalBody::Present(contents, content_type, Some(ContentTypeHint::BINARY));
    }
  }
}

ffi_fn! {
    /// Get a copy of the description.
    ///
    /// # Safety
    ///
    /// The returned string must be deleted with `pactffi_string_delete`.
    ///
    /// Since it is a copy, the returned string may safely outlive the `AsynchronousMessage`.
    ///
    /// # Errors
    ///
    /// On failure, this function will return a NULL pointer.
    ///
    /// This function may fail if the Rust string contains embedded
    /// null ('\0') bytes.
    fn pactffi_async_message_get_description(message: *const AsynchronousMessage) -> *const c_char {
        let message = as_ref!(message);
        let description = string::to_c(&message.description)?;
        description as *const c_char
    } {
        std::ptr::null()
    }
}

ffi_fn! {
    /// Write the `description` field on the `AsynchronousMessage`.
    ///
    /// # Safety
    ///
    /// `description` must contain valid UTF-8. Invalid UTF-8
    /// will be replaced with U+FFFD REPLACEMENT CHARACTER.
    ///
    /// This function will only reallocate if the new string
    /// does not fit in the existing buffer.
    ///
    /// # Error Handling
    ///
    /// Errors will be reported with a non-zero return value.
    fn pactffi_async_message_set_description(message: *mut AsynchronousMessage, description: *const c_char) -> c_int {
        let message = as_mut!(message);
        let description = safe_str!(description);

        // Wipe out the previous contents of the string, without
        // deallocating, and set the new description.
        message.description.clear();
        message.description.push_str(description);

        EXIT_SUCCESS
    } {
        EXIT_FAILURE
    }
}


ffi_fn! {
    /// Get a copy of the provider state at the given index from this message.
    ///
    /// # Safety
    ///
    /// The returned structure must be deleted with `provider_state_delete`.
    ///
    /// Since it is a copy, the returned structure may safely outlive the `AsynchronousMessage`.
    ///
    /// # Error Handling
    ///
    /// On failure, this function will return a variant other than Success.
    ///
    /// This function may fail if the index requested is out of bounds,
    /// or if any of the Rust strings contain embedded null ('\0') bytes.
    fn pactffi_async_message_get_provider_state(message: *const AsynchronousMessage, index: c_uint) -> *const ProviderState {
        let message = as_ref!(message);
        let index = index as usize;

        // Get a raw pointer directly, rather than boxing it, as its owned by the `SynchronousMessage`
        // and will be cleaned up when the `SynchronousMessage` is cleaned up.
        let provider_state = message
            .provider_states
            .get(index)
            .ok_or(anyhow!("index is out of bounds"))?;

        provider_state as *const ProviderState
    } {
        std::ptr::null()
    }
}

ffi_fn! {
    /// Get an iterator over provider states.
    ///
    /// # Safety
    ///
    /// The underlying data must not change during iteration.
    ///
    /// # Error Handling
    ///
    /// Returns NULL if an error occurs.
    fn pactffi_async_message_get_provider_state_iter(message: *mut AsynchronousMessage) -> *mut ProviderStateIterator {
        let message = as_mut!(message);
        let iter = ProviderStateIterator::new(message);
        ptr::raw_to(iter)
    } {
        std::ptr::null_mut()
    }
}

#[cfg(test)]
mod tests {
  use std::ffi::CString;

  use expectest::prelude::*;
  use libc::c_char;

  use pact_models::generators;
  use pact_models::generators::Generator;

  use super::{
    pactffi_async_message_delete,
    pactffi_async_message_generate_contents,
    pactffi_async_message_get_contents_length,
    pactffi_async_message_get_contents_str,
    pactffi_async_message_new,
    pactffi_async_message_set_contents_str,
  };

  #[test]
    fn get_and_set_message_contents() {
      let message = pactffi_async_message_new();
      let message_contents = CString::new("This is a string").unwrap();

      pactffi_async_message_set_contents_str(message, message_contents.as_ptr(), std::ptr::null());
      let contents = pactffi_async_message_get_contents_str(message) as *mut c_char;
      let len = pactffi_async_message_get_contents_length(message);
      let str = unsafe { CString::from_raw(contents) };

      pactffi_async_message_delete(message);

      expect!(str.to_str().unwrap()).to(be_equal_to("This is a string"));
      expect!(len).to(be_equal_to(16));
    }

    #[test]
    fn test_generate_contents() {
        let message = pactffi_async_message_new();
        let message_contents = CString::new(r#"{ "id": 1 }"#).unwrap();
        let content_type = CString::new("application/json").unwrap();
        pactffi_async_message_set_contents_str(message, message_contents.as_ptr(), content_type.as_ptr());

        unsafe { &mut *message }.contents.generators.add_generators(generators!{
            "body" => {
                "$.id" => Generator::RandomInt(1000, 1000)
            }
        });

        let contents = pactffi_async_message_generate_contents(message);

        assert_eq!(
            r#"{"id":1000}"#,
            unsafe { &*contents }.contents.value_as_string().unwrap()
        );
    }
}