File: backend_params_manager.cc

package info (click to toggle)
chromium 141.0.7390.107-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,246,132 kB
  • sloc: cpp: 35,264,965; ansic: 7,169,920; javascript: 4,250,185; python: 1,460,635; asm: 950,788; xml: 751,751; pascal: 187,972; sh: 89,459; perl: 88,691; objc: 79,953; sql: 53,924; cs: 44,622; fortran: 24,137; makefile: 22,313; tcl: 15,277; php: 14,018; yacc: 8,995; ruby: 7,553; awk: 3,720; lisp: 3,096; lex: 1,330; ada: 727; jsp: 228; sed: 36
file content (453 lines) | stat: -rw-r--r-- 15,068 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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// Copyright 2025 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/persistent_cache/backend_params_manager.h"

#include <algorithm>
#include <array>
#include <cstdint>
#include <queue>
#include <string>
#include <string_view>

#include "base/files/file.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/metrics/histogram_functions.h"
#include "base/sequence_checker.h"
#include "base/strings/strcat.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/thread_pool.h"
#include "components/persistent_cache/sqlite/sqlite_backend_impl.h"

namespace {

#if BUILDFLAG(IS_WIN)
const uint32_t kMaxFilePathLength = MAX_PATH - 1;
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
const uint32_t kMaxFilePathLength = PATH_MAX - 1;
#endif

struct FilePathWithInfo {
  base::FilePath file_path;
  base::File::Info info;
};

// Comparator to be used with priority_queue to make sure that smallest times
// representing the oldest files are at the top.
class FilePathWithInfoComparator {
 public:
  bool operator()(const FilePathWithInfo& a, const FilePathWithInfo& b) {
    return a.info.last_modified > b.info.last_modified;
  }
};

const base::FilePath::CharType kDbFile[] = FILE_PATH_LITERAL(".db_file");
const base::FilePath::CharType kJournalFile[] =
    FILE_PATH_LITERAL(".journal_file");

constexpr size_t kLruCacheCapacity = 100;

// Character not allowed in keys or filenames (by itself). Used to mark the
// start of a replacement token.
constexpr char kTokenMarker = '`';

// All characters allowed in filenames.
constexpr std::string_view kAllowedCharsInFilenames =
    "abcdefghijklmnopqrstuvwxyz0123456789-._~"
    "#[]@!$&'()+,;= ";

// Use to translate a character `c` viable for a filename into another arbitrary
// but equally viable character. To reverse the process the function is called
// with the opposite value for `forward`. If `c` is invalid empty is returned.
std::optional<char> RotateChar(char c, bool forward) {
  static_assert(kAllowedCharsInFilenames.length() < 128,
                "Allowed chars are a subset of ASCII and overflow while "
                "indexing should never be a worry");
  size_t char_index = kAllowedCharsInFilenames.find(c);

  // Characters illegal in filenames are not handled in this function.
  if (char_index == std::string::npos) {
    return std::nullopt;
  }

  // Arbitrary offset to rotate index in the list of allowed characters.
  constexpr int64_t kRotationOffset = 37;

  // Use a rotating index to find a character to replace `c`. Using XOR is not
  // viable because it doesn't always give a character that is viable in a
  // filename.
  if (forward) {
    return kAllowedCharsInFilenames[(char_index + kRotationOffset) %
                                    kAllowedCharsInFilenames.length()];
  }
  return kAllowedCharsInFilenames[(char_index +
                                   kAllowedCharsInFilenames.length() -
                                   kRotationOffset) %
                                  kAllowedCharsInFilenames.length()];
}

// Mapping of characters illegal in filenames to a unique token to represent
// them in filenames. This prevents collisions by avoiding two characters get
// mapped to the same value. Ex:
// "*/" --> "`9`2"
// "><" --> "`5`4"
//
// Mapping both strings to "`1`1" for example would result in a valid filename
// but in backing files being shared for two keys which is not correct.
static_assert(kAllowedCharsInFilenames.find(kTokenMarker) == std::string::npos,
              "Space is not allowed in filenames by itself.");
using ConstStringPair = std::pair<char, const char*>;
std::array<ConstStringPair, 10> kCharacterToTokenMap{
    ConstStringPair{'\\', "`1"}, ConstStringPair{'/', "`2"},
    ConstStringPair{'|', "`3"},  ConstStringPair{'<', "`4"},
    ConstStringPair{'>', "`5"},  ConstStringPair{':', "`6"},
    ConstStringPair{'\"', "`7"}, ConstStringPair{'?', "`8"},
    ConstStringPair{'*', "`9"},  ConstStringPair{'\n', "`0"}};

// Use to get a token to insert in a filename if `c` is a character
// illegal in filenames and an empty string if it's not.
std::string_view FilenameIllegalCharToReplacementToken(char c) {
  for (const auto& pair : kCharacterToTokenMap) {
    if (c == pair.first) {
      return pair.second;
    }
  }
  return "";
}

// Use to get a character associated with `token` if it exists and empty
// if it doesn't.
std::optional<char> ReplacementTokenToFilenameIllegalChar(
    std::string_view token) {
  for (const auto& pair : kCharacterToTokenMap) {
    if (token == pair.second) {
      return pair.first;
    }
  }

  return {};
}

}  // namespace

namespace persistent_cache {

BackendParamsManager::BackendParamsManager(base::FilePath top_directory)
    : backend_params_map_(kLruCacheCapacity),
      top_directory_(std::move(top_directory)) {
  if (!base::PathExists(top_directory_)) {
    base::CreateDirectory(top_directory_);
  }
}
BackendParamsManager::~BackendParamsManager() = default;

void BackendParamsManager::GetParamsSyncOrCreateAsync(
    BackendType backend_type,
    const std::string& key,
    AccessRights access_rights,
    CompletedCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  auto it = backend_params_map_.Get(
      BackendParamsKey{.backend_type = backend_type, .key = key});
  if (it != backend_params_map_.end()) {
    std::move(callback).Run(it->second);
    return;
  }

  std::string filename = FileNameFromKey(key);
  if (filename.empty()) {
    std::move(callback).Run(BackendParams());
    return;
  }

  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE,
      {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&BackendParamsManager::CreateParamsSync, top_directory_,
                     backend_type, filename, access_rights),
      base::BindOnce(&BackendParamsManager::SaveParams,
                     weak_factory_.GetWeakPtr(), key, std::move(callback)));
}

BackendParams BackendParamsManager::GetOrCreateParamsSync(
    BackendType backend_type,
    const std::string& key,
    AccessRights access_rights) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  auto it = backend_params_map_.Get(
      BackendParamsKey{.backend_type = backend_type, .key = key});
  if (it != backend_params_map_.end()) {
    return it->second.Copy();
  }

  std::string filename = FileNameFromKey(key);
  if (filename.empty()) {
    return BackendParams();
  }

  BackendParams new_params =
      CreateParamsSync(top_directory_, backend_type, filename, access_rights);
  SaveParams(key, CompletedCallback(), new_params.Copy());

  return new_params;
}

void BackendParamsManager::DeleteAllFiles() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Clear params cache so they don't hold on to files or prevent their
  // deletion. BackendParam instances that were vended by this class and
  // retained somewhere else can still create problems and need to be handled
  // appropriately.
  backend_params_map_.Clear();

  base::DeletePathRecursively(top_directory_);

  // Recreate the directory since the objective was to delete files only.
  base::CreateDirectory(top_directory_);
}

FootprintReductionResult BackendParamsManager::BringDownTotalFootprintOfFiles(
    int64_t target_footprint) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Clear params cache so they don't hold on to files or prevent their
  // deletion. BackendParam instances that were vended by this class and
  // retained somewhere else can still create problems and need to be handled
  // appropriately.
  backend_params_map_.Clear();

  int64_t total_footprint = 0;

  std::priority_queue<FilePathWithInfo, std::vector<FilePathWithInfo>,
                      FilePathWithInfoComparator>
      file_paths_with_info;
  base::FileEnumerator file_enumerator(top_directory_, /*recursive=*/false,
                                       base::FileEnumerator::FILES);

  file_enumerator.ForEach([&total_footprint, &file_paths_with_info](
                              const base::FilePath& file_path) {
    base::File::Info info;
    base::GetFileInfo(file_path, &info);

    // Only target database files for deletion.
    if (file_path.MatchesFinalExtension(kDbFile)) {
      file_paths_with_info.emplace(file_path, info);
    }

    // All files count towards measured footprint.
    total_footprint += info.size;
  });

  // Nothing to do.
  if (total_footprint <= target_footprint) {
    return FootprintReductionResult{.current_footprint = total_footprint,
                                    .number_of_bytes_deleted = 0};
  }

  int64_t size_of_necessary_deletes = total_footprint - target_footprint;
  int64_t deleted_size = 0;

  while (!file_paths_with_info.empty()) {
    if (size_of_necessary_deletes <= deleted_size) {
      break;
    }

    const FilePathWithInfo& file_path_with_info = file_paths_with_info.top();

    bool db_file_delete_success =
        base::DeleteFile(file_path_with_info.file_path);
    base::UmaHistogramBoolean(
        "PersistentCache.ParamsManager.DbFile.DeleteSucess",
        db_file_delete_success);

    if (db_file_delete_success) {
      deleted_size += file_path_with_info.info.size;

      base::FilePath journal_file_path =
          file_path_with_info.file_path.ReplaceExtension(kJournalFile);
      base::File::Info journal_file_info;
      base::GetFileInfo(journal_file_path, &journal_file_info);

      // TODO (https://crbug.com/377475540): Cleanup when deletion of journal
      // failed.
      bool journal_file_delete_success = base::DeleteFile(journal_file_path);
      base::UmaHistogramBoolean(
          "PersistentCache.ParamsManager.JournalFile.DeleteSucess",
          journal_file_delete_success);

      if (journal_file_delete_success) {
        deleted_size += journal_file_info.size;
      }
    };

    file_paths_with_info.pop();
  }

  return FootprintReductionResult{
      .current_footprint = total_footprint - deleted_size,
      .number_of_bytes_deleted = deleted_size};
}

// static
std::string BackendParamsManager::FileNameFromKey(const std::string& key) {
  std::string filename;
  filename.reserve(key.size());

  for (char c : key) {
    std::string_view token = FilenameIllegalCharToReplacementToken(c);
    if (!token.empty()) {
      filename += token;
    } else {
      std::optional<char> rotated_char = RotateChar(c, true);

      if (!rotated_char.has_value()) {
        // There's no way to rotate an illegal character so return an empty
        // string.
        return "";
      }
      filename += rotated_char.value();
    }
  }

  return filename;
}

// static
std::string BackendParamsManager::KeyFromFileName(const std::string& filename) {
  std::string key;
  key.reserve(filename.size());

  for (auto it = filename.begin(); it != filename.end(); ++it) {
    if (*it == kTokenMarker) {
      // Token markers cannot be by themselves in filenames. Return an empty
      // string instead of CHECKing here because it's not advisable to have a
      // crash because something renamed a file.
      if (it + 1 == filename.end()) {
        return "";
      }

      std::optional<char> c =
          ReplacementTokenToFilenameIllegalChar(std::string_view(it, it + 2));
      if (c.has_value()) {
        key += c.value();

        // Skip the character already parsed.
        ++it;
        continue;
      }

      // If execution gets here it's that a token marker was followed by a
      // character that didn't resolve to anything. This means the file name is
      // invalid.
      return "";
    } else {
      std::optional<char> rotated_char = RotateChar(*it, false);

      if (!rotated_char.has_value()) {
        // There's no way to rotate an illegal character so return an empty
        // string.
        return "";
      }

      key += rotated_char.value();
    }
  }

  return key;
}

// static
BackendParams BackendParamsManager::CreateParamsSync(
    base::FilePath directory,
    BackendType backend_type,
    const std::string& filename,
    AccessRights access_rights) {
  BackendParams params;
  params.type = backend_type;

  const bool writes_supported = (access_rights == AccessRights::kReadWrite);
  uint32_t flags = base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_READ;

  if (writes_supported) {
    flags |= base::File::FLAG_WRITE;
  }

#if BUILDFLAG(IS_WIN)
  // PersistentCache backing files are not executables.
  flags |= base::File::FLAG_WIN_NO_EXECUTE;

  // String conversion to wstring necessary on Windows.
  std::wstring filename_part = base::UTF8ToWide(filename);
  base::FilePath db_file_name =
      base::FilePath(base::StrCat({filename_part, kDbFile}));
  base::FilePath journal_file_name =
      base::FilePath(base::StrCat({filename_part, kJournalFile}));
#else
  base::FilePath db_file_name =
      base::FilePath(base::StrCat({filename, kDbFile}));
  base::FilePath journal_file_name =
      base::FilePath(base::StrCat({filename, kJournalFile}));
#endif

  base::FilePath db_file_full_path = directory.Append(db_file_name);
  params.db_file = base::File(db_file_full_path, flags);
  params.db_file_is_writable = writes_supported;

  base::FilePath journal_file_full_path = directory.Append(journal_file_name);
  params.journal_file = base::File(journal_file_full_path, flags);
  params.journal_file_is_writable = writes_supported;

  if (!params.db_file.IsValid() || !params.journal_file.IsValid()) {
    size_t smallest_path_length =
        std::min(db_file_full_path.value().length(),
                 journal_file_full_path.value().length());
    if (smallest_path_length > kMaxFilePathLength) {
      base::UmaHistogramCounts100(
          "PersistentCache.ParamsManager.FilenameCharactersOverLimit",
          smallest_path_length - kMaxFilePathLength);
    }
  }

  return params;
}

void BackendParamsManager::SaveParams(const std::string& key,
                                      CompletedCallback callback,
                                      BackendParams backend_params) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (callback) {
    std::move(callback).Run(backend_params);
  }

  // Avoid saving invalid files.
  if (backend_params.db_file.IsValid() &&
      backend_params.journal_file.IsValid()) {
    backend_params_map_.Put(
        BackendParamsKey{.backend_type = backend_params.type, .key = key},
        std::move(backend_params));
  }
}

// static
std::string BackendParamsManager::GetAllAllowedCharactersInKeysForTesting() {
  // Start with all characters allowed in both keys and filenames.
  std::string allowed_characters(kAllowedCharsInFilenames);

  // Add characters only allowed in keys.
  for (const auto& pair : kCharacterToTokenMap) {
    allowed_characters += pair.first;
  }

  return allowed_characters;
}

}  // namespace persistent_cache