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
use crate::bundle::{
  poller::{BundlePoller, Error, PollResult, Result},
  Bundle,
};

use async_trait::async_trait;
use rusoto_core::RusotoError;
use rusoto_s3::{
  GetObjectError, GetObjectRequest, HeadObjectError, HeadObjectRequest, S3Client, S3,
};
use snafu::{ResultExt, Snafu};
use std::path::PathBuf;
use tokio_tar::Archive;

#[derive(Snafu, Debug)]
pub enum InternalError {
  S3HeadObjectError {
    source: RusotoError<HeadObjectError>,
  },
  S3GetObjectError {
    source: RusotoError<GetObjectError>,
  },
  S3MissingBody,
  S3MissingETag,
}

impl From<InternalError> for Error {
  fn from(err: InternalError) -> Self {
    Error::InternalPollerError {
      source: Box::new(err),
    }
  }
}

pub struct S3BundlePoller {
  client: S3Client,
  bucket: String,
  object_name: String,
}

impl S3BundlePoller {
  pub fn new(
    access_key: String,
    secret_key: String,
    endpoint: String,
    bucket: String,
    region: String,
    object_name: String,
  ) -> S3BundlePoller {
    let region = rusoto_core::Region::Custom {
      name: region,
      endpoint,
    };
    let credentials = rusoto_credential::StaticProvider::new_minimal(access_key, secret_key);
    let dispatcher = rusoto_core::HttpClient::new().unwrap();
    let client = S3Client::new_with(dispatcher, credentials, region);

    S3BundlePoller {
      client,
      bucket,
      object_name,
    }
  }
}

#[async_trait]
impl BundlePoller for S3BundlePoller {
  async fn poll(&self, active_bundle: &Option<Bundle>) -> Result<PollResult> {
    if let Some(active_bundle) = active_bundle {
      if active_bundle.etag.is_some() {
        let head_request = HeadObjectRequest {
          bucket: self.bucket.clone(),
          key: self.object_name.clone(),
          ..Default::default()
        };

        let head_response = self
          .client
          .head_object(head_request)
          .await
          .context(S3HeadObjectError)?;

        if head_response.e_tag == active_bundle.etag {
          log::info!(
            "S3BundlePoller: No updates found for object: {}",
            self.object_name
          );

          // Skip update download
          return Ok(PollResult::Skip);
        } else {
          log::info!(
            "S3BundlePoller: Object {} has changed. Starting bundle update.",
            self.object_name
          );
        }
      } else {
        log::error!("S3BundlePoller: Expected the active bundle to have a valid ETag.");

        return Err(Error::MissingBundleID);
      }
    }

    // Head object
    let head_request = HeadObjectRequest {
      bucket: self.bucket.clone(),
      key: self.object_name.clone(),
      ..Default::default()
    };

    let head_response = self
      .client
      .head_object(head_request)
      .await
      .context(S3HeadObjectError)?;

    Ok(PollResult::UpdateReady {
      etag: head_response.e_tag.ok_or(InternalError::S3MissingETag)?,
    })
  }

  async fn retrieve(&self, bundle_id: &str, path: PathBuf) -> Result<()> {
    log::info!("S3BundlePoller: Starting bundle download...");

    let get_object_request = GetObjectRequest {
      bucket: self.bucket.clone(),
      key: self.object_name.clone(),
      ..Default::default()
    };

    let get_object_response = self
      .client
      .get_object(get_object_request)
      .await
      .context(S3GetObjectError)?;

    let current_bundle_id = get_object_response
      .e_tag
      .ok_or(InternalError::S3MissingETag)?;

    if current_bundle_id != bundle_id {
      return Err(Error::MismatchedBundleID {
        original_id: String::from(bundle_id),
        current_id: current_bundle_id,
      });
    }

    log::info!("S3BundlePoller: Unpacking bundle...");

    let stream = get_object_response
      .body
      .ok_or(InternalError::S3MissingBody)?
      .into_async_read();

    // TODO: Write temp file to disk.
    let mut archive = Archive::new(stream);

    archive
      .unpack(path)
      .await
      .map_err(|err| Error::UnpackError { source: err })?;

    Ok(())
  }
}