1use std::collections::HashMap;
2
3use async_trait::async_trait;
4use pipedash_plugin_api::*;
5use tracing::{
6 debug,
7 info,
8 warn,
9};
10
11use crate::{
12 client,
13 config,
14 mapper,
15 metadata,
16};
17
18const DEFAULT_PAGE_SIZE: usize = 1000;
19
20pub struct ArgocdPlugin {
21 metadata: PluginMetadata,
22 client: Option<client::ArgocdClient>,
23 provider_id: Option<i64>,
24 config: HashMap<String, String>,
25 server_url: Option<String>,
26 status_source: Option<StatusSource>,
27 organizations_filter: Option<Vec<String>>,
28}
29
30impl Default for ArgocdPlugin {
31 fn default() -> Self {
32 Self::new()
33 }
34}
35
36impl ArgocdPlugin {
37 pub fn new() -> Self {
38 Self {
39 metadata: metadata::create_metadata(),
40 client: None,
41 provider_id: None,
42 config: HashMap::new(),
43 server_url: None,
44 status_source: None,
45 organizations_filter: None,
46 }
47 }
48
49 fn client(&self) -> PluginResult<&client::ArgocdClient> {
50 self.client
51 .as_ref()
52 .ok_or_else(|| PluginError::Internal("Plugin not initialized".to_string()))
53 }
54
55 fn get_server_url(&self) -> PluginResult<&str> {
56 self.server_url
57 .as_deref()
58 .ok_or_else(|| PluginError::Internal("Server URL not set".to_string()))
59 }
60}
61
62#[async_trait]
63impl Plugin for ArgocdPlugin {
64 fn metadata(&self) -> &PluginMetadata {
65 &self.metadata
66 }
67
68 fn provider_type(&self) -> &str {
69 "argocd"
70 }
71
72 fn client_options(&self, config: &HashMap<String, String>) -> ClientOptions {
73 ClientOptions {
74 origin: config::get_server_url(config)
75 .ok()
76 .and_then(|url| reqwest::Url::parse(&url).ok()),
77 accept_invalid_certs: config::is_insecure(config),
78 }
79 }
80
81 fn status_source(&self) -> Option<&StatusSource> {
82 self.status_source.as_ref()
83 }
84
85 fn initialize(
86 &mut self, provider_id: i64, config: HashMap<String, String>,
87 http_client: Option<std::sync::Arc<reqwest::Client>>,
88 ) -> PluginResult<()> {
89 info!(provider_id, "Initializing ArgoCD plugin");
90 debug!(config_keys = ?config.keys().collect::<Vec<_>>());
91
92 let server_url = config::get_server_url(&config)?;
93 debug!(server_url, "Configured server URL");
94
95 let token = config::get_token(&config)?;
96 debug!(token_length = token.len(), "Retrieved authentication token");
97
98 let insecure = config::is_insecure(&config);
99 if insecure {
100 warn!("Insecure TLS mode enabled - certificate verification disabled");
101 }
102
103 let organizations_filter = config::parse_organizations_filter(&config);
104 debug!(?organizations_filter, "Organizations filter configured");
105
106 let status_source = custom_status_source(&config)?;
107
108 let http_client = http_client.ok_or_else(|| {
109 PluginError::Internal("ArgoCD plugin requires an HTTP client".to_string())
110 })?;
111 let client = client::ArgocdClient::new(http_client, &server_url, &token);
112 debug!("ArgoCD client created successfully");
113
114 self.client = Some(client);
115 self.provider_id = Some(provider_id);
116 self.server_url = Some(server_url);
117 self.status_source = status_source;
118 self.organizations_filter = organizations_filter;
119 self.config = config;
120
121 info!("ArgoCD plugin initialization complete");
122 Ok(())
123 }
124
125 async fn validate_credentials(&self) -> PluginResult<bool> {
126 debug!("Validating ArgoCD credentials");
127 let client = self.client()?;
128 match client.list_applications(None).await {
129 Ok(apps) => {
130 info!(app_count = apps.len(), "Credentials validated successfully");
131 Ok(true)
132 }
133 Err(e) => {
134 warn!(error = ?e, "Credential validation failed");
135 Err(e)
136 }
137 }
138 }
139
140 async fn fetch_available_pipelines(
141 &self, params: Option<PaginationParams>,
142 ) -> PluginResult<PaginatedResponse<AvailablePipeline>> {
143 debug!("Fetching available pipelines");
144 let client = self.client()?;
145
146 let mut apps = client.list_applications(None).await?;
147 debug!(
148 total_apps = apps.len(),
149 "Retrieved applications from ArgoCD"
150 );
151
152 if let Some(ref orgs_filter) = self.organizations_filter {
153 debug!(?orgs_filter, "Filtering applications by organizations");
154 apps.retain(|app| {
155 let git_org = config::extract_git_org(&app.spec.primary_source().repo_url);
156 orgs_filter.contains(&git_org)
157 });
158 debug!(
159 filtered_apps = apps.len(),
160 "Applications after organization filtering"
161 );
162 }
163
164 let total_count = apps.len();
165 let mut available_pipelines: Vec<AvailablePipeline> =
166 apps.iter().map(mapper::map_available_pipeline).collect();
167
168 let (page, page_size) = if let Some(p) = params {
169 let page_num = if p.page == 0 { 1 } else { p.page };
170 let size = if p.page_size == 0 {
171 DEFAULT_PAGE_SIZE
172 } else {
173 p.page_size
174 };
175
176 let offset = (page_num.saturating_sub(1)) * size;
177
178 available_pipelines = available_pipelines
179 .into_iter()
180 .skip(offset)
181 .take(size)
182 .collect();
183
184 (page_num, size)
185 } else {
186 (1, DEFAULT_PAGE_SIZE)
187 };
188
189 debug!(
190 pipeline_count = available_pipelines.len(),
191 total = total_count,
192 page,
193 page_size,
194 "Mapped and paginated available pipelines"
195 );
196
197 Ok(PaginatedResponse::new(
198 available_pipelines,
199 page,
200 page_size,
201 total_count,
202 ))
203 }
204
205 async fn fetch_organizations(&self) -> PluginResult<Vec<Organization>> {
206 debug!("Fetching Git organizations from applications");
207 let client = self.client()?;
208
209 let apps = client.list_applications(None).await?;
210
211 debug!(
212 app_count = apps.len(),
213 "Extracting organizations from applications"
214 );
215
216 let mut orgs_map: std::collections::HashMap<String, Organization> =
217 std::collections::HashMap::new();
218
219 for app in apps {
220 let git_org = config::extract_git_org(&app.spec.primary_source().repo_url);
221
222 if git_org == "unknown" || git_org.is_empty() {
223 continue;
224 }
225
226 if !orgs_map.contains_key(&git_org) {
227 orgs_map.insert(
228 git_org.clone(),
229 Organization {
230 id: git_org.clone(),
231 name: git_org.clone(),
232 description: Some(format!("Git Organization: {}", git_org)),
233 },
234 );
235 }
236 }
237
238 let organizations: Vec<Organization> = orgs_map.into_values().collect();
239 debug!(
240 org_count = organizations.len(),
241 org_names = ?organizations.iter().map(|o| &o.name).collect::<Vec<_>>(),
242 "Extracted unique Git organizations"
243 );
244
245 Ok(organizations)
246 }
247
248 async fn fetch_available_pipelines_filtered(
249 &self, org: Option<String>, search: Option<String>, params: Option<PaginationParams>,
250 ) -> PluginResult<PaginatedResponse<AvailablePipeline>> {
251 debug!(?org, ?search, "Fetching filtered available pipelines");
252
253 let client = self.client()?;
254
255 let apps = client.list_applications(None).await?;
256
257 debug!(
258 total_apps = apps.len(),
259 "Retrieved applications for filtering"
260 );
261
262 let filtered_apps: Vec<_> = apps
263 .into_iter()
264 .filter(|app| {
265 let org_match = org.as_ref().is_none_or(|o| {
266 let git_org = config::extract_git_org(&app.spec.primary_source().repo_url);
267 git_org == *o
268 });
269
270 let search_match = search.as_ref().is_none_or(|s| {
271 app.metadata.name.to_lowercase().contains(&s.to_lowercase())
272 || app
273 .spec
274 .primary_source()
275 .repo_url
276 .to_lowercase()
277 .contains(&s.to_lowercase())
278 });
279
280 org_match && search_match
281 })
282 .collect();
283
284 debug!(
285 filtered_apps = filtered_apps.len(),
286 "Applications after applying filters"
287 );
288
289 let total_count = filtered_apps.len();
290 let mut available_pipelines: Vec<AvailablePipeline> = filtered_apps
291 .iter()
292 .map(mapper::map_available_pipeline)
293 .collect();
294
295 let (page, page_size) = if let Some(p) = params {
296 let page_num = if p.page == 0 { 1 } else { p.page };
297 let size = if p.page_size == 0 {
298 DEFAULT_PAGE_SIZE
299 } else {
300 p.page_size
301 };
302
303 let offset = (page_num.saturating_sub(1)) * size;
304
305 available_pipelines = available_pipelines
306 .into_iter()
307 .skip(offset)
308 .take(size)
309 .collect();
310
311 (page_num, size)
312 } else {
313 (1, DEFAULT_PAGE_SIZE)
314 };
315
316 debug!(
317 pipeline_count = available_pipelines.len(),
318 total = total_count,
319 page,
320 page_size,
321 "Mapped and paginated filtered pipelines"
322 );
323
324 Ok(PaginatedResponse::new(
325 available_pipelines,
326 page,
327 page_size,
328 total_count,
329 ))
330 }
331
332 async fn fetch_pipelines(&self) -> PluginResult<Vec<Pipeline>> {
333 debug!("Fetching configured pipelines");
334 let provider_id = self
335 .provider_id
336 .ok_or_else(|| PluginError::Internal("Provider ID not set".to_string()))?;
337
338 let client = self.client()?;
339 let server_url = self.get_server_url()?;
340 debug!(server_url, "Using configured server URL");
341
342 let mut apps = client.list_applications(None).await?;
343 debug!(total_apps = apps.len(), "Retrieved all applications");
344
345 if let Some(ref orgs_filter) = self.organizations_filter {
346 debug!(?orgs_filter, "Applying organization filter");
347 apps.retain(|app| {
348 let git_org = config::extract_git_org(&app.spec.primary_source().repo_url);
349 orgs_filter.contains(&git_org)
350 });
351 debug!(
352 filtered_apps = apps.len(),
353 "Applications after organization filter"
354 );
355 }
356
357 let filtered_apps = if let Some(selected_items) = config::parse_selected_items(&self.config)
358 {
359 debug!(
360 selected_count = selected_items.len(),
361 "Applying user selection filter"
362 );
363 apps.into_iter()
364 .filter(|app| selected_items.contains(&app.metadata.name))
365 .collect()
366 } else {
367 debug!("No user selection - returning all applications");
368 apps
369 };
370
371 debug!(
372 final_apps = filtered_apps.len(),
373 "Applications after all filters"
374 );
375
376 let pipelines: Vec<Pipeline> = filtered_apps
377 .iter()
378 .map(|app| mapper::map_application_to_pipeline(app, provider_id, server_url))
379 .collect();
380
381 debug!(
382 pipeline_count = pipelines.len(),
383 "Mapped applications to pipelines"
384 );
385 Ok(pipelines)
386 }
387
388 async fn fetch_run_history(
389 &self, pipeline_id: &str, limit: usize,
390 ) -> PluginResult<Vec<PipelineRun>> {
391 let (provider_id, _namespace, app_name) = config::parse_pipeline_id(pipeline_id)?;
392 let client = self.client()?;
393 let server_url = self.get_server_url()?;
394
395 let app = client.get_application(&app_name).await?;
396
397 let history = app.status.history.as_deref().unwrap_or(&[]);
398
399 let mut runs: Vec<PipelineRun> = history
400 .iter()
401 .rev()
402 .take(limit)
403 .map(|h| mapper::map_history_to_run(h, &app, provider_id, server_url))
404 .collect();
405
406 if let Some(current_run) = mapper::map_operation_to_run(&app, provider_id, server_url) {
407 runs.insert(0, current_run);
408 }
409
410 Ok(runs)
411 }
412
413 async fn fetch_run_details(
414 &self, pipeline_id: &str, run_number: i64,
415 ) -> PluginResult<PipelineRun> {
416 let (provider_id, _namespace, app_name) = config::parse_pipeline_id(pipeline_id)?;
417 let client = self.client()?;
418 let server_url = self.get_server_url()?;
419
420 let app = client.get_application(&app_name).await?;
421
422 if let Some(operation) = mapper::map_operation_to_run(&app, provider_id, server_url) {
423 if operation.run_number == run_number {
424 return Ok(operation);
425 }
426 }
427
428 let history = app.status.history.as_deref().unwrap_or(&[]);
429 let history_item = history
430 .iter()
431 .find(|h| h.deployed_at.timestamp() == run_number)
432 .ok_or_else(|| {
433 PluginError::PipelineNotFound(format!("Run {} not found", run_number))
434 })?;
435
436 Ok(mapper::map_history_to_run(
437 history_item,
438 &app,
439 provider_id,
440 server_url,
441 ))
442 }
443
444 async fn trigger_pipeline(&self, params: TriggerParams) -> PluginResult<String> {
445 let (_provider_id, _namespace, app_name) = config::parse_pipeline_id(¶ms.workflow_id)?;
446 let client = self.client()?;
447
448 let inputs = params.inputs.as_ref();
449
450 let revision = inputs
451 .and_then(|i| i.get("revision"))
452 .and_then(|v| v.as_str())
453 .map(String::from);
454
455 let prune = inputs
456 .and_then(|i| i.get("prune"))
457 .and_then(|v| v.as_bool())
458 .unwrap_or(false);
459
460 let dry_run = inputs
461 .and_then(|i| i.get("dry_run"))
462 .and_then(|v| v.as_bool())
463 .unwrap_or(false);
464
465 let force = inputs
466 .and_then(|i| i.get("force"))
467 .and_then(|v| v.as_bool())
468 .unwrap_or(false);
469
470 let apply_only = inputs
471 .and_then(|i| i.get("apply_only"))
472 .and_then(|v| v.as_bool())
473 .unwrap_or(false);
474
475 info!(
476 app_name,
477 ?revision,
478 prune,
479 dry_run,
480 force,
481 apply_only,
482 "Triggering ArgoCD sync operation"
483 );
484
485 client
486 .sync_application(&app_name, revision, prune, dry_run, force, apply_only)
487 .await?;
488
489 let sync_type = if dry_run { "Dry run" } else { "Sync" };
490 Ok(format!(
491 "{} triggered for application: {}",
492 sync_type, app_name
493 ))
494 }
495
496 async fn cancel_run(&self, pipeline_id: &str, _run_number: i64) -> PluginResult<()> {
497 let (_provider_id, _namespace, app_name) = config::parse_pipeline_id(pipeline_id)?;
498 let client = self.client()?;
499
500 client.terminate_operation(&app_name).await?;
501
502 Ok(())
503 }
504
505 async fn fetch_workflow_parameters(
506 &self, _workflow_id: &str,
507 ) -> PluginResult<Vec<WorkflowParameter>> {
508 Ok(vec![
509 WorkflowParameter {
510 name: "revision".to_string(),
511 label: Some("Revision".to_string()),
512 description: Some("Git revision (branch, tag, or commit SHA) to sync to. Leave empty to use target revision.".to_string()),
513 param_type: WorkflowParameterType::String { default: None },
514 required: false,
515 },
516 WorkflowParameter {
517 name: "prune".to_string(),
518 label: Some("Prune Resources".to_string()),
519 description: Some("Delete resources that are no longer defined in Git".to_string()),
520 param_type: WorkflowParameterType::Boolean { default: false },
521 required: false,
522 },
523 WorkflowParameter {
524 name: "dry_run".to_string(),
525 label: Some("Dry Run".to_string()),
526 description: Some("Preview sync without applying changes".to_string()),
527 param_type: WorkflowParameterType::Boolean { default: false },
528 required: false,
529 },
530 WorkflowParameter {
531 name: "force".to_string(),
532 label: Some("Force Sync".to_string(),),
533 description: Some("Force sync even if resources are already synced (overrides any state)".to_string()),
534 param_type: WorkflowParameterType::Boolean { default: false },
535 required: false,
536 },
537 WorkflowParameter {
538 name: "apply_only".to_string(),
539 label: Some("Apply Only (Skip Hooks)".to_string()),
540 description: Some("Skip pre and post sync hooks".to_string()),
541 param_type: WorkflowParameterType::Boolean { default: false },
542 required: false,
543 },
544 ])
545 }
546
547 async fn fetch_agents(&self) -> PluginResult<Vec<BuildAgent>> {
548 Ok(vec![])
549 }
550
551 async fn fetch_artifacts(&self, _run_id: &str) -> PluginResult<Vec<BuildArtifact>> {
552 Ok(vec![])
553 }
554
555 async fn fetch_queues(&self) -> PluginResult<Vec<BuildQueue>> {
556 Ok(vec![])
557 }
558
559 fn get_migrations(&self) -> Vec<String> {
560 vec![]
561 }
562
563 async fn get_field_options(
564 &self, field_key: &str, _config: &HashMap<String, String>,
565 ) -> PluginResult<Vec<String>> {
566 if field_key == "organizations" {
567 let apps = self.client()?.list_applications(None).await?;
568
569 let mut git_orgs = std::collections::HashSet::new();
570 for app in apps {
571 let git_org = config::extract_git_org(&app.spec.primary_source().repo_url);
572 if git_org != "unknown" && !git_org.is_empty() {
573 git_orgs.insert(git_org);
574 }
575 }
576
577 let mut orgs: Vec<String> = git_orgs.into_iter().collect();
578 orgs.sort();
579
580 debug!(
581 org_count = orgs.len(),
582 "Returning Git organizations for dropdown"
583 );
584 Ok(orgs)
585 } else {
586 Ok(vec![])
587 }
588 }
589}
590
591#[cfg(test)]
592mod tests {
593 use super::*;
594
595 fn cfg(pairs: &[(&str, &str)]) -> HashMap<String, String> {
596 pairs
597 .iter()
598 .map(|(k, v)| (k.to_string(), v.to_string()))
599 .collect()
600 }
601
602 #[test]
603 fn client_options_parse_origin_and_insecure() {
604 let plugin = ArgocdPlugin::new();
605 let options = plugin.client_options(&cfg(&[
606 ("server_url", " https://Argo.example.com:8443/ "),
607 ("insecure", "true"),
608 ]));
609 assert_eq!(
610 options.origin.as_ref().map(|u| u.as_str()),
611 Some("https://argo.example.com:8443/")
612 );
613 assert!(options.accept_invalid_certs);
614 }
615
616 #[test]
617 fn client_options_default_secure_for_missing_or_bad_values() {
618 let plugin = ArgocdPlugin::new();
619 for insecure in ["false", "yes", ""] {
620 let options = plugin.client_options(&cfg(&[
621 ("server_url", "https://argo.example.com"),
622 ("insecure", insecure),
623 ]));
624 assert!(!options.accept_invalid_certs);
625 }
626 assert!(
627 !plugin
628 .client_options(&cfg(&[("server_url", "https://a.io")]))
629 .accept_invalid_certs
630 );
631 }
632
633 #[test]
634 fn client_options_origin_none_when_missing_or_invalid() {
635 let plugin = ArgocdPlugin::new();
636 assert_eq!(plugin.client_options(&cfg(&[])).origin, None);
637 assert_eq!(
638 plugin
639 .client_options(&cfg(&[("server_url", "not a url")]))
640 .origin,
641 None
642 );
643 }
644
645 #[test]
646 fn initialize_requires_client_and_validates_status_page() {
647 let base = [("server_url", "https://a.io"), ("token", "t")];
648 let mut plugin = ArgocdPlugin::new();
649
650 assert!(matches!(
651 plugin.initialize(1, cfg(&base), None),
652 Err(PluginError::Internal(_))
653 ));
654
655 let mut bad = base.to_vec();
656 bad.push(("status_page_url", "http://example.com"));
657 assert!(matches!(
658 plugin.initialize(1, cfg(&bad), None),
659 Err(PluginError::InvalidConfig(_))
660 ));
661 assert!(plugin.status_source().is_none());
662 }
663}