1 // Copyright 2017 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.
4 
5 #ifndef COMPONENTS_FEATURE_ENGAGEMENT_INTERNAL_PERSISTENT_EVENT_STORE_H_
6 #define COMPONENTS_FEATURE_ENGAGEMENT_INTERNAL_PERSISTENT_EVENT_STORE_H_
7 
8 #include <memory>
9 #include <vector>
10 
11 #include "base/files/file_path.h"
12 #include "base/macros.h"
13 #include "base/memory/weak_ptr.h"
14 #include "components/feature_engagement/internal/event_store.h"
15 #include "components/feature_engagement/internal/proto/feature_event.pb.h"
16 #include "components/leveldb_proto/public/proto_database.h"
17 
18 namespace feature_engagement {
19 
20 // A PersistentEventStore provides a DB layer that persists the data to disk.
21 // The data is retrieved once during the load process and after that this store
22 // is write only.  Data will be persisted asynchronously so it is not guaranteed
23 // to always save every write during shutdown.
24 class PersistentEventStore : public EventStore {
25  public:
26   // Builds a PersistentEventStore backed by the ProtoDatabase |db|.
27   PersistentEventStore(std::unique_ptr<leveldb_proto::ProtoDatabase<Event>> db);
28   ~PersistentEventStore() override;
29 
30   // EventStore implementation.
31   void Load(OnLoadedCallback callback) override;
32   bool IsReady() const override;
33   void WriteEvent(const Event& event) override;
34   void DeleteEvent(const std::string& event_name) override;
35 
36  private:
37   void OnInitComplete(OnLoadedCallback callback,
38                       leveldb_proto::Enums::InitStatus status);
39   void OnLoadComplete(OnLoadedCallback callback,
40                       bool success,
41                       std::unique_ptr<std::vector<Event>> entries);
42 
43   const base::FilePath storage_dir_;
44   std::unique_ptr<leveldb_proto::ProtoDatabase<Event>> db_;
45 
46   // Whether or not the underlying ProtoDatabase is ready.  This will be false
47   // until the OnLoadedCallback is broadcast.  It will also be false if loading
48   // fails.
49   bool ready_;
50 
51   base::WeakPtrFactory<PersistentEventStore> weak_ptr_factory_{this};
52 
53   DISALLOW_COPY_AND_ASSIGN(PersistentEventStore);
54 };
55 
56 }  // namespace feature_engagement
57 
58 #endif  // COMPONENTS_FEATURE_ENGAGEMENT_INTERNAL_PERSISTENT_EVENT_STORE_H_
59