File: active_status.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; 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 (292 lines) | stat: -rw-r--r-- 10,645 bytes parent folder | download | duplicates (6)
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/report/device_metrics/churn/active_status.h"

#include "base/check.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/time.h"
#include "chromeos/ash/components/report/utils/time_utils.h"
#include "components/prefs/pref_service.h"

namespace ash::report::device_metrics {

namespace {

template <size_t N>
int ConvertBitsetToInteger(std::bitset<N> bitset) {
  return static_cast<int>(bitset.to_ulong());
}

template <size_t N>
std::bitset<N> ConvertIntegerToBitset(int val) {
  return std::bitset<N>(val);
}

}  // namespace

ActiveStatus::ActiveStatus(PrefService* local_state)
    : local_state_(local_state) {}

int ActiveStatus::GetValue() const {
  return local_state_->GetInteger(
      ash::report::prefs::kDeviceActiveLastKnownChurnActiveStatus);
}

void ActiveStatus::SetValue(int val) {
  return local_state_->SetInteger(
      ash::report::prefs::kDeviceActiveLastKnownChurnActiveStatus, val);
}

std::optional<int> ActiveStatus::CalculateNewValue(base::Time ts) const {
  if (ts.is_null() || ts == base::Time::UnixEpoch()) {
    LOG(ERROR) << "Cannot calculate new value for invalid ts.";
    return std::nullopt;
  }

  base::Time::Exploded exploded;
  ts.UTCExplode(&exploded);

  int year = exploded.year;
  int month = exploded.month;

  // Calculate total number of months since January 2000 to current month.
  // e.g. Dec 2022 should return a total of 275 months.
  int new_months_from_inception =
      ((year - kInceptionYear) * utils::kMonthsInYear) + (month - 1);
  int previous_months_from_inception = GetMonthsSinceInception();

  // Check |ts| represents a new month than previously reported.
  if (new_months_from_inception <= previous_months_from_inception) {
    LOG(ERROR) << "Failed to update churn active status. "
               << "New number of months must be larger than the previous.";
    LOG(ERROR) << "Previous months from inception = "
               << previous_months_from_inception;
    LOG(ERROR) << "New months from inception = " << new_months_from_inception;

    return std::nullopt;
  }

  // Calculate new_active_months since we are in a new month.
  // Shift the 18 bits N to the left to represent the inactive months, and
  // set the last bit to 1 to mark this month as active.
  std::bitset<kActiveMonthsBitSize> new_active_months(GetActiveMonthBits());
  new_active_months <<=
      (new_months_from_inception - previous_months_from_inception);
  new_active_months |= 1;

  // Recreate active status bitset formatted with first 10 bits representing
  // months from inception to current month. Followed by 18 bits representing
  // last 18 months of actives from current month.
  std::bitset<kActiveStatusBitSize> updated_value(new_months_from_inception);

  updated_value <<= kActiveMonthsBitSize;
  updated_value |= static_cast<int>(new_active_months.to_ulong());

  return ConvertBitsetToInteger<kActiveStatusBitSize>(updated_value);
}

std::optional<base::Time> ActiveStatus::GetCurrentActiveMonthTimestamp() const {
  DCHECK_GE(GetMonthsSinceInception(), 0);

  int months_from_inception = GetMonthsSinceInception();
  std::optional<base::Time> inception_ts = GetInceptionMonthTimestamp();
  if (!inception_ts.has_value()) {
    LOG(ERROR) << "Failed to get the inception month as timestamp.";
    return std::nullopt;
  }

  int years_from_inception = std::floor(months_from_inception / 12);
  int months_from_inception_remaining = months_from_inception % 12;

  base::Time::Exploded exploded;
  inception_ts.value().UTCExplode(&exploded);

  exploded.year += years_from_inception;
  exploded.month += months_from_inception_remaining;

  base::Time current_active_month_ts;
  bool success =
      base::Time::FromUTCExploded(exploded, &current_active_month_ts);

  if (!success) {
    LOG(ERROR) << "Failed to convert current active month back to timestamp.";
    return std::nullopt;
  }

  return current_active_month_ts;
}

std::optional<ChurnCohortMetadata> ActiveStatus::CalculateCohortMetadata(
    base::Time active_ts) const {
  ChurnCohortMetadata metadata;

  std::optional<int> new_active_status = CalculateNewValue(active_ts);
  if (!new_active_status.has_value()) {
    LOG(ERROR) << "Failed to generate new value. Old Value = " << GetValue();
    return std::nullopt;
  }

  metadata.set_active_status_value(new_active_status.value());

  std::optional<bool> is_first_active = IsFirstActiveInCohort(active_ts);
  if (is_first_active.has_value()) {
    metadata.set_is_first_active_in_cohort(is_first_active.value());
  }

  return metadata;
}

std::optional<ChurnObservationMetadata>
ActiveStatus::CalculateObservationMetadata(base::Time active_ts,
                                           int period) const {
  DCHECK(period >= 0 && period <= 2) << "Period must be in [0,2] range.";

  // Observation metadata is generated if cohort ping was sent for the month.
  std::optional<base::Time> cur_active_month_ts =
      GetCurrentActiveMonthTimestamp();
  if (cur_active_month_ts.has_value() &&
      !utils::IsSameYearAndMonth(cur_active_month_ts.value(), active_ts)) {
    LOG(ERROR) << "Observation metadata require a current active status value. "
               << "This occurs after successful cohort pinging.";
    return std::nullopt;
  }

  ChurnObservationMetadata metadata;

  bool is_monthly_active = IsDeviceActiveInMonth(kMonthlyChurnOffset + period);
  bool is_yearly_active = IsDeviceActiveInMonth(kYearlyChurnOffset + period);
  metadata.set_monthly_active_status(is_monthly_active);
  metadata.set_yearly_active_status(is_yearly_active);

  std::optional<base::Time> first_active_week = utils::GetFirstActiveWeek();
  if (!first_active_week.has_value()) {
    LOG(ERROR) << "Cannot calculate observation metadata for first active "
               << "during cohort without the first active week.";
    return metadata;
  }

  std::optional<base::Time> last_month_ts = utils::GetPreviousMonth(active_ts);
  std::optional<base::Time> two_months_ago_ts =
      utils::GetPreviousMonth(last_month_ts.value_or(base::Time()));
  std::optional<base::Time> three_months_ago_ts =
      utils::GetPreviousMonth(two_months_ago_ts.value_or(base::Time()));

  if (!last_month_ts.has_value() || !two_months_ago_ts.has_value() ||
      !three_months_ago_ts.has_value()) {
    LOG(ERROR) << "Failed to calculate observation metadata for period.";
    return std::nullopt;
  }

  std::optional<base::Time> month_before_observation_period_start_ts;
  std::optional<base::Time> year_before_observation_period_start_ts;

  if (period == 0) {
    month_before_observation_period_start_ts = last_month_ts;
    year_before_observation_period_start_ts = utils::GetPreviousYear(
        month_before_observation_period_start_ts.value_or(base::Time()));

  } else if (period == 1) {
    month_before_observation_period_start_ts = two_months_ago_ts;
    year_before_observation_period_start_ts = utils::GetPreviousYear(
        month_before_observation_period_start_ts.value_or(base::Time()));

  } else if (period == 2) {
    month_before_observation_period_start_ts = three_months_ago_ts;
    year_before_observation_period_start_ts = utils::GetPreviousYear(
        month_before_observation_period_start_ts.value_or(base::Time()));
  }

  if (!month_before_observation_period_start_ts.has_value() ||
      !year_before_observation_period_start_ts.has_value()) {
    LOG(ERROR) << "Failed to get timestamps used to calculate first active "
                  "during cohort.";
    return metadata;
  }

  // Calculate the device's first active status in different cohort months.
  if (utils::IsSameYearAndMonth(
          first_active_week.value(),
          month_before_observation_period_start_ts.value()) &&
      is_monthly_active) {
    metadata.set_first_active_during_cohort(
        ChurnObservationMetadata_FirstActiveDuringCohort_FIRST_ACTIVE_IN_MONTHLY_COHORT);
  } else if (utils::IsSameYearAndMonth(
                 first_active_week.value(),
                 year_before_observation_period_start_ts.value()) &&
             is_yearly_active) {
    metadata.set_first_active_during_cohort(
        ChurnObservationMetadata_FirstActiveDuringCohort_FIRST_ACTIVE_IN_YEARLY_COHORT);
  } else {
    metadata.set_first_active_during_cohort(
        ChurnObservationMetadata_FirstActiveDuringCohort_EXISTED_OR_NOT_ACTIVE_YET);
  }

  return metadata;
}

std::optional<base::Time> ActiveStatus::GetInceptionMonthTimestamp() const {
  base::Time inception_ts;
  bool success = base::Time::FromUTCString(
      ActiveStatus::kActiveStatusInceptionDate, &inception_ts);

  if (!success) {
    LOG(ERROR) << "Failed to convert kActiveStatusInceptionDate to timestamp.";
    return std::nullopt;
  }

  return inception_ts;
}

int ActiveStatus::GetMonthsSinceInception() const {
  std::string month_from_inception =
      ConvertIntegerToBitset<kActiveStatusBitSize>(GetValue())
          .to_string()
          .substr(0, kMonthCountBitSize);

  return ConvertBitsetToInteger<kMonthCountBitSize>(
      std::bitset<kMonthCountBitSize>(month_from_inception));
}

int ActiveStatus::GetActiveMonthBits() const {
  std::string active_months =
      ConvertIntegerToBitset<kActiveStatusBitSize>(GetValue())
          .to_string()
          .substr(kMonthCountBitSize,
                  kActiveStatusBitSize - kMonthCountBitSize);

  return ConvertBitsetToInteger<kActiveMonthsBitSize>(
      std::bitset<kActiveMonthsBitSize>(active_months));
}

bool ActiveStatus::IsDeviceActiveInMonth(int month_idx) const {
  DCHECK(month_idx >= 0 && month_idx <= 17) << "Month must be in [0,17] range.";
  return ConvertIntegerToBitset<kActiveMonthsBitSize>(GetActiveMonthBits())
      .test(month_idx);
}

std::optional<bool> ActiveStatus::IsFirstActiveInCohort(
    base::Time active_ts) const {
  auto first_active_week = utils::GetFirstActiveWeek();
  if (!first_active_week.has_value()) {
    LOG(ERROR)
        << "First Active Week could not be retrieved correctly from VPD.";
    return std::nullopt;
  }

  base::Time::Exploded exploded;
  first_active_week.value().UTCExplode(&exploded);
  int first_active_year = exploded.year;
  int first_active_month = exploded.month;

  active_ts.UTCExplode(&exploded);
  int cohort_year = exploded.year;
  int cohort_month = exploded.month;

  return first_active_year == cohort_year && first_active_month == cohort_month;
}

}  // namespace ash::report::device_metrics