File: stream_model.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (341 lines) | stat: -rw-r--r-- 11,066 bytes parent folder | download | duplicates (10)
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/feed/core/v2/stream_model.h"

#include <algorithm>
#include <sstream>
#include <utility>

#include "base/base64.h"
#include "base/check.h"
#include "base/check_op.h"
#include "base/json/string_escape.h"
#include "base/observer_list.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "components/feed/core/proto/v2/store.pb.h"
#include "components/feed/core/proto/v2/wire/content_id.pb.h"
#include "components/feed/core/v2/feedstore_util.h"
#include "components/feed/core/v2/proto_util.h"
#include "components/feed/core/v2/protocol_translator.h"
#include "components/feed/core/v2/types.h"

namespace feed {
namespace {
using Context = StreamModel::Context;
using UiUpdate = StreamModel::UiUpdate;
using StoreUpdate = StreamModel::StoreUpdate;

bool HasClearAll(const std::vector<feedstore::StreamStructure>& structures) {
  for (const feedstore::StreamStructure& data : structures) {
    if (data.operation() == feedstore::StreamStructure::CLEAR_ALL)
      return true;
  }
  return false;
}

void MergeSharedStateIds(const feedstore::StreamData& model_data,
                         feedstore::StreamData& update_request_data) {
  for (const auto& content_id : model_data.shared_state_ids()) {
    bool found = false;
    for (const auto& update_request_content_id :
         update_request_data.shared_state_ids()) {
      if (Equal(update_request_content_id, content_id)) {
        found = true;
        break;
      }
    }
    if (!found) {
      *update_request_data.add_shared_state_ids() = content_id;
    }
  }
}

}  // namespace

Context::Context() = default;
Context::~Context() = default;
UiUpdate::UiUpdate() = default;
UiUpdate::~UiUpdate() = default;
UiUpdate::UiUpdate(const UiUpdate&) = default;
UiUpdate& UiUpdate::operator=(const UiUpdate&) = default;
StoreUpdate::StoreUpdate() = default;
StoreUpdate::~StoreUpdate() = default;
StoreUpdate::StoreUpdate(StoreUpdate&&) = default;
StoreUpdate& StoreUpdate::operator=(StoreUpdate&&) = default;

StreamModel::StreamModel(Context* context,
                         const LoggingParameters& logging_parameters)
    : logging_parameters_(logging_parameters),
      content_map_(&(context->revision_generator)) {}

StreamModel::~StreamModel() = default;

void StreamModel::SetStoreObserver(StoreObserver* store_observer) {
  DCHECK(!store_observer || !store_observer_)
      << "Attempting to set store_observer multiple times";
  store_observer_ = store_observer;
}

void StreamModel::SetStreamType(const StreamType& stream_type) {
  stream_type_ = stream_type;
}

const StreamType& StreamModel::GetStreamType() const {
  return stream_type_;
}

void StreamModel::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void StreamModel::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

const feedstore::Content* StreamModel::FindContent(
    ContentRevision revision) const {
  return GetFinalFeatureTree()->FindContent(revision);
}

feedwire::ContentId StreamModel::FindContentId(ContentRevision revision) const {
  const feedstore::Content* content = FindContent(revision);
  return content ? content->content_id() : feedwire::ContentId();
}

const std::string* StreamModel::FindSharedStateData(
    const std::string& id) const {
  auto iter = shared_states_.find(id);
  if (iter != shared_states_.end()) {
    return &iter->second.data;
  }
  return nullptr;
}

std::vector<std::string> StreamModel::GetSharedStateIds() const {
  std::vector<std::string> ids;
  for (auto& entry : shared_states_) {
    ids.push_back(entry.first);
  }
  return ids;
}

void StreamModel::Update(
    std::unique_ptr<StreamModelUpdateRequest> update_request) {
  std::vector<feedstore::StreamStructure>& stream_structures =
      update_request->stream_structures;
  const bool has_clear_all = HasClearAll(stream_structures);

  switch (update_request->source) {
    case StreamModelUpdateRequest::Source::kNetworkUpdate:
      // In this case, the stream state has been saved to persistent
      // storage by the caller. Next sequence number is always 1.
      next_structure_sequence_number_ = 1;
      break;
    case StreamModelUpdateRequest::Source::kInitialLoadFromStore:
      // In this case, use max_structure_sequence_number to derive the next
      // sequence number.
      next_structure_sequence_number_ =
          update_request->max_structure_sequence_number + 1;
      break;
    case StreamModelUpdateRequest::Source::kNetworkLoadMore: {
      // In this case, |StreamModel| is responsible for triggering the update
      // to the store. There are two main cases:
      // 1. The update request has a CLEAR_ALL (this is unexpected).
      //    In this case, we want to overwrite all stored stream data, since
      //    the old data is no longer useful. Start using sequence number 0.
      // 2. The update request does not have a CLEAR_ALL.
      //    Save the new stream data with the next sequence number.
      if (has_clear_all) {
        next_structure_sequence_number_ = 0;
      } else {
        MergeSharedStateIds(stream_data_, update_request->stream_data);
      }
      // Never allow overwriting the root event ID.
      update_request->stream_data.set_root_event_id(
          stream_data_.root_event_id());

      // Note: We might be overwriting some shared-states unnecessarily.
      StoreUpdate store_update;
      store_update.stream_type = stream_type_;
      store_update.overwrite_stream_data = has_clear_all;
      store_update.update_request =
          std::make_unique<StreamModelUpdateRequest>(*update_request);
      store_update.sequence_number = next_structure_sequence_number_++;
      store_observer_->OnStoreChange(std::move(store_update));
      break;
    }
  }

  stream_data_ = update_request->stream_data;

  if (has_clear_all) {
    shared_states_.clear();
  }

  // Update the feature tree.
  for (const feedstore::StreamStructure& structure : stream_structures) {
    base_feature_tree_.ApplyStreamStructure(structure);
  }
  for (feedstore::Content& content : update_request->content) {
    base_feature_tree_.AddContent(std::move(content));
  }

  for (feedstore::StreamSharedState& shared_state :
       update_request->shared_states) {
    std::string id = ContentIdString(shared_state.content_id());
    if (!shared_states_.contains(id)) {
      shared_states_[id].data =
          std::move(*shared_state.mutable_shared_state_data());
    }
  }

  // TODO(harringtond): We're not using StreamData's content_id for anything.

  UpdateFlattenedTree();
}

EphemeralChangeId StreamModel::CreateEphemeralChange(
    std::vector<feedstore::DataOperation> operations) {
  const EphemeralChangeId id =
      ephemeral_changes_.AddEphemeralChange(std::move(operations))->id();

  UpdateFlattenedTree();

  return id;
}

void StreamModel::ExecuteOperations(
    std::vector<feedstore::DataOperation> operations) {
  for (const feedstore::DataOperation& operation : operations) {
    if (operation.has_structure()) {
      base_feature_tree_.ApplyStreamStructure(operation.structure());
    }
    if (operation.has_content()) {
      base_feature_tree_.AddContent(operation.content());
    }
  }

  if (store_observer_) {
    StoreUpdate store_update;
    store_update.stream_type = stream_type_;
    store_update.operations = std::move(operations);
    store_update.sequence_number = next_structure_sequence_number_++;
    store_observer_->OnStoreChange(std::move(store_update));
  }

  UpdateFlattenedTree();
}

bool StreamModel::CommitEphemeralChange(EphemeralChangeId id) {
  std::unique_ptr<stream_model::EphemeralChange> change =
      ephemeral_changes_.Remove(id);
  if (!change)
    return false;

  // Note: it's possible that the does change even upon commit because it
  // may change the order that operations are applied. ExecuteOperations
  // will ensure observers are updated.
  ExecuteOperations(change->GetOperations());
  return true;
}

bool StreamModel::RejectEphemeralChange(EphemeralChangeId id) {
  if (ephemeral_changes_.Remove(id)) {
    UpdateFlattenedTree();
    return true;
  }
  return false;
}

void StreamModel::UpdateFlattenedTree() {
  if (ephemeral_changes_.GetChangeList().empty()) {
    feature_tree_after_changes_.reset();
  } else {
    feature_tree_after_changes_ =
        ApplyEphemeralChanges(base_feature_tree_, ephemeral_changes_);
  }
  // Update list of visible content.
  std::vector<ContentRevision> new_state =
      GetFinalFeatureTree()->GetVisibleContent();
  const bool content_list_changed = content_list_ != new_state;
  content_list_ = std::move(new_state);

  // Pack and send UiUpdate.
  UiUpdate update;
  update.content_list_changed = content_list_changed;
  for (auto& entry : shared_states_) {
    SharedState& shared_state = entry.second;
    UiUpdate::SharedStateInfo info;
    info.shared_state_id = entry.first;
    info.updated = shared_state.updated;
    update.shared_states.push_back(std::move(info));

    shared_state.updated = false;
  }

  for (Observer& observer : observers_)
    observer.OnUiUpdate(update);
}

bool StreamModel::HasVisibleContent() {
  return !content_list_.empty();
}

stream_model::FeatureTree* StreamModel::GetFinalFeatureTree() {
  return feature_tree_after_changes_ ? feature_tree_after_changes_.get()
                                     : &base_feature_tree_;
}
const stream_model::FeatureTree* StreamModel::GetFinalFeatureTree() const {
  return const_cast<StreamModel*>(this)->GetFinalFeatureTree();
}

const std::string& StreamModel::GetNextPageToken() const {
  return stream_data_.next_page_token();
}

base::Time StreamModel::GetLastAddedTime() const {
  return feedstore::GetLastAddedTime(stream_data_);
}
ContentHashSet StreamModel::GetContentIds() const {
  return feedstore::GetContentIds(stream_data_);
}

ContentStats StreamModel::GetContentStats() const {
  ContentStats stats;
  for (auto content_revision : content_list_) {
    const feedstore::Content* content = FindContent(content_revision);
    if (content) {
      stats.total_content_frame_size_bytes += content->frame().size();
      stats.card_count++;
    }
  }

  for (auto& entry : shared_states_) {
    stats.shared_state_size += entry.second.data.size();
  }
  return stats;
}

const std::string& StreamModel::GetRootEventId() const {
  return stream_data_.root_event_id();
}

std::string StreamModel::DumpStateForTesting() {
  std::stringstream ss;
  ss << "StreamModel{\n";
  { ss << "root_event_id=" << base::Base64Encode(GetRootEventId()) << "'\n"; }
  ss << "next_page_token='" << GetNextPageToken() << "'\n";
  for (auto& entry : shared_states_) {
    ss << "shared_state[" << entry.first
       << "]=" << base::GetQuotedJSONString(entry.second.data.substr(0, 100))
       << "\n";
  }
  ss << GetFinalFeatureTree()->DumpStateForTesting();
  ss << "}StreamModel\n";
  return ss.str();
}

}  // namespace feed