1use crate::{
2 process::Process,
3 trust::{unix_now, TrustChain},
4 RigError,
5};
6use serde_json::json;
7use std::{
8 collections::BTreeSet,
9 path::PathBuf,
10 process::{Command, Stdio},
11 time::{Duration, Instant},
12};
13use tokio::{
14 io::{AsyncReadExt, AsyncWriteExt},
15 net::TcpStream,
16};
17
18pub const LOOPBACK: &str = "127.0.0.1";
19
20pub struct PreloadedAccount {
22 pub public_key: String,
23 pub signing_keys: Vec<String>,
24}
25
26pub struct BusOptions {
27 pub binary: Option<PathBuf>,
29 pub directory: Option<PathBuf>,
31 pub trust: Option<TrustChain>,
32 pub preload: Vec<PreloadedAccount>,
33 pub startup_timeout: Duration,
34}
35
36impl Default for BusOptions {
37 fn default() -> Self {
38 Self {
39 binary: None,
40 directory: None,
41 trust: None,
42 preload: vec![],
43 startup_timeout: Duration::from_secs(20),
44 }
45 }
46}
47
48pub struct BusServer {
49 child: Process,
51 _temporary: Option<tempfile::TempDir>,
52 pub dir: PathBuf,
53 pub url: String,
54 pub port: u16,
55 pub listen_host: String,
56 pub log: PathBuf,
57 pub operator_jwt: PathBuf,
58 pub system_account: String,
59 pub trust: TrustChain,
60 pub version: String,
61}
62
63impl BusServer {
64 pub async fn start(options: BusOptions) -> Result<Self, RigError> {
65 let (bin, version) = match options.binary {
66 Some(path) => crate::binaries::checked_nats(path)?,
67 None => crate::nats_server_bin()?,
68 };
69 let temporary = if options.directory.is_none() {
70 Some(tempfile::tempdir()?)
71 } else {
72 None
73 };
74 let dir = options
75 .directory
76 .unwrap_or_else(|| temporary.as_ref().unwrap().path().to_path_buf());
77 std::fs::create_dir_all(dir.join("jwt"))?;
78 let dir = dir.canonicalize()?;
79 let trust = options.trust.unwrap_or_else(TrustChain::generate);
80 let operator_jwt = dir.join("operator.jwt");
81 std::fs::write(&operator_jwt, trust.operator_jwt())?;
82 let port = free_port()?;
83 let mut http_port = free_port()?;
84 while http_port == port {
85 http_port = free_port()?;
86 }
87 let log = dir.join("server.log");
88 let mut preload = format!(
89 "{}: {}\n",
90 trust.system_account,
91 json!(trust.system_account_jwt())
92 );
93 for account in options.preload {
94 let jwt = trust.account_jwt(&account.public_key, &account.signing_keys);
95 preload.push_str(&format!("{}: {}\n", account.public_key, json!(jwt)));
96 }
97 let conf = format!(
100 "listen: \"127.0.0.1:{port}\"\n\
101 max_control_line: 65536\ndebug: true\n\
102 http: \"127.0.0.1:{http_port}\"\n\
103 log_file: {log}\njetstream {{ store_dir: {js} }}\n\
104 operator: {operator}\nsystem_account: {system}\n\
105 resolver {{ type: full, dir: {jwt}, allow_delete: false, interval: \"2m\" }}\n\
106 resolver_preload {{\n{preload}}}\n",
107 log = json!(log),
108 js = json!(dir.join("js")),
109 operator = json!(operator_jwt),
110 system = json!(trust.system_account),
111 jwt = json!(dir.join("jwt")),
112 );
113 let conf_path = dir.join("server.conf");
114 std::fs::write(&conf_path, conf)?;
115 let child = Process(
116 Command::new(bin)
117 .arg("-c")
118 .arg(conf_path)
119 .env("XDG_DATA_HOME", dir.join("data"))
120 .env("XDG_RUNTIME_DIR", dir.join("run"))
121 .env("XDG_CONFIG_HOME", dir.join("config"))
122 .stdout(Stdio::null())
123 .stderr(Stdio::null())
124 .spawn()?,
125 );
126 let mut server = Self {
127 child,
128 _temporary: temporary,
129 dir,
130 url: format!("nats://127.0.0.1:{port}"),
131 port,
132 listen_host: LOOPBACK.to_string(),
133 log,
134 operator_jwt,
135 system_account: trust.system_account.clone(),
136 trust,
137 version,
138 };
139 let deadline = Instant::now() + options.startup_timeout;
140 loop {
141 if let Some(status) = server.child.0.try_wait()? {
142 return Err(RigError::Invalid(format!(
143 "nats-server exited {status}: {}",
144 server.log_text()
145 )));
146 }
147 if tokio::time::timeout(Duration::from_millis(500), healthz(http_port))
148 .await
149 .unwrap_or(false)
150 {
151 break;
152 }
153 if Instant::now() >= deadline {
154 return Err(RigError::Timeout {
155 waiting_for: "NATS /healthz".into(),
156 details: server.log_text(),
157 });
158 }
159 tokio::time::sleep(Duration::from_millis(50)).await;
160 }
161 Ok(server)
162 }
163
164 pub fn pid(&self) -> u32 {
165 self.child.0.id()
166 }
167
168 pub fn ckbus_env(&self) -> Vec<(String, String)> {
170 vec![
171 ("CKBUS_NATS_URL".into(), self.url.clone()),
172 (
173 "CKBUS_OPERATOR_JWT".into(),
174 self.operator_jwt.display().to_string(),
175 ),
176 ("CKBUS_SYSTEM_ACCOUNT".into(), self.system_account.clone()),
177 ]
178 }
179
180 pub fn stored_accounts(&self) -> BTreeSet<String> {
181 std::fs::read_dir(self.dir.join("jwt"))
182 .into_iter()
183 .flatten()
184 .filter_map(Result::ok)
185 .filter_map(|entry| {
186 entry
187 .file_name()
188 .to_str()
189 .and_then(|name| name.strip_suffix(".jwt"))
190 .map(str::to_string)
191 })
192 .collect()
193 }
194 pub fn log_text(&self) -> String {
195 std::fs::read_to_string(&self.log).unwrap_or_default()
196 }
197 pub async fn stop(self) {
198 drop(self);
199 }
200}
201
202fn free_port() -> Result<u16, RigError> {
203 Ok(std::net::TcpListener::bind((LOOPBACK, 0))?
204 .local_addr()?
205 .port())
206}
207
208async fn healthz(port: u16) -> bool {
209 let Ok(mut stream) = TcpStream::connect((LOOPBACK, port)).await else {
210 return false;
211 };
212 if stream
213 .write_all(b"GET /healthz HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n")
214 .await
215 .is_err()
216 {
217 return false;
218 }
219 let mut buf = Vec::new();
220 stream.read_to_end(&mut buf).await.is_ok() && String::from_utf8_lossy(&buf).contains("\"ok\"")
221}
222
223impl TrustChain {
224 pub(crate) fn account_jwt(&self, public_key: &str, signing_keys: &[String]) -> String {
225 crate::trust::encode_jwt(
226 &self.operator_root,
227 public_key,
228 "fixture-account",
229 unix_now() - 120,
230 json!({"type": "account", "version": 2,
231 "limits": {"subs": -1, "data": -1, "payload": -1, "imports": -1, "exports": -1,
232 "wildcards": true, "conn": -1, "leaf": -1},
233 "signing_keys": signing_keys, "default_permissions": {"pub": {}, "sub": {}}}),
234 )
235 }
236}