1use crate::Lb;
2use crate::io::server::Server;
3use crate::model::clock;
4use crate::model::core_config::Config;
5use crate::model::errors::LbResult;
6use crate::service::lb_id::LbID;
7use basic_human_duration::ChronoHumanDuration;
8use chrono::NaiveDateTime;
9use serde::{Deserialize, Serialize};
10use std::path::PathBuf;
11use time::Duration;
12
13#[cfg(not(target_family = "wasm"))]
14use std::path::Path;
15
16#[cfg(not(target_family = "wasm"))]
17use std::env;
18
19#[cfg(not(target_family = "wasm"))]
20use chrono::{DateTime, Local, TimeZone};
21
22#[cfg(not(target_family = "wasm"))]
23use tokio::fs::{self, OpenOptions};
24
25#[cfg(not(target_family = "wasm"))]
26use tokio::io::AsyncWriteExt;
27
28#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
29pub struct DebugInfo {
30 pub lb_id: LbID,
31 pub time: String,
32 pub name: String,
33 pub last_synced: String,
34 pub lb_version: String,
35 pub rust_triple: String,
36 pub os_info: String,
37 pub lb_dir: String,
38 pub server_url: String,
39 pub integrity: String,
40 pub is_syncing: bool,
41 pub status: String,
42 pub panics: Vec<String>,
43}
44
45pub trait DebugInfoDisplay {
46 fn to_string(&self) -> String;
47}
48
49impl DebugInfoDisplay for LbResult<DebugInfo> {
50 fn to_string(&self) -> String {
51 match self {
52 Ok(debug_info) => serde_json::to_string_pretty(debug_info).unwrap_or_default(),
53 Err(err) => format!("Error retrieving debug info: {:?}", err),
54 }
55 }
56}
57
58impl<S: Server> Lb<S> {
59 async fn human_last_synced(&self) -> String {
60 let tx = self.ro_tx().await;
61 let db = tx.db();
62
63 let last_synced = *db.last_synced.as_ref().unwrap_or(&0);
64
65 if last_synced != 0 {
66 Duration::milliseconds(clock::get_time().0 - last_synced)
67 .format_human()
68 .to_string()
69 } else {
70 "never".to_string()
71 }
72 }
73
74 async fn lb_id(&self) -> LbResult<LbID> {
75 let mut tx = self.begin_tx().await;
76 let db = tx.db();
77
78 let lb_id = if let Some(id) = db.id.as_ref().copied() {
79 id
80 } else {
81 let new_id = LbID::generate();
82 db.id.replace(new_id)?;
83 new_id
84 };
85
86 tx.end();
87
88 Ok(lb_id)
89 }
90
91 fn now(&self) -> String {
92 let now = chrono::Local::now();
93 now.format("%Y-%m-%d %H:%M:%S %Z").to_string()
94 }
95
96 #[cfg(not(target_family = "wasm"))]
97 async fn collect_panics(&self, populate_content: bool) -> LbResult<Vec<PanicInfo>> {
98 let mut panics = vec![];
99 let mut iter = iter_panic_files(&self.config.writeable_path).await?;
100 while let Some(entry) = iter.next().await? {
101 let content = if populate_content { entry.content().await? } else { String::new() };
102 panics.push(PanicInfo { time: entry.time, file_path: entry.file_path, content });
103 }
104 panics.sort_by_key(|panic| std::cmp::Reverse(panic.time));
105
106 Ok(panics)
107 }
108
109 #[cfg(not(target_family = "wasm"))]
111 pub async fn recent_panic(&self) -> LbResult<Option<DateTime<Local>>> {
112 let panics = self.collect_panics(false).await?;
113 Ok(panics
114 .first()
115 .and_then(|panic| Local.from_local_datetime(&panic.time).single()))
116 }
117
118 #[instrument(level = "debug", skip(self), err(Debug))]
119 #[cfg(not(target_family = "wasm"))]
120 pub async fn write_panic_to_file(&self, error_header: String, bt: String) -> LbResult<String> {
121 let file_name = generate_panic_filename(&self.config.writeable_path);
122 let content = generate_panic_content(&self.config, &error_header, &bt);
123
124 let mut file = OpenOptions::new()
125 .create(true)
126 .append(true)
127 .open(&file_name)
128 .await?;
129
130 file.write_all(content.as_bytes()).await?;
131
132 Ok(file_name)
133 }
134
135 #[instrument(level = "debug", skip(self), err(Debug))]
136 #[cfg(not(target_family = "wasm"))]
137 pub async fn debug_info(&self, check_docs: bool) -> LbResult<DebugInfo> {
138 let account = self.get_account()?;
139
140 let arch = env::consts::ARCH;
141 let os = env::consts::OS;
142 let family = env::consts::FAMILY;
143
144 let (integrity, last_synced, panics, lb_id) = tokio::join!(
145 self.test_repo_integrity(check_docs),
146 self.human_last_synced(),
147 self.collect_panics(true),
148 self.lb_id()
149 );
150
151 let panics = panics?.into_iter().map(|panic| panic.content).collect();
152
153 let mut status = self.status().await;
154 status.space_used = None;
155 let status = format!("{status:?}");
156 let is_syncing = self.syncer.try_lock().is_err();
157
158 Ok(DebugInfo {
159 time: self.now(),
160 name: account.username.clone(),
161 lb_version: self.config.lb_version.clone(),
162 lb_id: lb_id?,
163 rust_triple: format!("{arch}.{family}.{os}"),
164 server_url: account.api_url.clone(),
165 integrity: format!(
166 "{} {integrity:?}",
167 if check_docs { "" } else { "doc checks skipped" }
168 ),
169 lb_dir: self.config.writeable_path.clone(),
170 last_synced,
171 os_info: self.config.os_version.clone().unwrap_or_default(),
172 status,
173 is_syncing,
174 panics,
175 })
176 }
177}
178
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct PanicInfo {
181 pub time: NaiveDateTime,
182 pub file_path: PathBuf,
183 pub content: String,
184}
185
186#[cfg(not(target_family = "wasm"))]
187pub struct PanicFiles {
188 entries: tokio::fs::ReadDir,
189 base_path: PathBuf,
190}
191
192#[cfg(not(target_family = "wasm"))]
193pub struct PanicFile {
194 pub time: NaiveDateTime,
195 pub file_path: PathBuf,
196}
197
198#[cfg(not(target_family = "wasm"))]
199impl PanicFiles {
200 pub async fn next(&mut self) -> LbResult<Option<PanicFile>> {
201 const PREFIX: &str = "panic---";
202 const SUFFIX: &str = ".log";
203 const TIMESTAMP_FORMAT: &str = "%Y-%m-%d---%H-%M-%S";
204
205 while let Some(entry) = self.entries.next_entry().await? {
206 let file_name = entry.file_name().into_string().unwrap_or_default();
207 if !file_name.starts_with(PREFIX) || !file_name.ends_with(SUFFIX) {
208 continue;
209 }
210 let timestamp_str = &file_name[PREFIX.len()..file_name.len() - SUFFIX.len()];
211 let Ok(time) = NaiveDateTime::parse_from_str(timestamp_str, TIMESTAMP_FORMAT) else {
212 continue;
213 };
214 let file_path = self.base_path.join(file_name);
215 return Ok(Some(PanicFile { time, file_path }));
216 }
217 Ok(None)
218 }
219}
220
221#[cfg(not(target_family = "wasm"))]
222impl PanicFile {
223 pub async fn content(&self) -> LbResult<String> {
224 Ok(fs::read_to_string(&self.file_path).await?)
225 }
226}
227
228#[cfg(not(target_family = "wasm"))]
229pub(crate) async fn iter_panic_files(path: &str) -> LbResult<PanicFiles> {
230 let base_path = Path::new(path).to_path_buf();
231 let entries = fs::read_dir(&base_path).await?;
232 Ok(PanicFiles { entries, base_path })
233}
234
235#[cfg(not(target_family = "wasm"))]
237pub(crate) async fn latest_panic_time(path: &str) -> LbResult<Option<i64>> {
238 let mut iter = iter_panic_files(path).await?;
239 let mut max: Option<i64> = None;
240 while let Some(entry) = iter.next().await? {
241 let new_ts = entry.time.and_utc().timestamp_millis();
242 match &mut max {
243 Some(ts) => {
244 if new_ts > *ts {
245 *ts = new_ts;
246 }
247 }
248 None => max = Some(new_ts),
249 }
250 }
251 Ok(max)
252}
253
254pub fn generate_panic_filename(path: &str) -> String {
255 let timestamp = chrono::Local::now().format("%Y-%m-%d---%H-%M-%S");
256 format!("{path}/panic---{timestamp}.log")
257}
258
259pub fn generate_panic_content(config: &Config, panic_info: &str, bt: &str) -> String {
260 let version = &config.lb_version;
261 let time = chrono::Local::now().format("%Y-%m-%d %H:%M:%S %Z");
262 let config = serde_json::to_string_pretty(config).unwrap_or_default();
263 format!("{version} panicked at {panic_info}\n\ntime: {time}\n\n{}\n\n{config}\n", bt.trim_end())
264}