Add a Notification Settings Button to all web notifications behind the web platform...
[chromium-blink-merge.git] / base / prefs / json_pref_store.h
blobd9dcdbdc6cdbd64b5acf395fb8b34425edad1ad4
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_PREFS_JSON_PREF_STORE_H_
6 #define BASE_PREFS_JSON_PREF_STORE_H_
8 #include <set>
9 #include <string>
11 #include "base/basictypes.h"
12 #include "base/callback_forward.h"
13 #include "base/compiler_specific.h"
14 #include "base/files/file_path.h"
15 #include "base/files/important_file_writer.h"
16 #include "base/gtest_prod_util.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/observer_list.h"
20 #include "base/prefs/base_prefs_export.h"
21 #include "base/prefs/persistent_pref_store.h"
22 #include "base/threading/non_thread_safe.h"
24 class PrefFilter;
26 namespace base {
27 class Clock;
28 class DictionaryValue;
29 class FilePath;
30 class HistogramBase;
31 class JsonPrefStoreLossyWriteTest;
32 class SequencedTaskRunner;
33 class SequencedWorkerPool;
34 class Value;
35 FORWARD_DECLARE_TEST(JsonPrefStoreTest, WriteCountHistogramTestBasic);
36 FORWARD_DECLARE_TEST(JsonPrefStoreTest, WriteCountHistogramTestSinglePeriod);
37 FORWARD_DECLARE_TEST(JsonPrefStoreTest, WriteCountHistogramTestMultiplePeriods);
38 FORWARD_DECLARE_TEST(JsonPrefStoreTest, WriteCountHistogramTestPeriodWithGaps);
41 // A writable PrefStore implementation that is used for user preferences.
42 class BASE_PREFS_EXPORT JsonPrefStore
43 : public PersistentPrefStore,
44 public base::ImportantFileWriter::DataSerializer,
45 public base::SupportsWeakPtr<JsonPrefStore>,
46 public base::NonThreadSafe {
47 public:
48 struct ReadResult;
50 // Returns instance of SequencedTaskRunner which guarantees that file
51 // operations on the same file will be executed in sequenced order.
52 static scoped_refptr<base::SequencedTaskRunner> GetTaskRunnerForFile(
53 const base::FilePath& pref_filename,
54 base::SequencedWorkerPool* worker_pool);
56 // Same as the constructor below with no alternate filename.
57 JsonPrefStore(
58 const base::FilePath& pref_filename,
59 const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner,
60 scoped_ptr<PrefFilter> pref_filter);
62 // |sequenced_task_runner| must be a shutdown-blocking task runner, ideally
63 // created by the GetTaskRunnerForFile() method above.
64 // |pref_filename| is the path to the file to read prefs from.
65 // |pref_alternate_filename| is the path to an alternate file which the
66 // desired prefs may have previously been written to. If |pref_filename|
67 // doesn't exist and |pref_alternate_filename| does, |pref_alternate_filename|
68 // will be moved to |pref_filename| before the read occurs.
69 JsonPrefStore(
70 const base::FilePath& pref_filename,
71 const base::FilePath& pref_alternate_filename,
72 const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner,
73 scoped_ptr<PrefFilter> pref_filter);
75 // PrefStore overrides:
76 bool GetValue(const std::string& key,
77 const base::Value** result) const override;
78 void AddObserver(PrefStore::Observer* observer) override;
79 void RemoveObserver(PrefStore::Observer* observer) override;
80 bool HasObservers() const override;
81 bool IsInitializationComplete() const override;
83 // PersistentPrefStore overrides:
84 bool GetMutableValue(const std::string& key, base::Value** result) override;
85 void SetValue(const std::string& key,
86 scoped_ptr<base::Value> value,
87 uint32 flags) override;
88 void SetValueSilently(const std::string& key,
89 scoped_ptr<base::Value> value,
90 uint32 flags) override;
91 void RemoveValue(const std::string& key, uint32 flags) override;
92 bool ReadOnly() const override;
93 PrefReadError GetReadError() const override;
94 // Note this method may be asynchronous if this instance has a |pref_filter_|
95 // in which case it will return PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE.
96 // See details in pref_filter.h.
97 PrefReadError ReadPrefs() override;
98 void ReadPrefsAsync(ReadErrorDelegate* error_delegate) override;
99 void CommitPendingWrite() override;
100 void SchedulePendingLossyWrites() override;
101 void ReportValueChanged(const std::string& key, uint32 flags) override;
103 // Just like RemoveValue(), but doesn't notify observers. Used when doing some
104 // cleanup that shouldn't otherwise alert observers.
105 void RemoveValueSilently(const std::string& key, uint32 flags);
107 // Registers |on_next_successful_write| to be called once, on the next
108 // successful write event of |writer_|.
109 void RegisterOnNextSuccessfulWriteCallback(
110 const base::Closure& on_next_successful_write);
112 private:
113 // Represents a histogram for recording the number of writes to the pref file
114 // that occur every kHistogramWriteReportIntervalInMins minutes.
115 class BASE_PREFS_EXPORT WriteCountHistogram {
116 public:
117 static const int32_t kHistogramWriteReportIntervalMins;
119 WriteCountHistogram(const base::TimeDelta& commit_interval,
120 const base::FilePath& path);
121 // Constructor for testing. |clock| is a test Clock that is used to retrieve
122 // the time.
123 WriteCountHistogram(const base::TimeDelta& commit_interval,
124 const base::FilePath& path,
125 scoped_ptr<base::Clock> clock);
126 ~WriteCountHistogram();
128 // Record that a write has occured.
129 void RecordWriteOccured();
131 // Reports writes (that have not yet been reported) in all of the recorded
132 // intervals that have elapsed up until current time.
133 void ReportOutstandingWrites();
135 base::HistogramBase* GetHistogram();
137 private:
138 // The minimum interval at which writes can occur.
139 const base::TimeDelta commit_interval_;
141 // The path to the file.
142 const base::FilePath path_;
144 // Clock which is used to retrieve the current time.
145 scoped_ptr<base::Clock> clock_;
147 // The interval at which to report write counts.
148 const base::TimeDelta report_interval_;
150 // The time at which the last histogram value was reported for the number
151 // of write counts.
152 base::Time last_report_time_;
154 // The number of writes that have occured since the last write count was
155 // reported.
156 uint32_t writes_since_last_report_;
158 DISALLOW_COPY_AND_ASSIGN(WriteCountHistogram);
161 FRIEND_TEST_ALL_PREFIXES(base::JsonPrefStoreTest,
162 WriteCountHistogramTestBasic);
163 FRIEND_TEST_ALL_PREFIXES(base::JsonPrefStoreTest,
164 WriteCountHistogramTestSinglePeriod);
165 FRIEND_TEST_ALL_PREFIXES(base::JsonPrefStoreTest,
166 WriteCountHistogramTestMultiplePeriods);
167 FRIEND_TEST_ALL_PREFIXES(base::JsonPrefStoreTest,
168 WriteCountHistogramTestPeriodWithGaps);
169 friend class base::JsonPrefStoreLossyWriteTest;
171 ~JsonPrefStore() override;
173 // This method is called after the JSON file has been read. It then hands
174 // |value| (or an empty dictionary in some read error cases) to the
175 // |pref_filter| if one is set. It also gives a callback pointing at
176 // FinalizeFileRead() to that |pref_filter_| which is then responsible for
177 // invoking it when done. If there is no |pref_filter_|, FinalizeFileRead()
178 // is invoked directly.
179 void OnFileRead(scoped_ptr<ReadResult> read_result);
181 // ImportantFileWriter::DataSerializer overrides:
182 bool SerializeData(std::string* output) override;
184 // This method is called after the JSON file has been read and the result has
185 // potentially been intercepted and modified by |pref_filter_|.
186 // |initialization_successful| is pre-determined by OnFileRead() and should
187 // be used when reporting OnInitializationCompleted().
188 // |schedule_write| indicates whether a write should be immediately scheduled
189 // (typically because the |pref_filter_| has already altered the |prefs|) --
190 // this will be ignored if this store is read-only.
191 void FinalizeFileRead(bool initialization_successful,
192 scoped_ptr<base::DictionaryValue> prefs,
193 bool schedule_write);
195 // Schedule a write with the file writer as long as |flags| doesn't contain
196 // WriteablePrefStore::LOSSY_PREF_WRITE_FLAG.
197 void ScheduleWrite(uint32 flags);
199 const base::FilePath path_;
200 const base::FilePath alternate_path_;
201 const scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_;
203 scoped_ptr<base::DictionaryValue> prefs_;
205 bool read_only_;
207 // Helper for safely writing pref data.
208 base::ImportantFileWriter writer_;
210 scoped_ptr<PrefFilter> pref_filter_;
211 base::ObserverList<PrefStore::Observer, true> observers_;
213 scoped_ptr<ReadErrorDelegate> error_delegate_;
215 bool initialized_;
216 bool filtering_in_progress_;
217 bool pending_lossy_write_;
218 PrefReadError read_error_;
220 std::set<std::string> keys_need_empty_value_;
222 WriteCountHistogram write_count_histogram_;
224 DISALLOW_COPY_AND_ASSIGN(JsonPrefStore);
227 #endif // BASE_PREFS_JSON_PREF_STORE_H_