1 // Copyright 2018 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 CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_STREAM_BLOB_H_
6 #define CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_STREAM_BLOB_H_
7 
8 #include "base/callback.h"
9 #include "base/containers/queue.h"
10 #include "base/memory/scoped_refptr.h"
11 #include "content/browser/devtools/devtools_io_context.h"
12 #include "net/base/net_errors.h"
13 #include "storage/browser/blob/blob_storage_constants.h"
14 
15 #include <memory>
16 
17 namespace net {
18 class IOBufferWithSize;
19 }
20 
21 namespace storage {
22 class BlobDataHandle;
23 class BlobReader;
24 }  // namespace storage
25 
26 namespace content {
27 class ChromeBlobStorageContext;
28 class StoragePartition;
29 
30 class DevToolsStreamBlob : public DevToolsIOContext::Stream {
31  public:
32   using OpenCallback = base::OnceCallback<void(bool)>;
33 
34   static scoped_refptr<DevToolsIOContext::Stream> Create(
35       DevToolsIOContext* io_context,
36       ChromeBlobStorageContext* blob_context,
37       StoragePartition* partition,
38       const std::string& handle,
39       const std::string& uuid);
40 
41  private:
42   DevToolsStreamBlob();
43 
44   void Open(scoped_refptr<ChromeBlobStorageContext> context,
45             StoragePartition* partition,
46             const std::string& handle,
47             OpenCallback callback);
48 
49   void Read(off_t position, size_t max_size, ReadCallback callback) override;
50 
51   struct ReadRequest {
52     off_t position;
53     size_t max_size;
54     ReadCallback callback;
55 
56     void Fail();
57 
58     ReadRequest() = delete;
59     ReadRequest(off_t position, size_t max_size, ReadCallback callback);
60     ~ReadRequest();
61   };
62 
63   ~DevToolsStreamBlob() override;
64 
65   void OpenOnIO(scoped_refptr<ChromeBlobStorageContext> blob_context,
66                 const std::string& uuid,
67                 OpenCallback callback);
68   void ReadOnIO(std::unique_ptr<ReadRequest> request);
69   void CloseOnIO(bool invoke_pending_callbacks);
70 
71   void FailOnIO();
72   void FailOnIO(OpenCallback callback);
73 
74   void StartReadRequest();
75   void CreateReader();
76   void BeginRead();
77 
78   void OnReadComplete(int bytes_read);
79   void OnBlobConstructionComplete(storage::BlobStatus status);
80   void OnCalculateSizeComplete(int net_error);
81 
82   std::unique_ptr<storage::BlobDataHandle> blob_handle_;
83   OpenCallback open_callback_;
84   std::unique_ptr<storage::BlobReader> blob_reader_;
85   base::queue<std::unique_ptr<ReadRequest>> pending_reads_;
86   scoped_refptr<net::IOBufferWithSize> io_buf_;
87   off_t last_read_pos_;
88   bool failed_;
89   bool is_binary_;
90 };
91 
92 }  // namespace content
93 
94 #endif  // CONTENT_BROWSER_DEVTOOLS_DEVTOOLS_STREAM_BLOB_H_
95