plane 0.5.5

Session backend orchestrator for ambitious browser-based apps.
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
use crate::database::{
    backend_key::{KeysDatabase, KEY_LEASE_EXPIRATION},
    drone::DroneDatabase,
};

use super::{
    backend::emit_state_change,
    backend_actions::create_pending_action,
    backend_key::{KEY_LEASE_RENEW_AFTER, KEY_LEASE_SOFT_TERMINATE_AFTER},
    drone::DroneForSpawn,
};
use plane_common::{
    log_types::LoggableTime,
    names::{BackendName, OrRandom},
    protocol::{AcquiredKey, BackendAction, KeyDeadlines},
    types::{
        BackendState, BackendStatus, BearerToken, ClusterName, ConnectRequest, ConnectResponse,
        KeyConfig, RevokeRequest, SecretToken, SpawnConfig,
    },
    util::random_token,
    PlaneClient,
};
use serde_json::{Map, Value};
use sqlx::{postgres::types::PgInterval, PgPool};
use std::time::Duration;
use valuable::Valuable;

const TOKEN_LIFETIME_SECONDS: u64 = 3600;

/// Unique violation error code in Postgres.
/// NOTE: typically we should use "on conflict do nothing", but that only
/// works with insert queries, not update queries.
/// From: https://www.postgresql.org/docs/9.2/errcodes-appendix.html
pub const PG_UNIQUE_VIOLATION_ERROR: &str = "23505";
fn violates_uniqueness(err: &sqlx::Error) -> bool {
    if let sqlx::Error::Database(err) = &err {
        if let Some(code) = err.code() {
            return code == PG_UNIQUE_VIOLATION_ERROR;
        }
    }
    false
}

type Result<T> = std::result::Result<T, ConnectError>;

#[derive(thiserror::Error, Debug)]
pub enum ConnectError {
    #[error("No active drone available.")]
    NoDroneAvailable,

    #[error("Key held and tag does not match. {request_tag:?} != {key_tag:?}")]
    KeyHeld {
        request_tag: String,
        key_tag: String,
    },

    #[error("The key is held but unhealthy.")]
    KeyHeldUnhealthy,

    #[error("The key is unheld and no spawn config was provided.")]
    KeyUnheldNoSpawnConfig,

    #[error("Failed to remove key.")]
    FailedToRemoveKey,

    #[error("Failed to acquire key.")]
    FailedToAcquireKey,

    #[error("SQL error: {0}")]
    DatabaseError(#[from] sqlx::Error),

    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    #[error("No cluster provided, and no default cluster for this controller.")]
    NoClusterProvided,

    #[error("Other internal error. {0}")]
    Other(String),
}

impl ConnectError {
    /// Some errors are due to race conditions, but if we retry they should work.
    fn retryable(&self) -> bool {
        matches!(
            self,
            ConnectError::FailedToRemoveKey | ConnectError::FailedToAcquireKey
        )
    }
}

/// Attempts to create a new backend that owns the given key. If the key is already held, returns
/// Err(ConnectError::FailedToAcquireKey). If the key is not held, creates a new backend and
/// returns Ok(backend_id).
async fn create_backend_with_key(
    pool: &PgPool,
    key: &KeyConfig,
    spawn_config: &SpawnConfig,
    cluster: &ClusterName,
    drone_for_spawn: &DroneForSpawn,
    static_token: Option<&BearerToken>,
) -> Result<BackendName> {
    let backend_id = spawn_config.id.clone().or_random();
    let mut txn = pool.begin().await?;

    let initial_status = BackendStatus::Scheduled;
    let initial_state = BackendState::Scheduled;

    let result = sqlx::query!(
        r#"
        with backend_insert as (
            insert into backend (
                id,
                cluster,
                last_status,
                last_status_time,
                last_status_number,
                drone_id,
                expiration_time,
                allowed_idle_seconds,
                last_keepalive,
                state,
                static_token,
                subdomain
            )
            values ($1, $2, $3, now(), $14, $4, now() + $5, $6, now(), $11, $12, $13)
            returning id
        )
        insert into backend_key (id, key_name, namespace, tag, expires_at, fencing_token)
        select $1, $7, $8, $9, now() + $10, extract(epoch from now()) * 1000 from backend_insert
        returning fencing_token
        "#,
        backend_id.to_string(),
        cluster.to_string(),
        initial_status.to_string(),
        drone_for_spawn.id.as_i32(),
        spawn_config
            .lifetime_limit_seconds
            .map(
                |limit| PgInterval::try_from(Duration::from_secs(limit as _))
                    .expect("valid interval")
            ),
        spawn_config.max_idle_seconds,
        key.name,
        key.namespace,
        key.tag,
        PgInterval::try_from(KEY_LEASE_EXPIRATION).expect("valid constant interval"),
        serde_json::to_value(&initial_state).expect("state is always serializable"),
        static_token.map(|t| t.to_string()),
        spawn_config.subdomain.as_ref().map(|s| s.to_string()),
        initial_status.as_int(),
    )
    .fetch_one(&mut *txn)
    .await;

    let result = match result {
        Ok(result) => result,
        Err(err) => {
            if violates_uniqueness(&err) {
                return Err(ConnectError::FailedToAcquireKey);
            }
            return Err(err.into());
        }
    };

    emit_state_change(&mut txn, &backend_id, &initial_state).await?;

    let acquired_key = AcquiredKey {
        key: key.clone(),
        deadlines: KeyDeadlines {
            renew_at: LoggableTime(drone_for_spawn.last_local_time + KEY_LEASE_RENEW_AFTER),
            soft_terminate_at: LoggableTime(
                drone_for_spawn.last_local_time + KEY_LEASE_SOFT_TERMINATE_AFTER,
            ),
            hard_terminate_at: LoggableTime(
                drone_for_spawn.last_local_time + KEY_LEASE_SOFT_TERMINATE_AFTER,
            ),
        },
        token: result.fencing_token,
    };

    let pending_action = BackendAction::Spawn {
        executable: spawn_config.executable.clone(),
        key: acquired_key,
        static_token: static_token.cloned(),
    };

    // Create an action to spawn the backend. If we succeed in acquiring the key,
    // this will cause the backend to spawn. If we fail to acquire the key, this
    // will be abandoned.
    create_pending_action(&mut txn, &backend_id, drone_for_spawn.id, &pending_action)
        .await
        .map_err(|e| ConnectError::Other(e.to_string()))?;

    txn.commit().await?;

    Ok(backend_id)
}

async fn create_token(
    pool: &PgPool,
    backend: &BackendName,
    user: Option<&str>,
    auth: Map<String, Value>,
) -> Result<(BearerToken, SecretToken)> {
    let token = random_token();
    let secret_token = random_token();

    sqlx::query!(
        r#"
        insert into token (token, backend_id, username, auth, secret_token, expiration_time)
        values ($1, $2, $3, $4, $5, now() + $6)
        "#,
        token,
        backend.to_string(),
        user,
        serde_json::to_value(auth).expect("json map is always serializable"),
        secret_token,
        PgInterval::try_from(Duration::from_secs(TOKEN_LIFETIME_SECONDS)).expect("valid interval"),
    )
    .execute(pool)
    .await?;

    Ok((BearerToken::from(token), SecretToken::from(secret_token)))
}

pub async fn revoke(pool: &PgPool, request: &RevokeRequest) -> Result<()> {
    sqlx::query!(
        r#"
        delete from token
        where backend_id = $1 and username = $2
        "#,
        request.backend_id.to_string(),
        request.user,
    )
    .execute(pool)
    .await?;
    Ok(())
}

async fn attempt_connect(
    pool: &PgPool,
    default_cluster: Option<&ClusterName>,
    request: &ConnectRequest,
    client: &PlaneClient,
) -> Result<ConnectResponse> {
    let key = if let Some(key) = &request.key {
        // Request includes a key, so we need to check if it is held.
        let key_result = KeysDatabase::new(pool).check_key(key).await?;

        if let Some(key_result) = key_result {
            // Key is held. Check if we can connect to existing backend.

            if key_result.is_live() {
                if key_result.tag != key.tag {
                    return Err(ConnectError::KeyHeld {
                        request_tag: key.tag.clone(),
                        key_tag: key_result.tag,
                    });
                }

                let (token, secret_token) = if let Some(token) = key_result.static_connection_token
                {
                    (token, None)
                } else {
                    let (token, secret_token) = create_token(
                        pool,
                        &key_result.id,
                        request.user.as_deref(),
                        request.auth.clone(),
                    )
                    .await?;

                    (token, Some(secret_token))
                };

                let connect_response = ConnectResponse::new(
                    key_result.id,
                    &key_result.cluster,
                    false,
                    key_result.status,
                    token,
                    secret_token,
                    key_result.subdomain,
                    client,
                    None,
                );

                return Ok(connect_response);
            } else {
                tracing::info!("Key will be removed");

                // Key is expired. Remove it.
                let removed = KeysDatabase::new(pool).remove_key(key_result.id).await?;
                if !removed {
                    // Key was not removed, so it must have been renewed
                    // since we checked it. Return error.
                    return Err(ConnectError::FailedToRemoveKey);
                }
            }
        }

        key.clone()
    } else {
        // Request does not include a key, so we create one.
        KeyConfig::new_random()
    };

    let Some(spawn_config) = &request.spawn_config else {
        return Err(ConnectError::KeyUnheldNoSpawnConfig);
    };

    let cluster = spawn_config
        .cluster
        .as_ref()
        .or(default_cluster)
        .ok_or(ConnectError::NoClusterProvided)?;

    let drone = DroneDatabase::new(pool)
        .pick_drone_for_spawn(cluster, &spawn_config.pool)
        .await?
        .ok_or(ConnectError::NoDroneAvailable)?;

    // If the spawn config specifies a static token, create one and use it.
    // Note that if this is non-None, the call to create_token below will be skipped.
    let bearer_token = spawn_config
        .use_static_token
        .then(BearerToken::new_random_static);

    let backend_id = create_backend_with_key(
        pool,
        &key,
        spawn_config,
        cluster,
        &drone,
        bearer_token.as_ref(),
    )
    .await?;
    tracing::info!(backend_id = backend_id.as_value(), "Created backend");

    let (token, secret_token) = if let Some(token) = bearer_token {
        (token, None)
    } else {
        let (token, secret_token) = create_token(
            pool,
            &backend_id,
            request.user.as_deref(),
            request.auth.clone(),
        )
        .await?;

        (token, Some(secret_token))
    };

    let connect_response = ConnectResponse::new(
        backend_id,
        cluster,
        true,
        BackendStatus::Scheduled,
        token,
        secret_token,
        spawn_config.subdomain.clone(),
        client,
        Some(drone.drone),
    );

    Ok(connect_response)
}

pub async fn connect(
    pool: &PgPool,
    default_cluster: Option<&ClusterName>,
    request: &ConnectRequest,
    client: &PlaneClient,
) -> Result<ConnectResponse> {
    let mut attempt = 1;
    loop {
        match attempt_connect(pool, default_cluster, request, client).await {
            Ok(response) => return Ok(response),
            Err(error) => {
                if !error.retryable() || attempt >= 3 {
                    return Err(error);
                }
                tracing::info!(error = ?error, attempt, "Retrying connect");
                attempt += 1;
            }
        }
    }
}

pub async fn clean_up_tokens(pool: &PgPool) -> std::result::Result<(), sqlx::Error> {
    let result = sqlx::query!(
        r#"
        delete from token
        where expiration_time < now()
        "#,
    )
    .execute(pool)
    .await?;

    let row_count = result.rows_affected();
    tracing::info!(row_count, "Cleaned up expired tokens");

    Ok(())
}