plane_drone/
database.rs

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
//! Interface to the shared sqlite database.
//!
//! All interaction between the proxy and the agent happen
//! asynchronously by updating the state of the sqlite
//! database.
//!
//! Queries are type-checked by the Rust compiler using sqlx,
//! based on type information stored in `sqlx-data.json`. If
//! you change a query in this file, you will likely need to
//! run `generate-sqlx-data.mjs` to get Rust to accept it.
use chrono::{DateTime, TimeZone, Utc};
use plane_core::{
    messages::agent::{BackendState, SpawnRequest},
    types::BackendId,
};
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use sqlx::{migrate, Result, SqlitePool};
use std::{path::Path, str::FromStr};

#[allow(unused)]
#[derive(Clone, Debug)]
pub struct DroneDatabase {
    pool: SqlitePool,
}

pub struct Backend {
    pub backend_id: BackendId,
    pub state: BackendState,
    pub spec: SpawnRequest,
}

#[allow(unused)]
impl DroneDatabase {
    pub async fn new(db_path: &Path) -> Result<DroneDatabase> {
        let co = SqliteConnectOptions::new()
            .filename(&db_path)
            .create_if_missing(true);
        let pool = SqlitePoolOptions::new().connect_with(co).await?;
        migrate!("./migrations").run(&pool).await?;

        let connection = DroneDatabase { pool };
        Ok(connection)
    }

    pub async fn insert_backend(&self, spec: &SpawnRequest) -> Result<()> {
        let backend_id = spec.backend_id.id().to_string();
        let spec =
            serde_json::to_string(&spec).expect("SpawnRequest serialization should never fail.");

        sqlx::query!(
            r"
            insert into backend
            (name, spec, state)
            values
            (?, ?, 'Loading')
            ",
            backend_id,
            spec,
        )
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    pub async fn get_backends(&self) -> anyhow::Result<Vec<Backend>> {
        sqlx::query!(
            r"
            select name, spec, state
            from backend
            "
        )
        .fetch_all(&self.pool)
        .await?
        .iter()
        .map(|d| {
            Ok(Backend {
                backend_id: BackendId::new(d.name.clone()),
                spec: serde_json::from_str(&d.spec)?,
                state: BackendState::from_str(&d.state)?,
            })
        })
        .collect()
    }

    pub async fn update_backend_state(
        &self,
        backend: &BackendId,
        state: BackendState,
    ) -> Result<()> {
        let state = state.to_string();

        sqlx::query!(
            r"
            update backend
            set state = ?
            ",
            state
        )
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    /// Get the downstream source to direct a request on an incoming subdomain to.
    pub async fn get_proxy_route(&self, subdomain: &str) -> Result<Option<String>> {
        Ok(sqlx::query!(
            r"
            select address
            from route
            where subdomain = ?
            ",
            subdomain
        )
        .fetch_optional(&self.pool)
        .await?
        .map(|d| d.address))
    }

    pub async fn insert_proxy_route(
        &self,
        backend: &BackendId,
        subdomain: &str,
        address: &str,
    ) -> Result<()> {
        let backend_id = backend.id().to_string();
        sqlx::query!(
            r"
            insert into route
            (backend, subdomain, address, last_active)
            values
            (?, ?, ?, unixepoch())
            ",
            backend_id,
            subdomain,
            address
        )
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    pub async fn reset_last_active_times(&self, subdomains: &[String]) -> Result<()> {
        for subdomain in subdomains {
            sqlx::query!(
                r"
                update route
                set last_active = unixepoch()
                where subdomain = ?
                ",
                subdomain
            )
            .execute(&self.pool)
            .await?;
        }

        Ok(())
    }

    pub async fn get_backend_last_active(&self, backend: &BackendId) -> Result<DateTime<Utc>> {
        let backend_id = backend.id();

        let time = sqlx::query!(
            r#"
            select last_active
            from route
            where backend = ?
            "#,
            backend_id
        )
        .fetch_one(&self.pool)
        .await?
        .last_active;

        Ok(Utc.timestamp(time, 0))
    }
}