File: ash_event_storage.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; 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,811; 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 (242 lines) | stat: -rw-r--r-- 7,618 bytes parent folder | download | duplicates (5)
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
// 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 "chrome/browser/metrics/structured/ash_event_storage.h"

#include "base/functional/callback_forward.h"
#include "base/task/current_thread.h"
#include "chrome/browser/profiles/profile.h"
#include "components/metrics/structured/lib/histogram_util.h"
#include "third_party/metrics_proto/structured_data.pb.h"

namespace metrics::structured {

using ::google::protobuf::RepeatedPtrField;

AshEventStorage::AshEventStorage(base::TimeDelta write_delay,
                                 const base::FilePath& pre_user_event_path)
    : write_delay_(write_delay) {
  // Store to persist events before a user has logged-in.
  pre_user_events_ = std::make_unique<PersistentProto<EventsProto>>(
      pre_user_event_path, write_delay_,
      base::BindOnce(&AshEventStorage::OnRead, weak_factory_.GetWeakPtr()),
      base::BindRepeating(&AshEventStorage::OnWrite,
                          weak_factory_.GetWeakPtr()));
}

AshEventStorage::~AshEventStorage() = default;

void AshEventStorage::OnReady() {
  CHECK(pre_user_events_.get());
  is_initialized_ = true;

  for (auto& event : pre_storage_events_) {
    AddEvent(std::move(event));
  }
}

void AshEventStorage::AddEvent(StructuredEventProto event) {
  PersistentProto<EventsProto>* event_store_to_write = GetStoreToWriteEvent();

  if (!event_store_to_write) {
    pre_storage_events_.emplace_back(std::move(event));
    return;
  }

  event_store_to_write->get()->mutable_events()->Add(std::move(event));
  event_store_to_write->QueueWrite();
}

RepeatedPtrField<StructuredEventProto> AshEventStorage::TakeEvents() {
  if (IsPreUserStorageReadable()) {
    RepeatedPtrField<StructuredEventProto> events =
        std::move(*pre_user_events()->mutable_events());
    pre_user_events_->Purge();
    return events;
  }

  // Profile must be ready if |pre_user_events| has been cleanedup.
  CHECK(IsProfileReady());

  RepeatedPtrField<StructuredEventProto> events =
      std::move(*user_events()->mutable_events());
  user_events_->Purge();
  return events;
}

int AshEventStorage::RecordedEventsCount() const {
  int total_event_count = 0;
  if (IsPreUserStorageReadable()) {
    total_event_count += pre_user_events_->get()->events_size();
  }
  if (is_user_initialized_) {
    total_event_count += user_events_->get()->events_size();
  }
  return total_event_count;
}

void AshEventStorage::Purge() {
  if (IsProfileReady()) {
    user_events_->Purge();
  }
  if (IsPreUserStorageReadable()) {
    pre_user_events_->Purge();
  }
  if (!pre_storage_events_.empty()) {
    pre_storage_events_.clear();
  }
}

void AshEventStorage::AddBatchEvents(
    const google::protobuf::RepeatedPtrField<StructuredEventProto>& events) {
  PersistentProto<EventsProto>* event_store = GetStoreToWriteEvent();
  if (event_store) {
    event_store->get()->mutable_events()->MergeFrom(events);
    event_store->QueueWrite();
  } else if (!is_initialized_) {
    pre_storage_events_.insert(pre_storage_events_.end(), events.begin(),
                               events.end());
  }
}

void AshEventStorage::ProfileAdded(const Profile& profile) {
  DCHECK(base::CurrentUIThread::IsSet());

  if (is_user_initialized_) {
    return;
  }

  const base::FilePath& path = profile.GetPath();

  // The directory used to store unsent logs. Relative to the user's cryptohome.
  // This file is created by chromium.
  user_events_ = std::make_unique<PersistentProto<EventsProto>>(
      path.Append(FILE_PATH_LITERAL("structured_metrics"))
          .Append(FILE_PATH_LITERAL("events")),
      write_delay_,
      base::BindOnce(&AshEventStorage::OnProfileRead,
                     weak_factory_.GetWeakPtr()),
      base::BindRepeating(&AshEventStorage::OnWrite,
                          weak_factory_.GetWeakPtr()));
}

void AshEventStorage::CopyEvents(EventsProto* events_proto) const {
  if (IsPreUserStorageReadable() && pre_user_events()->events_size() > 0) {
    events_proto->mutable_events()->MergeFrom(pre_user_events()->events());
  }
  if (IsProfileReady() && user_events()->events_size() > 0) {
    events_proto->mutable_events()->MergeFrom(user_events()->events());
  }
}

void AshEventStorage::OnWrite(const WriteStatus status) {
  switch (status) {
    case WriteStatus::kOk:
      break;
    case WriteStatus::kWriteError:
      LogInternalError(StructuredMetricsError::kEventWriteError);
      break;
    case WriteStatus::kSerializationError:
      LogInternalError(StructuredMetricsError::kEventSerializationError);
      break;
  }
}

void AshEventStorage::OnRead(const ReadStatus status) {
  switch (status) {
    case ReadStatus::kOk:
    case ReadStatus::kMissing:
      break;
    case ReadStatus::kReadError:
      LogInternalError(StructuredMetricsError::kEventReadError);
      break;
    case ReadStatus::kParseError:
      LogInternalError(StructuredMetricsError::kEventParseError);
      break;
  }

  OnReady();
}

void AshEventStorage::OnProfileRead(const ReadStatus status) {
  switch (status) {
    case ReadStatus::kOk:
    case ReadStatus::kMissing:
      break;
    case ReadStatus::kReadError:
      LogInternalError(StructuredMetricsError::kEventReadError);
      break;
    case ReadStatus::kParseError:
      LogInternalError(StructuredMetricsError::kEventParseError);
      break;
  }

  OnProfileReady();
}

void AshEventStorage::OnProfileReady() {
  CHECK(user_events_.get());
  is_user_initialized_ = true;

  // Move any events that are current in |pre_user_events_| into the
  // |user_events_|.
  if (pre_user_events() && pre_user_events()->events_size() > 0) {
    RepeatedPtrField<StructuredEventProto>* users_events =
        user_events()->mutable_events();
    RepeatedPtrField<StructuredEventProto>* pre_users_events =
        pre_user_events()->mutable_events();

    // Moving events from |pre_users_events| to |users_events|.
    users_events->Reserve(users_events->size() + pre_users_events->size());

    // Temporary buffer to extract the |pre_users_events| into.
    std::vector<StructuredEventProto*> extracted(pre_users_events->size(),
                                                 nullptr);

    // Extract and add the elements into |users_events|
    pre_users_events->ExtractSubrange(0, pre_users_events->size(),
                                      extracted.data());

    for (auto* element : extracted) {
      users_events->AddAllocated(element);
    }
  }

  // Regardless of if there are any events cleanup the storage.
  if (pre_user_events()) {
    (*pre_user_events_)->Clear();
    pre_user_events_->QueueWrite();
  }

  // The write is fine because it will add to a task that is not tied to the
  // lifetime of |pre_user_events_|.
  pre_user_events_.reset();

  // Dealloc any memory that the vector is occupying as it will not be used
  // anymore.
  std::vector<StructuredEventProto>().swap(pre_storage_events_);
}

bool AshEventStorage::IsProfileReady() const {
  return is_user_initialized_ && user_events_.get();
}

bool AshEventStorage::IsPreUserStorageReadable() const {
  return pre_user_events_ && is_initialized_;
}

PersistentProto<EventsProto>* AshEventStorage::GetStoreToWriteEvent() {
  // If user storage is ready, all events should be stored in user event store
  // regardless of the type.
  if (IsProfileReady()) {
    return user_events_.get();
  }
  // Use the shared storage if user storage is not ready.
  if (IsPreUserStorageReadable()) {
    return pre_user_events_.get();
  }
  return nullptr;
}

}  // namespace metrics::structured