1use std::collections::HashMap;
4use std::fmt::{Display, Formatter};
5use std::sync::Arc;
6use std::sync::atomic::{AtomicUsize, Ordering};
7
8use anyhow::anyhow;
9use async_trait::async_trait;
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12use tracing::trace;
13
14use crate::child_process::ChildPluginProcess;
15use crate::proto::*;
16use crate::proto_v2;
17
18#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Debug, Hash)]
20pub enum PluginDependencyType {
21 OSPackage,
23 Plugin,
25 Library,
27 Executable,
29}
30
31impl Default for PluginDependencyType {
32 fn default() -> Self {
33 PluginDependencyType::Plugin
34 }
35}
36
37#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug, Hash)]
39#[serde(rename_all = "camelCase")]
40pub struct PluginDependency {
41 pub name: String,
43 pub version: Option<String>,
45 #[serde(default)]
47 pub dependency_type: PluginDependencyType,
48}
49
50impl Display for PluginDependency {
51 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
52 if let Some(version) = &self.version {
53 write!(f, "{}:{}", self.name, version)
54 } else {
55 write!(f, "{}:*", self.name)
56 }
57 }
58}
59
60#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
62#[serde(rename_all = "camelCase")]
63pub struct PactPluginManifest {
64 #[serde(skip)]
66 pub plugin_dir: String,
67
68 pub plugin_interface_version: u8,
70
71 pub name: String,
73
74 pub version: String,
76
77 pub executable_type: String,
79
80 pub minimum_required_version: Option<String>,
82
83 pub entry_point: String,
85
86 #[serde(default)]
88 pub entry_points: HashMap<String, String>,
89
90 pub args: Option<Vec<String>>,
92
93 pub dependencies: Option<Vec<PluginDependency>>,
95
96 #[serde(default)]
98 pub plugin_config: HashMap<String, Value>,
99}
100
101impl PactPluginManifest {
102 pub fn as_dependency(&self) -> PluginDependency {
103 PluginDependency {
104 name: self.name.clone(),
105 version: Some(self.version.clone()),
106 dependency_type: PluginDependencyType::Plugin,
107 }
108 }
109}
110
111impl Default for PactPluginManifest {
112 fn default() -> Self {
113 PactPluginManifest {
114 plugin_dir: "".to_string(),
115 plugin_interface_version: 1,
116 name: "".to_string(),
117 version: "".to_string(),
118 executable_type: "".to_string(),
119 minimum_required_version: None,
120 entry_point: "".to_string(),
121 entry_points: Default::default(),
122 args: None,
123 dependencies: None,
124 plugin_config: Default::default(),
125 }
126 }
127}
128
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub enum PluginInterfaceVersion {
131 V1,
132 V2,
133}
134
135#[derive(Clone, Debug, PartialEq, Eq)]
136pub struct PluginInitRequest {
137 pub implementation: String,
138 pub version: String,
139 pub host_capabilities: Vec<String>,
140 pub plugin_instance_id: String,
141}
142
143#[derive(Clone, Debug, PartialEq)]
144pub struct PluginInitResponse {
145 pub catalogue: Vec<CatalogueEntry>,
146 pub plugin_capabilities: Vec<String>,
147}
148
149impl TryFrom<u8> for PluginInterfaceVersion {
150 type Error = anyhow::Error;
151
152 fn try_from(value: u8) -> Result<Self, Self::Error> {
153 match value {
154 1 => Ok(PluginInterfaceVersion::V1),
155 2 => Ok(PluginInterfaceVersion::V2),
156 _ => Err(anyhow!("Unsupported plugin interface version {}", value)),
157 }
158 }
159}
160
161#[async_trait]
163pub trait PactPluginRpc {
164 async fn init_plugin(&mut self, request: PluginInitRequest)
166 -> anyhow::Result<PluginInitResponse>;
167}
168
169#[async_trait]
174pub trait PluginInstance: std::fmt::Debug + Send + Sync {
175 fn manifest(&self) -> &PactPluginManifest;
177
178 fn instance_id(&self) -> &str;
180
181 fn has_capability(&self, capability: &str) -> bool;
183
184 fn kill(&self) {}
187
188 async fn compare_contents(
190 &self,
191 request: CompareContentsRequest,
192 ) -> anyhow::Result<CompareContentsResponse>;
193
194 async fn compare_contents_with_chain(
201 &self,
202 request: CompareContentsRequest,
203 chain_id: &str,
204 deadline_ms: u64,
205 ) -> anyhow::Result<CompareContentsResponse> {
206 let _ = (chain_id, deadline_ms);
207 self.compare_contents(request).await
208 }
209
210 async fn configure_interaction(
212 &self,
213 request: ConfigureInteractionRequest,
214 ) -> anyhow::Result<ConfigureInteractionResponse>;
215
216 async fn generate_content(
218 &self,
219 request: GenerateContentRequest,
220 ) -> anyhow::Result<GenerateContentResponse>;
221
222 async fn generate_content_with_chain(
226 &self,
227 request: GenerateContentRequest,
228 chain_id: &str,
229 deadline_ms: u64,
230 ) -> anyhow::Result<GenerateContentResponse> {
231 let _ = (chain_id, deadline_ms);
232 self.generate_content(request).await
233 }
234
235 async fn start_mock_server(
237 &self,
238 request: StartMockServerRequest,
239 ) -> anyhow::Result<StartMockServerResponse>;
240
241 async fn start_mock_server_v2(
243 &self,
244 request: proto_v2::StartMockServerRequest,
245 ) -> anyhow::Result<StartMockServerResponse> {
246 let _ = request;
247 Err(anyhow!("V2 interface not supported by this plugin"))
248 }
249
250 async fn shutdown_mock_server(
252 &self,
253 request: ShutdownMockServerRequest,
254 ) -> anyhow::Result<ShutdownMockServerResponse>;
255
256 async fn get_mock_server_results(
258 &self,
259 request: MockServerRequest,
260 ) -> anyhow::Result<MockServerResults>;
261
262 async fn prepare_interaction_for_verification(
264 &self,
265 request: VerificationPreparationRequest,
266 ) -> anyhow::Result<VerificationPreparationResponse>;
267
268 async fn prepare_interaction_for_verification_v2(
270 &self,
271 request: proto_v2::VerificationPreparationRequest,
272 ) -> anyhow::Result<VerificationPreparationResponse> {
273 let _ = request;
274 Err(anyhow!("V2 interface not supported by this plugin"))
275 }
276
277 async fn verify_interaction(
279 &self,
280 request: VerifyInteractionRequest,
281 ) -> anyhow::Result<VerifyInteractionResponse>;
282
283 async fn verify_interaction_v2(
285 &self,
286 request: proto_v2::VerifyInteractionRequest,
287 ) -> anyhow::Result<VerifyInteractionResponse> {
288 let _ = request;
289 Err(anyhow!("V2 interface not supported by this plugin"))
290 }
291
292 async fn update_catalogue(&self, request: Catalogue) -> anyhow::Result<()>;
294}
295
296#[derive(Debug, Clone)]
298pub struct PactPlugin {
299 pub manifest: PactPluginManifest,
301
302 pub interface_version: PluginInterfaceVersion,
304
305 #[deprecated(
310 note = "Not all plugin types have a child process; use PluginInstance methods for plugin lifecycle"
311 )]
312 pub child: Arc<ChildPluginProcess>,
313
314 pub plugin_capabilities: Vec<String>,
316
317 pub instance_id: String,
319
320 access_count: Arc<AtomicUsize>,
322}
323
324impl PactPlugin {
325 #[allow(deprecated)]
327 pub fn new(manifest: &PactPluginManifest, child: ChildPluginProcess) -> anyhow::Result<Self> {
328 let instance_id = child.instance_id.clone();
329 Ok(PactPlugin {
330 manifest: manifest.clone(),
331 interface_version: PluginInterfaceVersion::try_from(manifest.plugin_interface_version)?,
332 instance_id,
333 child: Arc::new(child),
334 plugin_capabilities: vec![],
335 access_count: Arc::new(AtomicUsize::new(1)),
336 })
337 }
338
339 pub fn has_plugin_capability(&self, capability: &str) -> bool {
340 self.plugin_capabilities.iter().any(|value| value == capability)
341 }
342
343 pub fn has_capability(&self, capability: &str) -> bool {
345 self.plugin_capabilities.iter().any(|c| c == capability)
346 }
347
348 pub fn instance_id(&self) -> &str {
350 &self.instance_id
351 }
352
353 #[deprecated(note = "Port is specific to gRPC plugins; access it via GrpcPactPlugin")]
357 #[allow(deprecated)]
358 pub fn port(&self) -> u16 {
359 self.child.port()
360 }
361
362 #[deprecated(note = "Use PluginInstance::kill() instead")]
366 #[allow(deprecated)]
367 pub fn kill(&self) {
368 self.child.kill();
369 }
370
371 pub fn update_access(&self) {
373 let count = self.access_count.fetch_add(1, Ordering::SeqCst);
374 trace!(
375 "update_access: Plugin {}/{} access is now {}",
376 self.manifest.name,
377 self.manifest.version,
378 count + 1
379 );
380 }
381
382 pub fn drop_access(&self) -> usize {
384 let check = self
385 .access_count
386 .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |count| {
387 if count > 0 { Some(count - 1) } else { None }
388 });
389 let count = if let Ok(v) = check {
390 if v > 0 { v - 1 } else { v }
391 } else {
392 0
393 };
394 trace!(
395 "drop_access: Plugin {}/{} access is now {}",
396 self.manifest.name, self.manifest.version, count
397 );
398 count
399 }
400}
401
402#[derive(Clone, Debug, PartialEq)]
404pub struct PluginInteractionConfig {
405 pub pact_configuration: HashMap<String, Value>,
407 pub interaction_configuration: HashMap<String, Value>,
409}
410
411#[cfg(test)]
412pub(crate) mod tests {
413 use std::sync::RwLock;
414
415 use async_trait::async_trait;
416
417 use crate::plugin_models::{PactPluginManifest, PluginInitRequest, PluginInitResponse, PluginInstance};
418 use crate::proto::verification_preparation_response::Response;
419 use crate::proto::*;
420
421 pub(crate) struct MockPlugin {
422 pub manifest: PactPluginManifest,
423 pub prepare_request: RwLock<VerificationPreparationRequest>,
424 pub verify_request: RwLock<VerifyInteractionRequest>,
425 }
426
427 impl std::fmt::Debug for MockPlugin {
428 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
429 f.debug_struct("MockPlugin")
430 .field("manifest", &self.manifest)
431 .finish()
432 }
433 }
434
435 impl Default for MockPlugin {
436 fn default() -> Self {
437 MockPlugin {
438 manifest: PactPluginManifest::default(),
439 prepare_request: RwLock::new(VerificationPreparationRequest::default()),
440 verify_request: RwLock::new(VerifyInteractionRequest::default()),
441 }
442 }
443 }
444
445 #[async_trait]
446 impl PluginInstance for MockPlugin {
447 fn manifest(&self) -> &PactPluginManifest {
448 &self.manifest
449 }
450
451 fn instance_id(&self) -> &str {
452 "test-instance"
453 }
454
455 fn has_capability(&self, _capability: &str) -> bool {
456 false
457 }
458
459 async fn compare_contents(
460 &self,
461 _request: CompareContentsRequest,
462 ) -> anyhow::Result<CompareContentsResponse> {
463 unimplemented!()
464 }
465
466 async fn configure_interaction(
467 &self,
468 _request: ConfigureInteractionRequest,
469 ) -> anyhow::Result<ConfigureInteractionResponse> {
470 unimplemented!()
471 }
472
473 async fn generate_content(
474 &self,
475 _request: GenerateContentRequest,
476 ) -> anyhow::Result<GenerateContentResponse> {
477 unimplemented!()
478 }
479
480 async fn start_mock_server(
481 &self,
482 _request: StartMockServerRequest,
483 ) -> anyhow::Result<StartMockServerResponse> {
484 unimplemented!()
485 }
486
487 async fn shutdown_mock_server(
488 &self,
489 _request: ShutdownMockServerRequest,
490 ) -> anyhow::Result<ShutdownMockServerResponse> {
491 unimplemented!()
492 }
493
494 async fn get_mock_server_results(
495 &self,
496 _request: MockServerRequest,
497 ) -> anyhow::Result<MockServerResults> {
498 unimplemented!()
499 }
500
501 async fn prepare_interaction_for_verification(
502 &self,
503 request: VerificationPreparationRequest,
504 ) -> anyhow::Result<VerificationPreparationResponse> {
505 let mut w = self.prepare_request.write().unwrap();
506 *w = request;
507 let data = InteractionData {
508 body: None,
509 metadata: Default::default(),
510 };
511 Ok(VerificationPreparationResponse {
512 response: Some(Response::InteractionData(data)),
513 })
514 }
515
516 async fn verify_interaction(
517 &self,
518 request: VerifyInteractionRequest,
519 ) -> anyhow::Result<VerifyInteractionResponse> {
520 let mut w = self.verify_request.write().unwrap();
521 *w = request;
522 let result = VerificationResult {
523 success: false,
524 response_data: None,
525 mismatches: vec![],
526 output: vec![],
527 };
528 Ok(VerifyInteractionResponse {
529 response: Some(verify_interaction_response::Response::Result(result)),
530 })
531 }
532
533 async fn update_catalogue(&self, _request: Catalogue) -> anyhow::Result<()> {
534 unimplemented!()
535 }
536 }
537
538 pub(crate) struct FailingInitPlugin {
539 pub error: String,
540 }
541
542 #[async_trait]
543 impl crate::plugin_models::PactPluginRpc for FailingInitPlugin {
544 async fn init_plugin(
545 &mut self,
546 _request: PluginInitRequest,
547 ) -> anyhow::Result<PluginInitResponse> {
548 Err(anyhow::anyhow!("{}", self.error))
549 }
550 }
551
552 pub(crate) struct InitRecordingPlugin {
553 pub request: RwLock<Option<PluginInitRequest>>,
554 }
555
556 impl Default for InitRecordingPlugin {
557 fn default() -> Self {
558 Self {
559 request: RwLock::new(None),
560 }
561 }
562 }
563
564 #[async_trait]
565 impl crate::plugin_models::PactPluginRpc for InitRecordingPlugin {
566 async fn init_plugin(
567 &mut self,
568 request: PluginInitRequest,
569 ) -> anyhow::Result<PluginInitResponse> {
570 *self.request.write().unwrap() = Some(request);
571 Ok(PluginInitResponse {
572 catalogue: vec![],
573 plugin_capabilities: vec!["interaction/request-response".to_string()],
574 })
575 }
576 }
577}