prest 0.5.1

Progressive RESTful framework
Documentation
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
use crate::*;

use chrono::{DateTime, NaiveDateTime, Utc};
use russh::*;
use russh_keys::*;
use semver::Version;
use std::time::Duration;
use tokio::{io::AsyncWriteExt, sync::RwLock, time::sleep};

const APPS_PATH: &str = "/home";
const DEPLOY_PREFIX: &str = "prest__";
const DEPLOY_DATETIME: &str = "%Y-%m-%d_%H:%M:%S";

state!(REMOTE: Option<RemoteHost> = async { RemoteHost::try_connect().await? });

pub(crate) async fn upload_and_activate(binary_path: &str) -> Result {
    let Some(remote) = &*REMOTE else {
        return Err(e!("No connection to the remote host"));
    };

    let deployment = DeploymentInfo::new();
    let package = deployment.package();

    info!(target:"remote", "initiated update for {package}");
    let mut conn = remote.conn().await?;

    info!(target:"remote", "uploading the binary");
    remote.set_state(DeploymentState::Uploading).await;
    conn.upload(binary_path, &deployment).await?;
    info!(target:"remote", "upload finished successfully");

    match conn.find_current_deployment(&deployment.pkg_name).await? {
        Some(p) => {
            let pid = p.pid.expect("Current deployment must have pid");
            conn.kill_process(pid).await?;
            while conn.check_process(pid).await? {
                info!(target:"remote", "stopping current deployment...");
                conn.kill_process(pid).await?;
                sleep(Duration::from_millis(1000)).await;
            }
            info!(target:"remote", "stopped current process")
        }
        None => warn!(target:"remote", "no current deployment found"),
    }

    conn.activate_deployment(&deployment).await?;
    info!(target:"remote", "started new {package} process");

    remote.sync_deployments().await?;

    OK
}

pub(crate) struct RemoteHost {
    pub addr: String,
    pub user: String,
    pub pass: String,
    pub deployments: RwLock<Vec<DeploymentInfo>>,
    pub state: RwLock<DeploymentState>,
}

impl RemoteHost {
    pub async fn try_connect() -> Result<Option<Self>> {
        if *IS_REMOTE {
            return Ok(None);
        }

        let (addr, user, pass) = match (
            env_var("SSH_ADDR").ok(),
            env_var("SSH_USER").ok(),
            env_var("SSH_PASSWORD").ok(),
        ) {
            (Some(addr), Some(user), Some(password)) => {
                match SshSession::connect(&addr, &user, &password).await {
                    Ok(_) => info!(target: "remote", "established connection with {addr}"),
                    Err(e) => {
                        warn!(target: "remote", "failed to connect to {addr} : {e}");
                        return Ok(None);
                    }
                }
                (addr, user, password)
            }
            _ => return Ok(None),
        };

        let state = DeploymentState::Idle;

        let host = RemoteHost {
            addr,
            user,
            pass,
            deployments: RwLock::default(),
            state: RwLock::new(state),
        };

        host.sync_deployments().await?;

        Ok(Some(host))
    }

    pub async fn conn(&self) -> Result<SshSession> {
        Ok(SshSession::connect(&self.addr, &self.user, &self.pass).await?)
    }

    pub async fn state(&self) -> DeploymentState {
        *self.state.read().await
    }

    pub async fn sync_deployments(&self) -> Result {
        let mut conn = self.conn().await?;
        let mut deployments = conn.list_deployments().await?;

        let active = conn.find_current_deployment(APP_CONFIG.name).await?;

        if let Some(active) = active {
            if let Some(deployment) = deployments.iter_mut().find(|d| {
                d.pkg_name == active.pkg_name
                    && d.version == active.version
                    && d.datetime == active.datetime
            }) {
                deployment.pid = active.pid;
            }
        }

        *self.deployments.write().await = deployments;
        OK
    }

    pub async fn set_state(&self, new_state: DeploymentState) {
        *self.state.write().await = new_state;
    }

    pub async fn ready_to_deploy(&self) -> bool {
        matches!(
            self.state().await,
            DeploymentState::Idle | DeploymentState::Success | DeploymentState::Failure
        )
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct DeploymentInfo {
    pub pid: Option<u32>,
    pub pkg_name: String,
    pub version: Version,
    pub datetime: DateTime<Utc>,
}

impl DeploymentInfo {
    pub fn new() -> Self {
        let pkg_name = APP_CONFIG.name;
        let version = APP_CONFIG.version.clone();

        DeploymentInfo {
            pid: None,
            pkg_name: pkg_name.to_owned(),
            version,
            datetime: Utc::now(),
        }
    }

    pub fn from(command: &str, pid: Option<&str>) -> Result<Self> {
        let Some(binary) = command.strip_prefix(&format!("{APPS_PATH}/{DEPLOY_PREFIX}")) else {
            return Err(e!("Unexpected process command: {command}"));
        };

        let mut values = binary.split("__");

        let Some(pkg_name) = values.next().map(|s| s.to_owned()) else {
            return Err(e!("Expected process package name: {command}"));
        };

        let Some(raw_version) = values.next() else {
            return Err(e!("Expected process package version: {command}"));
        };
        let version = raw_version.parse::<semver::Version>().somehow()?;

        let Some(raw_datetime) = values.next() else {
            return Err(e!("Expected process package datetime: {command}"));
        };
        let datetime = NaiveDateTime::parse_from_str(raw_datetime, DEPLOY_DATETIME)
            .somehow()?
            .and_utc();

        let pid = match pid {
            Some(s) => Some(
                s.trim()
                    .parse::<u32>()
                    .map_err(|e| e!("Failed to parse process ID: {e}"))?,
            ),
            None => None,
        };

        Ok(Self {
            pid,
            pkg_name,
            version,
            datetime,
        })
    }

    pub fn path(&self) -> String {
        let datetime = self.datetime.format(DEPLOY_DATETIME).to_string();
        let remote_filename = format!(
            "{DEPLOY_PREFIX}{}__{}__{datetime}",
            self.pkg_name, self.version
        );
        format!("{APPS_PATH}/{remote_filename}")
    }

    pub fn package(&self) -> String {
        format!("{} v{}", self.pkg_name, self.version)
    }
}

#[derive(Debug, PartialEq, Clone, Copy)]
pub(crate) enum DeploymentState {
    Idle,
    Building,
    Uploading,
    Success,
    Failure,
}

struct Client {}
#[async_trait]
impl client::Handler for Client {
    type Error = russh::Error;

    async fn check_server_key(
        &mut self,
        _server_public_key: &PublicKey,
    ) -> Result<bool, Self::Error> {
        Ok(true)
    }
}

pub(crate) struct SshSession {
    session: client::Handle<Client>,
}

impl SshSession {
    pub async fn connect(addr: &str, user: &str, password: &str) -> Result<Self> {
        let config = client::Config {
            inactivity_timeout: Some(std::time::Duration::from_secs(5)),
            ..<_>::default()
        };

        let config = Arc::new(config);

        let mut session = client::connect(config, addr, Client {}).await?;
        let auth_res = session.authenticate_password(user, password).await?;

        if !auth_res {
            return Err(e!("SSH authentication failed"));
        }

        Ok(Self { session })
    }

    pub async fn upload(&mut self, local_path: &str, deployment: &DeploymentInfo) -> Result {
        let binary = std::fs::read(local_path).somehow()?;

        let remote_path = deployment.path();

        let channel = self
            .session
            .channel_open_session()
            .await
            .map_err(|e| e!("failed to open ssh channel: {e}"))?;

        channel
            .request_subsystem(true, "sftp")
            .await
            .map_err(|e| e!("failed to request sftp subsystem: {e}"))?;

        let sftp = russh_sftp::client::SftpSession::new(channel.into_stream())
            .await
            .map_err(|e| e!("failed to initialize sftp session: {e}"))?;

        let mut file = sftp
            .create(&remote_path)
            .await
            .map_err(|e| e!("failed to open the remote file: {e}"))?;

        file.write_all(&binary)
            .await
            .map_err(|e| e!("failed to write into the remote file: {e}"))?;

        file.sync_all()
            .await
            .map_err(|e| e!("failed to sync the remote binary: {e}"))?;

        self.call(&format!("chmod +x {}", &remote_path))
            .await
            .map_err(|e| e!("failed to make the remote binary executable: {e}"))?;

        let _ = sftp.close().await;
        OK
    }

    pub async fn call(&mut self, command: &str) -> Result {
        let mut channel = self.session.channel_open_session().await?;
        channel.exec(true, command).await?;

        let mut stdout = tokio::io::stdout();

        loop {
            let Some(msg) = channel.wait().await else {
                break;
            };
            if let ChannelMsg::Data { ref data } = msg {
                tokio::io::AsyncWriteExt::write_all(&mut stdout, data).await?;
                tokio::io::AsyncWriteExt::flush(&mut stdout).await?;
            }
        }
        OK
    }

    #[allow(dead_code)]
    pub async fn close(&mut self) -> Result {
        self.session
            .disconnect(Disconnect::ByApplication, "", "English")
            .await?;
        OK
    }

    pub async fn find_prest_processes(&mut self) -> Result<Vec<DeploymentInfo>> {
        let mut channel = self.session.channel_open_session().await?;
        channel
            .exec(true, format!(r#"pgrep -fa "{DEPLOY_PREFIX}""#))
            .await?;

        let mut output = Vec::new();
        while let Some(msg) = channel.wait().await {
            if let ChannelMsg::Data { ref data } = msg {
                output.extend_from_slice(data);
            }
        }

        Ok(String::from_utf8_lossy(&output)
            .lines()
            .filter_map(|line| {
                let parts: Vec<&str> = line.splitn(2, ' ').collect();
                match parts[..] {
                    [pid, cmd] => match DeploymentInfo::from(cmd, Some(pid)) {
                        Ok(p) => Some(p),
                        Err(e) => {
                            warn!(target:"remote", "Invalid process info: {e}");
                            None
                        }
                    },
                    _ => None,
                }
            })
            .collect())
    }

    pub async fn find_current_deployment(
        &mut self,
        package: &str,
    ) -> Result<Option<DeploymentInfo>> {
        Ok(self
            .find_prest_processes()
            .await?
            .into_iter()
            .find(|p| &p.pkg_name == package))
    }

    pub async fn kill_process(&mut self, pid: u32) -> Result {
        self.call(&format!("kill -SIGTERM {pid}")).await?;
        OK
    }

    pub async fn check_process(&mut self, pid: u32) -> Result<bool> {
        Ok(self
            .find_prest_processes()
            .await?
            .iter()
            .filter_map(|p| p.pid)
            .find(|process_pid| *process_pid == pid)
            .is_some())
    }

    pub async fn list_deployments(&mut self) -> Result<Vec<DeploymentInfo>> {
        let mut channel = self.session.channel_open_session().await?;
        channel
            .exec(true, format!(r#"ls -1 {APPS_PATH}/{DEPLOY_PREFIX}*"#))
            .await?;

        let mut output = Vec::new();
        while let Some(msg) = channel.wait().await {
            if let ChannelMsg::Data { ref data } = msg {
                output.extend_from_slice(data);
            }
        }

        Ok(String::from_utf8_lossy(&output)
            .lines()
            .filter_map(|line| match DeploymentInfo::from(line, None) {
                Ok(p) => Some(p),
                Err(e) => {
                    warn!(target:"remote", "invalid deployment file: {e}");
                    None
                }
            })
            .collect())
    }

    pub async fn activate_deployment(&mut self, deployment: &DeploymentInfo) -> Result {
        self.call(&format!("DEPLOYED_TO_REMOTE=true {}", deployment.path()))
            .await?;
        OK
    }

    pub async fn delete_deployment(&mut self, deployment: &DeploymentInfo) -> Result {
        self.call(&format!("rm {}", deployment.path())).await?;
        OK
    }
}