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
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use anyhow::{bail, Result};
use linera_base::{command::CommandExt, time::Duration};
use tokio::process::{Child, Command};

use crate::client::{storage_service_check_absence, storage_service_check_validity};

/// Configuration for a storage service running as a child process
pub struct StorageService {
    endpoint: String,
    binary: String,
}

/// A storage service running as a child process.
///
/// The guard preserves the child from destruction and destroys it when
/// it drops out of scope.
pub struct StorageServiceGuard {
    _child: Child,
}

impl StorageService {
    /// Creates a new `StorageServiceChild`
    pub fn new(endpoint: &str, binary: String) -> Self {
        Self {
            endpoint: endpoint.to_string(),
            binary,
        }
    }

    async fn command(&self) -> Command {
        let mut command = Command::new(&self.binary);
        command.args(["memory", "--endpoint", &self.endpoint]);
        command.kill_on_drop(true);
        command
    }

    /// Waits for the absence of the endpoint. If a child is terminated
    /// then it might take time to wait for its absence.
    async fn wait_for_absence(&self) -> Result<()> {
        for i in 1..10 {
            if storage_service_check_absence(&self.endpoint).await? {
                return Ok(());
            }
            linera_base::time::timer::sleep(Duration::from_secs(i)).await;
        }
        bail!("Failed to start child server");
    }

    pub async fn run(&self) -> Result<StorageServiceGuard> {
        self.wait_for_absence().await?;
        let mut command = self.command().await;
        let _child = command.spawn_into()?;
        let guard = StorageServiceGuard { _child };
        // We iterate until the child is spawned and can be accessed.
        // We add an additional waiting period to avoid problems.
        for i in 1..10 {
            let result = storage_service_check_validity(&self.endpoint).await;
            if result.is_ok() {
                return Ok(guard);
            }
            linera_base::time::timer::sleep(Duration::from_secs(i)).await;
        }
        bail!("Failed to start child server");
    }
}