lockbook_server_lib/
debug_info.rs1use crate::ServerError::ClientError;
2use crate::guard::ServerTx;
3use std::fmt::Debug;
4
5use lb_rs::model::{
6 account::BETA_USERS,
7 api::{UpsertDebugInfoError, UpsertDebugInfoRequest},
8 file_metadata::Owner,
9};
10use lb_rs::service::debug::DebugInfo;
11use libsecp256k1::PublicKey;
12use reqwest::multipart;
13use serde_json::json;
14use tracing::{info, warn};
15
16use crate::{
17 RequestContext, ServerError, ServerState,
18 billing::{
19 app_store_client::AppStoreClient, google_play_client::GooglePlayClient,
20 stripe_client::StripeClient,
21 },
22 document_service::DocumentService,
23 schema::ServerV6,
24};
25
26impl<S, A, G, D> ServerState<S, A, G, D>
27where
28 S: StripeClient,
29 A: AppStoreClient,
30 G: GooglePlayClient,
31 D: DocumentService,
32{
33 pub async fn upsert_debug_info(
34 &self, context: RequestContext<UpsertDebugInfoRequest>,
35 ) -> Result<(), ServerError<UpsertDebugInfoError>> {
36 let mut lock = self.index_db.lock().await;
37
38 let mut tx = ServerTx::begin(&mut lock)?;
39 let db = &mut *tx;
40
41 if !Self::is_beta_user::<UpsertDebugInfoError>(db, &context.public_key) {
42 return Err(ClientError(UpsertDebugInfoError::NotPermissioned));
43 }
44
45 let owner = Owner(context.public_key);
46
47 let debug_info = context.request.debug_info.clone();
48 let new_panics_count = debug_info.panics.len();
49
50 let maybe_old_debug_info = db.debug_info.insert(
51 owner,
52 context.request.debug_info.lb_id,
53 context.request.debug_info,
54 )?;
55
56 let old_panics_count =
57 if let Some(debug_info) = maybe_old_debug_info { debug_info.panics.len() } else { 0 };
58
59 if new_panics_count > old_panics_count {
60 if let Some(panic) = debug_info.panics.first() {
61 warn!(?debug_info, "beta user experienced a panic");
62
63 self.send_panic_to_discord(&debug_info, panic).await?;
64 }
65 }
66
67 tx.end()?;
68
69 Ok(())
70 }
71
72 async fn send_panic_to_discord(
73 &self, debug_info: &DebugInfo, panic: &str,
74 ) -> Result<(), ServerError<UpsertDebugInfoError>> {
75 let discord_webhook_url = match &self.config.server.discord_webhook_url {
76 Some(url) => url,
77 None => return Ok(()),
78 };
79
80 let panic_title: String = panic
81 .lines()
82 .next()
83 .unwrap_or_default()
84 .chars()
85 .take(256)
86 .collect();
87
88 let payload = json!({
89 "username": "Panic Reporter",
90 "embeds": [{
91 "color": 14622784,
92 "author": { "name": debug_info.name },
93 "title": panic_title,
94 }]
95 });
96
97 let debug_info_part =
98 multipart::Part::bytes(panic_report_markdown(debug_info)?.into_bytes())
99 .file_name(format!("{}_{}_debug_info.md", debug_info.name, debug_info.panics.len()))
100 .mime_str("text/markdown")?;
101
102 let form = multipart::Form::new()
103 .part("file", debug_info_part)
104 .text("payload_json", payload.to_string());
105
106 let response = self
107 .discord_client
108 .post(discord_webhook_url)
109 .multipart(form)
110 .send()
111 .await?;
112
113 if response.status().is_success() {
114 info!("Notifed discord of a panic!");
115 } else {
116 warn!("Failed to notify discord: {:?} {:?}", response.status(), response.text().await?);
117 }
118 Ok(())
119 }
120
121 pub fn is_beta_user<E: Debug>(db: &ServerV6, public_key: &PublicKey) -> bool {
122 let is_beta = match db.accounts.get(&Owner(*public_key)) {
123 None => false,
124 Some(account) => BETA_USERS.contains(&account.username.as_str()),
125 };
126
127 is_beta
128 }
129}
130
131fn panic_report_markdown(debug_info: &DebugInfo) -> Result<String, serde_json::Error> {
132 let mut summary = serde_json::to_value(debug_info)?;
133 if let Some(fields) = summary.as_object_mut() {
134 fields.remove("panics");
135 }
136
137 let mut report = format!(
138 "# {}'s current debug info\n\n```json\n{}\n```\n",
139 debug_info.name,
140 serde_json::to_string_pretty(&summary)?
141 );
142
143 let count = debug_info.panics.len();
144 for (index, panic) in debug_info.panics.iter().enumerate() {
145 let panic = panic.trim();
146 let (panic, config) = match panic.rsplit_once("\n\n") {
147 Some((rest, config)) if config.starts_with('{') => (rest.trim_end(), Some(config)),
148 _ => (panic, None),
149 };
150 let title = panic.lines().next().unwrap_or_default();
151
152 report += &format!("\n# panic {} - {title}\n\n```\n{panic}\n```\n", count - index);
153 if let Some(config) = config {
154 report += &format!("\n```json\n{config}\n```\n");
155 }
156 }
157
158 Ok(report)
159}