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
use crate::config::Config;
use collective::rundir::{self, RunDir};
use s3::packager::S3BundlePackager;
use serde::Serialize;
use snafu::{ResultExt, Snafu};
use std::{path::PathBuf, sync::Arc};
use tokio::{
  sync::RwLock,
  time::{interval, Duration},
};

use self::{local_dir::poller::LocalBundlePoller, s3::poller::S3BundlePoller};

pub mod local_dir;
pub mod packager;
pub mod poller;
pub mod s3;

#[derive(Snafu, Debug)]
pub enum Error {
  InitRunDir { source: rundir::RunDirError },
  DeinitRunDir { source: rundir::RunDirError },
  LockRead,
  LockWrite,
  AttachSignalHook { source: std::io::Error },
  MissingETag,
  PollError { source: poller::Error },
  SubDirError { source: rundir::RunDirError },
}

type Result<T, E = Error> = std::result::Result<T, E>;

#[derive(Copy, Clone, Debug, Serialize, PartialEq)]
pub enum UnbundlerStatus {
  /// Poller is instantiated but not initialized.
  Idle = 0,
  /// Poller is initialized.
  Initialized = 1,
  /// Poller is performing it's initial poll.
  InitialPolling = 2,
  /// Poller has set up a bundle and is ready to be served.
  Ready = 3,
  /// Poller is checking for bundle updates.
  Polling = 4,
}

#[derive(Clone)]
pub struct Bundle {
  etag: Option<String>,
}

pub struct Bundler {
  packager: Box<dyn packager::BundlePackager + Sync + Send>,
}

impl Bundler {
  pub fn new(config: Arc<Config>) -> Bundler {
    let packager: Box<dyn packager::BundlePackager + Sync + Send> = match &config.bundle {
      crate::config::BundleConfig::S3Bundle {
        access_key,
        secret_key,
        endpoint,
        bucket,
        region,
        object_name,
      } => Box::new(S3BundlePackager::new(
        access_key.clone(),
        secret_key.clone(),
        endpoint.clone(),
        bucket.clone(),
        region.clone(),
        object_name.clone(),
      )),
      crate::config::BundleConfig::LocalBundle { dir: _ } => {
        panic!("Local bundler is not currently implemented.")
      }
    };

    Bundler { packager }
  }

  pub async fn package(&self, path: PathBuf) -> Result<(), packager::Error> {
    log::info!("Packaging bundle at {}", path.display());

    self.packager.generate(path).await
  }
}

struct UnbundlerState {
  rundir: RunDir,
  status: UnbundlerStatus,
  active_bundle: Option<Bundle>,
  staging_bundle: Option<Bundle>,
  temp_dir: Option<PathBuf>,
}

pub struct Unbundler {
  config: Arc<Config>,
  serve_dir: Arc<RwLock<Option<PathBuf>>>,
  state: RwLock<UnbundlerState>,
  poller: Box<dyn poller::BundlePoller + Sync + Send>,
}

impl Unbundler {
  pub fn new(config: Arc<Config>, serve_dir: Arc<RwLock<Option<PathBuf>>>) -> Unbundler {
    let mut rundir = RunDir::new(config.server.run_dir.clone());

    if let Some(allow_cleaning) = config.server.auto_cleanup {
      rundir = rundir.allow_cleaning(allow_cleaning);
    }

    let poller: Box<dyn poller::BundlePoller + Sync + Send> = match &config.bundle {
      crate::config::BundleConfig::S3Bundle {
        access_key,
        secret_key,
        endpoint,
        bucket,
        region,
        object_name,
      } => Box::new(S3BundlePoller::new(
        access_key.clone(),
        secret_key.clone(),
        endpoint.clone(),
        bucket.clone(),
        region.clone(),
        object_name.clone(),
      )),
      crate::config::BundleConfig::LocalBundle { dir } => {
        Box::new(LocalBundlePoller::new(dir.clone()))
      }
    };

    Unbundler {
      config,
      state: RwLock::new(UnbundlerState {
        rundir,
        status: UnbundlerStatus::Idle,
        active_bundle: None,
        staging_bundle: None,
        temp_dir: None,
      }),
      poller,
      serve_dir,
    }
  }

  pub async fn get_status(&self) -> Result<UnbundlerStatus> {
    let state = self.state.read().await;

    Ok(state.status)
  }

  pub async fn get_serve_dir(&self) -> Result<Option<PathBuf>> {
    let serve_dir = self.serve_dir.read().await;

    Ok(serve_dir.clone())
  }

  pub async fn enter(&self) -> Result<()> {
    self.init().await?;

    let mut interval = interval(Duration::from_secs(self.config.unbundler.poll_seconds));
    let ctrl_c_fut = tokio::signal::ctrl_c();

    tokio::pin!(ctrl_c_fut);

    loop {
      let me = self;

      tokio::select! {
          _ = &mut ctrl_c_fut => {
            break;
          }
          _ = interval.tick() => {
            match me.poll().await {
                Ok(_) => {}
                Err(err) => log::error!("Unbundler: Got an error while invoking poller: {:?}", err),
            };
          }
      }
    }

    self.deinit().await
  }

  async fn init(&self) -> Result<()> {
    log::info!("Unbundler: Initializing...");

    let mut state = self.state.write().await;

    state.rundir.initialize().context(InitRunDir)?;
    state.temp_dir = Some(state.rundir.create_subdir("temp").context(InitRunDir)?);

    state.status = UnbundlerStatus::Initialized;

    Ok(())
  }

  async fn poll(&self) -> Result<()> {
    log::info!("Unbundler: Checking for updates...");

    // Update state on a spearate scope to avoid holding a write lock while
    // the poller runs.
    //
    // Lock will be released when `initial_state` goes out of scope.
    let active_bundle = {
      let mut initial_state = self.state.write().await;

      let active_bundle = initial_state.active_bundle.clone();
      if active_bundle.is_none() {
        initial_state.status = UnbundlerStatus::InitialPolling;
      } else {
        initial_state.status = UnbundlerStatus::Polling;
      }

      active_bundle
    };

    // Invoke the poller.
    let result = match self.poller.poll(&active_bundle).await {
      Err(err) => {
        let mut state = self.state.write().await;

        // Rollback status if the poll fails.
        if active_bundle.is_none() {
          state.status = UnbundlerStatus::Initialized;
        } else {
          state.status = UnbundlerStatus::Ready;
        }

        Err(err)
      }
      res => res,
    }
    .context(PollError)?;

    match result {
      poller::PollResult::Skip => {
        let mut state = self.state.write().await;

        state.status = UnbundlerStatus::Ready;

        log::info!("Unbundler: No updates from poller.");

        Ok(())
      }
      poller::PollResult::StaticUpdateReady { etag, path } => {
        let mut state = self.state.write().await;

        // Replacing active bundle.
        state.active_bundle = Some(Bundle { etag });
        state.staging_bundle = None;
        state.status = UnbundlerStatus::Ready;

        let mut serve_dir = self.serve_dir.write().await;

        serve_dir.replace(path);

        Ok(())
      }
      poller::PollResult::UpdateReady { etag } => {
        let mut state = self.state.write().await;

        if state.rundir.subdir_exists(&etag).context(SubDirError)? {
          log::warn!("Unbundler: Skipping update. Subdir already exists.");

          return Ok(());
        }

        state.staging_bundle = Some(Bundle {
          etag: Some(etag.clone()),
        });

        let newdir = state.rundir.create_subdir(&etag).context(SubDirError)?;

        let result = self.poller.retrieve(&etag, newdir.clone()).await;

        if result.is_err() {
          log::warn!("Unbundler: Poller failed to retrieve new bundle. Rolling back.");

          state.staging_bundle = None;
          state.status = UnbundlerStatus::Ready;

          state.rundir.remove_subdir_all(&etag).context(SubDirError)?;

          return Ok(());
        }

        // Replacing active bundle.
        state.active_bundle = state.staging_bundle.clone();
        state.staging_bundle = None;
        state.status = UnbundlerStatus::Ready;

        let mut serve_dir = self.serve_dir.write().await;

        serve_dir.replace(newdir);

        Ok(())
      }
    }
  }

  async fn deinit(&self) -> Result<()> {
    let mut state = self.state.write().await;

    state.status = UnbundlerStatus::Idle;
    state.rundir.cleanup().context(DeinitRunDir)?;

    Ok(())
  }
}