diff --git a/AGENTS.md b/AGENTS.md index fde9ed31..c069e598 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,7 +76,7 @@ All `RoomDelegate` callbacks and stream handler callbacks (e.g., `registerTextSt | `VideoSource::captureFrame` | No | Not safe to call concurrently from multiple threads. | | `LocalAudioTrack` / `LocalVideoTrack` | No | Thin `sendRequest` wrappers with no internal synchronization. | | `LocalDataTrack::tryPush` | No | Thin `sendRequest` wrapper with no internal synchronization. | -| `TextStreamReader` / `ByteStreamReader` | Yes | Fed on the FFI callback thread, read on a user thread (internal `std::mutex` + `condition_variable`). End-of-stream attributes are merged into `info()` on the reading thread, so don't call `info()` concurrently with `readNext()`. | +| `TextStreamReader` / `ByteStreamReader` | Yes | Fed on the FFI callback thread, read on a user thread (internal `std::mutex` + `condition_variable`). End-of-stream attributes are merged into `info()` on the reading thread, so don't call `info()` concurrently with `readNext()`. A byte stream is consumed once: the first `readNext()` / `readAll()` starts reading, or `writeToFile()` (never on the FFI callback thread) hands it to the SDK core; `Room` holds byte readers weakly, so an unconsumed reader that is dropped releases its stream. | | `LocalParticipant::sendText` / `sendBytes` / `sendFile` | Yes | Independent async FFI requests; each call blocks its caller until its own callback arrives. They throw `DataStreamError` once the room has disconnected rather than reaching the FFI. | | `TextStreamWriter` / `ByteStreamWriter` | Serialized | `write()` is serialized by an internal `write_mutex_`. | diff --git a/README.md b/README.md index 4bf10eb8..807b79fc 100644 --- a/README.md +++ b/README.md @@ -227,8 +227,9 @@ token source helpers for endpoint, development token server, and custom backends - Receive remote audio/video tracks - Publish local audio/video tracks - Data tracks (low-level) and data streams (high-level): one-shot `sendText` / - `sendBytes` / `sendFile` with compression, incremental writers, and - per-topic stream handlers + `sendBytes` / `sendFile` with compression, incremental writers, per-topic + stream handlers, and writing received byte streams straight to a file + (`ByteStreamReader::writeToFile`) - RPC between participants - End-to-end encryption (E2EE) - Hardware-accelerated codecs (via the underlying Rust SDK) diff --git a/include/livekit/data_stream.h b/include/livekit/data_stream.h index 35fa39d4..238f58b1 100644 --- a/include/livekit/data_stream.h +++ b/include/livekit/data_stream.h @@ -45,7 +45,7 @@ constexpr std::size_t kStreamChunkSize = 15'000; // 15 KB /// LocalParticipant::sendText()) when the send fails or the participant is no /// longer connected, and by TextStreamReader / ByteStreamReader when an /// incoming stream ends abnormally (for example the sender closed it with a -/// reason, the stream exceeded the receive size limit, or the room +/// reason, the stream exceeded RoomOptions::data_stream limits, or the room /// disconnected mid-stream). The message carries the SDK's error description. /// /// Derives from std::runtime_error, so existing @@ -282,6 +282,11 @@ class LIVEKIT_API TextStreamReader { /// with a handler registered via Room::registerByteStreamHandler(). The SDK /// decompresses and reassembles the stream. /// +/// A stream is consumed once, either by reading it (readNext() / readAll()) +/// or by having the SDK write it to disk (writeToFile()). The SDK holds the +/// incoming data until one of them is called; dropping every reference to an +/// unconsumed reader discards the stream. +/// /// Reading blocks the calling thread. Stream handlers run on the SDK's event /// thread, which also delivers the chunks, so never read from inside the /// handler: move the reader to another thread first. @@ -312,6 +317,28 @@ class LIVEKIT_API ByteStreamReader { /// before the error are returned first. bool readNext(std::vector& out); + /// @brief Write the whole stream to a file instead of reading it. + /// + /// Blocks until the stream has been written, so call it from your own + /// thread, not from the stream handler. Call it instead of readNext() / + /// readAll(): a stream can only be consumed once. Afterwards readNext() + /// reports the end of the stream. + /// + /// The file is named after the stream (info().name) unless + /// @p name_override is given. Either must be a plain file name: names with + /// path separators, "..", or an absolute path are rejected, so a sender + /// can't choose where the file goes. An existing file is overwritten. + /// + /// @param directory Directory to write into; the system temporary + /// directory when unset. + /// @param name_override File name to use instead of the stream's name. + /// @return Path of the written file. + /// @throws DataStreamError if the stream was already read or closed, the + /// file name is not a plain file name, the file can't be written, + /// or the stream ended abnormally. + std::string writeToFile(const std::optional& directory = std::nullopt, + const std::optional& name_override = std::nullopt); + /// @brief Read the entire stream into a single buffer. /// /// Blocks until the stream ends. @@ -348,6 +375,14 @@ class LIVEKIT_API ByteStreamReader { /// ended abnormally. void onStreamEnded(const std::map& attributes, std::optional error); + /// Called by the Room with the stream's owned FFI reader handle. The reader + /// consumes it on the first readNext() / readAll() / writeToFile(), and + /// drops it if it is closed or destroyed first. + void attachUnreadHandle(std::uint64_t handle); + + /// Starts incremental reading if the stream has not been consumed yet. + void startReading(); + ByteStreamInfo info_; std::unique_ptr impl_; }; diff --git a/include/livekit/room.h b/include/livekit/room.h index adf0d223..8e7a1a2b 100644 --- a/include/livekit/room.h +++ b/include/livekit/room.h @@ -73,6 +73,15 @@ struct RtcConfig { std::vector ice_servers; }; +/// @brief Data stream settings applied when connecting. +struct DataStreamOptions { + /// Maximum number of (decompressed) bytes accepted per incoming data stream. + /// A stream that exceeds it ends with a DataStreamError on the reader. + /// + /// If unset, the SDK default (5 GB) is used. + std::optional max_payload_byte_length; +}; + /// Top-level room connection options. struct RoomOptions { /// If true (default), automatically subscribe to all remote tracks. @@ -127,6 +136,9 @@ struct RoomOptions { /// If unset, the Rust SDK default is used. std::optional connect_timeout; + /// Data stream settings, such as the incoming stream size limit. + DataStreamOptions data_stream; + /// @cond /// Additional LiveKit SDKs layered on top of this one, reported to the server /// as part of the client info. @@ -369,7 +381,10 @@ class LIVEKIT_API Room { // Active incoming stream readers, keyed by FFI reader handle id. A reader is // removed when its end-of-stream event arrives or the room shuts down. using TextStreamReaderMap = std::unordered_map>; - using ByteStreamReaderMap = std::unordered_map>; + // Byte readers are held weakly: a byte stream is consumed lazily (read or + // written to a file), so a reader nobody keeps must be free to go away and + // release its stream. + using ByteStreamReaderMap = std::unordered_map>; TextStreamReaderMap text_stream_readers_; ByteStreamReaderMap byte_stream_readers_; // The E2EE manager is owned by the room and is not shared with other objects. diff --git a/src/data_stream.cpp b/src/data_stream.cpp index 0d88da8e..4d43a105 100644 --- a/src/data_stream.cpp +++ b/src/data_stream.cpp @@ -20,9 +20,12 @@ #include #include #include +#include #include +#include #include #include +#include #include "ffi_client.h" #include "livekit/local_participant.h" @@ -203,7 +206,26 @@ class ReaderState { } // namespace struct TextStreamReader::Impl : ReaderState {}; -struct ByteStreamReader::Impl : ReaderState> {}; +struct ByteStreamReader::Impl : ReaderState> { + enum class Consumer { kNone, kReader, kFile, kDiscarded }; + + /// Guards the one-time choice of how the stream is consumed. + std::mutex consume_mutex; + /// Owned FFI reader handle, until something consumes or drops it. + std::uint64_t unread_handle = 0; + Consumer consumer = Consumer::kNone; + + /// Claims the stream for @p who. Returns the unread handle (0 if there is + /// none) when the stream was unclaimed; std::nullopt if already claimed. + std::optional claim(Consumer who) { + const std::scoped_lock lock(consume_mutex); + if (consumer != Consumer::kNone) { + return std::nullopt; + } + consumer = who; + return std::exchange(unread_handle, 0); + } +}; TextStreamReader::TextStreamReader(TextStreamInfo info) : info_(std::move(info)), impl_(std::make_unique()) {} @@ -231,7 +253,31 @@ void TextStreamReader::close() { impl_->close(); } ByteStreamReader::ByteStreamReader(ByteStreamInfo info) : info_(std::move(info)), impl_(std::make_unique()) {} -ByteStreamReader::~ByteStreamReader() = default; +ByteStreamReader::~ByteStreamReader() { + // Nobody consumed the stream: release it so the SDK core stops buffering. + if (const auto handle = impl_->claim(Impl::Consumer::kDiscarded); handle && *handle != 0) { + (void)dropFfiHandle(*handle); + } +} + +void ByteStreamReader::attachUnreadHandle(std::uint64_t handle) { + const std::scoped_lock lock(impl_->consume_mutex); + impl_->unread_handle = handle; +} + +void ByteStreamReader::startReading() { + const auto handle = impl_->claim(Impl::Consumer::kReader); + if (!handle || *handle == 0) { + return; + } + try { + // Consumes the handle; chunks then arrive through the Room. + FfiClient::instance().byteStreamReadIncremental(*handle); + } catch (const std::exception& e) { + (void)dropFfiHandle(*handle); + impl_->end({}, std::string(e.what())); + } +} void ByteStreamReader::onChunkReceived(std::vector bytes) { impl_->push(std::move(bytes)); } @@ -240,7 +286,10 @@ void ByteStreamReader::onStreamEnded(const std::map& a impl_->end(attributes, std::move(error)); } -bool ByteStreamReader::readNext(std::vector& out) { return impl_->next(out, info_, "ByteStreamReader"); } +bool ByteStreamReader::readNext(std::vector& out) { + startReading(); + return impl_->next(out, info_, "ByteStreamReader"); +} std::vector ByteStreamReader::readAll() { std::vector result; @@ -251,7 +300,47 @@ std::vector ByteStreamReader::readAll() { return result; } -void ByteStreamReader::close() { impl_->close(); } +std::string ByteStreamReader::writeToFile(const std::optional& directory, + const std::optional& name_override) { + if (isOnFfiCallbackThread()) { + // The result arrives on this same thread, so waiting here would deadlock. + throw DataStreamError("ByteStreamReader::writeToFile cannot be called on the SDK event thread"); + } + const auto handle = impl_->claim(Impl::Consumer::kFile); + if (!handle) { + throw DataStreamError("ByteStreamReader::writeToFile: the stream was already read or closed"); + } + if (*handle == 0) { + throw DataStreamError("ByteStreamReader::writeToFile: the stream is not available"); + } + + try { + std::future written; + try { + written = FfiClient::instance().byteStreamWriteToFileAsync(*handle, directory, name_override); + } catch (...) { + // The request never reached the SDK core, so the handle is still ours. + (void)dropFfiHandle(*handle); + throw; + } + std::string path = written.get(); + impl_->end({}, std::nullopt); + return path; + } catch (const DataStreamError& e) { + impl_->end({}, std::string(e.what())); + throw; + } catch (const std::exception& e) { + impl_->end({}, std::string(e.what())); + throw DataStreamError(e.what()); + } +} + +void ByteStreamReader::close() { + if (const auto handle = impl_->claim(Impl::Consumer::kDiscarded); handle && *handle != 0) { + (void)dropFfiHandle(*handle); + } + impl_->close(); +} // ===================================================================== // Writer implementation (uses your future-based FfiClient) diff --git a/src/ffi_client.cpp b/src/ffi_client.cpp index ccb70300..433b71fe 100644 --- a/src/ffi_client.cpp +++ b/src/ffi_client.cpp @@ -1265,6 +1265,53 @@ void FfiClient::byteStreamReadIncremental(std::uint64_t reader_handle) { } } +std::future FfiClient::byteStreamWriteToFileAsync(std::uint64_t reader_handle, + const std::optional& directory, + const std::optional& name_override) { + const AsyncId async_id = generateAsyncId(); + + auto fut = registerAsync( + async_id, + [async_id](const proto::FfiEvent& e) { + return e.has_byte_stream_reader_write_to_file() && e.byte_stream_reader_write_to_file().async_id() == async_id; + }, + [](const proto::FfiEvent& e, std::promise& pr) { + const auto& cb = e.byte_stream_reader_write_to_file(); + if (cb.has_error()) { + pr.set_exception(std::make_exception_ptr(DataStreamError(cb.error().description()))); + return; + } + if (!cb.has_file_path()) { + pr.set_exception(std::make_exception_ptr(DataStreamError("write_to_file callback missing file_path"))); + return; + } + pr.set_value(cb.file_path()); + }); + + proto::FfiRequest req; + auto* msg = req.mutable_byte_write_to_file(); + msg->set_reader_handle(reader_handle); + msg->set_request_async_id(async_id); + if (directory) { + msg->set_directory(*directory); + } + if (name_override) { + msg->set_name_override(*name_override); + } + + try { + const proto::FfiResponse resp = sendRequest(req); + if (!resp.has_byte_write_to_file()) { + logAndThrow("FfiResponse missing byte_write_to_file"); + } + } catch (...) { + cancelPendingByAsyncId(async_id); + throw; + } + + return fut; +} + std::future FfiClient::sendStreamHeaderAsync(std::uint64_t local_participant_handle, const proto::DataStream::Header& header, const std::vector& destination_identities, diff --git a/src/ffi_client.h b/src/ffi_client.h index 1359f891..6e437e0f 100644 --- a/src/ffi_client.h +++ b/src/ffi_client.h @@ -176,6 +176,13 @@ class LIVEKIT_INTERNAL_API FfiClient { void textStreamReadIncremental(std::uint64_t reader_handle); void byteStreamReadIncremental(std::uint64_t reader_handle); + // Write an owned byte reader handle's stream to a file (the SDK core + // validates the file name). Consumes the handle. Resolves to the written + // file's path. + std::future byteStreamWriteToFileAsync(std::uint64_t reader_handle, + const std::optional& directory, + const std::optional& name_override); + // Low-level data stream functionalities (legacy v1 framing) std::future sendStreamHeaderAsync(std::uint64_t local_participant_handle, const proto::DataStream::Header& header, diff --git a/src/room.cpp b/src/room.cpp index 28e69ef7..85aa2af1 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -1426,7 +1426,9 @@ void Room::endStreamReaders(const TextStreamReaderMap& text_readers, const ByteS kv.second->onStreamEnded({}, std::string(kDisconnectedWhileReceiving)); } for (const auto& kv : byte_readers) { - kv.second->onStreamEnded({}, std::string(kDisconnectedWhileReceiving)); + if (const auto reader = kv.second.lock()) { + reader->onStreamEnded({}, std::string(kDisconnectedWhileReceiving)); + } } } @@ -1464,11 +1466,14 @@ bool Room::dispatchStreamReaderEvent(const FfiEvent& event) { if (it == byte_stream_readers_.end()) { return true; } - reader = it->second; + reader = it->second.lock(); if (ev.has_eos()) { byte_stream_readers_.erase(it); } } + if (!reader) { + return true; // The application dropped the reader; discard its data. + } if (ev.has_chunk_received()) { const std::string& content = ev.chunk_received().content(); reader->onChunkReceived(std::vector(content.begin(), content.end())); @@ -1545,7 +1550,14 @@ void Room::onByteStreamOpened(const proto::ByteStreamOpened& opened, RoomDelegat if (room_handle_ && it != byte_stream_handlers_.end()) { handler = it->second; reader = std::make_shared(fromProto(owned.info())); - // Register before read_incremental so no chunk can arrive unrouted. + // Reading starts lazily: the reader consumes the handle on its first + // readNext() / readAll() / writeToFile(), or drops it if discarded. + reader->attachUnreadHandle(reader_handle); + // Forget readers the application dropped without consuming; no events + // will ever arrive for them. + for (auto r = byte_stream_readers_.begin(); r != byte_stream_readers_.end();) { + r = r->second.expired() ? byte_stream_readers_.erase(r) : std::next(r); + } byte_stream_readers_[reader_handle] = reader; } } @@ -1555,18 +1567,6 @@ void Room::onByteStreamOpened(const proto::ByteStreamOpened& opened, RoomDelegat const FfiHandle unread(static_cast(reader_handle)); LK_LOG_DEBUG("No byte stream handler for topic '{}'; ignoring stream {}", owned.info().topic(), owned.info().stream_id()); - } else { - try { - FfiClient::instance().byteStreamReadIncremental(reader_handle); - } catch (const std::exception& e) { - LK_LOG_ERROR("Failed to start reading byte stream {}: {}", owned.info().stream_id(), e.what()); - { - const std::scoped_lock guard(lock_); - byte_stream_readers_.erase(reader_handle); - } - const FfiHandle unread(static_cast(reader_handle)); - reader->onStreamEnded({}, std::string(e.what())); - } } if (reader) { diff --git a/src/room_proto_converter.cpp b/src/room_proto_converter.cpp index ea1b642d..b72710fe 100644 --- a/src/room_proto_converter.cpp +++ b/src/room_proto_converter.cpp @@ -472,6 +472,9 @@ proto::RoomOptions toProto(const RoomOptions& in) { if (in.other_sdks) { out.set_other_sdks(*in.other_sdks); } + if (in.data_stream.max_payload_byte_length) { + out.mutable_data_stream()->set_max_payload_byte_length(*in.data_stream.max_payload_byte_length); + } return out; } diff --git a/src/tests/integration/test_data_stream_conformance_receive_api.cpp b/src/tests/integration/test_data_stream_conformance_receive_api.cpp index 4ba7417d..9677f78f 100644 --- a/src/tests/integration/test_data_stream_conformance_receive_api.cpp +++ b/src/tests/integration/test_data_stream_conformance_receive_api.cpp @@ -15,13 +15,12 @@ */ // Receive-side data stream conformance for behavior controlled through the -// C++ receive API: closing a reader early (TextStreamReader::close / -// ByteStreamReader::close). +// C++ receive API: the per-stream payload cap (RoomOptions::data_stream) and +// closing a reader early (TextStreamReader::close / ByteStreamReader::close). // // Ported from the incoming-manager tests of the Rust `livekit-data-stream` // crate (client-sdk-rust/livekit-data-stream/src/incoming/manager.rs); the // remote side is an FfiPeer, as in the other receive-side conformance tests. -// // Run with: // ./build-debug/bin/livekit_integration_tests --gtest_filter=DataStreamReceiveApi* @@ -37,6 +36,122 @@ namespace livekit::test::ds { +namespace { + +constexpr std::uint64_t kPayloadCap = 1'000; +constexpr char kPayloadTooLarge[] = "stream payload exceeds maximum size"; + +} // namespace + +/// The receiver (room B) caps incoming streams at kPayloadCap bytes. +class DataStreamReceiveApiCapTest : public DataStreamConformanceTest { +protected: + void SetUp() override { + LiveKitTestBase::SetUp(); + skipIfNotConfigured(); + if (IsSkipped()) { + return; + } + std::vector configs(2); + configs[1].room_options.data_stream.max_payload_byte_length = kPayloadCap; + rooms_ = testRooms(configs); + } + + /// Sends `payload` with an FfiPeer stream writer in `chunk`-byte writes, + /// optionally declaring `total_length`, and returns the received stream. + ReceivedStream sendWithWriter(const std::string& payload, std::size_t chunk, + std::optional total_length) { + const auto topic = uniqueTopic("cap_writer"); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + PeerByteOptions opts; + opts.topic = topic; + opts.name = "capped.bin"; + opts.total_length = total_length; + const auto writer = peer.openBytes(opts); + EXPECT_TRUE(writer.ok) << writer.error; + for (std::size_t off = 0; off < payload.size(); off += chunk) { + (void)peer.writeBytes(writer.writer_handle, payload.substr(off, chunk)); + } + (void)peer.closeBytes(writer.writer_handle); + EXPECT_TRUE(collector.waitFor(1)) << "stream never ended"; + return collector.streams().empty() ? ReceivedStream{} : collector.streams().front(); + } +}; + +// Rust: v1_max_payload_size_breached_with_unknown_total +TEST_F(DataStreamReceiveApiCapTest, BreachedWithUnknownTotal) { + const auto s = sendWithWriter(std::string(1'200, '\0'), 400, std::nullopt); + EXPECT_TRUE(s.errored) << "a stream that grows past the cap must fail"; + EXPECT_NE(s.error.find(kPayloadTooLarge), std::string::npos) << s.error; +} + +// Rust: v1_max_payload_size_fast_fails_on_declared_total +TEST_F(DataStreamReceiveApiCapTest, FastFailsOnDeclaredTotal) { + const auto s = sendWithWriter(std::string(10, '\0'), 10, 2'000); + EXPECT_TRUE(s.errored) << "a stream that declares more than the cap must fail"; + EXPECT_NE(s.error.find(kPayloadTooLarge), std::string::npos) << s.error; + EXPECT_TRUE(s.content.empty()) << "no data is delivered for a stream rejected by its header"; +} + +// Rust: v1_payload_exactly_at_max_payload_size_succeeds +TEST_F(DataStreamReceiveApiCapTest, PayloadExactlyAtCapSucceeds) { + const std::string payload(kPayloadCap, '\x07'); + const auto s = sendWithWriter(payload, 400, kPayloadCap); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, payload); +} + +// Rust: v2_inline_uncompressed_max_payload_size_breached +TEST_F(DataStreamReceiveApiCapTest, InlineUncompressedBreached) { + const auto topic = uniqueTopic("cap_inline"); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + PeerByteOptions opts; + opts.topic = topic; + ASSERT_TRUE(peer.sendBytes(randomBytes(2'000), opts).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_TRUE(s.errored); + EXPECT_NE(s.error.find(kPayloadTooLarge), std::string::npos) << s.error; +} + +// Rust: v2_inline_compressed_max_payload_size_breached. The compressed inline +// packet is tiny, but it decompresses far past the cap. +TEST_F(DataStreamReceiveApiCapTest, InlineCompressedBreached) { + const auto topic = uniqueTopic("cap_inline_z"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + PeerTextOptions opts; + opts.topic = topic; + ASSERT_TRUE(peer.sendText(compressibleText(220'000), opts).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_TRUE(s.errored); + EXPECT_NE(s.error.find(kPayloadTooLarge), std::string::npos) << s.error; +} + +// Rust: v2_max_payload_size_breached +TEST_F(DataStreamReceiveApiCapTest, CompressedMultipacketBreached) { + const auto topic = uniqueTopic("cap_multi_z"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + PeerTextOptions opts; + opts.topic = topic; + ASSERT_TRUE(peer.sendText(randomText(60'000), opts).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_TRUE(s.errored); + EXPECT_NE(s.error.find(kPayloadTooLarge), std::string::npos) << s.error; +} + // --------------------------------------------------------------------------- // Closing a reader early // --------------------------------------------------------------------------- diff --git a/src/tests/integration/test_data_stream_conformance_write_to_file.cpp b/src/tests/integration/test_data_stream_conformance_write_to_file.cpp new file mode 100644 index 00000000..913fcaaa --- /dev/null +++ b/src/tests/integration/test_data_stream_conformance_write_to_file.cpp @@ -0,0 +1,323 @@ +/* + * Copyright 2026 LiveKit + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// ByteStreamReader::writeToFile, end to end. Ports the write_to_file tests of +// the Rust `livekit-data-stream` crate +// (client-sdk-rust/livekit-data-stream/src/incoming/stream_reader.rs): the +// file name comes from the sender, so it must be a plain file name. Also +// covers the one-consumer rule (read or write to a file, not both) and +// readers that are dropped without being consumed. +// +// Run with: +// ./build-debug/bin/livekit_integration_tests --gtest_filter=DataStreamWriteToFile* + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../common/data_stream_test_utils.h" + +namespace livekit::test::ds { + +namespace { + +constexpr char kInvalidFileName[] = "file name must be a plain file name"; + +/// Captures byte readers as they open, without consuming them. +class ByteReaderCapture { +public: + ByteReaderCapture() = default; + ByteReaderCapture(const ByteReaderCapture&) = delete; + ByteReaderCapture& operator=(const ByteReaderCapture&) = delete; + ByteReaderCapture(ByteReaderCapture&&) = delete; + ByteReaderCapture& operator=(ByteReaderCapture&&) = delete; + ~ByteReaderCapture() { + const std::scoped_lock lock(mutex_); + for (auto& r : readers_) { + r->close(); + } + } + + void registerOn(Room& room, const std::string& topic) { + room.registerByteStreamHandler(topic, [this](std::shared_ptr reader, const std::string&) { + { + const std::scoped_lock lock(mutex_); + readers_.push_back(std::move(reader)); + } + cv_.notify_all(); + }); + } + + std::shared_ptr waitForReader(std::size_t index = 0) { + std::unique_lock lock(mutex_); + if (!cv_.wait_for(lock, kStreamTimeout, [&] { return readers_.size() > index; })) { + return nullptr; + } + return readers_[index]; + } + +private: + std::mutex mutex_; + std::condition_variable cv_; + std::vector> readers_; +}; + +/// A fresh, empty directory, removed on destruction. +class TempDir { +public: + TempDir() : path_(std::filesystem::temp_directory_path() / uniqueStreamId("ds_conf_dir")) { + std::filesystem::create_directories(path_); + } + ~TempDir() { + std::error_code ec; + std::filesystem::remove_all(path_, ec); + } + TempDir(const TempDir&) = delete; + TempDir& operator=(const TempDir&) = delete; + TempDir(TempDir&&) = delete; + TempDir& operator=(TempDir&&) = delete; + + const std::filesystem::path& path() const { return path_; } + std::string str() const { return path_.string(); } + bool empty() const { return std::filesystem::is_empty(path_); } + +private: + std::filesystem::path path_; +}; + +std::string readFile(const std::string& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +} // namespace + +class DataStreamWriteToFileTest : public DataStreamConformanceTest { +protected: + /// Sends `content` from the peer as a one-shot byte stream named `name` + /// (unset: the writer default, an empty name) and returns its reader. + std::shared_ptr receive(ByteReaderCapture& capture, const std::optional& name, + const std::string& content = "hello") { + const auto topic = uniqueTopic("to_file"); + capture.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + if (name) { + PeerByteOptions opts; + opts.topic = topic; + opts.name = *name; + EXPECT_TRUE(peer.sendBytes(content, opts).ok); + } else { + // Stream writers default to an empty name. + PeerByteOptions opts; + opts.topic = topic; + const auto writer = peer.openBytes(opts); + EXPECT_TRUE(writer.ok) << writer.error; + (void)peer.writeBytes(writer.writer_handle, content); + (void)peer.closeBytes(writer.writer_handle); + } + return capture.waitForReader(); + } + + /// Expects writeToFile to reject the stream's name and write nothing. + void expectRejected(const std::shared_ptr& reader, const TempDir& dir, + const std::optional& name_override = std::nullopt) { + ASSERT_NE(reader, nullptr); + try { + const auto path = reader->writeToFile(dir.str(), name_override); + FAIL() << "unsafe file name accepted; wrote " << path; + } catch (const DataStreamError& e) { + EXPECT_NE(std::string(e.what()).find(kInvalidFileName), std::string::npos) << e.what(); + } + EXPECT_TRUE(dir.empty()) << "nothing may be written for a rejected name"; + EXPECT_FALSE(std::filesystem::exists(dir.path().parent_path() / "evil.txt")); + } +}; + +// Rust: write_to_file_accepts_plain_name +TEST_F(DataStreamWriteToFileTest, AcceptsPlainName) { + TempDir dir; + ByteReaderCapture capture; + auto reader = receive(capture, "file.txt"); + ASSERT_NE(reader, nullptr); + + const auto path = reader->writeToFile(dir.str()); + + EXPECT_EQ(std::filesystem::path(path), dir.path() / "file.txt"); + EXPECT_EQ(readFile(path), "hello"); + std::vector chunk; + EXPECT_FALSE(reader->readNext(chunk)) << "a stream written to a file has nothing left to read"; +} + +// Rust: write_to_file_rejects_traversal_in_stream_name +TEST_F(DataStreamWriteToFileTest, RejectsTraversalInStreamName) { + TempDir dir; + ByteReaderCapture capture; + expectRejected(receive(capture, "../evil.txt"), dir); +} + +// Rust: write_to_file_rejects_traversal_in_name_override +TEST_F(DataStreamWriteToFileTest, RejectsTraversalInNameOverride) { + TempDir dir; + ByteReaderCapture capture; + expectRejected(receive(capture, "safe.txt"), dir, "../evil.txt"); +} + +// Rust: write_to_file_rejects_absolute_path_in_stream_name +TEST_F(DataStreamWriteToFileTest, RejectsAbsolutePathInStreamName) { + TempDir dir; + ByteReaderCapture capture; + const auto absolute = (dir.path().parent_path() / "evil.txt").string(); + expectRejected(receive(capture, absolute), dir); +} + +// Rust: write_to_file_rejects_nested_path_in_stream_name +TEST_F(DataStreamWriteToFileTest, RejectsNestedPathInStreamName) { + TempDir dir; + ByteReaderCapture capture; + expectRejected(receive(capture, "nested/evil.txt"), dir); +} + +// Rust: write_to_file_rejects_empty_stream_name +TEST_F(DataStreamWriteToFileTest, RejectsEmptyStreamName) { + TempDir dir; + ByteReaderCapture capture; + expectRejected(receive(capture, std::nullopt), dir); +} + +TEST_F(DataStreamWriteToFileTest, NameOverrideIsUsed) { + TempDir dir; + ByteReaderCapture capture; + auto reader = receive(capture, "original.txt"); + ASSERT_NE(reader, nullptr); + + const auto path = reader->writeToFile(dir.str(), "renamed.bin"); + + EXPECT_EQ(std::filesystem::path(path), dir.path() / "renamed.bin"); + EXPECT_EQ(readFile(path), "hello"); +} + +TEST_F(DataStreamWriteToFileTest, DefaultsToTheTempDirectory) { + ByteReaderCapture capture; + const auto name = uniqueStreamId("default_dir") + ".txt"; + auto reader = receive(capture, name); + ASSERT_NE(reader, nullptr); + + const auto path = reader->writeToFile(); + + EXPECT_EQ(std::filesystem::path(path).filename(), name); + EXPECT_EQ(readFile(path), "hello"); + std::error_code ec; + std::filesystem::remove(path, ec); +} + +// A file sent with C++ sendFile (compressed, multi-packet) lands intact. +TEST_F(DataStreamWriteToFileTest, WritesACompressedMultipacketFile) { + TempDir dir; + ByteReaderCapture capture; + const auto topic = uniqueTopic("to_file_large"); + capture.registerOn(receiverRoom(), topic); + const auto content = randomText(60'000); + const auto source = dir.path() / "source.txt"; + { + std::ofstream out(source, std::ios::binary); + out << content; + } + StreamByteOptions opts; + opts.topic = topic; + opts.name = "received.txt"; + (void)lockLocalParticipant(senderRoom())->sendFile(source.string(), opts); + + auto reader = capture.waitForReader(); + ASSERT_NE(reader, nullptr); + const auto path = reader->writeToFile(dir.str()); + EXPECT_EQ(readFile(path), content); +} + +TEST_F(DataStreamWriteToFileTest, CannotWriteAfterReading) { + ByteReaderCapture capture; + auto reader = receive(capture, "file.txt"); + ASSERT_NE(reader, nullptr); + EXPECT_EQ(fromBytes(reader->readAll()), "hello"); + EXPECT_THROW((void)reader->writeToFile(), DataStreamError) << "a stream can only be consumed once"; +} + +TEST_F(DataStreamWriteToFileTest, CannotWriteFromTheStreamHandler) { + const auto topic = uniqueTopic("to_file_handler"); + std::mutex mutex; + std::condition_variable cv; + std::optional error; + receiverRoom().registerByteStreamHandler(topic, [&](std::shared_ptr reader, const std::string&) { + std::string message; + try { + (void)reader->writeToFile(); + message = "no error"; + } catch (const DataStreamError& e) { + message = e.what(); + } + const std::scoped_lock lock(mutex); + error = message; + cv.notify_all(); + }); + FfiPeer peer(senderRoom()); + PeerByteOptions opts; + opts.topic = topic; + opts.name = "file.txt"; + ASSERT_TRUE(peer.sendBytes("hello", opts).ok); + + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, kStreamTimeout, [&] { return error.has_value(); })); + EXPECT_NE(error->find("SDK event thread"), std::string::npos) + << "writeToFile on the event thread would deadlock and must throw: " << *error; + lock.unlock(); + receiverRoom().unregisterByteStreamHandler(topic); +} + +// A handler that ignores its reader releases the stream; later streams on the +// topic are unaffected. +TEST_F(DataStreamWriteToFileTest, IgnoredReaderDoesNotBlockLaterStreams) { + const auto topic = uniqueTopic("ignored_reader"); + std::atomic opened{0}; + receiverRoom().registerByteStreamHandler(topic, [&](std::shared_ptr, const std::string&) { + ++opened; // Drop the reader without consuming it. + }); + FfiPeer peer(senderRoom()); + PeerByteOptions opts; + opts.topic = topic; + for (int i = 0; i < 3; ++i) { + ASSERT_TRUE(peer.sendBytes(randomText(40'000, static_cast(i) + 1), opts).ok); + } + const auto deadline = std::chrono::steady_clock::now() + kStreamTimeout; + while (opened < 3 && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(20ms); + } + EXPECT_EQ(opened, 3); + receiverRoom().unregisterByteStreamHandler(topic); + + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + ASSERT_TRUE(peer.sendBytes("after", opts).ok); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, "after"); +} + +} // namespace livekit::test::ds diff --git a/src/tests/integration/test_data_streams.cpp b/src/tests/integration/test_data_streams.cpp index dc048b3b..2d73e7c3 100644 --- a/src/tests/integration/test_data_streams.cpp +++ b/src/tests/integration/test_data_streams.cpp @@ -490,6 +490,24 @@ TEST_F(DataStreamE2ETest, SendAfterDisconnectThrows) { // Receive-side behaviour // --------------------------------------------------------------------------- +TEST_F(DataStreamE2ETest, ReceiveSizeLimitEndsStreamWithError) { + const auto topic = makeTopic("size_limit"); + std::vector configs(2); + configs[1].room_options.data_stream.max_payload_byte_length = 1000; + auto rooms = testRooms(configs); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamTextOptions options; + options.topic = topic; + (void)lockLocalParticipant(*rooms[0])->sendText(compressibleText(50 * 1024), options); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; + ASSERT_TRUE(collector.error().has_value()) << "an oversized stream must surface an error"; + EXPECT_NE(collector.error()->find("payload exceeds maximum size"), std::string::npos) << *collector.error(); +} + TEST_F(DataStreamE2ETest, TrailerAttributesAreMergedIntoInfo) { const auto topic = makeTopic("trailer_attrs"); auto rooms = testRooms(2); diff --git a/src/tests/unit/test_data_stream.cpp b/src/tests/unit/test_data_stream.cpp index fc5bd389..d4a020a9 100644 --- a/src/tests/unit/test_data_stream.cpp +++ b/src/tests/unit/test_data_stream.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -25,6 +26,7 @@ #include "data_stream_proto_converter.h" #include "ffi_client.h" +#include "room_proto_converter.h" namespace livekit { @@ -352,6 +354,16 @@ TEST(DataStreamConversionTest, ByteInfoFromProto) { EXPECT_EQ(*out.size, 2048u); } +TEST(DataStreamConversionTest, RoomOptionsDataStreamToProto) { + RoomOptions options; + EXPECT_FALSE(toProto(options).has_data_stream()) << "unset limit leaves the SDK default"; + + options.data_stream.max_payload_byte_length = 1000; + const auto proto = toProto(options); + ASSERT_TRUE(proto.has_data_stream()); + EXPECT_EQ(proto.data_stream().max_payload_byte_length(), 1000u); +} + // --------------------------------------------------------------------------- // One-shot sends refuse to reach an uninitialized FFI // ---------------------------------------------------------------------------