-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhandler.rs
More file actions
895 lines (777 loc) · 30.5 KB
/
handler.rs
File metadata and controls
895 lines (777 loc) · 30.5 KB
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
//! Release command handler implementation
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tracing::{error, info, instrument};
use super::errors::ReleaseCommandHandlerError;
use crate::adapters::ansible::AnsibleClient;
use crate::application::command_handlers::common::StepResult;
use crate::application::steps::{
application::{
CreatePrometheusStorageStep, CreateTrackerStorageStep, DeployCaddyConfigStep,
DeployGrafanaProvisioningStep, DeployPrometheusConfigStep, DeployTrackerConfigStep,
InitTrackerDatabaseStep,
},
rendering::{
RenderCaddyTemplatesStep, RenderGrafanaTemplatesStep, RenderPrometheusTemplatesStep,
RenderTrackerTemplatesStep,
},
DeployComposeFilesStep, RenderDockerComposeTemplatesStep,
};
use crate::domain::environment::repository::{EnvironmentRepository, TypedEnvironmentRepository};
use crate::domain::environment::state::{ReleaseFailureContext, ReleaseStep};
use crate::domain::environment::{Configured, Environment, Released, Releasing};
use crate::domain::template::TemplateManager;
use crate::domain::EnvironmentName;
use crate::shared::error::Traceable;
/// `ReleaseCommandHandler` orchestrates the software release workflow
///
/// The `ReleaseCommandHandler` orchestrates the software release workflow to
/// deploy software to a configured environment.
///
/// This command handler handles all steps required to release software:
/// 1. Load the environment from storage
/// 2. Validate the environment is in the correct state
/// 3. Render Docker Compose templates to the build directory
/// 4. Deploy compose files to the remote host via Ansible
/// 5. Transition environment to `Released` state
///
/// # Architecture
///
/// Follows the three-level architecture:
/// - **Command** (Level 1): This handler orchestrates the release workflow
/// - **Step** (Level 2): `RenderDockerComposeTemplatesStep`, `DeployComposeFilesStep`
/// - **Remote Action** (Level 3): Ansible playbook executes on remote host
///
/// # State Management
///
/// The command handler integrates with the type-state pattern for environment lifecycle:
/// - Accepts environment in `Configured` state
/// - Transitions to `Environment<Releasing>` at start
/// - Returns `Environment<Released>` on success
/// - Transitions to `Environment<ReleaseFailed>` on error
///
/// State is persisted after each transition using the injected repository.
pub struct ReleaseCommandHandler {
clock: Arc<dyn crate::shared::Clock>,
repository: TypedEnvironmentRepository,
}
impl ReleaseCommandHandler {
/// Create a new `ReleaseCommandHandler`
#[must_use]
pub fn new(
repository: Arc<dyn EnvironmentRepository>,
clock: Arc<dyn crate::shared::Clock>,
) -> Self {
Self {
clock,
repository: TypedEnvironmentRepository::new(repository),
}
}
/// Execute the release workflow
///
/// # Arguments
///
/// * `env_name` - The name of the environment to release to
///
/// # Returns
///
/// Returns `Ok(Environment<Released>)` on success
///
/// # Errors
///
/// Returns an error if:
/// * Environment not found
/// * Environment is not in `Configured` state
/// * Docker Compose template rendering fails
/// * File deployment to VM fails
/// * State persistence fails
#[instrument(
name = "release_command",
skip_all,
fields(
command_type = "release",
environment = %env_name
)
)]
pub async fn execute(
&self,
env_name: &EnvironmentName,
) -> Result<Environment<Released>, ReleaseCommandHandlerError> {
let environment = self.load_configured_environment(env_name)?;
let instance_ip = environment.instance_ip().ok_or_else(|| {
ReleaseCommandHandlerError::MissingInstanceIp {
name: env_name.to_string(),
}
})?;
let started_at = self.clock.now();
info!(
command = "release",
environment = %env_name,
instance_ip = %instance_ip,
current_state = "configured",
target_state = "releasing",
"Environment loaded and validated. Transitioning to Releasing state."
);
let releasing_env = environment.start_releasing();
self.repository.save_releasing(&releasing_env)?;
info!(
command = "release",
environment = %env_name,
current_state = "releasing",
"Releasing state persisted. Executing release steps."
);
match self
.execute_release_workflow(&releasing_env, instance_ip)
.await
{
Ok(released) => {
info!(
command = "release",
environment = %released.name(),
final_state = "released",
"Software release completed successfully"
);
self.repository.save_released(&released)?;
Ok(released)
}
Err((e, current_step)) => {
error!(
command = "release",
environment = %releasing_env.name(),
error = %e,
step = ?current_step,
"Software release failed"
);
let context =
self.build_failure_context(&releasing_env, &e, current_step, started_at);
let failed = releasing_env.release_failed(context);
self.repository.save_release_failed(&failed)?;
Err(e)
}
}
}
/// Execute the release workflow with step tracking
///
/// This method orchestrates the complete release workflow:
/// 1. Create tracker storage directories
/// 2. Initialize tracker `SQLite` database
/// 3. Render Docker Compose templates to the build directory
/// 4. Deploy compose files to the remote host via Ansible
///
/// If an error occurs, it returns both the error and the step that was being
/// executed, enabling accurate failure context generation.
///
/// # Arguments
///
/// * `environment` - The environment in Releasing state
/// * `instance_ip` - The validated instance IP address (precondition checked by caller)
///
/// # Errors
///
/// Returns a tuple of (error, `current_step`) if any release step fails
async fn execute_release_workflow(
&self,
environment: &Environment<Releasing>,
instance_ip: IpAddr,
) -> StepResult<Environment<Released>, ReleaseCommandHandlerError, ReleaseStep> {
// Step 1: Create tracker storage directories
Self::create_tracker_storage(environment, instance_ip)?;
// Step 2: Initialize tracker database
Self::init_tracker_database(environment, instance_ip)?;
// Step 3: Render tracker configuration templates
let tracker_build_dir = Self::render_tracker_templates(environment)?;
// Step 4: Deploy tracker configuration to remote
self.deploy_tracker_config_to_remote(environment, &tracker_build_dir, instance_ip)?;
// Step 5: Create Prometheus storage directories (if enabled)
Self::create_prometheus_storage(environment, instance_ip)?;
// Step 6: Render Prometheus configuration templates (if enabled)
Self::render_prometheus_templates(environment)?;
// Step 7: Deploy Prometheus configuration to remote (if enabled)
self.deploy_prometheus_config_to_remote(environment, instance_ip)?;
// Step 8: Render Grafana provisioning templates (if enabled)
Self::render_grafana_templates(environment)?;
// Step 9: Deploy Grafana provisioning to remote (if enabled)
self.deploy_grafana_provisioning_to_remote(environment, instance_ip)?;
// Step 10: Render Caddy configuration templates (if HTTPS enabled)
Self::render_caddy_templates(environment)?;
// Step 11: Deploy Caddy configuration to remote (if HTTPS enabled)
self.deploy_caddy_config_to_remote(environment, instance_ip)?;
// Step 12: Render Docker Compose templates
let compose_build_dir = self.render_docker_compose_templates(environment).await?;
// Step 13: Deploy compose files to remote
self.deploy_compose_files_to_remote(environment, &compose_build_dir, instance_ip)?;
let released = environment.clone().released();
Ok(released)
}
/// Create tracker storage directories on the remote host
///
/// # Errors
///
/// Returns a tuple of (error, `ReleaseStep::CreateTrackerStorage`) if creation fails
#[allow(clippy::result_large_err)]
fn create_tracker_storage(
environment: &Environment<Releasing>,
_instance_ip: IpAddr,
) -> StepResult<(), ReleaseCommandHandlerError, ReleaseStep> {
let current_step = ReleaseStep::CreateTrackerStorage;
let ansible_client = Arc::new(AnsibleClient::new(environment.build_dir().join("ansible")));
CreateTrackerStorageStep::new(ansible_client)
.execute()
.map_err(|e| {
(
ReleaseCommandHandlerError::TrackerStorageCreation(e.to_string()),
current_step,
)
})?;
info!(
command = "release",
step = %current_step,
"Tracker storage directories created successfully"
);
Ok(())
}
/// Initialize tracker database on the remote host
///
/// # Errors
///
/// Returns a tuple of (error, `ReleaseStep::InitTrackerDatabase`) if initialization fails
#[allow(clippy::result_large_err)]
fn init_tracker_database(
environment: &Environment<Releasing>,
_instance_ip: IpAddr,
) -> StepResult<(), ReleaseCommandHandlerError, ReleaseStep> {
let current_step = ReleaseStep::InitTrackerDatabase;
let ansible_client = Arc::new(AnsibleClient::new(environment.build_dir().join("ansible")));
InitTrackerDatabaseStep::new(ansible_client)
.execute()
.map_err(|e| {
(
ReleaseCommandHandlerError::TrackerDatabaseInit(e.to_string()),
current_step,
)
})?;
info!(
command = "release",
step = %current_step,
"Tracker database initialized successfully"
);
Ok(())
}
/// Render Tracker configuration templates to the build directory
///
/// # Errors
///
/// Returns a tuple of (error, `ReleaseStep::RenderTrackerTemplates`) if rendering fails
#[allow(clippy::result_large_err)]
fn render_tracker_templates(
environment: &Environment<Releasing>,
) -> StepResult<PathBuf, ReleaseCommandHandlerError, ReleaseStep> {
let current_step = ReleaseStep::RenderTrackerTemplates;
let template_manager = Arc::new(TemplateManager::new(environment.templates_dir()));
let step = RenderTrackerTemplatesStep::new(
Arc::new(environment.clone()),
template_manager,
environment.build_dir().clone(),
);
let tracker_build_dir = step.execute().map_err(|e| {
(
ReleaseCommandHandlerError::TemplateRendering(e.to_string()),
current_step,
)
})?;
info!(
command = "release",
tracker_build_dir = %tracker_build_dir.display(),
"Tracker configuration templates rendered successfully"
);
Ok(tracker_build_dir)
}
/// Render Prometheus configuration templates to the build directory (if enabled)
///
/// This step is optional and only executes if Prometheus is configured in the environment.
/// If Prometheus is not configured, the step is skipped without error.
///
/// # Errors
///
/// Returns a tuple of (error, `ReleaseStep::RenderPrometheusTemplates`) if rendering fails
#[allow(clippy::result_large_err)]
fn render_prometheus_templates(
environment: &Environment<Releasing>,
) -> StepResult<(), ReleaseCommandHandlerError, ReleaseStep> {
let current_step = ReleaseStep::RenderPrometheusTemplates;
// Check if Prometheus is configured
if environment.context().user_inputs.prometheus.is_none() {
info!(
command = "release",
step = %current_step,
status = "skipped",
"Prometheus not configured - skipping template rendering"
);
return Ok(());
}
let template_manager = Arc::new(TemplateManager::new(environment.templates_dir()));
let step = RenderPrometheusTemplatesStep::new(
Arc::new(environment.clone()),
template_manager,
environment.build_dir().clone(),
);
step.execute().map_err(|e| {
(
ReleaseCommandHandlerError::TemplateRendering(e.to_string()),
current_step,
)
})?;
info!(
command = "release",
step = %current_step,
"Prometheus configuration templates rendered successfully"
);
Ok(())
}
/// Create Prometheus storage directories on the remote host (if enabled)
///
/// This step is optional and only executes if Prometheus is configured in the environment.
/// If Prometheus is not configured, the step is skipped without error.
///
/// # Errors
///
/// Returns a tuple of (error, `ReleaseStep::CreatePrometheusStorage`) if creation fails
#[allow(clippy::result_large_err)]
fn create_prometheus_storage(
environment: &Environment<Releasing>,
_instance_ip: IpAddr,
) -> StepResult<(), ReleaseCommandHandlerError, ReleaseStep> {
let current_step = ReleaseStep::CreatePrometheusStorage;
// Check if Prometheus is configured
if environment.context().user_inputs.prometheus.is_none() {
info!(
command = "release",
step = %current_step,
status = "skipped",
"Prometheus not configured - skipping storage creation"
);
return Ok(());
}
let ansible_client = Arc::new(AnsibleClient::new(environment.build_dir().join("ansible")));
CreatePrometheusStorageStep::new(ansible_client)
.execute()
.map_err(|e| {
(
ReleaseCommandHandlerError::PrometheusStorageCreation(e.to_string()),
current_step,
)
})?;
info!(
command = "release",
step = %current_step,
"Prometheus storage directories created successfully"
);
Ok(())
}
/// Deploy Prometheus configuration to the remote host via Ansible (if enabled)
///
/// This step is optional and only executes if Prometheus is configured in the environment.
/// If Prometheus is not configured, the step is skipped without error.
///
/// # Arguments
///
/// * `environment` - The environment in Releasing state
/// * `instance_ip` - The target instance IP address
///
/// # Errors
///
/// Returns a tuple of (error, `ReleaseStep::DeployPrometheusConfigToRemote`) if deployment fails
#[allow(clippy::result_large_err, clippy::unused_self)]
fn deploy_prometheus_config_to_remote(
&self,
environment: &Environment<Releasing>,
_instance_ip: IpAddr,
) -> StepResult<(), ReleaseCommandHandlerError, ReleaseStep> {
let current_step = ReleaseStep::DeployPrometheusConfigToRemote;
// Check if Prometheus is configured
if environment.context().user_inputs.prometheus.is_none() {
info!(
command = "release",
step = %current_step,
status = "skipped",
"Prometheus not configured - skipping config deployment"
);
return Ok(());
}
let ansible_client = Arc::new(AnsibleClient::new(environment.build_dir().join("ansible")));
DeployPrometheusConfigStep::new(ansible_client)
.execute()
.map_err(|e| {
(
ReleaseCommandHandlerError::TemplateRendering(e.to_string()),
current_step,
)
})?;
info!(
command = "release",
step = %current_step,
"Prometheus configuration deployed successfully"
);
Ok(())
}
/// Render Grafana provisioning templates (if enabled)
///
/// This step is optional and only executes if Grafana is configured in the environment.
/// If Grafana is not configured, the step is skipped without error.
///
/// # Errors
///
/// Returns a tuple of (error, `ReleaseStep::RenderGrafanaTemplates`) if rendering fails
#[allow(clippy::result_large_err)]
fn render_grafana_templates(
environment: &Environment<Releasing>,
) -> StepResult<(), ReleaseCommandHandlerError, ReleaseStep> {
let current_step = ReleaseStep::RenderGrafanaTemplates;
// Check if Grafana is configured
if environment.context().user_inputs.grafana.is_none() {
info!(
command = "release",
step = %current_step,
status = "skipped",
"Grafana not configured - skipping provisioning template rendering"
);
return Ok(());
}
// Check if Prometheus is configured (required for datasource)
if environment.context().user_inputs.prometheus.is_none() {
info!(
command = "release",
step = %current_step,
status = "skipped",
"Prometheus not configured - skipping Grafana provisioning (datasource requires Prometheus)"
);
return Ok(());
}
let template_manager = Arc::new(TemplateManager::new(environment.templates_dir()));
let step = RenderGrafanaTemplatesStep::new(
Arc::new(environment.clone()),
template_manager,
environment.build_dir().clone(),
);
step.execute().map_err(|e| {
(
ReleaseCommandHandlerError::TemplateRendering(e.to_string()),
current_step,
)
})?;
info!(
command = "release",
step = %current_step,
"Grafana provisioning templates rendered successfully"
);
Ok(())
}
/// Render Caddy configuration templates (if HTTPS enabled)
///
/// This step is optional and only executes if HTTPS is configured in the environment.
/// If HTTPS is not configured, the step is skipped without error.
///
/// # Errors
///
/// Returns a tuple of (error, `ReleaseStep::RenderCaddyTemplates`) if rendering fails
#[allow(clippy::result_large_err)]
fn render_caddy_templates(
environment: &Environment<Releasing>,
) -> StepResult<(), ReleaseCommandHandlerError, ReleaseStep> {
let current_step = ReleaseStep::RenderCaddyTemplates;
// Check if HTTPS is configured
if environment.context().user_inputs.https.is_none() {
info!(
command = "release",
step = %current_step,
status = "skipped",
"HTTPS not configured - skipping Caddy template rendering"
);
return Ok(());
}
let template_manager = Arc::new(TemplateManager::new(environment.templates_dir()));
let step = RenderCaddyTemplatesStep::new(
Arc::new(environment.clone()),
template_manager,
environment.build_dir().clone(),
);
step.execute().map_err(|e| {
(
ReleaseCommandHandlerError::TemplateRendering(e.to_string()),
current_step,
)
})?;
info!(
command = "release",
step = %current_step,
"Caddy configuration templates rendered successfully"
);
Ok(())
}
/// Deploy Caddy configuration to the remote host (if HTTPS enabled)
///
/// This step is optional and only executes if HTTPS is configured in the environment.
/// If HTTPS is not configured, the step is skipped without error.
///
/// # Errors
///
/// Returns a tuple of (error, `ReleaseStep::DeployCaddyConfigToRemote`) if deployment fails
#[allow(clippy::result_large_err, clippy::unused_self)]
fn deploy_caddy_config_to_remote(
&self,
environment: &Environment<Releasing>,
_instance_ip: IpAddr,
) -> StepResult<(), ReleaseCommandHandlerError, ReleaseStep> {
let current_step = ReleaseStep::DeployCaddyConfigToRemote;
// Check if HTTPS is configured
if environment.context().user_inputs.https.is_none() {
info!(
command = "release",
step = %current_step,
status = "skipped",
"HTTPS not configured - skipping Caddy config deployment"
);
return Ok(());
}
let ansible_client = Arc::new(AnsibleClient::new(environment.build_dir().join("ansible")));
DeployCaddyConfigStep::new(ansible_client)
.execute()
.map_err(|e| {
(
ReleaseCommandHandlerError::CaddyConfigDeployment(e.to_string()),
current_step,
)
})?;
info!(
command = "release",
step = %current_step,
"Caddy configuration deployed to remote successfully"
);
Ok(())
}
/// Deploy Grafana provisioning configuration to the remote host (if enabled)
///
/// This step is optional and only executes if Grafana is configured in the environment.
/// If Grafana is not configured, the step is skipped without error.
///
/// # Errors
///
/// Returns a tuple of (error, `ReleaseStep::DeployGrafanaProvisioning`) if deployment fails
#[allow(clippy::result_large_err, clippy::unused_self)]
fn deploy_grafana_provisioning_to_remote(
&self,
environment: &Environment<Releasing>,
_instance_ip: IpAddr,
) -> StepResult<(), ReleaseCommandHandlerError, ReleaseStep> {
let current_step = ReleaseStep::DeployGrafanaProvisioning;
// Check if Grafana is configured
if environment.context().user_inputs.grafana.is_none() {
info!(
command = "release",
step = %current_step,
status = "skipped",
"Grafana not configured - skipping provisioning deployment"
);
return Ok(());
}
// Check if Prometheus is configured (required for datasource)
if environment.context().user_inputs.prometheus.is_none() {
info!(
command = "release",
step = %current_step,
status = "skipped",
"Prometheus not configured - skipping Grafana provisioning deployment"
);
return Ok(());
}
let ansible_client = Arc::new(AnsibleClient::new(environment.build_dir().join("ansible")));
DeployGrafanaProvisioningStep::new(ansible_client)
.execute()
.map_err(|e| {
(
ReleaseCommandHandlerError::TemplateRendering(e.to_string()),
current_step,
)
})?;
info!(
command = "release",
step = %current_step,
"Grafana provisioning configuration deployed successfully"
);
Ok(())
}
/// Deploy tracker configuration to the remote host via Ansible
///
/// # Arguments
///
/// * `environment` - The environment in Releasing state
/// * `tracker_build_dir` - Path to the rendered tracker configuration
/// * `instance_ip` - The target instance IP address
///
/// # Errors
///
/// Returns a tuple of (error, `ReleaseStep::DeployTrackerConfigToRemote`) if deployment fails
#[allow(clippy::result_large_err, clippy::unused_self)]
fn deploy_tracker_config_to_remote(
&self,
environment: &Environment<Releasing>,
tracker_build_dir: &Path,
_instance_ip: IpAddr,
) -> StepResult<(), ReleaseCommandHandlerError, ReleaseStep> {
let current_step = ReleaseStep::DeployTrackerConfigToRemote;
let ansible_client = Arc::new(AnsibleClient::new(environment.build_dir().join("ansible")));
DeployTrackerConfigStep::new(ansible_client, tracker_build_dir.to_path_buf())
.execute()
.map_err(|e| {
(
ReleaseCommandHandlerError::Deployment {
message: e.to_string(),
source: Box::new(e),
},
current_step,
)
})?;
info!(
command = "release",
step = %current_step,
"Tracker configuration deployed successfully"
);
Ok(())
}
/// Render Docker Compose templates to the build directory
///
/// # Errors
///
/// Returns a tuple of (error, `ReleaseStep::RenderDockerComposeTemplates`) if rendering fails
async fn render_docker_compose_templates(
&self,
environment: &Environment<Releasing>,
) -> StepResult<PathBuf, ReleaseCommandHandlerError, ReleaseStep> {
let current_step = ReleaseStep::RenderDockerComposeTemplates;
let template_manager = Arc::new(TemplateManager::new(environment.templates_dir()));
let step = RenderDockerComposeTemplatesStep::new(
Arc::new(environment.clone()),
template_manager,
environment.build_dir().clone(),
);
let compose_build_dir = step.execute().await.map_err(|e| {
(
ReleaseCommandHandlerError::TemplateRendering(e.to_string()),
current_step,
)
})?;
info!(
command = "release",
compose_build_dir = %compose_build_dir.display(),
"Docker Compose templates rendered successfully"
);
Ok(compose_build_dir)
}
/// Deploy compose files to the remote host via Ansible
///
/// # Arguments
///
/// * `environment` - The environment in Releasing state
/// * `compose_build_dir` - Path to the rendered compose files
/// * `instance_ip` - The target instance IP address
///
/// # Errors
///
/// Returns a tuple of (error, `ReleaseStep::DeployComposeFilesToRemote`) if deployment fails
#[allow(clippy::result_large_err, clippy::unused_self)]
fn deploy_compose_files_to_remote(
&self,
environment: &Environment<Releasing>,
compose_build_dir: &Path,
instance_ip: IpAddr,
) -> StepResult<(), ReleaseCommandHandlerError, ReleaseStep> {
let current_step = ReleaseStep::DeployComposeFilesToRemote;
let ansible_client = Arc::new(AnsibleClient::new(environment.ansible_build_dir()));
let step = DeployComposeFilesStep::new(ansible_client, compose_build_dir.to_path_buf());
step.execute().map_err(|e| {
(
ReleaseCommandHandlerError::DeploymentFailed {
message: e.to_string(),
source: e,
},
current_step,
)
})?;
info!(
command = "release",
compose_build_dir = %compose_build_dir.display(),
instance_ip = %instance_ip,
"Compose files deployed to remote host successfully"
);
Ok(())
}
/// Build failure context for a release error and generate trace file
///
/// This helper method builds structured error context including the failed step,
/// error classification, timing information, and generates a trace file for
/// post-mortem analysis.
///
/// # Arguments
///
/// * `environment` - The environment being released (for trace directory path)
/// * `error` - The release error that occurred
/// * `current_step` - The step that was executing when the error occurred
/// * `started_at` - The timestamp when release execution started
///
/// # Returns
///
/// A `ReleaseFailureContext` with all failure metadata and trace file path
fn build_failure_context(
&self,
environment: &Environment<Releasing>,
error: &ReleaseCommandHandlerError,
current_step: ReleaseStep,
started_at: chrono::DateTime<chrono::Utc>,
) -> ReleaseFailureContext {
use crate::application::command_handlers::common::failure_context::build_base_failure_context;
use crate::infrastructure::trace::ReleaseTraceWriter;
// Step that failed is directly provided - no reverse engineering needed
let failed_step = current_step;
// Get error kind from the error itself (errors are self-describing)
let error_kind = error.error_kind();
// Build base failure context using common helper
let base = build_base_failure_context(&self.clock, started_at, error.to_string());
// Build handler-specific context
let mut context = ReleaseFailureContext {
failed_step,
error_kind,
base,
};
// Generate trace file (logging handled by trace writer)
let traces_dir = environment.traces_dir();
let writer = ReleaseTraceWriter::new(traces_dir, Arc::clone(&self.clock));
if let Ok(trace_file) = writer.write_trace(&context, error) {
context.base.trace_file_path = Some(trace_file);
}
context
}
/// Load environment from storage and validate it is in `Configured` state
///
/// # Errors
///
/// Returns an error if:
/// * Persistence error occurs during load
/// * Environment does not exist
/// * Environment is not in `Configured` state
#[allow(clippy::result_large_err)]
fn load_configured_environment(
&self,
env_name: &EnvironmentName,
) -> Result<Environment<Configured>, ReleaseCommandHandlerError> {
let any_env = self
.repository
.inner()
.load(env_name)
.map_err(ReleaseCommandHandlerError::StatePersistence)?;
let any_env = any_env.ok_or_else(|| ReleaseCommandHandlerError::EnvironmentNotFound {
name: env_name.to_string(),
})?;
Ok(any_env.try_into_configured()?)
}
}