gear_node_wrapper/instance.rs
1// This file is part of Gear.
2//
3// Copyright (C) 2024-2025 Gear Technologies Inc.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5//
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10//
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15//
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19use crate::Log;
20use anyhow::{Result, anyhow};
21use std::{net::SocketAddrV4, process::Child};
22
23/// The instance of the node
24///
25/// NOTE: This instance should be built from [`Node`](crate::node::Node).
26pub struct NodeInstance {
27 /// RPC address of this node
28 pub address: SocketAddrV4,
29 /// Node log interface
30 pub(crate) log: Log,
31 /// Node process
32 pub(crate) process: Child,
33}
34
35impl NodeInstance {
36 /// Get the RPC address in string.
37 ///
38 /// NOTE: If you want [`SocketAddrV4`], just call [`NodeInstance::address`]
39 pub fn ws(&self) -> String {
40 format!("ws://{}", self.address)
41 }
42
43 /// Get the recent cached node logs, the max limit is 256 lines.
44 pub fn logs(&self) -> Result<Vec<String>> {
45 let Ok(logs) = self.log.logs.read() else {
46 return Err(anyhow!("Failed to read logs from the node process."));
47 };
48
49 Ok(logs.clone().into_vec())
50 }
51}
52
53impl Drop for NodeInstance {
54 fn drop(&mut self) {
55 self.process.kill().expect("Unable to kill node process.")
56 }
57}