blob: e91a4063f7bf4307486017741afe8b666a27c25d [file] [log] [blame]
[email protected]d3b05ea2012-01-24 22:57:051// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]277404c22010-04-22 13:09:452// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
brettwf00b9b42016-02-01 22:11:385#include "components/prefs/json_pref_store.h"
[email protected]277404c22010-04-22 13:09:456
avi9ef8bb02015-12-24 05:29:367#include <stddef.h>
8
[email protected]277404c22010-04-22 13:09:459#include <algorithm>
danakj0c8d4aa2015-11-25 05:29:5810#include <utility>
[email protected]277404c22010-04-22 13:09:4511
[email protected]844a1002011-04-19 11:37:2112#include "base/bind.h"
13#include "base/callback.h"
[email protected]ac771fb362014-07-16 06:04:4414#include "base/files/file_path.h"
[email protected]e3177dd52014-08-13 20:22:1415#include "base/files/file_util.h"
[email protected]ffbec692012-02-26 20:26:4216#include "base/json/json_file_value_serializer.h"
17#include "base/json/json_string_value_serializer.h"
avi9ef8bb02015-12-24 05:29:3618#include "base/macros.h"
[email protected]844a1002011-04-19 11:37:2119#include "base/memory/ref_counted.h"
[email protected]ac771fb362014-07-16 06:04:4420#include "base/metrics/histogram.h"
[email protected]fb441962013-05-08 05:35:2421#include "base/sequenced_task_runner.h"
raymesbfb910a2015-04-29 07:43:0922#include "base/strings/string_number_conversions.h"
[email protected]ac771fb362014-07-16 06:04:4423#include "base/strings/string_util.h"
[email protected]f2456592014-07-22 19:30:1724#include "base/task_runner_util.h"
probergefc46ac12016-09-21 18:03:0025#include "base/threading/sequenced_task_runner_handle.h"
[email protected]0de615a2012-11-08 04:40:5926#include "base/threading/sequenced_worker_pool.h"
raymesbfb910a2015-04-29 07:43:0927#include "base/time/default_clock.h"
[email protected]277404c22010-04-22 13:09:4528#include "base/values.h"
brettwf00b9b42016-02-01 22:11:3829#include "components/prefs/pref_filter.h"
[email protected]277404c22010-04-22 13:09:4530
[email protected]f2456592014-07-22 19:30:1731// Result returned from internal read tasks.
32struct JsonPrefStore::ReadResult {
33 public:
34 ReadResult();
35 ~ReadResult();
36
dcheng5f043bc2016-04-22 19:09:0637 std::unique_ptr<base::Value> value;
[email protected]f2456592014-07-22 19:30:1738 PrefReadError error;
39 bool no_dir;
40
41 private:
42 DISALLOW_COPY_AND_ASSIGN(ReadResult);
43};
44
45JsonPrefStore::ReadResult::ReadResult()
46 : error(PersistentPrefStore::PREF_READ_ERROR_NONE), no_dir(false) {
47}
48
49JsonPrefStore::ReadResult::~ReadResult() {
50}
51
[email protected]277404c22010-04-22 13:09:4552namespace {
53
54// Some extensions we'll tack on to copies of the Preferences files.
[email protected]f2456592014-07-22 19:30:1755const base::FilePath::CharType kBadExtension[] = FILE_PATH_LITERAL("bad");
[email protected]277404c22010-04-22 13:09:4556
[email protected]f2456592014-07-22 19:30:1757PersistentPrefStore::PrefReadError HandleReadErrors(
[email protected]a43a667b2013-06-14 17:56:0858 const base::Value* value,
[email protected]023ad6ab2013-02-17 05:07:2359 const base::FilePath& path,
[email protected]844a1002011-04-19 11:37:2160 int error_code,
[email protected]f2456592014-07-22 19:30:1761 const std::string& error_msg) {
[email protected]844a1002011-04-19 11:37:2162 if (!value) {
[email protected]0de615a2012-11-08 04:40:5963 DVLOG(1) << "Error while loading JSON file: " << error_msg
64 << ", file: " << path.value();
[email protected]844a1002011-04-19 11:37:2165 switch (error_code) {
prashhir54a994502015-03-05 09:30:5766 case JSONFileValueDeserializer::JSON_ACCESS_DENIED:
[email protected]f2456592014-07-22 19:30:1767 return PersistentPrefStore::PREF_READ_ERROR_ACCESS_DENIED;
prashhir54a994502015-03-05 09:30:5768 case JSONFileValueDeserializer::JSON_CANNOT_READ_FILE:
[email protected]f2456592014-07-22 19:30:1769 return PersistentPrefStore::PREF_READ_ERROR_FILE_OTHER;
prashhir54a994502015-03-05 09:30:5770 case JSONFileValueDeserializer::JSON_FILE_LOCKED:
[email protected]f2456592014-07-22 19:30:1771 return PersistentPrefStore::PREF_READ_ERROR_FILE_LOCKED;
prashhir54a994502015-03-05 09:30:5772 case JSONFileValueDeserializer::JSON_NO_SUCH_FILE:
[email protected]f2456592014-07-22 19:30:1773 return PersistentPrefStore::PREF_READ_ERROR_NO_FILE;
[email protected]844a1002011-04-19 11:37:2174 default:
[email protected]844a1002011-04-19 11:37:2175 // JSON errors indicate file corruption of some sort.
76 // Since the file is corrupt, move it to the side and continue with
77 // empty preferences. This will result in them losing their settings.
78 // We keep the old file for possible support and debugging assistance
79 // as well as to detect if they're seeing these errors repeatedly.
80 // TODO(erikkay) Instead, use the last known good file.
[email protected]023ad6ab2013-02-17 05:07:2381 base::FilePath bad = path.ReplaceExtension(kBadExtension);
[email protected]844a1002011-04-19 11:37:2182
83 // If they've ever had a parse error before, put them in another bucket.
84 // TODO(erikkay) if we keep this error checking for very long, we may
85 // want to differentiate between recent and long ago errors.
[email protected]f2456592014-07-22 19:30:1786 bool bad_existed = base::PathExists(bad);
[email protected]5553d5b2013-07-01 23:07:3687 base::Move(path, bad);
[email protected]f2456592014-07-22 19:30:1788 return bad_existed ? PersistentPrefStore::PREF_READ_ERROR_JSON_REPEAT
89 : PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE;
[email protected]844a1002011-04-19 11:37:2190 }
[email protected]844a1002011-04-19 11:37:2191 }
thestig1433edb2015-08-06 21:45:2792 if (!value->IsType(base::Value::TYPE_DICTIONARY))
93 return PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE;
[email protected]f2456592014-07-22 19:30:1794 return PersistentPrefStore::PREF_READ_ERROR_NONE;
95}
96
gabf16b59a2015-01-31 19:09:0297// Records a sample for |size| in the Settings.JsonDataReadSizeKilobytes
98// histogram suffixed with the base name of the JSON file under |path|.
99void RecordJsonDataSizeHistogram(const base::FilePath& path, size_t size) {
100 std::string spaceless_basename;
101 base::ReplaceChars(path.BaseName().MaybeAsASCII(), " ", "_",
102 &spaceless_basename);
103
104 // The histogram below is an expansion of the UMA_HISTOGRAM_CUSTOM_COUNTS
105 // macro adapted to allow for a dynamically suffixed histogram name.
106 // Note: The factory creates and owns the histogram.
107 base::HistogramBase* histogram = base::Histogram::FactoryGet(
108 "Settings.JsonDataReadSizeKilobytes." + spaceless_basename, 1, 10000, 50,
109 base::HistogramBase::kUmaTargetedHistogramFlag);
110 histogram->Add(static_cast<int>(size) / 1024);
111}
112
dcheng5f043bc2016-04-22 19:09:06113std::unique_ptr<JsonPrefStore::ReadResult> ReadPrefsFromDisk(
[email protected]f2456592014-07-22 19:30:17114 const base::FilePath& path,
115 const base::FilePath& alternate_path) {
116 if (!base::PathExists(path) && !alternate_path.empty() &&
117 base::PathExists(alternate_path)) {
118 base::Move(alternate_path, path);
119 }
120
121 int error_code;
122 std::string error_msg;
dcheng5f043bc2016-04-22 19:09:06123 std::unique_ptr<JsonPrefStore::ReadResult> read_result(
[email protected]f2456592014-07-22 19:30:17124 new JsonPrefStore::ReadResult);
prashhir54a994502015-03-05 09:30:57125 JSONFileValueDeserializer deserializer(path);
olli.raulaba045252015-10-16 06:16:40126 read_result->value = deserializer.Deserialize(&error_code, &error_msg);
[email protected]f2456592014-07-22 19:30:17127 read_result->error =
128 HandleReadErrors(read_result->value.get(), path, error_code, error_msg);
129 read_result->no_dir = !base::PathExists(path.DirName());
gabf16b59a2015-01-31 19:09:02130
131 if (read_result->error == PersistentPrefStore::PREF_READ_ERROR_NONE)
prashhir54a994502015-03-05 09:30:57132 RecordJsonDataSizeHistogram(path, deserializer.get_last_read_size());
gabf16b59a2015-01-31 19:09:02133
danakj0c8d4aa2015-11-25 05:29:58134 return read_result;
[email protected]844a1002011-04-19 11:37:21135}
136
[email protected]277404c22010-04-22 13:09:45137} // namespace
138
[email protected]f2456592014-07-22 19:30:17139// static
[email protected]0de615a2012-11-08 04:40:59140scoped_refptr<base::SequencedTaskRunner> JsonPrefStore::GetTaskRunnerForFile(
[email protected]023ad6ab2013-02-17 05:07:23141 const base::FilePath& filename,
[email protected]0de615a2012-11-08 04:40:59142 base::SequencedWorkerPool* worker_pool) {
143 std::string token("json_pref_store-");
144 token.append(filename.AsUTF8Unsafe());
145 return worker_pool->GetSequencedTaskRunnerWithShutdownBehavior(
146 worker_pool->GetNamedSequenceToken(token),
147 base::SequencedWorkerPool::BLOCK_SHUTDOWN);
148}
149
dcheng077d1b22014-08-28 18:47:38150JsonPrefStore::JsonPrefStore(
thestig1433edb2015-08-06 21:45:27151 const base::FilePath& pref_filename,
dcheng077d1b22014-08-28 18:47:38152 const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner,
dcheng5f043bc2016-04-22 19:09:06153 std::unique_ptr<PrefFilter> pref_filter)
thestig1433edb2015-08-06 21:45:27154 : JsonPrefStore(pref_filename,
raymes4b6e14e2015-05-12 00:10:30155 base::FilePath(),
156 sequenced_task_runner,
danakj0c8d4aa2015-11-25 05:29:58157 std::move(pref_filter)) {}
[email protected]277404c22010-04-22 13:09:45158
dcheng077d1b22014-08-28 18:47:38159JsonPrefStore::JsonPrefStore(
thestig1433edb2015-08-06 21:45:27160 const base::FilePath& pref_filename,
161 const base::FilePath& pref_alternate_filename,
dcheng077d1b22014-08-28 18:47:38162 const scoped_refptr<base::SequencedTaskRunner>& sequenced_task_runner,
dcheng5f043bc2016-04-22 19:09:06163 std::unique_ptr<PrefFilter> pref_filter)
thestig1433edb2015-08-06 21:45:27164 : path_(pref_filename),
165 alternate_path_(pref_alternate_filename),
[email protected]cfcf0e52014-06-20 18:29:47166 sequenced_task_runner_(sequenced_task_runner),
167 prefs_(new base::DictionaryValue()),
168 read_only_(false),
thestig1433edb2015-08-06 21:45:27169 writer_(pref_filename, sequenced_task_runner),
danakj0c8d4aa2015-11-25 05:29:58170 pref_filter_(std::move(pref_filter)),
[email protected]cfcf0e52014-06-20 18:29:47171 initialized_(false),
172 filtering_in_progress_(false),
raymes4b6e14e2015-05-12 00:10:30173 pending_lossy_write_(false),
raymesbfb910a2015-04-29 07:43:09174 read_error_(PREF_READ_ERROR_NONE),
probergefc46ac12016-09-21 18:03:00175 has_pending_successful_write_reply_(false),
probergec503d692016-09-28 19:51:05176 has_pending_write_callbacks_(false),
raymesbfb910a2015-04-29 07:43:09177 write_count_histogram_(writer_.commit_interval(), path_) {
bratell970f39d2015-01-07 16:40:58178 DCHECK(!path_.empty());
[email protected]cfcf0e52014-06-20 18:29:47179}
180
[email protected]892f1d62012-11-08 18:24:34181bool JsonPrefStore::GetValue(const std::string& key,
[email protected]a43a667b2013-06-14 17:56:08182 const base::Value** result) const {
[email protected]f2456592014-07-22 19:30:17183 DCHECK(CalledOnValidThread());
184
thestig1433edb2015-08-06 21:45:27185 base::Value* tmp = nullptr;
[email protected]892f1d62012-11-08 18:24:34186 if (!prefs_->Get(key, &tmp))
187 return false;
188
189 if (result)
190 *result = tmp;
191 return true;
[email protected]f2d1f612010-12-09 15:10:17192}
193
194void JsonPrefStore::AddObserver(PrefStore::Observer* observer) {
[email protected]f2456592014-07-22 19:30:17195 DCHECK(CalledOnValidThread());
196
[email protected]f2d1f612010-12-09 15:10:17197 observers_.AddObserver(observer);
198}
199
200void JsonPrefStore::RemoveObserver(PrefStore::Observer* observer) {
[email protected]f2456592014-07-22 19:30:17201 DCHECK(CalledOnValidThread());
202
[email protected]f2d1f612010-12-09 15:10:17203 observers_.RemoveObserver(observer);
204}
205
[email protected]14e0ec62013-08-26 22:01:39206bool JsonPrefStore::HasObservers() const {
[email protected]f2456592014-07-22 19:30:17207 DCHECK(CalledOnValidThread());
208
[email protected]14e0ec62013-08-26 22:01:39209 return observers_.might_have_observers();
[email protected]d3b05ea2012-01-24 22:57:05210}
211
[email protected]845b43a82011-05-11 10:14:43212bool JsonPrefStore::IsInitializationComplete() const {
[email protected]f2456592014-07-22 19:30:17213 DCHECK(CalledOnValidThread());
214
[email protected]845b43a82011-05-11 10:14:43215 return initialized_;
216}
217
[email protected]892f1d62012-11-08 18:24:34218bool JsonPrefStore::GetMutableValue(const std::string& key,
[email protected]a43a667b2013-06-14 17:56:08219 base::Value** result) {
[email protected]f2456592014-07-22 19:30:17220 DCHECK(CalledOnValidThread());
221
[email protected]892f1d62012-11-08 18:24:34222 return prefs_->Get(key, result);
[email protected]68bf41a2011-03-25 16:38:31223}
224
raymes76de1af2015-05-06 03:22:21225void JsonPrefStore::SetValue(const std::string& key,
dcheng5f043bc2016-04-22 19:09:06226 std::unique_ptr<base::Value> value,
avi9ef8bb02015-12-24 05:29:36227 uint32_t flags) {
[email protected]f2456592014-07-22 19:30:17228 DCHECK(CalledOnValidThread());
229
[email protected]9b5f56b42011-08-24 21:17:59230 DCHECK(value);
thestig1433edb2015-08-06 21:45:27231 base::Value* old_value = nullptr;
[email protected]9b5f56b42011-08-24 21:17:59232 prefs_->Get(key, &old_value);
233 if (!old_value || !value->Equals(old_value)) {
danakj0c8d4aa2015-11-25 05:29:58234 prefs_->Set(key, std::move(value));
raymes76de1af2015-05-06 03:22:21235 ReportValueChanged(key, flags);
[email protected]9b5f56b42011-08-24 21:17:59236 }
[email protected]f2d1f612010-12-09 15:10:17237}
238
[email protected]a43a667b2013-06-14 17:56:08239void JsonPrefStore::SetValueSilently(const std::string& key,
dcheng5f043bc2016-04-22 19:09:06240 std::unique_ptr<base::Value> value,
avi9ef8bb02015-12-24 05:29:36241 uint32_t flags) {
[email protected]f2456592014-07-22 19:30:17242 DCHECK(CalledOnValidThread());
243
[email protected]9b5f56b42011-08-24 21:17:59244 DCHECK(value);
thestig1433edb2015-08-06 21:45:27245 base::Value* old_value = nullptr;
[email protected]9b5f56b42011-08-24 21:17:59246 prefs_->Get(key, &old_value);
[email protected]25308672011-10-10 17:22:50247 if (!old_value || !value->Equals(old_value)) {
danakj0c8d4aa2015-11-25 05:29:58248 prefs_->Set(key, std::move(value));
raymes4b6e14e2015-05-12 00:10:30249 ScheduleWrite(flags);
[email protected]25308672011-10-10 17:22:50250 }
[email protected]f2d1f612010-12-09 15:10:17251}
252
avi9ef8bb02015-12-24 05:29:36253void JsonPrefStore::RemoveValue(const std::string& key, uint32_t flags) {
[email protected]f2456592014-07-22 19:30:17254 DCHECK(CalledOnValidThread());
255
thestig1433edb2015-08-06 21:45:27256 if (prefs_->RemovePath(key, nullptr))
raymes76de1af2015-05-06 03:22:21257 ReportValueChanged(key, flags);
[email protected]f2d1f612010-12-09 15:10:17258}
259
avi9ef8bb02015-12-24 05:29:36260void JsonPrefStore::RemoveValueSilently(const std::string& key,
261 uint32_t flags) {
[email protected]f2456592014-07-22 19:30:17262 DCHECK(CalledOnValidThread());
263
thestig1433edb2015-08-06 21:45:27264 prefs_->RemovePath(key, nullptr);
raymes4b6e14e2015-05-12 00:10:30265 ScheduleWrite(flags);
[email protected]e33c9512014-05-12 02:24:13266}
267
[email protected]ddb1e5a2010-12-13 20:10:45268bool JsonPrefStore::ReadOnly() const {
[email protected]f2456592014-07-22 19:30:17269 DCHECK(CalledOnValidThread());
270
[email protected]ddb1e5a2010-12-13 20:10:45271 return read_only_;
272}
273
[email protected]59c10712012-03-13 02:10:34274PersistentPrefStore::PrefReadError JsonPrefStore::GetReadError() const {
[email protected]f2456592014-07-22 19:30:17275 DCHECK(CalledOnValidThread());
276
[email protected]59c10712012-03-13 02:10:34277 return read_error_;
278}
279
[email protected]7b2720b2012-04-25 16:59:11280PersistentPrefStore::PrefReadError JsonPrefStore::ReadPrefs() {
[email protected]f2456592014-07-22 19:30:17281 DCHECK(CalledOnValidThread());
282
[email protected]f2456592014-07-22 19:30:17283 OnFileRead(ReadPrefsFromDisk(path_, alternate_path_));
284 return filtering_in_progress_ ? PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE
285 : read_error_;
[email protected]7b2720b2012-04-25 16:59:11286}
287
[email protected]e33c9512014-05-12 02:24:13288void JsonPrefStore::ReadPrefsAsync(ReadErrorDelegate* error_delegate) {
[email protected]f2456592014-07-22 19:30:17289 DCHECK(CalledOnValidThread());
290
[email protected]7b2720b2012-04-25 16:59:11291 initialized_ = false;
292 error_delegate_.reset(error_delegate);
[email protected]7b2720b2012-04-25 16:59:11293
[email protected]3b268bc2014-07-28 17:43:15294 // Weakly binds the read task so that it doesn't kick in during shutdown.
[email protected]f2456592014-07-22 19:30:17295 base::PostTaskAndReplyWithResult(
dchengd81e7d72014-08-27 00:23:23296 sequenced_task_runner_.get(),
[email protected]f2456592014-07-22 19:30:17297 FROM_HERE,
298 base::Bind(&ReadPrefsFromDisk, path_, alternate_path_),
[email protected]3b268bc2014-07-28 17:43:15299 base::Bind(&JsonPrefStore::OnFileRead, AsWeakPtr()));
[email protected]7b2720b2012-04-25 16:59:11300}
301
302void JsonPrefStore::CommitPendingWrite() {
[email protected]f2456592014-07-22 19:30:17303 DCHECK(CalledOnValidThread());
304
raymes4b6e14e2015-05-12 00:10:30305 // Schedule a write for any lossy writes that are outstanding to ensure that
306 // they get flushed when this function is called.
benwells26730592015-05-28 13:08:08307 SchedulePendingLossyWrites();
raymes4b6e14e2015-05-12 00:10:30308
[email protected]7b2720b2012-04-25 16:59:11309 if (writer_.HasPendingWrite() && !read_only_)
310 writer_.DoScheduledWrite();
311}
312
benwells26730592015-05-28 13:08:08313void JsonPrefStore::SchedulePendingLossyWrites() {
314 if (pending_lossy_write_)
315 writer_.ScheduleWrite(this);
316}
317
avi9ef8bb02015-12-24 05:29:36318void JsonPrefStore::ReportValueChanged(const std::string& key, uint32_t flags) {
[email protected]f2456592014-07-22 19:30:17319 DCHECK(CalledOnValidThread());
320
[email protected]a0ce7e72014-01-21 16:50:56321 if (pref_filter_)
322 pref_filter_->FilterUpdate(key);
[email protected]56cbcb3a2013-12-23 21:24:46323
[email protected]7b2720b2012-04-25 16:59:11324 FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key));
[email protected]56cbcb3a2013-12-23 21:24:46325
raymes4b6e14e2015-05-12 00:10:30326 ScheduleWrite(flags);
[email protected]7b2720b2012-04-25 16:59:11327}
328
probergefc46ac12016-09-21 18:03:00329void JsonPrefStore::RunOrScheduleNextSuccessfulWriteCallback(
330 bool write_success) {
[email protected]f2456592014-07-22 19:30:17331 DCHECK(CalledOnValidThread());
332
probergec503d692016-09-28 19:51:05333 has_pending_write_callbacks_ = false;
probergefc46ac12016-09-21 18:03:00334 if (has_pending_successful_write_reply_) {
335 has_pending_successful_write_reply_ = false;
336 if (write_success) {
337 on_next_successful_write_reply_.Run();
338 } else {
339 RegisterOnNextSuccessfulWriteReply(on_next_successful_write_reply_);
340 }
341 }
342}
343
344// static
345void JsonPrefStore::PostWriteCallback(
346 const base::Callback<void(bool success)>& on_next_write_reply,
347 const base::Callback<void(bool success)>& on_next_write_callback,
348 scoped_refptr<base::SequencedTaskRunner> reply_task_runner,
349 bool write_success) {
350 if (!on_next_write_callback.is_null())
351 on_next_write_callback.Run(write_success);
352
353 // We can't run |on_next_write_reply| on the current thread. Bounce back to
354 // the |reply_task_runner| which is the correct sequenced thread.
355 reply_task_runner->PostTask(FROM_HERE,
356 base::Bind(on_next_write_reply, write_success));
357}
358
359void JsonPrefStore::RegisterOnNextSuccessfulWriteReply(
360 const base::Closure& on_next_successful_write_reply) {
361 DCHECK(CalledOnValidThread());
362 DCHECK(!has_pending_successful_write_reply_);
363
364 has_pending_successful_write_reply_ = true;
365 on_next_successful_write_reply_ = on_next_successful_write_reply;
366
probergec503d692016-09-28 19:51:05367 // If there are pending callbacks, avoid erasing them; the reply will be used
368 // as we set |on_next_successful_write_reply_|. Otherwise, setup a reply with
369 // an empty callback.
370 if (!has_pending_write_callbacks_) {
371 writer_.RegisterOnNextWriteCallbacks(
372 base::Closure(),
373 base::Bind(
374 &PostWriteCallback,
375 base::Bind(&JsonPrefStore::RunOrScheduleNextSuccessfulWriteCallback,
376 AsWeakPtr()),
377 base::Callback<void(bool success)>(),
378 base::SequencedTaskRunnerHandle::Get()));
probergefc46ac12016-09-21 18:03:00379 }
380}
381
probergec503d692016-09-28 19:51:05382void JsonPrefStore::RegisterOnNextWriteSynchronousCallbacks(
383 OnWriteCallbackPair callbacks) {
probergefc46ac12016-09-21 18:03:00384 DCHECK(CalledOnValidThread());
probergec503d692016-09-28 19:51:05385 DCHECK(!has_pending_write_callbacks_);
probergefc46ac12016-09-21 18:03:00386
probergec503d692016-09-28 19:51:05387 has_pending_write_callbacks_ = true;
probergefc46ac12016-09-21 18:03:00388
probergec503d692016-09-28 19:51:05389 writer_.RegisterOnNextWriteCallbacks(
390 callbacks.first,
391 base::Bind(
392 &PostWriteCallback,
393 base::Bind(&JsonPrefStore::RunOrScheduleNextSuccessfulWriteCallback,
394 AsWeakPtr()),
395 callbacks.second, base::SequencedTaskRunnerHandle::Get()));
[email protected]e33c9512014-05-12 02:24:13396}
397
dvadym53fc0d42016-02-05 13:34:57398void JsonPrefStore::ClearMutableValues() {
399 NOTIMPLEMENTED();
400}
401
dcheng5f043bc2016-04-22 19:09:06402void JsonPrefStore::OnFileRead(std::unique_ptr<ReadResult> read_result) {
[email protected]f2456592014-07-22 19:30:17403 DCHECK(CalledOnValidThread());
404
405 DCHECK(read_result);
406
dcheng5f043bc2016-04-22 19:09:06407 std::unique_ptr<base::DictionaryValue> unfiltered_prefs(
408 new base::DictionaryValue);
[email protected]e33c9512014-05-12 02:24:13409
[email protected]f2456592014-07-22 19:30:17410 read_error_ = read_result->error;
[email protected]845b43a82011-05-11 10:14:43411
[email protected]f2456592014-07-22 19:30:17412 bool initialization_successful = !read_result->no_dir;
[email protected]e33c9512014-05-12 02:24:13413
414 if (initialization_successful) {
415 switch (read_error_) {
416 case PREF_READ_ERROR_ACCESS_DENIED:
417 case PREF_READ_ERROR_FILE_OTHER:
418 case PREF_READ_ERROR_FILE_LOCKED:
419 case PREF_READ_ERROR_JSON_TYPE:
420 case PREF_READ_ERROR_FILE_NOT_SPECIFIED:
421 read_only_ = true;
422 break;
423 case PREF_READ_ERROR_NONE:
[email protected]f2456592014-07-22 19:30:17424 DCHECK(read_result->value.get());
[email protected]e33c9512014-05-12 02:24:13425 unfiltered_prefs.reset(
[email protected]f2456592014-07-22 19:30:17426 static_cast<base::DictionaryValue*>(read_result->value.release()));
[email protected]e33c9512014-05-12 02:24:13427 break;
428 case PREF_READ_ERROR_NO_FILE:
429 // If the file just doesn't exist, maybe this is first run. In any case
430 // there's no harm in writing out default prefs in this case.
[email protected]e33c9512014-05-12 02:24:13431 case PREF_READ_ERROR_JSON_PARSE:
432 case PREF_READ_ERROR_JSON_REPEAT:
433 break;
434 case PREF_READ_ERROR_ASYNCHRONOUS_TASK_INCOMPLETE:
435 // This is a special error code to be returned by ReadPrefs when it
436 // can't complete synchronously, it should never be returned by the read
437 // operation itself.
[email protected]e33c9512014-05-12 02:24:13438 case PREF_READ_ERROR_MAX_ENUM:
439 NOTREACHED();
440 break;
441 }
[email protected]845b43a82011-05-11 10:14:43442 }
443
[email protected]e33c9512014-05-12 02:24:13444 if (pref_filter_) {
445 filtering_in_progress_ = true;
446 const PrefFilter::PostFilterOnLoadCallback post_filter_on_load_callback(
447 base::Bind(
[email protected]3b268bc2014-07-28 17:43:15448 &JsonPrefStore::FinalizeFileRead, AsWeakPtr(),
449 initialization_successful));
[email protected]e33c9512014-05-12 02:24:13450 pref_filter_->FilterOnLoad(post_filter_on_load_callback,
danakj0c8d4aa2015-11-25 05:29:58451 std::move(unfiltered_prefs));
[email protected]e33c9512014-05-12 02:24:13452 } else {
danakj0c8d4aa2015-11-25 05:29:58453 FinalizeFileRead(initialization_successful, std::move(unfiltered_prefs),
454 false);
[email protected]844a1002011-04-19 11:37:21455 }
[email protected]844a1002011-04-19 11:37:21456}
457
[email protected]7b2720b2012-04-25 16:59:11458JsonPrefStore::~JsonPrefStore() {
459 CommitPendingWrite();
[email protected]f89ee342011-03-07 09:28:27460}
461
[email protected]277404c22010-04-22 13:09:45462bool JsonPrefStore::SerializeData(std::string* output) {
[email protected]f2456592014-07-22 19:30:17463 DCHECK(CalledOnValidThread());
464
raymes4b6e14e2015-05-12 00:10:30465 pending_lossy_write_ = false;
466
raymesbfb910a2015-04-29 07:43:09467 write_count_histogram_.RecordWriteOccured();
468
probergec503d692016-09-28 19:51:05469 if (pref_filter_) {
470 OnWriteCallbackPair callbacks =
471 pref_filter_->FilterSerializeData(prefs_.get());
472 if (!callbacks.first.is_null() || !callbacks.second.is_null())
473 RegisterOnNextWriteSynchronousCallbacks(callbacks);
474 }
[email protected]a0ce7e72014-01-21 16:50:56475
[email protected]277404c22010-04-22 13:09:45476 JSONStringValueSerializer serializer(output);
gab97c50ac2015-03-06 20:41:43477 // Not pretty-printing prefs shrinks pref file size by ~30%. To obtain
478 // readable prefs for debugging purposes, you can dump your prefs into any
479 // command-line or online JSON pretty printing tool.
480 serializer.set_pretty_print(false);
gabf16b59a2015-01-31 19:09:02481 return serializer.Serialize(*prefs_);
[email protected]277404c22010-04-22 13:09:45482}
[email protected]e33c9512014-05-12 02:24:13483
dcheng5f043bc2016-04-22 19:09:06484void JsonPrefStore::FinalizeFileRead(
485 bool initialization_successful,
486 std::unique_ptr<base::DictionaryValue> prefs,
487 bool schedule_write) {
[email protected]f2456592014-07-22 19:30:17488 DCHECK(CalledOnValidThread());
489
[email protected]e33c9512014-05-12 02:24:13490 filtering_in_progress_ = false;
491
492 if (!initialization_successful) {
493 FOR_EACH_OBSERVER(PrefStore::Observer,
494 observers_,
495 OnInitializationCompleted(false));
496 return;
497 }
498
danakj0c8d4aa2015-11-25 05:29:58499 prefs_ = std::move(prefs);
[email protected]e33c9512014-05-12 02:24:13500
501 initialized_ = true;
502
raymes4b6e14e2015-05-12 00:10:30503 if (schedule_write)
504 ScheduleWrite(DEFAULT_PREF_WRITE_FLAGS);
[email protected]e33c9512014-05-12 02:24:13505
506 if (error_delegate_ && read_error_ != PREF_READ_ERROR_NONE)
507 error_delegate_->OnError(read_error_);
508
509 FOR_EACH_OBSERVER(PrefStore::Observer,
510 observers_,
511 OnInitializationCompleted(true));
512
513 return;
514}
raymesbfb910a2015-04-29 07:43:09515
avi9ef8bb02015-12-24 05:29:36516void JsonPrefStore::ScheduleWrite(uint32_t flags) {
raymes4b6e14e2015-05-12 00:10:30517 if (read_only_)
518 return;
519
520 if (flags & LOSSY_PREF_WRITE_FLAG)
521 pending_lossy_write_ = true;
522 else
523 writer_.ScheduleWrite(this);
524}
525
raymesbfb910a2015-04-29 07:43:09526// NOTE: This value should NOT be changed without renaming the histogram
527// otherwise it will create incompatible buckets.
528const int32_t
529 JsonPrefStore::WriteCountHistogram::kHistogramWriteReportIntervalMins = 5;
530
531JsonPrefStore::WriteCountHistogram::WriteCountHistogram(
532 const base::TimeDelta& commit_interval,
533 const base::FilePath& path)
dcheng5f043bc2016-04-22 19:09:06534 : WriteCountHistogram(
535 commit_interval,
536 path,
537 std::unique_ptr<base::Clock>(new base::DefaultClock)) {}
raymesbfb910a2015-04-29 07:43:09538
539JsonPrefStore::WriteCountHistogram::WriteCountHistogram(
540 const base::TimeDelta& commit_interval,
541 const base::FilePath& path,
dcheng5f043bc2016-04-22 19:09:06542 std::unique_ptr<base::Clock> clock)
raymesbfb910a2015-04-29 07:43:09543 : commit_interval_(commit_interval),
544 path_(path),
545 clock_(clock.release()),
546 report_interval_(
547 base::TimeDelta::FromMinutes(kHistogramWriteReportIntervalMins)),
548 last_report_time_(clock_->Now()),
dcheng5f043bc2016-04-22 19:09:06549 writes_since_last_report_(0) {}
raymesbfb910a2015-04-29 07:43:09550
551JsonPrefStore::WriteCountHistogram::~WriteCountHistogram() {
552 ReportOutstandingWrites();
553}
554
555void JsonPrefStore::WriteCountHistogram::RecordWriteOccured() {
556 ReportOutstandingWrites();
557
558 ++writes_since_last_report_;
559}
560
561void JsonPrefStore::WriteCountHistogram::ReportOutstandingWrites() {
562 base::Time current_time = clock_->Now();
563 base::TimeDelta time_since_last_report = current_time - last_report_time_;
564
565 if (time_since_last_report <= report_interval_)
566 return;
567
568 // If the time since the last report exceeds the report interval, report all
569 // the writes since the last report. They must have all occurred in the same
570 // report interval.
571 base::HistogramBase* histogram = GetHistogram();
572 histogram->Add(writes_since_last_report_);
573
574 // There may be several report intervals that elapsed that don't have any
575 // writes in them. Report these too.
avi9ef8bb02015-12-24 05:29:36576 int64_t total_num_intervals_elapsed =
raymesbfb910a2015-04-29 07:43:09577 (time_since_last_report / report_interval_);
avi9ef8bb02015-12-24 05:29:36578 for (int64_t i = 0; i < total_num_intervals_elapsed - 1; ++i)
raymesbfb910a2015-04-29 07:43:09579 histogram->Add(0);
580
581 writes_since_last_report_ = 0;
582 last_report_time_ += total_num_intervals_elapsed * report_interval_;
583}
584
585base::HistogramBase* JsonPrefStore::WriteCountHistogram::GetHistogram() {
586 std::string spaceless_basename;
587 base::ReplaceChars(path_.BaseName().MaybeAsASCII(), " ", "_",
588 &spaceless_basename);
589 std::string histogram_name =
590 "Settings.JsonDataWriteCount." + spaceless_basename;
591
592 // The min value for a histogram is 1. The max value is the maximum number of
593 // writes that can occur in the window being recorded. The number of buckets
594 // used is the max value (plus the underflow/overflow buckets).
595 int32_t min_value = 1;
596 int32_t max_value = report_interval_ / commit_interval_;
597 int32_t num_buckets = max_value + 1;
598
599 // NOTE: These values should NOT be changed without renaming the histogram
600 // otherwise it will create incompatible buckets.
601 DCHECK_EQ(30, max_value);
602 DCHECK_EQ(31, num_buckets);
603
604 // The histogram below is an expansion of the UMA_HISTOGRAM_CUSTOM_COUNTS
605 // macro adapted to allow for a dynamically suffixed histogram name.
606 // Note: The factory creates and owns the histogram.
607 base::HistogramBase* histogram = base::Histogram::FactoryGet(
608 histogram_name, min_value, max_value, num_buckets,
609 base::HistogramBase::kUmaTargetedHistogramFlag);
610 return histogram;
611}