Skip to main content

gear_node_wrapper/
instance.rs

1// Copyright (C) Gear Technologies Inc.
2// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
3
4use crate::Log;
5use anyhow::{Result, anyhow};
6use std::{net::SocketAddrV4, process::Child};
7
8/// The instance of the node
9///
10/// NOTE: This instance should be built from [`Node`](crate::node::Node).
11pub struct NodeInstance {
12    /// RPC address of this node
13    pub address: SocketAddrV4,
14    /// Node log interface
15    pub(crate) log: Log,
16    /// Node process
17    pub(crate) process: Child,
18}
19
20impl NodeInstance {
21    /// Get the RPC address in string.
22    ///
23    /// NOTE: If you want [`SocketAddrV4`], just call [`NodeInstance::address`]
24    pub fn ws(&self) -> String {
25        format!("ws://{}", self.address)
26    }
27
28    /// Get the recent cached node logs, the max limit is 256 lines.
29    pub fn logs(&self) -> Result<Vec<String>> {
30        let Ok(logs) = self.log.logs.read() else {
31            return Err(anyhow!("Failed to read logs from the node process."));
32        };
33
34        Ok(logs.clone().into_vec())
35    }
36}
37
38impl Drop for NodeInstance {
39    fn drop(&mut self) {
40        self.process.kill().expect("Unable to kill node process.")
41    }
42}