Skip to main content

lockbook_server_lib/
metrics.rs

1use crate::billing::app_store_client::AppStoreClient;
2use crate::billing::billing_model::{BillingPlatform, SubscriptionProfile};
3use crate::billing::google_play_client::GooglePlayClient;
4use crate::billing::stripe_client::StripeClient;
5use crate::document_service::DocumentService;
6use crate::guard::ServerTx;
7use crate::schema::ServerV6;
8use crate::{ServerError, ServerState};
9use lazy_static::lazy_static;
10use lb_rs::model::clock::get_time;
11use lb_rs::model::file_like::FileLike;
12use lb_rs::model::file_metadata::Owner;
13use lb_rs::model::server_tree::ServerTree;
14use lb_rs::model::tree_like::TreeLike;
15use prometheus::{IntGaugeVec, register_int_gauge_vec};
16use prometheus_static_metric::make_static_metric;
17use std::collections::HashMap;
18use std::fmt::Debug;
19use tracing::*;
20
21pub struct UserInfo {
22    account_age: i64,
23    total_documents: i64,
24    total_bytes: i64,
25    total_egress: i64,
26    is_user_active: bool,
27    is_user_active_v2: bool,
28    is_user_sharer_or_sharee: bool,
29}
30
31make_static_metric! {
32    pub struct MetricsStatistics: IntGauge {
33        "type" => {
34            total_users,
35            share_feature_users,
36            premium_users,
37            active_users,
38            deleted_users,
39            total_documents,
40            total_document_bytes,
41            total_egress_bytes,
42        },
43    }
44}
45
46lazy_static! {
47    pub static ref METRICS_COUNTERS_VEC: IntGaugeVec = register_int_gauge_vec!(
48        "lockbook_metrics_counters",
49        "Lockbook's basic metrics of users and files derived from redis",
50        &["type"]
51    )
52    .unwrap();
53    pub static ref METRICS_STATISTICS: MetricsStatistics =
54        MetricsStatistics::from(&METRICS_COUNTERS_VEC);
55    pub static ref METRICS_USAGE_BY_USER_VEC: IntGaugeVec = register_int_gauge_vec!(
56        "lockbook_metrics_usage_by_user",
57        "Lockbook's total usage by user",
58        &["username"]
59    )
60    .unwrap();
61    pub static ref ACTIVITY_BY_USER: IntGaugeVec = register_int_gauge_vec!(
62        "lockbook_activity_by_user",
63        "Lockbook's active users",
64        &["username"]
65    )
66    .unwrap();
67    pub static ref EGRESS_BY_USER: IntGaugeVec = register_int_gauge_vec!(
68        "lockbook_egress_by_user",
69        "Lockbook's egress by user",
70        &["username"]
71    )
72    .unwrap();
73    pub static ref AGE_BY_USER: IntGaugeVec =
74        register_int_gauge_vec!("lockbook_age_by_user", "Lockbook's account ages", &["username"])
75            .unwrap();
76    pub static ref METRICS_PREMIUM_USERS_BY_PAYMENT_PLATFORM_VEC: IntGaugeVec =
77        register_int_gauge_vec!(
78            "lockbook_premium_users_by_payment_platform",
79            "Lockbook's total number of premium users by payment platform",
80            &["platform"]
81        )
82        .unwrap();
83}
84
85const STRIPE_LABEL_NAME: &str = "stripe";
86const GOOGLE_PLAY_LABEL_NAME: &str = "google-play";
87const APP_STORE_LABEL_NAME: &str = "app-store";
88
89#[derive(Debug)]
90pub enum MetricsError {}
91
92const TWO_DAYS_IN_MILLIS: u128 = 1000 * 60 * 60 * 24 * 2;
93const TWO_HOURS_IN_MILLIS: u128 = 1000 * 60 * 60;
94
95impl<S, A, G, D> ServerState<S, A, G, D>
96where
97    S: StripeClient,
98    A: AppStoreClient,
99    G: GooglePlayClient,
100    D: DocumentService,
101{
102    pub fn start_metrics_worker(&self) {
103        let state_clone = self.clone();
104
105        tokio::spawn(async move {
106            info!("Started capturing metrics");
107
108            if let Err(e) = state_clone.start_metrics_loop().await {
109                error!("interrupting metrics loop due to error: {:?}", e)
110            }
111        });
112    }
113
114    pub async fn start_metrics_loop(self) -> Result<(), ServerError<MetricsError>> {
115        loop {
116            info!("Metrics refresh started");
117
118            let public_keys_and_usernames = self
119                .index_db
120                .lock()
121                .await
122                .schema
123                .usernames
124                .iter()
125                .map(|(key, value)| (key.clone(), *value))
126                .collect::<HashMap<_, _>>();
127            let server_wide_egress = self
128                .index_db
129                .lock()
130                .await
131                .schema
132                .server_egress
133                .as_ref()
134                .map(|total| total.all_bandwidth())
135                .unwrap_or_default();
136
137            let total_users_ever = public_keys_and_usernames.len() as i64;
138            let mut total_documents = 0;
139            let mut total_bytes = 0;
140            let mut active_users = 0;
141            let mut deleted_users = 0;
142            let mut share_feature_users = 0;
143            let mut other_usage = 0;
144            let mut other_egress = 0;
145
146            let mut premium_users = 0;
147            let mut premium_stripe_users = 0;
148            let mut premium_google_play_users = 0;
149            let mut premium_app_store_users = 0;
150
151            for (username, owner) in public_keys_and_usernames {
152                {
153                    let mut guard = self.index_db.lock().await;
154                    let mut tx = ServerTx::begin(&mut guard)?;
155                    let db = &mut *tx;
156                    let maybe_user_info = Self::get_user_info(db, owner)?;
157
158                    let user_info = match maybe_user_info {
159                        None => {
160                            deleted_users += 1;
161                            let _ = METRICS_USAGE_BY_USER_VEC.remove_label_values(&[&username]);
162                            let _ = EGRESS_BY_USER.remove_label_values(&[&username]);
163                            let _ = ACTIVITY_BY_USER.remove_label_values(&[&username]);
164                            let _ = AGE_BY_USER.remove_label_values(&[&username]);
165                            continue;
166                        }
167                        Some(user_info) => user_info,
168                    };
169
170                    if user_info.is_user_active {
171                        active_users += 1;
172                    }
173                    if user_info.is_user_sharer_or_sharee {
174                        share_feature_users += 1;
175                    }
176
177                    total_documents += user_info.total_documents;
178                    total_bytes += user_info.total_bytes;
179
180                    if user_info.total_bytes > 50_000 {
181                        METRICS_USAGE_BY_USER_VEC
182                            .with_label_values(&[&username])
183                            .set(user_info.total_bytes);
184                    } else {
185                        other_usage += user_info.total_bytes;
186                    }
187
188                    if user_info.total_egress > 100_000 {
189                        EGRESS_BY_USER
190                            .with_label_values(&[&username])
191                            .set(user_info.total_egress);
192                    } else {
193                        other_egress += user_info.total_egress;
194                    }
195
196                    ACTIVITY_BY_USER
197                        .with_label_values(&[&username])
198                        .set(if user_info.is_user_active_v2 { 1 } else { 0 });
199
200                    AGE_BY_USER
201                        .with_label_values(&[&username])
202                        .set(user_info.account_age);
203
204                    let billing_info = Self::get_user_billing_info(db, &owner)?;
205
206                    if billing_info.is_premium() {
207                        premium_users += 1;
208
209                        match billing_info.billing_platform {
210                            None => {
211                                return Err(internal!(
212                                    "Could not retrieve billing platform although it was used moments before."
213                                ));
214                            }
215                            Some(billing_platform) => match billing_platform {
216                                BillingPlatform::GooglePlay { .. } => {
217                                    premium_google_play_users += 1
218                                }
219                                BillingPlatform::Stripe { .. } => premium_stripe_users += 1,
220                                BillingPlatform::AppStore { .. } => premium_app_store_users += 1,
221                            },
222                        }
223                    }
224                    tx.end()?;
225                }
226
227                tokio::time::sleep(self.config.metrics.time_between_metrics).await;
228            }
229            METRICS_USAGE_BY_USER_VEC
230                .with_label_values(&["OTHER"])
231                .set(other_usage);
232            EGRESS_BY_USER
233                .with_label_values(&["OTHER"])
234                .set(other_egress);
235
236            METRICS_STATISTICS
237                .total_users
238                .set(total_users_ever - deleted_users);
239
240            METRICS_STATISTICS.total_documents.set(total_documents);
241            METRICS_STATISTICS.active_users.set(active_users);
242            METRICS_STATISTICS.deleted_users.set(deleted_users);
243            METRICS_STATISTICS.total_document_bytes.set(total_bytes);
244            METRICS_STATISTICS
245                .total_egress_bytes
246                .set(server_wide_egress as i64);
247            METRICS_STATISTICS
248                .share_feature_users
249                .set(share_feature_users);
250            METRICS_STATISTICS.premium_users.set(premium_users);
251
252            METRICS_PREMIUM_USERS_BY_PAYMENT_PLATFORM_VEC
253                .with_label_values(&[STRIPE_LABEL_NAME])
254                .set(premium_stripe_users);
255            METRICS_PREMIUM_USERS_BY_PAYMENT_PLATFORM_VEC
256                .with_label_values(&[GOOGLE_PLAY_LABEL_NAME])
257                .set(premium_google_play_users);
258            METRICS_PREMIUM_USERS_BY_PAYMENT_PLATFORM_VEC
259                .with_label_values(&[APP_STORE_LABEL_NAME])
260                .set(premium_app_store_users);
261
262            info!("metrics refresh finished");
263            tokio::time::sleep(self.config.metrics.time_between_metrics_refresh).await;
264        }
265    }
266    pub fn get_user_billing_info(
267        db: &ServerV6, owner: &Owner,
268    ) -> Result<SubscriptionProfile, ServerError<MetricsError>> {
269        let account = db
270            .accounts
271            .get(owner)
272            .ok_or_else(|| internal!("Could not get user's account during metrics {:?}", owner))?;
273
274        Ok(account.billing_info.clone())
275    }
276
277    pub fn get_user_info(
278        db: &mut ServerV6, owner: Owner,
279    ) -> Result<Option<UserInfo>, ServerError<MetricsError>> {
280        if db.owned_files.get(&owner).is_none() {
281            return Ok(None);
282        }
283
284        let mut tree = ServerTree::new(
285            owner,
286            &mut db.owned_files,
287            &mut db.shared_files,
288            &mut db.file_children,
289            &mut db.file_attachments,
290            &mut db.metas,
291        )?
292        .to_lazy();
293
294        let mut ids = Vec::new();
295
296        for id in tree.ids() {
297            if !tree.calculate_deleted(&id)? {
298                ids.push(id);
299            }
300        }
301
302        let is_user_sharer_or_sharee = tree
303            .all_files()?
304            .iter()
305            .any(|k| k.owner() != owner || k.is_shared());
306
307        let root_creation_timestamp =
308            if let Some(root_creation_timestamp) = tree.all_files()?.iter().find(|f| f.is_root()) {
309                root_creation_timestamp.file.timestamped_value.timestamp
310            } else {
311                return Ok(None);
312            };
313
314        let account_age = get_time().0 - root_creation_timestamp;
315
316        let last_seen = *db
317            .last_seen
318            .get(&owner)
319            .unwrap_or(&(root_creation_timestamp as u64));
320
321        let total_egress = db
322            .egress_by_owner
323            .get(&owner)
324            .cloned()
325            .unwrap_or_default()
326            .all_bandwidth() as i64;
327
328        let time_two_days_ago = get_time().0 as u64 - TWO_DAYS_IN_MILLIS as u64;
329        let last_seen_since_account_creation = last_seen as i64 - root_creation_timestamp;
330        let delay_buffer_time = 5000;
331        let not_the_welcome_doc = last_seen_since_account_creation > delay_buffer_time;
332        let is_user_active = not_the_welcome_doc && last_seen > time_two_days_ago;
333        let time_one_hour_ago = get_time().0 as u64 - TWO_HOURS_IN_MILLIS as u64;
334        let is_user_active_v2 = not_the_welcome_doc && last_seen > time_one_hour_ago;
335
336        let total_bytes = tree.calculate_usage(owner).unwrap_or_default();
337
338        let total_documents = if let Some(owned_files) = db.owned_files.get(&owner) {
339            owned_files.len() as i64
340        } else {
341            return Ok(None);
342        };
343
344        Ok(Some(UserInfo {
345            total_documents,
346            total_bytes: total_bytes as i64,
347            is_user_active,
348            is_user_sharer_or_sharee,
349            is_user_active_v2,
350            total_egress,
351            account_age,
352        }))
353    }
354}