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_FILES_IMPORTANT_FILE_WRITER_H_
6 #define BASE_FILES_IMPORTANT_FILE_WRITER_H_
10 #include "base/base_export.h"
11 #include "base/basictypes.h"
12 #include "base/callback.h"
13 #include "base/files/file_path.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/threading/non_thread_safe.h"
16 #include "base/time/time.h"
17 #include "base/timer/timer.h"
21 class SequencedTaskRunner
;
24 // Helper to ensure that a file won't be corrupted by the write (for example on
25 // application crash). Consider a naive way to save an important file F:
27 // 1. Open F for writing, truncating it.
28 // 2. Write new data to F.
30 // It's good when it works, but it gets very bad if step 2. doesn't complete.
31 // It can be caused by a crash, a computer hang, or a weird I/O error. And you
32 // end up with a broken file.
34 // To be safe, we don't start with writing directly to F. Instead, we write to
35 // to a temporary file. Only after that write is successful, we rename the
36 // temporary file to target filename.
38 // If you want to know more about this approach and ext3/ext4 fsync issues, see
39 // http://valhenson.livejournal.com/37921.html
40 class BASE_EXPORT ImportantFileWriter
: public NonThreadSafe
{
42 // Used by ScheduleSave to lazily provide the data to be saved. Allows us
43 // to also batch data serializations.
44 class BASE_EXPORT DataSerializer
{
46 // Should put serialized string in |data| and return true on successful
47 // serialization. Will be called on the same thread on which
48 // ImportantFileWriter has been created.
49 virtual bool SerializeData(std::string
* data
) = 0;
52 virtual ~DataSerializer() {}
55 // Save |data| to |path| in an atomic manner (see the class comment above).
56 // Blocks and writes data on the current thread.
57 static bool WriteFileAtomically(const FilePath
& path
,
58 const std::string
& data
);
60 // Initialize the writer.
61 // |path| is the name of file to write.
62 // |task_runner| is the SequencedTaskRunner instance where on which we will
63 // execute file I/O operations.
64 // All non-const methods, ctor and dtor must be called on the same thread.
65 ImportantFileWriter(const FilePath
& path
,
66 base::SequencedTaskRunner
* task_runner
);
68 // You have to ensure that there are no pending writes at the moment
70 ~ImportantFileWriter();
72 const FilePath
& path() const { return path_
; }
74 // Returns true if there is a scheduled write pending which has not yet
76 bool HasPendingWrite() const;
78 // Save |data| to target filename. Does not block. If there is a pending write
79 // scheduled by ScheduleWrite, it is cancelled.
80 void WriteNow(const std::string
& data
);
82 // Schedule a save to target filename. Data will be serialized and saved
83 // to disk after the commit interval. If another ScheduleWrite is issued
84 // before that, only one serialization and write to disk will happen, and
85 // the most recent |serializer| will be used. This operation does not block.
86 // |serializer| should remain valid through the lifetime of
87 // ImportantFileWriter.
88 void ScheduleWrite(DataSerializer
* serializer
);
90 // Serialize data pending to be saved and execute write on backend thread.
91 void DoScheduledWrite();
93 // Registers |on_next_successful_write| to be called once, on the next
94 // successful write event. Only one callback can be set at once.
95 void RegisterOnNextSuccessfulWriteCallback(
96 const base::Closure
& on_next_successful_write
);
98 TimeDelta
commit_interval() const {
99 return commit_interval_
;
102 void set_commit_interval(const TimeDelta
& interval
) {
103 commit_interval_
= interval
;
107 // Helper method for WriteNow().
108 bool PostWriteTask(const std::string
& data
);
110 // If |result| is true and |on_next_successful_write_| is set, invokes
111 // |on_successful_write_| and then resets it; no-ops otherwise.
112 void ForwardSuccessfulWrite(bool result
);
114 // Invoked once and then reset on the next successful write event.
115 base::Closure on_next_successful_write_
;
117 // Path being written to.
118 const FilePath path_
;
120 // TaskRunner for the thread on which file I/O can be done.
121 const scoped_refptr
<base::SequencedTaskRunner
> task_runner_
;
123 // Timer used to schedule commit after ScheduleWrite.
124 OneShotTimer
<ImportantFileWriter
> timer_
;
126 // Serializer which will provide the data to be saved.
127 DataSerializer
* serializer_
;
129 // Time delta after which scheduled data will be written to disk.
130 TimeDelta commit_interval_
;
132 WeakPtrFactory
<ImportantFileWriter
> weak_factory_
;
134 DISALLOW_COPY_AND_ASSIGN(ImportantFileWriter
);
139 #endif // BASE_FILES_IMPORTANT_FILE_WRITER_H_