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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use anyhow::Result;
use chrono::{DateTime, Utc};
use plane_common::{
    log_types::LoggableTime,
    names::BackendName,
    protocol::{BackendEventId, BackendStateMessage},
    types::BackendState,
};
use rusqlite::Connection;

/// An array of sqlite commands used to initialize the state store.
/// These must be idempotent, because they are run every time a state store
/// is initialized.
const SCHEMA: &[&str] = &[
    r#"
        create table if not exists "backend" (
            "id" text primary key,
            "state" json not null
        );
    "#,
    r#"
        create table if not exists "event" (
            "id" integer primary key autoincrement,
            "backend_id" text,
            "event" json not null,
            "timestamp" integer not null,
            foreign key ("backend_id") references "backend"("id")
        );
    "#,
];

/// Stores state information about running backends.
pub struct StateStore {
    db_conn: Connection,

    /// A function that is called when a backend's state changes.
    listener: Option<Box<dyn Fn(BackendStateMessage) + Send + Sync + 'static>>,
}

impl StateStore {
    pub fn new(db_conn: Connection) -> Result<Self> {
        for table in SCHEMA {
            db_conn.execute(table, [])?;
        }

        Ok(Self {
            db_conn,
            listener: None,
        })
    }

    /// Make the state store aware of a change to a backend's state.
    pub fn register_event(
        &mut self,
        backend_id: &BackendName,
        state: &BackendState,
        timestamp: DateTime<Utc>,
    ) -> Result<()> {
        let tx = self.db_conn.transaction()?;

        // "Upsert" the current backend state into the table. Per sqlite docs (https://www.sqlite.org/lang_upsert.html):
        // > Column names in the expressions of a DO UPDATE refer to the original unchanged value of the column,
        // > before the attempted INSERT. To use the value that would have been inserted had the constraint not
        // > failed, add the special "excluded." table qualifier to the column name.

        tx.execute(
            r#"
                insert into "backend" (
                    "id",
                    "state"
                )
                values (?, ?)
                on conflict ("id")
                do update set
                    "state" = excluded."state"
            "#,
            (backend_id.to_string(), serde_json::to_value(state)?),
        )?;

        tx.execute(
            r#"
                insert into "event" (
                    "backend_id",
                    "event",
                    "timestamp"
                ) values (?, ?, ?)
            "#,
            (
                backend_id.to_string(),
                serde_json::to_value(state)?,
                timestamp.timestamp_millis(),
            ),
        )?;

        tx.commit()?;

        if let Some(listener) = &self.listener {
            let event_id = BackendEventId::from(self.db_conn.last_insert_rowid());
            let event_message = BackendStateMessage {
                event_id,
                backend_id: backend_id.clone(),
                timestamp: LoggableTime(timestamp),
                state: state.clone(),
            };

            listener(event_message);
        }

        Ok(())
    }

    pub fn backend_state(&self, backend_id: &BackendName) -> Result<BackendState> {
        let mut stmt = self.db_conn.prepare(
            r#"
                select "state"
                from "backend"
                where id = ?
                limit 1
            "#,
        )?;

        let mut rows = stmt.query([backend_id.to_string()])?;

        let row = rows.next()?.ok_or_else(|| {
            anyhow::anyhow!(
                "No backend with id {} found in state store.",
                backend_id.to_string()
            )
        })?;

        let state: String = row.get(0)?;
        let state: BackendState = serde_json::from_str(&state)?;

        Ok(state)
    }

    fn unacked_events(&self) -> Result<Vec<BackendStateMessage>> {
        let mut stmt = self.db_conn.prepare(
            r#"
                select
                    id,
                    backend_id,
                    event,
                    timestamp
                from "event"
                order by timestamp asc
            "#,
        )?;

        let mut rows = stmt.query([])?;
        let mut result = Vec::new();

        while let Some(row) = rows.next()? {
            let event_id: i64 = row.get(0)?;
            let backend_id: String = row.get(1)?;
            let state: String = row.get(2)?;
            let timestamp: i64 = row.get(3)?;

            let state: BackendState = serde_json::from_str(&state)?;

            let event = BackendStateMessage {
                event_id: BackendEventId::from(event_id),
                backend_id: BackendName::try_from(backend_id)?,
                state: state.clone(),
                timestamp: LoggableTime(
                    DateTime::UNIX_EPOCH
                        + chrono::Duration::try_milliseconds(timestamp)
                            .expect("duration is always valid"),
                ),
            };

            result.push(event);
        }

        Ok(result)
    }

    pub fn register_listener<F>(&mut self, listener: F) -> Result<()>
    where
        F: Fn(BackendStateMessage) + Send + Sync + 'static,
    {
        // We assume that events that have been sent but not acked are now dropped,
        // so we replay them here.
        for event in self.unacked_events()? {
            listener(event);
        }

        self.listener = Some(Box::new(listener));

        Ok(())
    }

    pub fn ack_event(&self, event_id: BackendEventId) -> Result<()> {
        self.db_conn.execute(
            r#"
                delete from "event"
                where id = ?
            "#,
            (i64::from(event_id),),
        )?;

        Ok(())
    }

    /// Retrieves a list of all backends that are not in a Terminated state.
    pub fn active_backends(&self) -> Result<Vec<(BackendName, BackendState)>> {
        let mut stmt = self.db_conn.prepare(
            r#"
                select "id", "state"
                from "backend"
            "#,
        )?;

        let mut rows = stmt.query([])?;
        let mut active_backends = Vec::new();

        while let Some(row) = rows.next()? {
            let id: String = row.get(0)?;
            let state_json: String = row.get(1)?;
            let state: BackendState = serde_json::from_str(&state_json)?;

            if !matches!(state, BackendState::Terminated { .. }) {
                active_backends.push((BackendName::try_from(id)?, state));
            }
        }

        Ok(active_backends)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use plane_common::{
        log_types::BackendAddr,
        names::Name,
        types::{BackendStatus, TerminationReason},
    };
    use std::{
        net::{SocketAddr, SocketAddrV4},
        sync::mpsc,
    };

    fn dummy_addr() -> BackendAddr {
        BackendAddr(SocketAddr::V4(SocketAddrV4::new(
            "12.34.12.34".parse().unwrap(),
            1234,
        )))
    }

    #[test]
    fn single_event() {
        let conn = Connection::open_in_memory().unwrap();
        let mut state_store = StateStore::new(conn).unwrap();
        let backend_id = BackendName::new_random();

        state_store
            .register_event(
                &backend_id,
                &BackendState::Ready {
                    address: dummy_addr(),
                },
                Utc::now(),
            )
            .unwrap();

        let result = state_store.backend_state(&backend_id).unwrap();
        assert_eq!(
            result,
            BackendState::Ready {
                address: dummy_addr()
            }
        );
    }

    #[test]
    fn two_events() {
        let conn = Connection::open_in_memory().unwrap();
        let mut state_store = StateStore::new(conn).unwrap();
        let backend_id = BackendName::new_random();

        let ready_state = BackendState::Ready {
            address: dummy_addr(),
        };
        {
            state_store
                .register_event(&backend_id, &ready_state, Utc::now())
                .unwrap();

            let result = state_store.backend_state(&backend_id).unwrap();
            assert_eq!(
                result,
                BackendState::Ready {
                    address: dummy_addr()
                }
            );
        }

        {
            state_store
                .register_event(
                    &backend_id,
                    &ready_state.to_hard_terminating(TerminationReason::External),
                    Utc::now(),
                )
                .unwrap();

            let result = state_store.backend_state(&backend_id).unwrap();
            assert_eq!(
                result,
                BackendState::HardTerminating {
                    last_status: BackendStatus::Ready,
                    reason: TerminationReason::External,
                }
            );
        }
    }

    #[test]
    fn subscribe_events() {
        let (send, recv) = mpsc::channel::<BackendStateMessage>();

        let conn = Connection::open_in_memory().unwrap();
        let mut state_store = StateStore::new(conn).unwrap();

        state_store
            .register_listener(move |event| {
                send.send(event).unwrap();
            })
            .unwrap();

        let backend_id = BackendName::new_random();

        let ready_state = BackendState::Ready {
            address: dummy_addr(),
        };
        state_store
            .register_event(&backend_id, &ready_state, Utc::now())
            .unwrap();

        {
            let result = state_store.backend_state(&backend_id).unwrap();
            assert_eq!(result, ready_state);

            let event = recv.try_recv().unwrap();
            assert_eq!(event.backend_id, backend_id);
            assert_eq!(
                event.state,
                BackendState::Ready {
                    address: dummy_addr()
                }
            );
        }

        {
            state_store
                .register_event(
                    &backend_id,
                    &ready_state.to_hard_terminating(TerminationReason::Swept),
                    Utc::now(),
                )
                .unwrap();

            let result = state_store.backend_state(&backend_id).unwrap();
            assert_eq!(
                result,
                ready_state.to_hard_terminating(TerminationReason::Swept)
            );

            let event = recv.try_recv().unwrap();
            assert_eq!(event.backend_id, backend_id);
            assert_eq!(
                event.state,
                BackendState::HardTerminating {
                    last_status: BackendStatus::Ready,
                    reason: TerminationReason::Swept,
                }
            );
        }
    }

    #[test]
    fn events_are_durable() {
        let (send, recv) = mpsc::channel::<BackendStateMessage>();

        let conn = Connection::open_in_memory().unwrap();
        let mut state_store = StateStore::new(conn).unwrap();

        let backend_id = BackendName::new_random();

        let ready_state = BackendState::Ready {
            address: dummy_addr(),
        };
        state_store
            .register_event(&backend_id, &ready_state, Utc::now())
            .unwrap();

        state_store
            .register_event(
                &backend_id,
                &ready_state.to_hard_terminating(TerminationReason::Swept),
                Utc::now(),
            )
            .unwrap();

        state_store
            .register_listener(move |event| {
                send.send(event).unwrap();
            })
            .unwrap();

        {
            let event = recv.try_recv().unwrap();
            assert_eq!(event.backend_id, backend_id);
            assert_eq!(event.event_id, BackendEventId::from(1));
            assert_eq!(
                event.state,
                BackendState::Ready {
                    address: dummy_addr()
                }
            );
        }

        {
            let event = recv.try_recv().unwrap();
            assert_eq!(event.backend_id, backend_id);
            assert_eq!(event.event_id, BackendEventId::from(2));
            assert_eq!(
                event.state,
                BackendState::HardTerminating {
                    last_status: BackendStatus::Ready,
                    reason: TerminationReason::Swept,
                }
            );
        }

        assert!(recv.try_recv().is_err());

        // Events are replayed when we install a new listener.
        let (send, recv) = mpsc::channel::<BackendStateMessage>();
        state_store
            .register_listener(move |event| {
                send.send(event).unwrap();
            })
            .unwrap();

        {
            let event = recv.try_recv().unwrap();
            assert_eq!(event.backend_id, backend_id);
            assert_eq!(
                event.state,
                BackendState::Ready {
                    address: dummy_addr()
                }
            );
        }

        {
            let event = recv.try_recv().unwrap();
            assert_eq!(event.backend_id, backend_id);
            assert_eq!(
                event.state,
                BackendState::HardTerminating {
                    last_status: BackendStatus::Ready,
                    reason: TerminationReason::Swept,
                }
            );
        }

        assert!(recv.try_recv().is_err());

        // Events are NOT replayed once acked.
        let (send, recv) = mpsc::channel::<BackendStateMessage>();

        state_store.ack_event(BackendEventId::from(1)).unwrap();

        state_store
            .register_listener(move |event| {
                send.send(event).unwrap();
            })
            .unwrap();

        {
            let event = recv.try_recv().unwrap();
            assert_eq!(event.backend_id, backend_id);
            assert_eq!(
                event.state,
                BackendState::HardTerminating {
                    last_status: BackendStatus::Ready,
                    reason: TerminationReason::Swept,
                }
            );
        }

        assert!(recv.try_recv().is_err());
    }
}