1use crate::Lb;
2use crate::io::docs::LocalDocuments;
3use crate::io::server::Server;
4use crate::model::clock;
5use crate::model::core_config::Config;
6use crate::model::errors::LbResult;
7use crate::service::lb_id::LbID;
8use basic_human_duration::ChronoHumanDuration;
9use chrono::NaiveDateTime;
10use serde::{Deserialize, Serialize};
11use std::path::PathBuf;
12use time::Duration;
13
14#[cfg(not(target_family = "wasm"))]
15use std::path::Path;
16
17#[cfg(not(target_family = "wasm"))]
18use std::env;
19
20#[cfg(not(target_family = "wasm"))]
21use chrono::{DateTime, Local, TimeZone};
22
23#[cfg(not(target_family = "wasm"))]
24use tokio::fs::{self, OpenOptions};
25
26#[cfg(not(target_family = "wasm"))]
27use tokio::io::AsyncWriteExt;
28
29#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
30pub struct DebugInfo {
31 pub lb_id: LbID,
32 pub time: String,
33 pub name: String,
34 pub last_synced: String,
35 pub lb_version: String,
36 pub rust_triple: String,
37 pub os_info: String,
38 pub lb_dir: String,
39 pub server_url: String,
40 pub integrity: String,
41 pub is_syncing: bool,
42 pub status: String,
43 pub panics: Vec<String>,
44}
45
46pub trait DebugInfoDisplay {
47 fn to_string(&self) -> String;
48}
49
50impl DebugInfoDisplay for LbResult<DebugInfo> {
51 fn to_string(&self) -> String {
52 match self {
53 Ok(debug_info) => serde_json::to_string_pretty(debug_info).unwrap_or_default(),
54 Err(err) => format!("Error retrieving debug info: {:?}", err),
55 }
56 }
57}
58
59impl<S: Server, D: LocalDocuments> Lb<S, D> {
60 async fn human_last_synced(&self) -> String {
61 let tx = self.ro_tx().await;
62 let db = tx.db();
63
64 let last_synced = *db.last_synced.as_ref().unwrap_or(&0);
65
66 if last_synced != 0 {
67 Duration::milliseconds(clock::get_time().0 - last_synced)
68 .format_human()
69 .to_string()
70 } else {
71 "never".to_string()
72 }
73 }
74
75 async fn lb_id(&self) -> LbResult<LbID> {
76 let mut tx = self.begin_tx().await;
77 let db = tx.db();
78
79 let lb_id = if let Some(id) = db.id.as_ref().copied() {
80 id
81 } else {
82 let new_id = LbID::generate();
83 db.id.replace(new_id)?;
84 new_id
85 };
86
87 tx.end();
88
89 Ok(lb_id)
90 }
91
92 fn now(&self) -> String {
93 let now = chrono::Local::now();
94 now.format("%Y-%m-%d %H:%M:%S %Z").to_string()
95 }
96
97 #[cfg(not(target_family = "wasm"))]
98 async fn collect_panics(&self, populate_content: bool) -> LbResult<Vec<PanicInfo>> {
99 let mut panics = vec![];
100 let mut iter = iter_panic_files(&self.config.writeable_path).await?;
101 while let Some(entry) = iter.next().await? {
102 let content = if populate_content { entry.content().await? } else { String::new() };
103 panics.push(PanicInfo { time: entry.time, file_path: entry.file_path, content });
104 }
105 panics.sort_by_key(|panic| std::cmp::Reverse(panic.time));
106
107 Ok(panics)
108 }
109
110 #[cfg(not(target_family = "wasm"))]
112 pub async fn recent_panic(&self) -> LbResult<Option<DateTime<Local>>> {
113 let panics = self.collect_panics(false).await?;
114 Ok(panics
115 .first()
116 .and_then(|panic| Local.from_local_datetime(&panic.time).single()))
117 }
118
119 #[instrument(level = "debug", skip(self), err(Debug))]
120 #[cfg(not(target_family = "wasm"))]
121 pub async fn write_panic_to_file(&self, error_header: String, bt: String) -> LbResult<String> {
122 let file_name = generate_panic_filename(&self.config.writeable_path);
123 let content = generate_panic_content(&self.config, &error_header, &bt);
124
125 let mut file = OpenOptions::new()
126 .create(true)
127 .append(true)
128 .open(&file_name)
129 .await?;
130
131 file.write_all(content.as_bytes()).await?;
132
133 Ok(file_name)
134 }
135
136 #[instrument(level = "debug", skip(self), err(Debug))]
137 #[cfg(not(target_family = "wasm"))]
138 pub async fn debug_info(&self, check_docs: bool) -> LbResult<DebugInfo> {
139 let account = self.get_account()?;
140
141 let arch = env::consts::ARCH;
142 let os = env::consts::OS;
143 let family = env::consts::FAMILY;
144
145 let (integrity, last_synced, panics, lb_id) = tokio::join!(
146 self.test_repo_integrity(check_docs),
147 self.human_last_synced(),
148 self.collect_panics(true),
149 self.lb_id()
150 );
151
152 let panics = panics?.into_iter().map(|panic| panic.content).collect();
153
154 let status = self.status().await;
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}