electron/shell/browser/api/electron_api_data_pipe_holder.cc
Charles Kerr 60c4c9fec6
chore: remove unused #includes (#42971)
* chore: iwyu buildflags.h

* chore: iwyu dictionary.h

* chore: iwyu arguments.h

* chore: iwyu values.h

* chore: iwyu compiler_specific.h

* chore: iwyu binder_map.h

* chore: iwyu <vector>

* chore: iwyu <set>

* chore: iwyu raw_ptr

* chore: iwyu gfx/canvas.h

* chore: iwyu gfx/color_utils.h

* chore: iwyu base/strings/stringprintf.h

* chore: iwyu base/task/thread_pool.h

* chore: iwyu base/no_destructor.h

* chore: iwyu base/path_service.h

* chore: iwyu base/files/file_pathh

* chore: iwyu base/strings/sys_string_conversions.h

* chore: iwyu base/logging.h

* chore: iwyu base/command_line.h

* chore: iwyu base/files/file_util.h

* chore: iwyu base/files/scoped_file.h

* chore: iwyu base/strings/utf_string_conversions.h

* chore: iwyu base/environment.h

* chore: iwyu base/scoped_observation.h

* chore: iwyu base/strings/string_split.h

* chore: iwyu base/strings/pattern.h

* chore: iwyu base/json/string_escape.h

* chore: iwyu base/json/json_reader.h

* chore: iwyu base/memory/singleton.h

* chore: iwyu base/observer_list.h

* chore: iwyu base/timer/timer.h

* fixup! chore: iwyu values.h

* chore: iwyu shell/browser/browser.h

* chore: iwyu base/stl_util.h

* chore: iwyu base/strings/string_util.h

* chore: iwyu shell/browser/javascript_environment.h

* chore: iwyu base/memory/ref_counted.h

* chore: iwyu base/environment.h

* chore: iwyu content/public/browser/browser_thread.h

* chore: remove unused typedef gin_helper::EventEmitter::ValueArray

* chore: iwyu gin/wrappable.h

* chore: iwyu shell/common/gin_helper/function_template_extensions.h

* chore: iwyu shell/common/gin_converters/login_item_settings_converter.h

* chore: iwyu shell/common/gin_helper/arguments.h

* chore: iwyu ui/gfx/skia_util.h

* chore: iwyu ui/gfx/geometry/rect.h

* chore: iwyu ui/gfx/image/image.h

* chore: iwyu base/strings/strcat.h

* chore: iwyu ui/native_theme/native_theme.h

* fixup! chore: iwyu shell/browser/javascript_environment.h

* fixup! chore: iwyu gfx/canvas.h

* fixup! chore: iwyu content/public/browser/browser_thread.h

* fixup! chore: iwyu ui/native_theme/native_theme.h

* fixup! chore: iwyu ui/native_theme/native_theme.h
2024-07-22 11:31:32 +02:00

193 lines
5.8 KiB
C++

// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_data_pipe_holder.h"
#include <utility>
#include <vector>
#include "base/memory/weak_ptr.h"
#include "base/no_destructor.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/simple_watcher.h"
#include "net/base/net_errors.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/key_weak_map.h"
#include "shell/common/node_includes.h"
namespace electron::api {
namespace {
// Incremental ID.
int g_next_id = 0;
// Map that manages all the DataPipeHolder objects.
KeyWeakMap<std::string>& AllDataPipeHolders() {
static base::NoDestructor<KeyWeakMap<std::string>> weak_map;
return *weak_map.get();
}
// Utility class to read from data pipe.
class DataPipeReader {
public:
DataPipeReader(gin_helper::Promise<v8::Local<v8::Value>> promise,
mojo::Remote<network::mojom::DataPipeGetter> data_pipe_getter)
: promise_(std::move(promise)),
data_pipe_getter_(std::move(data_pipe_getter)),
handle_watcher_(FROM_HERE,
mojo::SimpleWatcher::ArmingPolicy::MANUAL,
base::SequencedTaskRunner::GetCurrentDefault()) {
// Get a new data pipe and start.
mojo::ScopedDataPipeProducerHandle producer_handle;
CHECK_EQ(mojo::CreateDataPipe(nullptr, producer_handle, data_pipe_),
MOJO_RESULT_OK);
data_pipe_getter_->Read(std::move(producer_handle),
base::BindOnce(&DataPipeReader::ReadCallback,
weak_factory_.GetWeakPtr()));
handle_watcher_.Watch(data_pipe_.get(), MOJO_HANDLE_SIGNAL_READABLE,
base::BindRepeating(&DataPipeReader::OnHandleReadable,
weak_factory_.GetWeakPtr()));
}
~DataPipeReader() = default;
// disable copy
DataPipeReader(const DataPipeReader&) = delete;
DataPipeReader& operator=(const DataPipeReader&) = delete;
private:
// Callback invoked by DataPipeGetter::Read.
void ReadCallback(int32_t status, uint64_t size) {
if (status != net::OK) {
OnFailure();
return;
}
buffer_.resize(size);
head_offset_ = 0;
remaining_size_ = size;
handle_watcher_.ArmOrNotify();
}
// Called by |handle_watcher_| when data is available or the pipe was closed,
// and there's a pending Read() call.
void OnHandleReadable(MojoResult result) {
if (result != MOJO_RESULT_OK) {
OnFailure();
return;
}
// Read.
size_t length = remaining_size_;
result = data_pipe_->ReadData(
MOJO_READ_DATA_FLAG_NONE,
base::as_writable_byte_span(buffer_).subspan(head_offset_, length),
length);
if (result == MOJO_RESULT_OK) { // success
remaining_size_ -= length;
head_offset_ += length;
if (remaining_size_ == 0) {
OnSuccess();
} else {
handle_watcher_.ArmOrNotify();
}
} else if (result == MOJO_RESULT_SHOULD_WAIT) { // IO pending
handle_watcher_.ArmOrNotify();
} else { // error
OnFailure();
}
}
void OnFailure() {
promise_.RejectWithErrorMessage("Could not get blob data");
delete this;
}
void OnSuccess() {
// Copy the buffer to JS.
// TODO(nornagon): make this zero-copy by allocating the array buffer
// inside the sandbox
v8::HandleScope handle_scope(promise_.isolate());
v8::Local<v8::Value> buffer =
node::Buffer::Copy(promise_.isolate(), &buffer_.front(), buffer_.size())
.ToLocalChecked();
promise_.Resolve(buffer);
// Destroy data pipe.
handle_watcher_.Cancel();
delete this;
}
gin_helper::Promise<v8::Local<v8::Value>> promise_;
mojo::Remote<network::mojom::DataPipeGetter> data_pipe_getter_;
mojo::ScopedDataPipeConsumerHandle data_pipe_;
mojo::SimpleWatcher handle_watcher_;
// Stores read data.
std::vector<char> buffer_;
// The head of buffer.
size_t head_offset_ = 0;
// Remaining data to read.
uint64_t remaining_size_ = 0;
base::WeakPtrFactory<DataPipeReader> weak_factory_{this};
};
} // namespace
gin::WrapperInfo DataPipeHolder::kWrapperInfo = {gin::kEmbedderNativeGin};
DataPipeHolder::DataPipeHolder(const network::DataElement& element)
: id_(base::NumberToString(++g_next_id)) {
data_pipe_.Bind(
element.As<network::DataElementDataPipe>().CloneDataPipeGetter());
}
DataPipeHolder::~DataPipeHolder() = default;
v8::Local<v8::Promise> DataPipeHolder::ReadAll(v8::Isolate* isolate) {
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!data_pipe_) {
promise.RejectWithErrorMessage("Could not get blob data");
return handle;
}
new DataPipeReader(std::move(promise), std::move(data_pipe_));
return handle;
}
const char* DataPipeHolder::GetTypeName() {
return "DataPipeHolder";
}
// static
gin::Handle<DataPipeHolder> DataPipeHolder::Create(
v8::Isolate* isolate,
const network::DataElement& element) {
auto handle = gin::CreateHandle(isolate, new DataPipeHolder(element));
AllDataPipeHolders().Set(isolate, handle->id(),
handle->GetWrapper(isolate).ToLocalChecked());
return handle;
}
// static
gin::Handle<DataPipeHolder> DataPipeHolder::From(v8::Isolate* isolate,
const std::string& id) {
v8::MaybeLocal<v8::Object> object = AllDataPipeHolders().Get(isolate, id);
if (!object.IsEmpty()) {
gin::Handle<DataPipeHolder> handle;
if (gin::ConvertFromV8(isolate, object.ToLocalChecked(), &handle))
return handle;
}
return gin::Handle<DataPipeHolder>();
}
} // namespace electron::api