File: shared_storage_database.h

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 (715 lines) | stat: -rw-r--r-- 32,596 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
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
// 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.

#ifndef COMPONENTS_SERVICES_STORAGE_SHARED_STORAGE_SHARED_STORAGE_DATABASE_H_
#define COMPONENTS_SERVICES_STORAGE_SHARED_STORAGE_SHARED_STORAGE_DATABASE_H_

#include <inttypes.h>

#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "base/files/file_path.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/sequence_checker.h"
#include "base/thread_annotations.h"
#include "base/threading/sequence_bound.h"
#include "base/time/clock.h"
#include "base/types/optional_ref.h"
#include "components/services/storage/public/mojom/storage_usage_info.mojom-forward.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "sql/database.h"
#include "sql/meta_table.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "third_party/blink/public/mojom/shared_storage/shared_storage_worklet_service.mojom.h"

namespace base {
class FilePath;
class Time;
class TimeDelta;
}  // namespace base

namespace net {
class SchemefulSite;
}  // namespace net

namespace sql {
class Statement;
}  // namespace sql

namespace url {
class Origin;
}  // namespace url

namespace storage {
struct SharedStorageDatabaseOptions;
class SpecialStoragePolicy;

// Wraps its own `sql::Database` instance on behalf of the Shared Storage
// backend implementation. This object is not sequence-safe and must be
// instantiated on a sequence which allows use of blocking file operations.
class SharedStorageDatabase {
 public:
  // A callback type to check if a given StorageKey matches a storage policy.
  // Can be passed empty/null where used, which means the StorageKey will always
  // match.
  using StorageKeyPolicyMatcherFunction =
      base::RepeatingCallback<bool(const blink::StorageKey&,
                                   SpecialStoragePolicy*)>;

  enum class DataClearSource {
    kSite,
    kUI,
    kExpiration,
  };

  enum class InitStatus {
    kUnattempted =
        0,  // Status if `LazyInit()` has not yet been called or if `LazyInit()`
            // has early returned due to `DBCreationPolicy::kIgnoreIfAbsent`.
    kSuccess = 1,  // Status if `LazyInit()` was successful.
    kError = 2,    // Status if `LazyInit()` failed and a more specific error
                   // wasn't diagnosed.
    kTooNew = 3,   // Status if `LazyInit()` failed due to a compatible version
                   // number being too high.
    kTooOld = 4,  // Status if `LazyInit()` failed due to a version number being
                  // too low.
    kUpgradeFailed =
        5,  // Status if migration to current database version failed.
  };

  enum class DBFileStatus {
    kNotChecked = 0,  // Status if DB is file-backed and there hasn't been an
                      // attempt to open the SQL database for the given FilePath
                      // to see if it exists and contains data.
    kNoPreexistingFile =
        1,  // Status if the DB is in-memory or if the DB is file-backed but the
            // attempt to open it was unsuccessful or any pre-existing file
            // contained no data.
    kPreexistingFile =
        2,  // Status if there was a pre-existing file containing at least one
            // table that we were able to successfully open.
  };

  enum class SetBehavior {
    kDefault = 0,  // Sets entry regardless of whether one previously exists.
    kIgnoreIfPresent = 1,  // Does not set an entry if one previously exists.
  };

  // This enum is used to record UMA. Do not reorder, delete, nor
  // insert elements, unless you insert at the end. Also, update
  // the corresponding enum in enums.xml (i.e.
  // "AutofillSharedStorageServerCardDataSetResult"
  // in tools/metrics/histograms/metadata/autofill/enums.xml).
  enum class OperationResult {
    kSuccess = 0,      // Result if a non-setting operation is successful.
    kSet = 1,          // Result if value is set.
    kIgnored = 2,      // Result if value was present and ignored; no error.
    kSqlError = 3,     // Result if there is a SQL database error.
    kInitFailure = 4,  // Result if database initialization failed and a
                       // database is required.
    kNoCapacity = 5,   // Result if there was insufficient capacity for the
    // requesting origin.
    kInvalidAppend = 6,  // Result if the length of the value after appending
    // would exceed the maximum allowed length.
    kNotFound =
        7,  // Result if a key could not be retrieved via `Get()`, a creation
            // time could not be retrieved for an origin via
            // `GetCreationTime()`, or the data from `per_origin_mapping` could
            // not be found via `GetOriginInfo()`, because the key or origin
            // doesn't exist in the database.
    kTooManyFound = 8,  // Result if the number of keys/entries retrieved for
                        // `Keys()`/`Entries()` exceeds INT_MAX.
    kExpired = 9,       // Result if the retrieved entry is expired.
    kMaxValue = kExpired,
  };

  struct BatchUpdateResult {
    BatchUpdateResult(OperationResult overall_result,
                      std::vector<OperationResult> inner_method_results);
    ~BatchUpdateResult();

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

    // Indicates the overall result of the batch update operation. If the entire
    // batch succeeded, it will be `kSuccess`. Otherwise, it will hold the first
    // error encountered, either from the batch itself or from an individual
    // inner method. If an inner method failed, this will match the last element
    // of `inner_method_results`.
    OperationResult overall_result = OperationResult::kSqlError;

    // Stores the results of each inner method, in the order they were executed.
    // Contains results up to and including the first failed method or all
    // methods if the entire batch succeeded. Note that even if an inner method
    // succeeds, it will be rolled back if a subsequent operation within the
    // same transaction fails.
    std::vector<OperationResult> inner_method_results;
  };

  // Bundles a retrieved string `data` and its last write time `last_used_time`
  // from the database along with a field `result` indicating whether the
  // transaction was free of SQL errors.
  struct GetResult {
    std::u16string data;
    base::Time last_used_time = base::Time::Min();
    OperationResult result = OperationResult::kSqlError;
    GetResult();
    GetResult(const GetResult&) = delete;
    GetResult(GetResult&&);
    explicit GetResult(OperationResult result);
    GetResult(std::u16string data,
              base::Time last_used_time,
              OperationResult result);
    ~GetResult();
    GetResult& operator=(const GetResult&) = delete;
    GetResult& operator=(GetResult&&);
  };

  // Bundles a double `bits` representing the available bits remaining for the
  // queried origin along with a field indicating whether the database retrieval
  // was free of SQL errors.
  struct BudgetResult {
    double bits = 0.0;
    OperationResult result = OperationResult::kSqlError;
    BudgetResult(const BudgetResult&) = delete;
    BudgetResult(BudgetResult&&);
    BudgetResult(double bits, OperationResult result);
    ~BudgetResult();
    BudgetResult& operator=(const BudgetResult&) = delete;
    BudgetResult& operator=(BudgetResult&&);
  };

  // Bundles a `time` with a field indicating whether the database retrieval
  // was free of SQL errors.
  struct TimeResult {
    base::Time time;
    OperationResult result = OperationResult::kSqlError;
    TimeResult();
    TimeResult(const TimeResult&) = delete;
    TimeResult(TimeResult&&);
    explicit TimeResult(OperationResult result);
    ~TimeResult();
    TimeResult& operator=(const TimeResult&) = delete;
    TimeResult& operator=(TimeResult&&);
  };

  // Bundles info about an origin's shared storage for DevTools integration.
  struct MetadataResult {
    int length = -1;
    int bytes_used = -1;
    base::Time creation_time = base::Time::Min();
    double remaining_budget = 0;
    OperationResult time_result = OperationResult::kSqlError;
    OperationResult budget_result = OperationResult::kSqlError;
    MetadataResult();
    MetadataResult(const MetadataResult&) = delete;
    MetadataResult(MetadataResult&&);
    ~MetadataResult();
    MetadataResult& operator=(const MetadataResult&) = delete;
    MetadataResult& operator=(MetadataResult&&);
  };

  // Bundles an origin's shared storage entries with an `OperationResult` for
  // DevTools integration.
  struct EntriesResult {
    std::vector<std::pair<std::string, std::string>> entries;
    OperationResult result = OperationResult::kSqlError;
    EntriesResult();
    EntriesResult(const EntriesResult&) = delete;
    EntriesResult(EntriesResult&&);
    ~EntriesResult();
    EntriesResult& operator=(const EntriesResult&) = delete;
    EntriesResult& operator=(EntriesResult&&);
  };

  // Exposed for testing.
  static const int kCurrentVersionNumber;
  static const int kCompatibleVersionNumber;
  static const int kDeprecatedVersionNumber;

  // When `db_path` is empty, the database will be opened in memory only.
  SharedStorageDatabase(
      base::FilePath db_path,
      scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy,
      std::unique_ptr<SharedStorageDatabaseOptions> options);

  SharedStorageDatabase(const SharedStorageDatabase&) = delete;
  SharedStorageDatabase(const SharedStorageDatabase&&) = delete;

  ~SharedStorageDatabase();

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

  // Deletes the database and returns whether the operation was successful.
  //
  // It is OK to call `Destroy()` regardless of whether `Init()` was successful.
  [[nodiscard]] bool Destroy();

  // Returns a pointer to the database containing the actual data.
  [[nodiscard]] sql::Database* db() {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return &db_;
  }

  // Returns whether or not the database is file-backed (rather than in-memory).
  [[nodiscard]] bool is_filebacked() {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return !db_path_.empty();
  }

  // Releases all non-essential memory associated with this database connection.
  void TrimMemory();

  // Retrieves the `value` for `context_origin` and `key`. Returns a
  // struct containing a `data` string if a `value` is found, with an
  // `OperationResult` indicating whether the value was found and the
  // transaction was free of errors.
  //
  // If an expired value is found, then `OperationResult::kExpired` is returned;
  // if no value is found, `OperationResult::kNotFound` is returned.
  //
  // Note that `key` is assumed to be of length at most
  // `max_string_length_`, with the burden on the caller to handle errors for
  // strings that exceed this length.
  [[nodiscard]] GetResult Get(const url::Origin& context_origin,
                              std::u16string_view key);

  // Sets an entry for `context_origin` and `key` to have `value`.
  // If `behavior` is `kIgnoreIfPresent` and an unexpired entry already exists
  // for `context_origin` and `key`, then the table is not modified. If an
  // expired entry is found, the entry is replaced, regardless of `behavior`.
  // Returns an enum indicating whether or not a new entry is added, the request
  // is ignored, or if there is an error.
  //
  // Note that `key` and `value` are assumed to be each of length at most
  // `max_string_length_`, with the burden on the caller to handle errors for
  // strings that exceed this length. Moreover, if `BytesUsed(context_origin)`
  // plus any additional bytes to be stored by this call would exceed
  // `max_bytes_per_origin_`, `Set()` will return a value of
  // `OperationResult::kNoCapacity` and the table will not be modified.
  [[nodiscard]] OperationResult Set(
      const url::Origin& context_origin,
      std::u16string_view key,
      std::u16string_view value,
      SetBehavior behavior = SetBehavior::kDefault);

  // Appends `tail_value` to the end of the current `value`
  // for `context_origin` and `key`, if `key` exists and is not expired. If
  // `key` does not exist, creates an entry for `key` with value `tail_value`.
  // If `key` is expired, creates an entry for `key` with value `tail_value`
  // after deleting the expired entry. Returns an enum indicating whether or not
  // an entry is added/modified or if there is an error.
  //
  // Note that `key` and `tail_value` are assumed to be each of length at most
  // `max_string_length_`, with the burden on the caller to handle errors for
  // strings that exceed this length. Moreover, if the length of the string
  // obtained by concatening the current `value` (if one exists) and
  // `tail_value` exceeds `max_string_length_`, `Append()` will return a value
  // of `OperationResult::kInvalidAppend` and the table will not be modified.
  // Similarly,if `BytesUsed(context_origin)` plus any additional bytes to be
  // stored by this call would exceed `max_bytes_per_origin_`, `Append()` will
  // return a value of `OperationResult::kNoCapacity` and the table will not be
  // modified.
  [[nodiscard]] OperationResult Append(const url::Origin& context_origin,
                                       std::u16string_view key,
                                       std::u16string_view tail_value);

  // Deletes the entry for `context_origin` and `key`. Returns whether the
  // deletion is successful.
  //
  // Note that `key` is assumed to be of length at most `max_string_length_`,
  // with the burden on the caller to handle errors for strings that exceed this
  // length.
  [[nodiscard]] OperationResult Delete(const url::Origin& context_origin,
                                       std::u16string_view key);

  // Clears all entries for `context_origin`. Returns whether the operation is
  // successful.
  [[nodiscard]] OperationResult Clear(
      const url::Origin& context_origin,
      DataClearSource source = DataClearSource::kSite);

  // Executes `methods_with_options` as a transaction. If any method fails, the
  // entire batch operation is rolled back, and a failure result is returned.
  [[nodiscard]] BatchUpdateResult BatchUpdate(
      const url::Origin& context_origin,
      const std::vector<
          network::mojom::SharedStorageModifierMethodWithOptionsPtr>&
          methods_with_options);

  // Returns the number of unexpired entries for `context_origin` in the
  // database, or -1 on error.
  // TODO(crbug.com/40207867): Consider renaming to something more descriptive.
  [[nodiscard]] int64_t Length(const url::Origin& context_origin);

  // From a list of all the unexpired keys for `context_origin` taken in
  // lexicographic order, send batches of keys to the Shared Storage worklet's
  // async iterator via a remote that consumes `pending_listener`. Returns
  // whether the operation was successful.
  [[nodiscard]] OperationResult Keys(
      const url::Origin& context_origin,
      mojo::PendingRemote<blink::mojom::SharedStorageEntriesListener>
          pending_listener);

  // From a list of all the unexpired key-value pairs for `context_origin` taken
  // in lexicographic order, send batches of key-value pairs to the Shared
  // Storage worklet's async iterator via a remote that consumes
  // `pending_listener`. Returns whether the operation was successful.
  [[nodiscard]] OperationResult Entries(
      const url::Origin& context_origin,
      mojo::PendingRemote<blink::mojom::SharedStorageEntriesListener>
          pending_listener);

  // Returns the number of bytes used by unexpired entries for `context_origin`
  // in the database, or -1 on error.
  [[nodiscard]] int64_t BytesUsed(const url::Origin& context_origin);

  // Clears all origins that match `storage_key_matcher` run on the owning
  // StoragePartition's `SpecialStoragePolicy` and have any key with a
  // `last_used_time` between the times `begin` and `end`. If
  // `perform_storage_cleanup` is true, vacuums the database afterwards. Returns
  // whether the transaction was successful.
  [[nodiscard]] OperationResult PurgeMatchingOrigins(
      StorageKeyPolicyMatcherFunction storage_key_matcher,
      base::Time begin,
      base::Time end,
      bool perform_storage_cleanup = false);

  // Clear all entries whose `last_used_time` (currently the last write access)
  // falls before `clock_->Now() - staleness_threshold_`. Also purges, for all
  // origins, all privacy budget withdrawals that have `time_stamps` older than
  // `clock_->Now() - budget_interval_`. Returns whether the transaction was
  // successful.
  [[nodiscard]] OperationResult PurgeStale();

  // Fetches a vector of `mojom::StorageUsageInfoPtr`, with one
  // `mojom::StorageUsageInfoPtr` for each origin currently using shared
  // storage in this profile.
  [[nodiscard]] std::vector<mojom::StorageUsageInfoPtr> FetchOrigins();

  // Makes a withdrawal of `bits_debit` stamped with the current time from the
  // privacy budget of `context_site`.
  [[nodiscard]] OperationResult MakeBudgetWithdrawal(
      const net::SchemefulSite& context_site,
      double bits_debit);

  // Determines the number of bits remaining in the privacy budget of
  // `context_site`, where only withdrawals within the most recent
  // `budget_interval_` are counted as still valid, and returns this information
  // bundled with an `OperationResult` value to indicate whether the database
  // retrieval was successful.
  [[nodiscard]] BudgetResult GetRemainingBudget(
      const net::SchemefulSite& context_site);

  // Retrieves the most recent `creation_time` for `context_origin`.
  [[nodiscard]] TimeResult GetCreationTime(const url::Origin& context_origin);

  // Calls `Length()`, `GetRemainingBudget()`, and `GetCreationTime()`, then
  // bundles this info along with the accompanying `OperationResult`s into a
  // struct to send to the DevTools `StorageHandler`. Because DevTools displays
  // shared storage data by origin, we continue to pass a `url::Origin` in as
  // parameter `context_origin` and compute the site on the fly to use as
  // parameter for `GetRemainingBudget()`.
  [[nodiscard]] MetadataResult GetMetadata(const url::Origin& context_origin);

  // Returns an origin's entries in a vector bundled with an `OperationResult`.
  // To only be used by DevTools.
  [[nodiscard]] EntriesResult GetEntriesForDevTools(
      const url::Origin& context_origin);

  // Removes all budget withdrawals for `context_origin`'s site. Intended as a
  // convenience for the DevTools UX. Because DevTools displays shared storage
  // data by origin, we continue to pass a `url::Origin` in as parameter
  // `context_origin` and compute the site on the fly.
  [[nodiscard]] OperationResult ResetBudgetForDevTools(
      const url::Origin& context_origin);

  // Returns whether the SQLite database is open.
  [[nodiscard]] bool IsOpenForTesting() const;

  // Returns the `db_status_` for tests.
  [[nodiscard]] InitStatus DBStatusForTesting() const;

  // Changes `creation_time` to `new_creation_time` for `context_origin`.
  [[nodiscard]] bool OverrideCreationTimeForTesting(
      const url::Origin& context_origin,
      base::Time new_creation_time);

  // Changes `last_used_time` to `new_last_used_time` for `context_origin` and
  // `key`.
  [[nodiscard]] bool OverrideLastUsedTimeForTesting(
      const url::Origin& context_origin,
      std::u16string_view key,
      base::Time new_last_used_time);

  // Overrides the clock used to check the time.
  void OverrideClockForTesting(base::Clock* clock);

  // Overrides the `SpecialStoragePolicy` for tests.
  void OverrideSpecialStoragePolicyForTesting(
      scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy);

  // Gets the number of entries (including stale entries) in the table
  // `budget_mapping` for `context_site`. Returns -1 in case of database
  // initialization failure or SQL error.
  [[nodiscard]] int64_t GetNumBudgetEntriesForTesting(
      const net::SchemefulSite& context_site);

  // Returns the total number of entries in the table for all origins, or -1 in
  // case of database initialization failure or SQL error.
  [[nodiscard]] int64_t GetTotalNumBudgetEntriesForTesting();

  // Returns the total number of bytes used by `context_origin`, including for
  // any expired entries, or -1 in case of database initialization failure or
  // SQL error.
  [[nodiscard]] int64_t NumBytesUsedIncludeExpiredForTesting(
      const url::Origin& context_origin);

 private:
  // Policy to tell `LazyInit()` whether or not to create a new database if a
  // pre-existing on-disk database is not found.
  enum class DBCreationPolicy {
    kIgnoreIfAbsent = 0,
    kCreateIfAbsent = 1,
  };

  // Called at the start of each public operation, and initializes the database
  // if it isn't already initialized (unless there is no pre-existing on-disk
  // database to initialize and `policy` is
  // `DBCreationPolicy::kIgnoreIfAbsent`).
  [[nodiscard]] InitStatus LazyInit(DBCreationPolicy policy)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Calls `db_.Open(db_path_)` and records a histogram measuring the load
  // timing.
  [[nodiscard]] bool OpenImpl() VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Determines whether or not an uninitialized DB already exists on disk.
  [[nodiscard]] bool DBExists() VALID_CONTEXT_REQUIRED(sequence_checker_);

  // If `db_path_` is empty, opens a temporary database in memory; otherwise
  // opens a persistent database with the absolute path `db_path`, creating the
  // file if it does not yet exist. Returns whether opening was successful.
  [[nodiscard]] bool OpenDatabase() VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Callback for database errors. Schedules a call to Destroy() if the
  // error is catastrophic.
  void DatabaseErrorCallback(int extended_error, sql::Statement* stmt)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Helper function to implement internals of `Init()`.  This allows
  // Init() to retry in case of failure, since some failures run
  // recovery code.
  [[nodiscard]] InitStatus InitImpl() VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Vacuums the database. This will cause sqlite to defragment and collect
  // unused space in the file. It can be VERY SLOW. Returns whether the
  // operation was successful.
  [[nodiscard]] bool Vacuum() VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Clears all entries for `context_origin`. Returns whether deletion is
  // successful. Not named `Clear()` to distinguish it from the public method
  // called via `SequenceBound::AsyncCall()`. We remove `context_origin` from
  // `per_origin_mapping` if the origin becomes empty.
  [[nodiscard]] bool Purge(std::string_view context_origin,
                           DataClearSource source)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Performs the common last steps for calls to `Set()` or `Append()`.
  [[nodiscard]] OperationResult InternalSetOrAppend(
      std::string_view context_origin,
      std::u16string_view key,
      std::u16string_view value,
      OperationResult result_for_get,
      base::optional_ref<const std::u16string> previous_value)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Returns the number of entries for `context_origin`, not including any
  // expired entries, as determined by a manual "COUNT(*)" query. Returns -1 if
  // there is a database error.
  [[nodiscard]] int64_t NumEntriesManualCountExcludeExpired(
      std::string_view context_origin)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Returns the total number of bytes used by `context_origin`, including for
  // any expired entries that have not yet been purged. Returns -1 if there is a
  // database error.
  [[nodiscard]] int64_t NumBytesUsedIncludeExpired(
      std::string_view context_origin)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Returns the number of bytes used by `context_origin`, not including for any
  // expired entries, as determined by a manual "SUM(LENGTH(key) +
  // LENGTH(value))" query, rather than by relying on the `num_bytes` recorded
  // in `per_origin_mapping`. Returns -1 if there is a database error.
  [[nodiscard]] int64_t NumBytesUsedManualCountExcludeExpired(
      std::string_view context_origin)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Returns the corresponding `value` if an entry exists for `context_origin`
  // and `key`, otherwise `std::nullopt`. This method does not check whether an
  // existing entry is expired.
  [[nodiscard]] std::optional<std::u16string> MaybeGetValueFor(
      std::string_view context_origin,
      std::u16string_view key) VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Retrieves the `num_bytes` in `out_num_bytes` and `creation_time` in
  // `out_creation_time`, of `context_origin`. Leaves the `out_*` parameters
  // unchanged if `context_origin` is not found in the database. Returns an
  // `OperationResult` indicating success, error, or that the origin was not
  // found.
  [[nodiscard]] OperationResult GetOriginInfo(std::string_view context_origin,
                                              int64_t* out_num_bytes,
                                              base::Time* out_creation_time)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Updates `num_bytes` by `delta_bytes` for `context_origin`.
  [[nodiscard]] bool UpdateBytes(std::string_view context_origin,
                                 int64_t delta_bytes)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // If `previous_value` is non-null, this means the key already exists; this
  // method then updates the row for `context_origin` in `values_mapping` to
  // `(context_origin,key,value,last_used_time)`. Otherwise, inserts a tuple for
  // `(context_origin,key,value,last_used_time)` into `values_mapping` and calls
  // `UpdateBytes()` with a positive `delta_bytes`.
  //
  // Precondition: Must have called `Get()` synchronously beforehand to check
  // whether row already exists and populated the `previous_value` if it does.
  [[nodiscard]] bool UpdateValuesMappingWithTime(
      std::string_view context_origin,
      std::u16string_view key,
      std::u16string_view value,
      base::Time last_used_time,
      base::optional_ref<const std::u16string> previous_value)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // If `previous_value` is non-null, this means the key already exists; this
  // method then updates the row for `context_origin` in `values_mapping` to
  // `(context_origin,key,value,clock_->Now())`  (i.e. uses the current time as
  // `last_used_time`). Otherwise, inserts a tuple for
  // `(context_origin,key,value,clock_->Now())` into `values_mapping` and calls
  // `UpdateBytes()` with a positive `delta_bytes`.
  //
  // Precondition: Must have called `Get()` synchronously beforehand to check
  // whether row already exists.
  [[nodiscard]] bool UpdateValuesMapping(
      std::string_view context_origin,
      std::u16string_view key,
      std::u16string_view value,
      base::optional_ref<const std::u16string> previous_value)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Deletes the row for `context_origin` from `per_origin_mapping`.
  [[nodiscard]] bool DeleteFromPerOriginMapping(std::string_view context_origin,
                                                DataClearSource source)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Inserts the tuple for `(context_origin, creation_time, num_bytes)`
  // into `per_origin_mapping`.
  [[nodiscard]] bool InsertIntoPerOriginMapping(std::string_view context_origin,
                                                base::Time creation_time,
                                                uint64_t num_bytes)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Updates the row for `context_origin` from `per_origin_mapping` with the
  // tuple `(context_origin, creation_time, num_bytes)`, unless `num_bytes` is 0
  // and/or `context_origin` does not yet exist. In the case where `num_bytes`
  // is 0 and `context_origin` exists, we simply delete the existing row. If
  // `context_origin` does not yet exist, and `num_bytes` is positive, we simply
  // insert the row instead of updating. `origin_exists` specifies whether or
  // not `context_origin` already exists in `per_origin_mapping`.
  //
  // Precondition: Must have called `GetOriginInfo()` synchronously beforehand
  // to determine whether origin already exists.
  [[nodiscard]] bool UpdatePerOriginMapping(std::string_view context_origin,
                                            base::Time creation_time,
                                            uint64_t num_bytes,
                                            bool origin_exists)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Returns whether the `num_bytes` for `context_origin` in
  // `per_origin_mapping` is less than or equal to `max_bytes_per_origin_ -
  // delta_bytes`. This byte count includes the bytes for any expired but
  // unpurged entries for `context_origin`.
  [[nodiscard]] bool HasCapacityIncludingExpired(
      std::string_view context_origin,
      int64_t delta_bytes) VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Purges expired rows from `values_mapping` for `context_origin`, then
  // updates `context_origin`'s row in `per_origin_mapping`. Returns true on
  // success, false on database error.
  [[nodiscard]] bool ManualPurgeExpiredValues(std::string_view context_origin)
      VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Logs following initialization various histograms, including e.g. the number
  // of origins currently in `per_origin_mapping`, as well as 5-number summaries
  // of the bytes used and the lengths of the origins.
  void LogInitHistograms() VALID_CONTEXT_REQUIRED(sequence_checker_);

  // Database containing the actual data.
  sql::Database db_ GUARDED_BY_CONTEXT(sequence_checker_);

  // Contains the version information.
  sql::MetaTable meta_table_ GUARDED_BY_CONTEXT(sequence_checker_);

  // Initialization status of `db_`.
  GUARDED_BY_CONTEXT(sequence_checker_)
  InitStatus db_status_ = InitStatus::kUnattempted;

  // Only set to true if `DBExists()
  DBFileStatus db_file_status_ GUARDED_BY_CONTEXT(sequence_checker_);

  // Path to the database, if file-backed.
  base::FilePath db_path_ GUARDED_BY_CONTEXT(sequence_checker_);

  // Owning partition's storage policy.
  scoped_refptr<storage::SpecialStoragePolicy> special_storage_policy_
      GUARDED_BY_CONTEXT(sequence_checker_);

  // Maximum allowed number of total bytes in database entries per origin.
  const int64_t max_bytes_per_origin_ GUARDED_BY_CONTEXT(sequence_checker_);

  // Maximum size of a string input from any origin's script. Applies
  // separately to both script keys and script values.
  size_t max_string_length_ GUARDED_BY_CONTEXT(sequence_checker_);

  // Maxmium number of times that SQL database attempts to initialize.
  size_t max_init_tries_ GUARDED_BY_CONTEXT(sequence_checker_);

  // Maximum number of keys or key-value pairs returned per batch by the
  // async `Keys()` and `Entries()` iterators, respectively.
  size_t max_iterator_batch_size_ GUARDED_BY_CONTEXT(sequence_checker_);

  // Maximum number of bits of entropy allowed per origin to output via the
  // Shared Storage API.
  const double bit_budget_ GUARDED_BY_CONTEXT(sequence_checker_);

  // Interval over which `bit_budget_` is defined.
  const base::TimeDelta budget_interval_ GUARDED_BY_CONTEXT(sequence_checker_);

  // Length of time between last key write access and key expiration. When an
  // entry's data is older than this threshold, it will be auto-purged.
  const base::TimeDelta staleness_threshold_
      GUARDED_BY_CONTEXT(sequence_checker_);

  // Clock used to determine current time. Can be overridden in tests.
  raw_ptr<base::Clock> clock_ GUARDED_BY_CONTEXT(sequence_checker_);

  SEQUENCE_CHECKER(sequence_checker_);
};

}  // namespace storage

#endif  // COMPONENTS_SERVICES_STORAGE_SHARED_STORAGE_SHARED_STORAGE_DATABASE_H_