Skip to content

Commit fa954b5

Browse files
javachemeta-codesync[bot]
authored andcommitted
Add portable C++ Blob and FileReader modules
Summary: Make the portable C++ Blob, FileReader, blob storage and networking response handler available under `ReactCxxPlatform/react/io`. Relocate the implementation and its existing tests into the public I/O build, add standard licence headers, and document registration and supported behaviour. The relocation does not change decoding, byte storage, collector binding, or module behaviour. Those improvements are already in the prerequisite. The modules retain UTF-8-only text decoding and unsupported WebSocket-blob operations. Changelog: [General][Added] - Make portable C++ Blob and FileReader modules available in ReactCxxPlatform Differential Revision: D132267695
1 parent 6f78f85 commit fa954b5

9 files changed

Lines changed: 911 additions & 0 deletions

File tree

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
#include "BlobModule.h"
9+
10+
#include <cmath>
11+
#include <limits>
12+
#include <utility>
13+
14+
namespace facebook::react {
15+
16+
namespace {
17+
18+
constexpr const char* kBlobCollectorProvider = "__blobCollectorProvider";
19+
20+
/// Lets JavaScript-held blobs free their bytes when garbage collected.
21+
/// BlobManager.createFromOptions attaches a collector to each Blob.
22+
class BlobCollector : public jsi::HostObject {
23+
public:
24+
BlobCollector(std::weak_ptr<BlobStore> store, std::string blobId)
25+
: store_(std::move(store)), blobId_(std::move(blobId)) {}
26+
27+
BlobCollector(const BlobCollector&) = delete;
28+
BlobCollector& operator=(const BlobCollector&) = delete;
29+
BlobCollector(BlobCollector&&) = delete;
30+
BlobCollector& operator=(BlobCollector&&) = delete;
31+
32+
~BlobCollector() override {
33+
if (auto store = store_.lock()) {
34+
store->remove(blobId_);
35+
}
36+
}
37+
38+
private:
39+
std::weak_ptr<BlobStore> store_;
40+
std::string blobId_;
41+
};
42+
43+
/// Converts a JavaScript offset/size to an index, rejecting values that are not
44+
/// non-negative integers representable as `std::size_t`.
45+
std::optional<std::size_t> toBlobIndex(const jsi::Value& value) {
46+
if (!value.isNumber()) {
47+
return std::nullopt;
48+
}
49+
const double number = value.getNumber();
50+
// `!(number >= 0)` also rejects NaN. The size_t maximum rounds up to a power
51+
// of two as a double, so `<` keeps the cast in range.
52+
if (!(number >= 0) ||
53+
number >= static_cast<double>(std::numeric_limits<std::size_t>::max()) ||
54+
std::trunc(number) != number) {
55+
return std::nullopt;
56+
}
57+
return static_cast<std::size_t>(number);
58+
}
59+
60+
} // namespace
61+
62+
std::optional<std::vector<uint8_t>> resolveBlobData(
63+
jsi::Runtime& rt,
64+
const jsi::Object& blobData,
65+
const BlobStore& store) {
66+
auto blobId = blobData.getProperty(rt, "blobId");
67+
auto offset = toBlobIndex(blobData.getProperty(rt, "offset"));
68+
auto size = toBlobIndex(blobData.getProperty(rt, "size"));
69+
if (!blobId.isString() || !offset || !size) {
70+
return std::nullopt;
71+
}
72+
return store.resolve(blobId.getString(rt).utf8(rt), *offset, *size);
73+
}
74+
75+
BlobModule::BlobModule(
76+
std::shared_ptr<CallInvoker> jsInvoker,
77+
std::shared_ptr<BlobStore> store)
78+
: NativeBlobModuleCxxSpec(std::move(jsInvoker)), store_(std::move(store)) {}
79+
80+
jsi::Object BlobModule::getConstants(jsi::Runtime& rt) {
81+
auto constants = jsi::Object(rt);
82+
constants.setProperty(
83+
rt, "BLOB_URI_SCHEME", jsi::String::createFromAscii(rt, "blob"));
84+
constants.setProperty(rt, "BLOB_URI_HOST", jsi::Value::null());
85+
return constants;
86+
}
87+
88+
void BlobModule::addNetworkingHandler(jsi::Runtime& /*rt*/) {}
89+
90+
void BlobModule::addWebSocketHandler(jsi::Runtime& rt, double /*id*/) {
91+
throw jsi::JSError(rt, "BlobModule: WebSocket blobs are not supported");
92+
}
93+
94+
void BlobModule::removeWebSocketHandler(jsi::Runtime& /*rt*/, double /*id*/) {}
95+
96+
void BlobModule::sendOverSocket(
97+
jsi::Runtime& rt,
98+
jsi::Object /*blob*/,
99+
double /*socketID*/) {
100+
throw jsi::JSError(rt, "BlobModule: WebSocket blobs are not supported");
101+
}
102+
103+
void BlobModule::createFromParts(
104+
jsi::Runtime& rt,
105+
jsi::Array parts,
106+
const std::string& withId) {
107+
std::vector<uint8_t> bytes;
108+
const auto count = parts.size(rt);
109+
for (size_t i = 0; i < count; ++i) {
110+
auto part = parts.getValueAtIndex(rt, i).asObject(rt);
111+
auto type = part.getProperty(rt, "type").asString(rt).utf8(rt);
112+
if (type == "string") {
113+
auto text = part.getProperty(rt, "data").asString(rt).utf8(rt);
114+
bytes.insert(bytes.end(), text.begin(), text.end());
115+
} else if (type == "blob") {
116+
auto data = resolveBlobData(
117+
rt, part.getProperty(rt, "data").asObject(rt), *store_);
118+
if (!data) {
119+
throw jsi::JSError(
120+
rt, "BlobModule: createFromParts references an invalid blob");
121+
}
122+
bytes.insert(bytes.end(), data->begin(), data->end());
123+
} else {
124+
throw jsi::JSError(rt, "BlobModule: invalid type for blob: " + type);
125+
}
126+
}
127+
store_->store(withId, std::move(bytes));
128+
}
129+
130+
void BlobModule::release(jsi::Runtime& /*rt*/, const std::string& blobId) {
131+
store_->remove(blobId);
132+
}
133+
134+
void BlobModule::installJSIBindingsWithRuntime(jsi::Runtime& rt) {
135+
auto global = rt.global();
136+
if (global.hasProperty(rt, kBlobCollectorProvider)) {
137+
return;
138+
}
139+
auto name = jsi::PropNameID::forAscii(rt, kBlobCollectorProvider);
140+
global.setProperty(
141+
rt,
142+
name,
143+
jsi::Function::createFromHostFunction(
144+
rt,
145+
name,
146+
1,
147+
[store = std::weak_ptr<BlobStore>(store_)](
148+
jsi::Runtime& rt,
149+
const jsi::Value& /*thisVal*/,
150+
const jsi::Value* args,
151+
size_t count) -> jsi::Value {
152+
if (count < 1 || !args->isString()) {
153+
throw jsi::JSError(
154+
rt, "__blobCollectorProvider expects a blob id");
155+
}
156+
return jsi::Object::createFromHostObject(
157+
rt,
158+
std::make_shared<BlobCollector>(
159+
store, args->getString(rt).utf8(rt)));
160+
}));
161+
}
162+
163+
BlobNetworkingResponseHandler::BlobNetworkingResponseHandler(
164+
std::shared_ptr<BlobStore> store)
165+
: store_(std::move(store)) {}
166+
167+
bool BlobNetworkingResponseHandler::supports(
168+
const std::string& responseType) const {
169+
return responseType == "blob";
170+
}
171+
172+
jsi::Value BlobNetworkingResponseHandler::toResponseData(
173+
jsi::Runtime& rt,
174+
std::vector<uint8_t> body) {
175+
const auto size = static_cast<double>(body.size());
176+
auto blobId = store_->store(std::move(body));
177+
auto blobData = jsi::Object(rt);
178+
blobData.setProperty(rt, "blobId", jsi::String::createFromUtf8(rt, blobId));
179+
blobData.setProperty(rt, "offset", 0);
180+
blobData.setProperty(rt, "size", size);
181+
return blobData;
182+
}
183+
184+
} // namespace facebook::react
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
#pragma once
9+
10+
#include <FBReactNativeSpec/FBReactNativeSpecJSI.h>
11+
#include <ReactCommon/TurboModuleWithJSIBindings.h>
12+
#include <jsi/jsi.h>
13+
#include <react/io/BlobStore.h>
14+
#include <react/io/NetworkingModule.h>
15+
#include <memory>
16+
#include <optional>
17+
#include <string>
18+
19+
namespace facebook::react {
20+
21+
/// Returns the bytes referenced by a JS `BlobData` object
22+
/// (`{blobId, offset, size}`), or `std::nullopt` if they are not stored.
23+
std::optional<std::vector<uint8_t>>
24+
resolveBlobData(facebook::jsi::Runtime &rt, const facebook::jsi::Object &blobData, const BlobStore &store);
25+
26+
/// C++ implementation of React Native's `BlobModule` TurboModule (see
27+
/// `Libraries/Blob/NativeBlobModule.js`). WebSocket blobs are not supported.
28+
class BlobModule : public NativeBlobModuleCxxSpec<BlobModule>, public TurboModuleWithJSIBindings {
29+
public:
30+
BlobModule(std::shared_ptr<CallInvoker> jsInvoker, std::shared_ptr<BlobStore> store);
31+
32+
facebook::jsi::Object getConstants(facebook::jsi::Runtime &rt);
33+
void addNetworkingHandler(facebook::jsi::Runtime &rt);
34+
[[noreturn]] void addWebSocketHandler(facebook::jsi::Runtime &rt, double id);
35+
void removeWebSocketHandler(facebook::jsi::Runtime &rt, double id);
36+
[[noreturn]] void sendOverSocket(facebook::jsi::Runtime &rt, facebook::jsi::Object blob, double socketID);
37+
void createFromParts(facebook::jsi::Runtime &rt, facebook::jsi::Array parts, const std::string &withId);
38+
void release(facebook::jsi::Runtime &rt, const std::string &blobId);
39+
40+
private:
41+
void installJSIBindingsWithRuntime(jsi::Runtime &rt) override;
42+
43+
std::shared_ptr<BlobStore> store_;
44+
};
45+
46+
/// Stores `Networking` response bodies requested with responseType "blob" and
47+
/// delivers them to JS as `BlobData`, as Android's `BlobModule` does.
48+
class BlobNetworkingResponseHandler : public INetworkingResponseHandler {
49+
public:
50+
explicit BlobNetworkingResponseHandler(std::shared_ptr<BlobStore> store);
51+
52+
[[nodiscard]] bool supports(const std::string &responseType) const override;
53+
facebook::jsi::Value toResponseData(facebook::jsi::Runtime &rt, std::vector<uint8_t> body) override;
54+
55+
private:
56+
std::shared_ptr<BlobStore> store_;
57+
};
58+
59+
} // namespace facebook::react
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
#include "BlobStore.h"
9+
10+
#include <utility>
11+
12+
namespace facebook::react {
13+
14+
std::string BlobStore::store(std::vector<uint8_t> bytes) {
15+
std::lock_guard<std::mutex> lock(mutex_);
16+
// JavaScript blob identifiers are UUIDs; this generated prefix is distinct.
17+
auto blobId = "native-blob-" + std::to_string(nextId_++);
18+
blobs_.insert_or_assign(blobId, std::move(bytes));
19+
return blobId;
20+
}
21+
22+
void BlobStore::store(const std::string& blobId, std::vector<uint8_t> bytes) {
23+
std::lock_guard<std::mutex> lock(mutex_);
24+
blobs_.insert_or_assign(blobId, std::move(bytes));
25+
}
26+
27+
std::optional<std::vector<uint8_t>> BlobStore::resolve(
28+
const std::string& blobId,
29+
std::size_t offset,
30+
std::size_t size) const {
31+
std::lock_guard<std::mutex> lock(mutex_);
32+
auto it = blobs_.find(blobId);
33+
if (it == blobs_.end()) {
34+
return std::nullopt;
35+
}
36+
const auto& bytes = it->second;
37+
if (offset > bytes.size() || size > bytes.size() - offset) {
38+
return std::nullopt;
39+
}
40+
auto first = bytes.begin() +
41+
static_cast<std::vector<uint8_t>::difference_type>(offset);
42+
return std::vector<uint8_t>(
43+
first, first + static_cast<std::vector<uint8_t>::difference_type>(size));
44+
}
45+
46+
void BlobStore::remove(const std::string& blobId) {
47+
std::lock_guard<std::mutex> lock(mutex_);
48+
blobs_.erase(blobId);
49+
}
50+
51+
} // namespace facebook::react
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
#pragma once
9+
10+
#include <cstddef>
11+
#include <cstdint>
12+
#include <mutex>
13+
#include <optional>
14+
#include <string>
15+
#include <unordered_map>
16+
#include <vector>
17+
18+
namespace facebook::react {
19+
20+
/// Thread-safe byte storage shared by BlobModule, FileReaderModule and
21+
/// blob-aware Networking. Contents are undecoded byte vectors.
22+
class BlobStore {
23+
public:
24+
/// Stores `bytes` under a newly generated id and returns that id.
25+
std::string store(std::vector<uint8_t> bytes);
26+
void store(const std::string &blobId, std::vector<uint8_t> bytes);
27+
28+
/// Returns `size` bytes starting at `offset`, or `std::nullopt` when the id
29+
/// is unknown or the range is out of bounds.
30+
std::optional<std::vector<uint8_t>> resolve(const std::string &blobId, std::size_t offset, std::size_t size) const;
31+
32+
void remove(const std::string &blobId);
33+
34+
private:
35+
mutable std::mutex mutex_;
36+
std::unordered_map<std::string, std::vector<uint8_t>> blobs_;
37+
uint64_t nextId_{0};
38+
};
39+
40+
} // namespace facebook::react

‎packages/react-native/ReactCxxPlatform/react/io/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ add_library(react_cxx_platform_react_io OBJECT ${react_cxx_platform_react_io_SRC
1414
target_include_directories(react_cxx_platform_react_io PUBLIC ${REACT_CXX_PLATFORM_DIR})
1515

1616
target_link_libraries(react_cxx_platform_react_io
17+
folly_runtime
1718
glog
1819
jsi
1920
react_cxx_platform_react_nativemodule

0 commit comments

Comments
 (0)