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
//! Structs for shared parts of message interactions

use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};

use anyhow::anyhow;
use itertools::Itertools;
use maplit::hashmap;
use serde_json::{json, Value};

use crate::bodies::OptionalBody;
use crate::content_types::ContentType;
use crate::generators::{Generators, generators_from_json, generators_to_json};
use crate::http_parts::HttpPart;
use crate::json_utils::{hash_json, json_to_string};
use crate::matchingrules::{matchers_from_json, matchers_to_json, MatchingRules};
use crate::message::Message;
use crate::PactSpecification;
use crate::v4::calc_content_type;
use crate::v4::http_parts::body_from_json;

/// Contents of a message interaction
#[derive(Default, Clone, Debug, Eq)]
pub struct MessageContents {
  /// The contents of the message
  pub contents: OptionalBody,
  /// Metadata associated with this message.
  pub metadata: HashMap<String, Value>,
  /// Matching rules
  pub matching_rules: MatchingRules,
  /// Generators
  pub generators: Generators,
}

impl MessageContents {
  /// Parse the JSON into a MessageContents struct
  pub fn from_json(json: &Value) -> anyhow::Result<MessageContents> {
    if json.is_object() {
      let metadata = match json.get("metadata") {
        Some(&Value::Object(ref v)) => v.iter().map(|(k, v)| {
          (k.clone(), v.clone())
        }).collect(),
        _ => hashmap! {}
      };
      let as_headers = metadata_to_headers(&metadata);
      Ok(MessageContents {
        metadata,
        contents: body_from_json(json, "contents", &as_headers),
        matching_rules: matchers_from_json(json, &None)?,
        generators: generators_from_json(json)?,
      })
    } else {
      Err(anyhow!("Expected a JSON object for the message contents, got '{}'", json))
    }
  }

  /// Convert this message part into a JSON struct
  pub fn to_json(&self) -> Value {
    let mut json = json!({});

    let body = self.contents.with_content_type_if_not_set(self.message_content_type());
    if let Value::Object(body) = body.to_v4_json() {
      let map = json.as_object_mut().unwrap();
      map.insert("contents".to_string(), Value::Object(body));
    }

    if !self.metadata.is_empty() {
      let map = json.as_object_mut().unwrap();
      map.insert("metadata".to_string(), Value::Object(
        self.metadata.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
      ));
    }

    if !self.matching_rules.is_empty() {
      let map = json.as_object_mut().unwrap();
      map.insert("matchingRules".to_string(), matchers_to_json(&self.matching_rules, &PactSpecification::V4));
    }

    if !self.generators.is_empty() {
      let map = json.as_object_mut().unwrap();
      map.insert("generators".to_string(), generators_to_json(&self.generators, &PactSpecification::V4));
    }

    json
  }


  /// Returns the content type of the message by returning the content type associated with
  /// the body, or by looking it up in the message metadata
  pub fn message_content_type(&self) -> Option<ContentType> {
    calc_content_type(&self.contents, &metadata_to_headers(&self.metadata))
  }

  /// Convert this message contents to a V3 asynchronous message
  pub fn as_v3_message(&self) -> Message {
    Message {
      contents: self.contents.clone(),
      metadata: self.metadata.clone(),
      matching_rules: self.matching_rules.clone(),
      generators: self.generators.clone(),
      .. Message::default()
    }
  }
}

impl Display for MessageContents {
  fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
    write!(f, "Message Contents ( contents: {}, metadata: {:?} )", self.contents,
           self.metadata)
  }
}

impl Hash for MessageContents {
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.contents.hash(state);
    for (k, v) in self.metadata.iter()
      .sorted_by(|(a, _), (b, _)| Ord::cmp(a, b)) {
      k.hash(state);
      hash_json(v, state);
    }
    self.matching_rules.hash(state);
    self.generators.hash(state);
  }
}

impl PartialEq for MessageContents {
  fn eq(&self, other: &Self) -> bool {
    self.contents == other.contents &&
      self.metadata == other.metadata &&
      self.matching_rules == other.matching_rules &&
      self.generators == other.generators
  }
}

impl HttpPart for MessageContents {
  fn headers(&self) -> &Option<HashMap<String, Vec<String>>> {
    unimplemented!()
  }

  fn headers_mut(&mut self) -> &mut HashMap<String, Vec<String>> {
    unimplemented!()
  }

  fn body(&self) -> &OptionalBody {
    &self.contents
  }

  fn body_mut(&mut self) -> &mut OptionalBody {
    &mut self.contents
  }

  fn matching_rules(&self) -> &MatchingRules {
    &self.matching_rules
  }

  fn matching_rules_mut(&mut self) -> &mut MatchingRules {
    &mut self.matching_rules
  }

  fn generators(&self) -> &Generators {
    &self.generators
  }

  fn generators_mut(&mut self) -> &mut Generators {
    &mut self.generators
  }

  fn lookup_content_type(&self) -> Option<String> {
    self.metadata.iter().find(|(k, _)| {
      let key = k.to_ascii_lowercase();
      key == "contenttype" || key == "content-type"
    }).map(|(_, v)| json_to_string(&v[0]))
  }
}

pub(crate) fn metadata_to_headers(metadata: &HashMap<String, Value>) -> Option<HashMap<String, Vec<String>>> {
  metadata.get("contentType").map(|content_type| {
    hashmap! {
      "Content-Type".to_string() => vec![ json_to_string(content_type) ]
    }
  })
}

#[cfg(test)]
mod tests {
  use std::collections::hash_map::DefaultHasher;
  use std::hash::{Hash, Hasher};

  use bytes::Bytes;
  use expectest::prelude::*;
  use maplit::hashmap;
  use serde_json::Value;

  use crate::bodies::OptionalBody;
  use crate::v4::message_parts::MessageContents;

  fn hash<T: Hash>(t: &T) -> u64 {
    let mut s = DefaultHasher::new();
    t.hash(&mut s);
    s.finish()
  }

  #[test]
  fn hash_test() {
    let m1 = MessageContents::default();
    expect!(hash(&m1)).to(be_equal_to(13646096770106105413));

    let m2 = MessageContents {
      contents: OptionalBody::Present(Bytes::from("jhsgdajshdjashd"), None, None),
      .. MessageContents::default()
    };
    expect!(hash(&m2)).to(be_equal_to(17404772499757827990));

    let m3 = MessageContents {
      metadata: hashmap!{
        "q1".to_string() => Value::String("1".to_string()),
        "q2".to_string() => Value::String("2".to_string())
      },
      .. MessageContents::default()
    };
    expect!(hash(&m3)).to(be_equal_to(3336593541520431912));

    let mut m3 = MessageContents {
      metadata: hashmap!{
        "q2".to_string() => Value::String("2".to_string())
      },
      .. MessageContents::default()
    };
    m3.metadata.insert("q1".to_string(), Value::String("1".to_string()));
    expect!(hash(&m3)).to(be_equal_to(3336593541520431912));
  }

  #[test]
  fn equals_test_for_request() {
    let m1 = MessageContents::default();
    expect!(hash(&m1)).to(be_equal_to(13646096770106105413));

    let m2 = MessageContents {
      contents: OptionalBody::Present(Bytes::from("jhsgdajshdjashd"), None, None),
      .. MessageContents::default()
    };
    expect!(hash(&m2)).to(be_equal_to(17404772499757827990));

    let m3 = MessageContents {
      metadata: hashmap!{
        "q1".to_string() => Value::String("1".to_string()),
        "q2".to_string() => Value::String("2".to_string())
      },
      .. MessageContents::default()
    };

    assert_eq!(m1, m1);
    assert_eq!(m2, m2);
    assert_eq!(m3, m3);

    assert_ne!(m1, m2);
    assert_ne!(m1, m3);
    assert_ne!(m2, m3);
  }
}