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
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::anyhow;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tonic::metadata::MetadataValue;
use tonic::transport::Channel;
use tracing::{debug, trace};
use crate::child_process::ChildPluginProcess;
use crate::proto::*;
use crate::proto::pact_plugin_client::PactPluginClient;
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Debug, Hash)]
pub enum PluginDependencyType {
OSPackage,
Plugin,
Library,
Executable
}
impl Default for PluginDependencyType {
fn default() -> Self {
PluginDependencyType::Plugin
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug, Hash)]
#[serde(rename_all = "camelCase")]
pub struct PluginDependency {
pub name: String,
pub version: Option<String>,
#[serde(default)]
pub dependency_type: PluginDependencyType
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PactPluginManifest {
#[serde(skip)]
pub plugin_dir: String,
pub plugin_interface_version: u8,
pub name: String,
pub version: String,
pub executable_type: String,
pub minimum_required_version: Option<String>,
pub entry_point: String,
#[serde(default)]
pub entry_points: HashMap<String, String>,
pub dependencies: Option<Vec<PluginDependency>>,
#[serde(default)]
pub plugin_config: HashMap<String, Value>
}
impl PactPluginManifest {
pub fn as_dependency(&self) -> PluginDependency {
PluginDependency {
name: self.name.clone(),
version: Some(self.version.clone()),
dependency_type: PluginDependencyType::Plugin
}
}
}
impl Default for PactPluginManifest {
fn default() -> Self {
PactPluginManifest {
plugin_dir: "".to_string(),
plugin_interface_version: 1,
name: "".to_string(),
version: "".to_string(),
executable_type: "".to_string(),
minimum_required_version: None,
entry_point: "".to_string(),
entry_points: Default::default(),
dependencies: None,
plugin_config: Default::default()
}
}
}
#[async_trait]
pub trait PactPluginRpc {
async fn init_plugin(&self, request: InitPluginRequest) -> anyhow::Result<InitPluginResponse>;
async fn compare_contents(&self, request: CompareContentsRequest) -> anyhow::Result<CompareContentsResponse>;
async fn configure_interaction(&self, request: ConfigureInteractionRequest) -> anyhow::Result<ConfigureInteractionResponse>;
async fn generate_content(&self, request: GenerateContentRequest) -> anyhow::Result<GenerateContentResponse>;
async fn start_mock_server(&self, request: StartMockServerRequest) -> anyhow::Result<StartMockServerResponse>;
async fn shutdown_mock_server(&self, request: ShutdownMockServerRequest) -> anyhow::Result<ShutdownMockServerResponse>;
async fn prepare_interaction_for_verification(&self, request: VerificationPreparationRequest) -> anyhow::Result<VerificationPreparationResponse>;
async fn verify_interaction(&self, request: VerifyInteractionRequest) -> anyhow::Result<VerifyInteractionResponse>;
}
#[derive(Debug, Clone)]
pub struct PactPlugin {
pub manifest: PactPluginManifest,
pub child: Arc<ChildPluginProcess>,
access_count: usize
}
#[async_trait]
impl PactPluginRpc for PactPlugin {
async fn init_plugin(&self, request: InitPluginRequest) -> anyhow::Result<InitPluginResponse> {
let channel = self.connect_channel().await?;
let auth_str = self.child.plugin_info.server_key.as_str();
let token = MetadataValue::from_str(auth_str)?;
let mut client = PactPluginClient::with_interceptor(channel, move |mut req: tonic::Request<_>| {
req.metadata_mut().insert("authorization", token.clone());
Ok(req)
});
let response = client.init_plugin(tonic::Request::new(request)).await?;
Ok(response.get_ref().clone())
}
async fn compare_contents(&self, request: CompareContentsRequest) -> anyhow::Result<CompareContentsResponse> {
let channel = self.connect_channel().await?;
let auth_str = self.child.plugin_info.server_key.as_str();
let token = MetadataValue::from_str(auth_str)?;
let mut client = PactPluginClient::with_interceptor(channel, move |mut req: tonic::Request<_>| {
req.metadata_mut().insert("authorization", token.clone());
Ok(req)
});
let response = client.compare_contents(tonic::Request::new(request)).await?;
Ok(response.get_ref().clone())
}
async fn configure_interaction(&self, request: ConfigureInteractionRequest) -> anyhow::Result<ConfigureInteractionResponse> {
let channel = self.connect_channel().await?;
let auth_str = self.child.plugin_info.server_key.as_str();
let token = MetadataValue::from_str(auth_str)?;
let mut client = PactPluginClient::with_interceptor(channel, move |mut req: tonic::Request<_>| {
req.metadata_mut().insert("authorization", token.clone());
Ok(req)
});
let response = client.configure_interaction(tonic::Request::new(request)).await?;
Ok(response.get_ref().clone())
}
async fn generate_content(&self, request: GenerateContentRequest) -> anyhow::Result<GenerateContentResponse> {
let channel = self.connect_channel().await?;
let auth_str = self.child.plugin_info.server_key.as_str();
let token = MetadataValue::from_str(auth_str)?;
let mut client = PactPluginClient::with_interceptor(channel, move |mut req: tonic::Request<_>| {
req.metadata_mut().insert("authorization", token.clone());
Ok(req)
});
let response = client.generate_content(tonic::Request::new(request)).await?;
Ok(response.get_ref().clone())
}
async fn start_mock_server(&self, request: StartMockServerRequest) -> anyhow::Result<StartMockServerResponse> {
let channel = self.connect_channel().await?;
let auth_str = self.child.plugin_info.server_key.as_str();
let token = MetadataValue::from_str(auth_str)?;
let mut client = PactPluginClient::with_interceptor(channel, move |mut req: tonic::Request<_>| {
req.metadata_mut().insert("authorization", token.clone());
Ok(req)
});
let response = client.start_mock_server(tonic::Request::new(request)).await?;
Ok(response.get_ref().clone())
}
async fn shutdown_mock_server(&self, request: ShutdownMockServerRequest) -> anyhow::Result<ShutdownMockServerResponse> {
let channel = self.connect_channel().await?;
let auth_str = self.child.plugin_info.server_key.as_str();
let token = MetadataValue::from_str(auth_str)?;
let mut client = PactPluginClient::with_interceptor(channel, move |mut req: tonic::Request<_>| {
req.metadata_mut().insert("authorization", token.clone());
Ok(req)
});
let response = client.shutdown_mock_server(tonic::Request::new(request)).await?;
Ok(response.get_ref().clone())
}
async fn prepare_interaction_for_verification(&self, request: VerificationPreparationRequest) -> anyhow::Result<VerificationPreparationResponse> {
let channel = self.connect_channel().await?;
let auth_str = self.child.plugin_info.server_key.as_str();
let token = MetadataValue::from_str(auth_str)?;
let mut client = PactPluginClient::with_interceptor(channel, move |mut req: tonic::Request<_>| {
req.metadata_mut().insert("authorization", token.clone());
Ok(req)
});
let response = client.prepare_interaction_for_verification(tonic::Request::new(request)).await?;
Ok(response.get_ref().clone())
}
async fn verify_interaction(&self, request: VerifyInteractionRequest) -> anyhow::Result<VerifyInteractionResponse> {
let channel = self.connect_channel().await?;
let auth_str = self.child.plugin_info.server_key.as_str();
let token = MetadataValue::from_str(auth_str)?;
let mut client = PactPluginClient::with_interceptor(channel, move |mut req: tonic::Request<_>| {
req.metadata_mut().insert("authorization", token.clone());
Ok(req)
});
let response = client.verify_interaction(tonic::Request::new(request)).await?;
Ok(response.get_ref().clone())
}
}
impl PactPlugin {
pub fn new(manifest: &PactPluginManifest, child: ChildPluginProcess) -> Self {
PactPlugin { manifest: manifest.clone(), child: Arc::new(child), access_count: 1 }
}
pub fn port(&self) -> u16 {
self.child.port()
}
pub fn kill(&self) {
self.child.kill();
}
pub fn update_access(&mut self) {
self.access_count += 1;
trace!("update_access: Plugin {}/{} access is now {}", self.manifest.name, self.manifest.version,
self.access_count);
}
pub fn drop_access(&mut self) -> usize {
if self.access_count > 0 {
self.access_count -= 1;
}
trace!("drop_access: Plugin {}/{} access is now {}", self.manifest.name, self.manifest.version,
self.access_count);
self.access_count
}
async fn connect_channel(&self) -> anyhow::Result<Channel> {
let port = self.child.port();
match Channel::from_shared(format!("http://[::1]:{}", port))?.connect().await {
Ok(channel) => Ok(channel),
Err(err) => {
debug!("IP6 connection failed, will try IP4 address - {err}");
Channel::from_shared(format!("http://127.0.0.1:{}", port))?.connect().await
.map_err(|err| anyhow!(err))
}
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct PluginInteractionConfig {
pub pact_configuration: HashMap<String, Value>,
pub interaction_configuration: HashMap<String, Value>
}