Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 189 additions & 0 deletions packages/react-native/ReactCxxPlatform/react/io/BlobModule.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#include "BlobModule.h"

#include <cmath>
#include <limits>
#include <utility>

namespace facebook::react {

namespace {

constexpr const char* kBlobCollectorProvider = "__blobCollectorProvider";

/// Lets JavaScript-held blobs free their bytes when garbage collected.
/// BlobManager.createFromOptions attaches a collector to each Blob.
class BlobCollector : public jsi::HostObject {
public:
BlobCollector(std::weak_ptr<BlobStore> store, std::string blobId)
: store_(std::move(store)), blobId_(std::move(blobId)) {}

BlobCollector(const BlobCollector&) = delete;
BlobCollector& operator=(const BlobCollector&) = delete;
BlobCollector(BlobCollector&&) = delete;
BlobCollector& operator=(BlobCollector&&) = delete;

~BlobCollector() override {
if (auto store = store_.lock()) {
store->remove(blobId_);
}
}

private:
std::weak_ptr<BlobStore> store_;
std::string blobId_;
};

/// Converts a JavaScript offset/size to an index, rejecting values that are not
/// non-negative integers representable as `std::size_t`.
std::optional<std::size_t> toBlobIndex(const jsi::Value& value) {
if (!value.isNumber()) {
return std::nullopt;
}
const double number = value.getNumber();
// `!(number >= 0)` also rejects NaN. The size_t maximum rounds up to a power
// of two as a double, so `<` keeps the cast in range.
if (!(number >= 0) ||
number >= static_cast<double>(std::numeric_limits<std::size_t>::max()) ||
std::trunc(number) != number) {
return std::nullopt;
}
return static_cast<std::size_t>(number);
}

} // namespace

std::optional<std::vector<uint8_t>> resolveBlobData(
jsi::Runtime& rt,
const jsi::Object& blobData,
const BlobStore& store) {
auto blobId = blobData.getProperty(rt, "blobId");
auto offset = toBlobIndex(blobData.getProperty(rt, "offset"));
auto size = toBlobIndex(blobData.getProperty(rt, "size"));
if (!blobId.isString() || !offset || !size) {
return std::nullopt;
}
return store.resolve(blobId.getString(rt).utf8(rt), *offset, *size);
}

BlobModule::BlobModule(
std::shared_ptr<CallInvoker> jsInvoker,
std::shared_ptr<BlobStore> store)
: NativeBlobModuleCxxSpec(std::move(jsInvoker)), store_(std::move(store)) {}

jsi::Object BlobModule::getConstants(jsi::Runtime& rt) {
auto constants = jsi::Object(rt);
constants.setProperty(
rt, "BLOB_URI_SCHEME", jsi::String::createFromAscii(rt, "blob"));
constants.setProperty(rt, "BLOB_URI_HOST", jsi::Value::null());
return constants;
}

void BlobModule::addNetworkingHandler(jsi::Runtime& /*rt*/) {}

void BlobModule::addWebSocketHandler(jsi::Runtime& rt, double /*id*/) {
throw jsi::JSError(rt, "BlobModule: WebSocket blobs are not supported");
}

void BlobModule::removeWebSocketHandler(jsi::Runtime& /*rt*/, double /*id*/) {}

void BlobModule::sendOverSocket(
jsi::Runtime& rt,
jsi::Object /*blob*/,
double /*socketID*/) {
throw jsi::JSError(rt, "BlobModule: WebSocket blobs are not supported");
}

void BlobModule::createFromParts(
jsi::Runtime& rt,
jsi::Array parts,
const std::string& withId) {
std::vector<uint8_t> bytes;
const auto count = parts.size(rt);
for (size_t i = 0; i < count; ++i) {
auto part = parts.getValueAtIndex(rt, i).asObject(rt);
auto type = part.getProperty(rt, "type").asString(rt).utf8(rt);
if (type == "string") {
auto text = part.getProperty(rt, "data").asString(rt).utf8(rt);
bytes.insert(bytes.end(), text.begin(), text.end());
} else if (type == "blob") {
auto data = resolveBlobData(
rt, part.getProperty(rt, "data").asObject(rt), *store_);
if (!data) {
throw jsi::JSError(
rt, "BlobModule: createFromParts references an invalid blob");
}
bytes.insert(bytes.end(), data->begin(), data->end());
} else {
throw jsi::JSError(rt, "BlobModule: invalid type for blob: " + type);
}
}
store_->store(withId, std::move(bytes));
}

void BlobModule::release(jsi::Runtime& /*rt*/, const std::string& blobId) {
store_->remove(blobId);
}

void BlobModule::installJSIBindingsWithRuntime(jsi::Runtime& rt) {
auto global = rt.global();
if (global.hasProperty(rt, kBlobCollectorProvider)) {
return;
}
auto name = jsi::PropNameID::forAscii(rt, kBlobCollectorProvider);
global.setProperty(
rt,
name,
jsi::Function::createFromHostFunction(
rt,
name,
1,
[store = std::weak_ptr<BlobStore>(store_)](
jsi::Runtime& rt,
const jsi::Value& /*thisVal*/,
const jsi::Value* args,
size_t count) -> jsi::Value {
if (count < 1 || !args->isString()) {
throw jsi::JSError(
rt, "__blobCollectorProvider expects a blob id");
}
return jsi::Object::createFromHostObject(
rt,
std::make_shared<BlobCollector>(
store, args->getString(rt).utf8(rt)));
}));
}

BlobNetworkingResponseHandler::BlobNetworkingResponseHandler(
std::shared_ptr<BlobStore> store)
: store_(std::move(store)) {}

bool BlobNetworkingResponseHandler::supports(
const std::string& responseType) const {
return responseType == "blob";
}

jsi::Value BlobNetworkingResponseHandler::toResponseData(
jsi::Runtime& rt,
std::vector<uint8_t> body) {
const auto size = static_cast<double>(body.size());
auto blobId = store_->store(std::move(body));
try {
auto blobData = jsi::Object(rt);
blobData.setProperty(rt, "blobId", jsi::String::createFromUtf8(rt, blobId));
blobData.setProperty(rt, "offset", 0);
blobData.setProperty(rt, "size", size);
return blobData;
} catch (...) {
store_->remove(blobId);
throw;
}
}

} // namespace facebook::react
59 changes: 59 additions & 0 deletions packages/react-native/ReactCxxPlatform/react/io/BlobModule.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#pragma once

#include <FBReactNativeSpec/FBReactNativeSpecJSI.h>
#include <ReactCommon/TurboModuleWithJSIBindings.h>
#include <jsi/jsi.h>
#include <react/io/BlobStore.h>
#include <react/io/NetworkingModule.h>
#include <memory>
#include <optional>
#include <string>

namespace facebook::react {

/// Returns the bytes referenced by a JS `BlobData` object
/// (`{blobId, offset, size}`), or `std::nullopt` if they are not stored.
std::optional<std::vector<uint8_t>>
resolveBlobData(facebook::jsi::Runtime &rt, const facebook::jsi::Object &blobData, const BlobStore &store);

/// C++ implementation of React Native's `BlobModule` TurboModule (see
/// `Libraries/Blob/NativeBlobModule.js`). WebSocket blobs are not supported.
class BlobModule : public NativeBlobModuleCxxSpec<BlobModule>, public TurboModuleWithJSIBindings {
public:
BlobModule(std::shared_ptr<CallInvoker> jsInvoker, std::shared_ptr<BlobStore> store);

facebook::jsi::Object getConstants(facebook::jsi::Runtime &rt);
void addNetworkingHandler(facebook::jsi::Runtime &rt);
[[noreturn]] void addWebSocketHandler(facebook::jsi::Runtime &rt, double id);
void removeWebSocketHandler(facebook::jsi::Runtime &rt, double id);
[[noreturn]] void sendOverSocket(facebook::jsi::Runtime &rt, facebook::jsi::Object blob, double socketID);
void createFromParts(facebook::jsi::Runtime &rt, facebook::jsi::Array parts, const std::string &withId);
void release(facebook::jsi::Runtime &rt, const std::string &blobId);

private:
void installJSIBindingsWithRuntime(jsi::Runtime &rt) override;

std::shared_ptr<BlobStore> store_;
};

/// Stores `Networking` response bodies requested with responseType "blob" and
/// delivers them to JS as `BlobData`, as Android's `BlobModule` does.
class BlobNetworkingResponseHandler : public INetworkingResponseHandler {
public:
explicit BlobNetworkingResponseHandler(std::shared_ptr<BlobStore> store);

[[nodiscard]] bool supports(const std::string &responseType) const override;
facebook::jsi::Value toResponseData(facebook::jsi::Runtime &rt, std::vector<uint8_t> body) override;

private:
std::shared_ptr<BlobStore> store_;
};

} // namespace facebook::react
51 changes: 51 additions & 0 deletions packages/react-native/ReactCxxPlatform/react/io/BlobStore.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#include "BlobStore.h"

#include <utility>

namespace facebook::react {

std::string BlobStore::store(std::vector<uint8_t> bytes) {
std::lock_guard<std::mutex> lock(mutex_);
// JavaScript blob identifiers are UUIDs; this generated prefix is distinct.
auto blobId = "native-blob-" + std::to_string(nextId_++);
blobs_.insert_or_assign(blobId, std::move(bytes));
return blobId;
}

void BlobStore::store(const std::string& blobId, std::vector<uint8_t> bytes) {
std::lock_guard<std::mutex> lock(mutex_);
blobs_.insert_or_assign(blobId, std::move(bytes));
}

std::optional<std::vector<uint8_t>> BlobStore::resolve(
const std::string& blobId,
std::size_t offset,
std::size_t size) const {
std::lock_guard<std::mutex> lock(mutex_);
auto it = blobs_.find(blobId);
if (it == blobs_.end()) {
return std::nullopt;
}
const auto& bytes = it->second;
if (offset > bytes.size() || size > bytes.size() - offset) {
return std::nullopt;
}
auto first = bytes.begin() +
static_cast<std::vector<uint8_t>::difference_type>(offset);
return std::vector<uint8_t>(
first, first + static_cast<std::vector<uint8_t>::difference_type>(size));
}

void BlobStore::remove(const std::string& blobId) {
std::lock_guard<std::mutex> lock(mutex_);
blobs_.erase(blobId);
}

} // namespace facebook::react
40 changes: 40 additions & 0 deletions packages/react-native/ReactCxxPlatform/react/io/BlobStore.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#pragma once

#include <cstddef>
#include <cstdint>
#include <mutex>
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>

namespace facebook::react {

/// Thread-safe byte storage shared by BlobModule, FileReaderModule and
/// blob-aware Networking. Contents are undecoded byte vectors.
class BlobStore {
public:
/// Stores `bytes` under a newly generated id and returns that id.
std::string store(std::vector<uint8_t> bytes);
void store(const std::string &blobId, std::vector<uint8_t> bytes);

/// Returns `size` bytes starting at `offset`, or `std::nullopt` when the id
/// is unknown or the range is out of bounds.
std::optional<std::vector<uint8_t>> resolve(const std::string &blobId, std::size_t offset, std::size_t size) const;

void remove(const std::string &blobId);

private:
mutable std::mutex mutex_;
std::unordered_map<std::string, std::vector<uint8_t>> blobs_;
uint64_t nextId_{0};
};

} // namespace facebook::react
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ add_library(react_cxx_platform_react_io OBJECT ${react_cxx_platform_react_io_SRC
target_include_directories(react_cxx_platform_react_io PUBLIC ${REACT_CXX_PLATFORM_DIR})

target_link_libraries(react_cxx_platform_react_io
folly_runtime
glog
jsi
react_cxx_platform_react_nativemodule
Expand Down
Loading
Loading