File: profile_activity_metrics_recorder.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (229 lines) | stat: -rw-r--r-- 8,135 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/profiles/profile_activity_metrics_recorder.h"

#include <string>

#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/metrics/histogram_macros.h"
#include "base/task/sequenced_task_runner.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_attributes_entry.h"
#include "chrome/browser/profiles/profile_attributes_storage.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"

namespace {

ProfileActivityMetricsRecorder* g_profile_activity_metrics_recorder = nullptr;

// The maximum number of profiles that are recorded. This means that all
// profiles with bucket index greater than |kMaxProfileBucket| won't be included
// in the metrics.
constexpr int kMaxProfileBucket = 100;

// Long time of inactivity that is treated as if user starts the browser anew.
constexpr base::TimeDelta kLongTimeOfInactivity = base::Minutes(30);

int GetMetricsBucketIndex(const Profile* profile) {
  if (profile->IsGuestSession())
    return 0;

  if (!g_browser_process->profile_manager()) {
    VLOG(1) << "Failed to read profile bucket index because profile manager "
               "doesn't exist.";
    return -1;
  }

  ProfileAttributesEntry* entry =
      g_browser_process->profile_manager()
          ->GetProfileAttributesStorage()
          .GetProfileAttributesWithPath(profile->GetPath());
  if (!entry) {
    // This can happen if the profile is deleted.
    VLOG(1) << "Failed to read profile bucket index because attributes entry "
               "doesn't exist.";
    return -1;
  }
  return entry->GetMetricsBucketIndex();
}

void RecordProfileSessionDuration(const Profile* profile,
                                  base::TimeDelta session_length) {
  if (!profile || session_length.InMinutes() <= 0)
    return;

  int profile_bucket = GetMetricsBucketIndex(profile);

  if (0 <= profile_bucket && profile_bucket <= kMaxProfileBucket) {
    base::Histogram::FactoryGet("Profile.SessionDuration.PerProfile", 0,
                                kMaxProfileBucket, kMaxProfileBucket + 1,
                                base::HistogramBase::kUmaTargetedHistogramFlag)
        ->AddCount(profile_bucket, session_length.InMinutes());
  }
}

void RecordBrowserActivation(const Profile* profile) {
  DCHECK(profile);
  int profile_bucket = GetMetricsBucketIndex(profile);

  if (0 <= profile_bucket && profile_bucket <= kMaxProfileBucket) {
    UMA_HISTOGRAM_EXACT_LINEAR("Profile.BrowserActive.PerProfile",
                               profile_bucket, kMaxProfileBucket);
  }
}

void RecordProfileSwitch() {
  int profiles_count =
      g_browser_process->profile_manager()->GetNumberOfProfiles();
  UMA_HISTOGRAM_COUNTS_100("Profile.NumberOfProfilesAtProfileSwitch",
                           profiles_count);
}

void RecordUserAction(const Profile* profile) {
  if (!profile)
    return;

  int profile_bucket = GetMetricsBucketIndex(profile);

  if (0 <= profile_bucket && profile_bucket <= kMaxProfileBucket) {
    UMA_HISTOGRAM_EXACT_LINEAR("Profile.UserAction.PerProfile", profile_bucket,
                               kMaxProfileBucket);
  }
}

void RecordProfilesState() {
  g_browser_process->profile_manager()
      ->GetProfileAttributesStorage()
      .RecordProfilesState();
}

void RecordAccountMetrics(const Profile* profile) {
  DCHECK(profile);

  ProfileAttributesEntry* entry =
      g_browser_process->profile_manager()
          ->GetProfileAttributesStorage()
          .GetProfileAttributesWithPath(profile->GetPath());
  if (!entry) {
    // This can happen if the profile is deleted / for guest profile.
    return;
  }

  entry->RecordAccountNamesMetric();
}

}  // namespace

// static
void ProfileActivityMetricsRecorder::Initialize() {
  DCHECK(!g_profile_activity_metrics_recorder);
  g_profile_activity_metrics_recorder = new ProfileActivityMetricsRecorder();
}

// static
void ProfileActivityMetricsRecorder::CleanupForTesting() {
  DCHECK(g_profile_activity_metrics_recorder);
  delete g_profile_activity_metrics_recorder;
  g_profile_activity_metrics_recorder = nullptr;
}

void ProfileActivityMetricsRecorder::OnBrowserSetLastActive(Browser* browser) {
  Profile* active_profile = browser->profile()->GetOriginalProfile();

  RecordBrowserActivation(active_profile);
  RecordAccountMetrics(active_profile);

  if (running_session_profile_ != active_profile) {
    // No-op, if starting a new session (|running_session_profile_| is nullptr).
    RecordProfileSessionDuration(
        running_session_profile_,
        base::TimeTicks::Now() - running_session_start_);

    running_session_profile_ = active_profile;
    running_session_start_ = base::TimeTicks::Now();
    profile_observation_.Reset();
    profile_observation_.Observe(running_session_profile_.get());

    // Record state at startup (when |last_session_end_| is 0) and whenever the
    // user starts browsing after a longer time of inactivity. Do it
    // asynchronously because active_time of the just activated profile is also
    // updated from OnBrowserSetLastActive() in another BrowserListObserver and
    // we have no guarantee if this happens before or after this function call.
    if (last_session_end_.is_null() ||
        (running_session_start_ - last_session_end_ > kLongTimeOfInactivity)) {
      base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
          FROM_HERE, base::BindOnce(&RecordProfilesState));
    }
  }

  if (last_active_profile_ != active_profile) {
    if (last_active_profile_ != nullptr)
      RecordProfileSwitch();
    last_active_profile_ = active_profile;
  }

  // This browsing session is still lasting.
  last_session_end_ = base::TimeTicks::Now();
}

void ProfileActivityMetricsRecorder::OnSessionEnded(
    base::TimeDelta session_length,
    base::TimeTicks session_end) {
  // If this call is emitted after OnProfileWillBeDestroyed, return
  // early. We already logged the session duration there.
  if (!running_session_profile_)
    return;

  // |session_length| can't be used here because it was measured across all
  // profiles.
  RecordProfileSessionDuration(running_session_profile_,
                               session_end - running_session_start_);
  DCHECK(
      profile_observation_.IsObservingSource(running_session_profile_.get()));
  profile_observation_.Reset();
  running_session_profile_ = nullptr;
  last_session_end_ = base::TimeTicks::Now();
}

void ProfileActivityMetricsRecorder::OnProfileWillBeDestroyed(
    Profile* profile) {
  DCHECK_EQ(profile, running_session_profile_);

  // The profile may be deleted without an OnSessionEnded call if, for
  // example, the browser shuts down.
  //
  // TODO(crbug.com/40700582): explore having
  // DesktopSessionDurationTracker call OnSessionEnded() when the
  // profile is destroyed. Remove this workaround if this is done.
  DCHECK(
      profile_observation_.IsObservingSource(running_session_profile_.get()));
  profile_observation_.Reset();
  running_session_profile_ = nullptr;
  last_active_profile_ = nullptr;
  last_session_end_ = base::TimeTicks::Now();
}

ProfileActivityMetricsRecorder::ProfileActivityMetricsRecorder() {
  BrowserList::AddObserver(this);
  metrics::DesktopSessionDurationTracker::Get()->AddObserver(this);
  action_callback_ = base::BindRepeating(
      &ProfileActivityMetricsRecorder::OnUserAction, base::Unretained(this));
  base::AddActionCallback(action_callback_);
}

ProfileActivityMetricsRecorder::~ProfileActivityMetricsRecorder() {
  BrowserList::RemoveObserver(this);
  metrics::DesktopSessionDurationTracker::Get()->RemoveObserver(this);
  base::RemoveActionCallback(action_callback_);
}

void ProfileActivityMetricsRecorder::OnUserAction(const std::string& action,
                                                  base::TimeTicks action_time) {
  RecordUserAction(running_session_profile_);
}