File: feedstore_util.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 (301 lines) | stat: -rw-r--r-- 10,725 bytes parent folder | download | duplicates (3)
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
// Copyright 2021 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/feedstore_util.h"

#include <string_view>

#include "base/base64url.h"
#include "base/hash/hash.h"
#include "base/strings/strcat.h"
#include "components/feed/core/proto/v2/store.pb.h"
#include "components/feed/core/proto/v2/wire/consistency_token.pb.h"
#include "components/feed/core/v2/config.h"
#include "components/feed/core/v2/feed_store.h"
#include "components/feed/core/v2/public/stream_type.h"

namespace feedstore {
using feed::LocalActionId;
using feed::StreamType;

// This returns a string version of StreamType which can be used in datastore
// keys.
std::string StreamKey(const StreamType& stream_type) {
  if (stream_type.IsForYou())
    return kForYouStreamKey;
  if (stream_type.IsWebFeed())
    return kFollowStreamKey;
  DCHECK(stream_type.IsSingleWebFeed());
  std::string encoding;
  base::Base64UrlEncode(stream_type.GetWebFeedId(),
                        base::Base64UrlEncodePolicy::INCLUDE_PADDING,
                        &encoding);
  if (stream_type.IsSingleWebFeedEntryMenu()) {
    return base::StrCat({std::string(kSingleWebFeedStreamKeyPrefix), "/",
                         std::string(kSingleWebFeedMenuStreamKeyPrefix),
                         encoding});
  } else {
    return base::StrCat({std::string(kSingleWebFeedStreamKeyPrefix), "/",
                         std::string(kSingleWebFeedOtherStreamKeyPrefix),
                         encoding});
  }
}

std::string_view StreamPrefix(feed::StreamKind stream_kind) {
  switch (stream_kind) {
    case feed::StreamKind::kForYou:
      return kForYouStreamKey;
    case feed::StreamKind::kFollowing:
      return kFollowStreamKey;
    case feed::StreamKind::kSingleWebFeed:
      return kSingleWebFeedStreamKeyPrefix;
    case feed::StreamKind::kUnknown:
      NOTREACHED();
  }
}

StreamType DecodeSingleWebFeedKeySuffix(
    std::string_view suffix,
    feed::SingleWebFeedEntryPoint entry_point,
    std::string_view prefix) {
  if (base::StartsWith(suffix, prefix, base::CompareCase::SENSITIVE)) {
    suffix.remove_prefix(prefix.size());
    std::string single_web_feed_key;
    if (base::Base64UrlDecode(suffix,
                              base::Base64UrlDecodePolicy::IGNORE_PADDING,
                              &single_web_feed_key)) {
      return StreamType(feed::StreamKind::kSingleWebFeed, single_web_feed_key,
                        entry_point);
    }
  }
  return {};
}

StreamType StreamTypeFromKey(std::string_view id) {
  if (id == kForYouStreamKey)
    return StreamType(feed::StreamKind::kForYou);
  if (id == kFollowStreamKey)
    return StreamType(feed::StreamKind::kFollowing);
  if (base::StartsWith(id, kSingleWebFeedStreamKeyPrefix,
                       base::CompareCase::SENSITIVE)) {
    if ((id.size() < (kSingleWebFeedStreamKeyPrefix.size() +
                      kSingleWebFeedMenuStreamKeyPrefix.size() + 1))) {
      return {};
    }
    // add  +1 to account for the '/' separating the c/[mo]/webid
    std::string_view substr =
        id.substr(kSingleWebFeedStreamKeyPrefix.size() + 1);
    StreamType result = DecodeSingleWebFeedKeySuffix(
        substr, feed::SingleWebFeedEntryPoint::kMenu,
        kSingleWebFeedMenuStreamKeyPrefix);
    if (!result.IsValid()) {
      result = DecodeSingleWebFeedKeySuffix(
          substr, feed::SingleWebFeedEntryPoint::kOther,
          kSingleWebFeedOtherStreamKeyPrefix);
    }
    return result;
  }
  return {};
}

int64_t ToTimestampMillis(base::Time t) {
  return t.is_null() ? 0L : (t - base::Time::UnixEpoch()).InMilliseconds();
}

base::Time FromTimestampMillis(int64_t millis) {
  return base::Time::UnixEpoch() + base::Milliseconds(millis);
}

int64_t ToTimestampNanos(base::Time t) {
  return t.is_null() ? 0L : (t - base::Time::UnixEpoch()).InNanoseconds();
}

base::Time FromTimestampMicros(int64_t micros) {
  return base::Time::UnixEpoch() + base::Microseconds(micros);
}

void SetLastAddedTime(base::Time t, feedstore::StreamData& data) {
  data.set_last_added_time_millis(ToTimestampMillis(t));
}

base::Time GetLastAddedTime(const feedstore::StreamData& data) {
  return FromTimestampMillis(data.last_added_time_millis());
}

base::Time GetSessionIdExpiryTime(const Metadata& metadata) {
  return base::Time::FromDeltaSinceWindowsEpoch(
      base::Milliseconds(metadata.session_id().expiry_time_ms()));
}

void SetSessionId(Metadata& metadata,
                  std::string token,
                  base::Time expiry_time) {
  Metadata::SessionID* session_id = metadata.mutable_session_id();
  session_id->set_token(std::move(token));
  session_id->set_expiry_time_ms(
      expiry_time.ToDeltaSinceWindowsEpoch().InMilliseconds());
}

void SetContentLifetime(
    feedstore::Metadata& metadata,
    const StreamType& stream_type,
    feedstore::Metadata::StreamMetadata::ContentLifetime content_lifetime) {
  feedstore::Metadata::StreamMetadata& stream_metadata =
      feedstore::MetadataForStream(metadata, stream_type);
  *stream_metadata.mutable_content_lifetime() = std::move(content_lifetime);
}

void MaybeUpdateSessionId(Metadata& metadata,
                          std::optional<std::string> token) {
  if (token && metadata.session_id().token() != *token) {
    base::Time expiry_time =
        token->empty()
            ? base::Time()
            : base::Time::Now() + feed::GetFeedConfig().session_id_max_age;
    SetSessionId(metadata, *token, expiry_time);
  }
}

std::optional<Metadata> MaybeUpdateConsistencyToken(
    const feedstore::Metadata& metadata,
    const feedwire::ConsistencyToken& token) {
  if (token.has_token() && metadata.consistency_token() != token.token()) {
    auto metadata_copy = metadata;
    metadata_copy.set_consistency_token(token.token());
    return metadata_copy;
  }
  return std::nullopt;
}

LocalActionId GetNextActionId(Metadata& metadata) {
  uint32_t id = metadata.next_action_id();
  // Never use 0, as that's an invalid LocalActionId.
  if (id == 0)
    ++id;
  metadata.set_next_action_id(id + 1);
  return LocalActionId(id);
}

const Metadata::StreamMetadata* FindMetadataForStream(
    const Metadata& metadata,
    const StreamType& stream_type) {
  std::string key = StreamKey(stream_type);
  for (const auto& sm : metadata.stream_metadata()) {
    if (sm.stream_key() == key)
      return &sm;
  }
  return nullptr;
}

Metadata::StreamMetadata& MetadataForStream(Metadata& metadata,
                                            const StreamType& stream_type) {
  const Metadata::StreamMetadata* existing =
      FindMetadataForStream(metadata, stream_type);
  if (existing)
    return *const_cast<Metadata::StreamMetadata*>(existing);
  Metadata::StreamMetadata* sm = metadata.add_stream_metadata();
  sm->set_stream_key(std::string(StreamKey(stream_type)));
  return *sm;
}

void SetStreamViewContentHashes(Metadata& metadata,
                                const StreamType& stream_type,
                                const feed::ContentHashSet& content_hashes) {
  Metadata::StreamMetadata& stream_metadata =
      MetadataForStream(metadata, stream_type);
  stream_metadata.clear_view_content_hashes();
  stream_metadata.mutable_view_content_hashes()->Add(
      content_hashes.original_hashes().begin(),
      content_hashes.original_hashes().end());
}

bool IsKnownStale(const Metadata& metadata, const StreamType& stream_type) {
  const Metadata::StreamMetadata* sm =
      FindMetadataForStream(metadata, stream_type);
  return sm ? sm->is_known_stale() : false;
}

base::Time GetLastFetchTime(const Metadata& metadata,
                            const feed::StreamType& stream_type) {
  const Metadata::StreamMetadata* sm =
      FindMetadataForStream(metadata, stream_type);
  return sm ? FromTimestampMillis(sm->last_fetch_time_millis()) : base::Time();
}

void SetLastFetchTime(Metadata& metadata,
                      const StreamType& stream_type,
                      const base::Time& fetch_time) {
  Metadata::StreamMetadata& stream_metadata =
      MetadataForStream(metadata, stream_type);
  stream_metadata.set_last_fetch_time_millis(ToTimestampMillis(fetch_time));
}

feedstore::Metadata MakeMetadata(const std::string& gaia) {
  feedstore::Metadata md;
  md.set_stream_schema_version(feed::FeedStore::kCurrentStreamSchemaVersion);
  md.set_gaia(gaia);
  return md;
}

feedstore::DocView CreateDocView(uint64_t docid, base::Time timestamp) {
  feedstore::DocView doc_view;
  doc_view.set_docid(docid);
  doc_view.set_view_time_millis(feedstore::ToTimestampMillis(timestamp));
  return doc_view;
}

std::optional<Metadata> SetStreamViewContentHashes(
    const Metadata& metadata,
    const StreamType& stream_type,
    const feed::ContentHashSet& content_hashes) {
  std::optional<Metadata> result;
  if (!(GetViewContentIds(metadata, stream_type) == content_hashes)) {
    result = metadata;
    SetStreamViewContentHashes(*result, stream_type, content_hashes);
  }
  return result;
}

feed::ContentHashSet GetContentIds(const StreamData& stream_data) {
  return feed::ContentHashSet{{stream_data.content_hashes().begin(),
                               stream_data.content_hashes().end()}};
}
feed::ContentHashSet GetViewContentIds(const Metadata& metadata,
                                       const StreamType& stream_type) {
  const Metadata::StreamMetadata* stream_metadata =
      FindMetadataForStream(metadata, stream_type);
  if (stream_metadata) {
    return feed::ContentHashSet({stream_metadata->view_content_hashes().begin(),
                                 stream_metadata->view_content_hashes().end()});
  }
  return {};
}

void SetLastServerResponseTime(Metadata& metadata,
                               const feed::StreamType& stream_type,
                               const base::Time& server_time) {
  Metadata::StreamMetadata& stream_metadata =
      MetadataForStream(metadata, stream_type);
  stream_metadata.set_last_server_response_time_millis(
      ToTimestampMillis(server_time));
}

int32_t ContentHashFromPrefetchMetadata(
    const feedwire::PrefetchMetadata& prefetch_metadata) {
  return base::PersistentHash(prefetch_metadata.uri());
}

base::flat_set<uint32_t> GetViewedContentHashes(const Metadata& metadata,
                                                const StreamType& stream_type) {
  const Metadata::StreamMetadata* stream_metadata =
      FindMetadataForStream(metadata, stream_type);
  if (stream_metadata) {
    return base::flat_set<uint32_t>(
        stream_metadata->viewed_content_hashes().begin(),
        stream_metadata->viewed_content_hashes().end());
  }
  return {};
}

}  // namespace feedstore