1 // Copyright 2014 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 CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_DATABASE_H_
6 #define CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_DATABASE_H_
13 #include "base/files/file_path.h"
14 #include "base/gtest_prod_util.h"
15 #include "base/macros.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/sequence_checker.h"
18 #include "base/time/time.h"
19 #include "content/common/content_export.h"
20 #include "content/common/service_worker/service_worker_status_code.h"
32 // Class to persist serviceworker registration data in a database.
33 // Should NOT be used on the IO thread since this does blocking
34 // file io. The ServiceWorkerStorage class owns this class and
35 // is responsible for only calling it serially on background
36 // non-IO threads (ala SequencedWorkerPool).
37 class CONTENT_EXPORT ServiceWorkerDatabase
{
39 // We do leveldb stuff in |path| or in memory if |path| is empty.
40 explicit ServiceWorkerDatabase(const base::FilePath
& path
);
41 ~ServiceWorkerDatabase();
43 // Used in UMA. A new value must be appended only.
46 STATUS_ERROR_NOT_FOUND
,
47 STATUS_ERROR_IO_ERROR
,
48 STATUS_ERROR_CORRUPTED
,
52 static const char* StatusToString(Status status
);
54 struct CONTENT_EXPORT RegistrationData
{
55 // These values are immutable for the life of a registration.
56 int64 registration_id
;
59 // Versions are first stored once they successfully install and become
60 // the waiting version. Then transition to the active version. The stored
61 // version may be in the ACTIVATED state or in the INSTALLED state.
65 bool has_fetch_handler
;
66 base::Time last_update_check
;
68 // Not populated until ServiceWorkerStorage::StoreRegistration is called.
69 int64_t resources_total_size_bytes
;
75 struct ResourceRecord
{
78 // Signed so we can store -1 to specify an unknown or error state. When
79 // stored to the database, this value should always be >= 0.
82 ResourceRecord() : resource_id(-1), size_bytes(0) {}
83 ResourceRecord(int64 id
, GURL url
, int64 size_bytes
)
84 : resource_id(id
), url(url
), size_bytes(size_bytes
) {}
87 // Reads next available ids from the database. Returns OK if they are
88 // successfully read. Fills the arguments with an initial value and returns
89 // OK if they are not found in the database. Otherwise, returns an error.
90 Status
GetNextAvailableIds(
91 int64
* next_avail_registration_id
,
92 int64
* next_avail_version_id
,
93 int64
* next_avail_resource_id
);
95 // Reads origins that have one or more than one registration from the
96 // database. Returns OK if they are successfully read or not found.
97 // Otherwise, returns an error.
98 Status
GetOriginsWithRegistrations(std::set
<GURL
>* origins
);
100 // Reads registrations for |origin| from the database. Returns OK if they are
101 // successfully read or not found. Otherwise, returns an error.
102 Status
GetRegistrationsForOrigin(
104 std::vector
<RegistrationData
>* registrations
);
106 // Reads all registrations from the database. Returns OK if successfully read
107 // or not found. Otherwise, returns an error.
108 Status
GetAllRegistrations(std::vector
<RegistrationData
>* registrations
);
110 // Saving, retrieving, and updating registration data.
111 // (will bump next_avail_xxxx_ids as needed)
112 // (resource ids will be added/removed from the uncommitted/purgeable
115 // Reads a registration for |registration_id| and resource records associated
116 // with it from the database. Returns OK if they are successfully read.
117 // Otherwise, returns an error.
118 Status
ReadRegistration(
119 int64 registration_id
,
121 RegistrationData
* registration
,
122 std::vector
<ResourceRecord
>* resources
);
124 // Looks up the origin for the registration with |registration_id|. Returns OK
125 // if a registration was found and read successfully. Otherwise, returns an
127 Status
ReadRegistrationOrigin(int64 registration_id
, GURL
* origin
);
129 // Writes |registration| and |resources| into the database and does following
131 // - If an old version of the registration exists, deletes it and sets
132 // |deleted_version| to the old version registration data object
133 // |newly_purgeable_resources| to its resources. Otherwise, sets
134 // |deleted_version->version_id| to -1.
135 // - Bumps the next registration id and the next version id if needed.
136 // - Removes |resources| from the uncommitted list if exist.
137 // Returns OK they are successfully written. Otherwise, returns an error.
138 Status
WriteRegistration(const RegistrationData
& registration
,
139 const std::vector
<ResourceRecord
>& resources
,
140 RegistrationData
* deleted_version
,
141 std::vector
<int64
>* newly_purgeable_resources
);
143 // Updates a registration for |registration_id| to an active state. Returns OK
144 // if it's successfully updated. Otherwise, returns an error.
145 Status
UpdateVersionToActive(
146 int64 registration_id
,
149 // Updates last check time of a registration for |registration_id| by |time|.
150 // Returns OK if it's successfully updated. Otherwise, returns an error.
151 Status
UpdateLastCheckTime(
152 int64 registration_id
,
154 const base::Time
& time
);
156 // Deletes a registration for |registration_id| and moves resource records
157 // associated with it into the purgeable list. If deletion occurred, sets
158 // |version_id| to the id of the version that was deleted and
159 // |newly_purgeable_resources| to its resources; otherwise, sets |version_id|
160 // to -1. Returns OK if it's successfully deleted or not found in the
161 // database. Otherwise, returns an error.
162 Status
DeleteRegistration(int64 registration_id
,
164 RegistrationData
* deleted_version
,
165 std::vector
<int64
>* newly_purgeable_resources
);
167 // Reads user data for |registration_id| and |user_data_name| from the
169 Status
ReadUserData(int64 registration_id
,
170 const std::string
& user_data_name
,
171 std::string
* user_data
);
173 // Writes |user_data| into the database. Returns NOT_FOUND if the registration
174 // specified by |registration_id| does not exist in the database.
175 Status
WriteUserData(int64 registration_id
,
177 const std::string
& user_data_name
,
178 const std::string
& user_data
);
180 // Deletes user data for |registration_id| and |user_data_name| from the
181 // database. Returns OK if it's successfully deleted or not found in the
183 Status
DeleteUserData(int64 registration_id
,
184 const std::string
& user_data_name
);
186 // Reads user data for all registrations that have data with |user_data_name|
187 // from the database. Returns OK if they are successfully read or not found.
188 Status
ReadUserDataForAllRegistrations(
189 const std::string
& user_data_name
,
190 std::vector
<std::pair
<int64
, std::string
>>* user_data
);
192 // As new resources are put into the diskcache, they go into an uncommitted
193 // list. When a registration is saved that refers to those ids, they're
194 // removed from that list. When a resource no longer has any registrations or
195 // caches referring to it, it's added to the purgeable list. Periodically,
196 // the purgeable list can be purged from the diskcache. At system startup, all
197 // uncommitted ids are moved to the purgeable list.
199 // Reads uncommitted resource ids from the database. Returns OK on success.
200 // Otherwise clears |ids| and returns an error.
201 Status
GetUncommittedResourceIds(std::set
<int64
>* ids
);
203 // Writes |ids| into the database as uncommitted resources. Returns OK on
204 // success. Otherwise writes nothing and returns an error.
205 Status
WriteUncommittedResourceIds(const std::set
<int64
>& ids
);
207 // Deletes uncommitted resource ids specified by |ids| from the database.
208 // Returns OK on success. Otherwise deletes nothing and returns an error.
209 Status
ClearUncommittedResourceIds(const std::set
<int64
>& ids
);
211 // Reads purgeable resource ids from the database. Returns OK on success.
212 // Otherwise clears |ids| and returns an error.
213 Status
GetPurgeableResourceIds(std::set
<int64
>* ids
);
215 // Writes |ids| into the database as purgeable resources. Returns OK on
216 // success. Otherwise writes nothing and returns an error.
217 Status
WritePurgeableResourceIds(const std::set
<int64
>& ids
);
219 // Deletes purgeable resource ids specified by |ids| from the database.
220 // Returns OK on success. Otherwise deletes nothing and returns an error.
221 Status
ClearPurgeableResourceIds(const std::set
<int64
>& ids
);
223 // Moves |ids| from the uncommitted list to the purgeable list.
224 // Returns OK on success. Otherwise deletes nothing and returns an error.
225 Status
PurgeUncommittedResourceIds(const std::set
<int64
>& ids
);
227 // Deletes all data for |origins|, namely, unique origin, registrations and
228 // resource records. Resources are moved to the purgeable list. Returns OK if
229 // they are successfully deleted or not found in the database. Otherwise,
231 Status
DeleteAllDataForOrigins(const std::set
<GURL
>& origins
,
232 std::vector
<int64
>* newly_purgeable_resources
);
234 // Completely deletes the contents of the database.
235 // Be careful using this function.
236 Status
DestroyDatabase();
239 // Opens the database at the |path_|. This is lazily called when the first
240 // database API is called. Returns OK if the database is successfully opened.
241 // Returns NOT_FOUND if the database does not exist and |create_if_missing| is
242 // false. Otherwise, returns an error.
243 Status
LazyOpen(bool create_if_missing
);
245 // Helper for LazyOpen(). |status| must be the return value from LazyOpen()
246 // and this must be called just after LazyOpen() is called. Returns true if
247 // the database is new or nonexistent, that is, it has never been used.
248 bool IsNewOrNonexistentDatabase(Status status
);
250 // Upgrades the database schema from version 1 to version 2. Called by
251 // LazyOpen() when the stored schema is older than version 2.
252 Status
UpgradeDatabaseSchemaFromV1ToV2();
254 // Reads the next available id for |id_key|. Returns OK if it's successfully
255 // read. Fills |next_avail_id| with an initial value and returns OK if it's
256 // not found in the database. Otherwise, returns an error.
257 Status
ReadNextAvailableId(
259 int64
* next_avail_id
);
261 // Reads registration data for |registration_id| from the database. Returns OK
262 // if successfully reads. Otherwise, returns an error.
263 Status
ReadRegistrationData(
264 int64 registration_id
,
266 RegistrationData
* registration
);
268 // Reads resource records for |version_id| from the database. Returns OK if
269 // it's successfully read or not found in the database. Otherwise, returns an
271 Status
ReadResourceRecords(
273 std::vector
<ResourceRecord
>* resources
);
275 // Deletes resource records for |version_id| from the database. Returns OK if
276 // they are successfully deleted or not found in the database. Otherwise,
278 Status
DeleteResourceRecords(
280 std::vector
<int64
>* newly_purgeable_resources
,
281 leveldb::WriteBatch
* batch
);
283 // Reads resource ids for |id_key_prefix| from the database. Returns OK if
284 // it's successfully read or not found in the database. Otherwise, returns an
286 Status
ReadResourceIds(
287 const char* id_key_prefix
,
288 std::set
<int64
>* ids
);
290 // Write resource ids for |id_key_prefix| into the database. Returns OK on
291 // success. Otherwise, returns writes nothing and returns an error.
292 Status
WriteResourceIds(
293 const char* id_key_prefix
,
294 const std::set
<int64
>& ids
);
295 Status
WriteResourceIdsInBatch(
296 const char* id_key_prefix
,
297 const std::set
<int64
>& ids
,
298 leveldb::WriteBatch
* batch
);
300 // Deletes resource ids for |id_key_prefix| from the database. Returns OK if
301 // it's successfully deleted or not found in the database. Otherwise, returns
303 Status
DeleteResourceIds(
304 const char* id_key_prefix
,
305 const std::set
<int64
>& ids
);
306 Status
DeleteResourceIdsInBatch(
307 const char* id_key_prefix
,
308 const std::set
<int64
>& ids
,
309 leveldb::WriteBatch
* batch
);
311 // Deletes all user data for |registration_id| from the database. Returns OK
312 // if they are successfully deleted or not found in the database.
313 Status
DeleteUserDataForRegistration(
314 int64 registration_id
,
315 leveldb::WriteBatch
* batch
);
317 // Reads the current schema version from the database. If the database hasn't
318 // been written anything yet, sets |db_version| to 0 and returns OK.
319 Status
ReadDatabaseVersion(int64
* db_version
);
321 // Writes a batch into the database.
322 // NOTE: You must call this when you want to put something into the database
323 // because this initializes the database if needed.
324 Status
WriteBatch(leveldb::WriteBatch
* batch
);
326 // Bumps the next available id if |used_id| is greater than or equal to the
328 void BumpNextRegistrationIdIfNeeded(
330 leveldb::WriteBatch
* batch
);
331 void BumpNextResourceIdIfNeeded(
333 leveldb::WriteBatch
* batch
);
334 void BumpNextVersionIdIfNeeded(
336 leveldb::WriteBatch
* batch
);
341 const tracked_objects::Location
& from_here
,
343 void HandleOpenResult(
344 const tracked_objects::Location
& from_here
,
346 void HandleReadResult(
347 const tracked_objects::Location
& from_here
,
349 void HandleWriteResult(
350 const tracked_objects::Location
& from_here
,
353 base::FilePath path_
;
354 scoped_ptr
<leveldb::Env
> env_
;
355 scoped_ptr
<leveldb::DB
> db_
;
357 int64 next_avail_registration_id_
;
358 int64 next_avail_resource_id_
;
359 int64 next_avail_version_id_
;
368 base::SequenceChecker sequence_checker_
;
370 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerDatabaseTest
, OpenDatabase
);
371 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerDatabaseTest
, OpenDatabase_InMemory
);
372 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerDatabaseTest
, DatabaseVersion
);
373 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerDatabaseTest
, GetNextAvailableIds
);
374 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerDatabaseTest
,
375 Registration_UninitializedDatabase
);
376 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerDatabaseTest
,
377 UserData_UninitializedDatabase
);
378 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerDatabaseTest
, DestroyDatabase
);
379 FRIEND_TEST_ALL_PREFIXES(ServiceWorkerDatabaseTest
, UpgradeSchemaToVersion2
);
381 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerDatabase
);
384 } // namespace content
386 #endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_DATABASE_H_