summaryrefslogtreecommitdiff
path: root/src/apply.rs
blob: bf8373f74e301e2ab5a7442fe003111fd3844b13 (plain)
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
use std::fmt::Debug;

use anyhow::Result;
use aws_sdk_route53::types::{Change, ChangeAction, ChangeBatch};
// Needed until try_collect is stable, see <https://github.com/rust-lang/rust/issues/94047>
use itertools::Itertools;

use crate::route53::{ResourceRecordSet, Route53};

#[derive(Debug)]
pub struct Transaction<T> {
    pub zone_id: String,
    pub changes: Changes<T>,
}

#[derive(Debug)]
pub struct Changes<T> {
    pub remove: T,
    pub insert: T,
}

pub enum ApplyMode {
    DryRun,
    Apply,
}

impl ApplyMode {
    pub async fn apply<C, R>(&self, aws_context: &C, transaction: Transaction<R>) -> Result<()>
    where
        C: Route53,
        R: IntoIterator<Item = ResourceRecordSet> + Debug,
    {
        match self {
            ApplyMode::DryRun => dry_run(transaction).await,
            ApplyMode::Apply => apply(aws_context, transaction).await,
        }
    }
}

async fn dry_run<R>(transaction: Transaction<R>) -> Result<()>
where
    R: IntoIterator<Item = ResourceRecordSet> + Debug,
{
    println!("ZONE: {}", transaction.zone_id);
    println!("REMOVE: {:#?}", transaction.changes.remove);
    println!("INSERT: {:#?}", transaction.changes.insert);

    Ok(())
}

async fn apply<C, R>(aws_context: &C, transaction: Transaction<R>) -> Result<()>
where
    C: Route53,
    R: IntoIterator<Item = ResourceRecordSet>,
{
    let Changes {
        remove: remove_records,
        insert: insert_records,
    } = transaction.changes;

    let remove_records = remove_records.into_iter().map(|record| {
        Change::builder()
            .action(ChangeAction::Delete) // <--
            .resource_record_set(record.into())
            .build()
    });
    let insert_records = insert_records.into_iter().map(|record| {
        Change::builder()
            .action(ChangeAction::Create) // <--
            .resource_record_set(record.into())
            .build()
    });

    let change_records: Vec<_> = remove_records.chain(insert_records).try_collect()?;
    if !change_records.is_empty() {
        let change_batch = ChangeBatch::builder()
            .set_changes(Some(change_records))
            .build()?;

        aws_context
            .route53()
            .change_resource_record_sets()
            .hosted_zone_id(transaction.zone_id)
            .change_batch(change_batch)
            .send()
            .await?;
    }

    Ok(())
}