Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / chrome / browser / extensions / activity_log / activity_database.h
blob9479f0d2f1be30d89369af6bc89cadb0571d4e36
1 // Copyright (c) 2013 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 CHROME_BROWSER_EXTENSIONS_ACTIVITY_LOG_ACTIVITY_DATABASE_H_
6 #define CHROME_BROWSER_EXTENSIONS_ACTIVITY_LOG_ACTIVITY_DATABASE_H_
8 #include <string>
9 #include <vector>
11 #include "base/basictypes.h"
12 #include "base/files/file_path.h"
13 #include "base/gtest_prod_util.h"
14 #include "base/memory/ref_counted_memory.h"
15 #include "base/synchronization/lock.h"
16 #include "base/timer/timer.h"
17 #include "chrome/browser/extensions/activity_log/activity_actions.h"
18 #include "extensions/common/extension.h"
19 #include "sql/connection.h"
21 namespace base {
22 class Clock;
23 class FilePath;
26 namespace extensions {
28 // Encapsulates the SQL connection for the activity log database. This class
29 // holds the database connection and has methods for writing. All of the
30 // methods except the constructor need to be called on the DB thread.
32 // Object ownership and lifetime is a bit complicated for ActivityLog,
33 // ActivityLogPolicy, and ActivityDatabase:
35 // ActivityLog ----> ActivityLogPolicy ----> ActivityDatabase
36 // ^ |
37 // | |
38 // \--(ActivityDatabase::Delegate)-/
40 // The ActivityLogPolicy object contains a pointer to the ActivityDatabase, and
41 // the ActivityDatabase contains a pointer back to the ActivityLogPolicy object
42 // (as an instance of ActivityDatabase::Delegate).
44 // Since some cleanup must happen on the database thread, deletion should occur
45 // as follows:
46 // 1. ActivityLog calls ActivityLogPolicy::Close()
47 // 2. ActivityLogPolicy should call ActivityDatabase::Close() on the database
48 // thread.
49 // 3. ActivityDatabase::Close() shuts down the database, then calls
50 // ActivityDatabase::Delegate::OnDatabaseClose().
51 // 4. ActivityDatabase::Delegate::OnDatabaseClose() should delete the
52 // ActivityLogPolicy object.
53 // 5. ActivityDatabase::Close() finishes running by deleting the
54 // ActivityDatabase object.
56 // (This assumes the common case that the ActivityLogPolicy uses an
57 // ActivityDatabase and implements the ActivityDatabase::Delegate interface.
58 // It is also possible for an ActivityLogPolicy to not use a database at all,
59 // in which case ActivityLogPolicy::Close() should directly delete itself.)
60 class ActivityDatabase {
61 public:
62 // Interface defining calls that the ActivityDatabase can make into a
63 // ActivityLogPolicy instance to implement policy-specific behavior. Methods
64 // are always invoked on the database thread. Classes other than
65 // ActivityDatabase should not call these methods.
66 class Delegate {
67 protected:
68 friend class ActivityDatabase;
70 // A Delegate is never directly deleted; it should instead delete itself
71 // after any final cleanup when OnDatabaseClose() is invoked.
72 virtual ~Delegate() {}
74 // Initializes the database schema; this gives a policy a chance to create
75 // or update database tables as needed. Should return true on success.
76 // Will be called from within a database transaction.
77 virtual bool InitDatabase(sql::Connection* db) = 0;
79 // Requests that the policy flush any pending actions to the database.
80 // Should return true on success or false on a database error. Will not be
81 // called from a transaction (the implementation may wish to use a
82 // transaction for the flush).
83 virtual bool FlushDatabase(sql::Connection* db) = 0;
85 // Called if the database encounters a permanent error; the policy should
86 // not expect to make any future writes to the database and may want to
87 // discard any queued data.
88 virtual void OnDatabaseFailure() = 0;
90 // Called by ActivityDatabase just before the ActivityDatabase object is
91 // deleted. The database will make no further callbacks after invoking
92 // this method, so it is an appropriate time for the policy to delete
93 // itself.
94 virtual void OnDatabaseClose() = 0;
97 // Value to be passed to AdviseFlush below to force a database flush.
98 static const int kFlushImmediately = -1;
100 // Need to call Init to actually use the ActivityDatabase. The Delegate
101 // provides hooks for an ActivityLogPolicy to control the database schema and
102 // reads/writes.
103 explicit ActivityDatabase(Delegate* delegate);
105 // Opens the DB. This invokes OnDatabaseInit in the delegate to create or
106 // update the database schema if needed.
107 void Init(const base::FilePath& db_name);
109 // An ActivityLogPolicy should call this to kill the ActivityDatabase.
110 void Close();
112 // Inform the database that there may be additional data which could be
113 // written out. The size parameter should indicate (approximately) how many
114 // records are queued to be written; the database may use this information to
115 // schedule a flush early if too much data is queueing up. A value of
116 // kFlushImmediately will force an immediate call into
117 // Delegate::FlushDatabase(); otherwise, it is up to the database to
118 // determine when to flush.
119 void AdviseFlush(int size);
121 // Turns off batch I/O writing mode. This should only be used in unit tests,
122 // browser tests, or in our special --enable-extension-activity-log-testing
123 // policy state.
124 void SetBatchModeForTesting(bool batch_mode);
126 bool is_db_valid() const { return valid_db_; }
128 // A helper method for initializing or upgrading a database table. The
129 // content_fields array should list the names of all of the columns in the
130 // database. The field_types should specify the types of the corresponding
131 // columns (e.g., INTEGER or LONGVARCHAR). There should be the same number of
132 // field_types as content_fields, since the two arrays should correspond.
133 static bool InitializeTable(sql::Connection* db,
134 const char* table_name,
135 const char* const content_fields[],
136 const char* const field_types[],
137 const int num_content_fields);
139 // Runs the given callback, passing it a handle to the database connection.
140 // If the database is not valid, the callback is run (to allow it to do any
141 // needed cleanup) but passed a NULL value.
142 void RunOnDatabase(const base::Callback<void(sql::Connection*)>& callback);
144 private:
145 // This should never be invoked by another class. Use Close() to order a
146 // suicide.
147 virtual ~ActivityDatabase();
149 // Used by the Init() method as a convenience for handling a failed database
150 // initialization attempt. Prints an error and puts us in the soft failure
151 // state.
152 void LogInitFailure();
154 // When we're in batched mode (which is on by default), we write to the db
155 // every X minutes instead of on every API call. This prevents the annoyance
156 // of writing to disk multiple times a second.
157 void RecordBatchedActions();
159 // If an error is unrecoverable or occurred while we were trying to close
160 // the database properly, we take "emergency" actions: break any outstanding
161 // transactions, raze the database, and close. When next opened, the
162 // database will be empty.
163 void HardFailureClose();
165 // Doesn't actually close the DB, but changes bools to prevent further writes
166 // or changes to it.
167 void SoftFailureClose();
169 // Handle errors in database writes. For a serious & permanent error, it
170 // invokes HardFailureClose(); for a less serious/permanent error, it invokes
171 // SoftFailureClose().
172 void DatabaseErrorCallback(int error, sql::Statement* stmt);
174 // For unit testing only.
175 void RecordBatchedActionsWhileTesting();
176 void SetTimerForTesting(int milliseconds);
178 // Retrieve a handle to the raw SQL database. This is only intended to be
179 // used by ActivityLogDatabasePolicy::GetDatabaseConnection(), and should
180 // only be called on the database thread.
181 sql::Connection* GetSqlConnection();
183 // A reference a Delegate for policy-specific database behavior. See the
184 // top-level comment for ActivityDatabase for comments on cleanup.
185 Delegate* delegate_;
187 sql::Connection db_;
188 bool valid_db_;
189 bool batch_mode_;
190 base::TimeDelta batching_period_;
191 base::RepeatingTimer<ActivityDatabase> timer_;
192 bool already_closed_;
193 bool did_init_;
195 friend class ActivityLogDatabasePolicy;
196 FRIEND_TEST_ALL_PREFIXES(ActivityDatabaseTest, BatchModeOff);
197 FRIEND_TEST_ALL_PREFIXES(ActivityDatabaseTest, BatchModeOn);
198 FRIEND_TEST_ALL_PREFIXES(ActivityDatabaseTest, BatchModeFlush);
199 DISALLOW_COPY_AND_ASSIGN(ActivityDatabase);
202 } // namespace extensions
204 #endif // CHROME_BROWSER_EXTENSIONS_ACTIVITY_LOG_ACTIVITY_DATABASE_H_