File: no_vary_search_cache_storage.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 (693 lines) | stat: -rw-r--r-- 26,356 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
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
// 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 "net/http/no_vary_search_cache_storage.h"

#include <stdint.h>

#include <algorithm>
#include <string>
#include <type_traits>
#include <utility>

#include "base/check.h"
#include "base/check_op.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/metrics/histogram_functions.h"
#include "base/numerics/byte_conversions.h"
#include "base/pickle.h"
#include "base/sequence_checker.h"
#include "base/strings/string_util.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "base/types/cxx23_to_underlying.h"
#include "net/base/pickle.h"
#include "net/base/pickle_base_types.h"
#include "net/base/pickle_traits.h"
#include "net/http/http_no_vary_search_data.h"
#include "net/http/no_vary_search_cache.h"
#include "net/http/no_vary_search_cache_storage_file_operations.h"

namespace net {

namespace {

using FileOperations = NoVarySearchCacheStorageFileOperations;

// Efficiently creates an HttpNoVarySearchData object whose contents don't
// matter because it is going to be overwritten anyway.
HttpNoVarySearchData CreateHttpNoVarySearchData() {
  return HttpNoVarySearchData::CreateFromNoVaryParams({}, false);
}

// Persists `pickle` to kSnapshotFilename with kSnapshotMagicNumber using
// `operations`.
bool PersistPickleAsSnapshot(FileOperations* operations, base::Pickle pickle) {
  auto magic =
      base::U32ToBigEndian(NoVarySearchCacheStorage::kSnapshotMagicNumber);
  auto result = operations->AtomicSave(
      NoVarySearchCacheStorage::kSnapshotFilename, {magic, pickle});
  if (!result.has_value()) {
    base::UmaHistogramExactLinear("HttpCache.NoVarySearch.SnapshotSaveError",
                                  -result.error(), -base::File::FILE_ERROR_MAX);
    return false;
  }

  return true;
}

// Serializes and persists `cache` using `operations`. Returns the size of the
// created file on success, or zero on error.
size_t PersistCache(FileOperations* operations,
                    const NoVarySearchCache& cache) {
  base::Pickle pickle;
  WriteToPickle(pickle, cache);
  const size_t snapshot_size = pickle.size();
  return PersistPickleAsSnapshot(operations, std::move(pickle)) ? snapshot_size
                                                                : 0;
}

// Do not modify this enum without changing kJournalMagicNumber.
enum class JournalEntryType : uint32_t {
  kInsert = 0,
  kErase = 1,
};

}  // namespace

// Make JournalEntryType serializable.
template <>
struct PickleTraits<JournalEntryType> {
  static void Serialize(base::Pickle& pickle, const JournalEntryType& value) {
    WriteToPickle(pickle, base::to_underlying(value));
  }

  static std::optional<JournalEntryType> Deserialize(
      base::PickleIterator& iter) {
    auto underlying =
        ReadValueFromPickle<std::underlying_type_t<JournalEntryType>>(iter);
    if (!underlying) {
      return std::nullopt;
    }
    JournalEntryType value = static_cast<JournalEntryType>(underlying.value());
    if (value != JournalEntryType::kInsert &&
        value != JournalEntryType::kErase) {
      return std::nullopt;
    }
    return value;
  }

  static size_t PickleSize(const JournalEntryType& value) {
    return EstimatePickleSize(base::to_underlying(value));
  }
};

// Performs journalling operations on the background sequence on behalf of
// NoVarySearchCacheStorage. Is created, destroyed, and called exclusively on
// the background sequence.
class NoVarySearchCacheStorage::Journaller final {
 public:
  enum CreateResult {
    kSuccess,
    kCouldntCreateJournal,
    kCouldntStartJournal,
  };

  // Journal using `operations` for `storage_ptr`, which should be notified
  // about important events by posting tasks to `parent_sequence`.
  // `snapshot_size` is the size of the "snapshot.baf" file, which is used to
  // decide when the journal has got too big and we should trigger a new
  // snapshot of the cache. This object is always constructed by
  // NoVarySearchCacheStorage::Loader.
  Journaller(std::unique_ptr<FileOperations> operations,
             base::WeakPtr<NoVarySearchCacheStorage> storage_ptr,
             scoped_refptr<base::SequencedTaskRunner> parent_sequence,
             size_t snapshot_size)
      : operations_(std::move(operations)),
        storage_ptr_(std::move(storage_ptr)),
        parent_sequence_(std::move(parent_sequence)),
        snapshot_size_(snapshot_size) {}

  ~Journaller() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); }

  // Creates a new "journal.baj" file and writes the magic number to it. Called
  // by NoVarySearchCacheStorage::Loader and the WriteSnapshot() method.
  CreateResult Start() {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    CHECK(!failed_);
    auto maybe_writer = operations_->CreateWriter(kJournalFilename);
    if (!maybe_writer.has_value()) {
      base::UmaHistogramExactLinear("HttpCache.NoVarySearch.JournalCreateError",
                                    -maybe_writer.error(),
                                    -base::File::FILE_ERROR_MAX);
      return CreateResult::kCouldntCreateJournal;
    }
    writer_ = std::move(maybe_writer.value());
    size_ = 0u;
    if (!writer_->Write(base::U32ToBigEndian(kJournalMagicNumber))) {
      base::UmaHistogramBoolean("HttpCache.NoVarySearch.JournalStartError",
                                true);
      return CreateResult::kCouldntStartJournal;
    }
    size_ += sizeof(kJournalMagicNumber);
    return CreateResult::kSuccess;
  }

  // Appends an update to the journal. Called via PostTask by
  // NoVarySearchCacheStorage.
  void Append(const base::Pickle& pickle) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    // Multiple calls to `Append()` may be pending in the task queue. After one
    // has failed the rest should be ignored.
    if (failed_) {
      return;
    }

    // The Pickle format has a length field, but because it supports arbitrary
    // header lengths it is not properly self-delimiting. So we need to prepend
    // our own length field to be able to read it back reliably. It's better to
    // do a single write to increase the chance that it will succeed or fail
    // atomically, so pre-assemble the output.
    std::vector<uint8_t> assembled;
    assembled.reserve(sizeof(uint32_t) + pickle.size());
    const auto size_as_bytes =
        base::U32ToLittleEndian(base::checked_cast<uint32_t>(pickle.size()));
    assembled.insert(assembled.end(), size_as_bytes.begin(),
                     size_as_bytes.end());
    assembled.insert(assembled.end(), pickle.begin(), pickle.end());

    if (!writer_->Write(assembled)) {
      base::UmaHistogramBoolean("HttpCache.NoVarySearch.JournalAppendError",
                                true);
      JournallingFailed();
      return;
    }
    size_ += assembled.size();
    if (size_ > std::max(snapshot_size_, kMinimumAutoSnapshotSize)) {
      MaybeRequestSnapshot();
    }
  }

  // Rewrites the "snapshot.baf" file from `pickle` and then creates a new empty
  // journal file. Called via PostTask by NoVarySearchCacheStorage.
  void WriteSnapshot(base::Pickle pickle) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    if (failed_) {
      return;
    }

    requested_snapshot_ = false;
    snapshot_size_ = pickle.size();

    if (!PersistPickleAsSnapshot(operations_.get(), std::move(pickle))) {
      JournallingFailed();
      return;
    }

    if (!Start()) {
      JournallingFailed();
    }
  }

 private:
  // Notify NoVarySearchCacheStorage that journalling has failed and it should
  // destroy this object.
  void JournallingFailed() VALID_CONTEXT_REQUIRED(sequence_checker_) {
    CHECK(!failed_);
    failed_ = true;
    // This object will be deleted shortly.
    parent_sequence_->PostTask(
        FROM_HERE,
        base::BindOnce(&NoVarySearchCacheStorage::OnJournallingFailed,
                       storage_ptr_));
  }

  // Request NoVarySearchCacheStorage to serialize the NoVarySearchCache object
  // and call WriteSnapshot() with it.
  void MaybeRequestSnapshot() VALID_CONTEXT_REQUIRED(sequence_checker_) {
    if (requested_snapshot_) {
      // TODO(https://crbug.com/399562754): Write a unit test for this line.
      return;
    }
    requested_snapshot_ = true;
    parent_sequence_->PostTask(
        FROM_HERE,
        base::BindOnce(&NoVarySearchCacheStorage::TakeSnapshot, storage_ptr_));
  }

  // The FileOperations implementation to be used for file operations.
  const std::unique_ptr<FileOperations> operations_;

  // A pointer back to the object that owns this Journaller. This pointer must
  // not be dereferenced on this sequence; it is only for use in binding
  // closures to be posted to `parent_sequence_`.
  const base::WeakPtr<NoVarySearchCacheStorage> storage_ptr_;

  // The sequence that the NoVarySearchCacheStorage object lives on.
  const scoped_refptr<base::SequencedTaskRunner> parent_sequence_;

  // Handle to write to "journal.baj".
  std::unique_ptr<FileOperations::Writer> writer_
      GUARDED_BY_CONTEXT(sequence_checker_);

  // The current size of "journal.baj".
  size_t size_ GUARDED_BY_CONTEXT(sequence_checker_) = 0;

  // The current size of "snapshot.baf".
  size_t snapshot_size_ GUARDED_BY_CONTEXT(sequence_checker_);

  // True if journalling has failed. There may still be tasks in flight.
  bool failed_ GUARDED_BY_CONTEXT(sequence_checker_) = false;

  // True if we've requested a snapshot since the last one. This stops us
  // sending multiple requests.
  bool requested_snapshot_ GUARDED_BY_CONTEXT(sequence_checker_) = false;

  SEQUENCE_CHECKER(sequence_checker_);
};

// Loading the previous cache is a synchronous operation and could be defined
// in a single function, but for readability it is split into methods.
// Everything in this class happens on the background thread.
class NoVarySearchCacheStorage::Loader final {
 public:
  // This must match the argument type of
  // NoVarySearchCacheStorage::OnStartComplete().
  using ResultType = base::expected<CacheAndJournalPointers, LoadFailed>;

  // Creates a Loader object, loads the cache, and returns the result. On
  // success, returns the loaded NoVarySearchCache object and a Journaller
  // object which will post tasks to the NoVarySearchCacheStorage object pointed
  // to by `storage_ptr` using `parent_sequence`. `default_max_size` is the
  // max_size to use for a new NoVarySearchCache object if we are unable to load
  // an existing one. This is called via PostTaskAndReplyWithResult() from
  // NoVarySearchCacheStorage::Load(), which arranges for the result to be sent
  // to the OnLoadComplete() method of that object on the original thread.
  static ResultType CreateAndLoad(
      std::unique_ptr<FileOperations> operations,
      base::WeakPtr<NoVarySearchCacheStorage> storage_ptr,
      scoped_refptr<base::SequencedTaskRunner> parent_sequence,
      size_t default_max_size) {
    // As this whole process is synchronous, the Loader object can be allocated
    // on the stack.
    Loader loader(std::move(operations), std::move(storage_ptr),
                  std::move(parent_sequence), default_max_size);
    return loader.Load();
  }

  Loader(const Loader&) = delete;
  Loader& operator=(const Loader&) = delete;

 private:
  // Possible results of attempted load.
  //
  // These values are persisted to logs. Entries should not be renumbered and
  // numeric values should never be reused.
  //
  // LINT.IfChange(Result)
  enum class Result {
    kSuccess = 0,
    kSnapshotFileTooSmall = 1,
    kSnapshotLoadFailed = 2,
    kBadSnapshotMagicNumber = 3,
    kInvalidSnapshotPickle = 4,
    kJournalLoadFailed = 5,
    kJournalTooOld = 6,
    kJournalTooSmall = 7,
    kBadJournalMagicNumber = 8,
    kCorruptJournal = 9,
    kCorruptJournalEntry = 10,
    kCouldntCreateCacheFile = 11,
    kCouldntCreateJournal = 12,
    kCouldntStartJournal = 13,
    kOperationsInitFailed = 14,
    kMaxValue = kOperationsInitFailed,
  };
  // LINT.ThenChange(//tools/metrics/histograms/metadata/net/enums.xml:NoVarySearchCacheStorageLoadResult)

  struct ReplayJournalResult {
    size_t replayed_journal_entries = 0u;
    bool had_error = false;
  };

  Loader(std::unique_ptr<FileOperations> operations,
         base::WeakPtr<NoVarySearchCacheStorage> storage_ptr,
         scoped_refptr<base::SequencedTaskRunner> parent_sequence,
         size_t default_max_size)
      : operations_(std::move(operations)),
        storage_ptr_(std::move(storage_ptr)),
        parent_sequence_(std::move(parent_sequence)),
        default_max_size_(default_max_size) {}

  ~Loader() = default;

  // Starts loading persisted cache files and preparing to journal. The return
  // value from this object will be posted back to the main thread. Calls into
  // other methods of this object to handle various exceptional conditions.
  [[nodiscard]] ResultType Load() {
    if (!operations_->Init()) {
      return GiveUp(Result::kOperationsInitFailed);
    }
    auto maybe_load_result = operations_->Load(kSnapshotFilename, kMaxFileSize);
    if (!maybe_load_result.has_value()) {
      base::UmaHistogramExactLinear("HttpCache.NoVarySearch.SnapshotLoadError",
                                    -maybe_load_result.error(),
                                    -base::File::FILE_ERROR_MAX);
      return StartFromScratch(Result::kSnapshotLoadFailed);
    }
    auto [snapshot_contents, snapshot_last_modified] =
        std::move(maybe_load_result.value());
    static constexpr size_t kMagicNumberSize = sizeof(kSnapshotMagicNumber);
    snapshot_size_ = snapshot_contents.size();
    if (snapshot_size_ < kMagicNumberSize) {
      return StartFromScratch(Result::kSnapshotFileTooSmall);
    }
    auto [snapshot_magic_number, snapshot_pickle] =
        base::span(snapshot_contents).split_at<kMagicNumberSize>();
    if (base::U32FromBigEndian(snapshot_magic_number) != kSnapshotMagicNumber) {
      return StartFromScratch(Result::kBadSnapshotMagicNumber);
    }

    auto pickle = base::Pickle::WithUnownedBuffer(snapshot_pickle);
    auto maybe_cache = ReadValueFromPickle<NoVarySearchCache>(pickle);
    if (!maybe_cache) {
      return StartFromScratch(Result::kInvalidSnapshotPickle);
    }
    cache_ =
        std::make_unique<NoVarySearchCache>(std::move(maybe_cache.value()));

    auto journal_load_result =
        operations_->Load(kJournalFilename, kMaxFileSize);
    if (!journal_load_result.has_value()) {
      base::UmaHistogramExactLinear("HttpCache.NoVarySearch.JournalLoadError",
                                    -journal_load_result.error(),
                                    -base::File::FILE_ERROR_MAX);
      return StartJournal(Result::kJournalLoadFailed);
    }
    auto [journal_contents, journal_last_modified] =
        std::move(journal_load_result.value());
    if (journal_last_modified < snapshot_last_modified) {
      // This can happen if the previous run was interrupted during rewriting
      // the cache.
      return StartJournal(Result::kJournalTooOld);
    }
    if (journal_contents.size() < kMagicNumberSize) {
      return StartJournal(Result::kJournalTooSmall);
    }
    auto [journal_magic_number, journal_pickles] =
        base::span(journal_contents).split_at<kMagicNumberSize>();
    if (base::U32FromBigEndian(journal_magic_number) != kJournalMagicNumber) {
      return StartJournal(Result::kBadJournalMagicNumber);
    }
    if (journal_pickles.empty()) {
      return StartJournal(Result::kSuccess);
    }
    auto [replayed_journal_entries, had_error] = ReplayJournal(journal_pickles);
    if (replayed_journal_entries == 0u) {
      return StartJournal(had_error ? Result::kCorruptJournal
                                    : Result::kSuccess);
    }
    // Now that we've replayed the journal into `cache`, write a new snapshot
    // of it to disk along with a fresh empty journal.
    return WriteCache(had_error ? Result::kCorruptJournalEntry
                                : Result::kSuccess);
  }

  // Creates an empty cache and journal file. Used when we couldn't load a
  // persisted cache.
  [[nodiscard]] ResultType StartFromScratch(Result result) {
    cache_ = std::make_unique<NoVarySearchCache>(default_max_size_);
    return WriteCache(result);
  }

  // Deserializes base::Pickle objects representing cache mutations from
  // `pickles` and applies them to `cache`. Each base::Pickle is preceded by a
  // 32-bit length field. Continues until it encounters the end of `pickles` or
  // an error.
  ReplayJournalResult ReplayJournal(base::span<const uint8_t> pickles) {
    size_t replayed_journal_entries = 0u;
    bool had_error = false;

    while (!pickles.empty() && !had_error) {
      if (pickles.size() < sizeof(uint32_t)) {
        had_error = true;
        break;
      }
      const auto size_as_bytes = pickles.take_first<sizeof(uint32_t)>();
      const uint32_t size = base::U32FromLittleEndian(size_as_bytes);
      if (pickles.size() < size) {
        had_error = true;
        break;
      }
      const auto pickle_span = pickles.take_first(size);
      const auto pickle = base::Pickle::WithUnownedBuffer(pickle_span);
      if (pickle.size() == 0) {
        // The Pickle header was invalid.
        had_error = true;
        break;
      }
      base::PickleIterator iter(pickle);
      auto maybe_type = ReadValueFromPickle<JournalEntryType>(iter);
      if (!maybe_type) {
        had_error = true;
        break;
      }
      switch (maybe_type.value()) {
        case JournalEntryType::kInsert: {
          std::string base_url_cache_key;
          auto nvs_data = CreateHttpNoVarySearchData();
          std::optional<std::string> query;
          base::Time update_time;
          if (!ReadPickleInto(iter, base_url_cache_key, nvs_data, query,
                              update_time) ||
              !iter.ReachedEnd()) {
            had_error = true;
            break;
          }
          cache_->ReplayInsert(std::move(base_url_cache_key),
                               std::move(nvs_data), std::move(query),
                               update_time);
          ++replayed_journal_entries;
          break;
        }

        case JournalEntryType::kErase: {
          std::string base_url_cache_key;
          auto nvs_data = CreateHttpNoVarySearchData();
          std::optional<std::string> query;
          if (!ReadPickleInto(iter, base_url_cache_key, nvs_data, query) ||
              !iter.ReachedEnd()) {
            had_error = true;
            break;
          }
          cache_->ReplayErase(base_url_cache_key, nvs_data, query);
          ++replayed_journal_entries;
          break;
        }
      }
    }
    base::UmaHistogramCounts100000(
        "HttpCache.NoVarySearch.ReplayedJournalEntries",
        replayed_journal_entries);

    return {replayed_journal_entries, had_error};
  }

  // Creates or replaces the snapshot.baf file with a new snapshot created by
  // serializing `cache`.
  [[nodiscard]] ResultType WriteCache(Result result) {
    snapshot_size_ = PersistCache(operations_.get(), *cache_);
    if (snapshot_size_ == 0u) {
      return GiveUp(Result::kCouldntCreateCacheFile);
    }
    return StartJournal(result);
  }

  // Stops attempting to restore the persisted data or create a new journal.
  // Logs a histogram with `result` and then returns a LoadFailed value which
  // will be posted back to the main thread.
  [[nodiscard]] ResultType GiveUp(Result result) {
    LogResult(result);
    return base::unexpected(LoadFailed::kCannotJournal);
  }

  // Starts a new journal.baj file. On success, `cache_` and `result` will be
  // passed back to the main thread. On failure, gives up.
  [[nodiscard]] ResultType StartJournal(Result result) {
    CHECK_GT(snapshot_size_, 0u);
    auto journal = std::make_unique<Journaller>(
        std::move(operations_), std::move(storage_ptr_),
        std::move(parent_sequence_), snapshot_size_);
    auto create_result = journal->Start();
    if (create_result != Journaller::CreateResult::kSuccess) {
      return GiveUp(create_result ==
                            Journaller::CreateResult::kCouldntCreateJournal
                        ? Result::kCouldntCreateJournal
                        : Result::kCouldntStartJournal);
    }
    LogResult(result);
    CHECK(cache_);
    return CacheAndJournalPointers(
        std::move(cache_),
        JournallerPtr(journal.release(),
                      base::OnTaskRunnerDeleter(
                          base::SequencedTaskRunner::GetCurrentDefault())));
  }

  // Logs a histogram with the final result of loading.
  void LogResult(Result result) {
    base::UmaHistogramEnumeration("HttpCache.NoVarySearch.LoadResult", result);
  }

  // The FileOperations implementation used by this object and passed to the
  // Journaller object when it is created.
  std::unique_ptr<FileOperations> operations_;

  // The NoVarySearchCacheStorage object is not directly used by this object,
  // but the pointer is retained to be transferred to the Journaller object when
  // it is created. This pointer must not be dereferenced on this thread.
  base::WeakPtr<NoVarySearchCacheStorage> storage_ptr_;

  // This object doesn't use `parent_sequence_` except to pass it to the
  // Journaller object.
  scoped_refptr<base::SequencedTaskRunner> parent_sequence_;

  // The size of the created "snapshot.baf" file.
  size_t snapshot_size_ = 0;

  // The default `max_size` parameter used if we create a NoVarySearchCache
  // object from scratch.
  size_t default_max_size_;

  // This will be passed back to the main thread on success.
  std::unique_ptr<NoVarySearchCache> cache_;
};

NoVarySearchCacheStorage::CacheAndJournalPointers::CacheAndJournalPointers(
    std::unique_ptr<NoVarySearchCache> cache,
    JournallerPtr journal)
    : cache(std::move(cache)), journal(std::move(journal)) {}

NoVarySearchCacheStorage::CacheAndJournalPointers::CacheAndJournalPointers(
    CacheAndJournalPointers&&) = default;
NoVarySearchCacheStorage::CacheAndJournalPointers::~CacheAndJournalPointers() =
    default;

NoVarySearchCacheStorage::NoVarySearchCacheStorage()
    : journal_(nullptr, base::OnTaskRunnerDeleter(nullptr)) {}

NoVarySearchCacheStorage::~NoVarySearchCacheStorage() {
  if (cache_) {
    cache_->SetJournal(nullptr);
  }
}

void NoVarySearchCacheStorage::Load(
    std::unique_ptr<NoVarySearchCacheStorageFileOperations> file_operations,
    size_t default_max_size,
    LoadCallback callback) {
  CHECK(!cache_);
  CHECK(!background_task_runner_);
  CHECK(!journal_);
  CHECK(start_time_.is_null());

  background_task_runner_ = base::ThreadPool::CreateSequencedTaskRunner(
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN});
  start_time_ = base::Time::Now();
  background_task_runner_->PostTaskAndReplyWithResult(
      FROM_HERE,
      base::BindOnce(&Loader::CreateAndLoad, std::move(file_operations),
                     weak_factory_.GetWeakPtr(),
                     base::SequencedTaskRunner::GetCurrentDefault(),
                     default_max_size),
      base::BindOnce(&NoVarySearchCacheStorage::OnLoadComplete,
                     weak_factory_.GetWeakPtr(), std::move(callback)));
}

void NoVarySearchCacheStorage::TakeSnapshot() {
  if (!cache_ || !journal_) {
    return;
  }
  CHECK(background_task_runner_);
  base::Pickle pickle;
  WriteToPickle(pickle, *cache_);
  // This use of `base::Unretained` is safe because `journal_` is owned by this
  // object and always deleted on `background_task_runner_`.
  background_task_runner_->PostTask(
      FROM_HERE,
      base::BindOnce(&Journaller::WriteSnapshot,
                     base::Unretained(journal_.get()), std::move(pickle)));
}

void NoVarySearchCacheStorage::OnInsert(const std::string& base_url_cache_key,
                                        const HttpNoVarySearchData& nvs_data,
                                        const std::optional<std::string>& query,
                                        base::Time update_time) {
  base::Pickle pickle;
  WriteToPickle(pickle, JournalEntryType::kInsert, base_url_cache_key, nvs_data,
                query, update_time);
  AppendToJournal(std::move(pickle));
}

void NoVarySearchCacheStorage::OnErase(
    const std::string& base_url_cache_key,
    const HttpNoVarySearchData& nvs_data,
    const std::optional<std::string>& query) {
  base::Pickle pickle;
  WriteToPickle(pickle, JournalEntryType::kErase, base_url_cache_key, nvs_data,
                query);
  AppendToJournal(std::move(pickle));
}

void NoVarySearchCacheStorage::AppendToJournal(base::Pickle pickle) {
  CHECK(journal_);
  CHECK(background_task_runner_);
  // This use of `base::Unretained` is safe because `journal_` is owned by this
  // object and always deleted on `background_task_runner_`.
  background_task_runner_->PostTask(
      FROM_HERE,
      base::BindOnce(&Journaller::Append, base::Unretained(journal_.get()),
                     std::move(pickle)));
}

void NoVarySearchCacheStorage::OnLoadComplete(
    LoadCallback callback,
    base::expected<CacheAndJournalPointers, LoadFailed> result) {
  const base::TimeDelta elapsed = base::Time::Now() - start_time_;
  if (!result.has_value()) {
    base::UmaHistogramTimes("HttpCache.NoVarySearch.LoadTime.Failure", elapsed);
    background_task_runner_ = nullptr;
    // Continue without persistence.
    std::move(callback).Run(base::unexpected(result.error()));
    return;
  }
  base::UmaHistogramTimes("HttpCache.NoVarySearch.LoadTime.Success", elapsed);
  auto [cache, journal] = std::move(result.value());
  CHECK(journal);
  CHECK(!journal_);
  journal_ = std::move(journal);
  CHECK(cache);
  base::UmaHistogramCounts10000("HttpCache.NoVarySearch.EntriesLoaded",
                                cache->size());
  CHECK(!cache_);
  cache_ = cache.get();
  cache_->SetJournal(this);
  std::move(callback).Run(std::move(cache));
}

void NoVarySearchCacheStorage::OnJournallingFailed() {
  cache_->SetJournal(nullptr);
  journal_ = nullptr;
  cache_ = nullptr;
  background_task_runner_ = nullptr;
}

}  // namespace net