jocker-lib 0.5.1

Run your monorepo binaries locally with ease !
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
use std::{collections::HashSet, path::Path, sync::Arc};

use chrono::{DateTime, Utc};
use redb::{ReadableTable, TableDefinition, TypeName, Value};
use serde::{Deserialize, Serialize};

use crate::{
    common::{Binary, Process, ProcessState, Stack},
    error::{Error, InnerError, Result},
};

const DB_FILE: &str = "db.redb";
const METADATA: TableDefinition<u8, Metadata> = TableDefinition::new("metadata");
const BINARY: TableDefinition<&str, Binary> = TableDefinition::new("binary");
const PROCESS: TableDefinition<&str, Process> = TableDefinition::new("process");
const STACK: TableDefinition<&str, Stack> = TableDefinition::new("stack");

#[derive(Debug, Default, Deserialize, Serialize)]
struct Metadata {
    binaries_updated_at: DateTime<Utc>,
    config_updated_at: DateTime<Utc>,
    default_stack: Option<String>,
}

impl Value for Metadata {
    type SelfType<'a>
        = Metadata
    where
        Self: 'a;

    type AsBytes<'a>
        = Vec<u8>
    where
        Self: 'a;

    fn fixed_width() -> Option<usize> {
        None
    }

    fn from_bytes<'a>(data: &'a [u8]) -> Self::SelfType<'a>
    where
        Self: 'a,
    {
        serde_json::from_slice(data).unwrap()
    }

    fn as_bytes<'a, 'b: 'a>(value: &'a Self::SelfType<'b>) -> Self::AsBytes<'a>
    where
        Self: 'b,
    {
        serde_json::to_vec(value).unwrap()
    }

    fn type_name() -> redb::TypeName {
        TypeName::new("jocker-lib_metadata")
    }
}

impl Value for Binary {
    type SelfType<'a>
        = Binary
    where
        Self: 'a;

    type AsBytes<'a>
        = Vec<u8>
    where
        Self: 'a;

    fn fixed_width() -> Option<usize> {
        None
    }

    fn from_bytes<'a>(data: &'a [u8]) -> Self::SelfType<'a>
    where
        Self: 'a,
    {
        serde_json::from_slice(data).unwrap()
    }

    fn as_bytes<'a, 'b: 'a>(value: &'a Self::SelfType<'b>) -> Self::AsBytes<'a>
    where
        Self: 'b,
    {
        serde_json::to_vec(value).unwrap()
    }

    fn type_name() -> TypeName {
        TypeName::new("jocker-lib_binary-package")
    }
}

impl Value for Process {
    type SelfType<'a>
        = Process
    where
        Self: 'a;

    type AsBytes<'a>
        = Vec<u8>
    where
        Self: 'a;

    fn fixed_width() -> Option<usize> {
        None
    }

    fn from_bytes<'a>(data: &'a [u8]) -> Self::SelfType<'a>
    where
        Self: 'a,
    {
        serde_json::from_slice(data).unwrap()
    }

    fn as_bytes<'a, 'b: 'a>(value: &'a Self::SelfType<'b>) -> Self::AsBytes<'a>
    where
        Self: 'b,
    {
        serde_json::to_vec(value).unwrap()
    }

    fn type_name() -> TypeName {
        TypeName::new("jocker-lib_process")
    }
}

impl Value for Stack {
    type SelfType<'a>
        = Stack
    where
        Self: 'a;

    type AsBytes<'a>
        = Vec<u8>
    where
        Self: 'a;

    fn fixed_width() -> Option<usize> {
        None
    }

    fn from_bytes<'a>(data: &'a [u8]) -> Self::SelfType<'a>
    where
        Self: 'a,
    {
        serde_json::from_slice(data).unwrap()
    }

    fn as_bytes<'a, 'b: 'a>(value: &'a Self::SelfType<'b>) -> Self::AsBytes<'a>
    where
        Self: 'b,
    {
        serde_json::to_vec(value).unwrap()
    }

    fn type_name() -> TypeName {
        TypeName::new("jocker-lib_stack")
    }
}

pub(crate) struct Database {
    db: Arc<redb::Database>,
}

impl Database {
    pub(crate) async fn new(database_directory_path: impl AsRef<Path>) -> Result<Self> {
        let database_path = database_directory_path.as_ref().join(DB_FILE);
        let mut db = redb::Database::create(database_path)?;
        db.upgrade()?;
        let txn = db.begin_write()?;
        {
            txn.open_table(METADATA)?;
            txn.open_table(BINARY)?;
            txn.open_table(PROCESS)?;
            txn.open_table(STACK)?;
        }
        txn.commit()?;
        Ok(Self { db: Arc::new(db) })
    }

    pub(crate) async fn get_binaries(&self) -> Result<Vec<Binary>> {
        let txn = self.db.begin_read()?;
        let table = txn.open_table(BINARY)?;

        Ok(table
            .iter()?
            .map(|v| v.map(|vv| vv.1.value()))
            .collect::<std::result::Result<_, _>>()?)
    }

    pub(crate) async fn get_binaries_updated_at(&self) -> Result<Option<DateTime<Utc>>> {
        let txn = self.db.begin_read()?;
        let table = txn.open_table(METADATA)?;

        Ok(table.get(0)?.map(|v| v.value().binaries_updated_at))
    }

    pub(crate) async fn get_config_updated_at(&self) -> Result<Option<DateTime<Utc>>> {
        let txn = self.db.begin_read()?;
        let table = txn.open_table(METADATA)?;

        Ok(table.get(0)?.map(|v| v.value().config_updated_at))
    }

    pub(crate) async fn get_default_stack(&self) -> Result<Option<String>> {
        let txn = self.db.begin_read()?;
        let table = txn.open_table(METADATA)?;

        Ok(table.get(0)?.and_then(|v| v.value().default_stack))
    }

    pub(crate) async fn get_processes(&self) -> Result<Vec<Process>> {
        let txn = self.db.begin_read()?;
        let table = txn.open_table(PROCESS)?;

        Ok(table
            .iter()?
            .map(|v| v.map(|vv| vv.1.value()))
            .collect::<std::result::Result<_, _>>()?)
    }

    pub(crate) async fn get_stack(&self, stack: &str) -> Result<Stack> {
        let txn = self.db.begin_read()?;
        let table = txn.open_table(STACK)?;

        table
            .get(stack)?
            .map(|v| v.value())
            .ok_or_else(|| Error::new(InnerError::StackNotFound(stack.to_owned())))
    }

    pub(crate) async fn set_binaries(&self, binaries: &[Binary]) -> Result<()> {
        let txn = self.db.begin_write()?;
        {
            txn.delete_table(BINARY)?;
            let mut table = txn.open_table(BINARY)?;
            for bin in binaries {
                table.insert(bin.name.as_str(), bin)?;
            }
        }
        txn.commit()?;
        Ok(())
    }

    pub(crate) async fn set_binaries_updated_at(&self, date: DateTime<Utc>) -> Result<()> {
        let txn = self.db.begin_write()?;
        {
            let mut metadata = txn
                .open_table(METADATA)?
                .get(0)?
                .map(|v| v.value())
                .unwrap_or_default();
            metadata.binaries_updated_at = date;
            let mut table = txn.open_table(METADATA)?;
            table.insert(0, metadata)?;
        }
        txn.commit()?;
        Ok(())
    }

    pub(crate) async fn set_config_updated_at(&self, date: DateTime<Utc>) -> Result<()> {
        let txn = self.db.begin_write()?;
        {
            let mut metadata = txn
                .open_table(METADATA)?
                .get(0)?
                .map(|v| v.value())
                .unwrap_or_default();
            metadata.config_updated_at = date;
            let mut table = txn.open_table(METADATA)?;
            table.insert(0, metadata)?;
        }
        txn.commit()?;
        Ok(())
    }

    pub(crate) async fn set_default_stack(&self, stack: &Option<String>) -> Result<()> {
        if let Some(stack) = stack {
            self.get_stack(stack).await?;
        }
        let txn = self.db.begin_write()?;
        {
            let mut metadata = txn
                .open_table(METADATA)?
                .get(0)?
                .map(|v| v.value())
                .unwrap_or_default();
            metadata.default_stack = stack.clone();
            let mut table = txn.open_table(METADATA)?;
            table.insert(0, metadata)?;
        }
        txn.commit()?;
        Ok(())
    }

    pub(crate) async fn set_process_pid(
        &self,
        process_name: &str,
        pid: Option<usize>,
    ) -> Result<()> {
        let txn = self.db.begin_write()?;
        {
            let mut process = txn
                .open_table(PROCESS)?
                .get(process_name)?
                .map(|v| v.value())
                .unwrap_or_default();
            process.pid = pid;
            let mut table = txn.open_table(PROCESS)?;
            table.insert(process_name, process)?;
        }
        txn.commit()?;
        Ok(())
    }

    pub(crate) async fn set_process_state(
        &self,
        process_name: &str,
        state: ProcessState,
    ) -> Result<()> {
        let txn = self.db.begin_write()?;
        {
            let mut process = txn
                .open_table(PROCESS)?
                .get(process_name)?
                .map(|v| v.value())
                .unwrap_or_default();
            process.state = state;
            let mut table = txn.open_table(PROCESS)?;
            table.insert(process_name, process)?;
        }
        txn.commit()?;
        Ok(())
    }

    pub(crate) async fn set_processes(&self, processes: &[Process]) -> Result<()> {
        let txn = self.db.begin_write()?;
        {
            txn.delete_table(PROCESS)?;
            let mut table = txn.open_table(PROCESS)?;
            for process in processes {
                table.insert(process.name.as_str(), process)?;
            }
        }
        txn.commit()?;
        Ok(())
    }

    pub(crate) async fn set_stacks(&self, stacks: &[Stack]) -> Result<()> {
        let processes: HashSet<String> = self
            .get_processes()
            .await?
            .iter()
            .map(|p| p.name.to_owned())
            .collect();

        // Lock after getting processes to avoid deadlock
        let txn = self.db.begin_write()?;
        {
            txn.delete_table(STACK)?;
            let mut table = txn.open_table(STACK)?;
            for stack in stacks {
                let stack_processes = stack.processes.iter();
                let inherited_processes = stack.inherited_processes.iter();
                let missing_processes: Vec<String> = stack_processes
                    .clone()
                    .chain(inherited_processes.clone())
                    .filter(|&stack_process| !processes.contains(stack_process))
                    .cloned()
                    .collect();
                if !missing_processes.is_empty() {
                    return Err(Error::new(InnerError::ProcessNotFound(missing_processes)));
                }
                table.insert(stack.name.as_str(), stack)?;
            }
        }
        txn.commit()?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::{collections::HashMap, thread::sleep, time::Duration};

    use tempfile::{tempdir, TempDir};
    use url::Url;

    use super::*;

    #[tokio::test]
    async fn get_set_binaries() {
        let (dir, db) = setup().await.unwrap();
        let base_url = format!("file://{}", dir.path().to_str().unwrap());
        let source_bins = [
            Binary {
                name: "foo".to_owned(),
                id: Url::parse(&format!("{base_url}/foo")).unwrap(),
            },
            Binary {
                name: "bar".to_owned(),
                id: Url::parse(&format!("{base_url}/bar")).unwrap(),
            },
            Binary {
                name: "baz".to_owned(),
                id: Url::parse(&format!("{base_url}/baz")).unwrap(),
            },
        ];

        let bins = db.get_binaries().await.unwrap();
        assert_eq!(bins.len(), 0);

        db.set_binaries(&source_bins[0..1]).await.unwrap();
        let bins = db.get_binaries().await.unwrap();
        assert_eq!(bins.len(), 1);
        assert_eq!(bins[0].name, source_bins[0].name);
        assert_eq!(bins[0].id, source_bins[0].id);

        db.set_binaries(&source_bins[1..2]).await.unwrap();
        let bins = db.get_binaries().await.unwrap();
        assert_eq!(bins.len(), 1);
        assert_eq!(bins[0].name, source_bins[1].name);
        assert_eq!(bins[0].id, source_bins[1].id);

        db.set_binaries(&source_bins).await.unwrap();
        let bins = db.get_binaries().await.unwrap();
        assert_eq!(bins.len(), 3);
        // Test order
        assert_eq!(bins[0].name, source_bins[1].name);
        assert_eq!(bins[0].id, source_bins[1].id);
        assert_eq!(bins[1].name, source_bins[2].name);
        assert_eq!(bins[1].id, source_bins[2].id);
        assert_eq!(bins[2].name, source_bins[0].name);
        assert_eq!(bins[2].id, source_bins[0].id);
    }

    #[tokio::test]
    async fn get_set_binaries_updated_at() {
        let (dir, db) = setup().await.unwrap();

        let date = db.get_binaries_updated_at().await.unwrap();
        assert!(date.is_none());
        sleep(Duration::from_millis(100));

        let now = Utc::now();
        db.set_binaries_updated_at(now).await.unwrap();
        let date = db.get_binaries_updated_at().await.unwrap();
        assert_eq!(date, Some(now));

        drop(dir);
    }

    #[tokio::test]
    async fn get_set_config_updated_at() {
        let (dir, db) = setup().await.unwrap();

        let date = db.get_config_updated_at().await.unwrap();
        assert!(date.is_none());

        let now = Utc::now();
        db.set_config_updated_at(now).await.unwrap();
        let date = db.get_config_updated_at().await.unwrap();
        assert_eq!(date, Some(now));

        drop(dir);
    }

    #[tokio::test]
    async fn get_set_default_stack() {
        let (dir, db) = setup().await.unwrap();

        let stack = db.get_default_stack().await.unwrap();
        assert!(stack.is_none());

        let default_stack = None;
        db.set_default_stack(&default_stack).await.unwrap();
        let stack = db.get_default_stack().await.unwrap();
        assert_eq!(stack, default_stack);

        let default_stack = Some("foo".to_owned());
        let err = db.set_default_stack(&default_stack).await;
        assert!(err.is_err());

        let processes = test_processes();
        db.set_processes(&processes).await.unwrap();
        let stacks = test_stacks();
        db.set_stacks(&stacks).await.unwrap();
        let default_stack = Some("foo".to_owned());
        db.set_default_stack(&default_stack).await.unwrap();
        let stack = db.get_default_stack().await.unwrap();
        assert_eq!(stack, default_stack);

        let default_stack = None;
        db.set_default_stack(&default_stack).await.unwrap();
        let stack = db.get_default_stack().await.unwrap();
        assert_eq!(stack, default_stack);

        drop(dir);
    }

    #[tokio::test]
    async fn get_set_process_properties() {
        let (dir, db) = setup().await.unwrap();

        let processes = db.get_processes().await.unwrap();
        assert!(processes.is_empty());

        let expected_processes = test_processes();
        db.set_processes(&expected_processes).await.unwrap();
        db.set_process_pid(&expected_processes[0].name, Some(42))
            .await
            .unwrap();
        db.set_process_state(&expected_processes[0].name, ProcessState::Building)
            .await
            .unwrap();
        let processes = db.get_processes().await.unwrap();
        assert_eq!(processes.len(), 2);
        assert_eq!(processes[0], expected_processes[1]);
        assert_eq!(processes[1].name, expected_processes[0].name);
        assert_eq!(processes[1].pid(), &Some(42));
        assert_eq!(processes[1].state, ProcessState::Building);

        drop(dir);
    }

    #[tokio::test]
    async fn get_set_processes() {
        let (dir, db) = setup().await.unwrap();

        let processes = db.get_processes().await.unwrap();
        assert!(processes.is_empty());

        let expected_processes = test_processes();
        db.set_processes(&expected_processes).await.unwrap();
        let processes = db.get_processes().await.unwrap();
        assert_eq!(processes.len(), 2);
        assert_eq!(processes[0], expected_processes[1]);
        assert_eq!(processes[1], expected_processes[0]);

        db.set_processes(&expected_processes[1..=1]).await.unwrap();
        let processes = db.get_processes().await.unwrap();
        assert_eq!(processes.len(), 1);
        assert_eq!(processes[0], expected_processes[1]);

        drop(dir);
    }

    #[tokio::test]
    async fn get_set_stacks() {
        let (dir, db) = setup().await.unwrap();

        let stack = db.get_stack("foo").await.unwrap_err();
        assert!(matches!(stack.inner_error, InnerError::StackNotFound(_)));

        let expected_processes = test_processes();
        db.set_processes(&expected_processes).await.unwrap();
        let expected_stacks = test_stacks();
        db.set_stacks(&expected_stacks).await.unwrap();
        let stack = db.get_stack("foo").await.unwrap();
        assert_eq!(&stack.name, "foo");
        assert_eq!(stack.processes, HashSet::from(["bar".to_owned()]));
        assert_eq!(stack.inherited_processes, HashSet::new());
        let stack = db.get_stack("baz").await.unwrap();
        assert_eq!(&stack.name, "baz");
        assert_eq!(stack.processes, HashSet::from(["foo".to_owned()]));
        assert_eq!(stack.inherited_processes, HashSet::from(["bar".to_owned()]));

        db.set_processes(&expected_processes[1..=1]).await.unwrap();
        let processes = db.get_processes().await.unwrap();
        assert_eq!(processes.len(), 1);
        assert_eq!(processes[0], expected_processes[1]);

        drop(dir);
    }

    async fn setup() -> Result<(TempDir, Database)> {
        let dir = tempdir()?;
        let db = Database::new(&dir).await?;
        Ok((dir, db))
    }

    fn test_processes() -> Vec<Process> {
        vec![
            Process {
                name: "foo".to_owned(),
                binary: "foo".to_owned(),
                state: ProcessState::Stopped,
                pid: None,
                args: Vec::new(),
                cargo_args: Vec::new(),
                env: HashMap::new(),
            },
            Process {
                name: "bar".to_owned(),
                binary: "bar".to_owned(),
                state: ProcessState::Stopped,
                pid: None,
                args: Vec::new(),
                cargo_args: Vec::new(),
                env: HashMap::new(),
            },
        ]
    }

    fn test_stacks() -> Vec<Stack> {
        vec![
            Stack {
                name: "foo".to_owned(),
                processes: HashSet::from(["bar".to_owned()]),
                inherited_processes: Default::default(),
            },
            Stack {
                name: "baz".to_owned(),
                processes: HashSet::from(["foo".to_owned()]),
                inherited_processes: HashSet::from(["bar".to_owned()]),
            },
        ]
    }
}