blob: 832d233d1eb1cbc4cba35080919783bedf47761c [file] [log] [blame]
James Robinson646469d2014-10-03 15:33:28 -07001// 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.
4
James Robinson1572dd52015-09-28 14:17:16 -07005#ifndef SERVICES_JS_SYSTEM_DRAIN_DATA_H_
6#define SERVICES_JS_SYSTEM_DRAIN_DATA_H_
James Robinson646469d2014-10-03 15:33:28 -07007
8#include "base/memory/scoped_vector.h"
9#include "gin/runner.h"
10#include "mojo/public/c/environment/async_waiter.h"
Viet-Trung Luuadf6aa82016-03-15 11:28:19 -070011#include "mojo/public/c/system/result.h"
12#include "mojo/public/cpp/system/data_pipe.h"
13#include "mojo/public/cpp/system/handle.h"
James Robinson646469d2014-10-03 15:33:28 -070014#include "v8/include/v8.h"
15
16namespace mojo {
17namespace js {
18
19// This class is the implementation of the Mojo JavaScript core module's
20// drainData() method. It is not intended to be used directly. The caller
21// allocates a DrainData on the heap and returns GetPromise() to JS. The
22// implementation deletes itself after reading as much data as possible
23// and rejecting or resolving the Promise.
24
25class DrainData {
26 public:
27 // Starts waiting for data on the specified data pipe consumer handle.
28 // See WaitForData(). The constructor does not block.
29 DrainData(v8::Isolate* isolate, mojo::Handle handle);
30
31 // Returns a Promise that will be settled when no more data can be read.
32 // Should be called just once on a newly allocated DrainData object.
33 v8::Handle<v8::Value> GetPromise();
34
35 private:
36 ~DrainData();
37
38 // Registers an "async waiter" that calls DataReady() via WaitCompleted().
39 void WaitForData();
40 static void WaitCompleted(void* self, MojoResult result) {
41 static_cast<DrainData*>(self)->DataReady(result);
42 }
43
44 // Use ReadData() to read whatever is availble now on handle_ and save
45 // it in data_buffers_.
46 void DataReady(MojoResult result);
47 MojoResult ReadData();
48
49 // When the remote data pipe handle is closed, or an error occurs, deliver
50 // all of the buffered data to the JS Promise and then delete this.
51 void DeliverData(MojoResult result);
52
Viet-Trung Luu9acf1aa2015-05-22 11:24:40 -070053 using DataBuffer = std::vector<char>;
James Robinson646469d2014-10-03 15:33:28 -070054
55 v8::Isolate* isolate_;
56 ScopedDataPipeConsumerHandle handle_;
57 MojoAsyncWaitID wait_id_;
58 base::WeakPtr<gin::Runner> runner_;
59 v8::UniquePersistent<v8::Promise::Resolver> resolver_;
60 ScopedVector<DataBuffer> data_buffers_;
61};
62
63} // namespace js
64} // namespace mojo
65
James Robinson1572dd52015-09-28 14:17:16 -070066#endif // SERVICES_JS_SYSTEM_DRAIN_DATA_H_